text
stringlengths
10
2.61M
class AddResolvedCaptchToTail < ActiveRecord::Migration[5.1] def change add_column :tails, :resolved_captcha, :boolean, default: false end end
class Selection < ApplicationRecord belongs_to :restaurant end
# encoding: utf-8 describe Faceter::Functions, ".wrap" do let(:arguments) { [:wrap, :foo, Selector.new(options)] } let(:input) { { foo: :FOO, bar: :BAR, baz: :BAZ, qux: :QUX } } it_behaves_like :transforming_immutable_data do let(:options) { {} } let(:output) { { foo: { foo: :FOO, bar: :BAR, baz: :BAZ...
class UserSerializer < ActiveModel::Serializer attributes :id, :username, :bio has_many :user_shows has_many :shows, through: :user_shows end
require 'json' require_relative '../lib/pul_solr' set :application, 'pul_solr' set :repo_url, 'https://github.com/pulibrary/pul_solr.git' # Default branch is :main # ask :branch, `git rev-parse --abbrev-ref HEAD`.chomp set :branch, ENV['BRANCH'] || 'main' # Default deploy_to directory is /var/www/my_app_name set :de...
require("rspec") require("title_case") describe("title_case") do it("capitalizes first letter of inputted words except those blacklisted") do title_case("sometimes a great notion").should(eq("Sometimes a Great Notion")) end it("still capitalizes blacklisted words if they are the first word in the title") do ...
class RemoveIndexItemsDefault < ActiveRecord::Migration def change change_column_default(:items, :lunch, nil) change_column_default(:items, :combo, nil) end end
class RemoveColumnFromMeal < ActiveRecord::Migration[6.0] def change remove_reference :meals, :meal_plan, null: false, foreign_key: true end end
require 'spec_helper' describe Api::V1::AlexPelanController do describe 'GET #portfolio' do before(:each) { get :portfolio, :format => :json } it "populates the 3 projects" do expect(json['alex_pelan'].count).to eq 3 end it "contains the proper JSON keys for github projects" do project_hash = j...
class SessionsController < ApplicationController def new end def create user = User.find_by_email(params[:email]) if user && user.authenticate(params[:password]) # log_in user # redirect_to user # flash[:success] = 'Logged in successfully.' if params[...
class TagsController < ApplicationController before_action :retrieve_user before_action :find_task def create unless params[:name].blank? tag = Tag.where(name: params[:name]).first || Tag.create(name: params[:name]) @task.tags << tag unless @task.tags.where(id: tag.id).first end ...
require "rulp" Rulp::log_level = Logger::UNKNOWN Rulp::print_solver_outputs = false class IntegerLinearProgram def initialize(students, sections, fte_per_section = 0.25, students_per_ta = 30) @students = students @sections = sections @fte_per_section = fte_per_section @students_per_ta = students_p...
class AddWantsToDrink < ActiveRecord::Migration def change add_column :drinks, :wants, :boolean, :default => false end end
class Category < ApplicationRecord has_and_belongs_to_many :escort_profiles end
module DialogB START_OF_RECORD = '$$' LINE_CONTINUATION = ' ' def self.find_records_in_stream(io, options = {}) options[:before_continuation] ||= '' record = [] io.each do |line| line.chomp! type, data = split_line(line, options) if type == START_OF_RECORD # Start of ...
require "pry" require_relative "./concerns/findable.rb" class Genre attr_accessor :name, :songs extend Concerns::Findable @@all = [] def initialize(name) self.name = name self.songs = [] end def self.all @@all end def self.destroy_all self.all.clear end def save self.class...
require_dependency YourPlatform::Engine.root.join('app/models/user').to_s class User def title name + " " + corporations.map(&:token).join(" ") end end
class User < ActiveRecord::Base has_many :phones has_many :subscriptions has_many :subscription_configurations, through: :subscriptions def self.fetch_by_phone_number(number) self.joins(:phones).where(['number = ?', number]).first end end
require 'test_helper' class SubchaptersControllerTest < ActionController::TestCase setup do @subchapter = subchapters(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:subchapters) end test "should get new" do get :new assert_response :...
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'tapbot/version' Gem::Specification.new do |spec| spec.name = "tapbot" spec.version = Tapbot::VERSION spec.authors = ["David Ramirez"] spec.email = ["david@dav...
class Api::EntriesController < ApplicationController before_action :authenticate_user def index @entries = current_user.entries.order(:created_at) @entries.where(word_count: 0).delete_all Entry.create(user: current_user) if @entries.empty? # TODO: time zone @entries << Entry.create(user: curre...
class AddTransidToOrders < ActiveRecord::Migration def change add_column :orders, :transid, :string, default: '', null: false end end
class CreateExpReservations < ActiveRecord::Migration[5.0] def change create_table :exp_reservations do |t| t.integer "user_id" t.integer "experience_id" t.date "data_entrada" t.date "data_saida" end end end
class Ability include CanCan::Ability def initialize(admin) admin ||= Admin.new is_super_admin = admin.is_super_admin? if is_super_admin [:new, :create, :reset_password, :change_password, :view_activities].each do |action| can action, Admin end else [:new, :create, :manag...
Fabricator(:calorie) do protein { Random.rand(200) } fat { 10 + Random.rand(200) } carbs { 10 + Random.rand(200) } date_of_entry { Faker::Date.between(20.days.ago, Date.today) } end
# Este módulo se ha creado para la asignatura de # Lenguajes y Paradigmas de la Programación impartida # en la Universidad de la Laguna como práctica, # haciendo uso del lenguaje de programación Ruby. # # Author:: Javier Esteban Pérez Rivas (mailto:alu0100946499@ull.edu.es) # Copyright:: Creative Commons # License::...
=begin dfefine a method that utilizes a specific alphabet that does not include vowels An array made up of string objects is passed in as the argument I need to return a new transformed array object witout vowels pass in the argment to a block using the .map method iterate over the variable for the string, using...
require 'rails_helper' describe "appointments", type: :feature do before do @hawkeye = Doctor.create({name: "Hawkeye Pierce", department: "Surgery"}) @homer = Patient.create({name: "Homer Simpson", age:38}) @appointment = Appointment.create({appointment_datetime: DateTime.new(2016, 03, 15, 18, 00, 0), p...
Admin.controllers :cartes do get :index do @cartes = Carte.all render 'cartes/index' end get :new do @carte = Carte.new render 'cartes/new' end post :create do @carte = Carte.new(params[:carte].slice("name", "image")) params[:carte][:items].split(/\r?\n/).each do |i| item_name...
module Helpers def self.symbolize_keys(hash) Hash[hash.map{ |k, v| [k.to_sym, v] }] end def self.parse_path_word(word) # validate keyword word =~ /(\w+)\.(\w+)/ word = $1 format = $2 [word, format] end def self.sanitize_word_list(word_list) word_list.map { |w| w.to_s } end ...
class G0120a attr_reader :options, :name, :field_type, :node def initialize @name = "Bathing (Self-Performance) - how resident takes bath/shower, sponge bath, and transfers in/out of tub/shower . (G0120a)" @field_type = DROPDOWN @node = "G0120A" @options = [] @options << FieldOption.new("^", "...
class AppointmentsController < ApplicationController before_action :find_appointment, only: [:show, :edit, :update, :destroy] # before_action -> {authorized_for(@appointment)} before_action :require_login def index @type = params[:value] if params[:appointment_type_id] @appointments = App...
require 'collins_client' require 'lib/collins_integration' describe "Asset Find" do before :all do @integration = CollinsIntegration.new('default.yaml') @client = @integration.collinsClient end def checkQuery(params, expected_size) params[:size] = 50 assets = @client.find params assets.siz...
class PublishersController < ApplicationController def index @publishers = Publisher.all end def show end def new @publisher = Publisher.new end def edit end def create @publisher = Publisher.new(publisher_params) respond_to do |format| if @publisher.save format.html...
#base class for common functionality #implement the indicated methods in a subclass, the handlers in the #class that will handle the response, and then call the class #method handle_responses to take messages off the queue and handle them. class MessageResponse::Base < Object attr_accessor :payload def initialize...
# Virus Predictor # I worked on this challenge [with Ted Bogen]. # We spent [1.5] hours on this challenge. # EXPLANATION OF require_relative # Links this page to another file to pull information from it, require_relative is special because instead # of requiring a file path to the linked file it looks for it in the s...
class CommandLineInterface attr_accessor :user PROMPT = TTY::Prompt.new ############################################################################## ##### HELPER METHODS ######################################################### ############################################################################## ...
module MachineContextInputMethods def initialize( machine ) self[:machine] = machine self[:conds] = [] end def input # self[:input] = eval_input( self[:input] ) || [] # feature:nodup - теперь надо в отдельный ключ сохранять, ибо иначе постоянное дублирование - плохо # однако мы теперь [:inpu...
require "application_system_test_case" class UsersConversationsTest < ApplicationSystemTestCase setup do @users_conversation = users_conversations(:one) end test "visiting the index" do visit users_conversations_url assert_selector "h1", text: "Users Conversations" end test "creating a Users co...
require './heroes/powers' class Storm include Powers attr_accessor :undercover def initialize @undercover = true @secret_identity = "Ororo Munroe" @description = "Storm" end def weak_to?(element) case element when :psychic_powers false when :krytonite false when :lightning false when ...
class EventsController < ApplicationController before_action :authenticate_user!, only:[:new, :edit, :manage] def new @event = Event.new end def create @event = current_user.events.new(event_params) if @event.save redirect_to root_path, success:'イベント作成に成功しました' else flash.now[:dange...
require "OTP" class SpinlockQueue class Node attr_accessor :item, :successor def initialize(item, successor) self.item = item self.successor = successor end end attr_accessor :head, :tail def initialize @lock = OTP::Spinlock.new dummy_node = Node.new(:dummy, nil) se...
class PeopleController < ApplicationController before_action :authenticate_user! before_action :set_person, only: [:show, :versions, :edit, :update, :destroy] before_action :set_tmks, only: [:show, :destroy] after_action :verify_authorized after_action :set_last_page, only: [:edit, :new] def index @qu...
require_relative 'menumodule' class SetTravelNotificationPage include PageObject include MenuPanel include AccountsSubMenu include ServicesSubMenu include MyInfoSubMenu include MessagesAlertsSubMenu include PaymentsSubMenu table(:heading, :id => 'tblMain') button(:settravelnotifica...
require 'spec_helper' module TextToNoise describe Router do it "reloads its configuration if it has changed" describe ".parse" do let( :mapping ) { double( NoiseMapping, :to => nil ) } context "given a nil configuration" do it "raises an ArgumentError" do lambda { ...
module ApplicationHelper class HTMLwithPygments < Redcarpet::Render::HTML def block_code(code, language) Pygments.highlight(code, :lexer => language) end end def markdown(text) markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML.new( :hard_wrap => true, :filter_html => true, :saf...
# frozen_string_literal: true # == Schema Information # # Table name: lessons # # id :integer not null, primary key # date :date not null # deleted_at :datetime # uid :uuid not null # created_at :datetime not null # updated_at :datetime not nu...
class PasswordController < ApplicationController def forgot if params[:email].blank? return render json: {error: 'Operação inválida'}, status: :404 end user = User.find_by(email: params[:email]) if user.present? user.save if user.generate_password_token PasswordMailer.with(user: us...
class RemoveApiurlFromReferenceSource < ActiveRecord::Migration def up remove_column :reference_sources, :apiurl end def down add_column :reference_sources, :apiurl, :string end end
require_relative "../lib/eventhub/base" module EventHub class Receiver < Processor2 def handle_message(message, args = {}) id = message.body["id"] EventHub.logger.info("[#{id}] - Received") file_name = "data/#{id}.json" begin File.delete(file_name) EventHub.logger.info("[...
module Ricer::Plug::Params class IntegerParam < Base INT_MIN ||= -2123123123 INT_MAX ||= 2123123123 def default_options { min: INT_MIN, max: INT_MAX } end def min (options[:min].to_i rescue INT_MIN) or INT_MIN end def max (options[:max].to_i rescue INT_MAX) or...
class AddNumRetweetsToDataSet < ActiveRecord::Migration[5.2] def change add_column :data_sets, :num_retweets, :integer end end
class AddUpdatedByIdToTradeRestrictionTerms < ActiveRecord::Migration def change add_column :trade_restriction_terms, :updated_by_id, :integer end end
module V1 class Base < ApplicationAPI version "v1", using: :path helpers do def success_response(message) { status: true, message: message } end def failure_response(message) { status: false, message: message } end def set_current_user(de...
require 'rails_helper' RSpec.describe Trip do it { should belong_to(:passenger) } it { should belong_to(:flight) } end
#shared the scope between all of the methods lambda{ TABLE_X = 5 TABLE_Y = 5 STEP = 1 #4 directions used now DIRECTIONS = ["NORTH", "EAST", "SOUTH", "WEST"] NORTH, EAST, SOUTH, WEST = DIRECTIONS RIGHT, LEFT, MOVE, PLACE = ["right", "left", "move", "place"] is_robot_availabe = false...
class AddColumnToTutor2 < ActiveRecord::Migration def change add_column :tutors, :welcome_message, :string end end
# Practice for how polymorphism works in Ruby class Bird def tweet(bird_type) bird_type.tweet # calling its version of tweet here end end class Cardinal < Bird #inherit from bird def tweet puts "Tweet" end end class Parrot < Bird def tweet puts "Squawk" end end generi...
class AddCurrentJobToUser < ActiveRecord::Migration[6.0] def change add_column :users, :current_job, :string end end
#Public: Takes an integer and muliplies it with itself and returning the result. # # number - The integer that will be multiplied with itself # # Examples # # square(5) # # => 25 # # Returns the squared integer def square(number) return number * number end
require 'test_helper' require "helpers/file_data" class DiscrepancyCsvParserTest < ActiveSupport::TestCase include FileData::CSV test "converts csv into discrepancy data models" do model = DiscrepancyCsvParser.parse(csv_data).first assert model.is_a?(DiscrepancyData) assert model.valid? end end
require 'state_machine' class Notification include Mongoid::Document include Mongoid::Timestamps::Created field :verb, type:String field :count, type:Integer, default:0 # Relationships belongs_to :receiver, :class_name => 'User', :inverse_of => :notifications_received belongs_to :sender, :class_name =...
class VendingMachine MONEY = [10, 50, 100, 500, 1000].freeze def initialize(drink) @insert_money = 0 @sales_amount = 0 @drinks = drink end def insert_money(money) if MONEY.include?(money) @insert_money += money puts "現在の投入金額は#{@insert_money}円です。" else puts "...
require "spec_helper" feature "Job title assignments" do scenario "Adding a new one" do department = create(:department) job_title = create(:job_title) user = create(:user) expect(user.job_title_assignments.count).to eq 0 visit edit_user_path(user, as: user) select department.name, from: "Dep...
# == Schema Information # # Table name: responses # # id :bigint not null, primary key # answer_choice_id :integer not null # responder_id :integer not null # created_at :datetime not null # updated_at :datetime not null # class Response < ...
# write the migration code to create # a shows table. The table should # have name, network, day, and # rating columns. name, network, # and day have a datatype of string, # and rating has a datatype of # integer. class CreateShows < ActiveRecord::Migration def change create_table :shows do |t| t.string :n...
require 'active_support/core_ext/numeric/time' require 'deliveryboy/rails/active_record' require 'deliveryboy/loggable' require 'deliveryboy/plugins' require 'email_address' require 'email_history' class Deliveryboy::Plugins::History include Deliveryboy::Plugins # Deliveryboy::Maildir needs this to load plugins prop...
class SpreadsheetsController < ApplicationController def index @title = "Spreadsheet Manager" # Push this over to the model hash = {} Spreadsheet.gather_thine_spreadsheets.each do |f| @last = ActiveRecord.const_get(f).last hash.merge!(f.to_sym => @last) end @hash = hash ...
require 'rails_helper' describe VideosController, type: :controller do let(:user) { create(:user) } let(:video) { create(:video) } before do session[:user_id] = user.id end describe 'show' do it 'returns http success' do get :show, id: video.id expect(response).to be_success expec...
class Quip < ActiveRecord::Base belongs_to :user attr_accessible :image, :jackass_count, :message, :rating, :user_id has_many :inappropriates has_many :likes has_many :feedbacks validates :message, presence: true validates_length_of :message, maximum: 141 validates :rating, presence: true valida...
class LikesController < ApplicationController def create @like = Like.new(params[:like]) respond_to do |format| if @like.save format.html { redirect_to @like, notice: 'Like was successfully created.' } format.json { render json: @like, status: :created, location: @like } else ...
# frozen_string_literal: true require "rails/source_annotation_extractor" desc "Enumerate all annotations (use notes:optimize, :fixme, :todo for focus)" task :notes do SourceAnnotationExtractor.enumerate "OPTIMIZE|FIXME|TODO", tag: true end namespace :notes do ["OPTIMIZE", "FIXME", "TODO"].each do |annotation| ...
# == Schema Information # # Table name: photos # # id :bigint(8) not null, primary key # title :string not null # description :string # owner_id :integer not null # created_at :datetime not null # updated_at :datetime not null # class Photo < Applicat...
class AccountingCategory < ActiveRecord::Base belongs_to :accounting_category has_and_belongs_to_many :devices end
#!/usr/bin/env ruby require 'shellwords' # Will open all files with jshint errors in vim class FixJshint def get_error_list output = %x[grunt jshint --no-color | grep '^Linting'] return output.split("\n") end def get_error_files get_error_list.map do |line| matches = line.match(/^Linting (.*)...
class Comment < ApplicationRecord belongs_to :user belongs_to :commentable, polymorphic: true validates :review, presence: true, allow_blank: false def comment_user(id) User.find(id).username end def comment_status(status) if status == 'A' 'Activated' else 'Disabled' end end e...
module Jekyll class Title < Liquid::Tag def render(context) site = context.registers[:site] page = context.registers[:page] config = site.config page_title = page['title'] page_tag = page['tag'] title = config['title'] if ...
LauncherJournal::Application.routes.draw do root to: 'entries#index' resources :entries resources :categories end
class Budget < ActiveRecord::Base belongs_to :budgetpost, :foreign_key => 'budget_id' belongs_to :user, :foreign_key => 'user_id' #validate :is_value_positive? def value if self.isexpense return -self.dollarAmount else return self.dollarAmount end end # DEPRECATED def is_va...
# frozen_string_literal: true require 'rails_helper' require 'pundit/matchers' RSpec.describe CompletionPolicy, type: :policy do subject { described_class.new user, completion } let(:completion) { Completion.new } context 'when logged out' do let(:user) { nil } it { is_expected.to forbid_action :crea...
require 'sinatra/base' require 'mongoid' require 'digest/sha1' class Alarm include Mongoid::Document INTERVALS = %w( hourly daily monthly ).freeze KEY_FORMAT = /[0-9a-f]{7}/ field :key, type: String field :interval, type: String field :last_call, type: DateTime field :tag, type: String field :thresho...
class ContactsController < ApplicationController before_action :set_contact, only: [:show, :update, :destroy] # GET /contacts def index @contacts = Contact.all # ADICIONANDO NOVOS CONTATOS (quando tiver uma coleção): # render json: @contacts.map { |contact| contact.attributes.merge({ author: "Maiqu...
class RemoveDefaultRailsTimpstampsFromInsOutsClicks < ActiveRecord::Migration[5.2] def change remove_column :ins, :created_at remove_column :ins, :updated_at remove_column :outs, :created_at remove_column :outs, :updated_at remove_column :clicks, :created_at remove_column :clicks, :updated_at ...
module Travis::API::V3 class Queries::EnvVar < Query params :id, :name, :value, :public, prefix: :env_var def find(repository) repository.env_vars.find(id) end def update(repository) if env_var = find(repository) env_var.update(env_var_params) repository.save! env...
# frozen_string_literal: true # == Schema Information # # Table name: authors # # id :bigint(8) not null, primary key # description :string # name :string # created_at :datetime not null # updated_at :datetime not null # FactoryBot.define do factory :author do seque...
# frozen_string_literal: true require 'prawn/core' require 'prawn/format' require "prawn/measurement_extensions" require 'gruff' require "open-uri" module Pdf module Finance class InvoiceGenerator include Pdf::Printer # TODO: remove include ActionView::Helpers::NumberHelper include Thre...
# frozen_string_literal: true class PersonalMessage < ApplicationRecord belongs_to :conversation belongs_to :user has_attached_file :attachment do_not_validate_attachment_file_type :attachment validates :body, presence: true after_create_commit do conversation.touch ConversationJob.perform_later...
class WelcomeController < ApplicationController def index if user_signed_in? redirect_to lists_path, notice: "You're signed in, here are your lists! :D" else redirect_to new_user_session_path, notice: "Please sign in!" end end end
# Class: Category # # Models our Product objects that live within categories and shelves. # # Attributes: # @name - String: Primary Key related to the shelves table of db. # @shelf_id - Integer: Denotes what shelf the object belongs to. # @category_id - Integer: Denotes what category the object belongs to....
module Abroaders module Cell # An alert-info that will be shown at the top of most pages when an # onboarded account is logged in. It will tell them one of three things # related to recommendations (or it might not render anything): # # 1. You have unresolved recommendations - please visit cards...
# frozen_string_literal: true class Simulation def initialize(num_blobs) @blobs = [] init_blobs(num_blobs) end def init_blobs(num_blobs) num_blobs.times do @blobs.push Blob.new end end def tick display end def display line_width = 20 stats = [ ['Total Blobs:',...
class Post < ApplicationRecord has_many :comments, dependent: :destroy belongs_to :user validates :title, :content, presence: true # length: { is: 5 } # scope :by_user_comments, -> { where(id: User.first.comments.map(&:post_id).uniq).pluck('title') } scope :by_user, -> { order(user_id: :asc) } scope :ord...
require 'rails_helper' RSpec.describe Link, type: :model do it { should belong_to :linkable } it { should validate_presence_of :name } it { should validate_presence_of :url } it { should allow_value("http://foo.com").for(:url) } it { should_not allow_value("somevalue").for(:url) } #GIST filename: 'gis...
require 'spec_helper' describe Mongoid::Scribe::DocumentsHelper do let(:user) { FactoryGirl.create(:user, slug: "john-doe") } let(:address) { FactoryGirl.create(:address) } describe "#model_param" do it "should format a model for use as a parameter" do expect(helper.model_param(User)).to eq("user") ...
#Create empty hash interior_info = {} #Ask designer for user information & put information into a hash puts "What is the client's name?" interior_info[:name] = gets.chomp puts "How old are they?" interior_info[:age] = gets.chomp.to_i puts "How many kids do they have?" interior_info[:kids] = gets.chomp.to_i puts "...
Then(/^I should see the thank you message$/) do wait_for_ajax page.should have_content('Thank you') end And(/^the project should have a helper$/) do @project.helpers.count.should eq(1) end When(/^I submit the help form$/) do fill_in 'contact_enquiry_email', with: 'example@example.com' fill_in 'contact_enqui...
# 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...
class ProyectoTerminado < Material has_many :storage_infos, foreign_key: :material_id accepts_nested_attributes_for :storage_infos class << self def sti_name "finished" end end end
xml.instruct! :xml, :version => '1.0' xml.rss(:version => '2.0') do xml.channel do xml.title(@topic) xml.link(url_for(:format => 'rss', :only_path => false)) xml.description() xml.language('fr-fr') @posts.each do |post| xml.item do xml.title(@topic) xml.category() x...
class ChangeAffiliationEnumOnReview < ActiveRecord::Migration # Refresh for :sample enum option. def self.up change_column :reviews, :affiliation, :enum, :limit => Review::AFFILIATION_ENUM_VALUES, :default => nil, :allow_nil => true end def self.down change_column :reviews, :affiliation, :enum, ...