text stringlengths 10 2.61M |
|---|
class CreateCustomerIdCardPictures < ActiveRecord::Migration
def change
create_table :customer_id_card_pictures do |t|
t.string :file_name
t.binary :file_raw
t.string :customer_type
t.integer :customer_id
t.string :content_type
t.integer :user_id
t.timestamps null: false... |
require 'spec_helper'
describe MDS::Responses::ShippingSKUAck do
subject { described_class.new(body) }
let(:body) do
Hash.from_xml(xml)["ROOT"]
end
let(:xml) do
'<ROOT>
<Order>
<OrderID>R123</OrderID>
<OrderShipDate>4/19/2014</OrderShipDate>
<ServiceType>FedEx Sm... |
class CreateKeybords < ActiveRecord::Migration[6.0]
def change
create_table :keyboards do |t|
t.integer :user_id, null: false
t.string :name, null: false
t.jsonb :keys, null: false, default: {}
end
add_index(:keyboards, %i[user_id name], unique: true)
end
end
|
class SessionsController < ApplicationController
before_action :ensure_logged_in, only: [:destroy]
def new
@user = User.new
end
def create
@user = User.find_by_credentials(user_params[:email], user_params[:password])
if @user
login!(@user)
render js: "window.location = '/'"
else
... |
# config valid only for Capistrano 3.1
lock '3.2.1'
set :application, ''
set :repo_url, 'git@github.com:'
set :deploy_to, '/tmp/airt-server'
set :scm, :git
set :branch, :master
set :format, :pretty
set :keep_releases, 5
set :rbenv_type, :system # :system or :user
set :rbenv_ruby, '2.1.2'
set :rbenv_prefix, "RBENV_R... |
class CreateAccounts < ActiveRecord::Migration[5.1]
def change
create_table :accounts do |t|
t.date :start_date, null: false
t.integer :months_number, default: 1
t.decimal :total, precision: 10, scale: 2, default: 0.0
t.integer :flat_id, null: false
t.ti... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "debian/stretch64"
config.vm.hostname = "cloudmigration.dev"
config.vm.network "private_network", ip: "192.168.33.123"
config.ssh.forward_agent = true
config.vm.sy... |
require "runner"
require "pry"
require 'pry-nav'
describe Run do
describe "attributes" do
subject do
Run.new(:distance => 2,
:duration => 30.2,
:timestamp => "02/27/2018")
end
it { is_expected.to respond_to(:distance) }
it { is_expected.to respond_to(:duration)... |
#!/usr/bin/env ruby
require "yaml"
require "tmpdir"
VERSION = /^refs\/tags\/v(\d+(\.\d+)*)$/
Dir.mktmpdir do |dir|
cred_file = File.join(dir, ".git-credentials")
`touch #{cred_file}`
`chmod 600 #{cred_file}`
File.write cred_file, "https://mosop:#{ENV["MOSOP_GITHUB_ACCESS_TOKEN"]}@github.com\n"
Dir.mktmpdir ... |
require 'spec_helper'
shared_examples "systemd" do
context 'with default values ' do
it { should contain_file('/lib/systemd/system/nexus.service') }
it { should contain_service('nexus').with(
'ensure' => 'running',
'enable' => true,
) }
end
end
shared_examples "initd" do
it { should conta... |
class Badge < ActiveRecord::Base
attr_accessible :description, :image, :name, :restriction
belongs_to :restriction, :dependent => :destroy
accepts_nested_attributes_for :restriction
end
|
module Larvata::Signing
class ResourceRecord < ApplicationRecord
if ENV['ENUM_GEM'] == 'enum_help'
STATES = [:pending, :signing, :rejected, :implement, :archived]
else
STATES = {"pending" => "0", "signing" => "1", "rejected" => "2", "implement" => "3", "archived" => "4"}
end
enum state: S... |
# -*- encoding : utf-8 -*-
require 'net/http'
require 'net/https'
require 'uri'
module OpenPayU
class Connection
def self.post(url, data, headers)
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true if OpenPayU::Configuration.use_ssl?
request = Net::HTTP::P... |
require 'rails_helper'
feature 'reviewing' do
before { Restaurant.create(name: 'KFC', description: 'Nasty chicken') }
scenario 'user can click add review link and leave a review' do
visit '/restaurants'
click_link 'Review KFC'
fill_in 'Thoughts', with: 'Far too greasy for my taste'
select '3', fr... |
# frozen_string_literal: true
require 'jiji/test/test_configuration'
require 'jiji/utils/requires'
require 'jiji/model/trading/restart_examples'
describe 'バックテストの停止と再開のテスト' do
let(:long_sleep_time) { 7 }
let(:short_sleep_time) { 5 }
before(:example) do
@backtest_repository = container.lookup(:backtest_rep... |
require 'base64'
require 'digest/sha1'
require 'color'
module GeoPattern
class Pattern
DEFAULTS = {
:base_color => '#933c3c'
}
PATTERNS = %w[
octogons
overlapping_circles
plus_signs
xes
sine_waves
hexagons
overlapping_rings
plaid
triangles
... |
class AddUniqueConstraintToIntent < ActiveRecord::Migration[5.1]
def change
add_index(:intents, [:intentname, :agent_id], unique: true)
end
end
|
require 'rails_helper'
RSpec.describe Spend, type: :model do
# validations
describe 'validations' do
it {should validate_presence_of(:points_req)}
end
end
|
require 'sinatra/base'
module Sinatra
module StandardAPI
Rabl.register!
def self.included(base)
base.extend ClassMethods
end
def multiple_models_get(model_class, template)
protected!
@collection = params[:ids].split(",").collect do |id|
return 404 if !model_class.exists?(id.strip... |
class FeaturesController < ApplicationController
SORT_MAP = {
1 => "name"
}
##
#Get user_group list except an user_group of Administrator
#Parameters::
# * (Integer) *iDisplayLength*: number of row per page
# * (Integer) *iDisplayStart*: starting number
# * (Integer) *iSortCol_0*: locate of sort c... |
module Editor::Controllers::Document
# This code is called restfully by Javascript,
# ajaxs $.post. See javascripts/editor.js
class JsonUpdate
include Editor::Action
expose :active_item
def call(params)
redirect_if_not_signed_in('editor, document, JsonUpdate')
id = request.env['REQUEST_... |
require 'rest-client'
require 'json'
class TranslateServiceYandex
def initialize(lang_src,lang_dst,text)
@language = "#{lang_src}-#{lang_dst}"
@text = text
@key = "trnsl.1.1.20190119T104230Z.77f633d2d53a0031.ec4be61e8296f3ce425c154283e00ddaae58a1f8"
end
def translate
begin
translate_a... |
module Contributors
class ZipGenerator
include Interactor
delegate :data, to: :context
def call
dir = "#{Rails.root}/public/pdf/"
zipfile_path = "#{Rails.root}/public/zip/all.zip"
File.delete(zipfile_path) if File.exist?(zipfile_path)
data.map do |contributor|
contribut... |
class AddDefaultToRanking < ActiveRecord::Migration
def change
rename_column :players, :ranking, :rating
change_column :players, :rating, :integer, :default => 1000
end
end
|
describe Elevate::Callback do
describe "#call" do
describe "on the main thread" do
it "invokes the block within the provided context" do
callback = Elevate::Callback.new(self, lambda { |v| @value = v })
callback.call(42)
@value.should == 42
end
end
describe "on a back... |
require_relative 'player'
class Game
attr_reader :player1, :player2, :player_turn, :winner
def self.create(player1, player2)
p 'creating new game...'
@game = Game.new(Player.new(player1), Player.new(player2))
end
def initialize(player1, player2)
@player1 = player1
@player2 = player2
@pl... |
require 'test_helper'
class PetCategoriesControllerTest < ActionController::TestCase
setup do
@pet_category = pet_categories(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:pet_categories)
end
test "should get new" do
get :new
assert_... |
class HoursController < ApplicationController
before_action :set_hour, only: [:show, :update, :destroy]
# GET /hours
def index
@hours = Hour.all
render json: @hours
end
# GET /hours/1
def show
render json: @hour
end
# POST /hours
def create
@hour = Hour.new(hour_params)
if @ho... |
#!/usr/bin/env ruby -w
require 'fileutils'
require 'optparse'
include FileUtils
def main(source,destination,checkout_dir)
checkout_dotfiles(source,checkout_dir)
if dotfiles_symlinked?(checkout_dir,destination)
STDERR.puts "error: dotfiles already set up in #{destination}"
1
else
symlink_dotfiles(ch... |
# frozen_string_literal: true
module WasteExemptionsShared
module OrganisationTypes
unless defined? TYPES_DISPLAY_LIST
TYPES_DISPLAY_LIST = [WasteExemptionsShared::OrganisationType::Individual,
WasteExemptionsShared::OrganisationType::LimitedCompany,
... |
class Computer < ApplicationRecord
belongs_to :customer
has_many :mining_histories, dependent: :destroy
end
|
#https://www.codeeval.com/open_challenges/158/
class InterruptedBubbleSort
def initialize(line)
@line = line
end
def bubble_sort
arr = @line.chomp.split(' ').map(&:to_i)
iteration = arr.pop
arr.pop
iteration.times do
sorted = true
(1...(arr.length)).each do |i|
if arr[i-1... |
# frozen_string_literal: true
require 'rails/generators'
require 'rails/generators/named_base'
require_relative 'core'
module Graphql
module Generators
# TODO: What other options should be supported?
#
# @example Generate a `GraphQL::Schema::RelayClassicMutation` by name
# rails g graphql:mutatio... |
class Stormpath::Resource::Organization < Stormpath::Resource::Instance
include Stormpath::Resource::CustomDataStorage
prop_accessor :name, :description, :name_key, :status, :account_store_mappings,
:default_account_store_mapping, :default_group_store_mapping
prop_reader :created_at, :modified_at
has_man... |
class Good < ApplicationRecord
belongs_to :measure_unit
belongs_to :good_type
belongs_to :donation
#belongs_to :address
end
|
require_relative '../commands'
require 'dry-validation'
class Commands::ClearBitmap
def initialize(state:, args: nil)
@state = state
validate!
end
def run()
n = @state.size.to_i
m = @state.map(&:size).first.to_i
Array.new(n, Array.new(m, 'O'))
end
private
def validate!
validation... |
class AddImageUrlAndThumbnailUrlToAdAccountCreative < ActiveRecord::Migration
def change
add_attachment :ad_account_creatives, :image
add_attachment :ad_account_creatives, :thumbnail
end
end
|
require_relative '../test_helper'
class SchemeTest < Test::Unit::TestCase
setup do
@obj = Scheme.new
end
def test_eval1
exp = [:+, 1, 2]
assert_equal 3, @obj._eval(exp, $global_env)
end
def test_eval2
exp = [:+, [:+, 1, 2], 3]
assert_equal 6, @obj._eval(exp, $global_env)
end
def te... |
require 'rails_helper'
RSpec.describe SessionsController, type: :controller do
render_views
describe "GET #new" do
before {get :new}
context "Fonctionne bien" do
it {expect(response).to have_http_status(:success)}
it {expect(response.body).to have_title("identifier")}
end
end
... |
class Relationship < ApplicationRecord
belongs_to :user
validates :follower_id, presence: true
validates :followee_id, presence: true
end
|
# encoding: utf-8
#
# © Copyright 2013 Hewlett-Packard Development Company, L.P.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
#... |
# frozen_string_literal: true
module GeoPattern
module StructureGenerators
class PlusSignsGenerator < BaseGenerator
private
attr_reader :square_size, :plus_size, :plus_shape
def after_initialize
@square_size = map(hex_val(0, 1), 0, 15, 10, 25)
@plus_size = square_size * 3
... |
require_relative 'validation_exception'
class MinLength
attr_reader :field, :min_length
def initialize(field, params)
@field = field
min_length = params.pop
raise 'Не указана минимальная длина' if min_length.nil?
@min_length = min_length
end
def validate(value)
raise ValidationException... |
class TimeSlot < ActiveRecord::Base
has_many :location_times
has_many :movies, through: :location_times
has_many :locations, through: :location_times
validates :name, presence: true
# returns the total staff needed for a particular time slot
#
# returns an Integer
def num_staff_needed
sum =... |
#encoding: utf-8
class Taggle < Botpop::Plugin
include Cinch::Plugin
match(/!tg (.+)/, use_prefix: false, method: :exec_tg)
HELP = ["!tg [nick]"]
CONFIG = config(safe: true) || {}
ENABLED = CONFIG['enable'].nil? ? true : CONFIG['enable']
NTIMES = CONFIG['ntimes'] || 10
WAIT = CONFIG['wait'] || 0.3
d... |
class Category < ActiveRecord::Base
has_many :post_categories
has_many :posts, :through => :post_categories, :dependent => :destroy
attr_accessible :description, :title
end
|
class CatalogController < ApplicationController
include Hydra::Catalog
include Hydra::Controller::ControllerBehavior
# This filter applies the hydra access controls
before_action :enforce_show_permissions, only: :show
def self.uploaded_field
solr_name('system_create', :stored_sortable, type: :date)
en... |
module Chandler
class GitHub
Error = Class.new(StandardError)
class InvalidRepository < Error
def initialize(repository)
@repository = repository
end
def message
"Failed to find GitHub repository: #{@repository}.\n"\
"Verify you have permission to access it. Use the... |
class RecipeCategory < ActiveRecord::Base
belongs_to :recipe
belongs_to :category
validates :category_id, presence: true
validates :recipe_id, presence: true
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
describe 'valdations' do
it { should validate_presence_of :email }
it { should validate_presence_of :provider }
it { should validate_presence_of :token }
it { should validate_presence_of :uid }
end
describe 'relationships' do
it { s... |
require 'spec_helper'
describe SessionsController, :type => :controller do
describe "GET new" do
it "renders the new template" do
get :new
response.should render_template("new")
end
end
describe "POST create" do
before(:each) do
@user = create(:user, :password => "correct",... |
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
layout :layout_by_resource
helper CategoriesHelper
helper AuthHelper
helper FlashHelper
helper LayoutHelper
... |
require 'rake/tasklib'
require 'pathname'
class AnyenvSetupTask < Rake::TaskLib
def initialize(name)
@name = name
@anyenv_tasks = []
@anyenv_home = Pathname.new(File.expand_path('~/.anyenv'))
define
end
private
def define
namespace :anyenv do
define_install_anyenv
define_inst... |
class User < ActiveRecord::Base
# relationship to slog posts. if user is destroyed then post is destroyed
# well. cascading relationship (deletions)
has_many :slogs, dependent: :destroy
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :... |
#
# Copyright (C) 2015 Red Hat, Inc.
#
# Author: Martin Magr <mmagr@redhat.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... |
# == Schema Information
#
# Table name: curated_collections
#
# id :integer not null, primary key
# content :text
# title :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# cover_image :string(255) not null
# published_at :datet... |
# -*- coding: utf-8 -*-
module BrowsingSupport
module WordsHelper
QUERY_TEXT_LIST = [
['あ行', 'あ い う え お ぁ ぃ ぅ ぇ ぉ'],
['か行', 'か き く け こ が ぎ ぐ げ ご'],
['さ行', 'さ し す せ そ ざ じ ず ぜ ぞ'],
['た行', 'た ち つ て と だ ぢ づ で ど っ'],
... |
# {{project_name}} vagrant configuration
num_slaves = 4
boxname = 'bento/ubuntu-14.04'
ram = 256
cpus = 1
base_ip = '172.16.1.'
nodes = Array.new
for i in 0..num_slaves do
node = Hash.new
node[:box] = boxname
node[:ram] = ram
node[:cpus] = cpus
if i == 0
node[:hostname] = 'masterpi'
... |
class CreateLocations < ActiveRecord::Migration
def change
create_table :locations do |t|
t.float :latitude, null: false
t.float :longitude, null: false
t.string :address, null: false
t.string :sub_address, null: false, default: ''
t.string :name, null: false
t.text :info, null... |
## --- BEGIN LICENSE BLOCK ---
# Copyright (c) 2017-present WeWantToKnow AS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to... |
require File.dirname(__FILE__) + '/../test_helper'
class PersonTest < Test::Unit::TestCase
fixtures :people, :locations, :memos, :bbs_memos, :interested_people
def test_association_location
assert_kind_of(Person, people(:user1))
assert_kind_of(Location, people(:user1).location)
end
def test_associat... |
# frozen_string_literal: true
module GraphQL
class Schema
class Member
module HasAstNode
def self.extended(child_cls)
super
child_cls.ast_node = nil
end
def inherited(child_cls)
super
child_cls.ast_node = nil
end
# If this sch... |
# == Schema Information
#
# Table name: users
#
# id :bigint(8) not null, primary key
# email :string default(""), not null
# encrypted_password :string default(""), not null
# reset_password_token :string
# reset_password_sent_at :datetime
# r... |
require 'helper'
require 'chrono/server'
class TestServer < MiniTest::Unit::TestCase
include Rack::Test::Methods
def app
Chrono::Server
end
def test_default
get '/'
assert last_response.body =~ /Chrono - Application Metrics/
end
def test_metrics_push
load('foo_bar')
end
def ... |
module OrdersHelper
# Creates an HSL representation of an order's due date. Orders are green up
# until two weeks from the due date, when they begin to turn yellow, orange,
# and red.
#
def color order
hue = [[(order.due - Date.today).to_f / 14.0 * 75 + 25, 100].min, 25].max
saturation = "100%"
l... |
module Auto::JobModule
STATE_WAITING = "waiting"
STATE_RUNNING = "running"
STATE_CANCELED = "canceled"
STATE_DONE = "done"
CATEGORY ="category_"
DONE=" state = 'done' "
STATES = {STATE_WAITING => "排队中",
STATE_RUNNING => "执行中",
STATE_DONE => "已完毕",
STATE_CANCELED => "已取消"}.with_... |
class LinkedList
attr_accessor :head, :tail
def initialize
@head = nil
@tail = nil
end
def append(node)
if @head.nil?
@head = node
@tail = node
else
@tail.next_node = node
@tail = node
end
end
def prepend(node)
if @head.nil?
@head = node
@tail =... |
require 'student_directory2'
describe "Student Directory TDD Project" do
let(:student) {{name: "Eddie", cohort: :June, hobby: "snowboarding"}}
it "prints the header using p" do
expect(self).to receive(:p).with("The students of Makers Academy\n=======================================")
print_header
end
... |
require 'spec_helper'
describe House do
let(:house) {House.new("74 Bellevue Street","Malden",29388,600000)}
describe ".new" do
it "should create a new house object" do
expect(house).to be_a(House)
end
it "should have an address" do
expect(house.address).to eq("74 Bellevue Street")
end
... |
require 'rack-rabbit/signals'
require 'rack-rabbit/subscriber'
require 'rack-rabbit/handler'
require 'rack-rabbit/adapter'
module RackRabbit
class Worker
#--------------------------------------------------------------------------
attr_reader :config, # provided by the Server
:logger, ... |
cask 'expresso' do
version '1.3.0'
sha256 '683e9084f1448e03b959c7256933108c6f486e0e06e608ef3b678e651b8357b2'
conflicts_with formula: 'expresso'
url "https://github.com/sttz/expresso/releases/download/#{version}/expresso-#{version}-osx64.zip"
name 'expresso'
homepage 'https://github.com/sttz/expresso/'
... |
require 'rails_helper'
RSpec.describe Member, type: :model do
it { is_expected.to validate_presence_of(:name) }
it { is_expected.to have_many(:member_projects) }
it { is_expected.to have_many(:projects).through(:member_projects) }
end
|
class Comment < ApplicationRecord
belongs_to :place
belongs_to :user
after_create :send_comment_email
RATINGS = {
'one star': '1_star',
'two stars': '2_stars',
'three stars': '3_stars',
'four stars': '4_stars',
'five stars': '5_stars'
}
def humanized_rating
RATINGS.invert[self.rating]
end
def send_comment_email
No... |
require_relative '../spec_helper'
require 'model/life_visualizer'
describe LifeVisualizer do
subject { LifeVisualizer.new }
let (:model) { SampleLifeModel.new(5, 8) }
it "should return a 5 line string" do
subject.to_display_string(model).count("\n").should == 5
end
it "should return '*' for ali... |
RSpec.describe RequestCreateService do
let(:workflow) { create(:workflow, :groups => [create(:group)]) }
subject { described_class.new(workflow.id) }
context 'without auto approval' do
it 'creates a request' do
request = subject.create(:name => 'req1', :requester => 'test', :content => 'test me')
... |
class AddOrchNameEnToOrchestras < ActiveRecord::Migration
def change
add_column :orchestras, :orch_name_en, :string
end
end
|
class AlterTableUpdatesDropConstraintFkUpdatesUserId < ActiveRecord::Migration
def up
execute <<-SQL
ALTER TABLE updates DROP CONSTRAINT IF EXISTS fk_updates_user_id;
SQL
end
def down
end
end
|
require 'rubygems'
require 'sinatra'
require "sinatra/config_file"
require 'sinatra/namespace'
require 'newrelic_rpm'
require 'opentok'
require 'mongo_mapper'
require 'json'
require 'aescrypt'
require 'bcrypt'
require 'json-schema'
require 'rufus-scheduler'
require 'redis'
require 'logster'
require 'pry'
require 'sucke... |
class ApplicationController < ActionController::Base
include AuthenticatedSystem
include ApplicationMethods
include CreateHelper
include TabFilter
helper_method :current_semester, :get_semester
helper :all
protected
def current_semester
Semester.now
end
def get_semester
semester = params[:s... |
class Forum < ActiveRecord::Base
belongs_to :section
has_many :topics
has_many :subforums, :class_name => 'Forum', :foreign_key => :is_subforum
def last_topic(id)
@topic = Topic.order(lastpost_date: :desc).where(forum_id: id).first(1)
end
end
|
class AddColumnCaptionBottomToSlide < ActiveRecord::Migration
def change
add_column :slides, :caption_bottom, :string
end
end
|
module Vcard
# Exception used to indicate that data being decoded is invalid, the message
# should describe what is invalid.
class InvalidEncodingError < StandardError; end
# Exception used to indicate that data being decoded is unsupported, the message
# should describe what is unsupported.
#
# If its u... |
module FontHelper
def faction_icon(faction_name)
case faction_name
when 'First Order'
'firstorder'
when 'Galactic Empire'
'empire'
when 'Rebel Alliance'
'rebel'
when 'Resistance'
'rebel-outline'
when 'Scum and Villainy'
'scum'
when 'Gala... |
class DestroyShelfTray
prepend SimpleCommand
def initialize(tray_id)
@tray_id = tray_id
end
def call
delete_tray_from_shelf
end
private
def delete_tray_from_shelf
tray = Tray.find(@tray_id)
tray.delete
end
end
|
# Represents a user account in the system
#
# auth_token::
# phone_number::
# uuid::
# public_key::
# private_key::
class User < ActiveRecord::Base
# Relations
has_many :spots
# Validations
validates :auth_token, :phone_number, :uuid, presence: true
# Callbacks
before_validation :set_auth_token, :s... |
class Authentication < ActiveRecord::Base
belongs_to :user
def Authentication.find_by_provider_and_uid(provider,id)
u = self.find_by({provider: provider, uid: id})
return u
end
end
|
require 'spec_helper'
require 'generators/nice_acl/nice_acl_generator'
RSpec.describe NiceACL::Generators::NiceACLGenerator, type: :generator do
destination File.expand_path("../.././../tmp", __FILE__)
before { prepare_destination }
it 'runs hello wolrd command' do
gen = generator
allow(gen).to receiv... |
require 'spec_helper'
require_relative '../../lib/models/item_order.rb'
RSpec.describe ItemOrder, type: :model do
it "should have an item" do
expect(FactoryBot.build(:item_order, item_id: nil)).to_not be_valid
end
it "should have an order" do
expect(FactoryBot.build(:item_order, order_id: nil)).to_not b... |
require 'rails_helper'
RSpec.describe Transaction, type: :model do
context 'successfull validation and association' do
it 'should be valid with a transaction_type' do
FactoryGirl.build(:transaction).should be_valid
end
it 'should belongs to account' do
account = FactoryGirl.create(:account)
... |
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@bets = @user.joined_bets
@rounds = @user.rounds.all.order(created_at: :desc)
@requested_bets = @user.pending_bets.all.order(created_at: :desc)
end
end
|
require 'rails_helper'
module ChefHelper
RSpec.describe BaritoFlowProducerRoleAttributesGenerator do
before(:each) do
@infrastructure = create(:infrastructure, cluster_name: 'test')
@consul_component = create(:infrastructure_component,
infrastructure: @infrastructure,
hostname: ... |
require_relative "../lib/unicode/age"
require "minitest/autorun"
describe Unicode::Age do
it "returns required Unicode version to display a string" do
assert_equal 1.1, Unicode::Age.of("A")
assert_equal 2.0, Unicode::Age.of("\u{10FFFD}")
assert_equal 3.0, Unicode::Age.of("ℜսᖯʏ")
assert_equal 3.1, Uni... |
class PuzzleSerializer < ActiveModel::Serializer
has_many :scores
has_many :users
attributes :id, :imageUrl, :score_id
end |
Rails.application.routes.draw do
get '/topics/index'
resources :topics
resources :posts
resources :votes
resources :users
resources :conversations
resources :moderators
root 'topics#index'
end
|
FactoryGirl.define do
factory :game do
active true
trait :with_users do
transient do
user_count 0
end
after(:build) do |g, factory|
(1..factory.user_count).map { g.add_user(FactoryGirl.create(:user)) }
end
end
end
end
|
require_relative 'partition_array'
module Kata
module Algorithms
module Sorting
class QuickSelect < Struct.new(:array, :kth_lowest)
def select
if array.size == 1
array[0]
end
partition_array = Kata::Algorithms::Sorting::PartitionArray.new(array)
... |
# frozen_string_literal: true
# Copyright (c) 2019 Danil Pismenny <danil@brandymint.ru>
module StoreMessage
private
def store_message(message)
attrs = {
telegram_message_id: telegram_message_id,
telegram_date: telegram_date
}
message_text = message['text']
# Сохраняем только текстов... |
class User < ApplicationRecord
has_many :notes
has_many :note_comments
end
|
require "minitest_helper"
require "chandler/github/client"
class Chandler::GitHub::ClientTest < Minitest::Test
class FakeOctokitClient
attr_reader :netrc, :access_token, :api_endpoint
def initialize(options)
@netrc = options.fetch(:netrc, false)
@access_token = options[:access_token]
@api_... |
# This is a helper mixin to try to keep the processing strategies DRY while
# still being flexible
#
# For full documentation see the class-level documentation for
# ProcessingStrategyHelper
#
# Author:: Ryan Schenk (mailto:rschenk@mbl.edu)
module LigerEngine
module ProcessingStrategies
# A processin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.