text
stringlengths
10
2.61M
require 'test_helper' class UserTest < ActiveSupport::TestCase context 'creating a User from RPX' do setup do Credential.delete_all User.delete_all @user, @credential = User.build_from_rpx({ :provider => 'OpenID', :identifier => 'http://me.example.com', :email => 'me@...
# Author:: AlexTAB # Version:: 0.1 # Copyright:: © 2017 # License:: Distributes under the same terms as Ruby ## ## Modèle pour le score ## class Score < Model attr_accessor :difficulte ## ## Initialisation ## def initialize() ## Crée la table Score @@db.execute "CREATE TAB...
module LruCache2 class Node attr_accessor :key, :value, :previous, :next def initialize(**opts) raise ArgumentError.new('key and value are mandatory parameters') unless opts[:key] && opts[:value] @key = opts[:key] @value = opts[:value] @previous = opts[:previous] @next ...
require 'test_helper' class Student::ExamsControllerTest < ActionController::TestCase setup do @student_exam = student_exams(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:student_exams) end test "should get new" do get :new assert_r...
# -*- mode: ruby -*- # vi: set ft=ruby : # Vagrantfile API/syntax version. Don't touch unless you know what you're doing! VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "Centos" config.vm.box_url = "http://box.puphpet.com/centos64-x64-vbox43.box" config.vm.netw...
class UsersController < ApplicationController def index @users=User.all end def new @user=User.new end def create @user=User.new(user_params) if @user.save flash[:notice] = "the user added succesfully" redirect_to users_path else @user.errors render :new end end ...
require 'open-uri' module Kickstarter module DailyReports module Scrapers class GetDailyReportSimpleDataService private attr_reader :campaign public def initialize(campaign) @campaign = campaign end def call stats_url = "#{campaign.kicks...
# A plugin to try to determine the remote servers this server # uses (ex. mysql databases, etc...) by listing the addresses # and ports that this server connects to. # # Data is returned is an hash with remote ip and a port list. # Inbound connections are assumed based on LISTENing ports and # are not included in the o...
module Effect # Ability doesn't work cross-plane yet... Also needs to rebuild link on server restart class AlonaiAegisAbility < ActivatedTarget def initialize(parent, costs = {ap: 1}, name = 'Alonai\'s Aegis') super parent, costs, name, [Entity::Character] @costs[:mo_check] = self.method(:mo_check) @costs...
class Adv < ActiveRecord::Base upload_column :logo, :versions => {:thumb200 => "c200x200", :thumb100=> "c160x160", :thumb50=>"c50x50"} validates_presence_of :logo, :message=>"必须上传图片" validates_presence_of :link, :message=>"请输入链接网址" def self.get(tp) Adv.find(:all, :conditions=>"tp=#{tp} and hide = 0 ", ...
class FileSizeValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) file_megabytes = value / 1.megabytes.to_f record.errors[attribute] << (options[:message] || "file size must be under #{options[:max_megabytes]}") if file_megabytes > options[:max_megabytes] end end
# encoding: UTF-8 class Gauge < Wx::Frame MAX = 100 attr_accessor :loading def initialize(parent, loading = "") super(parent, :title => "Logo", :size => [300,120], :style => Wx::NO_BORDER|Wx::FRAME_NO_TASKBAR|Wx::STAY_ON_TOP) set_own_background_colour(Wx::Colour.new(240,230, 235)) @delta = [0,0] @loadi...
Rails.application.routes.draw do resources :users do resources :chats do resources :messages end resources :friends end root "users#index" end
require 'rails_helper' RSpec.describe "Routing to manufacturers", type: :routing do it 'routes GET /manufacturers to manufacturers#index' do expect(get: "/manufacturers").to route_to("manufacturers#index") end end
class Var < ActiveRecord::Base belongs_to :product has_many :models, dependent: :destroy accepts_nested_attributes_for :models, :allow_destroy => true def self.check_and_create(product,vars_params,model_params) color = "" if vars_params["color"].present? color = vars_params[:color] end @...
class ListsController < ApplicationController respond_to :html, :js before_action :authenticate_user! # users must be signed in before any lists_controller method def index @lists = current_user.lists # @item = current_user.lists.find(params[:list_id]), Item.find(params[:id]) end def show ...
module ActionView::Helpers class FormBuilder def inputs(options = {}, &block) update_options_with_class!(options, 'form-inputs') @template.content_tag(:div, options) { yield } end def actions(options = {}, &block) update_options_with_class!(options, 'form-actions') @template.cont...
module ActiveCommand module Exceptions class UnexistentDefaultType < StandardError def initialize(type) @type = type super("Unexistent default type: `#{type}`") end end class IncompatibleType < StandardError def initialize(object, expected) @object = object ...
require 'spec_helper' describe Fappu::Manga , vcr: {cassette_name: 'manga'} do context "The manga is 'Right now while cleaning the pool'", vcr: { cassette_name: 'pool_cleaning_comments' } do subject(:manga) { described_class.new(url: 'https://www.fakku.net/manga/right-now-while-cleaning-the-pool') } descri...
json.array! @categories do |category| json.id category.id json.title category.title json.image_url polymorphic_url(category.image) if category.image.attached? end
begin puts 'code before raise.' raise 'exception occurred.' puts 'code after raise.' rescue puts 'I am rescued.' end puts 'code after begin block.'
#============================================================================== # Attract Mode # by: Racheal # Version 1.3 # Created: 09/12/2013 # Updated: 10/12/2013 #============================================================================== # Allows you to set up an attract mode map if the player idles on the tit...
# frozen_string_literal: true RSpec.describe SendContactUsLetterService do let(:service) { described_class.new } describe '#call' do subject(:call) do service.call(name: name, email: email, message: message) end let(:name) { FFaker::Name.name } let(:email) { FFaker::Internet.email } let...
class CreateMomentumCmsLocales < ActiveRecord::Migration def change create_table :momentum_cms_locales do |t| t.string :label t.string :identifier end end end
class User < ApplicationRecord attr_reader :current_user has_secure_password enum role: [:guest, :standard, :administrator] validates :username, presence: true, uniqueness: true alias_attribute :name, :username # validate :cannot_set_your_own_role validate :username_must_be_all_lowercase_with_underscor...
class City < ApplicationRecord belongs_to :state has_many :addresses end
class Vehicle < ActiveRecord::Base has_many :assignments accepts_nested_attributes_for :assignments attr_accessible :make, :model, :year, :checked_out validates_presence_of :make, :model, :year end
class Book < ApplicationRecord belongs_to :user validates :title, presence: true validates :body, presence: true end
# Source: https://launchschool.com/exercises/51e98567 # Q: Write a method that takes one argument, a string, and returns a new string # with the words in reverse order. sentence = 'We reversed this sentence successfully' def reverse_sentence(sentence) sentence.split.reverse.join(' ') end puts reverse_sentence(...
class ProjectsController < ApplicationController before_action :authenticate_user!, except: [:show, :index] def new @project = Project.new end def create @project = Project.new(project_params) if @project.save flash[:success] = "Project has been created" redirect_to projects_path e...
class Reservation attr_reader :tickets, :email def initialize(tickets, email) @tickets = tickets @email = email end def total_cost tickets.map(&:price).sum end def complete!(payment_gateway, payment_token) payment_gateway.charge(total_cost, payment_token) Order.for_tickets(tickets, e...
require_relative "deck" require_relative "hand" # require_relative 'betting' require 'pry' class Blackjack def initialize @player @computer @current_deck @hit_stay @yes_no # @betting = Betting.new end def start_game @current_deck = Deck.new @player = Hand.new @computer = Han...
class Api::PicsController < ApplicationController before_filter :require_signed_in! def index @pics = Pic.all end def show @pic = Pic.find(params[:id]) end def create @pic = Pic.new(pic_params) @pic.user_id = current_user.id @pic.save! end def destroy @pic = Pic.find(params[:...
require 'spec_helper' feature 'Creating DJs' do let!(:user) { FactoryGirl.create(:confirmed_user) } before do sign_in_as!(user) @club_night = FactoryGirl.create(:club_night, :name => "DnB Tuesdays") user.club_nights << @club_night visit club_night_path(@club_night) click_link "Add a DJ to DnB...
# Source: https://launchschool.com/exercises/16ab1e1f def greetings(name, job) full_name = name.join(' ') title = job[:title] occupation = job[:occupation] "Hello, #{full_name}! Nice to have a #{title} #{occupation} around." end greetings(['John', 'Q', 'Doe'], { title: 'Master', occupation: 'Plumber' })
class AssetsController < ApplicationController respond_to :html, :js def new @number = params[:number].to_i end def show asset = Asset.find(params[:id]) if can?(:read, asset.ticket.project) send_file asset.asset.path, :filename => asset.asset_file_name, :con...
require_relative './render' require_relative '../engine/dependencies' class TextRender < Render extend Dependencies add_dependency(:position) attr_accessor :text attr_accessor :font def initialize(name, parent, text = '', height = 12, font = 'Norasi') @font = Gosu::Font.new(height, name: font) @tex...
class Restaurant attr_reader :menu def initialize(menu, notification_service=Notificationservice.new) @menu = menu @notification_service = notification_service end def submit_order(customer_name, customer_phone_number, order_dishes, expected_sum) order_dishes.each_key do |dish| fail "Di...
require('minitest/autorun') require('minitest/reporters') require_relative('../models/property.rb') Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new class PropertyTest < Minitest::Test # address # value # number of bedrooms # year built def test_can_create_a_property__address property_deta...
vagrant_api_version = "2" instance_count = 3 if ENV['INSTANCES'] instance_count = ENV['INSTANCES'].to_i end Vagrant.configure(vagrant_api_version) do |config| config.vm.define :server do |server| server.vm.box = "jeremyot/ubuntu-14.04.3LTS" server.vm.provider :virtualbox do |v, override| v.customiz...
class Dessert attr_reader :dessert, :bakery @@all = [] def initialize(dessert, bakery) @dessert = dessert @bakery = bakery @@all << self end def self.all @@all end def ingredients Ingredient.all.select { |ingredient| ingredient.dessert == self} # - should return an array of ingred...
module Collisions INV_MAGIC = 0xe59b19bd R = 16 MASK_32 = 0xffffffff DIFF = "\x00\x00\x00\x80\x00\x00\x00\x80" module_function def find(blocks) num_collisions = 1 << blocks in0 = Random.new.bytes(8 * blocks) in1 = "".tap do |s| in0.each_byte.each_with_index do |b, i| s << (in0...
# frozen_string_literal: true class ArticlePreviewSerializer < ApplicationSerializer attributes :id, :title, :permalink, :published def published object.published.iso8601 end end
begin require "specific_install/version" require "rubygems/commands/specific_install_command" rescue LoadError # This happens with `bundle exec gem build <gemspec>` commands. # But in that context we don't care. end
class Ability include CanCan::Ability def initialize(user) # set user to new User if not logged in user ||= User.new # i.e., a guest user if user.role? :admin can :manage, :all elsif user.role? :customer can :show, Customer do |customer| customer.id == user.customer.id ...
class User < ApplicationRecord before_save { self.email = email.downcase } has_many :stuffs, dependent: :destroy validates :username, presence: true, uniqueness: { case_sensitive: false }, length: { minimum: 3, maximum: 25 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\...
require 'test_helper' # bundle exec ruby -Itest test/controllers/links_controller_test.rb class LinksControllerTest < ActionDispatch::IntegrationTest ### # For project links ### describe "for project links" do describe "#edit" do describe "when user is not logged in" do test "redirect to logi...
require_relative('../db/sql_runner') class City attr_reader :country_id, :id attr_accessor :name def initialize(options) @id = options['id'].to_i @name = options['name'] @country_id = options['country_id'].to_i end def save() sql = "INSERT INTO cities ( name, country_id ...
class AddBilirubinUrinalysisToClinicalBloodRecords < ActiveRecord::Migration def change add_column :clinical_blood_records, :bilirubin_urinalysis, :float end end
class User < ActiveRecord::Base has_secure_password has_many :posts has_many :likes validates :name, :alias, :email, presence: true validates :password, length: { in: 8..20 }, on: :create end
class Client < User has_many :owners has_many :horses, through: :owners has_one :info, class_name: "ClientInfo", dependent: :destroy end
# frozen_string_literal: true module Kafka module Protocol class DescribeGroupsResponse class Group attr_reader :error_code, :group_id, :state, :members, :protocol def initialize(error_code:, group_id:, protocol_type:, protocol:, state:, members:) @error_code = error_code ...
class Gift < Purchase has_many :purchases, :foreign_key => "seller_id" has_many :products #, through: :products # attr_accessible :title, :body # attr_reader :product_description attr_reader :product_description #attr_accessor :revenue_donation_percent, :profit_donation_percent, :product_description ...
class InterviewsController < ApplicationController before_action :authenticate_user! before_action :check_interviewer respond_to :json, :html add_breadcrumb "interviews", :interviews_path def index @interviews = Interview.order(created_at: :desc).paginate(page: params[:page], :per_page => 10) respond_...
class CreateProfilePics < ActiveRecord::Migration def change create_table :profile_pics do |t| t.integer :profile_id, :null => false t.string :title, :length => 40 t.boolean :is_default, :default => false end add_attachment :profile_pics, :image ...
class CartsController < ApplicationController # before_action :set_cart class DisallowSaleMode < ActiveModel::ForbiddenAttributesError; end before_action :check_for_mobile, only: [:show] def show @items = current_cart.items end # def add # if allow_sale_modes.include? sale_mode # @cart.ite...
class SaveFacilityAddSection prepend SimpleCommand def initialize(facility_id, room_id) @facility_id = facility_id @room_id = room_id end def call save_record end private def save_record facility = Facility.find(@facility_id) room = facility.rooms.find(@room_id) room.sections |...
require 'find' class Phile < ActiveRecord::Base belongs_to :media_root has_one :movie, :dependent => :destroy has_one :episode, :dependent => :destroy has_one :seen, :dependent => :destroy has_one :show, :through => :episode scope :deleted, :conditions => ["deleted_at is not null"] scope :existing...
# frozen_string_literal: true require 'sidekiq/web' Rails.application.routes.draw do mount Sidekiq::Web => '/sidekiq' api_version( module: 'v1', path: { value: 'v1' }, defaults: { format: 'json' }, default: true ) do constraints subdomain: 'api' do post 'authenticate', to: 'authenticat...
require 'rails_helper' RSpec.describe "Mass create performance", type: :unit do it 'checks current performance' do expect { data = GenerateContacts.new.call emails = data.collect { |contact| contact[:email] } Contact.insert_all!(data) contacts = Contact.select(:id, :name, :email).wher...
class AddContainerCapacityToBoats < ActiveRecord::Migration[5.1] def change add_column :boats, :container_capacity, :integer end end
# Copyright 2012 AMG.lab, a Bull Group Company # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
require 'spec_helper' require 'tempfile' describe "Identity exports" do it "should export the simplest PSD" do filepath = 'spec/files/simplest.psd' psd = PSD.new(filepath) psd.parse! tmpfile = Tempfile.new("simplest_export.psd") psd.export tmpfile.path Digest::MD5.hexdigest(tmpfile.read).sho...
class CreateJoinTableGuardiansStudents < ActiveRecord::Migration def change create_table :guardians_students, :id => false do |t| t.belongs_to :guardians t.belongs_to :students end end end
class Party < ApplicationRecord has_many :guests end
# Combining Arrays # https://launchschool.com/exercises/1ba11514 # Write a method that takes two Arrays as arguments, and returns an Array that contains all of the values from the argument Arrays. There should be no duplication of values in the returned Array, even if there are duplicates in the original Arrays. def ...
require 'rails_helper' RSpec.describe ReservationsController do describe "GET #index" do before do get :index end it "returns http success" do expect(response).to have_http_status(:success) end end describe "POST #create" do before do params = { start_date: "202...
class Store < ApplicationRecord validates :name, presence: true, uniqueness: true validates :contact_info, presence:true validates :location, presence:true has_many :comments, dependent: :destroy has_many :ratings, dependent: :destroy end
class MarketsController < ApplicationController before_action :authenticate_user! def new @user = current_user @market = Market.new end def create @user = current_user @market = @user.markets.create!(market_params) redirect_to markets_path end def index user = current_user @ma...
class AddCatIdPhotoIdToCatPhotos < ActiveRecord::Migration def change add_column :categorized_photos, :category_id, :integer add_column :categorized_photos, :photo_id, :integer end end
class Api::UsersController < ApplicationController # before_action :authenticate_user, only: [:destroy] def index @users = User.all render "index.json.jb" end def show @user = User.find(params[:id]) render "show.json.jb" end def create user = User.new( name: params[:name], ...
class PostsController < ApplicationController before_action :authenticate_user!, only: [:create] before_action :set_post, only: [:show, :edit, :update, :destroy] # def post # end # def post # @post= post # end # def index # @posts = Post.all # end # def new # ...
require 'rest-client' require 'json' require 'pry' def next_page url = "http://www.swapi.co/api/people/" new_list = [] response_hash = JSON.parse(RestClient.get(url)) while !!response_hash["next"] new_list << response_hash["results"] response_hash = JSON.parse(RestClient.get(response_hash["next"])) e...
require 'test_helper' class EntryItemsControllerTest < ActionController::TestCase setup do @entry_item = entry_items(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:entry_items) end test "should get new" do get :new assert_response :s...
#You are in an infinite 2D grid where you can move in any of the 8 directions : #You are given a sequence of points and the order in which you need to cover the points. Give the minimum number of steps in which you can achieve it. You start from the first point. #Input x-axis array and y-axi array Eg: Input : [(0, 0),...
module SimpleJsonapi::Node # Represents a resource's +relationships+ object, which contains the # individual +relationship+ object. # # @!attribute [r] resource # @return [Object] # @!attribute [r] resource_type # @return [String] # @!attribute [r] relationship_definitions # @return [Hash{Symbol...
# Copyright (c) 2016 Scott O'Hara, oharagroup.net # frozen_string_literal: true # Favouritable module Measurable extend ActiveSupport::Concern # Methods for measuring things, in particular date periods module ClassMethods # Weeks since a given date def weeks_since(date) ((Time.zone.today - date) / 7).to_i ...
class UserUrlsController < ApplicationController def index @urls = UserUrl.all_urls end def show @url = UserUrl.find(params[:id]) log_ip_address redirect_to @url.long_url end def create @url = UserUrl.new(url_params) @url.short_url = @url.make_short_url if @url.save redir...
#Fedena #Copyright 2011 Foradian Technologies Private Limited # #This product includes software developed at #Project Fedena - http://www.projectfedena.org/ # #Licensed under the Apache License, Version 2.0 (the "License"); #you may not use this file except in compliance with the License. #You may obtain a copy of the ...
require 'rails/engine' class ExpiringTags::Engine < Rails::Engine engine_name :expiring_tags # Allow the migrations to be run in the main app # http://pivotallabs.com/leave-your-migrations-in-your-rails-engines/ initializer :append_migrations do |app| unless app.root.to_s.match root.to_s config.path...
# encoding: UTF-8 require_relative '../spec_helper' describe Post do it "should require a title" do post = build(:post) [nil,"", " "].each do |invalid_title| post.title = invalid_title post.should have_error_on(:title).with_message("can't be blank") end end it "should require a use...
class Pig < Animal def initialize @name = 'pig' @noise = 'Oink!' end end
class Tab < OpenStruct def build_32_bit? odisabled "Tab.build_32_bit?" end end
class User < ApplicationRecord has_many :microposts #microposts is plural because a user has many (a lot, not just one) microposts validates :name, :email, presence: true end
class AddIndexToDevelopmentResult < ActiveRecord::Migration[5.2] def change add_index :development_results, [:e_no, :result_no, :generate_no], :unique => false, :name => 'resultno_and_eno' add_index :development_results, :development_result add_index :development_results, :bellicose add_index :develop...
require 'spec_helper' describe 'Collection GIBS Filtering', reset: false do before :all do Capybara.reset_sessions! load_page :search, facets: true, env: :sit end context 'when selecting the GIBS filter' do before :all do find('p.facets-item', text: 'Map Imagery').click wait_for_xhr ...
$stdout.sync = true require 'sinatra' require 'dotenv' Dotenv.load require "web_task_runner/version" require "web_task_runner/redis_module" require "web_task_runner/task_worker" class WebTaskRunner < Sinatra::Application VERSION = WebTaskRunnerVersion::VERSION @@jobs = [] def self.jobs @@jobs end be...
class AddWanikaniStatsToUsers < ActiveRecord::Migration def change add_column :users, :username, :string add_column :users, :gravatar, :string add_column :users, :wanikani_level, :integer remove_column :users, :wanikani_user_info end end
class Oauth2Controller < ApplicationController include ApplicationHelper before_action :authenticate_user! def redirect client = Signet::OAuth2::Client.new(oauth_client_options) redirect_to client.authorization_uri.to_s end def callback client = Signet::OAuth2::Client.new(oauth_client_options) ...
module RegularizationTreatment class CadastreProceduralStatusesController < ApplicationController before_action :set_cadastre,except: [:show] before_action :set_step before_action :set_cadastre_show, only: [:show] def new @cadastre_procedural_status = Candidate::CadastreProceduralStatus.new ...
require './lib/board.rb' RSpec.describe Board do context "#end_board" do subject { described_class.new } it "returns the length of the board" do expect(subject.end_board).to eq(0) end end end
require 'simplecov' SimpleCov.start 'rails' require 'spec_helper' ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) abort("The Rails environment is running in production mode!") if Rails.env.production? require 'rspec/rails' require 'webmock/rspec' ActiveRecord::Migration.main...
# Methods added to this helper will be available to all templates in the application. module ApplicationHelper include TagsHelper def page_title @title || "no-title-fix-me" end def is_admin? session[:admin] end end
require 'insanity/version' require 'insanity/screen_printer' require 'insanity/file_writer' require 'open3' module Insanity class Runner def initialize(command:, options:, printer: ScreenPrinter.new, persistence_klass: FileWriter) @command = command @iterations = options[:iterations] @printer ...
class Person < Praxis::MediaType attributes do attribute :id, Integer attribute :name, String, example: /[:name:]/ attribute :href, String, example: proc { |person| "/people/#{person.id}" } attribute :links, Praxis::Collection.of(String) end view :default do attribute :id attribute :name...
class CountdownController < ApplicationController def index render layout: "countdown" @message = "" end end
module AchievementConcerns module CommentAchievementable extend ActiveSupport::Concern include AchievementConcerns::SimpleAchievementable private def comment_post grant_on_create self.resource.publisher_type == "EducationalInstitution" ? :comment_institution_post : :comment_post g...
# Extension for events, for better readability module SDC class Event def has_type?(event_type) return self.type == SDC::EventType.const_get(event_type) end def key_pressed?(key) return self.key_code == SDC.key(key) end def mouse_button_pressed?(button) return self.mouse_button_code == SDC.mous...
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| config.vm.box = "base" config.vm.box_url = "http://cloud-images.ubuntu.com/vagrant/raring/current/raring-server-cloudimg-amd64-vagrant-disk1.box" config.vm.network :private_network, ip: "192.168.12.34" config.vm.provider :virtu...
class CustomMailer < ApplicationMailer def custom_mail(body, email, subject, event) @event = event @email = email @subject = subject @body = body mail(bcc: @email, subject: @subject) end end