text
stringlengths
10
2.61M
require 'spec_helper' feature 'user signs out', %Q{ As an authenticated user I want to sign out because the I want to } do scenario 'a registered user can sign out' do user = FactoryGirl.create(:user) sign_in_as(user) visit root_path click_link 'Log Out' expect(page).to have_content(...
require 'rails_helper' RSpec.describe User, type: :model do # Association test # ensure User model has a 1:m relationship with the Contact model it do should have_many(:contacts).dependent(:destroy) end # ensure User model has a 1:m relationship with the UserToken model it do should have_many(:user...
# frozen_string_literal: true class User < ApplicationRecord class Unauthorized < StandardError; end devise :database_authenticatable, :validatable, :jwt_authenticatable, jwt_revocation_strategy: JwtBlacklist validates :email, presence: true, uniqueness: true, format: { with: URI::Ma...
# frozen_string_literal: true require_relative 'test_helper' DB.create_table :humans do primary_key :id column :encrypted_email, :string column :encrypted_email_salt, String column :encrypted_email_iv, :string column :password, :string column :encrypted_credentials, :string column :encrypted_credentials...
class InboxController < ApplicationController # GET /inbox def missions @events = Event.all end end
class CreatePublishes < ActiveRecord::Migration def change create_table :publishes do |t| t.string :publish_name t.integer :sort_no t.integer :category_id t.integer :sub_category_id t.integer :store_id t.boolean :disp_flg t.timestamps null: false end end end
class Favorite < ApplicationRecord belongs_to :book belongs_to :user validates_uniqueness_of :book_id, scope: :user_id #一つの投稿に対して1いいね end
class Event < ApplicationRecord def as_json(options = {}) super(options.merge({ except: [:created_at,:updated_at] })) end end
class BuyInformation < ApplicationRecord belongs_to :user has_many :purchase_histories validates :user_id, presence: true validates :payment, presence: true validates :subtotal, presence: true validates :final_postal_code, presence: true validates :final_address, presence: true validates :final_name, pr...
require 'mina/bundler' require 'mina/rails' require 'mina/git' require 'mina/rbenv' # for rbenv support. (http://rbenv.org) # require 'mina/rvm' # for rvm support. (http://rvm.io) # Basic settings: # domain - The hostname to SSH to. # deploy_to - Path to deploy into. # repository - Git repo to clo...
class Test attr_reader :test_params, :parser def initialize(params) @test_params = params @parser = Parser.new end def start_httperf_test conn = test_params.fetch(:num_conn) host = test_params.fetch(:host) port = test_params.fetch(:port) url = test_params.fetch(:url) rate = test_p...
module GitConcern extend ActiveSupport::Concern def client @client ||= Octokit::Client.new(:login => Rails.application.secrets.user_name, :password => Rails.application.secrets.password) end def search_repo(query) res = client.search_repositories query, { :page => 1, :per_page => 25 } if res.total_co...
class VisibilityCopyWorker def queue_name :permissions end attr_accessor :pid def initialize(pid) self.pid = pid end def run work = ActiveFedora::Base.find(pid) work.generic_files.each do |file| # visibility must come first, because it can clear an embargo/lease file.visibilit...
class Array def my_uniq unique = [] self.each do |el| unique << el unless unique.include?(el) end unique end def two_sum return [] if self.length < 2 [].tap do |sum_indices| (0...self.length - 1).each do |i| (i+1...self.length).each do |j| sum_indices << [...
class Form < ApplicationRecord audited belongs_to :company has_many :fields, dependent: :destroy, inverse_of: :form accepts_nested_attributes_for :fields validates :company, :name, presence: true end
class Api::MessagesController < ApplicationController def index @messages = Message.where("sender_id = ? OR receiver_id = ?", current_user.id, current_user.id) end def show @message = Message.find(params[:id]) end def create @message = current_user.sent_messages.build(message_params) if @mes...
require 'spec_helper' describe Hydra::SearchBuilder do let(:processor_chain) { [:add_access_controls_to_solr_params] } let(:context) { double('context') } let(:user) { double('user', user_key: 'joe') } let(:current_ability) { double('ability', user_groups: [], current_user: user) } subject { described_class...
module Spree module TickerNewsHelper def insert_ticker_news(params={}) params[:class] ||= 'news-ticker' params[:ticker_id] ||= 'news-container' params[:background_color] ||= '#e02f67' params[:text_color] ||= '#fff' params[:font_size] ||= '14px' container_default_styles = "borde...
class TruckPolicy < ApplicationPolicy class Scope < Scope def resolve scope.all end end def chinese? true end def indian? true end def burgers? true end def thai? true end def mexican? true end def lebanese? true end def italian? true end ...
class Timer attr_accessor :seconds def initialize @seconds = 0 end def time_string currentHour = @seconds / 3600 currentMinute = (@seconds % 3600) / 60 currentSecond = (@seconds % 3600) % 60 return "%02d:%02d:%02d" % [currentHour, currentMinute, currentSecond] end end
# oauth.rb # model of a basic OAuth protocol require 'view.rb' resOwner = mod :ResourceOwner do stores :authGrants, :Credential, :AuthGrant creates :AuthGrant exports(:reqAuth, :args => [item(:cred, :Credential)], # must include a valid credential :when => [hasKey(:authGrants, a...
require File.dirname(__FILE__) + '/spec_helper' describe Invotrak do before(:each) do @invotrak = Invotrak.new @invotrak.establish_connection!('some_key') end describe "clients" do it "should list" do clients = @invotrak.clients clients.class.should == Array client = clients...
class MessagesSerializer def initialize(messages) @messages = messages end def serialized_hash message_array = @messages.map do |msg| { sender: msg.sender, message_id: msg.id, created_at: msg.created_at.strftime('%m-%d-%Y %H:%M:%S %Z'), body: msg.body } en...
class Library attr_reader :name, :books, :authors def initialize(name) @name = name @books = [] @authors = [] end def publish(book) @books << book end def add_author(author) @authors << author end def publication_time_frame_for(aut...
@states = { OR: 'Oregon', FL: 'Florida', CA: 'California', NY: 'New York', MI: 'Michigan', AZ: 'Arizona', RI: 'Rhode Island' } # states[:AZ] = "Arizona" # states[:RI] = "Rhode Island" @cities = { OR:['Salum','Seaside'], FL:['Miami','Beverly'], CA:['Los Angeles','River Side','Berkely','San Fran...
class ContainersController < ApplicationController CATEGORY = 'biobank' SUBCATEG = 'containers' layout "fridges_and_containers" # GET /containers # GET /containers.xml def index @current_action_name = 'index' if allow_action @search_field = params[:search_field] @per_page = (params[:per_page] || 1...
class AddUrlAnToRepresentative < ActiveRecord::Migration[6.0] def change add_column :representatives, :url_an, :text end end
class Profile < ActiveRecord::Base belongs_to :user validates :zipcode, presence: true validate :zip private def zip errors.add(:base, "Zipcode must be even") unless zipcode.even? end end
require 'test_helper' class EmailablesControllerTest < ActionController::TestCase setup do @emailable = emailables(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:emailables) end test "should get new" do get :new assert_response :succ...
def consolidate_cart(cart) new_cart = {} cart.each do |element| element.each do |item, info| info.each do |k, v| if !new_cart.include?(item) new_cart[item] = {} end new_cart[item][k] = v end if new_cart[item][:count] == nil new_cart[item][:count] = 0 end new...
json.array!(@fav_recipes) do |fav_recipe| json.extract! fav_recipe, :recipe_id json.url fav_recipe_url(fav_recipe, format: :json) end
class CreatArtShares < ActiveRecord::Migration[5.2] def change create_table :art_shares do |t| t.integer :artist_id, null: false t.integer :viewer_id, null: false t.timestamps end add_index :art_shares, :artist_id, unique: true add_index :art_shares, :viewer_id, unique: true add...
# frozen_string_literal: true module GraphQL class Schema module FindInheritedValue def self.extended(child_cls) child_cls.singleton_class.include(GraphQL::EmptyObjects) end def self.included(child_cls) child_cls.include(GraphQL::EmptyObjects) end private def...
require_relative '../../controllers/application_controller' require_relative '../../views/users_view' RSpec.describe ApplicationController do describe '#render' do let(:request) { { path: 'users' } } let(:controller) { 'users' } let(:action) { 'index' } let(:template) { :index } let(:locals) { 'l...
class Travelport::Request::AirPriceReq < Travelport::Request::Base attr_accessor :check_o_b_fees attr_accessor :fare_rule_type attr_accessor :ignore_availability attr_accessor :supplier_code attr_accessor :termial_session_info attr_accessor :adults attr_accessor :children attr_accessor :infants attr_...
module Refinery module Press class PressController < ::ApplicationController before_filter :find_all_press before_filter :find_page def index # you can use meta fields from your model instead (e.g. browser_title) # by swapping @page for @endorsement in the line below: p...
require_relative '../../spec_helper.rb' require 'tmpdir' require 'fileutils' describe 'MatchFiles::GitignoreMatcher' do before(:all) do prepare_test_dir end after(:all) do clear_test_dir end # Paths should match pattern { '*.md' => ['readme.md', 'usage.md', 'a/readme.md', ...
class Claim < ActiveRecord::Base # attr_accessible :claim_date, :incident_date, :resolution_date, :claim_number, :record_number, :incident_address, :incident_address_type, :total_claimed, :total_awarded has_many :people has_many :claim_examiners has_many :examiners, :through => :claim_examiners has_many :d...
# frozen_string_literal: true module Hanamimastery module CLI module Transformations class Touch PATTERN = /^modifiedAt\:[[:space:]]"\d{4}-\d{2}-\d{2}"$/ # Updates the modifiedAt with the passed date # def call(content, timestamp: nil) timestamp ||= Time.now ...
# frozen_string_literal: true module CookRoulette class Flash FLASH_TYPES = %i(success info warning error) attr_reader :messages def initialize @messages = {} clear! end def clear! FLASH_TYPES.each do |flash_type| messages[flash_type] = nil end end def ...
class Oystercard attr_reader :balance, :limit, :current_journey, :journeylog DEFAULT_LIMIT = 90 MIN_BALANCE = 1 def initialize(balance = 0, limit = DEFAULT_LIMIT, journeylog_class = JourneyLog) @balance = balance @limit = limit @journeylog = journeylog_class.new end def top_up(money) r...
module Concurrent module Actress # Provides publicly expose-able methods from {Core}. module CoreDelegations def name core.name end def path core.path end def parent core.parent end def terminated? core.terminated? end ...
class DoubleLinkedList attr_accessor :head, :tail def initialize(arr=[]) insert_data(arr) end class Node attr_accessor :key, :data, :next, :prev def initialize(data, key) @data = data @key = key end end def insert_to_head(data, key) node = Node.new(data, key) if @head...
# frozen_string_literal: true class Topic module Notify extend ActiveSupport::Concern included do before_save :notify_admin_editing_node_changed after_commit :async_create_topic_notification, on: :create after_commit :publish_draft_notify, on: :update end module ClassMethods ...
# p028xrandom.rb # Precisamos mostrar o conteúdo do arquivo a partir da palavra EUA f = File.new('hellousa.rb') # SEEK_CUR - Busca a partir do primeiro parâmetro inteiro mais a posição atual # SEEK_END - Busca a partir do primeiro parâmetro inteiro mais a posição final do stream # (você provavelmente quer um valor ne...
# Copyright (c) 2009-2011 VMware, Inc. module VCAP module Services module Rabbit class RabbitError < VCAP::Services::Base::Error::ServiceError # 31300 - 31399 Rabbit-specific Error RABBIT_SAVE_INSTANCE_FAILED = [31300, HTTP_INTERNAL, "Could not save instance: %s"] RABBIT_DE...
class CreateProtocols < ActiveRecord::Migration def change create_table :protocols do |t| t.integer :sparc_id t.text :title t.string :short_title t.string :sponsor_name t.string :udac_project_number t.integer :requester_id t.datetime :start_date t.datetime :end_date...
class CreateTeams < ActiveRecord::Migration def self.up create_table :teams do |t| t.column :name, :string, :null => false t.column :email, :string t.column :coach_names, :string t.column :coach_email, :string end create_table :members do |t| t.column :team_id, :intege...
require 'rails_helper' RSpec.describe EntriesController, :type => :controller do let(:user) { FactoryGirl.create(:user) } let(:entry) do {id: 2, entry: {title: "First entry", body: "Bla bla bla", author: "me XD" }} end describe "GET index" do it "returns http success" do get :index expec...
class Space < ApplicationRecord validates :position, presence: true, uniqueness: true belongs_to :property, optional: true belongs_to :event, optional: true def tile property || event end end
# XXX I am so lazy require 'prime' class Prime def self.nth(number) assert_valid_number(number) lazy.drop(number - 1).first end private def self.assert_valid_number(number) fail ArgumentError, 'invalid number' if number < 1 end end
require './lib/menu' class Order attr_reader :menu, :menu_klass, :order attr_accessor :output def initialize menu, menu_klass=Menu @menu = menu @menu_klass = menu_klass @order = [] @total = 0 end def pick_menu_item menu_item,quantity=1 quantity.times do order << menu.read(menu_it...
class Keyword < ApplicationRecord has_many :keyword_movies has_many :movies, through: :keyword_movies validates :name, uniqueness: true end
# Strategy Design Pattern class Formatter def output_report(title, text) raise "Called #{__method__} from abstract class" end end class HTMLFormatter < Formatter def output_report(title, text) puts('<html>') puts('<head>') puts("<title>#{title}</title>") puts('</head>') puts('<body>') ...
require_relative '../base' module CDI module FakeData module Generators class User < Base attr_reader :profile_type def initialize(options = {}) super(options) @profile_type = options.fetch(:profile_type, :student) end def create run do ...
class Wagon < ActiveRecord::Base validates :train_id, :model, :top_seats, :bottom_seats, presence: true belongs_to :train end
class AthletesController < ApplicationController before_action :authenticate_user! before_action :set_athlete, only: [:edit, :update, :destroy] def index @athletes = Athlete.where(trainer_id: nil) end def show @athlete = Athlete.find(params[:id]) if current_user.trainer? @trainer = Trainer...
module Webrat #:nodoc: def self.adapter_class #:nodoc: TestAdapter end class TestAdapter #:nodoc: attr_accessor :response_body attr_writer :response_code def initialize(*args) end def response @response ||= Object.new end def response_code @response_code || 200 ...
require 'stringio' require 'test/unit' require 'rubygems' require 'redgreen' rescue nil require 'shoulda' require 'mocha' require File.dirname(__FILE__) + '/../lib/simplepay' module Simplepay #:nodoc: module Macros #:nodoc: all def should_have_service_field(*names) delegate_class, service_name, re...
class RemoveTagsFromBookmarks < ActiveRecord::Migration def change remove_column :bookmarks, :tags end end
class AddTransactionIdToTransactionReviews < ActiveRecord::Migration[5.0] def change add_column :transaction_reviews, :transaction_id, :integer end end
require 'rubygems' require '../HeatMap' require 'rubygems' # In this example we use EDWARDS-BELL-OHLSON algorithm to compute the intrinsic # value of a company based on financial information and forecasts # # The code is adapted from https://github.com/sotoseattle/EBOlve # # We want to see how the iintrinsic value va...
require 'pry' class Scrabble attr_reader :word LETTER_VALUE = { ['A','E','I','O','U','L','N','R','S','T'] => 1, ['D','G'] => 2, ['B','C','M','P'] => 3, ['F','H','V','W','Y'] => 4, ['K'] => 5, ['J','X'] => 8, ['Q','Z'] => 10} def initialize(word) @wor...
class TadpolesController < ApplicationController before_action :set_tadpole, only: [:show, :edit, :update, :destroy, :evolve] def index @tadpoles = Tadpole.all end def new @frog = Frog.find_by(:id => params[:frog_id]) # raise params.inspect @tadpole = Tadpole.new end def create @frog ...
# http://pivotallabs.com/users/alex/blog/articles/1232-basic-ruby-webapp-performance-tuning-rails-or-sinatra- class Marking def initialize(app) @app = app end def call(env) response = nil Marker.mark("#{env['REQUEST_METHOD']} #{env['SCRIPT_NAME']}#{env['PATH_INFO']}") do response = @app.call(e...
module RSpec module Core class CommandLine def initialize(options, configuration=RSpec::configuration, world=RSpec::world) if Array === options options = ConfigurationOptions.new(options) options.parse_options end @options = options @configuration = ...
require 'byebug' require 'active_record' require File.expand_path('../../lib/will_publish', __FILE__) # set adapter to use, default is sqlite3 # to use an alternative adapter run => rake spec DB='postgresql' db_name = (ENV['DB'] || 'sqlite3').to_sym database_yml = File.expand_path('../db/database.yml', __FILE__) if ...
class AddShowPostBody2 < ActiveRecord::Migration def change add_column :endpoints, :show_body, :boolean, default: true end end
require './test_helper' require 'packaging' class TestOrderPricing < MiniTest::Test def setup @order1 = Order.new() @order2 = Order.new(base_price: 1299.99, number_of_workers: 3, product_type: 'food') @order3 = Order.new(base_price: 5432.00, number_of_workers: 1, product_type: 'drugs') @order4 = Ord...
class AddOrderCheckToBuyAndSellOrders < ActiveRecord::Migration def change add_column :buy_orders, :check, :boolean, default:false add_column :sell_orders, :check, :boolean, default:false end end
# == Schema Information # # Table name: stores # # id :integer not null, primary key # name :string(255) # kind :string(255) # price :integer # distance :integer # level :integer # logo :string(255) # creater_id :integer # address :string(255) # created_at :da...
class Accounts attr_accessor :name @@all = [] def initialize(name) @name = name @@all << self end def self.all @@all end def self.find_or_create(account_name) found_account = @@all.find do |account| account.name.include?(account_name) end if found_account return ...
class AddLotSizeToTrnProdPlanHeaders < ActiveRecord::Migration[6.0] def change add_column :trn_prod_plan_headers, :lot_size, :integer end end
class FollowsController < ApplicationController before_action :set_user, only: [:follow, :unfollow, :siguiendo] def siguiendo end def follow @u = User.find(2) current_user.follow(@user) redirect_to :back end def unfollow current_user.stop_following(@user) redirect_to :back end p...
module IndicatorValidation extend ActiveSupport::Concern included do validates :quantity_volume_of_production, :workers_who_quit_their_own_volition, :number_of_dismissed, :number_of_newly_adopted, :months_of_received_fixed_assets, :months_of...
module ApplicationHelper def blank(val) val.blank? ? '- empty -' : val end def breadcrumbs(*paths) paths.map do |pair| if pair.is_a? Array and pair.length == 2 link_to pair[0], pair[1], class: 'link subtitle-2 orange' elsif pair.is_a? String content_tag :span, pair, class: 'su...
class MainSubjectDetail < ActiveRecord::Base belongs_to :academic belongs_to :main_subject validates :main_subject_id, presence: true, numericality: { only_integer: true } validates :academic_id, presence: true, numericality: { only_integer: true} validates :marks, presence: true, numericality: { only_integer...
class MembershipsController < ApplicationController def create # For Kurtis to write @group = Group.find(params[:group_id]) @user = User.find(params[:user_id]) if !@group.users.include?(@user) @membership = @group.memberships.create(user: @user) end end def destroy @membership = M...
class EndUser < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable validates :first_name, presence: true validates :last_name, presence: true validates :first_name_kana, presence: true, format:{ with: /\A[\p{katakana}...
require 'rails_helper' RSpec.describe History, type: :model do let!(:user) { create(:user) } context 'insert' do it 'must crate one' do History.create(user: user) expect(History.count).to eq(1) end end end
class Transaction < ApplicationRecord belongs_to :subcategory has_one_attached :image end
class AddMuscleIdToExercises < ActiveRecord::Migration[5.0] def change add_column :exercises, :muscle_id, :integer add_index :exercises, :muscle_id end end
# frozen_string_literal: true require 'common/models/redis_store' class MHVAccountIneligible < Common::RedisStore redis_store REDIS_CONFIG['mhv_account_ineligible']['namespace'] redis_ttl REDIS_CONFIG['mhv_account_ineligible']['each_ttl'] redis_key :tracker_id attribute :uuid attribute :account_state att...
require 'test_helper' class OpinionsControllerTest < ActionDispatch::IntegrationTest setup do @opinion = opinions(:one) end test 'should get index' do get opinions_url assert_response :success end test 'should get new' do get new_opinion_url assert_response :success end test 'shoul...
json.array!(@episodes) do |episode| json.title episode.title json.description episode.description json.episode_thumbnail episode.episode_thumbnail end
class OrgFlyerPdf < Prawn::Document def initialize(animal, organization) super() @animal = animal @organization = organization top_header body footer end def top_header image open("#{@organization.logo_external_url}"), at: [bounds.right - 500, bounds.top], fit: [300,100] if @organiz...
# == Schema Information # # Table name: author # # id :integer not null, primary key # book_id :integer not null, primary key # author_id :integer not null, primary key # class Work < ActiveRecord::Base belongs_to :book, :foreign_key => 'book_id' belongs_t...
class AddApprovedToProposals < ActiveRecord::Migration def change add_column :cfp_proposals, :approved, :boolean end end
class Transmission < ApplicationRecord validates :altitude, presence: true validates :latitude, presence: true validates :longitude, presence: true validates :temperature, presence: true validates_numericality_of :altitude, greater_than: 0 validates_numericality_of :latitude, greater_than: -90, less_than:...
FactoryBot.define do factory :review do comment { Faker::Lorem.word } document_id nil end end
class BirthRegistrationType < ActiveRecord::Base self.table_name = :birth_registration_type self.primary_key = :birth_registration_type_id include EbrsMetadata has_many :person_birth_details, foreign_key: "birth_registration_type_id" end
# encoding: UTF-8 # Copyright 2012 Twitter, Inc # http://www.apache.org/licenses/LICENSE-2.0 # Documentation: https://github.com/hunspell/hyphen/blob/21127cc8493a68d4fe9adbb71377b469b4f2b550/doc/tb87nemeth.pdf module TwitterCldr module Shared class Hyphenator class UnsupportedLocaleError < StandardError;...
# Grocery List =begin (Understand the Problem) Problem: Write a method which takes a grocery list (array) of fruits with quantities and converts it into an array of the correct number of each fruit. Inputs: Array (containing sub arrays of fruits with quantities) Outputs: Array (containing the correct number...
class PasswordResetController < ApplicationController before_action :find_password_reset, only: [:show, :update] def new end def create email = params[:email] user = User.find_by_email(email) if user PasswordReset.where(user_id: user.id).destroy_all password_reset = PasswordReset.crea...
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :posts, dependent: :destroy has_many :like...
require 'ruby2d' require_relative 'paddle.rb' class Ball HEIGHT = 25 attr_reader :shape, :x_velocity, :y_velocity def initialize(speed) @x = 320 @y = 400 @speed = speed @y_velocity = speed @x_velocity = -speed end def move if hit_bottom? || hit_top...
require './raster_graphics' class RGBColour # the difference between two colours def -(a_colour) (@red - a_colour.red).abs + (@green - a_colour.green).abs + (@blue - a_colour.blue).abs end end class Pixmap # the difference between two images def -(a_pixmap) if @width != a_pixmap.width or @he...
# frozen_string_literal: true FactoryBot.define do factory :organization do sequence(:name) { |n| "organization_name_#{n}" } form_of_ownership { 'ООО' } sequence(:inn) { |n| (1_000_000_000 + n).to_s } sequence(:ogrn) { |n| (1_000_000_000_000 + n).to_s } end trait :ip do form_of_ownership { '...
class TeamMailerWorker include Sidekiq::Worker sidekiq_options retry: false def perform(options = {}) send(options['perform'], options) if respond_to? options['perform'] end def send_new_employer(options) member = Member.find options['member_id'] TeamMailer.send_new_employer(member).deliver en...
require 'rexml/document' require 'uri' include REXML module Svt_play BASE_URL = 'http://www.svtplay.se' START_URL = BASE_URL + '/xml/start.xml' ALL_PROGRAMS_URL = BASE_URL + '/xml/programmes.xml' CATEGORIES_URL = BASE_URL + '/xml/categories.xml' VIDEO_URL_TEMPLATE = BASE_URL + '/video/' ATV_URL_TEMPATE = ...