text
stringlengths
10
2.61M
# frozen_string_literal: true class SearchController < ApplicationController def index @query = params[:q].presence return unless @query if admin? all_users = User.search(@query).to_a signup_users, non_signups = all_users.partition(&:signup) @signups = signup_users.map(&:signup) member_users, @users = non_signups.partition(&:last_membership) @deleted_users = User.only_deleted.search(@query).to_a @former_members, @members = member_users.map(&:last_membership).partition(&:left?) @user_messages = UserMessage.search(@query).to_a end query = "%#{@query.upcase.gsub(/(_|%)/, '\\\\\\1')}%" pages = InformationPage.where('title ILIKE :query OR body ILIKE :query', query: query).order(:title) pages = pages.for_all unless current_user pages = pages.visible unless current_user&.admin? @pages = pages.to_a news_items = NewsItem .where('title ILIKE :query OR summary ILIKE :query OR UPPER(body) LIKE :query', query: query) .order(created_at: :desc) .to_a @news = news_items.group_by { |n| n.created_at.year } @events = Event .where(%i[name name_en description description_en].map { |f| "#{f} ILIKE :query" }.join(' OR '), query: query) .order(start_at: :desc) .group_by { |e| e.start_at.year } @images = Image.where('UPPER(name) LIKE :query', query: query).order(:name).to_a @basic_techniques = BasicTechnique.includes(rank: { curriculum_group: :martial_art }) .where('UPPER(basic_techniques.name) LIKE :query', query: query) .where(martial_arts: { original_martial_art_id: nil }) .order(:name).to_a @technique_applications = TechniqueApplication.where('UPPER(name) LIKE :query', query: query).order(:name).to_a end end
require 'date' module Gaman module Clip # Internal: Parses a FIBS WhoInfo CLIP message. Message is in the format: # # name opponent watching ready away rating experience idle login \ # hostname client email # # name: The login name for the user this line is referring to. # opponent: The login name of the person the user is currently playing # against, or a hyphen if they are not playing anyone. # watching: The login name of the person the user is currently watching, # or a hyphen if they are not watching anyone. # ready: 1 if the user is ready to start playing, 0 if not. Note that # the ready status can be set to 1 even while the user is # playing a game and thus, technically unavailable. # away: 1 for yes, 0 for no. # rating: The user's rating as a number with two decimal places. # experience: The user's experience. # idle: The number of seconds the user has been idle. # login: The time the user logged in as the number of seconds since # midnight, January 1, 1970 UTC. # hostname: The host name or IP address the user is logged in from. Note # that the host name can change from an IP address to a host # name due to the way FIBS host name resolving works. # client: The client the user is using (see login) or a hyphen if not # specified. # email: The user's email address, or a hyphen if not specified. class WhoInfo def initialize(text) name, opponent, watching, ready, away, rating, experience, idle, login, hostname, client, email = text.split(' ', 12) @name = name @opponent = (opponent == '-' ? nil : opponent) @watching = (watching == '-' ? nil : watching) @ready = (ready == '1') @away = (away == '1') @rating = rating.to_f @experience = experience.to_i @idle = idle.to_i @last_login = Time.at(login.to_i).utc.to_datetime @hostname = hostname @client = (client == '-' ? nil : client) @email = (email == '-' ? nil : email) end def update(state) state.update_player( @name, opponent: @opponent, watching: @watching, ready: @ready, away: @away, rating: @rating, experience: @experience, idle: @idle, last_login: @last_login, hostname: @hostname, client: @client, email: @email ) end end end end
Spree::PaymentMethod.class_eval do def self.loyalty_points_id_included?(method_ids) where(type: 'Spree::PaymentMethod::LoyaltyPoints').where(id: method_ids).size != 0 end end
require 'spec_helper' require 'timecop' require 'sidekiq' require 'sidekiq/testing' Sidekiq::Testing.fake! class MySidekiqWorker include Sidekiq::Worker def perform(_name) end end Sidekiq.configure_client do |config| config.client_middleware do |chain| chain.add Loga::Sidekiq::ClientLogger end end describe 'Sidekiq client logger' do before(:all) { Timecop.freeze(time_anchor) } after(:all) { Timecop.return } before do Loga.configure do |config| config.service_name = 'hello_world_app' config.service_version = '1.0' config.device = target end Loga::Logging.reset end let(:target) { StringIO.new } context 'when the job is successful' do let(:json_line) do target.rewind JSON.parse(target.read) end it 'logs the job enqueue' do MySidekiqWorker.perform_async('Bob') expect(json_line).to match( 'version' => '1.1', 'host' => be_a(String), 'short_message' => 'MySidekiqWorker Enqueued', 'full_message' => '', 'timestamp' => '1450171805.123', 'level' => 6, '_event' => 'job_enqueued', '_service.name' => 'hello_world_app', '_service.version' => '1.0', '_job.enqueued_at' => '1450171805.123', '_job.jid' => be_a(String), '_job.params' => ['Bob'], '_job.klass' => 'MySidekiqWorker', '_job.queue' => 'default', '_job.retry' => true, '_job.duration' => 0, '_job.retried_at' => nil, '_job.failed_at' => nil, '_job.retry_count' => nil, ) end end end
require 'nokogiri' require 'open-uri' module Parsers class ScoresExtractor def self.extract(webpage_url) content = [] puts '' puts "Extracting from #{webpage_url}" page = Nokogiri::HTML(open(webpage_url)) items = page.css('div.schedules-list').css('li') # Extracting info items.each do |item| next if item.attributes['class'].value == 'schedules-list-date next-game' next if item.attributes['class'].value =~ /expanded/ if item.attributes['class'].value =~ /schedules-list-matchup/ game_data = { visitor: item.css('div.list-matchup-row-team span.team-name.away').text, visitor_score: item.css('span.team-score.away').text, local: item.css('div.list-matchup-row-team span.team-name.home').text, local_score: item.css('span.team-score.home').text } puts game_data content << game_data end end content end end end
require 'spec_helper' describe 'knife cookbook site download COOKBOOK' do it 'indicates the version that will be downloaded' do cookbook = TestCook.create_cookbook command = run "knife cookbook site download #{cookbook.name}" download_status = command.stdout.lines[0].strip expect(download_status).to include("version #{cookbook.version}") end it 'downloads the tarball' do cookbook = TestCook.create_cookbook command = run "knife cookbook site download #{cookbook.name}" filename = "#{cookbook.name}-#{cookbook.version}.tar.gz" expect(TestCook.downloads.include?(filename)).to eql(true) end end
class Testquestion < ActiveRecord::Base attr_accessible :question_id, :jktest_id, :user_id #association belongs_to :question belongs_to :jktest belongs_to :user #validation validates :user_id, :presence => true validates :question_id, :presence => true, :uniqueness => { :scope => :jktest_id, :message => "should happen once per Test" } validates :jktest_id, :presence => true #callback before_validation :validate_question, :validate_jktest, :validate_user def validate_question errors.add(:question_id, 'not presence') if Question.find_by_id( self[:question_id] ) == nil end def validate_jktest errors.add(:jktest_id, 'Test not presence') if Jktest.find_by_id( self[:jktest_id] ) == nil end def validate_user errors.add(:user_id, 'not presence') if User.find_by_id( self[:user_id] ) == nil end end
# frozen_string_literal: true class CreateWords < ActiveRecord::Migration[6.0] def change create_table(:apple_music_track_words) do |t| t.string(:apple_music_track_id, limit: 16, null: false) t.string(:text, limit: 191, null: false) t.integer(:position, null: false) end add_foreign_key(:apple_music_track_words, :apple_music_tracks) add_index(:apple_music_track_words, :text) add_index( :apple_music_track_words, %i[apple_music_track_id position], unique: true, name: 'index_apple_music_track_words_on_amt_id_and_position' ) create_table(:spotify_track_words) do |t| t.string(:spotify_track_id, limit: 16, null: false) t.string(:text, limit: 191, null: false) t.integer(:position, null: false) end add_foreign_key(:spotify_track_words, :spotify_tracks) add_index(:spotify_track_words, :text) add_index( :spotify_track_words, %i[spotify_track_id position], unique: true, name: 'index_spotify_track_words_on_st_id_and_position' ) end end
require_relative 'test_helper' class AcceptanceTest < MiniTest::Unit::TestCase include Breaker::TestCases InMemoryFuse = Struct.new :state, :failure_count, :retry_threshold, :failure_threshold, :retry_timeout, :timeout attr_reader :fuse, :repo def setup @repo = Breaker::InMemoryRepo.new @fuse = InMemoryFuse.new :closed, 0, 1, 3, 15, 10 super end end
require 'rails_helper' RSpec.describe User, type: :model do pending "add some examples to (or delete) #{__FILE__}" subject(:user) { User.new(username: 'kevin', password: '1234567')} it { should validate_presence_of(:email) } it { should validate_presence_of(:password_digest) } it { should validate_length_of(:password).is_at_least(6) } it "creates a password digest when given a password" do expect(user.password_digest).to_not be_nil end it "creates a session token before validation" do user.valid? expect(user.session_token).to_not be_nil end describe ':find_by_credentials' do it 'should return a user with good params' do expect(user.find_by_credentials('kevin', '1234567')).to eq(user) end it 'shoudl return nil with bad params' do expect(user.find_by_credentials('kevin', '12663337')).to be_nil end end describe '#reset_session_token!' do it 'changes the session token ' do old_session_token = user.session_token user.reset_session_token! expect(user.session_token).not_to equal(old_session_token) end it 'returns new session token' do expect(user.reset_session_token!).to eq(user.session_token) end end describe ':password=(password)' do it 'should check if the password_digest is not nil' do expect(user.password_digest).to_not be_nil end end describe '#is_password?' do it 'should return true with a good password' do expect(user.is_password?('1234567')).to be true end it 'should return false with a BAD PASSWOD ' do expect(user.is_password?('12345678')).to be false end end end
VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "precise64" config.vm.network :forwarded_port, guest: 80, host: 8080 #config.vm.network :private_network, ip: "192.168.10.100" config.vm.network :private_network, ip: "192.168.111.222" config.vm.provision "ansible" do |ansible| #ansible.playbook = "provisioning/playbook.yml" ansible.playbook = "provisioning/site.yml" ansible.inventory_path = "provisioning/hosts" ansible.verbose = 'v' end end
require "levenshtein" BananaBotState = {} class BananaBot def initialize(message) @message = message @sender_id = message.sender["id"] # puts "Received '#{message.inspect}' from #{message.sender}" end def message_text @message.text end def state BananaBotState[@sender_id] || [:start] end def set_state(*new_state) BananaBotState[@sender_id] = new_state end def known_fruit ["apple", "banana", "clementine", "pear", "plum", "papaya", "tangerine"] end def call case state[0] when :start reply "Hello. Please name a fruit." set_state :fruit when :fruit if known_fruit.include?(message_text) reply "#{message_text} is a nice fruit!" set_state :start else closest_fruit = known_fruit.min_by{|f| Levenshtein.distance(f, message_text)} reply "Did you mean #{closest_fruit}? Yes/No" set_state :guessing, closest_fruit end when :guessing guess = state[1] if message_text =~ /yes/i reply "#{guess} is a nice fruit!" set_state :start elsif message_text =~ /no/i reply "Then pick another fruit please." set_state :fruit else reply "Did you mean #{guess}? Yes/No" end else raise "Unknown state: #{state.inspect}" end end def reply(text) @message.reply(text: text) rescue warn $! end end
describe CloudFormula do it 'should have a version' do expect(CloudFormula::VERSION).to_not be_nil expect(CloudFormula::VERSION).to_not be_empty end it 'template method should return a new Template object' do expect(CloudFormula.template).to be_an_instance_of(CloudFormula::Template) end it 'create_stack method' do expect(CloudFormula).to respond_to(:create_stack) end it 'update_stack method' do expect(CloudFormula).to respond_to(:update_stack) end end
class Profile < ActiveRecord::Base belongs_to :user has_many :posts, :through => :user has_many :divisions, :through => :posts has_many :achievements, through: :user belongs_to :degree belongs_to :academic_title has_and_belongs_to_many :attachments validates :first_name, :last_name, :middle_name, :length => { :maximum => 50 } def full_name [last_name, first_name, middle_name].compact.join(' ').strip end def full_name_reg full_name + (reg.empty? ? "" : " - #{reg}" ) end def reg deg = degree.short_name if degree ac = academic_title.name if academic_title [deg, ac].compact.join(', ').strip end def import(row) self.attributes = row.to_hash.slice('last_name', 'first_name', 'middle_name', 'email', 'phone', 'discipline', 'qualification', 'development', 'general_experience', 'special_experience') self.academic_title = AcademicTitle.find_by_name(row["academic_title"]) if row["academic_title"] self.degree = Degree.find_by_name(row["degree"]) if row["degree"] self.save! end def open_spreadsheet(file) case File.extname(file.original_filename) when ".ods" then Roo::Openoffice.new(file.path, nil, :ignore) when ".csv" then Roo::Csv.new(file.path, nil, :ignore) when ".xls" then Roo::Excel.new(file.path, nil, :ignore) when ".xlsx" then Roo::Excelx.new(file.path, nil, :ignore) else raise "Unknown file type: #{file.original_filename}" end end end
class RideTheme < ActiveRecord::Base has_many :course_ride_themes, dependent: :destroy has_many :courses, :through => :course_ride_themes end
class Word < ApplicationRecord belongs_to :category, optional: true has_many :lesson_words has_many :learned_words has_many :word_answers accepts_nested_attributes_for :word_answers, allow_destroy: true, reject_if: proc { |att| att['description'].blank? } def self.create_lesson_words(match_lessons_ids) # Select All Lesson Words of match_lessons lesson_words = LessonWord.words_of_lesson(match_lessons_ids) # Find All Answers of Lesson Words word_answers = WordAnswer.joins(:lesson_words) # Select the answers have status = correct # correct_answers = word_answers.where(status: "Correct") # correct_answers_ids = correct_answers.pluck :id # correct_answers_ids = "SELECT word_id FROM #{@word_answers} WHERE status = Correct" correct_answers_ids = word_answers.where(id: word_answers.where(status: "Correct")).pluck :id skip_word_ids = Word.where("word_id IN (#{correct_answers_ids})") Word.where("word_id NOT IN (#{skip_word_ids})") end end
class PeopleCasesController < ApplicationController def new @case = Case.find_by_id(params[:case_id]) @person_case = params[:person_class].safe_constantize.new @people = Person.all end def create @case = Case.find_by_id(people_case_params[:case_id]) PeopleCase.subclasses.map { |c| c.to_s.underscore }.each do |subclass| if params[subclass] @person_case = subclass.to_s.camelcase.safe_constantize.new(people_case_params) break end end unless @person_case.save flash.alert = 'Failed to link to case' end redirect_to @case end def show @person_case = PeopleCase.where(id: params['id']).first redirect_to @person_case.person end def edit @person_case = PeopleCase.where(id: params['id']).first end def update @person_case = PeopleCase.where(id: params['id']).first if @person_case.update(people_case_params) redirect_to @person_case.case else render 'edit' end end def destroy person_case = PeopleCase.where(id: params[:id]).first @case = person_case.case if person_case.is_a?(Defendant) && person_case.defendant_charges.size > 0 flash.alert = "Cannot delete Defendant who still has charges! (Remove all charges first)." else notice = "Removed #{person_case.class} #{person_case.person.name} from Docket Number #{person_case.case.docket_number}" person_case.destroy flash.notice = notice end redirect_to @case end private def people_case_params local_params = params.require(:people_case).permit(:person_id, :case_id, :comment) PeopleCase.subclasses.map { |c| c.to_s.underscore }.each do |subclass| if params[subclass] local_params.merge!(params.require(subclass).permit(:person_id, :case_id, :comment)) end end local_params end end
class SportsController < ApplicationController def new @sport = Sport.new end def create @player = current_player @sports = Sport.all if @sports.any? {|sport| sport.name = params[:sport][:name]} redirect_to root_path end @sport = @player.sports.new(sport_params) if @sport.save redirect_to root_path else render :new end end def show end def destroy @player =current_player @sport = @sport.positions.find(params[:id]) @sport.destroy redirect_to root_path end private def sports_params sports_params = params.require(:sports).permit(:name) end end
module ActionClient module Middleware class ResponseParser def initialize(app) @app = app end def call(env) status, headers, body_proxy = @app.call(env) body = body_proxy.each(&:yield_self).sum content_type = headers["Content-Type"].to_s if body.present? if content_type.starts_with?("application/json") body = JSON.parse(body) elsif content_type.starts_with?("application/xml") body = Nokogiri::XML(body) else body end end [ status, headers, body ] end end end end
# == Schema Information # # Table name: matches # # id :integer not null, primary key # token :string(255) not null # comment :string(255) # positive :boolean # win :boolean # created_at :datetime not null # updated_at :datetime not null # game_id :integer # FactoryGirl.define do factory :match do token { SecureRandom.hex } comment { Forgery(:lorem_ipsum).words(10) } trait :win { win true } trait :loss { win false } trait :positive { positive true } trait :negative { positive false } end end
require File.join(File.dirname(__FILE__), 'test_helper') class AftfilrGeneratorTest < GeneratorTestCase # APPTODO: assert_generated_directory - new method for GeneratorTestCase # Note: Most of these tests are intended not to test the functionality in # Rails, but to better understand it. def test_generated_names g = build_generator('aftfilr', %w(document)) assert_equal 'document', g.name assert_equal 'document', g.singular_name assert_equal 'document', g.file_name # aliased to singular_name assert_equal 'documents', g.plural_name assert_equal 'documents', g.table_name assert_equal [], g.class_path assert_equal 'Document', g.class_name assert_equal 'Document', g.model_class_name assert_equal 'Documents', g.controller_class_name assert_equal 'DocumentDialog', g.tinymce_dialog_name assert_equal 'Document Manager', g.tinymce_window_title assert_equal '/documents', g.controller_index_path assert_equal 'CreateDocuments', g.migration_class_name end def test_generated_names_for_capitalized_arg g = build_generator('aftfilr', %w(Document)) assert_equal 'Document', g.name assert_equal 'document', g.singular_name assert_equal 'documents', g.plural_name assert_equal 'documents', g.table_name assert_equal [], g.class_path assert_equal 'Document', g.class_name assert_equal 'Document Manager', g.tinymce_window_title assert_equal '/documents', g.controller_index_path end def test_generated_names_for_camelcased_arg g = build_generator('aftfilr', %w(GeologyDocument)) assert_equal 'GeologyDocument', g.name assert_equal 'geology_document', g.singular_name assert_equal 'geology_documents', g.plural_name assert_equal 'geology_documents', g.table_name assert_equal [], g.class_path assert_equal 'GeologyDocument', g.class_name assert_equal 'GeologyDocuments', g.controller_class_name # APPTODO: Make below loc pass. Need something like decamelize. # assert_equal 'Geology Document Manager', g.tinymce_window_title assert_equal '/geology_documents', g.controller_index_path end def test_generated_namespaced_names_with_path_arg g = build_generator('aftfilr', %w(admin/document)) assert_equal 'admin/document', g.name assert_equal 'document', g.singular_name assert_equal 'documents', g.plural_name assert_equal 'admin_documents', g.table_name assert_equal %w(admin), g.class_path assert_equal 'Admin::Document', g.class_name assert_equal 'Admin::Documents', g.controller_class_name assert_equal 'admin/document', g.file_path assert_equal 'Admin', g.class_nesting assert_equal 'Document Manager', g.tinymce_window_title assert_equal '/admin/documents', g.controller_index_path end def test_generated_namespaced_names_with_scoped_arg g = build_generator('aftfilr', %w(Admin::Document)) assert_equal 'Admin::Document', g.name assert_equal 'document', g.singular_name assert_equal 'documents', g.plural_name assert_equal 'admin_documents', g.table_name assert_equal %w(admin), g.class_path assert_equal 'Admin::Document', g.class_name assert_equal 'Admin::Documents', g.controller_class_name assert_equal '/admin/documents', g.controller_index_path end end
class AddStatusToImsExport < ActiveRecord::Migration[5.1] def change add_column :ims_exports, :status, :string, default: "processing" add_column :ims_exports, :message, :string, limit: 2048 end end
module EasyMapper class Query include Enumerable attr_accessor :model ''" builder methods "'' def initialize(model) @model = model @where = {} @order = {} end def where(query = nil) return @where unless query if @where @where.merge!(query) else @where = query end self end def order(fields = nil) return @order unless fields if @order @order.merge!(fields) else @order = fields end self end def limit(value = nil) return @limit unless value @limit = value self end def offset(value = nil) return @offset unless value @offset = value self end ''" kickers "'' def exec map_to_model_instances @model.repository.find(self) end def all where({}).exec end def single_result # TODO: return single result, raise exception if none or more exec.first end def each(&block) exec.each(&block) end def count(field = '*') @model.repository.aggregate('COUNT', field, @where) end def avg(field) @model.repository.aggregate('AVG', field, @where).to_f end def sum(field) @model.repository.aggregate('SUM', field, @where) end def inspect exec.inspect end def delete_all @model.repository.delete({}) end private def map_to_model_instances(records) records.map do |record| associations = map_associations_to_many(record) .merge(map_associations_to_one(record)) @model.new(record.merge(associations)) end end def map_associations_to_many(record) @model.associations_to_many.map do |assoc_to_many| [ assoc_to_many.name, assoc_to_many.cls.objects.where(assoc_to_many.mapped_by => record[:id]) ] end.to_h end def map_associations_to_one(record) @model.associations_to_one.map do |assoc| assoc_record = record .select { |key, _| key.to_s.include? "#{assoc.name}." } .map { |k, v| [k.to_s.gsub("#{assoc.name}.", '').to_sym, v] } .to_h [ assoc.name, assoc.cls.new(assoc_record) ] end.to_h end end end
require 'spec_helper' describe GapIntelligence::Pricing do before { stub_api_auth('CLIENTID', 'ASECRET') } subject(:client) { GapIntelligence::Client.new(client_id: 'CLIENTID', client_secret: 'ASECRET') } describe '#pricings' do let!(:pricings) { build_list(:pricing, 3) } before { stub_api_request(:get, response: { data: pricings }) } subject { client.pricings } it 'requests the endpoint' do subject expect(api_get('/pricings')).to have_been_made end it 'contains proper count of elements' do expect(subject.count).to eq(3) end end end
# frozen_string_literal: true class WelcomeController < ApplicationController def index return front_parallax unless user? now = Time.current today = now.to_date beginning_of_month = today.beginning_of_month @news_start_date = beginning_of_month - 1.month @news_items = [] add_items_for_month(today, beginning_of_month) add_items_for_month(today, @news_start_date) add_birthday_card(beginning_of_month, today) add_birthday_card(@news_start_date, today) add_newyears_card(beginning_of_month) add_newyears_card(@news_start_date) add_attendance_card(beginning_of_month, now) add_event_cards(today, beginning_of_month.next_month) # Future events if current_user.member load_graduation_cards(today) add_practice_cards(now) end @news_items.sort_by!(&:sort_time).reverse! @next_news_start_date = @news_start_date - 1.month end def news_by_month @news_items = [] @news_start_date = Date.parse(params[:date]) if current_user add_items_for_month(Date.current, @news_start_date) @news_items.sort_by!(&:sort_time).reverse! end @next_news_start_date = @news_start_date - 1.month if @news_items.empty? oldest_news_date = NewsItem.minimum('COALESCE(publish_at, created_at)').to_date @next_news_start_date = oldest_news_date if oldest_news_date > @next_news_start_date end render partial: 'news/items', layout: false end def front_parallax load_front_page_content render 'front_parallax', layout: 'public' end private def add_attendance_card(beginning_of_month, now) attendances_by_user = Attendance.present.from_date(beginning_of_month).to_datetime(now).group_by(&:user) return if (recent_attendances = attendances_by_user[current_user]).blank? attendances_since_graduation = current_user.attendances_since_graduation.count attendances_by_user = attendances_by_user.sort_by do |u, a| [-a.size, u == current_user ? 0 : 1, u.name] end @news_items << FrontCard.new( title: "Oppmøte #{helpers.month_name beginning_of_month.month}", publish_at: recent_attendances.map(&:date).max, body: render_to_string( partial: 'welcome/attendance', locals: { recent_attendances: recent_attendances, attendances_by_user: attendances_by_user, attendances_since_graduation: attendances_since_graduation } ) ) end def add_appointments_card(beginning_of_month) recent_elections = Election.current recent_appointments = Appointment.current instructors = GroupInstructor.active recent_committees = Committee.all recent_committee_memberships = CommitteeMember.all current_appointments = recent_elections + recent_appointments + recent_committees + recent_committee_memberships + instructors end_of_month = beginning_of_month + 1.month return unless current_appointments.any? do |e| e.updated_at >= beginning_of_month && e.updated_at < end_of_month && (!e.respond_to?(:to) || e.to.nil? || e.to >= beginning_of_month) end publish_date = current_appointments.map(&:updated_at).max return unless publish_date >= beginning_of_month && publish_date < end_of_month appointments_by_user = current_appointments.map do |a| case a when Election, Appointment [a.member.user, a.role.name] when Committee [a.head_user, "#{a.name} (leder)"] when CommitteeMember [a.user, a.committee.name] when GroupInstructor title = a.group_semester.chief_instructor == a.member ? 'Hovedinstruktør' : 'Instruktør' [a.member.user, "#{title} #{a.group_schedule.group.name}"] else raise "Unknown appointment type: #{a.inspect}" end end appointments_by_user.uniq! @news_items << FrontCard.new( title: 'Hvem gjør hva?', publish_at: publish_date, body: render_to_string( partial: 'welcome/appointments', locals: { current_appointments: appointments_by_user } ) ) end def add_birthday_card(beginning_of_month, today) birthdate = current_user.birthdate return unless birthdate && birthdate.mon == beginning_of_month.mon birthdate_this_year = Date.new(beginning_of_month.year, birthdate.mon, birthdate.day) return unless today >= birthdate_this_year body = +'' if current_user.member practice_years = current_user.member.years practice_count = current_user.practice_count practice_hours = current_user.practice_hours practice_hours_limit = 40 if practice_years > 1 body << <<~HTML <div class="mt-3"> I dine <b>#{practice_years} år</b> i klubben har vi registrert <b>#{practice_count} treninger</b> på deg. Det er over <b>#{practice_hours} timer#{practice_hours >= practice_hours_limit ? '!</b>' : '</b>.'} </div> HTML else body << <<~HTML <div class="mt-3"> Vi har registrert <b>#{practice_count} treninger</b> på deg. Det er over <b>#{practice_hours} timer#{practice_hours >= practice_hours_limit ? '!</b>' : '</b>.'} </div> HTML end end body << <<~HTML <div class="text-center mt-4"> <i class="fa fa-5x fa-birthday-cake"></i> <i class="fa fa-5x fa-gifts"></i> HTML if current_user.age >= 18 body << <<~HTML <i class="fa fa-5x fa-glass-cheers"></i> HTML end body << <<~HTML <h3 class="mt-3"> Ha en flott dag! </h3> </div> HTML birthday_item = FrontCard.new( created_at: birthdate_this_year, title: 'Gratulerer med dagen!', body: body ) @news_items << birthday_item end def add_newyears_card(from) return unless from.mon == 1 body = +'' body << <<~HTML <div class="text-center mt-4"> <i class="fa fa-5x fa-birthday-cake"></i> <i class="fa fa-5x fa-gifts"></i> HTML if current_user.age&.>=(18) body << <<~HTML <i class="fa fa-5x fa-glass-cheers"></i> HTML end body << <<~HTML <h3 class="mt-3"> Ha et flott #{from.year}! </h3> </div> HTML @news_items << FrontCard.new(created_at: from, title: 'Godt nytt år!', body: body) end def add_web_report_card(from) web_report = WebReport.where(year: from.year, month: from.month).first end_of_month = from.end_of_month.end_of_day technical_committee = technical_committee? if web_report if technical_committee title_link = <<~MD <a class="btn btn-#{web_report.published ? :secondary : :warning}" href="#{edit_web_report_path(web_report)}"><i class="fa fa-edit"/></a> MD elsif !web_report.published return end summary = web_report.summary body = web_report.body publish_at = [end_of_month, web_report.updated_at].min publication_state = web_report.published ? NewsItem::PublicationState::PUBLISHED : NewsItem::PublicationState::DRAFT elsif technical_committee && from.year >= 2022 summary = <<~MD [Skriv rapport](#{new_web_report_path(web_report: { year: from.year, month: from.month })}) MD publish_at = end_of_month publication_state = NewsItem::PublicationState::PUBLISHED else return end card = FrontCard.new( publish_at: publish_at, publication_state: publication_state, title: "Utvikling på web i #{helpers.month_name(from.month)}!", title_link: title_link, summary: summary, body: body ) @news_items << card end def add_practice_cards(now) return unless load_next_practices @next_practices.each do |next_practice| @news_items << FrontCard.new( publish_at: now + (now - next_practice.start_at), body: render_to_string( partial: 'layouts/next_practice', locals: { next_practice: next_practice } ) ) end end def add_event_cards(today, from) event_query = Event.from_date(from) event_query = event_query.to_date(from + 1.month) if from < today event_query = event_query.where.not(type: InstructorMeeting.name) unless current_user.instructor? event_query.each do |event| @news_items << FrontCard.new(publish_at: event.publish_at, body: render_to_string(partial: 'layouts/event_main', locals: { event: event, display_year: event.start_at.to_date.year != today.year, display_month: true, display_times: true })) end end def add_new_members_card(_today, from) new_members = Member.where('DATE(created_at) >= ? AND DATE(created_at) < ?', from, from + 1.month).to_a return if new_members.empty? @news_items << FrontCard.new( title: "Nye medlemmer i #{helpers.month_name from.month}", publish_at: new_members.map(&:created_at).max, body: new_members.map { |m| admin? ? "* [#{m.name}](#{edit_member_path(m)})" : "* #{m.name}" } .join("\n") ) end def add_items_for_month(today, from) @news_items.concat NewsItem.front_page_items(from: from, to: from + 1.month) add_curriculum_changes(from) add_event_cards(today, from) add_new_members_card(today, from) add_appointments_card(from) add_web_report_card(from) end def load_graduation_cards(today) graduations = Graduation .where(group_notification: true) .where('held_on BETWEEN ? AND ?', today, 1.month.from_now) .order(:held_on).to_a if graduations.any? publish_at = 1.month.before(graduations.map(&:held_on).min) graduation_news = FrontCard.new(created_at: publish_at, title: 'Graderinger', body: graduation_body(graduations)) @news_items.prepend graduation_news end graduates = Graduate.includes(:graduation).references(:graduations) .without_failed .where(member_id: current_user.member.id) .where.not(graduation_id: graduations.map(&:id)) .where('graduations.held_on BETWEEN ? AND ?', today, 1.month.from_now) .map { |c| GraduationNewsItem.new c.graduation } @news_items.concat graduates censors = Censor.includes(:graduation, :member).references(:graduations) .where(member_id: current_user.member.id) .where('graduations.held_on BETWEEN ? AND ? OR (approved_grades_at IS NULL)', today, 1.month.from_now) .where('declined IS NULL OR NOT declined') .map { |c| GraduationNewsItem.new c.graduation } @news_items.concat censors end def add_curriculum_changes(beginning_of_month) return unless current_user.member new_rank_articles = RankArticle.includes(:rank) .where('created_at >= ?', beginning_of_month) .where('created_at < ?', beginning_of_month + 1.month) .order(:created_at) .to_a.select { |ra| ra.rank.accessable? } new_basic_techniques = BasicTechnique.includes(:rank) .where('basic_techniques.created_at >= ?', beginning_of_month) .where('basic_techniques.created_at < ?', beginning_of_month + 1.month) .order('basic_techniques.created_at') .to_a new_applications = TechniqueApplication.includes(:rank) .where('technique_applications.created_at >= ?', beginning_of_month) .where('technique_applications.created_at < ?', beginning_of_month + 1.month) .to_a new_application_videos = ApplicationVideo.includes(technique_application: :rank) .where('application_videos.created_at >= ?', beginning_of_month) .where('application_videos.created_at < ?', beginning_of_month + 1.month) .order('application_videos.created_at') .to_a new_technique_links = TechniqueLink.includes(linkable: :rank) .where('technique_links.created_at >= ?', beginning_of_month) .where('technique_links.created_at < ?', beginning_of_month + 1.month) .order('technique_links.created_at') .to_a ranks = ( new_rank_articles.map(&:rank) + new_basic_techniques.map(&:rank) + new_applications.map(&:rank) + new_application_videos.map(&:technique_application).map(&:rank) + new_technique_links.map(&:linkable).map(&:rank) ).uniq.select(&:accessable?).select { |r| r.curriculum_group.martial_art.original? }.sort return if ranks.empty? rank_articles = new_rank_articles.select { |ra| ranks.include?(ra.rank) } new_basic_technique_links = new_technique_links.select { |tl| tl.linkable_type == 'BasicTechnique' } basic_technique_links = new_basic_technique_links.select { |tl| ranks.include?(tl.linkable.rank) } basic_techniques = (new_basic_techniques.select { |bt| ranks.include?(bt.rank) } + basic_technique_links.map(&:linkable)).uniq new_application_links = new_technique_links.select { |tl| tl.linkable_type == 'TechniqueApplication' } application_links = new_application_links.select { |al| ranks.include?(al.linkable.rank) } application_videos = new_application_videos.select do |av| ranks.include?(av.technique_application.rank) end technique_applications = (new_applications.select { |a| ranks.include?(a.rank) } + application_videos.map(&:technique_application) + application_links.map(&:linkable)).uniq articles_by_rank = rank_articles.group_by(&:rank) basic_techniques_by_rank = basic_techniques.group_by(&:rank) technique_applications_by_rank = technique_applications.group_by(&:rank) publish_at = (rank_articles + basic_techniques + technique_applications + application_videos + application_links + basic_technique_links).map(&:created_at).max videos_by_application = new_application_videos.group_by(&:technique_application_id) links_by_basic_technique = basic_technique_links.group_by(&:linkable_id) links_by_application = application_links.group_by(&:linkable_id) article_icon = "<i class='fa fa-newspaper'/>" video_icon = "<i class='fa fa-video'/>" link_icon = "<i class='fa fa-link'/>" @news_items << FrontCard.new( publish_at: publish_at, title: "Pensum-nyheter i #{helpers.month_name beginning_of_month.month}", body: ranks.map do |rank| rank_md = "##### [#{rank.name}](#{rank_path(rank)})\n" if (articles = articles_by_rank[rank]) articles.each do |ra| rank_md << <<~MD <a class="badge bg-danger ms-1 float-end" title="#{ra.information_page.title}" href="#{url_for(ra.information_page)}">#{article_icon}</a> [#{ra.information_page.title}](#{url_for(ra.information_page)})\n\n MD end end if (techniques = basic_techniques_by_rank[rank]) rank_md << (techniques.map do |technique| links = +'' if (app_links = links_by_basic_technique[technique.id]) links << app_links.map { |tl| <<~HTML }.join <a class="badge bg-info ms-1" title="#{tl.linkable.label}" href="#{helpers.basic_technique_path(tl.linkable, anchor: :links_tab)}">#{link_icon}</a> HTML end if basic_techniques.include?(technique) links << <<~HTML <span class="badge bg-warning ms-1">Ny!</span> HTML end links_span = "<span class='float-end'>#{links}</span>" <<~MD #{links_span}[#{technique.name}](#{url_for(technique)})\n\n MD end.join) end rank_md << (technique_applications_by_rank[rank].map do |application| links = +'' if (app_links = links_by_application[application.id]) links << app_links.map { |tl| <<~HTML }.join <a class="badge bg-info ms-1" title="#{tl.linkable.label}" href="#{helpers.technique_application_path(tl.linkable, anchor: :links_tab)}">#{link_icon}</a> HTML end if (app_videos = videos_by_application[application.id]) links << app_videos.map { |av| <<~HTML }.join <a class="badge bg-info ms-1" title="#{av.technique_application.label}" href="#{helpers.image_url_with_cl(av.image)}">#{video_icon}</a> HTML end if new_applications.include?(application) links << <<~HTML <span class="badge bg-warning ms-1">Ny!</span> HTML end links_span = "<span class='float-end'>#{links}</span>" <<~MD #{links_span}[#{application.name}](#{url_for(application)}) MD end.join("\n\n")) end.join("\n\n") ) end def load_front_page_content @promo_video = Image.find_by(id: 1265) @front_page_sections = FrontPageSection.includes(:image).order(:position).to_a @event = Event.upcoming.order(:start_at).find { |e| current_user&.member || e.public? } end def graduation_body(graduations) table_rows = graduations.map do |g| weekday = helpers.day_name(g.held_on.wday) "|#{g.group.name}|#{weekday}|#{g.held_on}|kl. #{g.start_at.strftime('%R')}|" end "Følgende graderinger er satt opp dette semesteret:\n\n#{table_rows.join("\n")}" end end
class RenamePassedCarsToMoves < ActiveRecord::Migration def change rename_table :passed_cars, :moves end end
class Admin::RunLogsController < Admin::Backend def index if !params[:run_log_ids].nil? RunLog.destroy_all(["id in (?)", params[:run_log_ids]]) end @run_logs = RunLog.paginate :page => params[:page], :per_page => 15, :order => "id desc" end def destroy @log = RunLog.find(params[:id]) @log.destroy redirect_to [:admin, :run_logs] end def clear RunLog.destroy_all redirect_to [:admin, :run_logs] end end
require 'faker' require 'factory_girl' FactoryGirl.define do factory :locuser_location, :class => 'Locuser::Location' do name "Home" end factory :address_owner, :class => 'Locuser::TestAddressOwner' do end factory :owned_address, :class => 'Locuser::TestOwnerAddress' do association :owner, factory: :address_owner, strategy: :build end factory :hashed_address, :class => 'Locuser::TestHashedAddress' do end factory :random_hashed_address, :parent => :hashed_address do name Faker::Company.name after(:build) { |a| a.address = Locuser::SpecSeedData.addresses.shift } end factory :uwmc, :parent => :hashed_address do name "University of Washington Medical Center" after(:build) { |a| a.address = "1959 NE Pacific Avenue, Seattle, WA 98195" } end factory :uwmc_hashed, :parent => :hashed_address do name "University of Washington Medical Center" after(:build) { |a| a.address_hash = { :street => '1959 NE Pacific Ave', :city => 'Seattle', :state => 'WA', :postal_code => '98195' } } end end
require 'java' require 'bundler' require 'logger' require 'tempfile' require 'killbill' require 'killbill/killbill_logger' # JRuby specific, not required by default require 'killbill/http_servlet' require 'killbill/payment_test' require 'killbill/notification_test' require 'killbill/invoice_test' require 'killbill/helpers/active_merchant' require 'killbill/helpers/active_merchant/active_record/models/helpers' require 'killbill/helpers/active_merchant/killbill_spec_helper' require 'killbill/ext/active_merchant/typhoeus_connection' %w( MockAccountUserApi ).each do |api| begin java_import "org.killbill.billing.mock.api.#{api}" rescue LoadError end end require 'rspec' RSpec.configure do |config| config.color_enabled = true config.tty = true config.formatter = 'documentation' end require 'active_record' ActiveRecord::Base.establish_connection( :adapter => 'sqlite3', :database => 'test.db' ) # For debugging #ActiveRecord::Base.logger = Logger.new(STDOUT) # Create the schema require File.expand_path(File.dirname(__FILE__) + '/killbill/helpers/test_schema.rb') begin require 'securerandom' SecureRandom.uuid rescue LoadError, NoMethodError # See http://jira.codehaus.org/browse/JRUBY-6176 module SecureRandom def self.uuid ary = self.random_bytes(16).unpack("NnnnnN") ary[2] = (ary[2] & 0x0fff) | 0x4000 ary[3] = (ary[3] & 0x3fff) | 0x8000 "%08x-%04x-%04x-%04x-%04x%08x" % ary end unless respond_to?(:uuid) end end
Given(/^I am on the "([^"]*)" page(?: for "([^"]*)")?$/) do |page, email| user = email == nil ? @user : User.find_by(email: email) visit path_with_locale(get_path(page, user)) end When(/^I fail to visit the "([^"]*)" page$/) do |page| path = get_path(page) visit path_with_locale(path) expect(current_path).not_to be path end When(/^I am on the static workgroups page$/) do visit page_path('yrkesrad') end When(/^I am on the test member page$/) do path = File.join(Rails.root, 'spec', 'fixtures', 'member_pages', 'testfile.html') allow_any_instance_of(ShfDocumentsController).to receive(:page_and_file_path) .and_return([ 'testfile', path ]) visit contents_show_path('testfile') end Then(/^(?:I|they) click the browser back button and "([^"]*)" the prompt$/) do |modal_action| case modal_action when 'accept' # accept == leave page page.accept_confirm { page.evaluate_script('window.history.back()') } when 'dismiss' # dismiss == stay on page page.dismiss_confirm { page.evaluate_script('window.history.back()') } else raise 'invalid modal_action specified' end end
module Api::V1 class MembershipsController < ApplicationController def create @membership = Membership.new(membership_params) @membership.user = session_user @membership.mod = false if @membership.save render json: { id: @membership.id.to_s, userId: @membership.user_id.to_s, clubId: @membership.club_id.to_s, isMod: @membership.mod }, status: :created else render json: {errors: @membership.errors.full_messages}, status: :unprocessable_entity end end def destroy @membership = Membership.find(params[:id]) if @membership.destroy render json: { id: @membership.id.to_s, userId: @membership.user_id.to_s, clubId: @membership.club_id.to_s, success: "#{@membership.user.name} left #{@membership.club.name}." }, status: :accepted else render json: {errors: @membership.errors.full_messages}, status: :unprocessable_entity end end private def membership_params params.require(:membership).permit(:club_id, :user_id) end end end
# frozen-string-literal: true module EncryptedFormFields module Helpers module FormTagHelper # Creates a hidden input field used with encrypted content. Use this field # to transmit data that user shouldn't see or be able to modify. # # ==== Options # * Creates standard HTML attributes for the tag. # # ==== Examples # encrypted_field_tag 'email_verified_at', Time.now.to_s # => <input id="email_verified_at" name="_encrypted_email_verified_at" type="hidden" value="[encrypted]" /> def encrypted_field_tag(name, value = nil, options = {}) encrypted_value = EncryptedFormFields.encrypt_and_sign(value) prefixed_name = EncryptedFormFields.prefix_name(name.to_s) tag :input, { "type" => "hidden", "name" => prefixed_name, "id" => sanitize_to_id(name), "value" => encrypted_value }.update(options.stringify_keys) end end end end
# Copyright (c) 2006, 2007 Ruffdogs Software, Inc. # Authors: Adam Lebsack <adam@holonyx.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. module Restore module Restorer module_require_dependency :filesystem, 'restorer' require 'net/ftp' class Ftp < Restore::Restorer::Filesystem def execute @ftp = Net::FTP::new @ftp.passive = @target.passive @ftp.connect(@target.hostname, @target.port) @ftp.login(@target.username, @target.password) begin super ensure @ftp.close end end def create_directory(path) stack = [] until path == stack.last # dirname("/")=="/", dirname("C:/")=="C:/" stack.push path path = File.dirname(path) end stack.reverse_each do |path| begin @ftp.mkdir(path) rescue => e raise unless directory?(path) || e.to_s =~ /File exists/ end end end def directory?(path) pwd = @ftp.pwd @ftp.chdir(path) rescue => e false if e.to_s =~ /Not a directory$/ ensure @ftp.chdir pwd end def copy_file(file, log) # XXX apply mtime! if log.file_type == 'D' create_directory(File.join(@subdir,file.path)) elsif log.file_type == 'F' create_directory(File.dirname(File.join(@subdir,file.path))) log.storage.open('r') do |local| @ftp.storbinary("STOR " + File.join(@subdir,file.path), local, 64.kilobytes) end end end end end end
require 'aws/templates/utils' module Aws module Templates module Utils ## # Introduces class method inheritance through module hierarchy module Inheritable ## # Core class-level mixins # # Contains core logic of the inheritance feature. This module is used as extention # in every including module/class to expose appropriate module-level primitives for # handling inheritance of class-scope methods. module ClassMethods ## # Empty class scope # # Identity class scope which contains nothing. Used as base case for class scope # inheritance hierarchy. module ClassScope end ## # To add class methods also while including the module def included(base) super(base) base.extend(ClassMethods) base.extend(ClassScope) end def instance_scope(&blk) module_eval(&blk) end def class_scope(&blk) raise ScriptError.new('class_scope should have a block') if blk.nil? _define_class_scope unless _class_scope_defined? ClassScope.module_eval(&blk) extend ClassScope end def _class_scope_defined? @class_scope_defined || false end def _define_class_scope const_set(:ClassScope, ClassScope.dup) @class_scope_defined = true end end extend ClassMethods end end end end
class TimingsController < ApplicationController before_action :require_admin, :admin_privacy, only: [:index, :new, :edit] def index @timings = Timing.all end def user_timings @timings = Timing.all @timings.each do |timing| timing.date = date_of_next(timing.day) end @timings = @timings.sort_by &:date end def new @timing = Timing.new end def edit @timing = Timing.find(params[:id]) end def create @timing = Timing.new(timing_params) respond_to do |format| if @timing.save format.html { redirect_to timings_path, notice: 'Timing was successfully created.' } format.json { render :show, status: :created, location: @timing } else format.html { render :new } format.json { render json: @timing.errors, status: :unprocessable_entity } end end end def update @timing = Timing.find(params[:id]) respond_to do |format| if @timing.update(timing_params) format.html { redirect_to timings_path, notice: 'Timing was successfully updated.' } format.json { render :show, status: :ok, location: @timing } #already filled in timing is of correct format. This check is not needed. #else # format.html { render :edit } # format.json { render json: @timing.errors, status: :unprocessable_entity } end end end def destroy Timing.find(params[:id]).destroy respond_to do |format| format.html { redirect_to timings_path, notice: 'Timing was successfully destroyed.' } format.json { head :no_content } end end private def timing_params params.require(:timing).permit(:day, :hours, :minutes, :ampm) end def format_time(time) startTime = time.length <= 2 ? time + ":00" : time endTime = time.to_i + 2 endTime = endTime > 24 ? 00 : endTime endTime = time.length <= 2 ? endTime.to_s + ":00" : endTime.to_s time = startTime + " - " + endTime end end
#!/usr/bin/env ruby require 'rake' require 'rake/file_utils' # Excluding these HTML elements produces a file with only <p>, <i>, and <b> elements. # A reasonably simple sed command can translate the resulting HTML to DBP TeX. EXCLUDED_ELEMENTS = %w[a body font head html span xml] EXCLUSION_OPTION = ['-excludedelements', "(#{EXCLUDED_ELEMENTS.join(',')})"] RTF_TO_HTML_COMMAND = %w[textutil -stdout -convert html] + EXCLUSION_OPTION + ARGV sh *RTF_TO_HTML_COMMAND
# encoding: utf-8 class BaseUploader < CarrierWave::Uploader::Base include CarrierWave::MiniMagick storage :fog def cache_dir dir = Rails.configuration.app['carrierwave']['cache_dir'] (dir && File.directory?(dir)) ? dir : super end # Override the directory where uploaded files will be stored. # This is a sensible default for uploaders that are meant to be mounted: def store_dir if model.respond_to?(:sha) && model.sha.present? "uploads/#{model.class.to_s.underscore}/#{mounted_as}/sha/#{sha_hierarchy}" else "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{id_hierarchy}/#{model.id}/#{model.uuid}" end end def filename model.respond_to?(:sha) ? "#{model.sha}.#{file.extension}" : super end # Limit the number of items in each subdirectory # to make manual browsing/lookups much faster def id_hierarchy id_string = model.id.to_s dirs = [] while !id_string.empty? dirs << id_string.slice!(0..1).ljust(2, '0') end dirs.join('/') end # Limit the number of items in each subdirectory # to make manual browsing/lookups much faster def sha_hierarchy sha_string = model.sha.to_s dirs = [sha_string[0..1], sha_string[2..3], sha_string[4..5]] dirs.join('/') end def media_type(file) type = file.content_type MIME::Types[type].first.try(:media_type) || type.split('/').first end private def image?(file) media_type(file) == 'image' end def video?(file) media_type(file) == 'video' end end
class RenameLabeliColumnToCategories < ActiveRecord::Migration[6.0] def change rename_column :categories, :labeli, :name end end
Before do Subcheat::Runner.output = StringIO.new Subcheat::Runner.perform_run = false end Given /^a working copy$/ do @wc ||= {} end Given /^(?:a working copy )?with attribute ([^:]+?): (.+?)$/ do |attribute, value| Subcheat::Svn.any_instance.expects(:attr).with(attribute).returns(value) end When /^I run "subcheat([^\"]*)"$/ do |arguments| Subcheat::Runner.new(*arguments.strip.split(/\s+/)) end Then /^subcheat should run "([^\"]*)"$/ do |command| assert_equal command, Subcheat::Runner.output.string.gsub(/\s*$/, '') end Then /^subcheat should output "([^\"]*)"$/ do |output| assert_match(/#{output}/, Subcheat::Runner.output.string) end
FactoryGirl.define do factory :tax_type do code { Faker::Lorem.characters(3)} name { Faker::Lorem.word } description { Faker::Lorem.paragraph } sequence(:sequence) end end
class Api::V1::FollowsController < ApplicationController skip_before_action :authorized def create @follow = Follow.create(follow_params) if @follow.valid? render json: @follow, status: :created else render json: { error: 'failed to create follow' }, status: :unprocessable_entity end end def index @follows = Follow.all render json: @follows end private def follow_params params.require(:follow).permit(:follower_id,:followed_user_id) end end
FactoryGirl.define do factory :plan, class: Plan do association :asset, factory: :asset association :contact, factory: :contact token SecureRandom.urlsafe_base64 expiration Time.zone.now description "" end end
class AddColumnCostCenterIdToPartOfEquipments < ActiveRecord::Migration def change unless column_exists? :part_of_equipments, :cost_center_id add_column :part_of_equipments, :cost_center_id, :integer end end end
require 'test_helper' class DealMilestonesControllerTest < ActionController::TestCase setup do @deal_milestone = deal_milestones(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:deal_milestones) end test "should get new" do get :new assert_response :success end test "should create deal_milestone" do assert_difference('DealMilestone.count') do post :create, deal_milestone: { color: @deal_milestone.color, description: @deal_milestone.description, probability: @deal_milestone.probability, sort_order: @deal_milestone.sort_order, status: @deal_milestone.status, title: @deal_milestone.title } end assert_redirected_to deal_milestone_path(assigns(:deal_milestone)) end test "should show deal_milestone" do get :show, id: @deal_milestone assert_response :success end test "should get edit" do get :edit, id: @deal_milestone assert_response :success end test "should update deal_milestone" do put :update, id: @deal_milestone, deal_milestone: { color: @deal_milestone.color, description: @deal_milestone.description, probability: @deal_milestone.probability, sort_order: @deal_milestone.sort_order, status: @deal_milestone.status, title: @deal_milestone.title } assert_redirected_to deal_milestone_path(assigns(:deal_milestone)) end test "should destroy deal_milestone" do assert_difference('DealMilestone.count', -1) do delete :destroy, id: @deal_milestone end assert_redirected_to deal_milestones_path end end
class Order < ApplicationRecord belongs_to :ordered, class_name: 'User' belongs_to :attended_order, class_name: 'Product' validates :ordered_id, presence: true end
class ActionlogsController < ApplicationController # GET /actionlogs # GET /actionlogs.json def index @actionlogs = Actionlog.all respond_to do |format| format.html # index.html.erb format.json { render json: @actionlogs } end end # GET /actionlogs/1 # GET /actionlogs/1.json def show @actionlog = Actionlog.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @actionlog } end end # GET /actionlogs/new # GET /actionlogs/new.json def new @actionlog = Actionlog.new respond_to do |format| format.html # new.html.erb format.json { render json: @actionlog } end end # GET /actionlogs/1/edit def edit @actionlog = Actionlog.find(params[:id]) end # POST /actionlogs # POST /actionlogs.json def create @actionlog = Actionlog.new(params[:actionlog]) respond_to do |format| if @actionlog.save #format.html { redirect_to @actionlog, notice: 'Actionlog was successfully created.' } #format.json { render json: @actionlog, status: :created, location: @actionlog } format.html { redirect_to actionlogs_url } else format.html { render action: "new" } format.json { render json: @actionlog.errors, status: :unprocessable_entity } end end end # PUT /actionlogs/1 # PUT /actionlogs/1.json def update @actionlog = Actionlog.find(params[:id]) respond_to do |format| if @actionlog.update_attributes(params[:actionlog]) format.html { redirect_to actionlogs_url } #format.html { redirect_to @actionlog, notice: 'Actionlog was successfully updated.' } #format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @actionlog.errors, status: :unprocessable_entity } end end end # DELETE /actionlogs/1 # DELETE /actionlogs/1.json def destroy @actionlog = Actionlog.find(params[:id]) @actionlog.destroy respond_to do |format| format.html { redirect_to actionlogs_url } format.json { head :no_content } end end end
class Pnameforms::Piece21sController < ApplicationController before_action :set_piece21, only: [:show, :edit, :update, :destroy] # GET /piece21s # GET /piece21s.json def index @pnameform = Pnameform.find(params[:pnameform_id]) @piece21s = @pnameform.piece21s end # GET /piece21s/21 # GET /piece21s/21.json def show @pnameform = Pnameform.find(params[:pnameform_id]) @piece21s = Piece21.all end # GET /piece21s/new def new @pnameform = Pnameform.find(params[:pnameform_id]) @piece21 = current_user.piece21s.build end # GET /piece21s/21/edit def edit @pnameform = Pnameform.find(params[:pnameform_id]) @piece21.pnameform = @pnameform end # POST /piece21s # POST /piece21s.json def create @pnameform = Pnameform.find(params[:pnameform_id]) @piece21 = current_user.piece21s.build(piece21_params) @piece21.pnameform = @pnameform respond_to do |format| if @piece21.save format.html { redirect_to pnameform_piece21s_path(@pnameform), notice: 'Piece21 was successfully created.' } format.json { render :show, status: :created, location: @piece21 } else format.html { render :new } format.json { render json: @piece21.errors, status: :unprocessable_entity } end end end # PATCH/PUT /piece21s/21 # PATCH/PUT /piece21s/21.json def update @pnameform = Pnameform.find(params[:pnameform_id]) @piece21.pnameform = @pnameform respond_to do |format| if @piece21.update(piece21_params) format.html { redirect_to pnameform_piece21s_path(@pnameform), notice: 'Piece21 was successfully updated.' } format.json { render :show, status: :ok, location: @piece21 } else format.html { render :edit } format.json { render json: @piece21.errors, status: :unprocessable_entity } end end end # DELETE /piece21s/21 # DELETE /piece21s/21.json def destroy @pnameform = Pnameform.find(params[:pnameform_id]) @piece21 = Piece21.find(params[:id]) title = @piece21.name if @piece21.destroy flash[:notice] = "\"#{title}\" was deleted successfully." redirect_to pnameform_piece21s_path(@pnameform) else flash[:error] = "There was an error deleting." render :show end end private # Use callbacks to share common setup or constraints between actions. def set_piece21 @piece21 = Piece21.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def piece21_params params.require(:piece21).permit(:name, :user_id) end end
require 'codeclimate-test-reporter' require 'simplecov' SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[ SimpleCov::Formatter::HTMLFormatter, CodeClimate::TestReporter::Formatter ] SimpleCov.start 'rails' ENV['RAILS_ENV'] ||= 'test' require 'spec_helper' require File.expand_path('../../config/environment', __FILE__) require 'rspec/rails' require 'shoulda/matchers' require 'capybara/email/rspec' require 'sidekiq/testing' Sidekiq::Testing.inline! Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } ActiveRecord::Migration.maintain_test_schema! RSpec.configure do |config| config.fixture_path = "#{::Rails.root}/spec/fixtures" config.use_transactional_fixtures = false config.infer_spec_type_from_file_location! config.filter_run focus: true config.run_all_when_everything_filtered = true config.include AbstractController::Translation config.include FactoryGirl::Syntax::Methods config.include FactoryGirl::Syntax:: Methods config.include Devise::TestHelpers, type: :controller config.include FeatureMacros, type: :feature config.include ControllerMacros, type: :controller config.include RequestMacros, type: :request config.include OmniAuthTestHelper, type: :request OmniAuth.config.test_mode = true config.before(:each) do |example| OmniAuth.config.mock_auth[:twitter] = nil OmniAuth.config.mock_auth[:facebook] = nil DatabaseCleaner.strategy = example.metadata[:js] ? :truncation : :transaction DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean ActionMailer::Base.deliveries = [] end config.after(:each, js: true) do expect(page).to_not have_content "No theme CSS loaded" end config.after(:suite) do FileUtils.rm_rf(Dir["#{Rails.root}/spec/test_files/"]) end Capybara.javascript_driver = :selenium Capybara.asset_host = "http://localhost:5000" Capybara.server_port = 53023 end
require 'rails_helper' describe Users::AddressesController do describe "#index" do context 'not login' do before do @request.env["devise.mapping"] = Devise.mappings[:user] session[:received_form] = { user: { nickname: Faker::Name.last_name, email: Faker::Internet.free_email, password: "password", password_confirmation: "password", last_name: Gimei.last.kanji, first_name: Gimei.first.hiragana, last_name_kana: Gimei.last.katakana, first_name_kana: Gimei.first.katakana, birth_day: "20190415" } } get :index end it 'assigns @user' do expect(assigns(:user)).to be_a_new(User) end it 'renders the :index template' do expect(response).to render_template :index end end end describe "#create" do context 'not login' do before do @request.env["devise.mapping"] = Devise.mappings[:user] end let(:params) do { user: { nickname: Faker::Name.last_name, email: Faker::Internet.free_email, password: "password", password_confirmation: "password", last_name: Gimei.last.kanji, first_name: Gimei.first.hiragana, last_name_kana: Gimei.last.katakana, first_name_kana: Gimei.first.katakana, birth_day: "20190415" }, address: { postal_code: Faker::Number.number(digits: 7), prefecture: Gimei.prefecture.kanji , city: Gimei.city.kanji, street: Gimei.town.kanji, building_name: Gimei.last.kanji, phone: Faker::Number.number(digits: 11) } } end let(:invalid_params) do { user: { nickname: Faker::Name.last_name, birth_day: "19450111" }, address: { postal_code: "88888888", phone: Faker::Number.number(digits: 11) } } end context 'pass validation' do subject { post :create, params: params } it 'redirect to users_phones_path' do subject expect(response).to redirect_to(users_creditcards_path) end end context 'not pass validation' do subject { post :create, params: invalid_params } it 'renders users/addresses/index' do subject expect(response).to render_template 'users/addresses/index' end end end end end
require "test_helper" class Admin::WeekendsControllerTest < ActionController::TestCase def setup setup_admin_user end def test_index weekend_1 = FactoryBot.create(:weekend, created_at: "2020-04-25") weekend_2 = FactoryBot.create(:weekend, created_at: "2020-04-26") get :index assert_template "admin/weekends/index" assert_primary_keys([weekend_2, weekend_1], assigns(:weekends)) end def test_show weekend = FactoryBot.create(:weekend) get :show, params: { id: weekend } assert_template "admin/weekends/show" assert_equal(weekend, assigns(:weekend)) end def test_new get :new assert_template "admin/weekends/new" assert_not_nil(assigns(:weekend)) end def test_create_invalid front_user_1 = FactoryBot.create(:front_user) Weekend.any_instance.stubs(:valid?).returns(false) post( :create, params: { weekend: { front_user: front_user_1, body: "The Body Wadus" } } ) assert_template "new" assert_not_nil(flash[:alert]) end def test_create_valid front_user_1 = FactoryBot.create(:front_user) post( :create, params: { weekend: { front_user_id: front_user_1, body: "Wadus Message longer than 20 chars" } } ) weekend = Weekend.last assert_redirected_to [:admin, weekend] assert_equal("Wadus Message longer than 20 chars", weekend.body) assert_equal(front_user_1, weekend.front_user) end def test_edit weekend = FactoryBot.create(:weekend) get :edit, params: { id: weekend } assert_template "edit" assert_equal(weekend, assigns(:weekend)) end def test_update_invalid weekend = FactoryBot.create(:weekend) Weekend.any_instance.stubs(:valid?).returns(false) put( :update, params: { id: weekend, weekend: { body: "Wadus Message longer than 20 chars" } } ) assert_template "edit" assert_not_nil(flash[:alert]) end def test_update_valid weekend = FactoryBot.create(:weekend) put( :update, params: { id: weekend, weekend: { body: "Wadus Message longer than 20 chars" } } ) assert_redirected_to [:admin, weekend] assert_not_nil(flash[:notice]) weekend.reload assert_equal("Wadus Message longer than 20 chars", weekend.body) end def test_destroy weekend = FactoryBot.create(:weekend) delete :destroy, params: { id: weekend } assert_redirected_to :admin_weekends assert_not_nil(flash[:notice]) assert !Weekend.exists?(weekend.id) end end
require 'uri' require_relative '../../lib/scoped_wiremock/scoped_wiremock_client' describe ScopedWireMock::ScopedWireMockClient do DOCKER_HOST=WireMock.get_first_ip_not_in('172', '127') it 'should start a new global scope' do wiremock_client= ScopedWireMock::ScopedWireMockClient.new("http://#{DOCKER_HOST}:8083") wiremock_client.reset_all #given: 'a service under test' #when: 'I start a new global scope' result_global_scope = wiremock_client.start_new_global_scope( run_name: 'android_regression', wiremock_public_url: "http://#{DOCKER_HOST}:8083", integration_scope: 'something', url_of_service_under_test: "http://#{DOCKER_HOST}:8080", global_journal_mode: 'RECORD', payload: {prop1: 'val1'} ) #then: 'the correlation path must reflect the WireMock host name, port, the testRunName and the number 0' expect(result_global_scope['correlationPath']).to eq "#{DOCKER_HOST}/8083/android_regression/0" expect(result_global_scope['payload']['prop1']).to eq 'val1' end it 'should start multiple concurrent global scopes' do wiremock_client= ScopedWireMock::ScopedWireMockClient.new("http://#{DOCKER_HOST}:8083") wiremock_client.reset_all #given: 'a service under test' #when: 'I start a new global scope' result_global_scope1 = wiremock_client.start_new_global_scope( run_name: 'android_regression', wiremock_public_url: "http://#{DOCKER_HOST}:8083", integration_scope: 'something', url_of_service_under_test: "http://#{DOCKER_HOST}:8080", global_journal_mode: 'RECORD' ) result_global_scope2 = wiremock_client.start_new_global_scope( run_name: 'android_regression', wiremock_public_url: "http://#{DOCKER_HOST}:8083", integration_scope: 'something', url_of_service_under_test: "http://#{DOCKER_HOST}:8080", global_journal_mode: 'RECORD' ) #then: 'the correlation path must reflect the WireMock host name, port, the testRunName and the number 1' expect(result_global_scope1['correlationPath']).to eq "#{DOCKER_HOST}/8083/android_regression/0" expect(result_global_scope2['correlationPath']).to eq "#{DOCKER_HOST}/8083/android_regression/1" end it 'should stop a global scope' do wiremock_client= ScopedWireMock::ScopedWireMockClient.new("http://#{DOCKER_HOST}:8083") wiremock_client.reset_all #given: 'a service under test' #and" 'a global scope' result_global_scope = wiremock_client.start_new_global_scope( run_name: 'android_regression', wiremock_public_url: "http://#{DOCKER_HOST}:8083", integration_scope: 'something', url_of_service_under_test: "http://#{DOCKER_HOST}:8080", global_journal_mode: 'RECORD' ) #when: 'I stop the global scope' stopped_scope=wiremock_client.stop_global_scope(run_name: 'android_regression', wiremock_public_url: "http://#{DOCKER_HOST}:8083", sequence_number: result_global_scope['sequenceNumber'], url_of_service_under_test: "http://#{DOCKER_HOST}:8080", payload: {prop1: 'val1'} ) #then: 'the correlation path must reflect the WireMock host name, port, the testRunName and the number 1' expect(stopped_scope['correlationPath']).to eq "#{DOCKER_HOST}/8083/android_regression/0" expect(stopped_scope['payload']['prop1']).to eq 'val1' end it 'should start a nested scope' do wiremock_client= ScopedWireMock::ScopedWireMockClient.new("http://#{DOCKER_HOST}:8083") wiremock_client.reset_all #given: 'a global scope' global_scope = wiremock_client.start_new_global_scope( run_name: 'android_regression', wiremock_public_url: "http://#{DOCKER_HOST}:8083", integration_scope: 'something', url_of_service_under_test: "http://#{DOCKER_HOST}:8080", global_journal_mode: 'RECORD' ) #when: 'I start a nested scope' nested_scope = wiremock_client.start_nested_scope(global_scope['correlationPath'], 'nested1', {'prop1' => 'val1'}) #then: 'the correlation path must reflect the WireMock host name, port, the testRunName and the number 1' expect(nested_scope['correlationPath']).to(eq(global_scope['correlationPath'] + '/nested1')) retrieved_scope=wiremock_client.get_correlated_scope(nested_scope['correlationPath']) expect(nested_scope['correlationPath']).to(eq(retrieved_scope['correlationPath'])) end it 'should start a nested scope within another nested scope' do wiremock_client= ScopedWireMock::ScopedWireMockClient.new("http://#{DOCKER_HOST}:8083") wiremock_client.reset_all #given: 'a global scope' global_scope = wiremock_client.start_new_global_scope( run_name: 'android_regression', wiremock_public_url: "http://#{DOCKER_HOST}:8083", integration_scope: 'something', url_of_service_under_test: "http://#{DOCKER_HOST}:8080", global_journal_mode: 'RECORD' ) #when: 'I start a nested scope within another nested scope' feature_scope = wiremock_client.start_nested_scope(global_scope['correlationPath'], 'feature1', {'prop1' => 'val1'}) scenario_scope = wiremock_client.start_nested_scope(feature_scope['correlationPath'], 'scenario1', {'prop1' => 'val1'}) #then: 'the correlation path must reflect the WireMock host name, port, the testRunName and the number 1' expect(scenario_scope['correlationPath']).to(eq(global_scope['correlationPath'] + '/feature1/scenario1')) retrieved_scope=wiremock_client.get_correlated_scope(scenario_scope['correlationPath']) expect(scenario_scope['correlationPath']).to(eq(retrieved_scope['correlationPath'])) end it 'should stop a nested scope' do wiremock_client= ScopedWireMock::ScopedWireMockClient.new("http://#{DOCKER_HOST}:8083") wiremock_client.reset_all #given: 'a global scope' global_scope = wiremock_client.start_new_global_scope( run_name: 'android_regression', wiremock_public_url: "http://#{DOCKER_HOST}:8083", integration_scope: 'something', url_of_service_under_test: "http://#{DOCKER_HOST}:8080", global_journal_mode: 'RECORD' ) #and: 'a nested scope' nested_scope = wiremock_client.start_nested_scope(global_scope['correlationPath'], 'nested1', {'prop1' => 'val1'}) #when: 'I stop the nested scope' wiremock_client.stop_nested_scope(nested_scope['correlationPath'], {'prop1' => 'val1'}) #then: 'the correlation path must reflect the WireMock host name, port, the testRunName and the number 1' expect(nested_scope['correlationPath']).to(eq(global_scope['correlationPath'] + '/nested1')) end it 'should start a guest scope' do wiremock_client= ScopedWireMock::ScopedWireMockClient.new("http://#{DOCKER_HOST}:8083") wiremock_client.reset_all #given: 'a global scope' global_scope = wiremock_client.start_new_global_scope( run_name: 'android_regression', wiremock_public_url: "http://#{DOCKER_HOST}:8083", integration_scope: 'something', url_of_service_under_test: "http://#{DOCKER_HOST}:8080", global_journal_mode: 'RECORD' ) #and: 'a nested scope' nested_scope = wiremock_client.start_nested_scope(global_scope['correlationPath'], 'nested1', {'prop1' => 'val1'}) #when: 'I stop the nested scope' user_scope = wiremock_client.start_user_scope(nested_scope['correlationPath'],'guest', {'prop1' => 'val1'}) puts user_scope.to_json #then: 'the correlation path must reflect the WireMock host name, port, the testRunName and the number 1' expect(user_scope['correlationPath']).to(eq(nested_scope['correlationPath'] + '/:guest')) end end
class AddForeignKeysAndIndexes < ActiveRecord::Migration def change add_foreign_key :data_data_values, :data add_foreign_key :data_data_values, :data_values add_index :data_data_values, :data_value_id add_index :data_data_values, :datum_id add_foreign_key :data_quality_flags, :data add_foreign_key :data_quality_flags, :quality_flags add_index :data_quality_flags, :datum_id add_index :data_quality_flags, :quality_flag_id add_foreign_key :event_quality_flags, :events add_foreign_key :event_quality_flags, :quality_flags add_index :event_quality_flags, :event_id add_index :event_quality_flags, :quality_flag_id add_foreign_key :events, :subjects add_foreign_key :events, :sources add_foreign_key :events, :documentations add_index :events, :subject_id add_index :events, :source_id add_index :events, :documentation_id add_foreign_key :sources, :users add_foreign_key :sources, :source_types add_index :sources, :user_id add_index :sources, :source_type_id add_foreign_key :study_nicknames, :studies add_index :study_nicknames, :study_id add_foreign_key :subjects, :studies add_index :subjects, :study_id add_foreign_key :documentations, :users add_index :documentations, :user_id add_foreign_key :data, :sources add_foreign_key :data, :documentations add_foreign_key :data, :events add_index :data, :source_id add_index :data, :documentation_id add_index :data, :event_id add_foreign_key :subjects_irbs, :subjects add_foreign_key :subjects_irbs, :irbs add_index :subjects_irbs, :subject_id add_index :subjects_irbs, :irb_id add_foreign_key :subjects_publications, :subjects add_foreign_key :subjects_publications, :publications add_index :subjects_publications, :subject_id add_index :subjects_publications, :publication_id add_foreign_key :subjects_project_leaders, :subjects add_foreign_key :subjects_project_leaders, :researchers add_index :subjects_project_leaders, :subject_id add_index :subjects_project_leaders, :researcher_id add_foreign_key :subjects_pis, :subjects add_foreign_key :subjects_pis, :researchers add_index :subjects_pis, :subject_id add_index :subjects_pis, :researcher_id end end
class AddStatusToPolls < ActiveRecord::Migration[5.2] def change add_column :polls, :status, :text end end
class CreateGroupings < ActiveRecord::Migration[6.0] def change create_table :groupings do |t| t.integer :account t.integer :group_account t.timestamps end end end
require "rails_helper" Rails.application.load_seed describe "Query: Movie.all" do it "should list movie rows" do visit "/" fill_in "Enter a Query", with: "Movie.all" click_on "Execute" visit "/levels/1/results" expect(page).to have_content('id') expect(page).to have_content('title') expect(page).to have_content('year') expect(page).to have_content('duration') expect(page).to have_content('director_id') end end describe "Query: Director.all" do it "should list director rows" do visit "/" fill_in "Enter a Query", with: "Director.all" click_on "Execute" visit "/levels/1/results" expect(page).to have_content('id') expect(page).to have_content('name') expect(page).to have_content('dob') expect(page).to have_content('bio') end end describe "Query: Actor.all" do it "should list actor rows" do visit "/" fill_in "Enter a Query", with: "Actor.all" click_on "Execute" visit "/levels/1/results" expect(page).to have_content('id') expect(page).to have_content('name') expect(page).to have_content('dob') expect(page).to have_content('bio') end end describe "Query: Role.all" do it "should list role rows" do visit "/" fill_in "Enter a Query", with: "Role.all" click_on "Execute" visit "/levels/1/results" expect(page).to have_content('id') expect(page).to have_content('movie_id') expect(page).to have_content('actor_id') expect(page).to have_content('character_name') end end describe "Query: Random Invalid text" do it "should display error: Uh oh" do # expect(page.find("th").text).eql ("Error") visit "/" fill_in "Enter a Query", with: "asdfghjkl" click_on "Execute" expect(page).to have_selector 'th', text: 'Error' end end describe "Query: Movie.find(0)" do it "should display error: Record not found" do visit "/" fill_in "Enter a Query", with: "Movie.find(0)" click_on "Execute" expect(page).to have_selector 'td', text: 'Record not found' end end # RSpec.feature "Query: Movie.first.banana_nut", type: :feature do # pending "should display error: Attribute doesn't exist for Record" # end
class Room attr_reader(:guests, :songs) def initialize(guests, songs) @guests = guests @songs = songs @capacity = 8 end def add_song_to_room(song) return @songs << song end def number_of_songs return @songs.length end def add_guest_to_room(guest) # ternary check if guests is less than capacity and if true it will add the guest into the room, else it display message saying room is full. return number_of_guests < @capacity ? @guests << guest : "Sorry this room is full." end def number_of_guests return @guests.length end def remove_guest_from_room(guest) return guests.pop end end
require 'spec_helper' describe 'profile::bind' do it { should contain_class 'firewall' } it { should contain_class 'profile::docker' } it { should contain_service 'docker-bind' } it { should contain_docker__image 'jenkinsciinfra/bind' } it { should contain_file('/etc/bind/local').with({ :ensure => 'directory', :purge => true, }) } it { should contain_file('/etc/bind/local/jenkins-ci.org.zone') } it { should contain_file('/etc/bind/local/named.conf.local') } end
class Result < ActiveRecord::Base belongs_to :exam belongs_to :question has_many :answers, dependent: :destroy has_many :options, through: :answers, dependent: :destroy after_create :create_answers accepts_nested_attributes_for :answers scope :incorrects, ->{where correct: false} def create_answers answers.create unless question.multiple_choice? end def result_status if exam.checked? status = correct? ? I18n.t("questions.labels.correct") : I18n.t("questions.labels.wrong") end status ||= "" end def result_correct_count? Answer.option_correct(id) == Option.count_correct_option(question_id) end def check_result if self.question.question_type == "text" self.update correct: self.answers.first.content.strip == self.question.options.first.content.strip ? true : nil else self.update correct: Answer.not_correct(self.id) <= 0 && Answer.option_correct(self.id) > 0 end end end
require "commander" require "yaml" require "droplet_kit" require "open-uri" module Dovpn class App include Commander::Methods def run program :name, 'dovpn' program :version, Dovpn::VERSION program :description, 'Set up an OpenVPN server on DigitalOcean on demand.' config = YAML.load(File.read(File.join(ENV["HOME"], ".dovpn.yml"))) || Hash.new("") command :start do |c| c.syntax = 'dovpn start [options]' c.summary = '' c.description = '' c.option '--token TOKEN', String, 'DigitalOcean API Token' c.action do |args, options| options.default token: config["token"] unless config["id"] client = DropletKit::Client.new(access_token: options.token) user_data = open("https://raw.githubusercontent.com/digitalocean/do_user_scripts/673d1a0b97c4c5306dd6432c90cc8c6fcb05860f/Ubuntu-14.04/network/open-vpn.yml").read droplet = DropletKit::Droplet.new(name: 'dovpn', region: 'nyc2', image: 'ubuntu-14-04-x64', size: '512mb', user_data: user_data) created = client.droplets.create(droplet) config["id"] = created["id"] end end end command :stop do |c| c.syntax = 'dovpn stop [options]' c.summary = '' c.description = '' c.option '--token TOKEN', String, 'DigitalOcean API Token' c.action do |args, options| options.default token: config["token"] if config["id"] client = DropletKit::Client.new(access_token: options.token) droplet = client.droplets.delete(id: config["id"]) config.delete("id") end end end command :status do |c| c.syntax = 'dovpn status [options]' c.summary = '' c.description = '' c.action do |args, options| if config["id"] puts "VPN online" else puts "VPN offline" end end end run! File.write(File.join(ENV["HOME"], ".dovpn.yml"), config.to_yaml) end end end
# U2.W6: Testing Assert Statements # I worked on this challenge by myself. # 2. Review the simple assert statement # def assert # raise "Assertion failed!" unless yield # end # name = "bettysue" # assert { name == "bettysue" } # assert { name == "billybob" } # 2. Pseudocode what happens when the code above runs # In the above code, there is an assert method and that assert method is called on two blocks (the code within the curly brackets). When the code in the block is equiivalent to the variable 'name' the code "yields" and prints the name to the console. Otherwise, if the code in the block does not equal what is assigned to the variable 'name,' it raises an error. # 3. Copy your selected challenge here def create_list(items) list = Hash.new(1) list_items = items.split(' ') list_items.each do |shopping_item| list[shopping_item] = 1 end print_list(list) end def add_item(list, item, quantity) list[item] = quantity.to_i print_list(list) end def remove_item(list, item) list.delete(item) print_list(list) end def update_quantity(list, item, quantity) list.each { |existing_item, existing_quantity| existing_item == item ? list[existing_item] = quantity : list[existing_item] = existing_quantity } print_list(list) end def print_list(list) puts "Shopping List" list.each do |item, quantity| puts "#{item.upcase} - #{quantity}" end end # TEST CODE - CREATE LIST # items = "apple orange milk eggs" # list = create_list(items) # p list == {"apple" => 1, "orange"=> 1, "milk" => 1, "eggs" => 1} # TEST CODE - ADD ITEM TO LIST # p list == {"apple" => 1, "orange"=> 1, "milk" => 1, "eggs" => 1, "butter" => 4} # TEST CODE - REMOVE ITEM FROM LIST # remove_item(list, "orange") # p list == {"apple" => 1, "milk" => 1, "eggs" => 1, "butter" => 4} # TEST CODE - UPDATE LIST # update_quantity(list, "apple", 3) # p list == {"apple" => 3, "milk" => 1, "eggs" => 1, "butter" => 4} # 4. Convert your driver test code from that challenge into Assert Statements: # Feature List: # - Create a new list # - Add an item with a quantity to the list # - Remove an item from the list # - Update quantities for items in your list # - Print the list items = "apple orange milk eggs" list = create_list(items) def display (message) puts "*" * 50 puts message end def display_error (actual, expected) "[ERROR] expected #{expected} but got #{actual}" end def assert (actual, expected, message) display message puts actual == expected || display_error(actual, expected) end def assert_create (actual, expected, message) assert actual, expected, message puts "*" * 50 end def assert_add (actual, expected, message) assert actual, expected, message puts "*" * 50 end def assert_remove(actual, expected, message) assert actual, expected, message puts "*" * 50 end def assert_update(actual, expected, message) assert actual, expected, message puts "*" * 50 end def assert_print(actual, expected, message) assert actual, expected, message puts "*" * 50 end assert_create(list, create_list(items), "user can create a list of grocery items") assert_add(list, add_item(list, 'butter', 4), "user can add an item to their grocery list") assert_remove(list, remove_item(list, 'apple'), "user can remove an item from their grocery list") assert_update(list, update_quantity(list, 'orange', 5), "user can update the quantity of an item on their list") assert_update(list, print_list(list), "user can print the list to the console") # 5. Reflection: # What concepts did you review in this challenge? # This challenge was a good review of how to write methods and pass information between methods. # What is still confusing to you about Ruby? # Because of the nature of the challenge I used to create my assert statements (I used our first Ruby GPS - Make a Grocery List), makign the assert statements was a bit difficult. In the example video, the instructor was using a class, with attribute and instance methods which seemed a bit more straightforward. # What are you going to study to get more prepared for Phase 1? # I'm definitely going to do keep looking into how to create assert methods because I'm not entirely sure I've created them correctly in this assignment.
require 'rails_helper' describe "get all parks route", :type => :request do let!(:parks) { FactoryBot.create_list(:park, 3)} before { get '/parks'} it 'returns all parks' do expect(JSON.parse(response.body).size).to eq(3) end it 'returns status code 200' do expect(response).to have_http_status(:success) end end describe "get park id:1", :type => :request do let!(:park) { FactoryBot.create(:park, area: 'test_area', description: 'test_description', state: 'test_state', name: 'test_name', id: 1) } before { get '/parks/1' } it 'returns the area of the park' do expect(JSON.parse(response.body)['area']).to eq('test_area') end it 'returns the park description' do expect(JSON.parse(response.body)['description']).to eq('test_description') end it 'returns the state' do expect(JSON.parse(response.body)['state']).to eq('test_state') end it 'returns the park name' do expect(JSON.parse(response.body)['name']).to eq('test_name') end it 'returns status code 200' do expect(response).to have_http_status(:success) end end describe "returns first 10 parks", :type => :request do let!(:parks) { FactoryBot.create_list(:park, 20)} before { get '/parks?page=1'} it 'returns 10 parks' do expect(JSON.parse(response.body).size).to eq(10) end it 'returns status code 200' do expect(response).to have_http_status(:success) end end describe "get park id:2", :type => :request do let!(:park) { FactoryBot.create(:park, area: 'test_area', description: 'test_description', state: 'test_state', name: 'test_name', id: 1) } before { get '/parks/2' } it 'returns status code 404' do expect(response).to have_http_status(:not_found) end end
class Controller < ApplicationRecord validates :name, presence: true has_many :controller_methods end
# == Schema Information # # Table name: checkins # # id :integer not null, primary key # enrollment_id :integer # problem :text # github_repository :string # time_cost :integer # degree_of_difficulty :integer # lesson_id :integer # discourse_post_id :integer # timestamps :datetime # class Checkin < ActiveRecord::Base belongs_to :enrollment belongs_to :lesson validates :lesson_id, presence: true before_save do if self.github_repository.nil? self.github_repository = project_repo_url end end after_commit do |checkin| PublishTopicJob.perform_later(checkin) end def self.checkin?(enroll, temp_lesson) return false unless (enroll && temp_lesson) enroll.checkins.any? do |checkin| temp_lesson.id == checkin.lesson_id end end def publish discourse_poster.publish end def published? !self.discourse_post_id.nil? end def github_repository_name return nil if github_repository.nil? URI.parse(github_repository).path[1..-1] end def project_repo_url return nil if lesson.project.blank? # <github-username>/besike-<course-name>-<project-name> lesson.project_repo_url_for(enrollment.user) end def discourse_poster @discourse_poster ||= Checkin::DiscoursePoster.new(self) end end
describe ::PPC::API::Qihu::Group do auth = $qihu_auth test_plan_id = ::PPC::API::Qihu::Plan::ids( auth )[:result][0].to_i test_group_id = 0 it 'can add a group' do group = { plan_id:test_plan_id, name:'testGroup', price:999} response = ::PPC::API::Qihu::Group::add( auth, group) is_success(response) test_group_id = response[:result][0][:id] end it 'can update a group' do group = { id: test_group_id, price:990} response = ::PPC::API::Qihu::Group::update( auth, group ) is_success(response) end it 'can get a group' do response = ::PPC::API::Qihu::Group::get( auth, test_group_id ) is_success( response ) end it 'can search id by plan id ' do response = ::PPC::API::Qihu::Group::search_id_by_plan_id( auth, test_plan_id ) is_success( response ) end it 'can search by plan id ' do response = ::PPC::API::Qihu::Group::search_by_plan_id( auth, test_plan_id ) is_success( response ) end it 'can delete a group' do response = ::PPC::API::Qihu::Group::delete( auth, test_group_id) is_success( response ) end end
# frozen_string_literal: true class UserSerializer < ActiveModel::Serializer attributes :id, :uid, :email, :nickname, :avatar_thumb_url, :avatar_medium_url def avatar_thumb_url object.avatar.url(:thumb) end def avatar_medium_url object.avatar.url(:medium) end end
class Standard < ApplicationRecord def self.expired_in(timestamp) where("expires_at <= ?", timestamp) end end
# frozen_string_literal: true if System::Database.mysql? # This is for Rails 4, I do not know if it is needed ActiveRecord::ConnectionAdapters::Mysql2Adapter::NATIVE_DATABASE_TYPES[:primary_key] = "BIGINT(20) auto_increment PRIMARY KEY" # Works in rails 5 ActiveRecord::ConnectionAdapters::MySQL::TableDefinition.prepend(Module.new do def new_column_definition(name, type, options) column = super if type == :primary_key column.type = :bigint column.unsigned = false column.auto_increment = true end column end end) end
class PokemonsController < ApplicationController def index pokemons = Pokemon.all render json: pokemons end def create api_pokemon = PokemonApi::Adapter.new.random_pokemon pokemon = Pokemon.create_from_api(api_pokemon, params[:lat], params[:lng]) if pokemon.valid? render json: pokemon, status: :created else render json: { errors: pokemon.errors.full_messages }, status: :bad_request end end end
require 'rails_helper' RSpec.describe ModelTypesController, type: :controller do describe "GET models/:model_slug/model_types" do let(:organisation) { create(:organisation)} let(:model){create(:model,organisation_id: organisation.id)} let(:model_type){create(:model_tyep,model_id: model_id)} it "responds successfully with an HTTP 200 status code" do get :index, {model_slug: model.model_slug} expect(response).to be_success expect(response).to have_http_status(200) end it "responds with error json if model is not present" do get :index, {model_slug: "dummy slug"} expect(response).to have_http_status(404) end end end
class CreateDatosUsers < ActiveRecord::Migration def change create_table :datos_users do |t| t.text :nombre, null: false t.text :email t.text :telefono t.text :pref, null: false t.text :localidad, null: false t.timestamps null: false end end end
lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'indoctrinatr/tools/version' Gem::Specification.new do |spec| spec.name = 'indoctrinatr-tools' spec.version = Indoctrinatr::Tools::VERSION spec.authors = ['Nicolai Reuschling', 'Eike Henrich'] spec.email = ['nicolai.reuschling@dkd.de', 'eike.henrich@dkd.de'] spec.summary = 'indoctrinatr-tools provides a set of command line tools for Indoctrinatr (an Open Source Software project by dkd Internet Service GmbH, Frankfurt am Main, Germany).' spec.homepage = 'https://github.com/dkd/indoctrinatr' spec.license = 'MIT' spec.required_ruby_version = '~> 3.1' spec.files = Dir.chdir(File.expand_path(__dir__)) do `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } end spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] spec.add_development_dependency 'aruba', '~> 2.1' spec.add_development_dependency 'bundler', '~> 2.0' spec.add_development_dependency 'cucumber', '~> 8.0' spec.add_development_dependency 'rake', '~> 13.0' spec.add_development_dependency 'rspec', '~> 3.10' spec.add_development_dependency 'rubocop', '~> 1.0' spec.add_development_dependency 'rubocop-performance', '~> 1.10' spec.add_development_dependency 'rubocop-rspec', '~> 2.0' spec.add_development_dependency 'simplecov', '~> 0.21' spec.add_dependency 'dry-cli', '~> 1.0' spec.add_dependency 'dry-transaction', '~> 0.13' spec.add_dependency 'erubis', '~> 2.7' spec.add_dependency 'RedCloth', '~> 4.3' spec.add_dependency 'rubyzip', '~> 2' spec.add_dependency 'to_latex', '~> 0.5' spec.add_dependency 'zeitwerk', '~> 2.6' spec.requirements << 'LaTeX development enviroment' spec.metadata['rubygems_mfa_required'] = 'true' end
# encoding: utf-8 # copyright: 2016, you # license: All rights reserved # date: 2016-09-16 # description: The Microsoft Internet Explorer 11 Security Technical Implementation Guide (STIG) is published as a tool to improve the security of Department of Defense (DoD) information systems. Comments or proposed revisions to this document should be sent via e-mail to the following address: disa.stig_spt@mail.mil # impacts title 'V-46513 - Launching programs and files in IFRAME must be disallowed (Internet zone).' control 'V-46513' do impact 0.5 title 'Launching programs and files in IFRAME must be disallowed (Internet zone).' desc 'This policy setting allows you to manage whether applications may be run and files may be downloaded from an IFRAME reference in the HTML of the pages in this zone. Launching of programs in IFRAME must have a level of protection based upon the site being accessed. If you enable this policy setting, applications can run and files can be downloaded from IFRAMEs on the pages in this zone without user intervention. If you disable this setting, users are prevented from running applications and downloading files from IFRAMEs on the pages in this zone.' tag 'stig', 'V-46513' tag severity: 'medium' tag checkid: 'C-49703r2_chk' tag fixid: 'F-50303r1_fix' tag version: 'DTBI038-IE11' tag ruleid: 'SV-59377r1_rule' tag fixtext: 'Set the policy value for Computer Configuration -> Administrative Templates -> Windows Components -> Internet Explorer -> Internet Control Panel -> Security Page -> Internet Zone -> Launching applications and files in an IFRAME to Enabled, and select Disable from the drop-down box. ' tag checktext: 'The policy value for Computer Configuration -> Administrative Templates -> Windows Components -> Internet Explorer -> Internet Control Panel -> Security Page -> Internet Zone -> Launching applications and files in an IFRAME must be Enabled, and Disable selected from the drop-down box. Procedure: Use the Windows Registry Editor to navigate to the following key: HKLM\Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3 Criteria: If the value "1804" is REG_DWORD = 3, this is not a finding.' # START_DESCRIBE V-46513 describe registry_key({ hive: 'HKLM', key: 'Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3', }) do its('1804') { should eq 3 } end # STOP_DESCRIBE V-46513 end
class Notifyr < Cask url 'http://getnotifyr.com/app/Notifyr.zip' homepage 'http://getnotifyr.com' version 'latest' sha256 :no_check prefpane 'Notifyr.prefPane' end
# -*- mode: ruby -*- # vi: set ft=ruby : VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "ubuntu/trusty64" config.vm.network :forwarded_port, guest: 8080, host: 8080 config.vm.network :forwarded_port, guest: 8022, host: 8022 config.vm.network :private_network, ip: "192.168.10.2" # for NFS config.vm.synced_folder ".", "/vagrant", :nfs => true config.vm.provision :docker do |d| d.pull_images "pomin5/drupal7-nginx" d.run "drupal7_app", image: "pomin5/drupal7-nginx", args: "-p 8080:80 -p 8022:22 -p 8020:20 -p 8021:21 \\ -e ENABLE_FTP=1 \\ -e ENABLE_MY_KEY=1 \\ -v /vagrant/sites:/var/www/sites \\ -v /vagrant/.run/log:/var/log" end end
module SemanticNavigation module Core module MixIn module ConditionMethods def has_active_children? sub_elements.map(&:active).any? end end end end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'cocoapods-x/gem_version.rb' Gem::Specification.new do |spec| spec.name = 'cocoapods-x' spec.version = CocoapodsX::VERSION spec.authors = ['panghu'] spec.email = ['panghu.lee@gmail.com'] spec.description = %q{扩展pod x命令, 实现快速清理缓存, 快速打开Xcode等操作, 使用souce, pods两个dsl实现快速切换pod 'NAME', :path=>'url'开发模式, 对壳工程无入侵.} spec.summary = %q{扩展pod x命令, 实现快速清理缓存, 快速打开Xcode等操作, 使用souce, pods两个dsl实现快速切换pod 'NAME', :path=>'url'开发模式, 对壳工程无入侵.} spec.homepage = 'https://github.com/CocoapodsX/cocoapods-x' spec.license = 'MIT' spec.files = Dir["lib/**/*.rb"] + %w{ README.md LICENSE } spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ['lib'] spec.add_development_dependency 'bundler', '~> 1.3' spec.add_development_dependency 'rake' end
module Refinery module Fg class Profession < Refinery::Core::BaseModel attr_accessible :name, :open_at, :content, :recommend, :opened, :position acts_as_indexed :fields => [:name, :content, :open_at] validates :name, :presence => true, :uniqueness => true end end end
# frozen_string_literal: true FactoryBot.define do factory :user do email { Faker::Internet.email } password { Faker::Internet.password } first_name { Faker::Name.first_name } last_name { Faker::Name.last_name } phone_number { %w[0606060606 +33606060606].sample } city { create(:city) } is_admin { false } factory :user_empty_email do email { '' } end factory :user_bad_email do email { 'sdf' } end factory :user_empty_password do password { '' } end factory :user_bad_password do password { 'sdf' } end factory :user_empty_phone do phone_number { '' } end factory :user_bad_phone do phone_number { '0606' } end factory :user_empty_city do city {} end factory :user_admin do is_admin { true } end end end
require 'csv' class LoadLatLongJob < ApplicationJob queue_as :default def perform csv_options = { col_sep: ',', quote_char: '"', headers: :first_row } filepath = 'db/accountantlatlong.csv' CSV.foreach(filepath, csv_options) do |row| Accountant.find(row['id']).update!(latitude: row["latitude"], longitude: row["longitude"]) end end end # Run: # rails c # LoadLatLongJob.perform_now
require "test_helper" describe WorksController do it "should get index" do get works_path must_respond_with :success end describe "show" do it "should be OK to show an existing, valid work" do valid_work_id = works(:one).id get work_path(valid_work_id) must_respond_with :success end it "should flash instead of showing a non-existant, invalid book" do work = works(:one) invalid_work_id = work.id work.destroy get work_path(invalid_work_id) must_respond_with :redirect expect(flash[:error]).must_equal "Unknown work!" end end describe "create" do it "will save a new work and redirect if given valid input" do test_input = { work: { category: "movie", title: "test movie", creator: "test angela", publication_year: 1999, description: "test description", }, } expect { post works_path, params: test_input }.must_change "Work.count", 1 new_work = Work.find_by(title: test_input[:work][:title]) expect(new_work).wont_be_nil expect(new_work.title).must_equal test_input[:work][:title] expect(new_work.category).must_equal test_input[:work][:category] expect(new_work.creator).must_equal test_input[:work][:creator] expect(new_work.publication_year).must_equal test_input[:work][:publication_year] expect(new_work.description).must_equal test_input[:work][:description] expect(flash[:success]).must_equal "Work added successfully!" end it "should flash and return a 400 with an invalid work" do test_input = { work: { category: "movie", title: "", creator: "test angela", publication_year: 1999, description: "test description", }, } expect { post works_path, params: test_input }.wont_change "Work.count" expect(flash[:title]).must_equal ["can't be blank"] must_respond_with :bad_request end end describe "update" do it "will update an existing work" do work_to_update = works(:one) updates = { work: { title: "changed title", }, } expect { patch work_path(work_to_update.id), params: updates }.wont_change "Work.count" must_respond_with :redirect work_to_update.reload expect(work_to_update.title).must_equal "changed title" expect(flash[:success]).must_equal "Work updated successfully!" end it "should flash and return a 400 with an invalid updates" do work_to_update = works(:one) updates = { work: { title: "", }, } expect { patch work_path(work_to_update.id), params: updates }.wont_change "Work.count" must_respond_with :bad_request expect(work_to_update.title).wont_equal "" expect(flash[:title]).must_equal ["can't be blank"] end end describe "destroy" do it "shows a flash message if work is not found" do invalid_id = "NOT A VALID ID" expect { delete work_path(invalid_id) }.wont_change "Work.count" expect(flash[:error]).must_equal "Work already does not exist." must_respond_with :redirect end it "can delete a work" do delete_work = works(:two) expect { delete work_path(delete_work.id) }.must_change "Work.count", -1 must_redirect_to works_path end end describe "vote" do it "allows a user to make a vote" do perform_login voting_work = Work.create(category: "book", title: "test book", creator: "me", vote_count: 0) expect { post vote_path(voting_work.id) }.must_change "Vote.count", 1 expect(flash[:success]).must_equal "Work updated successfully!" end it "allows a user vote on multiple works" do perform_login voting_work_one = Work.create(category: "book", title: "test book", creator: "me", vote_count: 0) voting_work_two = Work.create(category: "album", title: "test album", creator: "me", vote_count: 0) expect { post vote_path(voting_work_one.id) }.must_change "Vote.count", 1 expect { post vote_path(voting_work_two.id) }.must_change "Vote.count", 1 expect(flash[:success]).must_equal "Work updated successfully!" end it "does not allow users to vote on work more than once" do perform_login voting_work = Work.create(category: "book", title: "test book", creator: "me", vote_count: 0) post vote_path(voting_work.id) expect { post vote_path(voting_work.id) }.wont_change "Vote.count" end it "does not allow user to vote if not logged in" do voting_work = Work.create(category: "book", title: "test book", creator: "me", vote_count: 0) expect { post vote_path(voting_work.id) }.wont_change "Vote.count" expect(flash[:error]).must_equal "You must be logged in to vote!" end it "flashes an error and redirects if work is no longer valid" do invalid_id = "INVALID ID" post vote_path(invalid_id) expect(flash[:error]).must_equal "Work no longer exists!" must_redirect_to works_path end end end
require 'spec_helper' require 'sem_ver' describe Magnum::Cli do context 'when requesting the version number' do subject(:version) { Magnum::VERSION } it { expect(version).to_not be_nil } it { expect(SemVer.parse(version).valid?).to be_truthy } end context 'when printing version' do subject(:cli) { Magnum::Cli.new } it { expect(cli).to be } it { expect(cli.version.to_s).to be } end end
class EditPartsComponents < ActiveRecord::Migration def change change_column :components, :parts, :integer, default: 1 end end
Rails.application.routes.draw do root to: 'homepage#index' resources :users, only: [:new, :create] resources :transactions, only: [:index, :create] do collection do get :withdraw get :pay end end end
class AddColumnAlAndClToLeaveRecords < ActiveRecord::Migration[5.2] def change add_column :leave_records, :al, :boolean add_column :leave_records, :cl, :boolean end end
[User].each do |klass| ActiveAdmin.register klass do menu parent: Rockauth::Configuration.active_admin_menu_name controller do helper_method :attribute_list def attribute_list (klass.attribute_names.map(&:to_sym) - %i(id password_digest created_at updated_at)) end end permit_params do (attribute_list + %i(password)) end index do id_column ((attribute_list & %i(email)) + %i(created_at)).each do |key| column key end actions end show do attributes_table do (attribute_list + %i{created_at updated_at}).each do |key| row key end end panel "Authentications" do table_for resource.authentications do column :id do |r| link_to r.id, admin_user_path(r) end column :auth_type column :client column :device_os column :expiration do |r| Time.at(r.expiration).to_formatted_s(:rfc822) if r.expiration.present? end column :issued_at do |r| Time.at(r.issued_at).to_formatted_s(:rfc822) if r.issued_at.present? end column do |r| text_node link_to('View', admin_authentication_path(r), class: 'member_link') text_node link_to('Destroy', admin_authentication_path(r), method: :delete, data: { confirm: 'Are you sure?' }, class: 'member_link') end end end panel "Provider Authentications (social authorizations)" do table_for resource.provider_authentications do column :id do |r| link_to r.id # link_to r.id, [:admin, r] end column :provider column :provider_user_id column :created_at column do |r| text_node link_to('View', admin_provider_authentication_path(r), class: 'member_link') text_node link_to('Destroy', admin_provider_authentication_path(r), method: :delete, data: { confirm: 'Are you sure?' }, class: 'member_link') end end end active_admin_comments end form do |f| f.semantic_errors f.inputs (attribute_list + %i(password)) f.actions end end end
require 'spec_helper' describe Rdf::VocabImportJob, dbscope: :example do let(:site) { cms_site } let(:class_list) { Rails.root.join("spec", "fixtures", "rdf", "class_list.txt") } let(:property_list) { Rails.root.join("spec", "fixtures", "rdf", "property_list.txt") } context "when IPA Core Vocab ttl is given" do let(:prefix) { "ic" } let(:file) { Rails.root.join("db", "seeds", "opendata", "rdf", "ipa-core.ttl") } it "import from IPA Core Vocab ttl" do described_class.new.call(site.host, prefix, file, Rdf::Vocab::OWNER_SYSTEM, 1000) expect(Rdf::Vocab.count).to eq 1 vocab = Rdf::Vocab.first expect(Rdf::Class.count).to be > 0 open(class_list) do |file| file.each do |line| line.chomp! name = line.gsub(vocab.uri, '') rdf_object = Rdf::Class.where(vocab_id: vocab.id).where(name: name).first expect(rdf_object).not_to be_nil end end open(property_list) do |file| file.each do |line| name, type, comment = line.chomp!.split("\t") break if name.blank? rdf_object = Rdf::Prop.where(vocab_id: vocab.id).where(name: name).first expect(rdf_object).not_to be_nil end end end end context "when IPA Core Vocab xml is given" do let(:prefix) { "ic" } let(:file) { Rails.root.join("spec", "fixtures", "rdf", "rdf.xml") } xit "import from IPA Core Vocab xml" do described_class.new.call(site.host, prefix, file, Rdf::Vocab::OWNER_SYSTEM, 1000) expect(Rdf::Vocab.count).to eq 1 expect(Rdf::Class.count).to be > 0 expect(Rdf::Prop.count).to be > 0 end end context "when XMLSchema ttl is given" do let(:prefix) { "xsd" } let(:file) { Rails.root.join("db", "seeds", "opendata", "rdf", "xsd.ttl") } xit "import from XMLSchema ttl" do described_class.new.call(site.host, prefix, file, Rdf::Vocab::OWNER_SYSTEM, 1000) expect(Rdf::Vocab.count).to eq 1 expect(Rdf::Class.count).to be > 0 expect(Rdf::Prop.count).to eq 0 end end context "when Dublin Core Term ttl is given" do let(:prefix) { "dc" } let(:file) { Rails.root.join("db", "seeds", "opendata", "rdf", "dcterms.ttl") } xit "import from Dublin Core Term ttl" do described_class.new.call(site.host, prefix, file, Rdf::Vocab::OWNER_SYSTEM, 1000) expect(Rdf::Vocab.count).to eq 1 expect(Rdf::Class.count).to be > 0 expect(Rdf::Prop.count).to be > 0 end end context "when Friend of a Friend rdf is given" do let(:prefix) { "foaf" } let(:file) { Rails.root.join("spec", "fixtures", "rdf", "foaf.rdf.xml") } xit "import from Friend of a Friend rdf" do described_class.new.call(site.host, prefix, file, Rdf::Vocab::OWNER_SYSTEM, 1000) expect(Rdf::Vocab.count).to eq 1 expect(Rdf::Class.count).to be > 0 expect(Rdf::Prop.count).to be > 0 end xit do graph = RDF::Graph.load(file, format: :rdfxml) puts "== dump ==" graph.each do |statement| puts statement.inspect end end end context "when DBpedia Ontology rdf is given" do let(:prefix) { "dbpont" } let(:file) { Rails.root.join("spec", "fixtures", "rdf", "dbpedia_2014.owl.xml") } xit "import from DBpedia Ontology rdf" do described_class.new.call(site.host, prefix, file, Rdf::Vocab::OWNER_SYSTEM, 1000) expect(Rdf::Vocab.count).to eq 1 expect(Rdf::Class.count).to be > 0 expect(Rdf::Prop.count).to be > 0 end xit do graph = RDF::Graph.load(file, format: :rdfxml) puts "== dump ==" graph.each do |statement| puts statement.inspect end end end context "when WGS84 Geo Positioning is given" do let(:prefix) { "geo" } let(:file) { Rails.root.join("spec", "fixtures", "rdf", "wgs84_pos.xml") } xit "import from WGS84 Geo Positioning" do described_class.new.call(site.host, prefix, file, Rdf::Vocab::OWNER_SYSTEM, 1000) expect(Rdf::Vocab.count).to eq 1 expect(Rdf::Class.count).to be > 0 expect(Rdf::Prop.count).to be > 0 end xit do graph = RDF::Graph.load(file, format: :rdfxml) puts "== dump ==" graph.each do |statement| puts statement.inspect end end end end
class Project attr_reader :name, :user @@all = [] def initialize (name, user) @name = name @user = user @@all << self end def self.all @@all end def self.no_pledges self.all-Pledge.all.map{|pledge|pledge.project}.uniq #subtracting the projects with an array of all the pledges #all individual/uniq end # def self.above_goal # end def backers Pledge.all.select{|pledge|pledge.project == self} end def self.most_backers most_backed_num = 0 most_backed = nil self.all.each do |project| if project.backers.length > most_backed_num most_backed_num = project.backers.length most_backed = project end end most_backed end end
Rails.application.routes.draw do get 'rooms/index' devise_for :users root to: 'pages#home' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html resources :motels, only: [:show, :index] do resources :rooms, only: [:show, :index] end resources :bookings, only: [:index] end
def hashketball = { :home => { :team_name => "Monstars", :colors => ["black", "green"], :players => { "Pound" => { :number => 99, :shoe_size => 10, :stats => { :points => 40, :rebounds => 11, :assists => 12, :steals => 8, :blocks => 9, :slam_dunks => 6 } }, "Bupkus" => { :number => 95, :shoe_size => 11, :stats => { :points => 32, :rebounds => 16, :assists => 8, :steals => 12, :blocks => 15, :slam_dunks => 8 } }, "Bang" => { :number => 93, :shoe_size => 12, :stats => { :points => 24, :rebounds => 9, :assists => 13, :steals => 10, :blocks => 6, :slam_dunks => 3 } }, "Blanko" => { :number => 88, :shoe_size => 14, :stats => { :points => 10, :rebounds => 12, :assists => 8, :steals => 6, :blocks => 4, :slam_dunks => 0 } }, "Nawt" => { :number => 85, :shoe_size => 13, :stats => { :points => 18, :rebounds => 4, :assists => 10, :steals => 3, :blocks => 9, :slam_dunks => 7 } }, }, }, :away => { :team_name => "Toon Squad", :colors => ["white", "blue"], :players => { "Bugs" => { :number => 1, :shoe_size => 10, :stats => { :points => 30, :rebounds => 13, :assists => 10, :steals => 10, :blocks => 8, :slam_dunks => 5 } }, "Babs" => { :number => 3, :shoe_size => 6, :stats => { :points => 22, :rebounds => 13, :assists => 8, :steals => 10, :blocks => 12, :slam_dunks => 3 } }, "Taz" => { :number => 5, :shoe_size => 5, :stats => { :points => 28, :rebounds => 7, :assists => 15, :steals => 4, :blocks => 8, :slam_dunks => 0 } }, "Daffy" => { :number => 7, :shoe_size => 15, :stats => { :points => 14, :rebounds => 12, :assists => 8, :steals => 6, :blocks => 10, :slam_dunks => 3 } }, "Jordan" => { :number => 23, :shoe_size => 12, :stats => { :points => 40, :rebounds => 8, :assists => 4, :steals => 12, :blocks => 10, :slam_dunks => 12 } }, }, } } # Using the power of Ruby, and the Hashes you created above, answer the following questions: # Return the number of points scored for any player: def points_per_player(player, hashketball) player.capitalize! if hashketball[:home][:players].include?(player) hashketball[:home][:players][player][:stats][:points] elsif hashketball[:away][:players].include?(player) hashketball[:away][:players][player][:stats][:points] else "No player found." end end puts points_per_player("blanko", hashketball) # # Return the shoe size for any player: def player_shoe_size(player, hashketball) player.capitalize! if hashketball[:home][:players].include?(player) hashketball[:home][:players][player][:shoe_size] elsif hashketball[:away][:players].include?(player) hashketball[:away][:players][player][:shoe_size] else "No player found." end end puts player_shoe_size("taz", hashketball) # # Return both colors for any team: def team_colors(team, hashketball) sym = team.to_sym if hashketball.include?(sym) hashketball[sym][:colors] else "Try home or away." end end puts team_colors("away", hashketball) # # Return both teams names: def team_names(hashketball) puts "The #{hashketball[:home][:team_name]} welcome the #{hashketball[:away][:team_name]}" puts end puts team_names(hashketball) # # Return all the player numbers for a team: def player_nums(team, hashketball) sym = team.to_sym player_numbers = [] hashketball[sym][:players].each_value do |x| player_numbers << x[:number] end player_numbers end puts player_nums("away", hashketball) # Return all the stats for a player: def player_stats(player_name, hashketball) player_name.capitalize! if hashketball[:home][:players].include?(player_name) hashketball[:home][:players][player_name][:stats] elsif hashketball[:away][:players].include?(player_name) hashketball[:away][:players][player_name][:stats] else "No player found." end end puts player_stats("Daffy", hashketball) # # Return the rebounds for the player with the largest shoe size def biggest_shoe(hashketball) player_number_with_biggest_shoe = "" biggest_shoe_size = 0 hashketball[:home][:players].each do |name, player| if player[:shoe_size] > biggest_shoe_size player_number_with_biggest_shoe = name biggest_shoe_size = player[:shoe_size] end end hashketball[:away][:players].each do |name, player| if player[:shoe_size] > biggest_shoe_size player_number_with_biggest_shoe = name biggest_shoe_size = player[:shoe_size] end end " #{player_number_with_biggest_shoe} : #{biggest_shoe_size} " end
require_relative "../test_helper" class RobotWorldTest < Minitest::Test include TestHelpers def test_can_we_create_a_robot create_robot id = id_helper(1) robot = robot_world.find(id) assert_equal "Robo 1", robot.name assert_equal "Los Angeles 1", robot.city assert_equal "California 1", robot.state assert_equal "1991-4-7", robot.birthdate assert_equal "2011-4-7", robot.date_hired assert_equal "Computer Lab 1", robot.department end def test_we_can_list_all_the_robots create_robot assert_equal 2, robot_world.all.count id_1 = id_helper(1) id_2 = id_helper(2) robot1 = robot_world.find(id_1) robot2 = robot_world.find(id_2) assert_equal "Robo 1", robot1.name assert_equal "Robo 2", robot2.name end def test_we_can_update_a_robot create_robot assert_equal 2, robot_world.all.count id = id_helper(1) robot = robot_world.find(id) assert_equal "Robo 1", robot.name assert_equal "Los Angeles 1", robot.city assert_equal "California 1", robot.state robot_world.update(id, { name: "Bender", city: "Astral 9-ipz", state: "non changing" }) robot = robot_world.find(id) assert_equal "Bender", robot.name assert_equal "Astral 9-ipz", robot.city assert_equal "non changing", robot.state end def test_we_can_find_by_id create_robot(3) id_1 = id_helper(1) id_2 = id_helper(2) id_3 = id_helper(3) robo1 = robot_world.find(id_1) robo2 = robot_world.find(id_2) robo3 = robot_world.find(id_3) assert_equal "Robo 1", robo1.name assert_equal "Robo 2", robo2.name assert_equal "Robo 3", robo3.name end def test_we_can_delete_by_id create_robot(4) assert robot_world.all.any? {|robot| robot.name == 'Robo 1'} id = id_helper(1) robot_world.delete(id) refute robot_world.all.any? {|robot| robot.name == 'Robo 1'} end def test_can_find_robots_by_name_fragment create_robot robots = robot_world.find_by_name('rOb') assert_equal 2, robots.count assert_equal "Robo 1", robots[0].name assert_equal "Robo 2", robots[1].name end def test_average_age create_robot assert_equal 24.5, robot_world.average_age end def test_hirings_by_year create_robot assert_equal({2011=>1, 2012=>1}, robot_world.hired_by_year) end def test_robots_per_dept create_robot assert_equal({"Computer Lab 1"=>1, "Computer Lab 2"=>1}, robot_world.robots_per_dept) end def test_robots_per_city create_robot assert_equal({"Los Angeles 1"=>1, "Los Angeles 2"=>1}, robot_world.robots_per_city) end def test_robots_per_state create_robot assert_equal({"California 1"=>1, "California 2"=>1},robot_world.robots_per_state) end end
## This patch is from rails 4.2-stable. Remove it when 4.2.6 is released ## https://github.com/rails/rails/issues/21108 module ActiveRecord module ConnectionAdapters class AbstractMysqlAdapter < AbstractAdapter # SHOW VARIABLES LIKE 'name' def show_variable(name) variables = select_all("select @@#{name} as 'Value'", 'SCHEMA') variables.first['Value'] unless variables.empty? rescue ActiveRecord::StatementInvalid nil end # MySQL is too stupid to create a temporary table for use subquery, so we have # to give it some prompting in the form of a subsubquery. Ugh! def subquery_for(key, select) subsubselect = select.clone subsubselect.projections = [key] subselect = Arel::SelectManager.new(select.engine) subselect.project Arel.sql(key.name) # Materialized subquery by adding distinct # to work with MySQL 5.7.6 which sets optimizer_switch='derived_merge=on' subselect.from subsubselect.distinct.as('__active_record_temp') end end end end module ActiveRecord module ConnectionAdapters class MysqlAdapter < AbstractMysqlAdapter ADAPTER_NAME = 'MySQL'.freeze # Get the client encoding for this database def client_encoding return @client_encoding if @client_encoding result = exec_query( "select @@character_set_client", 'SCHEMA') @client_encoding = ENCODINGS[result.rows.last.last] end end end end
require 'rails_helper' describe RegistrationsController, type: :controller do render_views before do @request.env["devise.mapping"] = Devise.mappings[:admin] end it "should redirect to home when trying to register a new admin" do get :new expect(response).to have_http_status :redirect end it "should redirect to home when trying to create a new admin" do post :create expect(response).to have_http_status :redirect end end
# frozen_string_literal: true class Page include Mongoid::Document include Mongoid::Timestamps include Mongoid::Publishable field :url, type: String embedded_in :pageable, polymorphic: true has_mongoid_attached_file :image end
require 'byebug' class Maze attr_reader :maze_array def initialize(maze_file) #open maze file @maze = File.read(maze_file) restart_maze end def restart_maze #convert to array @maze_array = @maze.split("\n").map {|string| string.split("")} #determine starting position find_position #sets current position to starting location @current_position = @starting_position @previous_position = @starting_position set_current_position end def find_position #finds current position by iterating through the maze array @starting_position ||= [0, 0] @steps_taken = 0 @maze_array.each_with_index do |row, row_num| row.each_with_index do |space, col_num| @starting_position = [row_num, col_num] if space == "S" @steps_taken += 1 if space == "X" end end end def steps find_position return @steps_taken end def find_exit #explores until exit is found while true explore break if near_exit? end end def compass #determines the direction you are moving in return nil unless @previous_position return nil if @previous_position == @current_position return "North" if @previous_position == [@y+1, @x] return "South" if @previous_position == [@y-1, @x] return "West" if @previous_position == [@y, @x+1] return "East" if @previous_position == [@y, @x-1] end def set_current_position #sets global @x & @y variables to the current position @x = @current_position[1] @y = @current_position[0] end def mark_current_position(coordinates) @previous_position = @current_position @current_position = [coordinates[0], coordinates[1]] set_current_position @maze_array[@y][@x] = "X" end def print_maze #print current maze array @maze_array.each {|row| puts row.join("")} end def near_exit? return true if @maze_array[@y+1][@x] == "E" return true if @maze_array[@y-1][@x] == "E" return true if @maze_array[@y][@x+1] == "E" return true if @maze_array[@y][@x-1] == "E" return false byebug end #checks if you are stuck def stuck? north = (@maze_array[@y-1][@x] == " ") south = (@maze_array[@y+1][@x] == " ") east = (@maze_array[@y][@x+1] == " ") west = (@maze_array[@y][@x-1] == " ") return false if near_exit? return true unless north || south || east || west false end #methods for exploring the cardinal directions def explore_north if @maze_array[@y-1][@x] == " " && !near_exit? mark_current_position([@y-1, @x]) end end def explore_south if @maze_array[@y+1][@x] == " " && !near_exit? mark_current_position([@y+1, @x]) end end def explore_west if @maze_array[@y][@x-1] == " " && !near_exit? mark_current_position([@y, @x-1]) end end def explore_east if @maze_array[@y][@x+1] == " " && !near_exit? mark_current_position([@y, @x+1]) end end #method for optimal exploration of a maze by turning to the leftmost open route def explore direction = compass temp_position = @current_position if direction == nil explore_north elsif direction == "North" explore_west explore_north if temp_position == @current_position explore_east if temp_position == @current_position explore_south if temp_position == @current_position elsif direction == "West" explore_south explore_west if temp_position == @current_position explore_north if temp_position == @current_position explore_east if temp_position == @current_position elsif direction == "South" explore_east explore_south if temp_position == @current_position explore_west if temp_position == @current_position explore_north if temp_position == @current_position elsif direction == "East" explore_north explore_east if temp_position == @current_position explore_south if temp_position == @current_position explore_west if temp_position == @current_position end end def explore_randomly until near_exit? direction = ["North","South","East","West"].sample distance = (0..20).to_a.sample if direction == "North" distance.times {explore_north} elsif direction == "East" distance.times {explore_east} elsif direction == "South" distance.times {explore_south} elsif direction == "West" distance.times {explore_west} end #restarts if stuck restart_maze if stuck? end end end
#! /usr/bin/env ruby require "pathname" require "yaml" def sprints Enumerator.new do |y| number, start_date, end_date = nil old_milestones = YAML.load_file(Pathname.new(__dir__).join("old_sprint_boundaries.yml")) loop do if old_milestones.any? number, start_date, end_date = old_milestones.shift else number += 1 start_date = end_date + 1 # 1 day end_date += 14 # 2 weeks while (end_date.month == 12 && (22..31).cover?(end_date.day)) || (end_date.month == 1 && (1..4).cover?(end_date.day)) end_date += 7 # 1 week end end y << [number, start_date, end_date] end end end contents = <<~EOS # Sprint Boundaries Use the table below to look up which sprint a pull request was merged in. Sprint|Start|End|Merged PRs ---|---|---|--- EOS sprints .take_while { |_number, start_date, _end_date| start_date < Date.today } .reverse .each do |number, start_date, end_date| contents << [ number, start_date, end_date, "[link](https://github.com/issues?utf8=%E2%9C%93&q=org%3AManageiq+merged%3A#{start_date}..#{end_date})" ].join("|") << "\n" end Pathname.new(__dir__).join("..", "sprint_boundaries.md").write(contents)
class PhotosController < ApplicationController before_action :authenticate_user! def create @place = Place.find(params[:place_id]) @place.photos.create(photo_params) redirect_to place_path(@place) end private def photo_params params.fetch(:photo, {}).permit(:image) # params.require(:photo).permit(:image) end end
module Seeders module Genres class << self def seed genres.each do |name| genre = Genre.find_or_initialize_by(name: name) do |genre| genre.name = name genre.save end end end def genres ["Horror", "Sci-Fi", "Non Fiction", "Fiction"] end end end end
#!/usr/bin/env ruby require 'fileutils' tmpdir = File.expand_path(File.join(File.dirname(__FILE__),'..','tmp')) dbpath = File.join(tmpdir,'mongodb') if File.exists? dbpath puts "removing dbpath: #{dbpath}" FileUtils.rm_rf dbpath end unless File.exists? dbpath puts "creating dbpath: #{dbpath}" FileUtils.mkdir_p dbpath end command = %W(mongod -dbpath #{dbpath} -noprealloc -nojournal -noauth -port 26016 -bind_ip 127.0.0.1) puts "executing: #{command.join(' ')}" puts '************************************************************' puts 'Run specs: $ MONGO_URL=mongo://127.0.0.1:26016 bundle exec spec spec' puts '************************************************************' Kernel.exec *command
# frozen_string_literal: true module Nylas VERSION = "4.6.2" end
class Beatmap < ApplicationRecord has_many :match_scores, foreign_key: :beatmap_id validates_uniqueness_of :online_id def as_json(*) super.except('created_at', 'updated_at') end end