text
stringlengths
10
2.61M
class AddRodaIdentifier < ActiveRecord::Migration[6.0] def change change_table :activities do |t| t.string :roda_identifier_fragment t.string :roda_identifier_compound t.index [:roda_identifier_compound] end end end
module ListMore module Repositories class DBHelper < RepoHelper def create_tables db.exec <<-SQL CREATE TABLE IF NOT EXISTS users( id SERIAL PRIMARY KEY , username VARCHAR UNIQUE , password_digest VARCHAR ); CREATE TABLE IF NOT EXISTS lists( id SERIAL PRIMARY KEY , name VARCHAR UNIQUE , user_id INTEGER REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE ); CREATE TABLE IF NOT EXISTS items( id SERIAL PRIMARY KEY , content TEXT , user_id INTEGER REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE , list_id INTEGER REFERENCES lists(id) ON DELETE CASCADE ON UPDATE CASCADE ); CREATE TABLE IF NOT EXISTS shared_lists( id SERIAL PRIMARY KEY , user_id INTEGER REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE , list_id INTEGER REFERENCES lists(id) ON DELETE CASCADE ON UPDATE CASCADE ); CREATE TABLE IF NOT EXISTS sessions( user_id INTEGER REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE , token VARCHAR ); SQL end def clear_tables db.exec <<-SQL DELETE FROM users; DELETE FROM lists; DELETE FROM shared_lists; DELETE FROM items; DELETE FROM sessions; SQL end def drop_tables db.exec <<-SQL DROP TABLE users CASCADE; DROP TABLE lists CASCADE; DROP TABLE shared_lists CASCADE; DROP TABLE items CASCADE; DROP TABLE sessions CASCADE; SQL end def seed_users_table db.exec("INSERT INTO users (username, password) VALUES ($1, $2)", ["Ramses", "pitbull"]) db.exec("INSERT INTO users (username, password) VALUES ($1, $2)", ["Daisy", "collie"]) end end end end # create shared_lists repo/methods/tests # likely 3 methods one test for each # create share_list use case and test
Pod::Spec.new do |s| s.name = "RxResponderChain" s.version = "2.0.0" s.summary = "Notify Rx events via responder chain" s.description = <<-DESC `RxResponderChain` is an extension of `RxSwift`, `RxCocoa`. It provides the way to notify Rx events via responder chain. DESC s.homepage = "https://github.com/ukitaka/RxResponderChain" s.license = { :type => "MIT", :file => "LICENSE" } s.author = { "ukitaka" => "yuki.takahashi.1126@gmail.com" } s.platform = :ios, "9.0" s.source = { :git => "https://github.com/ukitaka/RxResponderChain.git", :tag => "#{s.version}" } s.source_files = "Sources/*.swift" s.requires_arc = true s.dependency "RxSwift", "~> 4.1" s.dependency "RxCocoa", "~> 4.1" end
class ChangeStartAndEndFromEvents < ActiveRecord::Migration def change rename_column :events, :start, :shoro rename_column :events, :end, :payan end end
module Database class Job < ActiveRecord::Base serialize :settings serialize :result before_save do self.status = 0 unless self.status # elimina cuvintele din array - /i case insensitive - \b word boundary \b %w[the of to and a in is it].each { |word| self.name = name.gsub(/\b#{word}\b/i, '').gsub(/[ ]{2,}/,' ').downcase.strip } if self.name end validates_presence_of :name validates_uniqueness_of :name, :case_sensitive => false validates_numericality_of :crossover_p, :mutation_p, :algo, :iterations def self.serialized_attr_accessor(*args) args.each do |method_name| method_declarations = <<-TOEVAL def #{method_name} self.settings = Hash.new unless self.settings self.settings.fetch(:#{method_name},0) end def #{method_name}=(value) self.settings = Hash.new unless self.settings self.settings[:#{method_name}] = value end TOEVAL eval method_declarations end end serialized_attr_accessor :iterations, :crossover_p, :mutation_p, :algo end end
module ApiHelper include Rack::Test::Methods def app Rails.application end def json_includes key JSON.parse(last_response.body)[key].should_not be_blank end def json_contains key, value JSON.parse(last_response.body)[key].should == value end def json_should_not_contain key JSON.parse(last_response.body).should_not have_key(key) end def status_code_is code last_response.status.should == code end def register_and_confirm credentials register credentials User.last.confirm! end def register credentials post('/users', credentials) end def sign_in credentials post('/sessions', credentials) end def user email User.find_by(email: email) end end RSpec.configure do |config| config.include ApiHelper, type: :api #apply to all spec for apis folder end
class ImageTextMixer require "mini_magick" BASE_IMAGE_PATH = Rails.root.join("app", "assets", "images", "twitter_post_v2.png") # BASE_IMAGE_PATH = "#{RAILS_ROOT}/app/assets/images/twitter_post.png" GRAVITY = 'west' TEXT_POSITION = '40,0' FONT = Rails.root.join("app", "assets", "fonts", "NotoSansJP-Black.otf") # FONT = "#{RAILS_ROOT}/app/assets/font/NotoSansJP-Black.otf" FONT_SIZE = 60 INDENTATION_COUNT = 15 def self.build(text, date) text = prepare_text(text, date) image = MiniMagick::Image.open(BASE_IMAGE_PATH) image.combine_options do |config| config.font FONT config.fill 'gray' config.gravity GRAVITY config.pointsize FONT_SIZE config.draw "text #{TEXT_POSITION} '#{text}'" end end private def self.prepare_text(text ,date) date + "\n" + text.scan(/.{1,#{INDENTATION_COUNT}}/).join("\n") end end
class ClassRoomsController < ApplicationController before_action :find_classroom, only: [:show,:new_student,:update] def index @class_rooms = ClassRoom.all end def new @class_room = ClassRoom.new @teachers = Teacher.all end def create @class_room = ClassRoom.new(class_params) if @class_room.save redirect_to class_room_path(@class_room.id) else render :new end end def show end def update @added_students = [] params[:students][:ids].each do |student_id| if !student_id.empty? found_student = Student.find_by(id: student_id) if found_student @added_students << found_student end end end @class_room.add_students(@added_students) redirect_to class_room_path(@class_room.id) end def new_students @students = Student.all @class_room = ClassRoom.find_by(id: params[:class_room_id]) end def find_classroom @class_room = ClassRoom.find_by(id: params[:id]) end private def class_params params.require(:class_room).permit(:subject,:teacher_id) end end
require 'rails_helper' describe "post a destination route", :type => :request do before do post '/destinations', params: { :city => 'test_city'} end it 'returns the city name' do expect(JSON.parse(response.body)['city']).to eq('test_city') end it 'returns a created status' do expect(response).to have_http_status(:created) end it 'returns updates city name' do expect(response).to be_an_instance_of(String) end end
require 'spec_helper' describe User do it { should have_valid(:email).when('test@test.com') } it { should_not have_valid(:email).when(nil, '', 'foo') } it { should have_valid(:username).when('mallgoats') } it { should_not have_valid(:username).when(nil, '') } it { should have_many(:reviews)} it { should have_many(:votes)} end
class SourceFile < ActiveRecord::Base set_table_name 'files' def last_action_before_commit commit_id all_actions = Action.where("file_id = ? AND commit_id <= ?", id, commit_id) last_action = nil all_actions.each do |a| if last_action.nil? or a.commit_id > last_action.commit_id last_action = a end end last_action end end
class Site include MongoMapper::Document key :user_ids, Array many :users, :in => :user_ids end
class CreateConshejointables < ActiveRecord::Migration[5.2] def change create_table :conshejointables do |t| t.integer :contact_id, default: 0 t.integer :sheet_id, default: 0 t.integer :order_number, default: 0 t.timestamps end end end
class CreateMeasurevalues < ActiveRecord::Migration def change create_table :measurevalues do |t| t.integer :person_id t.integer :measure_id t.decimal :value, :precision => 8, :scale => 2 t.date :value_date t.integer :created_by t.timestamps null: false end end end
require 'spec_helper' describe ServiceType do it "is an ActiveRecord mode" do expect(ServiceType.superclass).to eq(ActiveRecord::Base) end it "is true when true" do expect(true).to be_true end it "is valid with a name, description, agreement and active_record" do service_type = ServiceType.new( name: 'Tecnologia', description: 'Nenhum', agreement: true, active_record: true) expect(service_type).to be_valid end it "is invalid without a name" do expect(ServiceType.new(name: nil)).to have(1).errors_on(:name) end it "does not allow duplicate name per service type" do ServiceType.create(name: "Tecnologia") service_type = ServiceType.new(name: "Tecnologia") expect(service_type).to have(1).errors_on(:name) end end
class SampleGroupDestroyer < BaseServicer attr_accessor :sample_group def execute! SampleGroup.transaction do destroy_substructures destroy_sample_group end end private def destroy_sample_group sample_group.destroy end def destroy_substructures sample_group.substructures.each do |audit_structure| StructureDestroyer.execute!(audit_structure: audit_structure) end end end
require 'gosu' include Gosu #require_relative '../../features/step_definitions/sd_challenging_dom.rb' require_relative '../..//Helen Rubymine project/pong_ruby/player.rb' require_relative '../..//Helen Rubymine project/pong_ruby/ball.rb' require_relative '../..//Helen Rubymine project/pong_ruby/scoreboard.rb' class GamePong < Gosu::Window # each time you write a game start by creating a subclass of Gosu::Window # Constants #HEIGHT = 400 # WIDTH = 800 def initialize(width=800, height=600, fullscreen=false) #def initialize(WIDTH, HEIGHT) @ball = Ball.new(self, width, height) @state = :stopped @player_1 = Player.new(self, 40, height/2, 'player 1') @player_2 = Player.new(self,width - 40, height/2, 'player 2') @players = [@player_1, @player_2] @winner = nil @score_board = Scoreboard.new(self, width) @background_image = Gosu::Image.new("/home/helen/Desktop/Helen Rubymine project/pong_ruby/images/space.png", :tileable => true) super end def update if @state == :in_play if button_down?(kbDown) # (kbW) @player_1.move_up end if button_down?(kbs) @player_1.move_down end if button_down?(kbk) @player_2.move_down end if button_down?(kbI) @player_2.move_up end if @player_1.hit_ball(@ball) @ball.hit_stick(@player_1.y - @ball.y) end if @player_2.hit_ball(@ball) @ball.hit_stick(@player_2.y - @ball.y) end if @ball.x <0 @player_2.score @players.each(&:reset) @ball.reset @state = :stopped end if @ball.> width @player_1.score @players.each(&:reset) @ball.reset @state = :stopped end if @player_1.score == 10 @winner = @player_1 @state = :ended elsif if @player_2.score == 10 @winner = @player_2 @state = :ended end @ball.update elsif @state == :stopped if button_down?(kbSpace) @state = :in_play end end end def draw @background_image.draw(0, 0, 0) if @state == :ended @score_board.draw_win(@winner) end @score_board.draw(@players) @player_1.draw @player_2.draw @ball.draw end def load_sounds end end end GamePong.new.show
require "rails_helper" describe Reports::PerformanceScore, type: :model do let(:period) { Period.month("July 1 2020") } let(:facility) { build(:facility) } let(:reports_result) { double("Reports::Result") } let(:perf_score) { Reports::PerformanceScore.new(region: facility, reports_result: reports_result, period: period) } describe "#letter_grade" do it "returns the correct grade for a given score", :aggregate_failures do allow(perf_score).to receive(:overall_score).and_return(100) expect(perf_score.letter_grade).to eq("A") allow(perf_score).to receive(:overall_score).and_return(75.5) expect(perf_score.letter_grade).to eq("A") allow(perf_score).to receive(:overall_score).and_return(75) expect(perf_score.letter_grade).to eq("B") allow(perf_score).to receive(:overall_score).and_return(50.5) expect(perf_score.letter_grade).to eq("B") allow(perf_score).to receive(:overall_score).and_return(50) expect(perf_score.letter_grade).to eq("C") allow(perf_score).to receive(:overall_score).and_return(25.5) expect(perf_score.letter_grade).to eq("C") allow(perf_score).to receive(:overall_score).and_return(25) expect(perf_score.letter_grade).to eq("D") allow(perf_score).to receive(:overall_score).and_return(0) expect(perf_score.letter_grade).to eq("D") end end describe "#overall_score" do it "returns a score that sums control, visits, and registration scores" do allow(perf_score).to receive(:control_score).and_return(30) allow(perf_score).to receive(:visits_score).and_return(20) allow(perf_score).to receive(:registrations_score).and_return(15) expect(perf_score.overall_score).to eq(65) end it "returns a 100% if a facility matches the ideal rates" do allow(perf_score).to receive(:adjusted_control_rate).and_return(100) allow(perf_score).to receive(:adjusted_visits_rate).and_return(100) allow(perf_score).to receive(:adjusted_registrations_rate).and_return(100) expect(perf_score.overall_score).to eq(100) end end describe "#control_score" do it "returns a 50% weighted score based on adjusted control rate" do allow(perf_score).to receive(:adjusted_control_rate).and_return(40) expect(perf_score.control_score).to eq(20) end end describe "#adjusted_control_rate" do it "returns 100 when the control rate matches the ideal" do allow(perf_score).to receive(:control_rate).and_return(70) expect(perf_score.adjusted_control_rate).to eq(100) end it "returns 100 when the control rate is half of the ideal" do allow(perf_score).to receive(:control_rate).and_return(35) expect(perf_score.adjusted_control_rate).to eq(50) end it "returns 100 when the control rate exceeds the ideal" do allow(perf_score).to receive(:control_rate).and_return(90) expect(perf_score.adjusted_control_rate).to eq(100) end it "returns 0 when control rate is 0" do allow(perf_score).to receive(:control_rate).and_return(0) expect(perf_score.adjusted_control_rate).to eq(0) end end describe "#control_rate" do it "returns the control rate" do allow(reports_result).to receive(:controlled_patients_rate).and_return({period => 20}) expect(perf_score.control_rate).to eq(20) end it "returns 0 when control rate is empty hash" do allow(reports_result).to receive(:controlled_patients_rate).and_return({}) expect(perf_score.control_rate).to eq(0) end end describe "#visits_score" do it "returns a 30% weighted score based on adjusted visits rate" do allow(perf_score).to receive(:adjusted_visits_rate).and_return(60) expect(perf_score.visits_score).to eq(18) end end describe "#adjusted_visits_rate" do it "returns 100 when the visits rate matches the ideal" do allow(perf_score).to receive(:visits_rate).and_return(80) expect(perf_score.adjusted_visits_rate).to eq(100) end it "returns 100 when the visits rate is half of the ideal" do allow(perf_score).to receive(:visits_rate).and_return(40) expect(perf_score.adjusted_visits_rate).to eq(50) end it "returns 100 when the visits rate exceeds the ideal" do allow(perf_score).to receive(:visits_rate).and_return(90) expect(perf_score.adjusted_visits_rate).to eq(100) end it "returns 0 when visits rate is 0" do allow(perf_score).to receive(:visits_rate).and_return(0) expect(perf_score.adjusted_visits_rate).to eq(0) end end describe "#visits_rate" do it "returns the inverse of the missed visits rate" do allow(reports_result).to receive(:missed_visits_rate).and_return({period => 60}) expect(perf_score.visits_rate).to eq(40) end it "returns 100 when missed visits rate is 0" do allow(reports_result).to receive(:missed_visits_rate).and_return({period => 0}) expect(perf_score.visits_rate).to eq(100) end it "returns 100 when missed visits rate is empty hash" do allow(reports_result).to receive(:missed_visits_rate).and_return({}) expect(perf_score.visits_rate).to eq(100) end end describe "#registrations_score" do it "returns a 20% weighted score based on registrations rate" do allow(perf_score).to receive(:adjusted_registrations_rate).and_return(40) expect(perf_score.registrations_score).to eq(8) end end describe "#adjusted_registrations_rate" do it "returns 100 when the visits rate matches the ideal" do allow(perf_score).to receive(:registrations_rate).and_return(100) expect(perf_score.adjusted_registrations_rate).to eq(100) end it "returns 100 when the registrations rate is half of the ideal" do allow(perf_score).to receive(:registrations_rate).and_return(50) expect(perf_score.adjusted_registrations_rate).to eq(50) end it "returns 100 when the visits rate exceeds the ideal" do allow(perf_score).to receive(:registrations_rate).and_return(120) expect(perf_score.adjusted_registrations_rate).to eq(100) end it "returns 0 when registrations rate is 0" do allow(perf_score).to receive(:registrations_rate).and_return(0) expect(perf_score.adjusted_registrations_rate).to eq(0) end end describe "#registrations_rate" do it "returns registrations rate based on registrations / opd load" do allow(perf_score).to receive(:registrations).and_return(30) expect(perf_score.registrations_rate).to eq(10) end it "returns 100 if opd load is 0 and any registrations happen" do allow(facility).to receive(:monthly_estimated_opd_load).and_return(0) allow(perf_score).to receive(:registrations).and_return(10) expect(perf_score.registrations_rate).to eq(100) end it "returns 0 if opd load is 0 and no registrations happen" do allow(facility).to receive(:monthly_estimated_opd_load).and_return(0) allow(perf_score).to receive(:registrations).and_return(0) expect(perf_score.registrations_rate).to eq(0) end end describe "#registrations" do it "returns the registrations count" do allow(reports_result).to receive(:registrations).and_return(period => 20) expect(perf_score.registrations).to eq(20) end it "returns 0 when registrations count is empty hash" do allow(reports_result).to receive(:registrations).and_return({}) expect(perf_score.registrations).to eq(0) end end end
# frozen_string_literal: true Class.new(Nanoc::Filter) do identifier :fix_contributor_brackets def run(content, _params = {}) content.gsub(/ \[([^\]]+)\]\)?$/, ' \[\1\]') end end
require "spec_helper" describe Patient do it "should have a first name and second name" do user = Patient.create!(first_name: "Andy", last_name: "Lindeman") expect(user.first_name).to eq("Andy") expect(user.last_name).to eq("Lindeman") expect(user.name).to eq("Andy Lindeman") end it "should be of type Patient" do user = Patient.create!(first_name: "Andy", last_name: "Lindeman") expect(user).to be_an_instance_of(Patient) end it {should belong_to(:user) } it {should have_many(:wounds) } it {should have_db_column(:first_name) } it {should have_db_column(:last_name) } it {should have_db_column(:sex) } it {should have_db_column(:room_number) } it {should have_db_column(:user_id) } it {should have_db_column(:age)} end
require "formula" class GnuUnits < Formula homepage "https://www.gnu.org/software/units/" url "http://ftpmirror.gnu.org/units/units-2.02.tar.gz" mirror "http://ftp.gnu.org/gnu/units/units-2.02.tar.gz" sha1 "e460371dc97034d17ce452e6b64991f7fd2d1409" bottle do sha1 "255fd50fc880467483ae2654d1c34cd452247847" => :yosemite sha1 "43beaf9b66127bd29a393e2386c2c9a53522762f" => :mavericks sha1 "7d9b3438fbfeaa0d8a428a1ed6496df9d1c92cc6" => :mountain_lion end deprecated_option "default-names" => "with-default-names" option "with-default-names", "Do not prepend 'g' to the binary" def install args = ["--prefix=#{prefix}"] args << "--program-prefix=g" if build.without? "default-names" system "./configure", *args system "make", "install" end test do assert_equal "* 18288", shell_output("#{bin}/gunits '600 feet' 'cm' -1").strip end end
class Users::RegistrationsController < Devise::RegistrationsController before_action :has_invitation, only: [:new, :create] def create super if create_succeeded? @invitation.accepted! self.resource, Time.current end end def update_resource resource, params resource.update_without_password params end private def after_sign_up_path_for resource welcome_instructor_profiles_path end def create_succeeded? self.resource.persisted? end def has_invitation @invitation = Invitation.not_accepted.find_by token: params[:token] if @invitation.nil? redirect_to root_path end end def sign_up_params params.require(resource_name).permit(User::PERMITTED_PARAMS) end end
foo = ["foo", "bar", "nax", "pax"] puts foo[1] puts foo.include?("jar") puts foo.include?("foo") puts "" puts "Calling reverse will not mutate the array" p foo.reverse p foo puts "However using a bang(!) will mutate the array" p foo.reverse! p foo puts "" # To convert to an array p (1..15).to_a puts "" # random array of 0-100 y = (0..10).to_a.shuffle p y x = (0..10).to_a.shuffle! p x puts "" puts "Append to array" x = (1..10).to_a x << 15 p x x.push(20) p x x.unshift(-1) p x puts "" for number in x puts number end puts "" puts "using select works by giving it a boolean expression" p x.select { |num| num.odd? } puts "------------------------------------------------" foo = %w[foobar1 foobar2].freeze p foo puts "" # Looking into what Value equates to foo.each do |key, value| puts "key: #{key} value: #{value}" end puts "" # Value is never set, so it's not needed checking to see if using just a key works foo.each do |key| puts "key: #{key}" end puts "------------------------------------------------" # explodes a string fruits = "apple, bannana, grapes, orange" split_fruit = fruits.split(', ') # note to capture the space puts split_fruit
class ChangeFeederIdFormatInProsumers < ActiveRecord::Migration def up change_column :prosumers, :feeder_id, :string end def down change_column :prosumers, :feeder_id, "integer USING CAST(feeder_id AS integer)" end end
class PromotedOffer < ActiveRecord::Base include PgSearch pg_search_scope :search_by_name, :against => [:name, :location, :tag_list, :barcode], :using => { :tsearch => {:prefix => true, :any_word => true} } def self.search(search) PromotedOffer.search_by_name(search) end mount_uploader :image, ImageUploader belongs_to :user belongs_to :offer scope :published, -> { where('clicks <= set_clicks') } validates :set_clicks, numericality: { only_integer: true, :greater_than => 0, :less_than_or_equal_to => 100000 } end
require 'spec_helper' describe ActiveRecord do it 'should load classes with non-default primary key' do lambda { YAML.load(Story.create.to_yaml) }.should_not raise_error end it 'should load classes even if not in default scope' do lambda { YAML.load(Story.create(:scoped => false).to_yaml) }.should_not raise_error end end
=begin https://www.codewars.com/kata/52742f58faf5485cae000b9a Additional Test Cases: Test.assert_equals(format_duration(0), "now") =end # my solution 13/09/21 def format_duration(seconds) return "now" if seconds == 0 combinations = {year: 60*60*24*365, day: 60*60*24, hour: 60*60, minute: 60, second: 1} s = [] combinations.each do |key, value| if seconds / value > 0 s << pluralise(seconds / value, "#{key}") seconds = seconds % value end end s.length > 1 ? s[0...-1].join(", ") + " and " + s[-1] : s[0] end def pluralise(number, text) return number == 1 ? "#{number} #{text}" : "#{number} #{text}s" end
class ApplicationsController < ApplicationController def index @applications = Application.all end def show @application = Application.find(params[:id]) @pets = Pet.search(params[:pet_of_interst_name]) @pet = @application.pets end def new end def create application = Application.create(applications_params) application.status = "In Progress" if application.save redirect_to "/applications/#{application.id}" else flash[:alert] = "Error! Please fill out full form!" render :new end end def edit @application = Application.find(params[:id]) end def update application = Application.new(applications_params) end def destroy Application.find(params[:id]).destroy redirect_to '/applications' end def add_pet @application = Application.find(params[:id]) @pet = Pet.find(params[:pet_id]) @application.pets << @pet redirect_to "/applications/#{@application.id}" end def submit_pet @application = Application.find(params[:id]) @application.description = params[:description] @application.save redirect_to "/applications/#{@application.id}" end private def applications_params params.permit(:name, :address, :city, :state, :zip, :description, :status) end end
class RecipeBox < ActiveRecord::Base has_many :recipes belongs_to :profile end
class Dashboard < ActiveRecord::Base belongs_to :student belongs_to :job end
class AddEndOfLineToGeoLine < ActiveRecord::Migration def change add_column :geo_lines, :end_of_line, :boolean, default: false GeoLine.all.each do |line| line.update_attributes end_of_line: true end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) if User.first.nil? # no hay usuarios names = ["Fernando", "Camilo", "Diego", "Felipe", "Marco", "Rafael", "Manuel", "Diego", "Gabriel", "Javier", "Patricio", "Javier", "Antonio", "Tomas", "Nicolas", "Antonio", "Agustin", "Vicente", "Matías", "Gerardo", "Bastián", "Gerardo", "Hector", "Daniela", "Felipe", "David", "Rodrigo", "Fernando", "Cristobal", "Jorge", "Felix", "Maria", "Diego", "Fabio", "Juan"] names.uniq.map{|n| n.downcase }.each do |name| User.create(username: name, password: '12345678') end end
# frozen_string_literal: true WEEK = %w[понедельник вторник среда четверг пятница суббота воскресение].freeze print(WEEK.select { |el| el.start_with? 'с' })
module Fog module Compute class Google class Mock def set_instance_template(_instance_group_manager, _instance_template) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end class Real def set_instance_template(instance_group_manager, instance_template) request = ::Google::Apis::ComputeV1::InstanceGroupManagersSetInstanceTemplateRequest.new( :instance_template => instance_template.class == String ? instance_template : instance_template.self_link ) if instance_group_manager.zone zone = instance_group_manager.zone.split("/")[-1] @compute.set_instance_group_manager_instance_template(@project, zone, instance_group_manager.name, request) else region = instance_group_manager.region.split("/")[-1] @compute.set_region_instance_group_manager_instance_template(@project, region, instance_group_manager.name, request) end end end end end end
class User < ActiveRecord::Base devise :rememberable, :trackable, :omniauthable, omniauth_providers: [:vkontakte] def self.from_omniauth(auth) where(provider: auth.provider, uid: auth.uid).first_or_create do |user| user.name = auth.info.name user.image = auth.info.image user.profile_url = auth.info.urls[auth.provider.capitalize] end end def image_upload_allowed? last_image_upload_at.nil? || last_image_upload_at <= 1.day.ago end def update_image_upload_time touch :last_image_upload_at end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) require "ffaker" def drop_all_the_things puts "drop all the things" [Product, Category, Customer].map(&:destroy_all) end def set_up_development_database 200.times do |i| products = Product.create( { name: Faker::BaconIpsum.words.join(''), company: Faker::Company.name, description: Faker::BaconIpsum.paragraph, ups: Faker::Identification.drivers_license, price: rand(5..278), website: Faker::Internet.uri('http'), } ) end 30.times do |i| customers = Customer.create( { name: Faker::Name.name, last_name: Faker::Name.name, email: Faker::Internet.email, contact_phone: Faker::PhoneNumber.phone_number, street: Faker::AddressUS.street_address, city: Faker::AddressUS.city, state: Faker::AddressUS.state, zip: Faker::AddressUS.zip_code, } ) end @categories = ["Mens apparel", "Shoes", "School Supplies", "Accessories", "Woman apparel", "Sports Apparel", "Sports equipment", "Electronics" ] 20.times do |i| categories = Category.create( { name: @categories.sample, description: Faker::BaconIpsum.paragraph }) end end case Rails.env when 'development' drop_all_the_things set_up_development_database when 'production' end
# User factory FactoryGirl.define do factory :user do username 'developer' email 'developer@example.com' firstname 'Dev' lastname 'Eloper' password_salt Authlogic::Random.hex_token crypted_password { Authlogic::CryptoProviders::Sha512.encrypt("#{username}#{password_salt}") } persistence_token Authlogic::Random.hex_token trait :aleph_attributes do user_attributes do { nyuidn: (ENV['BOR_ID'] || 'BOR_ID'), primary_institution: :NYU, institutions: [:NYU], bor_status: '51' } end end factory :aleph_user, traits: [:aleph_attributes] end end
Dado("que apresentado o fomulário para autenticar no AgroHUB") do @login= LoginPage.new @login.abrirUrl end Quando("faço com login e-mail com o gestor:") do |table| @dadosGestor = table.rows_hash @login.logar(@dadosGestor) @login.entra end Então("sou autenticado com sucesso no AgroHUB") do @paginalogada = find('.description') expect(@paginalogada.text).to eql "Bem vindo ao Painel Administrativo AgroHUB" end Quando("faço com login e-mail com o usuário:") do |table| @dadosUsuario = table.rows_hash @login.logar(@dadosUsuario) @login.entra end
require "./q7/menu" class Q7::Drink < Q7::Menu attr_accessor :amount def initialize(name:, price:, amount:) super(name: name, price: price) @amount = amount end end
# frozen_string_literal: true # contains logic for basic moves for all pieces class BasicMovement attr_reader :row, :column, :board def initialize(board = nil, row = nil, column = nil) @board = board @row = row @column = column end def update_pieces(board, coords) @board = board @row = coords[:row] @column = coords[:column] update_basic_moves end def update_basic_moves remove_capture_piece_observer if @board.data[row][column] update_new_coordinates remove_original_piece update_active_piece_location end def remove_capture_piece_observer @board.delete_observer(@board.data[row][column]) end def update_new_coordinates @board.data[row][column] = @board.active_piece end def remove_original_piece location = @board.active_piece.location @board.data[location[0]][location[1]] = nil end def update_active_piece_location @board.active_piece.update_location(row, column) end end
require "pakyow_helper" RSpec.describe "Links", type: :feature do def rom Pakyow::Config.app.rom end def create_link(attributes) attributes = attributes.merge(created_at: Time.now, updated_at: Time.now) rom.command(:links).create.call(attributes) end def delete_all_links # TODO this sure isn't very intention revealing... rom.command(:links).delete.call end after do # TODO probably better to use database cleaner or # something than manually deleting these... delete_all_links end describe "viewing links" do it "displays all links" do create_link(url: "http://google.com") create_link(url: "http://iamvery.com") create_link(url: "http://youtube.com") visit "/links" expect(page).to have_content("iamvery.com") expect(page).to have_content("google.com") expect(page).to have_content("youtube.com") end end describe "creating link" do it "adds the link to the index" do # TODO are there path helper methods in pakyow visit "/links" fill_in "Url", with: "http://iamvery.com" click_on "Create link" expect(page).to have_content("iamvery.com") end end end
require 'rails_helper' RSpec.describe User, type: :model do before do @user = FactoryBot.build(:user) end describe 'ユーザー新規登録' do context '新規登録できるとき' do it 'nickname,email,password,password_confirmation,last_name,first_name,last_name_furigana,first_name_furigana,birthdayが存在すると登録できる' do expect(@user).to be_valid end it 'password,password_confirmationが半角英数字混合で、6文字以上あれば登録できる。' do @user.password = 'abcd12' @user.password_confirmation = 'abcd12' expect(@user).to be_valid end it 'last_name,first_nameが漢字、カタカナ、ひらがなの入力で登録できる。' do @user.last_name = '一アあ' @user.first_name = '一アあ' expect(@user).to be_valid end it 'last_name_furigana,first_name_furiganaがカタカナの入力で登録できる。' do @user.last_name_furigana = 'テストー' @user.first_name_furigana = 'テストー' expect(@user).to be_valid end end context '新規登録できないとき' do it 'nicknameが空では登録できない' do @user.nickname = '' @user.valid? expect(@user.errors.full_messages).to include "Nickname can't be blank" end it 'emailが空では登録できない' do @user.email = '' @user.valid? expect(@user.errors.full_messages).to include "Email can't be blank" end it 'passwordが空では登録できない' do @user.password = '' @user.valid? expect(@user.errors.full_messages).to include "Password can't be blank", 'Password is invalid', "Password confirmation doesn't match Password" end it 'passwordが存在してもpassword_confirmationが空では登録できない' do @user.password_confirmation = '' @user.valid? expect(@user.errors.full_messages).to include "Password confirmation doesn't match Password" end it 'last_nameが空では登録できない' do @user.last_name = '' @user.valid? expect(@user.errors.full_messages).to include "Last name can't be blank", 'Last name is invalid' end it 'first_nameが空では登録できない' do @user.first_name = '' @user.valid? expect(@user.errors.full_messages).to include "First name can't be blank", 'First name is invalid' end it 'last_name_furiganaが空では登録できない' do @user.last_name_furigana = '' @user.valid? expect(@user.errors.full_messages).to include "Last name furigana can't be blank", 'Last name furigana is invalid' end it 'first_name_furiganaが空では登録できない' do @user.first_name_furigana = '' @user.valid? expect(@user.errors.full_messages).to include "First name furigana can't be blank", 'First name furigana is invalid' end it 'birthdayが空では登録できない' do @user.birthday = '' @user.valid? expect(@user.errors.full_messages).to include "Birthday can't be blank" end it '重複したemailが存在する場合登録できない' do @user.save another_user = FactoryBot.build(:user) another_user.email = @user.email another_user.valid? expect(another_user.errors.full_messages).to include 'Email has already been taken' end it 'emailに@がない場合登録できない' do @user.email = 'testtest.com' @user.valid? expect(@user.errors.full_messages).to include 'Email is invalid' end it 'passwordが半角数字のみでは登録できない' do @user.password = '000000' @user.password_confirmation = '000000' @user.valid? expect(@user.errors.full_messages).to include 'Password is invalid' end it 'passwordが半角英字のみでは登録できない' do @user.password = 'aaaaaa' @user.password_confirmation = 'aaaaaa' @user.valid? expect(@user.errors.full_messages).to include 'Password is invalid' end it 'passwordが全角文字が入力された場合登録できない' do @user.password = 'Aa1234' @user.password_confirmation = 'Aa1234' @user.valid? expect(@user.errors.full_messages).to include 'Password is invalid' end it 'passwordが5文字以下では登録できない' do @user.password = 'abcd1' @user.password_confirmation = 'abcd1' @user.valid? expect(@user.errors.full_messages).to include 'Password is too short (minimum is 6 characters)' end it 'last_nameが漢字、カタカナ、ひらがな以外では登録できない' do @user.last_name = 'a' @user.valid? expect(@user.errors.full_messages).to include 'Last name is invalid' end it 'first_nameが漢字、カタカナ、ひらがな以外では登録できない' do @user.first_name = 'a' @user.valid? expect(@user.errors.full_messages).to include 'First name is invalid' end it 'last_name_furiganaがカタカナ以外では登録できない' do @user.last_name_furigana = '山田' @user.valid? expect(@user.errors.full_messages).to include 'Last name furigana is invalid' end it 'first_name_furiganaがカタカナ以外では登録できない' do @user.first_name_furigana = '太郎' @user.valid? expect(@user.errors.full_messages).to include 'First name furigana is invalid' end end end end
require 'test_helper' class TeacherTest < ActiveSupport::TestCase should have_many(:schedules).dependent(:destroy) should have_many(:subjects).through(:schedules) should have_many(:klasses).through(:schedules) should validate_presence_of(:name) should ensure_inclusion_of(:age).in_range(1..100) should ensure_inclusion_of(:gender).in_array(%w{male female}) should_not allow_value("foo").for(:email) should allow_value("foo@bar.com").for(:email) should allow_mass_assignment_of(:name) should allow_mass_assignment_of(:age) should allow_mass_assignment_of(:gender) should allow_mass_assignment_of(:email) end
#!/usr/bin/env ruby # Author: Courtney Cotton <cotton@cottoncourtney.com> 5-26-2015 # Desc: This script takes a list of IPs from a .txt file and grabs the # correct subnet/cidr from a provided FTP networks file. # Libraries/Gems require 'optparse' require 'net/ftp' require 'fileutils' require 'ipaddr' # Represents a Example Network, consisting of the subnet name, the cidr and a description class ExampleNetwork attr_accessor :name, :cidr, :description def initialize name, cidr, description @name = name @cidr = IPAddr.new cidr @description = description end # Returns true if a sample ip is present in the range of ipaddresses of this Network def includes_ip? ip begin testip = IPAddr.new ip return @cidr.include? ip rescue IPAddr::InvalidAddressError return false end end # Returns the subnet mask prefix for this particular network. def subnet_mask @cidr.instance_variable_get("@mask_addr").to_s(2).count('1') end end # Represents a collection of Example Networks class ExampleNetworks attr_accessor :list # Reads a networks.local file and constructs a Berkley Networks object def read_from_file filename @list = [] File.readlines(filename).each do |line| line = line.split(/\t/) unless is_comment? line name = line[0].strip cidr = line[1].strip description = line[2].strip @list.push ExampleNetwork.new name, cidr, description end end File.delete(filename) self end # Returns a list of all the subnets defined in ExampleNetworks which the ipaddress is a member of def all_subnets_for_ipaddress ipaddress subnets = [] @list.each do |example_network| subnets.push example_network.name if example_network.includes_ip? ipaddress end subnets end # Returns the most specifc subnet match for an ipaddress def subnet_for_ipaddress ipaddress # Start with something to compare the next match to most_specific_subnet = ExampleNetwork.new nil, '0.0.0.0/0', 'All ips' @list.each do |example_network| # The most specific subnet match is the one with the greatest subnet mask prefix (i.e. /25 is less specifc thatn /28 ) if example_network.includes_ip? ipaddress and example_network.subnet_mask > most_specific_subnet.subnet_mask most_specific_subnet = example_network end end most_specific_subnet end private def is_comment? line line[0].start_with? "#" end end class ExampleNetworksIpaddressMatcher attr_accessor :options def initialize @options = {} OptionParser.new do |opts| opts.banner = "Usage: looks up subnet/cidr for ip address" opts.on("-f", "--file path/filename", "Example: /path/to/filname.txt") do |f| @options[:ipfile] = f end end.parse! end def match_ipaddresses_from_net # Get most recent copy of networks.local file. unless File.exists? 'networks.local' # Change the URL to be the FTP download location of your subnet lists ftp = Net::FTP.new('ftp.net.example.edu') ftp.login files = ftp.chdir('pub') files = ftp.list('n*') remotefile = 'networks.local' ftp.gettextfile(remotefile, localfile = File.basename(remotefile)) ftp.close end # Verify required inputs abort("ABORTING: ip file not provided, please use ./cidrmagic -f path/to/filename.txt") if options[:ipfile].nil? networks = ExampleNetworks.new.read_from_file 'networks.local' ip_lines = File.readlines(options[:ipfile]).map do |line| line = line.split(/ /)[0] end infos = [] subnets_so_far = [] ip_lines.each do |ip| address = ip.strip subnets = networks.subnet_for_ipaddress address # If subnet has already been printed, no printsies again. unless subnets_so_far.include? subnets if subnets.name.nil? infos.push "#{ip.strip} NO MATCHES" else infos.push "- '#{subnets.cidr.to_s}/#{subnets.subnet_mask}' ##{subnets.name} " subnets_so_far.push(subnets) end end end infos end end bnim = ExampleNetworksIpaddressMatcher.new puts bnim.match_ipaddresses_from_net
module Ricer::Plugins::Conf class Help < Ricer::Plugin trigger_is :help bruteforce_protected :always => false has_usage :execute_list, '' def execute_list return if bruteforcing? # Manual bruteforce protection grouped = collect_groups grouped = Hash[grouped.sort] grouped.each do |k,v|; grouped[k] = v.sort; end sender.send_message t(:msg_triggers, :triggers => grouped_output(grouped)) end has_usage :execute_help, '<trigger>' def execute_help(trigger) reply trigger.get_help rescue rply :err_no_help end protected def help_plugins triggers = [] Ricer::Bot.instance.plugins.each do |plugin| triggers.push(plugin) if plugin.has_usage? end triggers end private def collect_groups() grouped = {} help_plugins.each do |plugin| if plugin.in_scope?(plugin.scope) && plugin.has_permission?(plugin.trigger_permission) m = plugin.plugin_module grouped[m] = [] if grouped[m].nil? grouped[m].push(plugin.trigger) end end grouped end def grouped_output(grouped) out = [] grouped.each do |k,v| group = lib.bold(k) + ': ' group += v.join(', ') out.push(group) end out.join('. ') end end end
class Gender < ActiveRecord::Base def name I18n.t("catalogs.gender.#{i18n_name}") end def to_s name end def self.ids_for_male_and_female_entries @ids_for_male_and_female_entries ||= self.where(:i18n_name => ['male','female']).select(:id).map(&:id) end def self.all_with_all_option [Struct.new(:id, :name).new('all', I18n.t('catalogs.options.all'))] + all end end
class ConversationsController < ApplicationController before_action :set_conversation, only: [:replay, :show] def index @conversations = current_user.mailbox.conversations end def show @conversation = current_user.mailbox.conversations.find(params[:id]) @messages = @conversation.messages.order(created_at: :asc) respond_to do |format| format.html {render :layout => !request.xhr?} end end def new @recipients = User.all end def create recipient = User.find(params[:user_id]) if params[:body] != nil receipt = current_user.send_message(recipient, params[:body], params[:subject]) redirect_to conversations_path(receipt.conversation) else redirect_to(:back) end end def replay @conversation = current_user.mailbox.conversations.find(params[:id]) @receipt = current_user.reply_to_conversation(@conversation, params[:body]) respond_to do |format| format.html {render :layout => !request.xhr?} format.js end end def replayForXs @conversation = current_user.mailbox.conversations.find(params[:id]) @receipt = current_user.reply_to_conversation(@conversation, params[:body]) respond_to do |format| format.html {render :layout => !request.xhr?} format.js end end private def set_conversation @conversation = current_user.mailbox.conversations.find(params[:id]) end end
class AddSettingsToTeamBotInstallation < ActiveRecord::Migration[4.2] def change config = CheckConfig.get('clamav_service_path') CheckConfig.set('clamav_service_path', nil) add_column(:users, :settings, :text) unless column_exists?(:users, :settings) add_column(:team_users, :settings, :text) unless column_exists?(:team_users, :settings) BotUser.reset_column_information TeamBotInstallation.reset_column_information bot = BotUser.keep_user bot.set_settings([ { "name" => "archive_archive_is_enabled", "label" => "Enable Archive.is", "type" => "boolean", "default" => "false" }, { "name" => "archive_archive_org_enabled", "label" => "Enable Archive.org", "type" => "boolean", "default" => "false" }, { "name" => "archive_keep_backup_enabled", "label" => "Enable Video Vault", "type" => "boolean", "default" => "false" } ]) bot.save! TeamBotInstallation.find_each do |installation| settings = {} installation.team.settings.select{ |key, _value| key.to_s =~ /^archive_.*_enabled/ }.each do |key, value| settings[key] = value.to_i == 1 end installation.settings = settings installation.save! end CheckConfig.set('clamav_service_path', config) end end
class Public::AddressesController < ApplicationController before_action :authenticate_customer! def index @addresses = Address.all.order(created_at: :desc) @address = Address.new end def create @address = Address.new(add_params) @address.customer_id = current_customer.id if @address.save flash[:success] = '配送先登録が完了しました!' redirect_to addresses_path else flash[:danger] = '内容に不備があります!' render :index end end def edit @address = Address.find(params[:id]) end def update @address = Address.find(params[:id]) if @address.update(add_params) flash[:success] = '編集内容を保存しました!' redirect_to addresses_path else flash[:danger] = '内容に不備があります!' render :edit end end def destroy @address = Address.find(params[:id]) @address.destroy flash[:success] = '配送先登録を削除しました!' redirect_to addresses_path end # 宛名データのストロングパラメータ private def add_params params.require(:address).permit(:customer_id, :postal_code, :address, :name) end end
# typed: false class Message < ApplicationRecord validates :content, presence: true belongs_to :game end
class Property < ActiveRecord::Base DOMAIN_HEAD_REGEX = '(?:[A-Z0-9\-]+\.)+'.freeze DOMAIN_TLD_REGEX = '(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|jobs|museum|local|asia)'.freeze DOMAIN_REGEX = /\A#{DOMAIN_HEAD_REGEX}#{DOMAIN_TLD_REGEX}\z/i has_many :campaigns has_many :sessions has_many :tracks, :extend => Analytics::Model::Stream has_many :redirects belongs_to :account has_attached_file :thumb, :styles => { :thumb => "100x100" } normalize_attributes :name, :description named_scope :user, lambda {|user| {:conditions => {:id => user.properties.map(&:id)} } } named_scope :search, lambda {|criteria| search = "%#{criteria}%" {:conditions => ['name like ? or host like ?', search, search ]} } validates_associated :account validates_presence_of :account_id validates_presence_of :name validates_length_of :name, :within => 3..40 validates_uniqueness_of :name, :scope => :account_id validates_presence_of :host validates_length_of :host, :within => 5..100 validates_uniqueness_of :host, :scope => :account_id validates_format_of :host, :with => DOMAIN_REGEX validates_format_of :search_parameter, :with => /[a-z0-9]+/i, :allow_nil => true, :allow_blank => true def host=(val) super(val.sub(/\/\Z/,'')) end def url "http://#{self.host}" end end
module SessionsHelper def sign_in(company) cookies.permanent[:remember_token] = company.remember_token current_company = company end def signed_in? !current_company.nil? end def current_company= (company) @current_company = company end def current_company @current_company ||= company_from_remember_token end def sign_out current_company = nil cookies.delete(:remember_token) end private def company_from_remember_token remember_token = cookies[:remember_token] Company.find_by_remember_token(remember_token) unless remember_token.nil? end end
require 'spec_helper' RSpec.describe Movie, type: :model do let(:movie) { build(:movie, title: "300", plot: "...") } it "must be valid" do expect(movie).to be_valid end end
require 'helper' =begin Signatures in tests generated by existing PHP signatory, to ensure compatibility. http://github.com/matchu/openneo-auth-server/blob/master/openneo_auth_signatory.class.php =end class TestOpenneoAuthSignatory < Test::Unit::TestCase def setup @signatory = Openneo::Auth::Signatory.new('MySecret32!!') end def test_sign assert_signature( '405f4c596ae21770ca6a304ff34f45e11c496fb7bc1d23abb58663719e061fb3', :foo => 'bar', :eggs => 'spam', :your => 'mom' ) end def test_multiple_signatures assert_signature( 'a21492375b22c4155f5c374b98de16c151ba3d721d86325c97f3f27741a0b7a2', :foo => 'bar' ) assert_signature( 'f2eff505366cc77f64204e5fcdc3fb58d0ac0aa442f6e58837de0fab3a121d1d', :bart => 'foot' ) end def test_order_insensitive signature = '3e105d0690d99e3c9046b393e9bc338301a69d710756a5a5cfc3872b1ca7bb36' assert_signature signature, :a => 1, :b => 2, :c => 3 assert_signature signature, :c => 3, :b => 2, :a => 1 end def test_nested_hash assert_signature( '8aa5f3b84750d0f8b67e1f9cc30010906457f576b22a82d6f5408c60fa9ede57', :hello => 'world', :foo => {:bar => 1, :baz => 2} ) end end
require 'docx_builder' plan_struct = Struct.new(:name, :areas, :goals_by_area, :objectives_by_goal) area_struct = Struct.new(:description, :id) goal_struct = Struct.new(:description, :id) objective_struct = Struct.new(:description) @plan = plan_struct.new @plan.name = 'Business Plan for 2011' @plan.areas = [area_struct.new('Software Development', 1), area_struct.new('Cooking', 2)] @plan.goals_by_area = { 1 => [ goal_struct.new('Create a new app', 1), goal_struct.new('Create another app', 2)], 2 => [ goal_struct.new('Make a new recipe', 3), goal_struct.new('Open a restaurant', 4)], } @plan.objectives_by_goal = { 1 => [ objective_struct.new('It should be interesting'), objective_struct.new('It should be simple') ], 2 => [ objective_struct.new('It should be revolutionary'), objective_struct.new('It should be unique') ], 3 => [ objective_struct.new('Make a unique recipe'), objective_struct.new('Make a tasty recipe') ], 4 => [ objective_struct.new('Serve high quality food'), objective_struct.new('Make it cheap') ], } file_path = "#{File.dirname(__FILE__)}/example/plan_report_template.xml" dir_path = "#{File.dirname(__FILE__)}/example/plan_report_template" report = DocxBuilder.new(file_path, dir_path).build do |template| template['head']['Plan Name'] = @plan.name template['area'] = @plan.areas.map do |area| area_slice = template['area'].clone area_slice['Area Name'] = area.description area_slice['goal'] = @plan.goals_by_area[area.id].map do |goal| goal_slice = template['goal'].clone goal_slice['Goal Name'] = goal.description goal_slice['objective'] = @plan.objectives_by_goal[goal.id].map do |objective| objective_slice = template['objective'].clone objective_slice['Objective Name'] = objective.description objective_slice end goal_slice end area_slice end end open("example.docx", "w") { |file| file.write(report) } # ... or in a Rails controller: # response.headers['Content-disposition'] = 'attachment; filename=plan_report.docx' # render :text => report, :content_type => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
require 'test_helper' class TodoTest < ActiveSupport::TestCase def todo todo = todos(:one) end def user @user ||= users(:one) end def member @member ||= users(:two) end def event Event.last end test 'finished shoulde be make finished to true' do todo.finished! assert todo.finished end test 'assign user' do todo.assign_to(member.id) assert_equal member.id, todo.user_id end test 'create should be touch created event' do todo = Todo.create(content: 'a new todo', handler_id: user.id) assert_equal 'todo_created', event.action assert_equal user.id, event.user_id end test 'destroy shoudle be touch destroyed event' do todo.handler_id = user.id todo.destroy assert_equal 'todo_destroyed', event.action assert_equal user.id, event.user_id end test 'finish shoudle be touch finished event' do todo.handler_id = user.id todo.finished! assert_equal 'todo_finished', event.action assert_equal user.id, event.user_id end test 'assign user from nil to member shoudle be touch assign user event' do todo.handler_id = user.id todo.assign_to(member.id) assert_equal 'todo_assign_user', event.action assert_equal user.id, event.user_id assert_equal nil, event.extra_1 assert_equal member.id.to_s, event.extra_2 end test 'change assgin user from user to member shoudle be touch change user event' do todo = todos(:two) todo.handler_id = user.id todo.assign_to(member.id) assert_equal 'todo_change_user', event.action assert_equal user.id, event.user_id assert_equal user.id.to_s, event.extra_1 assert_equal member.id.to_s, event.extra_2 end end
require 'rails_helper' require 'web_helper' feature 'liking posts' do it 'a user can endorse a review on the index page, which increments the endorsement count', js: true do create_user create_post sign_in visit '/posts' click_link 'Like' expect(page).to have_content("1 like") end scenario 'a post has no likes' do create_user create_post sign_in visit '/posts' expect(page).to have_content('0 likes') end scenario 'a review has one endorsement' do create_user post = Post.create(description: 'My lovely photo', user_id: 1, id: 1) post.likes.create(user_id: 1) sign_in visit '/posts' expect(page).to have_content('1 like') end end
module I18nBackendDatabase class Engine < Rails::Engine initializer "i18n_backend_database.initialize" do |app| I18n.backend = I18n::Backend::Database.new end initializer "common.init" do |app| # Publish #{root}/public path so it can be included at the app level if app.config.serve_static_assets app.config.middleware.use ::ActionDispatch::Static, "#{root}/public" end end end end
class PollChoice < ActiveRecord::Base belongs_to :poll has_many :votes, dependent: :destroy has_many :citizens, through: :votes normalize_attribute :name, with: [:strip, :blank] do |value| value.present? && value.is_a?(String) ? value.upcase : value end after_create do poll.keyword_listeners.create(keyword: name) end end
require_dependency "administration/application_controller" module Administration class ArticleTypesController < ApplicationController # Require this in order to avoid uninitialized constant require "#{Article::Engine.root}/app/models/article/publication.rb" def index @types = Article::Type.all.reverse end def new @type = Article::Type.new variables_for_new end def create @type = Article::Type.new(type_params) if @type.save redirect_to administration.article_types_path, :notice => "A new type was created!" else variables_for_new render action: :new, :notice => "An error occured, the type was not saved" end end def edit @type = Article::Type.find(params[:id]) variables_for_edit end def update @type = Article::Type.find(params[:id]) if @type.update_attributes(type_params) redirect_to administration.article_types_path, notice: 'Successfully updated.' else variables_for_edit render action: :edit, :notice => "An error occured, the type was not saved" end end def destroy @type = Article::Type.find(params[:id]) unless @type.destroy redirect_to(administration.article_types_path, notice: "An error occured, the deletion was not successful") else redirect_to(administration.article_types_path, notice: "A article type was deleted") end end private def type_params params.require(:type).permit(:title, :description) end # these variables are required whenever the new view is rendered def variables_for_new @path = administration.article_types_path @method = :post end # these variables are required whenever the edit view is rendered def variables_for_edit @path = administration.article_type_path @method = :patch end end end
class QuotesController < ApplicationController def new @accountant = Accountant.find(params[:accountant][:accountant_id]) @enquiry = Enquiry.find(params[:accountant][:id]) @quote = Quote.new(enquiry: @enquiry) authorize @quote end def new_admin authorize current_user @quote = Quote.new end def id_check authorize current_user @accountant = Accountant.where(id: params[:quote][:accountant_id]).first @enquiry = Enquiry.where(id: params[:quote][:enquiry_id]).first respond_to do |format| format.js # <-- will render `app/views/quotes/id_check.js.erb` end end def create @quote = Quote.new(quote_params) if @quote.save redirect_to user_path(@quote.enquiry.user) else render :new end authorize @quote end def destroy @quote = Quote.find(params[:id]) @quote.destroy authorize @quote end def change_status @quote = Quote.find(params[:quote_id]) @quote.successful = true authorize @quote unless @quote.save render :show end end private def quote_params params.require(:quote).permit(:message, :accountant_id, :enquiry_id, :invite, :successful) end end
class AddProgressiveVolumeDiscountToVariants < ActiveRecord::Migration def self.up add_column :variants, :progressive_volume_discount, :boolean, :null => false, :default => 0 end def self.down remove_column :variants, :progressive_volume_discount end end
class SiteOptionsController < ApplicationController before_action :set_site_option, only: [:show, :edit, :update, :destroy] # GET /site_options # GET /site_options.json def index @site_options = SiteOption.page params[:page] end # GET /site_options/1 # GET /site_options/1.json def show end # GET /site_options/new def new @site_option = SiteOption.new end # GET /site_options/1/edit def edit end # POST /site_options # POST /site_options.json def create @site_option = SiteOption.new(site_option_params) respond_to do |format| if @site_option.save format.html { redirect_to @site_option, notice: 'Site option was successfully created.' } format.json { render :show, status: :created, location: @site_option } else format.html { render :new } format.json { render json: @site_option.errors, status: :unprocessable_entity } end end end # PATCH/PUT /site_options/1 # PATCH/PUT /site_options/1.json def update respond_to do |format| if @site_option.update(site_option_params) format.html { redirect_to @site_option, notice: 'Site option was successfully updated.' } format.json { render :show, status: :ok, location: @site_option } else format.html { render :edit } format.json { render json: @site_option.errors, status: :unprocessable_entity } end end end # DELETE /site_options/1 # DELETE /site_options/1.json def destroy @site_option.destroy respond_to do |format| format.html { redirect_to site_options_url, notice: 'Site option was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_site_option @site_option = SiteOption.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def site_option_params params.require(:site_option).permit(:key, :value) end end
require "rails_helper" RSpec.describe Api::V4::CallResultsController, type: :controller do let(:request_user) { create(:user) } let(:request_facility_group) { request_user.facility.facility_group } let(:request_facility) { create(:facility, facility_group: request_facility_group) } let(:model) { CallResult } let(:build_payload) { -> { build_call_result_payload } } let(:build_invalid_payload) { -> { build_invalid_call_result_payload } } let(:invalid_record) { build_invalid_payload.call } let(:update_payload) { ->(call_result) { updated_call_result_payload call_result } } let(:number_of_schema_errors_in_invalid_payload) { 2 } def create_record(options = {result_type: :agreed_to_visit}) facility = options[:facility] || create(:facility, facility_group: request_facility_group) patient = create(:patient, registration_facility: facility) create(:call_result, {patient: patient}.merge(options)) end def create_record_list(n, options = {result_type: :agreed_to_visit}) facility = options[:facility] || create(:facility, facility_group: request_facility_group) patient = create(:patient, registration_facility: facility) create_list(:call_result, n, {patient: patient}.merge(options)) end it_behaves_like "a sync controller that authenticates user requests: sync_from_user" it_behaves_like "a sync controller that audits the data access: sync_from_user" describe "POST sync: send data from device to server;" do it_behaves_like "a working sync controller creating records" it_behaves_like "a working sync controller updating records" it "creates call results" do patient = create(:patient) call_results = (1..3).map { build_call_result_payload(build(:call_result, patient: patient)) } set_authentication_headers post(:sync_from_user, params: {call_results: call_results}, as: :json) expect(CallResult.count).to eq 3 expect(patient.call_results.count).to eq 3 expect(response).to have_http_status(200) end context "when patient_id is not supplied" do it "sets the patient_id from the appointment" do patient = create(:patient) appointment = create(:appointment, patient: patient) call_results = [build_call_result_payload(build(:call_result, appointment: appointment, patient_id: nil)), build_call_result_payload(build(:call_result, appointment: appointment)).except(:patient_id)] set_authentication_headers post(:sync_from_user, params: {call_results: call_results}, as: :json) expect(CallResult.count).to eq 2 expect(CallResult.pluck(:patient_id)).to all eq patient.id expect(response).to have_http_status(200) end it "leaves the patient_id nil if the appointment does not exist" do call_results = [build_call_result_payload(build(:call_result, appointment_id: SecureRandom.uuid, patient_id: nil)), build_call_result_payload(build(:call_result, appointment_id: SecureRandom.uuid)).except(:patient_id)] set_authentication_headers post(:sync_from_user, params: {call_results: call_results}, as: :json) expect(CallResult.count).to eq 2 expect(CallResult.pluck(:patient_id)).to all be nil expect(response).to have_http_status(200) end end context "when facility_id is not supplied" do it "sets the facility_id using the header" do patient = create(:patient) appointment = create(:appointment, patient: patient) call_results = [build_call_result_payload(build(:call_result, appointment: appointment, facility_id: nil)), build_call_result_payload(build(:call_result, appointment: appointment)).except(:facility_id)] set_authentication_headers post(:sync_from_user, params: {call_results: call_results}, as: :json) expect(CallResult.count).to eq 2 expect(CallResult.pluck(:facility_id)).to all eq request_facility.id expect(response).to have_http_status(200) end end context "when patient_id is supplied" do it "doesn't override the patient_id if it's supplied already" do patient = create(:patient) other_patient = create(:patient) appointment = create(:appointment, patient: patient) call_results = [build_call_result_payload(build(:call_result, appointment: appointment, patient: other_patient))] set_authentication_headers post(:sync_from_user, params: {call_results: call_results}, as: :json) expect(CallResult.count).to eq 1 expect(CallResult.pluck(:patient_id)).to all eq other_patient.id expect(response).to have_http_status(200) end end context "when facility_id is supplied" do it "doesn't override the facility_id if it's supplied already" do facility = create(:facility) other_facility = create(:facility) appointment = create(:appointment, facility: facility) call_results = [build_call_result_payload(build(:call_result, appointment: appointment, facility: other_facility))] set_authentication_headers post(:sync_from_user, params: {call_results: call_results}, as: :json) expect(CallResult.count).to eq 1 expect(CallResult.pluck(:facility_id)).to all eq other_facility.id expect(response).to have_http_status(200) end end end describe "GET sync: send data from server to device;" do it_behaves_like "a working V3 sync controller sending records" it_behaves_like "a working sync controller that supports region level sync" end end
require "rake" class Link include Rake::DSL def initialize(target, source) @target = target @source = source end def create log { File.symlink(@source, @target) } rescue Exception print "#{@target} already exists. Overwrite? [yn]: " STDIN.gets.chomp == "y" and rm_rf(@target) and retry end def log print "#{@target}: " yield puts "done" end class << self include Rake::DSL def symlinks destinations.zip(sources) end def sources FileList["**/*.symlink"].pathmap(File.expand_path("%p")) end def destinations sources.pathmap(File.expand_path("~/.%n")) end end end Link.symlinks do |target, source| file target => source do Link.new(target, source).create end end task :default => Link.destinations
#!/usr/bin/env ruby -wKU # Bilal Hussain # encoding: UTF-8 require 'optparse' Help = %{Usage: #{File.basename $0} [-t] $regex_match $regex_sub [glob] Example: #{File.basename $0} -t ".*([0-9]+).mp3" "Track \\1.mp3"} options = {excludes:[]}; glob = '*' OptionParser.new do |opts| opts.banner = Help opts.on("-t", "--[no-]test", "Only display the resulting filenames") do |v| options[:test] = v end opts.on( '-e', "--excludes" '--list a,b,c', Array, "Names to Excludes" ) do |l| options[:excludes] = l end end.parse! case ARGV.length when 2; when 3; glob = ARGV[2] else puts "Needs at lest TWO arguments", Help; exit end begin regex = Regexp.new(ARGV[0]) rescue RegexpError => e puts "RegexpError: #{e}"; exit end lamb = if options[:test] then ->(src, dst){ "Testing: #{src}:\t#{dst}" } else ->(src, dst){ File.rename src, dst } end Dir.glob(glob) do |name| next if options[:excludes].include? name dst = name.sub regex, ARGV[1] begin res = lamb[name, dst] res = "#{name}:\t#{dst}" if res == 0 puts res rescue Exception => e puts e end end
class UserResponseCache def initialize(user, question) #get response_options id's for response_options_selections responses = user.response_option_selections .where(:response_option_id => question.response_options.pluck(:id)).select([:id, :response_option_id]) @map = {} responses.each do |r| @map[r.response_option_id] = r.id end end # return this users selections for this response_option def response_for(response_option) @map[response_option.id] end end
class Provider::Admin::CMS::LayoutsController < Provider::Admin::CMS::TemplatesController private def templates current_account.layouts end end
require 'rails_helper' RSpec.describe ShipmentItemsController, type: :controller do let!(:product_1) { FactoryGirl.create :product, sku: '123456' } let!(:product_2) { FactoryGirl.create :product, sku: '654321' } let (:order) do FactoryGirl.create :processing_order, item_attributes: [ { sku: '123456', quantity: 2 }, { sku: '654321', quantity: 1 } ] end let (:order_item_1) do order.items.select{|i| i.sku == product_1.sku}.first end let (:order_item_2) do order.items.select{|i| i.sku == product_2.sku}.first end let (:shipment) { FactoryGirl.create :shipment, order: order } let (:attributes) do { order_item_id: order_item_1.id, external_line_no: 1, shipped_quantity: 2 } end before { order.items.select(&:standard_item?).each{|i| i.acknowledge!} } context 'for an authenticated user' do let (:user) { FactoryGirl.create :user } before { sign_in user } describe "GET #index" do it "returns http success" do get :index, shipment_id: shipment expect(response).to have_http_status(:success) end end describe "GET #new" do it "returns http success" do get :new, shipment_id: shipment expect(response).to have_http_status(:success) end end describe 'POST #create' do it 'creates the shipment item record' do expect do post :create, shipment_id: shipment, shipment_item: attributes end.to change(shipment.items, :count).by(1) end context 'when the order item still has unshipped quantity' do let (:partial_attributes) do attributes.merge shipped_quantity: 1 end it 'updates the item status to "partially shipped"' do expect do post :create, shipment_id: shipment, shipment_item: partial_attributes order_item_1.reload end.to change(order_item_1, :status).from('processing').to('partially_shipped') end end context 'when the order item is completely shipped' do it 'updates the item status to "shipped"' do expect do post :create, shipment_id: shipment, shipment_item: attributes order_item_1.reload end.to change(order_item_1, :status).from('processing').to('shipped') end end context 'when the last item in the order is shipped' do let (:attributes) do { order_item_id: order_item_2.id, shipped_quantity: 1, external_line_no: 2 } end before do shipment.items.create! order_item_id: order_item_1.id, shipped_quantity: 2, external_line_no: 1 end it 'redirects to the order show page' do post :create, shipment_id: shipment, shipment_item: attributes expect(response).to redirect_to order_path(order) end it 'updates the order status to "shipped"' do expect do post :create, shipment_id: shipment, shipment_item: attributes order.reload end.to change(order, :status).to('shipped') end end context 'when the order item is overshipped' do let (:overshipped_attributes) do attributes.merge shipped_quantity: 3 end it 'shows a warning' do post :create, shipment_id: shipment, shipment_item: overshipped_attributes expect(flash[:notice]).to match /more items were shipped than were ordered/ end end context 'when there are still unshipped items in the order' do it 'redirects to the shipment items page' do post :create, shipment_id: shipment, shipment_item: attributes expect(response).to redirect_to shipment_shipment_items_path(shipment) end it 'does not change the order status' do post :create, shipment_id: shipment, shipment_item: attributes order.reload expect(order).to be_processing end end end end context 'for an unauthenticated user' do describe "GET #index" do it 'redirects to the sign in page' do get :index, shipment_id: shipment expect(response).to redirect_to new_user_session_path end end describe "GET #new" do it 'redirects to the sign in page' do get :new, shipment_id: shipment expect(response).to redirect_to new_user_session_path end end describe 'POST #create' do it 'redirects to the sign in page' do post :create, shipment_id: shipment, shipment_item: attributes expect(response).to redirect_to new_user_session_path end it 'does not create a shipment item record' do expect do post :create, shipment_id: shipment, shipment_item: attributes end.not_to change(ShipmentItem, :count) end it 'does not change the status of the order item' do expect do post :create, shipment_id: shipment, shipment_item: attributes order_item_1.reload end.not_to change(order_item_1, :status) end it 'does not change the status of the order' do expect do post :create, shipment_id: shipment, shipment_item: attributes order.reload end.not_to change(order, :status) end end end end
require 'rails_helper' RSpec.describe Event, type: :model do context "Every new event needs" do it(:location) {should_not == nil} it(:event_date) {should_not == nil} end end
require "aethyr/core/actions/commands/command_action" module Aethyr module Core module Actions module Move class MoveCommand < Aethyr::Extend::CommandAction def initialize(actor, **data) super(actor, **data) end def action event = @data.dup room = $manager.get_object(@player.container) exit = room.exit(event[:direction]) if exit.nil? @player.output("You cannot go #{event[:direction]}.") return elsif exit.can? :open and not exit.open? @player.output("That exit is closed. Perhaps you should open it?") return end new_room = $manager.find(exit.exit_room) if new_room.nil? @player.output("That exit #{exit.name} leads into the void.") return end room.remove(@player) new_room.add(@player) @player.container = new_room.game_object_id event[:to_player] = "You move #{event[:direction]}." event[:to_other] = "#{@player.name} leaves #{event[:direction]}." event[:to_blind_other] = "You hear someone leave." room.out_event(event) look_text = new_room.look(@player) out_text = Window.split_message(look_text, 79).join("\n") @player.output(out_text, message_type: :look, internal_clear: true) end end end end end end
Rails.application.routes.draw do namespace :api do # Change URLs to /api/<whatever> resources :locations resources :characters end #Do not place any routes below this one get '*other', to: 'static#index' # For production end
class BrocadeHost < Host has_many :zones, :foreign_key => "host_id", :dependent => :destroy has_many :brocadePorts, :foreign_key => "host_id", :dependent => :destroy def load_switch_ports lines = exec('switchshow').split("\n") self.is_principal = false if m = /switchRole:(.*)/.match(lines[4]) if m[1].strip == 'Principal' self.is_principal = true end end if m = /switchDomain:(.*)/.match(lines[5]) self.domain = m[1].strip end BrocadePort.destroy_all(:host_id => id) self.brocadePorts = [] lines = lines[13..-1] lines.each do |line| items = line.split(' ') port = BrocadePort.new port.index = items[0].to_i port.slot = items[1].to_i port.port = items[2].to_i port.speed = items[5] port.state = items[6] port.type = items[8] if items.size >= 9 port.wwn = items[9] if items.size >= 10 port.brocadeHost = self if (port.wwn) port.save self.brocadePorts << port end end self.save end def create_zone(zone_name, members) zone = Zone.new zone.name = zone_name zone.brocadeHost = self zone.save members.each do |m| member = ZoneMember.new member.zone = zone member.member = m member.save zone.zoneMembers << member end end def load_switch_zones return unless self.is_principal lines = exec('cfgactvshow').split("\n") Zone.destroy_all(:host_id => id) started = false zone_name = '' zone_members = [] lines.each do |line| if !started && line.strip == 'Effective configuration:' started = true next end next unless started if m = /zone:(.*)/.match(line) if zone_name.size > 0 && zone_members.size > 0 create_zone(zone_name, zone_members) zone_members = [] end zone_name = m[1].strip next end zone_members.push(line.strip) if zone_name.size > 0 end if zone_name.size > 0 && zone_members.size > 0 create_zone(zone_name, zone_members) end end end
require './test_helper' require 'google_books' require 'job' ENV['RACK_ENV'] = 'test' class GoogleBooksTest < Test::Unit::TestCase include Rack::Test::Methods def app GoogleBooks end def test_index_should_save_page_to_redis_when_required # by stubbing Redis.get in this case, it simulates a situation without HTTP and Page Caching in place # so this test proves it does cache the require page Redis.any_instance.stubs(:get).returns nil Redis.any_instance.expects(:lpush).with('cached_page_ids', "http://example.org/?page=3") get '/?page=3' assert last_response.ok? end def test_index_should_not_save_page_to_redis_when_cached_page_is_found # No matching ETAG but page already cached Redis.any_instance.expects(:get).with("app:last_updated").returns nil Redis.any_instance.expects(:get).with("http://example.org/?page=3").returns "<html></html>" Redis.any_instance.expects(:lpush).with('cached_page_ids', "http://example.org/?page=3").never get '/?page=3' assert last_response.ok? end def test_css_request_should_save_stylesheet_to_redis_when_required # by stubbing Redis.get in this case, it simulates a situation without HTTP and Page Caching in place Redis.any_instance.stubs(:get).returns nil Redis.any_instance.expects(:lpush).with('cached_page_ids', "http://example.org/styles.css") get '/styles.css' assert last_response.ok? end def test_css_request_should_not_save_stylesheet_to_redis_when_cached_stylesheet_is_found # No matching ETAG but stylesheet already cached Redis.any_instance.expects(:get).with("app:last_updated").returns nil Redis.any_instance.expects(:get).with("http://example.org/styles.css").returns ".main{ margin-top: 50px;} " Redis.any_instance.expects(:lpush).with('cached_page_ids', "http://example.org/styles.css").never get '/styles.css' assert last_response.ok? end end
# Asset route definitions class App < Sinatra::Base # compile haml partials, for angular templating get "/partials/:file" do # path = request.path_info.gsub(/\.html$/, "") + ".haml" path = request.path_info ext = File.extname(path)[1..-1] path = root_path("app", path) if File.exists?(path) content_type :html if (ext == "haml") haml File.read(path), :layout => false elsif (ext == "slim") slim File.read(path), :layout => false end # not found else 404 end end end
class AddDeletedByToLeagueMatchComms < ActiveRecord::Migration[5.0] def change add_column :league_match_comms, :deleted_at, :datetime, null: true add_column :league_match_comms, :deleted_by_id, :integer, null: true, default: nil, index: true add_foreign_key :league_match_comms, :users, column: :deleted_by_id end end
class JobsController < ApplicationController def show @jobs = Job.all respond_to do |format| format.json end end end
class ReviewsController < ApplicationController before_filter :authorize def create @review = Review.new(review_params) @product = Product.find_by(id: params[:product_id]) # after @review has been initialized, but before calling .save on it: @review.user = current_user if @review.save redirect_to product_path(@product) else redirect_to product_path(@product) end end def destroy @product = Product.find_by(id: params[:product_id]) @review = Review.find_by(id: params[:id]) if current_user.id == @review.user_id @review.destroy end redirect_to product_path(@product) end private def review_params review = params.require(:review).permit(:comment, :rating) review[:product_id] = params[:product_id] review end end
class CubedController < ApplicationController def random @number=10 if params[:number].to_i.even? "even" else "odd" end render "random.html.erb" end end
class Tank < GameObject SHOOT_DELAY = 500 attr_accessor :x, :y, :gun_angle, :direction, :sounds, :physics, :throttle_down def initialize(object_pool, input) super(object_pool) @input = input @input.control(self) @physics = TankPhysics.new(self, object_pool) @graphics = TankGraphics.new(self) @sounds = TankSounds.new(self) @direction = rand(0..7)* 45.0 @gun_angle = rand(0..360) @last_shot = 0 end def shoot(target_x, target_y) if Gosu.milliseconds - @last_shot > SHOOT_DELAY @last_shot = Gosu.milliseconds Bullet.new(object_pool, @x, @y, target_x, target_y).fire(100) end end end
class Ability include CanCan::Ability def initialize(user) @user = user if user.is_admin? can [:destroy_all, :destroy, :index, :create, :show], Order can [:mark_availability, :destroy, :index, :create, :show], Item else can [:destroy, :create, :show], Order end end end
class TeamsController < ApplicationController before_action :set_team, only: [:show, :edit, :update, :leave, :destroy] before_action :ensure_that_signed_in # GET /teams # GET /teams.json def index @teams = current_user.recent_teams end # GET /teams/1 # GET /teams/1.json def show end # GET /teams/new def new @team = Team.new end # GET /teams/1/edit def edit end # POST /teams # POST /teams.json def create @team = Team.new(team_params) respond_to do |format| if @team.save @team.users << current_user render_success format, 'created', :created else render_errors format, @team.errors, :new end end end # PATCH/PUT /teams/1 # PATCH/PUT /teams/1.json def update respond_to do |format| if @team.update(team_params) render_success format, 'updated', :ok else render_errors format, @team.errors, :edit end end end # POST /teams/1/leave def leave UserTeam.find_by( user_id: current_user.id, team_id: params[:id] ).destroy if @team.users.count.zero? then @team.destroy end redirect_to teams_path, notice: "You're no longer a member of #{@team.name}" end # DELETE /teams/1 # DELETE /teams/1.json def destroy @team.destroy respond_to do |format| format.html { redirect_to teams_url, notice: 'Team was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_team @team = current_user.teams.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def team_params params.require(:team).permit(:name) end def render_success(format, action, status) format.html { redirect_to @team, notice: "Team was successfully #{action}." } format.json { render :show, status: status, location: @team } end end
require 'rails_helper' RSpec.describe Publisher, type: :model do context "relationships" do it { should have_many :books } end end
module Travel class CLI attr_accessor :api def initialize self.api = API.new end def call puts "welcome user" puts "To see locations for travel, enter 'begin'" puts "To exit the travel program, please enter 'exit'" destination # api.inspect end def destination input = gets.strip.downcase if input == "begin" location_list destination elsif input == "exit" goodbye else invalid_entry end end def location_list puts "" puts "Which destination would you like more details about:" input = gets.strip.downcase location_selection(input) end def location_selection end def goodbye puts "Goodbye, hope we can help with your next journey!" end def invalid_entry puts "Invalid entry, try again" destination end end end
require 'rails_helper' RSpec.describe VariantSerializer do let(:variant) { create(:variant) } let(:expected_serializer_hash) do { waist: variant.waist, length: variant.length, style: variant.style, count: variant.count } end subject(:serializer_hash) do VariantSerializer.new(variant).serializable_hash end it 'includes the waist' do expect(serializer_hash).to eq(expected_serializer_hash) end end
require_relative '_helper' require 'dbp/book_compiler/markdown_to_tex/translator' module DBP::BookCompiler::MarkdownToTex describe Translator, 'token patterns' do let(:scanner) { StringScanner.new(input) } let(:pattern) { Translator::TOKENS[subject] } before do scanner.scan(pattern) end describe :comment do subject { :comment } describe 'against a comment' do let(:content) { ' some comment ' } let(:comment) { "<!--#{content}-->" } let(:input) { "#{comment}additional text" } it 'matches the comment' do _(scanner.matched).must_equal comment end it 'captures the stripped comment content in capture group 1' do _(scanner[1]).must_equal content.strip end end end describe :emphasis do subject { :emphasis } %w(** _).each do |delimiter| describe "against the #{delimiter} delimiter" do let(:input) { "#{delimiter}additional text" } it 'matches the delimiter' do _(scanner.matched).must_equal delimiter end end end end describe :end_tag do subject { :end_tag } describe 'against an end tag' do let(:tag_name) { 'monkeymonkey' } let(:tag) { "</#{tag_name} >" } let(:input) { "#{tag}additional text" } it 'matches the tag' do _(scanner.matched).must_equal tag end it 'captures the tag name in capture group 1' do _(scanner[1]).must_equal tag_name end end end describe :open_tag do subject { :open_tag } describe 'against an open tag with a class attribute' do let(:class_attribute_value) { ' monkey ' } let(:tag_name) { 'mytag' } let(:tag) { %Q{<#{tag_name} class = "#{class_attribute_value}" >} } let(:input) { "#{tag}additional text" } it 'matches the tag' do _(scanner.matched).must_equal tag end it 'captures the tag name in capture group 1' do _(scanner[1]).must_equal tag_name end it 'captures the stripped class attribute value in capture group 2' do _(scanner[2]).must_equal class_attribute_value.strip end end end describe :text do subject { :text } describe 'against a string with no operator characters' do let(:input) { 'a string with no operator characters!@#$%&()-+=' } it 'matches the entire string' do _(scanner.matched).must_equal input end end %w{< * _}.each do |c| describe "against text followed by an operator character #{c}" do let(:text) { 'before the operator character' } let(:input) { "#{text}#{c}after the operator character" } it 'matches the text before the operator character' do _(scanner.matched).must_equal text end end end end describe :void_tag do subject { :void_tag } describe 'against a void tag' do let(:tag_name) { 'mytag' } let(:tag) { "<#{tag_name} />" } let(:input) { "#{tag}additional text" } it 'matches the tag' do _(scanner.matched).must_equal tag end it 'captures the tag name in capture group 1' do _(scanner[1]).must_equal tag_name end end end describe :yaml_header do subject { :yaml_header } let(:yaml) do [ '--- ', 'key1: value1', 'key2: value2', '...', ].join($/) end let(:input) { "#{yaml}additional text"} it 'matches a YAML document' do _(scanner.matched).must_equal yaml end end end end
class SendMessageJob < ApplicationJob queue_as :default def perform(message, user_name) me = ApplicationController.render( partial: 'messages/me', locals: {message: message} ) others = ApplicationController.render( partial: 'messages/others', locals: {message: message} ) ActionCable.server.broadcast "room_channel_#{message.room_id}", me: me, others: others, message: message, username: user_name end end
class ChangeColumntemplabelsBarcodeToText < ActiveRecord::Migration def change change_column :templabels, :barcode, :string end end
require 'rails_helper' describe 'User login', type: :request do let!(:test_user) { create(:user) } context 'Sending valid data' do it 'successfully logs in' do post api_v1_sign_in_path, params: {password: 'partnership'} token = json['token'] expect(response).to have_http_status(:success) end end context 'Sending invalid data' do it 'returns unauthorized status' do login_params = {password: 'invalid' } post api_v1_sign_in_path, params: login_params expect(response).to have_http_status(:unauthorized) expect(json['errors']).to include('Invalid login credentials. Please try again.') end end end
class Cliente < ActiveRecord::Base has_many :qualificacoes validates_presence_of :nome, message: "Nome deve ser preenchido" validates_uniqueness_of :nome, message: "Nome ja cadastrado" validates_numericality_of :idade, greater_than: 0, less_than: 100, message: "Idade deve ser um numero de 0 a 100" end
class Person attr_accessor:name # def name(name) # @name=name # end def speak "Hi, my name is #{@name}." end end class Student < Person def learn "I get it!" end end class Instructor < Person def teach "Everything in Ruby is an Object." end end instructor=Instructor.new instructor.name="Chris" puts instructor.speak student=Student.new student.name="Christina" puts student.speak puts instructor.teach puts student.learn
require 'rails_helper' RSpec.describe EventPolicy, type: :policy do let(:user) { FactoryBot.create(:user) } let(:event) { FactoryBot.create(:event, user: user) } context 'when owner' do subject { described_class.new(user, event) } it { is_expected.to permit_actions(%i[edit update destroy]) } it { is_expected.to permit_actions(%i[index new show create]) } end context 'when not owner' do subject { described_class.new(user2, event) } let(:user2) { FactoryBot.create(:user) } it { is_expected.to forbid_actions(%i[edit update destroy]) } end context 'when not authentificated' do subject { described_class.new(nil, event) } it { is_expected.to forbid_actions(%i[edit update destroy]) } end context 'not subscribe event self' do subject {described_class.new(user, event)} it {is_expected.to forbid_action(:subscribe)} end context 'subscribe other event' do subject {described_class.new(user3, event)} let(:user3) { FactoryBot.create(:user) } it {is_expected.to permit_action(:subscribe)} end end
class DropPostCategoryFromPosts < ActiveRecord::Migration def change remove_column :posts, :post_category_id end end
module RedmineTwitterBootstrap module Helper def nav_list_tag(caption, path) active = 'active' if params[:controller] == path[:controller] and params[:action] == path[:action] content_tag(:li, class: active) do link_to caption, path end.html_safe end def breadcrumb_tag(active, links=[]) content_tag(:ul, class: 'breadcrumb') do links.collect do |link| concat( content_tag(:li) do link_to(link[:caption], link[:path]) << ' ' << content_tag(:span, '/', class: 'divider') end << ' ' ) end concat(content_tag(:li, active, class: 'active')) end.html_safe end def icon_tag(options) if options[:icon] style = "icon-#{options[:icon]}" style << " icon-#{options[:color]}" if options[:color] content_tag(:i, class: style) do end.html_safe end end def icon_button_tag(caption, options={}) options[:class] ||= 'btn' options[:type] ||= 'button' button_tag(class: options[:class], type: options[:type]) do [icon_tag(options), caption].join(' ').html_safe end.html_safe end def link_button_tag(caption, path, options={}, link_options={}) link_options[:class] ||= 'btn' link_options[:class] << " btn-#{options[:action]}" if options[:action] link_options[:class] << " btn-#{options[:size]}" if options[:size] caption = [icon_tag(options), caption].join(' ') link_to caption.html_safe, path, link_options end end end
class RenameEdicaoLivroToBookEdition < ActiveRecord::Migration[6.0] def up rename_column :edicoes_livros, :nome, :name rename_column :edicoes_livros, :numero, :number rename_column :edicoes_livros, :editora, :publisher rename_column :edicoes_livros, :idioma, :language rename_column :edicoes_livros, :num_paginas, :total_pages rename_column :edicoes_livros, :livro_id, :book_id rename_table :edicoes_livros, :book_editions end def down rename_column :book_editions, :name, :nome rename_column :book_editions, :number, :numero rename_column :book_editions, :publisher, :editora rename_column :book_editions, :language, :idioma rename_column :book_editions, :total_pages, :num_paginas rename_column :book_editions, :book_id, :livro_id rename_table :book_editions, :edicoes_livros end end
post '/error' do response['Access-Control-Allow-Origin'] = '*' if params[:url] url_id = Url.rootify_find_create(params[:url]).id end if params[:user_id] begin decoded = Base64.decode64(params[:user_id].encode('ascii-8bit')) decrypted = Encryptor.decrypt(decoded, key: SECRET_KEY) params[:user_id] = decrypted rescue Exception => e $SERVER_LOG.error "handle message error = #{e.message}" $SERVER_LOG.error "handle message error = #{e.backtrace.inspect}" params[:user_id] = nil end else params[:user_id] = nil end error = PageError.create(url_id: url_id, user_id: params[:user_id], os: params[:os], description: params[:description], version: params[:version]) content_type :text "#{error.id}" end post '/error/check/:id' do error = PageError.find_by_id(params[:id]) if error error.update(resolved?: true) content_type :text "Error ##{error.id} taken care of" else content_type :text "Couldn't find error ##{params[:id]}" end end post '/error/:id' do response['Access-Control-Allow-Origin'] = '*' error = PageError.find_by_id(params[:id]) if params[:id] content_type :text if error error.update(description: params[:description]) "Added description to #{error.id}" else url_id = Url.rootify_find_create(params[:url]).id PageError.create(url_id: url_id, user_id: params[:user_id], os: params[:os], description: params[:description], version: params[:version]) "Could not find this error" end end
require "rails_helper" RSpec.describe TeleconsultationMedicalOfficer, type: :model do describe "default scope" do it "contains only users who can teleconsult" do users = [create(:teleconsultation_medical_officer), create(:teleconsultation_medical_officer, teleconsultation_facilities: [])] expect(TeleconsultationMedicalOfficer.all).to contain_exactly users.first end end end
class User < ApplicationRecord devise :authy_authenticatable, :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :confirmable, :lockable, :trackable has_many :profiles, dependent: :destroy has_many :messages, dependent: :destroy has_many :access_grants, class_name: 'Doorkeeper::AccessGrant', foreign_key: :resource_owner_id, dependent: :delete_all has_many :access_tokens, class_name: 'Doorkeeper::AccessToken', foreign_key: :resource_owner_id, dependent: :delete_all has_one :account_digest, dependent: :destroy after_create :generate_default_profiles validate :block_our_domain has_many :referral_codes def tokens Doorkeeper::AccessToken.where(resource_owner_id: id).all end def generate_default_profiles categories = ['Profile #3', 'Profile #2', 'Profile #1'] categories.collect {|title| profiles.create!(name: title) } end def can_create_profile? profiles.count < max_profiles end def referred_by User.find referred_by_id rescue ActiveRecord::RecordNotFound nil end def referred User.where(referred_by_id: id).all end def block_our_domain if !email.include? ENV['SEND_EMAIL_DOMAIN'] false else errors.add(:email, "can't be a local address") end end end
require 'pry' def second_supply_for_fourth_of_july(holiday_hash) holiday_hash[:summer][:fourth_of_july][1] end def add_supply_to_winter_holidays(holiday_hash, supply) holiday_hash[:winter][:christmas] << supply holiday_hash[:winter][:new_years] << supply end def add_supply_to_memorial_day(holiday_hash, supply) holiday_hash[:spring][:memorial_day] << supply end def add_new_holiday_with_supplies(holiday_hash, season, holiday_name, supply_array) holiday_hash[season][holiday_name] = supply_array end def all_winter_holiday_supplies(holiday_hash) holiday_hash[:winter].values.flatten end def all_supplies_in_holidays(holiday_hash) holiday_supplies.each do |season, holiday| puts "#{season.capitalize}:" holiday.each do |holiday_name, supplies| temp_holiday_name = holiday_name.to_s.split("_").map {|word| word.capitalize}.join(" ") temp_supplies = supplies.join(", ") puts " #{temp_holiday_name}: #{temp_supplies}" end end end def all_holidays_with_bbq(holiday_hash) holidays_with_bbqs = [] holiday_supplies.collect do |season, holidays| holidays.collect do |holiday, supplies| if supplies.include?("BBQ") holidays_with_bbqs << holiday end end end return holidays_with_bbqs end
#!/usr/bin/ruby def translateFile(f) infile = File.new(f,"r") lines = [] while (line = infile.gets) unless (line.strip()[0..0]=="#") values = line.strip.split(/\s+/) lines.push "{label:'',val:%i,lat:%.2f,lng:%.2f}" % values end end outfile = File.new("%s.json" % File.basename(f), "w") outfile.puts "celltowers = [" outfile.puts lines.join(",\n") outfile.puts "]" infile.close outfile.close end def printHelp puts " # Translate a mysql file # tower_count lat lng # into json # towers = [{val:tower_count, lat:lat, lng:lng}, {val:tower_count, lat:lat, lng:lng}] # Usage: ruby script_name.rb SoureceFile.dat " end if $0 == __FILE__ if $*.length>0 if $*[0]=="-h" || $*[0]=="--help" printHelp else translateFile($*[0]) end else printHelp end end