text
stringlengths
10
2.61M
# Copyright (c) 2006, 2007 Ruffdogs Software, Inc. # Authors: Adam Lebsack <adam@holonyx.com> # # This program 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 2 of the License. # # This program 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. module Restore module_require_dependency :filesystem, 'file' module_require_dependency :filesystem, 'log' module_require_dependency :filesystem, 'snapshot' module Target class Filesystem < Restore::Target::Base has_many :files, :class_name => 'Restore::Modules::Filesystem::File', :foreign_key => 'target_id', :dependent => :delete_all has_many :logs, :class_name => 'Restore::Modules::Filesystem::Log', :foreign_key => 'target_id', :dependent => :delete_all self.abstract_class = true def root_directory() files.find_by_parent_id(nil) end def self.snapshot_class module_require_dependency :filesystem, 'snapshot' Restore::Snapshot::Filesystem end def self.browser_class ('Restore::Browser::'+self.to_s.split(/::/)[-1]) end def root_name 'root' end end end end
# == Schema Information # # Table name: profiles # # id :bigint not null, primary key # age :integer # gender :integer # introduction :text # type :integer # created_at :datetime not null # updated_at :datetime not null # user_id :bigint not null # # Indexes # # index_profiles_on_user_id (user_id) # class Profile < ApplicationRecord belongs_to :user has_one_attached :avatar validates :introduction, presence: true validates :introduction, length: { maximum: 300 } self.inheritance_column = :_type_disabled enum gender: { male: 0, female: 1, other: 2 } enum age: { teens: 0, twenties: 1, thirties: 2, forties: 3, fifties: 4, sixtiesover: 5 } enum type: { maker: 0, trade: 1, it: 2, ad: 3, human: 4, realestate: 5, consulting: 6, dealer: 7, insurance: 8, finance: 9, typeother: 10 } end
require 'rails_helper' describe Solicitation do it "é válido quando o requerimento tem tipo, data de partida, data de retorno, origem, destino, descrição e status" do user = User.create(full_name: "Aluno", email: "student@student.com", password: "admin123", role: "student", registration: "000000000") solicitation = Solicitation.create(kind: 0, departure: DateTime.new(2020, 10, 16, 22, 35, 0), return: DateTime.new(2020, 10, 25, 22, 35, 0), origin: "Brasília", destination: "Tokyo", description: "bla_bla_bla_bla", status: "analise", user_id: user.id) expect(solicitation).to be_valid end it "é invalido sem o tipo" do user = User.create(full_name: "Aluno", email: "student@student.com", password: "admin123", role: "student", registration: "000000000") solicitation = Solicitation.create(kind: nil, departure: DateTime.new(2020, 10, 16, 22, 35, 0), return: DateTime.new(2020, 10, 25, 22, 35, 0), origin: "Brasília", destination: "Tokyo", description: "bla_bla_bla_bla", status: "analise", user_id: user.id) solicitation.valid? expect(solicitation.errors[:kind]).to include("não pode ficar em branco") end it "é invalido sem o data de partida" do user = User.create(full_name: "Aluno", email: "student@student.com", password: "admin123", role: "student", registration: "000000000") solicitation = Solicitation.create(kind: 0, departure: nil, return: DateTime.new(2020, 10, 25, 22, 35, 0), origin: "Brasília", destination: "Tokyo", description: "bla_bla_bla_bla", status: "analise", user_id: user.id) solicitation.valid? expect(solicitation.errors[:departure]).to include("não pode ficar em branco") end it "é invalido sem o data de retorno" do user = User.create(full_name: "Aluno", email: "student@student.com", password: "admin123", role: "student", registration: "000000000") solicitation = Solicitation.create(kind: 0, departure: DateTime.new(2020, 10, 16, 22, 35, 0), return: nil, origin: "Brasília", destination: "Tokyo", description: "bla_bla_bla_bla", status: "analise", user_id: user.id) solicitation.valid? expect(solicitation.errors[:return]).to include("não pode ficar em branco") end it "é invalido sem o origem" do user = User.create(full_name: "Aluno", email: "student@student.com", password: "admin123", role: "student", registration: "000000000") solicitation = Solicitation.create(kind: 0, departure: DateTime.new(2020, 10, 16, 22, 35, 0), return: DateTime.new(2020, 10, 25, 22, 35, 0), origin: nil, destination: "Tokyo", description: "bla_bla_bla_bla", status: "analise", user_id: user.id) solicitation.valid? expect(solicitation.errors[:origin]).to include("não pode ficar em branco") end it "é invalido sem o destino" do user = User.create(full_name: "Aluno", email: "student@student.com", password: "admin123", role: "student", registration: "000000000") solicitation = Solicitation.create(kind: 0, departure: DateTime.new(2020, 10, 16, 22, 35, 0), return: DateTime.new(2020, 10, 25, 22, 35, 0), origin: "Brasília", destination: nil, description: "bla_bla_bla_bla", status: "analise", user_id: user.id) solicitation.valid? expect(solicitation.errors[:destination]).to include("não pode ficar em branco") end it "é invalido sem o descrição" do user = User.create(full_name: "Aluno", email: "student@student.com", password: "admin123", role: "student", registration: "000000000") solicitation = Solicitation.create(kind: 0, departure: DateTime.new(2020, 10, 16, 22, 35, 0), return: DateTime.new(2020, 10, 25, 22, 35, 0), origin: "Brasília", destination: "Tokyo", description: nil, status: "analise", user_id: user.id) solicitation.valid? expect(solicitation.errors[:description]).to include("não pode ficar em branco") end it "é invalido sem o status" do user = User.create(full_name: "Aluno", email: "student@student.com", password: "admin123", role: "student", registration: "000000000") solicitation = Solicitation.create(kind: 0, departure: DateTime.new(2020, 10, 16, 22, 35, 0), return: DateTime.new(2020, 10, 25, 22, 35, 0), origin: "Brasília", destination: "Tokyo", description: "bla_bla_bla_bla", status: nil, user_id: user.id) solicitation.valid? expect(solicitation.errors[:status]).to include("não pode ficar em branco") end it "é invalido sem o user_id" do user = User.create(full_name: "Aluno", email: "student@student.com", password: "admin123", role: "student", registration: "000000000") solicitation = Solicitation.create(kind: 0, departure: DateTime.new(2020, 10, 16, 22, 35, 0), return: DateTime.new(2020, 10, 25, 22, 35, 0), origin: "Brasília", destination: "Tokyo", description: "bla_bla_bla_bla", status: "analise", user_id: nil) expect(solicitation).not_to be_valid end it "isAccepted funciona quando o status é \"aprovado\"" do user = User.create(full_name: "Aluno", email: "student@student.com", password: "admin123", role: "student", registration: "000000000") solicitation = Solicitation.create(kind: 0, departure: DateTime.new(2020, 10, 16, 22, 35, 0), return: DateTime.new(2020, 10, 25, 22, 35, 0), origin: "Brasília", destination: "Tokyo", description: "bla_bla_bla_bla", status: "aprovado", user_id: user.id) expect(solicitation.isAccepted).to eq true end it "isAccepted não funciona quando o status é \"analise\"" do user = User.create(full_name: "Aluno", email: "student@student.com", password: "admin123", role: "student", registration: "000000000") solicitation = Solicitation.create(kind: 0, departure: DateTime.new(2020, 10, 16, 22, 35, 0), return: DateTime.new(2020, 10, 25, 22, 35, 0), origin: "Brasília", destination: "Tokyo", description: "bla_bla_bla_bla", status: "analise", user_id: user.id) expect(solicitation.isAccepted).to eq false end it "isAccepted não funciona quando o status é \"reprovado\"" do user = User.create(full_name: "Aluno", email: "student@student.com", password: "admin123", role: "student", registration: "000000000") solicitation = Solicitation.create(kind: 0, departure: DateTime.new(2020, 10, 16, 22, 35, 0), return: DateTime.new(2020, 10, 25, 22, 35, 0), origin: "Brasília", destination: "Tokyo", description: "bla_bla_bla_bla", status: "reprovado", user_id: user.id) expect(solicitation.isAccepted).to eq false end it "isRefused funciona quando o status é \"aprovado\"" do user = User.create(full_name: "Aluno", email: "student@student.com", password: "admin123", role: "student", registration: "000000000") solicitation = Solicitation.create(kind: 0, departure: DateTime.new(2020, 10, 16, 22, 35, 0), return: DateTime.new(2020, 10, 25, 22, 35, 0), origin: "Brasília", destination: "Tokyo", description: "bla_bla_bla_bla", status: "aprovado", user_id: user.id) expect(solicitation.isRefused).to eq false end it "isRefused não funciona quando o status é \"analise\"" do user = User.create(full_name: "Aluno", email: "student@student.com", password: "admin123", role: "student", registration: "000000000") solicitation = Solicitation.create(kind: 0, departure: DateTime.new(2020, 10, 16, 22, 35, 0), return: DateTime.new(2020, 10, 25, 22, 35, 0), origin: "Brasília", destination: "Tokyo", description: "bla_bla_bla_bla", status: "analise", user_id: user.id) expect(solicitation.isRefused).to eq false end it "isRefused não funciona quando o status é \"reprovado\"" do user = User.create(full_name: "Aluno", email: "student@student.com", password: "admin123", role: "student", registration: "000000000") solicitation = Solicitation.create(kind: 0, departure: DateTime.new(2020, 10, 16, 22, 35, 0), return: DateTime.new(2020, 10, 25, 22, 35, 0), origin: "Brasília", destination: "Tokyo", description: "bla_bla_bla_bla", status: "reprovado", user_id: user.id) expect(solicitation.isRefused).to eq true end it "isAnalysing funciona quando o status é \"aprovado\"" do user = User.create(full_name: "Aluno", email: "student@student.com", password: "admin123", role: "student", registration: "000000000") solicitation = Solicitation.create(kind: 0, departure: DateTime.new(2020, 10, 16, 22, 35, 0), return: DateTime.new(2020, 10, 25, 22, 35, 0), origin: "Brasília", destination: "Tokyo", description: "bla_bla_bla_bla", status: "aprovado", user_id: user.id) expect(solicitation.isAnalysing).to eq false end it "isAnalysing não funciona quando o status é \"analise\"" do user = User.create(full_name: "Aluno", email: "student@student.com", password: "admin123", role: "student", registration: "000000000") solicitation = Solicitation.create(kind: 0, departure: DateTime.new(2020, 10, 16, 22, 35, 0), return: DateTime.new(2020, 10, 25, 22, 35, 0), origin: "Brasília", destination: "Tokyo", description: "bla_bla_bla_bla", status: "analise", user_id: user.id) expect(solicitation.isAnalysing).to eq true end it "isAnalysing não funciona quando o status é \"reprovado\"" do user = User.create(full_name: "Aluno", email: "student@student.com", password: "admin123", role: "student", registration: "000000000") solicitation = Solicitation.create(kind: 0, departure: DateTime.new(2020, 10, 16, 22, 35, 0), return: DateTime.new(2020, 10, 25, 22, 35, 0), origin: "Brasília", destination: "Tokyo", description: "bla_bla_bla_bla", status: "reprovado", user_id: user.id) expect(solicitation.isAnalysing).to eq false end end
class Drum VENDOR = "Wula Drum" OPTION1_NAME = "Title" OPTION1_VALUE = "Default Title" IMAGE_ALT_TEXT = "Wula Drum best djembe Special Piece" VARIANT_INVENTORY_TRACKER = "shopify" VARIANT_INVENTORY_QTY = "1" VARIANT_INVENTORY_POLICY = "deny" VARIANT_FULFILLMENT_SERVICE = "manual" VARIANT_REQUIRES_SHIPPING = "TRUE" VARIANT_TAXABLE = "TRUE" VARIANT_BARCODE = "" GIFT_CARD = "FALSE" SEO_TITLE = "Wula Drum's Best Djembe from West Africa - handmade" SEO_DESCRIPTION = "The special piece is Wula Drum's best djembe. This handmade djembe from West Africa comes in four models and features our best sound." VARIANT_WEIGHT_UNIT = "lb" @@shipment = "2015_june_shipment" @@type_map = { "dj" => "djembe", "dds" => "dundun set", "sb" => "sangban" } @@wood_map = { "k" => "Khadi", "a" => "Acajou", "l" => "Lengue", "d" => "Doukie" } attr_accessor :photo, :inventory_num, :item, :wood_class, :model, :wood_type, :diameter, :height, :weight, :received, :price def initialize(row) @photo, @inventory_num, @item, @wood_class, @model, @wood_type, @diameter, @height, @weight, @received, @price = row end def handle(id = "") "2015_" + @inventory_num + id + "_" + @item.downcase + @wood_class.downcase + @wood_type.downcase + "_" + @model.downcase end def handle_for_img_url(id = "") "2015_" + @inventory_num + id + "_" + @item + @wood_class + @wood_type + "_" + @model end def title "#{@model} #{@item} ##{@inventory_num}" end def body <<-BODYTEXT <br> <p><b>#{@model} ##{@inventory_num} Specs:</b></p> <ul> <li>Wood Type: #{@@wood_map[@wood_type.downcase]}</li> <li>Diameter: #{@diameter}"</li> <li>Height: #{@height}"</li> <li>Weight: #{@weight} lbs</li> </ul> BODYTEXT end def type @@type_map[@item.downcase] end def tags "" end def variant_sku handle.upcase end def variant_grams @weight.to_f * 453.592 end def variant_price @price end def aws_image_url "https://s3.amazonaws.com/wuladrum/products/#{@@shipment}/W_#{@model}/W_#{handle_for_img_url("a")}.JPG" end def return_row return [ handle, title, body, VENDOR, type, tags, "FALSE", OPTION1_NAME, OPTION1_VALUE, "", "", "", "", variant_sku, variant_grams, VARIANT_INVENTORY_TRACKER, VARIANT_INVENTORY_QTY, VARIANT_INVENTORY_POLICY, VARIANT_FULFILLMENT_SERVICE, variant_price, "", VARIANT_REQUIRES_SHIPPING, VARIANT_TAXABLE, VARIANT_BARCODE, aws_image_url, SEO_TITLE, SEO_DESCRIPTION, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", VARIANT_WEIGHT_UNIT ] end end
class Reference < ActiveRecord::Base belongs_to :topic before_validation :check_url validates :URL, :url => true def check_url unless self.URL[/\Ahttp:\/\//] || self.URL[/\Ahttps:\/\//] self.URL = "http://#{self.URL}" end end end
require_relative '../../../modules/utils/hamming' context Hamming do describe '#distance' do it 'returns the Hamming distance between two arrays of bytes' do control = Plaintext.to_bytes("control") test = Plaintext.to_bytes("this is a test") wokka = Plaintext.to_bytes("wokka wokka!!!") expect(Hamming.distance(control, control)).to eq 0 expect(Hamming.distance(test, wokka)).to eq 37 end end describe '#compare' do it 'returns the Hamming distance between 2 bytes' do expect(Hamming.compare(6, 4)).to eq 1 end end describe '#strict_binary' do it 'returns an 8-char binary byte as a string' do expect(Hamming.strict_binary(2)).to eq '00000010' expect(Hamming.strict_binary(6)).to eq '00000110' end end end
class CategorySerializer < ActiveModel::Serializer belongs_to :project has_many :tasks attributes :id, :name, :taskIds end
class ContractsController < ApplicationController helper_method :check_and_see_if_someone_is_logged_in_as_aide? before_action :authorized_to_see_page_aide skip_before_action :authorized_to_see_page_aide, only: [:index] # skip_before_action :authorized_to_see_page_client, only: [:login, :handle_login, :new, :create] def index @contracts = Contract.all end def show @contract = Contract.find(params[:id]) end def new @contract = Contract.new @aides = Aide.all @services = Service.all @clients = Client.all end def edit @contract = Contract.find(params[:id]) @aides = Aide.all @services = Service.all @clients = Client.all end def update @contract = Contract.find(params[:id]) @contract.update(contract_params) redirect_to contract_path(@contract) end def create @current_aide = Aide.find_by(id: session[:aide_id]) @contract = @current_aide.contracts.create(contract_params) redirect_to profile_path(@current_aide) end def destroy @contract = Contract.find(params[:id]) @contract.destroy redirect_to profile_path end private def contract_params params.require(:contract).permit(:aide_id, :service_id, :availability_to_start, :pay_rate, :title) end end
class AddCompletedAtToTodos < ActiveRecord::Migration def change add_column :todos, :completed_at, :datetime, default: :null end end
require 'peekj' require 'http' module Peekj class JiraApi def self.search(jql) response = new.get("search#{jql}") end def self.get_issue(issue_key) response = new.get("issue/#{issue_key}") OpenStruct.new( status: response['fields']['status']['name'], summary: response['fields']['summary'], description: response['fields']['description'], comments: response['fields']['comment']['comments'].map { |c| {author: c['author']['displayName'], body: c['body']} } ) end def self.add_comment(issue_key, comment_body) params = {body: comment_body} response = new.post("issue/#{issue_key}/comment", params) post_succeeded = !response['created'].nil? post_succeeded end def get(relative_path) HTTP.basic_auth(auth_params).get("#{base_url}#{relative_path}").parse end def post(relative_path, params) HTTP.basic_auth(auth_params).post("#{base_url}#{relative_path}", json: params).parse end private def auth_params @auth_params ||= {user: Credentials.username, pass: Credentials.api_token} end def base_url app_url = Credentials.app_url "#{app_url}/rest/api/latest/" end end end
require 'rails_helper' RSpec.describe FlickrAgent, type: :module do class TestClass include FlickrAgent end search_text = 'St.Petersburg' before :each do @test_class = TestClass.new @photos = flickr.photos.search(text: search_text) end # Test public method get_flickr_photos(text) describe 'FlickrAgent public methods' do it 'should have equal results quantity as @photos' do expect(@test_class.get_flickr_photos(search_text).count).to eq @photos.count end end # Test private methods generate_url(photo, suffix) and create_urls_hash(photos_array) describe 'FlickrAgent private methods' do # Generate variables for each test before :each do # We use random photo from @photos and random suffix for tests @photo = @photos.to_a.sample @suffix = %w(q h).sample end describe 'generate_url(photo, suffix)' do it 'should generate proper url' do url_mask = "https://farm#{@photo.farm}.staticflickr.com/#{@photo.server}/#{@photo.id}_#{@photo.secret}_#{@suffix}.jpg" expect(@test_class.send(:generate_url, @photo, @suffix)).to eq url_mask end end describe 'create_urls_hash(photos_array)' do subject { @test_class.send(:create_urls_hash, @photos) } it 'should have equal results quantity as @photos' do expect(subject.count).to eq @photos.count end it 'should have all the necessary elements in response' do [:id, :title, :thumb, :full].each do |key| puts key expect(subject.sample[key]).not_to be_nil end end describe 'compare method result with Flickraw response' do it 'should have same id as @photo' do # Get index of @photo to find the same element in Flickraw method response # to test method response order photo_index = @photos.to_a.index(@photo) expect(subject[photo_index][:id]).to eq @photo.id end end end end end
class Product < ApplicationRecord has_many :bundles has_many :order_lines, as: :lineable end
require 'httparty' class Snipe LAPTOP_CATEGORY_ID = 1 API_KEY_PATH = '/secrets/api_key.txt' def initialize(api_url) @api_url = api_url load_key end def error(message) raise "ERROR: #{ message }" end def load_key @@access_token ||= begin if not File.exist?(API_KEY_PATH) error('Missing api key') end File.read(API_KEY_PATH) end end def query(url, params = {}, offset = 0) headers = { 'Accept' => 'application/json', 'Content-Type' => 'application/json', 'Authorization' => "Bearer #{ @@access_token }", } params['offset'] = offset if offset > 0 response = HTTParty.get(@api_url + url, query: params, headers: headers) if response.code != 200 error(__method__.to_s) elsif not response.key?('rows') return response elsif (row_count = response['rows'].count) > 0 next_response = query(url, params, offset + row_count) response['rows'] += next_response['rows'] if next_response.code == 200 end response end # -------------------------------------------------------- # Laptops # -------------------------------------------------------- def laptop_query(additional_query = {}) set = query('hardware', { 'category_id' => LAPTOP_CATEGORY_ID }.merge(additional_query))['rows'] set.each {|i| add_warranty_status(i) } end def add_warranty_status(laptop) laptop['in_warranty'] = (not laptop['warranty_expires'].nil? and Date.parse(laptop['warranty_expires']['formatted']) > DateTime.now) end # Return all laptops that are not in the archived Snipe state def active_laptops @active_laptops ||= laptop_query end # Return all non-archived spare laptops def spare_laptops @spare_laptops ||= laptop_query({ 'status' => 'Requestable' }) end # Return all laptops that are in the archived Snipe state def archived_laptops @archived_laptops ||= laptop_query({ 'status' => 'Archived' }) end # Return all laptops that are not spares, regardless of current check out status def staff_laptops @staff_laptops ||= begin spare_ids = spare_laptops.map {|i| i['id'] } active_laptops.reject {|i| spare_ids.include?(i['id']) } end end def laptops(type) case type when 'spares' spare_laptops when 'staff' staff_laptops when 'archived' archived_laptops else active_laptops end end # Get one laptop by asset_tag def get_laptop(asset_tag) query("hardware/bytag/#{ asset_tag }") end # -------------------------------------------------------- # Other # -------------------------------------------------------- def users @users ||= begin user_list = query('users')['rows'] add_laptops_to_users(user_list) end end def add_laptops_to_users(user_list) user_list.each do |user| user['laptops'] = nil active_laptops.each do |laptop| if not laptop['assigned_to'].nil? and laptop['assigned_to']['username'] == user['username'] user['laptops'] = [] if user['laptops'].nil? user['laptops'] << laptop['asset_tag'] end end end end def users_with_laptops @users_with_laptops ||= users.reject {|i| i['laptops'].nil? } end def users_no_laptops @users_with_laptops ||= users.reject {|i| not i['laptops'].nil? } end def models @models ||= query('models')['rows'] end def laptop_models @laptop_models ||= models.reject {|i| i['category']['name'] != 'Laptop' } end def manufacturers @manufacturers ||= query('manufacturers')['rows'] end def laptop_manufacturers @laptop_manufacturers ||= models.map {|i| i['manufacturer']['name'] }.uniq! end def statuses @statuses ||= query('statuslabels')['rows'] end end
class CreateUsers < ActiveRecord::Migration[5.0] def change create_table :users do |t| t.column :pseudo, :string #simplifié pour le moment, ajouter plus d'infos par la suite t.column :password, :string #voir comment sécuriser les mot de passe t.column :role, :string, :default => "User" t.timestamps end end end
class RockPaperScissors attr_accessor :type def initialize(type) @type = type @rules = {} @rules[:scissors] = [:paper, :lizard] @rules[:paper] = [:rock, :spock] @rules[:rock] = [:scissors, :lizard] @rules[:lizard] = [:spock, :paper] @rules[:spock] = [:scissors, :rock] end def ==(other) type == other.type end def <(other) @rules[other.type].include? type end def <=(other) @rules[other.type].include?(type) || type == other.type end def >(other) @rules[type].include? other.type end def >=(other) @rules[type].include?(other.type) || type == other.type end end
module LaunchablePreparer include MarketplacePoolGroups def virtualmachines(params) find_by_group(params,:virtualmachines) end def prepackaged(params) find_by_group(params,:prepackaged) end def containers(params) find_by_group(params,:containers) end def customapps(params) find_by_group(params, :customapps) end def snapshots(params) return Hash[] end def prepared(params) { virtualmachines: virtualmachines(params), prepackaged: prepackaged(params), containers: containers(params), customapps: customapps(params), snapshots: snapshots(params) } end end
class AddFeaturesToProduct < ActiveRecord::Migration def change add_column :products, :feature_title, :string add_column :products, :feature_subtitle, :string end end
module Components module Icon class IconComponent < Middleman::Extension helpers do def icon(opts, &block) additional_classes = opts.dig(:html, :class) ? " #{opts[:html][:class]}" : '' link_to(opts[:href], class: "transition-all block text-white hover:text-gray-300 #{additional_classes} motion-reduce:transition-none motion-reduce:transform-none", target: '_blank', rel: 'nofollow noopener noreferrer', &block) end end end end end ::Middleman::Extensions.register(:icon_component, Components::Icon::IconComponent)
module RuboCop::Git # copy from https://github.com/thoughtbot/hound/blob/d2f3933/app/models/commit_file.rb class CommitFile def initialize(file, commit) @file = file @commit = commit end def filename @file.filename end def content @content ||= begin unless removed? @commit.file_content(filename) end end end def relevant_line?(line_number) modified_lines.detect do |modified_line| modified_line.line_number == line_number end end def removed? @file.status == 'removed' end def ruby? filename.match(/.*\.rb$/) end def modified_lines @modified_lines ||= patch.additions end def modified_line_at(line_number) modified_lines.detect do |modified_line| modified_line.line_number == line_number end end private def patch Patch.new(@file.patch) end end end
require 'spec_helper' require_relative '../lib/dwelling' describe Dwelling do let(:dwelling) {dwelling = Dwelling.new("35 Swan Rd", "Winchester, MA", "01890")} describe ".new" do it "creates a dwelling with an address, city_or_town, and zip_code" do expect(dwelling).to be_a(Dwelling) expect(dwelling.address).to eq("35 Swan Rd") expect(dwelling.city_or_town).to eq("Winchester, MA") expect(dwelling.zip_code).to eq("01890") end end end
class EventsController < ApplicationController def new @event = Event.new respond_to do |format| format.js { render :new } format.html { render :new } end end def create event_params = params.require(:event).permit(:title, :date, :time, :address, :description, :min) @event = Event.new event_params @event.creator = current_user.id if @event.save participants = params[:participants][0].gsub(', ', ',') p_array = participants.split(',') send_invites(p_array) else flash.now[:alert] = 'Your event was not created' render :new end respond_to do |format| format.js { render :show } format.html { render :show } end end def show @event = Event.find_by(id: params[:id]) @attending = Invitation.where(event_id: @event.id).where(answer: true).count @invite = Invitation.where(user: current_user, event: @event.id) respond_to do |format| format.js { render :show } format.html { render :show } end end def update @event = Event.find_by(id: params[:id]) u = Invitation.where(user_id: current_user.id).find_by(event_id: @event.id) return (u.answer = true) if u.answer == false u.save @attending = Invitation.where(event_id: @event.id).where(answer: true).count @invite = Invitation.where(user: current_user, event: @event.id) respond_to do |format| format.js { render :show } format.html { render :show } end end def send_invites(array) array.each do |a| unless User.find_by(email: a).nil? user = User.find_by(email: a) invite = Invitation.create(event_id: @event.id, user_id: user.id, answer: false) invite.save end end end end
module Karafka module Connection # Class that consumes messages for which we listen class Consumer # Consumes a message (does something with it) # It will route a message to a proper controller and execute it # Logic in this method will be executed for each incoming message # @note This should be looped to obtain a constant listening # @note We catch all the errors here, to make sure that none failures # for a given consumption will affect other consumed messages # If we would't catch it, it would propagate up until killing the Celluloid actor # @param controller_class [Karafka::BaseController] base controller descendant class # @param message [Poseidon::FetchedMessage] message that was fetched by poseidon def consume(controller_class, message) controller = Karafka::Routing::Router.new( Message.new(controller_class.topic, message.value) ).build Karafka.monitor.notice( self.class, controller_class: controller_class ) controller.schedule # This is on purpose - see the notes for this method # rubocop:disable RescueException rescue Exception => e # rubocop:enable RescueException Karafka.monitor.notice_error(self.class, e) end end end end
class RemoveNullConstraintFromAgreementsPartners < ActiveRecord::Migration def change change_column :agreements_partners, :created_at, :datetime, :null => true change_column :agreements_partners, :updated_at, :datetime, :null => true end end
class UserGuidesController < ApplicationController # GET /user_guides # GET /user_guides.json def index add_breadcrumb "Training Videos", training_videos_path respond_to do |format| format.html # index.html.erb format.json { render json: @user_guides } end end # GET /user_guides/1 # GET /user_guides/1.json def show @user_guide = UserGuide.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @user_guide } end end # GET /user_guides/new # GET /user_guides/new.json def new @user_guide = UserGuide.new respond_to do |format| format.html # new.html.erb format.json { render json: @user_guide } end end # GET /user_guides/1/edit def edit @user_guide = UserGuide.find(params[:id]) end # POST /user_guides # POST /user_guides.json def create @user_guide = UserGuide.new(params[:user_guide]) respond_to do |format| if @user_guide.save format.html { redirect_to @user_guide, notice: 'User guide was successfully created.' } format.json { render json: @user_guide, status: :created, location: @user_guide } else format.html { render action: "new" } format.json { render json: @user_guide.errors, status: :unprocessable_entity } end end end # PUT /user_guides/1 # PUT /user_guides/1.json def update @user_guide = UserGuide.find(params[:id]) respond_to do |format| if @user_guide.update_attributes(params[:user_guide]) format.html { redirect_to @user_guide, notice: 'User guide was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @user_guide.errors, status: :unprocessable_entity } end end end # DELETE /user_guides/1 # DELETE /user_guides/1.json def destroy @user_guide = UserGuide.find(params[:id]) @user_guide.destroy respond_to do |format| format.html { redirect_to user_guides_url } format.json { head :no_content } end end def hint_toggle current_account.update_attributes(:popup_tips => !current_account.popup_tips) flash[:notice] = "Hint Pop Ups are " + (!current_account.popup_tips? ? "Off" : "On") + " now" redirect_to :back end end
class Line attr_accessor :content def initialize @uri = URI.parse("https://notify-api.line.me/api/notify") @token = ENV['CC_LINE_TOKEN'] @content = "" end def notify(msg) request = make_request(msg) response = Net::HTTP.start(@uri.hostname, @uri.port, use_ssl: @uri.scheme == "https") do |https| https.request(request) end end def content_notify puts 'LINE送信-content_notify' request = make_request(@content) response = Net::HTTP.start(@uri.hostname, @uri.port, use_ssl: @uri.scheme == "https") do |https| https.request(request) end p response end def make_request(msg) request = Net::HTTP::Post.new(@uri) request["Authorization"] = "Bearer #{@token}" request.set_form_data(message: msg) request end # メッセージに改行を加えて新しいメッセージを追加する def update_content(msg) @content = @content + "\n" + msg end def reset_content @content = '' end end
class TodoesController < ApplicationController #ログインしていなければ機能が使えない # before_action :authenticate_user! def index #ログインしてたらShowページに if (user_signed_in?) redirect_to controller: 'todoes', action: 'show', id: current_user.id end end #目標作成 def new @goal = Goal.new end def create @goal = Goal.new(goal_params) @goal.user_id = current_user.id monster_max = Monster.count @goal.monster_id = rand(1..monster_max) if @goal.save! redirect_to mypage_path(current_user.id) else redirect_to "http://www.pikawaka.com" end # redirect_to controller: 'todoes', action: 'show', id: current_user.id end def show @user = User.find(params[:id]) @goal = @user.goals.last # @@goal = @user.goals.last #タスク完了にわたすため #初回は目標を設定させる if (@goal.nil?) redirect_to controller: 'todoes', action: 'new' return end if !(@goal.nil?) #@@current_goal_id = @goal.id @current_monster_id = @goal.monster_id end @monster = Monster.find(@current_monster_id) @task = Task.new # 完了、未完了タスク @get_check = Task.where(goal_id: @goal.id).where(check: true) @get_uncheck = Task.where(goal_id: @goal.id).where(check: false) # タスク完了、削除 @check_task = Task.find_by(goal_id: @goal.id) @destroy_task = Task.find_by(goal_id: @goal.id) # モンスターコメント comment_max = Encourage.count; @comment = Encourage.find(rand(1..comment_max)).comment end #タスク作成 def task_create @task = Task.new(task_params) #@task.goal_id = @@current_goal_id #@task.goal_id = id_params @task.save redirect_to controller: 'todoes', action: 'show', id: current_user.id end #タスク完了 def task_check @task = Task.find(params[:id]) @task.update(check: true) #経験値追加 @goal = current_user.goals.last @goal.increment(:ex , 10) @goal.save if @goal.ex >= 30 @goal.increment(:lv ,1) @goal.save @goal.update(ex: 0) end redirect_to controller: 'todoes', action: 'show', id: current_user.id end def destroy Task.find(params[:id]).destroy redirect_to controller: 'todoes', action: 'show', id: current_user.id end private def goal_params params.require(:goal).permit(:goal) end def task_params params.require(:task).permit(:task, :goal_id) end end
class Playlist < ActiveRecord::Base belongs_to :post belongs_to :user belongs_to :topic validates :url, length: { minimum: 5 }, presence: true validates :user, presence: true default_scope order('updated_at DESC') def youtube_or_soundcloud(url) if url(0..1) == "//" true else false end end end
module RSence require 'rubygems' require 'json' ## Shared messaging-object: require 'rsence/msg' ## Unique random number generator: require 'randgen' ## SessionStorage is the superclass of SessionManager require 'rsence/sessionstorage' require 'digest/sha1' # SessionManager does session creation, validation, expiration and storage duties. class SessionManager < SessionStorage include Digest attr_reader :randgen ## Makes everything ready to run def initialize( transporter ) super() @transporter = transporter @valuemanager = @transporter.valuemanager @plugins = @transporter.plugins ## 'Unique' Random String generator for ses_key:s and cookie_key:s @randgen = RandGen.new( @config[:key_length] ) # regex to match ipv4 addresses @ipv4_reg = /^([1][0-9][0-9]|[2][0-5][0-9]|[1-9][0-9]|[1-9])\.([1][0-9][0-9]|[2][0-5][0-9]|[1-9][0-9]|[0-9])\.([1][0-9][0-9]|[2][0-5][0-9]|[1-9][0-9]|[0-9])\.([1][0-9][0-9]|[2][0-5][0-9]|[1-9][0-9]|[0-9])$/ end ### Creates a new session def init_ses( msg=nil, ses_seed=false ) ## Perform old-session cleanup before creating another # expire_sessions if ses_seed == false ses_seed = @randgen.gen end ## Assigns new timeout for the session timeout = Time.now.to_i + @config[:timeout_first] #@config[:timeout_secs] ## Creates a new session key ses_key = @randgen.gen ## Creates a new cookie key cookie_key = @randgen.gen_many(@config[:cookie_key_multiplier]).join('') ## Makes a new database row for the session, returns its id ses_id = new_ses_id( cookie_key, ses_key, timeout ) ses_sha = SHA1.hexdigest(ses_key+ses_seed) ### Default session data structure, ### Please don't mess with it, unless you know exactly what you are doing. ses_data = { # the time, when the session will time out :timeout => timeout, :plugin_incr => @plugins.incr, # session id, used internally :ses_id => ses_id, # session key, used externally (client sync) :ses_key => ses_sha, # session key, used externally (client cookies) :cookie_key => cookie_key, # user id, map to your own user management code :user_id => 0, # unused in msg context: :_msg_unused => true, # user info, map to your own user management code :user_info => { :lang => RSence.config[:lang] }, # sequence number of session, incremented by each restore :ses_seq => 0, # valuemanager data :values => { :sync => [], # value id's to sync to client :check => [], # value id's to validate in server (from client) :by_id => {} # values by id } } # bind the session data to @sessions by its id @sessions[ ses_id ] = ses_data # map the key back to the id @session_keys[ ses_sha ] = ses_id # map the ses_id to cookie key @session_cookie_keys[ cookie_key ] = ses_id if msg ### Tell the client what the new key is msg.ses_key = ses_key ### Set the session data and id to the message object msg.session = ses_data # Flag the session as new, so associated # plugins know when to create new data msg.new_session = true end # Returns the cookie key, so it can be sent in the response header return cookie_key end def refresh_ses( msg, ses_data, ses_id, ses_key, ses_seed ) # new time-out ses_data[:timeout] = Time.now.to_i + @config[:timeout_secs] if ses_data.has_key?(:ses_seq) ses_data[:ses_seq] += 1 else ses_data[:ses_seq] = 0 end # re-generates the ses_key for each sync if @config[:disposable_keys] # disposes the old (current) ses_key: @session_keys.delete( ses_key ) unless ses_seed ses_seed = ses_key end # gets a new ses_key: ses_key = @randgen.gen ses_sha = SHA1.hexdigest(ses_key+ses_seed) # re-maps the session id to the new key @session_keys[ses_sha] = ses_id # changes the session key in the session data ses_data[:ses_key] = ses_sha # tell the client what its new session key is msg.ses_key = ses_key end if @config[:clone_cookie_sessions] and @clone_targets.has_key? ses_id targets = [] @clone_targets[ ses_id ].length.times do |n| target_id = @clone_targets[ ses_id ].shift target_ses = @sessions[ target_id ] if @sessions.has_key?( target_id ) and @sessions[ target_id ].class == Hash targets.push( target_ses ) end end @clone_targets.delete( ses_id ) if @clone_targets[ ses_id ].empty? msg.cloned_targets = targets unless targets.empty? end ### Bind the session data and id to the message object msg.session = ses_data end def clone_ses( msg, old_data, old_id, old_key, ses_seed ) if @plugins @plugins.delegate( :dump_ses, old_data ) @plugins.delegate( :dump_ses_id, old_id ) end begin old_dump = Marshal.dump( old_data ) if @plugins @plugins.delegate( :load_ses_id, old_id ) @plugins.delegate( :load_ses, old_data ) end ses_data = Marshal.load( old_dump ) rescue => e warn "Unable to clone session #{old_id}, because: #{e.message}" init_ses( msg, ses_seed ) return end old_data[:timeout] = Time.now.to_i + @config[:cloned_session_expires_in] timeout = Time.now.to_i + @config[:timeout_secs] cookie_key = @randgen.gen_many(@config[:cookie_key_multiplier]).join('') ses_key = @randgen.gen ses_sha = SHA1.hexdigest(ses_key+ses_seed) ses_data[:timeout] = timeout ses_data[:ses_key] = ses_key ses_data[:cookie_key] = cookie_key ses_data[:plugin_incr] = @plugins.incr ses_id = new_ses_id( cookie_key, ses_key, timeout ) ses_data[:ses_id] = ses_id ses_data[:ses_seq] = 0 @sessions[ ses_id ] = ses_data @session_keys[ ses_sha ] = ses_id @session_cookie_keys.delete( old_data[:cookie_key] ) @session_cookie_keys[ cookie_key ] = ses_id msg.ses_key = ses_key msg.session = ses_data if @plugins @plugins.delegate( :load_ses_id, ses_id ) @plugins.delegate( :load_ses, ses_data ) end if @clone_targets.has_key? old_id @clone_targets[ old_id ].push( ses_id ) else @clone_targets[ old_id ] = [ ses_id ] end @clone_sources[ ses_id ] = old_id msg.cloned_source = old_data msg.new_session = false msg.restored_session = true end ### Returns the current session data, if the session is valid. ### Otherwise stops the client and returns false. def check_ses( msg, ses_key, ses_seed=false ) # first, check if the session key exists (sync) if @session_keys.has_key?( ses_key ) # get the session's id based on its key ses_id = @session_keys[ ses_key ] # get the session's data based on its id ses_data = @sessions[ ses_id ] if not ses_data.has_key?(:_msg_unused) and @config[:clone_cookie_sessions] and ses_seed clone_ses( msg, ses_data, ses_id, ses_key, ses_seed ) return [true, true] else refresh_ses( msg, ses_data, ses_id, ses_key, ses_seed ) return [true, false] end ## The session was either faked or expired: elsif RSence.args[:debug] ### Tells the client to stop connecting with its session key and reload instead to get a new one. stop_client_with_message( msg, @config[:messages][:invalid_session][:title], @config[:messages][:invalid_session][:descr], @config[:messages][:invalid_session][:uri] ) ## Return failure return [false, false] else msg.error_msg( [ "COMM.Transporter.stop = true;", "setTimeout(function(){window.location.reload(true);},1000);" # "COMM.Transporter.setInterruptAnim('Session failure, reloading in 3 seconds..','#039');", # "setTimeout(function(){COMM.Transporter.setInterruptAnim('Reloading...');},2500);", # "setTimeout(function(){COMM.Transporter.setInterruptAnim('Session failure, reloading in 1 seconds..');},2000);", # "setTimeout(function(){COMM.Transporter.setInterruptAnim('Session failure, reloading in 2 seconds..');},1000);", ] ) return [ false, false ] end end def js_str( str ) return str.to_json.gsub('<','&lt;').gsub('>','&gt;').gsub(/\[\[(.*?)\]\]/,'<\1>') end ## Displays error message and stops the client def stop_client_with_message( msg, title = 'Unknown Issue', descr = 'No issue description given.', uri = RSence.config[:index_html][:respond_address] ) msg.error_msg( [ # "jsLoader.load('default_theme');", # "jsLoader.load('controls');", # "jsLoader.load('servermessage');", "ReloadApp.nu( #{js_str(title)}, #{js_str(descr)}, #{js_str(uri)} );" ] ) end def servlet_cookie_ses( request, response ) cookie_raw = request.cookies if cookie_raw.has_key?('ses_key') cookie_key = cookie_raw['ses_key'].split(';')[0] else cookie_key = nil end if @session_cookie_keys.has_key?( cookie_key ) timeout = Time.now.to_i + @config[:timeout_secs] else cookie_key = init_ses timeout = Time.now.to_i + @config[:timeout_first] end ses_id = @session_cookie_keys[ cookie_key ] ses_data = @sessions[ ses_id ] ses_data[:timeout] = timeout renew_cookie_req_res( request, response, cookie_key, request.fullpath ) return ses_data end ### Checks / Sets cookies def check_cookie( msg, ses_seed ) # default to no cookie key found: cookie_key = false # gets the cookie array from the request object cookie_raw = msg.request.cookies # checks, if a cookie named 'ses_key' is found if cookie_raw.has_key?('ses_key') # gets just the data itself (discards comment, domain, expiration etc) cookie_key = cookie_raw['ses_key'].split(';')[0] end # if a cookie key is found (non-false), checks if it's valid if cookie_key # checks for validity by looking the key up in @session_cookie_keys cookie_key_exist = @session_cookie_keys.has_key?( cookie_key ) # sets the cookie key to false, if it doesn't exist cookie_key = false unless cookie_key_exist end # at this point, the cookie key seems valid: if cookie_key and cookie_key_exist # get the session identifier ses_id = @session_cookie_keys[ cookie_key ] # get the last session key from session data ses_key = @sessions[ses_id][:ses_key] # make additional checks on the session validity (expiry etc) (ses_status, ses_cloned) = check_ses( msg, ses_key, ses_seed ) if ses_status and ses_cloned ses_id = msg.ses_id ses_key = msg.session[:ses_key] cookie_key = msg.session[:cookie_key] @valuemanager.resend_session_values( msg ) elsif ses_status unless @sessions[ses_id].has_key?(:_msg_unused) # delete the old cookie key: @session_cookie_keys.delete( cookie_key ) # get a new cookie key cookie_key = @randgen.gen_many(@config[:cookie_key_multiplier]).join('') # map the new cookie key to the old session identifier @session_cookie_keys[ cookie_key ] = ses_id # binds the new cookie key to the old session data @sessions[ses_id][:cookie_key] = cookie_key end msg.session[:plugin_incr] = @plugins.incr # Sets the restored_session flag of msg to true # It signals plugins to re-set data msg.restored_session = true # Sets the new_session flag of msg to false # It signals plugins to not create new server-side values msg.new_session = false # tells ValueManager to re-send client-side HValue objects # with data to the client @valuemanager.resend_session_values( msg ) # if the session is not valid, make sure to mark the # cookie key as invalid (false) else cookie_key = false end end # if the cookie key failed validation in the # tests above, create a new session instead unless cookie_key cookie_key = init_ses( msg, ses_seed ) ses_status = true end renew_cookie( msg, cookie_key ) ## Return the session status. Actually, ## the value is always true, but future ## versions might not accept invalid ## cookies as new sessions. return ses_status end def renew_cookie( msg, cookie_key ) renew_cookie_req_res( msg.request, msg.response, cookie_key ) end def renew_cookie_req_res( request, response, cookie_key, ses_cookie_path=nil ) # Uses a cookie comment to tell the user what the # cookie is for, change it to anything valid in the # configuration. ses_cookie_comment = @config[:ses_cookie_comment] ## mod_rewrite changes the host header to x-forwarded-host: if request.header.has_key?('x-forwarded-host') domain = request.header['x-forwarded-host'] ## direct access just uses host (at least mongrel ## does mod_rewrite header translation): else domain = request.host end if domain == 'localhost' warn "Warning: Cookies won't be set for 'localhost'. Use '127.0.0.1' instead." if RSence.args[:debug] return end if request.header.has_key?( 'x-forwarded-port' ) server_port = request.header['x-forwarded-port'] else server_port = request.port end ## if the host address is a real domain ## (not just hostname or 'localhost'), ## but not an ip-address, prepend it with ## a dot to accept wildcards (useful for ## dns-load-balanced server configurations) if not @ipv4_reg.match(domain) and domain.include?('.') ses_cookie_domain = ".#{domain}" ## Otherwise, use the domain as-is else ses_cookie_domain = domain end ## uses the timeout to declare the max age ## of the cookie, allows the browser to delete ## it, when it expires. ses_cookie_max_age = @config[:timeout_secs] # IE not support Max-Age. So, have to send Expires, too. ses_cookie_expires = CGI.rfc1123_date( Time.now + ses_cookie_max_age ) ## Only match the handshaking address of rsence, ## prevents unnecessary cookie-juggling in sync's if @config[:trust_cookies] ses_cookie_path = '/' elsif ses_cookie_path == nil ses_cookie_path = RSence.config[:broker_urls][:hello] end ## Formats the cookie to string ## (through array, to keep it readable in the source) ses_cookie_arr = [ "ses_key=#{cookie_key}", "Path=#{ses_cookie_path}", "Port=#{server_port}", "Max-Age=#{ses_cookie_max_age}", "Expires=#{ses_cookie_expires}", "Comment=#{ses_cookie_comment}", "Domain=#{ses_cookie_domain}" ] ### Sets the set-cookie header response['Set-Cookie'] = ses_cookie_arr.join('; ') end def expire_ses_by_req( req, res ) cookie_raw = req.cookies # checks, if a cookie named 'ses_key' is found if cookie_raw.has_key?('ses_key') # gets just the data itself (discards comment, domain, expiration etc) cookie_key = cookie_raw['ses_key'].split(';')[0] end # if a cookie key is found (non-false), checks if it's valid if cookie_key # checks for validity by looking the key up in @session_cookie_keys cookie_key_exist = @session_cookie_keys.has_key?( cookie_key ) # sets the cookie key to false, if it doesn't exist cookie_key = false unless cookie_key_exist end # at this point, the cookie key seems valid: if cookie_key and cookie_key_exist # get the session identifier ses_id = @session_cookie_keys[ cookie_key ] # Expire the session # expire_session( ses_id ) return true end return false end ### Creates a message and checks the session def init_msg( request, response, options = { :cookies => false, :servlet => false } ) cookies = options[:cookies] if options.has_key?(:query) query = options[:query] else query = request.query end ## The 'ses_id' request query key is required. ## The client defaults to '0', which means the ## client needs to be initialized. ## The client's ses_id is the server's ses_key. if not options.has_key?( :ses_key ) return Message.new( @transporter, request, response, options ) else ## get the ses_key from the request query: ses_key = options[:ses_key] ## The message object binds request, response ## and all user/session -related data to one ## object, which is passed around where ## request/response/user/session -related ## data is needed. msg = Message.new( @transporter, request, response, options ) ## The client tells that its ses_key is '0', ## until the server tells it otherwise. (req_num, ses_seed) = ses_key.split(':1:') if req_num == '0' # If Broker encounters a '/hello' request, it # sets cookies to true. # # It means that a session should have its cookies # checked. # if cookies ses_status = check_cookie( msg, ses_seed ) # Otherwise, a new session is created: else init_ses( msg, ses_seed ) ses_status = true end # for non-'0' ses_keys: else ## Validate the session key ses_status = check_ses( msg, ses_seed )[0] ## Renew the cookie even when the request is a "x" (not "hello") if @config[:session_cookies] and ses_status renew_cookie( msg, msg.session[:cookie_key] ) end end # /ses_key ## msg.ses_valid is false by default, meaning ## it's not valid or hasn't been initialized. msg.ses_valid = ses_status return msg end # /ses_key end # /init_msg end end
class ChangeHeadersAssoc < ActiveRecord::Migration def change remove_column :headers, :phase1_id add_reference :headers, :phase1, index: true end end
begin require 'aws-sdk' rescue LoadError raise LoadError.new("Missing required 'aws-sdk'. Please 'gem install "\ "aws-sdk' and require it in your application, or "\ "add: gem 'aws-sdk' to your Gemfile.") end module SitemapGenerator # Class for uploading the sitemaps to an S3 bucket using the plain AWS SDK gem class AwsSdkAdapter # @param [String] bucket name of the S3 bucket # @param [Hash] opts alternate means of configuration other than ENV # @option opts [String] :aws_access_key_id instead of ENV['AWS_ACCESS_KEY_ID'] # @option opts [String] :aws_region instead of ENV['AWS_REGION'] # @option opts [String] :aws_secret_access_key instead of ENV['AWS_SECRET_ACCESS_KEY'] # @option opts [String] :path use this prefix on the object key instead of 'sitemaps/' def initialize(bucket, opts = {}) @bucket = bucket @aws_access_key_id = opts[:aws_access_key_id] || ENV['AWS_ACCESS_KEY_ID'] @aws_region = opts[:aws_region] || ENV['AWS_REGION'] @aws_secret_access_key = opts[:aws_secret_access_key] || ENV['AWS_SECRET_ACCESS_KEY'] @path = opts[:path] || 'sitemaps/' end # Call with a SitemapLocation and string data def write(location, raw_data) SitemapGenerator::FileAdapter.new.write(location, raw_data) credentials = Aws::Credentials.new(@aws_access_key_id, @aws_secret_access_key) s3 = Aws::S3::Resource.new(credentials: credentials, region: @aws_region) s3_object_key = "#{@path}#{location.path_in_public}" s3_object = s3.bucket(@bucket).object(s3_object_key) content_type = location[:compress] ? 'application/x-gzip' : 'application/xml' s3_object.upload_file(location.path, acl: 'public-read', cache_control: 'private, max-age=0, no-cache', content_type: content_type) end end end
class SimplySearchableGenerator < Rails::Generator::NamedBase def manifest record do |m| m.template "search.html.erb", "app/views/#{plural_name}/search.html.erb" end end end
class ResultsMailer < ActionMailer::Base default from: Rails.configuration.results_sender def results(recipient) @results = VoteResult.week(DateTime.now.beginning_of_day).order('weight DESC').limit(5) mail(to: recipient, subject: 'AEWOT Voting Results') end end
# frozen_string_literal: true require 'rails_helper' describe 'dra_score_students', type: :request do let(:headers) do { 'Accept' => 'application/vnd.api+json', 'Content-Type' => 'application/vnd.api+json' } end let(:params) { { dra_score_student: dra_score_student }.to_json } subject do request! response end describe 'GET index' do before do dra_score_students end let(:request!) { get dra_score_students_path, headers: headers } context 'when there are no dra_score_students' do let(:dra_score_students) {} it { is_expected.to have_http_status(:ok) } it 'should return an empty array' do body = JSON.parse(subject.body) expect(body).to be_empty end end context 'when there are dra_score_students' do let(:dra_score_students) { create_list(:dra_score_student, 2) } it { is_expected.to have_http_status(:ok) } it 'should return a list of dra_score_students' do body = JSON.parse(subject.body) expect(body.size).to eq(dra_score_students.size) body.each_with_index do |dra_score_student, index| expect(dra_score_student['id']).to eq(dra_score_students[index].id) expect(dra_score_student['dra_score_id']) .to eq(dra_score_students[index].dra_score_id) expect(dra_score_student['student_id']) .to eq(dra_score_students[index].student_id) expect(dra_score_student['score_date'].to_date) .to eq(dra_score_students[index].score_date) end end end end describe 'GET show' do before do dra_score_student_id end let(:request!) { get dra_score_student_path(dra_score_student_id) } context 'when the dra_score_student can be found' do let(:dra_score_student) { create(:dra_score_student) } let(:dra_score_student_id) { dra_score_student.id } it { is_expected.to have_http_status(:ok) } it 'should return a dra_score_student' do body = JSON.parse(subject.body) expect(body['id']).to eq(dra_score_student.id) expect(body['dra_score_id']).to eq(dra_score_student.dra_score_id) expect(body['student_id']).to eq(dra_score_student.student_id) expect(body['score_date'].to_date).to eq(dra_score_student.score_date) end end context 'when the dra_score_student can not be found' do let(:dra_score_student_id) { SecureRandom.uuid } it { is_expected.to have_http_status(:not_found) } it 'should return an error message' do body = JSON.parse(subject.body) expect(body) .to eq( "Couldn't find DraScoreStudent with 'id'=#{dra_score_student_id}" ) end end end describe 'POST create' do let(:request!) do post dra_score_students_path, params: params, headers: headers end context 'when the dra_score_student attributes are valid' do let(:dra_score) { create(:dra_score) } let(:dra_score_student) do attributes_for( :dra_score_student, dra_score_id: dra_score.id, student_id: student.id ) end let(:student) { create(:student) } it { is_expected.to have_http_status(:ok) } it 'should return a success message' do message = JSON.parse(subject.body)['message'] expect(message).to eq(I18n.t('dra_score_students.create.success')) end end context 'when the dra_score_student attributes are not valid' do let(:dra_score_student) do attributes_for(:dra_score_student, score_date: nil) end it { is_expected.to have_http_status(:unprocessable_entity) } it 'should return a success message' do message = JSON.parse(subject.body)['message'] expect(message).to eq(I18n.t('dra_score_students.create.failure')) end end end describe 'PATCH update' do let(:request!) do patch dra_score_student_path(dra_score_student_id), params: params, headers: headers end context 'when the dra_score_student is valid' do let(:params) do { dra_score_student: { score_date: dra_score_student.score_date + 1 } }.to_json end let(:dra_score_student) { create(:dra_score_student) } let(:dra_score_student_id) { dra_score_student.id } it { is_expected.to have_http_status(:ok) } it 'they see a success message' do body = JSON.parse(subject.body) expect(body['message']) .to eq(I18n.t('dra_score_students.update.success')) expect(body['resource']['score_date'].to_date) .to eq(dra_score_student.score_date + 1) end end context 'when the dra_score_student is not valid' do let(:params) do { dra_score_student: { score_date: 'test' } }.to_json end let(:dra_score_student) { create(:dra_score_student) } let(:dra_score_student_id) { dra_score_student.id } it { is_expected.to have_http_status(:unprocessable_entity) } it 'should return a success message' do message = JSON.parse(subject.body)['message'] expect(message).to eq(I18n.t('dra_score_students.update.failure')) end end context 'when the dra_score_student is not found' do let(:params) do { dra_score_student: { score_date: dra_score_student.score_date + 1 } }.to_json end let(:dra_score_student) { create(:dra_score_student) } let(:dra_score_student_id) { SecureRandom.uuid } it { is_expected.to have_http_status(:not_found) } it 'should return an error message' do body = JSON.parse(subject.body) expect(body) .to eq( "Couldn't find DraScoreStudent with 'id'=#{dra_score_student_id}" ) end end end describe 'DELETE destory' do let(:request!) do delete dra_score_student_path(dra_score_student_id), params: params, headers: headers end context 'when the student exists' do let(:dra_score_student) { create(:dra_score_student) } let(:dra_score_student_id) { dra_score_student.id } it { is_expected.to have_http_status(:ok) } it 'they see a success message' do body = JSON.parse(subject.body) expect(body['message']) .to eq(I18n.t('dra_score_students.destroy.success')) end end context 'when the student does not exist' do let(:dra_score_student) { create(:dra_score_student) } let(:dra_score_student_id) { SecureRandom.uuid } it { is_expected.to have_http_status(:not_found) } it 'should return an error message' do body = JSON.parse(subject.body) expect(body) .to eq( "Couldn't find DraScoreStudent with 'id'=#{dra_score_student_id}" ) end end end end
class ApplicationController < ActionController::Base protect_from_forgery before_filter :set_locale rescue_from Exception, :with => :catch_exception if Rails.env.production? rescue_from Invite::NoInvitationException, :with => :catch_no_invitation_exception protected def set_locale I18n.locale = extract_locale_from_accept_language_header end def catch_exception e logger.info e.to_yaml end def catch_no_invitation_exception e redirect_to sorry_page_path end private def extract_locale_from_accept_language_header http_accept_language = request.env['HTTP_ACCEPT_LANGUAGE'] if http_accept_language.present? http_accept_language.scan(/^[a-z]{2}/).first else :en end end end
# TL;DR: YOU SHOULD DELETE THIS FILE # # This file was generated by Cucumber-Rails and is only here to get you a head start # These step definitions are thin wrappers around the Capybara/Webrat API that lets you # visit pages, interact with widgets and make assertions about page content. # # If you use these step definitions as basis for your features you will quickly end up # with features that are: # # * Hard to maintain # * Verbose to read # # A much better approach is to write your own higher level step definitions, following # the advice in the following blog posts: # # * http://benmabey.com/2008/05/19/imperative-vs-declarative-scenarios-in-user-stories.html # * http://dannorth.net/2011/01/31/whose-domain-is-it-anyway/ # * http://elabs.se/blog/15-you-re-cuking-it-wrong # require 'uri' require 'cgi' require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "paths")) require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "selectors")) module WithinHelpers def with_scope(locator) locator ? within(*selector_for(locator)) { yield } : yield end end World(WithinHelpers) # Single-line step scoper When /^(.*) within (.*[^:])$/ do |step, parent| with_scope(parent) { When step } end # Multi-line step scoper When /^(.*) within (.*[^:]):$/ do |step, parent, table_or_string| with_scope(parent) { When "#{step}:", table_or_string } end When /^(?:|I )press "([^"]*)"$/ do |button| click_button(button) end When /^(?:|I )follow "([^"]*)"$/ do |link| click_link(link) end And /^select box "([^"]*)" is selected with "([^"]*)"$/ do |dropdown, selected_text| assert page.has_select?(dropdown, selected: selected_text) end When /^(?:|I )fill in "([^"]*)" with "([^"]*)"$/ do |field, value| fill_in(field, :with => value) end When /^(?:|I )fill in "([^"]*)" for "([^"]*)"$/ do |value, field| fill_in(field, :with => value) end Given /^I am a registered user$/ do @user = User.create!({:uid => 1, :email => "orlandoscarpa95@gmail.com", :password => "10101010", :password_confirmation => "10101010", :roletype => true }) @user.remove_role(:user) @user.add_role(:admin) end Given /^I am on the sign up page$/ do step "I am on the home page" if @user == nil step 'I follow "Esci"' end step 'I follow "Registrati"' end Given /^I am on the home page$/ do visit root_path end Given /^I am on the login page$/ do step "I am on the home page" if @user == nil step 'I follow "Esci"' end step 'I follow "Accedi"' end And /^I am on my profile page$/ do visit edit_user_registration_path end When /^I log in$/ do steps %Q{ Given I am on the login page When I fill in "Email" with "orlandoscarpa95@gmail.com" And I fill in "Password" with "10101010" And I press "Login" Then I should see "Profilo" And I should see "Statistiche" And I should see "Esci" } end When /^(?:|I )attach the file "([^"]*)" to "([^"]*)"$/ do |path, field| attach_file(field, File.expand_path(path)) end Then /^I should be on the login page$/ do visit new_user_session_path end Then /^I should be on the sign up page$/ do visit new_user_registration_path end Then /^I should be on the home page$/ do visit root_path end Then /^(?:|I )should see "([^"]*)"$/ do |text| if page.respond_to? :should expect(page).to have_content(text) else assert page.has_content?(text) end end Then /^(?:|I )should see \/([^\/]*)\/$/ do |regexp| regexp = Regexp.new(regexp) if page.respond_to? :should expect(page).to have_xpath('//*', :text => regexp) else assert page.has_xpath?('//*', :text => regexp) end end Then /^I should see my avatar$/ do User.last.avatar_file_name != nil end When(/^I select the option containing "([^\"]*)" in "([^\"]*)"$/) do |text, field| select text, from: field end And /^show me the page$/ do save_and_open_page end When /^I log out$/ do steps %Q{ When I am on the home page And I follow "Esci" Then I should be on the home page } end
#!/usr/bin/env rspec # Encoding: utf-8 require 'spec_helper' provider_class = Puppet::Type.type(:package).provider(:portagegt) describe provider_class do describe '#install' do describe 'slot' do before :each do # Stub some provider methods to avoid needing the actual software # installed, so we can test on whatever platform we want. provider_class.stubs(:command).with(:emerge).returns('/usr/bin/emerge') Puppet.expects(:warning).never end # Good [ { options: { name: 'mysql:2' }, command: ['/usr/bin/emerge', 'mysql:2'] }, { options: { name: 'mysql:2.2' }, command: ['/usr/bin/emerge', 'mysql:2.2'] }, { options: { name: 'mysql', package_settings: { 'slot' => '2' } }, command: ['/usr/bin/emerge', 'mysql:2'] }, { options: { name: 'mysql', package_settings: { 'slot' => '2.2' } }, command: ['/usr/bin/emerge', 'mysql:2.2'] }, { options: { name: 'mysql', package_settings: { 'slot' => 2 } }, command: ['/usr/bin/emerge', 'mysql:2'] }, { options: { name: 'mysql', package_settings: { 'slot' => 2.2 } }, command: ['/usr/bin/emerge', 'mysql:2.2'] }, { options: { name: 'mysql', package_settings: { 'slot' => 'word' } }, command: ['/usr/bin/emerge', 'mysql:word'] }, { options: { name: 'mysql:word', package_settings: { 'slot' => 'word' } }, command: ['/usr/bin/emerge', 'mysql:word'] }, { options: { name: 'mysql:word' }, command: ['/usr/bin/emerge', 'mysql:word'] } ].each do |c| it c[:options].inspect do provider = provider_class.new(pkg(c[:options])) provider.expects(:execute).with(c[:command]) provider.install end end # Bad [ { options: { name: 'dev-lang/php:5.6', package_settings: { 'slot' => 5.5 } }, error: 'Slot disagreement on Package[dev-lang/php:5.6]' } ].each do |c| it c[:options].inspect + ' fails' do expect do provider = provider_class.new(pkg(c[:options])) provider.install end.to raise_error(Puppet::Error, c[:error]) end end end end end
require('minitest/autorun') require('minitest/reporters') Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new require_relative('../bear') require_relative('../fish') class BearTest < MiniTest::Test def setup @bear1 = Bear.new('Poo', :cuddly) @fish1 = Fish.new('Goldie') end def test_get_name assert_equal('Poo', @bear1.name) end def test_get_type assert_equal(:cuddly, @bear1.type) end def test_get_stomach_contents_at_start assert_equal(0, @bear1.stomach_contents) end def test_eat_fish @bear1.eat_fish(@fish1) assert_equal(1, @bear1.stomach_contents) end def test_roar assert_equal('Roar', @bear1.roar) end def test_food_count @bear1.eat_fish(@fish1) assert_equal(1, @bear1.stomach_contents) end end
require 'active_model' require 'lib/validators/iso31661_alpha2' require 'lib/validators/iso8601' RSpec.describe Contact::Ident, db: false do let(:ident) { described_class.new } describe 'country code' do it_behaves_like 'iso31661_alpha2' do let(:model) { ident } let(:attribute) { :country_code } end end describe 'code validation' do it 'rejects absent' do ident.code = nil ident.validate expect(ident.errors).to be_added(:code, :blank) end context 'when type is :birthday' do let(:ident) { described_class.new(type: 'birthday') } it_behaves_like 'iso8601' do let(:model) { ident } let(:attribute) { :code } end end context 'when type is not :birthday' do let(:ident) { described_class.new(type: 'priv') } it 'accepts any' do ident.code = '%123456789%' ident.validate expect(ident.errors).to_not include(:code) end end context 'when country code is EE' do context 'when type is :priv' do let(:ident) { described_class.new(country_code: 'EE', type: 'priv') } it 'rejects invalid' do ident.code = 'invalid' ident.validate expect(ident.errors).to be_added(:code, :invalid_national_id, country: 'Estonia') end it 'accepts valid' do ident.code = '47101010033' ident.validate expect(ident.errors).to_not be_added(:code, :invalid_national_id, country: 'Estonia') end end context 'when ident type is :org' do let(:ident) { described_class.new(country_code: 'EE', type: 'org') } it 'rejects invalid' do ident.code = '1' * 7 ident.validate expect(ident.errors).to be_added(:code, :invalid_reg_no, country: 'Estonia') end it 'accepts valid length' do ident.code = '1' * 8 ident.validate expect(ident.errors).to_not be_added(:code, :invalid_reg_no, country: 'Estonia') end end end context 'when ident country code is not EE' do let(:ident) { described_class.new(country_code: 'US') } it 'accepts any' do ident.code = 'test-123456789' ident.validate expect(ident.errors).to_not include(:code) end end it 'translates :invalid_national_id error message' do expect(ident.errors.generate_message(:code, :invalid_national_id, country: 'Germany')) .to eq('does not conform to national identification number format of Germany') end it 'translates :invalid_reg_no error message' do expect(ident.errors.generate_message(:code, :invalid_reg_no, country: 'Germany')) .to eq('does not conform to registration number format of Germany') end end describe 'type validation' do before do allow(described_class).to receive(:types).and_return(%w(valid)) end it 'rejects absent' do ident.type = nil ident.validate expect(ident.errors).to be_added(:type, :blank) end it 'rejects invalid' do ident.type = 'invalid' ident.validate expect(ident.errors).to be_added(:type, :inclusion) end it 'accepts valid' do ident.type = 'valid' ident.validate expect(ident.errors).to_not be_added(:type, :inclusion) end end describe 'country code validation' do it 'rejects absent' do ident.country_code = nil ident.validate expect(ident.errors).to be_added(:country_code, :blank) end end describe 'mismatch validation' do let(:ident) { described_class.new(type: 'test', country_code: 'DE') } before do mismatches = [Contact::Ident::MismatchValidator::Mismatch.new('test', Country.new('DE'))] allow(Contact::Ident::MismatchValidator).to receive(:mismatches).and_return(mismatches) end it 'rejects mismatched' do ident.validate expect(ident.errors).to be_added(:base, :mismatch, type: 'test', country: 'Germany') end it 'accepts matched' do ident.validate expect(ident.errors).to_not be_added(:base, :mismatch, type: 'another-test', country: 'Germany') end it 'translates :mismatch error message' do expect(ident.errors.generate_message(:base, :mismatch, type: 'test', country: 'Germany')) .to eq('Ident type "test" is invalid for Germany') end end describe '::types' do it 'returns types' do types = %w[ org priv birthday ] expect(described_class.types).to eq(types) end end describe '#birthday?' do context 'when type is birthday' do subject(:ident) { described_class.new(type: 'birthday') } it { is_expected.to be_birthday } end context 'when type is not birthday' do subject(:ident) { described_class.new(type: 'priv') } it { is_expected.to_not be_birthday } end end describe '#national_id?' do context 'when type is priv' do subject(:ident) { described_class.new(type: 'priv') } it { is_expected.to be_national_id } end context 'when type is not' do subject(:ident) { described_class.new(type: 'org') } it { is_expected.to_not be_national_id } end end describe '#reg_no?' do context 'when type is birthday' do subject(:ident) { described_class.new(type: 'org') } it { is_expected.to be_reg_no } end context 'when type is not birthday' do subject(:ident) { described_class.new(type: 'priv') } it { is_expected.to_not be_reg_no } end end describe '#country' do let(:ident) { described_class.new(country_code: 'US') } it 'returns country' do expect(ident.country).to eq(Country.new('US')) end end describe '#==' do let(:ident) { described_class.new(code: 'test', type: 'test', country_code: 'US') } context 'when code, type and country code are the same' do let(:another_ident) { described_class.new(code: 'test', type: 'test', country_code: 'US') } it 'returns true' do expect(ident).to eq(another_ident) end end context 'when code, type and country code are not the same' do let(:another_ident) { described_class.new(code: 'another-test', type: 'test', country_code: 'US') } it 'returns false' do expect(ident).to_not eq(another_ident) end end end end
class Api::V1::CurrentUserController < ApplicationController def index render json: active_user end end
class BalloonsController < ApplicationController respond_to :html def index end def new @balloon = Balloon.new respond_with @balloon end def create # refactor this action @balloon = Balloon.new balloon_params if @balloon.save respond_with @balloon, location: balloons_path else render :new end end def edit @balloon = Balloon.find params[:id] respond_with @balloon end private def balloon_params params.require(:balloon).permit(:name, :color, :altitude, :location) end end
class AddPasswordToEmployees < ActiveRecord::Migration def change add_column :employees,:password_hash,:string add_column :employees,:password_salt,:string end end
class ChangeFieldIdsToIntegers < ActiveRecord::Migration def change change_column :field_conditions, :field_id, 'integer USING CAST(field_id AS integer)' change_column :field_conditions, :user_id, 'integer USING CAST(user_id AS integer)' change_column :events, :field_id, 'integer USING CAST(field_id AS integer)' end end
class CreatePumps < ActiveRecord::Migration def change create_table :pumps do |t| t.string :pumpmodel t.string :pumpDiameter t.decimal :pumplineNumber t.decimal :stroke t.decimal :strokeTimes t.decimal :traffic t.decimal :pressure t.decimal :power t.string :overallsize t.decimal :weight t.string :manufacture t.string :manufactureContact t.string :picture t.string :remark t.timestamps end end end
class SettingsController < ApplicationController before_action :authenticate_user! def index @new_tag = Tag.new(user: current_user) @new_location = Location.new(user: current_user) @new_time_range = TimeRange.new(user: current_user) @new_day_range = DayRange.new(user: current_user) end end
class CreateReservas < ActiveRecord::Migration def change create_table :reservas do |t| t.references :escenario, index: true, foreign_key: true t.references :user, index: true, foreign_key: true t.date :fecha t.datetime :horainicio t.datetime :horafin t.timestamps null: false end end end
require 'rails_helper' RSpec.describe 'Disbursements', type: :request do let(:merchant) { create(:merchant) } let(:merchant_two) { create(:merchant) } let!(:disbursement) { create(:disbursement, merchant_id: merchant.id, total: 200) } let!(:disbursement_two) { create(:disbursement, merchant_id: merchant_two.id, total: 300) } describe 'GET' do context 'when no merchant_id' do it 'returns all disbursements' do get '/disbursements' expect(response).to have_http_status(200) resp = parsed_response(response.body) expect(resp['RECORDS'].count).to eq(2) end end context 'when merchant_id' do it 'returns all disbursements for given merchant' do get '/disbursements', params: { merchant_id: merchant.id } expect(response).to have_http_status(200) resp = parsed_response(response.body) expect(resp['RECORDS'].count).to eq(1) expect(resp['RECORDS'].first).to match( hash_including({ 'id' => disbursement.id, 'fee' => 0.95, 'merchant_id' => merchant.id, 'order_id' => disbursement.order_id, 'total' => '200.0' }) ) end it 'returns empty when given start_date and end_date' do get '/disbursements', params: { merchant_id: merchant.id, start_date: Date.current - 1.week, end_date: Date.current - 1.day } expect(response).to have_http_status(200) resp = parsed_response(response.body) expect(resp['RECORDS'].count).to eq(0) end end end describe 'POST' do context 'when no merchant_id' do it 'returns 422' do post '/disbursements' expect(response).to have_http_status(422) resp = parsed_response(response.body) expect(resp).to eq({ 'error' => 'Mercant not valid' }) end end context 'when merchant_id' do it 'returns 200' do post '/disbursements', params: { merchant_id: merchant.id } expect(response).to have_http_status(200) resp = parsed_response(response.body) expect(resp).to include( { 'start_date' => be_an(String), 'end_date' => be_an(String), 'merchant_id' => merchant.id, 'status' => 'calculating' } ) end end end def parsed_response(body) JSON.parse(body).to_h end end
module Ripple class TokenController < NetworkController layout 'tabs' before_action :set_token before_action :breadcrumb def show; end private def set_token @token = params[:address] @token = @network[:currency] if native_token? end def native_token? @token == @network[:currency] end def breadcrumb return if action_name != 'show' end end end
class Pnameforms::Piece16sController < ApplicationController before_action :set_piece16, only: [:show, :edit, :update, :destroy] # GET /piece16s # GET /piece16s.json def index @pnameform = Pnameform.find(params[:pnameform_id]) @piece16s = @pnameform.piece16s end # GET /piece16s/16 # GET /piece16s/16.json def show @pnameform = Pnameform.find(params[:pnameform_id]) @piece16s = Piece16.all end # GET /piece16s/new def new @pnameform = Pnameform.find(params[:pnameform_id]) @piece16 = current_user.piece16s.build end # GET /piece16s/16/edit def edit @pnameform = Pnameform.find(params[:pnameform_id]) @piece16.pnameform = @pnameform end # POST /piece16s # POST /piece16s.json def create @pnameform = Pnameform.find(params[:pnameform_id]) @piece16 = current_user.piece16s.build(piece16_params) @piece16.pnameform = @pnameform respond_to do |format| if @piece16.save format.html { redirect_to pnameform_piece16s_path(@pnameform), notice: 'Piece16 was successfully created.' } format.json { render :show, status: :created, location: @piece16 } else format.html { render :new } format.json { render json: @piece16.errors, status: :unprocessable_entity } end end end # PATCH/PUT /piece16s/16 # PATCH/PUT /piece16s/16.json def update @pnameform = Pnameform.find(params[:pnameform_id]) @piece16.pnameform = @pnameform respond_to do |format| if @piece16.update(piece16_params) format.html { redirect_to pnameform_piece16s_path(@pnameform), notice: 'Piece16 was successfully updated.' } format.json { render :show, status: :ok, location: @piece16 } else format.html { render :edit } format.json { render json: @piece16.errors, status: :unprocessable_entity } end end end # DELETE /piece16s/16 # DELETE /piece16s/16.json def destroy @pnameform = Pnameform.find(params[:pnameform_id]) @piece16 = Piece16.find(params[:id]) title = @piece16.name if @piece16.destroy flash[:notice] = "\"#{title}\" was deleted successfully." redirect_to pnameform_piece16s_path(@pnameform) else flash[:error] = "There was an error deleting." render :show end end private # Use callbacks to share common setup or constraints between actions. def set_piece16 @piece16 = Piece16.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def piece16_params params.require(:piece16).permit(:name, :user_id) end end
class Podcast attr_accessor :name def initialize(name) @name = name @epizodes = [] @count = 1 end def <<(epizode) epizode.id = @count @count += 1 @epizodes << epizode end def find(filter) if filter[:name] return @epizodes.select do |e| e.name.downcase.include?(filter[:name].downcase) end end @epizodes.select do |e| is_valid = true filter[:description].each do |f| is_valid = false unless e.description.downcase.include?(f.downcase) end is_valid end end def info output = '' output += "Podcast: #{name}\n" output += "Total episodes: #{@epizodes.size}\n" output += "Total duration: #{@epizodes.map{|e| e.minutes}.reduce(:+)}\n" @epizodes.each do |e| output += '==========' output += "\n" output += "Episode #{e.id}\n" output += "Name: #{e.name}\n" output += e.description output += "\n" output += "Duration: #{e.minutes} minutes" output += "\n" end p output end end class Episode attr_accessor :id, :name, :description, :minutes def initialize(name, description, minutes) @name = name @description = description @minutes = minutes end end
class OpenSource::Category attr_accessor :name attr_reader :projects #Still not adding projects to category @@all = [] def initialize(name) @name = name self.save @projects = [] end def save @@all << self self end def self.all @@all end def self.destroy_all all.clear end def self.find_by_name(name) name = name.split("-").join(" ").downcase all.detect {|c| c.name.downcase == name} end end
feature 'StoriesController' do let!(:user){ create(:user) } let!(:place){ create(:place) } let!(:picture){ create(:picture) } let!(:story){ create(:story, user: user, place: place, picture: picture) } describe 'stories associations' do context 'has_many and belongs_to' do it 'has correct associations' do expect(story.place).to be place expect(story.picture).to be picture expect(story.user).to be user end end end describe 'story services' do context 'get stories' do it 'gets story by ID, get story by ID with error' do visit("/stories/#{story.id}.json") response = JSON.parse(page.body) expect(response['success']).to be true expect(response['result']['id']).to eql story.id visit("/stories/#{story.id}22.json") response = JSON.parse(page.body) expect(response['success']).to be false expect(response['error']).to eql "El momento de verdad que estás buscando no existe" end it 'gets stories by place correctly, gets stories by place with error' do story = Story.create(place_id: place.id, picture_id: picture.id, user_id: user.id, description: "test test", vote_plus: 10, vote_minus:5) visit("/stories/by_place.json?place_id=202020") response = JSON.parse(page.body) expect(response['success']).to be true expect(response['result'].length).to eql 0 visit("/stories/by_place.json?place_id=#{place.id}") response = JSON.parse(page.body) expect(response['success']).to be true expect(response['result'].length).to eql 2 expect(response['result'][0]["active"]).to be true visit("/stories/by_place.json") response = JSON.parse(page.body) expect(response['success']).to be false expect(response['error']).to eql "Es necesario seleccionar un lugar para obtener los momentos de verdad" end end context 'mark stories' do it 'mark story as true, mark story as false' do page1 = nil page2 = nil expect(story.vote_plus).to eql 10 with_rack_test_driver do page1 = page.driver.post "#{stories_path}/#{story.id}/mark.json", {real: true} end response1 = JSON.parse(page1.body) expect(response1['success']).to be true expect(response1['result']['vote_plus']).to eql 11 expect(story.vote_minus).to eql 45 with_rack_test_driver do page2 = page.driver.post "#{stories_path}/#{story.id}/mark.json", {real: false} end response2 = JSON.parse(page2.body) expect(response2['success']).to be true expect(response2['result']['vote_minus']).to eql 46 end end context 'create story' do it 'should create story successfuly' do test_file = "moto.jpg" picture = Rack::Test::UploadedFile.new(Rails.root + "spec/images/#{test_file}", 'image/jpg') user = {name: "Ricardo Rosas", email: "test@starts.com"} story = {place_id: place.id, user_attributes: user, picture: picture, description: "Description test"} new_story_request = {story: story} with_rack_test_driver do page.driver.post "#{stories_path}.json", new_story_request end response = JSON.parse(page.body) expect(response['success']).to be true story = response['result'] expect(story['user']['email']).to eql "test@starts.com" expect(User.last.email).to eql "test@starts.com" expect(story['description']).to eql "Description test" expect(story['picture']['id']).to be Picture.last.id Cloudinary::Uploader.destroy(Story.last.picture.uid) end it 'should show errors on story creation' do user = {name: "Ricardo Rosas", email: "test@starts.com"} story = {place_id: place.id, user_attributes: user, description: "Description test"} new_story_request = {story: story} with_rack_test_driver do page.driver.post "#{stories_path}.json", new_story_request end response = JSON.parse(page.body) expect(response['success']).to be false expect(response['error']).to eql "no implicit conversion of nil into String" end end end end
class ApplicationController < ActionController::Base protect_from_forgery before_filter :current_p def current_p #method that makes sure all places/events on the site are current @places = Place.where("date >= ?", Date.today) @places end private def current_user #if user is logged in @current_user ||= User.find(session[:user_id]) if session[:user_id] end helper_method :current_user #turns this into a helper method so it can be used in views def authorize redirect_to login_url, alert: "You must log in to add or edit events" if current_user.nil? end end
# frozen_string_literal: true Sequel.migration do change do create_table(:dynflow_scheduled_plans) do foreign_key :execution_plan_uuid, :dynflow_execution_plans, type: String, size: 36, fixed: true index :execution_plan_uuid column :start_at, Time index :start_at column :start_before, Time column :data, String, text: true column :args_serializer, String end end end
class Guest < ActiveRecord::Base # attr_accessible :title, :body has_one :user has_many :scraps has_one :guest_rsvp attr_accessible :name, :surname, :email, :user_id validates_presence_of :email, :on => :create validates_presence_of :name validates_uniqueness_of :email end
#!/usr/local/bin/ruby # Guess My Number # ------------------------------------------------------------------------------ # From: Head First Ruby puts "Welcome to 'Get My Number!'" # The difference between "puts" and "print" is that "puts" adds a new-line cha- # racter at the end of the line. # Sometimes you don't have to specify a receiver for a method call. For example # in the "puts" "p" "print" methods. These methods are so important, and so com- # monly used,that they have been included in Ruby's top-level execution environ- # ment. Methods defined at this level are available to call anywhere in your Ru- # by code, without specifying a receiver. # The "puts" method can take more than one argument; just separate the arguments # with commas. Each argument gets printed on its own line. puts "first line", "second line", "third line" print "What's your name? " input = gets puts "Welcome, #{input}"
require 'test_helper' class ReviewsApi < ActionDispatch::IntegrationTest describe 'Reviews' do it 'should get a list of reviews for a product' do get "/products/#{products(:one).id}" answer = JSON.parse(response.body, symbolize_names: true)[:product] response.status.must_equal 200 response.content_type.must_equal Mime::JSON answer[:reviews].size.must_equal( Product.find(products(:one).id).reviews.count) answer[:reviews][0][:body].must_equal 'Amazing' answer[:reviews][0][:author].must_equal 'good@good.com' answer[:reviews][0][:stars].must_equal 5 end it 'should create a review' do post '/reviews', { body: 'I love this!', stars: 5, author: 'joe@joe.com', product_id: 2 }.to_json, { 'Accept' => 'application/json', 'Content-Type' => 'application/json' } review = JSON.parse(response.body, symbolize_names: true)[:review] response.status.must_equal 201 response.content_type.must_equal Mime::JSON review[:body].must_equal 'I love this!' review[:stars].must_equal 5 review[:author].must_equal 'joe@joe.com' Review.last.body.must_equal 'I love this!' end end end
class Admin::AdminController < ApplicationController before_action :check_for_admin protected def check_for_admin redirect_to root_path unless current_user.admin? end end
class ClickScore < ApplicationRecord default_scope { order(score: :desc) } validates :name, presence: true, length: { minimum: 1, maximum: 20 } validates :score, presence: true, numericality: { only_integer: true, greater_than: 0 } def self.top_five order(score: :desc).limit(5) end end
# Read about factories at http://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :gemeinschaft_setup do association :user association :sip_domain association :country association :language end end
require 'uri' require 'net/http' require 'site_mapper/version' require 'site_mapper/logger' require 'site_mapper/request' require 'site_mapper/robots' require 'site_mapper/crawler' require 'site_mapper/crawl_url' # Find all links on domain to domain module SiteMapper # SiteMapper info link INFO_LINK = 'https://rubygems.org/gems/site_mapper' # SiteMapper User-Agent USER_AGENT = "SiteMapper/#{SiteMapper::VERSION} (+#{INFO_LINK})" # Map all links on a given site. # @return [Array] with links. # @param [String] link to domain # @param [Hash] options hash # @example Collect all URLs from example.com # SiteMapper.map('example.com') # @example Collect all URLs from example.com with custom User-agent # SiteMapper.map('example.com', user_agent: 'MyUserAgent') # @example Collect all URLs from example.com with custom logger class # class MyLogger # def self.log(msg); puts msg;end # def self.err_log(msg); puts msg;end # end # SiteMapper.map('example.com', logger: MyLogger) def self.map(link, options = {}) set_logger(options.delete(:logger)) options = { user_agent: USER_AGENT }.merge(options) Crawler.collect_urls(link, options) { |url| yield(url) if block_given? } end # Set logger. # @param [Object] logger # @example set system logger # SiteMapper.set_logger(:system) # @example set nil logger # SiteMapper.set_logger(:nil) # @example set your own logger # SiteMapper.set_logger(YourLogger) def self.set_logger(logger) return if logger.nil? if logger.is_a?(Symbol) Logger.use_logger_type(logger) else Logger.use_logger(logger) end end end
require 'forwardable' module DataMagic module Index class Importer attr_reader :raw_data, :options def initialize(raw_data, options) @raw_data = raw_data @options = options end def process setup parse_and_log finish! [row_count, headers] end def client @client ||= SuperClient.new(es_client, options) end def builder_data @builder_data ||= BuilderData.new(raw_data, options) end def output @output ||= Output.new end def parse_and_log parse_csv rescue InvalidData => e trigger("error", e.message) raise InvalidData, "invalid file format" if empty? end def chunk_size (ENV['CHUNK_SIZE'] || 100).to_i end def nprocs (ENV['NPROCS'] || 1).to_i end def parse_csv if nprocs == 1 parse_csv_whole else parse_csv_chunked end data.close end def parse_csv_whole CSV.new( data, headers: true, header_converters: lambda { |str| str.strip.to_sym } ).each do |row| RowImporter.process(row, self) break if at_limit? end end def parse_csv_chunked CSV.new( data, headers: true, header_converters: lambda { |str| str.strip.to_sym } ).each.each_slice(chunk_size) do |chunk| break if at_limit? chunks_per_proc = (chunk.size / nprocs.to_f).ceil Parallel.each(chunk.each_slice(chunks_per_proc)) do |rows| rows.each_with_index do |row, idx| RowImporter.process(row, self) end end if !headers single_document = DocumentBuilder.create(chunk.first, builder_data, DataMagic.config) set_headers(single_document) end increment(chunk.size) end end def setup client.create_index log_setup end def finish! validate! refresh_index log_finish end def log_setup opts = options.reject { |k,v| k == :mapping } trigger("info", "options", opts) trigger("info", "new_field_names", new_field_names) trigger("info", "additional_data", additional_data) end def log_finish trigger("info", "skipped (missing parent id)", output.skipped) if !output.skipped.empty? trigger('info', "done #{row_count} rows") end def event_logger @event_logger ||= EventLogger.new end def at_limit? options[:limit_rows] && row_count == options[:limit_rows] end extend Forwardable def_delegators :output, :set_headers, :skipping, :skipped, :increment, :row_count, :log_limit, :empty?, :validate!, :headers def_delegators :builder_data, :data, :new_field_names, :additional_data def_delegators :client, :refresh_index def_delegators :event_logger, :trigger def self.process(*args) new(*args).process end private def es_client DataMagic.client end end end end
FactoryBot.define do factory(:state) do name { 'Alaska' } end end
FactoryBot.define do factory :purchase_record_shipping_address do postal_code { '165-0035' } area_id { 2 } city { '中野区' } street { '白鷺1-1-1' } building { 'フォンティスビル' } phone { '09011111111' } token { 'tok_abcdefghijk00000000000000000' } end end
#!/usr/bin/env ruby require 'json' json = JSON.parse(STDIN.read) def order_hash_by_keys(hash) hash.keys.sort.each_with_object({}) do |key, result_hash| value = hash[key] result_hash[key] = if value.is_a?(Hash) order_hash_by_keys(value) elsif value.is_a?(Array) && value.first.is_a?(Hash) value.map {|e| order_hash_by_keys(e) }.sort_by {|e| e.fetch('metadata').fetch('guid') } else value end end end print JSON.pretty_generate(order_hash_by_keys(json))
# Invoice class class Invoice attr_accessor :items def initialize @@total_price = 0 @items = Array.new end def total_items @items.length end end
require 'rails_helper' describe "Designer can interact with applications" do it "they can approve them" do user = User.create(username: 'designer', password: 'test', role: 'designer') producer = User.create(username: 'producer', password: 'test', role: 'producer') design = user.designs.create(title: 'dress', description: 'leopard print', price_range: '10', due_date: Date.new) design.active! app = producer.applications.create(production_plan: "a new plan", due_date: Date.new, price: '10', design: design) login_user(user.username, user.password) click_on 'dress' expect(page).to have_content('Applications') click_on app.id expect(current_path).to eq(designer_design_application_path(user, design, app)) click_on "Accept Application" order = Order.last expect(page).to have_content("Order ##{order.id} has been created for #{design.title}!") expect(current_path).to eq(designer_order_path(user, order)) end it "they can decline them" do user = User.create(username: 'designer', password: 'test', role: 'designer') producer = User.create(username: 'producer', password: 'test', role: 'producer') design = user.designs.create(title: 'dress', description: 'leopard print', price_range: '10', due_date: Date.new) design.active! app = producer.applications.create(production_plan: "a new plan", due_date: Date.new, price: '10', design: design) login_user(user.username, user.password) click_on 'dress' click_on app.id click_on "Decline Application" expect(current_path).to eq(designer_design_path(user, design)) end end
# frozen_string_literal: true module Importers module Events class Record include ActiveModel::Validations module HeaderNames TITLE = 'title' STARTTIME = 'starttime' ENDTIME = 'endtime' DESCRIPTION = 'description' RSVP = 'users#rsvp' ALLDAY = 'allday' end module AllDayValues TRUE = 'true' FALSE = 'false' end HEADERS = [ HeaderNames::TITLE, HeaderNames::STARTTIME, HeaderNames::ENDTIME, HeaderNames::DESCRIPTION, HeaderNames::RSVP, HeaderNames::ALLDAY ].freeze EVENT_REJECTION_NOTES = 'Busy with another meeting' validate :header_to_be_valid, if: :header? attr_reader :row, :opts def initialize(row, opts = {}) @row = row @opts = opts end def process return false unless valid? create_event create_attendants end private def create_event @event = ::Event.create!( title: title, start_time: parsed_start_time, end_time: parsed_end_time, description: description, status: event_status, all_day: boolean_value(all_day) ) end def create_attendants return true unless users_rsvp users_rsvp_details.each do |user_rspv_detail| user = fetch_user(user_rspv_detail[:user_name]) next unless user rspv_status = user_rspv_detail[:status] update_existing_user_marked_yes_events(user.id) if rspv_status == ::Attendant::Statuses::YES Attendant.create!( user_id: user.id, event_id: @event.id, status: rspv_status ) end end def update_existing_user_marked_yes_events(user_id) user = User.find(user_id) overlapping_events = user.overlapping_events(start_time, end_time) attendant_ids = overlapping_events.pluck('attendants.id') Attendant.where(id: attendant_ids).update_all( status: ::Attendant::Statuses::NO, notes: EVENT_REJECTION_NOTES, updated_at: Time.zone.now ) end def fetch_user(user_name) User.where(user_name: user_name).last end def event_status return ::Event::Statuses::IN_PROGRESS if boolean_value(all_day) return ::Event::Statuses::UPCOMING if parsed_start_time > current_time return ::Event::Statuses::COMPLETED if parsed_end_time < current_time ::Event::Statuses::IN_PROGRESS end def users_rsvp_details @users_rsvp_details ||= users_rsvp.split(';').map { |user_rspv| user_rspv.split('#') }.map do |details| { user_name: details[0], status: details[1] } end end def parsed_start_time @parsed_start_time ||= Time.zone.parse(start_time) end def parsed_end_time @parsed_end_time ||= Time.zone.parse(end_time) end def title @title ||= row[HeaderNames::TITLE].strip end def start_time @start_time ||= row[HeaderNames::STARTTIME].strip end def end_time @end_time ||= row[HeaderNames::ENDTIME].strip end def description @description ||= row[HeaderNames::DESCRIPTION].strip end def all_day @all_day ||= row[HeaderNames::ALLDAY].strip end def users_rsvp @users_rsvp ||= row[HeaderNames::RSVP].try(:strip) end def current_time @current_time ||= Time.zone.now end def header_to_be_valid return unless header? && row.sort != HEADERS.sort invalid_headers = row - (HEADERS & row) errors.add(:base, "invalid headers - #{invalid_headers.join(', ')}") end def header? opts[:header] end def boolean_value(value) if value.downcase == AllDayValues::TRUE.downcase true elsif value.downcase == AllDayValues::FALSE.downcase false end end end end end
class Guide < ApplicationRecord has_many :sections, :dependent => :destroy, :autosave => true accepts_nested_attributes_for :sections, allow_destroy: true belongs_to :series, :optional => true end
module Utils::Line class Line attr_accessor :access_token,:user def initialize @access_token=nil @user=nil @access_token_uri = "https://api.line.me/oauth2/v2.1/token" @profile_uri = "https://api.line.me/v2/profile" @access_token_check_uri="https://api.line.me/oauth2/v2.1/verify" end #アクセストークンの有効性チェック def check_access_token() if @access_token.present? uri = URI.parse(@access_token_check_uri) para = {:access_token => @access_token} uri.query = URI.encode_www_form(para) res = Net::HTTP.get_response(uri) if res.code =="200" return true else return false end else return false end end #ユーザー情報を取得する def get_user_info() if @access_token !=nil user_info_response = self.get_line_user_info_response() #レスポンスが失敗の場合 if user_info_response.code !='200' return false else @user = JSON.parse(user_info_response.body) return true end else return false end end #ユーザー情報をリクエストする def get_line_user_info_response() if @access_token!=nil uri = URI.parse(@profile_uri) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE headers={"Authorization" =>"Bearer "+ @access_token} http.start do req = Net::HTTP::Get.new(uri.path) req.initialize_http_header(headers) return http.request(req) end else return false end end #アクセストークンを取得する def get_access_token(code) access_token_response = self.get_access_token_response(code) #レスポンスが失敗の場合 if access_token_response.code != '200' return false else access_token_body = JSON.parse(access_token_response.body) @access_token = access_token_body["access_token"] return true end end #access_tokenのレスポンスを取得する def get_access_token_response(code) uri = URI.parse(@access_token_uri) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE grant_type = "authorization_code" http.start do req = Net::HTTP::Post.new(uri.path) req.set_form_data(grant_type: grant_type,code: code,redirect_uri: LINE_REDIRECT_URL,client_id: LINE_CLIENT_ID,client_secret: LINE_SECRET) return http.request(req) end end end end
class OrderDetailsController < ApplicationController include CommentsHelper before_action :authenticate_user!, only: :create before_action :load_current_order, only: %i(create update destroy) before_action :load_order_detail, only: %i(update destroy) before_action :load_order_detail_by_product_id, only: :create before_action :check_params_quantity, only: %i(create update) authorize_resource def create if @order_detail.nil? @order_detail = @order.order_details.new order_detail_params else quantity = @order_detail.quantity @order_detail.update_attribute(:quantity, quantity + params[:order_detail][:quantity].to_i) end @order.user_id = current_user.id @order.save respond_to do |format| format.html format.js end end def update @order_detail.update_attributes order_detail_params @order_details = @order.order_details respond_to do |format| format.html format.js end end def destroy @order_detail.destroy @order_details = @order.order_details respond_to do |format| format.html format.js end end private def load_order_detail_by_product_id @order_detail = @order.order_details.find_by(product_id: params[:order_detail][:product_id]) end def load_current_order @order = current_order end def load_order_detail @order_detail = @order.order_details.find_by id: params[:id] end def order_detail_params params.require(:order_detail).permit :quantity, :product_id end def check_params_quantity @product = Product.find_by id: params[:order_detail][:product_id] if @product return if params[:order_detail][:quantity].to_i <= @product.quantity flash[:danger] = t "order_details.check_params_quantity.greater_quantity" redirect_to products_path else flash[:danger] = t "order_details.check_params_quantity.product_not_found" end end end
class NorthStarsController < ApplicationController before_action :set_north_star, only: %i[ show edit update destroy ] # GET /north_stars or /north_stars.json def index @north_stars = NorthStar.all end # GET /north_stars/1 or /north_stars/1.json def show end # GET /north_stars/new def new @north_star = NorthStar.new end # GET /north_stars/1/edit def edit end # POST /north_stars or /north_stars.json def create @north_star = NorthStar.new(north_star_params) respond_to do |format| if @north_star.save format.html { redirect_to @north_star, notice: "North star was successfully created." } format.json { render :show, status: :created, location: @north_star } else format.html { render :new, status: :unprocessable_entity } format.json { render json: @north_star.errors, status: :unprocessable_entity } end end end # PATCH/PUT /north_stars/1 or /north_stars/1.json def update respond_to do |format| if @north_star.update(north_star_params) format.html { redirect_to @north_star, notice: "North star was successfully updated." } format.json { render :show, status: :ok, location: @north_star } else format.html { render :edit, status: :unprocessable_entity } format.json { render json: @north_star.errors, status: :unprocessable_entity } end end end # DELETE /north_stars/1 or /north_stars/1.json def destroy @north_star.destroy respond_to do |format| format.html { redirect_to north_stars_url, notice: "North star was successfully destroyed." } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_north_star @north_star = NorthStar.find(params[:id]) end # Only allow a list of trusted parameters through. def north_star_params params.require(:north_star).permit(:solar_system_id, :name, :description, :data_source) end end
require File.expand_path(File.dirname(__FILE__) + "/../spec_helper") require "pairtree" describe "Pairtree" do before(:all) do @base_path = File.join(File.dirname(__FILE__), "../test_data/working") end it "should raise an error if a non-existent is specified without :create" do expect { Pairtree.at(@base_path) }.to raise_error(Pairtree::PathError) end describe "new pairtree" do after(:all) do FileUtils.rm_rf(@base_path) end it "should create a new pairtree" do prefix = "my_prefix:" pt = Pairtree.at(@base_path, prefix: prefix, create: true) expect(pt.prefix).to eql(prefix) expect(File.read(File.join(@base_path, "pairtree_prefix"))).to eql(prefix) expect(pt.root).to eql(File.join(@base_path, "pairtree_root")) expect(pt.pairtree_version).to eql(Pairtree::SPEC_VERSION) end end describe "existing pairtree" do before(:all) do Dir.chdir(File.join(File.dirname(__FILE__), "../test_data")) do FileUtils.cp_r("fixtures/pairtree_root_spec", "./working") end end after(:all) do FileUtils.rm_rf(@base_path) end it "should raise an error if a regular file is specified as a root" do expect { Pairtree.at(File.join(@base_path, "pairtree_prefix"), create: true) }.to raise_error(Pairtree::PathError) end it "should read the prefix if none is specified" do expect(Pairtree.at(@base_path).prefix).to eql(File.read(File.join(@base_path, "pairtree_prefix"))) end it "should not complain if the given prefix matches the saved prefix" do expect(Pairtree.at(@base_path, prefix: "pfx:").prefix).to eql(File.read(File.join(@base_path, "pairtree_prefix"))) end it "should raise an error if the given prefix does not match the saved prefix" do expect { Pairtree.at(@base_path, prefix: "wrong-prefix:") }.to raise_error(Pairtree::IdentifierError) end it "should not complain if the given version matches the saved version" do expect(Pairtree.at(@base_path, version: Pairtree::SPEC_VERSION).pairtree_version).to eql(Pairtree::SPEC_VERSION) expect(Pairtree.at(@base_path, version: Pairtree::SPEC_VERSION, create: true).pairtree_version).to eql(Pairtree::SPEC_VERSION) end it "should raise an error if the given version does not match the saved version" do expect { Pairtree.at(@base_path, version: 0.2) }.to raise_error(Pairtree::VersionMismatch) expect { Pairtree.at(@base_path, version: 0.2, create: true) }.to raise_error(Pairtree::VersionMismatch) end end end
module ApplicationHelper def bootstrap_paperclip_picture(form, paperclip_object) if form.object.send("#{paperclip_object}?") image_tag form.object.send(paperclip_object).send(:url, :small) end end def can_display_post?(post) signed_in? && !current_user.has_blocked?(post.user) || !signed_in? end def avatar_profile_link(user, image_options={}, html_options={}) link_to(image_tag(user.avatar.url(:thumb), image_options), profile_path(user), html_options) end def flash_class(type) case type when :alert "alert-error" when :notice "alert-success" else "" end end end
Given /^I am on the spinner page$/ do visit SpinnerPage end When(/^I click the increment button$/) do on(SpinnerPage).increment_the_spinner end Then(/^the Spinner Widget should read "([^"]*)"$/) do |value| expect(on(SpinnerPage).the_spinner).to eql value end When(/^I click the decrement button$/) do on(SpinnerPage).decrement_the_spinner end When(/^I set the spinner value to "([^"]*)"$/) do |value| on(SpinnerPage).the_spinner = value end
require "spec_helper" describe Moped::Protocol::GetMore do let(:get_more) do described_class.allocate end describe ".fields" do it "matches the specification's field list" do described_class.fields.should eq [ :length, :request_id, :response_to, :op_code, :reserved, :full_collection_name, :limit, :cursor_id ] end end describe "#initialize" do let(:get_more) do described_class.new "moped", "people", 123, 10 end it "sets the database" do get_more.database.should eq "moped" end it "sets the collection" do get_more.collection.should eq "people" end it "sets the full collection name" do get_more.full_collection_name.should eq "moped.people" end it "sets the cursor id" do get_more.cursor_id.should eq 123 end it "sets the limit" do get_more.limit.should eq 10 end context "when request id option is supplied" do let(:get_more) do described_class.new "moped", "people", 123, 10, request_id: 123 end it "sets the request id" do get_more.request_id.should eq 123 end end end describe "#op_code" do it "should eq 2005" do get_more.op_code.should eq 2005 end end end
class User < ActiveRecord::Base ############# CONFIGURATION ############# =begin require 'geokit' include GeoKit::Geocoders =end ############# CONFIGURATION ############# include Extensions::Authenticatable ## SETUP ASSOCIATIONS has_many :attachments, as: :attachable, dependent: :destroy accepts_nested_attributes_for :attachments, allow_destroy: true has_and_belongs_to_many :certifications =begin has_and_belongs_to_many :products has_and_belongs_to_many :categories has_many :delivery_windows, as: :deliverable, dependent: :destroy accepts_nested_attributes_for :delivery_windows, allow_destroy: true, reject_if: proc { |attrs| attrs['weekday'].blank? or attrs['start_hour'].blank? or attrs['start_hour'].blank? or attrs['transport_by'].blank? } has_many :agreements, foreign_key: :creator_id, dependent: :destroy =end has_attached_file :pic, styles: IMAGE_STYLES, default_url: :set_default_url_on_role has_many :goods, foreign_key: :creator_id, dependent: :destroy belongs_to :market accepts_nested_attributes_for :market ## ATTRIBUTE PROTECTION attr_accessible :first_name, :last_name, :email, :notes, :attachments_attributes, :role, :name, :phone, :growing_methods, :street_address_1, :street_address_2, :city, :state, :country, :zip, :billing_street_address_1, :billing_street_address_2, :billing_city, :billing_state, :billing_country, :billing_zip, :description, :website, :twitter, :facebook, :pic, :certification_ids, :text_updates, :complete, :has_eggs, :has_dairy, :has_livestock, :has_pantry, :custom_growing_methods, :delivery_windows_attributes, :size, :market_id, :market_attributes, :product_ids, :category_ids ## ATTRIBUTE VALIDATION validates :first_name, :last_name, presence: true validates :role, inclusion: {:in => ROLES.map{ |r| r.first}} validates :name, :phone, :market_id, :street_address_1, :city, :state, :zip, :country, :growing_methods, :size, presence: true, :if => lambda { self.role == "producer" and self.complete == true } validates :name, :phone, :market_id, :street_address_1, :city, :state, :zip, :country, presence: true, :if => lambda { self.role == "buyer" and self.complete == true } validates_attachment :pic, :size => { :in => 0..4.megabytes } ######################################### ################ CALLBACKS ################ before_save :strip_whitespace#, :set_lat_long ######################################### ################ SCOPES ################# scope :by_not_admin, where("role != 'admin' AND name != ''") scope :by_producer, where("role = 'producer' AND name != ''") scope :by_buyer, where("role = 'buyer' AND name != ''") scope :by_market_manager, where("role = 'marketmanager' AND name != ''") scope :by_other, lambda {|u| u.producer? ? where("role = 'buyer' AND name != ''") : where("role = 'producer' AND name != ''")} =begin scope :by_size, lambda {|s| where("size = ?", s)} scope :by_growing_methods, lambda {|g| where("growing_methods = ?", g)} scope :order_best_available, order("size ASC") scope :near, lambda{ |*args| origin = *args.first[:origin] origin_lat, origin_lng = origin origin_lat, origin_lng = (origin_lat.to_f / 180.0 * Math::PI), (origin_lng.to_f / 180.0 * Math::PI) within = *args.first[:within] { :conditions => %( (ACOS(COS(#{origin_lat})*COS(#{origin_lng})*COS(RADIANS(users.lat))*COS(RADIANS(users.lng))+ COS(#{origin_lat})*SIN(#{origin_lng})*COS(RADIANS(users.lat))*SIN(RADIANS(users.lng))+ SIN(#{origin_lat})*SIN(RADIANS(users.lat)))*3963) <= #{within[0]} ), :select => %( users.*, (ACOS(COS(#{origin_lat})*COS(#{origin_lng})*COS(RADIANS(users.lat))*COS(RADIANS(users.lng))+ COS(#{origin_lat})*SIN(#{origin_lng})*COS(RADIANS(users.lat))*SIN(RADIANS(users.lng))+ SIN(#{origin_lat})*SIN(RADIANS(users.lat)))*3963) AS distance ) } } =end ######################################### ############ CLASS METHODS ############## def self.csv_header "First Name,Last Name,Name,Email".split(',') end def self.build_from_csv(row) # find existing customer from email or create new user = find_or_initialize_by_email(row[2]) user.attributes = { :first_name => row[0], :last_name => row[1], :name => row[2], :email => row[3] } return user end ############ PUBLIC METHODS ############# def to_csv [first_name, last_name, email] end def admin? role == "admin" end def buyer? role == "buyer" end def producer? role == "producer" end def market_manager? role == "market_manager" end def role_label ROLES[role] end def full_name first_name.capitalize + " " + last_name.capitalize end def formal_name last_name.capitalize + ", " + first_name.capitalize end =begin def distance_from(otherlatlong) puts street_address_1 puts otherlatlong a = Geokit::LatLng.new(latlong) b = Geokit::LatLng.new(otherlatlong) return '%.2f' % a.distance_to(b) end ## PRODUCER METHODS def display_size return "S" if size == 0 return "M" if size == 1 return "L" if size == 2 return "" end =end def role_avatar "/assets/#{role}_profile_pics/thumb/missing.png" end ############ PRIVATE METHODS ############ private def set_default_url_on_role "/assets/#{role}_profile_pics/:style/missing.png" end def strip_whitespace self.first_name = self.first_name.strip self.last_name = self.last_name.strip self.email = self.email.strip self.name = self.name.strip if self.name end =begin def set_lat_long if complete res = MultiGeocoder.geocode(self.street_address_1 + (self.street_address_2 ? " " + self.street_address_2 : "") + ", " + self.city + ", " + self.state + " " + self.zip) self.latlong = res.ll self.lat = res.lat self.lng = res.lng end end =end end
require './lib/journey' describe Journey do subject(:journey) { Journey.new("edgeware") } # TODO: attributes context 'attributes' do it 'returns an empty list of journeys by default' do expect(journey.journey_history).to eq [] end it 'returns nil for entry_station' do expect(journey.entry_station).to eq "edgeware" end it 'returns nil for exit_station' do expect(journey.exit_station).to eq nil end end # TODO finish method context '#finish' do it "method takes an argument of exit_station" do expect(journey). to respond_to(:finish).with(1).argument end it 'finishes the journey by updating @journeys array with exit_station' do # let(:correct_answer_dbl) { double("This is needed but doesn't matter??", correct?: true) } journey.finish("waterloo") expect(journey.journey_history).to eq [{:entry => "edgeware", :exit =>"waterloo"}] end end end # TODO complete? method # TODO in fare method
# If nodejs is enabled, install Bower? if node[:box_setup][:nodejs][:install] execute "Installing Bower via NPM" do cwd '/home/vagrant/app' user 'root' command '/usr/local/bin/npm install -g bower' action :run end end
require 'rails_helper' RSpec.describe MatchAnswer, type: :model do describe 'validations' do it { should validate_presence_of(:answer) } it { should validate_presence_of(:match) } it { should validate_presence_of(:team) } end describe 'relationships' do it { should belong_to(:answer) } it { should belong_to(:match) } it { should belong_to(:team) } end end
class CreateInstantBookings < ActiveRecord::Migration def change create_table :instant_bookings do |t| t.string :first_name t.string :last_name t.string :phone_number t.string :email t.datetime :start_time t.decimal :price, :precision => 8, :scale => 2 t.integer :service_type_id t.text :requests t.timestamps end add_index :instant_bookings, :service_type_id add_column :custom_fields, :service_type_id, :integer add_column :custom_fields, :price, :decimal, :precision => 8, :scale => 2 add_index :custom_fields, :service_type_id add_column :pricing_tables, :custom_field_ids, :text end end
# frozen_string_literal: true class AddEmailUpdatesToUsers < ActiveRecord::Migration[5.0] def change add_column :users, :email_updates, :boolean end end
module CompaniesHelper def display_company_avatar(company, size = :medium) content_tag(:img, nil,:src => company.avatar.url(size)) end def company_label_customer(company) return unless company.has_invoices? content_tag(:span, "cliente", :class => "label label-customer") end def company_label_provider(company) return unless company.has_invoices? content_tag(:span, "proveedor", :class => "label label-provider") end def payment_days_message(company) return unless company.payment_days_median message = "Paga generalmente con <strong>#{company.payment_days_median} días de atraso</strong>" message = "Cliente siempre paga al día" if company.payment_days_median < 1 content_tag :div, class: "pull-right totals-kpi-box-header" do content_tag :h5, class: "payment-days-message" do message.html_safe end end end end
Rails.application.routes.draw do mount TestEngine::Engine, at: 'test_engine' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
class AgendaController < ApplicationController #skip_after_action :verify_authorized def new @availability = Availability.new @availability.specialist = current_user.specialist authorize @availability end def create @availability = Availability.new(availability_params) @availability.specialist = current_user.specialist authorize @availability if @availability.save redirect_to profile_agenda_index_path else render :new end end def index @availabilities = policy_scope(Availability) @json_availabilities = @availabilities.map { |a| a.calender_formatting }.to_a respond_to do |format| format.html format.json { render json: @json_availabilities } end end def edit @availability = Availability.find(params[:id]) authorize @availability end def update @availability = Availability.find(params[:id]) authorize @availability if @availability.update(availability_params) redirect_to profile_agenda_index_path else render :edit end end def show @availability = Availability.find(params[:id]) authorize @availability end private def availability_params params.require(:availability).permit(:start_time, :end_time, :location, :range) end end
require 'formula' class XmlrpcC < Formula homepage 'http://xmlrpc-c.sourceforge.net/' url 'http://svn.code.sf.net/p/xmlrpc-c/code/stable', :revision => 2489 version '1.33.03' def install ENV.deparallelize # --enable-libxml2-backend to lose some weight and not statically link in expat system "./configure", "--enable-libxml2-backend", "--prefix=#{prefix}" # xmlrpc-config.h cannot be found if only calling make install system "make" system "make install" end end
module PhoneWords class RedisBuilder DICTIONARY = 'dictionary.txt' attr_reader :redis def initialize(redis, dictionary = DICTIONARY) @redis = redis @words = File.readlines(dictionary).map &:strip end def seed_dictionary @words.each do |word| next if word.length < Finder::MIN_LENGTH redis.sadd "words:#{word[0, Finder::MIN_LENGTH]}", word redis.hset 'word_nums', word, word_to_numbers(word) end end private def word_to_numbers(word) word.downcase.chars.map do |char| Finder::NUMBER_LETTERS.find { |k,v| v.include? char }.first[0] end.join end end end
class User::UserAnswersController < User::StaticPagesController def create question = Option.find(params[:user_answer][:option_id]).question user_answer = UserTest.find(params[:user_test_id]).user_answers .find_or_initialize_by(question_id: question.id) user_answer.update!(user_answer_params) respond_to do |format| format.json { head :ok } end end private def user_answer_params params.require(:user_answer).permit(:option_id) end end
class Trashderived < Formula desc "Remove your Xcode DerivedData folder" homepage "https://github.com/carambalabs/trashderived" url "https://github.com/carambalabs/trashderived/archive/0.0.3.tar.gz" sha256 "7331333a356a8c0b7c80fc871fc679dbd73f4ffc9a4470a3a7077624c718554f" head "https://github.com/carambalabs/trashderived.git" depends_on :xcode def install xcodebuild "-project", "trashderived.xcodeproj", "-scheme", "trashderived", "-configuration", "Release", "CONFIGURATION_BUILD_DIR=build", "SYMROOT=." bin.install "build/trashderived" end end
#!/usr/local/bin/ruby require 'rubygems' require 'optparse' options = {} optparse = OptionParser.new do|opts| opts.banner = "Usage: getReport.rb --chains --date" options[:chains] = "" opts.on('-c', '--chains CHAINS' , 'Chains to output comma-separated') do |chs| options[:chains] = chs end opts.on('-d', '--date DATE' , 'Position Date') do |pdte| options[:date] = pdte end opts.on( '-h', '--help', 'Display this screen' ) do puts opts exit end opts.on('-f FROM', '--from FROM' , 'Sender Mail address') do |f| options[:from] = f end opts.on('-t TO', '--to TO' , 'Receiver Mail address') do |t| options[:to] = t end opts.on('-s SUBJECT', '--subject SUBJECT' , 'Subject') do |s| options[:subject] = s end opts.on( '-h', '--help', 'Display this screen' ) do puts opts exit end end optparse.parse! stamp=Time.now.strftime("%Y%m%d%H%M%S") currPid=Process.pid outputFile= "/apps/mxadmin/mxTools/ops/tmp/#{stamp}_#{currPid}_Table.html" `/apps/mxadmin/mxTools/ops/getReport.rb --chains #{options[:chains]} --date #{options[:date]} -o #{outputFile}` #`/apps/products/mxadmin/sybadm/mla/Operation/mail.rb -f #{options[:from]} -t #{options[:to]} -s "[HAWK] Production Status [Bb]" -b #{outputFile} -m html ` puts `/apps/mxadmin/mxTools/ops/mail_for_bo.pl --from=#{options[:from]} --to=#{options[:to]} --subject="[HAWK] Production Status [Bb]" --attachments=#{outputFile} --attachment_mime_types=text/html --smtp_relay=vip-m-parpop.fr.net.intra`
require 'test_helper' class PeopleControllerTest < ActionController::TestCase fixtures :all setup do @person = people(:one) end test "should get success for index" do get :index assert_response :success assert_not_nil assigns(:people) RackCASRailsTest::APP_CONTROLLER_METHODS.each do |method| assert @controller.methods.include?(method.to_sym) end end test "should get unauthorized for new" do # should get :unauthorized because of the before_action in PeopleController # that says: # before_action :authenticate! except: [:index, :show] get :new assert_response :unauthorized end # test "should create person" do # assert_difference('Person.count') do # post :create, person: { age: @person.age, name: @person.name } # end # assert_redirected_to person_path(assigns(:person)) # end test "should get success for show" do get :show, params: { id: @person.id } assert_response :success end # test "should get edit" do # get :edit, id: @person # assert_response :success # end # test "should update person" do # patch :update, id: @person, person: { age: @person.age, name: @person.name } # assert_redirected_to person_path(assigns(:person)) # end # test "should destroy person" do # assert_difference('Person.count', -1) do # delete :destroy, id: @person # end # assert_redirected_to people_path # end end
require 'spec_helper' describe "emprestimos/edit" do before(:each) do @emprestimo = assign(:emprestimo, stub_model(Emprestimo, :item => nil, :user => nil )) end it "renders the edit emprestimo form" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form", :action => emprestimos_path(@emprestimo), :method => "post" do assert_select "input#emprestimo_item", :name => "emprestimo[item]" assert_select "input#emprestimo_user", :name => "emprestimo[user]" end end end
# -*- mode: ruby -*- # vi: set ft=ruby : VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.define :manager, :autostart => true do |node| node.vm.box = 'ubuntu/trusty64' node.vm.hostname = "manager" node.vm.network :private_network, ip: "10.0.11.10", hostsupdater: "skip" node.vm.provider "virtualbox" do |vb| vb.memory = "512" vb.gui = false vb.customize ['modifyvm', :id, '--natdnshostresolver1', 'on'] end node.vm.provision :shell, path: "vagrant/upgrade_ansible.sh", privileged: false node.vm.provision "ansible_local" do |ansible| ansible.playbook = "site.yml" ansible.verbose = true ansible.install = true ansible.limit = "manager" ansible.inventory_path = "inventory" end end config.vm.define :test, :autostart => true do |node| node.vm.box = 'ubuntu/trusty64' node.vm.hostname = 'test' node.vm.network :private_network, ip: "10.0.11.11", hostsupdater: "skip" node.vm.provider "virtualbox" do |vb| vb.memory = "1024" vb.gui = false vb.customize ['modifyvm', :id, '--natdnshostresolver1', 'on'] end node.vm.provision :shell, path: "vagrant/test.sh", privileged: false end end
require 'spec_helper' describe Review do context "with an album" do let(:album) do Album.new.tap do |a| a.id = 1 a.name = "Banks" end end subject do Review.new.tap do |r| r.album_id = album.id end end it "find_album should return the review's album" do subject.find_album.should == album end end end
require "spec_helper" feature "checking delete a book" do scenario "deleting a existent book", :js, :selenium do book = create(:book) visit book_path(book) click_on "Delete" page.should_not have_content(book[:name]) end end
# == Schema Information # # Table name: gamerounds # # id :integer not null, primary key # number :integer # start_date :datetime # end_date :datetime # processed :boolean # period_id :integer # created_at :datetime not null # updated_at :datetime not null # class Gameround < ActiveRecord::Base belongs_to :period has_many :results, dependent: :destroy has_many :scores, dependent: :destroy has_many :jokers, dependent: :destroy has_many :rankings, dependent: :destroy accepts_nested_attributes_for :jokers accepts_nested_attributes_for :results attr_accessible :end_date, :number, :period_id, :processed, :start_date, :jokers_attributes, :results_attributes validates :end_date, :number, :period_id, :start_date, presence: true scope :active, where("start_date >= ?", DateTime.now.to_date) scope :processed, where(processed: true) scope :not_processed, where(processed: false) scope :next, where(processed: false).limit(1) end
class AddFileNameToJobItemBulkImport < ActiveRecord::Migration def change add_column :job_item_bulk_imports, :file_name, :string end end
class WebAnalytics VALID_PARAMS = { :utac => :site_code, :utvis => :visitor, :utses => :session, :utmdt => :page_title, :utmsr => :screen_size, :utmsc => :color_depth, :utmul => :language, :utmcs => :charset, :utmfl => :flash_version, :utmn => :unique_request, :utm_campaign => :campaign_name, :utm_source => :campaign_source, :utm_medium => :campaign_medium, :utm_content => :campaign_content, :utmp => :url, :utob => :outbound } attr_accessor :params URL = /\A(\/tracker.gif)\?(.*)/ # Parse the analytics url. We recognise that the # referring URL parameter (utmr) might itself have # parameters. We assume that there is not overlap # between the referer parameters and the GA # parameters. That might need to change. def parse_url(url) params = split_into_parameters(url) params ? params_to_hash(params) : {} end def create(url, model = Track) row = model.new data = parse_url(url) data.each do |k, v| row.send "#{VALID_PARAMS[k].to_s}=", v end row end def save(url, model = Track) row = create(url, model) row.save! end private def split_into_parameters(url) param_string = url.match(URL) param_string ? param_string[2].split('&') : [] end def params_to_hash(params) result = {} params.delete_if do |p| var, value = p.split('=') if value VALID_PARAMS[var.to_sym] ? result[var.to_sym] = URI.unescape(value) : false end end if params result end end
Gem::Specification.new do |s| s.name="rbygem" s.version="0.0.1" s.summary="hello,こんにちは" s.description="課題" s.authors=["aoji"] s.files=["lib/rbygem.rb"] end
class TripsController < ApplicationController before_filter :admin_required, :only => [:update, :destroy] helper_method :sort_column, :sort_direction def queue if params[:shift].present? session[:shift] = params[:shift] elsif !session[:shift] session[:shift] = 'd' end drivers = Driver.active.where('drivers.id IS NOT NULL') @driver_shifts = DriverShift.includes(:driver). where("driver_shifts.shift" => session[:shift].upcase). merge(drivers). order("#{sort_column} #{sort_direction}") end def index @trips = Trip.includes(:driver, :customer). order('trips.created_at DESC'). paginate(:page => params[:page], :per_page => 20) end def show @trip = Trip.find(params[:id]) end def new @trip = Trip.new @trip.driver_id = params[:driver_id] @trip.scheduled = true if params[:scheduled] @trip.skipped = true if params[:skip] session[:continue] = params[:continue] render :action => (@trip.skipped ? 'skip' : 'new') end def edit @trip = Trip.find(params[:id]) end def create @trip = Trip.new(params[:trip]) @trip.user_id = current_user.id @trip.skip = true if params[:skip] if @trip.save redirect_to(session[:continue] || trips_path) else render :action => "new" end end def update @trip = Trip.find(params[:id]) if @trip.update_attributes(params[:trip]) redirect_to(trips_path) else render :action => "edit" end end def destroy @trip = Trip.find(params[:id]) @trip.destroy redirect_to :action => :index end private def sort_column %w[last_random_trip last_scheduled_trip].include?(params[:sort]) ? params[:sort] : 'last_random_trip' end def sort_direction "asc" end end
require 'rspec' def new_max array_of_elements max = 0 array_of_elements.each do |i| if i > max max = i end end max end describe 'New Max method' do it 'returns the max value from an array efficiently' do test_array = [2, 4, 10, 3, 1] expect(new_max(test_array)).to eq(10) end end