text
stringlengths
10
2.61M
#-- # mysql.rb # # Copyright (C) 2009 GemStone Systems, Inc. All rights reserved. # #++ # = Overview # # This script shows basic usage of the MySQL driver provided with MagLev. # # To run the script, ensure you have MySQL running, and edit the variables # for your configuration. require 'ruby-mysql/mysql' # CONFIGURATION host = 'localhost' user = 'webuser' pass = 'webuser' my = Mysql.new(host, user, pass) my.query("create database test_db") puts "Created database" my.select_db "test_db" puts "Database test_db selected" my.query("create table data(id int not null, str char(32) not null)") puts "Table created" my.query("insert into data (id, str) values (1, 'foo')") my.query("insert into data (id, str) values (2, 'bar')") puts "Rows inserted" res = my.query("select * from data") if res.num_rows != 2 then raise "num_rows: failed" end if res.fetch_row != ["1", "foo"] then raise "fetch_row: failed" end if res.fetch_hash != {"id"=>"2", "str"=>"bar"} then raise "fetch_hash: failed" end puts "Select complete" my.query("update data set id=0, str='hoge'") if my.affected_rows != 2 then raise "update: failed" end puts "Update complete" my.query("drop table data") puts "Tabled dropped" my.query("drop database test_db") puts "Database test_db dropped" my.close puts "Connection closed"
class RaidStopSaga < Saga def start(disk_number, context) @context = context @disk_number = disk_number Log4r::Logger['agent'].info "stoping /dev/md#{disk_number} [#{id}]" handle() end def handle(message = nil) case @state when STATE_START raid_state = Raid::check_raid(@disk_number) if raid_state == :active || raid_state == :failed result = Raid::stop_raid(@disk_number) if result notify_finished() finish() else Log4r::Logger['agent'].warn "failed to stop array /dev/md#{@disk_number} [#{id}]" notify_failure(:unknown_error) error() end elsif raid_state == :stopped Log4r::Logger['agent'].debug "RAID array is already stoped, finished [#{id}]" notify_finished() finish() end end end private def notify_finished() msg = Cirrocumulus::Message.new(nil, 'inform', Sexpistol.new.to_sexp([ [:stop, [:raid, @disk_number]], [:finished] ])) msg.ontology = @agent.default_ontology msg.receiver = @context.sender msg.in_reply_to = @context.reply_with @cm.send(msg) end def notify_failure(err) msg = Cirrocumulus::Message.new(nil, 'failure', Sexpistol.new.to_sexp([ [:stop, [:raid, @disk_number]], [err] ])) msg.ontology = @agent.default_ontology msg.receiver = @context.sender msg.in_reply_to = @context.reply_with @cm.send(msg) end end
# Preview all emails at http://localhost:3000/rails/mailers/company_lead_mailer class CompanyLeadMailerPreview < ActionMailer::Preview def welcome_email company_lead = CompanyLead.last CompanyLeadMailer.welcome_email(company_lead) end end
require_relative 'portfolio' class Client attr_accessor :name, :balance, :my_portfolios def initialize (name, balance) @name = name.downcase @balance = balance.to_f @my_portfolios = {} end #Allow creation of new portfolio with ID for seperation def create_portfolio(p_id) # portfolio = Portfolio.new(id) @my_portfolios[p_id] = Portfolio.new puts "You have created the portfolio: #{p_id}" return @my_portfolios end #Allow stock purchase. Make sure to check balance later. def buy_stock(ticker, shares, p_id) @my_portfolios[p_id].buy_stock(ticker, shares) invest(shares * pull_ticker(ticker)) puts "/n#{@name} invested in #{ticker}. #{shares} shares purchased." # would like user input end def sell_stock(p_id, ticker, shares) @my_portfolios[p_id].subtract_shares(ticker, shares) @balance += shares * pull_ticker(ticker) puts "/n#{@name} sold #{shares} shares of #{ticker}" end def display_portfolios #identifier error :( @my_portfolios.each do |id, portfolio| # if portfolio_value == nil # puts "Portfolio empty" # else puts "Total value of #{portfolio.portfolio_value}" portfolio.stocks.each do |ticker, shares| puts " #{ticker}: #{shares} value: #{stock.stock_value}" end end end end def pull_ticker(ticker) return YahooFinance::get_quotes(YahooFinance::StandardQuote, pull_ticker)[pull_ticker].lastTrade end def invest(amount) if @balance < amount puts "Insufficient funds for investment." else @balance -= amount end end
class ProductsController < ApplicationController load_resource :user, find_by: :slug, id_param: :profile_id, only: [:index, :new] load_and_authorize_resource :product, find_by: :slug, shallow: true, except: [:index, :by_category, :update, :create, :destroy] load_and_authorize_resource :product, find_by: :id, shallow: true, only: [:update, :destroy] def index end # GET /products/1 def show @comment = Comment.new if user_signed_in? and not current_user.is_owner_of? @product @message = @product.last_message_with(current_user) end end # GET /profiles/:profile_id/products/new def new raise CanCan::AccessDenied.new('Not authorized!') if @user != current_user end # GET /products/1/edit def edit end # POST /profiles/:profile_id/products def create @product = current_user.products.build(product_params) if @product.save redirect_to product_path(@product.slug), notice: I18n.t('product.create.success') else render action: :new end end # PATCH/PUT /products/1 def update if @product.update(product_params) redirect_to edit_product_path(@product.slug), notice: I18n.t('product.update.success') else render action: :edit end end # DELETE /products/1 def destroy if @product.destroy flash[:notice] = I18n.t('product.destroy.success') else flash[:alert] = I18n.t('product.destroy.error') end redirect_to products_path(@product.owner.slug) end private def product_params params.require(:product).permit(:name, :description, :category_id) end end
class RemoveApiAuthtokenToUsers < ActiveRecord::Migration def change remove_column :users, :api_authtoken, :string end end
require "stringio" if ARGV.length != 2 # TODO: allow for I/O via standard I/O (pipes) puts "usage: ruby dynare_fixer.rb INPUT_FILE OUTPUT_FILE" exit end # replaces a function with the arguments passed in # - command: the command to do the substitution in # - name: the name of the function # - args: the argument list # - expression: the expression of the function def args_replace command, name, args, expression initial_offset = offset = (command =~ /\b#{Regexp.escape name}\(/) + name.length + 1 bracket_count = 1 # find the last bracket while offset < command.length if command[offset] == ?( bracket_count += 1 elsif command[offset] == ?) bracket_count -= 1 break if bracket_count == 0 end offset += 1 end args_expr = command[initial_offset..(offset - 1)].split(",").map(&:strip) # passed the wrong number of arguments to this function if args_expr.length != args.length raise Exception.new("Error: wrong number of arguments for call to #{name} in command '#{command}'") end # do the substitutions command[0..(initial_offset - name.length - 2)] + "(" + args.zip(args_expr).inject(expression) do |result, (find, repl)| result.gsub(/\b#{Regexp.escape find}\b/, "(" + repl + ")") end + ")" + command[(offset + 1)..-1] end defines = [] output_lines = [] input_commands = [] # First, we need to parse out the individual commands and the comments input = StringIO.new File.read(ARGV[0]) buffer = StringIO.new state = :begin input.each_char do |c| # 3 states: # - not in a comment # - almost a comment (for comments using //) # - in a comment case state when :begin if c == "/" state = :comment? elsif c == "%" state = :comment elsif c == ";" input_commands << buffer.string + ";" buffer.string = "" else buffer.putc c end when :comment? if c == "/" state = :comment input_commands << buffer.string buffer.string = "" buffer.print "//" else state = :begin buffer.print "/" + c end when :comment if c == "\n" state = :begin input_commands << buffer.string + "\n" buffer.string = "" else buffer.putc c end end end input_commands << buffer.string output_lines << "// Auto-generated by Dynare Fixer\n" # now check each command to see if it is a function definition, # until we get to the model block. Once we're in the model block, # start replacing function calls with their corresponding expressions state = :start input_commands.each do |cmd| case state when :start if cmd =~ /def\s+([\w\d]+)\((.*?)\)\s*=\s*(.*);\s*/ expr = $3 defines << [$1, $2.split(/\s*,\s*/), expr] output_lines << cmd.sub("def", "//def") elsif cmd =~ /^\s*model\s*;/ state = :model output_lines << cmd else output_lines << cmd end when :model if cmd =~ /end/ state = :done else defines.each do |name, args, expression| while cmd =~ /\b#{Regexp.escape name}\(/ cmd = args_replace(cmd, name, args, expression) end end end output_lines << cmd else output_lines << cmd end end # dump to a file File.open(ARGV[1], "w") do |output| output.write output_lines.join end
require 'pry' VERSION = 1 class Hamming def self.compute(a, b) raise ArgumentError, "Distance between both strands are different." unless a.length == b.length a.chars.zip(b.chars).count{|x,y| x != y} end end
class AddCurrencyAndCountryColumns < ActiveRecord::Migration def change add_column :users, :country, :string, :after => :email add_column :payments, :currency, :string, :after => :wepay_credit_card_id end end
module Visualization class Month < Range def self.between(start_date, end_date) [].tap do |months| (start_date.year..end_date.year).each do |y| (starting_month(start_date, y)..ending_month(end_date, y)).each do |m| months << new(y,m) end end end end def initialize(year, month) beginning_of_month = DateTime.new(year, month).beginning_of_day end_of_month = beginning_of_month.at_end_of_month.end_of_day super(beginning_of_month, end_of_month) end def overlaps_with?(range) self.include?(range.first) || self.include?(range.last) || range.include?(self.first) end def to_s first.strftime(self.class.string_format) end private def self.starting_month(start_date, year) (start_date.year == year) ? start_date.month : 1 end def self.ending_month(end_date, year) (end_date.year == year) ? end_date.month : 12 end def self.string_format "%m/%Y" end end end
require 'spec_helper' describe "Replies" do subject { page } let(:user) { FactoryGirl.create(:user) } let(:another_user) { FactoryGirl.create(:user) } before do user.activate! another_user.activate! valid_signin user add_micropost('Lorem ipsum') click_link "Sign out" end describe "from micropost" do describe "of his own" do before do valid_signin user visit user_path user end it { should_not have_link("reply") } end describe "of another user" do before do valid_signin another_user visit user_path user end it { should have_link "reply" } describe "when clicking reply link" do before { click_link "reply" } it { should be_the_homepage } it { should have_micropost_content_filled_with "@#{user.name}: " } end end end describe "from another user's profile" do before do valid_signin user visit user_path another_user end it { should have_link "Send micropost" } describe "when clicking Send micropost link" do before { click_link "Send micropost" } it { should be_the_homepage } it { should have_micropost_content_filled_with "@#{another_user.name}: " } end end end
require 'redis' module Cache class << self def client return @redis if @redis @redis = connect end private def connect @redis = Redis.new @redis end end end
class AddPloneFieldsToUser < ActiveRecord::Migration def self.up add_column :users, :plone_password, :string, :limit => 40 add_column :users, :tmp_password, :string, :limit => 40 end def self.down remove_column :users, :plone_password remove_column :users, :tmp_password end end
class AgendaMailer < ApplicationMailer def agenda_mail(agenda) @agenda = agenda @members = @agenda.team.members mail to:@members.map(&:email).join(","), subject: "アジェンダ削除の通知メール" end end
module GitP4Sync class Sync attr_accessor :git_path, :p4_path, :branch, :simulate, :submit, :show, :ignore, :ignore_list, :diff_files, :timestamp, :current_branch def initialize self.git_path = "./" self.show = false self.submit = false self.simulate = false self.ignore = nil # always ignore .git folder because P4 doesnt need it self.ignore_list = [".git"] self.diff_files = [] self.timestamp = Time.now.utc.to_i end def prepare_for_sync # Handle defaults and missing # handling slash in filenames self.git_path = add_slash(File.expand_path(git_path)) self.p4_path = add_slash(File.expand_path(p4_path)) # verifying if these path exist verify_path_exist!(git_path) verify_path_exist!(p4_path) # store current branch name to restore it after the whole process. Dir.chdir(git_path) do self.current_branch = `git rev-parse --abbrev-ref HEAD`.split("\n").first end # setting up git repo on a new branch with the timestamp. puts "\n**********************************************************************\n " puts "Preparing for sync.\nThis will create a branch named temp_sync_branch_<timestamp> in local from the given branch.\nThis branch will be deleted after the sync." Dir.chdir(git_path) do cmd = system("git fetch && git checkout -b temp_sync_branch_#{timestamp} #{branch}") exit_with_error("Cannot checkout, verify if git_path and branch name are correct.") unless cmd end # preparing the files to be ignored. prepare_ignored_files # prepare diff files and reject the ones in ignored. self.diff_files.concat(diff_dirs(p4_path, git_path).reject{|file| is_ignored?(file.last) }) # if no diff, there is nothing to do -- PS : I know ! its not really an error... if diff_files.empty? puts "Directories are identical. Nothing to do." cleanup exit 0 end # exit if there is a file that has a status other than new, edited or deleted # TODO : Check if other status present and handle them exit_with_error("Unknown change type present. Task aborted !") if (diff_files.collect{|arr| arr.first} - [:new, :deleted, :modified]).any? # UNTESTED CODE. HAVE TO REWORK ON THIS # # handle @ charachter in file name and replace with ascii value # self.diff_files.each{|element| element.last.gsub!('@','%40')} end def cleanup Dir.chdir(git_path) do result = system("git checkout #{current_branch} && git branch -D temp_sync_branch_#{timestamp}") puts "\n**********************************************************************\n " puts "Could not delete the temp branch. Please delete it manually later." unless result puts "Sync process completed. Please follow the logs to trace any discrepancies." puts "\n**********************************************************************\n " end end def show_changes puts " \n**********************************************************************\n " puts "Change List : \n" diff_files.each{|ele| puts "#{ele[0].to_s.upcase} in Git: #{ele[1]}"} end def run show_changes if show puts "\n**********************************************************************\n " puts "A total of #{diff_files.size} change(s) !" if submit || simulate handle_files git_head_commit = "" Dir.chdir(git_path) do git_head_commit = `git show -v -s --pretty=format:"%s : SHA:%H"` end puts "\n**********************************************************************\n " Dir.chdir(p4_path) do puts "Submitting changes to Perforce" run_cmd "p4 submit -d '#{git_head_commit.gsub("'", "''")}'", simulate end end end def prepare_ignored_files # if ignore files provided on commandline add them if ignore if ignore.include?(":") self.ignore_list.concat(ignore.split(":")) elsif ignore.include?(",") self.ignore_list.concat(ignore.split(",")) else self.ignore_list << ignore end end # if there is a gitignore file, the files inside also have to be ignored. # TODO : gitignore files could be inside directories as well. Need to handle that case. if File.exist?(gitignore = File.join(git_path, ".gitignore")) self.ignore_list.concat(File.read(gitignore).split(/\n/).reject{|i| (i.size == 0) or i.strip.start_with?("#") }.map {|i| i.gsub("*",".*") } ) end end # generic method to exit with error. def exit_with_error(msg="Exiting for unknown reasons.Check the history", clean = true) puts msg cleanup if clean exit 1 end def handle_files diff_files.each do |d| action = d[0] file = strip_leading_slash(d[1]) puts "#{action.to_s.upcase} in Git: #{file}" Dir.chdir(p4_path) do case action when :new run_cmd "cp -r '#{git_path}#{file}' '#{p4_path}#{file}'", simulate run_cmd "#{p4_add_recursively("'#{p4_path}#{file}'")}", simulate when :deleted file_path="#{p4_path}#{file}" Find.find(file_path) do |f| puts "DELETED in Git (dir contents): #{f}" if file_path != f run_cmd("p4 delete '#{f}'", simulate) end FileUtils.remove_entry_secure(file_path,:force => true) when :modified run_cmd "p4 edit '#{p4_path}#{file}'", simulate run_cmd "cp '#{git_path}#{file}' '#{p4_path}#{file}'", simulate end end end end def run_cmd(cmd, simulate = false, puts_prefix = " ") if simulate puts "#{puts_prefix}simulation: #{cmd}" else puts "#{puts_prefix}#{cmd}" end output = false output = system("#{cmd}") unless simulate exit_with_error unless output [output, $?] end def lambda_ignore(item) re = Regexp.compile(/#{item}/) lambda {|diff| diff =~ re } end def is_ignored?(file) ignore_list.each {|ignored| return true if lambda_ignore(ignored).call(file) } return false end def add_slash(path) path << '/' unless path.end_with?('/') path end def strip_leading_slash(path) path.sub(/^\//, "") end def p4_add_recursively(path) # This will recursively add the files when a new folder is added # TODO : If one of the files in the new folder is in gitignore, it will still get added. Need to handle it ! "find #{path} -type f -print | p4 -x - add -f" end def verify_path_exist!(path) if !File.exist?(path) || !File.directory?(path) exit_with_error("#{path} must exist and be a directory.", false) end end end end
# Change request helpers module ChangeRequestsHelper def change_request_class(status) case status when 'pending' 'danger' when 'accepted' 'success' else '' end end end
def consolidate_cart(cart) new_cart = {} cart.each do |items_array| items_array.each do |item, attribute_hash| new_cart[item] ||= attribute_hash new_cart[item][:count] ? new_cart[item][:count] += 1 : new_cart[item][:count] = 1 end end new_cart end def apply_coupons(cart, coupons) hash = cart coupons.each do |coupon_hash| # add coupon to cart item = coupon_hash[:item] if !hash[item].nil? && hash[item][:count] >= coupon_hash[:num] temp = {"#{item} W/COUPON" => { :price => coupon_hash[:cost], :clearance => hash[item][:clearance], :count => 1 } } if hash["#{item} W/COUPON"].nil? hash.merge!(temp) else hash["#{item} W/COUPON"][:count] += 1 #hash["#{item} W/COUPON"][:price] += coupon_hash[:cost] end hash[item][:count] -= coupon_hash[:num] end end def apply_clearance(cart) cart.each do |item, attribute_hash| if attribute_hash[:clearance] == true attribute_hash[:price] = (attribute_hash[:price] * 0.8).round(2) end end cart end def checkout(cart, coupons) total = 0 new_cart = consolidate_cart(cart) coupon_cart = apply_coupons(new_cart, coupons) clearance_cart = apply_clearance(coupon_cart) clearance_cart.each do |item, attribute_hash| total += (attribute_hash[:price] * attribute_hash[:count]) end total = (total * 0.9) if total > 100 total end
class CreateGoods < ActiveRecord::Migration def change create_table :goods do |t| t.integer :creator_id, null: false t.integer :buyer_id, null: false, default: 0 t.integer :producer_id, null: false, default: 0 t.references :market, null: false t.references :product, null: false t.references :selling_unit, null: false t.integer :quantity t.boolean :indefinite, null: false, default: true t.date :start_date t.date :end_date t.timestamps end add_index :goods, :creator_id add_index :goods, :buyer_id add_index :goods, :producer_id add_index :goods, :market_id add_index :goods, :product_id add_index :goods, :selling_unit_id end end
Redis::Objects.redis = ConnectionPool.new(size: 5, timeout: 5) { Redis.new(host: SIDEKIQ_CONFIG[:redis_host], port: SIDEKIQ_CONFIG[:redis_port], db: SIDEKIQ_CONFIG[:redis_database]) } if defined?(SIDEKIQ_CONFIG) class CheckStateMachine include Redis::Objects include AASM value :state value :message def initialize(uid) @uid = uid super() end def id @uid end aasm column: 'state' do state :waiting_for_message, initial: true state :main state :secondary state :query state :human_mode state :subscription state :search state :search_result state :add_more_details state :ask_if_ready ALL_STATES = [:human_mode, :main, :secondary, :query, :waiting_for_message, :subscription, :search, :search_result, :add_more_details, :ask_if_ready] event :start do transitions :from => [:waiting_for_message, :main], :to => :main end event :reset do transitions :from => ALL_STATES, :to => :waiting_for_message end event :enter_human_mode do transitions :from => ALL_STATES, :to => :human_mode end event :leave_human_mode do transitions :from => :human_mode, :to => :waiting_for_message end event :go_to_secondary do transitions :from => ALL_STATES, :to => :secondary end event :go_to_main do transitions :from => ALL_STATES, :to => :main end event :go_to_query do transitions :from => ALL_STATES, :to => :query end event :go_to_subscription do transitions :from => ALL_STATES, :to => :subscription end event :go_to_search do transitions :from => ALL_STATES, :to => :search end event :go_to_search_result do transitions :from => ALL_STATES, :to => :search_result end event :go_to_ask_if_ready do transitions :from => ALL_STATES, :to => :ask_if_ready end event :go_to_add_more_details do transitions :from => ALL_STATES, :to => :add_more_details end end end
module Codegrade module Grader class Grader attr_reader :commit def initialize(commit) @commit = commit end def grade offenses = [] commit_message = CommitMessage.new(@commit.message) commit_message.grade offenses.concat(commit_message.offenses) ruby_files.each do |file| offenses.concat(Rubocop.new(file).grade) end offenses end private def ruby_files commit.files.select { |filename| File.extname(filename) == '.rb' } end end end end
require 'spec_helper' module DmtdVbmappData describe Guide do it 'can be created' do client = Client.new(date_of_birth: Date.today, gender: DmtdVbmappData::GENDER_FEMALE) expect(Guide.new(client: client)).to_not be nil end it 'can provide chapters' do prev_chapters = nil AVAILABLE_LANGUAGES.each do |language| guide = Guide.new(client: Client.new(date_of_birth: Date.today, gender: DmtdVbmappData::GENDER_FEMALE, language: language)) expect(guide.chapters).to_not be nil expect(guide.chapters.is_a?(Array)).to eq(true) guide.chapters.each do |chapter| expect(chapter.is_a?(DmtdVbmappData::GuideChapter)).to eq(true) expect(chapter.title).to eq("CHAPTER 1") if language == 'en' && chapter.chapter_num == 1 expect(chapter.title).to eq("CAPÍTULO 1") if language == 'es' && chapter.chapter_num == 1 expect(chapter.title).to eq("CHAPITRE 1") if language == 'fr' && chapter.chapter_num == 1 end expect(guide.chapters).to_not eq(prev_chapters) unless prev_chapters.nil? prev_chapters = guide.chapters end end it 'can recover from expiry' do guide = Guide.new(client: Client.new(date_of_birth: Date.today, gender: DmtdVbmappData::GENDER_FEMALE), language: AVAILABLE_LANGUAGES[0]) expect(guide.chapters).to_not be nil guide.expire_cache force: true expect(guide.chapters).to_not be nil end end end
# Public: Takes an array and returns the last element. # # arr - The Array the gives the output. # # Examples # # last_of(1337, 2, -1) # # => -1 # # Returns the last element in the array. def last_of(arr) return arr[arr.length-1] end
# -*- coding: utf-8 -*- module Smshelper module Api class Base include APISmith::Client attr_reader :sent_message_ids, :sent_message_statuses attr_accessor :extra_options def initialize(*args) @sent_message_ids, @sent_message_statuses = Array.new, Hash.new @response_code = ResponseCodes.new @extra_options = (args.empty? ? {} : args.shift) @uuid = UUID.new class_factory 'DeliveryReport', 'InboundMessage', 'UnknownReply', 'HlrReport' end protected def class_factory(*names) names.each do |name| unless self.class.const_defined?(name) klass = self.class.const_set(name, Class.new) klass.class_eval do include Virtus define_method(:initialize) do |args = {}| args.each do |k,v| # Sinatra params has splat, captures unless k.to_s =~ (/splat/ || /captures/) self.class.attribute(k, v.class, :default => v) end end self.class.attribute(:uuid, String, :default => UUID.generate) unless args[:uuid] self.class.attribute(:service, String, :default => self.class.name.split('::')[2]) end # I was lazy to lookup which method takes precedence in # what situation, hence: def _dump(level) attributes.to_yaml end def marshal_dump attributes.to_yaml end def marshal_load(str) self.class.new(YAML.load(str)) end def self._load(str) self.class.new(YAML.load(str)) end end end end end end # class Base end # module Api end # module Smshelper
require 'rails_helper' RSpec.describe "project_reports/show", type: :view do before(:each) do @project_report = assign(:project_report, ProjectReport.create!( :project_id => "", :status_cd => "MyText" )) end it "renders attributes in <p>" do render expect(rendered).to match(//) expect(rendered).to match(/MyText/) end end
class App < ActiveRecord::Base has_many :nav_nodes, :dependent => :delete_all def self.authenticate(code, secret) where("code = ? AND secret = ?", code, secret).first end end
require 'thor' class DeliveryCenter::Cli < Thor require 'delivery_center/cli/database' require 'delivery_center/cli/revision' require 'delivery_center/cli/application' desc 'db SUBCOMMAND ...ARGS', 'manage db' subcommand 'db', DeliveryCenter::Cli::Database desc 'revision SUBCOMMAND ...ARGS', 'manage db' subcommand 'revision', DeliveryCenter::Cli::Revision desc 'application SUBCOMMAND ...ARGS', 'manage db' subcommand 'application', DeliveryCenter::Cli::Application desc 'server', 'run delivery center web application' option 'port', desc: 'listen port', default: 8080, aliases: 'p', type: :numeric option 'address', desc: 'listen address', default: 'localhost', aliases: 'b', type: :string def server DeliveryCenter::App.run!(options) end desc 'deploy [application name]', 'deploy latest revision' def deploy(application_name) application = find_application(application_name) application.deploy! puts "current revision: #{application.current_revision.value}" end desc 'rollback [application name]', 'rollback previous revision' def rollback(application_name) application = find_application(application_name) application.rollback! puts "current revision: #{application.current_revision.value}" end private def find_application(name) application = DeliveryCenter::Application.find_by(name: name) if application.nil? DeliveryCenter.logger.error("notfound #{application}") exit 1 end application end end
require_relative '../solver' require 'test/unit' class TestSolver < Test::Unit::TestCase def test_most_present_value grid = Grid.new(4) solver = Solver.new(grid) assert_equal(1, solver.most_present_value) grid[0, 0].value = 1 assert_equal(1, solver.most_present_value) grid[0, 1].value = 1 assert_equal(1, solver.most_present_value) grid[0, 2].value = 2 assert_equal(1, solver.most_present_value) grid[0, 3].value = 2 grid[1, 0].value = 2 assert_equal(2, solver.most_present_value) end def test_cells_by_val grid = Grid.new(2) solver = Solver.new(grid) grid[0, 0].value = 1 grid[1, 1].value = 1 grid[0, 1].value = 2 grid[1, 0].value = 2 cells_by_val = solver.cells_by_val assert_equal(2, cells_by_val.count) ones = cells_by_val[1] twos = cells_by_val[2] assert_equal(2, ones.count) assert_equal(0, ones[0].row) assert_equal(0, ones[0].column) assert_equal(1, ones[1].row) assert_equal(1, ones[1].column) assert_equal(2, twos.count) end def test_can_hold grid = Grid.new(4) solver = Solver.new(grid) grid[0, 0].value = 1 grid[0, 1].value = 2 grid[0, 2].value = 3 grid[0, 3].value = 4 grid[1, 0].value = 3 grid[1, 1].value = 4 grid[1, 2].value = 2 grid[1, 3].value = 1 grid[2, 0].value = 2 grid[2, 1].value = 1 grid[2, 2].value = 4 grid[2, 3].value = 3 assert_equal(true, solver.can_hold(3, 0, 4)) assert_equal(false, solver.can_hold(3, 1, 4)) assert_equal(false, solver.can_hold(3, 2, 4)) assert_equal(false, solver.can_hold(3, 3, 4)) assert_equal(false, solver.can_hold(3, 0, 3)) assert_equal(true, solver.can_hold(3, 1, 3)) assert_equal(false, solver.can_hold(3, 2, 3)) assert_equal(false, solver.can_hold(3, 3, 3)) assert_equal(false, solver.can_hold(3, 0, 1)) assert_equal(false, solver.can_hold(3, 1, 1)) assert_equal(true, solver.can_hold(3, 2, 1)) assert_equal(false, solver.can_hold(3, 3, 1)) assert_equal(false, solver.can_hold(3, 0, 2)) assert_equal(false, solver.can_hold(3, 1, 2)) assert_equal(false, solver.can_hold(3, 2, 2)) assert_equal(true, solver.can_hold(3, 3, 2)) assert_equal(true, solver.can_hold(0, 0, 1)) assert_equal(false, solver.can_hold(0, 0, 2)) assert_equal(false, solver.can_hold(0, 0, 3)) end end
require_relative '../test_helper' class TaskManagerTest < Minitest::Test ####Change tests so they are not dependent on the ID ##So instead of using TaskManager.create, use Task.new and store the task def create_tasks(num) num.times do |x| TaskManager.create({ :title => "task#{x+1}", :description => "#{x+1}"}) end end def test_it_creates_a_task create_tasks(1) task = TaskManager.all.last assert_equal "task1", task.title assert_equal "1", task.description end def test_it_shows_all_tasks create_tasks(2) tasks = TaskManager.all assert_equal 2, tasks.count assert tasks[0].is_a?(Task) end def test_it_finds_a_task create_tasks(2) task1 = TaskManager.all[-2] task2 = TaskManager.all.last assert_equal "task1", task1.title assert_equal "2", task2.description end def test_it_can_update_a_task create_tasks(1) task = TaskManager.all.last assert_equal "task1", task.title assert_equal "1", task.description data = {:title => "new title", :description => "new description"} TaskManager.update(task.id, data) task = TaskManager.all.last assert_equal "new title", task.title assert_equal "new description", task.description end def test_it_can_destroy_a_task create_tasks(1) count = TaskManager.all.count task = TaskManager.all.last assert_equal count, TaskManager.all.count TaskManager.destroy(task.id) assert_equal count - 1, TaskManager.all.count end end
require 'base64' require_relative '../spec_helper' require_relative '../../helpers/auth' require_relative '../../helpers/logger' describe 'Auth Helper' do include Auth include MagicLogger attr_reader :slack_dummy, :email_dummy def invite_to_slack(*args) @slack_dummy.invite_to_slack(*args) end def email_welcome(*args) @email_dummy.email_welcome(*args) end before(:each) do @slack_dummy = double('slack-dummy') @email_dummy = double('email-dummy') end def with_secret ENV['SECRET'] = SecureRandom.hex(16) # 16 * 2 yield ENV.delete 'SECRET' end context 'cipher' do it 'functions should exist' do expect(respond_to?('encrypt')).to be true expect(respond_to?('decrypt')).to be true end it 'should have basic error handling' do ENV.delete 'SECRET' expect { encrypt('foo') }.to raise_error expect { decrypt('bar', 'baz') }.to raise_error end it 'can encrypt and decrypt' do with_secret do target_phrase = "What's up unit test!" encrypted, iv = encrypt target_phrase expect(encrypted).not_to eq(target_phrase) expect(iv).not_to eq(target_phrase) expect(encrypted.length).to be > target_phrase.length decrypted = decrypt(encrypted, iv) expect(decrypted).to eq(target_phrase) end end end context 'jwt' do it 'can generate and veryify magic-stick issuer' do user = User.new(username: 'sample-jwt-user', password: 'test-password', email: 'no-reply@gmail.com', name: 'same user') user.save expect(user).not_to be_nil token = nil found_user = nil expect do token = encode_jwt(user) end.not_to raise_error expect(token).not_to be_nil expect do found_user = decode_jwt_user(token) end.not_to raise_error expect(found_user).to be_instance_of(User) expect(found_user.id).to eq(user.id) dt = JWT.decode token, hmac_secret, true, algorithm: 'HS256' expect(dt[0]).to have_key('user') end it 'can veryify auth0 issuer if user dne' do expect(@email_dummy).to receive(:email_welcome) expect(@slack_dummy).to receive(:invite_to_slack) expect(User.find(email: sample_auth0_payload['email'])).to be_nil token = nil user = nil expect do token = sample_auth0_jwt payload: sample_auth0_payload end.not_to raise_error expect(token).not_to be_nil expect do user = decode_jwt_user(token) end.not_to raise_error expect(user).to be_instance_of(User) expect(user.username).not_to be_nil expect(user.password).not_to be_nil expect(user.email).to eq(sample_auth0_payload['email']) expect(user.user_identities.count).to eq(1) ident = user.user_identities.first expect(ident.user_id).to eq(user.id) expect(ident.provider_id).to eq(sample_auth0_payload['sub']) expect(ident.user.id).to eq(user.id) end it 'can veryify auth0 issuer if user exists, identity does not' do user = User.new(username: 'sample-jwt-user33', password: 'test-password', email: 'some-crazy-outage@gmail.com', name: 'same user') user.save expect(user).not_to be_nil expect(User.find(email: user.email)).not_to be_nil expect(user.user_identities.count).to eq(0) user2 = nil payload = sample_auth0_payload.merge( 'email' => user.email, 'sub' => 'google-oauth2|99382' ) expect do token = sample_auth0_jwt( payload: payload ) user2 = decode_jwt_user(token) end.not_to raise_error expect(user2).to be_instance_of(User) expect(user2.email) expect(user2.id).to eq(user.id) expect(user2.user_identities.count).to eq(1) ident = user2.user_identities.first expect(ident.provider_id).to eq(payload['sub']) expect(ident.user_id).to eq(user.id) expect(ident.user.id).to eq(user.id) end it 'can veryify auth0 issuer if user exists, identity does' do user = User.new(username: 'sample-jwt-user5', password: 'test-password5', email: 'howareyou@foo.com', name: 'some other user') user.save expect(user).not_to be_nil ident = UserIdentity.new(provider_id: 'google-oauth2|8675309') user.add_user_identity ident user.reload expect(user.user_identities.count).to eq(1) user2 = nil expect do token = sample_auth0_jwt payload: sample_auth0_payload.merge( 'email' => 'random-unrelated-email@gmail.com', 'sub' => ident.provider_id ) user2 = decode_jwt_user(token) end.not_to raise_error expect(user2).to be_instance_of(User) expect(user2.id).to eq(user.id) expect(user.email).to eq(user2.email) expect(user2.user_identities.count).to eq(1) end end end
class Api::V1::RegistrationsController < Devise::RegistrationsController require 'json_web_token' skip_before_action :verify_authenticity_token respond_to :json def create user = User.new(user_params) if user.save # auth_token = jwt_token(user) render json: user, status: 201 #render json: { user:user, auth_token: auth_token}, status: 201 return else render json: { errors: user.errors}, status: 422 end end private # def jwt_token(user) # JsonWebToken.encode({id: user.id, email: user.email}) # end def user_params params.permit(:username,:email,:password) end end
#!/usr/bin/env ruby ############################################################################### # # Core Libraries # version 1.1 # # Written By: Ari Mizrahi # # Core libraries for Dvash Defense # ############################################################################### def random_string # generate a bucket of chars for randomization bucket = [('a'..'z'),('A'..'Z'),(0..9)].map{|i| i.to_a}.flatten # pick random chars from the bucket and return a 255 char string return (0...255).map{ bucket[rand(bucket.length)] }.join end def load_conf # load the config file begin @cfgfile = ParseConfig.new('./etc/dvash.conf') if @debug then puts 'DEBUG: loaded conf file' end if @log then write_log('INFO,dvash config file loaded') end rescue puts "CRITICAL: couldn't find dvash.conf!".red if @log then write_log('CRITICAL,dvash config file missing and exit') end Process.exit end end def load_modules # loop through Modules group and find enabled Modules @cfgfile['modules'].each do |key, value| if value == "true" then # load the required module from lib require "./mod/#{key}.rb" # push the module into the thread bucket @module_threads << Thread.new { send("start_#{key}") } if @debug then puts "DEBUG: loaded #{key} module into thread bucket" end if @log then write_log("INFO,successfully loaded #{key} module") end end end end def validate_ip(address) # no need to reinvent the wheel, self-explanatory begin if IPAddr.new("#{address}") then if @debug then puts "DEBUG: #{address} is valid!" end if @log then write_log("INFO,#{address} was validated") end return true end rescue if @debug then puts "DEBUG: #{address} is invalid!" end if @log then write_log("CRITICAL,#{address} was invalid and was not processed") end return false end end def block_ip(address) badip = IPAddr.new("#{address}") # ban ipv4 address if badip.ipv4? and @ipv4tables then system("#{@cfgfile['iptables']['ipv4']} -I DVASH -s #{badip} -j DROP") if @debug then puts "DEBUG: IPv4 address #{badip} blocked!" end if @log then write_log("BLOCKED,IPv4 address #{badip} was blocked") end # write to blocklist.log end # ban ipv6 address if badip.ipv6? and @ipv6tables then system("#{@cfgfile['iptables']['ipv6']} -I DVASH -s #{badip} -j DROP") if @debug then puts "DEBUG: IPv6 address #{badip} blocked!" end if @log then write_log("BLOCKED,IPv6 address #{badip} was blocked") end # write to blocklist.log end end def prepare_iptables if @ipv4tables then # do not create if it has already been created if `"#{@cfgfile['iptables']['ipv4']}" -L INPUT`.include?('DVASH') then if @debug then puts "DEBUG: DVASH IPv4 chain already created!" end if @log then write_log('INFO,dvash ipv4 chain already created skipping prepare') end return false end # create a new chain system("#{@cfgfile['iptables']['ipv4']} -N DVASH") # flush the new chain system("#{@cfgfile['iptables']['ipv4']} -F DVASH") # associate new chain to INPUT chain system("#{@cfgfile['iptables']['ipv4']} -I INPUT -j DVASH") if @debug then puts "DEBUG: iptables ready for blocking!" end if @log then write_log('INFO,iptables prepared for blocking') end end end def prepare_ip6tables if @ipv6tables then # do not create if it has already been created if `"#{@cfgfile['iptables']['ipv6']}" -L INPUT`.include?('DVASH') then if @debug then puts "DEBUG: DVASH IPv6 chain already created!" end if @log then write_log('INFO,dvash ipv6 chain already created skipping prepare') end return false end # create a new chain system("#{@cfgfile['iptables']['ipv6']} -N DVASH") # flush the new chain system("#{@cfgfile['iptables']['ipv6']} -F DVASH") # associate new chain to INPUT chain system("#{@cfgfile['iptables']['ipv6']} -I INPUT -j DVASH") if @debug then puts "DEBUG: ip6tables ready for blocking!" end if @log then write_log('INFO,ip6tables prepared for blocking') end end end
require 'rails_helper' RSpec.describe Invite, :type => :model do describe '#memorials' do it 'should show me the memorial it belongs to' do @memorial = Memorial.create(deceased_name: "John Jacob") @invite = Invite.create(email: "ev@example.com", memorial: @memorial) expect(@invite.memorial).to eq(@memorial) end end end
class PostsController < InheritedResources::Base private def post_params params.require(:post).permit(:image, :title, :description, :date, :author) end end
class AddResourcesToMessages < ActiveRecord::Migration[5.2] def change add_reference :messages, :resource, polymorphic: true, index: true end end
# # Copyright 2011 National Institute of Informatics. # # # 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 'test_helper' class SoftwareTest < ActiveSupport::TestCase # Replace this with your real tests. # called before every single test def setup @software = Software.new(:name => 'test', :desc => 'desc') end # called after every single test def teardown end test "should not save software without name" do @software.name = nil assert !@software.save end test "should not save software without desc" do @software.desc = nil assert !@software.save end test "should not save software with the same name" do assert @software.save new_soft = Software.new(:name => 'test', :desc => 'desc1') assert !new_soft.save end test "should not save software with the same desc" do assert @software.save new_soft = Software.new(:name => 'test2', :desc => 'desc') assert !new_soft.save end test "should save software" do assert @software.save end end
require 'rpcoder/param' require 'camelizer' module RPCoder class Type attr_accessor :name, :description, :array_type def fields @fields ||= [] end def add_field(name, type, options = {}) options[:array_type] = @array_type if options[:array_type] == nil fields << Field.new(name, type, options) end def array if @array_type == :array "#{name}[]" else "List<#{name}>" end end class Field < Param attr_accessor :default def initialize(name, type, options = {}) super(name, type, options) @default = options[:default] end end end end
# frozen_string_literal: true module Admin # TemplateService class TemplateService def initialize(file) @file = file end def name(file) "#{file.to_s.split('/').last.split('.').first.capitalize} Template" end def install clear_template unzip_template install_template_html [:css, :img, :js, :fonts].each do |stack| install_template(stack) end end def uninstall clear_template end def set_defaut clear_template end private def dir { template: 'public/templates', css: 'app/assets/stylesheets/css', img: 'app/assets/images/img', fonts: 'app/assets/images/fonts', js: 'app/assets/javascripts/js' } end def clear_template file_name = Dir[File.join("#{Rails.root}/#{dir[:template]}", '**', '*')].first template_name = file_name.split('/').last if file_name names = build_array_html_files_names(template_name, 'html') system "rails d keppler_front front #{names.join(' ')}" system "rm -rf #{Rails.root}/app/views/app/front/" [:template, :css, :img, :fonts, :js].each do |stack| clear_assets("#{Rails.root}/#{dir[stack]}") end system "rails g keppler_front front index --skip-migration -f" system "rm -rf #{Rails.root}/app/model/front.rb" end def unzip_template system "unzip #{Rails.root}/public/#{@file} -d #{Rails.root}/public/templates" end def build_array_html_files_names(template_name, extention) names = [] Dir[File.join("#{Rails.root}/public/templates/#{template_name}", '**', '*')].each do |file| if File.file?(file) name = file.to_s.split("/").last.split(".").first extentions = file.to_s.split("/").last.split(".").second if extentions.eql?(extention) names << name end end end return names end def build_array_assets_files_names(template_name, extention) names = [] Dir[File.join("#{Rails.root}/public/templates/#{template_name}/assets/#{extention}", '**', '*')].each do |file| if File.file?(file) name = file.to_s.split("/").last names << name end end return names end def install_template_html system "rails d keppler_front front index" folder = "#{Rails.root}/app/views/app/front" template_name = Dir[File.join("#{Rails.root}/public/templates", '**', '*')].first.split("/").last names = build_array_html_files_names(template_name, "html") system "rails g keppler_front front #{names.join(' ')} --skip-migration -f" system "rm -rf #{Rails.root}/app/model/front.rb" names.each do |name| system "rm -rf #{folder}/#{name}.html.haml" system "cp #{Rails.root}/public/templates/#{template_name}/#{name}.html #{folder}/#{name}.html" system "html2haml #{folder}/#{name}.html #{folder}/#{name}.html.haml" system "rm -rf #{folder}/#{name}.html" add_assets_keppler(folder, name) end end def clear_assets(folder) system "rm -rf #{folder}" system "mkdir #{folder}" end def install_template(stack) folder = "#{Rails.root}/#{dir[stack]}" clear_assets(folder) template_name = Dir[File.join("#{Rails.root}/public/templates", '**', '*')].first.split("/").last names = build_array_assets_files_names(template_name, "#{stack}") names.each do |name| system "cp #{Rails.root}/public/templates/#{template_name}/assets/#{stack}/#{name} #{folder}/#{name}" end end def add_assets_keppler(folder, name) index_html = File.readlines("#{folder}/#{name}.html.haml") head_idx = 0 index_html.each do |i| head_idx = index_html.find_index(i) if i.include?('%html') end index_html.insert(head_idx.to_i + 2, " = render 'app/layouts/head'\n") index_html = index_html.join('') File.write("#{folder}/#{name}.html.haml", index_html) end end end
require_relative 'test_helper' require 'blue_hawaii/rental_unit' require 'json' require 'pp' require 'bigdecimal' describe RentalUnit do include TestHelper describe "#initialize" do describe "with simple rental" do before do @rental_json = JSON.parse simple_rental_json @rental_unit = RentalUnit.new data: simple_rental_json end it "should assign name" do assert_equal @rental_json["name"], @rental_unit.name end it "should assign rate" do assert_equal BigDecimal.new(@rental_json["rate"][1..-1]), @rental_unit.rate end it "should assign cleaning fee" do assert_equal BigDecimal.new(@rental_json["cleaning fee"][1..-1]), @rental_unit.cleaning_fee end it "should not have seasons" do refute @rental_unit.has_seasons? end end describe "with complex rental" do before do @rental_json = JSON.parse complex_rental_json @rental_unit = RentalUnit.new data: complex_rental_json end it "should have seasons" do assert @rental_unit.has_seasons? assert_equal 2, @rental_unit.seasons.size end it "should populate season" do season = @rental_unit.seasons[0] assert_equal "one", season.name assert_equal BigDecimal.new("137.00"), season.rate assert_equal MonthDay.new(5,1), season.start_on assert_equal MonthDay.new(5,13), season.end_on end end end describe "#rental_cost" do describe "simple rental" do before do @rental_unit = RentalUnit.new data: simple_rental_json end it "should calculate rental cost" do assert_equal BigDecimal.new("3508.65"), @rental_unit.rental_cost("2011/05/07", "2011/05/20") end end describe "complex rental" do before do @rental_unit = RentalUnit.new data: complex_rental_json end it "should calculate rental cost" do assert_equal "2474.79", @rental_unit.rental_cost("2011/05/07", "2011/05/20").to_s('F') end end end end
# Be sure to restart your server when you modify this file. # # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] end # Disable root element in JSON by default. ActiveSupport.on_load(:active_record) do self.include_root_in_json = false end ActiveRecord::Base.connection.execute('SELECT 1') ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do def begin_db_transaction end def commit_db_transaction end end
class Genre < ActiveRecord::Base include Slugifiable::InstanceMethods has_many :song_genres has_many :songs, through: :song_genres has_many :artists, through: :songs end
class AddIndexToSuggestionsTable < ActiveRecord::Migration def change #Adding the index can massively speed up join tables. add_index(:suggestions, [:subchapter_id, :profile_id], :unique => true) end end
class Venue < ActiveRecord::Base belongs_to :region validates_uniqueness_of :name validates :full_address, :region_id, presence: true end
# frozen_string_literal: true class ApplicationPlanDecorator < ApplicationDecorator def link_to_edit(**options) h.link_to(name, h.edit_admin_application_plan_path(self), options) end def link_to_applications(**options) live_applications = cinstances.live text = h.pluralize(live_applications.size, 'application') if h.can?(:show, Cinstance) h.link_to(text, plan_path, options) else text end end def plan_path service = context.fetch(:service) { object.service } h.admin_service_applications_path(service, search: { plan_id: id }) end def index_table_data { id: id, name: name, editPath: h.edit_polymorphic_path([:admin, object]), applications: contracts_count, applicationsPath: h.admin_service_applications_path(service, search: { plan_id: id }), state: state, actions: index_table_actions } end def index_table_actions [ published? ? nil : { title: 'Publish', path: h.publish_admin_plan_path(object), method: :post }, published? ? { title: 'Hide', path: h.hide_admin_plan_path(object), method: :post } : nil, { title: 'Copy', path: h.admin_plan_copies_path(plan_id: id), method: :post }, can_be_destroyed? ? { title: 'Delete', path: h.polymorphic_path([:admin, object]), method: :delete } : nil ].compact end end
class RenameIcecastTitle < ActiveRecord::Migration def self.up rename_column :display_infos, :icecast_display, :icecast_title end def self.down rename_column :display_infos, :icecast_title, :icecast_display end end
require 'test_helper' class SessionsControllerTest < ActionController::TestCase test "logs user in using omniauth credentials" do @controller.env['omniauth.auth'] = OmniAuth::auth_hash get :create user = assigns(:user) assert_equal '1', user.uid assert_equal 'Ritter', user.provider assert_redirected_to root_path end test "clears user session" do session[:user_id] = "logged in" delete :destroy assert_nil session[:user_id] assert_redirected_to root_path end end
module Gollum class Site def self.default_layout_dir() ::File.join(::File.dirname(::File.expand_path(__FILE__)), "layout") end attr_reader :output_path attr_reader :layouts attr_reader :pages def initialize(path, options = {}) @wiki = Gollum::Wiki.new(path, { :markup_class => Gollum::SiteMarkup, :page_class => Gollum::SitePage, :base_path => options[:base_path], :sanitization => sanitization(options), :history_sanitization => sanitization(options) }) @wiki.site = self @output_path = options[:output_path] || "_site" @version = options[:version] || "master" end # Prepare site for specified version def prepare() @pages = {} @files = {} @layouts = {} @commit = @version == :working ? @wiki.repo.head.commit : @wiki.repo.commit(@version) items = self.ls(@version) items.each do |item| filename = ::File.basename(item.path) dirname = ::File.dirname(item.path) if filename =~ /^_Footer./ # ignore elsif filename =~ /^_Sidebar./ # ignore elsif filename =~ /^_Layout.html/ # layout @layouts[item.path] = ::Liquid::Template.parse(item.data) elsif @wiki.page_class.valid_page_name?(filename) # page page = @wiki.page_class.new(@wiki) blob = OpenStruct.new(:name => filename, :data => item.data) page.populate(blob, dirname) page.version = @commit @pages[page.name.downcase] = page else # file @files[item.path] = item.data end end end def ls(version = 'master') if version == :working ls_opts = { :others => true, :exclude_standard => true, :cached => true, :z => true } ls_opts_del = { :deleted => true, :exclude_standard => true, :z => true } # if output_path is in work_tree, it should be excluded if ::File.expand_path(@output_path).match(::File.expand_path(@wiki.repo.git.work_tree)) ls_opts[:exclude] = @output_path ls_opts_del[:exclude] = @output_path end cwd = Dir.pwd # need to change directories for git ls-files -o Dir.chdir(@wiki.repo.git.work_tree) deleted = @wiki.repo.git.native(:ls_files, ls_opts_del).split("\0") working = @wiki.repo.git.native(:ls_files, ls_opts).split("\0") work_tree = (working - deleted).map do |path| path = decode_git_path(path) OpenStruct.new(:path => path, :data => IO.read(path)) end Dir.chdir(cwd) # change back to original directory return work_tree else return @wiki.tree_map_for(version).map do |entry| OpenStruct.new(:path => entry.path, :data => entry.blob(@wiki.repo).data) end end end def sanitization(options) site_sanitization = Gollum::SiteSanitization.new site_sanitization.elements.concat options[:allow_elements] || [] site_sanitization.attributes[:all].concat options[:allow_attributes] || [] site_sanitization.protocols['a']['href'].concat options[:allow_protocols] || [] site_sanitization end # Public: generate the static site def generate() prepare ::Dir.mkdir(@output_path) unless ::File.exists? @output_path @pages.each do |name, page| SiteLog.debug("Starting page generation - #{name}") page.generate(@output_path, @version) SiteLog.debug("Finished page generation - #{name}") end @files.each do |path, data| path = ::File.join(@output_path, path) ::FileUtils.mkdir_p(::File.dirname(path)) ::File.open(path, "w") do |f| f.write(data) end end end def to_liquid { "pages" => @pages } end # Decode octal sequences (\NNN) in tree path names. # # path - String path name. # # Returns a decoded String. def decode_git_path(path) if path[0] == ?" && path[-1] == ?" path = path[1...-1] path.gsub!(/\\\d{3}/) { |m| m[1..-1].to_i(8).chr } end path.gsub!(/\\[rn"\\]/) { |m| eval(%("#{m.to_s}")) } path end end end
require 'rbbt/rest/common/users' require 'rbbt/rest/common/table' module RbbtRESTHelpers def escape_url(url) base, _sep, query = url.partition("?") base = base.split("/").collect{|p| CGI.escape(p) }* "/" if query && ! query.empty? query = query.split("&").collect{|e| e.split("=").collect{|pe| CGI.escape(pe) } * "=" } * "&" [base, query] * "?" else base end end MEMORY_CACHE = {} def old_cache(path, check) return false if production? return false if check.nil? or check.empty? return false if not File.exist? path check = [check] unless Array === check check.each do |file| if not File.exist?(file) return true end if File.mtime(file) > File.mtime(path) return true end end return false end def cache(name, params = {}, &block) @cache_type ||= params.delete :cache_type if params[:cache_type] return yield if name.nil? or @cache_type.nil? or @cache_type == :none send_file = consume_parameter(:_send_file, params) # Setup Step check = [params[:_template_file]].compact check += consume_parameter(:_cache_check, params) || [] check.flatten! orig_name = name path = if params[:cache_file] params[:cache_file] else if post_hash = params["__post_hash_id"] name = name.gsub("/",'>') << "_" << post_hash elsif params param_hash = Misc.obj2digest(params) name = name.gsub("/",'>') << "_" << param_hash end settings.cache_dir[name].find end task = Task.setup(:name => orig_name, :result_type => :string, &block) step = Step.new(path, task, nil, nil, self) halt 200, step.info.to_json if @format == :info self.instance_variable_set("@step", step) if @file send_file step.file(@file), :filename => @file end # Clean/update job clean_url = request.url clean_url = remove_GET_param(clean_url, :_update) clean_url = remove_GET_param(clean_url, :_) clean_url = add_GET_param(clean_url, "__post_hash_id", params["__post_hash_id"]) if params.include?("__post_hash_id") && @is_method_post if not @fragment and (old_cache(step.path, check) or update == :reload) begin pid = step.info[:pid] step.abort if pid and Misc.pid_exists?(pid) and not pid == Process.pid step.pid = nil rescue Exception Log.medium{$!.message} end step.clean redirect remove_GET_param(clean_url, "__post_hash_id") end class << step def url @url end end #step.instance_variable_set(:@url, clean_url) #step.instance_variable_set(:@url_path, URI(clean_url).path) step.instance_variable_set(:@url, clean_url) step.instance_variable_set(:@url_path, URI(clean_url).path) step.clean if step.error? || step.aborted? Thread.current["step_path"] = step.path # Issue if not step.started? if cache_type == :synchronous or cache_type == :sync step.run else # $rest_cache_semaphore is defined in rbbt-util etc/app.d/semaphores.rb step.fork(true, $rest_cache_semaphore) step.soft_grace end step.set_info :template_file, params[:_template_file].to_s end redirect clean_url if params.include?("__post_hash_id") && @is_method_post # Return fragment if @fragment fragment_file = step.file(@fragment) if Open.exists?(fragment_file) case @format.to_s when "query-entity" tsv, table_options = load_tsv(fragment_file, true) begin res = tsv[@entity].to_json content_type "application/json" rescue res = nil.to_json end halt 200, res when "query-entity-field" tsv, table_options = load_tsv(fragment_file, true) begin res = tsv[@entity] res = [res] if tsv.type == :single or tsv.type == :flat rescue res = nil.to_json end fields = tsv.fields content_type "application/json" hash = {} fields.each_with_index do |f,i| hash[f] = res.nil? ? nil : res[i] end halt 200, hash.to_json when "table" halt_html tsv2html(fragment_file) when "json" content_type "application/json" halt 200, tsv_process(load_tsv(fragment_file).first).to_json when "tsv" content_type "text/tab-separated-values" halt 200, tsv_process(load_tsv(fragment_file).first).to_s when "values" tsv = tsv_process(load_tsv(fragment_file).first) list = tsv.values.flatten content_type "application/json" halt 200, list.compact.to_json when "entities" raw_tsv, tsv_options = load_tsv(fragment_file) tsv = tsv_process(raw_tsv) list = tsv.values.flatten tsv.prepare_entity(list, tsv.fields.first, tsv.entity_options) type = list.annotation_types.last list_id = "List of #{type} in table #{ @fragment }" list_id << " (#{ @filter })" if @filter Entity::List.save_list(type.to_s, list_id, list, user) url = Entity::REST.entity_list_url(list_id, type) url = url + '?_layout=false' unless @layout url = escape_url(url) redirect to(url) when "map" raw_tsv, tsv_options = load_tsv(fragment_file) raw_tsv.unnamed = true tsv = tsv_process(raw_tsv) field = tsv.key_field column = tsv.fields.first if tsv.entity_templates[field] type = tsv.entity_templates[field].annotation_types.first else type = [Entity.formats[field]].compact.first || field end map_id = "Map #{type}-#{column} in #{ @fragment }" map_id << " (#{ @filter.gsub(';','|') })" if @filter Entity::Map.save_map(type.to_s, column, map_id, tsv, user) url = Entity::REST.entity_map_url(map_id, type, column) url = url + '?_layout=false' unless @layout url = escape_url(url) redirect to(url) when "excel" require 'rbbt/tsv/excel' tsv, tsv_options = load_tsv(fragment_file) tsv = tsv_process(tsv) data = nil excel_file = TmpFile.tmp_file tsv.excel(excel_file, :sort_by => @excel_sort_by, :sort_by_cast => @excel_sort_by_cast, :name => true, :remove_links => true) name = tsv_options[:table_id] name ||= "rbbt-table" name = name.sub(/\s/,'_') name = name.sub('.tsv','') send_file excel_file, :type => 'application/vnd.ms-excel', :filename => "#{name}.xls" when "heatmap" require 'rbbt/util/R' tsv, tsv_options = load_tsv(fragment_file) content_type "text/html" data = nil png_file = TmpFile.tmp_file + '.png' width = tsv.fields.length * 10 + 500 height = tsv.size * 10 + 500 width = 10000 if width > 10000 height = 10000 if height > 10000 tsv.R <<-EOF rbbt.pheatmap(file='#{png_file}', data, width=#{width}, height=#{height}) data = NULL EOF send_file png_file, :type => 'image/png', :filename => fragment_file + ".heatmap.png" when 'binary' send_file fragment_file, :type => 'application/octet-stream' else require 'mimemagic' mime = nil Open.open(fragment_file) do |io| begin mime = MimeMagic.by_path(fragment_file) if mime.nil? io.rewind mime = MimeMagic.by_magic(io) end if mime.nil? io.rewind if IO === io mime = "text/tab-separated-values" if io.gets =~ /^#/ and io.gets.include? "\t" end rescue Exception Log.exception $! end end if mime.nil? txt = Open.read(fragment_file) if txt =~ /<([^> ]+)[^>]*>.*?<\/\1>/m mime = "text/html" else begin JSON.parse(txt) mime = "application/json" rescue end end else txt = nil end if mime content_type mime else content_type "text/plain" end if mime && mime.to_s.include?("text/html") halt_html txt || Open.read(fragment_file) else if File.exist?(fragment_file) send_file fragment_file else halt 200, Open.read(fragment_file) end end end elsif Open.exists?(fragment_file + '.error') klass, _sep, message = Open.read(fragment_file + '.error').partition(": ") backtrace = Open.read(fragment_file + '.backtrace').split("\n") exception = Kernel.const_get(klass).new message || "no message" exception.set_backtrace backtrace raise exception #halt 500, html_tag(:span, File.read(fragment_file + '.error'), :class => "message") + # html_tag(:ul, File.read(fragment_file + '.backtrace').split("\n").collect{|l| html_tag(:li, l)} * "\n", :class => "backtrace") elsif Open.exists?(fragment_file + '.pid') pid = Open.read(fragment_file + '.pid') if Misc.pid_exists?(pid.to_i) halt 202, "Fragment not completed" else halt 500, "Fragment aborted" end else halt 500, "Fragment not completed and no pid file" end end # Monitor begin if step.done? case when @permalink redirect to(permalink(step.path)) when send_file send_file step.path else step.load end else case step.status when :error, :aborted error_for step, !@ajax else # check for problems begin check_step step rescue Aborted step.clean raise RbbtRESTHelpers::Retry end #if File.exist?(step.info_file) and Time.now - File.atime(step.info_file) > 60 # Log.debug{ "Checking on #{step.info_file}" } # running = (not step.done?) and step.running? # if FalseClass === running # Log.debug{ "Aborting zombie #{step.info_file}" } # step.abort unless step.done? # raise RbbtRESTHelpers::Retry # end # FileUtils.touch(step.info_file) #end wait_on step, false end end rescue RbbtRESTHelpers::Retry retry end end end
Contextually.define do roles :admin, :user, :visitor group :admin, :user, :as => :member before :user do controller.stub!(:current_user).and_return(:user) end before :visitor do controller.stub!(:current_user).and_return(nil) end before :admin do controller.stub!(:current_user).and_return(:admin) end deny_access_to :visitor do it("should deny access") { should redirect_to(new_session_url) } end deny_access do it("should deny access") { should redirect_to(root_url) } end end
require 'rails_helper' # Specs in this file have access to a helper object that includes # the ReviewsHelper. For example: # # describe ReviewsHelper do # describe "string concat" do # it "concats two strings with spaces" do # expect(helper.concat_strings("this","that")).to eq("this that") # end # end # end describe ReviewsHelper do describe '#star_rating' do context 'zero stars' do it 'returns five empty stars' do expect(star_rating(0)).to eq '☆☆☆☆☆' end end context 'one to four stars' do it 'returns one star for each point and the rest is empty' do expect(star_rating(3)).to eq '★★★☆☆' end end context 'five start' do it 'returns five filled stars' do expect(star_rating(5)).to eq '★★★★★' end end context 'float' do it 'rounds to the nearest star' do expect(star_rating(3.7)).to eq '★★★★☆' end end context 'message given instead of numerical rating' do it 'returns the message as-is' do expect(star_rating('No reviews yet')).to eq 'No reviews yet' end end end end
require 'spec_helper' describe 'pcmk_nodes_added' do context 'interface' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::Error, /Got unsupported nodes input data/) } it { is_expected.to run.with_params('foo', []).and_raise_error(Puppet::Error, /Got unsupported crm_node_list/) } end it 'returns no added nodes because cluster is not set up' do is_expected.to run.with_params('foo', '').and_return([]) is_expected.to run.with_params('foo bar', '').and_return([]) is_expected.to run.with_params('', '').and_return([]) end it 'returns added nodes when cluster is fully up' do crm_out = "\n3 ctr-2 member\n2 ctr-1 member\n1 ctr-0 member\n" is_expected.to run.with_params('ctr-0 ctr-1 ctr-2', crm_out).and_return([]) is_expected.to run.with_params('ctr-0 ctr-1 ctr-2 ctr-3', crm_out).and_return(['ctr-3']) is_expected.to run.with_params('ctr-1 ctr-3 ctr-2', crm_out).and_return(['ctr-3']) is_expected.to run.with_params('', crm_out).and_return([]) end it 'returns added nodes when cluster is not fully up' do crm_out = "\n3 ctr-2 lost\n2 ctr-1 member\n1 ctr-0 member\n" is_expected.to run.with_params('ctr-0 ctr-1 ctr-2', crm_out).and_return([]) is_expected.to run.with_params('ctr-0 ctr-1 ctr-2 ctr-3', crm_out).and_return(['ctr-3']) is_expected.to run.with_params('ctr-1 ctr-3 ctr-2', crm_out).and_return(['ctr-3']) is_expected.to run.with_params('', crm_out).and_return([]) end end
class Note < ActiveRecord::Base attr_accessible :note, :page, :book, :user scope :of_user, lambda { |user_id| where("user_id = ?", user_id) } default_scope order('page, created_at') belongs_to :book belongs_to :user end
class TagGroup < ActiveRecord::Base validates_presence_of :name validates_uniqueness_of :name has_many :company_tag_groups has_many :companies, :through => :company_tag_groups, :after_add => :after_add_company, :after_remove => :after_remove_company named_scope :search_name, lambda { |s| {:conditions => ["name REGEXP '%s'", s] }} named_scope :search_name_and_tags, lambda { |s| {:conditions => ["name REGEXP '%s' OR tags REGEXP '%s'", s, s] }} # find tag groups with no tags named_scope :empty, { :conditions => ["tags = '' OR tags IS NULL"] } named_scope :order_by_name, { :order => "name ASC" } named_scope :order_by_companies_count, { :order => "companies_count DESC" } # tags have a limited word length TAG_MAX_WORDS = 3 def self.to_csv csv = TagGroup.all.collect do |o| "#{o.id}|#{o.name}|#{o.tags}" end end def after_initialize # after_initialize can also be called when retrieving objects from the database return unless new_record? # initialize applied_at timestamp for new objects self.applied_at = Time.now end def name=(s) return if s.blank? # capitalize words, except for 'and', 'or' s = s.split.map{ |s| ['and', 'or'].include?(s.downcase) ? s : s.capitalize }.join(" ") write_attribute(:name, s) end # tags can be a comma separated list or an array def tags=(s) s = TagGroup::validate_and_clean_string(s) write_attribute(:tags, s.join(",")) end # tags to add as a comma separated list or an array def add_tags(s) s = TagGroup::validate_and_clean_string(s) t = tag_list s = (t + s).uniq.sort # keep track of recently added tags write_attribute(:recent_add_tags, (s-t).join(",")) write_attribute(:tags, s.join(",")) end # tags to remove as a comma separated list or an array def remove_tags(s) s = TagGroup::validate_and_clean_string(s) t = tag_list s = (t - s).uniq.sort # keep track of recently removed tags write_attribute(:recent_remove_tags, (t-s).join(",")) write_attribute(:tags, s.join(",")) end # build the tag list array from the tags string def tag_list Array.new(self.tags ? self.tags.split(",") : []) end def recent_add_tag_list Array.new(self.recent_add_tags ? self.recent_add_tags.split(",") : []) end def recent_remove_tag_list Array.new(self.recent_remove_tags ? self.recent_remove_tags.split(",") : []) end # (re-)apply tags to all companies def apply companies.each { |company| apply_tags(company) } # update applied_at timestamp update_attribute(:applied_at, Time.now) end def dirty? self.applied_at < self.updated_at end # convert tag group to a string of attributes separated by '|' def to_csv [self.id, self.name, self.tags].join("|") end protected def self.validate_and_clean_string(s) raise ArgumentError, "expected String or Array" unless [String, Array].include?(s.class) case s.class.to_s when "String" s = clean(s.split(",")) when "Array" s = clean(s) end s end def self.clean(array) array.reject(&:blank?).map{|s| s.split(/\S+/).size > TAG_MAX_WORDS ? nil : s.downcase.strip }.compact.uniq.sort end def apply_tags(company) return false if company.blank? company.tag_list.add(tag_list) company.save end def after_add_company(company) apply_tags(company) end def after_remove_company(company) return if company.blank? company.tag_list.remove(tag_list) company.save # decrement companies_count counter cache # TODO: find out why the built-in counter cache doesn't work here TagGroup.decrement_counter(:companies_count, id) end end
# Method to create a list # input: string of items separated by spaces (example: "carrots apples cereal pizza") # steps: # Create a hash with items and associated quantities. # set default quantity # print the list to the console using print method # output: hash def create_a_list(items) item_array = items.split shopping_list = {} item_array.each do |x| shopping_list[x] = 1 end #shopping_list.store(items) shopping_list end my_list = create_a_list("carrots apples cereal pizza") #p my_list # Method to add an item to a list # input: list, item name, and optional quantity # steps: Add an item in the list with the quantity. # output: print each item out with the associated quantity. (hash) def add_item(list, key, quantity) list["#{key}"] = quantity list end add_item(my_list, "bananas", 2) #p my_list # Method to remove an item from the list # input: list, item # steps: Remove key from hash (list). # output: New hash without the item. def deleted_item(list, key) list.delete_if {|k, v| k == "#{key}"} list end puts deleted_item(my_list, "carrots") #p my_list # Method to update the quantity of an item # input: list, item, quantity # steps: Update the value and the associated key. # output: New hash with updated quantity. def update_quantity(list, key, quantity) list["#{key}"] = quantity list end puts update_quantity(my_list, "pizza", 5) # Method to print a list and make it look pretty # input: list # steps: print "Your shopping list: key -- value". # output: Interpolated pretty hash. def print_list(list) puts "Your shopping list:" list.each do |k, v| puts "#{k} -- #{v}" end end print_list(my_list)
# frozen_string_literal: true require 'spec_helper' describe PagerdutyRestApi::HttpTransport do describe '#get' do let(:faraday) { instance_double(Faraday::Connection).as_null_object } before do allow(Faraday).to receive(:new).with(url: 'https://api.pagerduty.com') .and_yield(faraday) .and_return(faraday) end it 'should send a GET request to the given endpoint' do expect(faraday).to receive(:get).with('/some/endpoint') subject.get('/some/endpoint') end it 'should configure the REST client properly' do expect(faraday).to receive(:adapter).with(Faraday.default_adapter) subject.get('/some/endpoint') end end end
class ChangeJobsV2 < ActiveRecord::Migration[5.0] def change change_column :jobs, :description, :text, default: nil change_column :jobs, :field, :integer, default: 0 end end
require_relative '../spec_helper' require "./app/services/text_sampler" describe TextSampler, type: :service do sampler = TextSampler.new it 'sample a random file' do expect(sampler.randomize_file.file).not_to be_nil expect(sampler.randomize_file.file.class).to eql File expect(sampler.randomize_file.file.path).to match /texts\/\d+/ end it 'returns nil for text if no file has been sampled yet' do expect(TextSampler.new.text).to be_nil end it 'can read text of random file' do expect(sampler.text).not_to be_nil expect(sampler.text.class).to eql String end end
require "spec_helper" describe M::Either do it_behaves_like "a monad" describe "shortcut methods" do it "Right() is a shortcut to Right.return" do expect(Right(1)).to eq Right.return(1) expect(Right("1")).to eq Right.return("1") expect(Right(nil)).to eq Right.return(nil) end it "Left() is a shortcut to Left.return" do expect(Left(1)).to eq Left.return(1) expect(Left("1")).to eq Left.return("1") expect(Left(nil)).to eq Left.return(nil) end end describe ".return" do it "wraps any Exception into Left" do expect(Either.return(Exception.new)).to eq Left(Exception.new) expect(Either.return(RuntimeError.new)).to eq Left(RuntimeError.new) end it "wraps any other into Right" do expect(Either.return(1)).to eq Right(1) expect(Either.return("1")).to eq Right("1") expect(Either.return(nil)).to eq Right(nil) end end describe ".fail" do it "wraps given value into Left" do expect(Either.fail(1)).to eq Left(1) expect(Either.fail(nil)).to eq Left(nil) expect(Either.fail(Exception.new)).to eq Left(Exception.new) end end describe "#fmap" do context "Left" do it "returns self" do f = ->(v){ v + 1 } expect(Left(1).fmap(f)).to eq Left(1) end it "doesn't cause side effects" do @var = false f = ->(v){ @var = true } expect{ Left(1).fmap(f) }.to_not change{ @var } end end context "Right" do it "performs calculation" do @var = false f = ->(v){ @var = true; v + 1 } expect{ Right(1).fmap(f) }.to change{ @var } expect(Right(1).fmap(f)).to eq Right(2) end end it "wraps any occuring error with Left" do f = ->(v){ fail StandardError.new("error") } result = Right(1).fmap(f) expect(result).to be_a Left expect(result.fetch).to be_a StandardError expect(result.fetch.message).to eq "error" end end describe "#bind" do context "Left" do it "returns self" do f = ->(v){ Right(v + 1) } expect(Left(1).bind(f)).to eq Left(1) end it "doesn't cause side effects" do @var = false f = ->(v){ Right(@var = true) } expect{ Left(1).bind(f) }.to_not change{ @var } end end context "Right" do it "performs calculation" do @var = false f = ->(v){ @var = true; Right(v + 1) } expect{ Right(1).bind(f) }.to change{ @var } expect(Right(1).bind(f)).to eq Right(2) end end it "wraps any occuring error into Left" do f = ->(v){ fail StandardError.new("error") } result = Right(1).bind(f) expect(result).to be_a Left expect(result.fetch).to be_a StandardError expect(result.fetch.message).to eq "error" end end end
user = node['ubuntu_i3-gaps_workstation']['user'] i3_repo_path = "#{node['ubuntu_i3-gaps_workstation']['tmp_dir']}/i3-gaps" # Install required packages listed here: https://github.com/Airblader/i3/wiki/Compiling-&-Installing#1610- %w[ libxcb1-dev libxcb-keysyms1-dev libpango1.0-dev libxcb-util0-dev libxcb-icccm4-dev libyajl-dev libstartup-notification0-dev libxcb-randr0-dev libev-dev libxcb-cursor-dev libxcb-xinerama0-dev libxcb-xkb-dev libxkbcommon-dev libxkbcommon-x11-dev autoconf libxcb-xrm0 libxcb-xrm-dev automake ].each do |package| package "install_#{package}" do package_name package end end # Clone the i3-gaps repository git i3_repo_path do repository node['ubuntu_i3-gaps_workstation']['i3-gaps']['repo_url'] revision 'gaps-next' user user group user end # Generate the i3-gaps configuration files execute 'run_autoreconf' do command 'autoreconf --force --install' cwd i3_repo_path user user live_stream true end # Delete the i3-gaps/build directory and its content if it exists directory "#{i3_repo_path}/build" do recursive true action :delete end # Create the i3-gaps/build directory directory "#{i3_repo_path}/build" do user user group user end # Configure i3-gaps before compiling it execute 'configure_i3-gaps' do command '../configure --prefix=/usr --sysconfdir=/etc --disable-sanitizers' cwd "#{i3_repo_path}/build" user user live_stream true end # Compile i3-gaps execute 'compile_i3-gaps' do command 'make' cwd "#{i3_repo_path}/build" user user live_stream true end # Install i3-gaps execute 'install_i3-gaps' do command 'make install' cwd "#{i3_repo_path}/build" live_stream true end # Cleanup directory i3_repo_path do recursive true action :delete end
class User < ApplicationRecord include Name require 'open-uri' belongs_to :host, -> {where(visible: true)}, counter_cache: true, optional: true belongs_to :seat, optional:true belongs_to :game, optional: true belongs_to :mod, optional: true has_many :api_keys has_many :identities, -> {where(enabled: true).where(banned: false)} def as_json(options={}) super(:only => [:clan, :handle], :methods => [:playing], :include => { :seat => {:only => [:seat, :section, :row, :number]}, :host => {:only => [:url]}, :identities => {:only => [:uid, :provider, :name, :url, :avatar]} } ) end scope :active, -> { where( banned: false ) } def self.create_with_omniauth User.create end def self.update_with_omniauth(user_id, name) user = User.find_by(:id => user_id) if user.auto_update == true name = Name.clean_name(name) user.update_attributes( clan: set_clan(name, user.id, user.seat_id), handle: set_handle(name, user.id, user.seat_id) ) end end def User.update(player, host_id, game_id, mod_id=nil) identity = Identity.find_by(:uid => player["steamid"], :provider => :steam) user = User.find_by(:id => identity.user_id) if identity.nil? puts "Could not find Identity for #{player["steamid"]}" return end if user.nil? puts "Could not find User for #{player["steamid"]}" return end if user.auto_update == false user.update_attributes( :host_id => host_id, :updated => true ) return end unless identity.name == player["personaname"] identity.update_attribute(:name, Name.clean_name(player["personaname"])) end unless identity.url == player["profileurl"] identity.update_attribute(:url, Name.clean_url(player["profileurl"])) end unless identity.avatar == player["avatar"] identity.update_attribute(:avatar, Name.clean_url(player["avatar"])) end user.update_attributes( :host_id => host_id, :game_id => game_id, :mod_id => mod_id, :clan => set_clan(player["personaname"], user.id, user.seat_id), :handle => set_handle(player["personaname"], user.id, user.seat_id), :updated => true ) end def User.url_cleanup(url) return nil unless url.include? "steamcommunity.com" unless url.start_with? "steamcommunity.com" url.slice!(0..(url.index('steamcommunity.com')-1)) end url.prepend("https://") if url.last != "/" url << "/" end return url end def User.steamid_from_url(url) begin url = url_cleanup(url) html = URI.open("#{url}?xml=1") doc = Nokogiri::XML(html) return doc.at_css("steamID64").text rescue => e return nil end end def User.search_summary_for_seat(steamid, seat) begin url = "https://steamcommunity.com/profiles/#{steamid}/" html = URI.open(url) doc = Nokogiri::HTML(html) if doc.css('div.profile_summary').blank? return "Please set your steam profile to public to link your seat." end if doc.css('div.profile_summary').text.include? seat return true else return "Could not find #{seat} in your steam profile summary." end rescue => e return "Unable to read your steam profile. Please try again." end end def User.update_seat_from_omniauth(user_id, seat_id) success = false message = "" user = User.find_by(id: user_id) if user.nil? message = "That user doesn't exist!" return {:success => success, :message => message} end seat = Seat.where(:seat => seat_id).first if seat.nil? message = "That seat doesn't exist!" return {:success => success, :message => message} end #just for 2020 taken_seat = User.where(seat_id: seat.id).first if !taken_seat.nil? && taken_seat.id != user.id message = "That seat is taken!" return {:success => success, :message => message} end if seat == user.seat message = "You're linked to #{seat.seat}!" return {:success => true, :message => message} end if (user.banned == true) message = "You're linked to #{seat.seat}!" return {:success => true, :message => message} end success = user.update_attributes( :seat_id => seat.id, :seat_count => user.seat_count + 1 ) if success == true message = "You're linked to #{seat.seat}!" return {:success => success, :message => message} else message = "Unable to save your seat." return {:success => success, :message => message} end end def User.update_seat(seat_id, url) success = false message = "" if seat_id.nil? message = "Please select a seat." return {:success => success, :message => message} end if url.nil? message = "Please enter your profile URL" return {:success => success, :message => message} end url = User.url_cleanup(url) unless url.start_with?('http://steamcommunity.com/id/','http://steamcommunity.com/profiles/','https://steamcommunity.com/id/','https://steamcommunity.com/profiles/') message "Please enter a valid profile URL" return {:success => success, :message => message} end steamid = User.steamid_from_url(url) if steamid.nil? message = "Could not parse steamid from URL. Please check the url and try again." return {:success => success, :message => message} end seat = Seat.where(:seat => seat_id).first if seat.nil? message = "Unknown seat." return {:success => success, :message => message} end response = search_summary_for_seat(steamid, seat.seat) if response == false message = response return {:success => success, :message => message} end user = User.lookup(steamid) #just for 2020 taken_seat = User.where(seat_id: seat.id).first if !taken_seat.nil? && taken_seat.id != user.id message = "That seat is taken!" return {:success => success, :message => message} end if seat == user.seat message = "You're linked to #{seat.seat}!" return {:success => true, :message => message} end unless (user.banned == true) user.update_attributes( :seat_id => seat.id, :seat_count => user.seat_count + 1 ) User.fill(steamid) end success = true message = "You're linked to #{seat.seat}!" return {:success => success, :message => message} end def User.lookup(steamid) identity = Identity.find_by(uid: steamid, provider: :steam) if identity.nil? identity = Identity.create(uid: steamid, provider: :steam, enabled: true) end if identity.user_id.nil? user = User.create identity.user = user identity.save end return identity.user end def User.fill(steamid) parsed = SteamWebApi.get_json(SteamWebApi.get_player_summaries + steamid) if parsed != nil parsed["response"]["players"].each do |player| User.update(player, nil, nil) end end end def User.set_clan(username, user_id, seat_id) return nil if username.blank? h = Name.clean_name(username) if h.match(/^\[.*\S.*\].*\S.*$/) h.split(/[\[\]]/)[1].strip else nil end end def User.set_handle(username, user_id, seat_id) return nil if username.blank? handle = Name.clean_name(username) handle = handle.index('#').nil? ? handle : handle[0..(handle.rindex('#')-1)] if handle.match(/^\[.*\S.*\].*\S.*$/) handle = handle.split(/[\[\]]/)[-1].strip end return handle end def display_handle if seat_id.nil? handle else prepend_seat(handle, id, seat_id) end end def prepend_seat(handle, user_id, seat_id) return handle if seat_id.blank? seat = User.find_by(:id => user_id).seat unless seat.nil? handle.prepend("[#{seat.seat}] ") end end def url Identity.where(:user_id => id).specific(:steam).url end def playing if mod_id? mod.name elsif game_id? game.name else nil end end end
class AddLocationToTapiocas < ActiveRecord::Migration def change change_table :tapiocas do |t| t.string :location end end end
module CheckArchivedFlags class FlagCodes def self.archived_codes { "NONE" => NONE, "TRASHED" => TRASHED, "UNCONFIRMED" => UNCONFIRMED, "PENDING_SIMILARITY_ANALYSIS" => PENDING_SIMILARITY_ANALYSIS, "SPAM" => SPAM } end NONE = 0 # Default, means that the item is visible in lists and "all items" and actionable (can be annotated) # All other values mean that the item is hidden and not actionable until reverted to zero TRASHED = 1 # When a user sends an item to the trash or when a rule action sends an item to a trash UNCONFIRMED = 2 # When the item is submitted by a tipline user without explicit confirmation PENDING_SIMILARITY_ANALYSIS = 3 # When an item is submitted throught the tipline but was not analyzed by the text similarity yet (Alegre Bot)... after similarity analysis, it goes back to zero SPAM = 4 # When a user sends an item to the spam list end end
class CreateReadingWorker include Sidekiq::Worker sidekiq_options queue: 'critical' def perform(thermostat_id, household_token, reading_params = {}) reading_params = eval(reading_params) reading = Reading.create(reading_params.merge(thermostat_id: thermostat_id)) if !reading.blank? && !household_token.blank? TrackingNumberWorker.perform_async(reading.id, household_token) end end end
class CreateEasySettings < ActiveRecord::Migration def self.up create_table :easy_settings do |t| t.string :name t.text :value t.integer :project_id end end def self.down drop_table :easy_settings end end
require "minitest_helper" feature "Create list" do scenario "adding a new list" do # Given visit lists_path click_on "New List" fill_in "List name", with: "Personal To Do List" # When click_on "Create List" # Then page.text.must_include "List was successfully created" page.text.must_include "Personal To Do List" end end
class Discussion < ActiveRecord::Base validates :summary, presence: true validates :article, presence: true belongs_to :article, inverse_of: :discussions belongs_to( :source_discussion, class_name: "Discussion", primary_key: :id, foreign_key: :branched_from_discussion_id, inverse_of: :branches ) has_many :comments, dependent: :destroy, order: :created_at has_many( :branches, class_name: "Discussion", primary_key: :id, foreign_key: :branched_from_discussion_id, dependent: :nullify ) def visible_branches branches.where(visible: true) end # Banish and promote both remove a comment and all of its children into # a parallel discussion. Promote advertises it at the top of the discussion # page; banish just does it invisibly. def banish(comment) comment.form_new_discussion(hide: true) end def promote(comment) comment.form_new_discussion end # The only reason this method belongs to discussion instead of comment # is so that discussion can grab all its comments in a single db action def find_children_of(comment) children = [] all_comments = comments_by_parent to_check = [comment] until to_check.empty? current = to_check.shift children << current to_check += all_comments[current.id] end children end private def comments_by_parent hashed = Hash.new { |h, k| h[k] = [] } # TODO: may need to .to_a this to avoid needless db hits comments.reload.each do |comment| hashed[comment.parent_id] << comment end hashed end end
require 'rails_helper' RSpec.describe QuestionsController, type: :controller do describe 'GET #index' do let(:questions){FactoryGirl.create_list(:question,2)} before { get :index } it 'populates array of all Q' do expect(assigns(:questions)).to match_array(questions) end it 'renders index view' do expect(response).to render_template :index end end describe 'GET #show' do let(:question){FactoryGirl.create(:question)} before { get :show, id: question.id } it 'assign requested question by ID' do expect(assigns(:question)).to eq question end it 'asigns new answer for question' do expect(assigns(:answer)).to be_a_new(Answer) end it 'renders show view' do expect(response).to render_template :show end end describe 'GET #new' do sign_in_user before { get :new } it 'assigned new question to question' do expect(assigns(:question)).to be_a_new(Question) end it 'renders new view' do expect(response).to render_template :new end end describe 'GET #edit' do sign_in_user let(:question){FactoryGirl.create(:question)} before { get :edit , id: question} it 'assign requested question by ID' do expect(assigns(:question)).to eq question end it 'renders edit view' do expect(response).to render_template :edit end end describe 'POST #create' do sign_in_user context 'with valid attr' do it 'save new question in db' do expect { post :create , question: FactoryGirl.attributes_for(:question) }.to change(Question, :count).by(1) end it 'make redirect to show view' do post :create , question: FactoryGirl.attributes_for(:question) expect(response).to redirect_to question_path(assigns(:question)) end end context 'with invalid attr' do it 'doesnot save question' do expect { post :create , question: FactoryGirl.attributes_for(:invalid_question) }.to_not change(Question, :count) end it 'rerender new view' do post :create , question: FactoryGirl.attributes_for(:invalid_question) expect(response).to render_template :new end end end describe 'PATCH #update' do sign_in_user let(:question){FactoryGirl.create(:question)} context 'valid attr' do it 'assign requested question to @question' do patch :update, id: question.id, question: FactoryGirl.attributes_for(:question) expect(assigns(:question)).to eq question end it 'change question attr' do patch :update, id: question.id, question: {title: 'new title', body: 'new body'} question.reload expect(question.title).to eq 'new title' expect(question.body).to eq 'new body' end it 'rerender update view' do patch :update, id: question,question: FactoryGirl.attributes_for(:question) expect(response).to redirect_to question end end context 'with invalid attr' do it 'doesnot change question attr' do patch :update, id: question.id, question: {title: 'new title', body: nil} question.reload expect(question.title).to eq 'MyString' expect(question.body).to eq 'MyText' end it 'rerender edit view ' do patch :update, id: question.id, question: {title: 'new title', body: nil} expect(response).to render_template :edit end end end describe 'DELETE #destroy' do sign_in_user let(:question){FactoryGirl.create(:question)} it 'delete question' do question expect { delete :destroy, id: question }.to change(Question,:count).by(-1) end it 'rerender edit view ' do delete :destroy, id: question expect(response).to redirect_to questions_path end end end
Rails.application.routes.draw do devise_for :users root 'shows#index' resource :shows patch 'shows/edit' end
apiconfig = YAML.load(File.open(Rails.root.to_s + "/config/apiconfig.yml")) TweetStream.configure do |config| config.consumer_key = apiconfig["twitter"]["citore"]["consumer_key"] config.consumer_secret = apiconfig["twitter"]["citore"]["consumer_secret"] config.oauth_token = apiconfig["twitter"]["citore"]["bot"]["access_token_key"] config.oauth_token_secret = apiconfig["twitter"]["citore"]["bot"]["access_token_secret"] config.auth_method = :oauth end natto = ApplicationRecord.get_natto extra_info = ExtraInfo.read_extra_info citore_client = TwitterRecord.get_twitter_rest_client("citore") sugarcoat_client = TwitterRecord.get_twitter_rest_client("sugarcoat") sugarcoat_keywords = ['@sugarcoat_bot', '#sugarcoat'] citore_keywords = ['#citore', '@citore_bot'] CacheStore.cache! stream_client = TweetStream::Client.new stream_client.track('#citore', '@citore_bot', '@sugarcoat_bot', '#sugarcoat') do |status| next if status.lang != "ja" || ["811029389575979008", "811024427487936512"].include?(status.user.id.to_s) sanitaized_word = TwitterRecord.sanitized(status.text) without_url_tweet, urls = ApplicationRecord.separate_urls(sanitaized_word) if citore_keywords.any?{|k| without_url_tweet.include?(k) } reading = ApplicationRecord.reading(without_url_tweet) erotic_word = Citore::EroticWord.reading_words.detect{|r| reading.include?(r) } citore_client.update("@#{status.user.screen_name} テスト") end if citore_keywords.any?{|k| without_url_tweet.include?(k) } reading = ApplicationRecord.reading(without_url_tweet) sugarcoat_client.update("@#{status.user.screen_name} テスト") end end
require 'rails_helper' RSpec.describe "contents/new", type: :view do before(:each) do assign(:content, Content.new( :userid => 1, :post => "MyText" )) end it "renders new content form" do render assert_select "form[action=?][method=?]", contents_path, "post" do assert_select "input#content_userid[name=?]", "content[userid]" assert_select "textarea#content_post[name=?]", "content[post]" end end end
module ProjectRazor module PolicyTemplate # ProjectRazor Policy Default class # Used for default booting of Razor MK class BootMK < ProjectRazor::PolicyTemplate::Base include(ProjectRazor::Logging) # @param hash [Hash] def initialize(hash) super(nil) @hidden = :true @template = :hidden @description = "Default MK boot object. Hidden" @data = ProjectRazor::Data.instance @data.check_init @config = @data.config end # TODO - add logging ability from iPXE back to Razor for detecting node errors def get_boot_script image_svc_uri = "http://#{@config.image_svc_host}:#{@config.image_svc_port}/razor/image" rz_mk_boot_debug_level = @config.rz_mk_boot_debug_level # only allow values of 'quiet' or 'debug' for this parameter; if it's anything else set it # to an empty string rz_mk_boot_debug_level = '' unless ['quiet','debug'].include? rz_mk_boot_debug_level boot_script = "" boot_script << "#!ipxe\n" boot_script << "kernel #{image_svc_uri}/mk/kernel maxcpus=1" boot_script << " #{rz_mk_boot_debug_level}" if rz_mk_boot_debug_level && !rz_mk_boot_debug_level.empty? boot_script << " || goto error\n" boot_script << "initrd #{image_svc_uri}/mk/initrd || goto error\n" boot_script << "boot || goto error\n" boot_script << "\n\n\n" boot_script << ":error\necho ERROR, will reboot in #{@config.mk_checkin_interval}\nsleep #{@config.mk_checkin_interval}\nreboot\n" boot_script end end end end
# encoding: utf-8 class SessionsController < ApplicationController skip_before_filter :check_login before_filter :filter_login def new @hide_footer = true end def create @hide_footer = true auth = request.env["omniauth.auth"] if (User.find_by_provider_and_uid(auth["provider"], auth["uid"])) user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) else user = User.create_with_omniauth(auth) end session[:user_id] = user.id redirect_to root_url end def destroy session[:user_id] = nil redirect_to login_url, notice: "Byl jste úspěšně odhlášen" end def failure redirect_to login_url, notice: "Chybná kombinace e-mailu a hesla" end end
require 'rails_helper' RSpec.describe User, type: :model do it "is valid with a name, email, password and admin" do user= User.new(name: "name", email: "test@e.mail", password: "password", admin: false) expect(user).to be_valid end it "is invalid without a name" do user= User.new(email: "test@e.mail", password: "password", admin: false) expect(user).not_to be_valid end it "is invalid without an email" do user= User.new(name: "name", password: "password", admin: false) expect(user).not_to be_valid end it "is invalid without a password" do user= User.new(name: "name", email: "test@e.mail", admin: false) expect(user).not_to be_valid end it "is valid without setting admin because of default value" do user= User.new(name: "name", email: "test@e.mail", password: "password") expect(user).to be_valid end end
class Machine < ApplicationRecord has_one :desk, dependent: :nullify has_many :assignment_histories, class_name: 'DeskAssignmentHistory', dependent: :nullify validates :mac, presence: true def mac=(value) write_attribute(:mac, normalize_mac(value)) end def normalize_mac(value) value.gsub(/:/, '').downcase.chars.each_slice(2).map(&:join).join(':') end end
require 'fileutils' module ActiveFile def save @new_record = false File.open("db/revistas/#{@id}.yml", "w") do |file| file.puts serialize end end def destroy unless @destroy or @new_record @destroyed = true FileUtils.rm "db/revistas/#{@id}.yml" end end module ClassMethods def find(id) raise DocumentNotFound, "Arquivo db/revistas/#{id} nao encontrado.", caller unless File.exists?("db/revistas/#{id}.yml") YAML.load File.open("db/revistas/#{id}.yml", "r") end end def next_id Dir.glob("db/revistas/*yml").size + 1 end def field(name) @fields ||= [] @fields << name get = %Q{ def #{name} @#{name} end } set = %Q{ def #{name}=(valor) @#{name}=valor end } self.class_eval get self.class_eval set end end def self.included(base) base.extend ClassMethods base.class_eval do attr_reader :id, :destroyed, :new_record def initialize(parameters = {}) @id = self.class.next_id @destroyed = false @new_record = true parameters.each do |key, value| instance_variable_set "@#{key}", value end end end end def method_missing(name, *args, &block) super unless name.to_s =~ /^find_by_/ argument = args.first field = name.to_split("_").last super if @fields.include? field load_all.select do |object| shoud_select? object, field, argument end end private def should_select?(object, field, argument) if argument.kind_of? Regexp object.send(field) =~ argument else object.send(field) == argument end end def load_all Dir.glob('db/revistas/*.yml').map do |file| deserialize file end end def deserialize(file) YAML.load File.open(file, "r") end end
class NotHexError < StandardError def initialize(msg="Please input a valid hexadecimal value. Value should be between 3-6 digits.") super(msg) end end
module Sandra class SuperColumnValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) if record.attributes[attribute.to_s].nil? record.errors[attribute] << "#{attribute.to_s} cannot be nil." else record.errors[attribute] << "#{record.send(attribute.to_s)} has been taken under this key." if record.new_record? && record.class.get(record.attributes[record.class.key.to_s], record.attributes[attribute.to_s]) end end end end
class Valllnparam < ApplicationRecord belongs_to :mpoint, inverse_of: :valllnparams belongs_to :line, inverse_of: :valllnparams end
require_relative 'spec_helper' describe 'API Spec' do subject(:api) { Hyperclient.new(api_root) } it 'return a HAL API description' do expect(api._response.status).to eql(HTTP_OK) expect(api._response[:content_type]).to eql(HAL) end it 'does not contain embedded entities' do expect(api._embedded.to_a).to be_empty end it 'does contain links' do expect(api._links.to_a).not_to be_empty end it 'links use the item IANA link relation' do expect(api._links.to_h.keys).to eql(['item']) end it 'can navigate to "nanopub" resource' do nanopub_link = api._links.item.find { |item| item._url =~ %r{/nanopub$} } expect(nanopub_link._options._response.status).to eq(HTTP_OK) expect(nanopub_link._options._response[:allow]).to eq('OPTIONS,POST,GET') end end
class ParticipantsController < ApplicationController before_action :authenticate_user! def index @people = Participant.all @search = Participant.search(params[:q]) @participants = @search.result.page(params[:page]) @search.build_condition # if @search.nil? # respond_to do |format| # format.html # format.csv { send_data @people.to_csv, :filename => 'Participant-list.csv' } # end # end end def search index render :index end def new @participant = Participant.new end def create @participant = Participant.new(participant_params) if @participant.save flash[:notice] = "Entry Saved Successfully." redirect_to participant_path(@participant.id) else render 'new' end end def show @xxs = "7–7.4" @xs = "7.5–7.8" @s = "7.9–8.2" @m = "8.3–8.6" @l = "8.7–9.0" @xl = "9.1–9.2" @xxl = "9.5–9.8" @xxxl = "9.9–10.3" @participant = Participant.find(params[:id]) end def edit @xxs = "7–7.4" @xs = "7.5–7.8" @s = "7.9–8.2" @m = "8.3–8.6" @l = "8.7–9.0" @xl = "9.1–9.2" @xxl = "9.5–9.8" @xxxl = "9.9–10.3" @participant = Participant.find(params[:id]) end def update @participant = Participant.find(params[:id]) if @participant.update(participant_params) flash[:notice] = "Participant Updated Successfully" redirect_to participant_path(@participant.id) else render 'edit' end end def destroy @participant = Participant.find(params[:id]) @participant.destroy flash[:notice] = "Participant Successfully Deleted." redirect_to new_participant_path end private def participant_params params.require(:participant).permit(:fname, :lname, :address, :city, :state, :zipcode, :email, :sales_area, :discipline, :participant_type, :age, :gender, :ethnicity, :height_ft, :height_in, :weight, :bra_size, :chest, :natural_waist, :low_hip, :high_hip, :inseam, :thigh, :upper_arm, :sleeve_length, :shoe_size, :lf_width, :lf_heel_to_arch, :lf_heel_to_toe, :rf_width, :rf_heel_to_arch, :rf_heel_to_toe, :lh_palm_width_flat, :lh_palm_width_round, :lh_palm_length, :lh_middle_finger, :rh_palm_width_flat, :rh_palm_width_round, :rh_palm_length, :rh_middle_finger, :tops_size, :alpha_bottoms, :numeric_bottoms, :comments, :phone, :stated_shoe_size, :stated_height_ft, :stated_height_in, :stated_pants_waist, :stated_pants_inseam, :stated_weight, :pant_waist) end end
class AddServiceToShippingMethods < ActiveRecord::Migration def change add_column :shipping_methods, :service, :string end end
require 'ecraft/extensions/mixins/hashable' module Ecraft module Extensions module Mixins describe Hashable do let(:klass) { Class.new do include Hashable end } subject do klass.new end let(:array_test_data) { ['', '123', 1232, '1232 '] } let(:array_test_response) { ['', '123', 1232, '1232'] } let(:object_test) { Struct.new(:foo) do def to_h { foo: foo.upcase } end end.new('bar') } let(:object_result) { { foo: 'BAR' } } describe '#to_h' do context 'when passing an Array of values' do it 'trims all instances' do result = subject.to_h(array_test_data) expect(result).to eq array_test_response end end context 'when passing an Array of Hashes' do let(:symbol_key_hash) do { foo: 'bar ' } end let(:string_key_hash) do { 'foo' => 'bar ' } end let(:stripped_symbol_key_hash) { { foo: 'bar' } } it 'trims and symbolizes all instances' do result = subject.to_h([symbol_key_hash, string_key_hash]) expect(result).to eq [stripped_symbol_key_hash, stripped_symbol_key_hash] end end context 'when passing an Array of Structs' do it 'returns the expected result' do result = subject.to_h([object_test]) expect(result).to eq [object_result] end end context 'when passing a Struct' do it 'calls the to_h metod' do result = subject.to_h(object_test) expect(result).to eq object_result end end context 'when passing a Hash' do let(:source_data) do { foo: 'bar ', bar: 'baz ' } end let(:expected_result) do { foo: 'bar', bar: 'baz' } end it 'strips whitespace from all values' do result = subject.to_h(source_data) expect(result).to eq expected_result end end context 'when passing a Hash with String keys' do let(:source_data) do { 'foo' => 'bar ' } end let(:expected_result) { { foo: 'bar' } } it 'strips whitespace from all values and symbolizes the keys' do result = subject.to_h(source_data) expect(result).to eq expected_result end end context 'when passing a Hash with Symbol keys' do let(:source_data) { { foo: 'bar ' } } let(:expected_result) { { foo: 'bar' } } it 'strips whitespace from all values' do result = subject.to_h(source_data) expect(result).to eq expected_result end end context 'when passing an OpenStruct' do let(:source_data) { OpenStruct.new(foo: 'bar') } let(:expected_result) { { foo: 'bar' } } it 'returns the expected result' do result = subject.to_h(source_data) expect(result).to eq expected_result end end context 'when passing an arbitrary object' do let(:source_data) { Class.new do def initialize # Whitespace in values will be automatically trimmed even for PORO objects... @foo = 'bar ' @baz = 'zot' end end.new } let(:expected_result) { { # ...like this. foo: 'bar', baz: 'zot' } } it 'returns the expected result' do result = subject.to_h(source_data) expect(result).to eq expected_result end end end end end end end
class Account < ApplicationRecord belongs_to :account_type belongs_to :account_sheet end
require 'rubygems' require 'bundler' begin Bundler.setup(:default, :development) rescue Bundler::BundlerError => e $stderr.puts e.message $stderr.puts "Run `bundle install` to install missing gems" exit e.status_code end require 'rack' require 'rspec/core/rake_task' RSpec::Core::RakeTask.new(:spec) do |spec| spec.pattern = FileList['spec/api/*_spec.rb'] end task :default => :spec task :test => :spec task :environment do ENV["RACK_ENV"] ||= 'development' require File.expand_path("../config/environment", __FILE__) end desc "API Routes" task routes: :environment do EasyPaint::API.routes.each do |api| method = api.route_method.ljust(10) path = api.route_path puts " #{method} #{path}" end end
dir = File.dirname(__FILE__) require "#{dir}/../spec_helper" describe Gallery::Generator do attr_reader :generator before do fixtures_path = "#{dir}/../fixtures" @generator = Gallery::Generator.new(fixtures_path) end describe "#generate" do it "takes a recipe and returns an index page based on it" do content = generator.generate content.should match(/2392/) content.should match(/2391/) content.should match(/2390/) content.should match(/07\/31\/2008/) content.should match(/06\/15\/2008/) content.should match(/04\/10\/2008/) content.should match(/2392_Silverlign_2008_07_31/) content.should match(/2391_Silverlign_2008_06_15/) content.should match(/2390_Silverlign_2008_04_10/) puts content end end describe "#recipe" do it "returns a recipe based on the target directory" do generator.recipe.should == { :current_job => { :date => "07/31/2008", :number => "2392", :href => "2392_Silverlign_2008_07_31" }, :archives => [ { :date => "06/15/2008", :number => "2391", :href => "2391_Silverlign_2008_06_15" }, { :date => "04/10/2008", :number => "2390", :href => "2390_Silverlign_2008_04_10" } ] } end describe "#format_date" do it "converts an ugly date to a pretty one" do generator.format_date(generator.parse_date('2008_04_10')).should == '04/10/2008' end end end end
first_name = "Romeo" last_name = "Enso" #string interpolation puts "My name is #{first_name} #{last_name}" #escaping single quites puts 'Hey Romeo, Joy said \'How are you doing?\'' puts first_name.length #get input from user in terminal puts "Enter your first name: " first_name = gets.chomp puts "Enter your last name: " last_name = gets.chomp puts "Welcome to the playground, #{first_name} #{last_name}" puts "Your first name length is #{first_name.length}, Last name length is #{last_name.length}" puts "Your name in revers #{first_name.reverse} #{last_name.reverse}"
NUMBER_OF_ALLELES = 100 NUMBER_OF_PHYSICAL_GENES = 7 NUMBER_OF_ANIMALS = 100 NUMBER_OF_SPECIES = 3 NUMBER_OF_GENERATIONS = 5 GENERATION_DURATION = 3 STARTING_PLANTS = 1000 STARTING_INSECTS = 1000 STARTING_FISH = 1000
# frozen_string_literal: true class ReactionsController < ApplicationController layout 'internal' before_action :authenticate_user! before_action :block_crossprofile_access before_action :recover_profile def index @reactions = @profile.reactions end def new; end def edit @reaction = Reaction.find(params[:id]) end def create @reaction = Reaction.new(reaction_params) @reaction.profile = @profile if @reaction.save flash[:success] = 'Adverse Reaction registered sucessfully' redirect_to profile_reactions_path(profile_email: @profile.email) else render 'new' end end def update @reaction = Reaction.find(params[:id]) if @reaction.update(reaction_params) flash[:success] = 'Adverse Reaction updated sucessfully' redirect_to profile_reactions_path(profile_email: @reaction.profile.email) else render 'edit' end end def destroy @reaction = Reaction.find(params[:id]) profile_email = @reaction.profile.email @reaction.destroy redirect_to profile_reactions_path(profile_email: profile_email) end private def reaction_params params.require(:reaction).permit(:name, :cause, :description, :start, :finish) end end
# -*- encoding: utf-8 -*- # stub: nakayoshi_fork 0.0.4 ruby lib Gem::Specification.new do |s| s.name = "nakayoshi_fork".freeze s.version = "0.0.4" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["Koichi Sasada".freeze] s.date = "2018-04-13" s.description = "nakayoshi_fork gem solves CoW friendly problem on MRI 2.2 and later.".freeze s.email = ["ko1@atdot.net".freeze] s.homepage = "https://github.com/ko1/nakayoshi_fork".freeze s.licenses = ["MIT".freeze] s.rubygems_version = "2.6.14.1".freeze s.summary = "nakayoshi_fork gem solves CoW friendly problem on MRI 2.2 and later.".freeze s.installed_by_version = "2.6.14.1" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<bundler>.freeze, ["~> 1.7"]) s.add_development_dependency(%q<rake>.freeze, ["~> 10.0"]) else s.add_dependency(%q<bundler>.freeze, ["~> 1.7"]) s.add_dependency(%q<rake>.freeze, ["~> 10.0"]) end else s.add_dependency(%q<bundler>.freeze, ["~> 1.7"]) s.add_dependency(%q<rake>.freeze, ["~> 10.0"]) end end
FactoryGirl.define do factory :user do name 'anonmimous' # default values email 'unkown@xyz.com' #release_date { 10. years.ago } 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). # # # # # # Account roles Role.create(:role_name => 'Administrator') #role_ids: 1 Role.create(:role_name => 'Student_admission_staff') #role_ids: 2 Role.create(:role_name => 'Student_details_viewer') #role_ids: 3 Role.create(:role_name => 'HR_staff') #role_ids: 4 Role.create(:role_name => 'Employee_details_viewer') #role_ids 5 Role.create(:role_name => 'Department_manager') #role_ids: 6 Role.create(:role_name => 'Complaint_manager') #role_ids: 7 Role.create(:role_name => 'Complaint_staff') #role_ids: 8 Role.create(:role_name => 'Complaint_assigner') #role_ids: 9 Role.create(:role_name => 'Complainer') #role_ids: 10 Role.create(:role_name => 'Academic_advisor') #role_ids: 10 Role.create(:role_name => 'Academic_support') #role_ids: 11 # # # ################################################################################################### # # # # Accounts User.create(email: "admin@academy.com" , password: "123456" , password_confirmation: "123456", first_name: "Mostafa" , last_name: "Hussein", user_name: "Root" , role_ids: 1, user_type: "admin") # # # ################################################################################################### # # # ################################################################################################### # # # # States Model State.create(:name => 'Emergency', :background => '#FF60C9', :color => 'black') State.create(:name => 'High', :background => '#FFA500', :color => 'black') State.create(:name => 'Normal', :background => '#FFFF00', :color => 'black') State.create(:name => 'Undefined',:background => '#A0A0A0', :color => 'black') # # # ################################################################################################### # # # # Department Names EmployeeDepartment.create(:name => 'Business Administration', :code => '15A') #id: 1 EmployeeDepartment.create(:name => 'Accounting', :code => '14B') #id: 2 EmployeeDepartment.create(:name => 'Economics', :code => '13C') #id: 3 EmployeeDepartment.create(:name => 'Management Information System', :code => '12D') #id: 4 EmployeeDepartment.create(:name => 'Basic Science', :code => '11E') #id: 5 EmployeeDepartment.create(:name => 'Academic Support', :code => '10F') #id: 6 # # # #------------------------------------------------------------------------------------------------# EmployeePosition.create(:position_title => 'Professor', employee_department_id: 1) #1 #1 EmployeePosition.create(:position_title => 'Assistant Lecturer', employee_department_id: 1) #1 #2 EmployeePosition.create(:position_title => 'Teaching Assistant', employee_department_id: 1) #1 #3 EmployeePosition.create(:position_title => 'Professor ', employee_department_id: 2) #2 #4 EmployeePosition.create(:position_title => 'Assistant Lecturer ', employee_department_id: 2) #2 #5 EmployeePosition.create(:position_title => 'Teaching Assistant ', employee_department_id: 2) #2 #6 EmployeePosition.create(:position_title => 'Professor ', employee_department_id: 3) #3 #7 EmployeePosition.create(:position_title => 'Assistant Lecturer ', employee_department_id: 3) #3 #8 EmployeePosition.create(:position_title => 'Teaching Assistant ', employee_department_id: 3) #3 #9 EmployeePosition.create(:position_title => 'Professor ', employee_department_id: 4) #4 #10 EmployeePosition.create(:position_title => 'Assistant Lecturer ', employee_department_id: 4) #4 #11 EmployeePosition.create(:position_title => 'Teaching Assistant ', employee_department_id: 4) #4 #12 EmployeePosition.create(:position_title => 'Professor ', employee_department_id: 5) #5 #13 EmployeePosition.create(:position_title => 'Assistant Lecturer ', employee_department_id: 5) #5 #14 EmployeePosition.create(:position_title => 'Teaching Assistant ', employee_department_id: 5) #5 #15 EmployeePosition.create(:position_title => 'Help Desk', employee_department_id: 6) #6 #16 # # # #------------------------------------------------------------------------------------------------# # # # Employee Names #guidance supervisors #teaching staff Employee.create(employee_number: '1001' , first_name: 'Amr' , middle_name: '', last_name: 'Abd Elgawad' , gender: 'm' , employee_department_id: 2, email: "employee1@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 4) Employee.create(employee_number: '1002' , first_name: 'Nahla' , middle_name: '', last_name: 'Galal' , gender: 'f' , employee_department_id: 2, email: "employee2@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 4) # #--------------------------------------------------------------------------------------------# Employee.create(employee_number: '1003' , first_name: 'Abd Elwahed' , middle_name: 'Mohamed', last_name: 'Ahmed' , gender: 'm' , employee_department_id: 1, email: "employee3@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 1) Employee.create(employee_number: '1004' , first_name: 'Marwa' , middle_name: 'Said', last_name: 'Mohamed' , gender: 'f' , employee_department_id: 1, email: "employee4@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 1) Employee.create(employee_number: '1005' , first_name: 'Doaa' , middle_name: 'Omar', last_name: 'Abd Allah' , gender: 'f' , employee_department_id: 1, email: "employee5@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 1) Employee.create(employee_number: '1006' , first_name: 'Yasser' , middle_name: 'Saber', last_name: 'Mohamed' , gender: 'm' , employee_department_id: 1, email: "employee6@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 1) # #--------------------------------------------------------------------------------------------# Employee.create(employee_number: '1007' , first_name: 'Mohamed' , middle_name: 'Ashry', last_name: 'Hassan' , gender: 'm' , employee_department_id: 3, email: "employee7@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 7) Employee.create(employee_number: '1008' , first_name: 'Nessren' , middle_name: 'Ahmed', last_name: 'Abbas' , gender: 'f' , employee_department_id: 3, email: "employee8@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 7) # #--------------------------------------------------------------------------------------------# Employee.create(employee_number: '1009' , first_name: 'Hanaa' , middle_name: 'Mousa', last_name: 'Abd Elrahman' , gender: 'f' , employee_department_id: 5, email: "employee9@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 13) Employee.create(employee_number: '1010' , first_name: 'Ola' , middle_name: 'Abd Elfatah', last_name: 'Ahmed' , gender: 'f' , employee_department_id: 5, email: "employee10@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 13) # # #-----------------------------------------------------------------------------------------------------------------# # # #-----------------------------------------------------------------------------------------------------------------# Employee.create(employee_number: '1011' , first_name: 'Aya' , middle_name: 'Mahmoud', last_name: 'Bshir' , gender: 'f' , employee_department_id: 4, email: "employee11@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 12) Employee.create(employee_number: '1012' , first_name: 'Nanis' , middle_name: 'Nabil', last_name: 'Mohamed' , gender: 'f' , employee_department_id: 4, email: "employee12@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 12) Employee.create(employee_number: '1013' , first_name: 'Mariz' , middle_name: 'Safwat', last_name: 'George' , gender: 'f' , employee_department_id: 4, email: "employee13@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 12) Employee.create(employee_number: '1014' , first_name: 'Dina' , middle_name: 'Mohamed', last_name: 'Mahmoud' , gender: 'f' , employee_department_id: 4, email: "employee14@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 12) Employee.create(employee_number: '1015' , first_name: 'Alaa' , middle_name: 'Mostafa', last_name: 'Abd Elaal' , gender: 'f' , employee_department_id: 4, email: "employee15@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 12) Employee.create(employee_number: '1016' , first_name: 'Lina' , middle_name: 'Mohamed', last_name: 'Khattab' , gender: 'f' , employee_department_id: 4, email: "employee16@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 12) # # #--------------------------------------------------------------------------------------------------# Employee.create(employee_number: '1017' , first_name: 'Sherif' , middle_name: 'Farouq', last_name: 'Elwy' , gender: 'm' , employee_department_id: 2, email: "employee17@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 5) Employee.create(employee_number: '1018' , first_name: 'Hanan' , middle_name: 'Ahmed', last_name: 'Talaat' , gender: 'f' , employee_department_id: 2, email: "employee18@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 5) Employee.create(employee_number: '1019' , first_name: 'Rasha' , middle_name: 'Mohamed', last_name: 'Hamdy' , gender: 'f' , employee_department_id: 2, email: "employee19@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 5) Employee.create(employee_number: '1020' , first_name: 'Heba' , middle_name: 'Hassan', last_name: 'Megahed' , gender: 'f' , employee_department_id: 2, email: "employee20@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 5) Employee.create(employee_number: '1021' , first_name: 'Raghda' , middle_name: '', last_name: 'Salah' , gender: 'f' , employee_department_id: 2, email: "employee21@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 5) Employee.create(employee_number: '1022' , first_name: 'Tareq' , middle_name: 'Saad', last_name: 'Ahmed' , gender: 'm' , employee_department_id: 2, email: "employee22@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 6) Employee.create(employee_number: '1023' , first_name: 'Mohamed' , middle_name: 'Said', last_name: 'Abd Elhafez' , gender: 'm' , employee_department_id: 2, email: "employee23@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 6) Employee.create(employee_number: '1024' , first_name: 'Khaled' , middle_name: 'Mohamed', last_name: 'Mahmoud' , gender: 'm' , employee_department_id: 2, email: "employee24@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 6) # #-------------------------------------------------------------------------------------------------------# Employee.create(employee_number: '1025' , first_name: 'Mohamed' , middle_name: 'Hussein', last_name: 'Salah' , gender: 'm' , employee_department_id: 1, email: "employee25@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 2) Employee.create(employee_number: '1026' , first_name: 'Elshaimaa' , middle_name: 'Nabil', last_name: 'Ebrahim' , gender: 'f' , employee_department_id: 1, email: "employee26@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 2) Employee.create(employee_number: '1027' , first_name: 'Amira' , middle_name: 'Mohamed', last_name: 'Ahmed' , gender: 'f' , employee_department_id: 1, email: "employee27@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 2) Employee.create(employee_number: '1028' , first_name: 'Elham' , middle_name: 'Abd Ellatef', last_name: 'Abd Elghafar' , gender: 'f' , employee_department_id: 1, email: "employee28@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 2) Employee.create(employee_number: '1029' , first_name: 'Rady' , middle_name: 'Mohamed', last_name: 'Hussein' , gender: 'm' , employee_department_id: 1, email: "employee29@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 3) # # #-------------------------------------------------------------------------------------------------------# Employee.create(employee_number: '1030' , first_name: 'Sherin' , middle_name: 'Ahmed', last_name: 'Abd Allah' , gender: 'f' , employee_department_id: 3, email: "employee30@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 8) Employee.create(employee_number: '1031' , first_name: 'Rania' , middle_name: 'Ramadan', last_name: 'Moawad' , gender: 'f' , employee_department_id: 3, email: "employee31@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 8) Employee.create(employee_number: '1032' , first_name: 'Abd Elaziz' , middle_name: '', last_name: 'Abd Elmeged' , gender: 'm' , employee_department_id: 3, email: "employee32@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 8) Employee.create(employee_number: '1033' , first_name: 'Sbah' , middle_name: 'Salah', last_name: 'Abd Allah' , gender: 'f' , employee_department_id: 3, email: "employee33@academy.com", :employee_category => 'Teaching Staff',:employee_position_id => 8) Employee.create(employee_number: '1034' , first_name: 'Ahmed' , middle_name: '', last_name: 'Ramzy' , gender: 'm' , employee_department_id: 3, email: "employee34@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 8) Employee.create(employee_number: '1035' , first_name: 'Mohamed' , middle_name: 'Mahmoud', last_name: 'Ahmed' , gender: 'm' , employee_department_id: 3, email: "employee35@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 8) Employee.create(employee_number: '1036' , first_name: 'Dalia' , middle_name: 'Farouq', last_name: 'Othman' , gender: 'f' , employee_department_id: 3, email: "employee36@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 8) # # #---------------------------------------------------------------------------------------------------------# Employee.create(employee_number: '1037' , first_name: 'Dina' , middle_name: 'Mohamed', last_name: 'Ahmed' , gender: 'f' , employee_department_id: 5, email: "employee37@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 14) Employee.create(employee_number: '1038' , first_name: 'Marwa' , middle_name: 'Yehia', last_name: 'Ramadan' , gender: 'f' , employee_department_id: 5, email: "employee38@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 14) Employee.create(employee_number: '1039' , first_name: 'Amira' , middle_name: 'Mohamed', last_name: 'Hamdy' , gender: 'f' , employee_department_id: 5, email: "employee39@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 14) Employee.create(employee_number: '1040' , first_name: 'Mohamed' , middle_name: 'Salem', last_name: 'Elbaz' , gender: 'm' , employee_department_id: 5, email: "employee40@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 14) Employee.create(employee_number: '1041' , first_name: 'Amr' , middle_name: 'Mohamed', last_name: 'Salah Eldin' , gender: 'm' , employee_department_id: 5, email: "employee41@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 14) Employee.create(employee_number: '1042' , first_name: 'Mamdouh' , middle_name: 'Ahmed', last_name: 'Mohamed' , gender: 'm' , employee_department_id: 5, email: "employee42@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 14) Employee.create(employee_number: '1043' , first_name: 'Tamer' , middle_name: 'Rezq', last_name: 'Abd Elmenaem' , gender: 'm' , employee_department_id: 5, email: "employee43@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 15) # ################################################################################################### ####leadership Employee.create(employee_number: '1044' , first_name: 'Mohamed' , middle_name: '' , last_name: 'Shaaban', gender: 'm' , employee_department_id: 4 , email: 'employee44@academy.com' , employee_category: 'Teaching Staff' , employee_position_id: 10) Employee.create(employee_number: '1045' , first_name: 'Hesham' , middle_name: '' , last_name: 'Mahmoud', gender: 'm' , employee_department_id: 4 , email: 'employee45@academy.com' , employee_category: 'Teaching staff' , employee_position_id: 10) Employee.create(employee_number: '1046' , first_name: 'Ahmed' , middle_name: '' , last_name: 'Attia', gender: 'm' , employee_department_id: 4 , email: 'emolpyee46@academy.com' , employee_category: 'Teaching Staff' , employee_position_id: 10) Employee.create(employee_number: '1047' , first_name: 'Sameh', middle_name: '' , last_name: 'Saudy' , gender: 'm' , employee_department_id: 2 , email: 'employee47@academy.com' , employee_category: 'Teaching Staff' , employee_position_id: 4) Employee.create(employee_number: '1048' , first_name: 'Mohamed' , middle_name: '' , last_name: 'Alfrargy', gender: 'm' , employee_department_id: 2 , email: 'employee48@academy.com' , employee_category: 'Teaching Staff' , employee_position_id: 4) ##-----------------------------------------------------------------------------------------------------------------------------## Employee.create(employee_number: '1049' , first_name: 'Katharyn' , middle_name: '' , last_name: 'Paxson', gender: 'f' , employee_department_id: 6 , email: 'employee49@academy.com' , employee_category: 'Non-teaching Staff' , employee_position_id: 16) Employee.create(employee_number: '1050' , first_name: 'Mertie' , middle_name: '' , last_name: 'Seman', gender: 'f' , employee_department_id: 6 , email: 'employee50@academy.com' , employee_category: 'Non-teaching Staff' , employee_position_id: 16) Employee.create(employee_number: '1051' , first_name: 'Denny' , middle_name: '' , last_name: 'Kantner', gender: 'm' , employee_department_id: 6 , email: 'employee51@academy.com' , employee_category: 'Non-teaching Staff' , employee_position_id: 16) Employee.create(employee_number: '1052' , first_name: 'Gaylene' , middle_name: '' , last_name: 'Archer', gender: 'f' , employee_department_id: 6 , email: 'employee52@academy.com' , employee_category: 'Non-teaching Staff' , employee_position_id: 16) Employee.create(employee_number: '1053' , first_name: 'Antonina' , middle_name: '' , last_name: 'Wille', gender: 'f' , employee_department_id: 6 , email: 'employee53@academy.com' , employee_category: 'Non-teaching Staff' , employee_position_id: 16) Employee.create(employee_number: '1054' , first_name: 'Jamee' , middle_name: '' , last_name: 'Cornwall', gender: 'f' , employee_department_id: 6 , email: 'employee54@academy.com' , employee_category: 'Non-teaching Staff' , employee_position_id: 16) Employee.create(employee_number: '1055' , first_name: 'Jennifer' , middle_name: '' , last_name: 'Periera', gender: 'f' , employee_department_id: 6 , email: 'employee55@academy.com' , employee_category: 'Non-teaching Staff' , employee_position_id: 16) Employee.create(employee_number: '1056' , first_name: 'Alisia' , middle_name: '' , last_name: 'Bruner', gender: 'f' , employee_department_id: 6 , email: 'employee56@academy.com' , employee_category: 'Non-teaching Staff' , employee_position_id: 16) Employee.create(employee_number: '1057' , first_name: 'Michaela' , middle_name: '' , last_name: 'Wentworth', gender: 'f' , employee_department_id: 6 , email: 'employee57@academy.com' , employee_category: 'Non-teaching Staff' , employee_position_id: 16) Employee.create(employee_number: '1058' , first_name: 'Nicolasa' , middle_name: '' , last_name: 'Circle', gender: 'f' , employee_department_id: 6 , email: 'employee58@academy.com' , employee_category: 'Non-teaching Staff' , employee_position_id: 16) ############################################################################################################### Employee.create(employee_number: '1059' , first_name: 'Habiba' , middle_name: 'Nour Eldin', last_name: 'Mostafa' , gender: 'f' , employee_department_id: 1, email: "employee59@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 2) Employee.create(employee_number: '1060' , first_name: 'Heba' , middle_name: 'Elsaid', last_name: 'Mohamed' , gender: 'f' , employee_department_id: 3, email: "employee60@academy.com", :employee_category => 'Teaching Staff', :employee_position_id => 9) # # ################################################################################################################# #Batches should represent: where a student registered or in which year he is. #Batches Names - Management Information System # #English Sector # Batch.create(:name => '1 MIS E') # Batch.create(:name => '2 MIS E') # Batch.create(:name => '3 MIS E') # Batch.create(:name => '4 MIS E') # #Arabic Sector # Batch.create(:name => '1 MIS A') # Batch.create(:name => '2 MIS A') # Batch.create(:name => '3 MIS A') # Batch.create(:name => '4 MIS A') ################################################################################################### # #Batches Name - Business Administration # Batch.create(:name => '1 BUS E') # Batch.create(:name => '2 BUS E') # Batch.create(:name => '3 BUS E') # Batch.create(:name => '4 BUS E') # #Arabic Sector # Batch.create(:name => '1 BUS A') # Batch.create(:name => '2 BUS A') # Batch.create(:name => '3 BUS A') # Batch.create(:name => '4 BUS A') # StudentClass.create(:name => '1', :batch_id => 1) # StudentClass.create(:name => '2', :batch_id => 1) # StudentClass.create(:name => '3', :batch_id => 1) # StudentClass.create(:name => '4', :batch_id => 1) # StudentClass.create(:name => '1', :batch_id => 2) # StudentClass.create(:name => '2', :batch_id => 2) # StudentClass.create(:name => '3', :batch_id => 2) # StudentClass.create(:name => '4', :batch_id => 2) # StudentClass.create(:name => '5', :batch_id => 2) # ################################################################################################### # 1 business english #class 1 # Student.create(admission_date: "2013-8-15", first_name: "Abanoub" , middle_name: "Fawzy", last_name: "Kamal", gender: 'm', email: 'student1@academy.com',batch_id: 1, student_class_id: 1) # Student.create(admission_date: "2013-8-15", first_name: "Ahmed", middle_name: "Hamdy", last_name: "Mostafa", gender: 'm', email: 'student2@academy.com', batch_id: 1, student_class_id: 1) # #class 2 # Student.create(admission_date: "2013-8-15", first_name: "Ahmed", middle_name: "Mohsen", last_name: "Abd Elghafar", gender: 'm', email: 'student3@academy.com', batch_id: 1, student_class_id: 2) # Student.create(admission_date: "2013-8-15", first_name: "Ahmed", middle_name: "Mohamed", last_name: "Hagag", gender: 'm', email: 'student4@academy.com', batch_id: 1, student_class_id: 2) # #class 3 # Student.create(admission_date: "2013-8-15", first_name: "Gehad", middle_name: "Essam", last_name: "Mohamed", gender: 'f', email: 'student5@academy.com', batch_id: 1, student_class_id: 3) # Student.create(admission_date: "2013-9-15", first_name: "Randa", middle_name: "Anes", last_name: "Hosny", gender: 'f', email: 'student6@academy.com', batch_id: 1, student_class_id: 3) # #class 4 # Student.create(admission_date: "2013-9-15", first_name: "Saleh", middle_name: "Hassan", last_name: "Abd Elaziz", gender: 'm', email: 'student7@academy.com', batch_id: 1, student_class_id: 4) # Student.create(admission_date: "2013-9-15", first_name: "Doha", middle_name: "Ahmed Eldin", last_name: "Qotb", gender: 'f', email: 'student8@academy.com', batch_id: 1, student_class_id: 4) # #class 5 # Student.create(admission_date: "2013-9-15", first_name: "Amr", middle_name: "Abd Elazeem", last_name: "Mohamed", gender: 'm', email: 'student9@academy.com', batch_id: 1, student_class_id: 5) # Student.create(admission_date: "2013-9-15", first_name: "Mohamed", middle_name: "Osama", last_name: "Abd Elhamid", gender: 'm', email: 'student10@academy.com', batch_id: 1, student_class_id: 5) # #class 6 # Student.create(admission_date: "2013-9-20", first_name: "Mohamed", middle_name: "Abd Elmenaem", last_name: "Mohamed", gender: 'm', email: 'student11@academy.com', batch_id: 1, student_class_id: 6) # Student.create(admission_date: "2013-9-20", first_name: "Mohamed", middle_name: "Abd Elnaem", last_name: "Mohamed", gender: 'm', email: 'student12@academy.com', batch_id: 1, student_class_id: 6) # #class 7 # Student.create(admission_date: "2013-9-20", first_name: "Mahmoud", middle_name: "Mohamed", last_name: "Sobhy", gender: 'm', email: 'student13@academy.com', batch_id: 1, student_class_id: 7) # Student.create(admission_date: "2013-9-22", first_name: "Marwan", middle_name: "Mohamed", last_name: "Abd Elhafez", gender: 'm', email: 'student14@academy.com', batch_id: 1, student_class_id: 7) # #class 8 # Student.create(admission_date: "2013-9-22", first_name: "Nariman", middle_name: "Mohamed", last_name: "Salem", gender: 'f', email: 'student15@academy.com', batch_id: 1, student_class_id: 8) # Student.create(admission_date: "2013-9-22", first_name: "Hesham", middle_name: "Ahmed", last_name: "Hassan", gender: 'm', email: 'student16@academy.com', batch_id: 1, student_class_id: 8) # # # #=========================================================================================# # 1 business english # # # class 1 # Student.create(admission_date: "2013-10-15", first_name: "Fawzy" , middle_name: "", last_name: "Kamal", gender: 'm', email: 'student17@academy.com',batch_id: 4, student_class_id: 1) # Student.create(admission_date: "2013-10-15", first_name: "Hamdy", middle_name: "", last_name: "Mostafa", gender: 'm', email: 'student18@academy.com', batch_id: 4, student_class_id: 1) # #class 2 # Student.create(admission_date: "2013-10-15", first_name: "Ahmed", middle_name: "", last_name: "Abd Elghafar", gender: 'm', email: 'student19@academy.com', batch_id: 4, student_class_id: 2) # Student.create(admission_date: "2013-10-15", first_name: "Ahmed", middle_name: "", last_name: "Hagag", gender: 'm', email: 'student20@academy.com', batch_id: 4, student_class_id: 2) # #class 3 # Student.create(admission_date: "2013-10-15", first_name: "Gehad", middle_name: "", last_name: "Mohamed", gender: 'f', email: 'student21@academy.com', batch_id: 4, student_class_id: 3) # Student.create(admission_date: "2013-10-15", first_name: "Randa", middle_name: "", last_name: "Hosny", gender: 'f', email: 'student22@academy.com', batch_id: 4, student_class_id: 3) # #class 4 # Student.create(admission_date: "2013-10-15", first_name: "Saleh", middle_name: "", last_name: "Abd Elaziz", gender: 'm', email: 'student23@academy.com', batch_id: 4, student_class_id: 4) # Student.create(admission_date: "2013-10-15", first_name: "Doha", middle_name: "", last_name: "Qotb", gender: 'f', email: 'student24@academy.com', batch_id: 4, student_class_id: 4) # #class 5 # Student.create(admission_date: "2013-10-15", first_name: "Amr", middle_name: "", last_name: "Mohamed", gender: 'm', email: 'student25@academy.com', batch_id: 4, student_class_id: 5) # Student.create(admission_date: "2013-10-15", first_name: "Mohamed", middle_name: "", last_name: "Abd Elhamid", gender: 'm', email: 'student26@academy.com', batch_id: 4, student_class_id: 5) # #class 6 # Student.create(admission_date: "2013-10-20", first_name: "Mohamed", middle_name: "", last_name: "Mohamed", gender: 'm', email: 'student27@academy.com', batch_id: 4, student_class_id: 6) # Student.create(admission_date: "2013-10-20", first_name: "Mohamed", middle_name: "", last_name: "Mohamed", gender: 'm', email: 'student28@academy.com', batch_id: 4, student_class_id: 6) # #class 7 # Student.create(admission_date: "2013-10-20", first_name: "Mahmoud", middle_name: "", last_name: "Sobhy", gender: 'm', email: 'student29@academy.com', batch_id: 4, student_class_id: 7) # Student.create(admission_date: "2013-10-22", first_name: "Marwan", middle_name: "", last_name: "Abd Elhafez", gender: 'm', email: 'student30@academy.com', batch_id: 4, student_class_id: 7) # #class 8 # Student.create(admission_date: "2013-10-22", first_name: "Nariman", middle_name: "", last_name: "Salem", gender: 'f', email: 'student31@academy.com', batch_id: 4, student_class_id: 8) # Student.create(admission_date: "2013-10-22", first_name: "Hesham", middle_name: "", last_name: "Hassan", gender: 'm', email: 'student32@academy.com', batch_id: 4, student_class_id: 8) # Student.create(admission_date: "2013-10-15", first_name: "Fawzy" , middle_name: "", last_name: "Kamal", gender: 'm', email: 'student33@academy.com',batch_id: 4, student_class_id: 9) # Student.create(admission_date: "2013-10-15", first_name: "Hamdy", middle_name: "", last_name: "Mostafa", gender: 'm', email: 'student34@academy.com', batch_id: 4, student_class_id: 9) # #class 2 # Student.create(admission_date: "2013-10-15", first_name: "Ahmed", middle_name: "", last_name: "Abd Elghafar", gender: 'm', email: 'student35@academy.com', batch_id: 4, student_class_id: 10) # Student.create(admission_date: "2013-10-15", first_name: "Ahmed", middle_name: "", last_name: "Hagag", gender: 'm', email: 'student36@academy.com', batch_id: 4, student_class_id: 10) # #class 3 # Student.create(admission_date: "2013-10-15", first_name: "Gehad", middle_name: "", last_name: "Mohamed", gender: 'f', email: 'student37@academy.com', batch_id: 4, student_class_id: 11) # Student.create(admission_date: "2013-10-15", first_name: "Randa", middle_name: "", last_name: "Hosny", gender: 'f', email: 'student38@academy.com', batch_id: 4, student_class_id: 11) # #class 4 # Student.create(admission_date: "2013-10-15", first_name: "Saleh", middle_name: "", last_name: "Abd Elaziz", gender: 'm', email: 'student38@academy.com', batch_id: 4, student_class_id: 12) # Student.create(admission_date: "2013-10-15", first_name: "Doha", middle_name: "", last_name: "Qotb", gender: 'f', email: 'student39@academy.com', batch_id: 4, student_class_id: 12) # #class 5 # Student.create(admission_date: "2013-10-15", first_name: "Amr", middle_name: "", last_name: "Mohamed", gender: 'm', email: 'student40@academy.com', batch_id: 4, student_class_id: 5) # Student.create(admission_date: "2013-10-15", first_name: "Mohamed", middle_name: "", last_name: "Abd Elhamid", gender: 'm', email: 'student41@academy.com', batch_id: 4, student_class_id: 5) # #class 6 # Student.create(admission_date: "2013-10-20", first_name: "Mohamed", middle_name: "", last_name: "Mohamed", gender: 'm', email: 'student42@academy.com', batch_id: 4, student_class_id: 6) # Student.create(admission_date: "2013-10-20", first_name: "Mohamed", middle_name: "", last_name: "Mohamed", gender: 'm', email: 'student43@academy.com', batch_id: 4, student_class_id: 6) # #class 7 # Student.create(admission_date: "2013-10-20", first_name: "Mahmoud", middle_name: "", last_name: "Sobhy", gender: 'm', email: 'student44@academy.com', batch_id: 4, student_class_id: 7) # Student.create(admission_date: "2013-10-22", first_name: "Marwan", middle_name: "", last_name: "Abd Elhafez", gender: 'm', email: 'student45@academy.com', batch_id: 4, student_class_id: 7) # #class 8 # Student.create(admission_date: "2013-10-22", first_name: "Nariman", middle_name: "", last_name: "Salem", gender: 'f', email: 'student46@academy.com', batch_id: 4, student_class_id: 8) # Student.create(admission_date: "2013-10-22", first_name: "Hesham", middle_name: "", last_name: "Hassan", gender: 'm', email: 'student47@academy.com', batch_id: 4, student_class_id: 8) # Student.create(admission_date: "2013-10-15", first_name: "Doha", middle_name: "", last_name: "Qotb", gender: 'f', email: 'student48@academy.com', batch_id: 5, student_class_id: 12) # #class 5 # Student.create(admission_date: "2013-10-15", first_name: "Amr", middle_name: "", last_name: "Mohamed", gender: 'm', email: 'student49@academy.com', batch_id: 5, student_class_id: 5) # Student.create(admission_date: "2013-10-15", first_name: "Mohamed", middle_name: "", last_name: "Abd Elhamid", gender: 'm', email: 'student50@academy.com', batch_id: 5, student_class_id: 5) # #class 6 # Student.create(admission_date: "2013-10-20", first_name: "Mohamed", middle_name: "", last_name: "Mohamed", gender: 'm', email: 'student51@academy.com', batch_id: 5, student_class_id: 6) # Student.create(admission_date: "2013-10-20", first_name: "Mohamed", middle_name: "", last_name: "Mohamed", gender: 'm', email: 'student52@academy.com', batch_id: 5, student_class_id: 6) # #class 7 # Student.create(admission_date: "2013-10-20", first_name: "Mahmoud", middle_name: "", last_name: "Sobhy", gender: 'm', email: 'student53@academy.com', batch_id: 5, student_class_id: 7) # Student.create(admission_date: "2013-10-22", first_name: "Marwan", middle_name: "", last_name: "Abd Elhafez", gender: 'm', email: 'student54@academy.com', batch_id: 5, student_class_id: 7) # #class 8 # Student.create(admission_date: "2013-10-22", first_name: "Nariman", middle_name: "", last_name: "Salem", gender: 'f', email: 'student55@academy.com', batch_id: 5, student_class_id: 8) # Student.create(admission_date: "2013-10-22", first_name: "Hesham", middle_name: "", last_name: "Hassan", gender: 'm', email: 'student56@academy.com', batch_id: 5, student_class_id: 8) # 1 bussiness arabic # # #=========================================================================================== # #2 business english # #class 1 # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # #class 2 # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # #class 3 # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # #class 4 # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # #class 5 # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # #class 6 # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # #============================================================================================= # #2 business arabic # #class 1 # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # #class 2 # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # #class 3 # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # #class 4 # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # #class 5 # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # #class 6 # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # Student.create(first_name: "", middle_name: "", last_name: "", batch_id: , student_class_id: ) # #============================================================================================= # ################################################################################################### # #Courses # # Management Information System Course.create(course_code: "IS101", course_name: "Office Application Packages",course_department: "Management Information System", course_batch: "1MIS", course_semester: "second semester") Course.create(course_code: "IS201", course_name: "Management Information Systems",course_department: "Management Information System", course_batch: "2MIS", course_semester: "second semester") Course.create(course_code: "IS202", course_name: "Internet and Mutimedia Applictions",course_department: "Management Information System", course_batch: "2MIS", course_semester: "second semester") Course.create(course_code: "IS203", course_name: "Introduction to Information Systems",course_department: "Management Information System", course_batch: "2C", course_semester: "first semester") Course.create(course_code: "IS301", course_name: "Information Systems Analysis & Design",course_department: "Management Information System", course_batch: "3MIS", course_semester: "second semester") Course.create(course_code: "IS312", course_name: "Marketing and Electronic Commerce",course_department: "Management Information System", course_batch: "3MIS", course_semester: "second semester") Course.create(course_code: "IS401", course_name: "Decision Support Systems",course_department: "Management Information System", course_batch: "4MIS", course_semester: "first semester") Course.create(course_code: "IS403", course_name: "Comp.Application For Reports Prep.",course_department: "Management Information System", course_batch: "4MIS", course_semester: "second semester") Course.create(course_code: "IS404", course_name: "Accounting Informormation Systems",course_department: "Management Information System", course_batch: "4MIS", course_semester: "second semester") Course.create(course_code: "IS405", course_name: "Graduation Project",course_department: "Management Information System", course_batch: "4MIS", course_semester: "first semester") Course.create(course_code: "IS405", course_name: "Graduation Project",course_department: "Management Information System", course_batch: "4MIS", course_semester: "second semester") Course.create(course_code: "IS408", course_name: "Information Systems Technology",course_department: "Management Information System", course_batch: "4AC", course_semester: "first semester") Course.create(course_code: "IS409", course_name: "Decision Support Systems",course_department: "Management Information System", course_batch: "4AC", course_semester: "second semester") # ################################################################################################## # ####Country / Nationality name Country.create(:name => "Algeria") Country.create(:name => "Bahrain") Country.create(:name => "Egypt") Country.create(:name => "Iraq") Country.create(:name => "Jordan") Country.create(:name => "Kuwait") Country.create(:name => "Lebanon") Country.create(:name => "Libya") Country.create(:name => "Morocco") Country.create(:name => "Oman") Country.create(:name => "Palestine") Country.create(:name => "Qatar") Country.create(:name => "Saudi Arabia") Country.create(:name => "Syria") Country.create(:name => "Sudan") Country.create(:name => "Tunisia") Country.create(:name => "United Arab Emirates") Country.create(:name => "Yemen") # ################################################################################################### # # Help topic # # Examples: # # # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # # Mayor.create(name: 'Emanuel', city: cities.first)
class DiariesController < ApplicationController def index @user = User.find(current_user) @diaries = current_user.diaries.order(id: :desc) end def new @user = User.find(current_user.id) @diary = Diary.new end def create @diary = Diary.new(diary_params) if @diary.save redirect_to diaries_path else render :new end end def destroy @diary = Diary.find(params[:id]) @diary.destroy redirect_to diaries_path end private def diary_params params.require(:diary).permit( :id, :title, :date, :image, :text, :type).merge(user_id: current_user.id) end end
# frozen_string_literal: true # Configure Rails Envinronment ENV['RAILS_ENV'] = 'test' CI_ORM = (ENV['CI_ORM'] || :active_record).to_sym CI_TARGET_ORMS = %i[active_record mongoid].freeze PK_COLUMN = {active_record: :id, mongoid: :_id}[CI_ORM] if RUBY_ENGINE == 'jruby' # Workaround for JRuby CI failure https://github.com/jruby/jruby/issues/6547#issuecomment-774104996 require 'i18n/backend' require 'i18n/backend/simple' end require 'simplecov' require 'simplecov-lcov' SimpleCov.formatters = [SimpleCov::Formatter::HTMLFormatter, SimpleCov::Formatter::LcovFormatter] SimpleCov.start do add_filter '/spec/' add_filter '/vendor/bundle/' end SimpleCov::Formatter::LcovFormatter.config do |c| c.report_with_single_file = true c.single_report_path = 'coverage/lcov.info' end require File.expand_path('dummy_app/config/environment', __dir__) require 'rspec/rails' require 'factory_bot' require 'factories' require 'policies' require "database_cleaner/#{CI_ORM}" require "orm/#{CI_ORM}" require 'paper_trail/frameworks/rspec' if defined?(PaperTrail) Dir[File.expand_path('support/**/*.rb', __dir__), File.expand_path('shared_examples/**/*.rb', __dir__)].sort.each { |f| require f } ActionMailer::Base.delivery_method = :test ActionMailer::Base.perform_deliveries = true ActionMailer::Base.default_url_options[:host] = 'example.com' Rails.backtrace_cleaner.remove_silencers! require 'capybara/cuprite' Capybara.javascript_driver = :cuprite Capybara.register_driver(:cuprite) do |app| Capybara::Cuprite::Driver.new(app, js_errors: true, logger: ConsoleLogger) end Capybara.server = :webrick RailsAdmin.setup_all_extensions RSpec.configure do |config| config.expect_with :rspec do |c| c.syntax = :expect end config.disable_monkey_patching! config.include RSpec::Matchers config.include RailsAdmin::Engine.routes.url_helpers config.include Warden::Test::Helpers config.include Capybara::DSL, type: :request config.verbose_retry = true config.display_try_failure_messages = true config.around :each, :js do |example| example.run_with_retry retry: (ENV['CI'] && RUBY_ENGINE == 'jruby' ? 3 : 2) end config.retry_callback = proc do |example| Capybara.reset! if example.metadata[:js] end config.before(:all) do Webpacker.instance.compiler.compile if CI_ASSET == :webpacker end config.before do |example| DatabaseCleaner.strategy = if CI_ORM == :mongoid || example.metadata[:js] :deletion else :transaction end DatabaseCleaner.start RailsAdmin::Config.reset RailsAdmin::Config.asset_source = CI_ASSET end config.after(:each) do Warden.test_reset! DatabaseCleaner.clean end CI_TARGET_ORMS.each do |orm| if orm == CI_ORM config.filter_run_excluding "skip_#{orm}".to_sym => true else config.filter_run_excluding orm => true end end config.filter_run_excluding composite_primary_keys: true unless defined?(CompositePrimaryKeys) end
# frozen_string_literal: true module EventRegistrationHelper def event_registration_link(event) event.registration_url.presence || new_event_registration_path(event_invitee: { event_id: event.id }) end def event_registration_target(event) "event_#{event.id}" if event.registration_url end end
require 'spec_helper' require_relative '../monad_axioms' include Deterministic describe Deterministic::Success do it_behaves_like 'a Monad' do let(:monad) { described_class } end subject { described_class.new(1) } specify { expect(subject).to be_an_instance_of described_class } specify { expect(subject.value).to eq 1 } specify { expect(subject).to be_success } specify { expect(subject).not_to be_failure } specify { expect(subject).to be_an_instance_of described_class } specify { expect(subject).to eq(described_class.new(1)) } specify { expect(subject << Success(2)).to eq(Success(2)) } specify { expect(subject << Failure(2)).to eq(Failure(2)) } specify { expect(Success(subject)).to eq Success(1) } specify { expect(subject.map { |v| v + 1} ).to eq Success(2) } it "#bind" do expect( subject.bind { |v| true ? Success(v + 1) : Failure(v + 2)} ).to eq Success(2) end end
Factory.define :admin_image, :class => Admin::Image do |f| f.image_file_name "featured-contributor.png" f.image_content_type "image/png" f.image_file_size 64.kilobytes f.cobrand { Cobrand.root } end Factory.define :question do |f| f.asking_text "this is the question asking text" end Factory.define :answer do |f| f.association :question f.association :user f.text "the answer value" end Factory.define :content_document, :class => Viewpoints::Acts::Moderateable::ContentDocument do |f| f.association :owner, :factory => :review f.content_fields {|field| [field.association(:content_field)]} f.comment "Generated Content document" end Factory.define :content_history, :class => Viewpoints::Acts::Moderateable::ContentHistory do |f| f.association :content_document, :factory => :content_document f.user_id nil f.comment "system generated comment" end Factory.define :rejected_content_document, :parent => :content_document do |f| f.status 'rejected' f.reason_codes "1" end Factory.define :content_field, :class => Viewpoints::Acts::Moderateable::ContentField do |f| f.filtered_words {|field| [field.association(:filtered_word)]} end Factory.define :filtered_word do |f| end Factory.define :category_relationship do |f| end Factory.define :permalink do |f| end Factory.define :ad_tag do |f| f.association :owner f.width 300 f.height 300 f.position 1 f.active true end Factory.define :cobrand do |f| f.name "Viewpoints" f.short_name { |c| c.name.underscore } f.subdomain "www" f.host { |c| "#{c.subdomain}.#{c.short_name}.com" } f.mail_host { |c| c.host } end Factory.define :report do |f| f.name 'name' f.start_date 5.days.ago f.end_date 2.day.ago f.cobrands [1] f.recipients ['jenny@smth.com'] f.kind 'by_review' f.deleted false f.scheduled_at 1.day.ago end Factory.define :idea do |f| f.association :user f.idea_category { |i| Factory :idea_category, :parent_category => Factory(:idea_category) } f.idea_instance { |i| i.idea_category.idea_instance } f.title "Here's an idea..." f.description "Lipsum orem..." f.status "new" end Factory.define :idea_category do |f| f.association :idea_instance f.title "General Ideas" f.display_text "General Ideas for General Things" end Factory.define :idea_instance do |f| f.cobrand { Cobrand.root } f.sequence(:name) { |n| "Ideas#{n}"} f.title { |i| i.name } f.short_name { |i| i.title.downcase } f.status :active end Factory.define :user_todo do |utd| utd.cobrand Cobrand.root utd.link_text "Link Text!" utd.rule "InviteAFriend" end Factory.define :landing_page do |f| f.sequence(:permalink) { |n| "Lander#{n}" } end Factory.define :landing_page_relationship do |f| f.association :parent f.association :child f.position 1 end Factory.define :landing_page_trigger do |f| end Factory.define :endeca_dimension do |f| end Factory.define :endeca_dimension_value do |f| end Factory.define :local_photo do |f| f.content_type "image/png" f.caption "Pictures!" f.file_base_name "picture" end Factory.define :user_tag do |ut| ut.association :user ut.value "my tag" end Factory.define :product do |f| f.association :category f.source { Source["system"] } f.title "The Bouncer 3000" end Factory.define :product_question do |f| f.label Time.now.to_s f.covary_group "covary" end Factory.define :product_answer do |f| end Factory.define :reputable_event, :class => Reputable::Event do |f| f.association :user end Factory.define :reputable_badge, :class => Reputable::Badge do |f| f.name "Top Reviewer" end Factory.define :badging, :class => Reputable::Badging do |f| f.association :badge, :factory => :reputable_badge f.association :user end Factory.define :review do |f| f.association :user f.association :product f.cobrand { Cobrand.root } f.sound_bite "Love it." f.content "Love it. It does everything I need it to do!" f.stars 5 f.photos [] f.source { Source["user"] } f.published_at Time.now end Factory.define :activated_review, :class => Review, :parent => :review do |review| review.after_create do |review| cd = review.content_documents.first cd.activate_content! end end Factory.define :rejected_review, :class => Review, :parent => :review do |review| review.after_create do |review| cd = review.content_documents.first cd.reason_codes = "Misc" cd.reject_content! end end Factory.define :zip_code do |f| f.sequence(:zip_code) { |n| "%05d" % n } f.last_line_city_preferred_name "Chicago" f.state_abbreviation "IL" end Factory.define :user do |f| f.sequence(:screen_name) { |n| "foo#{Time.now.to_i * n}" } f.email { |u| "#{u.screen_name}@example.com" } f.new_password "secret" f.new_password_confirmation { |u| u.new_password } f.zip_code { (ZipCode.first || Factory(:zip_code)).zip_code } f.cobrand { Cobrand.root } f.sequence(:photos) { |n| n %= 6 and [LocalPhoto.find(:first, :offset => n, :conditions => { :sort_order => 0 })] } end Factory.define :anonymous_token do |f| f.session_id UUIDTools::UUID.timestamp_create.to_s f.association :user end Factory.define :role do |f| f.name "superuser" end Factory.define :superuser, :parent => :user do |f| f.roles { [Role.find_or_create_by_name("superuser")] } end Factory.define :adminuser, :parent => :user do |f| f.roles { [Role.find_or_create_by_name("admin")] } end Factory.define :cms_admin_user, :parent => :user do |f| f.roles { [Role.find_or_create_by_name("cms_admin")] } end Factory.define :cached_contents do |f| f.sequence(:contents_key) { |n| "contents#{n}" } f.name "Test Content Name" f.contents 'Test Content' end Factory.define :reporter, :parent => :user do |f| f.roles { [Role.find_or_create_by_name("reporter")] } end Factory.define :source do |f| f.sequence(:name) { |n| "source#{n})" } end Factory.define :aggregate_product_stat, :class => Admin::AggregateProductStat do |f| f.report_date Date.yesterday f.product_count 400 f.reviewed_product_count 400 f.review_count 800 f.average_reviews 2 end Factory.define :aggregate_product_source_stat, :class => Admin::AggregateProductSourceStat do |f| f.association :source f.association :aggregate_product_stat f.product_count 100 f.reviewed_product_count 100 f.review_count 200 f.average_reviews 2 f.percent_products 0.50 f.percent_reviewed_products 0.25 end Factory.define :category do |f| f.sequence(:name) { |n| "category#{n})" } f.association :source f.active true f.sequence(:dim_value_id) { |n| n } #f.after_create { |c| Factory :category_relationship, :broader_than => Category.find_root, :narrower_than => c } end Factory.define :product_stat do |f| end Factory.define :review_stat do |f| end Factory.define :user_stat do |f| end # Factory.define :product do |f| # f.sequence(:title) { |n| "title#{Time.now.to_i * n}" } # f.sequence(:permalink) { |n| "permalink#{Time.now.to_i * n}" } # f.association :category # f.association :source # f.association :stat, :factory => :product_stat # end # # Factory.define :review do |f| # f.association :user # f.association :product # f.sequence(:sound_bite) { |n| "sb#{Time.now.to_i * n}" } # f.association :product # f.association :stat, :factory => :review_stat # f.points 60 # end Factory.define :review_tag do |f| f.sequence(:value) { |n| "value#{Time.now.to_i * n}" } f.association :review f.kind :about_me end Factory.define :helpful do |f| f.association :source f.value 1 end Factory.define :message do |f| f.association :from_user, :factory => :user f.association :to_user, :factory => :user #f.association :about f.text "Message text" end Factory.define :forum_group do |f| f.name "Community" f.position 0 end Factory.define :forum do |f| f.name "General Discussion" f.position 0 f.cobrand { Cobrand.root } end Factory.define :topic do |f| f.association :forum f.association :user f.locked :locked f.body "1st!!1!" f.title "Discuss!" end Factory.define :post do |f| f.association :user f.association :topic f.body "2nd!!1!" end Factory.define :profanity do |f| f.association :owner end ETTriggeredSendAdd.class_eval do def self.method_missing(*args, &block) end end Factory.define :affiliate do |f| f.sequence(:name) {|n| "Affiliate #{n}" } end Factory.define :affiliate_program do |f| f.association :affiliate f.association :reputable_badge, :factory => :reputable_badge end Factory.define :affiliate_user do |f| f.association :affiliate_program f.association :user end Factory.define :article_instance do |f| f.sequence(:short_name) { |n| "test_article_instance#{Time.now.to_i * n}" } f.name "Article to test #{Time.now.to_i}" f.cobrand { Cobrand.root } end Factory.define :article_category do |f| f.display_text "ArticleCategoryToTest" f.display_order 1 f.association :article_instance end Factory.define :another_article_category, :class => 'ArticleCategory' do |f| f.display_text "AnotherArticleCategoryToTest" f.display_order 1 f.association :article_instance end Factory.define :article_category_with_children, :class => 'ArticleCategory' do |f| f.display_text "ArticleCategoryToTestWithChildren" f.display_order 1 f.association :article_instance f.children {|children| [children.association(:another_article_category)]} end Factory.define :article do |f| f.title "article_in_draft_for_index_test" f.association :article_instance f.association :user, :factory => :superuser f.status 'draft' end Factory.define :event do |e| e.title "some event title" e.association :article_instance e.association :user, :factory => :superuser e.status "draft" e.start_time 1.day.from_now e.end_time 1.week.from_now end Factory.define :published_article, :class => 'Article' do |f| f.title "article_in_draft_for_index_test" f.association :article_instance f.association :user, :factory => :superuser f.status 'published' f.teaser "the teaser" f.content "the content" f.association :article_category end Factory.define :article_to_delete, :class => 'Article' do |f| f.title "article_to_be_deleted" f.content "Content Foo" f.teaser "Teaser Bar" f.article_category_id 1 f.association :article_instance f.association :user, :factory => :superuser f.status 'published' f.published_at { Time.now } end Factory.define :qa_article_instance, :class => 'ArticleInstance' do |f| f.name "Article Instance With qa articles" f.short_name "qa_aa_#{Time.now.to_i}" f.cobrand { Cobrand.root } end Factory.define :qa_article_category, :class => 'ArticleCategory' do |f| f.display_text "QaArticleCategory" f.display_order 1 f.association :article_instance, :factory => :qa_article_instance f.association :primary_author, :factory => :superuser f.short_name "qa_ac_#{Time.now.to_i}" f.partner_key "qa_ac_pk_#{Time.now.to_i}" end Factory.define :qa_article, :class => 'Article' do |f| f.article_type 'qa' f.content "This is the answer to the question" f.sequence(:teaser) { |n| "This is question number #{n}" } f.association :article_category f.association :article_instance f.association :user, :factory => :superuser f.association :contributor, :factory => :user f.status 'published' f.published_at { Time.now } end Factory.define :blog_article_shoevert, :class => 'Article' do |f| f.article_type 'article' f.title 'Blog Article Title' f.teaser "<p>Blog Teaser</p>" f.content "<p>Blog Text</p>" f.association :article_category f.association :article_instance f.association :user, :factory => :superuser f.status 'published' f.published_at { Time.now } end Factory.define :partner_product do |f| f.partner_key { "#{Time.now.to_i}P" } f.source { Source["user"] } # association :source f.association :product f.sort_order 1 end Factory.define :price do |f| f.association :partner_product end Factory.define :user_activity do |f| f.association :user f.association :subject, :factory => :product f.action "reviewed" end Factory.define :partner_category do |f| f.partner_key { "#{Time.now.to_i}C" } f.association :source f.association :category f.name { |p| p.category.name } end Factory.define :sampling_program, :class => Sampling::Program do |f| f.association :affiliate_program f.sequence(:name) { |n| "Sampling Program #{n}"} f.number_of_samples 100 end Factory.define :bdrb_job_queue do |f| f.worker_name "programs_export_worker" f.job_key UUIDTools::UUID.timestamp_create.to_s end Factory.define :sampling_participant, :class => Sampling::Participant do |f| f.association :user end Factory.define :sampling_program_participant, :class => Sampling::ProgramParticipant do |f| f.association :program, :factory => :sampling_program f.association :participant, :factory => :sampling_participant end Factory.define :sampling_program_question, :class => Sampling::ProgramQuestion do |f| f.association :program, :factory => :sampling_program end Factory.define :sampling_program_question_answer, :class => Sampling::ProgramQuestionAnswer do |f| f.association :program_question, :factory => :sampling_program_question end #<ProductPrompt id: 1, interest_id: 1, value: "college or university", position: 1, status: :active, category_id: 2847, cobrand_id: 6, quick_rate_weight: 1, back_fill_weight: 0, created_at: nil, updated_at: nil> Factory.define :product_prompt do |f| f.association :interest f.value "college or university" f.association :category f.cobrand { Cobrand.root } f.quick_rate_weight 1 f.back_fill_weight 1 end Factory.define :purchase_transaction do |f| f.transaction_id "#{Time.now.to_i}" f.purchasers_email "test#{Time.now.to_i}@vp.com" f.purchased_at Time.now f.cobrand { Cobrand.root } f.user_guid "#{Time.now.to_i}" end Factory.define :purchase_transaction_product do |f| f.association :purchase_transaction f.association :product f.shipped_at Time.now end Factory.define :purchase_email_optout do |f| f.email 'foo@bar.com' f.status 'out' f.user_guid "#{Time.now.to_i}" end Factory.define :ratable_entity do |f| f.partner_key "#{Time.now.to_i}P" f.association :source end Factory.define :content_document, :class => Viewpoints::Acts::Moderateable::ContentDocument do |content_document| content_document.association :owner, :factory => :qa_question end Factory.define :feed do |f| f.feed_type 'test' f.directory "#{RAILS_ROOT}/tmp" f.filename 'test_feed.txt' f.content_type 'text/plain' end Factory.define :feed_definition do |f| f.interval 'daily' f.active true f.content_type 'json' f.root_location '/tmp' f.start_date Date.today end Factory.define :scribble do |f| f.association :user f.text "the is the content" end Factory.define :user_interest do |f| f.association :user f.association :interest end Factory.define :user_detail do |f| f.association :user f.key "detail_key" f.value "detail_value" end Factory.define :favorite do |f| f.association :user f.association :target, :factory => :product end Factory.define :notification_preference do |f| f.association :notifiable, :factory => :question f.association :user, :factory => :user f.frequency NotificationPreference::REAL_TIME f.preference NotificationPreference::ANSWERS end Factory.define :interest do |f| f.sequence(:name) {|n| "Interest #{n}" } f.cobrand { Cobrand.root } f.status :active f.parent { InterestTree.for_reg_path(Cobrand.root).root_node } f.source {Source[Source::NAME_SYSTEM]} f.children_attributes do [{ :name => "Sub Interest", :status => :active, :source => Source[Source::NAME_SYSTEM], :position => 1, :cobrand => Cobrand.root }] end end Factory.define :cobrand_param do |f| f.key :admin_sources f.cobrand { Cobrand.root } f.value Source.all.collect(&:id).to_yaml end
module Extensions module Parameterizable def with(*fields) define_getters_for fields define_initializer_for fields block_child_initializers end private def define_getters_for(fields) self.class_eval do attr_reader *Array(fields) end end def define_initializer_for(fields) define_method 'initialize' do |params| fields.each do |field| value = params.fetch(field) { params.fetch(field.to_s) } self.instance_variable_set "@#{field}", value end end end def block_child_initializers self.class_eval do def self.method_added(name) if name == :initialize fail InvalidOverride, "Stop using this module if you want to have your own initializer" end end end end InvalidOverride = Class.new(StandardError) end end
FactoryGirl.define do factory :collage_image, class: CollageImage do association :collage, factory: :collage # picture "picture" picture_file_name 'picture.jpg' picture_content_type 'image/jpeg' picture_file_size 1.megabyte order 1 end end
require 'flex_trans/mapper' RSpec.describe FlexTrans::Mapper do it 'has the mapping attributes' do mapper = FlexTrans::Mapper.mapping_attributes(:id, :name, :price) expect(mapper.current_mapping_attributes).to eq [:id, :name, :price] end it 'has the mapping type' do Product = Struct.new(:id, :name, :price) mapper = FlexTrans::Mapper.mapping_attributes(:id, :name, :price).mapping_type(Product) expect(mapper.current_mapping_type).to eq Product end it 'has the default mapping type with FlexTrans::Struct' do mapper = FlexTrans::Mapper.mapping_attributes(:id, :name, :price) expect(mapper.current_mapping_type).to_not be nil end it "works (just fake it)" do relation = [] objects = FlexTrans::Mapper.mapping_attributes(:id, :name).map(relation, limit: 10) expect(objects).to be_a(Array) end # it 'map to defautl type (struct)' do # # FlexTrans::Mapper.map(relation, limit: 10) # mapper = FlexTrans::Mapper # .map_attrs(:id, :name, :price) # .map_type(MemberPresenter) # # mapper = FlexTrans::Mapper.attributes({ id: :memberId }, :name, :price) # objects = mapper.map(relation, limit: 10) # expect(objects.length).to eq 10 # end # it 'map to specific type with default constructor' do # # FlexTrans::Mapper.map(relation, limit: 10, map_type: ProductViewModel) # end # it 'map to specific type with specific constructor' do # # FlexTrans::Mapper.map(relation, limit: 10, map_type: ProductViewModel, construct_with: :from_attributes) # end end # TODO # FlexTrans::Mapper.register do |registerer| # registerer.register :member do # attribute :id # attribute :name # # mapping_to MemberPresenter # end # end # class Hoge # attr_reader :args # # def initialize(*args) # @args = args # end # end # # >>hoge = FlexTrans::Mapper[{ id: 'product_id' }, :name, :price] # # hoge = FlexTrans::Mapper.new do # map :id, from: 'id' # map :name, from: 'name' # map :price # end # # class ProductMapper < FlexTrans::Mapper # map :id, from: 'id' # map :name, from: 'name' # map :price # end # # >>- attributes # >>- relation # >>- limit
class Load class << self attr_accessor :item_storage end self.item_storage = [] def self.start puts "*loading files..."; puts "" require_relative "load" require_relative "conv/array" require_relative "app/item" require_relative "app/cart" require_relative "app/order" require_relative "app/menu" require_relative "admin/admin_menu" require_relative "admin/admin" require_relative "admin/admin_mode" self.load_storage self.run end def self.run Menu.greeting #default : "Menu.greeting" end def self.load_storage array = File.readlines("storage/items.txt") array.map! {|l| l.chomp} array.map! {|l| l.split(";")} array.each {|l| Load.item_storage << Item.new(name: l[0], price: l[1].to_i, state: l[2], item_id: l[3].to_i)} end def self.save_storage File.open("storage/items.txt", "w") do |f| Load.item_storage.each {|item| f.puts "#{item.name}; #{item.price}; #{item.state}; #{item.item_id}"} end puts "Файл успешно перезаписан"; puts "" AdminMenu.menu end end
#!/opt/local/bin/ruby require 'find' require 'fileutils' $invalid_characters = "[]{}()=+-'," def has_invalid_chacters(path) if path.index(' ') != nil return true end $invalid_characters.each_byte do |c| if path.index(c.chr) != nil return true end end return false end def renamed_file(path) new_path = path $invalid_characters.each_byte do |c| regex = "\\#{c.chr}" new_path = new_path.gsub(/#{regex}/, "").gsub(/ /, "_") end return new_path end def find_invalid_path(dir) Find.find(dir) do |path| if FileTest.directory?(path) if File.basename(path)[0] == ?. and File.basename(path) != '.' Find.prune elsif has_invalid_chacters(path) return path else next end elsif has_invalid_chacters(path) return path end end return nil end def rename_files(dir) path = find_invalid_path(dir) while path != nil do FileUtils.mv(path, renamed_file(path)) path = find_invalid_path(dir) end end rename_files(ARGV[0])