text
stringlengths
10
2.61M
class UserProfilesController < ApplicationController def index @user_profiles = UserProfile.all end def new @user_profile = UserProfile.new end def show @user_profile = UserProfile.find(params[:id]) respond_to do |format| format.html format.js end end def edit end ...
class Organization < ActiveRecord::Base #belongs_to :Profile has_many :Profile end
class CommentsController < ApplicationController skip_before_action :authenticate, only: [:show] def create render json: Comment.create(comment_params) end def destroy render json: Comment.find(params[:id]).destroy end def show render json: Comment.find(params[:id]) end private def com...
require 'rails_helper' require 'helper_methods' describe Nod do before :each do populate_users(10) init_variables @discussion0 = Discussion.start(@user0, @text) @discussion1 = Discussion.start(@user1, @text) @discussion2 = Discussion.start(@user2, @text) @discussion3 = Discussion.start(@user3...
require 'rack/throttle' require "#{Rails.root}/lib/rack/throttle/custom_rules.rb" module Quota def self.cache Redis.new( url: ENV.fetch('VIKYAPP_QUOTA_REDIS_URL') { "redis://localhost:6379/4/#{Rails.env}" } ) end def self.reset_cache self.cache.flushdb end def self.throttle_rules_for(peri...
require File.dirname(__FILE__) + '/../../../test_helper' class TinyCI::Util::ExecutorTest < ActiveSupport::TestCase class TestExecutor include TinyCI::Util::Executor def initialize(build) @build = build end end def setup @shell = stub @build = stub(:shell => @shell, :workspace_path =...
shared_examples "purchasable" do it { is_expected.to have_one(:purchase) } end
class RenameSubscriptionChallenges < ActiveRecord::Migration def change rename_table :subscription_challenges, :challenge_subscriptions end end
require 'rails_helper' RSpec.describe DnsRecord, type: :model do it "is valid with ip_address" do expect(DnsRecord.new(ip_address: "1.1.1.2")).to be_valid end it "is not valid without an ip_address" do expect(DnsRecord.new).to_not be_valid end end
require 'rails_helper' RSpec.describe FormulasHelper, type: :helper do describe '#age_range' do it 'expects an unbounded senior age to return string' do expect(helper.age_range(16, nil)).to eq 'Senior - 16 +' end it 'expects an bounded senior age to return string' do expect(helper.age_range(...
require 'test_helper' class ProductTypeTest < ActiveSupport::TestCase test "should find product type" do product_type_id = product_types(:whiskey).id assert_nothing_raised { ProductType.find(product_type_id) } end test "should not create product type with duplicate name" do product_type = ProductTy...
# frozen_string_literal: true # Advent of Code 2020 # # Robert Haines # # Public Domain require 'set' require 'aoc2020' module AOC2020 class CrabCombat < Day def setup @decks = read_decks(read_input_file) end def part1 result = play(@decks) puts "Part 1: #{score(result)}" end ...
class AddFamilyIdToArchiveGuardian < ActiveRecord::Migration def self.up add_column :archived_guardians, :family_id, :integer end def self.down remove_column :archived_guardians, :family_id end end
class ProductOrder < ApplicationRecord belongs_to :product, inverse_of: :product_order, optional: true, class_name: 'Product' belongs_to :order, inverse_of: :product_order, optional: true accepts_nested_attributes_for :product def product_attributes=(attributes) if attributes['id'].present? s...
Given(/^a user without an account provides new credentials$/) do start_page = StartPage.new(@driver) home_page = start_page.agree_and_start @sign_up_page = home_page.click_sign_up end Then(/^an account will be created and the message "([^"]*)" displayed$/) do |message| success_msg = @sign_up_page.create_acc...
ActiveAdmin.register Activity do remove_filter :activities_addresses # See permitted parameters documentation: # https://github.com/gregbell/active_admin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters # # permit_params :list, :of, :attributes, :on, :model # # or # # permi...
class PartnerNotifier < ActionMailer::Base default from: "nathan@passportfitnessdc.com" # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.partner_notifier.partner_subscription_confirmation.subject # def partner_subscription_confirmation(potential_partne...
#!/usr/bin/env ruby require_relative 'class_example_2.rb' class SavingsAccount < Account def initialize(balance, name, phone_number, interest, minimum) super(balance, name, phone_number) @interest = interest @minimum = minimum end def accumulate_interest @balance += @balance * interest end ...
class LeadsPage include PageObject page_section :top_bar, TopBarSection, css: '.pull-left' page_section :top_bar_settings, TopBarSettingSection, id: 'user-dd' link :newLead, id: 'leads-new' text_field :lastName, id: 'lead-last-name' button :save, css: '.save' span :lead_status, css: '.lead-status' bod...
module Effect class CastSpells attr_reader :parent def initialize(parent) @parent = parent unserialise end def unserialise character = @parent character = @parent.stateful if character.is_a? Entity::Status character = @parent.carrier if character.is_a? Entity::Item character.cast_spells = ...
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html resources :plots, only: :index do resources :growing_plants, only: :destroy end resources :gardens, only: :show end
require "rails_helper" RSpec.describe Cultivation::ActivateBatch, type: :command do let(:uom) { SeedUnitOfMeasure.call } let!(:facility) do facility = create(:facility, :is_complete) facility.rooms.each do |room| room.rows.each do |row| row.shelves.each do |shelf| shelf.trays.each(&...
FactoryBot.define do factory :product do name {'Default Product Name'} picture {'http://www.google.com'} origin { 'Default Product Origin' } cultural_history { 'Default Product Cultural History' } vegan {true} gluten_free {false} dairy_free {false} lc_based {true} fair {true} eco_sound {true} hum...
# Write an efficient algorithm for the following assumptions: # N is an integer within the range [1..100,000]; # each element of array A is an integer that can have one of the following values: 0, 1. EAST_DIRECTION = 0 def solution(a) going_east = 0 passings = 0 a.each do |direction| return -1 if pass...
require 'nokogiri' require 'open-uri' class Gravatar attr_accessor :url, :name, :thumbnail_url, :profile_url, :about_me, :current_location, :has_profile def initialize(url) @url = url end def self.url(email) hash = Digest::MD5.hexdigest(email) "http://gravatar.com/avatar/#{hash}?d=mm" end d...
class RemovingNullConstraintsOnPreferenceColumns < ActiveRecord::Migration def change change_column :preferences, :target_people, :string, null: true change_column :preferences, :target_age_range, :string, null: true change_column :preferences, :target_location, :string, null: true change_column :pref...
class ChangeDisplayLinkedinPitcureToDisplayLinkedinPicture < ActiveRecord::Migration[5.2] def change rename_column :talents, :display_linkedin_pitcure, :display_linkedin_picture end end
# Be sure to restart your server when you modify this file. # Add new inflection rules using the following format # (all these examples are active by default): # ActiveSupport::Inflector.inflections do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', ...
class Game < ActiveRecord::Base TOKEN = %w(Shoe Tophat Horse) end
class CreateThanhviens < ActiveRecord::Migration[5.0] def change create_table :thanhviens do |t| t.string :hoten t.string :password_digest t.string :gioitinh t.date :ngaysinh t.string :sdt t.string :email t.integer :role, :default => 2 t.integer :luotxem, :default ...
AdminType = GraphQL::ObjectType.define do name 'Admin' description 'Current admin user.' interfaces [GraphQL::Relay::Node.interface] global_id_field :id field :accounts, types[AccountType] do resolve -> (object, args, ctx) { if ctx[:current_user].is_super Account.all else Acco...
bash 'Clean libvirt networks' do user 'root' code <<-EOH virsh net-destroy default virsh net-undefine default EOH action :nothing end package 'libvirt-bin' do action :install notifies :run, resources(:bash => 'Clean libvirt networks'), :immediately end package 'pm-utils' do action :install end serv...
module OCELOT Java::OrgOdftoolkitSimpleTable::Cell.class_eval do def << val self.set_string_value val end end # Note: # # Tables are row-major Java::OrgOdftoolkitSimpleTable::Table.class_eval do # Read table cell using array syntax def [] col, row self.get_cell_by_position c...
class Api::FavoritesController < ApplicationController before_action :require_login def index @favorites = Favorite.where(user_id: params[:user_id]) render :index end def create @favorite = Favorite.new(user: current_user, restaurant_id: params[:restaurant_id]) if @favorite.save render ...
class Problem < CachedModel belongs_to :contest has_many :statements has_many :runs after_save :invalidate_cache after_destroy :invalidate_cache validates_presence_of :display_name def set_defaults! self.memory_limit = 64 self.time_limit = 5000 self.available = true self.displa...
class Result < ApplicationRecord belongs_to :questionnaire has_many :answers, dependent: :destroy validates :uid, presence: true validates_uniqueness_of :uid, scope: :questionnaire_id end
class ReminderController < ApplicationController before_filter :authenticate_user! before_filter :find_patient def new @reminder = @patient.build_reminder respond_to do |format| format.html # new.html.erb format.json { render json: @reminder } end end def create @reminder = @pa...
class FontDarkerGrotesque < Formula head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/darkergrotesque" desc "Darker Grotesque" homepage "https://fonts.google.com/specimen/Darker+Grotesque" def install (share/"fonts").install "DarkerGrotesque-Bla...
class CreateJoinTableDealershipResponseContacts < ActiveRecord::Migration def change create_table :dealership_response_contacts do |t| t.references :dealership_response_message, :dealership_contact t.timestamps end end end
require "sinatra" require 'sinatra/partial' require 'rack-flash' require_relative "./lib/sudoku" require_relative "./lib/cell" require_relative "./helpers/application" enable :sessions set :session_secret, "I'm the secret key to sign the cookie" use Rack::Flash set :partial_template_engine, :erb def random_sudoku ...
require_relative './cheater_stuff' module Smash class FtFeServer include Smash::CheaterStuff attr_accessor :clues def initialze(**opts) @project_root = File.expand_path(__FILE__) @message = String.new end def self.build(**opts) client = new client.inject_workflow(client...
class ExpansionsController < ApplicationController before_action :set_expansion, only: [:show, :update, :destroy] # GET /expansions def index @expansions = Expansion.all render json: @expansions.to_json(include: :raids) end # GET /expansions/1 def show render json: @expansion end # POST ...
class ApplicantPreviousData < ActiveRecord::Base belongs_to :applicant def validate mandatory_attributes = self.applicant.m_p_attr if mandatory_attributes.present? mandatory_attributes.split(", ").each do|m| self.applicant.errors.add_to_base("#{ApplicantPreviousData.human_attribute_name(m)}...
# 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 rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
class ProductsController < ApplicationController def index @products = Product.all() end #loads up the view of the same name after the action as executed #app/views/products/index.html.erb def show end end
require 'spec_helper' module Codebreaker describe Game do let(:output) { double('output').as_null_object } let(:game) { Game.new(output, 3) } describe "#start" do it "sends a welcome message" do output.should_receive(:puts).with("Welcome to Codebreaker! You have 3 guesses and 2 hints") ...
# -*- mode: ruby -*- # vi: set ft=ruby : # Load local settings - these may contain personalized settings such # as server keys. # # A sample Vagrantfile.local.dist.rb lists the expected settings. # if File.exist?('./Vagrantfile.local.rb') require './Vagrantfile.local' puts "Loaded local API keys and settings" inclu...
class BaseImageUploader < CarrierWave::Uploader::Base include CarrierWave::MiniMagick storage Rails.env.development? ? CDI::Config.enabled?(:upload_to_s3_in_development) ? :fog : :file : :fog def store_dir "uploads/#{Rails.env.to_s}/images/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end ...
class Api::MemoriesController < ApplicationController before_action :signed_in_user before_action :correct_user def index @user = User.find(params[:user_id]) @subject = @user.subjects.find(params[:subject_id]) render json: @subject.memories.as_json(include: [:subject]) end def show @user = U...
require 'phobos/cli/runner' module Phobos module CLI class Start def initialize(options) @config_file = File.expand_path(options[:config]) @boot_file = File.expand_path(options[:boot]) end def execute validate_config_file! Phobos.configure(config_file) l...
class ChangeDefaultPostState < ActiveRecord::Migration[6.0] def change change_column_default :posts, :state, from: :accepting, to: :open end end
class CreateMultiFeesTransactions < ActiveRecord::Migration def self.up create_table :multi_fees_transactions do |t| t.decimal :amount, :precision =>15, :scale => 2 t.string :payment_mode t.text :payment_note t.date :transaction_date t.references :student t.timestamps end ...
class CollegeCourse < ApplicationRecord # Associations belongs_to :college belongs_to :course # ------------ # Validations validates :college_id, presence: true validates :course_id, presence: true # ---------------- end
require "characterize/version" require "characterize/controller" require "characterize/feature_controls" require "casting" require "characterize/collection" require "characterize/railtie" if defined?(::Rails) module Characterize def self.included(klass) klass.class_eval { include Casting::Client dele...
# Model model: rest_name: cloudendpointdataproductinfo resource_name: cloudendpointdataproductinfo entity_name: CloudEndpointDataProductInfo package: yeul group: pcn/infrastructure description: Parameters associated with a cloud endpoint data product. detached: true # Attributes attributes: v1: - nam...
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :inclusao do incluido false motivo "MyString" voluntario_id 1 usuario_id 1 end end
class CreateGatherings < ActiveRecord::Migration def change drop_table :gatherings if (ActiveRecord::Base.connection.table_exists? :gatherings) create_table :gatherings do |t| t.string "artist", null: false t.text "location", null: false t.datetime "start_date", null: false...
# frozen_string_literal: true Sequel.migration do change do alter_table :coaches do add_column :social_links, :jsonb, null: false, default: {}.to_json end end end
class ApplicationController < ActionController::Base protect_from_forgery protected def current_user return unless session[:usuario_id] @current_user ||= Usuario.find_by_id(session[:usuario_id]) end helper_method :current_user def authenticate logged_in? ? true : access_d...
require "forwardable" require "time" require "sentry/version" require "sentry/core_ext/object/deep_dup" require "sentry/configuration" require "sentry/logger" require "sentry/event" require "sentry/transaction_event" require "sentry/span" require "sentry/transaction" require "sentry/hub" require "sentry/background_wor...
class AddDetailsToAgentes < ActiveRecord::Migration def change add_column :agentes, :nombre, :string, :limit=>25 add_column :agentes, :apellidos, :string, :limit=>50 add_column :agentes, :email, :string, :default => "", :null => false add_column :agentes, :password, :string, :limit => 40, :null => fals...
# # This fact prints a single ipv6 address from reverse dns lookup # # (c) 2013 Spencer Krum # Released under Apache2 Facter.add("dns_ip_6") do setcode do os = Facter.value('kernel') case os when /Linux/ hostname = `hostname -f` else hostname = `hostname` end host_output = `host #...
# -*- coding: utf-8 -*- =begin Escreva um programa que pergunte a velocidade do carro de um usuário. Caso ultrapasse 80 km/h, exiba uma mensagem dizendo que o usuário foi multado. Nesse caso, exiba o valor da multa, cobrando R$ 5 por km acima de 80 km/h. =end puts("=" * 60) print("Digite a velocidade do carro (Km)...
class CancionesService < Service def initialize params @parametros = params end def crear_cancion on_transaction do Cancion.create! parametros_de_creacion end end def todas_las_canciones Cancion.all end def ver_cancion on_transaction do Cancion.find parametros_de_busque...
class FacebookHelper attr_reader :strategy def initialize @strategy = OmniAuth::Strategies::Facebook.new(nil, SETTING['f_key'], SETTING['f_secret']) end def info(acc: xx) access_token = 'xx' end end
class ProfitabilitiesController < ApplicationController before_action :set_profitability, only: [:show, :edit, :update, :destroy] # GET /profitabilities # GET /profitabilities.json def index @profitabilities = Profitability.all end # GET /profitabilities/1 # GET /profitabilities/1.json def show ...
require 'spec_helper' feature 'Organization admin watches entries' do attr_reader :member, :organization, :challenge_one, :challenge_two before do user = create :user, name: 'Juanito' @member = create :member, user: user @organization = create :organization end scenario 'when there is no challeng...
require 'sinatra' require 'sinatra/reloader' @@guess_counter = 6 @@secret_num = rand(101) def check_guess(guess) if !params.include?("guess") ["Enter your guess below:", "pink"] else case guess - @@secret_num when 10..100 then ["Way too high! Number of guesses left: #{@@guess_counter-1}", "red"] ...
class CreateChatrooms < ActiveRecord::Migration[5.2] def change create_table :chatrooms do |t| t.references :user, null:false, foreign_key: true t.references :photographer, null:false, foreign_key: true t.bigint :readed_photographer_message, null: false, default: 0 t.bigint ...
FactoryBot.define do factory :collection do transient do user { FactoryBot.create(:user) } end id { 'test-collection-id' } title { ['Test title'] } collection_type_gid { 'gid://nextgen/hyrax-collectiontype/1' } after(:build) do |work, evaluator| work.apply_depositor_metadata(eval...
# Copyright (c) 2010 Anna <tanna22@gmail.com> # Copyright (c) 2006 Guilhem Vellut <guilhem.vellut+ym4r@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software # and associated documentation files (the "Software"), to deal in the Software without # restriction,...
module PmailHelper include NoteHelper include TextHelper def get_pmail_detail_preview(pmail) get_pure_text_one_line(pmail.mail_detail).truncate(Settings.pmail_detail_preview_length) end def make_reply_pmail(note, url) pmail = make_up_pmail_with_user_id get_user_name_by_note_id(note.reply_to) pma...
class Booking < ActiveRecord::Base belongs_to :car belongs_to :user belongs_to :specification end
module FormsHelper def forms_to_create required_forms = ['new', 'conditions', 'employee'] required_forms.reject { |form_name| @company.forms.find_by(name: form_name).present? } end def display_name(name) case name when 'new' return 'Add Employee (Manager)' when 'conditions' return...
# 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 CreateSnacks < ActiveRecord::Migration def change create_table :snacks do |t| t.string :name t.string :image_url t.string :country t.text :description t.string :mood t.string :taste t.integer :nutrition_level t.string :seller_url end end end
# frozen_string_literal: true class Tree attr_accessor :nodes def initialize(starting_coords) @moves = {} insert(starting_coords) end def insert(coords, parent_coords = nil) @moves[coords] = { parent: parent_coords, children: [] } @moves[parent_coords][:children] << coords if parent_coords ...
class StudentsController < ApplicationController before_action :authenticate_student! def show @student = Student.find(current_student.id) end def edit @student = current_student end def update @student = Student.find(current_student.id) if @student.update_with_password(student_params) ...
class AddNombreToEvaluador < ActiveRecord::Migration def change add_column :evaluadors, :nombre, :string end end
class PhysiciansController < ApplicationController before_action :set_physician, only: [:show, :edit, :update, :destroy] # GET /physicians def index @physicians = Physician.all end # GET /physicians/1 def show end # GET /physicians/new def new @physician = Physician.new end # GET /phys...
require_relative 'reporter' require 'json' require 'optparse' require 'colorize' require_relative 'ascii_report' require_relative 'data_util' def load_raw_data_files(file_paths) hashes = [] file_paths.each do |file_path| hashes << Marshal.load(File.read(file_path)) end return hashes end # given a list of ...
#Ranges as conditions num=50 result=case num when 0..10 then "childrens" when 10..20 then "teengers" when 20..30 then "young stars" when 30..40 then "middle aged" when 40..60 then "old people" end print result,"\n"
module User class ActivityLogsController < JsonController def index @logs = ActivityLogs.order("activity_logs.created_at DESC").includes(:system_user) if not params[:user_action].nil? @logs = @logs.where("action like ?", "%#{params[:user_action]}%") end if not params[:object].nil? ...
class Api::EmployeeCategoriesController < ApiController filter_access_to :all def index @xml = Builder::XmlMarkup.new @employee_categories = EmployeeCategory.active.search(params[:search]) respond_to do |format| format.xml { render :employee_categories } end end end
require 'spec_helper' describe User, '.present_at? event' do subject(:user) { create(:user, :paul) } let(:billy) { create :user, :billy } let(:event) { create(:event, :tasafoconf, owner: billy) } context 'when user does not have enrollment' do it 'search for enrollment' do expect(Enrollment).to rece...
# Source: https://launchschool.com/exercises/ae80cee3 class Person def initialize(name) @name = name end def name @name.dup # prevent mutation on the original instance var val end end person1 = Person.new('James') person1.name.reverse! puts person1.name
# frozen_string_literal: true require "test_helper" require "generators/boring/simple_form/install/install_generator" class SimpleFormInstallGeneratorTest < Rails::Generators::TestCase tests Boring::SimpleForm::InstallGenerator setup :build_app teardown :teardown_app include GeneratorHelper include ActiveS...
class CreateResponses < ActiveRecord::Migration[5.0] def change create_table :responses do |t| t.references :commit, index: true, foreign_key: true t.references :url, index: true, foreign_key: true t.string :request_id t.text :production t.text :shadow t.integer :commit_id ...
class BriefingSessionUrl < ActiveRecord::Base belongs_to :briefing_session belongs_to :url end
class Song attr_accessor :name, :artist_name @@all = [] def self.all @@all end def save @@all << self # self.class.all << self end # initializes a song and saves it to # the `@@all` class variable either literally or through the class method # Song.all`. This method should return the s...
# frozen_string_literal: true describe Kafka::Client do let(:logger) { LOGGER } let(:kafka_brokers) { KAFKA_BROKERS } let(:client_opts) do { seed_brokers: KAFKA_BROKERS, client_id: "test", logger: logger } end describe ".new" do context "when SASL SCRAM has been configured with...
require 'test_helper' class CommentTest < ActiveSupport::TestCase # Instance Method Tests # # Comment#user test "comment returns user if user is present" do order = FactoryGirl.create(:order) user = FactoryGirl.create(:user) comment = FactoryGirl.create(:comment, order: order, user: user) as...
module BookKeeping VERSION = 4 end class Pangram ALPHABET = ('a'..'z').to_a def self.pangram?(sentence) (ALPHABET - sentence.downcase.chars).empty? end end
class OVOST::User attr_reader :email, :user_id, :is_admin def initialize(email, password, user_id, is_admin=false) @email = email @password = password @user_id = user_id @is_admin = is_admin end end
class PodcastsController < ApplicationController before_action :set_podcast, only: [:show, :subscribe_new, :subscribe_create, :subscribe_success, :subscribe_error] # GET /podcasts # GET /podcasts.json def index @podcasts = Podcast.where(:public => true).order(:updated_at => :desc) @meta_title = Brick::...
class TechnologyCategory < ActiveRecord::Base has_many :technologies validates :name, presence: true end
class CreateQuestions < ActiveRecord::Migration[5.2] def change create_table :questions do |t| t.string :question_id t.string :question t.string :description t.string :answer_a t.string :answer_b t.string :answer_c t.string :answer_d t.string :answer_e t.strin...
require 'digest/sha2' class User < ActiveRecord::Base include RpxSupport validates_presence_of :email validates_uniqueness_of :email validates_format_of :email, :with => /^.*@.+\..+$/, :allow_blank => true validates_presence_of :privacy_token validates_format_of :privacy_t...
require 'rails_helper' RSpec.describe Link, type: :model do let(:link) { Link.create!({ :url => "http://example.com", :description => "sample Mark description" }) } it "creates a Link" do expect(link.persisted?).to eq true expect(link.url).to eq "http://example.com" expect(link.description...
class AddHiddenToEpic < ActiveRecord::Migration[5.2] def change add_column :epics, :hidden, :boolean, default: false end end