text
stringlengths
10
2.61M
require 'rails_helper' feature 'restaurants' do before do User.create(email: 'freddy@gmail.lol', password: 'password', password_confirmation: 'password') visit '/' click_link 'Sign in' fill_in 'Email', with: 'freddy@gmail.lol' fill_in 'Password', with: 'password' click_button 'Log in' end context 'no restaurants have been added' do scenario 'should display a prompt to add a restaurant' do visit '/restaurants' expect(page).to have_content 'No restaurants yet' end end context 'restaurants have been added' do before do user = User.first user.restaurants.create(name: 'KFC') end scenario 'display restaurants' do visit '/restaurants' expect(page).to have_content('KFC') expect(page).not_to have_content('No restaurants yet') end end context 'creating restaurants' do scenario 'prompts user to fill out a form, then dsipalys the new restaurant' do visit '/restaurants' click_link 'Add a restaurant' fill_in 'Name', with: 'KFC' click_button 'Create Restaurant' expect(page).to have_content 'KFC' expect(current_path).to eq '/restaurants' end context 'an invalid restaurant' do scenario 'does not let you submit a name that is too short' do visit '/restaurants' click_link 'Add a restaurant' fill_in 'Name', with: 'kf' click_button 'Create Restaurant' expect(page).not_to have_css 'h2', text: 'kf' expect(page).to have_content 'error' end end end context 'viewing restaurants' do before do user = User.first user.restaurants.create(name: 'KFC', description: 'deep fried chillvibes') end scenario 'lets a user view a restaurant' do visit '/restaurants' click_link 'KFC' expect(page).to have_content 'KFC' expect(current_path).to eq "/restaurants/#{Restaurant.last.id}" end end context 'editing restaurants' do before do user = User.first user.restaurants.create(name: 'KFC', description: 'Deep fried goodness') end scenario 'let a user edit a restaurant' do visit '/restaurants' click_link 'Edit KFC' fill_in 'Name', with: 'Kentucky Fried Chicken' fill_in 'Description', with: 'Deep fried goodness' click_button 'Update Restaurant' click_link 'Kentucky Fried Chicken' expect(page).to have_content 'Kentucky Fried Chicken' expect(page).to have_content 'Deep fried goodness' expect(current_path).to eq "/restaurants/#{Restaurant.last.id}" end scenario "does not let a user edit a restaurant that they don't own" do visit '/restaurants' click_link 'Sign out' click_link 'Sign up' fill_in 'Email', with: 'otheruser@test.com' fill_in 'Password', with: '123456' fill_in 'Password confirmation', with: '123456' click_button 'Sign up' expect(page).not_to have_link 'Edit KFC' end end context 'deleting restaurants' do before do user = User.first user.restaurants.create(name: 'KFC') end scenario 'removes a restaurant when a user clicks a delete link' do visit '/restaurants' click_link 'Delete KFC' expect(page).not_to have_content 'KFC' expect(page).to have_content 'Restaurant deleted successfully' end scenario "does not let a user delete a restaurant that they don't own" do visit '/restaurants' click_link 'Sign out' click_link 'Sign up' fill_in 'Email', with: 'otheruser@test.com' fill_in 'Password', with: '123456' fill_in 'Password confirmation', with: '123456' click_button 'Sign up' expect(page).not_to have_link 'Delete KFC' end end end
Rails.application.routes.draw do resources :tracks do resources :comments end root to: "users#index" # get "/", to: "application#index" get 'passwords/new' get 'passwords/create' get 'passwords/edit' get 'passwords/update' resources :users, except: [:new, :edit] # match "*path", to: "users#index", via: "get" get "/login", to: "session#new" post "/login", to: "session#create" delete "/logout", to: "session#destroy" get "/logout", to: "session#destroy" #TO DO: delete this before production get "/signup", to: "users#new" post '/signup', to: "users#create" get '/about', to: "users#about", as: "about" end
# frozen_string_literal: true require_relative 'rest_client' module Uploadcare module Client # client for webhook management # @see https://uploadcare.com/api-refs/rest-api/v0.7.0/#tag/Webhook class WebhookClient < RestClient # Create webhook # @see https://uploadcare.com/docs/api_reference/rest/webhooks/#subscribe def create(options = {}) body = { target_url: options[:target_url], event: options[:event] || 'file.uploaded', is_active: options[:is_active].nil? ? true : options[:is_active] }.merge( { signing_secret: options[:signing_secret] }.compact ).to_json post(uri: '/webhooks/', content: body) end # Returns array (not paginated list) of webhooks # @see https://uploadcare.com/docs/api_reference/rest/webhooks/#get-list def list get(uri: '/webhooks/') end # Permanently deletes subscription # @see https://uploadcare.com/docs/api_reference/rest/webhooks/#unsubscribe def delete(target_url) body = { target_url: target_url }.to_json request(method: 'DELETE', uri: '/webhooks/unsubscribe/', content: body) end # Updates webhook # @see https://uploadcare.com/docs/api_reference/rest/webhooks/#subscribe-update def update(id, options = {}) body = options.to_json put(uri: "/webhooks/#{id}/", content: body) end alias create_webhook create alias list_webhooks list alias delete_webhook delete alias update_webhook update end end end
# Generated by jeweler # DO NOT EDIT THIS FILE # Instead, edit Jeweler::Tasks in Rakefile, and run `rake gemspec` # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{lifelog} s.version = "0.2.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Yutaka HARA"] s.date = %q{2009-10-03} s.description = %q{A lifelogging tool written in Ramaze} s.email = %q{yutaka.hara/at/gmail.com} s.extra_rdoc_files = [ "README.md" ] s.files = [ "README.md", "Rakefile", "VERSION", "controller/init.rb", "controller/main.rb", "layout/default.xhtml", "lifelog.gemspec", "main.rb", "model/init.rb", "model/migrations.rb", "model/post.rb", "model/tag.rb", "spec/helper.rb", "spec/main.rb", "spec/models.rb", "view/index.xhtml" ] s.homepage = %q{http://github.com/yhara/lifelog} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.5} s.summary = %q{A lifelogging tool written in Ramaze} s.test_files = [ "spec/helper.rb", "spec/main.rb", "spec/models.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<ramaze>, ["= 2009.10"]) s.add_runtime_dependency(%q<do_sqlite3>, ["= 0.10.0"]) s.add_runtime_dependency(%q<dm-core>, ["= 0.10.1"]) s.add_runtime_dependency(%q<dm-validations>, ["= 0.10.1"]) s.add_runtime_dependency(%q<dm-aggregates>, ["= 0.10.1"]) else s.add_dependency(%q<ramaze>, ["= 2009.10"]) s.add_dependency(%q<do_sqlite3>, ["= 0.10.0"]) s.add_dependency(%q<dm-core>, ["= 0.10.1"]) s.add_dependency(%q<dm-validations>, ["= 0.10.1"]) s.add_dependency(%q<dm-aggregates>, ["= 0.10.1"]) end else s.add_dependency(%q<ramaze>, ["= 2009.10"]) s.add_dependency(%q<do_sqlite3>, ["= 0.10.0"]) s.add_dependency(%q<dm-core>, ["= 0.10.1"]) s.add_dependency(%q<dm-validations>, ["= 0.10.1"]) s.add_dependency(%q<dm-aggregates>, ["= 0.10.1"]) end end
class Tour < ActiveRecord::Base has_many :tours, class_name:"TourTime", foreign_key: "tour_id" has_many :reviews has_many :tour_times, class: "TourTime", foreign_key: "tour_time_id" has_attached_file :image, styles: { medium: "400x245#" } validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/ def self.search(search) where("title LIKE ?", "%#{search}%") end end
# frozen_string_literal: true require 'spec_helper' RSpec.describe SymmetricDifferenceArray do let(:challenge) { described_class.new(arr_n, arr_m).call } describe '.call' do context 'when result successed' do let(:arr_n) { [1, 2, 3] } let(:arr_m) { [3, 4] } it { expect(challenge).to eq([1, 2, 4]) } end context 'when raise integer in array greater than 100' do let(:error_message) { 'Integer in array cannot be greater than 100' } let(:arr_n) { [1, 2, 3] } let(:arr_m) { [3, 4, 101] } it { expect { challenge }.to raise_error(error_message) } end end end
require 'spec_helper' feature "User contacts sites staff", %q{ As a site visitor I want to contact the site's staff So that i can tell them how awesome they are } do before(:each) do visit '/inquiries/new' click_on "Sign up" user = "doug" fill_in "Email", with: "dhgrainger@gmail.com" fill_in "Password", with: "asdfg123" fill_in "Password confirmation", with: "asdfg123" click_on "Sign up" end context 'with valid attributes' do it 'creates an iquiry with valid attributes' do visit '/inquiries/new' fill_in "Email", with: "dhgrainger@gmail.com" fill_in "Subject", with: "you're awesome" fill_in "Description", with: "this place is a mess awesome job" fill_in "First name", with: "doug" fill_in "Last name", with: "grainger" click_on "Submit Inquiry" expect(page).to have_content "you're awesome" end it 'requires a user to have an first name' do fill_in "Email", with: 'dhgrainger@gmail.com' fill_in "Subject", with: "you're awesome" fill_in "Description", with: "this place is a mess awesome job" fill_in "First name", with: '' fill_in "Last name", with: "grainger" click_on "Submit Inquiry" expect(page).to have_content("First name can't be blank") end end end
class ReviewsController < ApplicationController def create @review = Review.new(review_params) @review.user_id = current_user.id @review.save redirect_to movie_path(@review.movie_id) end def destroy @review = Review.find(params[:id]) @review.destroy redirect_to movie_path(@review.movie_id) end protected def review_params params.require(:review).permit(:movie_id, :description, :rating) end end
class ProjectCompletionReportGeneration def initialize(project) @project = project end def generate_projectcompletion_report try_create_projectcompletion_full_report end private def create_projectcompletion_full_report completionreporter.report(@project) end def completionreporter if @project.m_servicetype == "Damper Inspection" DamperInspectionJob.projectcompletion_reporter_class.new elsif @project.m_servicetype == "Damper Repair" DamperRepairJob.projectcompletion_reporter_class.new elsif @project.m_servicetype == "Firedoor Inspection" DoorInspectionJob.projectcompletion_reporter_class.new elsif @project.m_servicetype == "Firestop Survey" FirestopSurveyJob.projectcompletion_reporter_class.new else FirestopInstallationJob.projectcompletion_reporter_class.new end end def try_create_projectcompletion_full_report begin create_projectcompletion_full_report rescue => error Rails.logger.debug("Error Class :#{error.class.name.inspect}") Rails.logger.debug("Error Message :#{error.message.inspect}") end end end
require 'reform/form/coercion' module OtherInformation include Reform::Form::Module property :rate property :willing_to_travel validates :rate, numericality: { greater_than: 0, less_than_or_equal_to: 5_000 }, presence: true validates :willing_to_travel, presence: true property :entity, populate_if_empty: Entity do property :entity_type property :title property :name property :address property :address2 property :city property :state property :zip validates :entity_type, presence: true end property :address, populate_if_empty: Address do property :address validates :address, presence: true, length: { in: 3..512 } end collection :phones, populate_if_empty: Phone do model :phone # TODO: When Reform releases _destroy support implement that instead of this hack property :id, virtual: true property :_destroy, virtual: false property :number property :ext property :phone_type_id, type: Integer validates :number, presence: true, format: { with: RegexConstants::Phone::PHONE_NUMBER, message: I18n.t('activerecord.errors.messages.regex.phone') } validates :phone_type_id, presence: true end validate :phone_length property :military, populate_if_empty: Military do property :military property :service_start_date, type: DateTime property :service_end_date, type: DateTime property :investigation_date, type: DateTime property :clearance_expiration_date, type: DateTime property :clearance_active property :clearance_level_id, type: Integer property :rank_id, type: Integer property :branch_id, type: Integer validates :rank_id, presence: true, if: ->() { branch_id.present? } validates :branch_id, presence: true, if: ->() { rank_id.present? } validates :service_start_date, date: { on_or_before: DateTime.now } validates :service_end_date, date: { after: :service_start_date, on_or_before: DateTime.now }, allow_blank: true, if: ->() { service_start_date } end # TODO: When Reform releases _destroy support implement that instead of this hack def save # you might want to wrap all this in a transaction super do |attrs| if model.persisted? to_be_removed = ->(i) { i[:_destroy] == '1' } ids_to_rm = attrs[:phones].select(&to_be_removed).map { |i| i[:id] } Phone.destroy(ids_to_rm) phones.reject! { |i| ids_to_rm.include? i.id } end end # this time actually save super end private def phone_length remaining_phones = phones.reject { |i| i._destroy == '1' } errors.add :base, 'At most 3 phones' if remaining_phones.size > 3 errors.add :base, 'At least 1 phone' if remaining_phones.size < 1 end end
require 'immutable/list' module Immutable # A `Deque` (or double-ended queue) is an ordered, sequential collection of # objects, which allows elements to be retrieved, added and removed at the # front and end of the sequence in constant time. This makes `Deque` perfect # for use as an immutable queue or stack. # # A `Deque` differs from a {Vector} in that vectors allow indexed access to # any element in the collection. `Deque`s only allow access to the first and # last element. But adding and removing from the ends of a `Deque` is faster # than adding and removing from the ends of a {Vector}. # # To create a new `Deque`: # # Immutable::Deque.new([:first, :second, :third]) # Immutable::Deque[1, 2, 3, 4, 5] # # Or you can start with an empty deque and build it up: # # Immutable::Deque.empty.push('b').push('c').unshift('a') # # Like all `immutable-ruby` collections, `Deque` is immutable. The four basic # operations that "modify" deques ({#push}, {#pop}, {#shift}, and # {#unshift}) all return a new collection and leave the existing one # unchanged. # # @example # deque = Immutable::Deque.empty # => Immutable::Deque[] # deque = deque.push('a').push('b').push('c') # => Immutable::Deque['a', 'b', 'c'] # deque.first # => 'a' # deque.last # => 'c' # deque = deque.shift # => Immutable::Deque['b', 'c'] # # @see http://en.wikipedia.org/wiki/Deque "Deque" on Wikipedia # class Deque class << self # Create a new `Deque` populated with the given items. # @return [Deque] def [](*items) items.empty? ? empty : new(items) end # Return an empty `Deque`. If used on a subclass, returns an empty instance # of that class. # # @return [Deque] def empty @empty ||= new end # "Raw" allocation of a new `Deque`. Used internally to create a new # instance quickly after consing onto the front/rear lists or taking their # tails. # # @return [Deque] # @private def alloc(front, rear) result = allocate result.instance_variable_set(:@front, front) result.instance_variable_set(:@rear, rear) result.freeze end end def initialize(items=[]) @front = List.from_enum(items) @rear = EmptyList freeze end # Return `true` if this `Deque` contains no items. # @return [Boolean] def empty? @front.empty? && @rear.empty? end # Return the number of items in this `Deque`. # # @example # Immutable::Deque["A", "B", "C"].size # => 3 # # @return [Integer] def size @front.size + @rear.size end alias length size # Return the first item in the `Deque`. If the deque is empty, return `nil`. # # @example # Immutable::Deque["A", "B", "C"].first # => "A" # # @return [Object] def first return @front.head unless @front.empty? @rear.last # memoize? end # Return the last item in the `Deque`. If the deque is empty, return `nil`. # # @example # Immutable::Deque["A", "B", "C"].last # => "C" # # @return [Object] def last return @rear.head unless @rear.empty? @front.last # memoize? end # Return a new `Deque` with elements rotated by `n` positions. # A positive rotation moves elements to the right, negative to the left, and 0 is a no-op. # # @example # Immutable::Deque["A", "B", "C"].rotate(1) # # => Immutable::Deque["C", "A", "B"] # Immutable::Deque["A", "B", "C"].rotate(-1) # # => Immutable::Deque["B", "C", "A"] # # @param n [Integer] number of positions to move elements by # @return [Deque] def rotate(n) return self.class.empty if empty? n %= size return self if n == 0 a, b = @front, @rear if b.size >= n n.times { a = a.cons(b.head); b = b.tail } else (size - n).times { b = b.cons(a.head); a = a.tail } end self.class.alloc(a, b) end # Return a new `Deque` with `item` added at the end. # # @example # Immutable::Deque["A", "B", "C"].push("Z") # # => Immutable::Deque["A", "B", "C", "Z"] # # @param item [Object] The item to add # @return [Deque] def push(item) self.class.alloc(@front, @rear.cons(item)) end alias enqueue push # Return a new `Deque` with the last item removed. # # @example # Immutable::Deque["A", "B", "C"].pop # # => Immutable::Deque["A", "B"] # # @return [Deque] def pop front, rear = @front, @rear if rear.empty? return self.class.empty if front.empty? front, rear = EmptyList, front.reverse end self.class.alloc(front, rear.tail) end # Return a new `Deque` with `item` added at the front. # # @example # Immutable::Deque["A", "B", "C"].unshift("Z") # # => Immutable::Deque["Z", "A", "B", "C"] # # @param item [Object] The item to add # @return [Deque] def unshift(item) self.class.alloc(@front.cons(item), @rear) end # Return a new `Deque` with the first item removed. # # @example # Immutable::Deque["A", "B", "C"].shift # # => Immutable::Deque["B", "C"] # # @return [Deque] def shift front, rear = @front, @rear if front.empty? return self.class.empty if rear.empty? front, rear = rear.reverse, EmptyList end self.class.alloc(front.tail, rear) end alias dequeue shift # Return an empty `Deque` instance, of the same class as this one. Useful if you # have multiple subclasses of `Deque` and want to treat them polymorphically. # # @return [Deque] def clear self.class.empty end # Return a new `Deque` with the same items, but in reverse order. # # @return [Deque] def reverse self.class.alloc(@rear, @front) end # Return true if `other` has the same type and contents as this `Deque`. # # @param other [Object] The collection to compare with # @return [Boolean] def eql?(other) return true if other.equal?(self) instance_of?(other.class) && to_ary.eql?(other.to_ary) end alias == eql? # Return an `Array` with the same elements, in the same order. # @return [Array] def to_a @front.to_a.concat(@rear.to_a.tap(&:reverse!)) end alias entries to_a alias to_ary to_a # Return a {List} with the same elements, in the same order. # @return [Immutable::List] def to_list @front.append(@rear.reverse) end # Return the contents of this `Deque` as a programmer-readable `String`. If all the # items in the deque are serializable as Ruby literal strings, the returned string can # be passed to `eval` to reconstitute an equivalent `Deque`. # # @return [String] def inspect result = "#{self.class}[" i = 0 @front.each { |obj| result << ', ' if i > 0; result << obj.inspect; i += 1 } @rear.to_a.tap(&:reverse!).each { |obj| result << ', ' if i > 0; result << obj.inspect; i += 1 } result << ']' end # Return `self`. Since this is an immutable object duplicates are # equivalent. # @return [Deque] def dup self end alias clone dup # @private def pretty_print(pp) pp.group(1, "#{self.class}[", ']') do pp.breakable '' pp.seplist(to_a) { |obj| obj.pretty_print(pp) } end end # @return [::Array] # @private def marshal_dump to_a end # @private def marshal_load(array) initialize(array) end end # The canonical empty `Deque`. Returned by `Deque[]` when # invoked with no arguments; also returned by `Deque.empty`. Prefer using this # one rather than creating many empty deques using `Deque.new`. # # @private EmptyDeque = Immutable::Deque.empty end
class ClientsController < ApplicationController layout 'ajoke' skip_before_filter :verify_authenticity_token before_action :authenticate_user! before_action :admin_check def index @client = Client.new @Cl = Client.all @Client = @Cl.order(name: :asc) @Clients = @Client.paginate(:page => params[:page],:per_page => 10) @title = "All Clients" end def create name = params[:name] email = params[:email] @client = Client.new(name: name, email: email) if @client.save redirect_to ajoke_clients_edit_path(client: @client.id) else render 'index' end end def edit @client = Client.find_by(id: params[:client]) @cities = ['Andhra Pradesh','Arunachal Pradesh','Assam','Bihar','Chhattisgarh','Goa','Gujarat','Haryana', 'Himachal Pradesh','Jammu & Kashmir','Jharkhand','Karnataka','Kerala','Madhya Pradesh','Maharashtra','Manipur', 'Meghalaya','Mizoram','Nagaland','Odisha (Orissa)','Pondicherry (Puducherry)','Punjab','Rajasthan','Sikkim','Tamil Nadu','Telangana ', 'Tripura','Uttar Pradesh','Uttarakhand','West Bengal','Andaman and Nicobar Islands','Chandigarh','Dadra and Nagar Haveli', 'Daman and Diu','Lakshadweep','Delhi' ] @galleries = Gallery.where("id != 1") @gals = [] gals = ClientGallery.where(client_id: @client.id) unless gals.nil? gals.each do |g| @gals.push(g.gallery_id) end end end def update @client = Client.find(params[:client][:id]) galleries = params[:client][:galleries].split(",") ClientGallery.where(client_id: @client.id).destroy_all if @client.update_attributes(params[:client].permit(:name, :email, :phone_no, :city)) galleries.each do |g| ClientGallery.create(gallery_id: g, client_id: @client.id) end flash[:notice] = "Client details updated!" redirect_to ajoke_clients_path else render 'edit' end end def update_client if params[:client][:id].nil? ClientGallery.create(gallery_id: g, client_id: params[:client][:gallery]) else @client = ClientGallery.find(params[:client][:id]) @client.client_id = params[:client][:name] @client.save cl = Client.find(params[:client][:name]) end # Tell the UserMailer to send a welcome email after save ClientMailer.delay(:queue => 'mailer').welcome_email(cl) #flash[:notice] = "Client details updated!" render :json => 'success' end def delete end end
class UsersController < ApplicationController # POST /register def register @user = User.create(user_params) if @user.save response = { token: JsonWebToken.encode(user_id: @user.id)} render json: response, status: :created else render json: @user.errors, status: :bad end end private def user_params params.permit( :name, :email, :password ) end end
class Project < ActiveRecord::Base STATES = ["closed", "open"] belongs_to :user has_many :likes has_many :pledges has_many :donations, through: :pledges before_destroy :ensure_not_referenced_by_any_pledge validates :title, :description, :contact_email, presence: true validates :estimate, numericality: {greater_than_or_equal_to: 0.01} validates :title, uniqueness: true #validates :image_url, allow_blank: true, format: { # with: %r{\.(gif|jpg|png)\Z}i, #message: 'must be a URL for GIF, JPG or PNG image.' #} validate :picture_size validates :slug, presence: true, uniqueness: true #serialize :custom_fields, Array scope :recent, -> { order('title ASC') } scope :live, -> { where("state = 'open' and (closes_at is null or closes_at > ?)", Time.current).order('closes_at ASC') } scope :top_featured, -> { where(featured: true) } scope :top_watched, -> { where(watch: true) } before_validation :generate_slug before_save :update_closes_at_if_manually_closed mount_uploader :picture, PictureUploader def self.latest Project.order(:updated_at).last end def thumbs_up_total self.likes.where(like: true).size end def thumbs_down_total self.likes.where(like: false).size end def custom_fields_string=(custom_fields_string) self.custom_fields = self.custom_fields_string_to_array(custom_fields_string) end def custom_fields_string_to_array(string) (string || '').split(',').map(&:strip).reject(&:blank?).uniq end def custom_fields_string custom_fields.join(',') end def to_param slug end def generate_slug self.slug = title.parameterize if slug.blank? end def to_s title end def open? state == 'open' && (closes_at.nil? || closes_at > Time.current) end def close? !open? end def past_open? state == 'open' && closes_at < Time.current end def unmet_requirements_for_scheduling missing_prereqs = [] missing_prereqs << "Project must have a start date" unless start_date missing_prereqs << "Project must have a end date" unless end_date missing_prereqs end def archive if current? update_attribute(:archived, true) end end def unarchive if archived? update_attribute(:archived, false) end end def faeture if not_priority? update_attribute(:featured, true) end end def unfaeture if featured? update_attribute(:featured, false) end end def not_priority? !featured? end def current? !archived? end def interesting? !watch? end def watched if interesting? update_attribute(:watch, true) end end def unwatched if watch? update_attribute(:watch, false) end end def donation_opens opens_at && opens_at.to_s(:long_with_zone) end def donation_closes closes_at && closes_at.to_s(:long_with_zone) end def fundraising_date(fundraising_day) start_date + (fundraising_day - 1).days end private # ensure that there are no line items referencing this product def ensure_not_referenced_by_any_pledge if pledges.empty? return true else errors.add(:base, 'Pledges are present') return false end end def picture_size if picture.size > 5.megabytes errors.add(:picture, "should be less than 5mb") end end def update_closes_at_if_manually_closed if changes.key?(:state) && changes[:state] == ['open', 'closed'] self.closes_at = DateTime.now end end end # == Schema Information # # Table name: projects # # t.string "title" # t.text "description" # t.decimal "estimate", precision: 8, scale: 2 # t.datetime "created_at", null: false # t.datetime "updated_at", null: false # t.integer "user_id" # t.string "picture" # t.string "slug" # t.string "contact_email" # t.string "state" # t.string "archived", default(FALSE) # t.text "review_tags" # t.string "url" # t.datetime "start_date" # t.datetime "end_date" # t.text "custom_fields" # t.datetime "opens_at" # t.datetime "closes_at" # t.boolean "featured" # t.boolean "watch" # #add_index "projects", ["user_id"], name: "index_projects_on_user_id", using: :btree # # # #
require 'yaml' class PropertiesManager def initialize(file) @file = file end def getPropertiesHash() node = YAML::load(File.open(@file)) #puts node #puts node.class properties = Hash.new node.split(' ').each do |item| k = item.split("=").first v = item.split("=").last properties[k] = v end properties end end
class ApplicationController < ActionController::Base include CanCan::ControllerAdditions # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. include CanCan::ControllerAdditions # protect_from_forgery with: :exception protect_from_forgery with: :null_session, :if => Proc.new { |c| c.request.format == 'application/json' } acts_as_token_authentication_handler_for User before_action :authenticate_user!, :except => [:getdata, :prosumer, :getdayahead] check_authorization :unless => :do_not_check_authorization? rescue_from CanCan::AccessDenied do |exception| redirect_to request.referer || root_path, :alert => exception.message end def after_sign_in_path_for(resource) sign_in_url = url_for(:action => 'new', :controller => 'sessions', :only_path => false, :protocol => 'http') if request.referer == sign_in_url super else stored_location_for(resource) || request.referer || root_path end end def after_sign_out_path_for(resource_or_scope) root_path end private def do_not_check_authorization? respond_to?(:devise_controller?) # or # condition_one? or # condition_two? end end
class OffersController < ApplicationController before_action :set_offer, only: [:show, :edit, :update, :promotion, :imaging, :remove] before_action :authenticate_user!, except: [:show, :index, :promotion, :imaging, :remove] before_action :require_permission, only: [:edit, :update, :imaging, :remove] before_action :must_be_completely_verified, except: [:show, :index, :search] def index @offers = Offer.published.order('created_at DESC').paginate(:page => params[:page], :per_page => 20) end def search @poffers = PromotedOffer.published.search(params[:search]).paginate(:page => params[:page]).limit(2) @offers = Offer.published.search(params[:search]).paginate(:page => params[:page], :per_page => 10) end def show @offer.increment!(:total_clicks) @promoted_offer = PromotedOffer.new @reviewable = @offer @reviews = @reviewable.reviews.where("buyer_id != ?", @offer.user.id).order('created_at DESC').paginate(:page => params[:page], :per_page => 10) @positive_reviews = @reviewable.reviews.positive.where("buyer_id != ?", @offer.user.id) @negative_reviews = @reviewable.reviews.negative.where("buyer_id != ?", @offer.user.id) @convoable = @offer @conversations = @convoable.conversations @conversation = Conversation.new end def new @offer = Offer.new(:sell => (params[:sell] == '1')) end def edit end def create @offer = Offer.new(offer_params) if @offer.save @offer.create_activity :create, owner: current_user redirect_to @offer else render :new end end def update if @offer.update(offer_params) redirect_to @offer else render :edit end end def promotion end def imaging end def remove @offer.toggle!(:deleted) redirect_to root_url end private def set_offer @offer = Offer.find(params[:id]) end def offer_params params.require(:offer).permit(:name, :description, :image, :new, :price, :user_id, :tag_list, :deleted, :image_a, :image_b, :image_c, :image_d, :image_e, :location, :quantity, :barcode, :free_delivery, :sell) end def require_permission if current_user != Offer.find(params[:id]).user redirect_to root_path end end end
class CreateWorkorders < ActiveRecord::Migration def change create_table :workorders do |t| t.string :subject t.date :noticed t.string :location t.text :note t.boolean :action_taken t.boolean :invoiced t.boolean :mandatory t.boolean :denied t.boolean :m_email_sent t.string :contacted_via t.references :landlord, index: true t.references :tenant, index: true t.references :property, index: true t.timestamps end end end
require 'spec_helper' describe UserMailer do let :user do User.new(email: "new-user@example.com", password: "password1", password_confirmation: "password1") end let(:welcome_message) { UserMailer.welcome_email(user) } it 'comes from the proper email address' do expect(welcome_message.from).to eq ["notifications@g2-store.com"] end it 'goes to the right email address' do expect(welcome_message.to).to eq ["new-user@example.com"] end it 'has the proper subject' do expect(welcome_message.subject).to eq 'Thank you for signing up!' end it 'has a welcome message in the body' do expect(welcome_message.body).to have_content 'Thanks for joining and have a great day!' end end
namespace :db do desc "Fill database with sample data" task populate: :environment do delete_old_files make_users make_charge_types make_charges make_charge_aliases make_surveys make_bookings make_booking_details make_filter_criteria end end def make_users admin = User.new(#name: "Example User", email: "admin@cochs.org", password: "foobar", password_confirmation: "foobar") #admin.skip_confirmation! admin.save! admin.toggle!(:admin) 5.times do |n| #name = Faker::Name.name email = "user-#{n+1}@cochs.org" password = "password" user = User.new(#name: name, email: email, password: password, password_confirmation: password) #user.skip_confirmation! user.save! end end def make_charge_types #[0,8,4,4,16,1,2].each do |n| # ChargeType.create!(score: n) #end populate_table('charge_types') end def make_charges # charge_types = ChargeType.all # charge_types.each { |type| 10.times { type.charges.create! } } populate_table('charges') end def make_charge_aliases #charges = Charge.all #charges.each do |charge| # 2.times do |n| # letter = ('a'..'z').to_a[n] # charge.charge_aliases.create!(alias: "#{charge.id}#{letter}") # end #end populate_table('charge_aliases') end def make_surveys admin = User.find_by_email("admin@cochs.org") 50.times do |n| admin.surveys.create!(name: "Example survey #{n}") end users = User.all(limit: 4) users.each do |user| 5.times do |n| user.surveys.create!(name: "User #{user.id} survey #{n}") end end end def make_bookings surveys = Survey.all surveys.each do |survey| 10.times do |n| survey.bookings.create!(zip_code: "94609", booking_date: n.days.ago) end end end def make_booking_details bookings = Booking.all bookings.each do |booking| n = 1 6.times do n += 1 charge = Charge.find(rand(1..50)) booking.booking_details.create!(rank: n, charge_id: charge.id) end end end def make_filter_criteria { 1 => 1, 4 => -1 }.each do |key, value| fc = FilterCriterion.new(charge_type_id: key, significance: value) fc.survey_id = 0 fc.save! end end def populate_table(table) file_path = "setup/#{table}.csv" field_names = CSV.parse(File.open(file_path, &:readline))[0] created_at = Time.now.strftime("%Y-%m-%d %H:%M:%S") CSV.foreach(file_path, {headers: :first_row}) do |row| sql_vals = [] field_names.each do |column| val = row[column] sql_vals << ActiveRecord::Base.connection.quote(val) end sql = "INSERT INTO #{table} " + "(#{field_names.join(', ')}, created_at, updated_at) " + "VALUES " + "(#{sql_vals.join(', ')}, '#{created_at}', '#{created_at}')" ActiveRecord::Base.connection.insert(sql) end end def delete_old_files FileUtils.rm_rf(Dir.glob('files/*')) end
require 'rails_helper' describe 'sweater weather api' do it 'returns background image', :vcr do get "/api/v1/backgrounds?location=denver,co" expect(response).to be_successful json = JSON.parse(response.body, symbolize_names: true) expect(json).to be_a(Hash) expect(json[:data][:attributes][:background]).to have_key(:image_url) end end
class Snippet < ActiveRecord::Base belongs_to :user belongs_to :board validates :name, :body, :board_id, presence: true attr_accessible :name, :body, :board_id, :board scope :search, lambda{|query| where("name LIKE ?", "%#{query}%") } def author_name user.username end end
require 'spec_helper' describe "Positions" do context "As signed in user" do let(:current_user) { FactoryGirl.create(:user) } before {login_as(current_user, :scope => :user)} describe "GET /" do it "should load root dashboard even when no positions added" do visit root_path expect(page).to have_content "New Position" end end describe "GET index" do before {@position = FactoryGirl.create(:position, :user => current_user)} before {visit root_path} it "Should list all positions" do expect(page).to have_content(@position.title) end context "show one position" do it "should show applied tab" do click_link @position.title expect(page).to have_content("Applied") end it "should show rejected tab" do click_link @position.title expect(page).to have_content("Rejected") end context "requests statuses" do before {@request = FactoryGirl.create(:position_request, :position => @position)} it "should show one pending status" do click_link @position.title click_link "Applied" expect(page).to have_content("pending") expect(page).to_not have_content("Status") end it "should show main chat screen" do click_link @position.title click_link "Applied" click_link "Process" expect(page).to have_content("Files") expect(page).to_not have_content("Status") end it "should remove request from the list" do click_link @position.title click_link "Process" click_link "Reject" expect(page).to_not have_content(@request.entity_email) end end end end end context "As not registered user" do before {visit root_path} it "Should not load positions" do expect(page).to_not have_content "New Position" end it "should show login screen" do click_login expect(page).to have_content "Sign in" end end end
class Setor < ApplicationRecord validates :nome, :sigla, uniqueness: true, presence: true has_many :estoques def nome=(nome) write_attribute :nome, nome.to_s.titleize self.nome.strip! end def sigla=(sigla) write_attribute :sigla, sigla.to_s[0,3].upcase end scope :principal, -> { where(principal: true).first } end
class Lifter attr_reader :name, :lift_total @@all =[] def initialize(name, lift_total) @name = name @lift_total = lift_total @@all << self end # Get a list of all lifters def self.all @@all end # Get a list of all the memberships that a specific lifter has def lifter_membership Membership.all.select {|membership| membership.lifter == self} end # Get a list of all the gyms that a specific lifter has memberships to def all_gyms lifter_membership.map {|lifter| lifter.gym} end # Get the average lift total of all lifters def self.average_lift_total all_lifters = self.all.count{ |lifter| lifter.lift_total} #self.all.map {|lifter| lifter.lift_total} self.all.reduce(0){ |total, lifttot| total + lifttot.lift_total}/ all_lifters end # Get the total cost of a specific lifter's gym memberships def total_cost lifter_membership.reduce(0){ |total, pay| total + pay.cost} end # Given a gym and a membership cost, sign a specific lifter up for a new gym def gym_signup(gym, cost) Membership.new(gym, cost, self) end end
# Monty Hall Problem Simulaton # https://en.wikipedia.org/wiki/Monty_Hall_problem class MontyHallSimulation def initialize # Assign Goat to all doors @doors = %w(Goat Goat Goat) # Upgrade one random door to Car @doors[rand(3)] = 'Car' end def pick_door @pick = rand(3) end def reveal_door @revealed = @doors.each_index.select { |i| i != @pick && @doors[i] == 'Goat' }.sample end def swapper @doors[@doors.each_index.select { |i| i != @pick && i != @revealed }.sample] == 'Car' ? 1 : 0 end def non_swapper @doors[@pick] == 'Car' ? 1 : 0 end def result print 'Doors: ', @doors, "\t Picked: ", @pick, "\tRevealed: ", @revealed, "\tSwapper: ", swapper, "\tNon Swapper: ", non_swapper, "\n" end end swapper_won = 0 non_swapper_won = 0 10_000.times do simulation = MontyHallSimulation.new simulation.pick_door simulation.reveal_door # simulation.result swapper_won += simulation.swapper non_swapper_won += simulation.non_swapper end print 'swapper_won ', swapper_won, ' out of 10000 times ie ', ((swapper_won.to_f / 10_000.to_f) * 100).round(2), "%\n" print 'non_swapper_won ', non_swapper_won, ' out of 10000 times ie ', ((non_swapper_won.to_f / 10_000.to_f) * 100).round(2), "%\n"
class Api::V1::AuthenticationController < ApplicationController skip_before_action :authenticate_request require 'json_web_token' def register @user = User.create(user_params) if @user.save response = { message: 'User created successfully'} render json: response, status: :created else render json: @user.errors, status: :bad end end def auth0Authenticate puts "auth 0 authenticate" end def authenticate command = AuthenticateUser.call(params[:email], params[:password]) if command.success? render json: { auth_token: command.result } else render json: { error: command.errors }, status: :unauthorized end end end private # Only allow a trusted parameter "white list" through. def user_params params.permit(:email, :password) end
# Helper Method def position_taken?(board, location) !(board[location].nil? || board[location] == " ") end # Define your WIN_COMBINATIONS constant WIN_COMBINATIONS = [ [0,1,2], #horizontal [3,4,5], #horizontal [6,7,8], #horizontal [0,3,6], #vertical [1,4,7], #vertical [2,5,8], #vertical [0,4,8], #diagnol [6,4,2] #diagnol ] def won?(board) win_arr = [] WIN_COMBINATIONS.each do |position| if (board[position[0]] == "X" && board[position[1]] == "X" && board[position[2]] == "X") win_arr.push(position[0]) win_arr.push(position[1]) win_arr.push(position[2]) return win_arr elsif (board[position[0]] == "O" && board[position[1]] == "O" && board[position[2]] == "O") win_arr.push(position[0]) win_arr.push(position[1]) win_arr.push(position[2]) return win_arr end end return false end def full?(board) if (!won?(board) && board.count("X") == 4 || board.count("O") == 4 && board.count(" ") == 0) return true else return false end end def draw?(board) if (!won?(board) && full?(board)) then true else return false end end def over?(board) if draw?(board) return true elsif won?(board) return true end end def winner(board) arr = [] if won?(board) arr = won?(board) return board[arr[0]] else nil end end
module Puppet::Parser::Functions newfunction(:landb_func, :type => :rvalue, :doc => "A puppet funtion to integrate with LanDB") do |args| require 'rubygems' require 'yaml' require 'landb' option_hash = args[0] config = begin YAML.load(File.open("/etc/puppet/landb_config.yml")) rescue ArgumentError => e puts "Could not parse YAML: #{e.message}" end LandbClient.set_config(config) client = LandbClient.instance client_method = client.method option_hash["method"].to_sym response = client_method.call option_hash["method_arguments"] if option_hash["response_info"].first.instance_of?(Array) response = response.get_values_for_paths option_hash["response_info"] else response = response.get_value_for_path option_hash["response_info"] end response end end
require_relative 'java_modules' module Aurora class Config < JavaModules::AuroraConfig def initialize super "/dev/null" end def load(config) config.each do |key, value| send("#{key}=", value_for_key(key, value)) end end def value_for_key(key, value) return value.to_i if key == :gpfdist_port value end end end
require 'digest/md5' module HashFunctions @@a1 = [18, 39, 3, 37, 12, 29, 7, 30, 23, 2, 5, 39, 24, 12, 26, 12, 27, 0, 25, 24, 9, 12, 9, 18, 32, 27, 38, 30, 18, 27, 12, 25] @@a2 = [6, 9, 38, 16, 21, 26, 3, 7, 13, 5, 30, 22, 15, 19, 31, 30, 32, 9, 9, 0, 18, 10, 7, 1, 16, 6, 12, 6, 22, 3, 5, 29] def h1(k) result = 0 n = 0 k.each_byte do |b| result = result + @@a1[n] * b n = n + 1 end return result.modulo(41) end def h2(k) result = 0 n = 0 k.each_byte do |b| result = result + @@a2[n] * b n = n + 1 end return result.modulo(41) end def hashKey(k) md5 = Digest::MD5.hexdigest(k) return [h1(md5), h2(md5)] end end
require 'spec_helper' describe PredictionsController do render_views context "when authenticated through Facebook" do before do request.env['omniauth.auth'] = OmniAuth.config.mock_auth[:facebook] request.session[:user] = { info: request.env['omniauth.auth']['info'], uid: request.env['omniauth.auth']['uid'], provider: request.env['omniauth.auth']['provider'] } @user = FactoryGirl.create(:user, uid: request.session[:user][:uid], provider: request.session[:user][:provider]) @forecast = FactoryGirl.create(:forecast, user_id: @user.id) @attrs = FactoryGirl.attributes_for(:prediction, forecast_id: @forecast.id) @prediction = FactoryGirl.create(:prediction, forecast_id: @forecast.id) end describe "GET 'new'" do before { get :new, forecast_id: @forecast.id } it "should be successful" do response.should be_success end it "should assign @user" do assigns(:user).should be_a(User) assigns(:user).id.should eq @forecast.user_id assigns(:user).uid.should eq request.session[:user][:uid] end it "should assign @forecast" do assigns(:forecast).should be_a(Forecast) assigns(:forecast).user_id.should eq @user.id end it "should assign @prediction" do assigns(:prediction).should be_a(Prediction) assigns(:prediction).forecast_id.should eq @forecast.id end it "should render 'predictions/new'" do response.should render_template('predictions/new') end end describe "POST 'create'" do context "when valid" do before { post :create, forecast_id: @forecast.id, prediction: @attrs } it "should be successful and redirect" do response.status.should be(301) end it "should assign @user" do assigns(:user).should be_a(User) assigns(:user).id.should eq @forecast.user_id assigns(:user).uid.should eq request.session[:user][:uid] end it "should assign @forecast" do assigns(:forecast).should be_a(Forecast) assigns(:forecast).user_id.should eq @user.id end it "should assign @prediction" do assigns(:prediction).should be_a(Prediction) assigns(:prediction).forecast_id.should eq @forecast.id end it "should redirect to 'predictions#new'" do response.should redirect_to new_prediction_path(forecast_id: assigns(:forecast).id) end end context "when invalid" do before { post :create, forecast_id: @forecast.id, prediction: @attrs.merge(winning_team_id: nil) } it "should be invalid" do response.status.should be(422) end it "should assign @user" do assigns(:user).should be_a(User) assigns(:user).id.should eq @forecast.user_id assigns(:user).uid.should eq request.session[:user][:uid] end it "should assign @forecast" do assigns(:forecast).should be_a(Forecast) assigns(:forecast).user_id.should eq @user.id end it "should assign @prediction" do assigns(:prediction).should be_a(Prediction) assigns(:prediction).forecast_id.should eq @forecast.id end it "should have errors" do assigns(:prediction).errors.any?.should be_true assigns(:prediction).errors.full_messages.should include("Winning team can't be blank") end it "should render 'predictions/new'" do response.should render_template('predictions/new') end end end describe "GET 'edit'" do before { get :edit, forecast_id: @forecast.id, id: @prediction.id } it "should be successful" do response.should be_success end it "should assign @user" do assigns(:user).should be_a(User) assigns(:user).id.should eq @forecast.user_id assigns(:user).uid.should eq request.session[:user][:uid] end it "should assign @forecast" do assigns(:forecast).should be_a(Forecast) assigns(:forecast).user_id.should eq @user.id end it "should assign @prediction" do assigns(:prediction).should be_a(Prediction) assigns(:prediction).forecast_id.should eq @forecast.id end it "should render 'predictions/edit'" do response.should render_template('predictions/edit') end end describe "PUT 'update'" do context "when valid" do before do @updated_attributes = @attrs.merge(winning_team_score: 34) put :update, forecast_id: @forecast.id, id: @prediction.id, prediction: @updated_attributes end it "should be successful and redirect" do response.status.should be(301) end it "should assign @user" do assigns(:user).should be_a(User) assigns(:user).id.should eq @forecast.user_id assigns(:user).uid.should eq request.session[:user][:uid] end it "should assign @forecast" do assigns(:forecast).should be_a(Forecast) assigns(:forecast).user_id.should eq @user.id end it "should assign @prediction" do assigns(:prediction).should be_a(Prediction) assigns(:prediction).forecast_id.should eq @forecast.id assigns(:prediction).winning_team_score.should eq @updated_attributes[:winning_team_score] end it "should redirect to 'users#show'" do response.should redirect_to user_path(@user.id) end end context "when invalid" do before do @invalid_updated_attributes = @attrs.merge(winning_team_id: nil) put :update, forecast_id: @forecast.id, id: @prediction.id, prediction: @invalid_updated_attributes end it "should be invalid" do response.status.should be(422) end it "should assign @user" do assigns(:user).should be_a(User) assigns(:user).id.should eq @forecast.user_id assigns(:user).uid.should eq request.session[:user][:uid] end it "should assign @forecast" do assigns(:forecast).should be_a(Forecast) assigns(:forecast).user_id.should eq @user.id end it "should assign @prediction" do assigns(:prediction).should be_a(Prediction) assigns(:prediction).forecast_id.should eq @forecast.id end it "should have errors" do assigns(:prediction).errors.any?.should be_true assigns(:prediction).errors.full_messages.should include("Winning team can't be blank") end it "should render 'predictions/edit'" do response.should render_template('predictions/edit') end end end end end
class AddShippableFiles < ActiveRecord::Migration def change create_table :orders_files, id: false, force: true do |t| t.integer :order_id t.integer :file_object_id end end end
# encoding: utf-8 control "V-92749" do title "The Apache web server must install security-relevant software updates within the configured time period directed by an authoritative source (e.g., IAVM, CTOs, DTMs, and STIGs)." desc "Security flaws with software applications are discovered daily. Vendors are constantly updating and patching their products to address newly discovered security vulnerabilities. Organizations (including any contractor to the organization) are required to promptly install security-relevant software updates (e.g., patches, service packs, and hot fixes). Flaws discovered during security assessments, continuous monitoring, incident response activities, or information system error handling must also be addressed expeditiously. The Apache web server will be configured to check for and install security-relevant software updates from an authoritative source within an identified time period from the availability of the update. By default, this time period will be every 24 hours.false" impact 0.5 tag "check": "Determine the most recent patch level of the Apache Web Server 2.4 software, as posted on the Apache HTTP Server Project website. In a command line, type 'httpd -v'. If the version is more than one version behind the most recent patch level, this is a finding." tag "fix": "Install the current version of the web server software and maintain appropriate service packs and patches." # Write Check Logic Here describe package('httpd') do its('version') { should cmp >= 'httpd-2.4.6-90.el7.x86_64' } end end
require 'spec_helper' describe Freee::Amount do let(:client_id) { get_client_id } let(:secret_key) { get_secret_key } let(:token) { get_token } let(:amount) { Freee::Amount } before(:each) do Freee::Base.config(client_id, secret_key, token) end describe 'should can be able to create instance' do subject { amount.current_report } it { is_expected.not_to be_nil } it { is_expected.to be_instance_of(Freee::Response::Amount) } end describe 'should be get information of amount by current' do subject { amount.current_report } it { is_expected.to include('company_id') } it { is_expected.to include('start_date') } it { is_expected.to include('end_date') } end end
class ReviewsController < ApplicationController before_action :check_for_login, :only => [:new] def index redirect_to root_path end def new @review = Review.new end def create #need tob build create page. review = Review.create review_params redirect_to products_path end def edit @review = Review.find params[:id] end def update review = Review.find params[:id] review.update review_params redirect_to review_path end def show @review = Review.find params[:id] end def destroy review = Review.find params[:id] review.destroy redirect_to products_path end private def review_params params.require(:review).permit(:title, :author, :date, :rating, :brief, :product_id, :user_id) end end
module DelayedExecution def self.after(delay, &block) Potion::Handler.new.postDelayed(BlockRunnable.new(&block), delay * 1000.0) end class BlockRunnable def initialize(&block) @block = block end def run @block.call end end end
class InvestorFinancing < ApplicationRecord belongs_to :investor belongs_to :loan accepts_nested_attributes_for :investor accepts_nested_attributes_for :loan end
require 'open-uri' require 'nokogiri' require 'data_mapper' require 'dm-sqlite-adapter' ENV['DATABASE_URL'] ||= "sqlite://#{Dir.pwd}/students.db" DataMapper.setup(:default, ENV['DATABASE_URL']) DataMapper.auto_migrate! class Student include DataMapper::Resource property :id, Serial property :image, String property :name, String property :tagline, String property :short, Text property :aspirations, Text property :interests, Text property :slug, String def self.slugify_students Student.all.each do |student| if student.name student.slugify! puts "Slugified #{student.name} into #{student.slug}" end end end def slugify! self.slug = name.downcase.gsub(" ", "-") self.save end @@url = 'http://students.flatironschool.com/' @@root_doc = Nokogiri::HTML(open(@@url)) def self.pull_student_links @@links = @@root_doc.css('.columns').css('a').collect { |s| s['href'] } end def self.pull_all_student_profiles self.pull_student_links @@links.each { |link| self.new_from_url(@@url + link) } end def self.get_page(link) begin html = open(link) Nokogiri::HTML(html) rescue => e puts "Failed to open #{link} because of #{e}" end end def self.new_from_url(url) doc = self.get_page(url) self.create(self.get_content(doc)) end def self.get_content(doc) content_paths = { :name => '#about h1', :image => '#about img', :tagline => '#about h2', :short => '#about h2 + p', :aspirations => '#about h3 + p', :interests => '#about h3 + p + h3 + p' } result = {} content_paths.each do |key, value| begin # ("#{key}=",doc.css(value).text) if key == :image result[key] = doc.css(value)[0]['src'] else result[key] = doc.css(value).text end rescue Exception => e puts "Scrape error for content key: #{key} error: #{e}" end end result end def self.find_by_name(name) self.first(:name=>name) end def self.find(id) self.get(id) end end DataMapper.finalize DataMapper.auto_upgrade!
class CreateTickets < ActiveRecord::Migration[5.2] def change unless table_exists? Ticket.table_name create_table Ticket.table_name do |t| t.integer :ticket_id, comment: 'Identifica o id do ticket' t.string :subject, comment: 'Identifica o assunto do ticket' t.string :raw_subject, comment: 'Identifica o assunto cru do ticket' t.string :description, comment: 'Identifica a descrição do ticket' t.string :priority, comment: 'Identifica a prioridade do ticket' t.string :status, comment: 'Identifica o status do ticket' t.string :recipient, comment: 'Identifica o recebedor do ticket' t.numeric :requester_id, comment: 'Identifica o solicitante id do ticket' t.numeric :submitter_id, comment: 'Identifica o apresentador id do ticket' t.numeric :assignee_id, comment: 'Identifica o atribuido id do ticket' t.numeric :organization_id, comment: 'Identifica a organização id do ticket' t.numeric :group_id, comment: 'Identifica o grupo id do ticket' t.numeric :forum_topic_id, comment: 'Identifica o forum do ticket' t.numeric :problem_id, comment: 'Identifica o problema id do ticket' t.integer :has_incidents, comment: 'Identifica o se tem incidentes id do ticket' t.integer :is_public, comment: 'Identifica o se é publico o ticket' t.integer :allow_channelback, comment: 'Identifica se permitir canal de retorno do ticket' t.integer :allow_attachments, comment: 'Identifica se permitir anexos no ticket' t.string :satisfaction_rating, comment: 'Identifica a satisfação do ticket' t.numeric :ticket_form_id, comment: 'Identifica o formulario id do ticket' t.numeric :brand_id, comment: 'Identifica a marca do ticket' t.date :due_at, comment: 'Identifica o horario de devido do ticket' t.integer :flag_game, default: 0, comment: 'Identifica se o ticket foi atualiazado nas regras do game 0-Não 1-Sim' t.numeric :xp, default: 0, comment: 'Identifica o xp do ticket' t.integer :flag_calc_level, default: 0, comment: 'Identifica o ticket foi calculado level 0-não 1-sim' t.timestamp :open_at, comment: 'Identifica o horario de abertura do ticket' t.timestamp :changed_at, comment: 'Identifica o horario de mudança do ticket' t.timestamp :closed_at, comment: 'Identifica o horario de abertura do ticket' t.timestamps end end end end
class AddAllowedVisitationToSubscriptionPlan < ActiveRecord::Migration[5.1] def change add_column :subscription_plans, :allowed_visitation_count, :string, default: 'unlimited' end end
=begin Create method encrypt with argument string Set index to 0 Create placeholder variable with "" Loop through each letter of the word until the last letter Use the .next method to advance every letter of a string one letter forward Have each letter add to the placeholder variable Print the final result =end def encrypt(string) index = 0 empty_string = "" while index < string.length if string[index] == "z" empty_string = "a" else empty_string = empty_string + string[index].next end index +=1 end p empty_string end encrypt("abc") =begin Create method encrypt with argument string Set index to 0 Create placeholder variable with "" Create variable containing "abcdefghijklmnopqrstuvwxyz" Loop through each letter of the word until the last letter is reached Create a new string that contains the letter corresponding to the original string Find the index of that new string letter in the "abcdefghijklmnopqrstuvwxyz" string and subtract by 1 Add each letter to the placeholder variable Print the final result =end def decrypt(string) index= 0 a_to_z = "abcdefghijklmnopqrstuvwxyz" empty_string = "" while index < string.length new_string = string[index] position = a_to_z.index(new_string) second_index = position - 1 empty_string = empty_string + a_to_z[second_index] end p empty_string end =begin DRIVER CODE encrypt("abc") encrypt("zed") decrypt("bcd") decrypt("afe") Why does decrypt(encrypt("swordfish")) work? This nested call method works because the output of the encrypt method provides the argument of the decrypt method. =end =begin Add an interface Ask user if they would like to decrypt or encrypt and save input as variable Ask for password and save it as variable Use if/else to call for encrypt or decrypt setting password as argument Run operation =end puts "Hello! Would you like to encrypt or decrypt your code?" input = gets.chomp puts "What is your password?" password = gets.chomp if input == "encrypt" p encrypt(password) elsif input == "decrypt" p decrypt(password) else p "Please choose to encrypt or decrypt." end
# == Schema Information # # Table name: resources_users # # resource_id :integer # user_id :integer # created_at :datetime # updated_at :datetime # # Indexes # # index_resources_users_on_resource_id_and_user_id (resource_id,user_id) UNIQUE # require 'rails_helper' RSpec.describe ResourceCompletion, type: :model do context 'associations' do it { should belong_to(:user) } it { should belong_to(:resource) } end end
class AwardType < ActiveRecord::Base attr_accessible :code, :name validates_presence_of :code, :name end
require 'rails_helper' require 'byebug' RSpec.describe KepplerFrontend::Urls::Assets, type: :services do context 'assets urls' do before(:all) do @root = KepplerFrontend::Urls::Roots.new @assets = KepplerFrontend::Urls::Assets.new end context 'core urls' do let(:result) {"#{@root.rocket_root}/app/assets/images/keppler_frontend/app"} it { expect(@assets.core_assets('images', 'app')).to eq(result) } end context 'front urls' do let(:result) {"/assets/keppler_frontend/app/image.jpg"} it { expect(@assets.front_assets('image.jpg')).to eq(result) } end end end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable before_validation :downcase_username before_validation :set_default_role devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or protected) attributes for your model has_many :trips, dependent: :destroy has_many :markers, through: :trips, dependent: :destroy attr_accessible :bio, :birthdate, :email, :firstname, :lastname, :password, :password_confirmation, :remember_me, :username, :avatar, :location mount_uploader :avatar, UserAvatarUploader validate :avatar_size_validation validates :firstname, presence: true, length:{minimum:2} validates :lastname, presence: true, length:{minimum:2} validates :username, presence: true, uniqueness: true, length:{maximum:15} accepts_nested_attributes_for :trips class << self def search_results query where(id: select('users.id').joins(:trips).joins(:markers).where( [search_query, Trip.search_query, Marker.search_query].join(' or '), search: "%#{query}%")) end def search_query 'LOWER(users.firstname) like :search OR LOWER(users.lastname) like :search OR LOWER(users.username) like :search OR LOWER(users.bio) like :search' end end def role?(role) self.role == role end private def downcase_username self.username.downcase! if self.username end private def set_default_role self.role ||= 'registered' end private def avatar_size_validation errors[:avatar] << "should be less than 1MB" if avatar.size > (1.2).megabyte end end
# Setup object construction and default behaviors class DataTable attr_reader :header def initialize( header = Array.new ) raise ArgumentError unless header.is_a?( Array ) @header = header end def to_s @header.join( ' ' ) + self.inject( "\n" ) { |str,row| str << row.join( ' ' ) + "\n" } end end
#encoding: utf-8 class EmailListingsController < ApplicationController before_filter :authenticate_user! # GET /email_listings # GET /email_listings.json def index @email_listings = EmailListing.all respond_to do |format| format.html # index.html.erb format.json { render json: @email_listings } end end # GET /email_listings/1 # GET /email_listings/1.json def show @email_listing = EmailListing.find(params[:id]) unless current_user.is_admin? @emails = [] else @emails = @email_listing.emails end @listing = (@emails.nil? ? [] : @emails.map(&:address).compact.each_slice(@email_listing.per_line).to_a) @listing_size = @emails.size respond_to do |format| format.html # show.html.erb format.json { render json: @email_listing } end end # GET /email_listings/new # GET /email_listings/new.json def new @email_listing = EmailListing.new @countries = [] respond_to do |format| format.html # new.html.erb format.json { render json: @email_listing } end end # GET /email_listings/1/edit def edit @email_listing = EmailListing.find(params[:id]) @countries = @email_listing.countries.split(";") rescue [] end # POST /email_listings # POST /email_listings.json def create params[:email_listing][:tags] = params[:email_listing][:tags].sort.first if params[:email_listing][:tags].present? params[:email_listing][:countries] = params[:email_listing][:countries].sort.join(";") if params[:email_listing][:countries].present? @email_listing = EmailListing.new(params[:email_listing]) # @email_listing.update_attribute(:countries, countries) respond_to do |format| if @email_listing.save format.html { redirect_to @email_listing, notice: 'Email listing was successfully created.' } #format.json { render json: @email_listing, status: :created, location: @email_listing } else @countries = params[:email_listing][:countries].split(';') rescue [] format.html { render action: "new" } #format.json { render json: @email_listing.errors, status: :unprocessable_entity } end end end # PUT /email_listings/1 # PUT /email_listings/1.json def update params[:email_listing][:tags] = params[:email_listing][:tags].sort.first if params[:email_listing][:tags].present? params[:email_listing][:countries] = params[:email_listing][:countries].sort.join(";") if params[:email_listing][:countries].present? @email_listing = EmailListing.find(params[:id]) respond_to do |format| if @email_listing.update_attributes(params[:email_listing]) format.html { redirect_to @email_listing, notice: 'Email listing was successfully updated.' } #format.json { head :no_content } else @countries = @email_listing.countries_to_a format.html { render action: "edit" } #format.json { render json: @email_listing.errors, status: :unprocessable_entity } end end end # DELETE /email_listings/1 # DELETE /email_listings/1.json def destroy @email_listing = EmailListing.find(params[:id]) @email_listing.destroy respond_to do |format| format.html { redirect_to email_listings_url } format.json { head :no_content } end end end
class ImageImporterWorker include Sidekiq::Worker def perform(gallery_id) image_import = Refinery::ImageImporter.new(gallery_id) image_import.import end end
# frozen_string_literal: true require 'swagger_helper' RSpec.describe 'News', type: :request do before do FactoryBot.create(:config) FactoryBot.create_list(:news, 5) end let(:news_limit) { 3 } after do |example| example.metadata[:response][:content] = { 'application/json' => { example: JSON.parse(response.body, symbolize_names: true) } } end path '/api/v1/news/index' do get('list news') do tags 'News' produces 'application/json' response(200, 'successful') do run_test! end end end path '/api/v1/news/relevant?news_limit={news_limit}' do get('relevant news') do tags 'News' produces 'application/json' parameter name: :news_limit, in: :path, type: :integer, required: true response(200, 'successful') do run_test! end end end end
Given /^that the app is set up$/ do # create questions question1 = Question.find_or_create_by_xml("Why is the sky blue?") question2 = Question.find_or_create_by_xml("What is the meaning of life?") # create tags tag1 = Tag.find_or_create_by_name("meteorology") tag2 = Tag.find_or_create_by_name("philosophy") # tag questions question1.tags << tag1 question2.tags << tag2 end Given /^I added a question with content "(.*?)"$/ do |question_xml| visit path_to("the new question page") fill_in 'question_xml', :with => question_xml click_button 'Save' end # filler method until feature is implemented Given /^I am logged in as an instructor$/ do visit path_to("the homepage") end # filler method until feature is implemented Given /^I am logged in as a non\-instructor$/ do visit path_to("the homepage") end When /^I try to generate a quiz$/ do click_on "Generate Quiz" end When /^I try to generate a quiz with (\d+) questions$/ do |num_questions| fill_in 'question[number_of_questions]', :with => num_questions # Something's wrong here ... end When /^I try to generate a quiz with the topic "(.*?)"$/ do |tag| select tag, :from => 'topic' end Given /^PENDING/ do pending end Given /^the "(.*?)" "(.*?)" exists$/ do |resource_type, resource_name| resource_type.to_s.classify.constantize.find_or_create_by_name(resource_name.to_s) end Given /^the user group "(.*?)" exists$/ do |group| UserGroup.create(:name => group) end Given /^the question group "(.*?)" exists$/ do |group| QuestionGroup.create(:name => group) end Given /^the users? "(.*?)" exists with uid "(.*?)"$/ do |user, uid| User.create(:name => user, :uid => uid, :provider => "twitter") end Given /^the following users exist:$/ do |fields| fields.rows_hash.each do |user, uid| User.create(:name => user, :uid => uid, :provider => "twitter") end end Given /^the following questions exist:$/ do |fields| fields.rows_hash.each do |question, number| Question.create(:xml => question) end end # Example: # # Given the following attempts exist: # | Question | User | Answer | Correctness | # | Question A | Student A | Apple | True | # | Question B | Student A | Orange | False | # | Question A | Student B | Orange | False | Given /^the following attempts exist:$/ do |fields| fields.hashes.each do |attempt| question = attempt["Question"] user = attempt["User"] answer = attempt["Anser"] correctness = attempt["Correctness"] Attempt.create( :user_id => User.find_by_name(user).uid, :question_id => Question.find_by_xml(question).id, :answer => answer, :is_correct => correctness == "True" ? true : false ) end end Given /^"(.*?)" is in the user group "(.*?)"$/ do |user, group| UserGroup.find_by_name(group).users << User.find_by_name(user) end Given /^"(.*?)" is in the question group "(.*?)"$/ do |question, group| QuestionGroup.find_by_name(group).questions << Question.find_by_xml(question) end Given /^"(.*?)" is the owner of "(.*?)"$/ do |user, group| User.find_by_name(user).add_role :owner, UserGroup.find_by_name(group) end Given /^"(.*?)" is the owner of question group "(.*?)"$/ do |user, group| User.find_by_name(user).add_role :owner, QuestionGroup.find_by_name(group) end Given /^"(.*?)" is a viewer of "(.*?)"$/ do |user, group| User.find_by_name(user).add_role :viewer, UserGroup.find_by_name(group) end Given /^"(.*?)" is a viewer of question group "(.*?)"$/ do |user, group| User.find_by_name(user).add_role :viewer, QuestionGroup.find_by_name(group) end When /^I visit the user group edit page of "(.*?)"$/ do |group| visit edit_user_group_path(UserGroup.find_by_name(group)) end # http://stackoverflow.com/questions/5255250/cucumber-test-file-download Then /^I should receive a file "(.*?)"$/ do |file| page.response_headers['Content-Type'].should == "text/csv" && page.response_headers['Content-Disposition'].should =~ /#{file}/ end When /^I upload a CSV file "(.*?)" with the following content:$/ do |filename, string| visit new_upload_path file = Tempfile.new(string) attach_file(:upload_upload_file, Rails.root.join('features', filename)) click_button "Upload CSV" end Given /^"(.*?)" is added as a question attribute$/ do |arg1| QuestionAttribute.create(name: arg1, backend_type: 'string') end Given /^I have admin privilege$/ do current_user.add_role :admin end Given /^"(.*?)" has admin privilege$/ do |name| User.find_by_name(name).add_role :admin end Then /^the quiz should have (\d+) questions$/ do |num_questions| body = page.body end Then /^the quiz should have the topic "(.*?)"$/ do |tag| if page.respond_to? :should page.should have_content(tag) else assert page.has_content?(tag) end end Then /^I should get a download with the filename "([^\"]*)"$/ do |filename| page.response_headers['Content-Disposition'].should include("filename=\"#{filename}\"") end Given /^I post to "(.*?)" with:$/ do |path, string| post path, string, "CONTENT_TYPE" => "application/json" end Given /^"(.*?)" is added as a user attribute$/ do |arg1| UserAttribute.create(name: arg1, backend_type: 'string') end And /^I should see an error message$/ do if page.respond_to? :should page.should have_selector('#flash_error') else assert page.has_selector?('#flash_error') end end
require 'test_helper' class ExpenseAccountsControllerTest < ActionDispatch::IntegrationTest setup do @expense_account = expense_accounts(:one) end test "should get index" do get expense_accounts_url assert_response :success end test "should get new" do get new_expense_account_url assert_response :success end test "should create expense_account" do assert_difference('ExpenseAccount.count') do post expense_accounts_url, params: { expense_account: { description: @expense_account.description, invoice_id: @expense_account.invoice_id, reverse_invoice: @expense_account.reverse_invoice, total: @expense_account.total, total_gross: @expense_account.total_gross } } end assert_redirected_to expense_account_url(ExpenseAccount.last) end test "should show expense_account" do get expense_account_url(@expense_account) assert_response :success end test "should get edit" do get edit_expense_account_url(@expense_account) assert_response :success end test "should update expense_account" do patch expense_account_url(@expense_account), params: { expense_account: { description: @expense_account.description, invoice_id: @expense_account.invoice_id, reverse_invoice: @expense_account.reverse_invoice, total: @expense_account.total, total_gross: @expense_account.total_gross } } assert_redirected_to expense_account_url(@expense_account) end test "should destroy expense_account" do assert_difference('ExpenseAccount.count', -1) do delete expense_account_url(@expense_account) end assert_redirected_to expense_accounts_url end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe DashboardController, type: :controller do describe 'GET :index' do describe 'html' do let(:user) { create(:user) } let(:company) { create(:company) } it 'redirects not signed in user to root' do get :index expect(response).to redirect_to root_path end it 'redirects to new company url when user has no company' do sign_in user get :index, format: :html expect(response).to redirect_to(new_company_url) end context 'when user has a company' do before do user.company = company user.save! end it 'renders SPA scaffold to signed in user' do sign_in user get :index, format: :html expect(response).to render_template :index end it 'is success' do sign_in user get :index, format: :html expect(response).to have_http_status(200) end end end end end
require './contact.rb' # Interfaces between a user and their contact list. Reads from and writes to standard I/O. class ContactList # TODO: Implement user interaction. This should be the only file where you use `puts` and `gets`. def initialize puts "Here is a list of available commands: new - Create a new contact list - list all contacts show - Show a contact search - Search contacts" command = gets.chomp.to_s.downcase if command == "list" Contact.all elsif command.include?("show") id = command.match(/\d{8}/) id = id.to_s Contact.find(id) elsif command.include?("search") term = command.split(" ") term = term[1] term = term.to_s Contact.search(term) else Contact.create end end end test_1 = ContactList.new
require 'test_helper' class QuestaosControllerTest < ActionDispatch::IntegrationTest setup do @questao = questaos(:one) end test "should get index" do get questaos_url assert_response :success end test "should get new" do get new_questao_url assert_response :success end test "should create questao" do assert_difference('Questao.count') do post questaos_url, params: { questao: { descricao: @questao.descricao } } end assert_redirected_to questao_url(Questao.last) end test "should show questao" do get questao_url(@questao) assert_response :success end test "should get edit" do get edit_questao_url(@questao) assert_response :success end test "should update questao" do patch questao_url(@questao), params: { questao: { descricao: @questao.descricao } } assert_redirected_to questao_url(@questao) end test "should destroy questao" do assert_difference('Questao.count', -1) do delete questao_url(@questao) end assert_redirected_to questaos_url end end
class ValidationTracker include Mongoid::Document field :environment_config, type: String field :server, type: String field :tag, type: String end
class CreateSharedUploads < ActiveRecord::Migration def self.up create_table :shared_uploads do |t| t.integer "uploadable_id" t.string "uploadable_type" t.integer "upload_id" t.integer "shared_by_id" t.timestamps end add_index "shared_uploads", "uploadable_id" add_index "shared_uploads", "upload_id" add_index "shared_uploads", "shared_by_id" end def self.down drop_table :shared_uploads end end
require 'spec_helper' describe RakutenWebService::Gora::CourseDetail do let(:endpoint) { 'https://app.rakuten.co.jp/services/api/Gora/GoraGolfCourseDetail/20170623' } let(:affiliate_id) { 'dummy_affiliate_id' } let(:application_id) { 'dummy_application_id' } let(:expected_query) do { affiliateId: affiliate_id, applicationId: application_id, formatVersion: '2', golfCourseId: 120092 } end before do RakutenWebService.configure do |c| c.affiliate_id = affiliate_id c.application_id = application_id end end describe '#find' do before do response = JSON.parse(fixture('gora/course_detail_search.json')) @expected_request = stub_request(:get, endpoint). with(query: expected_query).to_return(body: response.to_json) end context 'call the find method' do describe 'a respond object' do let(:expected_json) do response = JSON.parse(fixture('gora/course_detail_search.json')) response['Item'] end subject { RakutenWebService::Gora::CourseDetail.find(expected_query[:golfCourseId]) } it { is_expected.to be_a RakutenWebService::Gora::CourseDetail } specify 'should be accessed by key' do expect(subject['golfCourseName']).to eq(expected_json['golfCourseName']) expect(subject['golf_course_name']).to eq(expected_json['golfCourseName']) end describe '#golf_course_name' do subject { super().golf_course_name } it { is_expected.to eq(expected_json['golfCourseName']) } end specify 'should be accessed to ratings' do expect(subject.ratings.size).to eq(expected_json['ratings'].size) expect(subject.ratings.first.nick_name).to eq(expected_json['ratings'].first['nickName']) end specify 'should be accessed to new_plans' do expect(subject.new_plans.size).to eq(expected_json['newPlans'].size) expect(subject.new_plans.first.name).to eq(expected_json['newPlans'].first['planName']) end end end end end
require 'spec_helper' describe GraphQLIncludable::ConnectionIncludesBuilder do context 'A connection with only nodes' do context 'with no siblings or deep nesting' do it 'generates the correct includes pattern' do builder = subject builder.nodes(:nodes_a) expect(builder.includes?).to eq(true) expect(builder.nodes_builder.includes?).to eq(true) expect(builder.nodes_builder.included_path).to eq([:nodes_a]) expect(builder.nodes_builder.active_record_includes).to eq([:nodes_a]) expect(builder.edges_builder.builder.includes?).to eq(false) expect(builder.edges_builder.builder.included_path).to eq([]) expect(builder.edges_builder.builder.active_record_includes).to eq({}) expect(builder.edges_builder.node_builder.includes?).to eq(false) expect(builder.edges_builder.node_builder.included_path).to eq([]) expect(builder.edges_builder.node_builder.active_record_includes).to eq({}) end end context 'with deep nesting' do it 'generates the correct includes pattern' do builder = subject builder.nodes(:through_something, :to, :nodes_a) builder.edges do path(:through_something) node(:node_on_edge_a) end expect(builder.includes?).to eq(true) expect(builder.nodes_builder.includes?).to eq(true) expect(builder.nodes_builder.included_path).to eq([:through_something, :to, :nodes_a]) expect(builder.nodes_builder.active_record_includes).to eq(through_something: { to: [:nodes_a] }) expect(builder.edges_builder.builder.includes?).to eq(true) expect(builder.edges_builder.builder.included_path).to eq([:through_something]) expect(builder.edges_builder.builder.active_record_includes).to eq([:through_something]) expect(builder.edges_builder.node_builder.includes?).to eq(true) expect(builder.edges_builder.node_builder.included_path).to eq([:node_on_edge_a]) expect(builder.edges_builder.node_builder.active_record_includes).to eq([:node_on_edge_a]) end end end context 'A connection with only edges and node' do context 'when only edges is given' do it 'does not generate includes' do builder = subject builder.edges { path(:edges_a) } expect(builder.includes?).to eq(false) expect(builder.nodes_builder.includes?).to eq(false) expect(builder.edges_builder.builder.includes?).to eq(true) expect(builder.edges_builder.builder.included_path).to eq([:edges_a]) expect(builder.edges_builder.builder.active_record_includes).to eq([:edges_a]) expect(builder.edges_builder.node_builder.includes?).to eq(false) expect(builder.edges_builder.node_builder.included_path).to eq([]) expect(builder.edges_builder.node_builder.active_record_includes).to eq({}) end end context 'when only edge_node is given' do it 'does not generate includes' do builder = subject builder.edges { node(:node_on_edge_a) } expect(builder.includes?).to eq(false) expect(builder.nodes_builder.includes?).to eq(false) expect(builder.edges_builder.builder.includes?).to eq(false) expect(builder.edges_builder.builder.included_path).to eq([]) expect(builder.edges_builder.builder.active_record_includes).to eq({}) expect(builder.edges_builder.node_builder.includes?).to eq(true) expect(builder.edges_builder.node_builder.included_path).to eq([:node_on_edge_a]) expect(builder.edges_builder.node_builder.active_record_includes).to eq([:node_on_edge_a]) end end context 'when edges and edge_node are given' do it 'generates the correct includes pattern' do builder = subject builder.edges do path(:edges_a) node(:node_on_edge_a) end expect(builder.includes?).to eq(true) expect(builder.nodes_builder.includes?).to eq(false) expect(builder.nodes_builder.included_path).to eq([]) expect(builder.nodes_builder.active_record_includes).to eq({}) expect(builder.edges_builder.builder.includes?).to eq(true) expect(builder.edges_builder.builder.included_path).to eq([:edges_a]) expect(builder.edges_builder.builder.active_record_includes).to eq([:edges_a]) expect(builder.edges_builder.node_builder.includes?).to eq(true) expect(builder.edges_builder.node_builder.included_path).to eq([:node_on_edge_a]) expect(builder.edges_builder.node_builder.active_record_includes).to eq([:node_on_edge_a]) end end end context 'A connection with nodes and edges' do context 'with no siblings or deep nesting' do it 'generates the correct includes pattern' do builder = subject builder.nodes(:nodes_a) builder.edges do path(:edges_a) node(:node_on_edge_a) end expect(builder.includes?).to eq(true) expect(builder.nodes_builder.includes?).to eq(true) expect(builder.nodes_builder.included_path).to eq([:nodes_a]) expect(builder.nodes_builder.active_record_includes).to eq([:nodes_a]) expect(builder.edges_builder.builder.includes?).to eq(true) expect(builder.edges_builder.builder.included_path).to eq([:edges_a]) expect(builder.edges_builder.builder.active_record_includes).to eq([:edges_a]) expect(builder.edges_builder.node_builder.includes?).to eq(true) expect(builder.edges_builder.node_builder.included_path).to eq([:node_on_edge_a]) expect(builder.edges_builder.node_builder.active_record_includes).to eq([:node_on_edge_a]) end end context 'with deep nesting' do it 'generates the correct includes pattern' do builder = subject builder.nodes(:through_something, :to, :nodes_a) builder.edges do path(:through_something) node(:node_on_edge_a) end expect(builder.includes?).to eq(true) expect(builder.nodes_builder.includes?).to eq(true) expect(builder.nodes_builder.included_path).to eq([:through_something, :to, :nodes_a]) expect(builder.nodes_builder.active_record_includes).to eq(through_something: { to: [:nodes_a] }) expect(builder.edges_builder.builder.includes?).to eq(true) expect(builder.edges_builder.builder.included_path).to eq([:through_something]) expect(builder.edges_builder.builder.active_record_includes).to eq([:through_something]) expect(builder.edges_builder.node_builder.includes?).to eq(true) expect(builder.edges_builder.node_builder.included_path).to eq([:node_on_edge_a]) expect(builder.edges_builder.node_builder.active_record_includes).to eq([:node_on_edge_a]) end end context 'with siblings' do it 'generates the correct includes pattern' do builder = subject builder.nodes(:nodes_a) builder.edges do path(:edges_a) sibling_path(:other_association_for_edges) do path(:that_goes_deeper) end node(:node_on_edge_a) end expect(builder.includes?).to eq(true) expect(builder.nodes_builder.includes?).to eq(true) expect(builder.nodes_builder.included_path).to eq([:nodes_a]) expect(builder.nodes_builder.active_record_includes).to eq([:nodes_a]) expect(builder.edges_builder.builder.includes?).to eq(true) expect(builder.edges_builder.builder.included_path).to eq([:edges_a]) expect(builder.edges_builder.builder.active_record_includes).to eq( [ :edges_a, { other_association_for_edges: [:that_goes_deeper] } ] ) expect(builder.edges_builder.node_builder.includes?).to eq(true) expect(builder.edges_builder.node_builder.included_path).to eq([:node_on_edge_a]) expect(builder.edges_builder.node_builder.active_record_includes).to eq([:node_on_edge_a]) end end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) puts "Destroying old records" Purchase.destroy_all User.destroy_all puts "Seeding started" puts "Creating DB" user1 = User.create(username: "User1", email: "User1@test.com", password: "password") 3.times do user1.listings.create( name: "Face Masks", description: "Pack of 5 handmade facemasks", price: rand(10...100.0), category: "Clothing", status: 1, ) end user1.addresses.create( street: "Fake", number: 22, postcode: 3000, suburb: "Melbourne", state: "VIC", ) user2 = User.create(username: "User2", email: "User2@test.com", password: "password") 3.times do user2.listings.create( name: "Button Down Shirt", description: "Pack of Two Mens Button down Shirts, Large", price: rand(40.0...50.0), category: "Clothing", status: 1, ) end user2.addresses.create( street: "fake2", number: 22, postcode: 3123, suburb: "Hawthorne East", state: "VIC", ) user3 = User.create(username: "User3", email: "User3@test.com", password: "password") 3.times do user3.listings.create( name: "Pillow", description: "Knitted Pineapple pillow", price: rand(40.0...50.0), category: "Home", status: 1, ) end user3.addresses.create( street: "fake3", number: 22, postcode: 3123, suburb: "Hawthorne East", state: "VIC", ) # USER4 Start user4 = User.create(username: "User4", email: "User4@test.com", password: "password") 4.times do user4.listings.create( name: "Bike Accessories", description: "Random assortment of bike accessories", price: rand(40.0...50.0), category: "Sport", status: 1, ) end user4.addresses.create( street: "fake4", number: 22, postcode: 3000, suburb: "Melbourne", state: "VIC", ) puts "Seeding complete"
class ProfilesController < ApplicationController breadcrumb "Profile", :profile_path, match: :exact def show end def edit breadcrumb "Edit", :edit_profile_path end def update if current_user.update post_params redirect_to profile_path, flash: {success: 'Data updated successfully!'} else render action: :edit end end protected def post_params params.require(:user).permit(:full_name, :phone, :company_name, :password, :password_comfirmation) end end
require 'spec_helper' module WastebitsClient describe ForgotPassword do describe "Attributes" do it { should respond_to :email } it { should respond_to :url } end describe "Instance methods" do it { should respond_to :send_instructions } end end end
require ("pry") require('minitest/autorun') require('minitest/rg') require_relative('../Room.rb') require_relative('../Guest.rb') require_relative('../Song.rb') class RoomTest < MiniTest::Test def test_room_number room1 = Room.new(1,2) room2 = Room.new(2,2) room_number_1 = room1.number room_number_2 = room2.number assert_equal(1,room_number_1) assert_equal(2,room_number_2) end def test_room_capacity room3 = Room.new(3,6) room3_capacity = room3.capacity assert_equal(6,room3_capacity) end def test_guestlist_empty room2 = Room.new(2,2) room2_guestlist = room2.guestlist assert_equal([],room2_guestlist) end def test_playlist_empty room2 = Room.new(2,2) room2_playlist = room2.playlist assert_equal([],room2_playlist) end def test_add_guests_to_guestlist room4 = Room.new(4,3) guest1 = Guest.new("David",10) guest2 = Guest.new("Tom",3) guest3 = Guest.new("Terry",11) guest4 = Guest.new("Garry",12) guestlist = [guest1, guest2, guest3, guest4] # room4.remove_guest_from_guestlist("all") room4_guestlist = room4.add_guests_to_guestlist(guestlist,room4) # assert_equal(2,room1.guestlist.length) assert_equal("David",room4.guestlist[0].name) assert_equal(6,room4.guestlist[2].cash) # assert_equal("Tom",room1.guestlist[1].name) # assert_equal("Terry",room1_guestlist[2].name) end def test_remove_guest_from_guestlist room1 = Room.new(1,3) guest1 = Guest.new("David",0) guest2 = Guest.new("Tom",0) guest3 = Guest.new("Terry",0) guestlist = [guest1, guest2, guest3] # removes all guests from the guestlist room1.remove_guest_from_guestlist("all") assert_equal(0,room1.guestlist.length) room1.add_guests_to_guestlist(guestlist,room1.capacity) # removes specific guest from the guestlist room1.remove_guest_from_guestlist(guest1) assert_equal(2,room1.guestlist.length) assert_equal("Tom",room1.guestlist[0].name) end def test_add_song_to_playlist room1 = Room.new(1,2) song1 = Song.new("lalala","Pope") song2 = Song.new("Wonderwall","Oasis") song3 = Song.new("Wonderwall","Oasis") playlist = [song1, song2, song3] room1_playlist = room1.add_songs_to_playlist(playlist) assert_equal(3,room1_playlist.length) assert_equal("Wonderwall",room1_playlist[2].title) assert_equal("Oasis",room1_playlist[2].artist) end def test_enough_cash room3 = Room.new(3,2) guest1 = Guest.new("David",12) guest2 = Guest.new("Tom",5) guest3 = Guest.new("Terry",8) guestlist = [guest1, guest2, guest3] room3.enough_cash(guestlist) assert_equal(2, room3.guestlist.length) assert_equal(12, room3.guestlist[0].cash) end def test_fav_song room1 = Room.new(1,2) guest1 = Guest.new("David",12,"Porcelin","Moby") guest2 = Guest.new("David",12) song1 = Song.new("Munich","Editors") song2 = Song.new("Porcelin","Moby") guestlist = [guest1, guest2] playlist = [song1, song2] fav_song = room1.fav_song(guestlist,playlist) assert_equal("This is my favourite song",fav_song) end def test_total_cash_in_room room1 = Room.new(1,2) guest1 = Guest.new("David",12) guest2 = Guest.new("Tom",5) guest3 = Guest.new("Terry",8) guestlist = [guest1, guest2, guest3] # clear room room1.remove_guest_from_guestlist("all") # add guests room1.add_guests_to_guestlist(guestlist,room1.capacity) room1.add_guest_cash_to_room(8) assert_equal(8, room1.room_cash_available) end end
file "couchdb" => [] do sh 'git clone git://github.com/halorgium/couchdb.git' end desc "Update to the latest version of git://github.com/halorgium/couchdb.git" task :git_update do Dir.chdir('couchdb') begin sh 'git pull' ensure Dir.chdir('..') end end desc "Clean up as though this were a fresh distribution" task :dist_clean => [ :clean ] do sh 'rm -rf couchdb' end desc "Start from scratch" task :clean do sh 'rm -rf BUILD pkg' end directory "BUILD" root = `( cd .. ; pwd )`.split[0] icu = "#{root}/icu/BUILD" erlang = "#{root}/erlang/BUILD" spidermonkey = "#{root}/spidermonkey/BUILD" env = "export ERLANG_ROOT='#{erlang}' ; " env << "PATH=#{erlang}/bin:#{icu}/bin:/usr/bin:/bin:/usr/sbin:/sbin ; " if RUBY_PLATFORM =~ /linux/ env << "export LD_LIBRARY_PATH='#{icu}/lib:#{spidermonkey}/lib' ; " elsif RUBY_PLATFORM =~ /darwin/ env << "export DYLD_LIBRARY_PATH='#{icu}/lib:#{spidermonkey}/lib' ; " end prefix = Dir.getwd + "/BUILD" desc "Build CouchDB" task :build => [ :configure, :make ] do |t| end desc "Configure CouchDB" task :configure => [ "BUILD", "couchdb" ] do |t| Dir.chdir('couchdb') begin sh "#{env} ./bootstrap" sh "#{env} ./configure --prefix=#{prefix} --with-js-include=#{spidermonkey}/include/js --with-js-lib=#{spidermonkey}/lib --with-erlang=#{erlang}/lib/erlang/usr/include" ensure Dir.chdir('..') end end desc "Build CouchDB" task :make => [ "BUILD" ] do |t| Dir.chdir('couchdb') begin sh "#{env} make" sh "#{env} make install" ensure Dir.chdir('..') end sh 'rm -rf BUILD/Library BUILD/etc/logrotate.d' [ 'bin/couchdb', 'bin/couchjs', 'etc/couchdb/default.ini'].each do |f| str = IO.read("#{prefix}/#{f}") str.gsub!(prefix, ".") str.gsub!("`#{icu}/bin/icu-config --invoke`", "") str.gsub!("#{erlang}/bin/", "") File.open("#{prefix}/#{f}", "w") do |io| io.write(str) end end end desc "Run in-situ CouchDB" task :run do sh "#{env} ERLANG_ROOT=#{erlang} ; ( cd #{prefix} ; bin/couchdb )" end require 'rake/gempackagetask' gem_spec = Gem::Specification.new do |s| s.name = 'memetic-couchdb' s.version = "0.9.#{Time.new.strftime('%Y%m%d')}" s.summary = 'Memetic packaging of Couchdb' s.platform = Gem::Platform::CURRENT s.authors = ["Antony Blakey", "http://couchdb.org"] s.files = FileList["Rakefile", "{BUILD,lib}/**/*"] s.require_path = "lib" # I'm going to presume that pcre versioning is rational s.add_dependency("memetic", "~> 1.0") s.add_dependency("memetic-erlang", "~> 5.6") s.add_dependency("memetic-spidermonkey", ">= 1.7", "< 1.8") s.add_dependency("memetic-icu", "~> 4.0") end desc "Create the gem" Rake::GemPackageTask.new(gem_spec) do |pkg| pkg.need_zip = false pkg.need_tar = false end directory "../../GEM_SERVER/gems/" desc "Build the gem, move to ../../GEM_SERVER/gems/" task :default => [ :build, :gem, "../../GEM_SERVER/gems/"] do sh "mv pkg/*.gem ../../GEM_SERVER/gems/" end
require 'rails_helper' RSpec.feature 'Visiting the permissions page', type: :feature do scenario 'As an un-authenticated user, loads the login page' do visit 'permissions' expect(current_path).to eq('/users/sign_in') end scenario 'As a user with the athlete role, there should be a 403 status code' do login_athlete visit 'permissions' expect(page.status_code).to eq(403) end context 'As an authenticated user with the coach role' do before do login_coach FactoryGirl.create(:athlete_user, email: 'test@example.com') visit 'permissions' end scenario 'There should be a 200 status code' do expect(page.status_code).to eq(200) expect(current_path).to eq('/permissions') end scenario 'There should be an accurate athlete user in the table of information' do expect(page).to have_content('test@example.com') expect(page).to have_content('John') expect(page).to have_content('Smith') expect(page).to have_content(/athlete/i) end scenario 'Deleting a user should remove their information from the table' do FactoryGirl.create(:athlete_user, email: 'test1@example.com') expect { page.all('input', class: 'button-danger')[0].click } .to change { User.count }.by(-1) end scenario 'There should be a button to invite a new user which opens a modal' do expect(page).to have_content('Invite New User') click_on 'Invite New User' expect(page.find('#new-user')).not_to have_css('hidden') end scenario 'Inviting a new user should result in a pending invite' do click_on 'Invite New User' fill_in('email', with: 'invited@wisc.edu') click_on 'Invite User' expect(page).to have_content('Pending Invite') expect(page).to have_content('Successfully sent an invite to invited@wisc.edu!') end end end
#!/usr/bin/env ruby # @param {String} s # @return {Integer} def length_of_longest_substring(s) str_len = s.size max_str = '' max_len = 0 i = 0 while i < str_len if max_str.empty? max_str = s[i] end cursor = 1 loop do index = i + cursor if index == str_len break end char_check = s[index] max_str_index = max_str.index char_check if max_str_index.nil? max_str += char_check else max_len_tmp = max_str.size if max_len_tmp > max_len max_len = max_len_tmp end max_str = max_str[max_str_index + 1, max_str.size - max_str_index] + char_check break end cursor += 1 end i += cursor max_len_tmp = max_str.size if max_len_tmp > max_len max_len = max_len_tmp end end max_len end def test p length_of_longest_substring '' # 0 p length_of_longest_substring 'a' # 1 p length_of_longest_substring 'au' # 2 p length_of_longest_substring 'abcabcbb' # 3 p length_of_longest_substring 'bbbbbbb' # 1 p length_of_longest_substring 'abcdefg' # 7 p length_of_longest_substring 'aab' # 2 p length_of_longest_substring 'dvdf' # 3 p length_of_longest_substring 'anviaj' # 5 end
require 'spec_helper' describe Problem do it "is valid with a question, an answer, and a difficulty level" do expect(build :problem).to be_valid end it "is invalid without a question" do problem = build(:problem, question: nil) expect(problem).to have(1).error_on(:question) end it "is invalid without an answer" do problem = build(:problem, answer: nil) expect(problem).to have(1).error_on(:answer) end it "is invalid without a solution" do problem = build(:problem, solution: nil) expect(problem).to have(1).error_on(:solution) end end
class AddFileuploadToResults < ActiveRecord::Migration def change add_attachment :results, :attachment end end
# == Schema Information # # Table name: portfolios # # id :integer not null, primary key # date :string(255) # title :string(255) # details :string(255) # photo :string(255) # post_id :integer # created_at :datetime not null # updated_at :datetime not null # class Portfolio < ActiveRecord::Base attr_accessible :date, :title, :details, :photo, :front, :order validates_presence_of :date, :title, :post_id, :photo, :details, :order belongs_to :post mount_uploader :photo, PhotoUploader end
require 'vanagon/extensions/ostruct/json' describe "OpenStruct" do describe "with JSON mixins" do let(:test_ostruct) { OpenStruct.new(size: "big", shape: "spherical", name: "rover") } let(:json_ostruct) { %({"size":"big","shape":"spherical","name":"rover"}) } it "responds to #to_json" do expect(OpenStruct.new.respond_to?(:to_json)).to eq(true) end it "can be converted to a valid JSON object" do expect(JSON.parse(test_ostruct.to_json)).to eq(JSON.parse(json_ostruct)) end end end
class PostsController < ApplicationController before_action :find_post, only: [:edit, :update, :show, :delete] before_action :redirect_if_not_signed_in, only: [:new] def index @posts = Post.search(params[:search]) end def new @post = Post.new end # Create action saves the post into database def create @post = current_user.posts.new(post_params) @city = City.find_by(params[:city_id]) if @post.save(post_params) flash[:notice] = "Successfully created post!" redirect_to post_path(@post) else flash[:alert] = "Error creating new post!" render :new end end def find_post # @post = Post.find_by(params[:city_id]) end def show @post = Post.find_by(params[:id]) end def update @post = Post.find_by(params[:id]) if @post.update(post_params) redirect_to @post else render 'edit' end end def edit @post = Post.find_by(params[:id]) end def destroy @post = Post.find_by(params[:id]) @post.destroy redirect_to posts_path end private def post_params params.require(:post).permit(:title, :content, :city_id) end end
class Cordinate < ActiveRecord::Base reverse_geocoded_by :latitude, :longitude SAITAMA_KENCHO = { lat: 35.8569444, lng: 139.6488889 } NORTH_EDGE=36.2833376 EAST_EDGE=139.8652589 SOUTH_EDGE=35.7536154 WEST_EDGE=138.7092002 PRECISION_PAIR = { 11 => 9.5, 12 => 4.5, 13 => 2, 14 => 1, 15 => 0.5, 16 => 0.3, 17 => 0.15 } scope :quadKey, lambda { | lat, lng, precision | q = Quadkey.encode(lat, lng, precision) where("quadKey22 like ?", "#{q}%") } def self.boundary(quadKey) top_left = Quadkey.decode(quadKey) neighbors = Quadkey.neighbors(quadKey) top = top_left[0] left = top_left[1] right = Quadkey.decode(neighbors[5])[1] bottom = Quadkey.decode(neighbors[7])[0] return { top: top, bottom: bottom, left: left, right: right } end def enc_quadkey(precision) Quadkey.encode(self.latitude, self.longitude, precision) end def self.random_near @@counter ||= 0 val = PRECISION_PAIR.values[@@counter % PRECISION_PAIR.keys.count] Cordinate.near(random_cordinate, val, select: "id, latitude, longitude") end def self.random_quakey @@counter ||= 0 val = PRECISION_PAIR.keys[@@counter % PRECISION_PAIR.keys.count] Cordinate.quadKey(*random_cordinate, val) end private def self.random_cordinate lat = Kernel.rand(Cordinate::SOUTH_EDGE..Cordinate::NORTH_EDGE) lng = Kernel.rand(Cordinate::WEST_EDGE..Cordinate::EAST_EDGE) return lat, lng end end
class AddTypeToAspectLinks < ActiveRecord::Migration def change add_column :aspect_links, :type, :string end end
class NotificationsController < ApplicationController def welcome @message = "Welcome to OutResearch" end end
class Account < ActiveRecord::Base has_many :users, :dependent => :destroy has_one :subscription, :dependent => :destroy has_many :subscription_payments accepts_nested_attributes_for :users # From saas subscription project - not using subdomains yet #validates_format_of :domain, :with => /\A[a-zA-Z][a-zA-Z0-9]*\Z/ #validates_exclusion_of :domain, :in => %W( support blog www billing help api #{AppConfig['admin_subdomain']} ), :message => "The domain <strong>{{value}}</strong> is not available." #validate :valid_domain? validate_on_create :valid_user? validate_on_create :valid_plan? validate_on_create :valid_payment_info? validate_on_create :valid_subscription? attr_accessible :name, :domain, :user, :users_attributes, :plan, :plan_start, :creditcard, :address, :company_name, :phone_number attr_accessor :user, :plan, :plan_start, :creditcard, :address, :affiliate after_create :create_admin #after_create :send_welcome_email # Need better solution that acts_as_paranoid...look for using default_scope in Rails 2.3 # Using soft-deletes for now acts_as_authorizable acts_as_state_machine :initial => :login state :login state :joined state :paying state :invalid event :join do transitions :to => :joined, :from => :login end event :billing_update do transitions :to => :paying, :from => [:login, :joined] end event :expired do transitions :to => :invalid, :from => [:joined, :paying] end Limits = { 'user_limit' => Proc.new {|a| a.users.count }, 'disk_limit' => Proc.new {|a| a.backup_sources.map(&:bytes_backed_up).sum }, 'backup_site_limit' => Proc.new {|a| a.backup_sources.count } } Limits.each do |name, meth| define_method("reached_#{name}?") do return false unless self.subscription self.subscription.send(name) && self.subscription.send(name) <= meth.call(self) end end # Site (subdomain) to ID lookup class class Site SubdomainMap = HashWithIndifferentAccess.new({ 'www' => 0, 'vault' => 1 }).freeze def self.default_id SubdomainMap['www'] end def self.id_from_subdomain(sub) SubdomainMap[sub] || default_id end end # Returns admin user Member object def admin has_admins.first end def needs_payment_info? if new_record? AppConfig.require_payment_info_for_trials && @plan && @plan.amount.to_f + @plan.setup_amount.to_f > 0 else self.subscription.needs_payment_info? end end def using_domain? @plan && @plan.allow_subdomain end # Does the account qualify for a particular subscription plan # based on the plan's limits def qualifies_for?(plan) Subscription::Limits.keys.collect {|rule| rule.call(self, plan) }.all? end def active? self.subscription.next_renewal_at >= Time.now end def domain @domain ||= self.full_domain.blank? ? '' : self.full_domain.split('.').first end def domain=(domain) @domain = domain self.full_domain = "#{domain}.#{AppConfig.base_domain}" end def cancel touch(:deleted_at) expired! end protected def valid_domain? conditions = new_record? ? ['full_domain = ?', self.full_domain] : ['full_domain = ? and id <> ?', self.full_domain, self.id] self.errors.add(:domain, 'is not available') if self.full_domain.blank? || self.class.count(:conditions => conditions) > 0 end # An account must have an associated user to be the administrator def valid_user? u = @user ? @user : users.first if !u || !u.valid? errors.add_to_base("Missing or invalid user information") end end # Validate credit card & address if necessary, but not until after login state def valid_payment_info? return if state.nil? || login? if needs_payment_info? unless @creditcard && @creditcard.valid? errors.add_to_base("Invalid payment information") end unless @address && @address.valid? errors.add_to_base("Invalid address") end end end def valid_plan? errors.add_to_base("Invalid plan selected.") unless @plan end def valid_subscription? return if errors.any? # Don't bother with a subscription if there are errors already self.build_subscription(:plan => @plan, :next_renewal_at => @plan_start, :creditcard => @creditcard, :address => @address, :affiliate => @affiliate) if !subscription.valid? errors.add_to_base("Error with payment: #{subscription.errors.full_messages.to_sentence}") return false end end def create_admin self.user.is_admin_for self self.user.account = self self.user.save join! end def send_welcome_email spawn do SubscriptionNotifier.deliver_welcome(self) end end end
# frozen_string_literal: true # Before you leave, the Elves in accounting just need you to fix your expense # report (your puzzle input); # apparently, something isn't quite adding up. # # Specifically, they need you to find the two entries that sum to # 2020 and then multiply those two numbers together. module Day1 class ExpenseReport def pairs pair = load_file.combination(2).find { |x, y| x + y == 2020 } pair[0] * pair[1] end def triples pair = load_file.combination(3).find { |x, y, z| x + y + z == 2020 } pair[0] * pair[1] * pair[2] end def load_file return @values if @values @values = [] File.open('./day1/input.txt', 'r') do |f| f.each_line do |line| @values << Integer(line) end end @values end end end
class CrawlsController < ApplicationController def index crawls = Crawl.all render json: crawls, include: :bars end #A single crawl will include all bars def show crawl = Crawl.find(params[:id]) render json: crawl, include: :bars end def create crawl = Crawl.create(crawl_params) if crawl.valid? render json: crawl end end def update crawl = Crawl.find(params[:id]) crawl.update(crawl_params) if crawl.valid? render json: crawl else render json: crawl.errors, status: :unprocessable_entity end end def destroy crawl = Crawl.find(params[:id]) crawl.destroy if crawl.valid? render json: crawl else render json: crawl.errors, status: :unprocessable_entity end end private def crawl_params params.require(:crawl).permit(:title, :user_id) end end
require 'garage' describe Garage do let(:working_bike) {double :bike, broken?: false, is_a?: Bike} let(:broken_bike) {double :bike, broken?: true, is_a?: Bike} let(:van) {double :van, garage_pickup: [working_bike], release: nil} let(:garage) {Garage.new(:capacity => 30)} it "should allow setting default on initialization" do expect(garage.capacity).to eq(30) end it "should fix broken bikes" do expect(broken_bike).to receive(:fix!) garage.accept(broken_bike) end end
# encoding: utf-8 control "V-52249" do title "Database recovery procedures must be developed, documented, implemented, and periodically tested." desc "Information system backup is a critical step in maintaining data assurance and availability. User-level information is data generated by information system and/or application users. In order to assure availability of this data in the event of a system failure, DoD organizations are required to ensure user-generated data is backed up at a defined frequency. This includes data stored on file systems, within databases or within any other storage media. Applications performing backups must be capable of backing up user-level information per the DoD-defined frequency. Problems with backup procedures or backup media may not be discovered until after a recovery is needed. Testing and verification of procedures provides the opportunity to discover oversights, conflicts, or other issues in the backup procedures or use of media designed to be used.false" impact 0.5 tag "check": "Review the testing and verification procedures documented in the system documentation. Review evidence of implementation of testing and verification procedures by reviewing logs from backup and recovery implementation. Logs may be in electronic form or hardcopy and may include email or other notification. If testing and verification of backup and recovery procedures is not documented in the system documentation, this is a finding. If evidence of testing and verification of backup and recovery procedures does not exist, this is a finding." tag "fix": "Develop, document, and implement testing and verification procedures for database backup and recovery. Include requirements for documenting database backup and recovery testing and verification activities in the procedures." # Write Check Logic Here end
require 'sqlite3' require 'logger' class ClientMockup attr_reader :db, :log, :config, :users def initialize(options={}) @config = options @log = Logger.new($stdout) @db = SQLite3::Database.new('test.db') @last_send_msg = [] @users = options[:users] || {} File.open("./schema/schema.sql") do |f| @db.execute(f.read()) end end def finalize @db.close File.unlink('test.db') end def send_message(nick, text) @last_send_msg << text end def send(room, msg, to=nil) @last_send_msg << msg end def last_send_msg msgs = @last_send_msg.clone @last_send_msg.clear return msgs end end
require 'pry' class String def sentence? self.end_with?(".") end def question? self.end_with?("?") end def exclamation? self.end_with?("!") end def count_sentences count = 0 self.split.each do |sub_sent| if sub_sent.sentence? || sub_sent.question? || sub_sent.exclamation? count += 1 end end count end end
require 'rails_helper' # # Property's route path is to account # RSpec.describe 'Property#index', type: :system do before { log_in } it 'basic' do client = client_create property_create human_ref: 111, client: client, account: account_new property_create human_ref: 222, client: client, account: account_new property_create human_ref: 333, client: client, account: account_new visit '/accounts/' # shows more than one row expect(page).to have_text '111' expect(page).to have_text '222' # Displays expected columns expect(page).to have_text '333' expect_index_address end def expect_index_address [ 'Edgbaston Road', # Road 'Birmingham' # Town ].each do |line| expect(page).to have_text line end end end
#!/usr/bin/env ruby class Triangel def initialize(a, b, c) @a, @b, @c = a, b, c end def valid? @a + @b > @c && @b + @c > @a && @a + @c > @b end def circuit @a + @b + @c end def self.create_rectangular(a, b) c = Math.sqrt(a * a + b * b) self.new(a, b, c) end end
class AddEmailToAuthors < ActiveRecord::Migration def change add_column :authors, :e_mail, :text end end
#!/usr/bin/ruby require "optparse" require "termpic" options = {} opt = OptionParser.new opt.on('-f') {|v| options[:fit_terminal] = true } opt.on('-s') {|v| options[:show_size] = true } opt.on('-d') {|v| options[:double] = true } opt.on('--domain=VAL') {|v| options[:domain] = v } opt.parse!(ARGV) Termpic::Image.new(ARGV[0], options).draw
module Api module V1 class ProductsController < ApplicationController before_action :set_product, only: [:show, :destroy] def index render json: Product.all end def create @product = Product.create(product_params) #Scrape as we send the request scrape(@product.asin) if @product.save render json: @product, status: 201 else render json: {errors: @product.errors.full_messages}, status: 422 end end def show render json: @product end def destroy @product.destroy render :show, status: :ok end private def set_product @product = Product.find(params[:id]) end def product_params params.permit(:product_name, :avg_rating, :total_reviews, :asin) end def review_params params.permit(:review_header, :reviewer, :rating, :review_body, :date, :avatar, :type_and_verified) end def scrape(asin) #Initialize agent = Mechanize.new #Rate limiting to prevent timeouts agent.history_added = Proc.new { sleep 0.5 } #Interpolate the given ASIN to url page = agent.get("https://www.amazon.com/dp/#{asin}") #Pull Product's main information such as: title, image href, avg rating, total reviews product_name = page.at('span#productTitle').text.strip image = page.search("#landingImage").attribute('src').value avg_rating = page.at("i[data-hook='average-star-rating']").text[0..2] total_reviews = page.search("span[data-hook='total-review-count']").text #Associate to model object @product.product_name = product_name @product.image = image @product.avg_rating = avg_rating @product.total_reviews = total_reviews #Find top reviews on page reviews = page.search("div[data-hook='review']") all_reviews = reviews.map do |review| #Look into '.a-row' as this is how Amazon breaks down the review template review_data = review.search('.a-row') #Find the most important review information reviewer = review_data.search('span.a-profile-name').text avatar = review.search('.a-profile-avatar img')[1].attribute('src').value rating = review_data.search("i[data-hook='review-star-rating']").text review_header = review_data.search("a[data-hook='review-title']").text date = review.search("span[data-hook='review-date']").text review_body = review_data.search("div[data-hook='review-collapsed']").text type_and_verified = review.search(".a-row.review-format-strip").text #Store Review field with the scraped data @review = Review.new(review_params) @review.reviewer = reviewer @review.avatar = avatar @review.rating = rating @review.review_header = review_header @review.date = date @review.review_body = review_body @review.type_and_verified = type_and_verified #Associate relationship and save @review.product = @product @review.save end end end end end
$:.push File.expand_path("../lib", __FILE__) require "amazon_s3_index_proxy/version" Gem::Specification.new do |s| s.name = "amazon_s3_index_proxy" s.version = AmazonS3IndexProxy::VERSION s.authors = ["Netguru"] s.homepage = "https://github.com/netguru/amazon_s3_index_proxy" s.summary = "Proxies a page stored on s3 through the Rails app." s.description = "Proxies a page stored on s3 through the Rails app. Also takes care of caching." s.license = "MIT" s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", ">= 4.0.0" s.add_development_dependency "sqlite3" s.add_development_dependency "timecop" s.add_development_dependency "webmock" end
require "application_system_test_case" class EstoquesTest < ApplicationSystemTestCase setup do @estoque = estoques(:one) end test "visiting the index" do visit estoques_url assert_selector "h1", text: "Estoques" end test "creating a Estoque" do visit estoques_url click_on "New Estoque" fill_in "Ano", with: @estoque.ano fill_in "Banco", with: @estoque.banco fill_in "Chassi", with: @estoque.chassi fill_in "Chave", with: @estoque.chave fill_in "Cor", with: @estoque.cor fill_in "Dataentrada", with: @estoque.dataentrada fill_in "Datasaida", with: @estoque.datasaida fill_in "Enderecocoleta", with: @estoque.enderecocoleta fill_in "Funciona", with: @estoque.funciona fill_in "Local", with: @estoque.local fill_in "Placa", with: @estoque.placa fill_in "Reboque", with: @estoque.reboque fill_in "Situacao", with: @estoque.situacao fill_in "Tipoentrada", with: @estoque.tipoentrada fill_in "Transportado", with: @estoque.transportado fill_in "Veiculo", with: @estoque.veiculo click_on "Create Estoque" assert_text "Estoque was successfully created" click_on "Back" end test "updating a Estoque" do visit estoques_url click_on "Edit", match: :first fill_in "Ano", with: @estoque.ano fill_in "Banco", with: @estoque.banco fill_in "Chassi", with: @estoque.chassi fill_in "Chave", with: @estoque.chave fill_in "Cor", with: @estoque.cor fill_in "Dataentrada", with: @estoque.dataentrada fill_in "Datasaida", with: @estoque.datasaida fill_in "Enderecocoleta", with: @estoque.enderecocoleta fill_in "Funciona", with: @estoque.funciona fill_in "Local", with: @estoque.local fill_in "Placa", with: @estoque.placa fill_in "Reboque", with: @estoque.reboque fill_in "Situacao", with: @estoque.situacao fill_in "Tipoentrada", with: @estoque.tipoentrada fill_in "Transportado", with: @estoque.transportado fill_in "Veiculo", with: @estoque.veiculo click_on "Update Estoque" assert_text "Estoque was successfully updated" click_on "Back" end test "destroying a Estoque" do visit estoques_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Estoque was successfully destroyed" end end
class AddImageData3ToCatalog4ItemImage < ActiveRecord::Migration def change change_column :catalog4_category_item_images, :image_ratio, :float end end
require 'spec_helper' describe LinkedList do before do @linked_list = LinkedList.new end describe "#push" do it "lets you push on multiple values" do @linked_list.push(1) @linked_list.push(2) @linked_list.push(3) @linked_list.to_a.should == [1, 2, 3] end end describe "#delete" do it "lets you remove an element in the middle" do one = @linked_list.push(1) two = @linked_list.push(2) three = @linked_list.push(3) @linked_list.delete(two) @linked_list.to_a.should == [1, 3] end it "lets you remove the head" do one = @linked_list.push(1) two = @linked_list.push(2) three = @linked_list.push(3) @linked_list.delete(one) @linked_list.to_a.should == [2, 3] end it "lets you remove the last" do one = @linked_list.push(1) two = @linked_list.push(2) three = @linked_list.push(3) @linked_list.delete(three) @linked_list.to_a.should == [1, 2] end end describe "#shift" do it "removes the last item" do @linked_list.push(1) @linked_list.push(2) @linked_list.push(3) @linked_list.shift.should == 1 @linked_list.to_a.should == [2, 3] end it "removes from a list with one item" do @linked_list.push(1) @linked_list.shift.should == 1 @linked_list.to_a.should == [] end it "shifting an empty list does nothing" do @linked_list.shift.should == nil @linked_list.to_a.should == [] end end describe "#length" do it "is zero for the empty list" do @linked_list.length.should == 0 end it "returns the number of items in the list" do @linked_list.push(1) @linked_list.push(2) @linked_list.length.should == 2 end it "returns the number of items in the list even after a delete" do @linked_list.push(1) two = @linked_list.push(2) @linked_list.push(3) @linked_list.delete(two) @linked_list.length.should == 2 end it "returns zero when you remove all items" do one = @linked_list.push(1) @linked_list.delete(one) @linked_list.length.should == 0 end end end
def square_array(array) # Use an Enumerable to square every element in the passed in array array.map do |element| element * element end # Return a new array of the results end def summon_captain_planet(planeteer_calls) # Use an Enumerable to capitalize and add '!' to every element in the passed in array # Return a new array of the results planeteer_calls.collect{ |i| i.capitalize + "!" } end def long_planeteer_calls(planeteer_calls) # Use an Enumerable to check if any string in the passed in array is greater than 4 characters long # Return the boolean result of this check planeteer_calls.any? { |word| word.length >= 5} end def find_valid_calls(planeteer_calls) valid_calls = ["Earth!", "Wind!", "Fire!", "Water!", "Heart!"] # Use an Enumerable to check if any elements in the passed in array match the valid calls listed above # Return the first valid call found, or return nil if no valid calls are found i = 0 while i < valid_calls.length do break if results = planeteer_calls.find { |this| this == valid_calls[i] } i += 1 # valid_calls.each do |element| # break if results = planeteer_calls.find { |this| this == element } # results end results end
Rails.application.routes.draw do get 'sessions/new' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html root 'top#index' get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' get '/logout', to: 'sessions#destroy' get '/friends/search', to: 'friends#search' get '/groups/search/:id', to: 'groups#search' post '/groups/wakeup/:id', to: 'groups#wakeup' get '/groups/add/:id', to: 'groups#add' post '/groups/make/:id', to: 'groups#make' post '/groups/time/:id', to: 'groups#time' post '/groups/sleep/:id', to: 'groups#sleep' post '/groups/reset/:id', to: 'groups#reset' get '/groups/how', to: 'groups#how' get '/users/:id/delete', to: 'users#delete' post '/follower/delete', to: 'friends#follower' post '/following/delete', to: 'friends#following' get '/friends/:id/delete', to: 'friends#delete' post '/friends/break', to: 'friends#break' resources :users, only: [ :new, :create, :show, :edit, :update, :destroy ] resources :friends, only: [ :new, :create, :show ] resources :groups, only: [ :index, :new, :create, :show, :edit, :update ] end
class AddInterstatePalletIdToJob < ActiveRecord::Migration def change add_column :jobs, :interstate_pallet_id, :integer end end
require_relative '../constants' require_relative '../spec/web_resources' require_relative '../modules/aes' require_relative '../modules/xor' require_relative '../modules/utils/hex' require_relative '../modules/utils/utility' class Decryptor # Modules include AES attr_accessor :encoded_bytes attr_reader :input_type, :output_type def initialize(input_type, output_type) Utility.enforce_argument_type(Module, input_type) Utility.enforce_argument_type(Module, output_type) @input_type = input_type @output_type = output_type end def decrypt_aes(input, key_bytes) Utility.enforce_argument_type(String, input) Utility.enforce_argument_type(Array, key_bytes) input_bytes = input_type.to_bytes(input) decipher_aes(input_bytes, key_bytes) end def repeating_key_xor_to_english(input) Utility.enforce_argument_type(String, input) input_bytes = input_type.to_bytes(input) key_bytes = find_key_for(input_bytes, 28..29) message = XOR.repeating_key_gate(input_bytes, key_bytes) Plaintext.encode(message) end def find_english_line(lines_of_bytes) potential_messages = {} lines_of_bytes.each do |line| try = XOR.single_substitution(line)[:histogram] if Plaintext.score(try) > (line.length * MEAN_ENGLISH_CHAR_FREQUENCY) potential_messages[Plaintext.score(try)] = try else next end end return potential_messages.max end private def transposed_blocks(source_bytes, keysize) Utility.enforce_argument_type(Array, source_bytes) Utility.groups_of(keysize, source_bytes).transpose end def find_key_for(source_bytes, key_size_range) potential_keys = {} key_size_range.each do |try_keysize| key_bytes = [] transposed_blocks(source_bytes.dup, try_keysize).each do |block| key_bytes << XOR.single_substitution(block)[:key][:ord] end potential_keys[Plaintext.score(key_bytes.join)] = key_bytes end return potential_keys.max[1] end def score_keysizes(source_bytes) Utility.enforce_argument_type(Array, source_bytes) potential_keysizes = {} (min_key_size..max_key_size).each do |keysize| hamming_distances = [] (0..3).each do |i| chunk1 = source_bytes[i*keysize..keysize-1] chunk2 = source_bytes[(i+1)*keysize..2*keysize-1] next if chunk1.length != chunk2.length hamming_distances << Hamming.distance(chunk1, chunk2) end average_ham = hamming_distances.reduce(:+) / hamming_distances.length potential_keysizes[keysize] = average_ham end potential_keysizes end end
# frozen_string_literal: true require 'rails_helper' require_relative 'concerns/date_range' RSpec.describe Season do it_behaves_like 'date_range' describe SeasonValidator do let(:other) do start_date = Time.zone.now.change(month: 3).to_date end_date = Time.zone.now.change(month: 10).to_date build :season, start_date: start_date, end_date: end_date end before { create :season } it 'prohibits overlapping seasons' do expect(other).to be_invalid end it 'adds errors to base' do other.validate expect(other.errors[:base].join).to match(/overlaps/) end end describe '#months' do subject :months do build(:season, start_date: Date.new(2018, 5, 15), end_date: Date.new(2018, 9, 15)).months end it { is_expected.to be_an Array } it { is_expected.to all(be_a Date) } it 'is entirely firsts of the month' do expect(months.map(&:day)).to all(be 1) end it { is_expected.to include(Date.new(2018, 5, 1)) } it { is_expected.to include(Date.new(2018, 9, 1)) } it 'has the right number of months' do expect(months.count).to be 5 end end end
class Pokemon attr_accessor :name, :type, :db, :id, :hp @@all = [] def initialize(name: , type: , db:, id:, hp: nil) @name = name @type = type @db = db @id = id @hp = hp @@all << self end def self.save(pk_name, pk_type, db) db.execute("INSERT INTO pokemon (name, type) VALUES (?, ?)",pk_name, pk_type) end def self.find(id, db) found_pk = db.execute("SELECT * FROM pokemon WHERE id = ?", id) return self.new(id: id, db: db, name: found_pk[0][1], type: found_pk[0][2], hp: found_pk[0][3]) end def alter_hp(hp, db) db.execute("UPDATE pokemon SET hp = ? WHERE id = ?", hp, self.id) end end
require 'forwardable' require 'diff/lcs' require 'creola/html' require 'creola/txt' class CreolaList < CreolaTxt def root(content); content.flatten end def to_a; render end undef_method :to_txt end class CreolaDiff < Creola extend Forwardable def initialize(old_creole, new_creole, renderer) @old_content = CreolaList.new(old_creole).to_a @new_content = CreolaList.new(new_creole).to_a @renderer = renderer super(nil, nil) end def_delegators :@renderer, :root, :line_break, :heading, :paragraph, :nowiki, :nowiki_inline, :bold, :italic, :unnumbered, :numbered, :unnumbered_item, :numbered_item, :link, :table, :row, :cell, :header_cell, :image, :horizontal_rule, :words def match(event) @renderer.discard_state = nil @state = tokenize_string(event.new_element, @state) end def discard_a(event) @renderer.discard_state = :remove @state = tokenize_string(event.old_element, @state) end def discard_b(event) @renderer.discard_state = :add @state = tokenize_string(event.new_element, @state) end private def tokenize @state = State::Root.new(self) Diff::LCS.traverse_sequences(@old_content, @new_content, self) @state = @state.parse(:EOS, nil) root(@state.finish) end end class ContentDiffHTML < CreolaHTML attr_accessor :discard_state def words(*words); case @discard_state when :remove %{<span class="remove">} + words.join + "</span>" when :add %{<span class="add">} + words.join + "</span>" else words.join end end end class ContentDiffHTMLNoClass < CreolaHTML attr_accessor :discard_state def words(*words); case @discard_state when :remove %{<span style="background-color: #fdd; text-decoration: line-through;">} + words.join + "</span>" when :add %{<span style="background-color: #dfd;">} + words.join + "</span>" else words.join end end end class DocDiff < CreolaDiff attr_reader :doc_old, :doc_new def initialize(doc_old, doc_new, options = {}) options[:renderer] ||= ContentDiffHTML.new super(doc_old.content, doc_new.content, options[:renderer]) @doc_old, @doc_new, @options = doc_old, doc_new, options end def heading(level, text); super(level + 1, text) end def image(url, text) req_old = @doc_old.requirements.find {|creq| creq.name == url} req_new = @doc_new.requirements.find {|creq| creq.name == url} if req_old || req_new case @renderer.discard_state when :remove ReqDiff.new(req_old, EmptyReq.new, @options).to_html when :add ReqDiff.new(EmptyReq.new, req_new, @options).to_html else ReqDiff.new(req_old, req_new, @options).to_html end elsif url !~ %r(/) "{{" + url + (text ? "|" + text : "") + "}}" else super(url, text) end end end class EmptyReq < Doc def initialize; end end class ReqDiff TEMPLATE = 'req_inline.haml' def initialize(req_old, req_new, options = {}) @req_old, @req_new, @options = req_old || EmptyReq.new, req_new || EmptyReq.new, options @context = @options[:context] @content = CreolaDiff.new(@req_old.content, @req_new.content, options[:renderer]) end def attributes @attributes ||= Hash[@req_new.attributes.map {|k,v| [k, CreolaHTML.new(v)]}] end attr_reader :content def name; @req_new.name || @req_old.name end def date; @req_new.date || @req_old.date end def to_html template = File.join(@context.settings.views, TEMPLATE) engine = Haml::Engine.new(File.read(template)) @context.instance_variable_set :@inline, self engine.render(@context) end end
module Leagues module Rosters class CommentsController < ApplicationController include ::LeaguePermissions before_action do @roster = League::Roster.find(params[:roster_id]) @league = @roster.league end before_action only: [:edit, :update, :edits, :destroy, :restore] do @comment = @roster.comments.find(params[:id]) end before_action :require_league_permissions def create @comment = Comments::CreationService.call(current_user, @roster, comment_params) redirect_to edit_roster_path(@roster) end def edit end def update @comment = Comments::EditingService.call(current_user, @comment, comment_params) if @comment.valid? redirect_to edit_roster_path(@roster) else render :edit end end def edits @edits = @comment.edits.includes(:created_by) end def destroy @comment.delete!(current_user) redirect_to edit_roster_path(@roster) end def restore @comment.undelete! redirect_to edit_roster_path(@roster) end private def comment_params params.require(:comment).permit(:content) end def require_league_permissions redirect_back(fallback_location: root_path) unless user_can_edit_league? end end end end
module Super module Kafka class Processor include Super::Component inst_accessor :adapter, :task inst_reader :state interface :run, :start, :stop def initialize @state = :offline end def run(task) @task = task setup_consumer start end def start return if @consumer.nil? return unless @state == :offline Signal.trap('INT') { stop } @state = :online @consumer.subscribe(@task.settings.topic) @consumer.each_message(automatically_mark_as_processed: false) do |message| process(message) end end def stop @consumer.stop @state = :offline end private def setup_consumer options = { group_id: @task.settings.group_id, offset_commit_interval: @task.settings.offset_commit_interval || 1, offset_commit_threshold: @task.settings.offset_commit_threshold || 10 }.compact @consumer = @adapter.consumer(options) end def process(message) @task.call(message.value) @consumer.mark_message_as_processed(message) rescue StandardError => e messages = [e.message, *e.backtrace].join("\n") logger.error(messages) end def logger Application.logger end end end end
#!/usr/bin/env ruby VERSION='1.0.0' $:.unshift File.expand_path('../../lib', __FILE__) require 'hashie' require 'devops_api' require 'pry' require 'awesome_print' require 'ruby-progressbar' class Api include DevopsApi end def get_hz domain, api hzs = [] marker = "" while marker.class == String do resp = marker.empty? ? api.r53.list_hosted_zones : api.r53.list_hosted_zones({ marker: marker }) hzs = hzs + resp.hosted_zones marker = resp.next_marker end hzs.select!{|hz| hz.name == "#{domain}." } return nil if hzs.empty? hz_resp = api.r53.get_hosted_zone({ id: hzs[0].id }) hz_resp rescue Aws::Route53::Errors::Throttling sleep 30 get_hz(domain, api) end def hz_has_records? hosted_zone, api records = api.r53.list_resource_record_sets({ hosted_zone_id: hosted_zone.id }).resource_record_sets found = 0 records.each do |record| next unless record.type =~ /^(A|CNAME)$/ is_name = record.name == hosted_zone.name || record.name == "\\052.#{hosted_zone.name}" is_target = false is_target = !( record.resource_records[0].value =~ /univision-web-2-1444712993/ ).nil? if !record.resource_records.empty? is_target = !( record.alias_target.dns_name =~ /univision-web-2-1444712993/ ).nil? if !record.alias_target.nil? found = found + 1 if is_name && is_target break if found == 2 end found == 2 end def has_records? hosted_zone, api records = api.r53.list_resource_record_sets({ hosted_zone_id: hosted_zone.id }) found = 0 records.resource_record_sets.each do |record| is_type = record.type =~ /(A|CNAME)/ is_target = !( record.resource_records[0].value =~ /univision-cms-2-1255582201/ ).nil? if !record.resource_records.empty? is_target = !( record.alias_target.dns_name =~ /univision-cms-2-1255582201/ ).nil? if !record.alias_target.nil? found += 1 if is_type && is_target end found == 2 end begin opts = Slop.parse(strict: true, help: true) do banner "Domain Cutover List Hosted Zones, version #{VERSION}\n\nUsage: domain_import_r53 [options]" on 'p', 'profile', '[required] The name of the AWS credential profile to use.', argument: true on 'f', 'file', '[required] The location of the csv file to be tested.', argument: true on 'v', 'version' do puts 'domain cutover, version #{version}' exit 0 end end opts_slop = opts opts = Hashie::Mash.new(opts_slop.to_hash) # Profile required test raise 'AWS Profile name required!' unless opts.profile? raise 'Location of config YAML [-f PATHTOYAML] required!' unless opts.file? opts.file = File.expand_path( opts.file ) raise "Config YAML file not found at \"#{opts.file}\"." unless File.exist?( opts.file ) api = Api.new(opts.profile) caller_reference = "domain_import_#{Time.now.strftime("%Y%m%d%H%M%S")}" yml = YAML.load_file( opts.file ) domains = yml['domains'].map{|d| Hashie::Mash.new(d) } puts '# Domains to import #################################################' puts '' puts domains.map{ |d| d.name }.join("\n") puts '' delegation_sets = api.r53.list_reusable_delegation_sets.delegation_sets puts '# Creating Hosted Zones #############################################' puts '' @status = nil domain_report = { "not_set" => [] } delegation_sets.each do |delegation_set| domain_report["#{delegation_set.id}"] = [] end domains.each do |domain| begin if !get_hz(domain.name, api).nil? applied_delegation_set = Hashie::Mash.new({ id: "not_set" }) raise DevopsApi::Exceptions::HostedZoneFound end puts "Creating HZ #{domain.name}." puts '' # create hosted zone hz_resp = nil applied_delegation_set = nil delegation_sets.each do |delegation_set| hosted_zone = { name: "#{domain.name}.", caller_reference: "#{caller_reference}.#{rand(999)}", delegation_set_id: delegation_set.id } begin hz_resp = api.r53.create_hosted_zone(hosted_zone) applied_delegation_set = delegation_set rescue Aws::Route53::Errors::TooManyHostedZones => e puts "!!! Delegation Set #{delegation_set.id} Full !!!" next end end # create HZ with a new delegation set if hz_resp.nil? hosted_zone = { name: "#{domain.name}.", caller_reference: "#{caller_reference}.#{(rand(1000)+rand(1000)).to_s(36)}" } # create hosted zone hz_resp = api.r53.create_hosted_zone(hosted_zone) applied_delegation_set = api.r53.create_reusable_delegation_set({ caller_reference: caller_reference, hosted_zone_id: hz_resp.hosted_zone.id }) #refresh delegation sets delegation_sets = api.r53.list_reusable_delegation_sets.delegation_sets end # wait for change puts '' @status = api.r53.get_change( { id: hz_resp.change_info.id } ).change_info.status pb = ProgressBar.create( title: 'Create HZ Live? ', format: '%t %B', progress_mark: '✘', total: 1000 ) while @status == 'PENDING' do pb.increment @status = api.r53.get_change( { id: hz_resp.change_info.id } ).change_info.status sleep 0.25 end pb.stop puts "Create HZ is now #{@status}." puts '' rescue DevopsApi::Exceptions::HostedZoneFound => e puts "!!! HZ for #{domain.name} already exsists !!!" puts '' puts '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -' puts '' rescue Aws::Route53::Errors::HostedZoneAlreadyExists, Aws::Route53::Errors::ConflictingDomainExists => e puts "!!! HZ for #{domain.name} already exsists !!!" puts "||| #{e.message} !!!" puts '' puts '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -' puts '' applied_delegation_set = Hashie::Mash.new({ id: "not_set" }) sleep 1 # for AWS HZ Creation Throttling end domain_report[applied_delegation_set.id] << domain.name hz_resp = get_hz(domain.name, api) next if hz_resp.nil? || hz_has_records?(hz_resp.hosted_zone, api) begin puts "Creating Records for HZ #{hz_resp.hosted_zone.id}" change = { hosted_zone_id: hz_resp.hosted_zone.id, change_batch: { comment: "Cteating base records for #{domain.name}.", changes: [ { action: 'CREATE', resource_record_set: { name: "#{domain.name}.", type: 'A', alias_target: { hosted_zone_id: 'Z35SXDOTRQ7X7K', dns_name: 'dualstack.univision-web-2-1444712993.us-east-1.elb.amazonaws.com.', evaluate_target_health: false }, resource_records: nil } }, { action: 'CREATE', resource_record_set: { name: "*.#{domain.name}.", type: 'CNAME', ttl: 60, alias_target: nil, resource_records: [ { value: 'univision-web-2-1444712993.us-east-1.elb.amazonaws.com.' } ] } } ] } } # create HZ records record_resp = api.r53.change_resource_record_sets(change) # wait for status INSYNC puts '' @status = api.r53.get_change( { id: record_resp.change_info.id } ).change_info.status pb = ProgressBar.create( title: 'Create HZ records Live? ', format: '%t %B', progress_mark: '✘', total: 1000 ) while @status == 'PENDING' do pb.increment @status = api.r53.get_change( { id: record_resp.change_info.id } ).change_info.status sleep 0.25 end pb.stop puts "Create HZ records is now #{@status}." puts '' rescue Aws::Route53::Errors::InvalidChangeBatch => e puts "!!! #{domain.name} already has those records !!!" puts '' rescue => e raise e end puts '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -' puts '' end puts '# Name Servers to Use ###############################################' puts '' ap api.r53.list_reusable_delegation_sets puts '' puts '# Cut and Paste for CSC #############################################' puts '' domain_report.each do |k,v| puts "DelegationSet ID: #{k}" puts v.join(',') puts '' puts '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -' puts '' end rescue => e puts '' puts e.class puts e.message puts e.backtrace.join("\n") puts '' puts opts_slop end