text
stringlengths
10
2.61M
# Provides helper methods for writing webpack script/stylesheet tags module WebpackHelper WEBPACK_DEV_SERVER = "http://localhost:9123" WEBPACK_PROD = "https://tidywiki.com" def digested_bundle_name(bundle_name) manifest = Rails.root.join("public", "assets", "manifest.json") raise "Have you run webpack? ...
class GenresController < Sinatra::Base # sets root as the parent-directory of the current file set :root, File.join(File.dirname(__FILE__), '..') # sets the view directory correctly set :views, Proc.new { File.join(root, "views") } get '/genres' do @genres = Genre.all erb :genres end get '/genre...
require 'rails_helper' RSpec.describe Room, type: :model do context 'with two rooms' do before(:all) do @date_from = "01.06.2018" @date_to = "15.06.2018" @name = "standart" @room1 = Room.create!(id:1, number_of_people: 3, name: @name ) @room2 = Room.create!(id:2, number_of_people: 3...
class AddFiledsToCoupons < ActiveRecord::Migration def change add_column :coupons, :status, :string add_column :coupons, :benefit_type_id, :integer add_column :coupons, :user_id, :integer end end
require "i18n" module OrdinalizeFull I18n.load_path += Dir[File.join(__dir__, "ordinalize_full/locales/*.yml")] def ordinalize(in_full: false, noun_gender: :masculine , noun_plurality: :singular) in_full ? ordinalize_in_full(noun_gender: noun_gender , noun_plurality: noun_plurality) : ordinalize_in_short(no...
module Bitstamp module Net def self.to_uri(path) return "https://www.bitstamp.net/api#{path}/" end def self.curl(verb, path, options={}) verb = verb.upcase.to_sym c = Curl::Easy.new(self.to_uri(path)) if Bitstamp.configured? options[:key] = Bitstamp.key options[:...
class SafeValidator < ActiveModel::EachValidator def virus_found?(file) io = begin StringIO.new(File.read(file.file.file)) rescue StringIO.new(file.file.read) end client = ClamAV::Client.new response = client.execute(ClamAV::Commands::InstreamCommand.new(io)) response.class.name == 'ClamAV::VirusRespo...
class HomeController < ApplicationController before_filter :go_to_app? def index @user = User.new @user.company = nil end end
# frozen_string_literal: true class CinemaHallSerializer include JSONAPI::Serializer attributes :name, :row_number, :row_total_seats has_many :screenings end
Popcorn::Application.routes.draw do devise_for :users resources :movies root "pages#home" get "about" => "pages#about" get "search" => "pages#search" get "recommendations" => "pages#recommendations" get "test" => "pages#test" get "action" => "pages#action" get "adventure" => "pages#adventure" get ...
module VisionboardHelper def show_intention? @show_intention == true end alias :show_intentions? :show_intention? def show_gratitude? ! show_intention? end def url_for_visionboard_action_item(ai) case ai.component_type when Intention::COMPONENT_TYPE new_intention_url when Intenti...
module Output require 'colorize' def convert_to_color(number) case when number == 0 return :blue when number == 1 return :yellow when number == 2 return :red when number == 3 return :green when number == 4 ...
require 'rails_helper' RSpec.describe 'Hangar API', type: :request do before do @user = User.create(name: 'User1', password: 'Password1') end describe 'GET /hangar.json' do include_examples 'requires authentication', '/hangar.json' context 'with no owned ships' do before do get '/hang...
require 'spec_helper' describe CreditCardsController do describe 'new edit and update' do before(:each) do @customer = create(:customer) user = create(:user, customer: @customer) @credit_card = create(:credit_card, customer_id: @customer.id) controller.stub(:current_user).and_return(user)...
require "rails_helper" RSpec.feature "UserCanLogoutAndSeeHomePage", type: :feature do context "when logged in" do let!(:user) { User.create(username: "Mitchell", password: "password") } it "can see a login when not logged in" do visit root_path expect(page).to have_content("Login") end i...
class AddTelephoneAndEmailToAdminPeople < ActiveRecord::Migration def change add_column :admin_people, :telephone, :string add_column :admin_people, :email, :string end end
class CreateTasks < ActiveRecord::Migration[5.0] def change create_table :tasks do |t| t.string :name, null:false t.string :description t.string :status, default: 0, null: false t.belongs_to :card, foreign_key: { on_delete: :cascade } t.timestamps end end end
class Book < ActiveRecord::Base has_many :feeds, dependent: :destroy has_and_belongs_to_many :users, join_table: :schedules end
module Freelancer module Payment #Retrieve the current user's balance and the details of the last transaction. # #http://developer.freelancer.com/GetAccountBalanceStatus def getAccountBalanceStatus request "/Payment/getAccountBalanceStatus.json" end #Retrieve the list of transactions an...
require 'spec_helper' feature 'user can record manufacturer', %q{ As a car salesperson I want to record a car listing's manufacturer So that I can keep track of its manufacturer } do # I must specify a manufacturer name and country. # If I do not specify the required information, # I am prese...
class PeopleController < ApplicationController def index @people = Person.all end def show @person = Person.find(params[:id]) end def new @person = Person.new @person.addresses.build end def create @person = Person.new(permit_params) if @person.save redirect_to people_...
# encoding: utf-8 require_relative "support" class SeaBattle # It's random positions for new ship class RandomShip include ::SeaBattle::Support def initialize(board, length = 1) @board = board.board @length = length @horizontal = board.horizontal @vertical = board.vertical end...
# frozen_string_literal: true require 'spec_helper' module Uploadcare module Entity RSpec.describe Group do subject { Group } it 'responds to expected methods' do %i[create info store delete].each do |method| expect(subject).to respond_to(method) end end contex...
class MessagesController < ApplicationController def index @messages = current_user.received_messages end def new @users = current_user.friends @message = Message.new end def create @message = Message.new(message_params) @message.sender_id = current_user.id if @message.save flash...
class Udemy include Capybara::DSL attr_reader :title, :subtitle def initialize @title = find(:xpath, "//h1[@class='udlite-heading-xl clp-lead__title clp-lead__title--small']") @subtitle = find("[class='udlite-text-md clp-lead__headline']") end def getTextTitle @title.text...
class Quizmaster def start system ('clear') puts " ____ __ ___________ __ ___ __ / __ \/ / / / _/__ / / |/ /___ ______/ /____ __________ / / / / / / // / / / / /|_/ / __ `/ ___/ __/ _ \/ ___/ ___/ / /_/ / /_/ // / / /__ / / / / /_/ (__ ) /_/ __/ / (__ ...
class MailSorting def initialize @posts = [] end def add_post(new_post) @posts << new_post end #the number of parcels sent to some city def num_parcels_sent_to_city(city) count = 0 @posts.each {|x| count +=1 if x.city == city} return count end #how many parcels with value higher than...
require 'test_helper' class StaticPagesControllerTest < ActionDispatch::IntegrationTest test "should get home" do get root_path assert_response :success assert_select "title", "War-Rails" end test "should get regolamento" do get regolamento_url assert_response :success assert_select "...
require './player' require './db/song' require './playlist' require './options/list_option' require './options/play_option' require './options/stop_option' require './options/search_option' require './options/exit_option' require './options/playlist_view_option' require './watcher' # Requirements # # Your Jukebox sh...
class ListsController < ApplicationController def new @list = List.new @friends = current_user.friends end def create @list = List.new(list_params) @list.user = current_user if @list.save flash[:success] = "List was successfully created" listUser = ListUser.new(list: @list, user...
class CreateCookBooks < ActiveRecord::Migration[5.1] def change create_table :cook_books do |t| t.string :name, limit: 30 t.references :icon t.references :recipe, foreign_key: true t.timestamp :created_at t.timestamp :updated_at t.timestamps end end end
#!/usr/bin/env ruby # wthr.rb # a short script to tell me the weather # by adam defelice (ad.defelice@gmail.com) # the info here is taken from weather.gov # $ wthr hyannis # - prints the weather in hyannis # default location is lowell require 'open-uri' require 'rexml/document' require 'optparse' class WthrRep...
class SettingsController < ApplicationController before_action :authenticate_user! def index @client = Client.find(current_user.client_id) @center = Center.where(client_id: @client.id) @users = User.where(invited_by_id: current_user.id) end end
require 'test_helper' class TraingSessionsControllerTest < ActionController::TestCase setup do @traing_session = traing_sessions(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:traing_sessions) end test "should get new" do get :new as...
# frozen_string_literal: true class Report < ApplicationRecord mount_uploader :picture, PictureUploader belongs_to :user has_many :comments, as: :commentable, dependent: :destroy end
require 'database_connection' class Diaries attr_reader :id, :name, :input def initialize(id:, name:, input:) @id = id @name = name @input = input end def self.all result = DatabaseConnection.query('SELECT * FROM diary_entries') result.map { |entry| Diaries.new(id: entry['id'],...
module Vocab No_Player_Connection = 'Non riesco ad ottenere le informazioni online. Controlla la connessione.' Player_Connected = 'Tutto OK, sei online!' Player_Banned = 'Il tuo profilo è stato disattivato.' Player_Disabled = 'Hai disabilitato l\'online.' Maintenance = "I server di gioco sono in manutenzione....
class Api::CountriesController < ApplicationController before_action :set_country, only: %i[show] def index @countries = Country.all.order(order: :asc) render json: @countries, only: %i[id name] end def show render json: @country end private def set_country @country = Country.find(para...
module JsonSerialization extend ActiveSupport::Concern def serialize(obj, options = {}) obj.as_json(options) end end
class Users::RegistrationsController < Devise::RegistrationsController def create build_resource(sign_up_params) if sign_up_params[:type] == "Researcher" @email_domain = sign_up_params[:email].split("@")[1] if @university = University.find_by_domain_name(@email_domain) resource.universi...
if (!in_list && (is_admin? || is_current_user?(user))) json.extract! user, :id, :name, :email, :fullname, :is_admin, :created_at, :updated_at json.url user_url(user, format: :json) else json.extract! user, :id, :name end
require 'yaml-web-driver/runner/browser_spec_runner' require 'yaml-web-driver/spec/action_spec' require 'yaml-web-driver/spec/page_specs' module YamlWebDriver module Spec class BrowserSpec attr_reader :main, :pages def initialize(browser_spec_docs) action_and_page_specs = browser_spec_docs....
class Voyage < ApplicationRecord belongs_to :vessel has_many :port_calls, dependent: :destroy end
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 to: 'home#index' resources :recipes, only: [:show, :new, :create, :edit, :update, :destroy, :index] do collection do get 'search' get 'fav...
Rails.application.routes.draw do get "/", to: redirect("/flights") namespace :api do namespace :v1 do resources :flights end end resources :flights end
class UserGroup < ApplicationRecord validates :group_name, presence: true end
require 'spec_helper' RSpec.describe MenusController, type: :controller do context 'when user not logged in' do describe 'GET #index' do it 'redirects to login page' do get :index expect(response).to redirect_to new_user_session_path end end end context 'when user logged in' ...
class Team attr_reader :team_id, :franchiseId, :teamName, :abbreviation, :stadium, :link def initialize(line) @team_id = line.split(",")[0] @franchiseId = line.split(",")[1] @teamName = line.split(",")[2] @abbreviation = line.spl...
class CreateActRelations < ActiveRecord::Migration def change create_table :act_relations do |t| t.belongs_to :user, index: true, foreign_key: true t.integer :parent_id, comment: 'ID parent', index: true t.integer :child_id, comment: 'ID child', index: true t.datetime :start_date t.d...
# Custom hashMap challenge from CodeSignal # You are given an array of query types which should: # insert - key X is set to val Y # addToValue - increase all values by X # addToKey - increase all keys by X # get - return the value at key X # And an array of queries (values) which corresponds to the queryType array #...
class CreateImsExports < ActiveRecord::Migration[5.0] def change create_table :ims_exports do |t| t.string :token t.string :tool_consumer_instance_guid t.string :context_id t.string :custom_canvas_course_id t.jsonb :payload t.timestamps end add_index :ims_exports, :toke...
class Question < ActiveRecord::Base has_many :answers has_many :options, dependent: :destroy accepts_nested_attributes_for :options, reject_if: proc { |attributes| attributes['name'].blank? } scope :single_multiple_questions, {:conditions => ['type in ( ? )', ['SingleAnswerQuestion', 'MultipleAnswerQuestion']]...
class MoviesController < ApplicationController #include Movies::IndexTools include MoviesHelper::MoviesController #session :on def show id = params[:id] # retrieve movie ID from URI route @movie = Movie.find(id) # look up movie by unique ID # will render app/views/movies/show.<extension> by default end d...
# Create method `parrot` that outputs a given phrase and # returns the phrase def parrot(calling= "Squawk!") puts calling calling end
class AddRainForecastToCasino < ActiveRecord::Migration def change add_column :casinos, :rain_forecast, :boolean end end
class Store::Indices::InformationController < ApplicationController # GET /store/indices/information # GET /store/indices/information.json def index @store_indices_information = Store::Indices::Information.all respond_to do |format| format.html # index.html.erb format.json { render json: @sto...
class ResourcesController < ApplicationController before_action(:verify_login) before_action(:set_resource) before_action(:verify_edit_or_admin) # DELETE /resources/:id def destroy @resource.destroy() head :no_content end def set_resource() @resource = Resource.find_by('id': params[:id]) ...
require 'test_helper' class ThreeScale::SearchTest < ActiveSupport::TestCase class Model < ActiveRecord::Base self.table_name = 'accounts' include ThreeScale::Search::Scopes scope :by_fancy_scope, ->(value) { where(id: value == '1') } scope :by_another_scope, -> { where(created_at: :column) } en...
# Chapter 4 Trees and Graphs class Tree attr_accessor :root def initialize(root = Node.new) @root = root end end class Graph attr_accessor :nodes def initialize(nodes) @nodes = nodes end end class Node attr_accessor :value, :children def initialize(value, children = []) @value = value ...
class DriverCity < ActiveRecord::Base belongs_to :driver belongs_to :city end
class Product < ActiveRecord::Base # Validations validates :name, presence: { message: 'Tên sản phẩm không được bỏ trống' } validates :price, presence: { message: 'Giá sản phẩm không được bỏ trống' } validates :category_id, presence: { mesage: 'Loại không được bỏ trống' } validates :color_id, presence: { mes...
class Photograph attr_reader :id, :name, :artist_id, :year def initialize(hash) @id = hash[:id] @name = hash[:name] @artist_id = hash[:artist_id] @year = hash[:year] end end
Upmin.configure do |config| config.models = [:document, :product_category, :product, :order, :slide, :setting] config.colors = [:light_blue, :blue_green, :dark_red, :yellow, :orange, :puprle, :gray, :brown] config.items_per_page = 10 end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Ch...
require 'rails_helper' RSpec.describe 'Cycle#update', :ledgers, type: :system do before { log_in admin_attributes } context 'when Term' do it 'edits term' do cycle_create id: 1, name: 'Mar', charged_in: 'arrears', cycle_type: 'term', ...
require 'test_helper' class TagTest < ActiveSupport::TestCase test "tag should be valid" do tag = Tag.new(name: "test") assert tag.valid? end test "name should be unique" do tag = Tag.new(name: "tag_1") assert_not tag.valid? end end
# frozen_string_literal: true require 'test_helper' class ArticleTest < ActiveSupport::TestCase test 'valid article' do article = Article.new(title: 'Title', text: 'Body text') assert article.valid? end end
class Post < ActiveRecord::Base validates_presence_of :title, :body has_many :comments, :class_name => 'PostComment', :dependent => :destroy end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2019-2020 MongoDB Inc. # # 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 # # U...
ISTESTING = true require "./src/wheres_joe_hatcher.rb" require "./src/cRoom.rb" require "test/unit" class Test_game_class < Test::Unit::TestCase def test_command entrance = Room.new("Entrance", "You can go north.") northroom = Room.new("The north", "So cold here") entrance.update_exits({...
# in dev mode you can use "http://insecure.rails-assets.org" see https://rails-assets.org/#/ # NOTE: use "http://", not "https://" for proxy support source "http://rubygems.org" # Hello! This is where you manage which Jekyll version is used to run. # When you want to use a different version, change it below, save the ...
# encoding: utf-8 control "V-52461" do title "The DBMS must prevent the presentation of information system management-related functionality at an interface utilized by general (i.e., non-privileged) users." desc "Information system management functionality includes functions necessary to administer databases, networ...
module FormHelper #--------------------------------------------------------------- def icon(name, html_options={}) html_options[:class] = ['fa', "fa-#{name}", html_options[:class]].compact content_tag(:i, nil, html_options) end #--------------------------------------------------------------- def order_ur...
# Given a set of numbers, return the additive inverse of each. # Each positive becomes negatives, and the negatives become positives. # Example: # invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5] # invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5] # invert([]) == [] def invert(list) list.map(&:-@) end invert([1, -2, 3, -4, 5])
class Product < ApplicationRecord has_one_attached :image validates :title, :description, :price, presence: true end
class FixColumnSubcontractEquipment < ActiveRecord::Migration def change rename_column :subcontract_equipments, :type, :igv end end
class TagTicket < ActiveRecord::Base belongs_to :tag belongs_to :ticket end
require 'kintone/command' require 'kintone/api' class Kintone::Command::Form PATH = "form" def initialize(api) @api = api @url = @api.get_url(PATH) end def get(app) @api.get(@url, {:app => app}) end end
class Relation def initialize initialize_relations end def get_relations @relations end private def initialize_relations @relations = ActorRelation.all | ActRelation.all | ActActorRelation.all end end
require 'digest' require 'fileutils' class Indocker::DeployContext attr_reader :configuration, :logger def initialize(logger:, configuration:) @logger = logger @configuration = configuration @restart_policy = Indocker::Containers::RestartPolicy.new(configuration, logger) end def deploy(container,...
class CreateQualifyings < ActiveRecord::Migration[6.0] def change create_table :qualifyings do |t| t.integer :qualifyId, index: true t.integer :raceId, index: true t.integer :driverId, index: true t.integer :constructorId, index: true t.integer :number t.integer :position ...
class AccountsController < AuthenticatedUserController onboard :account_type, with: [:type, :submit_type] def edit run Registration::Edit render cell(Registration::Cell::Edit, @model, form: @form) end def update run Registration::Update do flash[:success] = 'Saved settings!' # If they ...
class AddForeignKeyConstraints < ActiveRecord::Migration[6.0] def change add_foreign_key :activities, :organisations, on_delete: :restrict # Already exists # add_foreign_key :activities, :activities, column: "activity_id", on_delete: :restrict # Already exists # add_foreign_key :activities, :org...
class AddDefaultValueToJoinedDate < ActiveRecord::Migration[6.0] def change change_column_default :users, :joined, Date.today end end
class UserAvailableLanguage < ApplicationRecord belongs_to :user belongs_to :available_language end
FactoryGirl.define do factory :track do name 'Test Track' enabled true references 'references' instructions 'instruction' description 'descriptions' owner_id 11111 reviewer_id 99999 end factory :track_without_owner, class: 'Track' do name 'Test Track2' references 'references' ...
require "rails_helper" describe Notifier do describe 'new project' do let!(:admin) { FactoryGirl.create(:admin) } let!(:user) { FactoryGirl.create(:user, mentor_id: admin.id) } let!(:project) do Project.new(id: 1, name: 'Rails 4', user_id: user.id) end let!(:email) { Notifier.new_project(pr...
class BaselineAssessmentsController < ApplicationController include BaselineAssessmentsHelper include ThreeSixtyAssessmentsHelper skip_before_filter :authenticate skip_before_filter :verify_subscription def new @window_title = 'Baseline Assessment' @menu_section = 'toolkit' # TODO ? @user = cur...
require 'test_helper' describe MutantSchoolAPIModel::Term do before do @fall2016 = TermFactory.build(:fall2016) end after do @fall2016.destroy if @fall2016.persisted? end describe '#save' do it 'creates a new term' do actual = Term.new(@fall2016.save) _(actual && actual.to_h).must_e...
class Card def initialize(attributes) @front = attributes[:front] @back = attributes[:back] end def play print "#{front} > " guess = gets.chomp if correct?(guess) puts "Correct!" else puts "Sorry, the correct answer is #{back}." end end private attr_reader :front,...
require 'origen' module Origen class <<self # Override the Origen.reset_interface method to clear out the TestIds # configuration, so that it doesn't carry over from one flow to the next alias_method :_orig_reset_interface, :reset_interface def reset_interface(options = {}) TestIds.send(:clear_c...
module ActiveRecord module Snapshot class Import def self.call(*args) new(*args).call end def initialize(version: nil, tables: []) @version = version if named_version? name = version else @version, name = SelectSnapshot.call(version) e...
# encoding: UTF-8 class Education < ActiveRecord::Base extend PersianNumbers persian_dates :started, :finished persian_numbers :average attr_accessible :average, :finished, :pursued, :started, :study_field, :teacher_id, :title, :univercity validates :title, :study_field, :univercity, :presence => {:message ...
class Aula < ApplicationRecord belongs_to :disciplina validates :objetivo, :realizado, presence: true validates :objetivo, :realizado, uniqueness: true end
class Status < ApplicationRecord belongs_to :user enum level: { terrible: 0, bad: 1, beginner: 2, low: 3, midterm: 4, high: 5 } validate :update_level, on: :update validates :points, :level, presence: true private def update_level case points when points < -200 se...
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2015-2020 MongoDB Inc. # # 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 # # U...
require 'jwk/key' module JWK class OctKey < Key def initialize(key) @key = key validate end def public? true end def private? true end def validate raise JWK::InvalidKey, 'Invalid RSA key.' unless @key['k'] end def to_pem raise NotImplemente...
#!/usr/bin/env ruby module Observer def initialize @observers = [] end def adiciona_observer(observer) @observers << observer end def notifica @observers.each do |observer| observer.alerta end end end class Restaurante include Observer def qualifica(nota) puts "Restauran...
class Post < ApplicationRecord validates :content, presence: true, length: {maximum: 140, minimum: 1} end
class LevelNumber < ActiveRecord::Base has_many :scripts has_many :phase_typizations has_many :phase_types, through: :phase_typizations validates :name, uniqueness: true end