text
stringlengths
10
2.61M
class AddHideHeadersToContentFragments < ActiveRecord::Migration def change add_column :content_fragments, :hide_header, :boolean end end
# encoding: UTF-8 require 'nokogiri' require 'peach' require 'mechanize' module ProductParser ITEM_NUMBER = 200 def self.all_products agent = Mechanize.new category_leafs = Category.find(:all).select {|c| c.children.empty?} page_count = 0 product_count = 0 #category_leafs.each do |c| category_leafs[0..10].peach (5) do |c| agent.get(c.url+"?catalog_numitems=200") pages,products = process_product(c,agent,1) product_count+=products page_count+=pages end puts "#{page_count} pages processed" puts "#{product_count} products created" end #spracuje jednu stranku kategorie (v ratane pokracovani zoznamu produktov) def self.process_product(category, agent, page = 1) base_url = category.url product_count = 0 agent.get(base_url+"?catalog_numitems=200") puts "" puts "processing: "+base_url puts "processing page: " + page.to_s product_count += process_list(agent.page.parser,category) page = 2 while ((count = process_list(agent.get(base_url+"?page=#{page}").parser,category)) > 0) product_count+=count puts "" puts "processing next page" page +=1 end return (page -1),product_count end #spracuje jeden zoznam produktov def self.process_list(doc,category) counter = 0 doc.css("h2 a").each do |p| product = Product.find_or_create_by_url(PRICEMANIA_URL+p[:href]) product.name = p.text puts p.text product.category = category product.save counter += 1 end doc.css("h3 a").each do |p| product = Product.find_or_create_by_url(PRICEMANIA_URL+p[:href]) product.name = p.text puts p.text product.category = category product.save counter += 1 end counter end #zisti celkovy pocet produktov na stranke pricemanie def self.products_number category_leafs = Category.find(:all).select {|c| c.children.empty?} sum = 0 count = 0 number = category_leafs.length category_leafs[1..100].peach (5) do |c| doc = Nokogiri::HTML(open(c.url)) sum+=doc.at_css(".filter-button")[:value][/[0-9]+/].to_i unless doc.at_css(".filter-button")==nil count+=1 puts count.to_s+ "\t/" +number.to_s end puts "sum: "+sum.to_s end end
class ProfilesController < ApplicationController before_filter :authenticate_user! respond_to :html, :xml, :json def show end def edit @profile = Profile.find(params[:id]) redirect_to current_user.profile unless current_user = @profile.user respond_with @profiles end def update @profile = Profile.find(params[:id]) respond_to do |format| if @profile.user == current_user && @profile.update_attributes(params[:profile]) format.html { redirect_to(@profile, :notice => 'Profile was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @profile.errors, :status => :unprocessable_entity } end end end end
class UserMailer < ActionMailer::Base helper.extend(ApplicationHelper) include FilepickerRails::ApplicationHelper default from: "Dabble Me Support <hello@#{ENV['MAIN_DOMAIN']}>" def welcome_email(user) @user = user mail(from: "Dabble Me <#{user.user_key}@#{ENV['SMTP_DOMAIN']}>", to: user.email, subject: "Let's write your first Dabble Me entry") end def second_welcome_email(user) @user = user @first_entry = user.entries.first @first_entry_filepicker_url = filepicker_image_url(@first_entry.image_url, w: 300, h: 300, fit: 'max', cache: true, rotate: :exif) if @first_entry.present? && @first_entry.image_url.present? mail(from: "Dabble Me <#{user.user_key}@#{ENV['SMTP_DOMAIN']}>", to: user.email, subject: "Congrats on writing your first entry!") end def thanks_for_donating(user) @user = user mail(to: user.email, subject: "Thanks for subscribing to Dabble Me PRO!") end end
# frozen_string_literal: true require 'json' require_relative 'display' require_relative 'game_input' # Plays a singular game of hangman class Gameplay include Display include GameInput attr_accessor :save_game_name def initialize( codeword, progress = [], guessed_letters = [], incorrect_letters = [], save_game_name = '' ) @codeword = codeword @progress = progress @guessed_letters = guessed_letters @incorrect_letters = incorrect_letters @save_game_name = save_game_name return unless progress.empty? codeword.length.times { progress.push('*') } end def to_json(*args) { JSON.create_id => self.class.name, 'codeword' => @codeword, 'progress' => @progress, 'guessed_letters' => @guessed_letters, 'incorrect_letters' => @incorrect_letters, 'save_game_name' => @save_game_name }.to_json(*args) end def self.json_create(hash) new(hash['codeword'], hash['progress'], hash['guessed_letters'], hash['incorrect_letters'], hash['save_game_name']) end def play until finished? display(@progress, @incorrect_letters) letter_guess = letter_guess_input(@guessed_letters) return 'save' if letter_guess == '1' guess_reaction(letter_guess) end conclusion end def guess_reaction(letter_guess) if @codeword.include?(letter_guess) puts "\"#{letter_guess}\" is correct!" update_progress(letter_guess) else puts "\"#{letter_guess}\" is not correct!" @incorrect_letters.push(letter_guess) end @guessed_letters.push(letter_guess) end def update_progress(letter_guess) @codeword.split('').each_with_index do |letter, index| @progress[index] = letter_guess if letter == letter_guess end end def finished? return true if @incorrect_letters.length == 6 return true unless @progress.include?('*') false end def conclusion display(@progress, @incorrect_letters) if @progress.include?('*') puts "\nYou didn't guess the word in time!" puts "The correct word was \"#{@codeword}\"" else puts "\nYou guessed the word in time - Congrats!" end 'finished' end end
require File.expand_path('../spec_helper', __FILE__) Dir["./lib/*.rb"].each {|file| require File.expand_path('../../'+file, __FILE__)} describe BankingCodeChallenge::Agent do before :each do @bank1 = BankingCodeChallenge::Bank.new( "Bank1" ) @bank2 = BankingCodeChallenge::Bank.new( "Bank2" ) @account_1_1 = BankingCodeChallenge::Account.new(1111,@bank1,100000) @account_2_1 = BankingCodeChallenge::Account.new(1111,@bank2,3000) @inter_bank_1 = BankingCodeChallenge::InterBank.new(@account_1_1, @account_2_1, 100) @inter_bank_2 = BankingCodeChallenge::InterBank.new(@account_1_1, @account_2_1, 100000) @agent = BankingCodeChallenge::Agent.new() end describe 'validations' do context '.initialize' do it '#agent' do expect(@agent).to be_an_instance_of(BankingCodeChallenge::Agent) end end context '#agent' do it '.makeTransfer successfully' do expect{@agent.makeTransfer(20000,@account_1_1,@account_2_1)}.to change{@account_1_1.balance}.by(-20105) expect{@agent.makeTransfer(20000,@account_1_1,@account_2_1)}.to change{@account_2_1.balance}.by(20000) expect(@agent.makeTransfer(20000,@account_1_1,@account_2_1)).to eq ('successfully delivered') end it '.makeTransfer fail' do expect{@agent.makeTransfer(200000,@account_1_1,@account_2_1)}.to raise_error(RuntimeError) end it '.checkTotalCommissions successfully' do expect(@agent.checkTotalCommissions @inter_bank_1).to have_key(:maxAmount) end it '.checkTotalCommissions fail' do expect{@agent.checkTotalCommissions @inter_bank_2}.to raise_error(RuntimeError) end it '.deliver' do expect(@agent.deliver(@inter_bank_1)).to eq ('successfully delivered') end end end end
class Vote < ApplicationRecord belongs_to :user belongs_to :course validates_uniqueness_of :course_id, scope: :user_id end
# frozen_string_literal: true # 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 rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) Fighter.create(name: 'Bruce', health: 100, attack: 20) Fighter.create(name: 'Rambo', health: 80, attack: 30) Equipment.create(name: 'knife', force: 10, protection: 0) Equipment.create(name: 'shield', force: 0, protection: 20) Equipment.create(name: 'gun', force: 80, protection: 0)
class ApplicationController < ActionController::API before_action :authenticate def authenticate authorization_header = request.headers[:authorization] if(!authorization_header) render status: :unauthorized else token = authorization_header.split(" ")[1] secret_key = Rails.application.secret_key_base[0] decoded_token = JWT.decode(token, secret_key)[0] @user = User.find(decoded_token["user_id"]) end end end
class AddRecordToCalls < ActiveRecord::Migration[5.2] def change add_column :calls, :recorded, :boolean, default: false end end
# frozen_string_literal: true Rails.application.routes.draw do devise_for :users devise_scope(:user) { unauthenticated { root to: 'home#index' } } root 'stocks#index' resources :stocks end
# frozen_string_literal: true # linus_quotes.rb # Author: Winston Weinert # ------------------------ # A Cinch plugin that provides Linus Torvalds quotes for yossarian-bot. # linus_quotes.txt generated from Wikiquote's article # ------------------------ # This code is licensed by Winston Weinert under the MIT License. # http://opensource.org/licenses/MIT require_relative "../yossarian_plugin" class LinusQuotes < YossarianPlugin include Cinch::Plugin use_blacklist QUOTES_FILE = File.expand_path(File.join(File.dirname(__FILE__), "linus_quotes.txt")) QUOTES = File.readlines(QUOTES_FILE) def usage "!linus - Fetch a random Linus Torvalds quote. Aliases: !torvalds." end def match?(cmd) cmd =~ /^(!)?(linus|torvalds)$/ end match /(linus|torvalds)$/, method: :linus_quote def linus_quote(m) m.reply QUOTES.sample end end
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "ditchdaddy" s.version = "0.0.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Jeremy McAnally"] s.date = "2011-12-23" s.description = "Bye GoDaddy, hello DNSimple." s.email = ["jeremy@arcturo.com"] s.executables = ["ditchdaddy"] s.extra_rdoc_files = ["History.txt", "Manifest.txt", "PostInstall.txt"] s.files = ["History.txt", "Manifest.txt", "PostInstall.txt", "README.rdoc", "Rakefile", "bin/ditchdaddy", "lib/ditchdaddy.rb", "script/console", "script/destroy", "script/generate", "test/test_ditchdaddy.rb", "test/test_ditchdaddy_cli.rb", "test/test_helper.rb", ".gemtest"] s.homepage = "http://github.com/jm/ditchdaddy" s.post_install_message = "PostInstall.txt" s.rdoc_options = ["--main", "README.rdoc"] s.require_paths = ["lib"] s.rubyforge_project = "ditchdaddy" s.rubygems_version = "1.8.10" s.summary = "Bye GoDaddy, hello DNSimple." s.test_files = ["test/test_ditchdaddy.rb", "test/test_ditchdaddy_cli.rb", "test/test_helper.rb"] if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<dnsimple>, ["> 0.0.0"]) s.add_runtime_dependency(%q<highline>, ["> 0.0.0"]) s.add_runtime_dependency(%q<rainbow>, ["> 0.0.0"]) s.add_development_dependency(%q<rdoc>, ["~> 3.10"]) s.add_development_dependency(%q<newgem>, [">= 1.5.3"]) s.add_development_dependency(%q<hoe>, ["~> 2.12"]) else s.add_dependency(%q<dnsimple>, ["> 0.0.0"]) s.add_dependency(%q<highline>, ["> 0.0.0"]) s.add_dependency(%q<rainbow>, ["> 0.0.0"]) s.add_dependency(%q<rdoc>, ["~> 3.10"]) s.add_dependency(%q<newgem>, [">= 1.5.3"]) s.add_dependency(%q<hoe>, ["~> 2.12"]) end else s.add_dependency(%q<dnsimple>, ["> 0.0.0"]) s.add_dependency(%q<highline>, ["> 0.0.0"]) s.add_dependency(%q<rainbow>, ["> 0.0.0"]) s.add_dependency(%q<rdoc>, ["~> 3.10"]) s.add_dependency(%q<newgem>, [">= 1.5.3"]) s.add_dependency(%q<hoe>, ["~> 2.12"]) end end
#!/usr/bin/env ruby def process(mp3) name = File.basename(mp3) raise 'weird' unless name root = name[1] webmName = "#{root}.webm" command = "ffmpeg -y -i #{mp3} #{webmName}" puts "#{mp3} -> #{webmName}" puts " * From: #{File.size(mp3)}" `#{command} 2>&1` puts " * To : #{File.size(webmName)}" end mp3s = Dir.glob('*.mp?') mp3s.each { |mp3| process(mp3) }
FactoryGirl.define do factory :plan do name 'Basic' end end
class Height module Units class Inches < Base def to_inches self end def to_millimeters millimeters = value * Height::MILLIMETERS_IN_INCH Millimeters.new(millimeters) end def to_centimeters to_millimeters.to_centimeters end def to_meters to_centimeters.to_meters end def to_feet feet = value / Height::INCHES_IN_FOOT.to_f Feet.new(feet) end end end end
# encoding: utf-8 class PeopleController < ApplicationController active_scaffold :person do |config| # Explicitly adds all columns we need, in specific order config.columns = [:name, :firstname, :lastname, :street, :zipcity, :birthday, :entry_date, :leave_date, :email, :phone, :mobile, :birthday, :image, :gender, :amount, :discount, :is_yearly, :salutation, :bill_name, :bill_firstname, :bill_lastname, :bill_streetprefix, :bill_street, :bill_zipcity, :bill_email, :gradex, :notex, :docx, :coursex] # Labels all columns columns[:name].label = 'Name, Vorname' columns[:lastname].label = 'Nachname' columns[:firstname].label = 'Vorname' columns[:street].label = 'Strasse' columns[:zipcity].label = 'PLZ Ort' columns[:email].label = 'E-Mail' columns[:phone].label = 'Telefon' columns[:mobile].label = 'Mobile' columns[:birthday].label = 'Geburtstag' columns[:entry_date].label = 'Eintritt' columns[:leave_date].label = 'Austritt' columns[:image].label = 'Bild' columns[:gender].label = 'Geschlecht' columns[:salutation].label = 'Anrede' columns[:bill_name].label = 'Name, Vorname' columns[:bill_lastname].label = 'Nachname' columns[:bill_firstname].label = 'Vorname' columns[:bill_streetprefix].label = 'Adresszusatz' columns[:bill_street].label = 'Strasse' columns[:bill_zipcity].label = 'PLZ Ort' columns[:bill_email].label = 'E-Mail' columns[:amount].label = 'Rechnungsbetrag' columns[:discount].label = 'Rabatt' columns[:is_yearly].label = 'Jahresrechnung' columns[:gradex].label = 'Prfg.' columns[:notex].label = 'Not.' columns[:docx].label = 'Dok.' columns[:coursex].label = 'Kurse' # Prepares List, we want to see only few col's here therefore explicit assignment list.columns = [:name, :gradex, :notex, :docx, :coursex] list.sorting = [{:lastname => :asc}, {:firstname => :asc}] # initial sort of list columns[:name].sort_by :sql => 'lastname||firstname' # adds sorting capability on virtual column list.always_show_search = true list.per_page = 50 # Prepares Show, we dopn't want to see single attributes if there are combined, and we want to see groups show.columns.exclude :firstname, :lastname, :bill_firstname, :bill_lastname, :gradex, :notex, :docx, :coursex show.columns.add_subgroup "Rechnungsdetails" do |bill_details| bill_details.add :amount, :discount, :is_yearly end show.columns.add_subgroup "Rechnungsadresse" do |bill_group| bill_group.add :salutation, :bill_name, :bill_streetprefix, :bill_street, :bill_zipcity, :bill_email end # Prepares Create # We don't want to have a leave date when we create a person # We want to see grouping create.columns.exclude :leave_date, :gradex, :notex, :docx, :coursex create.columns.add_subgroup "Rechnungsdetails" do |bill_details| bill_details.add :amount, :discount, :is_yearly end create.columns.add_subgroup "Rechnungsadresse" do |bill_group| bill_group.add :salutation, :bill_name, :bill_streetprefix, :bill_street, :bill_zipcity, :bill_email end update.columns.exclude :gradex, :notex, :docx, :coursex update.columns.add_subgroup "Rechnungsdetails" do |bill_details| bill_details.add :amount, :discount, :is_yearly end update.columns.add_subgroup "Rechnungsadresse" do |bill_group| bill_group.add :salutation, :bill_name, :bill_streetprefix, :bill_street, :bill_zipcity, :bill_email end columns[:birthday].description = "YYYY-mm-dd" columns[:entry_date].description = "YYYY-mm-dd" columns[:leave_date].description = "YYYY-mm-dd" # Headings list.label = 'Personen' search.link.label = 'Suchen' search.columns = [:lastname, :firstname] create.link.label = 'Neue Person' # Columns nested.add_link :notes, :label => "Notitzen" nested.add_link :bills, :label => "Rechnungen" nested.add_link :documents, :label => "Dokumente" nested.add_link :gradings, :label => "Prüfungen" nested.add_link :courses, :label => "Kurse" update.link.label = 'Ändern' delete.link.label = 'Löschen' show.link.label = 'Details' show.label = 'Details' end # in main form, show active people #def conditions_for_collection # if !nested? then # ['leave_date is null'] # end #end end
class CharacterBlessingAbility < ApplicationRecord belongs_to :blessing_level belongs_to :character end
require 'rails_helper' RSpec.describe Product, type: :model do let(:blank_product) {Product.new()} describe 'validations' do context 'Should not allow blank fields' do it 'for title' do blank_product.save expect(blank_product.errors[:title]).to include("can't be blank") end it 'for price' do blank_product.save expect(blank_product.errors[:price]).to include("can't be blank") end end end end
require 'rails_helper' include RandomData RSpec.describe ItemsController, type: :controller do describe '#create' do let(:user) { create(:user) } context 'user signed in' do before { sign_in user } it "should have a user" do expect(user).to_not be_nil end it 'can create an item' do expect { post :create, user_id: user.id, item: {name: 'something'} }.to change(Item,:count).by(1) end it 'redirects to user#show' do post :create, user_id: user.id, item: {name: 'something'} expect(response).to redirect_to user end it 'should belong to the user' do post :create, user_id: user.id, item: { user_id: user.id, name: 'something' } expect(Item.last.user).to eq(user) end context 'blank item' do it 'displays an error' do post :create, user_id: user.id, item: {name: 'something'} expect(:item).not_to be_nil end end end context 'user not signed in' do it 'does not create an item' do post :create, user_id: user.id, item: {name: 'something'} expect(response).to redirect_to(new_user_session_path) end end end end
require 'rails_helper' RSpec.describe UserApiController, type: :controller do render_views before do create :user end let(:signup_params) do { 'user_name' => 'signup', 'password' => 'password', 'password_confirmation' => 'password'} end let(:signup_failure_params) do { 'user_name' => '', 'password' => 'password', 'password_confirmation' => 'pazzword' } end let(:login_params) do { 'user_name' => 'test', 'password' => 'password' } end let(:login_failure_params) do { 'user_name' => '', 'password' => 'password' } end it 'サインアップのテスト' do post :signup, xhr: true, params: signup_params expect(response.status).to eq(200) body = JSON.parse(response.body) expect(body['status']).to be_truthy expect(body['token']) .to eq(User.find_by(name: 'signup').user_session.token) expect(body['user']) .to be_present end it 'サインアップ失敗のテスト' do post :signup, xhr: true, params: signup_failure_params expect(response.status).to eq(401) body = JSON.parse(response.body) expect(body['status']) .to be_falsy expect(body['message']).to be_present end it 'ログインのテスト' do post :login, xhr: true, params: login_params expect(response.status).to eq(200) body = JSON.parse(response.body) expect(body['status']).to be_truthy expect(body['token']) .to eq(User.find_by(name: 'test').user_session.token) expect(body['user']) .to be_present end it 'ログイン失敗のテスト' do post :login, xhr: true, params: login_failure_params expect(response.status).to eq(401) body = JSON.parse(response.body) expect(body['status']) .to be_falsy expect(body['message']).to be_present end it 'ログアウトのテスト' do post :logout, xhr: true, params: {} expect(response.status).to eq(401) body = JSON.parse(response.body) expect(body['status']) .to be_falsy expect(body['message']).to be_present end it 'ログインログアウトのテスト' do post :login, xhr: true, params: login_params expect(response.status).to eq(200) body = JSON.parse(response.body) token = User.find_by(name: 'test').user_session.token expect(body['token']).to eq(token) request.headers['Authorization'] = "Token #{token}" post :logout, xhr: true, params: {} expect(response.status).to eq(200) body = JSON.parse(response.body) expect(body['status']) .to be_truthy expect(body['message']).to be_present end it 'is_loginのテスト' do post :is_login, xhr: true, params: {} expect(response.status).to eq(401) body = JSON.parse(response.body) expect(body['status']).to be_falsy expect(body['user']) .to be_nil end it 'ログイン後is_loginのテスト' do post :login, xhr: true, params: login_params expect(response.status).to eq(200) body = JSON.parse(response.body) token = User.find_by(name: 'test').user_session.token expect(body['token']).to eq(token) request.headers['Authorization'] = "Token #{token}" post :is_login, xhr: true, params: {} expect(response.status).to eq(200) body = JSON.parse(response.body) expect(body['status']).to be_truthy expect(body['user']) .to be_present end it 'ログインログアウト後is_loginのテスト' do post :login, xhr: true, params: login_params expect(response.status).to eq(200) body = JSON.parse(response.body) token = User.find_by(name: 'test').user_session.token expect(body['token']).to eq(token) request.headers['Authorization'] = "Token #{token}" post :logout, xhr: true, params: {} expect(response.status).to eq(200) body = JSON.parse(response.body) expect(body['message']).to be_present request.headers['Authorization'] = "Token #{token}" post :is_login, xhr: true, params: {} expect(response.status).to eq(200) body = JSON.parse(response.body) expect(body['status']) .to be_falsy expect(body['message']).to be_present end end
module ApplicationHelper # Writes a given DateTime (e.g., a publication date) as a human-friendly # string, using an 'ago' phrase if the date is today. # # date - a DateTime # # Examples # # date_in_words(DateTime.new(1990, 2, 3, 4, 5, 6)) # => "Feb 3, 1990" # date_in_words(DateTime.now) # => "less than a minute ago" def date_in_words(date) date.today? ? time_ago_in_words(date) + ' ago' : date.strftime("%b. %d, %Y") end end
class ShortUrl < ActiveRecord::Base before_create :shorten def visited self.visits = self.visits.to_i + 1 self.lastvisit = Time.now save! end private def shorten self.short = bijective_encode(ShortUrl.count() + 1000) self.short_full = 'http://localhost:3001/' + self.short end ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".split(//) # make your own alphabet using: # (('a'..'z').to_a + ('A'..'Z').to_a + (0..9).to_a).shuffle.join def bijective_encode(i) # from http://refactormycode.com/codes/125-base-62-encoding # with only minor modification return ALPHABET[0] if i == 0 s = '' base = ALPHABET.length while i > 0 s << ALPHABET[i.modulo(base)] i /= base end s.reverse end end
require 'fastly' require 'vine/cdn/fastly/client' require 'vine/cdn/fastly/configuration' require 'vine/cdn/fastly/errors' require 'vine/cdn/fastly/mongoid' require 'vine/cdn/fastly/grape' module Vine module Fastly attr_reader :client def self.config Vine.config.fastly end def self.service_id raise Vine::Fastly::NoServiceIdProvidedError if config.invalid_service_id? config.service_id end def self.client raise Vine::Fastly::NoAPIKeyProvidedError unless config.authenticatable? @client ||= Vine::Fastly::Client.new( api_key: config.api_key, user: config.user, password: config.password ) end end end
class ApplicationController < ActionController::API include ActionController::MimeResponds include ActionController::ImplicitRender before_filter :cors_set_access_control_headers respond_to :json private def cors_set_access_control_headers unless Rails.env.production? || Rails.env.staging? headers['Access-Control-Allow-Origin'] = '*'# need to be changed once it goes to production 'http://localhost:8080' else headers['Access-Control-Allow-Origin'] = 'http://localhost:8080' end headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS' headers['Access-Control-Allow-Headers'] = '*, X-Requested-With, X-Prototype-Version, X-CSRF-Token, Content-Type' headers['Access-Control-Max-Age'] = "1728000" end end
# ==== GRAPH ==== class ArangoGraph < ArangoServer def initialize(graph: @@graph, database: @@database, edgeDefinitions: [], orphanCollections: []) # TESTED if database.is_a?(String) @database = database elsif database.is_a?(ArangoDatabase) @database = database.database else raise "database should be a String or an ArangoDatabase instance, not a #{database.class}" end if graph.is_a?(String) @graph = graph elsif database.is_a?(ArangoGraph) @graph = graph.graph else raise "graph should be a String or an ArangoGraph instance, not a #{graph.class}" end if edgeDefinitions.is_a?(Array) @edgeDefinitions = edgeDefinitions else raise "edgeDefinitions should be an Array, not a #{edgeDefinitions.class}" end if orphanCollections.is_a?(Array) @orphanCollections = orphanCollections else raise "orphanCollections should be an Array, not a #{orphanCollections.class}" end @idCache = "GRA_#{@graph}" end attr_reader :graph, :edgeDefinitions, :orphanCollections, :database, :idCache alias name graph # === RETRIEVE === def to_hash { "graph" => @graph, "collection" => @collection, "database" => @database, "edgeDefinitions" => @edgeDefinitions, "orphanCollections" => @orphanCollections, "idCache" => @idCache }.delete_if{|k,v| v.nil?} end alias to_h to_hash def database ArangoDatabase.new(database: @database) end # === GET === def retrieve # TESTED result = self.class.get("/_db/#{@database}/_api/gharial/#{@graph}", @@request) return result.headers["x-arango-async-id"] if @@async == "store" return true if @@async result = result.parsed_response return result if @@verbose return result["errorMessage"] if result["error"] @edgeDefinitions = result["graph"]["edgeDefinitions"] @orphanCollections = result["graph"]["orphanCollections"] self end # === POST === def create # TESTED body = { "name" => @graph, "edgeDefinitions" => @edgeDefinitions, "orphanCollections" => @orphanCollections } request = @@request.merge({ :body => body.to_json }) result = self.class.post("/_db/#{@database}/_api/gharial", request) return result.headers["x-arango-async-id"] if @@async == "store" return true if @@async result = result.parsed_response @@verbose ? result : result["error"] ? result["errorMessage"] : self end # === DELETE === def destroy # TESTED result = self.class.delete("/_db/#{@database}/_api/gharial/#{@graph}", @@request) return result.headers["x-arango-async-id"] if @@async == "store" return true if @@async result = result.parsed_response @@verbose ? result : result["error"] ? result["errorMessage"] : true end # === VERTEX COLLECTION === def vertexCollections # TESTED result = self.class.get("/_db/#{@database}/_api/gharial/#{@graph}/vertex", @@request) return result.headers["x-arango-async-id"] if @@async == "store" return true if @@async result = result.parsed_response @@verbose ? result : result["error"] ? result["errorMessage"] : result["collections"].map{|x| ArangoCollection.new(collection: x)} end def addVertexCollection(collection:) # TESTED collection = collection.is_a?(String) ? collection : collection.collection body = { "collection" => collection }.to_json request = @@request.merge({ :body => body }) result = self.class.post("/_db/#{@database}/_api/gharial/#{@graph}/vertex", request) return result.headers["x-arango-async-id"] if @@async == "store" return true if @@async result = result.parsed_response if @@verbose @orphanCollections << collection unless result["error"] result else return result["errorMessage"] if result["error"] @orphanCollections << collection self end end def removeVertexCollection(collection:) # TESTED collection = collection.is_a?(String) ? collection : collection.collection result = self.class.delete("/_db/#{@database}/_api/gharial/#{@graph}/vertex/#{collection}", @@request) return result.headers["x-arango-async-id"] if @@async == "store" return true if @@async result = result.parsed_response if @@verbose @orphanCollections -= [collection] unless result["error"] result else return result["errorMessage"] if result["error"] @orphanCollections -= [collection] self end end # === EDGE COLLECTION === def edgeCollections # TESTED result = self.class.get("/_db/#{@database}/_api/gharial/#{@graph}/edge", @@request) return result.headers["x-arango-async-id"] if @@async == "store" return true if @@async result = result.parsed_response @@verbose ? result : result["error"] ? result["errorMessage"] : result["collections"].map{|x| ArangoCollection.new(collection: x)} end def addEdgeCollection(collection:, from:, to:, replace: false) # TESTED from = from.is_a?(String) ? [from] : from.is_a?(ArangoCollection) ? [from.collection] : from to = to.is_a?(String) ? [to] : to.is_a?(ArangoCollection) ? [to.collection] : to body = {} collection = collection.is_a?(String) ? collection : collection.collection body["collection"] = collection body["from"] = from.map{|f| f.is_a?(String) ? f : f.id } body["to"] = to.map{|t| t.is_a?(String) ? t : t.id } request = @@request.merge({ :body => body.to_json }) if replace result = self.class.put("/_db/#{@database}/_api/gharial/#{@graph}/edge/#{collection}", request) else result = self.class.post("/_db/#{@database}/_api/gharial/#{@graph}/edge", request) end return result.headers["x-arango-async-id"] if @@async == "store" return true if @@async result = result.parsed_response if @@verbose unless result["error"] @edgeDefinitions = result["graph"]["edgeDefinitions"] @orphanCollections = result["graph"]["orphanCollections"] end result else return result["errorMessage"] if result["error"] @edgeDefinitions = result["graph"]["edgeDefinitions"] @orphanCollections = result["graph"]["orphanCollections"] self end end def replaceEdgeCollection(collection:, from:, to:) # TESTED self.addEdgeCollection(collection: collection, from: from, to: to, replace: true) end def removeEdgeCollection(collection:) # TESTED collection = collection.is_a?(String) ? collection : collection.collection result = self.class.delete("/_db/#{@database}/_api/gharial/#{@graph}/edge/#{collection}", @@request) return result.headers["x-arango-async-id"] if @@async == "store" return true if @@async result = result.parsed_response if @@verbose unless result["error"] @edgeDefinitions = result["graph"]["edgeDefinitions"] @orphanCollections = result["graph"]["orphanCollections"] end result else return result["errorMessage"] if result["error"] @edgeDefinitions = result["graph"]["edgeDefinitions"] @orphanCollections = result["graph"]["orphanCollections"] self end end end
Rails.application.routes.draw do root "books#index" # get "/books", to: "books#index", as: "books" # post "/books", to: "books#create" # get "/books/new", to: "books#new", as: "new_book" # get "/books/:id", to: "books#show", as: "book" # get "/books/:id/edit", to: "books#edit", as: "edit_book" # patch "/books/:id", to: "books#update" # delete "/books/:id", to: "books#destroy" resources :books #, except: [:destroy] resources :authors do # Why only index and new? resources :books, only: [:index, :new] end get "/users/current", to: "users#current", as: "current_user" get "/auth/github", as: "github_login" get "/auth/:provider/callback", to: "users#create", as: "auth_callback" delete "/logout", to: "users#destroy", as: "logout" end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2014-2020 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo class Collection class View # Defines read related behavior for collection view. # # @since 2.0.0 module Readable # Execute an aggregation on the collection view. # # @example Aggregate documents. # view.aggregate([ # { "$group" => { "_id" => "$city", "tpop" => { "$sum" => "$pop" }}} # ]) # # @param [ Array<Hash> ] pipeline The aggregation pipeline. # @param [ Hash ] options The aggregation options. # # @option options [ true, false ] :allow_disk_use Set to true if disk # usage is allowed during the aggregation. # @option options [ Integer ] :batch_size The number of documents to return # per batch. # @option options [ true, false ] :bypass_document_validation Whether or # not to skip document level validation. # @option options [ Hash ] :collation The collation to use. # @option options [ Object ] :comment A user-provided # comment to attach to this command. # @option options [ String ] :hint The index to use for the aggregation. # @option options [ Hash ] :let Mapping of variables to use in the pipeline. # See the server documentation for details. # @option options [ Integer ] :max_time_ms The maximum amount of time in # milliseconds to allow the aggregation to run. # @option options [ true, false ] :use_cursor Indicates whether the command # will request that the server provide results using a cursor. Note that # as of server version 3.6, aggregations always provide results using a # cursor and this option is therefore not valid. # @option options [ Session ] :session The session to use. # # @return [ Aggregation ] The aggregation object. # # @since 2.0.0 def aggregate(pipeline, options = {}) options = @options.merge(options) unless Mongo.broken_view_options aggregation = Aggregation.new(self, pipeline, options) # Because the $merge and $out pipeline stages write documents to the # collection, it is necessary to clear the cache when they are performed. # # Opt to clear the entire cache rather than one namespace because # the $out and $merge stages do not have to write to the same namespace # on which the aggregation is performed. QueryCache.clear if aggregation.write? aggregation end # Allows the server to write temporary data to disk while executing # a find operation. # # @return [ View ] The new view. def allow_disk_use configure(:allow_disk_use, true) end # Allows the query to get partial results if some shards are down. # # @example Allow partial results. # view.allow_partial_results # # @return [ View ] The new view. # # @since 2.0.0 def allow_partial_results configure(:allow_partial_results, true) end # Tell the query's cursor to stay open and wait for data. # # @example Await data on the cursor. # view.await_data # # @return [ View ] The new view. # # @since 2.0.0 def await_data configure(:await_data, true) end # The number of documents returned in each batch of results from MongoDB. # # @example Set the batch size. # view.batch_size(5) # # @note Specifying 1 or a negative number is analogous to setting a limit. # # @param [ Integer ] batch_size The size of each batch of results. # # @return [ Integer, View ] Either the batch_size value or a # new +View+. # # @since 2.0.0 def batch_size(batch_size = nil) configure(:batch_size, batch_size) end # Associate a comment with the query. # # @example Add a comment. # view.comment('slow query') # # @note Set profilingLevel to 2 and the comment will be logged in the profile # collection along with the query. # # @param [ Object ] comment The comment to be associated with the query. # # @return [ String, View ] Either the comment or a # new +View+. # # @since 2.0.0 def comment(comment = nil) configure(:comment, comment) end # Get a count of matching documents in the collection. # # @example Get the number of documents in the collection. # collection_view.count # # @param [ Hash ] opts Options for the operation. # # @option opts :skip [ Integer ] The number of documents to skip. # @option opts :hint [ Hash ] Override default index selection and force # MongoDB to use a specific index for the query. # @option opts :limit [ Integer ] Max number of docs to count. # @option opts :max_time_ms [ Integer ] The maximum amount of time to allow the # command to run. # @option opts [ Hash ] :read The read preference options. # @option opts [ Hash ] :collation The collation to use. # @option opts [ Mongo::Session ] :session The session to use for the operation. # @option opts [ Object ] :comment A user-provided # comment to attach to this command. # # @return [ Integer ] The document count. # # @since 2.0.0 # # @deprecated Use #count_documents or #estimated_document_count instead. However, note that # the following operators will need to be substituted when switching to #count_documents: # * $where should be replaced with $expr (only works on 3.6+) # * $near should be replaced with $geoWithin with $center # * $nearSphere should be replaced with $geoWithin with $centerSphere def count(opts = {}) opts = @options.merge(opts) unless Mongo.broken_view_options cmd = { :count => collection.name, :query => filter } cmd[:skip] = opts[:skip] if opts[:skip] cmd[:hint] = opts[:hint] if opts[:hint] cmd[:limit] = opts[:limit] if opts[:limit] if read_concern cmd[:readConcern] = Options::Mapper.transform_values_to_strings( read_concern) end cmd[:maxTimeMS] = opts[:max_time_ms] if opts[:max_time_ms] Mongo::Lint.validate_underscore_read_preference(opts[:read]) read_pref = opts[:read] || read_preference selector = ServerSelector.get(read_pref || server_selector) with_session(opts) do |session| read_with_retry(session, selector) do |server| Operation::Count.new( selector: cmd, db_name: database.name, options: {:limit => -1}, read: read_pref, session: session, # For some reason collation was historically accepted as a # string key. Note that this isn't documented as valid usage. collation: opts[:collation] || opts['collation'] || collation, comment: opts[:comment], ).execute(server, context: Operation::Context.new(client: client, session: session)) end.n.to_i end end # Get a count of matching documents in the collection. # # @example Get the number of documents in the collection. # collection_view.count # # @param [ Hash ] opts Options for the operation. # # @option opts :skip [ Integer ] The number of documents to skip. # @option opts :hint [ Hash ] Override default index selection and force # MongoDB to use a specific index for the query. Requires server version 3.6+. # @option opts :limit [ Integer ] Max number of docs to count. # @option opts :max_time_ms [ Integer ] The maximum amount of time to allow the # command to run. # @option opts [ Hash ] :read The read preference options. # @option opts [ Hash ] :collation The collation to use. # @option opts [ Mongo::Session ] :session The session to use for the operation. # @option ops [ Object ] :comment A user-provided # comment to attach to this command. # # @return [ Integer ] The document count. # # @since 2.6.0 def count_documents(opts = {}) opts = @options.merge(opts) unless Mongo.broken_view_options pipeline = [:'$match' => filter] pipeline << { :'$skip' => opts[:skip] } if opts[:skip] pipeline << { :'$limit' => opts[:limit] } if opts[:limit] pipeline << { :'$group' => { _id: 1, n: { :'$sum' => 1 } } } opts = opts.slice(:hint, :max_time_ms, :read, :collation, :session, :comment) opts[:collation] ||= collation first = aggregate(pipeline, opts).first return 0 unless first first['n'].to_i end # Gets an estimate of the count of documents in a collection using collection metadata. # # @example Get the number of documents in the collection. # collection_view.estimated_document_count # # @param [ Hash ] opts Options for the operation. # # @option opts :max_time_ms [ Integer ] The maximum amount of time to allow the command to # run. # @option opts [ Hash ] :read The read preference options. # @option opts [ Object ] :comment A user-provided # comment to attach to this command. # # @return [ Integer ] The document count. # # @since 2.6.0 def estimated_document_count(opts = {}) unless view.filter.empty? raise ArgumentError, "Cannot call estimated_document_count when querying with a filter" end %i[limit skip].each do |opt| if options.key?(opt) || opts.key?(opt) raise ArgumentError, "Cannot call estimated_document_count when querying with #{opt}" end end opts = @options.merge(opts) unless Mongo.broken_view_options Mongo::Lint.validate_underscore_read_preference(opts[:read]) read_pref = opts[:read] || read_preference selector = ServerSelector.get(read_pref || server_selector) with_session(opts) do |session| read_with_retry(session, selector) do |server| context = Operation::Context.new(client: client, session: session) cmd = { count: collection.name } cmd[:maxTimeMS] = opts[:max_time_ms] if opts[:max_time_ms] if read_concern cmd[:readConcern] = Options::Mapper.transform_values_to_strings(read_concern) end result = Operation::Count.new( selector: cmd, db_name: database.name, read: read_pref, session: session, comment: opts[:comment], ).execute(server, context: context) result.n.to_i end end rescue Error::OperationFailure => exc if exc.code == 26 # NamespaceNotFound # This should only happen with the aggregation pipeline path # (server 4.9+). Previous servers should return 0 for nonexistent # collections. 0 else raise end end # Get a list of distinct values for a specific field. # # @example Get the distinct values. # collection_view.distinct('name') # # @param [ String, Symbol ] field_name The name of the field. # @param [ Hash ] opts Options for the distinct command. # # @option opts :max_time_ms [ Integer ] The maximum amount of time to allow the # command to run. # @option opts [ Hash ] :read The read preference options. # @option opts [ Hash ] :collation The collation to use. # @option options [ Object ] :comment A user-provided # comment to attach to this command. # # @return [ Array<Object> ] The list of distinct values. # # @since 2.0.0 def distinct(field_name, opts = {}) if field_name.nil? raise ArgumentError, 'Field name for distinct operation must be not nil' end opts = @options.merge(opts) unless Mongo.broken_view_options cmd = { :distinct => collection.name, :key => field_name.to_s, :query => filter, } cmd[:maxTimeMS] = opts[:max_time_ms] if opts[:max_time_ms] if read_concern cmd[:readConcern] = Options::Mapper.transform_values_to_strings( read_concern) end Mongo::Lint.validate_underscore_read_preference(opts[:read]) read_pref = opts[:read] || read_preference selector = ServerSelector.get(read_pref || server_selector) with_session(opts) do |session| read_with_retry(session, selector) do |server| Operation::Distinct.new( selector: cmd, db_name: database.name, options: {:limit => -1}, read: read_pref, session: session, comment: opts[:comment], # For some reason collation was historically accepted as a # string key. Note that this isn't documented as valid usage. collation: opts[:collation] || opts['collation'] || collation, ).execute(server, context: Operation::Context.new(client: client, session: session)) end.first['values'] end end # The index that MongoDB will be forced to use for the query. # # @example Set the index hint. # view.hint(name: 1) # # @param [ Hash ] hint The index to use for the query. # # @return [ Hash, View ] Either the hint or a new +View+. # # @since 2.0.0 def hint(hint = nil) configure(:hint, hint) end # The max number of docs to return from the query. # # @example Set the limit. # view.limit(5) # # @param [ Integer ] limit The number of docs to return. # # @return [ Integer, View ] Either the limit or a new +View+. # # @since 2.0.0 def limit(limit = nil) configure(:limit, limit) end # Execute a map/reduce operation on the collection view. # # @example Execute a map/reduce. # view.map_reduce(map, reduce) # # @param [ String ] map The map js function. # @param [ String ] reduce The reduce js function. # @param [ Hash ] options The map/reduce options. # # @return [ MapReduce ] The map reduce wrapper. # # @since 2.0.0 def map_reduce(map, reduce, options = {}) MapReduce.new(self, map, reduce, @options.merge(options)) end # Set the max number of documents to scan. # # @example Set the max scan value. # view.max_scan(1000) # # @param [ Integer ] value The max number to scan. # # @return [ Integer, View ] The value or a new +View+. # # @since 2.0.0 # # @deprecated This option is deprecated as of MongoDB server # version 4.0. def max_scan(value = nil) configure(:max_scan, value) end # Set the maximum value to search. # # @example Set the max value. # view.max_value(_id: 1) # # @param [ Hash ] value The max field and value. # # @return [ Hash, View ] The value or a new +View+. # # @since 2.1.0 def max_value(value = nil) configure(:max_value, value) end # Set the minimum value to search. # # @example Set the min value. # view.min_value(_id: 1) # # @param [ Hash ] value The min field and value. # # @return [ Hash, View ] The value or a new +View+. # # @since 2.1.0 def min_value(value = nil) configure(:min_value, value) end # The server normally times out idle cursors after an inactivity period # (10 minutes) to prevent excess memory use. Set this option to prevent that. # # @example Set the cursor to not timeout. # view.no_cursor_timeout # # @return [ View ] The new view. # # @since 2.0.0 def no_cursor_timeout configure(:no_cursor_timeout, true) end # The fields to include or exclude from each doc in the result set. # # @example Set the fields to include or exclude. # view.projection(name: 1) # # @note A value of 0 excludes a field from the doc. A value of 1 includes it. # Values must all be 0 or all be 1, with the exception of the _id value. # The _id field is included by default. It must be excluded explicitly. # # @param [ Hash ] document The field and 1 or 0, to include or exclude it. # # @return [ Hash, View ] Either the fields or a new +View+. # # @since 2.0.0 def projection(document = nil) validate_doc!(document) if document configure(:projection, document) end # The read preference to use for the query. # # @note If none is specified for the query, the read preference of the # collection will be used. # # @param [ Hash ] value The read preference mode to use for the query. # # @return [ Symbol, View ] Either the read preference or a # new +View+. # # @since 2.0.0 def read(value = nil) return read_preference if value.nil? configure(:read, value) end # Set whether to return only the indexed field or fields. # # @example Set the return key value. # view.return_key(true) # # @param [ true, false ] value The return key value. # # @return [ true, false, View ] The value or a new +View+. # # @since 2.1.0 def return_key(value = nil) configure(:return_key, value) end # Set whether the disk location should be shown for each document. # # @example Set show disk location option. # view.show_disk_loc(true) # # @param [ true, false ] value The value for the field. # # @return [ true, false, View ] Either the value or a new # +View+. # # @since 2.0.0 def show_disk_loc(value = nil) configure(:show_disk_loc, value) end alias :show_record_id :show_disk_loc # The number of docs to skip before returning results. # # @example Set the number to skip. # view.skip(10) # # @param [ Integer ] number Number of docs to skip. # # @return [ Integer, View ] Either the skip value or a # new +View+. # # @since 2.0.0 def skip(number = nil) configure(:skip, number) end # Set the snapshot value for the view. # # @note When set to true, prevents documents from returning more than # once. # # @example Set the snapshot value. # view.snapshot(true) # # @param [ true, false ] value The snapshot value. # # @since 2.0.0 # # @deprecated This option is deprecated as of MongoDB server # version 4.0. def snapshot(value = nil) configure(:snapshot, value) end # The key and direction pairs by which the result set will be sorted. # # @example Set the sort criteria # view.sort(name: -1) # # @param [ Hash ] spec The attributes and directions to sort by. # # @return [ Hash, View ] Either the sort setting or a # new +View+. # # @since 2.0.0 def sort(spec = nil) configure(:sort, spec) end # If called without arguments or with a nil argument, returns # the legacy (OP_QUERY) server modifiers for the current view. # If called with a non-nil argument, which must be a Hash or a # subclass, merges the provided modifiers into the current view. # Both string and symbol keys are allowed in the input hash. # # @example Set the modifiers document. # view.modifiers(:$orderby => Mongo::Index::ASCENDING) # # @param [ Hash ] doc The modifiers document. # # @return [ Hash, View ] Either the modifiers document or a new +View+. # # @since 2.1.0 def modifiers(doc = nil) if doc.nil? Operation::Find::Builder::Modifiers.map_server_modifiers(options) else new(options.merge(Operation::Find::Builder::Modifiers.map_driver_options(BSON::Document.new(doc)))) end end # A cumulative time limit in milliseconds for processing get more operations # on a cursor. # # @example Set the max await time ms value. # view.max_await_time_ms(500) # # @param [ Integer ] max The max time in milliseconds. # # @return [ Integer, View ] Either the max await time ms value or a new +View+. # # @since 2.1.0 def max_await_time_ms(max = nil) configure(:max_await_time_ms, max) end # A cumulative time limit in milliseconds for processing operations on a cursor. # # @example Set the max time ms value. # view.max_time_ms(500) # # @param [ Integer ] max The max time in milliseconds. # # @return [ Integer, View ] Either the max time ms value or a new +View+. # # @since 2.1.0 def max_time_ms(max = nil) configure(:max_time_ms, max) end # The type of cursor to use. Can be :tailable or :tailable_await. # # @example Set the cursor type. # view.cursor_type(:tailable) # # @param [ :tailable, :tailable_await ] type The cursor type. # # @return [ :tailable, :tailable_await, View ] Either the cursor type setting or a new +View+. # # @since 2.3.0 def cursor_type(type = nil) configure(:cursor_type, type) end # @api private def read_concern if options[:session] && options[:session].in_transaction? options[:session].send(:txn_read_concern) || collection.client.read_concern else collection.read_concern end end # @api private def read_preference @read_preference ||= begin # Operation read preference is always respected, and has the # highest priority. If we are in a transaction, we look at # transaction read preference and default to client, ignoring # collection read preference. If we are not in transaction we # look at collection read preference which defaults to client. rp = if options[:read] options[:read] elsif options[:session] && options[:session].in_transaction? options[:session].txn_read_preference || collection.client.read_preference else collection.read_preference end Lint.validate_underscore_read_preference(rp) rp end end private def collation(doc = nil) configure(:collation, doc) end def server_selector @server_selector ||= if options[:session] && options[:session].in_transaction? ServerSelector.get(read_preference || client.server_selector) else ServerSelector.get(read_preference || collection.server_selector) end end def parallel_scan(cursor_count, options = {}) if options[:session] # The session would be overwritten by the one in +options+ later. session = client.send(:get_session, @options) else session = nil end server = server_selector.select_server(cluster, nil, session) spec = { coll_name: collection.name, db_name: database.name, cursor_count: cursor_count, read_concern: read_concern, session: session, }.update(options) session = spec[:session] op = Operation::ParallelScan.new(spec) # Note that the context object shouldn't be reused for subsequent # GetMore operations. context = Operation::Context.new(client: client, session: session) result = op.execute(server, context: context) result.cursor_ids.map do |cursor_id| spec = { cursor_id: cursor_id, coll_name: collection.name, db_name: database.name, session: session, batch_size: batch_size, to_return: 0, # max_time_ms is not being passed here, I assume intentionally? } op = Operation::GetMore.new(spec) context = Operation::Context.new( client: client, session: session, connection_global_id: result.connection_global_id, ) result = op.execute(server, context: context) Cursor.new(self, result, server, session: session) end end def validate_doc!(doc) raise Error::InvalidDocument.new unless doc.respond_to?(:keys) end end end end end
class LibYaml < FPM::Cookery::Recipe description 'Lib Yaml for ruby 1.9' name 'libyaml' version '0.1.4' revision '1' homepage 'http://pyyaml.org/wiki/LibYAML' source 'http://pyyaml.org/download/libyaml/yaml-0.1.4.tar.gz' sha256 '7bf81554ae5ab2d9b6977da398ea789722e0db75b86bffdaeb4e66d961de6a37' arch 'x86_64' section 'libs' build_depends 'rpmdevtools' def build configure :prefix => '/usr/local' make "jobs" => 4 end def install make :install, 'DESTDIR' => destdir end end
require 'mina/multistage' require 'mina/bundler' require 'mina/rails' require 'mina/git' require 'mina/rvm' require 'mina/whenever' require 'mina/appsignal' set :term_mode, nil set :rvm_path, '/home/deploy/.rvm/scripts/rvm' # Manually create these paths in shared/ (eg: shared/config/database.yml) in your server. # They will be linked in the 'deploy:link_shared_paths' step. set :shared_paths, %w(config/application.yml config/database.yml config/secrets.yml log config/unicorn.rb public/uploads unicorn_shared) set :domain, 'mark-1.snappler.com' set :user, 'deploy' set :repository, 'git@gitlab.snappler.com:snappler/jobbier.git' set :unicorn_file, "unicorn_jobbier_#{rails_env}.service" set :whenever_name, "jobbier_#{rails_env}" set :appsignal_api_key, '6fd70522-cf88-4a9e-8e71-804a1d07282a' set :appsignal_app_name, 'Jobbier' # Optional settings: # set :port, '30000' # SSH port number. # set :forward_agent, true # SSH forward_agent. # This task is the environment that is loaded for most commands, such as # `mina deploy` or `mina rake`. task :environment do invoke :'rvm:use[ruby-2.3.0@jobbier]' end # Put any custom mkdir's in here for when `mina setup` is ran. # For Rails apps, we'll make some of the shared paths that are shared between # all releases. task setup: :environment do queue! %[mkdir -p "#{deploy_to}/shared/public/uploads"] queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/public/uploads"] queue! %[mkdir -p "#{deploy_to}/#{shared_path}/log"] queue! %[chmod g+rx,u+rwx "#{deploy_to}/#{shared_path}/log"] queue! %[mkdir -p "#{deploy_to}/#{shared_path}/unicorn_shared"] queue! %[mkdir -p "#{deploy_to}/#{shared_path}/unicorn_shared/pids"] queue! %[mkdir -p "#{deploy_to}/#{shared_path}/unicorn_shared/sockets"] queue! %[mkdir -p "#{deploy_to}/#{shared_path}/unicorn_shared/log"] queue! %[chmod g+rx,u+rwx "#{deploy_to}/#{shared_path}/unicorn_shared"] queue! %[mkdir -p "#{deploy_to}/#{shared_path}/config"] queue! %[chmod g+rx,u+rwx "#{deploy_to}/#{shared_path}/config"] queue! %[touch "#{deploy_to}/#{shared_path}/config/application.yml"] queue! %[touch "#{deploy_to}/#{shared_path}/config/database.yml"] queue! %[touch "#{deploy_to}/#{shared_path}/config/secrets.yml"] queue! %[touch "#{deploy_to}/#{shared_path}/config/unicorn.rb"] queue %[echo "-----> Be sure to edit '#{deploy_to}/#{shared_path}/config/database.yml', 'secrets.yml' and 'unicorn.rb'"] # queue %[ # repo_host=`echo $repo | sed -e 's/.*@//g' -e 's/:.*//g'` && # repo_port=`echo $repo | grep -o ':[0-9]*' | sed -e 's/://g'` && # if [ -z "${repo_port}" ]; then repo_port=22; fi && # ssh-keyscan -p $repo_port -H $repo_host >> ~/.ssh/known_hosts # ] end desc 'Deploys the current version to the server.' task deploy: :environment do to :before_hook do # Put things to run locally before ssh end deploy do # Put things that will set up an empty directory into a fully set-up # instance of your project. invoke :'git:clone' invoke :'deploy:link_shared_paths' invoke :'bundle:install' invoke :'rails:db_create' #Esta linea se puede remover despues del primer deploy exitoso invoke :'rails:db_migrate:force' invoke :'rails:assets_precompile' invoke :'deploy:cleanup' to :launch do queue! 'echo "-----> Unicorn Restart"' invoke :'unicorn:restart' invoke :'whenever:update' if rails_env == 'production' invoke :'appsignal:notify' end end end namespace :nginx do desc 'Reiniciar el servidor nginx' task :restart do queue 'sudo service nginx restart' end end namespace :unicorn do desc 'Iniciar la applicaion unicorn - con environment' task :start do queue "sudo systemctl start #{unicorn_file}" end desc 'Frena la applicaion unicorn - con environment' task :stop do queue "sudo systemctl stop #{unicorn_file}" end desc 'Reinicia la applicaion unicorn - con environment' task :restart do queue "sudo systemctl restart #{unicorn_file}" end end namespace :figaro do # desc 'Envia el archivo config/application.yml al servidor' # task :upload do # %x[scp config/application.yml #{user}@#{domain}:#{dump_file}.gz .] # end desc 'Muestra el contenido del archivo config/application.yml en el servidor' task :show do queue "cat #{deploy_to}/#{shared_path}/config/application.yml" end end namespace :log do desc 'Muestra logs del servidor' task :server do queue "tail -f #{deploy_to}/#{shared_path}/log/nginx.* #{deploy_to}/#{shared_path}/unicorn_shared/log/unicorn.stderr.log" end desc 'Muestra logs de la aplicacion' task :app do queue "tail -f #{deploy_to}/#{shared_path}/log/#{rails_env}.log" end end namespace :db do desc 'DB production to staging' task :prod_to_staging do prod_db = 'jobbier_production' staging_db = 'jobbier_staging' mysql_usr = 'root' mysql_pwd = 'mysql.pass' queue "export MYSQL_PWD=#{mysql_pwd}" mysql_parameters = " -u #{mysql_usr} " mysql_command = "mysql #{mysql_parameters} " mysql_exec_command = "mysql #{mysql_parameters} -s -N -e " mysqldump_command = "mysqldump #{mysql_parameters} " puts "Dump de la base #{prod_db}" queue "#{mysqldump_command} #{prod_db} > /tmp/#{prod_db}.sql" puts "Borrando base: #{staging_db}" base = capture %Q[#{mysql_exec_command} "show databases like '#{staging_db}';"] if base.each_line.count == 1 queue %Q[#{mysql_exec_command} "drop database #{staging_db};"] end puts "Creando base: #{staging_db}" queue %Q[#{mysql_exec_command} "create database #{staging_db};"] puts "Load de #{staging_db}" queue "#{mysql_command} #{staging_db} < /tmp/#{prod_db}.sql" queue "rm /tmp/#{prod_db}.sql" end task :clone do database = "jobbier_#{rails_env}" dump_file = "/tmp/#{database}.sql" # DUMP EN EL SERVIDOR isolate do queue 'export MYSQL_PWD=dumper.pass' queue "mysqldump -u dumper #{database} > #{dump_file}" queue "gzip -f #{dump_file}" mina_cleanup! end # LOCAL %x[scp #{user}@#{domain}:#{dump_file}.gz .] %x[gunzip -f #{database}.sql.gz] %x[RAILS_ENV=development bundle exec rake db:drop db:create] %x[mysql -u root -p jobbier_development < #{database}.sql] %x[rm #{database}.sql] end end namespace :assets do task :clone do %x[mkdir -p public/uploads] %x[rsync -azP --delete #{user}@#{domain}:#{deploy_to}/#{shared_path}/public/uploads/ public/uploads] end end
require 'rails_helper' feature "visiting the clients homepage" do scenario "Client can navigate to log in" do visit "/" within("body") do click_link("Login") end expect(page).to have_current_path new_client_session_path end scenario "Client can navigate to register" do visit "/" within("body") do click_link("Register") end expect(page).to have_current_path new_client_registration_path end end
class Agreement < ApplicationRecord belongs_to :owner, polymorphic: true belongs_to :company end
# # A plant's growth progresses from 0-15. # Root health is expressed in 0-4. # # The simulator works like this: # 1) Plant health is controlled by Nitrogen, Potassium, and Water levels. # 2) Root health is controlled by Phosphorus levels. # 3) Nitrogen, Potassium, Phosphorus, and Water all have different half-lifes # which control the rate that each nutrient dissipates from the environment. # 4) Light does not dissipate and is modeled more simply than the other # nutrients; it only needs to be between the minimum and maximum values # for them plant. If there is an unacceptable level of light, the plant # will not grow. # 5) Plants have an ideal level of Nitrogen, Potassium, Phosphorus, and # Water levels, on a scale of 0-100. Each plant has what is effectively # a "fussiness factor" that is controlled by a min_health_for_growth and # a max_health_for_death. For roots, if the phosphorus level is between # the min and max percentage from ideal, the roots will grow. For the plant, # the nitrogen, potassium, and water level's difference from ideal is # summed, i.e. the percentage variance from ideal for all three has to be # within the min/max of the plant tolerance to grow. # # You should be able to test this thing without ActiveRecord if you instantiate # it directly and call the grow instance method. If you want to construct one # of these from an ActiveRecord object (which is probably what you'll want # to do most of the time), you can do so using the grow class method. # # The grow instance method returns a hash that describes the overall health of # the plant as well as the accumulated nutrient levels. # class GreenhouseService # Simulation parameters NUTRIENT_MAX = 100.0 HALF_LIFE = { nitrogen: 1.0, potassium: 2.0, phosphorus: 3.0, water: 0.5 } def self.grow(plant, new_nutrients) # After calling this, we aren't depending on ActiveRecord anymore. plant_attributes = plant.attributes turns_attributes = plant.turns.order(:id).map(&:attributes) new(plant_attributes, turns_attributes, plant.sim_params[plant.plant_type.to_sym], new_nutrients).grow end def initialize(plant, turns, sim_params, turn_params) @plant = plant @turns = turns @sim_params = OpenStruct.new(sim_params) @nitrogen = turn_params[:nitrogen].to_f @phosphorus = turn_params[:phosphorus].to_f @potassium = turn_params[:potassium].to_f @water = turn_params[:water].to_f @light = turn_params[:light].to_i end def grow { plant: { plant_health: new_plant_health, root_health: new_root_health, height: new_height, depth: new_depth }, turn: { accum_nitrogen: new_nutrient_level(:nitrogen, @nitrogen), accum_phosphorus: new_nutrient_level(:phosphorus, @phosphorus), accum_potassium: new_nutrient_level(:potassium, @potassium), accum_water: new_nutrient_level(:water, @water) } } end private def new_nutrient_level(nutrient, amount_added) result = amount_added @turns.each_with_index do |turn, index| # # The formula for half life is: # # number or turns # | # V # t/h <--- half life # N(t) = N(0)(0.5) # ^ ^ # | | # | Initial Amount # New Amount # # See https://www.wikihow.com/Calculate-Half-Life # turns_ago = @turns.length - index added = turn[nutrient.to_s].to_f remaining = added * (0.5**(turns_ago.to_f / HALF_LIFE[nutrient])) result += remaining end result.clamp(0, NUTRIENT_MAX) end def accumulated_variance_from_ideal(nutrient_name, amount_added, ideal_level) (1.0 - new_nutrient_level(nutrient_name, amount_added) / ideal_level).abs * 100.0 end # Plant health is a function of current water, nitrogen, and potassium levels. # "Health" is a number between 0 and 100. 100 = ideal conditions for growth. def new_plant_health nitrogen = accumulated_variance_from_ideal(:nitrogen, @nitrogen, @sim_params.ideal_n) potassium = accumulated_variance_from_ideal(:potassium, @potassium, @sim_params.ideal_k) water = accumulated_variance_from_ideal(:water, @water, @sim_params.ideal_water) (100.0 - [nitrogen, potassium, water].sum).clamp(0, 100) end # Root health is a function of current phosphorus levels def new_root_health (100.0 - accumulated_variance_from_ideal(:phosphorus, @phosphorus, @sim_params.ideal_p)).clamp(0, 100) end def acceptable_light? @light > @sim_params.min_light && @light < @sim_params.max_light end def new_height result = @plant["height"] return result unless acceptable_light? result += 1 if new_plant_health > @sim_params.min_health_for_growth result -= 1 if new_plant_health < @sim_params.max_health_for_death result.clamp(0, @sim_params.max_height) end def new_depth result = @plant["depth"] result += 1 if new_root_health > @sim_params.min_health_for_growth result -= 1 if new_root_health < @sim_params.max_health_for_death result.clamp(0, @sim_params.max_depth) end end
# # With buffered logs we don't need to log the request_id on every line. # Instead we log it once near the start of the request. # We do this via a Rack middleware to ensure that it's logged even for things # like a `RoutingError` or other exceptional cases. # class BufferingLogger::RailsRackLogRequestId def initialize(app) @app = app end def call(env) request = ActionDispatch::Request.new(env) Rails.logger.info("request_id=#{request.request_id.inspect}") @app.call(env) end end
require 'sinatra/base' require_relative 'helpers/helper' class FakePagseguro < Sinatra::Base post '/pre-approvals/request' do file = nil response_status = nil return_type = :xml req_body = request.body.string tag_name_exist_and_is_empty = (req_body.include?("<name>") && req_body.content_around('<name>', '</name>').empty?) tag_name_not_exist = (!req_body.include?("<name>")) tag_charge_exist_and_is_empty = (req_body.include?("<charge>") && req_body.content_around('<charge>', '</charge>').empty?) tag_charge_not_exist = (!req_body.include?("<charge>")) tag_amount_per_payment_exist_and_is_empty = (req_body.include?("<amountPerPayment>") && req_body.content_around('<amountPerPayment>', '</amountPerPayment>').empty?) tag_amount_per_payment_not_exist = (!req_body.include?("<amountPerPayment>")) if tag_name_exist_and_is_empty || tag_name_not_exist file = 'new_plan_without_name.xml' response_status = 400 elsif tag_charge_exist_and_is_empty || tag_charge_not_exist file = 'new_plan_without_charge.xml' response_status = 400 elsif tag_amount_per_payment_exist_and_is_empty || tag_amount_per_payment_not_exist file = 'new_plan_without_amount_per_payment.xml' response_status = 400 elsif req_body.content_around('<name>', '</name>') == '404' file = '404.html' response_status = 404 return_type = :html elsif req_body.content_around('<name>', '</name>') == '500' file = '500.html' response_status = 500 return_type = :html else file = 'new_plan_success.xml' response_status = 200 end response_request response_status, file, return_type end post '/v2/sessions' do file = nil response_status = 200 return_type = :xml if request.params['email'] == '404' file = '404.html' response_status = 404 return_type = :html elsif request.params['email'] == 'wrong@wrong.com' file = 'new_session_wrong_credentials.xml' response_status = 401 else file = 'new_session_success.xml' end response_request response_status, file, return_type end post '/v2/cards' do file = nil response_status = 200 return_type = :xml if params['sessionId'] != '' && params['cardNumber'] == '404' file = '404.html' response_status = 404 return_type = :html elsif params['sessionId'] != '' && params['cardNumber'] == '5132103426888543' file = 'new_card_token_success.xml' elsif params['sessionId'] != '' && params['cardNumber'].length != 16 file = 'new_card_token_invalid_credit_card_data.xml' else file = 'new_card_token_invalid_session_id.xml' end response_request response_status, file, return_type end get '/df-fe/mvc/creditcard/v1/getBin' do file = nil response_status = 200 return_type = :json if params['creditCard'] == '404' file = '404.html' response_status = 404 return_type = :html elsif params['creditCard'] != '454545' && params['tk'] == '6697c5ddac4f4d20bf310ded7d168175' file = 'get_card_brand_success.json' elsif params['creditCard'] == '454545' && params['tk'] == '6697c5ddac4f4d20bf310ded7d168175' file = 'get_card_brand_wrong_bin.json' else file = 'get_card_brand_invalid_session.json' end response_request response_status, file, return_type end private def response_request(response_code, file_name, return_type = :xml) content_type return_type status response_code File.open(File.dirname(__FILE__) + '/fixtures/' + file_name, 'rb').read end end
class ProductsController < ApplicationController # before_action :move_to_login, only: [:new] before_action :set_product, only: [:show, :destroy, :edit, :update] before_action :move_to_index, only: [:edit] before_action :set_image, only: [:show, :edit] def index @products = Product.where(status: 0) end def new @product = Product.new @product.images.new end def create @product = Product.new(product_params) if @product.save redirect_to products_path else render :new end end def show @images = Image.where(product_id: @product[:id]) @image_first = @images.first @comment = Comment.new @comments = @product.comments.includes(:user) end def edit @category_id = @product.category_id @category_parent = Category.find(@category_id).parent.parent @parent_array = [] @parent_array << @category_parent.name @parent_array << @category_parent.id @category_child = Category.find(@category_id).parent @child_array = [] @child_array << @category_child.name @child_array << @category_child.id @category_grandchild = Category.find(@category_id) @grandchild_array = [] @grandchild_array << @category_grandchild.name @grandchild_array << @category_grandchild.id @category_children_array = Category.where(ancestry: @category_child.ancestry) @category_grandchildren_array = Category.where(ancestry: @category_grandchild.ancestry) end def update if product_params[:images_attributes].nil? flash.now[:alert] = '更新できませんでした。画像を1枚以上入れてください。' render :edit else exit_ids = [] product_params[:images_attributes].each do |a,b| exit_ids << product_params[:images_attributes].dig(:"#{a}",:id).to_i end ids = Image.where(product_id: params[:id]).map{|image| image.id } delete__db = ids - exit_ids Image.where(id:delete__db).destroy_all @product.touch if @product.update(product_params) redirect_to product_path(@product.id) else flash[:alert] = '更新できませんでした' redirect_to edit_product_path(@product.id) end end end def destroy if @product.user_id == current_user.id && @product.destroy redirect_to products_path, method: :get, notice: '商品を削除しました' end end def get_category_children respond_to do |format| format.html format.json do @children = Category.find(params[:parent_id]).children end end end def get_category_grandchildren respond_to do |format| format.html format.json do @grandchildren = Category.find("#{params[:child_id]}").children end end end private def product_params params.require(:product).permit(:name, :description, :brand, :condition_id, :category_id, :delivery_cost_id, :region_id, :preparation_day_id, :price, images_attributes: [:src, :_destroy, :id], categories_attributes: [:category_name]).merge(user_id: current_user.id) end def set_product @product = Product.find(params[:id]) end def set_parents @parents = Category.where(ancestry: nil) end def set_image @images = Image.where(product_id: @product[:id]) @image_first = @images.first end def move_to_index redirect_to action: :index unless user_signed_in? || user_signed_in? && @product.user_id == current_user.id end end
require 'rails_helper' RSpec.describe ListsController, type: :controller do describe "lists#show action" do before :each do @school = FactoryGirl.create(:school) end it "should successfully show report 1" do user = FactoryGirl.create(:user) sign_in user get :show, school_id: @school, id: 1 expect(response).to have_http_status(:success) end it "should successfully show report 2" do user = FactoryGirl.create(:user) sign_in user get :show, school_id: @school, id: 2 expect(response).to have_http_status(:success) end it "should successfully show report 3" do user = FactoryGirl.create(:user) sign_in user get :show, school_id: @school, id: 3 expect(response).to have_http_status(:success) end it "should require users to be logged in" do get :show, school_id: @school, id: 1 expect(response).to redirect_to new_user_session_path end end end
json.array!(@spendings) do |spending| json.extract! spending, :id, :title, :description, :image_url, :price, :transaction_date json.url spending_url(spending, format: :json) end
class Platelet < ApplicationRecord belongs_to :profile validates :erythrocyte, presence: { message: "O nome do campo erythrocyte é obrigatório" }, numericality: { greater_than: 0 } validates :hemoglobin, presence: { message: "O nome do campo hemoglobin é obrigatório" } validates :hematocrit, presence: { message: "O nome do campo hematocrit é obrigatório" } validates :vcm, presence: { message: "O nome do campo vcm é obrigatório" } validates :hcm, presence: { message: "O nome do campo hcm é obrigatório" } validates :chcm, presence: { message: "O nome do campo chcm é obrigatório" } validates :rdw, presence: { message: "O nome do campo rdw é obrigatório" } validates :leukocytep, presence: { message: "O nome do campo leukocytep é obrigatório" } validates :neutrophilp, presence: { message: "O nome do campo neutrophilp é obrigatório" } validates :eosinophilp, presence: { message: "O nome do campo eosinophilp é obrigatório" } validates :basophilp, presence: { message: "O nome do campo basophilp é obrigatório" } validates :lymphocytep, presence: { message: "O nome do campo lymphocytep é obrigatório" } validates :monocytep, presence: { message: "O nome do campo monocytep é obrigatório" } validates :leukocyteul, presence: { message: "O nome do campo leukocyteul é obrigatório" } validates :neutrophilul, presence: { message: "O nome do campo neutrophilul é obrigatório" } validates :eosinophilul, presence: { message: "O nome do campo eosinophilul é obrigatório" } validates :basophilul, presence: { message: "O nome do campo erythrocyte é obrigatório" } validates :lymphocyteul, presence: { message: "O nome do campo lymphocyteul é obrigatório" } validates :monocyteul, presence: { message: "O nome do campo monocyteul é obrigatório" } validates :total, presence: { message: "O nome do campo total é obrigatório" } end
class RemoveTeamDependencyOnFormats < ActiveRecord::Migration[4.2] def change remove_column :teams, :format_id end end
Vagrant.configure("2") do |config| config.vm.define "puppet-master" do |puppet| puppet.vm.box = "bento/centos-7.4" puppet.vm.network "public_network", ip: "192.168.50.4", bridge: "en0: Wi-Fi (AirPort)" puppet.vm.provision "ansible" do |ansible| ansible.playbook = "ansible/puppet-master-deploy.yml" ansible.limit = "all" end puppet.vm.provider "virtualbox" do |vb| vb.name = "puppet-master" vb.memory = 3072 vb.cpus = 2 puppet.vm.hostname = "puppet-master.sysadminonline.net" end end config.vm.define "puppet-agent" do |agent| agent.vm.box = "bento/centos-7.4" agent.vm.network "public_network", ip: "192.168.50.5", bridge: "en0: Wi-Fi (AirPort)" agent.vm.provision "ansible" do |ansible| ansible.playbook = "ansible/puppet-agent-deploy.yml" ansible.limit = "all" end agent.vm.provider "virtualbox" do |vb| vb.name = "puppet-agent" vb.memory = 512 vb.cpus = 2 agent.vm.hostname = "puppet-agent.sysadminonline.net" end end end
class ParksController < ApplicationController def index parks = Park.all.order(:id) render json: parks end def create park = Park.create(park_params) render json: park end def update park = Park.find(params[:id]) park.update(park_params) render json: park end private def park_params params.permit(:name, :image, :votes) end end
name 'mapzen_tilestache' maintainer 'mapzen' maintainer_email 'grant@mapzen.com' license 'All rights reserved' description 'Installs/Configures tilestache' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.11.2' recipe 'mapzen_tilestache', 'Wraps tilestache' %w{ tilestache mapzen_logstash mapzen_sensu_clients}.each do |dep| depends dep end %w{ ubuntu }.each do |os| supports os end
Rails.application.routes.draw do resources :questions mount RailsAdmin::Engine => '/admin', as: 'rails_admin' resources :news root 'main#index' get 'contacts' => 'main#contacts' end
# encoding: utf-8 require 'spec_helper' describe TTY::Table::Header, '#new' do let(:object) { described_class } context 'with no arguments' do subject { object.new } it { is_expected.to be_instance_of(object) } it { is_expected.to be_empty } end context 'with attributes' do subject { object.new(attributes) } let(:attributes) { ['id', 'name', 'age'] } it { is_expected.to be_instance_of(object) } it { is_expected == attributes } end end
class Initiative < ApplicationRecord belongs_to :ong has_many :signs, class_name: 'InitiativeSign' scope :active, -> { where(active: true) } def short_description self.description.truncate(100) end end
class Project < ActiveRecord::Base has_many :tickets, dependent: :destroy validates :name, :description, presence: true end
require 'rails_helper' RSpec.describe Screening, type: :model do let(:html_row) do File.new('spec/fixtures/html_row.html').read end let(:attributes) do { title: 'André - The Voice of Wine', page_url: 'http://www.berlinale.de/en/programm/berlinale_programm/datenblatt.php?film_id=201715159', html_row: html_row } end subject { described_class.new(attributes) } describe '#screening_node' do it 'traverses up then down from an available ticket to find screening info' do expect(subject.screening_node).to_not be_nil end end describe '#update_from_html' do it 'updates various attributes using the raw html' do pending 'Refactor of ScreeningRow into Screening when deserialisation works' expect(subject).to receive(:set_starts_at).once subject.send(:update_from_html) end end describe '#set_starts_at' do let(:expected_starts_at) { '2017-02-16 19:00:00 +0100'.to_time } it 'constructs a datetime with timezone for the ticket row' do pending 'Refactor of ScreeningRow into Screening when deserialisation works' expect(subject.starts_at).to be_nil subject.send(:set_starts_at) expect(subject.starts_at).to eq expected_starts_at end end describe '#save' do it 'calls #update_from_html when html_row is changed' do pending 'Refactor of ScreeningRow into Screening when deserialisation works' subject.save expect(subject).to receive(:update_from_html).once subject.cinema = 'schmoodle' subject.save! subject.html_row = subject.html_row.gsub('first icons', 'second icons') subject.save! end end end
# TERNÁRIO sexo = 'M' sexo == 'M' ? (puts 'Masculino') : (puts 'Feminino') # CASE print 'Digite sua idade: ' idade = gets.chomp.to_i case idade when 0..2 puts "Bebê" when 3..12 puts "Criança" when 13.18 puts "Adolescente" else puts "Adulto" end # UNLESS print 'Digite um número: ' x = gets.chomp.to_i unless x >= 2 puts x.to_s + ' é menor que 2' else puts x.to_s + ' é maior que 2' end # IF print 'Digite um número: ' x = gets.chomp.to_i if x > 2 puts x.to_s + ' é maior que 2' end
# Generated via # `rails generate dog_biscuits:work ExamPaper` class ExamPaper < DogBiscuits::ExamPaper include ::Hyrax::WorkBehavior self.indexer = ::ExamPaperIndexer # Change this to restrict which works can be added as a child. # self.valid_child_concerns = [] validates :title, presence: { message: 'Your work must have a title.' } # This must be included at the end, because it finalizes the metadata # schema (by adding accepts_nested_attributes) # include ::Hyrax::BasicMetadata include DogBiscuits::ExamPaperMetadata before_save :combine_dates end
class CommentsController < ApplicationController include ApplicationHelper def index end def new @comment = Comment.new end def create current_user @memorial = Memorial.find(params[:memorial_id]) if params[:post_id] @post = Post.find(params[:post_id]) @comment = @post.comments.create(comment_params) @comment.update(commenter: @current_user) elsif params[:photo_id] @photo = Photo.find(params[:photo_id]) @comment = @photo.comments.create(comment_params) @comment.update(commenter: @current_user) end redirect_to memorial_path(@memorial) end def show end def edit @comment = Comment.find(params[:id]) end def update @comment = Comment.find(params[:id]) if @comment.update(comment_params) @memorial = Memorial.find(params[:memorial_id]) redirect_to memorial_path(@memorial) else render 'edit' end end def destroy @comment = Comment.find(params[:id]) @comment.destroy @memorial = Memorial.find(params[:memorial_id]) redirect_to memorial_path(@memorial) end private def comment_params params.require(:comment).permit(:commenter, :commentable, :text) end end
# -*- mode: ruby -*- # vi: set ft=ruby : # Vagrantfile API/syntax version. Don't touch unless you know what you're doing! VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "precise64" config.vm.box_url = "http://files.vagrantup.com/precise64.box" config.vm.provision "ansible" do |ansible| ansible.verbose = 'vvvv' ansible.playbook = 'bootstrap.yml' ansible.host_key_checking = false ansible.sudo=true # ansible.extra_vars = 'extra_vars.yml' end config.vm.provider "virtualbox" do |v| v.memory = 8096 end end
class AddColumnToStudents < ActiveRecord::Migration[6.0] def change add_column :students, :grade, :string add_column :students, :help_post, :string add_column :students, :location, :string end end
class CommentsController < ApplicationController http_basic_authenticate_with name: "dhh", password: "secret", only: :destroy #^^only allow authenticated users to delete comments. def create @article = Article.find(params[:article_id]) # ^^chooses which article a comment is going to deal with @comment = @article.comments.create(comment_params) #^^automatically links comment so it belongs to the particular article identified in @article line 3. redirect_to article_path(@article) #^^sends user back to original article using the article_path helper (which calls articles#show, which in turn renders the show.html.erb) end def destroy @article = Article.find(params[:article_id]) @comment = @article.comments.find(params[:id]) @comment.destroy redirect_to article_path(@article) end private def comment_params params.require(:comment).permit(:commenter, :body) end end
class Card attr_reader :rank, :suit, :index def initialize(rank, suit, index) @rank = rank @suit = suit @index = index end end
require 'test_helper' class UserTest < ActiveSupport::TestCase test "no name user" do user = User.new assert_not user.save, "Saved the user without name" end test "save user" do user = User.new user.name = "cosa" assert_not user.save, "User not saved" end test "delete user" do counter_user = User.count user = users(:juan) user.save user.destroy assert counter_user -1 == User.count, "User not deleted" end test "delete nonexistent user" do counter_user = User.count no_user = User.new no_user.destroy assert counter_user == User.count, "User not deleted" end test "update user name" do user = users(:howard) user.name = "new name" user.save assert user.name == "new name" end test "update user email" do user = users(:howard) user.email = "nuevo@mail.com" user.save assert user.email == "nuevo@mail.com" end test "update user birthplace" do user = users(:howard) user.birthplace = "Colama, Colima, México" user.save assert user.birthplace == "Colama, Colima, México" end test "update user birthdate" do user = users(:howard) user.birthdate = 2000-01-01 user.save assert user.birthdate == 2000-01-01 end test "update user institution" do user = users(:howard) user.institution = "CNCI" user.save assert user.institution == "CNCI" end test "update user career" do user = users(:howard) user.career = "Code writter" user.save assert user.career == "Code writter" end test "update user position" do user = users(:howard) user.position = "CEO" user.save assert user.position == "CEO" end test "update user responsibilities" do user = users(:howard) user.responsibilities = "make coffe" user.save assert user.responsibilities == "make coffe" end end
# Fedora allowed? Needs yum and curl to download packages if node[:lxc][:allowed_types].include?('fedora') ['yum', 'curl'].each do |pkg| package pkg end end # OpenSuse allowed? Needs zypper (no package available yet!) # package 'zypper' if node[:lxc][:allowed_types].include?('opensuse') raise 'OpenSuse not currently supported' if node[:lxc][:allowed_types].include?('opensuse') #store a copy of the Omnibus installer for use by the lxc containers if(node[:omnibus_updater] && node[:omnibus_updater][:cache_omnibus_installer]) include_recipe 'omnibus_updater::downloader' end
# frozen_string_literal: true require 'rack/request' require 'forwardable' require 'et_azure_insights/trace_parent' require 'sidekiq/api' module EtAzureInsights module RequestAdapter # A request adapter provides a normalised view of a request no matter where it came from # This adapter normalises a sidekiq job class SidekiqJob # Creates a new instance from the sidekiq job hash # @param [Hash] job_hash The sidekiq job hash # @return [EtAzureInsights::RequestAdapter::SidekiqJob] def self.from_job_hash(job_hash, trace_parent: ::EtAzureInsights::TraceParent) new(job_record_class.new(job_hash), trace_parent: trace_parent) end def self.job_record_class ::Sidekiq.const_defined?('JobRecord') ? ::Sidekiq::JobRecord : ::Sidekiq::Job end # A new instance given a rack request # @param [Rack::Request] request The rack request def initialize(request, trace_parent: ::EtAzureInsights::TraceParent) self.request = request self.trace_parent = trace_parent end def url "sidekiq://#{request.queue}/#{request.klass.split('::').last}#{path}" end def path "/#{request.jid}" end def name @name ||= "#{request_method.to_s.upcase} /#{request.queue}/#{request.klass.split('::').last}#{path}" end def request_method @request_method = :perform end def trace_id parsed_traceparent&.trace_id end def span_id parsed_traceparent&.span_id end def trace_info? !parsed_traceparent.nil? end def request_id SecureRandom.hex(16) end def fetch_header(key, &block) headers.fetch(key, &block) end def get_header(key) headers[key] end def has_header?(key) headers.key?(key) end private attr_accessor :request, :trace_parent def headers return @headers if defined?(@headers) @headers = request['azure_insights_headers'] @headers ||= {} end def parsed_traceparent return @parsed_traceparent if defined?(@parsed_traceparent) @parsed_traceparent = parse_traceparent end def parse_traceparent return unless has_header?('traceparent') header_value = fetch_header('traceparent') trace_parent.parse(header_value) end end end end
class MessagesController < ApplicationController before_filter :require_user # GET /messages # GET /messages.json def book @books=Book.all @book=Book.find(params[:id]) end def index # @message = Message.find(params[:id]) @user=User.find(params[:user_id]) @messages = Message.where("(sender_id = ? AND receiver_id = ?) OR (sender_id = ? AND receiver_id = ?)", current_user.id, @user.id, @user.id, current_user.id) # render :template => '/' #, message_user_path(@message.receiver_id) respond_to do |format| format.html # index.html.erb format.json { render :json => @messages } end end # GET /messages/1 # GET /messages/1.json def show @message = Message.find(params[:id]) @book = Book.find_by_id(:book_id) respond_to do |format| format.html # show.html.erb format.json { render :json => @message } end end # GET /messages/new # GET /messages/new.json def new @message = Message.new if params[:user_id].present? @user = User.find(params[:user_id]) elsif params[:book_id].present? @book = Book.find(params[:book_id]) end respond_to do |format| format.html # new.html.erb format.json { render :json => @message } end end # GET /messages/1/edit def edit @message = Message.find(params[:id]) end # POST /messages # POST /messages.json def create logger.info params[:message].to_yaml @message = Message.new(params[:message]) if @message.save UserMailer.new_message(@message).deliver redirect_to user_messages_path(@message.receiver) else # @messages = Message.where("(sender_id = ? AND receiver_id = ?) OR (sender_id = ? AND receiver_id = ?)", current_user.id, @user.id, @user.id, current_user.id) render :template => user_messages_path(@message.receiver_id) end end # PUT /messages/1 # PUT /messages/1.json def update @message = Message.find(params[:id]) respond_to do |format| if @message.update_attributes(params[:message]) format.html { redirect_to @message, :notice => 'Message was successfully set.' } format.json { head :no_content } else format.html { render :action => "edit" } format.json { render :json => @message.errors, :status => :unprocessable_entity } end end end # DELETE /messages/1 # DELETE /messages/1.json def destroy @message = Message.find(params[:id]) @message.destroy respond_to do |format| format.html { redirect_to messages_url } format.json { head :no_content } end end end
class PartnerCategoriesAlterNameWidth < ActiveRecord::Migration def self.up change_column :partner_categories, :name, :string, {:limit=>256} end def self.down change_column :partner_categories, :name, :string, {:limit=>128} end end
# frozen_string_literal: true source 'https://rubygems.org' gem 'rails', '>= 7.0.0' group :active_record do platforms :jruby do gem 'activerecord-jdbcmysql-adapter', '>= 1.2' gem 'activerecord-jdbcpostgresql-adapter', '>= 1.2' gem 'activerecord-jdbcsqlite3-adapter', '>= 1.2' end platforms :ruby, :mswin, :mingw do gem 'mysql2', '>= 0.3.14' gem 'pg', '>= 0.14' gem 'sqlite3', '>= 1.3.0' end gem 'composite_primary_keys' gem 'paper_trail', '>= 12.0' end gem 'carrierwave', '>= 2.0.0.rc', '< 3.0' gem 'cssbundling-rails' gem 'devise', '>= 3.2' gem 'dragonfly', '~> 1.0' gem 'importmap-rails', require: false gem 'mini_magick', '>= 3.4' gem 'mlb', '>= 0.7', github: 'mshibuya/mlb', branch: 'ruby-3' gem 'paperclip', '>= 3.4' gem 'rails_admin', path: '../../' gem 'shrine', '~> 3.0' gem 'webpacker', require: false gem 'webrick', '~> 1.7' # Gems used only for assets and not required # in production environments by default. group :assets do gem 'sassc-rails', '~> 2.1' # See https://github.com/sstephenson/execjs#readme for more supported runtimes # gem 'therubyracer' gem 'uglifier', '>= 1.3' end
# -*- encoding: utf-8 -*- require 'base64' require 'proton' require 'proton/raw' require 'proton/by_point' require 'proton/ip_port' require 'proton/refresh' require './wrappers/scanner_object' require './wrappers/rps_lock' require './lib/proton2scanner' require './lib/object_helpers' require_relative './baseline_check_job/run_extensions' require_relative './baseline_check_job/policies' require_relative './baseline_check_job/entries' require_relative './baseline_check_job/lock' require_relative './baseline_check_job/vulns' # Job for checking TestRuns class BaselineCheckJob BaselineCheckError = Class.new(RuntimeError) BaselineCheckErrorMissingReq = Class.new(BaselineCheckError) BaselineCheckTestRunIsGone = Class.new(BaselineCheckError) extend RunExtensionsHelper extend PoliciesHelper extend RpsHelper extend Vulns def self.get_serialized_request(job) if job['req'] msg = 'Retrieving the baseline request from job params' App.log(level: :info, msg: msg) Proton::SerializedRequest.new(Base64.decode64(job['req'])) else msg = "Retrieving the baseline request Hit##{job['es_hit_id']}" App.log(level: :info, msg: msg) App.wapi.req_by_es_hit_id(job['es_hit_id']) end end def self.get_connection_params(objects, job) use_ssl = [] objects.each do |object| object.params[:info][:baseline_check_id] = job['baseline_check_id'] object.job = job use_ssl << ObjectHelpers.check_connection(object, true) end use_ssl end def self.handle_last_retry(job, exception) msg = 'Exceeded the number of allowed retries' App.log(level: :error, msg: msg) BaselineCheckAPI.run(id: job['baseline_check_id']) case exception when BaselineCheckErrorMissingReq msg = "Marking test set for baseline ##{job['baseline_check_id']} as incomplete due to missing request data" App.log(level: :error, msg: msg) BaselineCheckAPI.tech_fail( id: job['baseline_check_id'], reason: :missing_req ) else msg = "Marking test set for baseline ##{job['baseline_check_id']} as incomplete due to exception" App.log(level: :error, msg: msg) BaselineCheckAPI.tech_fail( id: job['baseline_check_id'], reason: :exception ) end end def self.perform(job) Thread.current[:baseline_check_id] = job['baseline_check_id'] msg = "Running a test set for the baseline ##{job['baseline_check_id']}" App.log(level: :info, msg: msg) lock = job['fast'] ? get_local_rps_lock(job) : get_cloud_rps_lock(job) # job is retried due to rps lock return if lock == false run(job, lock) rescue ScannerExtensions::Helpers::FuzzerConditions::InvalidPolicies msg = 'Invalid value in a X-Wallarm-Test-Policy header, tests stopped' App.log(level: :error, msg: msg) BaselineCheckAPI.tech_fail( id: job['baseline_check_id'], reason: :invalid_policies ) return rescue BaselineCheckTestRunIsGone => ex App.logger.info(ex.message) rescue => detail App.logger.error(detail) msg = "Internal exception detected, the test set for the baseline ##{job['baseline_check_id']} will be retried" App.log(level: :error, msg: msg) BaselineCheckAPI.retry(id: job['baseline_check_id']) raise detail ensure lock && lock.unlock end def self.run(job, lock) msg = "Test set for the baseline ##{job['baseline_check_id']} is running" App.log(level: :info, msg: msg) BaselineCheckAPI.run(id: job['baseline_check_id']) req = get_serialized_request(job) job.heartbeat unless req msg = 'Cannot retrieve the baseline request' App.log(level: :error, msg: msg) raise BaselineCheckErrorMissingReq end policies = parse_policies(req, job['test_run_id']) all_entries = [] anomalies = nil could_connect = false found_points = false checks = [] policies.each do |policy| # one entry could have many scan objects for different ip/port/use_ssl pairs # so entries is array of arrays of scan objects entries = get_entries(req, policy) entries.each { |entry| entry.each { |object| object.job = job } } job.heartbeat next if entries.empty? found_points = true msg = 'Establishing a connection with the target server' App.log(level: :info, msg: msg) # check connection with auditable server for random entry # all entries has same ip/port/use_ssl order so if we check connection # for one entry then we can use this info for other entries ssl_connection_params = get_connection_params(entries.sample, job) next if ssl_connection_params.flatten.empty? could_connect = true checks << [entries, ssl_connection_params, policy] end total_checks = 0 checks.each do |entries, ssl_connection_params, policy| entries.each do |entry| entry.each_with_index do |object, i| (policy[:type_include] - policy[:type_exclude] + [:custom]).each do |detect_type| ObjectHelpers.get_extensions( detect_type, object.params[:point], :fast ).each do |ext| next if ext.respond_to?(:applicable?) && !ext.applicable?(object) use_ssl = ssl_connection_params[i] use_ssl.each do |ssl| total_checks += 1 end end end end end end BaselineCheckAPI.set_total_checks_count(job['baseline_check_id'], total_checks) checks.each do |entries, ssl_connection_params, policy| cur_anomalies = run_extensions(entries, ssl_connection_params, policy, job, lock) if cur_anomalies anomalies ||= {} anomalies.merge!(cur_anomalies) end all_entries += entries.flatten end reason = nil unless could_connect if found_points msg = "Target application is unreachable. The test set for baseline ##{job['baseline_check_id']} is marked as failed" App.log(level: :error, msg: msg) reason = :connection_failed BaselineCheckAPI.tech_fail(id: job['baseline_check_id'], reason: reason) else msg = "Nothing to test based on Test Policy used. Check Insertion section in Test Policy 'test-policy-name' https://my.wallarm.com/link-to-test-policy" App.log(level: :info, msg: msg) reason = :nothing_to_check BaselineCheckAPI.passed(id: job['baseline_check_id'], reason: reason) end return end handle_result(job, all_entries, anomalies) end def self.handle_result(job, all_entries, anomalies) # for all oob dns detects sleep 1 # process callbacks and handle vulns all_entries.each do |object| job.heartbeat object.vulns.clear begin object.oob_callbacks.each do |callback| callback.call job.heartbeat end rescue => detail App.logger.error(detail) end next if object.vulns.empty? sync_vulns_with_api(object, job) end finish_baseline_check(job, synced_vulns(job), anomalies) end def self.finish_baseline_check(job, vulns, anomalies) if vulns.empty? msg = "No issues found. Test set for baseline ##{job['baseline_check_id']} passed." App.log(level: :info, msg: msg) BaselineCheckAPI.passed(id: job['baseline_check_id']) else msg = "Found #{vulns.size} vulnerabilities, marking the test set for baseline ##{job['baseline_check_id']} as failed" App.log(level: :info, msg: msg) fail_opts = { id: job['baseline_check_id'], vulns: vulns.values } fail_opts[:anomalies] = anomalies if anomalies BaselineCheckAPI.failed(fail_opts) end end end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_and_belongs_to_many :companies def get_name if fName.present? && lName.present? return fName + " " + lName elsif fName.present? return fName elsif lName.present? return lName else return "<a href='/users/#{self.id}/edit'> You're concerned with privacy +1</a>" end end def username if fName.present? && lName.present? return fName + " " + lName else return email[0,email.index('@')] end end end
class CargoTrain < Train validate :number, :presence validate :number, :format, VALUE_FORMAT def attachable_wagon?(wagon) wagon.is_a?(CargoWagon) end def to_s "Поезд № #{number}. Грузовой поезд с #{wagons.size} вагонами" end end
rack_env = ENV['RACK_ENV'] || "production" rack_root = ENV['RACK_ROOT'] || "/var/www/apps/railsrumble/current" num_workers = rack_env == 'production' ? 2 : 1 num_workers.times do |num| God.watch do |w| w.dir = "#{rack_root}" w.name = "resque-#{num}" w.group = 'resque' w.interval = 30.seconds w.env = {"QUEUE"=>"*", "RACK_ENV"=>rack_env} w.start = "bundle exec rake -f #{rack_root}/Rakefile resque:work" w.uid = ENV['RESQUE_USER'] || 'www-data' w.gid = ENV['RESQUE_GROUP'] || 'www-data' # restart if memory gets too high w.transition(:up, :restart) do |on| on.condition(:memory_usage) do |c| c.above = 350.megabytes c.times = 2 end end # determine the state on startup w.transition(:init, { true => :up, false => :start }) do |on| on.condition(:process_running) do |c| c.running = true end end # determine when process has finished starting w.transition([:start, :restart], :up) do |on| on.condition(:process_running) do |c| c.running = true c.interval = 5.seconds end # failsafe on.condition(:tries) do |c| c.times = 5 c.transition = :start c.interval = 5.seconds end end # start if process is not running w.transition(:up, :start) do |on| on.condition(:process_running) do |c| c.running = false end end end end
# == Schema Information # # Table name: clientes # # created_at :datetime not null # id :bigint(8) not null, primary key # nombre :string default(""), not null # updated_at :datetime not null # require "net/http" require "open-uri" # require "net/http/post/multi+part" class ClientesController < ApplicationController before_action :set_cliente, only: %i[show edit update destroy] # GET /clientes def index @clientes = Cliente.all @user = current_user.id app_secret = "c7166257539efd50cf8f523de38618cd" app_id = "979922088853971" # @oauth = Koala::Facebook::OAuth.new(app_id, app_secret, 'https://127.0.0.1:3000') # @urlforauth = @oauth.url_for_oauth_code(permissions: "publish_actions") # redirect_to(@oauth.url_for_oauth_code) # @user = User.find(2).email # @test_result = post_test end # GET /clientes/1 def show # @redes = @cliente.redes end # GET /clientes/new def new @cliente = Cliente.new end # GET /clientes/1/edit def edit end # POST /clientes def create @cliente = Cliente.new(cliente_params) @cliente.logo.attach(cliente_params['logo']) if @cliente.save redirect_to @cliente, notice: "Cliente fue creado satisfactoriamente." else render :new end end # PATCH/PUT /clientes/1 def update if @cliente.update(cliente_params) redirect_to @cliente, notice: "Cliente fue guardado satisfactoriamente." else render :edit end end # DELETE /clientes/1 def destroy @cliente.destroy redirect_to clientes_url, notice: "Cliente fue eliminado satisfactoriamente." end private # Use callbacks to share common setup or constraints between actions. def set_cliente @cliente = Cliente.find(params[:id]) end # Only allow a trusted parameter "white list" through. def cliente_params params.require(:cliente).permit(:nombre, :logo) end end
class TravelPlan < TravelPlan.superclass module Cell # Overview of the entire travel plan, displaying as much data as possible # in a small area. # # At the time of writing, this cell is used on: # # - admin/people#show # - accounts#dashboard # - travel_plans#index # # @!method self.call(model, opts = {}) # @param model [TravelPlan] # @option opts [String] well (true) when true, the outermost `<div`> in # the rendered HTML will have the CSS class `well`. class Summary < Abroaders::Cell::Base include Escaped property :id property :further_information property :one_way? property :type option :current_admin, optional: true alias current_admin? current_admin def self.flight_summary_cell Flight::Cell::Summary end private def acceptable_classes cell AcceptableClasses, model end def dates cell Dates, model end # See comment in TravelPlan::Edit about old-style TPs being uneditable. def editable? !current_admin? && model.editable? end def flight model.flights[0] end def flight_summary cell(self.class.flight_summary_cell, flight) end def html_classes "travel_plan #{'well' if options.fetch(:well, true)}" end def further_information "Notes: #{super}" if super.present? end def link_to_destroy link_to( 'Delete', travel_plan_path(id), class: 'btn btn-primary btn-xs', method: :delete, data: { confirm: 'Are you sure? You cannot undo this action', }, ) end def link_to_edit link_to( 'Edit', edit_travel_plan_path(id), class: 'btn btn-primary btn-xs', ) end def no_of_passengers content_tag :span, class: 'travel_plan_no_of_passengers' do "#{fa_icon('male')} &times; #{model.no_of_passengers}" end end def type one_way? ? 'One-way' : 'Round trip' end # A <span>: 'Departure: MM/DD/YYYY Return: MM/DD/YYYY' class Dates < Abroaders::Cell::Base property :depart_on property :return_on property :round_trip? property :type private %w[depart_on return_on].each do |date| define_method date do super().strftime('%D') end end # some legacy TPs have type 'round_trip' but no return_on date: def return_date? round_trip? && !model.return_on.nil? end end end end end
require 'spec_helper' describe User do it { should have_many(:forecasts) } describe "attributes" do it { should respond_to(:email) } it { should respond_to(:uid) } it { should respond_to(:provider) } it { should respond_to(:sign_in_count) } it { should respond_to(:last_sign_in_at) } it { should respond_to(:teams) } it { should allow_mass_assignment_of(:email) } it { should allow_mass_assignment_of(:uid) } it { should allow_mass_assignment_of(:provider) } it { should allow_mass_assignment_of(:sign_in_count) } it { should allow_mass_assignment_of(:last_sign_in_at) } it { should allow_mass_assignment_of(:teams) } it "should instantiate PROVIDERS" do User::PROVIDERS.should_not be_nil User::PROVIDERS.length.should be(1) User::PROVIDERS.first.should eq "facebook" end it "PROVIDERS should be frozen" do assert_raise(RuntimeError) { User::PROVIDERS.delete(User::PROVIDERS.sample) } end it "should serialize teams as an Array" do user = User.new user.teams.should be_an(Array) end end end
# We want to keep track of all babies that are born # 1. where can we do that? - initialize # 2. whose responsibility? - class # 3. where to put data - initialize class Baby @@all_babies = [] attr_accessor :name def initialize(name=nil) cry @name = name # save the baby somewhere @@all_babies << self end def cry puts "Wah!" end end
def bucket_sort(arr, bucket_size = 5) if arr.empty? || arr.length == 1 return arr end # determine minimum and maximum values min = arr.min max = arr.max # calculate number of buckets needed, create array of buckets bucket_count = ((max - min) / bucket_size).ceil + 1 buckets = Array.new(bucket_count) (0..buckets.length - 1).each do |i| buckets[i] = [] end # put array values into buckets (0..arr.length - 1).each do |i| buckets[((arr[i] - min) / bucket_size).floor].push(arr[i]) end # Sort buckets and place back into input array arr = [] (0..buckets.length - 1).each do |i| buckets[i] = insertion_sort(buckets[i]) buckets[i].each do |value| arr.push(value) end end arr end def insertion_sort(collection) sorted_array = [collection.delete_at(0)] until collection.length == 0 insert_value = collection.shift i = 0 until i == sorted_array.length || insert_value < sorted_array[i] i += 1 end sorted_array.insert(i, insert_value) end sorted_array end arr = [3, 6, 1, 2, 8, 4, 9, 7, 5] puts "#{bucket_sort(arr)}"
# -*- mode: ruby -*- # vi: set ft=ruby : # Vagrantfile API/syntax version. Don't touch unless you know what you're doing! VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "centos-65-x64" config.vm.box_url = "http://puppet-vagrant-boxes.puppetlabs.com/centos-65-x64-virtualbox-puppet.box" config.vm.network :private_network, ip: "192.168.33.10" config.vm.synced_folder ".", "/vagrant", disabled: true config.vm.synced_folder ".", "/vagrant/code" # make symlinks work in shared /vagrant folder # will require the machine to run with admin previleges config.vm.provider :virtualbox do |vb| vb.customize ["setextradata", :id, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/vagrant-root", "1"] vb.customize ["modifyvm", :id, "--memory", 1024] end # fix for internet not working in vm issue config.vm.provision :shell, :inline => "sudo cp -f /vagrant/code/puppet/conf/resolv.conf /etc/resolv.conf" #inline shell stuff # turnoff firewall config.vm.provision :shell, :inline => "sudo /etc/init.d/iptables save" config.vm.provision :shell, :inline => "sudo /etc/init.d/iptables stop" # turnoff firewall on boot config.vm.provision :shell, :inline => "sudo chkconfig iptables off" # installing puppet modules # puppet module install puppetlabs/mysql --force --modulepath '/vagrant/code/puppet/modules' config.vm.provision :puppet do |puppet| puppet.manifests_path = "puppet/manifests" puppet.manifest_file = "init.pp" puppet.module_path = "puppet/modules" end config.vm.provision :shell, :path => "puppet/scripts/python.sh" config.vm.provision :shell, :path => "puppet/scripts/virtualenv.sh" end
require 'data_mapper' class Peep include DataMapper::Resource property :id, Serial property :content, String, :lazy => false property :created_at, DateTime belongs_to :user def time created_at.strftime("%H:%M:%S - %d/%m/%y") end end
class CabStatus < ApplicationRecord belongs_to :cab def update_status self.update_column( :available, !self.available) end #Update cab availabe loacton after ride def update_location(latitude, longitude) self.update_columns(latitude: latitude, longitude: longitude) end end
class Playlist < ActiveRecord::Base has_and_belongs_to_many :songs validates :name, presence: true validates :name, uniqueness: true #TODO check these figure out how these work def add_song(song) self.songs.push(song) unless self.songs.include?(song) end #TODO this to class methods def remove_song(song) self.songs.destroy(song) if self.songs.include?(song) end end
class TableImages < ActiveRecord::Migration[5.2] def change create_table :images add_column :images, :name, :string end end
class AddPriceToLineItem < ActiveRecord::Migration def change add_column :line_items, :price, :decimal,precision: 8, scale: 2 end end
class ConabioController < ApplicationController #before_filter :return_here, :only => [:options] before_filter :authenticate_usuario! # Return a HTML fragment containing checkbox inputs for CONABIO photos. # Params: # taxon_id: a taxon_id # q: a search param def photo_fields @photos = [] if params[:taxon_id].present? @taxon = Especie.find(params[:taxon_id]) if @taxon.nombre_cientifico != params[:q] @taxon = Especie.where(:nombre_cientifico => params[:q]).first end end per_page = params[:limit].to_i per_page = 36 if per_page.blank? || per_page.to_i > 36 page = params[:page].to_i page = 1 if page == 0 offset = per_page*(page-1)+(page-1) limit = if offset > per_page 75 else per_page end @photos = ConabioPhoto::search_conabio(@taxon) if @taxon @photos = @photos[offset,per_page] partial = params[:partial].to_s partial = 'photo_list_form' unless %w(photo_list_form bootstrap_photo_list_form).include?(partial) render :partial => "photos/#{partial}", :locals => { :photos => @photos, :index => params[:index], :local_photos => false } end end
TransisAuth::Application.routes.draw do mount Oauth2Provider::Engine, at: 'oauth' resources :users resources :user_sessions match '/logout', :to => 'user_sessions#destroy', :as => :logout root :to => 'home#home' end
#Example to demonstrate the concept of class in Ruby =begin CLASS SYNTAX: class className functions are defined in body of class end =end class ExampleClass def func1(arg) puts "func1 is invoked by obj#{arg}" end def func2(arg) puts "func2 is invoked by obj#{arg}" end end #creation of new object of ExampleClass obj1 = ExampleClass.new obj2 = ExampleClass.new #invocation of functions obj1.func1(1) obj1.func2(1) obj2.func1(2) obj2.func2(2)
require "csv" class PatientsExporter include QuarterHelper BATCH_SIZE = 20 BLOOD_SUGAR_TYPES = { random: "Random", post_prandial: "Postprandial", fasting: "Fasting", hba1c: "HbA1c" }.with_indifferent_access.freeze def self.csv(*args) new.csv(*args) end def csv(patients) CSV.generate(headers: true) do |csv| csv << timestamp csv << csv_headers patients.in_batches(of: BATCH_SIZE).each do |batch| batch.includes( :registration_facility, :assigned_facility, :phone_numbers, :address, :medical_history, :current_prescription_drugs ).each do |patient| csv << csv_fields(patient) end end end end def timestamp [ "Report generated at:", Time.current ] end def csv_headers [ "Registration Date", "Registration Quarter", "Patient died?", "Patient Name", "Patient Age", "Patient Gender", "Patient Phone Number", "Patient Street Address", "Patient Village/Colony", "Patient District", (zone_column if Rails.application.config.country[:patient_line_list_show_zone]), "Patient State", "Preferred Facility Name", "Preferred Facility Type", "Preferred Facility District", "Preferred Facility State", "Registration Facility Name", "Registration Facility Type", "Registration Facility District", "Registration Facility State", "Diagnosed with Hypertension", "Diagnosed with Diabetes", "Latest BP Date", "Latest BP Systolic", "Latest BP Diastolic", "Latest BP Quarter", "Latest BP Facility Name", "Latest BP Facility Type", "Latest BP Facility District", "Latest BP Facility State", "Latest Blood Sugar Date", "Latest Blood Sugar Value", "Latest Blood Sugar Type", "Follow-up Facility", "Follow-up Date", "Days Overdue", "Risk Level", "BP Passport ID", "Simple Patient ID", "Medication 1", "Dosage 1", "Medication 2", "Dosage 2", "Medication 3", "Dosage 3", "Medication 4", "Dosage 4", "Medication 5", "Dosage 5" ].compact end def csv_fields(patient) # We cannot rely on the ordered scopes on Patient (eg. latest_blood_pressures) to find most recent records because # the batching done here will invalidate any ordering on patients, as well as its associations. registration_facility = patient.registration_facility assigned_facility = patient.assigned_facility latest_bp = patient.blood_pressures.order(recorded_at: :desc).first latest_bp_facility = latest_bp&.facility latest_blood_sugar = patient.blood_sugars.order(recorded_at: :desc).first latest_appointment = patient.latest_scheduled_appointments.order(scheduled_date: :desc).first latest_bp_passport = patient.latest_bp_passports.order(device_created_at: :desc).first zone_column_index = csv_headers.index(zone_column) csv_fields = [ patient.recorded_at.presence && I18n.l(patient.recorded_at), patient.recorded_at.presence && quarter_string(patient.recorded_at), ("Died" if patient.status == "dead"), patient.full_name, patient.current_age, patient.gender.capitalize, patient.phone_numbers.last&.number, patient.address.street_address, patient.address.village_or_colony, patient.address.district, patient.address.state, assigned_facility&.name, assigned_facility&.facility_type, assigned_facility&.district, assigned_facility&.state, registration_facility&.name, registration_facility&.facility_type, registration_facility&.district, registration_facility&.state, patient.medical_history&.hypertension, patient.medical_history&.diabetes, latest_bp&.recorded_at.presence && I18n.l(latest_bp&.recorded_at), latest_bp&.systolic, latest_bp&.diastolic, latest_bp&.recorded_at.presence && quarter_string(latest_bp&.recorded_at), latest_bp_facility&.name, latest_bp_facility&.facility_type, latest_bp_facility&.district, latest_bp_facility&.state, latest_blood_sugar&.recorded_at.presence && I18n.l(latest_blood_sugar&.recorded_at), latest_blood_sugar&.to_s, blood_sugar_type(latest_blood_sugar), latest_appointment&.facility&.name, latest_appointment&.scheduled_date&.to_s(:rfc822), latest_appointment&.days_overdue, ("High" if patient.high_risk?), latest_bp_passport&.shortcode, patient.id, *medications_for(patient) ] csv_fields.insert(zone_column_index, patient.address.zone) if zone_column_index csv_fields end def medications_for(patient) patient.current_prescription_drugs.flat_map { |drug| [drug.name, drug.dosage] } end private_class_method def zone_column "Patient #{Address.human_attribute_name :zone}" end def blood_sugar_type(blood_sugar) return unless blood_sugar.present? BLOOD_SUGAR_TYPES[blood_sugar.blood_sugar_type] end end
class Person def initialize("first_name", "last_name") @first_name = first_name @last_name = last_name end #READER def first_name return @first_name end def last_name return @last_name end #WRITTER # def set_first_name(new_first_name) # @first_name = new_first_name # end def first_name=(first_name) @first_name = first_name end def full_name return "#{@first_name} #{@last_name}" end end
class Favorite < ApplicationRecord belongs_to :task belongs_to :label validates_uniqueness_of :task_id, scope: :label_id scope :between, -> (task_id,label_id) do where("(favorites.task_id = ? AND favorites.label_id =?) OR (favorites.task_id = ? AND favorites.label_id =?)", task_id,label_id, label_id, task_id) end end
class Machine class EndStop attr_accessor :triggered attr_reader :x, :y, :axis def initialize(machine:, x:, y:, axis:, size: 10, color: nil, triggered_color: nil) @machine = machine @x, @y = x, y @axis = axis @size = size @triggered = false if color.nil? && triggered_color.nil? color_from_axis(@axis) else @color, @triggered_color = color, triggered_color end end def color_from_axis(axis) if axis == :x @color = Gosu::Color.rgba(200, 0, 0, 100) @triggered_color = Gosu::Color.rgba(200, 0, 0, 200) elsif axis == :y @color = Gosu::Color.rgba(0, 200, 0, 100) @triggered_color = Gosu::Color.rgba(0, 200, 0, 200) else raise "Unknown Axis" end end def draw if @triggered Gosu.draw_rect(@x, @y, @size, @size, @triggered_color, 100) else Gosu.draw_rect(@x, @y, @size, @size, @color, 100) end end end end
# This file is a part of Redmine Products (redmine_products) plugin, # customer relationship management plugin for Redmine # # Copyright (C) 2011-2016 Kirill Bezrukov # http://www.redminecrm.com/ # # redmine_products is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # redmine_products is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with redmine_products. If not, see <http://www.gnu.org/licenses/>. class Product < ActiveRecord::Base unloadable include Redmine::SafeAttributes attr_accessible :code, :name, :project_id, :status_id, :currency, :price, :tag_list, :custom_fields, :category_id, :description, :custom_field_values belongs_to :project belongs_to :author, :class_name => "User", :foreign_key => "author_id" belongs_to :category, :class_name => "ProductCategory" if ActiveRecord::VERSION::MAJOR >= 4 has_one :image, lambda { where("#{Attachment.table_name}.description = 'default_image'") }, { :class_name => "Attachment", :as => :container, :dependent => :destroy } else has_one :image, :conditions => "#{Attachment.table_name}.description = 'default_image'", :class_name => "Attachment", :as => :container, :dependent => :destroy end has_many :product_lines has_many :orders, :through => :product_lines, :source_type => "Order", :source => :container, :uniq => true has_many :contacts, :through => :orders, :uniq => true has_many :products_bundles has_many :products, :through => :products_bundles, :class_name => "Product", :foreign_key => 'product_id', :dependent => :delete_all has_many :bundles, :through => :products_bundles, :foreign_key => 'bundle_id', :dependent => :delete_all scope :by_project, lambda {|project_id| where(:project_id => project_id) unless project_id.blank? } scope :visible, lambda {|*args| joins(:project). where(Project.allowed_to_condition(args.first || User.current, :view_products)) } scope :live_search, lambda {|search| where("(LOWER(#{Product.table_name}.name) LIKE LOWER(:p)) OR (LOWER(#{Product.table_name}.code) LIKE LOWER(:p)) OR (LOWER(#{Product.table_name}.description) LIKE LOWER(:p))", {:p => "%#{search.downcase}%"}) } acts_as_event :datetime => :created_at, :url => Proc.new {|o| {:controller => 'products', :action => 'show', :id => o}}, :type => 'icon-product', :title => Proc.new {|o| "#{l(:label_products_product_created)} #{o.name} - #{o.price.to_s}" }, :description => Proc.new {|o| [o.description.to_s, o.price.to_s].join(' ') } if ActiveRecord::VERSION::MAJOR >= 4 acts_as_activity_provider :type => 'products', :permission => :view_products, :timestamp => "#{table_name}.created_at", :author_key => :author_id, :scope => joins(:project) acts_as_searchable :columns => ["#{table_name}.name", "#{table_name}.description"], :project_key => "#{Project.table_name}.id", :scope => includes([:project]), :permission => :view_products, :date_column => "created_at" else acts_as_activity_provider :type => 'products', :permission => :view_products, :timestamp => "#{table_name}.created_at", :author_key => :author_id, :find_options => {:include => :project} acts_as_searchable :columns => ["#{table_name}.name", "#{table_name}.description"], :date_column => "#{table_name}.created_at", :include => [:project], :project_key => "#{Project.table_name}.id", :permission => :view_products, # sort by id so that limited eager loading doesn't break with postgresql :order_column => "#{table_name}.name" end acts_as_attachable rcrm_acts_as_taggable acts_as_priceable ACTIVE_PRODUCT = 1 INACTIVE_PRODUCT = 2 validates_presence_of :name, :status_id validates_uniqueness_of :code, :allow_nil => true validates_numericality_of :price, :allow_nil => true validates_inclusion_of :status_id, :in => [ACTIVE_PRODUCT, INACTIVE_PRODUCT] attr_protected :id safe_attributes 'code', 'name', 'status_id', 'category_id', 'currency', 'price', 'amount', 'description', 'custom_field_values', 'custom_fields', 'tag_list', :if => lambda {|product, user| product.new_record? || user.allowed_to?(:edit_products, product.project) } def initialize(attributes=nil, *args) super if new_record? # set default values for new records only self.status_id ||= INACTIVE_PRODUCT self.currency ||= ContactsSetting.default_currency end end def visible?(usr=nil) (usr || User.current).allowed_to?(:view_products, self.project) end def editable_by?(usr, prj=nil) prj ||= @project || self.project usr && (usr.allowed_to?(:edit_products, prj)) end def destroyable_by?(usr, prj=nil) prj ||= @project || self.project usr && (usr.allowed_to?(:delete_products, prj)) end def status case self.status_id when ACTIVE_PRODUCT l(:label_products_status_active) when INACTIVE_PRODUCT l(:label_products_status_inactive) else "" end end def is_active? status_id == ACTIVE_PRODUCT end def is_inactive? status_id == INACTIVE_PRODUCT end def to_s self.name end def all_dependent_products queue = [] dependencies = [] queue << self while (!queue.empty?) do current_product = queue.shift dependencies << current_product current_product.products.map(&:bundles).each do |related_product| queue << related_product end end dependencies.delete(self) dependencies end def self.available_tags(options = {}) limit = options[:limit] scope = RedmineCrm::Tag.where({}) scope = scope.where("#{Project.table_name}.id = ?", options[:project]) if options[:project] scope = scope.where(Project.allowed_to_condition(options[:user] || User.current, :view_products)) scope = scope.where("LOWER(#{RedmineCrm::Tag.table_name}.name) LIKE ?", "%#{options[:name_like].downcase}%") if options[:name_like] joins = [] joins << "JOIN #{RedmineCrm::Tagging.table_name} ON #{RedmineCrm::Tagging.table_name}.tag_id = #{RedmineCrm::Tag.table_name}.id " joins << "JOIN #{Product.table_name} ON #{Product.table_name}.id = #{RedmineCrm::Tagging.table_name}.taggable_id AND #{RedmineCrm::Tagging.table_name}.taggable_type = '#{Product.name}' " joins << "JOIN #{Project.table_name} ON #{Project.table_name}.id = #{Product.table_name}.project_id" scope = scope.select("#{RedmineCrm::Tag.table_name}.*, COUNT(DISTINCT #{RedmineCrm::Tagging.table_name}.taggable_id) AS count") scope = scope.joins(joins.flatten) scope = scope.group("#{RedmineCrm::Tag.table_name}.id, #{RedmineCrm::Tag.table_name}.name HAVING COUNT(*) > 0") scope = scope.limit(limit) if limit scope = scope.order("#{RedmineCrm::Tag.table_name}.name") scope end end
require "rubygems" require "hoe" require "spec/rake/spectask" require "./lib/version.rb" hoe = Hoe.new("gchart", GChart::VERSION) do |p| p.rubyforge_name = "gchart" p.author = "John Barnette" p.email = "jbarnette@rubyforge.org" p.summary = "GChart uses the Google Chart API to create pretty pictures." p.description = p.paragraphs_of("README.txt", 2..5).join("\n\n") p.url = "http://gchart.rubyforge.org" p.changes = p.paragraphs_of("CHANGELOG.txt", 0..1).join("\n\n") end desc "Run all specs" Spec::Rake::SpecTask.new do |t| t.spec_files = FileList["spec/**/*_spec.rb"] t.spec_opts = ["--options", "spec/spec.opts"] end desc "Run all specs and get coverage statistics" Spec::Rake::SpecTask.new('spec:rcov') do |t| t.spec_files = FileList["spec/**/*_spec.rb"] t.rcov = true t.spec_opts = ["--options", "spec/spec.opts"] end Rake::Task[:default].prerequisites.clear task :default => :spec
FactoryGirl.define do factory :record_type do name { FFaker::Lorem.characters(10) } user end end
class RenameCategoryTypeFieldToNameFieldToCategories < ActiveRecord::Migration def change rename_column(:auth_forum_categories, :category_type, :name) end end
# frozen_string_literal: true module Dynflow class Middleware::Stack include Algebrick::TypeCheck attr_reader :action, :middleware_class, :middleware def self.build(middleware_classes, method, action, &block) middleware_classes.reverse_each.reduce(block) do |stack, klass| Middleware::Stack.new(stack, klass, method, action) end end def initialize(next_stack, middleware_class, method, action) @middleware_class = Child! middleware_class, Middleware @middleware = middleware_class.new self @action = Type! action, Dynflow::Action, NilClass @method = Match! method, :delay, :plan, :run, :finalize, :plan_phase, :finalize_phase, :present, :hook @next_stack = Type! next_stack, Middleware::Stack, Proc end def call(*args) @middleware.send @method, *args end def pass(*args) @next_stack.call(*args) end end end
require 'test_helper' class CproProjectsControllerTest < ActionController::TestCase def test_should_get_index get :index, {}, { :user_id => users(:fred).id} assert_response :success assert_not_nil assigns(:cpro_projects) end def test_should_get_new get :new, {}, { :user_id => users(:fred).id} assert_response :success end def test_should_create_cpro_project assert_difference('CproProject.count') do post :create, { :cpro_project => { :id => 12345, :project_id => 1, :cpro_name => 'futest' } }, { :user_id => users(:fred).id} end assert_redirected_to cpro_project_path(assigns(:cpro_project)) end def test_should_show_cpro_project get :show, { :id => cpro_projects(:one).id }, { :user_id => users(:fred).id, :original_uri => '/cpro_projects' } assert_response :success end def test_should_get_edit get :edit, { :id => cpro_projects(:one).id }, { :user_id => users(:fred).id} assert_response :success end def test_should_update_cpro_project put :update, { :id => cpro_projects(:one).id, :cpro_project => { } },{ :user_id => users(:fred).id} assert_redirected_to cpro_project_path(assigns(:cpro_project)) end def test_should_destroy_cpro_project assert_difference('CproProject.count', -1) do delete :destroy, { :id => cpro_projects(:one).id }, { :user_id => users(:fred).id} end assert_redirected_to cpro_projects_path end end
object @order attributes :id, :total_tip,:tip_percent ,:location_id, :status, :is_paid, :receipt_no, :server_id, :tax, :current_tax, :store_no, :fee attribute :get_order_date => "order_date" attribute :get_paid_date => "paid_date" child @order_items => "order_items" do attributes :id, :order_item_comment_id, :order_item_comment, :category_id, :menu_id, :quantity, :note, :use_point, :price, :redemption_value, :status, :rating, :item_id, :item_name, :order_item_id, :combo_item_id child :order_item_combos => "order_item_combo" do attributes *OrderItemCombo.column_names - ['updated_at', 'created_at', 'build_menu_id'], :order_date node(:category_id) do |cate| cate.build_menu.get_category_id_by_buid_menu_id(cate.build_menu_id) end node(:menu_id) do |cate| cate.build_menu.get_menu_id_by_buid_menu_id(cate.build_menu_id) end child :item => "items" do attributes :id, :name end end end child @server => "server" do attributes :id, :name, :is_favorite node :avatar do |ser| ser.avatar.fullpath if ser.avatar end end
module Game::PlayersHelper def show_actions(player) html = '' (1..player.military_actions_left).each do |i| html << image_tag('game/icon_red.png', :style => "position: absolute; right: #{i*10-10}px; top: 0; width: 30px;") end (1..player.civil_actions_left).each do |i| html << image_tag('game/icon_white.png', :style => "position: absolute; right: #{(player.military_actions_left+i)*10+10}px; top: 0; width: 30px;") end return content_tag(:div, html.html_safe, :class => 'actions', :style => 'z-index: 100') end def blue_tokens_bank(player) bank = (1..player.blue_tokens_available).map do |i| offset = 11 if i > 8 offset = 7 if i <= 8 offset = 2 if i <= 4 j = (i-1)/2 if (i % 2 == 1) y = 35 x = offset +25*j else y = 5 x = offset +25*j end image_tag 'game/icon_blue.png', :alt => "Blue token \##{i}", :style => "position: absolute; left: #{x}px; top: #{y}px; width: 30px;" end return bank.join.html_safe end def yellow_tokens_bank(player) bank = (1..player.yellow_tokens_available).map do |i| offset = 2 j = (i-1)/2 if (i % 2 == 1) y = 60 x = offset +33.5*j else y = 25 x = offset +33.5*j end image_tag 'game/icon_yellow.png', :alt => "Yellow token \##{i}", :style => "position: absolute; left: #{x}px; top: #{y}px; width: 30px;" end return bank.join.html_safe end def happiness_level(player) html = [] smileys = [ 96, 130, 180, 230, 265, 298, 332, 365, 400 ] html << image_tag('game/icon_blue.png', :style => "position: absolute; right: #{smileys[player.happiness]}px; top: 0; width: 30px;") player.happiness_workers.times do |i| html << image_tag('game/icon_yellow.png', :style => "position: absolute; right: #{smileys[player.happiness + i + 1]}px; top: 0; width: 30px;") end # (1..player.happiness_workers).each do |i| # html << image_tag('game/icon_yellow.png', :style => "position: absolute; right: #{i*50+80}px; top: 0; width: 30px;") # end return content_tag(:div, html.join.html_safe, :class => 'happiness', :style => 'z-index: 100') end end
# frozen_string_literal: true class Region < ApplicationRecord validates :name, presence: true validates :name, uniqueness: true has_many :pokemons before_create :set_slug private def set_slug self.slug = name.downcase.gsub(/\s+/, "-") end end
class SettingController < ApplicationController before_filter :login_required def index @user = current_user @user.setting = Setting.new if !@user.setting end def update if request.post? @user = current_user current_user.setting.update_attributes!(params[:setting]) flash[:notice] = 'Ваши настройки успешно сохранены' end redirect_to "/" rescue ActiveRecord::RecordInvalid flash[:error] = 'При сохранении данных произошла ошибка' end end
# == Schema Information # # Table name: exams # # id :integer not null, primary key # name :string(255) # course_id :integer # created_at :datetime # updated_at :datetime # lesson_category_id :integer # duration :integer # max_points :integer default("0") # published :boolean default("f") # one_run :boolean default("f") # # Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :exam do name "MyString" lesson_category_id 1 duration 7200 course_id 1 end end
require 'ruby-processing' require 'point' class WindBarb include Processing::Proxy attr_accessor :speed, :direction, :pos, :previous_barb, :last_calm_barb BARB_STROKE_COLOR = 0 BARB_STROKE_WEIGHT = 2 MAIN_LINE_LENGTH = 80 DOT_WIDTH = 3 CIRCLE_WIDTH = 20 # Arrow head height and (center-to-edge) width ARROW_LINE_LENGTH = 80 ARROW_STROKE_COLOR = 50 ARROW_STROKE_WEIGHT = 1 ARROW_DOT_WIDTH = 1 ARROW_DOT_OFFSET = 8 ARROW_DOT_SEPARATION = 4 def initialize(speed, direction, previous_barb) @pos = Point.new(width/2, height/2) @speed = speed.to_f @direction = direction @previous_barb = previous_barb @last_calm_barb = false end def direction_in_radians case @direction when 'E' 0 when 'ENE' -Math::PI/8 when 'NE' -Math::PI/4 when 'NNE' -Math::PI*3/8 when 'N' -Math::PI/2 when 'NNW' -Math::PI*5/8 when 'NW' -Math::PI*3/4 when 'WNW' -Math::PI*7/8 when 'W' -Math::PI when 'WSW' -Math::PI*9/8 when 'SW' -Math::PI*5/4 when 'SSW' -Math::PI*11/8 when 'S' -Math::PI*3/2 when 'SSE' -Math::PI*13/8 when 'SE' -Math::PI*7/4 when 'ESE' -Math::PI*15/8 else 0 end end def render if @speed == 0 render_calm else render_step end end private def render_calm stroke ARROW_STROKE_COLOR stroke_weight ARROW_STROKE_WEIGHT # Draw center dot fill 0 ellipse @pos.x, @pos.y, DOT_WIDTH, DOT_WIDTH # Draw outer circle no_fill ellipse @pos.x, @pos.y, CIRCLE_WIDTH, CIRCLE_WIDTH push_matrix translate @pos.x, @pos.y rotate 3*Math::PI/2 + direction_in_radians # Draw the barb arrow stroke BARB_STROKE_COLOR stroke_weight BARB_STROKE_WEIGHT # Draw the arrow line line 0, 0, 0, ARROW_LINE_LENGTH # Draw a single dot above the arrow for the first calm barb in a sequence if !@previous_barb || @previous_barb.speed>0 fill 0 ellipse 0, ARROW_LINE_LENGTH+ARROW_DOT_OFFSET, ARROW_DOT_WIDTH, ARROW_DOT_WIDTH no_fill elsif @last_calm_barb # Draw a double dot above the arrow for the final calm barb in a sequence fill 0 ellipse 0, ARROW_LINE_LENGTH+ARROW_DOT_OFFSET, ARROW_DOT_WIDTH, ARROW_DOT_WIDTH ellipse 0, ARROW_LINE_LENGTH+ARROW_DOT_OFFSET+2*ARROW_DOT_SEPARATION, ARROW_DOT_WIDTH, ARROW_DOT_WIDTH no_fill end pop_matrix end def render_step stroke BARB_STROKE_COLOR stroke_weight BARB_STROKE_WEIGHT from_point = Point.new(@pos.x - (MAIN_LINE_LENGTH/2)*Math.cos(direction_in_radians), pos.y - (MAIN_LINE_LENGTH/2)*Math.sin(direction_in_radians)) to_point = Point.new(from_point.x+MAIN_LINE_LENGTH*Math.cos(direction_in_radians), from_point.y+MAIN_LINE_LENGTH*Math.sin(direction_in_radians)) line from_point.x, from_point.y, to_point.x, to_point.y render_barbs(from_point, MAIN_LINE_LENGTH, @speed) end def render_barbs(from_point, length, speed) full_flag_length = 40 flag_length = 0 flag_offset = 10 flag_angle = 3*Math::PI/8 to_point = Point.new(from_point.x+length*Math.cos(direction_in_radians), from_point.y+length*Math.sin(direction_in_radians)) # If there is greater than 1 left for the speed # draw a full flag and recurse if there is > 2 speed. # If there is less than 1, draw a half flag. if speed > 2 render_barbs(from_point, length-flag_offset, speed-2) flag_length = full_flag_length elsif speed > 1 flag_length = full_flag_length else flag_length = full_flag_length * 0.5 end # Draw a flag push_matrix translate to_point.x, to_point.y rotate direction_in_radians + flag_angle line 0, 0, flag_length, 0 pop_matrix end end
class ImagenesController < ApplicationController def inicio if params[:search] @imagenes = Imagene.where("nombre like ?", "#{params[:search]}%").order('id DESC').paginate(page: params[:page], per_page: 7) else @imagenes = Imagene.all.order('id DESC').paginate(page: params[:page], per_page: 7) end end def nuevo @imagenes = Imagene.new end def editar @imagenes = Imagene.find(params[:id]) end def mostrar @imagenes = Imagene.find(params[:id]) end def eliminar @imagenes = Imagene.find(params[:id]) @imagenes.destroy respond_to do |format| format.html {redirect_to imagenes_url, notice:'fue eliminado'} end end def buscar if params[:search] @imagenes = Imagene.where("descripcion like ?", "#{params[:search]}%") end end def create @imagenes = Imagene.new(user_params) if @imagenes.save redirect_to imagenes_url else render action: 'nuevo' end end def update @imagenes = Imagene.find(params[:id]) if @imagenes.update_attributes(user_params) redirect_to imagenes_url else render action: 'editar' end end def user_params params.require(:imagene).permit(:nombre,:photo1,:photo2,:photo3,:photo4,:photo5,:photo6,:photo7,:photo8) end end
require 'pry' def times(upper_bound) counter = 0 while counter < upper_bound yield(counter) counter += 1 end upper_bound end # Test implementation # p times(5) { |num| puts num } def select(array) result = [] counter = 0 while counter < array.size result << array[counter] if yield(array[counter]) counter += 1 end result end # Test implementation # p array.select { |num| num.odd? } # => [1, 3, 5] # p array.select { |num| puts num } # => [], because "puts num" returns nil and evaluates to false # p array.select { |num| num + 1 } # p select(array) { |num| num.odd? } # => [1, 3, 5] # p select(array) { |num| puts num } # => [], because "puts num" returns nil and evaluates to false # p select(array) { |num| num + 1 } # => [1, 2, 3, 4, 5], because "num + 1" evaluates to true def reduce(array, default = nil) index, acc = default ? [0, default] : [1, array.first] while index < array.size acc= yield(acc, array[index]) index += 1 end acc end array = [1, 2, 3, 4, 5] p reduce(array) { |acc, num| acc + num } # => 15 p reduce(array, 10) { |acc, num| acc + num } # => 25 p reduce(array) { |acc, num| acc + num if num.odd? } # => NoMethodError: undefined method `+' for nil:NilClass
require 'auth/migration_helper' class CreateCompetitionAuth < ActiveRecord::Migration[4.2] include Auth::MigrationHelper def change add_action_auth :user, :edit, :competition add_action_auth :user, :edit, :competitions end end
require 'pry' require_relative "../config/environment.rb" require 'active_support/inflector' class Song def self.table_name self.to_s.downcase.pluralize #takes the name of the class, turns it into a string, lowercases it and makes it plural end # example: A class Song would equal a table name of "songs" # .pluralize is available through 'active_support/inflector' def self.column_names DB[:conn].results_as_hash = true # returns an array of hashses describing the table itself. # Here is one of the many hashes in the array it will return. # [{"cid"=>0, | # "name"=>"id", | \ # "type"=>"INTEGER", | \ # "notnull"=>0, | \ # "dflt_value"=>nil, | \ # "pk"=>1, | \ # 0=>0, | ----- >>>> This is all the information from one column of the table. # 1=>"id", | / # 2=>"INTEGER", | / # 3=>0, | / # 4=>nil, | / # 5=>1}, | / sql = "pragma table_info('#{table_name}')" #=> pragma table_info returns the results of data type of the table. table_info = DB[:conn].execute(sql) #=> Iterate over the hashes to find the name of each columns. column_names = [] table_info.each do |row| column_names << row["name"] end column_names.compact #=> .compact just makes sure that there are no nil values included # The return value here would look like.... ["id", "name", "album"] # This now can be used to make our Song class attr_accessor names. end self.column_names.each do |col_name| #=> Iterates over the #column.names and creates a attr_accessor attr_accessor col_name.to_sym # for each. .to_sym converts it to a symbol. end def initialize(options={}) #=> Takes in an argument called options that defaults to an empty hash. options.each do |property, value| #Iterates over the hash and sets a #property= equal to its value. self.send("#{property}=", value) # As long as each property has a corresponding attr_accessor this will work. end #self.send("#{property}=", value) calls the method property= and its argument is value. end def save #=> The final step after metaprogramming the other values. sql = "INSERT INTO #{table_name_for_insert} (#{col_names_for_insert}) VALUES (#{values_for_insert})" DB[:conn].execute(sql) @id = DB[:conn].execute("SELECT last_insert_rowid() FROM #{table_name_for_insert}")[0][0] end def table_name_for_insert #=> Grabs the table name that was created from the class method #table_name self.class.table_name # and gives us access to it in an instance method. end def values_for_insert #= Iterates over the class #column_names and saves its values in an array. values = [] self.class.column_names.each do |col_name| values << "'#{send(col_name)}'" unless send(col_name).nil? #"'#{send(col_name)}'" returns the vlaue of the col_name key. #When we insert these values into the chart we want each value to be sepearte strings. #INSERT INTO songs (name, album) VALUES ('Hello', '25') ... Therefore, we wrap the return value #into a string. Each value shoudl be a seperate strin so we also use ' ' as well. This will #return a values array of ["'Hello', '25'"]. ...................................... end values.join(", ") # ............ #=> Returns 'Hello', '25' end def col_names_for_insert #=> Grabs the name created from the class method #col_names and gives us # access to it in an instance method. However self.col_names includes the id which we do not want # ["id", "name", "album"].The id should not be set when an instance is created, but when added to # the database. Thefore, we must remove the id. self.class.column_names.delete_if {|col| col == "id"}.join(", ") #=> Returns ["name", "album"] before the .join(", ") # But we don't insert an array into a table, but different values. # .join(", ") returns a string of "name, album" => This is what we need to insert columns into our table. end def self.find_by_name(name) sql = "SELECT * FROM #{self.table_name} WHERE name = '#{name}'" DB[:conn].execute(sql) end end
class Voter < ActiveRecord::Base has_many :contacts has_many :volunteers, :through => :contacts accepts_nested_attributes_for :contacts end