text
stringlengths
10
2.61M
class CreateDiaries < ActiveRecord::Migration[6.0] def change create_table :diaries do |t| t.date :date, null: false t.integer :alcohol_amount t.string :title t.text :comment t.integer :small_beer t.integer :large_beer t.integer :japanese_sake t.integer :wine ...
class ApplicationController < ActionController::Base protect_from_forgery before_filter :load_languages def load_languages @language = Language.where( { :acronym => params[:acronym] } ).first @languages = Language.all end end
require_relative '../lib/service/cashier' require_relative '../lib/service/packer' RSpec.describe 'Service' do context 'Cashier' do it 'should process the orders in the cart' do cart = Cart.new cart.add('VS5', 24) total = Service::Cashier.call(cart) expect(total).to eq('55.92') end ...
# frozen_string_literal: true describe Kafka::Compression do Kafka::Compression.codecs.each do |codec_name| describe codec_name.to_s do it "encodes and decodes data" do data = "yolo" codec = Kafka::Compression.find_codec(codec_name) expect(codec.decompress(codec.compress(data))).to...
class CreateRecords < ActiveRecord::Migration[6.0] def change create_table :records, id: :uuid do |t| t.references :user, null: false, index: true, foreign_key: true, type: :uuid t.integer :group, null: false t.integer :points, null: false t.string :country_code, limit: 2, null: false ...
#!/usr/bin/env ruby # :title: PlanR::Content::Node =begin rdoc (c) Copyright 2016 Thoughtgang <http://www.thoughtgang.org> =end module PlanR module ContentRepo autoload :DirNode, 'plan-r/content_repo/dir_node' =begin rdoc Base class for content tree nodes. A node basicall has the following attributes: * pat...
Pod::Spec.new do |s| s.name = "KHDataBinding" s.version = "0.8.8" s.summary = "using swizzle method to binding table view or collection view with a NSMutableArray" s.description = <<-DESC to sync table view display with an array DESC s.homepage = "https://g...
class Bs::Api::V1::Elawa::SegmentsController < Bs::Api::V1::ApplicationController def create @segment = Bs::Elawa::Segment.new(permit_params) authorize @segment res = @segment.save if res render_api_data(@segment) else render_api_error(t('helpers.form_error')) end end def s...
# CSS Media Fu # This plugin parses browser user agent # and sets the session[:media] variable # according to a look up table in # config/media_types.yml module CSS_Media_fu # Load the config file, and search for a match to the given string def find_media_type(agent) media_types = YAML::load(File.open("#{RAILS...
require 'spec_helper' describe GQLi::Response do let(:errors) { nil } let(:data) { {"testkey" => "test val"} } let(:query) { double(:query) } subject { described_class.new(data, errors, query) } describe "#data" do it "returns correct data Hashie" do expect(subject.data).to be_kind_of(Hashie::Mash...
class NotificationsController < ApplicationController def index @incomplete_notifications = Notification.where(recipient: current_user).incomplete.order("created_at DESC") @complete_notifications = Notification.where(recipient: current_user).completed end def create @classroom = Classroom.find(param...
class Deck def initialize @cards = Card::RANKS.map do |rank| Card::SUITS.map do |suit| Card.new(rank, suit) end end.flatten end def count @cards.size end def shuffle! @cards.shuffle! end def draw(n) @cards.pop(n) end end
require 'hyper_mapper' class Comment include HyperMapper::Document attr_accessible :user_id, :text autogenerate_id attribute :text attribute :user_id timestamps belongs_to :user embedded_in :post end
module Mutations module CalendarItems class CreateCalendarItem < BaseMutation description 'Creates a CalendarItem' argument :title, String, required: true argument :description, String, required: true argument :user_id, ID, required: true type Types::CalendarItemType def res...
require "test_helper" class FixerUpperTest < TestCase def test_it_figures_out_engines_from_filename renderer = new_fixer_upper.renderer( filename: "cool.txt.erb", engines: %w[erb txt], content: %(this file is <%= "cool" %>), view_scope: BasicObject.new ) assert_equal("this file i...
# frozen_string_literal: true module Admin # Appointment actions class AppointmentsController < ApplicationController before_action :authenticate_user! before_action :new_appointment before_action :find_appointment, only: %i[cancel_appointment] before_action :cannot_cancel_appointment_if_done, only...
require 'active_record' require './app/enums/attribute_param' ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: 'db/bot.db') class Animal < ActiveRecord::Base belongs_to :village belongs_to :player has_one :rpg_class has_one :rpg_attribute def self.type_value "" end def type_value se...
class PlayerSerializer < ActiveModel::Serializer has_one :user has_many :cards has_many :damage_tokens has_many :tanks attributes :ready, :damage, :outward_hand, :inward_hand def damage object.damage end def outward_hand object.cards.where(location: ["hand", "action","trashed"]) end def ...
module Resourceful module CollectionTableApi extend ActiveSupport::Concern included do @columns = [] def self.columns @columns end def columns self.class.columns || {} end protected def self.column(name, opts={}) @co...
module Tolaria # Contains a workflow for rendering Markdown. # If no renderer has been configured, defers to `simple_format`. class MarkdownRendererProxy include ::ActionView::Helpers::TextHelper # Calls the configured Markdown renderer, if none exists # then uses `simple_format` to return more tha...
require_relative 'Ante_1' describe Card do let(:card) {Card.new('AD')} it 'can parse the card value' do expect(card.val).to eq 'A' end it 'can parse the card suite' do expect(card.suite).to eq 'D' end end
class AddCurrencyToCoupons < ActiveRecord::Migration def change add_column :coupons, :currency, :string end end
require 'betfair_api_ng_rails/api/concerns/errorable' module BetfairApiNgRails module Api class SessionManager class << self include Api::Concerns::Errorable include Api::Constants def ssoid @ssoid ||= fetch_ssoid end def request_ssoid ssoid ...
require 'yaml' module Recipes class Recipe include FileEntity attr_accessor :data def initialize(directory, filename) super @data = YAML.load_file(file_name) end def respond_to_missing?(m, include_all) @data.key?(m) end protected def method_missing(m, *args, &bl...
module Caren class Base # New objects are found and created in this context by default def self.storage_context @storage_context ||= Caren::StorageContext.shared end def self.remote @remote ||= Caren::Remote::Proxy.new(self, array_root, node_root, properties) end def toXml ...
# frozen_string_literal: true require "spec_helper" module Decidim describe Search do subject { described_class.new(params) } include_context "when a resource is ready for global search" let(:current_component) { create :opinion_component, organization: organization } let!(:opinion) do creat...
json.array!(@peliculas) do |pelicula| json.extract! pelicula, :id, :Nombre, :Rating json.url pelicula_url(pelicula, format: :json) end
# @version 1.1.0 module Nordea # The gem version VERSION = "1.1.0" end
class ServiceType < ActiveRecord::Base has_many :highlights has_many :ecommers, :through => :highlights end
# frozen_string_literal: true class Deal < ApplicationRecord belongs_to :profile belongs_to :package belongs_to :item end
class Song < ApplicationRecord # validates :title, presence: true # validates :artist_name, presence: true # validates :released, inclusion: { in: [true, false], message: "%{value} is not valid" } validates :title, presence: true validates :title, uniqueness: { scope: :release_year, message: "should...
class UserLocationsController < ApiController requires_authentication def create @user = current_user @user.update_geolocation params[:latitude], params[:longitude] render :json => @user end end
module Errors class ValidationFailed < Error key :validation_failed custom_properties :details end end
DataMapper.setup(:default, ENV['DATABASE_URL'] || "sqlite3://#{Dir.pwd}/development.db") class Movie include DataMapper::Resource property :id, Serial property :name, String, :required => true property :director, String property :year, String end DataMapper.finalize
# frozen_string_literal: true module FacebookAds # https://developers.facebook.com/docs/marketing-api/reference/custom-audience class AdAudience < Base FIELDS = %w[id account_id subtype name description approximate_count data_source delivery_status external_event_source lookalike_audience_ids lookalike_spec op...
# frozen_string_literal: true module Api module V1 module JWT module Encode include Shared def create_jwt(data) data[:access] ||= default_access jwt = ::JWT.encode(jwt_payload(data), default_jwt_secret, 'HS512') NewJWT.new('JWT', jwt, jwt_expires_at) ...
require 'javaclass/classfile/access_flags' require 'javaclass/classfile/class_format_error' module JavaClass module ClassFile # The access flags of a class or interface. # Author:: Peter Kofler class ClassAccessFlags < AccessFlags # Bitmask for unknown/not supported flags on classes. ...
require 'ftp_client' class PagesController < ApplicationController before_filter :authenticate_all!, :only => [:show, :update] before_filter :authenticate_owner!, :except => [:show, :update] before_filter :find_site, :only => [:new, :create, :enable] before_filter :find_page, :only => [:show, :destroy, :update...
class RenameDataFileTable < ActiveRecord::Migration def change rename_table :data_files, :raw_data end end
#!/usr/bin/env ruby # Creates the files in lib/shaml/templates and builds the gem require 'rubygems' require 'fileutils' require 'zip/zipfilesystem' require "rexml/document" IGNORES = [ /bin$/, /obj$/, /TestResults$/, /TestResult\.xml$/, /drops$/, /log\.txt$/, /\.VisualState\.xml$/, /StyleCop.Cache$/,...
class CourseReview < ActiveRecord::Base attr_accessible :usefulness, :stimulating, :content_quality, :homework_difficulty, :lab_difficulty, :midterm_difficulty, :final_difficulty, :course_meta_id, :out_of_class_work_hours, :review_content, :author validates :usefulness, :stimulating, :content_quality, :homewo...
class Post < ActiveRecord::Base belongs_to :user has_many :replies validates_presence_of :title, :tekst validates :tekst, length: {minimum: 10} end
require 'formula' class I686ElfBinutils < Formula homepage 'https://www.gnu.org/software/binutils/' url 'https://mirrors.tuna.tsinghua.edu.cn/gnu/binutils/binutils-2.29.tar.xz' mirror 'http://ftp.gnu.org/gnu/binutils/binutils-2.29.tar.xz' sha256 '0b871e271c4c620444f8264f72143b4d224aa305306d85dd77ab8dce785b1e85...
class Repay < ApplicationRecord belongs_to :user before_create :set_status validates :value, presence: true validates :description, presence: true validates :kind, presence: true enum status: [:pendente, :negado, :pagamento_aprovado, :pago, :recibo_feito] enum kind: [:politica_de_beneficios, :reembolso]...
# Events controller so gooood class EventsController < ApplicationController before_action :set_event, only: %i[follow unfollow show] before_action :authenticate_user!, only: %i[follow unfollow] DATA_QUERIES = %w[s name_cont intro_cont date_cont time_cont ticket_link_cont price_cont name_or_intro_or_date_or_time...
# frozen_string_literal: true module ErrorHelpers def without_errors? errors.count.zero? end end
class AddClassCodeToClassrooms < ActiveRecord::Migration[5.0] def change add_column :classrooms, :class_code, :string end end
require "fog/core/collection" require "fog/brkt/models/compute/load_balancer" module Fog module Compute class Brkt class LoadBalancers < Fog::Collection model Fog::Compute::Brkt::LoadBalancer # Get load balancers. # # @return [Array<LoadBalancer>] load balancers def...
Rails.application.routes.draw do devise_for :admins namespace :backend do get 'pop_map/index' match 'pop_map/edit/:id', to: 'pop_map#edit', as: 'pop_map_edit', via: [:get, :post] get 'account/index' get 'account/buy' get 'account/show/:id', to: 'account#show', as: 'account_show' post 'acco...
class Order < ApplicationRecord self.per_page = 10 default_scope { order("created_at DESC") } end
class ChangUrlType < ActiveRecord::Migration def change remove_column :channels, :url add_column :channels, :url, :text end end
class ApiController < ApplicationController def routing_error render :json => {:error => 'URL must be in the format /RESOURCES and contain the correct Accept header'}, :status => :bad_request end end
require 'rails_helper' feature "Reviews" do context "Walking through needed CRUD actions" do xscenario "Review page shows correct content" do user = FactoryGirl.create(:reg_user) visit reg_user_reviews_path(user) expect(page).to have_content("Reviews Index page") end xscenario "New...
require 'spec_helper' describe Nation, type: :model do it 'should create a nation' do expect { Nation.make! }.not_to raise_error end it 'should require an abbr' do expect(Nation.make(abbr: nil)).to_not be_valid end it 'should assign upcase abbr' do expect(Nation.make!(abbr: 'br').abbr).to eq('B...
require "spec_helper" require "factory_girl" describe "validations" do before(:each) do @pool_attr = FactoryGirl.attributes_for(:pool) @college_attr = FactoryGirl.attributes_for(:college) @applicants_attr = FactoryGirl.attributes_for(:applicants) end it "should not create a new instance o...
#### Preparing tools # Ruby and many other programming languages allow one to load # additional code of which may be called upon when writing one's code. # Below several software libraries will be loaded for the task at hand. # [open-uri](http://ruby-doc.org/stdlib/libdoc/open-uri/rdoc/index.html) is part of the [Rub...
require 'holidays' # # # facilities management calculator based on Damolas spreadsheet - the first set framework calculations are repeated with a benchmark rate to give two values # # 1. Unit of measure of deliverables required # # # 3. Benchmarked costs # # the calculations are simple and sequential based on previou...
class AddFinishToGames < ActiveRecord::Migration def change add_column :games, :finish, :boolean end end
module Users class RegistrationsController < Devise::RegistrationsController include SetLayout before_action :find_organization layout :company def new @remote = params[:remote] == 'true' build_resource({}) if defined?(@organization) resource.role = 'client' resourc...
require 'account' describe Account do let(:history) do double :history, log_deposit: nil, log_withdrawal: nil, show_statement: 'statement' end let(:account) { described_class.new(history) } describe '#deposit' do it 'adds amount to balance' do expect { account.dep...
cask :v1 => 'yourkit-java-profiler' do version '2014-build-14114' sha256 'd64d6496a7ae8e240ab5c32f6b1727898cd69a8f2e2716cf9901e3a9cc8a4c26' url "http://www.yourkit.com/download/yjp-#{version}-mac.zip" name 'YourKit Java Profiler' homepage 'http://www.yourkit.com/overview/' license :commercial tags :vendo...
require 'spec_helper' require 'level_object/bomb' describe LevelObject::Bomb do subject { described_class.new(image_registry, level, x, y) } let(:image_registry) { double } let(:level) { double } let(:x) { 10 } let(:y) { 20 } context '#touch' do let(:object) { double(damage: double) } let(:damage)...
class IndividualReport < ActiveRecord::Base require "#{Rails.root}/lib/gradebook/reports/template.rb" Dir["#{Rails.root}/lib/gradebook/components/models/*.rb"].each {|file| require file} Report = Struct.new(:profile, :main_header, :header, :marks, :excluded_marks, :activities, :overall_marks, :overall_grades, ...
module Concerns::BookRequestBase extend ActiveSupport::Concern included do def get_link(name, path, icon_class) class_name = "btn btn-sm " + icon_class link_to(name, path , class: class_name, data: {role: "button"}) end def get_info_expired_button(request) if request.days_to_return >...
QUERY_API = "https://query.wikidata.org" # Wikidata SPARQL queries class Sparql def self.concept # Keep going until you get a concept that has a label, not just a Q-number loop do concept = new.random_concept_label return concept unless concept.match?(/Q\d+/) end end def self.orchid ...
class AddArtToDebits < ActiveRecord::Migration def change add_column :debits, :art, :string add_column :debits, :helper ,:string end end
module Fakes module ArgumentMatching def not_nil condition { |item| !item.nil? } end def nil condition(&:nil?) end def any condition { |ignored| true } end def greater_than(value) condition { |number| number > value } end def in_range(range) condi...
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure('2') do |config| # Strings identifying Bento baseboxes from https://github.com/opscode/bento %w{ centos-6.6 centos-7.0 debian-7.8 fedora-21 ubuntu-14.04 }.each do |basebox| # Easier instance naming without dots or dashes inst...
class PortfolioItemsController < ApplicationController before_filter :authenticate_admin!, except: [:index, :show] # GET /portfolio_items def index @portfolio_items = PortfolioItem.all end # GET /portfolio_items/1 def show @portfolio_item = PortfolioItem.find(params[:id]) end # GET /portfolio_...
namespace :pq do desc 'Object test generator' task :class do ruby 'lib/query.rb class' end desc 'Method test generator' task :method do ruby 'lib/query.rb method' end desc 'Invoke troubleshoot module from main pq command' task :help do ruby 'lib/query.rb help' end end
require_relative "node" class Linkedlist attr_reader :head, :tail def initialize @head = nil @tail = nil end def show_all n1 = @head while n1.nexxt do print n1.value.to_s + ", " n1 = n1.nexxt end print n1.value.to_s + "\n" end def to_a n1 = @head a = Array.n...
#! /usr/bin/ruby require 'optparse' require "./configuration.rb" require "./recipe.rb" class Solver attr_accessor :recipes,:speeds,:to_craft,:target_rate def initialize config @to_craft=config.options["to_craft"] @target_rate=config.options["target_rate"] @recipes={} @speeds={"smelting"=>2,"crafti...
#!/usr/bin/env ruby # -------------------------------------------------------------------------- # # Copyright 2002-2012, OpenNebula Project Leads (OpenNebula.org) # # # # Licensed under the Apache License, Version 2.0 (the "License...
git_src_path = ::File.join(node['git']['srcLocalDir'], node['git']['srcLocalFileVersion']) + node['git']['srcLocalFileExtension'] remote_file git_src_path do action :create_if_missing source node['git']['srcRemoteUrl'] checksum node['git']['srcChecksum'] notifies :run, 'bash[install_git]', :immediately end ba...
require 'rails_helper' RSpec.describe News, type: :model do describe 'DB table' do it {is_expected.to have_db_column :title} it {is_expected.to have_db_column :content} end describe 'Validations' do it {is_expected.to validate_presence_of :title} it {is_expected.to validate_presence_of :content}...
Rails.application.routes.draw do resources :favorites # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html root to: 'sessions#welcome' get '/auth/google_oauth2/callback', to: 'sessions#omniauth' get '/login', to: 'sessions#new' post '/login', to: 'sessions...
###Student Ruby Assessment # Instructions # Create a file with "<yourName>_assessment.rb". # Sections 1-6 # Title each section with a comment that includes the name and number of each section. # Then write the ruby that fulfills each lettered instruction under the title. There is no need to structure your code based ...
# frozen_string_literal: true module WasteExemptionsShared module OrganisationType class Partnership < Organisation has_many :partner_contacts, -> { where(contact_type: Contact.contact_types[:partner]) }, inverse_of: :partnership_organisation, foreign_key: "part...
require 'rails_helper' RSpec.describe EventsController do allow_user_to(:manage, Event) render_views describe 'GET #index' do it 'sets instance_variables' do create(:event, title: 'Second', start_time: 5.days.ago) create(:event, title: 'First', start_time: 10.days.ago) get(:index) e...
# frozen_string_literal: true class Users::RegistrationsController < Devise::RegistrationsController include Accessible before_action :configure_sign_up_params, only: [:create] # before_action :configure_account_update_params, only: [:update] # GET /resource/sign_up # def new # super # end # POST /...
require 'rails_helper' describe Token do describe '.active' do it 'returns tokens that are not expired' do t1 = create(:token) t2 = create(:token_expired) t3 = create(:token) expect(Token.active).to_not be_empty expect(Token.active.count).to eq(2) expect(Token.active).to_not ...
require 'yaml' require 'erb' namespace :rpm do namespace :spec do desc 'Generate RPM Spec file for this Rails Application' task :generate do puts "we are in #{Dir.pwd} - how do we get to the App dir and the Gem's templates dir?" opts = YAML.parse_file('./config/rpm/rpm_config.yml').to_ruby ...
require 'spec_helper' describe Susanoo::Admin::PageTemplatesController do shared_context "rubi_filter" do context "content_type = 'text/html', cookie[:ruby] = 'on' の場合" do before do cookies[:ruby] = 'on' end it "ルビがふられたテキストが出力されること" do subject expect(response.body).to e...
# workspace file for keeping all things slack require "dotenv" require "httparty" require_relative "user" require_relative "channels" Dotenv.load module Slack class Workspace URL = "https://slack.com/api/users.list" attr_reader :users, :channels attr_accessor :selected def initialize @users ...
class CoverInfo attr_accessor :source_name attr_accessor :last_checked attr_accessor :url attr_accessor :has_cover attr_accessor :isbn attr_accessor :upc @source_name @last_checked @url @has_cover @isbn @upc def initialize(source_name) @source_name = source_name end def to_json instance_variables....
class ChangeFeeDiscountIdAllowNullToFinanceFeeDiscounts < ActiveRecord::Migration def self.up change_column :finance_fee_discounts, :fee_discount_id, :integer, :null => true end def self.down change_column :finance_fee_discounts, :fee_discount_id, :integer, :null => false end end
class AddUserIdToTeamMasters < ActiveRecord::Migration def change add_column :team_masters, :user_id, :integer end end
Pod::Spec.new do |s| s.name = 'YLCategory' s.version = '1.2.6' s.summary = '分类' s.homepage = 'https://github.com/yulong000/YLCategory' s.license = { :type => 'MIT', :file => 'LICENSE'} s.author = { 'weiyulong' => 'weiyulong1987@163....
class AddSelfRefToPhase < ActiveRecord::Migration def change add_column :phases, :next_phase_id, :integer add_column :phases, :prev_phase_id, :integer end end
require 'spec_helper' describe "developers/edit.html.erb" do before(:each) do @developer = assign(:developer, stub_model(Developer, :userID => 1, :lessonID => 1 )) end it "renders the edit developer form" do render # Run the generator again with the --webrat flag if you want to use ...
class GiveDatRow < ActiveRecord::Migration def change add_column :eostoredats, :eorow, :integer end end
require 'oauth' require 'json' require 'csv' require 'time' require 'fileutils' class GoodDataTwitterAds::StatsPromotedTweets attr_reader :client def initialize config={} @client = config[:client] end #-----------------------------------------------------PROMOTED TWEETS STATS------------------------------------...
require "csv" path = ARGV[0] raise "需要指定csv 文件路径" if path.blank? raise "#{path} 不是一个有效的文件路径" if !File.exists?(path)
require File.dirname(__FILE__) + '/../../../spec_helper' require File.dirname(__FILE__) + '/../../../shared_examples/servers_examples' describe 'Fog::AWS::EC2::Servers' do it_should_behave_like "Servers" subject { @server = @servers.new(:image_id => GENTOO_AMI) } before(:each) do @servers = AWS[:ec2].serv...
class AddWhitelabelEnabledToSchoolGroups < ActiveRecord::Migration def self.up add_column :school_groups, :whitelabel_enabled, :boolean, :default=>false add_column :school_groups, :license_count, :integer end def self.down remove_column :school_groups, :whitelabel_enabled remove_column :school_gr...
require 'spec_helper' describe User do let(:user) { Fabricate(:user) } it 'has associated people' do expect(user.people).to be_instance_of(Array) end it 'builds associate people' do person1 = Fabricate :person person2 = Fabricate :person [person1, person2].each do |person| expect(user.peop...
require 'spec_helper.rb' feature 'Viewing links' do scenario 'prints list of links on homepage' do visit '/links' expect(page.status_code).to eq 200 expect(page).to have_content('Makers Academy') end before(:each) do Link.create(url: 'http://www.makersacademy.com', title: 'Mak...
class Chapter < ActiveRecord::Base attr_accessible :name, :dese, :course belongs_to :course validates :name, :presence => true end
FactoryBot.define do factory :order_address do postal_number { '123-4567' } prefecture_id { 2 } city { '横浜' } house_number { '青山' } building_number { '柳ビル' } phone_number { '00012345678' } token { "tok_abcdefghijk00000000000000000" } end end
# frozen_string_literal: true module TurnipPrice module Formula class LargeSpike < Base # :nodoc: # # @see TurnipPrice::Formula::Base#initialize # # @since 0.1.0 def initialize(*args) super @start = @random.int(3..9) @pointer = @start - 1 end ...