text
stringlengths
10
2.61M
class Conversation < ActiveRecord::Base # attr_accessible :title, :body has_many :messages has_many :conversation_users has_many :users, :through => :conversation_users belongs_to :owner, :class_name => "User" #user is referring to the model end
# frozen_string_literal: true require "rails_helper" module ThinkFeelDoDashboard RSpec.describe ParticipantsController, type: :controller do routes { Engine.routes } let(:authorized_user) do instance_double(User, admin?: true) end describe "when unauthorized" do describe "GET show" do ...
require "menu" describe Menu do let(:menu) {Menu.new} let(:dish) {double :dish} it "should start with no dishes when initialized" do expect(menu.items).to eq([]) end it "should be able to add a dish to the menu" do menu.add(dish) expect(menu.items).to eq([dish]) end it "should be able to delete a dis...
# A product is a named collection of jobs class Product attr_reader :name, :jobs def initialize(name) @name = name.rstrip @jobs = [] end def <<(job) @jobs << job end end # A job is a unique object with a type (to be called as a method) # & an optional text that pertains to the type class Job attr_reader...
# frozen_string_literal: true require 'rails_helper' RSpec.describe AfterKillMonsterService, type: :service do describe 'verify and create trophies about user kills' do let(:user) { User.create(username: 'BabyShark95') } let(:baby_shark) { Monster.create(name: 'Baby Shark') } context 'when have 2 kills...
require 'test_helper' class WsubscribesControllerTest < ActionDispatch::IntegrationTest setup do @wsubscribe = wsubscribes(:one) end test "should get index" do get wsubscribes_url assert_response :success end test "should get new" do get new_wsubscribe_url assert_response :success end...
require 'typhoeus' module Typhoid class RequestQueue attr_reader :queue attr_accessor :target def initialize(target, hydra = nil) @target = target @hydra = hydra || Typhoeus::Hydra.new end def resource(name, req, &block) @queue ||= [] @queue << QueuedRequest.new(@hydra, ...
class History < ActiveRecord::Base validates_presence_of :won_by_id, :lost_by_id, :card_id belongs_to :won_by, :class_name => "User" belongs_to :lost_by, :class_name => "User" belongs_to :card scope :after, ->(time) { where('created_at > ?', time) } default_scope { order(created_at: :desc) } end
Rails.application.routes.draw do post "/rate" => "rater#create", :as => "rate" scope "(:locale)", locale: /en|vi/ do root "static_pages#home" devise_for :users namespace :guest do resources :news_leases do collection do get :myleases match "search" => "news_leases#sea...
require 'json' require 'logger' require 'redis' require 'resque' require 'sinatra' require './mql_translator.rb' require './queued_event.rb' require './sync_database.rb' config = YAML.load(File.read('config/app.yml'))[ENV['RACK_ENV'] || 'development'] translator = MQLTranslator.load(config) # Receive an event get '/...
# See the Pagy documentation: https://ddnexus.github.io/pagy/extras/trim # encoding: utf-8 # frozen_string_literal: true class Pagy module Frontend # boolean used by the compact navs TRIM = true alias_method :pagy_link_proc_without_trim, :pagy_link_proc def pagy_link_proc_with_trim(pagy, link_extr...
require "minitest" require "minitest/autorun" require "minitest/pride" require "faker" require 'active_support/core_ext' require "./movie_store" require "./movie" describe MovieStore do before do @store = MovieStore.new("Blockbuster", Address.new(number, street, city, state, zip)) end let(:full_name){Faker:...
require 'spec_helper' describe Character do before { @character = Character.new(name: "Example User", intelligence: "21") } subject { @character } it { should respond_to(:name) } it { should respond_to(:intelligence) } end
#### # # User # # User represents a login into the application # # A new user has to be checked for a valid email # and the password has to be confirmed. # # #### # class User < ApplicationRecord enum role: { user: 0, admin: 1 } scope :by_nickname, -> { order(:nickname) } has_secure_password validates :nicknam...
# frozen_string_literal: true require 'twirp_rails/routes' module TwirpRails module RavenAdapter # :nodoc: def self.install return unless defined?(::Raven) TwirpRails::Routes::Helper.on_create_service do |service| RavenAdapter.attach service end end def self.attach(service) ...
require 'rails' module Rogger class Railtie < Rails::Railtie initializer "rogger.load-config" do config_file = Rails.root.join("config", "rogger.yml") if config_file.file? ::Rogger.load!(config_file) end end end end
class Enrolment < ActiveRecord::Base belongs_to :student belongs_to :state has_many :status_changes alias_method :original_state_assignment, :state= attr_accessor :previous_state validate :state_validation after_create :create_preenrolled_state_change def current_state state.try(:name) end ...
class SessionsController < ApplicationController before_action :authorize, only: [:destroy] def create user = User.find_by!(username: params[:username]) if user&.authenticate(params[:password]) session[:user_id] = user.id render json: user, status: :created else...
require "test_helper" describe MerchantsController do let (:ada) { merchants(:ada) } let (:grace) { merchants(:grace) } describe "LOGIN" do ### Copied from lecture notes, rewritten comments to make better sense to me it "logs in an existing merchant and redirects to the root route" do # Yml s...
require 'feidee_utils/record' require 'feidee_utils/mixins/type' module FeideeUtils class Transaction < Record include FeideeUtils::Mixins::Type class TransferLackBuyerOrSellerException < Exception end class TransferWithCategoryException < Exception end class InconsistentBuyerAndSellerExce...
class AddDateToObjectives < ActiveRecord::Migration def change add_column :objectives, :date, :date end end
class CreateBills < ActiveRecord::Migration[6.0] def change create_table :bills do |t| t.string :ref_bill t.references :quote, null: false, foreign_key: true t.references :customer, null: false, foreign_key: true t.text :description t.integer :deposit t.integer :price_duty_free...
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
class User < ActiveRecord::Base has_one :profile has_one :reminder has_many :entries # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validat...
module MazeCrosser # Class responsible for applying resursive algorithm to a maze. # # recursive_algorithm = RecursiveAlgorithmRunner.new(maze) # # Run the algorithm # recursive_algorithm.run class RecursiveAlgorithmRunner def initialize(maze) @maze = maze @path = [] end def run ...
{ :'de' => { :active_scaffold => { :add => 'Hinzufügen', :add_existing => 'Existierenden Eintrag hinzufügen', :add_existing_model => 'Existierende %{model} hinzufügen', :are_you_sure_to_delete => 'Sind Sie sicher?', :cancel => 'Abbrechen', :click_to_edit => 'Zum Editieren ankli...
RSpec.describe Entry, type: :model do context "associations" do it { is_expected.to belong_to(:journal) } it { is_expected.to have_many(:responses).dependent(:destroy) } end subject do FactoryBot.create(:entry) end describe '#create_response' do let(:response_attributes) do FactoryBot....
require 'test_helper' require 'test/unit' require_relative '../lib/accountant.rb' #http://stackoverflow.com/questions/16948645/how-do-i-test-a-function-with-gets-chomp-in-it class TestAccountant < Test::Unit::TestCase def test_initialize plan = {'public'=>100.0, 'discount'=>0.17, 'data'=>10} contacts = [{'...
class UsersController < ApplicationController before_action :logged_in_user, only: [:index, :edit, :update] def index @users = User.all end def show @user = User.find(params[:id]) end def new @user = User.new end def create user = User.find_by(email: params[:email].downcase) ...
###################################################################### # my extensions to Module. (taken from rake, named changed to not clash # when rake is used) # class Module # Check for an existing method in the current class before extending. If # the method already exists, then a warning is printed and the ...
class ChangeEreaCategories < ActiveRecord::Migration def up rename_table :erea_categories, :area_categories end def down rename_table :area_categories, :erea_categories end end
class ChangeDefaultDisableRestaurant < ActiveRecord::Migration def change change_column :restaurants, :disabled, :boolean, :default => nil add_column :restaurants, :is_owner, :boolean add_column :restaurants, :contact_note, :string add_column :restaurants, :suggester_name, :string end end
class User < ActiveRecord::Base has_many :expenses attr_accessor :password, :password_confirmation STRING_REGEX = /\A[a-zA-Z]+\z/ EMAIL_REGEX = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]+)\z/i validates :first_name, :last_name, length: { minimum: 2 }, format: { with: STRING_REGEX } validates :email, uniqueness: tru...
class ChangeRequestAtTableName < ActiveRecord::Migration def change drop_table :request_ats create_table :requested_ats do |t| t.datetime :time end end 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...
class RemoveColumnFromSeller < ActiveRecord::Migration[5.0] def change remove_column :sellers, :official_name, :string remove_column :sellers, :address, :string remove_column :sellers, :phone_number, :string end end
Rails.application.routes.draw do scope ":locale", :locale => /#{I18n.available_locales.join("|")}/ do devise_for :customer devise_for :admin, :skip => [:registrations] namespace :admin do # CRUD nested category, product, image resources :categories do resources :products do ...
class CreateTransitStations < ActiveRecord::Migration def self.up create_table :transit_stations do |t| t.integer :request_id t.integer :station_id t.timestamps end end def self.down drop_table :transit_stations end end
class New11QuotationProject < ActiveRecord::Migration[5.2] def change add_reference :quotations, :project, index: true, foreign_key: true end end
require File.dirname(__FILE__) + '/../../spec_helper' require File.dirname(__FILE__) + '/fixtures/common' describe "Float#<" do it "returns true if self is less than other" do (71.3 < 91.8).should == true (192.6 < -500).should == false (-0.12 < bignum_value).should == true (nan_value < 1.0).should ==...
class PropertyAgricultureDry < ActiveRecord::Base attr_accessible :acreage, :alfalfa_avg_annual_cutting, :alfalfa_avg_ton_per_acre, :meadow_avg_annual_cutting, :meadow_avg_ton_per_acre, :property_id, :dry, :dry_alfalfa, :dry_meadow, :person_id, :desired_property_profile_id serialize :dry belongs_to :property ...
require File.dirname(__FILE__) + '/../../spec_helper' describe "/opinions/index.html.erb" do include OpinionsHelper before(:each) do opinion_98 = mock_model(Opinion) opinion_98.should_receive(:user_id).and_return("1") opinion_98.should_receive(:track_id).and_return("1") opinion_98.should_receive...
class AddThrowerLeaverToMatches < ActiveRecord::Migration[5.1] def change add_column :matches, :enemy_thrower, :boolean add_index :matches, :enemy_thrower add_column :matches, :ally_thrower, :boolean add_index :matches, :ally_thrower add_column :matches, :enemy_leaver, :boolean add_index :ma...
# Read about factories at http://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :oui do association :manufacturer sequence(:value) { |n| (n + 11184810).to_s(16).upcase } end end
class AddDescriptionToStores < ActiveRecord::Migration[4.2] def change add_column :stores, :description, :text end end
class ParkSerializer include FastJsonapi::ObjectSerializer attributes :name, :state, :img_urls end
class RelationshipsController < ApplicationController before_action :authenticate_user! def create @user = User.find(params[:followed_id]) current_user.follow(@user) fetch_next_user respond_to do |format| format.html { redirect_to authenticated_root_url } format.js { } end end ...
module Helpers def stub_omniauth # first, set OmniAuth to run in test mode OmniAuth.config.test_mode = true # then, provide a set of fake oauth data that # omniauth will use when a user tries to authenticate OmniAuth.config.mock_auth[:twitter] = OmniAuth::AuthHash.new({ provider: "twitter", ...
class RuntimeFormatter def self.format(runtime) new(runtime).formatted end attr_reader :runtime def initialize(runtime) @runtime = runtime end def formatted text = [] text << "#{hours} #{'hour'.pluralize(hours)}" if hours > 0 text << " #{minutes} #{'minute'.pluralize(minutes)}" if min...
class Invoice < ApplicationRecord belongs_to :job_order has_many :tasks, inverse_of: :invoice accepts_nested_attributes_for :tasks, reject_if: :all_blank, allow_destroy: true end
class PasswordsController < Devise::PasswordsController protected def after_sending_reset_password_instructions_path_for(resource_name) flash[:notice] = "Reset password instructions have been sent to your email. Once you successfully reset it, you can log in again." root_url end end
class ApplicationController < ActionController::Base class AccessDenied < StandardError; end # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception helper_method :current_user rescue_from AccessDenied, with: :record_not_f...
class CreateLikes < ActiveRecord::Migration[5.0] def up create_table :likes do |t| t.string :user_ip, :null => false t.references :post, foreign_key: true t.timestamps end end def down drop_table :likes end end
class ControllerFile < ProtoFile def self.directory Pathname.new Rails.root.join('protoror/app/controllers') end def self.path_suffix '_controller.rb' end def self.route_name 'controllers' end end
require 'oauth' require 'json' module Yahoo CONSUMER_KEY = ENV['CONSUMER_KEY'] CONSUMER_SECRET = ENV['CONSUMER_SECRET'] class YQLFinance def initialize(consumer_key = CONSUMER_KEY, consumer_secret = CONSUMER_SECRET) @consumer_key = consumer_key @consumer_secret = consumer_secret acc...
class MakeConnectionContextProtocolJoinTableUnique < ActiveRecord::Migration def change remove_index :connection_context_protocols_connection_contexts, :name => :conntextion_context_protocol_implementors add_index :connection_context_protocols_connection_contexts, [:connection_context_protocol_id, :connection...
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :training_availability do association :user association :training available { [true, false].sample } end end
class Pet < ApplicationRecord has_one_attached :image belongs_to :user, optional: true belongs_to :litter, optional: true belongs_to :shelter, optional: true has_many :posters has_many :tags end
RSpec.describe Account::CardsController do render_views let(:user) { create :user } before { sign_in user } describe 'GET index' do subject { get :index } it { is_expected.to be_success } end describe 'POST sync' do let(:sync_result) { double('card-sync', success?: true) } before { allow...
require "rails_helper" RSpec.feature "User can view a page" do context "Given the page exists" do scenario "show action renders the page's content" do test_page = Page.create(title: "test_title", content: "test_content", slug: "test_slug") visit page_path(test_page.id) expect(page).to have_co...
require File.expand_path("../../spec_helper", __FILE__) # This uses the Google Apis as documented at: #https://developers.google.com/google-apps/calendar/v3/reference/calendarList#resource #https://developers.google.com/google-apps/calendar/v3/reference/events#resource #https://developers.google.com/google-apps/calend...
module ProductsHelper def registration_price(product) product.price_histories.order(created_at: :asc).first.current_price end def registration_date(product) product.price_histories.order(created_at: :asc).first.created_at.strftime('%d/%m/%Y') end def minimum_price(product) product.price_historie...
class RemoveBeerIdFromDrinks < ActiveRecord::Migration def change remove_column :drinks, :beer_id end end
require 'test_helper' class ProductTest < ActiveSupport::TestCase test 'valid product' do product = Product.new(name: 'Product1', code: 'product123') assert product.valid? end test 'invalid without name' do product = Product.new(code: 'product1') refute product.valid?, 'product is valid without ...
class ApplicationController < ActionController::Base protect_from_forgery helper_method :current_user, :is_logon_user?, :user_email private def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end private def is_logon_user? if session[:user_id] true else false e...
class Report < ActiveRecord::Base serialize :cobrands, Array serialize :product_brands, Array serialize :product_categories, Array serialize :product_keywords, Array serialize :product_partner_keys, Array serialize :recipients, Array serialize :review_star_ra...
Rails.application.routes.draw do resources :cats # The pattern the actions follow is: # lowercase_controller_name#action root "users#index" resources :books # resources :users get "/users" => "users#index" get "/users/:id" => "users#show" get "/users/new" => "users#new" post "/users" => "users#cr...
require 'tsort' module Codependency class Graph < Hash ## # Add the given file to this graph. Creates a new entry in the # graph, the key of which is the relative path to this file and # the value is the array of relative paths to its dependencies. # Any dependent files will also be recursively ...
class CharacterDecorator < Drape::Decorator delegate_all def take_guild_title guild ? guild.title : 'Character doesn`t have guild' end def take_avatar_link avatar_link.blank? ? 'character_default_avatar.png' : avatar_link end end
require 'rails_helper' def user_doesnt_see_post_form expect(page).not_to have_field("Body") expect(page).not_to have_field("Picture") expect(page).not_to have_button("Create Post") end def user_doesnt_see_comment_form expect(page).not_to have_field("Body") expect(page).not_to have_button("Create Comment") e...
class FplPlayer < ApplicationRecord after_create :add_additional_attributes def add_additional_attributes player_details = FplService.fetch_player_info(fpl_id) update_attributes(first_name: player_details["player_first_name"], last_name: player_details["player_last_name"], ...
class RequirePointsToRequiredPointsInBadges < ActiveRecord::Migration def change rename_column :badges, :require_points, :required_points end end
class ErrorsController < ApplicationController def show status_code = params[:code] || 500 flash.alert = "Status #{status_code}" render 'show', status: status_code end end
module Spree if Rails.application.config.use_paperclip ActiveSupport::Deprecation.warn(<<-EOS, caller) Paperclip support is deprecated, and will be removed in Spree 4.0. Please migrate to ActiveStorage, to avoid problems after update https://github.com/thoughtbot/paperclip/blob/master/MIGRATING.md ...
require 'test_helper' class SwitchboardsControllerTest < ActionController::TestCase setup do @switchboard = switchboards(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:switchboards) end test "should get new" do get :new assert_respon...
module BamHelpers # terminal column width def col_width `stty size`.split(" ").last.to_i end def border "="*col_width end def wrap_top(content) "#{border}\n#{content}" end def wrap_borders(content) "#{border}\n#{content}\n#{border}" end end
# frozen_string_literal: true module Renalware::Forms::Generic module Homecare::V1 class PatientDetails < Base def build move_down 10 font_size 10 table( [ [heading("Name"), args.patient_name], [heading("Modality"), args.modality], [head...
# frozen_string_literal: true require 'rails_helper' RSpec.describe ApplicationRecord, type: :model do let(:landlord) { create(:landlord) } let(:tenant) { create(:tenant) } describe 'Checking correct full name of' do it 'Landlord' do expect(landlord.full_name).to eq landlord.first_name.capitalize + '...
class CreateBatchLeadershipLeaders < ActiveRecord::Migration def change create_table :batch_leadership_leaders do |t| t.integer :leadership_leader_id t.integer :employee_department_id t.integer :batch_leadership_supervisor_id t.integer :student_class_id t.timestamps end end end
# frozen_string_literal: true def which(executable) ENV['PATH'] .split(File::PATH_SEPARATOR) .map { |p| "#{p}/#{executable}" } .detect { |p| File.executable?(p) } end
class ChangeColumnToUsers < ActiveRecord::Migration[5.2] def up change_column :users, :name, :string, null: false, limit: 128 change_column :users, :email, :string, null: false, limit: 255 end def down change_column :users, :name, :string change_column :users, :email, :string, default: "", null: ...
class ManageDistrictRegionService def self.update_blocks(district_region:, new_blocks: [], remove_blocks: []) create_blocks(district_region, new_blocks) destroy_blocks(remove_blocks) end private class << self def create_blocks(district_region, block_names) return if block_names.blank? ...
require 'spec_helper' describe Branch do let(:enterprise) { Enterprise.create(description: "Burguer King") } before { @branch = enterprise.branches.create(description: "Filial 01", cnpj: "37155216000136", adress: "Rua Libania", ...
class PetRoomsController < ApplicationController def index rooms = current_owner.pet.pet_rooms.pluck(:room_id) pet_rooms = PetRoom.where(room_id: rooms).where.not(pet_id: current_owner.pet) pets = pet_rooms.pluck(:pet_id) # binding.pry @pets = Pet.includes(:pet_rooms).where(id: pets).reverse_order...
class Product < ActiveRecord::Base belongs_to(:purchase) scope(:in_stock, -> do where({:in_stock => true}) end) end
# frozen_string_literal: true # ref: https://qiita.com/k-yamada-github/items/e8dbd6f53c638a930588 namespace :db do desc 'Dump the database to tmp/dbname.dump' task dump: %i[environment load_config] do config = ::ActiveRecord::Base.configurations.configs_for(env_name: ::Rails.env).first.configuration_hash i...
#!/usr/bin/env ruby require 'yaml' require 'erb' subtitle_maker = lambda { |data| data.slice('code', 'text').values.map(&:to_s).reject(&:empty?).join(' ') } # http error pages YAML.load_file('./http_status_code.yml').each do |group| group['list'].each do |data| file = "#{data['code']}.html" subtitle = s...
module BackgrounDRb module ClientHelper def gen_worker_key(worker_name,worker_key = nil) return worker_name.to_sym if worker_key.nil? return "#{worker_name}_#{worker_key}".to_sym end end end
require 'formula' # via: https://trac.macports.org/browser/trunk/dports/net/tsocks # via: https://github.com/mxcl/homebrew/issues/11870 # # === #{etc}/tsocks.conf # server = 127.0.0.1 # server_type = 5 # server_port = 1080 # class Tsocks < Formula url 'http://distfiles.macports.org/tsocks/tsocks-1.8.4.tar.bz2' hom...
json.array!(@gymdays) do |gymday| json.extract! gymday, :location json.url gymday_url(gymday, format: :json) end
class ItemsController < ApplicationController before_action :authenticate_user!, except: [:index, :show] before_action :set_item, only: [:edit, :show, :update, :destroy] before_action :move_to_index, only: [:edit, :update, :destroy] def index @items = Item.all.order("created_at DESC") end def new ...
class Booking < ApplicationRecord belongs_to :user belongs_to :listing validate :overlap? def overlap? if self.listing.bookings.where("(start_date BETWEEN ? AND ?) OR (end_date BETWEEN ? AND ?)", self.start_date, self.end_date, self.start_date, self.end_date).count > 0 errors.add(:start_date, "is not ...
# Класс «Заметка», разновидность базового класса «Запись» class Memo < Post # Отдельный конструктор здесь не нужен, т. к. у заметки нет дополнительных # переменных экземпляра. # Этот метод пока пустой, он будет спрашивать ввод содержимого Заметки def read_from_console puts "Новая заметка (все, что пишите д...
class AttendanceCategory < ActiveRecord::Base has_one :attendance_day end
require 'spec_helper' describe User, type: :model do it "has a valid factory for administrator" do user = build(:administrator) expect(user).to be_valid end it "has a valid factory for coach" do user = build(:coach) expect(user).to be_valid end it "has a valid factory for user" do user ...
class Order attr_reader :book, :reader, :date def initialize(book, reader) @date = Time.now.strftime('%d/%m/%Y %H:%M') @book = book @reader = reader end def to_s "#{@book.title}/#{@reader.name}" end end
class Particle attr_reader :x, :y, :w, :h attr_accessor :dead def initialize type, x, y, speedx, speedy @dead = false @x = x @y = y @speedx = speedx @speedy = speedy @img = Gosu::Image.new G.window, 'particle.png' @w = @img.width @h = @img.height end def update @x ...
module BooleanAttr def self.included(base) base.extend ClassMethods end module ClassMethods def boolean_attr_accessor(*args) options = args.extract_options! boolean_attr_writer(*args, options) attr_reader(*args) args.each { |arg| alias_method "#{arg}?".to_sym, arg.to_sym } ...
# frozen_string_literal: true require 'table_beet/version' require 'table_beet/runner' require 'slop' module TableBeet class CLI def initialize(opts = nil) @runner = TableBeet::Runner.new(opts || parse_options) end def run @runner.run end def self.run(opts = nil) TableBeet::C...
# == Route Map # # Prefix Verb URI Pattern Controller#Action # api_v1_top GET /api/v1/top(.:format) api/v1/top#top # api_v1_project_task_comments GET ...