text
stringlengths
10
2.61M
class CreateCustomers < ActiveRecord::Migration[5.2] def change create_table :customers do |t| t.string :name, null: false t.jsonb :preferences t.integer :preference_age_min, :unsigned => true, null: false, default: 0 t.integer :preference_age_max, :unsigned => true, null: false, default: ...
class ApplicationController < ActionController::Base protect_from_forgery helper_method :current_user helper_method :user_signed_in? private def board return @board if defined? @board if bo = cookies[:bo] if board = current_user.boards.where(:id => bo) return @board = board....
module FellowshipOne class Household < ApiObject f1_attr_accessor :id, :household_name, :household_sort_name, :household_first_name, :last_security_authorization, :last_activity_date, :created_date, :last_updated_date # Loa...
class Model < ApplicationRecord belongs_to :parent, class_name: 'Model', required: false has_many :models, foreign_key: :parent_id end
class Api::CommentsController < ApplicationController before_action :authenticate_user!, only: [:create, :update, :destroy] def index comments = if params[:article_id] Article.find(params[:article_id]).comments.paginate page: params[:page] else Comment.paginate page: params[:page] end r...
class CreateCompetitionEntries < ActiveRecord::Migration def change create_table :competition_entries do |t| t.references :competition t.references :team t.timestamps end add_index :competition_entries, :competition_id add_index :competition_entries, :team_id end end
class Node attr_reader :value def initialize(node_value) @value = node_value @next_node = nil end def set_next_node(node) @next_node = node end def get_next return @next_node end end
require 'aws-sdk-s3' class S3Check class << self def check # Configure aws client akid = Rails.env.production? ? ENV['AWS_ACCESS_KEY_ID'] : Rails.application.credentials.aws[:access_key_id] secret = Rails.env.production? ? ENV['AWS_SECRET_ACCESS_KEY'] : Rails.ap...
class OvenOffError < StandardError end class OvenEmptyError < StandardError end class SmallOven attr_accessor :contents def turn_on puts "Turning oven on." @state = "on" end def turn_off puts "Turning oven off." @state = "off" end def bake # Raise an error if we attemp...
class CreatePerks < ActiveRecord::Migration def change create_table :perks do |t| t.integer :campaign_id, null: false t.integer :price, null: false t.string :title, null: false t.text :description, null: false t.integer :number_available, null: false t.date :delivery_date, null...
class Comment < ActiveRecord::Base belongs_to :prototype belongs_to :user validates_presence_of :text def error_messages errors.full_messages end end
class AttachmentsController < ApplicationController def create attachments_params.each do |a_params| @attachment = Attachment.create(a_params) end respond_to do |format| if @attachment format.json { render json: @attachment.attributes.merge( stuff_url: url_for(@attachment), for_model: ...
# frozen_string_literal: true FactoryBot.define do sequence :email do |n| "person#{n}@example.com" end sequence :authy_id do |n| n.to_s end factory :user do email { generate(:email) } password { "correct horse battery staple" } factory :authy_user do authy_id { generate(:authy_id...
require 'test_helper' class CustomRoutesTest < ActionDispatch::IntegrationTest test "that feed route opens all statuses page" do get "/feed" assert_response :success end test "that login route opens login page" do get "/login" assert_response :success end test "that register route opens sign up page" do...
class TagRelationship < ActiveRecord::Base validates_presence_of :music_id, :tag_id belongs_to :music belongs_to :tag end
# frozen_string_literal: true require 'rack' require 'rack/test' require 'timecop' module SnowplowRubyDuid describe Helper do include Rack::Test::Methods describe 'snowplow_domain_userid' do let(:app) { App.new } before do Timecop.freeze(Time.local(1990)) end after do ...
class Api::V1::ProductionRecordsController < Api::V1::BaseController before_action :set_production_record, only: [:show, :update, :destroy] def index json_response(ProductionRecord.all.paginate(page: params[:page], per_page: 20)) end def show json_response(@production_record) end def create p...
require 'spec_helper' describe PageContent do describe "メソッド" do let(:top_event) { create(:genre, event_folder_type: Genre.event_folder_types[:top], parent: create(:top_genre)) } let(:event_page) { create(:page, genre: top_event, begin_event_date: Date.today, end_event_date: Date.today) } let(:event_page...
# frozen_string_literal: true require 'rails_helper' RSpec.describe Address, type: :model do describe 'validations' do it { validate_presence_of(:address1) } end it { belong_to :addressable } end
# frozen_string_literal: true require "beyond_api/utils" module BeyondApi module ProductAttachments # # A +POST+ request is used to create an attachment and add it to a product. # # $ curl 'https://api-shop.beyondshop.cloud/api/products/ecb997ce-79c3-4367-9373-058089a313e3/attachments' -i -X POST ...
class AddServerMeurioAccountsOlive < ActiveRecord::Migration def up if Rails.env.production? || Rails.env.staging? execute "DROP EXTENSION IF EXISTS postgres_fdw CASCADE;" raise "MEURIO_ACCOUNTS_DBNAME is missing" if ENV["MEURIO_ACCOUNTS_DBNAME"].nil? raise "MEURIO_ACCOUNTS_DBHOST is missing" if...
require_relative 'screen.rb' module FPrinter def self.slow(str, sec = 0.05) str.split("").each do |l| print l sleep(sec) end puts "" end def self.slow_unprint(str, sec = 0.05) s = str.length str.split("").each_with_index do |l, i| print "\e[K", str[0..(s-i)] sleep(s...
class CreateUsers < ActiveRecord::Migration[6.1] def change create_table :users do |t| t.string :name, null: false, unique: true t.string :password, null: false t.string :intra_id, null: false, unique: true t.string :image_url, null: false, default: "default_image_url" t.string :titl...
require_relative "errors" require_relative "nilist/version" class Nilist EH_REGEX = /\?$/ REPL_PRESENTERS = [ :inspect, :pretty_print ].freeze INVOKERS = [ :send, :__send__, :public_send ].freeze PRESERVED_METHODS = (REPL_PRESENTERS + INVOKERS).freeze self.methods.each do |m| ...
require 'rails_helper' RSpec.describe Api::StudentsController, type: :controller do describe "GET #show" do it "returns the student" do student = sign_in_student get :show, params: { id: student.id } student_response = json_response expect(student_response[:email]).to eql student.email ...
class Project < ActiveRecord::Base attr_accessible :description, :group_id, :name belongs_to :group has_many :tasks validates_presence_of :name validates_presence_of :description end
require "test_helper" require "loyalty_connect" module LoyaltyConnect module Model describe PagedItems do describe "parsing from json" do before do json = JSON.parse(%q({ "previous_uri": "/previous", "current_uri": "/current", "next_uri": "/next", ...
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'web_task_runner/version' Gem::Specification.new do |spec| spec.name = "web_task_runner" spec.version = WebTaskRunnerVersion::VERSION spec.authors = ["Neson"] spec.ema...
# frozen_string_literal: true module Rx module Middleware module Response class RxFailedStation < Faraday::Response::Middleware include SentryLogging def on_complete(env) return unless env.body.is_a? Hash station_list = env.body.try(:[], :metadata).try(:[], :failed_sta...
#!/usr/bin/ruby # frozen_string_literal: true require_relative 'panthage_ver_helper' # CartFileChecker for checking library's version acceptable logic class CartFileChecker def self.check_library_by(new_data, old_data) if new_data.is_private new_data.conflict_type = ConflictType::IGNORE new_data.err...
class Product < ActiveRecord::Base belongs_to :product_type belongs_to :prototype belongs_to :brand belongs_to :wishlist has_many :product_properties has_many :properties, through: :product_properties has_many :variants has_many :images, -> {order(:position)}, as: :imageable, ...
# @author Ben Slaughter, Jonathan Chrisp require 'rake' require 'optparse' begin load 'Brakefile' rescue LoadError puts "Brakefile load error" puts "please check your brake file" exit end # @author Ben Slaughter # class brake the heart and soul of brake # simply this is a wrapper disigned to give the end user...
class ArticlesController < ApplicationController before_action :set_article, only: [:show] skip_before_action :authenticate_user!, only: [:index, :show, :search] def index @articles = Article.all.page(params[:page]).per 20 end def show end def search @article = Article.find_by_old_url search_pa...
class CreatePositions < ActiveRecord::Migration[5.1] def change create_table :positions do |t| t.string :title, null: false, default: "" t.string :location, null: false, default: "" t.integer :min_salary t.integer :max_salary t.string :active_status t.string :occupation_type ...
class RemoveColumnUserIdFromSmartProducts < ActiveRecord::Migration def up remove_belongs_to :smart_products, :user, index: true, foreign_key: true end def down add_belongs_to :smart_products, :user, index: true, foreign_key: true end end
# frozen_string_literal: true # Produces properly URI escaped files class FileUri # @param [String] pathname an unescaped path to a file. def initialize(pathname) @raw = pathname end def uri URI::File.build(path: escaped_path) end delegate :to_s, to: :uri private def escaped_path File.j...
class CreateCards < ActiveRecord::Migration def self.up create_table :cards do |t| t.string :rank t.string :suit t.integer :deck_id end add_index :cards, :deck_id end def self.down drop_table :cards end end
require "open-uri" desc 'import suppliers from csv' task :supplier_csv_import => :environment do # expected field layout: website,name,email,phone,street_address,city,state,zip,country CSV.new(open(ENV['url']), headers: true).each do |row| puts "***** IMPORT DATA: #{row.to_csv}" supplier_params = {} s...
class Animal < ApplicationRecord has_many :questions end
class Order < ApplicationRecord belongs_to :customer has_many :order_items, dependent: :destroy validates :postcode, presence: true validates :address, presence: true validates :name, presence: true enum pay_type: {クレジットカード:0, 銀行振込:1} enum buy_status: {入金待ち:0, 入金確認:1, 製作中:2, 発送準備中:3, 発送済み:4} def shi...
class WeddingAlbumTranslation < ApplicationRecord belongs_to :wedding_album, optional: true belongs_to :language, optional: true end
# == Schema Information # # Table name: addresses # # id :integer not null, primary key # client_id :integer # region :string # city :string # street :string # number :string # created_at :datetime not null # updated_at :datetime not null # FactoryGirl.define...
# frozen_string_literal: true module Enumerable # Yield items in groups of n, for each group yield the group number, starting # with zero and an Array of n items, or all remaining items if less than n. # # ('a'..'z').to_a.groups_of(5) do |k, grp| # # On each iteration, grp is an Array of the next 5 i...
module LeanMotion module User attr_accessor :AVUser RESERVED_KEYS = ['username', 'password', 'email'] def initialize(av_user_object=nil) if av_user_object @AVUser = av_user_object else @AVUser = AVUser.user end end def method_missing(method, *args, &block) ...
json.array!(@alquilers) do |alquiler| json.extract! alquiler, :id, :num_alquiler, :fecha_out, :fecha_in, :pelicula_id, :cliente_id json.url alquiler_url(alquiler, format: :json) end
require 'spec_helper' describe Genre do it { should have_many :titles } it "validates the presence of genre" do genre = Genre.new(name: '') expect(genre.save()).to eq(false) end it "will capitalize the name of the genre" do genre = Genre.create(name: "political nonfiction") expect(genre.name(...
class ProductRequestsController < ApplicationController load_and_authorize_resource rescue_from CanCan::AccessDenied do redirect_to new_product_owner_registration_path end def create @product_request = ProductRequest.new(product_request_params) if @product_request.save flash[:success] = I18n...
class CreateGroupEvents < ActiveRecord::Migration def change create_table :group_events do |t| t.datetime :start t.datetime :stop t.string :name t.string :description t.belongs_to :coach, index: true, foreign_key: true t.belongs_to :area, index: true, foreign_key: true t...
class DebtPapersController < ApplicationController # GET /debt_papers # GET /debt_papers.json def index @debt_papers = DebtPaper.all respond_to do |format| format.html # index.html.erb format.json { render json: @debt_papers } end end # GET /debt_papers/1 # GET /debt_papers/1.json ...
# like RedirectCallback, but callback not store in session, # just in query params module ParamsCallback def self.included(mod) mod.class_eval do helper_method :callback_url end end private def callback_url params[:callback] end end
class IssueErrorReport attr_accessor :issue def initialize(issue) @issue = issue end def error_report return "" if issue.valid? @error_report ||= generate_descriptive_error_report end protected def generate_descriptive_error_report formatter = issue.errors.method(:full_message) ...
class Airplane attr_reader :model #Модель attr_reader :altitude # высота attr_reader :speed #скорость def initialize(model) @model = model @altitude = 0 @speed = 0 end def fly @speed = 800 @altitude = 10000 end def land @speed = 0 @altitude = 0 end def moving? @speed ...
class Trainer < ActiveRecord::Base belongs_to :user has_many :membership_request_responses end
module Mediable extend ActiveSupport::Concern module ClassMethods def create_media(doi, options={}) return OpenStruct.new(body: { "errors" => [{ "title" => "Username or password missing" }] }) unless options[:username].present? && options[:password].present? return OpenStruct.new(body: { "errors" =...
class PasswordsController < Devise::PasswordsController def ssl_required? true end end
# frozen_string_litaral: true FactoryBot.define do factory :comment do message { Faker::String.random(100) } association :book, factory: :book association :user, factory: :user end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'Eventモデルに関するテスト', type: :model do describe 'イベント情報の保存' do let(:user) { create(:user) } let(:prefecture) { create(:prefecture) } it "有効なイベント情報が全て入力されている場合保存できるか" do expect(FactoryBot.create(:event)).to be_valid end end con...
class ChangeReferenceColumnToProduct < ActiveRecord::Migration[5.2] def change add_reference :products, :date_purchase, index:true add_foreign_key :products, :date_purchase end end
class AddResponsibleToService < ActiveRecord::Migration[5.2] def change add_column :services, :responsible, :string end end
class Addpricetocraft < ActiveRecord::Migration def change add_column :crafts, :price, :decimal end end
Factory.define(:dmail) do |f| f.to {|x| x.association(:user)} f.title {Faker::Lorem.words.join(" ")} f.body {Faker::Lorem.sentences.join(" ")} end
# coding: utf-8 describe SQLiterate::StringParser do def should_parse(q) r = SQLiterate::StringParser.new.parse(q) expect(r).not_to be_nil r end it "parses a string" do should_parse("'string'") end it "parses a string with escaped quote" do should_parse("'str''ing'") end it "parses...
class CreateBars < ActiveRecord::Migration def up create_table :bars do |t| t.string :name t.string :logo t.string :street t.string :zipcode t.string :city t.integer :freebeer t.timestamps end end def down drop_table :bars 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...
# -*- encoding : utf-8 -*- module Network::ChangePowerHelper def change_power_table(applications) table_for applications, title: 'ქსელში ცვლილების განცხადებები', icon: '/icons/user--pencil.png', collapsible: true do |t| t.title_action network_add_change_power_url, label: 'ახალი განცხადება', icon: '/icons/pl...
#!/usr/bin/env ruby require 'rubygems' require 'active_support/inflector' unless action = ARGV[0] puts 'you must provide an argument to generate' exit end unless File.exist?(generator_file = File.join(File.dirname(__FILE__),'generators',"#{action}.rb")) puts "the action #{action} is not a valid generate option"...
class Domain < ActiveRecord::Base #translates :slug #extend FriendlyId #friendly_id :name, use: :slugged acts_as_tree attr_accessible :name, :description has_many :subjects validates_presence_of :name end
json.array!(@carbs) do |carb| json.extract! carb, :id, :valeur, :note, :date json.url carb_url(carb, format: :json) end
module Slickr module Generators class Entity < Base def start template "entity.erb", "lib/entities/#{name}.rb" Renderer.new(name.gsub("entity", "renderer")).start end end end end
class ChangeDataCreatedAtToCooks < ActiveRecord::Migration[5.2] def change change_column :cooks, :updated_at, :date end end
class Technology < ActiveRecord::Base attr_accessible :name has_and_belongs_to_many :portfolios end
require 'spec_helper' describe Buckaroo::Ideal::Response do let(:parameters) { { 'bpe_trx' => 'transaction_id', 'bpe_result' => '801', 'bpe_invoice' => 'inv001', 'bpe_reference' => 'ref001', 'bpe_signature' => 'response_signature_1', 'bpe_signature2' => 'respon...
describe 'Home page' do describe 'jumbo' do context 'when user is not signed id' do before do visit root_path end it 'shows signin button' do expect(page).to have_selector('.main-top-btn', text: 'Sign in') end it 'shows signin text' do expect(page).to have_c...
require 'spec_helper' describe PrinterFunction do it "should let us make add a new one" do printer_function = FactoryGirl.create(:printer_function) printer_function.save.should be_true end it "should require an name" do printer_function = FactoryGirl.build(:printer_function, name: nil) printer_fu...
module QML module Reactive # @!parse extend ClassMethods # @api private class PropertyInfo attr_accessor :initializer end # @api private class SignalInfo attr_accessor :params attr_accessor :listeners def initialize @listeners = [] end end def...
require 'digest/sha1' class User < ActiveRecord::Base acts_as_authentic attr_protected :admin def to_s name end def name "#{firstname} #{lastname}" end end
namespace :data do namespace :load do desc 'Init ES Industries Repository' task :industries do IndustriesRepositories.destroy_index! Industry::LIST.each_with_index do |industry_title, index| IndustriesRepositories.es_repository.save(Industry.new('id' => index, 'title' => industry_title)) ...
class Course < ActiveRecord::Base validates :number, :uniqueness => {:scope => :department, :message => "Course number can only occur once per dept."} # TODO should we add ":include => [:professors, :distribs]" to "has_many offerings"? has_many :offering_courses has_many :offerings, :through => :offering_c...
require 'test_helper' class VoteTest < ActiveSupport::TestCase test "vote exists and needs parameters" do vote = Vote.new refute vote.save end test "votes build correctly and must have all parameters" do vote_one = Vote.new(race_id: 1, candidate_id: 3, voter_id: 2) vote_two = Vote.new(candidate...
# --- Day 15: Oxygen System --- # Out here in deep space, many things can go wrong. Fortunately, many of those things have indicator lights. Unfortunately, one of those lights is lit: the oxygen system for part of the ship has failed! # # According to the readouts, the oxygen system must have failed days ago after a ru...
require 'rails_helper' RSpec.describe User, type: :model do let(:user1) { User.new } let(:user2) { User.new(fullname: 'example number', username: 'example', email: 'e@gmail.com', password: '123456') } describe 'associations' do it { should have_many(:opinions) } it { should have_many(:followers) } i...
class Book < ApplicationRecord belongs_to :user has_many :likes, dependent: :destroy has_many :liked_users, through: :likes, source: :user has_many :comments, dependent: :destroy validates :title, presence: true validates :body, presence: true, length: { maximum: 200 } is_impressionable scope :crea...
class Speakerdeck DOMAIN = 'speakerdeck.com'.freeze URL = "https://#{DOMAIN}".freeze FILES_URL = "https://files.#{DOMAIN}".freeze def self.frame(code) "<iframe src=\"#{URL}/player/#{code}\" allowfullscreen=\"true\" allowtransparency=\"true\" mozallowfullscreen=\"true\" style=\"border:0; padding...
module Spree module Admin class BulkUploadsController < Spree::Admin::BaseController respond_to :html def index @bulk_uploads = Spree::BulkUpload.all respond_with @bulk_uploads end def new @bulk_upload = Spree::BulkUpload.new respond_with(@bulk_upload) do...
# frozen_string_literal: true require 'client' describe '初期化' do before(:example) do @client = Jiji::Client.instance end context '初期化前' do it 'GET /settings/initialization/initialized がfalseを返す' do r = @client.get('settings/initialization/initialized') expect(r.status).to eq 200 expec...
class CreateRequestsTable < ActiveRecord::Migration[5.1] def change create_table :app_requests do |t| t.string :request_id t.string :api_key t.string :controller t.string :action t.string :query_parameters t.integer :request_time_in_milliseconds ...
FactoryGirl.define do factory :user, class: User do name "Someone" email {"#{name}@example.com"} password "password" password_confirmation "password" activated true activated_at {"#{Time.zone.now}"} end factory :post, clas...
module Bullhorn module Rest class AuthenticationError < StandardError; end # http://supportforums.bullhorn.com/viewtopic.php?f=104&t=14542 module Authentication attr_accessor :username, :password, :client_id, :client_secret, :auth_code, :access_token, :access_token_expires_at, :refresh_token, :ttl, :rest_token, :e...
require 'minitest/autorun' require 'mocha/setup' require_relative '../../app/services/finger_service' require_relative '../../app/models/feed_data' require_relative '../../app/models/finger_data' require 'redfinger' module RstatUs class InvalidSubscribeTo < StandardError; end end describe FingerService do descr...
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root 'welcome#home' resources :users do resources :workouts, only: [:index, :new, :create], controller: 'users/workouts' end resources :workouts, only: [:show, :update, :...
require 'rails_helper' RSpec.describe Admin::JudgesController, type: :controller do it { should route(:get, '/admin/judges').to(action: :index) } it { should route(:get, '/admin/judges/new').to(action: :new) } it { should route(:post, '/admin/judges').to(action: :create) } describe 'requests' do before do...
class CreateVirtualAssignments < ActiveRecord::Migration def self.up create_table :virtual_assignments do |t| t.column :parent_id, :integer, :null => false t.column :child_id, :integer, :null => false t.column :assigned_at, :datetime t.column :created_at, :datetim...
class Project < ActiveRecord::Base belongs_to :project_status validates_presence_of :description, :price, :link end
class RequestsController < ApplicationController def index @requests = Request.all @disable_nav = true end def show @request = Request.find(params[:id]) end def new @request = Request.new @disable_nav = true end def edit @request = Request.find(params[:id]) end def create @request = Request.new(...
require 'rails_helper' feature 'Checking if the data got updated after clicking the button', js: true do scenario 'Clicking on the button' do visit '/pages/test_4' click_link 'Click me to fire an AJAX call' expect(page).to have_content ('This is answer from the server') end e...
require "rails_helper" feature "visitor adds loans to shopping cart" do include_context("features") scenario "without being logged in from the loans index page" do visit "/" click_link("Loans") within(".loans") do first(".caption").click_button("Add to Cart") first(".caption").click_butto...
require 'test_helper' module SessionTest class PersistenceTest < ActiveSupport::TestCase def test_find aaron = users(:aaron) refute UserSession.find http_basic_auth_for(aaron) { assert UserSession.find } set_cookie_for(aaron) assert UserSession.find unset_cookie set_sess...
class FixMonitorStart < ActiveRecord::Migration def change rename_column :patient_assignments, :montior_start, :monitor_start end def down end end
class FacultyObserver < ActiveRecord::Observer def after_create(faculty) FacultyNotifier.deliver_signup_notification(faculty) end def after_save(faculty) FacultyNotifier.deliver_activation(faculty) if faculty.recently_activated? end end
class AddDonationValueCentsToCertificate < ActiveRecord::Migration def change add_column :certificates, :donation_value_cents, :integer end end