text
stringlengths
10
2.61M
FactoryBot.define do factory :course do name "Golf Club" tees "Blue" rating 72.0 slope 135 end end
module Commands class AddPi SYNONYMS = ['pi'] def self.keys SYNONYMS end def execute(repl = nil) repl.calculator.add_value(Math::PI) end end end
class CreateSelectedSubs < ActiveRecord::Migration[5.1] def change create_table :selected_subs do |t| t.boolean :confirmed t.references :sub_request, foreign_key: true t.references :sendee, foreign_key: true t.timestamps end end end
require "rails_helper" RSpec.describe SpecializationsController do describe "GET #new" do it "responds successfully with an HTTP 200 status code" do get :new expect(response).to be_success expect(response).to have_http_status(200) end it "renders the new template" do get :new ...
require 'spec_helper' feature 'Viewing Folders' do before do user = FactoryGirl.create(:user) student_project = FactoryGirl.create(:activity, name: "Student project") define_permission!(user, "view", student_project) folder = FactoryGirl.create(:folder, activity: student_project, name:"Bash project",...
require 'require_relative' if RUBY_VERSION[0,3] == '1.8' require_relative '../acceptance_helper' describe "Unauthenticated reading" do include AcceptanceHelper describe "ALPS starting URI, rstat.us homepage (logged out /)" do it "can transition to all updates" do visit "/" assert has_selector?(:xp...
module Pwinty def self.client @client ||= RestClient::Resource.new( Rails.application.credentials.pwinty[:api_url], headers: { "X-Pwinty-MerchantId" => Rails.application.credentials.pwinty[:merchant_id], "X-Pwinty-REST-API-Key" => Rails.application.credentials.pwinty[:api_key], ...
class TicketsDecorator def initialize(ticket) @ticket = ticket end def logs @ticket.logs.map(&:description) end def method_missing(method, *args) if @ticket.respond_to?(method) @ticket.send(method, *args) else super end end end
module Listable # Listable methods go here def format_description (description) "#{description}".ljust(25) end def format_date (date_01, date_02 = nil) if date_02 dates = date_01.strftime("%D") if date_01 dates << " -- " + date_02.strftime("%D") if date_02 dates = "N/A" if !dates ...
require 'rails_helper' RSpec.describe BookReview, type: :model do it { should validate_presence_of(:book_title) } it { should validate_presence_of(:body) } it { should validate_presence_of(:book_author) } it { should validate_length_of(:book_title).is_at_most(244) } it { should validate_length_of(:book_autho...
class Animal attr_reader :type attr_reader :age def initialize (type, age) @type = type @age = age end def to_s "The animal is a #{type} and it is #{age} years old." end end
#! /usr/bin/ruby require 'digest' $dir = File.expand_path File.dirname(__FILE__) require 'pp' def process_type type, var case type when "numeric" "#{var}->value->isNumeric()" when "map" "#{var}->value->isMap()" when "function" "#{var}->value->isFunction()" else "#{var}->value->type == Type::#{process_ra...
require 'rails_helper' RSpec.describe Plan, type: :model do it { should validate_presence_of(:name) } it { should validate_presence_of(:planner) } end
#!/usr/bin/env ruby require 'cgi' require 'optparse' require 'rubygems' require 'rest-client' SOURCES=['em01b-r2', 'em01b-r4'] $options = { :uri => 'metrics-stg.heroku.com/v1/metrics.json', :user => nil, :pass => nil, :path => nil } optparse = OptionParser.new do|opts| opts.banner = "Usage: report-em01b ...
module MaterializedViews class BaseMaterializedView < ActiveRecord::Base def self.refresh connection.execute("REFRESH MATERIALIZED VIEW #{table_name}") end # Cant change MATERIALIZED VIEW def readonly true end end end
#!/usr/bin/env ruby # frozen_string_literal: true # Advent of Code 2020 # # Robert Haines # # Public Domain lib = ::File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'aoc2020/extra/cli' days = AOC2020::Extra::CLI.parse_params(ARGV) unless days warn 'Usage: aoc-2020 ...
class AddUserprotectedToUpdateTweet < ActiveRecord::Migration def change add_column :update_tweets, :user_protected, :boolean end end
Spree::Product.class_eval do scope :individual_saled, where(["spree_products.individual_sale = ?", true]) scope :active, lambda { |*args| not_deleted.individual_saled.available(nil, args.first) } attr_accessible :can_be_part, :individual_sale # exlusive or implementation of spree's variants_including_...
require "rails_helper" describe Level do it { should have_many(:position_skills) } it { should have_many(:skill_levels) } it { should allow_value('foobar').for(:name) } it { should_not allow_value('foo').for(:name) } it { should_not allow_value('').for(:name) } end
class CreateContentSummaries < ActiveRecord::Migration def change create_table :content_summaries do |t| t.text :original_content t.text :summary t.integer :search_query_id, foreign_key: true t.timestamps null: false end end end
BrainDump::Application.routes.draw do root to: 'Todos#index' resources :users resources :todos end
Rails.application.routes.draw do devise_for :users root to: "users#index" scope '/user' do resources :games, only: [:index, :new, :create] end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception def show @bookmark=Bookmark.find_by_id(params['id']) end end
require 'rails_helper' RSpec.describe Thermostat, type: :model do describe 'Associations' do it { should have_many(:readings).dependent(:destroy) } end describe 'Validations' do subject { create(:thermostat) } it { should validate_presence_of(:address) } it { should validate_presence_of(:house...
class JourneyLog attr_reader :logs, :journey def initialize(journey_class = Journey) @logs = [] @journey_class = journey_class new_journey end def start(station) log_journey if current_journey == @journey && !@journey.entry_station.nil? new_journey @journey.add_entry_station(station) ...
[1, 3, 5, 7].each_with_index do |n, index| puts "#{index+1} \t #{n}" end
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 before_action :check_cookies private def is_loged_in? session[:user_id] != nil end def redirect_if_not...
class AddFieldsToUsers < ActiveRecord::Migration def change add_column :users, :full_name, :string add_column :users, :github_link, :string add_column :users, :twitter_link, :string add_column :users, :blog_link, :string add_column :users, :bio, :text add_column :users, :gravitar, :string en...
NUM_ALPHA = ("A".."Z").to_a + ("a".."z").to_a + (0..9).to_a def real_palindrome?(string) string = string.chars.keep_if do |letter| NUM_ALPHA.include?(letter) end.join string.downcase == string.downcase.reverse end # p real_palindrome?("dominik!!!") p real_palindrome?('madam') p real_palindrome?('Madam') ...
class Backend::InvitationsController < Devise::InvitationsController before_action :authenticate_admin!, only: :new before_action :configure_permitted_parameters layout :switch_layout # POST /resource/invitation def create self.resource = invite_resource resource_invited = resource.errors.empty? ...
class Category < ActiveRecord::Base attr_accessible :image, :name has_many :courses validates :name, length: { maximum: 40, minimum: 1 }, presence: true end
module ROM class Relation # Materializes a relation and exposes interface to access the data # # @api public class Loaded include Enumerable # Coerce loaded relation to an array # # @return [Array] # # @api public alias_method :to_ary, :to_a # Source r...
RSpec.describe BinanceAPI::REST do let(:rest) { BinanceAPI.rest } context 'Returns a BinanceAPI::REST' do it { expect(rest).to be_a_kind_of(BinanceAPI::REST) } end context '#ping' do subject { rest.ping } it { is_expected.to have_attributes(value: {}) } it { expect(subject.success?).to be_truth...
describe JobQueueManager do context "no jobs passed" do it "returns an empty array" do expect(described_class.new("").process_jobs_queue).to eq([]) end end context "single job passed" do it "returns the single job" do expect(described_class.new("a =>").process_jobs_queue).to eq(["a"]) ...
class Environment < ActiveRecord::Base has_many :characterenvironments has_many :shelters has_many :characters, through: :characterenvironments has_many :characters, through: :shelters end
# encoding: UTF-8 # # Author:: Xabier de Zuazo (<xabier@zuazo.org>) # Copyright:: Copyright (c) 2015 Xabier de Zuazo # License:: Apache License, Version 2.0 # # 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 t...
# encoding: utf-8 module TextUtils module ValueHelper # if it looks like a key (only a-z lower case allowed); assume it's a key # - also allow . in keys e.g. world.quali.america, at.cup, etc. # - also allow 0-9 in keys e.g. at.2, at.3.1, etc. # - also allow leading digits e.g. 1850muenchen, 3kronen, ...
module Pretentious # Generator for RSPEC class RspecGenerator < Pretentious::GeneratorBase def self.to_sym :spec end def begin_spec(test_class) buffer('# This file was automatically generated by the pretentious gem') buffer("require 'spec_helper'") whitespace buffer("RSpec...
require 'chemistry/element' Chemistry::Element.define "Neptunium" do symbol "Np" atomic_number 93 atomic_weight 237 melting_point '913K' end
class CreateCompanyVendorAgency < ActiveRecord::Migration[5.2] def change create_table :company_vendor_agencies do |t| t.references :vendor_agency, foreign_key: true t.references :company, foreign_key: true end end end
require 'yaml' module XcodeInstaller class ReleaseManager attr_accessor :data def initialize super @data = YAML::load_file(File.join(File.dirname(File.expand_path(__FILE__)), 'xcode-versions.yml')) end def get_all(interface_type) interface_type ||= 'gui' list = data[interfac...
# # test_rest_post.rb : REST POST client for debug # v0.1 2016/02 : developped for REST posting # # usage: # ruby test_rest_post.rb FILENAME www.sample.org 80 # require 'uri' require 'net/http' fname = ARGV[1] jsondata = "" if (fname != nil) then f=open(fname, "r") jsondata = f.read end #p jsondata uri = UR...
class Product attr_reader :category, :name, :unit_price, :quantity def initialize(category, name, unit_price, quantity) @category = category @name = name @unit_price = unit_price @quantity = quantity @hoarded = false @hoard_count = @quantity...
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 before_action :configure_devise_permitted_parameters, if: :devise_controller? before_filter :update_usuario, if: :de...
class LayersControllerTest < ActionController::TestCase fixtures :layers, :roles, :permissions test "index all layers" do get :index assert_response :success @layers = assigns(:layers) assert_not_nil @layers assert @layers.length == 2 end test "search for map via text" do get :...
class Mms::UsersController < Mms::MmsBackEndController def index @mms_users = Mms::User.paginate :page => params[:page], :per_page => 30, :order => 'id asc' end def new @keys = YAML.load_file(File.join(::Rails.root.to_s, 'config', 'permission.yml')).keys @user = Mms::User.new end def crea...
class UserMailer < ApplicationMailer def delete_notification_email(user) @user = user @url = 'http://example.com/register' mail(to: @user.email, subject: 'Your account is deleted') end end
class ChangeIsNvTypeFromWineDetailsAndRegisters < ActiveRecord::Migration def up change_column(:wine_registers, :is_nv, :boolean, :default => false) change_column(:wine_details, :is_nv, :boolean, :default => false) end def down change_column :wine_details, :is_nv, :integer, :limit => 1, :default => 0...
# frozen_string_literal: true require 'test_helper' class PhotoAlbumInterfaceTest < ActionDispatch::IntegrationTest include ActiveJob::TestHelper setup do @user = users :maymie @photo_album = photo_albums :first @image = fixture_file_upload('test/fixtures/files/haha.jpg', 'image/jpg') @images = [...
class CreateAlgorithms < ActiveRecord::Migration[5.1] def change create_table :algorithms do |t| t.string :title t.text :description t.string :author t.string :file_path t.string :time_complexity t.string :space_complexity t.timestamps end end end
# encoding: UTF-8 module API module V1 class UsersDiscussions < API::V1::Base helpers API::Helpers::V1::DiscussionsHelpers before do authenticate_user end namespace :discussions do paginated_endpoint do desc 'List all discussions of current_user.' ge...
Rails.application.routes.draw do mount Deviseadmin::Engine => "/deviseadmin" end
require 'spec_helper' describe User do self.instance_exec &$test_vars it "should have been tested by Divise" do #let's hope end describe "clean_phone_number" do it "should do nothing if the user doesn't have a phone number" do user2.phone.should be_nil user2.update_attributes(name: "Sar...
#Describes a question that a user may ask about a particular route, or potentially any question class Question #Command enum DISTANCE = "Distance" SHORTEST_ROUTE = "ShortestRoute" COUNT_ROUTES = "CountRoutes" attr_accessor :command, :parameters, :constraint, :action def initialize(command, parameters,...
class Customer < ApplicationRecord belongs_to :user has_many :estimates validates_presence_of :name, :email, :phone_number def self.dashboard_stats(time) date = Time.now - time.to_i * 86400 stats = [] ['Not contacted', 'Making decision', 'Customer declined', 'Deal closed'].each do |s| stats << Customer.jo...
# encoding: utf-8 require File.expand_path("../spec_helper", __FILE__) describe "TableBodies" do before :each do browser.goto(WatirSpec.files + "/tables.html") end describe "#length" do it "returns the correct number of table bodies (page context)" do browser.bodies.length.should == 5 end ...
require 'test_helper' class PageTest < ActiveSupport::TestCase # Replace this with your real tests. context "sanitization" do setup do @old_page = Factory.create(:test_page, :title => "yelp") @new_page = Factory.build( :test_page, :title => "<a href=\"http://google.com\">google</a>") end ...
class Song < ApplicationRecord has_many :likes has_many :users, through: :likes has_many :playlist_songs has_many :playlists, through: :playlist_songs validates :name, presence: true, uniqueness: true validates :artist, presence: true validates :genre, presence: true end
class Api::BaseController < ApplicationController def deny_access api_error(status: 403, message: '没有权限') end def api_error(status: 400, message: '') render json: {status: status, message: message, data: {}} end def api_success(message: '', data: {}) render json: {status: 0, message: message, d...
class Alert < Ohm::Model include Ohm::Timestamps attribute :severity attribute :message reference :device, :Device index :severity def reported_at Time.at(created_at).utc end def display_device device_id.nil? ? 'None' : device.serial_number end end
class ApplicationPolicy attr_reader :user, :record def initialize(user, record) @user = user @record = record end def index? false end def show? scope.where(:id => record.id).exists? end def create? false end def new? create? end def update? false end def e...
FactoryBot.define do factory :invitation, class: Invitation do association :user, factory: :user recipient_name "Recipient First Name" sequence(:recipient_email){ |n| "user-#{n}@whatever.mx" } sequence(:token){ |n| "token-string-#{n}" } end end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :validatable has_one :account before_create :build_account def hold(amount) self.balance -= ...
# frozen_string_literal: true module Aid module Scripts class Doctor < Aid::Script def self.description 'Checks the health of your development environment' end def self.help 'doctor - helps you diagnose any setup issues with this application' end def initialize(*ar...
FactoryBot.define do factory :msg do content {"Hello World"} user {build(:user)} room {build(:room)} end end
require_relative '../../../automated_init' context "CLI" do context "Runner" do context "File" do path = Controls::Path::TestFile.example context "Path Does Not Match Exclude File Pattern" do runner = CLI::Run.new runner.exclude_file_pattern = Controls::Pattern::None.example ...
class Admin::PlayersController < Admin::BaseController before_action :set_admin_User, only: [:show, :edit, :update, :destroy] # GET /admin/Users # GET /admin/Users.json def index @admin_players = User.where(user_type: 2) end # GET /admin/Users/1 # GET /admin/Users/1.json def show end # GET /a...
class AddTitleAndUserToCampaign < ActiveRecord::Migration def self.up add_column :campaigns, :title, :string add_column :campaigns, :user_id, :integer end def self.down remove_column :campaigns, :user_id remove_column :campaigns, :title end end
# encoding: utf-8 class ImageUploader < CarrierWave::Uploader::Base include CarrierWave::MiniMagick include CarrierWave::MimeTypes include Sprockets::Helpers::RailsHelper include Sprockets::Helpers::IsolatedHelper storage :file def store_dir "system/uploads/#{model.class.to_s.underscore}/#{mounted_...
module Spree class CartRemovalsReport < Spree::Report DEFAULT_SORTABLE_ATTRIBUTE = :product_name HEADERS = { sku: :string, product_name: :string, removals: :integer, quantity_change: :integer } SEARCH_ATTRIBUTES = { start_date: :product_removed_from, end_date: :product_removed_to } SORTABLE_ATTRIBUTES...
class CreateClassRooms < ActiveRecord::Migration def change create_table :class_rooms do |t| t.string :name t.references :creator, polymorphic: true, index: true t.references :school, index: true t.references :school_branch, index: true t.string :grade t.timestamps end e...
module Services class UserApplicationService < ApplicationService def self.base_url; "apps" ; end # Create a new user application. # Requires a user token post "/" do user = authenticate(:user) application = UserApplication.new(user: user, name: params[:name]) if application.save ...
class Season < ApplicationRecord belongs_to :pitcher end
class Pokemon attr_accessor :id, :name, :type, :db def initialize(id:, name:, type:, db:) @id = id @name = name @type = type @db = db end def self.save(name,type,db) new_pokemon = self.new(id: nil, name: name, type: type, db: db) sql = "INSERT INTO pokemon (name, type) VALUES (?, ?);" new_pokemon.db....
class ChangeNotNullToLocalregions < ActiveRecord::Migration def change change_table :localregions do |t| t.change :name, :string, limit: 30, null: false t.change :ranking, :integer, null: false t.remove :country_id t.references :country, null: false end end end
# frozen_string_literal: true require "spec_helper" RSpec.describe Tikkie::Api::V1::Responses::Users do subject { Tikkie::Api::V1::Responses::Users.new(response) } let(:response) { instance_double("Net::HTTPResponse", body: body, code: response_code) } let(:body) { File.read("spec/fixtures/responses/v1/users/l...
require "rails_helper" RSpec.describe Product, type: :model do it { is_expected.to belong_to(:brand) } it { is_expected.to belong_to(:category) } it { is_expected.to validate_presence_of(:name) } it { is_expected.to validate_presence_of(:brand) } it { is_expected.to validate_presence_of(:category) } it { ...
describe Bootcamp::TimeFormatter do it 'returns the right time format' do expect(Bootcamp::TimeFormatter.new(62).format_time).to eq('1 minute and 2 seconds') expect(Bootcamp::TimeFormatter.new(120).format_time).to eq('2 minutes') expect(Bootcamp::TimeFormatter.new(3600).format_time).to eq('1 hou...
class RemoveColumnFromItems < ActiveRecord::Migration def change remove_column :items, :description, :string remove_column :items, :slug, :string remove_column :items, :status, :string end end
require 'chemistry/element' Chemistry::Element.define "Praseodymium" do symbol "Pr" atomic_number 59 atomic_weight 140.90765 melting_point '1204K' end
class FontDelugiaPowerline < Formula version "2111.01.2" sha256 "4837f79108f43532935048208d423a17b159fa1f0ec436614c5248dd64b5a22f" url "https://github.com/adam7/delugia-code/releases/download/v#{version}/delugia-powerline.zip" desc "Delugia Code" desc "Cascadia Code + Nerd Fonts, minor difference between Cask...
class TaskDecorator include TimePresenter attr_reader :task, :name delegate :id, :time, :start_time, :stop_time, :duration, :user_id, :created_at, :updated_at, :project, :minutes, :hours, to: :task def initialize(task) @task = task @name = set_name end def time_span "#{start_time_fo...
require "adjustable_image/version" require 'adjustable_image/has_adjustable_image' require 'adjustable_image/adjustable_styles' require 'adjustable_image/image_adjustments' require 'paperclip' require 'adjustable_image/processors/dynamic_extent_processor' require 'adjustable_image/processors/dynamic_resize_processor...
ActiveAdmin.register Customer do batch_action :destroy, false filter :name filter :lastname filter :nickname filter :email filter :phone filter :created_at actions :all, :except => [:new,:edit,:delete] index do selectable_column column :name column :lastname column :nickname column :email column ...
class FriendshipsController < ApplicationController def create Friendship.create(params[:friends].permit!) redirect_to :controller => 'users', :action => 'show', id: session[:users] end def update pending = Friendship.find_by(requesting_id: params[:friends][:requesting_id],accepting_id: params[:frie...
RSpec.describe WorkflowCreateService do let(:template) { create(:template) } let(:groups) { create_list(:group, 3) } subject { described_class.new(template.id) } context 'create workflow' do it 'create a workflow with valid group ids' do workflow = subject.create(:name => 'workflow_1', :description...
ActiveRecord::Schema.define :version => 0 do create_table :things do |t| t.string :name end create_table :thing_groupings do |t| t.integer :thing_id t.string :thingable_type t.string :thingable_id end end
ActiveAdmin.register ConfigUserPermission do permit_params :is_accepting, :is_only_show index do panel "注意書き" do "'非表示' 状態 : 両方を'いいえ'に変更. 対応するTop Pageの登録フォームを非表示. ユーザからの編集不可. " end id_column column :form_name column :is_accepting column :is_only_show column :pan...
require 'capybara/rspec' require 'user' require_relative 'user_management_helpers' feature 'signing up' do include User_Management_Helpers scenario 'clicking sign up button' do visit('/') find_button('Sign Up').click expect(current_path).to eq('/signup') end scenario 'signing up' do expect(Use...
class CreateSubjects < ActiveRecord::Migration def change create_table :subjects do |t| t.string "provider" t.integer "uid" t.string "oauth_token" t.datetime "oauth_expires_at" t.string "first_name" t.string "middle_name" t.string "last_name" t.timestamps end end ...
module ResumeSearch extend ActiveSupport::Concern #Note that this aggregation includes the from value and excludes the to value for each range. EXPERIENCE_LEVELS = { 'less_than_1_year' => { where: { lt: 1 }, range: { to: 1 } }, '1-2_years' => { where: 1..2, range: { from: 1, to: 3 } }, '3-5_years' =>...
require "digest/md5" require "rufus/sc/cronline" module Zulu class Topic KEY_PREFIX = "topic".freeze UPCOMING_KEY = "#{KEY_PREFIX}:upcoming".freeze def self.happening(now=Time.now) Zulu.redis.zrangebyscore(UPCOMING_KEY, 0, now.to_i) end def initialize(options={}) @id ...
json.array!(@pessoas) do |pessoa| json.extract! pessoa, :id, :nome, :data_nasc, :sexo, :pais json.url pessoa_url(pessoa, format: :json) end
class Category < ActiveRecord::Base has_many :ts has_many :category_relationships, dependent: :destroy attr_accessible :name end
require 'spec_helper' require 'shoulda/matchers' RSpec.describe Artwork, type: :model do describe 'associations' do [:card].each do |association| it { is_expected.to belong_to association } end end describe 'attributes' do [:id, :image_path, :card_id].each do |attribute| it { is_expected...
class ProjectsController < ApplicationController before_action :set_project, only: [:show, :edit, :update, :destroy] def index @projects = Project.all end def show @contractors = @project.contractors @sites = @project.sites @proposals = @project.proposals end def new @project = Projec...
require 'faker' class Pedido attr_reader :codigo # attr_reader :total # la suma total del pedido attr_accessor :productos # almacenar una lista/array de productos attr_reader :fecha_creacion # fecha de hoy attr_accessor :fecha_entrega # sumar a la fecha...
require_relative '../nat_queue.feature' Given(/^I have a queue$/) do $queue = NatQueue.new end When(/^I enqueue the item (\d+)$/) do |item| $queue.enqueue(item.to_i) end Then(/^the item (\d+) is present in the queue$/) do |item| elem = $queue.dequeue expect(item.to_i).to eq(elem), "Expected #{item} got #{ele...
describe "Categories routing" do it 'routes to index' do { get: '/categories' }.should route_to controller: 'categories', action: 'index' end it 'no routes to show' do { get: '/categories/1/'}.should_not route_to controller: 'categories', action: 'show', id: '1' end it 'routes to new' do { get: ...
class Cinema attr_reader :name, :premiere_date def initialize(name) @name = name @observers = [ ] end def new_film(premiere_date) @premiere_date = premiere_date notify_observers end def add_observer(observer) @observers << observer end def notify_observers @observers.each { |...