text
stringlengths
10
2.61M
require_relative('basket') class Discount def initialize(params) end def calculate(basket, running_total) raise 'Not implemented' end end class MultiBuyDiscount < Discount def initialize(params) super(params) @amount_needed = params[:amount_needed] @code = params[:code] @discount_price...
require 'lib/racional.rb' require 'rspec' describe Racional do before :each do @rac = Racional end it "Debe existir un numerador" do @rac.new(1, 2).num.should == 1 end it "Debe existir un denominador" do @rac.new(1, 2).den.should == 2 end it "Debe de estar en su forma reducida" do @rac.new(2, 4).nu...
class Venue < ActiveRecord::Base has_many :gigs geocoded_by :address after_validation :geocode end
namespace :brewery_db do namespace :synchronize do things = %w[ingredients events guilds breweries styles beers locations].map(&:to_sym) things.each do |thing| desc "Synchronizes #{thing} with BreweryDB's data. Adds, updates, and removes as necessary." task thing => :environment do puts "...
class AddQuestionCountToTopics < ActiveRecord::Migration[5.0] def change add_column :topics, :questions_count, :integer, default: 0 add_column :topics, :recursive_questions_count, :integer, default: 0 end end
require 'rails_helper' RSpec.describe Goal, type: :model do describe 'validations' do it {should validate_presence_of(:user_id)} it {should validate_presence_of(:completed)} it {should validate_presence_of(:private)} it {should validate_presence_of(:details)} it {should validate_presence_of(:titl...
class Ability include CanCan::Ability def initialize(user) if user && user.admin? can :access, :rails_admin # only allow admin users to access Rails Admin can :dashboard # allow access to dashboard end if user && user.admin? can :manage, [Group, Server, User] ...
class CreateNats < ActiveRecord::Migration[5.1] def change create_table :nats do |t| t.string :name t.integer :ext_port t.integer :int_port t.string :int_ip t.boolean :state t.string :owner t.timestamps end add_index :nats, :ext_port, unique: true end end
def position_taken?(board, index) !(board[index].nil? || board[index] == " ") end WIN_COMBINATIONS = [[0, 1, 2],[3, 4, 5],[6, 7, 8],[2, 5, 8],[1, 4, 7],[0, 3, 6],[0, 4, 8],[6, 4, 2]] def won?(board) WIN_COMBINATIONS.detect do |combo| board[combo[0]] == "X" && board[combo[1]] == "X" && board[combo[2]] == "X" ...
class Ship attr_reader :location, :type, :xsize def initialize(matrix, options) @xsize = options[:size] @type = options[:type] @matrix = matrix @location = [] end def build begin destroy ship_len = @xsize mask = [] # random start point begin x...
class Link include Mongoid::Document include AASM include Mongoid::Timestamps field :href, type: String field :description, type: String field :aasm_state validates :href, presence: true validates :description, length: { maximum: 200 } before_save :normalize_href, if: :invalid_format? belongs_to...
class FixSendtForMailings < ActiveRecord::Migration def up rename_column :mailings, :sendt_at, :send_at change_column :mailings, :send_at, :time end def down change_column :mailings, :send_at, :date rename_column :mailings, :send_at, :sendt_at end end
require 'spec_helper' describe EssayStyle do subject { described_class.new } [:title].each do |field| it "has the ##{field} attribute" do expect(subject).to respond_to(field) expect(subject).to respond_to("#{field}=") end end describe '#friendly_id' do it "is based on the title" do ...
class Actor <ApplicationRecord validates_presence_of :name has_many :movie_actors has_many :movies, through: :movie_actors def associates movies.joins(:actors).where('name !=?', self.name).order("name").distinct.pluck(:name).join(", ") # I had trouble with the `order` method. # Is there a way to or...
class AddStateToOrders < ActiveRecord::Migration[5.1] def change add_column :orders, :payment_status, :integer, default: "0", null: false rename_column :orders, :status, :order_status end end
require 'spec_helper' describe Post do it { should respond_to :title } it { should respond_to :content } it { should respond_to :comments_count } it { should respond_to :user_id } it { should respond_to :created_at } end
class QuickReplacementOrder < ReplacementOrder state_machine :initial => :claim_asset_product do command :record_replacement_product, :parent_name => :order do transition :claim_asset_product => :complete end after_transition :on => :record_replacement_product do |replacement_order| repla...
# == Schema Information # # Table name: issues # # id :integer not null, primary key # project_id :integer # user_id :integer # assignee_id :integer # subject :string(255) # description :text # status :integer # created_at :datetime not null # updated_at :datetime ...
require 'ElevatorMedia' require 'spec_helper' describe ElevatorMedia do describe "Weather" do streamer = ElevatorMedia::Streamer.new("07112") context "test to get Streamer class" do it "return Streamer class" do expect(streamer).to be_a(ElevatorMedia::Streamer) end end context "test to ge...
class Types::FormTypeType < Types::BaseEnum Form::FORM_TYPE_CONFIG.each do |key, config| value key, config['description'].capitalize end end
Rails.application.routes.draw do get '/cities' => 'cities#index' end
require 'semverly' require 'open3' require 'bundler' require_relative '../base/engine' module CapsuleCD module Node class NodeEngine < Engine def build_step super # validate that the chef metadata.rb file exists unless File.exist?(@source_git_local_path + '/package.json') ...
require './lib/card.rb' class Deck attr_accessor :cards def initialize create_deck shuffle_deck end def create_deck @cards = [] suits = [:spades, :clubs, :hearts, :diamonds] for i in 2..14 do suits.each do |suit| @cards << Card.new(suit, i) end end end def shu...
class AddDefaultVoteCountToOptions < ActiveRecord::Migration[6.1] def change change_column :options, :vote_count, :integer, default: 0 end end
# frozen_string_literal: true # The Metric class represents a metric sample to be send by a backend. # # @!attribute type # @return [Symbol] The metric type. Must be one of {StatsD::Instrument::Metric::TYPES} # @!attribute name # @return [String] The name of the metric. {StatsD#prefix} will automatically be applie...
module GluttonRatelimit def rate_limit symbol, executions, time_period, rl_class = AveragedThrottle rl = rl_class.new executions, time_period old_symbol = "#{symbol}_old".to_sym alias_method old_symbol, symbol define_method symbol do |*args| rl.wait self.send old_symbol, *args end e...
class Auth::Slack < Grape::API namespace :auth do params do requires :code, desc: 'Oauth code from slack' end post :slack do authenticator = SlackAuth.new(params[:code]) user = User.from_slack(authenticator.user_info) user.save { auth_token: user.auth_token } end end ...
class YankProposalsController < ApplicationController def index @yank_proposals = YankProposal.all end def new @yank_proposal = YankProposal.new end def create @yank_proposal = YankProposal.new(params[:yank_proposal]) if @yank_proposal.save flash[:success] = "We've added your stock to...
require 'rails_helper' RSpec.describe Link, type: :model do describe 'associations' do it { should belong_to(:linkable) } end describe 'validations' do it { should validate_presence_of :name } context 'url' do it { should validate_presence_of :url } it { should_not allow_value('http:/...
class RacesController < ApplicationController def index @races = current_user.races end def show @race = Race.find_by(id: params[:id]) end def new @race = Race.new end def create @race = current_user.races.build(race_params) ...
class Customer < Base def self.columns [:id, :first_name, :last_name, :created_at, :updated_at] end def invoices InvoiceRepository.find_all_by_customer_id(self.id) end end
#designing methods for controllers # first thing specifying routes # @@ Configu # go to routes # inside routes.draw do () end ## get "/bleats" # this will in the example get the bleats #gets is a method that gets called on self # after this, the router needs to specify which controller actions it needs to go t...
json.array!(@hoteis) do |hotel| json.extract! hotel, :id, :nome, :cnpj, :email json.url hotel_url(hotel, format: :json) end
require 'rails_helper' describe 'an admin' do context 'visiting conditions index' do it 'can delete a condition and view an accompanying flash message' do admin = create(:user, role: 1) condition_1 = create(:condition, max_temperature_f: 500) condition_2 = create(:condition, max_temperature_f:...
class MessageThreadSubscription < ActiveRecord::Base belongs_to :user belongs_to :thread delegate :messages, to: :thread end
require "spec_helper" describe Lob::V1::BankAccount do before :each do @sample_address_params = { name: "TestAddress", email: "test@test.com", address_line1: "123 Test Street", address_line2: "Unit 199", address_city: "Mountain View", address_state: "CA", add...
class Bullshit def self.is_bullshit? word @bullshits = YAML.load_file("#{RAILS_ROOT}/db/bullshits.yml").split.map(&:downcase) @bullshits.include? word.match(/(\w+)/i)[0].downcase end end
class Message < ApplicationRecord after_create_commit { MessageBroadcastJob.perform_later self } belongs_to :sent_user, class_name: "User", foreign_key: 'user_id' belongs_to :room validates :content, presence: true end
class ReviewsController < ApplicationController def index @reviews = Review.asc(:created_at).page params[:page] @comment = Comment.new end def show @review = Review.find(params[:id]) @comment = ReviewComment.new end def photo content = @review.photo.read if stale?(etag: content, ...
class AddColumnToWishItem < ActiveRecord::Migration[5.0] def change add_column :wish_items, :wishlist_id, :integer end end
require 'sinatra' require 'sinatra/support' require_relative 'helpers' require_relative 'core/runner' configure do set :public_folder, Proc.new { File.join( root, "static" ) } enable :sessions end ### # The online version will handle multiple running instances # The offline version won't, so we define this globall...
class DeviceInformation < ActiveRecord::Base belongs_to :feedback attr_accessible :feedback, :os_name, :os_version, :model validates :os_name, :presence => true validates :os_version, :presence => true end
class Signed::AdminsController < ApplicationController layout 'signed' before_filter :authenticate_signed_user! end
class BudgetsController < ApplicationController before_action :logged_in_user def index @budgets = Budget.all @employers = Employer.all end def show @budget = Budget.find(params[:id]) @employer = @budget.employer @timesheets = @budget.timesheets @employees = @budget.employees.distinct.order(:id) end...
class DropDecksTableAndHandsTable < ActiveRecord::Migration[5.2] def change drop_table :decks drop_table :hands end end
class Book < ActiveRecord::Base belongs_to :author belongs_to :category belongs_to :publisher validates :title, presence: true, length: { minimum: 2, maximum: 255 } validates :category_id, presence: true validates :author_...
#! /usr/bin/env ruby # TODO: # - currently only works for ssh # - won't work for forks (or will it?) # - doesn't deal with multiple PRs for a branch require 'io/console' require 'git' require 'github_api' git_dir = Dir.new(Dir.pwd) until git_dir.entries.include? '.git' parent_path = git_dir.path[/.*(?=\/.*$)/] ...
class ColleagueButton attr_accessor :state def initialize(caption) @caption = caption @state = nil end def mediator=(mediator) @mediator = mediator end def set_colleague_enabled(enabled) @state = enabled end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe Talk, type: :model do before :each do @talk = Talk.new(title: 'opening speech 2', description: 'orem ipsum dolor sit amet, consectetur adipiscing, elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut ...
class Restaurant < ActiveRecord::Base belongs_to :vendor has_many :deals has_attached_file :image, styles: { medium: "300x300>"} do_not_validate_attachment_file_type :image validates_presence_of :name validates_presence_of :description validates_presence_of :phone validates_presence_of :email val...
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :playlist do url "MyString" order 1.5 end end
class Path < ActiveRecord::Base belongs_to :route validates :route, presence: true end
# frozen_string_literal: true module VmTranslator module Commands class Or def ==(other) self.class == other.class end def accept(visitor) visitor.visit_or(self) end end 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). # Set the locale, default is en-US Faker::Config.locale = 'ja' 10.times do user_name = Faker::Name.n...
module RSence module ArgvUtil # Main argument parser for the status command, sends the INFO (or PWR on linux) POSIX signal to # the process, if running. # Checks if the process responds on the port and address it's configured for. def parse_status_argv init_args expect_option = false option_name = ...
require "#{Rails.root}/app/operation_models/url_service.rb" module Api module V1 class UrlsController < ActionController::API $instance=Urloperation.new def getall shorturls = $instance.getall render json: {status: 'SUCCESS...
# Run me with `rails runner db/data/20230614151054_correct_partner_org_identifiers.rb` # Two partner org identifiers need correcting, as per this Zendesk ticket https://dxw.zendesk.com/agent/tickets/17993. # This is a one-off task. changes = [ { existing_partner_organisation_identifier: "_ES/X014088/1", new...
require 'rails_helper' describe IndexParser do describe 'start' do context 'when parsing the file' do subject do described_class.start end it 'should create new packages' do VCR.use_cassette('index_parser/package_file') do expect { subject }.to change(Package, :count)...
# frozen_string_literal: true require 'test_helper' class TeacherSetsHelperTest < ActiveSupport::TestCase extend Minitest::Spec::DSL include LogWrapper include TeacherSetsHelper before do @teacher_set = TeacherSet.new @mintest_mock1 = MiniTest::Mock.new @mintest_mock2 = MiniTest::Mock.new end ...
require 'optparse' require 'yaml' class Options def self.parse options = {} optparse = OptionParser.new do |opts| # Set a banner, displayed at the top of the help screen. opts.banner = "Usage: jifu [-f UPLOAD_FOLDER, -n NAME_FOLDER, -u USERNAME, -p PASSWORD] file1 file2 ..." conf...
class Announcement < ActiveRecord::Base acts_as_paranoid attr_accessible :course_id, :creator_id, :description, :important, :publish_at, :title scope :published, lambda { where("publish_at <= ? ", Time.now) } belongs_to :course belongs_to :creator, class_name: "User" end
# == Schema Information # # Table name: users # # id :integer not null, primary key # email :string(255) default(""), not null # encrypted_password :string(255) default(""), not null # reset_password_token :string(255) # reset_password_sent_at :datetime...
require 'gosu' require 'opengl' require 'glu' OpenGL.load_lib GLU.load_lib include OpenGL, GLU require_relative 'gl_texture.rb' require_relative 'tiled_optimizer.rb' class Window < Gosu::Window def initialize super(640, 480, false) @tiled_map = TiledMap.new('tiled_maps/test.json') @x, @y, @z = 0, 30, ...
module Git::Webby module HttpBackendHelpers #:nodoc: include GitHelpers def service_request? not params[:service].nil? end # select_service feature def service @service = params[:service] return false if @service.nil? return false if @service[0, 4] != "git-" @serv...
require 'singleton' module Kilomeasure class MeasuresRegistry include Singleton attr_accessor :loader def self.get(name) instance.get(name) end def self.load(data_path: nil) instance.loader.data_path = data_path if data_path instance.load_measures end def self.reset ...
# frozen_string_literal: true require 'spec_helper' describe RubyPx::Dataset do let(:subject) { described_class.new 'http://populate-data.s3.amazonaws.com/ruby_px/f1.px' } describe '#headings' do it 'should return the list of headings described in the file' do expect(subject.headings).to eq(['Fenómeno ...
class CreateInterfaces < ActiveRecord::Migration def self.up create_table :interfaces, :id => false do |t| t.string :type, :limit=>'128' t.string :name, :limit=>'1024' t.string :description, :limit=>'4096' t.string :ikey, :limit=>'1024' t.string :filename, ...
class Question < ActiveRecord::Base belongs_to :user has_one :topic has_many :comments acts_as_friendly_param :headline validates_presence_of :headline validates_presence_of :body acts_as_taggable cattr_reader :per_page @per_page = 25 HUMANIZED_ATTRIBUTES = { :headline => "Question", :bod...
require 'formula' class Repl < Formula homepage 'https://github.com/defunkt/repl' url 'https://github.com/defunkt/repl/archive/v1.0.0.tar.gz' sha1 'd47d31856a0c474daf54707d1575b45f01ef5cda' depends_on 'rlwrap' => :optional def install bin.install 'bin/repl' man1.install 'man/repl.1' end end
class Player < ActiveRecord::Base self.table_name = "pong_player" def self.merge_default_parameters(player_params) player_params.merge( { wins: 0, losses: 0, random_token: PasswordDigester.generate_token }) end def update_attributes_with_encrypted_password(player_params) se...
module MessageCenter module Concerns module Models autoload :Conversation, 'concerns/models/conversation' autoload :Item, 'concerns/models/item' autoload :Mailbox, 'concerns/models/mailbox' autoload :Message, 'concerns/models/message' autoload :Notification, 'concerns/models/notific...
class KwkFulfillmentMailerPreview < ActionMailer::Preview def shipping KwkFulfillmentMailer.shipping(KwkFulfillment.with_shipping_state.last) end end
require 'mongoid' class SchemaField include Mongoid::Document field :id field :name field :data_type field :required, :type => Boolean embedded_in :list validates :name, :presence => true end
# frozen_string_literal: true RSpec.describe NilLocalCampaign do let(:campaign) { described_class.new } %i[external_reference status description].each do |attr| describe "##{attr}" do subject { campaign.send(attr) } it { is_expected.to eq 'Non Existent' } end end end
require File.dirname(__FILE__) + '/../spec_helper.rb' require 'action_controller' require 'action_controller/assertions/selector_assertions' include ActionController::Assertions::SelectorAssertions describe MifToHtmlParser do before(:all) do Act.stub!(:from_name).and_return nil end def parser url=nil, oth...
require 'test_helper' class Piece10sControllerTest < ActionController::TestCase setup do @piece10 = piece10s(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:piece10s) end test "should get new" do get :new assert_response :success en...
require 'spec_helper' describe Rounders do it 'has a version number' do expect(Rounders::VERSION).not_to be nil end describe '.global?' do context 'when app directory not exists' do before do allow_any_instance_of(Pathname).to receive(:exist?).and_return(false) end it 'should r...
class Payment < ActiveRecord::Base belongs_to :loan validate :must_be_valid_amount def must_be_valid_amount errors.add(:base, 'Payment must no be larger than the loan balance') unless payment_amount <= self.loan.balance end end
class CommentMailer < ApplicationMailer def comment_created(user, comment) @user = user @comment = comment @post = @comment.post @url = post_url(@post.id) @title = "New comment on: #{@post.title}" mail(to: @user.email, subject: @title) end end
# == Schema Information # # Table name: users # # id :bigint not null, primary key # name :string not null # email :string not null # password_digest :string not null # fullname :string # is_admin :boolean default(FAL...
class CreateLoyaltyConfigs < ActiveRecord::Migration def change create_table :loyalty_configs do |t| t.integer :multiple_per_euro, default: 100 t.integer :max_points, default: 20000 t.integer :points_time_limit,default: 2 t.integer :accumulation_speed_time_limit, default: 1 t.string ...
require 'minitest/autorun' require_relative 'pet_shop_two' class PetShopTest < Minitest::Test def test_one_rat assert_equal ['B1'], Order.new(['R']).boxes end def test_one_hedgehog assert_equal ['B1'], Order.new(['H']).boxes end def test_one_mongoose assert_equal ['B2'], Order.new(['M']).boxes...
class FixColumnName < ActiveRecord::Migration def change rename_column :posts, :text, :description end end
class AccountsController < ApplicationController def new @account = Account.new(user: User.new) end def create @account = Account.new(account_params) user_pass = SecureRandom.hex(4) puts "=====> #{user_pass}" @account.user.password = user_pass @account.acc_id = SecureRandom.random_numbe...
class UsersController < ApplicationController before_action :set_user, only: %i[ show edit update destroy ] # GET /users or /users.json def index @users = User.all end # GET /users/1 or /users/1.json def show end # GET /users/new def new @user = User.new end # GET /users/1/edit def e...
class RegistrationsController < Devise::RegistrationsController protected def after_sign_up_path_for(resource) '/wikis' # '/charges/new' end end
Recaptcha.configure do |config| config.site_key = ENV['RECAPCHAUSER'] config.secret_key = ENV['RECAPCHASERVER'] # Uncomment the following line if you are using a proxy server: # config.proxy = 'http://myproxy.com.au:8080' end
actions :create, :delete, :dereg_instance, :reg_instance default_action :create attribute :lb_name, kind_of: String, name_attribute: true attribute :aws_access_key_id, kind_of: String, default: nil attribute :aws_secret_access_key, kind_of: String, default: nil attribute :region, ...
# frozen_string_literal: true namespace :invoices do desc 'Process the event queue' task process_pagseguro: :environment do CheckPagseguroInvoicesJob.perform_now end end
class WebApi # Copyright Vidaguard 2013 # Author: Claudio Mendoza require "net/http" require "uri" require "net/https" require 'json' BOUNDARY = "AaB03x" def self.get(url) uri = URI.parse(url) # Shortcut response = Net::HTTP.get_response(uri) # Will print response.body puts Net::HTTP.get...
require "test_helper" feature "CanAccessWelcome" do scenario "is displaying welcome" do visit root_path page.must_have_content "Welcome" end end
=begin This plugin allows you to read a news article, also marking it read. =end read = Command.new do name "Read" desc "Lets you read a news article" help <<-eof Using this command you can read news, which is kind of the purpose of having the newsboard here in the first place. eof syntax "+news <postpath>"...
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'Articles' do describe '#index' do it 'returns all Articles' do create_list(:article, 3) user = create(:user) sign_in(user) get '/api/articles' expect(json_body['articles'].size).to eq(3) expect(json_body['...
class GuiFunctionMembership < ActiveRecord::Base belongs_to :gui_function belongs_to :user_group validates_associated :gui_function validates_associated :user_group end
require 'rails_helper' RSpec.describe "shops/new", type: :view do before(:each) do assign(:shop, Shop.new( :name => "MyString", :prefecture => 1, :address => "MyString", :latitude => 1.5, :longitude => 1.5 )) end it "renders new shop form" do render assert_select "...
module Pact module Message module Consumer class Message attr_accessor :description, :content, :provider_state def initialize attributes = {} @description = attributes[:description] @provider_state = attributes[:provider_state] || attributes[:providerState] @co...
class GlossaryController < ApplicationController def index @page = Page.find_by_absolute_url!("/glossary", select: "id, title, meta_description, teaser, copy") @sorted_terms = sort_terms(GlossaryTerm.all.group_by { |g| g.name.upcase.first }) end #convert a hash into an array sorted alpha...
class GroupsController < ApplicationController before_action :new_group, only: :index before_action :load_group, only: [:show, :edit, :destroy, :update, :add_member, :delete_member] before_action :is_owner def index @title = t "groups.list_groups" @search = current_user.admin? ? Group.ransack(params[:q...
# -*- encoding: utf-8 -*- require File.expand_path('../lib/nyaa/version', __FILE__) Gem::Specification.new do |s| s.name = 'nyaa' s.version = Nyaa::VERSION s.homepage = 'https://github.com/mistofvongola/nyaa' s.summary = 'The nyaa gem is a CLI to NyaaTorrents.' s.description = 'Browse and d...
class TasksUser < ActiveRecord::Base attr_accessible :sender_id, :task_id, :user_id #belongs_to :sender, calss_name: 'User', foreign_key: :sender_id # belongs_to :user belongs_to :task belongs_to :sender, class_name: 'User', foreign_key: :sender_id validates_presence_of :task_id, :on => :create valida...