text
stringlengths
10
2.61M
require 'spec_helper' describe Question do it 'can create a new question' do question = Question.new(question: 'Feeling', long_form: 'How do you feel?') expect(question).to be_valid end it 'has a valid factory' do expect(FactoryGirl.create(:question)).to be_valid end it 'is not valid without a ...
# This class is linked to the lessons table class Lesson < ApplicationRecord # 1 cour - N lessons belongs_to :cour end
require 'rubygems' require 'mechanize' class Agent def initialize(product_name) @agent = Mechanize.new @product_name = product_name @@index = 'http://google.fr' end # go into the search page and enter the product name and submit # this function returns the search result page. def go_to_search(search_form_i...
require 'date' require 'open-uri' require 'csv' require 'cgi' require_relative 'constants' module Util module_function def cpubdate_to_timestamp(cpubdate) return '' if cpubdate.nil? || cpubdate.empty? date = cpubdate.gsub(/oktober/i, 'October') # hack for missing Oktober date = Date.parse(date) ...
# -*- encoding : utf-8 -*- class Cms::HolesController < Cms::BaseController before_action :find_group, only: [:new, :create] def index @holes = Hole.page(params[:page]) end def show @hole = Hole.find(params[:id]) end def new @hole = Hole.new end def edit @hole = Hole.find(par...
require "application_system_test_case" class MessagesTest < ApplicationSystemTestCase setup do @message = messages(:message_simple) end test "visiting the index" do _login() visit messages_url assert_selector "h1", text: "Messages" end test "creating a Message" do _login() visit mes...
require 'pathname' ## # Functionality for dealing with Sass (scss, sass) files. #TODO: Restructure as instance. class Sass attr_accessor :files def initialize(files, directory) @files = files @directory = directory end def self.[](dir=".") throw Exception.new("Expected a dir, got file #{ dir } ...
class RemoveUsernameEmployeeTable < ActiveRecord::Migration def up remove_column :users, :username end def down add_column :users, :username, :string, :limit => 24 end end
require 'spec_helper' describe "Discussion API", type: :api do let(:user) { build(:logged_user) } let!(:account) { create(:account_with_schema, subdomain: ApiHelper::SUBDOMAIN, owner: user) } before :each do set_header user end describe "GET /discussions" do it "should render 404 if no targetable n...
require_relative 'features_helper' feature 'Add review' do given!(:book) { FactoryGirl.create(:book) } given(:user) { FactoryGirl.create(:user) } scenario 'authenticated user can add review' do sign_in(user) visit(book_path(book)) click_on('Leave a Review') #fill_in('review[rating]', with...
# frozen_string_literal: true class Company < ApplicationRecord validates :name, :country, presence: true belongs_to :student has_many :cash_managements validates :name, :uniqueness => true #class method to find list of companies def self.list(user) if user.is_a? Teacher Company.all #if a user is teach...
class CommunitiesController < ApplicationController before_filter :authenticate_user!, :except => [:index, :show] has_widgets do |root| root << widget(:new_community) root << widget(:community_list) root << widget(:section_list, :community => @community) end def index if params[:categ...
require 'rails/generators' require 'rails/generators/base' require 'rails/generators/active_record' class InstallGenerator < Rails::Generators::NamedBase include ActiveRecord::Generators::Migration source_root File.expand_path("../templates", __FILE__) def create_migrations get_dir_path('migrations').sort....
class JpSynthetic < ActiveRecord::Base # mysql table used self.table_name = "jp_synthetics" ###################################################### ##### table refenrence ###################################################### belongs_to :lexeme, :class_name=>"JpLexeme", :foreign_key=>"sth_ref_id" has_...
## Classes # as a programmer, you'll often want to model some object and the properties #of the object, For example, a social media site may need to mdoel a user with their #user name and a profiel picture. Or perhaps a music site may need to model a song #with it's title, genre, and duration. Following App Academy t...
# frozen_string_literal: true require 'securerandom' class Part < ApplicationRecord has_many :sub_parts, inverse_of: :part accepts_nested_attributes_for :sub_parts, allow_destroy: true validates :identifier, presence: true, uniqueness: true update_index 'parts', :self after_initialize do self.identif...
class AddAreaToVillages < ActiveRecord::Migration def change add_column :villages, :area, :integer end end
class Logo < ActiveRecord::Base has_attached_file :image, :styles => { :original => "800x800", :large => "100x200", :medium => "50x100", :small => "25x50" }, :default_style => :large belongs_to :company # We shouldn't have a logo without an attached image validates_atta...
class AddRangeMaxToPayment < ActiveRecord::Migration[6.0] def change add_column :payments, :range_max, :decimal end end
### Testing task 2 code: # Carry out dynamic testing on the code below. # Correct the errors below that you spotted in task 1. require_relative('card.rb') # 5. changed folder class CardGame #6 changed test name to TestCardGame def self.check_for_ace(card) # 4. fixed lower case snake case, 7. changed to self r...
require 'cuba/test' require './fizz_buzz_app.rb' scope do test 'root' do get '/' assert last_response.body.include?('Welcome to Mario\'s FizzBuzz') end test 'any page should redirect to root' do get '/any-page' follow_redirect! assert last_response.body.include?('Welcome to Mario\'s FizzBuz...
RSpec.describe User, "login" do feature "Log in" do let!(:user) {FactoryGirl.create :user} scenario "Successful sign in" do visit "/users/sign_in" fill_in "E-mail", with: user.email fill_in "Mật khẩu", with: user.password click_button "Đăng nhập" expect(page).to have_content "Đ...
class Greeter @@salutation = 'hello' def initialize(name) @name = name end def greet puts "#{@@salutation}, #{@name}" end def self.perform new('world').greet end end Greeter.perform module Counter def initialize @count = 0 end def increment @count = count + 1 end def c...
class Group < ApplicationRecord has_many :users, optional: true end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_and_belongs_to_many :homeworks has_many :registri...
class Publication < ActiveRecord::Base include PublicActivity::Model mount_uploader :image, AvatarUploader belongs_to :project belongs_to :user has_many :comments, dependent: :destroy has_many :shares, dependent: :destroy has_many :activities, as: :trackable, class_name: 'PublicActivity::Activity', dependent: ...
class User < ApplicationRecord rolify # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable # setup relations, ensure to prevent orphan r...
# 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 RemoveValueFromPolls < ActiveRecord::Migration[5.2] def change remove_column :polls, :value add_column :polls, :value, :float end end
class HumanPlayer attr_accessor :mark_value def initialize(mark_value) @mark_value = mark_value end def get_position puts "Player #{mark_value.to_s}, enter two numbers representing a position in the format `row col`" pos = gets.chomp.split(' ').map(&:to_i) raise 'inv...
require 'test_helper' class ResultTest < ActiveSupport::TestCase # test "the truth" do # assert true # end test 'should not save new empty user' do posled = Result.new assert posled.save end =begin test 'should not save duplicate data' do @param = '1 2 3 3 4 5 6 7 8 1 2 3 3 3 3 34 35 72 96 1...
module Fog module Compute class Google class Mock def add_target_pool_health_checks(_target_pool, _region, _health_checks) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end class Real def add_target_pool_health_checks(target_...
class Holiday attr_reader :next_three_holidays def initialize holiday_service = HolidayService.new @next_three_holidays = holiday_service.get_holiday_data[0..2] end end
# encoding: utf-8 class Moip::Plan < Moip::Model include HTTParty include Moip::Header # see http://moiplabs.github.io/assinaturas-docs/api.html#criar_plano attr_accessor :code, :name, :description, :amount, :setup_fee, :interval, :billing_cycles, :status, :max_qty, :plans validates :code, :nam...
Rails.application.routes.draw do devise_for :users # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root 'home#index' get 'about', to: 'home#about' get 'methodology', to: 'home#methodology' resources :products, only: [:index, :show, :create] do re...
class ActivityPost < ApplicationRecord extend FriendlyId max_paginates_per 5 friendly_id :title, use: :slugged mount_uploader :image, ImageUploader belongs_to :user after_initialize :set_defaults validate :check_time # validate :check_start_date_and_end_date validates_presence_of :title, :descripti...
require 'json' module Actions module GladiatorsActions def generate_actions(data) data.each do |k, v| if v.is_a?(Hash) v.each do |k, v| if k == "name" define_method ("greeting") do p "Going to death #{v}, salute you!" end elsif k == "weapon" v.each do |v| d...
Sequel.migration do change do create_table :schools do foreign_key :id, :places String :name String :school_type Integer :gs_rating Integer :parent_rating String :grade_range Integer :enrollment String :website end end end
class Tag < ActiveRecord::Base # Remember to create a migration! has_many :taggings has_many :questions, through: :taggings validates_uniqueness_of :description validates :description, presence: true end
require 'rails_helper' RSpec.describe 'admin price update', settings: false do before :example do sign_in_to_admin_area end it 'updates zone' do price = create(:price) create(:zone, id: 2) patch admin_price_path(price), price: attributes_for(:price, zone_id: '2') price.reload expect(pr...
class CreateBrochures < ActiveRecord::Migration def change create_table :brochures do |t| t.belongs_to :type t.string :name t.boolean :rep_enabled t.boolean :dist_enabled t.string :kind t.integer :inventory t.integer :total t.datetime :deleted_at, :index => true ...
class Book include Mongoid::Document field :name, type: String field :store_id, type: String end
# frozen_string_literal: true Current::Application.configure do # Settings specified here will take precedence over those in config/application.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you d...
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :my_projects, class_name: "Project", foreig...
require 'spec_helper' require 'greenpeace/configuration/requirement' describe Greenpeace::Configuration::Requirement do subject do Greenpeace::Configuration::Requirement.new( :key, { type: :int, doc: 'DOC', defaults: { development: 5 } }, 'development') end describe '#identifier' do it...
class UserItemsController < ApplicationController before_action :set_user_item, only: [:destroy] # POST /user_items def create @user_item = UserItem.new(user_item_params) @user = User.find(params[:user_id]) @item = Item.find(params[:item_id]) if @user.bank <= @item.price render json: {...
# Copyright (c) 2016 Cameron Harper # # 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, including without limitation the rights to # use, copy, modify, merge, publish, dis...
module ApplicationHelper def statuses Coupon.statuses.keys.map { |w| [w.humanize, w] } end end
# The program "product_of_int.rb" modified to include validating user inputs: def sum_of_int(int) (1..int).sum end def product_of_int(int) (1..int).to_a.inject(:*) end def valid_int?(int) int.integer? && int > 0 end def valid_answer?(sum_or_product) sum_or_product == "s" || sum_or_product == "p" end puts "...
module Anetwork class Messages # setter and getter varibules attr_accessor :code , :text , :error , :error_code , :headers , :lang , :config ## # initialize method # # @author Alireza Josheghani <a.josheghani@anetwork.ir> # @since 1 Dec 2016 # @return [Object] # @param [String] ...
class LoginController < ApplicationController def create @skater = Skater.find_by(name: params[:name]) if @skater && @skater.authenticate(params[:password]) payload = { skater_id: @skater.id ,name:@skater.name, skater:@skater} token = encode_token(payload) ...
Rails.application.routes.draw do get 'reviews/new' get 'reviews/create' get 'restaurants/index' get 'restaurants/show' get 'restaurants/new' get 'restaurants/create' root to: 'restaurants#index' resources :restaurants, only: [:index, :new, :show, :create] do resources :reviews, only: [:new, :create]...
# frozen_string_literal: true # Custom method to check if string is an integer. class String def integer? self =~ /\A[-+]?\d+\z/ end end
require "./lib/snack" class VendingMachine attr_reader :inventory def initialize @inventory = [] end def add_snack(snack) @inventory << snack end def snacks_by_name @inventory.map do |snack| snack.name end end def how_many_snacks @inventory.group_by do |snack| snack.qu...
require File.join(File.dirname(__FILE__), 'spec_helper') require 'barby/barcode/bookland' include Barby describe Bookland do before :each do @isbn = '968-26-1240-3' @code = Bookland.new(@isbn) end it "should not touch the ISBN" do @code.isbn.should == @isbn end it "should have an isbn_only" do...
PlaygroundApp::Application.routes.draw do devise_for :users devise_scope :user do get 'sign_in', to: 'devise/sessions#new' delete 'sign_out', to: 'devise/sessions#destroy' get 'sign_up', to: 'devise/registrations#new' end resources :users, except: [:create] do member do match 'delete' ...
# # Cookbook:: apache_tomcat # Recipe:: default # # Copyright:: 2017, The Authors, All Rights Reserved. # Install java package 'java-1.7.0-openjdk-devel' # Add a group Tomcat group 'tomcat' # Install user user 'tomcat' do manage_home false shell '/bin/nologin' group 'tomcat' home '/opt/tomcat' end # Downlo...
class SeasonPresenter < AllTimePresenter def initialize(season:) @season = season end private def player_source season.players end attr_reader :season end
describe Rfm::Resultset do # These mocks were breaking the #initialize spec, but only when I added the Layout#modelize spec !?!? # let(:server) {mock(Rfm::Server)} # let(:layout) {mock(Rfm::Layout)} let(:server) {Rfm::Server.allocate} let(:layout) {Rfm::Layout.allocate} let(:data) {File.read("spec/dat...
module Noodall class CheckBox < Noodall::Field key :default, Boolean end end
class FlightsController < ApplicationController def index if params.has_key?(:departure) if params[:departure_airport] != params[:arrival_airport] @flights = Flight.search(params[:departure], Airport.select(:id).where(code: params[:departure_airport]), Airport.select(:id).where(code: params[:arrival_a...
class ContenuesController < ApplicationController def index @contenues = Contenue.all end def show @contenue = Contenue.find(params[:id]) end def new @contenue = Contenue.new end def create @contenue = Contenue.new(product_params) if @contenue.save redirect_to contenues...
module RSpec module Mocks RSpec.describe Matchers::Receive do include_context "with syntax", :expect describe "expectations/allowances on any instance recorders" do include_context "with syntax", [:expect, :should] it "warns about allow(Klass.any_instance).to receive..." do ...
module FlattenArray module_function def flatten(arr) arr.reduce([]) do |acc, el| el.respond_to?(:flatten) ? acc += flatten(el) : acc << el end.reject(&:nil?) end end module BookKeeping VERSION = 1 end
pain_descriptors = [ 'burning', 'aching', 'stinging', 'throbbing', 'itching', 'numbing', 'pins and needles', 'pulling', 'sharp', 'jabbing', 'shooting', 'electric', 'mechanical', 'thermal', 'abrupt', 'increasing', 'decreasing', 'with exercise', 'with movement' ] family_history = Top...
require 'spec_helper' describe Spree::LineItem do let(:order) { create :order_with_line_items, line_items_count: 1 } let(:line_item) { order.line_items.first } context '#save' do it 'should update inventory, totals, and tax' do # Regression check for #1481 line_item.order.should_receive(:create_...
module Post::Operation class Import < Trailblazer::Operation step :import_csv! def import_csv!(options, params:, **) CSV.foreach(params[:file].path, headers: true) do |row| post = Post.new post.title = row[0] post.description = row[1] post.status = row[2] pos...
=begin Write a method last_modified(file) that takes a file name and displays something like this: file was last modified 125.873605469919 days ago. =end require 'Time' SECONDS_IN_DAY=24*60*60 def last_modified(file) mod_time = (Time.now - File.mtime(file))/SECONDS_IN_DAY puts "#{file} was las...
# 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...
require 'net/http' require 'json' # Translates a string between two languages # using Google Translate's AJAX service. class Translate def initialize(from, to) # Languages to translate @from = URI::encode(from) @to = URI::encode(to) # Google Translate @gServiceUrl = "https://ajax.googleapis.com/ajax/servi...
class CheckForWin def checkForWin?(board,player) return checkForVerticalWins?(board,player) || checkForDiagonalWins?(board,player) || checkForHorizontalWins?(board,player) end def checkForVerticalWins?(board,player) return checkForVerticalWin1?(board,player) || checkForVerticalWin2?(board,player) || che...
# frozen_string_literal: true require "rails_helper" module Renalware module Diaverum module Incoming describe "rake diaverum:ingest", type: :task do include DiaverumHelpers let(:patient) { create(:hd_patient, local_patient_id: "KCH123", nhs_number: "0123456789") } around do |exam...
class AddColumnsToUsers < ActiveRecord::Migration def change add_column :users, :name, :string add_column :users, :lastname, :string add_reference :users, :organization, index: true, foreign_key: true add_reference :users, :user_type, index: true, foreign_key: true end end
require 'spec_helper' describe 'sections/_assignment_set' do before do stub_template 'sections/_assignment_table' => "foo" end it "renders a table containing a set of assignments" do asst = mock('assignment') do stub(:content).and_return "Assignment content" end sa = mock('section_assignment') do ...
class Permission < ActiveRecord::Base belongs_to :project belongs_to :person validates :project, presence: true validates :person, presence: true validates_uniqueness_of :project_id, :scope => :person_id validates_inclusion_of :write, in: [true, false] end
require 'spec_helper' RSpec.describe SemrushRuby do it 'has a version number' do expect(SemrushRuby::VERSION).not_to be nil end describe 'configuration' do context 'defaults' do let(:client) { SemrushRuby::Client.new } it 'uses the default api url' do expect(client.api_url).to eq('ht...
class ActSection < ActiveRecord::Base belongs_to :act belongs_to :act_part def label "Section #{section_number}: #{title}" end def legislation_uri_for_subsection subsection_number "#{legislation_url}/#{subsection_number}" end end
require 'rails_helper' RSpec.describe User, type: :model do let(:user){FactoryBot.create(:user)} let(:friends){FactoryBot.create_list(:user,4)} describe "friendships" do it "can get a list of Users that are friends" do user.friendships.create(friend: friends.first, status: :accepted) friends[1....
class VolunteerOpportunity include MongoMapper::Document attr_accessor :search_relevance, :rank, :current_page, :total_pages USELESS_TERMS = ["a", "the", "of", "it", "for", "is", "i", "to", "in", "be", "and", "on"] PUNCTUATION = Regexp.new("[>@!*~`;:<?,./;'\"\\)(*&^{}#]") key :title, String key :descriptio...
# == Schema Information # # Table name: courses # # id :integer not null, primary key # name :string # content :text # video_id :string # track_id :integer # created_at :datetime not null # updated_at :datetime not null # position :integer # # Indexes # # index_c...
class FixDataType < ActiveRecord::Migration[5.1] def change rename_column :build_sessions, :user_ids, :user_id end end
class AddCastleTrackingToGames < ActiveRecord::Migration[5.0] def change add_column :games, :white_can_castle_king_side, :boolean, default: true add_column :games, :black_can_castle_king_side, :boolean, default: true add_column :games, :white_can_castle_queen_side, :boolean, default: true add_column :game...
require 'spec_helper' Run.all(:read_only) do use_pacer_graphml_data(:read_only) describe '#as_var' do it 'should set the variable to the correct node' do vars = Set[] route = graph.v.as_var(:a_vertex) route.in_e(:wrote) { |edge| vars << route.vars[:a_vertex] }.count vars.should == Set[...
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :setup_user # make current user available in all view templates helper_method :current_user #memo...
class DealerBuilder attr_reader :computer def initialize @dealer = Dealer.new @dealer.contact_info = ContactInfo.new end def columns_values columns = Dealer.column_names + ContactInfo.column_names columns -= %w[created_at updated_at] columns end def contact_info @dealer.contanct_i...
class OpenMat < ActiveRecord::Base belongs_to :user validates :street_address, :city, :state, :starts_at, :asset, presence: true has_attached_file :asset, styles: { large: '400x400>', medium: '300x300>', small: '140x140', thumb: '64x64!' } validates_attachment_content_type :asset, content_ty...
require 'rails_helper' RSpec.describe "stores/edit", type: :view do before(:each) do @store = assign(:store, Store.create!( :name => "MyString", :email => "MyString", :open => false, :image => "MyString", :photos => "", :tags => "", :description => "MyString", :lat...
# # Cookbook:: thing.resource_test # Resource:: thing # resource_name :thing provides :thing property :thing_name, [String], required: true property :registry, [String], required: true action :create do if registry_key_exists?(new_resource.registry) Chef::Log.info('thing:create, the hive exists') else Ch...
require 'use_cases/bikes/find_bike' module Api module V1 class BikesController < ApplicationController def show find_bike_use_case = UseCases::Bikes::FindBike.new find_bike_use_case.on(:find_bike_success) { |bike| render json: bike, status: :ok } find_bike_use_case.on(:find_bike_f...
module Countable def items_by_merch_count merch_items_hash.values.map do |item_array| item_array.length end end def invoices_by_merch_count count = merch_invoices_hash.values.map do |invoice_array| invoice_array.length end count end def top_days_by_invoice_count days_high...
json.array!(@github_issues) do |github_issue| json.extract! github_issue, :id, :github_id, :path json.url github_issue_url(github_issue, format: :json) end
namespace :sinatrabar do desc "Sets up configuration and database" task :install do # Install task (sets up config/pianobar) and then runs db:migrate end desc "Starts the application" task :start do # Starts application end end namespace :db do desc "Set up initial database" task :setup do ...
# To run this code, be sure your current working directory # is the same as where this file is located. # ruby 6.rb # EXERCISE # Write a method called shuffled_deck that returns an array that # represents a shuffled deck of cards. # Write a method called deal_hand that allows an argument specifying # the number of car...
class ApplicationController < ActionController::Base include DeviseTokenAuth::Concerns::SetUserByToken before_action :configure_permitted_parameters, if: :devise_controller? before_action :set_locale protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :...
class ChangeColumnName < ActiveRecord::Migration[5.2] def change rename_column :bookings, :dote, :date end end
class CreateEngineerRegistrationTypes < ActiveRecord::Migration[5.2] def change create_table :engineer_registration_types, comment: EngineerRegistrationType.model_name.human do |t| t.string :name, comment:'流入種別' t.string :description, comment: '流入種別詳細' t.integer :sort, comment:'並び順' t.tim...
class RatingsController < ApplicationController def index @ratings = Rating.all end def show @rating = Rating.find(params[:id]) end def new @rating = Rating.new end def edit @rating = Rating.find(params[:id]) end def create sessionUser = UsersController.getSessionUser(session) ...
require 'fastlane_core/ui/ui' module Fastlane UI = FastlaneCore::UI unless Fastlane.const_defined?("UI") module Helper class Ipa ATTRS = [:size, :format_size] attr_accessor(*ATTRS) def initialize(ipa_path) return nil unless ipa_path return nil if ipa_path.empty? return...
class Api < Grape::API format :json prefix :api get :ping do { :pong => 'ok' } end end
class AddGaAccountNameAndGaWebsiteToAdvertisers < ActiveRecord::Migration def change remove_column :advertisers, :ga_script end end