text
stringlengths
10
2.61M
class CreateFlurries < ActiveRecord::Migration def change create_table :flurries do |t| t.date :day t.integer :tp #平台 t.integer :a1 #总激活 t.integer :a2 #当天新增 t.integer :a3 #当天活跃 t.integer :a4 #当天运行 t.float :a5 #当天人均运行 t.float :a6 #当天人均在线时长 ...
class BidsController < ApplicationController def create @auction = Auction.find(params[:auction_id]) @item = @auction.items.find(params[:item_id]) @item = Item.find(params[:item_id]) unless logged_in? redirect_to auction_item_path(@auction, @item), notice: "Please log in to make bid" r...
class AddWelcomeMailToChallenges < ActiveRecord::Migration[5.0] def change add_column :challenges, :welcome_mail, :text end end
Sequel.migration do up do create_table(:planes) do primary_key :id String :name end end down do drop_table(:planes) end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Ch...
require "./lib/Lesson 90 Tasks From Indeed Prime 2015 Challenge/LongestPassword/longest_password" describe 'LongestPassword' do describe 'Example Test' do it 'Example' do expect(longest_password("test 5 a0A pass007 ?xy1")).to eq 7 end end describe 'Correctness Tests' do context 'Simple' do ...
# Note: we're looking for Ruby commands for the below questions, not the actual answers, unless it's a question. # # Hint: you can type "irb" in your terminal to get a Ruby console to test things out. For multi-line code, use an editor that can run Ruby code, or copy/paste into irb. # # Hint 2: you can refer to the Ru...
# Stream: 4 # Environment: fntb stream = 4 # (stream 4 is for stress testing in fntb) env = "fntb" # (stream 4 is for stress testing in fntb) require 'rubygems' require 'fileutils' require 'time' class RequestResponse # Will create the appropriate request.xml file for the curl c...
Rails.application.routes.draw do devise_for :people, controllers: { sessions: 'people/sessions', passwords: 'people/passwords', registrations: 'people/registrations' } devise_for :users, controllers: { sessions: 'users/sessions', passwords: 'users/passwords', registrati...
class AddGuestsColumnToLairsTable < ActiveRecord::Migration def change add_column :lairs, :max_guests, :integer, { null: false } end end
describe "ActiveRecord::Base" do before(:each) do class User < ActiveRecord::Base attr_accessor :subdomain end end it "should have validates_subdomain_format_of which runs SubdomainRoutes.valid_subdomain? against the attributes" do User.validates_subdomain_format_of :subdomain SubdomainRout...
Gem::Specification.new do |s| s.name = 'scoop' s.version = '0.0.3' s.date = '2012-07-19' s.summary = "Scoop" s.description = "Gem to connect to SeedTheLearning's Granary api" s.authors = ["Jacqueline Chenault", "Austen Ito", "Jonan Scheffler", "Charles Strahan"] s.email = '...
require 'test_helper' class ConsentFormsControllerTest < ActionDispatch::IntegrationTest setup do @consent_form = consent_forms(:one) end test "should get index" do get consent_forms_url assert_response :success end test "should get new" do get new_consent_form_url assert_response :succ...
class ListsController < ApplicationController before_action :signed_in_user, only: [:index, :create, :show, :destroy] def index @lists = current_user.lists.all @list = List.new if @lists.empty? redirect_to :action => 'new' end end def new @list = List.new end def create @...
class AnswersController < ApplicationController before_action :authenticate_user! before_action :load_answer, only: [:update, :destroy, :choose_the_best] after_action :publish_answer, only: [:create] include Voted authorize_resource def create @answer = question.answers.new(answer_params) @answ...
=begin Problem: Write a method that takes a string, and then returns a hash that contains 3 entries: one represents the number of characters in the string that are lowercase letters, one the number of characters that are uppercase letters, and one the number of characters that are neither. Rephrase: Examples/tests...
class Folder < ActiveRecord::Base has_many :documents, :dependent => :destroy validates_presence_of :name accepts_nested_attributes_for :documents, :reject_if => lambda { |a| a[:attachment].blank? && a[:name].blank?}, :allow_destroy => true named_scope :is_favorite, :conditions => {:is_favorite => true} ...
class UserMailer < ApplicationMailer def user_welcome_mail(user) @user = user mail(to: @user.email, subject: 'Welcome to Our Application!') end end
# == Schema Information # # Table name: games # # created_at :datetime not null # id :integer not null, primary key # state :string # updated_at :datetime not null # require 'rails_helper' describe Game, type: :model do subject { create :game } describe 'validations' do...
require 'json' require 'socket' ethereum_ipc = ARGV[0] transaction_id = ARGV[1] if !ethereum_ipc || !transaction_id puts "Usage: ruby ethtracer.rb ipc_endpoint transaction_id" exit(1) end socket = UNIXSocket.new(ethereum_ipc) request = { method: "debug_traceTransaction", params: [transaction_id, {}], json...
require "application_system_test_case" class StuffsTest < ApplicationSystemTestCase setup do @stuff = stuffs(:one) end test "visiting the index" do visit stuffs_url assert_selector "h1", text: "Stuffs" end test "creating a Stuff" do visit stuffs_url click_on "New Stuff" fill_in "De...
class CreateAlogos < ActiveRecord::Migration def change create_table :alogos do |t| t.integer :aproduct_id t.string :path t.timestamps end end end
class CoachingOffer < ApplicationRecord belongs_to :user has_many :bookings, dependent: :destroy has_many :reviews, dependent: :destroy include PgSearch validates :user, :platform, :hourly_rate, presence: true validates :platform, inclusion: { in: ["PC", "PS4", "XBOX 360"], case_sensitive: false } valida...
module HomesHelper include UsersHelper include AssetsHelper include ImagesHelper RECENT_SIZE=5 def home_description_text simple_format(auto_link(Seek::Config.home_description.html_safe,:sanitize=>false),{},:sanitize=>false) end def show_guide_box? Seek::Config.guide_box_enabled && ((!logged_i...
class Activity < ActiveRecord::Base belongs_to :activity_type validates_presence_of :description, :credit end
Naptanapi.controllers :routes do get :index, :provides => [:html, :json] do page_size = 100 if params[:page].to_i >0 page = params[:page].to_i else page = 1 end case content_type when :html if params[:route] @routes = Route.find({'route' => params[:route]}, {:li...
require "fog/core/model" module Fog module Compute class Brkt class WorkloadTemplate < Fog::Model module State PUBLISHED = "PUBLISHED" DRAFT = "DRAFT" SAVED = "SAVED" end # @!group Attributes identity :id attribute :name attrib...
class UsersController < ApplicationController def favourite post = Post.find_by_id(params[:id]) current_user.toggle_favourite(post) render :nothing => true end end
Gem::Specification.new do |s| git_files = `git ls-files`.split("\n") s.name = 'algebrick' s.version = File.read(File.join(File.dirname(__FILE__), 'VERSION')) s.date = Time.now.strftime('%Y-%m-%d') s.summary = 'Algebraic types and pattern matching for Ruby' s.descr...
#! /usr/bin/env ruby ############################################################################## DIR = File.dirname($0) $: << File.join(DIR, 'lib') ############################################################################## require 'getoptlong' require 'process_species_name' ###############################...
class AddDemographicsToCharacters < ActiveRecord::Migration def change add_column :characters, :race, :string add_column :characters, :culture, :string add_column :characters, :costume, :integer add_column :characters, :costume_checked, :date add_column :characters, :history_approval, :boolean ...
module Helpers def user_roles [:end_user, :agent, :admin] end def http_status_text(status) case status when 200 then "OK" when 201 then "Created" when 204 then "No Content" when 400 then "Bad Request" when 401 then "Unauthorized" when 403 then "Forbidden" ...
class BookingsController < ApplicationController before_action :set_cheval, only: [:show, :create, :edit, :update, :destroy] before_action :set_booking, only: [:show, :edit, :update, :destroy, :validate, :refuse, :cancel] def show unless current_user.profile == @booking.profile || current_user.profile == @b...
Rails.application.routes.draw do scope :api , defaults:{format: :json } do resources :states, except:[:new,:edit] resources :cities, except:[:new,:edit] end get '/ui' => 'ui#index' get '/ui#' => 'ui#index' root 'ui#index' end
class ReportReasonController < ApplicationController def create user = @user board = Board.find(params[:board]) if user.perm("change_rules", board.url) reason = ReportReason.new reason.name = params[:name] reason.description = params[:description] reason.board = board if reas...
class News < ApplicationRecord has_many :taggings has_many :tags, through: :taggings, dependent: :destroy def all_tags=(names) self.tags = names.split(",").map do |name| Tag.where(name: name.strip).first_or_create! end end def all_tags self.tags.map(&:name).join(", ") end def self.tag...
# frozen_string_literal: true module GraphQL module Language # Exposes {.generate}, which turns AST nodes back into query strings. module Generation extend self # Turn an AST node back into a string. # # @example Turning a document into a query # document = GraphQL.parse(quer...
class CreateGoods < ActiveRecord::Migration[5.2] def change create_table :goods do |t| t.datetime :created_at, null: false t.string :title t.string :name t.string :nickname t.boolean :seller t.string :property_type t.string :location t.string :tel t.str...
# frozen_string_literal: true class ChangeGlicemyType < ActiveRecord::Migration[5.2] def change change_column :measurements, :glicemy, :integer, limit: 2 end end
class ChatroomsController < ApplicationController before_action :logged_in? before_action :get_chatroom, only: [:show, :destroy] def new @chatroom = Chatroom.new @user_races = User.find(session[:user_id]).get_races.uniq end def index @public = Chatroom.public_rooms ...
require 'spec_helper' require 'aws-sdk-resources' require 'sham_rack' require 'sham_s3' describe ShamS3::App do let(:sham_s3_hostname) { "sham-s3.example.com" } before do ENV["RACK_ENV"] = "test" ShamRack.prevent_network_connections ShamRack.at(sham_s3_hostname).mount(sham_s3_app) end after do ...
class ProductsController < ApplicationController before_action :authenticate_admin!, except: [:index, :show, :search] def index if params[:sort_attribute] @products = Product.order(:price) elsif params[:search] @products = Product.all.where("name ILIKE ?", "%#{params[:search]}%") elsif pa...
require './test/test_helper' class GeneratorTest < Minitest::Test def setup @enigma = Enigma.new @random_date = Time.now.strftime("%d%m%y") end def test_alphabet assert_equal ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", ...
FactoryBot.define do factory :idea do title { Faker::Coffee.blend_name } description { Faker::Coffee.notes } association(:user, factory: :user) end end
class Beer < ActiveRecord::Base belongs_to :brewery belongs_to :style mount_uploader :image, BeerUploader end
class UserNotification < ActiveRecord::Migration def change add_column :users, :wants_notifications, :boolean, :default => true add_column :users, :notification_language, :string add_index "users", "notification_language" add_index "users", "wants_notifications" create_table "notifications", :for...
class AnnotationsController < ApplicationController before_filter :admin_required, :only => [:audit, :valid, :invalid, :curate] before_filter :load_annotation, :only => [:curate, :predicate, :destroy] def index set_ontology_dropdown @query = params[:query] ? Regexp.escape(params[:query]) : "" page =...
class V1::PacksController < ApplicationController def index paginate json: user.packs, per_page: 3, include: 'effects, effects.*' end def show render json: pack, include: 'effects, effects.*' end private def pack params[:id] == 'latest' ? user.latest_pack : Pack.find(params[:id]) end ...
require 'rails_helper' RSpec.describe 'Projects show page' do it "shows all name, material, and challenge theme for a particular project" do recycled_material_challenge = Challenge.create(theme: "Recycled Material", project_budget: 1000) news_chic = recycled_material_challenge.projects.create(name: "News Ch...
require 'pry' class String def sentence? self.end_with?('.') end def question? self.end_with?('?') end def exclamation? self.end_with?('!') end def count_sentences squeezed = self.squeeze('?.!') squeezed.count('.?!') end end "This, well, is a sentence. This is too!! And so is t...
# find primes between two numbers # 1. iterate through the number num1..num2 # 2. select numbers that are divisible by 1 with a remainder of 0, and itself with a remainder of 0 # 3. # iterate through numbers, checking to see if require 'pry' def prime(num1, num2) original_array = (num1..num2).to_a (num1..num2)...
Date::DATE_FORMATS[:ordinalized] = lambda do |date| date.strftime("%B %-d").sub(/\d+/) do |day| day.to_i.ordinalize end end
require 'starcraft' module Starcraft class Ladder attr_reader :ladder_name, :ladder_id, :division, :rank, :league, :type, :wins, :losses, :showcase, :teams, :characters, :mmq, :id def initialize end def full_ladder id # data = JSON.parse(File.read("lib/#{id}.json")) data = JSON.parse(R...
class ListenController < ApplicationController def index # grab eight hours worth of schedule, starting now @schedule = ScheduleOccurrence.block(Time.now, 8.hours) # grab our homepage stories @homepage = Homepage.published.first render layout: false end end
class Api::AlbumResource < Api::BaseResource attribute :description attribute :title has_one :person has_many :images end
namespace :dojo do desc 'Update Dojo git repository.' task :update do DOJO_ROOT = File.join(RAILS_ROOT, 'vendor', 'dojo') Dir[File.join(DOJO_ROOT, '*')].each do |dir| sh %{cd "#{dir}" && git svn rebase && git gc} end end namespace :use do desc 'Use individual development script files.' ...
class Post attr_accessor :author, :title, :name def initialize(title,author = nil) @title = title @author = author end def author_name self.author.name if @author end end
#encoding: UTF-8 require "spec_helper" require "body_part_migrator" describe BodyPartMigrator, "#perform" do before(:each) do if Trip.count == 0 create(:trip) end @trip = Trip.first end it "converts a left knee case to expected string values" do bp_model = BodyPart.create!(:name_en => "...
# frozen_string_literal: true require 'simplecov' SimpleCov.start require 'minitest/autorun' require 'minitest/emoji' require './lib/transaction_repository' require './lib/transaction' # Transaction Repository class tests class TransactionRepositoryTest < Minitest::Test def setup @transrepo = TransactionRepos...
module Zebra class CheckWordPresentError < StandardError def initialize(e) super(e) warn "WARNING: commit aborted due to presence of #{e.length} blacklisted words" e.each do |error| warn "Found #{error.first.inspect} in #{error.last.first.filename}:#{error.last.first.lineno}" en...
class RatingsController < ApplicationController expose_decorated :post, find_by: :slug expose :rating before_action :authorize_resource def create rating.save end private def rating_params params.require(:rating).permit(:point).merge(user: current_user, post: post) end def authorize_resou...
class Api::V1::AttributeOptionsController < ApplicationController include Response def index @attribute_options = AttributeOption.all render json: { records: @attribute_options.as_json(root: false), methods: [] } # render json: { records: @attribute_options.as_json(root: false), methods: [], count: @at...
class Film # ------------------------------------------------------------------- # Sous-classe Film.Structure # ------------------------------------------------------------------- class Structure # Instance du film attr_reader :film def initialize film @film = film end d...
class Api::KioskController < Api::ApiController before_action :authenticate def get_company_info record = Company.find params[:sugar_id] status = record.nil? ? 404 : 200 record = confirm_mod_date(record, params[:modified_after]) resp = status == 200 ? {company: record.try(:kiosk_payload), status:s...
class AddEmailsToUsers < ActiveRecord::Migration def change add_column :users, :emails, :string, array: true, default: [], null: false end end
class CreateHours < ActiveRecord::Migration[5.2] def change create_table :hours do |t| t.integer :weekly_hours, default: 12 t.integer :max_hours, default: 15 t.timestamps 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が空だと登録できない" do @user.nickname = '' @user.valid? expect(@user.errors.full_messages).to include("Nickname can't be ...
class FaqsController < ApplicationController skip_before_filter :redirect_to_welcome def index redirect_to I18n.t(:desk_dot_com_url) end private end
def iterative_factorial(n) (1..n).inject(:*) end puts iterative_factorial(6) def recursive_factorial(n) # Base case return 1 if n <= 1 # Recursive call n * recursive_factorial(n-1) end puts recursive_factorial(6) # fibonacci # def fib(n) # return n if n < 2 # fib(n-1) + fib(n-2) # end # memoization...
require File.dirname(__FILE__) + '/../spec_helper' describe 'TwitterSearchTags' do dataset :pages describe '<r:twitter search="twitter" />' do it 'should render something' do tag = '<r:twitter search="twitter" />' expected = 'nothing' pages(:home).should render(tag).as(expected) e...
FactoryGirl.define do factory :task do user name { Faker::Lorem.word } description { Faker::Lorem.sentence } state { Task::STATES.sample } attachment { Rack::Test::UploadedFile.new(File.join(Rails.root, 'public', 'robots.txt')) } end end
require('minitest/autorun') require('minitest/rg') require_relative("../board.rb") require_relative("../tile.rb") class TestBoard < MiniTest::Test def setup() @tiles = (1..100).to_a() @board = Board.new(@tiles) end def test_board_has_100_positions assert_equal(100, @board.tiles.length) end ...
class ComponentTypesController < ApplicationController def index @componenttypes = ComponentType.paginate(page: params[:page]) end def show @componenttype = ComponentType.find(params[:id]) @components = Component.find_all_by_component_type_id(params[:id]) end end
class Event < ApplicationRecord has_many :event_users has_many :invited, through: :event_users, foreign_key: :user_id, source: :user has_many :comments, as: :commentable, dependent: :destroy has_attached_file :main_image, styles: { thumbnail: "60x60#" }, default_url: "#{...
class Book < ApplicationRecord belongs_to :user validates :body, length: {maximum:200}, presence: true validates :title, presence: true end
json.set! @post.id do json.id @post.id json.body @post.body json.user_id @post.user_id json.channel_id @post.channel_id json.created_at @post.created_at end
# Using Pry for debugging purposes. require 'pry' # Method works similar to #find, as it returns the first element in the array that # evaluates to true, not the return value itself. # Therefore, the return value will be set as a conditional. # In other words, the program will yield to a block with the given argument...
class Libdca < Formula desc "Library for decoding DTS Coherent Acoustics streams" homepage "https://www.videolan.org/developers/libdca.html" url "https://download.videolan.org/pub/videolan/libdca/0.0.5/libdca-0.0.5.tar.bz2" sha256 "dba022e022109a5bacbe122d50917769ff27b64a7bba104bd38ced8de8510642" bottle do ...
class Photo < ApplicationRecord belongs_to :album #has_many :comments, :as => :commentable has_many :comments, as: :commentable validates :name, presence: true validates :image, attachment_presence: true has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images...
# Find the sum of all the multiples of 3 or 5 below 1000. class ModulosSum def initialize(base) @base = base end def get_sum puts "Sum of #{@base}" mods = get_modulos() return mods.sum end def get_modulos mods = [] (1..@base-1).each do |i| if is_mod(i, 3) || is_mod(i, 5) ...
require 'helper' describe Resolver::DataMapper do subject { Resolver::DataMapper.new(mapping) } # entites let(:foo) { faked_class('Foo').new } let(:bar) { faked_class('Nested::Bar').new } # data mapper FooDataMapper = Class.new(Store::DataMapper) BarDataMapper = Class.new(Store::DataMapper) let(:ma...
module Smtp class EmailAddresses < Array def initialize(addresses) super addresses.split(', ').map { |e| EmailAddress.new(e) } end end end
describe Repositories::Interactors::CreatePullRequest do describe '.call' do subject(:interactor_result) do described_class.call(project: project) end let(:content_translated_file) do <<~CONTENT { "reserve": "Reserve", "users": "Users", "games": "Games", ...
class CordesController < ApplicationController # ログインしていない場合、top画面のみ表示 before_action :authenticate_user!,except: [:index] # gem kaminari使用のため #top画面 def index @cordes = Corde.page(params[:page]).per(18) end def new @corde = Corde.new end def show @corde = Corde.find(params[:id]) end ...
class Aluno #reader: attr_reader e writers: attr_writer e se um msm item deve permitir ambos: attr_accessor attr_accessor :nome, :telefone, :matricula def initialize(nome, telefone, matricula) @nome = nome @telefone = telefone @matricula = matricula end end
require 'spec_helper' describe :work_document do before :each do @work_document = Factory.create(:work_document) end it "Should create a valid work_document from an eaf fixture" do @work_document.should be_valid end describe "States" do context "waiting" do it "should be marked as ...
class EditContacts < ActiveRecord::Migration[5.0] def change remove_column :contacts, :user_id add_column :contacts, :user_id, :integer, :null => false, :unique => true end end
class PostsController < ApplicationController before_action :load_post, only: [:show] def index @posts = Post.all end def new @post = Post.new end def show end def create @post = Post.new(title: params[:post][:title], body: params[:post][:body]) if @post.sav...
class CompanySerializer < ActiveModel::Serializer attributes :id, :name, :staff_count, :schedule has_many :employees end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html scope 'api' do resources :users, :only =>[:create] resources :wallets, :only =>[:create] do get ':email/', to: 'wallets#list', on: :collection,constraints: { email: /[^...
require 'rails_helper' require 'apicall' RSpec.feature "Admin can view all gifs" do scenario "they can see all gifs sorted by category" do APICall.stub(:image_path) { "https://media.giphy.com/media/7e0EvlBD7nxZu/giphy.gif" } create_and_stub_admin categories = %w(funny silly crazy).map do |category| ...
# Euler Problem 36 # Solution by Kyle Owen and Alexander Leishman July 7, 2013 # Problem Text: # The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. # Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. # (Please note that the palindromic number, ...
class CreatePosts < ActiveRecord::Migration[6.0] def change create_table :posts do |t| t.string :title t.integer :bestanswer_reward t.string :source_url t.string :state, default: :accepting t.text :body t.text :code t.timestamps t.string :user_id end add_for...
class Feed include DataMapper::Resource property :id, Serial property :created_at, DateTime property :peep, Text belongs_to :user end
module Refinery module Tenants class Tenant < Refinery::Core::BaseModel self.table_name = 'refinery_tenants' attr_accessible :name, :logo_id, :position, :broker_ids, :is_exclusive_tenant acts_as_indexed :fields => [:name] validates :name, :presence => true, :uniqueness => true be...
require 'test_helper' class PeopleControllerTest < ActionController::TestCase setup do @person = people(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:people) end test "should get new" do get :new assert_response :success end te...
FactoryGirl.define do factory :consult_category, class: ConsultManagement::ConsultCategory do name 'test-name' description 'test-description' end end
class AudiobooksController < ApplicationController http_basic_authenticate_with name: "aim", password: ENV['STREAM_PASSWORD'] def show @current = find_content end def stream @audio = find_content send_file @audio.full_path, content_type: :'audio/mpeg' end def ...
require 'spec_helper' describe Pipejump::Contact do before do @session = PipejumpSpec.session @contact = @session.contacts.create(:name => 'contact1'+uuid) end after do @contact.destroy end describe "#custom_fields" do it "returns a hash of custom fields" do @contact.custom_fields['...
require_relative './config/routes' Dir[File.join('.', 'controllers/*.rb')].each do |controller| require controller end class Server def start clear_terminal show_instructions request = {} until request[:path] == 'quit' print '[URL] https://www.microweb.com/' request = { path: gets.chom...