text stringlengths 10 2.61M |
|---|
# frozen_string_literal: true
module GraphQL
module StaticValidation
module FragmentsAreOnCompositeTypes
def on_fragment_definition(node, parent)
validate_type_is_composite(node) && super
end
def on_inline_fragment(node, parent)
validate_type_is_composite(node) && super
en... |
#! /usr/bin/env ruby
#
require 'set'
def pick(number_count, upper_limit)
raise 'Upper limit must be >= the number to pick' if number_count > upper_limit
prng = Random.new
choices = Set[]
while choices.length < number_count do
choices.add 1 + prng.rand(upper_limit)
end
choices.sort
end
if __FILE__==$... |
class EventsController < ApplicationController
respond_to :html
before_filter :authenticate_speaker!, only: [:new, :create, :edit, :update]
before_filter :authenticate_school!, only: [:approve, :unapprove]
def index
current_member = current_speaker || current_school
@own_events = current_member.events... |
class OrganizationsController < ApplicationController
before_action :authenticate,:current_user
before_action :set_organization, only: [:show, :edit, :update, :destroy,
:finish_check, :set_user]
# GET /organizations
# GET /organizations.json
def index
@organiza... |
class AddAudioToSongs < ActiveRecord::Migration
def change
add_attachment :songs, :audio
end
end
|
class AddFieldAndDeleteOther < ActiveRecord::Migration
def change
remove_column :bids, :actual_bid
add_column :products, :actual_price, :integer
end
end
|
module Korekto
class Heap
def initialize(limit)
@limit = limit
@combos = (0...limit).to_a.combination(2)
.sort{|ij, kl| ij[0]**2 + ij[1]**2 <=> kl[0]**2 + kl[1]**2}
.map{|i, j| [[i,j], [j,i]]}
.inject([]){|a, ij_kl| a<<ij_kl[0]; a<<ij_kl[1]}
@a = []
end
def to_a
@a
end
def ... |
feature "Testing infrastructure" do
scenario 'Can run app and check page content' do
visit('/')
expect(page).to have_content 'THE BLACK LODGE'
end
scenario "Players can enter their names that are then displayed on screen" do
sign_in_and_play
expect(page).to have_content 'ALM'
expect(page).to ... |
class Admins::CakesController < Admins::BaseController
before_action :set_cake, only: [:show, :edit, :update, :destroy, :undo_delete]
# GET /cakes
# GET /cakes.json
def index
@cakes = Cake.with_deleted.order(deleted_at: :desc, id: :desc).includes(:item)
.page(params[:page])
.per(params[:per])
... |
# Letter Counter (Part 1)
# Write a method that takes a string with one or more space separated words and returns a hash that shows the number of words of different sizes.
# Words consist of any string of characters that do not include a space.
def word_sizes(str)
hsh = {}
# split up each word in the string to a ... |
=begin
* Modelo de la tabla MaterialType de la base de datos
* @author rails
* @version 14-10-2017
=end
class MaterialType < ApplicationRecord
has_many :products
validates :name, format: {with: /\A[a-zA-Z ]+\p{Latin}+\z/, message: "El nombre solo puede contener letras"}, length: { maximum: 50 }, presence: true
... |
require File.join(File.expand_path(File.dirname(__FILE__)), "..", 'test_helper')
class RoutesControllerTest < ActionController::TestCase
setup do
@route1 = routes(:one)
@route2 = routes(:two)
@stop1 = route_stops(:one)
@stop2 = route_stops(:two)
end
test "should get index" do
get :index,... |
json.array!(@schedules) do |schedule|
json.extract! schedule, :day, :content
json.url schedule_url(schedule, format: :json)
end |
# -*- mode: ruby -*-
# vi: set ft=ruby et:
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "debian/stretch64"
config.vm.network :forwarded_port, guest: 80, host: 8080
config.vm.synced_folder '.', '/vagrant', disabled: true
config.vm.provider "virtualbox" d... |
class User < ApplicationRecord
devise :omniauthable, :omniauth_providers => [:facebook]
has_many :reviews
has_many :orders, dependent: :destroy
has_many :credit_cards, dependent: :destroy
has_one :address
has_one :user_shipping,
-> { where addressable_type: 'shipping_address' },
cl... |
class User < ActiveRecord::Base
has_many :applications
has_many :user_roles
has_many :roles, through: :user_roles
has_one :company
has_secure_password
validates_presence_of :username
validates_presence_of :password, if: :new_record?
validates_uniqueness_of :username
has_one :address
validates_conf... |
require_relative 'account_history'
class Account
attr_reader :balance
def initialize(history = AccountHistory.new)
@balance = 0
@account_history = history
end
def deposit(amount)
check_valid(amount)
@balance += amount
@account_history.log_deposit(amount, @balance)
end
def withdraw(amo... |
require 'byebug/command'
require 'byebug/helpers/parse'
module Byebug
#
# Implements the step functionality.
#
# Allows the user the continue execution until the next instruction, possibily
# in a different frame. Use step to step into method calls or blocks.
#
class StepCommand < Command
include Hel... |
class Admin::JobsController < Admin::ResourceController
before_filter :find_job, :except => [:index, :new, :create]
model_class Job
def index
@jobs = Job.all
end
def new
@job = Job.new
end
def create
@job = Job.new(params[:job])
if @job.save
flash[:notice] = 'Job créé.'
redi... |
#!/usr/bin/env ruby
# fls - a mix of find(1) and ls(1)
# TODO: xdev, stat caching
require 'find'
require 'etc'
require 'optparse'
class Reversed < Struct.new(:object)
def <=>(other)
-(self.object <=> other.object)
end
end
sort = "N"
fmt = "%p%_%l%_%u%_%g%_%h%_%m%_%n" # roghly, ls -lha
maxdepth = nil
exclud... |
class Station
def initialize(name, zone)
@station = {name: name, zone: zone}
end
def name
@station[:name]
end
def zone
@station[:zone]
end
end
|
class ManageIQ::Consumption::ShowbackEvent < ApplicationRecord
belongs_to :resource, :polymorphic => true
has_many :showback_charges, :dependent => :destroy
has_many :showback_buckets, :through => :showback_charges
validates :start_time, :end_time, :resource, :presence => true
validate :start_time_before_... |
class CreateMyFavoriteRecipes < ActiveRecord::Migration
def change
create_table :my_favorite_recipes do |t|
t.integer :food_item_id
t.integer :hola_user_id
t.timestamps
end
end
end
|
FactoryGirl.define do
factory :group do
name { Faker::Cat.name }
created_at { Faker::Time.between(2.days.ago, Date.today, :all)}
end
end
|
# frozen_string_literal: true
class HomeController < PrivateController
def index
@recent_nippos = Nippo
.where.not(sent_at: nil)
.order(sent_at: :desc)
.limit(100)
@notification_from_admins = Notification::FromAdmin.for_display
end
end
|
class Holiday < ActiveRecord::Base
validates_date :date
validates_numericality_of :trip_offset, :only_integer => true
def self.offset date
holiday = Holiday.find_by_date date
return (holiday ? holiday.trip_offset : 0)
end
def to_s
"Holiday: " + date.to_s + " " + trip_offset.to_s + " " + comment... |
Rails.application.routes.draw do
mount Higan::Engine => "/higan"
end
|
$:.unshift File.join(File.dirname(__FILE__), "..", "lib")
require 'appscale_tools'
require 'test/unit'
class TestAppScaleRunInstances < Test::Unit::TestCase
def setup
EC2_ENVIRONMENT_VARIABLES.each { |var|
ENV[var] = "BOO"
}
file = flexmock(File)
file.should_receive(:exists?).and_return(true... |
require_relative 'spaceship'
describe Spaceship do
let(:spaceship_1) { Spaceship.new("USS Enterprise (NCC-1701)", 671000000)}
it "disables the shields is false" do
expect(spaceship_1.disable_shield).to be false
end
it "enables the shields is true" do
expect(spaceship_1.enable_shield).to be true
end
it "ha... |
class UsersController < ApplicationController
before_action :logged_in_user, except: [:create]
before_action :correct_user, only: [:show, :edit, :update]
before_action :is_liang, only: [:index]
#
def index
@users = User.all
end
def show
@user = User.find(params[:id])
end
def dashboard
@u... |
class UserMailer < ApplicationMailer
default :from => 'liptiavenica@gmail.com'
def send_signup_email()
mail(:to => 'ninikcancer.tgl@gmail.com', :subject => 'Welcome to My Awesome Site')
end
end
|
require "spec_helper"
describe "View ranking", :type => :request do
before do
visit root_path
click_link "Ranking"
end
it "redirects to the ranking page" do
expect(current_path).to eql(ranking_path)
end
it "displays the Top 5 title" do
expect(page).to have_content("Top 5")
end
end
|
class User < ApplicationRecord
has_many :clips
validates :name, presence: true
validates :email, presence: true
validates :provider, presence: true
validates :oauth_uid, presence: true
# todo reflect this constraint in a migration
## add_index :table_name, [:field1, ... , :fieldn], unique: true
valid... |
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def self.search(search)
if search
Product.where(['product_name LIKE ?', "%#{search}%"])
else
Product.all
end
end
end |
Rails.application.routes.draw do
devise_for :users, controllers: { registrations: 'registrations' }
root to: 'pages#home'
resources :vehicules do
resources :bookings, only: [:new, :create, :update, :destroy]
resources :reviews, only: [ :new, :create ]
end
get '/profile', to: 'pages#profile'
get "v... |
class Gmp < Package
desc "GNU multiple precision arithmetic library"
homepage "https://gmplib.org/"
url "https://gmplib.org/download/gmp/gmp-${version}.tar.xz"
release version: '6.1.2', crystax_version: 1
build_options use_cxx: true,
ldflags_in_c_wrapper: true
build_copy 'COP... |
class Notification < ActiveRecord::Base
belongs_to :user
belongs_to :notable, polymorphic: true
validates :title, :message, :user, presence: true
# Marks a notification as "read" using its status field.
#
def mark_as_read
self.update(read: true)
end
def self.notify_comment_created (comment, curr... |
class MessageTemplatesController < ApplicationController
before_filter :validate_edit_sms_template , :only=>[:new_message_template, :save_message_template, :edit_message_template, :update_message_template, :delete_message_template]
filter_access_to :all
def message_templates
@tempalte_edit_setting = Mu... |
# frozen_string_literal: true
module BPS
module PDF
class Roster
class Detailed
module Directory
def directory
users = User.for_roster
users.each_slice(6) do |page|
formatted_page do
directory_page(page)
end
... |
# frozen_string_literal: true
module J8
class Optional
include J8::Common
def initialize(value = nil)
@value = value
end
def self.empty
J8::Optional.new
end
def self.of(value)
raise J8::NilException if value.nil?
J8::Optional.new(value)
end
def self.of_nil... |
require "test_adventure/version"
module TestAdventure
class Error < StandardError; end
# Your code goes here...
def load_dependencies
rbfiles = File.join(__dir__,"**", "*.rb")
Dir.glob(rbfiles).each do |file|
require_relative file
puts "loaded #{file}"
end
end
def load_files(dir)
... |
class UsersController < ApplicationController
rescue_from ActiveRecord::RecordNotFound, with: :redirect_to_root
def show
params.require(:id)
@user = User.find(params[:id])
@project_list = Project.where(user_id: @user.id)
end
private
def redirect_to_root
redirect_to :root
end
end
|
class AddOrderToPeople < ActiveRecord::Migration
def change
add_column :people, :order, :integer
end
end
|
class FormSubmission < ActiveRecord::Base
belongs_to :form
belongs_to :user
serialize :response
if FedenaSetting.elasticsearch_enabled? and self.connection.table_exists? 'form_submissions'
searchkick :index_name => "#{table_name}_#{Rails.configuration.database_configuration[RAILS_ENV]['database']}_#{RAI... |
require 'spec_helper'
describe ImageProcessor do
let(:s3_bucket) { AppConstants::S3_BUCKET }
let(:s3_cover_images_path) { AppConstants::S3_COVER_IMAGES_PATH }
let(:cdn_book_url) { AppConstants::CDN_BOOK_URL }
let(:image_qualities) { [100,90] }
let(:image_filters) { [:unsharp_mask, :no_op] }
let(:test_cases... |
class MediaController < ApplicationController
include Mediable
prepend_before_action :authenticate_user_with_basic_auth!
before_action :set_doi
before_action :set_media, only: [:show, :destroy]
def index
response = MediaController.list_media(@doi, username: username, password: password)
if response... |
# ================================================================================
# Part:
# Desc:
# ================================================================================
class Winner
include Mongoid::Document
include Mongoid::Timestamps
include Ownerable
# ... |
class Api::V1::CustomersController < ApplicationController
def index
customers = Customer.all
if !params[:q]&.empty?
customers = Customer.where('name ilike ?', "%#{params[:q]}%")
.or(Customer.where('email ilike ?', "%#{params[:q]}%"))
.or(Customer.wher... |
require 'spec_helper'
describe RecyclingCentersController do
before(:each) do
Rails.cache.clear
end
context 'with no admin logged in' do
it 'redirects index' do
get :index
response.should be_redirect
end
it 'renders show' do
rc = FactoryGirl.create(:recycling_center)
get... |
class AssessmentGroupsController < ApplicationController
before_filter :login_required
filter_access_to :all
require 'lib/override_errors'
helper OverrideErrors
before_filter :fetch_courses, :only => [:new_course_exam, :create_course_exam]
check_request_fingerprint :create, :update
def new
pa... |
class Stop
attr_reader(:line, :station, :id)
define_method :initialize do |attributes|
@line = attributes.fetch(:line)
@station = attributes.fetch(:station)
@id = attributes.fetch(:id)
end
define_method :save do
result = DB.exec("INSERT INTO stops (station_id, line_id) VALUES (#{@station.id}, #... |
require 'fission-package-builder'
module Fission
module PackageBuilder
module Formatters
# Format payload for packagecloud
class Packagecloud < Fission::Formatter
# Origin of payload
SOURCE = :package_builder
# Destination of payload
DESTINATION = :packagecloud
... |
class UserDishesController < ApplicationController
skip_before_filter :authorize, :only => [ :create ]
# POST /user_dishes
# POST /user_dishes.xml
def create
dish = Dish.find(params[:user_dish])
respond_to do |format|
if dish
session[:user_dish] = params[:user_dish]
session[:use... |
class PostsController < ApplicationController
def index
@post = Post.new
3.times { @post.post_images.build }
end
def create
if @post = Post.create(post_params)
redirect_to posts_path
else
@post = Post.new
3.times { @post.post_images.build }
render 'index'
end
en... |
# shorten.rb
# Inspired by Leah Culver, my first Ruby/Sinatra app
# using the metamark.net REST API
# by Max Clark (http://github.com/maxclark)
require 'rubygems'
require 'sinatra'
require 'net/http'
url = URI.parse('http://metamark.net/api/rest/simple')
get '/' do
# Form for entering a fatty URL
<<-end_form
<... |
class Users::RegistrationsController < Devise::RegistrationsController
before_filter :configure_permitted_parameters
def new
redirect_to root_path
end
def create
redirect_to root_path
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:account_update) do |u|
... |
module Slickr
# Behaviors give entities the ability to do things. They should
# implement the logic to move around the world, detect collision,
# etc.
#
# A behavior should not care about what entities use it. It should
# specify all the attribute and methods relevant to what it does.
#
# module Spat... |
module Api::V1::Agents
class SessionsController < AgentUsersController
include Serializable
skip_before_action :disable_access_by_tk, only: [:create]
before_action :set_agent, only: [:create]
def create
if @user&.valid_password?(params[:agent][:password])
if @user.acquire_access_token!
... |
module QBIntegration
module Service
class Customer < Base
attr_reader :order
def initialize(config, payload)
super("Customer", config)
@order = payload[:order] || payload[:invoice] || payload[:credit_memo] || payload[:refund] || {}
@customer = payload[:customer] || @order[:cu... |
require 'yaml'
require 'rexml/document'
def create_node(parentnode, text)
el = parentnode.add_element('node')
el.add_attribute 'CREATED', Time.new.to_i*1000
el.add_attribute 'MODIFIED', Time.new.to_i*1000
el.add_attribute 'TEXT', text
el
end
def add_node(node, root)
if root.respond_to? :keys
root.e... |
# frozen_string_literal: true
require 'client'
describe 'SMTPサーバーの設定' do
before(:example) do
@client = Jiji::Client.instance
end
it 'GET /settings/smtp-server/status でステータスを取得できる' do
r = @client.get('/settings/smtp-server/status')
expect(r.status).to eq 200
expect(r.body['enable_postmark']).to ... |
json.array!(@entry_item_lines) do |entry_item_line|
json.extract! entry_item_line, :id, :entry_item_id, :subject_id, :direction, :amount
json.url entry_item_line_url(entry_item_line, format: :json)
end
|
require "spec_helper"
describe VraptorScaffold::Runner::Scaffold do
before(:all) do
@help = VraptorScaffold::Runner::Help
@runner_scaffold = VraptorScaffold::Runner::Scaffold
end
it "should print help command" do
@help.stub!(:help).with("--help").and_return true
ScaffoldGenerator.should_receive... |
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'httpalooza/version'
Gem::Specification.new do |spec|
spec.name = "httpalooza"
spec.version = HTTPalooza::VERSION
spec.authors = ["Quin Hoxie"]
spec.email = ["... |
class UsuariosController < ApplicationController
before_filter :authenticate, :only => [:index]
# POST /foto
# TODO: Esse método pode ficar mais lógico se o id do dia vier na url, por exemplo
# POST /foto/:id
def foto
require 'base64'
require 'json'
ajax_params = JSON.parse(params[:ajax_params])
... |
require 'spec_helper'
module SalarySummary
module Builders
describe TableBuilder do
let(:repository) { double(:repository) }
let(:salary_1) { double(:salary, month: 'January', year: 2016, amount: 200.0) }
let(:salary_2) { double(:salary, month: 'February', year: 2016, amount: 250.0) }
... |
# To change this template, choose Tools | Templates
# and open the template in the editor.
class WhitelabelSetting < AdditionalSetting
SETTING_FIELDS = [:company_name,:company_url]
end
|
require 'game_of_life'
describe Game do
let(:game){Game.new(100,100)}
it 'can be initialized with an array with empty strings' do
expect(game.board.flatten[0]).to eq ''
expect(game.board.flatten.count).to eq 10000
end
it 'can create a living cell on the array' do
game.populate([1,1])
expec... |
require 'test_helper'
class BookItemsControllerTest < ActionDispatch::IntegrationTest
setup do
@book_item = book_items(:one)
end
test "should get index" do
get book_items_url
assert_response :success
end
test "should get new" do
get new_book_item_url
assert_response :success
end
te... |
# coding: utf-8
module Kaede
class Program < Struct.new(:pid, :tid, :start_time, :end_time, :channel_name, :channel_for_syoboi, :channel_for_recorder, :count, :start_offset, :subtitle, :title, :comment)
def self.from_xml(doc)
doc.xpath('//progitem').map do |item|
prog = self.new
prog.pid = ... |
class AddNameToBillingaddress < ActiveRecord::Migration[6.0]
def change
add_column :billingaddresses, :first_name, :string
add_column :billingaddresses, :last_name, :string
end
end
|
# frozen_string_literal: true
module LogProcessor
module Formatter
# uniq views formatter
class Uniq < Base
FORMATTER = 'unique views'
end
end
end
|
class Post < ActiveRecord::Base
# has_attached_file :photo,
# :storage => :s3,
# :s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
# :path => ":attachment/:id/:style.:extension",
#:bucket => '8th_Light_Blog'
has_attached_file :photo,
#...
:storage ... |
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# password :string(128)
# created_at :datetime
# updated_at :datetime
#
class User < ActiveRecord::Base
# TODO: Validate this is an email!
validates :emai... |
module Selectize::Ajax
module ViewHelpers
def selectize_ajax_tag(resource, field, options = {})
control = Selectize::Ajax::Core::Control.new(resource, field, options)
script = Selectize::Ajax::Core::Script.new(control).call
render 'selectize_ajax/tag', control: control, script: script
end
... |
class RevampTables < ActiveRecord::Migration
def change
create_table :courses do |t|
t.string :description
t.string :price
t.string :user_id
t.string :subject_id
t.string :level
end
remove_column :rooms, :title
remove_column :rooms, :price
remove_column :rooms, :des... |
# frozen_string_literal: true
require 'factory_bot'
FactoryBot.define do
factory :event do
name { 'Event name' }
date { Date.current.noon + 1.day }
end
factory :ticket do
event
ticket_type { 'avoid_one' }
price { 100 }
end
factory :reservation do
event
user
end
facto... |
def ca_install_path(name = '')
install_path = case node[:platform]
when 'ubuntu', 'debian'
'/usr/local/share/ca-certificates/'
when 'redhat', 'centos', 'fedora'
'/etc/pki/ca-trust/source/anchors/'
end
File.join(install_... |
module MItamae
module ResourceExecutor
class File < Base
def apply
if desired.exist
if !current.exist && !@temppath
run_command(["touch", attributes.path])
end
change_target = @modified ? @temppath : attributes.path
if desired.mode
ru... |
require 'test_helper'
class WritersControllerTest < ActionController::TestCase
def setup
@writer = Writer.create!(email: 'new-writer@artsymail.com')
sign_in(@writer)
end
test 'renders an edit form' do
get :edit, id: @writer.to_param
assert_response :ok
end
test 'does not render a form for a... |
class CreateRequestedPokemons < ActiveRecord::Migration[5.0]
def change
create_table :requested_pokemons do |t|
t.integer :natdexnum
t.string :form
t.integer :min_level
t.integer :max_level
t.boolean :shiny
t.string :gender
t.string :ability
t.string :nature
... |
require 'test_helper'
class ReviewTest < ActiveSupport::TestCase
setup do
@review = reviews(:one)
@song = songs(:one)
end
test 'should not save empty review' do
review = Review.new
review.save
refute review.valid?
end
test 'should save valid review' do
review = Review.new
review.r... |
require 'ostruct'
module Advisor
module Advices
describe CallLogger do
subject(:advice) do
described_class.new(
object, method, args, logger: logger, with: tag, result: result
)
end
let(:object) { OpenStruct.new(id: 42, x: 'y') }
let(:method) { 'the_meaning_of_l... |
class NotesController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
def index
@notes = Note.all
end
def new
@note = Note.new
end
def create
@note = current_user.notes.build(note_params)
if @note.sav... |
require_relative 'test_helper'
require_relative '../lib/deck'
class DeckTest < Minitest::Test
def test_instance_of
card_1 = Card.new(question: "What is the capital of Alaska?", answer: "Juneau")
card_2 = Card.new(question: "The Viking spacecraft sent back to Earth photographs and reports about the surface o... |
class Addcpadefault < ActiveRecord::Migration
def change
change_column :menus, :cpa_period, :integer , :default => 1
end
end
|
require 'codeclimate-test-reporter'
CodeClimate::TestReporter.start
SimpleCov.start
require 'backpack_tf'
require 'webmock/rspec'
RSpec.configure do |config|
config.default_formatter = 'doc' if config.files_to_run.one?
end
def generate_fake_api_key
hex_nums = %w(0 1 2 3 4 5 6 7 8 9 a b c d e f)
key = ''
24.t... |
class MoodsController < ApplicationController
def create
# TODO: Fix flash messaging.
@mood = current_user.moods.build(mood_params)
if @mood.color
Mood.set_color(@mood.name, @mood.color)
end
if @mood.save
redirect_to usermood_url(current_user)
else
redirect_to usermood_ur... |
package "vim"
template "/etc/profile.d/sandbox.sh" do
source "sandbox.erb"
mode 0644
end
|
###
# Used by shiv
# A very basic controller handler that allows restarting and reloading on the fly..
class ControllerHandler < RackWelder
def initialize ( log, cfg, roundhouse )
@logger = log
@REMOTE_IP_TAG="HTTP_X_FORWARDED_FOR"
@cfg = cfg #cfg..
setup_access_list(cfg["controller"... |
class ChangeVoteSizeToVoteSum < ActiveRecord::Migration
def change
remove_column :answers, :vote_size
remove_column :questions, :vote_size
remove_column :users, :vote_size
add_column :answers, :vote_sum, :integer, default: 0
add_column :questions, :vote_sum, :integer, default: 0
end
end
|
puts "計算をはじめます"
puts "何回繰り返しますか?"
input = gets.to_i
i = 1
while i <= input do
puts "#{i}回目の計算"
puts "2つの値を入力してください"
a = gets.to_i
b = gets.to_i
puts "a=#{a}"
puts "b=#{b}"
puts "計算結果を出力します"
puts "a+b=#{a + b}"
puts "a-b=#{a - b}"
puts "a*b=#{a * b}"
puts "a/b=#{a / b}"
i += 1
end
puts "計算... |
class Customers::ReservationsController < ApplicationController
before_action :set_restaurant, only: [:show, :create]
before_action :set_reservation, only: [:show, :cancel]
def index
@reservations = policy_scope [:customer, Reservation]
end
def show
@reservation = current_customer.reservations.where... |
class RenameListIdToTaskListIdOfTasks < ActiveRecord::Migration
def self.up
rename_column :tasks, :list_id, :task_list_id
end
end
|
class ResearchUnit < ActiveRecord::Base
has_many :cohorts
validates_presence_of :name, :message => "in new research unit can't be blank"
def desc
[name,leader,location].compact.join(' - ')
end
alias :where_to_search :desc
end
|
Spree::Admin::OrdersController.class_eval do
def shipstation_export
order = Spree::Order.find_by_number(params[:id])
if Spree::ShipstationManager.new(:export_order, order: order, disable_error_handling: true).success?
flash[:success] = Spree.t(:shipstation_export_successful)
else
flash[:error... |
class Race
#This class handles the racing logic
MAX_LAPS = "4"
def initialize(lines)
@lines = lines
@players = Hash.new
@finished = Hash.new
# @first = ""
end
def mount
@lines.each do |line|
if (line != nil)
(time, code, name, l... |
describe UserDelegate do
describe "Associations" do
it { should belong_to(:assignee) }
it { should belong_to(:assigner) }
end
describe "Validations" do
it { should validate_presence_of(:assignee) }
it { should validate_presence_of(:assigner) }
it "validates that there is only one record for ... |
require 'van'
describe Van do
describe '#dock' do
it 'raises an error when full' do
subject.capacity.times do
subject.dock double :bike
end
expect { subject.dock double(:bike) }.to raise_error 'Van is full'
end
end
end |
require 'spec_helper'
describe User do
before do
@valid_attrs = {
username: 'matt',
password: 'password'
}
end
describe "hashed_password" do
it "should be set after saving the user" do
user = User.new(@valid_attrs)
user.hashed_password.should be_nil
user.save!
user.hashed_password.should_n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.