text
stringlengths
10
2.61M
class AddLatencyToSolutions < ActiveRecord::Migration def change add_column :solutions, :latency, :integer end end
class Question < ApplicationRecord validates :title, presence: true has_many :answers, inverse_of: :question accepts_nested_attributes_for :answers has_many :question_comments end
class Mutations::UpdateMutation < Mutations::BaseMutation def resolve(**params) resource = resource(params[:id]) yield(resource) if block_given? if resource.save { resource_node => resource, :errors => [] } else failed_update_response(resource_node, resource.errors.full_messages) end ...
class ExtendCreativeData < ActiveRecord::Migration def self.up change_column :azoogle_creatives, :data, :text end def self.down change_column :azoogle_creatives, :data, :string end end
class TasksController < ApplicationController # before_filter :correct_user, only: [:edit, :update, :destroy] def new @project = Project.find(params[:project_id]) @task = Task.new end def create @project = Project.find(params[:project_id]) @task = @project.tasks.build(params[:task]) if @ta...
class Garage attr_reader :name, :customers def initialize(name) @name = name end def add_customer(customer) customers = [] customers << customer end end
# frozen_string_literal: true require 'yaml' class DataDump < Aid::Script def self.description 'Helpers to get data out of the application.' end def self.help <<~HELP Usage: $ aid data [data_type] Available data types are: #{available_data_types.join(', ')} HELP end def self.availa...
class ChangeColumnInAlert < ActiveRecord::Migration[5.1] def change change_column :alerts, :reference_id, :string end end
class Booking < ApplicationRecord belongs_to :user def order_params params.require(:booking).permit( :bookingdate, :user_id, :status) end has_many :bookingitema end
require 'spec_helper' describe "batch_charities/show" do before(:each) do @batch_charity = assign(:batch_charity, stub_model(BatchCharity, :batch_id => "", :charity_id => "" )) end it "renders attributes in <p>" do render # Run the generator again with the --webrat flag if you want t...
class AddTotalWordsToCourses < ActiveRecord::Migration def change add_column :courses, :total_words, :integer end end
require 'sinatra/base' require 'sinatra/flash' require 'uri' require './lib/bookmark' require_relative './lib/comment' require_relative './lib/database_connection_setup' class Webapp < Sinatra::Base enable :sessions, :method_override register Sinatra::Flash get '/' do 'Hello world!' end get '/book...
require 'fog/powerdns/version' require 'fog/core' require 'fog/xml' module Fog module PowerDNS extend Fog::Provider service(:dns, 'DNS') end end
require 'rails_helper' RSpec.describe Author, type: :model do it 'should have a first and last name a well as a homepage string' do author = Author.new(first_name:'Rosa', last_name:'Schluepfer', homepage:'meineschluepfer.com') expect(author.first_name).to eq("Rosa") expect(author.last_name).to eq("Schlu...
# frozen_string_literal: true class Vote < ApplicationRecord belongs_to :subscriber belongs_to :post validates :value, presence: true, inclusion: { in: 1..7 } validates :post_id, uniqueness: { scope: :subscriber_id } end
class AddMoreIndices < ActiveRecord::Migration def self.up add_index :posts, :published_at add_index :events, :date add_index :events, :num_attendees end def self.down remove_index :events, :date remove_index :events, :num_attendees remove_index :posts, :published_at end end
class FuzzyFixture cattr_accessor :config cattr_accessor :last_key class FuzzyException < RuntimeError #:nodoc: def initialize(args) e = args[0] last_options = args[1] super("raised #{e.class}: #{e.message}\nYour args where:\n#{last_options.inspect}\n\n") set_backtrace(e.backtrace) ...
# coding: utf-8 #!/usr/bin/env ruby # Extend string to allow for bold text. class String def bold "\033[1m#{self}\033[0m" end end namespace "build" do task :dev, [:host, :port] do |t, args| ENV["JEKYLL_ENV"] = "development" args.with_defaults(:host => "127.0.0.1", :port => "4000") host = args[:...
require 'test_helper' class OpeningStatementsControllerTest < ActionController::TestCase setup do @opening_statement = opening_statements(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:opening_statements) end test "should get new" do get...
class Schedulator < ActiveRecord::Base attr_accessible :name belongs_to :user has_many :schedule_relationships has_many :sections, through: :schedule_relationships has_many :schedulator_saved_relationships has_many :active_schedulator_relationships def getName if self.name.nil? ...
# frozen_string_literal: true require 'rails_helper' describe MultipleChoiceQuestion, type: :model do describe 'validations' do subject { create :multiple_choice_question } # Presence it { is_expected.to validate_presence_of(:title) } it { is_expected.to validate_presence_of(:answers) } end end
require('test_helper') || require_relative('../test_helper') class Vaadin::ElementsTest < Minitest::Test def test_has_version_number refute_nil ::Vaadin::VERSION end end
require 'spec_helper' describe Swift::Pyrite::Cli do let(:pyrite) { double(:pyrite) } before do allow_any_instance_of(described_class).to(receive(:generator)).and_return(pyrite) end context "#generate" do let(:argv) { ["generate", "foo.swift", "fake_foo.swift"] } it 'delegates the options to the...
# 205. Isomorphic Strings # https://leetcode.com/problems/isomorphic-strings/ # Given two strings s and t, determine if they are isomorphic. # Two strings are isomorphic if the characters in s can be replaced to get t. # All occurrences of a character must be replaced with another character while preserving the ord...
require "rails_helper" RSpec.describe "First Associates Transactions" do let(:amount) { 123 } let(:id) { create(:first_associates_transaction, payment_amount: amount).id } it_behaves_like "a viewable resource", :first_associates_transactions it_behaves_like "a read-only resource", :first_associates_transactio...
module Hydra::Works class GetRelatedObjectsFromGenericWork ## # Get related objects from a generic_work. # # @param [Hydra::Works::GenericWork::Base] :parent_generic_work to which the child objects are related # # @return [Array<Hydra::Works::GenericWork::Base>] all related objects def s...
require "test_helper" describe ProductsController do let(:one) {products(:tree1)} let(:two) {products(:tree2)} let(:three) {products(:tree3)} describe "index" do it "must get the index view" do get products_path must_respond_with :success end it "must respond with success with valid f...
#!/usr/bin/env ruby require_relative '../lib/github_project' OWNER = "ministryofjustice" REPO = "cloud-platform" PROJECT_NAME = "Cloud Platform Team Kanban Board" ICEBOX_COLUMN_NAME = "Icebox" ICEBOX_COLUMN_ID = "MDEzOlByb2plY3RDb2x1bW4xMDQ3NDkzMw==" params = { organization: OWNER, repo: REPO, github_token: E...
#!/usr/bin/env ruby # Author: Joseph Pecoraro # Date: Friday December 11, 2009 # Help: http://snippets.dzone.com/posts/show/1785 # Description: IRC bot that # - joins a channel # - responds to some simple commands # - admin interface allows for adding/removing simple commands # - is just plain awesome require "rub...
# Account holders able to access all standard filebucket functionality. class User < ActiveRecord::Base has_many :assets has_many :folders has_many :access_keys, :dependent => :destroy has_many :shared_folders, :dependent => :destroy has_many :being_shared_folders, :class_name => "SharedFolder", :foreign_key ...
class RegistrationsController < Devise::RegistrationsController def new @plan = params[:plan] if @plan @user = User.new @user.pharmacies.build else redirect_to root_path, :notice => 'Please select a subscription plan below.' end end def update_plan @user = curren...
# frozen_string_literal: true require 'jiji/test/test_configuration' require 'jiji/model/securities/oanda_securities' require 'jiji/model/securities/internal/examples/ordering_examples' require 'jiji/model/securities/internal' \ + '/examples/ordering_response_pattern_examples' require 'date' if ENV['OANDA_AP...
describe Fog::Compute::Brkt::WorkloadTemplate do def new_workload_template(arguments={}) Fog::Compute::Brkt::WorkloadTemplate.new(arguments.merge(:service => compute)) end describe "#save" do context "new record" do it "requires name" do workload_template = new_workload_template({ ...
class CreateAlbumService def initialize(artist_id: nil, new_artist_name:, create_new_artist:, title:, year:, condition: 'excellent', image_url: nil) @artist_id = artist_id @new_artist_name = new_artist_name @create_new_artist = create_new_artist @title = title @year = year @condition = conditi...
# exercise_3.rb h = {key_1: "value 1", key_2: "value_2", key_3: "value_3"} def hash_keys(hash) hash.each_key do |k| puts k end end def hash_values(hash) hash.each_value do |v| puts v end end def hash_keys_and_values(hash) hash.each do |k,v| puts "One of the keys of this hash is #{k} and its corresponding...
class FontHack < Formula version "3.003" sha256 "0c2604631b1f055041c68a0e09ae4801acab6c5072ba2db6a822f53c3f8290ac" url "https://github.com/source-foundry/Hack/releases/download/v#{version}/Hack-v#{version}-ttf.zip", verified: "github.com/source-foundry/Hack/" desc "Hack" homepage "https://sourcefoundry.org/ha...
#!/usr/bin/env ruby require_relative '../lib/github/graphql.rb' require 'test/unit' class TestQuery < Test::Unit::TestCase TEST_TOKEN = '0000000000000000000000000000000000000000' def test_blank assert_equal(Github::GraphQL.new(TEST_TOKEN, '').query['message'], 'Bad credentials') end def test_nil_auth ...
module CassandraObject module BelongsTo class Builder def self.build(model, name, options) new(model, name, options).build end attr_reader :model, :name, :options def initialize(model, name, options) @model, @name, @options = model, name, options end def build...
class BuyingHistoryAddress include ActiveModel::Model attr_accessor :postcode, :area_id, :municipality, :addresses, :building, :phone_number, :buying_history_id, :user_id, :item_id, :token validates :postcode, presence: true, format: { with: /\A[0-9]{3}-[0-9]{4}\z/, message: 'is invalid. Incl...
class Search < ApplicationRecord has_many :cards has_many :colors, through: :cards self.inheritance_column = :_type_disabled def cards @cards = find_cards end def card @card = find_card end def colors @colors = find_colors end private def find_cards cards = MTG::Card.where(na...
Gem::Specification.new do |s| s.name = "domain_routing" s.version = "0.1.4" s.date = "2011-08-23" s.summary = "Domain Routing" s.description = "A Rails 3 gem that allows easy routing using different domains and subdomains" s.authors = ["Mike Stone"] s.email = "stonem...
require 'rails_helper' describe 'FeatureManagement', type: :feature do describe '#prefill_otp_codes?' do context 'when SMS sending is disabled' do before { allow(FeatureManagement).to receive(:telephony_disabled?).and_return(true) } it 'returns true in development mode' do allow(Rails.env).t...
describe :update do before { CACHE[:update] ||= reset_db <<-EOF CREATE TABLE "datoki_test" ( id serial NOT NULL PRIMARY KEY, title varchar(123) NOT NULL, body text DEFAULT 'hello' ); EOF } # === before it "updates the record" do c = Class.new { include Dat...
#==============================================================================# # ** IEX(Icy Engine Xelion) - Change Encounter #------------------------------------------------------------------------------# # ** Created by : IceDragon # ** Script-Status : Addon (Map Encounters) # ** Script Type : Map Encounter M...
class CreateCalculatorPosts < ActiveRecord::Migration def self.up create_table :calculator_posts do |t| t.float :avia t.boolean :warning t.float :max_weight t.float :weight_limit t.float :declared_value t.float :default_cost t.float :add_cost t.timestamps end ...
Rails.application.routes.draw do root to: 'articles#index' resources :articles, only:[:index, :show, :new, :create, :edit, :update, :destroy] end
require 'sequel' require_relative '../config/database' Sequel.extension :migration def db DB::Connection.connect end def migration_folder "db/migrations" end def data_migration_folder "db/data_migrations" end desc "readme" task :readme do puts "BIQ practice." end namespace :db do namespace :migrate do ...
RSpec.describe "Dashboard", type: :system, js: true do subject { admin_dashboard_path } context "When the super admin user also has an organization assigned" do before do @super_admin.organization = @organization @super_admin.save sign_in(@super_admin) visit subject end it "dis...
require 'rails_helper' RSpec.describe Project, type: :model do it '名前がないと有効ではないこと' do project = described_class.new(name: '') expect(project).not_to be_valid end end
require 'user_interface' describe UserInterface do before(:each) do @art_library = double(:art_library) allow(@art_library).to receive(:rubagotchi_idle_pose).and_return("") allow(@art_library).to receive(:main_title).and_return("") allow(@art_library).to receive(:large_horizontal_divider)....
require_relative 'helpers' require 'rspec' require 'pry' class Ingredient attr_accessor :name, :capacity, :durability, :flavor, :texture, :calories def initialize(name, capacity, durability, flavor, texture, calories) self.name = name self.capacity = capacity.to_i self.durability = durability.to_i ...
class Song < ActiveRecord::Base validates :title, uniqueness: {scope: :release_year, message: "cannot be repeated by artist"} validates :title, presence: true validates :released, inclusion: { in: [true,false] } validates :artist_name, presence: true validates :release_year, presence: true, if: :released va...
class AddUuidToPosts < ActiveRecord::Migration def self.up add_column :posts, :uuid, :string, limit: 36, unique: true add_index :posts, :uuid, unique: true end def self.down remove_index :posts, :uuid remove_column :posts, :uuid end end
json.array!(@cantons) do |canton| json.extract! canton, :id, :name, :province_id json.url canton_url(canton, format: :json) end
require 'spec_helper' describe PostgresEntityStore do class DummyEntity include EntityStore::Entity attr_accessor :name, :description def set_name(new_name) record_event DummyEntityNameSet.new(name: new_name) end end class DummyEntityWithDate include EntityStore::Entity attr_acc...
class AddColumnsToRestaurants < ActiveRecord::Migration def change add_column :restaurants, :opening_weekday, :string add_column :restaurants, :opening_weekend, :string end end
class VisualProperty < ActiveResourceRecord self.site = "#{Figaro.env.locate_design_app}/api/v1/" def property BlankProperty.find(self.property_id) end end
class AddSubjectAndAuthorizeToPosts < ActiveRecord::Migration def change add_column :posts, :subject, :string add_column :posts, :authorized, :boolean end end
module TeachersPet module Actions class MergePullRequests < Base def run repository = self.options[:repository] self.init_client open_pull_requests = self.client.pull_requests(repository, state: 'open') open_pull_requests.each do |pr| print "Merging #{pr.html_url}...
require 'bundler' Bundler.require(:default, :test) require 'minitest/autorun' require 'minitest/benchmark' require 'ccsv' require 'csv' __END__ TEST_CSV_FILES={ 100=>"/tmp/test1.csv", 10000=>"/tmp/test2.csv", 100000=>"/tmp/test3.csv" } def create_csvf(name,limit) open(name,"w") do |f| 1.upto(limit) do |...
#!/usr/bin/env ruby require 'pretentious' require 'optparse' require 'ripper' require 'readline' require 'json' require 'fileutils' require 'yaml' def eval_example(filename) example_body = '' index = 0 File.open(filename, "r") do |f| f.each_line do |line| example_body << "#{line}\n" end end e...
# Problem 426: Box-ball system # http://projecteuler.net/problem=426 # # Consider an infinite row of boxes. Some of the boxes contain a ball. For example, an initial configuration of 2 consecutive occupied boxes followed by 2 empty boxes, 2 occupied boxes, 1 empty box, and 2 occupied boxes can be denoted by the seque...
require 'uri' require 'cgi' require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "paths")) require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "selectors")) Given /^(?:|I )am on (.+)$/ do |page_name| visit path_to(page_name) end When /^(?:|I )go to (.+)$/ do |page_name...
listen (ENV["PORT"] || 3000).to_i timeout 15 preload_app true worker_processes Integer(ENV["WEB_CONCURRENCY"] || 3) before_fork do |server, worker| Signal.trap "TERM" do puts "Unicorn master intercepting TERM and sending myself QUIT instead." Process.kill("QUIT", Process.pid) end ...
class Notification attr_reader :text, :notification_type def initialize(msg, notification_type) proposed_type = notification_type.chomp.to_sym @notification_type = proposed_type if valid_type?(proposed_type) @text = msg end def valid_type?(notification_type) if [:problem, :clear].include?(noti...
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html devise_for :users, path: '', path_names: { sign_in: 'login', sign_out: 'logout', registration: 'signup' ...
# Use the each method of Array to iterate over [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], # and print out each value. arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] arr.each do |x| puts x end # Recactored to one line arr.each { |x| puts x }
$:.push File.expand_path("../lib", __FILE__) require 'webmachine-linking/version' Gem::Specification.new do |gem| gem.name = "webmachine-linking" gem.version = Webmachine::Linking::VERSION gem.summary = %Q{webmachine-linking extends webmachine-ruby to provide a richer linking API,} gem.description = <<-DESC.gs...
# -*- mode: ruby -*- # vi: set ft=ruby : $script = <<SCRIPT echo "Installing dependencies ..." sudo apt-get update sudo apt-get install -y unzip curl jq dnsutils echo "Determining Consul version to install ..." CHECKPOINT_URL="https://checkpoint-api.hashicorp.com/v1/check" if [ -z "$CONSUL_VERSION" ]; then CONSU...
class User < ActiveRecord::Base AVATAR_SW = 55 AVATAR_SH = 55 AVATAR_NW = 240 AVATAR_NH = 240 has_attached_file :avatar, :styles => { :normal => ["#{AVATAR_NW}x#{AVATAR_NH}>", :jpg], :small => ["#{AVATAR_SW}x#{AVATAR_SH}#", :jpg] }, :processors => [:jcropper], :...
$LOAD_PATH.unshift File.expand_path("../lib", __FILE__) require "activerecord-sharding-facade" require "pry" require "pry-byebug" require "awesome_print" require_relative "models" log_directry = File.expand_path("../../log/", __FILE__) Dir.mkdir log_directry unless Dir.exist? log_directry ActiveRecord::Base.logger...
class NotificationService NOTIFICATION = { create: ["SlackService", "MailerService"], update: ["SlackService"], delete: ["SlackService", "MailerService"] }.freeze def self.notify(task:, event:) message = task.notification_message(event: event) NOTIFICATION[event].each do|notification| ...
class AddLatestEditorToBookingsAndNotes < ActiveRecord::Migration def self.up add_column :bookings, :latest_editor_id, :integer add_column :booking_notes, :latest_editor_id, :integer end def self.down remove_column :bookings, :latest_editor_id remove_column :booking_notes, :latest_editor_id end...
# We need a function that can transform a number into a string. # # What ways of achieving this do you know? # # Examples: # number-to-string 123 ;; returns '123' # number-to-string 999 ;; returns '999' # def numberToString(num) # # Convert a Number to a String # end # My solution def numberToString(num) num.to...
class AddCerttificateCopyToUserCertificates < ActiveRecord::Migration[5.2] def change add_column :certificates_users, :certificates_copy, :binary add_column :certificates_users, :start_datetime, :datetime add_column :certificates_users, :end_datetime, :datetime add_column :certificates_users, :approve...
require File.dirname(__FILE__) + '/../test_helper' class BiosequenceTest < ActiveSupport::TestCase # Replace this with your real tests. should_validate_presence_of :name, :seq, :alphabet should_validate_uniqueness_of :name should_have_many :biodatabases, :biodatabase_biosequences def test_to_s_and_to_fasta ...
class Api::ChatsController < ApiController before_action :authenticate! before_action :find_chat, only: [ :update, :destroy ] def index chats = Chat.messages_of(current_user).page(params[:page] || 1) success(data: chats) end def chatting chats = if params[:goal_id].to_i > 0 Chat.buddies_ch...
require 'pry' NUMBERS = {zero: '0', one: '1', two: '2', three: '3', four: '4', five: '5', six: '6', seven: '7', eight: '8', nine: '9'} def computer(english) new_str = '' str = english.split.map {|x| x.gsub('divided', 'divided by')} str.delete('by') str.map do |word| if NUMBERS.keys.include?(wor...
class Lift MEN_LIMIT = 3 #предельная вместимость, чел. TOP_FLOOR = 9 #верхний этаж @@counter = 0 #счетчик пассажиров def initialize @men_inside = [] #массив пасажиров внутри лифта @men_outside = [] #массив ожидающих пассажиров, вызвавших лифт @current_floor = 1 #текущий этаж @...
module Charts class QueryWorkerCapacity prepend SimpleCommand def initialize(current_user, args = {}) @user = current_user @args = args end def call result = Cultivation::Task.collection.aggregate([ {"$match": {"batch_id": @args[:batch_id].to_bson_id}}, {"$lookup": ...
class Book < ActiveRecord::Base mount_uploader :picture, ProfileUploader belongs_to :user has_many :comment_books end
namespace :db do desc "Fill database with sample data" task populate: :environment do users = User.find(6) 50.times do content = Faker::Lorem.sentence(5) users.each { |user| user.merchandise.create!(content: content) } end end end
require 'rails_helper' RSpec.describe User, type: :model do describe '.find_for_google' do subject { described_class.find_for_google(auth_params) } let(:auth_params) do OmniAuth::AuthHash.new( provider: :google, uid: '012345678901234567890', info: {email: 'user@esm.co.jp'}, ...
namespace :jetty do desc "Apply all configs to Testing Server (relies on hydra:jetty:config tasks unless you override it)" task :config do Rake::Task["hydra:jetty:config"].invoke end end namespace :hydra do namespace :jetty do desc "Copies the default Solr config into the bundled Hydra Testing Server" ...
#write your code here class String def first_letter self[0, 1] end end $vowels = ['a', 'e', 'i', 'o', 'u'] def translate s words = s.split.map do |word| if vowel? word.first_letter word + "ay" elsif not vowel? word.first_letter current = word.first_letter i = 1 start_of_word...
class AddBirthdayPartyToBirthdayDealVouchers < ActiveRecord::Migration def change add_reference :birthday_deal_vouchers, :birthday_party, index: true, foreign_key: true, null: false remove_reference :birthday_deal_vouchers, :user, index: true end end
class ZhantingCapture < ActiveRecord::Base # attr_accessible :title, :body upload_column :logo belongs_to :user end
require_relative 'test_helper' begin require 'tilt/redcarpet' describe 'tilt/redcarpet' do it "works correctly with #extensions_for" do extensions = Tilt.default_mapping.extensions_for(Tilt::RedcarpetTemplate) assert_equal ['markdown', 'mkd', 'md'], extensions end it "registered above Blu...
# # Author:: Matheus Francisco Barra Mina (<mfbmina@gmail.com>) # © Copyright IBM Corporation 2015. # # LICENSE: MIT (http://opensource.org/licenses/MIT) # module Fog module Softlayer class Compute class Mock # Generate an order template for a Bare Metal # @param [Integer] order_template ...
# frozen_string_literal: true # 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:...
require "spec_helper" describe "brightbox sql instances" do describe "create" do let(:output) { FauxIO.new { Brightbox.run(argv) } } let(:stdout) { output.stdout } let(:stderr) { output.stderr } before do config = config_from_contents(USER_APP_CONFIG_CONTENTS) # Setup in the VCR recordi...
class Api::HomeTimelineSerializer < ActiveModel::Serializer attributes :goal_session def goal_session if object.class.name == "GoalSession" Api::HomeTimelineGoalSessionSerializer.new(object, { current_user: viewing_user }).attributes end end def viewing_user @viewing_user ||= @instance_optio...
desc "tasks for handling extension libraries" namespace :ext do def git_repo { :cabinet => "git://github.com/etrepum/tokyo-cabinet.git", :tyrant => "git://github.com/etrepum/tokyo-tyrant.git" } end def extensions [:cabinet, :tyrant] end def ext_root_path ...
require 'rails_helper' feature "Remove Cart" do context "Items are in the cart" do before(:each) do visit "/" click_link("All Products") first(:button, "Add To Cart").click end it "will redirect to cart" do click_link "Delete Cart" expect(current_path).to eq("/cart") en...
class Quiz < ApplicationRecord has_many :quiz_questions has_many :questions, through: :quiz_questions belongs_to :course def question_count Rails.cache.fetch([cache_key, __method__]) do questions.count end end end
class Invitation < ApplicationRecord after_create :generate_token belongs_to :event belongs_to :sender, class_name: 'User' belongs_to :recipent, class_name: 'User', optional: true has_many :tokens, as: :ownerable enum status: { sent: 10, accepted: 20, refused: 30, }...
class RenameOperatingRoom < ActiveRecord::Migration def self.up rename_table :operating_rooms, :rooms rename_column :operations, :operating_room_id, :room_id end def self.down rename_column :operations, :room_id, :operating_room_id rename_table :rooms end end
class CreateBaseModel < ActiveRecord::Migration def change create_table :accounts do |t| t.decimal :balance, default: 0 t.decimal :held_balance, default: 0 t.references :user t.integer :lock_version t.timestamps end create_table :addresses do |t| t.string :addre...
class Bst attr_reader :data, :left, :right def initialize(value) @data = value end def insert(value) if value <= data @left = create_node(value, @left) else @right = create_node(value, @right) end self end def each return to_enum(&:each) unless block_given? stack =...
require "spec_helper" describe "User" do before(:each) do @user1 = FactoryGirl.create :user # @user.confirm! @user2 = FactoryGirl.create :foodie # @user2.confirm! @user3 = FactoryGirl.create :admin # @user3.confirm! end describe "validations" do let!(:users){ [@user1, @...