text
stringlengths
10
2.61M
module AnimalQuiz class Property attr_reader :property def initialize(property) @property = property end def ==(other_obj) other_obj.property == @property end end end
class Issue < ApplicationRecord include Enum_status belongs_to :goal belongs_to :user has_many :tasks, dependent: :destroy validates :name, :solution, presence: true end
class FixScaleOffInvoices < ActiveRecord::Migration def change change_column :invoices, :original_currency_total, :decimal, precision: 20, scale: 4, default: 0 change_column :invoice_items, :price, :decimal, precision: 15, scale: 4, default: 0 change_column :invoice_items, :total, :decimal, precision: 15,...
module Searching extend ActiveSupport::Concern def search_params prms = params.permit(:q, :s, :v, :f, :t) cookies[:v] = prms[:v] if prms[:v].present? { q: prms[:q], s: enforce([:time, :stars, :rating, :year], prms[:s]), f: enforce([:none, :my_stars, :my_reviews, :unrated], prms[:f]), ...
class OrderDetail < ActiveRecord::Base self.primary_key = :product_id, :order_id belongs_to :order belongs_to :product end
class AddOptionTypesHasSameProductImage < ActiveRecord::Migration def change add_column :spree_option_types, :has_same_product_image, :boolean, :default => false end end
# frozen_string_literal: true class InformationPageNotifier # Flow: # Pages should be reviewed at least every 6 months. # Old reviewed pages should be sent to new members # New pages should be sent to all active members # Newly revised pages should be sent to all members unless they got it within the...
require_relative "../../lib/fuzzy_classnames/file_reader" RSpec.describe FuzzyClassnames::FileReader do let(:reader) { described_class.new(filename) } describe "#klasses" do context "with wrong filename" do let(:filename) { "data/wrong.txt" } it "should raise an exception" do expect { rea...
module Places def self.client @_client ||= GooglePlaces::Client.new(Rails.application.credentials.dig(:google_api_key)) end end
module Capybara class Session def has_image?(src) has_css?("img[src='#{src}']") end end end
require 'test_helper' class VoteFlowTest < ActionDispatch::IntegrationTest def setup @topic = topics(:one) end test "voting on a question anonymously" do get "/topics/#{@topic.slug}" assert_response :success assert_select '.question', 3 question = @topic.questions.find_by(slug: 'mystring1')...
class Panel::PlaceTypesController < Panel::BaseController before_action :set_place_type, only: [:show, :edit, :update, :destroy] respond_to :html def index @place_types = PlaceType.all.order('name') end def new @place_type = PlaceType.new end def edit end def create @place_type = Place...
class ApplicationMailer < ActionMailer::Base default from: ENV["MAILERS_FROM"].presence || "help@simple.org" layout "mailer" helper SimpleServerEnvHelper end
class Death < ApplicationRecord belongs_to :user def when created_at end end
module Ricer::Plugins::Admin class Reload < Ricer::Plugin trigger_is :reload permission_is :responsible has_usage def execute # rply :msg_reloading # FIXME: This causes a bug because sendqueue is done after reloading... clear_plugin_class_variables reload_core bot.load_plugins...
require 'rails_helper' RSpec.feature "Visitor Can View Items" do context "as a visitor" do it "can view all items" do item = Item.create(title: "Mask", description: "Something to put on your face.", price: 49.95, image: "https://slack-imgs.com/?c=1&url=http%3A%2F%2Fwww.scubadivingdreams.com%2Fwp-content%2F...
class DonationsController < ApplicationController include CurrentCart before_action :set_user_cart, only: [:new, :create] before_action :set_donation, only: [:show, :edit, :update, :destroy] before_action :require_user, except: [:show] #before_action :require_same_user, except: [:show] before_act...
#!/usr/bin/env ruby # encoding: utf-8 # # File: client_spec.rb # Created: 08/02/12 # # (c) Michel Demazure <michel@demazure.com> require_relative 'spec_helper.rb' require_relative '../lib/j2r/jaccess.rb' include J2R describe 'J2R::Tiers' do before { J2R.jaccess('test') } describe 'Finding a Tiers' do let(...
Fabricator(:category) do name {Faker::Name.name} end
class Home::AlbumController < ApplicationController respond_to :json def show @album = Album.find(params[:id]) @pictures_in_album = Picture.all.where(:album_id => params[:id]) @albums = Album.all end private def album_params params.require(:album).permit(:name, :id, :album_id) end end
class CreatePrograms < ActiveRecord::Migration def change create_table :programs do |t| t.string :program_name_hu t.string :program_name_en t.integer :price_full t.decimal :price_full_eur, :precision => 8, :scale => 2 t.decimal :price_discount_eur, :precision => 8, :scale => 2 ...
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'shelter update process', type: :feature do it "can take a user to '/shelters/:id/edit'" do visit "/shelters/#{@shelter1.id}" click_link 'Edit Shelter' expect(current_path).to eq("/shelters/#{@shelter1.id}/edit") end it "can see ...
require 'test_helper' class SessionsHelperTest < ActionView::TestCase def setup @user = users( :kurosaki) remember(@user) end test "current_user returns the right user when the session is nil" do assert_equal @user, current_user assert is_logged_in? end test "current_user returns nil when the remember ...
# frozen_string_literal: true class LitterAttachedImage < ApplicationRecord has_one_attached :image belongs_to :litter validates :litter_id, presence: true validates :image, attached: true, content_type: ['image/png', 'image/jpg', 'image/jpeg'] end
class SchoolExamsController < ApplicationController before_action :set_school_exam, only: [:show, :edit, :update, :destroy] # GET /school_exams # GET /school_exams.json def index @student = Student.find params[:student_id] @school_exams = SchoolExam.where(student: @student) end # GET /school_exams...
module NdrError # contains logic for registering callbacks module Callbacks def self.extended(base) base.mattr_accessor :_after_log_callbacks base._after_log_callbacks = [] end # Register callbacks that will be called after an exception # has been logged. # # NdrError.after_lo...
module Treasury module Processors module Errors class ProcessorError < StandardError; end class UnknownEventTypeError < ProcessorError; end class InconsistencyDataError < ProcessorError; end end end end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or protected) attributes for your...
require 'generators/feature_box/generator_base' module FeatureBox module Generators class MigrationsGenerator < Rails::Generators::Base include GeneratorBase desc "Installs migrations" def copy_migrations_task @model_name = ask("What is the User model name? [User]") ...
#usage: ini.rb INI_FILE #give options default value $options = {'ini_dbg' => 0, 'print' => false} # # output message if message level is no less than current setting # def iniDbg(msg, msgLevel = 1) if $options['ini_dbg'] >= msgLevel then puts "#{msg}" end end # Get array with given INI file # In : filaName # R...
class BashUtilities < Formula desc "Useful bash utilities" homepage "https://github.com/gibsjose/bash-utilities" url "https://github.com/gibsjose/bash-utilities/archive/1.1.0.tar.gz" version "1.1.0" sha256 "50ae58313798e9755ba97546116fc94c18ee0a4660a97c6a0b53e86e53138b32" def install bin.install "cou...
# frozen_string_literal: true class Transaction < ApplicationRecord validates :t_type, presence: true, length: { maximum: 1 }, inclusion: { in: %w[d w], message: 'must be d or w' } validates :amount, numericality: { greater_than: 0 }, length: { maximum: 6 } validates :account_id, numericality: { only_integer: tr...
require 'rails_helper' feature 'user clicks on state to view state details' do scenario 'visitor views state details page' do state = FactoryGirl.create(:state) visit state_path(state) expect(page).to have_content(state.name) end end
require "rails_helper" RSpec.describe Messaging::AlphaSms::Api do def stub_credentials allow(ENV).to receive(:[]).and_call_original allow(ENV).to receive(:[]).with("ALPHA_SMS_API_KEY").and_return("ABCDEF") allow(ENV).to receive(:[]).with("ALPHA_SMS_SENDER_ID").and_return("AAAAAA") end describe "#new...
require File.dirname(__FILE__) + '/../spec_helper' describe Order do fixtures :orders, :order_transactions before(:all) do OrderTransaction.gateway = BraintreeGateway.new( :login => 'demo', :password => 'password' ) end before(:each) do @order = orders(:pending) # @order = Order.c...
class PostsController < ApplicationController def index @user = User.find(session[:user_id]) @posts = Post.order("created_at DESC").limit(10) end end
require './test/test_helper' describe CliTasks do describe 'TEST_VERSION' do it 'should exist' do CliTasks::TEST_VERSION.must_be :present? end it 'should equal v0.0.1' do CliTasks::TEST_VERSION.must_equal '0.0.1' end end describe 'CliTasks::VERSION' do it 'should be a string' do...
require 'webmock/rspec' # This file was generated by the `rails generate rspec:install` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause this # file to always be loaded, without a ne...
class UserDisconnectLoginAccountMutation < Mutations::BaseMutation graphql_name "UserDisconnectLoginAccount" argument :provider, GraphQL::Types::String, required: true argument :uid, GraphQL::Types::String, required: true field :success, GraphQL::Types::Boolean, null: true field :user, UserType, null: true ...
####################################################################### # test_sys_proctable_all.rb # # Test suite for methods common to all platforms. Generally speaking # you should run this test case using the 'rake test' task. ####################################################################### require 'test-uni...
module Liquid class UrlProtected < DmCore::LiquidTag include ActionView::Helpers::TagHelper include ActionView::Helpers::AssetTagHelper include DmCore::UrlHelper include DmCore::ParamsHelper include DmCore::AccountHelper #----------------------------------------------------------------------...
class AddIndexToClientApiKey < ActiveRecord::Migration def change add_index :clients, :api_key, unique: true end end
module NavHelper #change the hash below to include the actual items you need in your navs. Use the :placement option to specify which nav an item goes in if there are multiple navs. def configure_nav_items [ <%- names.each do |name| -%> #nav items for :<%= name %> <%- unless name.to_s == 'footer' %> ...
module WindowSkin # Main settings Skins = [ "Window", # 0 "Window _MenuCommand", # 1 "Window_spellbook", # 2 "Window_infos", # 3 "Window_itemmoreinfo", # 4 "Rainbow dash5", # 5 "Luna", # 6 "Pinkie pie4", #...
class PhotosController < ApplicationController before_action :set_photo, only: [:show, :update, :destroy] # GET /photos # GET /photos.json def index @photos = Photo.all render json: @photos end # GET /photos/1 # GET /photos/1.json # def show # render json: @photo # end # POST /photos...
class Restaurant < ActiveRecord::Base attr_accessible :name, :longitude, :latitude, :description has_and_belongs_to_many :diets validates :name, :longitude, :latitude, :description, :presence => true validates :longitude, :numericality => { :only_float => true } validates :latitude, :numericality => { :onl...
module Kimurai::Dashboard class Run < Sequel::Model(DB) many_to_one :session many_to_one :spider plugin :json_serializer plugin :serialization plugin :serialization_modification_detection serialize_attributes :json, :visits, :items, :server, :events # scopes dataset_module do d...
require 'spec_helper' include Devise::TestHelpers describe ClientsController do describe 'GET index' do let(:user) { FactoryGirl.create(:user) } let(:client) { FactoryGirl.create(:client, user: user) } before { sign_in user } it 'assigns @clients' do get :index expect(assigns(:clients))....
class RemoveClassidFromLectures < ActiveRecord::Migration def change remove_column :lectures, :class_id, :integer change_column :lectures, :sub_id, :integer, :limit => 8 change_column :lectures, :id, :integer, :limit => 8 change_column :lectures, :created_at, :integer, :limit => 8 change_column :l...
class SeasonsController < ApplicationController def index @seasons = Season.all.order("created_at DESC") end end
class AddSubjectToSearches < ActiveRecord::Migration[5.1] def change add_column :searches, :subject, :string end end
require 'rails_helper' describe 'User can see all of communities', " In order to have to be to see all of communities As an authenticated user I'd like to be able to see all of communities " do let(:user) { create(:user) } let(:creator) { create(:user) } let!(:community) { create(:community, :with_avatar, cre...
class LocationsController < ApplicationController def index respond_to do |format| @locations = Location.all format.html format.json do render json: { type: "FeatureCollection", features: @locations.map do |location| ...
module Ticketing module Invoice class EntityCreationCommand include ActiveModel::Model attr_accessor :amount attr_accessor :owner_id validates :amount, presence: true validates :owner_id, presence: true def call if valid? create_invoice else ...
class FixIssueRepoUserForeignKey < ActiveRecord::Migration def change change_table :issue_assignments do |t| t.remove_references :user t.references :repo_user, null: false, foreign_key: true t.index [:repository_id, :issue_id], unique: true end end end
WheelerBoard::Application.routes.draw do devise_for :employees, controllers: { omniauth_callbacks: "employees/omniauth_callbacks" } devise_scope :employees do resource :employee do resource :profile end end resource :status resources :wheelers namespace :admin do resources :profiles ro...
require 'rails_helper' RSpec.describe Player do context 'is a model and has attributes' do it "is a valid model" do expect(Player.new).to be_a(Player) end it 'has a username attribute' do expect(Player.new).to respond_to(:username) end it 'has a email attribute' do expect(Player...
class ActionItem < ApplicationRecord # Direct associations has_many :comments, :dependent => :destroy belongs_to :recipient, :class_name => "User", :foreign_key => "actionee_id", :counter_cache => :received_follow_requests_count belongs_to :sender, ...
# frozen_string_literal: true require 'rails_helper' describe ZombiesController, type: :controller do let!(:zombie) { create(:zombie) } let(:body) { JSON.parse(response.body) } let(:data) { body['data'] } describe '#index' do let(:data) { body['data'].first } before { get :index } it_behaves_li...
class FixingBigNum < ActiveRecord::Migration def self.up add_column(:term_counts, :tweet_id, :integer) end def self.down remove_column(:term_counts, :tweet_id) end end
class Post < ActiveRecord::Base extend FriendlyId friendly_id :slug_candidates, use: :slugged def video_url sv = self.video if sv['watch?v='] sv['watch?v=']= 'embed/' sv end end def date_short d = self.created_at d.day.to_s + '/' + d.month.to_s end def date_complete self.d...
class Post < ActiveRecord::Base acts_as_indexed :fields => [:title, :name, :content] validates :name, :presence => true validates :title, :presence => true, :length => { :minimum =>5 } attr_accessible :content, :name, :title, :tags_attributes, :category_id, :body, :commenter has_many :com...
require_relative "tree_node.rb" class KnightPathFinder attr_reader :root_node, :considered_positions def initialize(pos) @root_node = PolyTreeNode.new(pos) @considered_positions = [pos] build_move_tree(root_node) end def self.valid_moves(pos) x,y = pos positi...
class RegistrationsController < Devise::RegistrationsController private def user_params params.require(:user).permit(:first_name, :last_name, :username, :email, :password, :password_confirmation, :role) end def sign_up_params params.require(:user).permit(:first_name, :last_name, :username, :email, :pa...
# frozen_string_literal: true # game messages, display methods and constants module Display INPUT_MSGS = { 'load_or_new' => ["\nEnter 1 for new game or 2 to load game.", /^[12]{1}$/, 'Invalid entry - Please enter 1 for new game or 2 to load game.'] }.freez...
shared_examples_for 'API resource with links' do let!(:links) { create_list(:link, 3, linkable: resource) } before { get api_path, params: { access_token: access_token.token },headers: headers } it 'returns all links of the resource' do expect(resource_response['links'].size).to eq resource.links.count ...
# == Schema Information # # Table name: intros # # id :integer not null, primary key # title :string # content :string # image :string # link :string # is_hidden :boolean default(FALSE) # created_at :datetime not null # updated_at :datetime not null ...
module Olelo module Hooks def self.included(base) base.extend(ClassMethods) end # Invoke before/after hooks def with_hooks(type, *args) result = [] result.push(*invoke_hook("BEFORE #{type}", *args)) result << yield ensure result.push(*invoke_hook("AFTER #{type}", *ar...
module ObjectHelper def mouse_hover? w, h = self.size return $window.mouse_x.between?(self.x - w/2, self.x + w/2) && $window.mouse_y.between?(self.y - h/2, self.y + h/2) end def move_to(x, y) @x = x @y = y end end
class AddActiveToUsers < ActiveRecord::Migration def change change_table :users do |t| t.column :active, "ENUM('Y','N')" end end end
class Piece attr_reader :color, :symbol, :board attr_accessor :position def initialize(position, board, color, symbol) @position = position @board = board @color = color @symbol = symbol end def inspect return self.color, self.symbol end def legal...
class OpenJtalk::TextCutter include Enumerable def initialize(text) @text = text end def each(&block) e = @text.each_line e = e.lazy if e.respond_to?(:lazy) # remove whites e = e.map do |line| remote_whites line end # filter out blanks e = e.select do |line| !line...
require 'yaml' module Misspelling class Config class ConfigError < StandardError; end def initialize(options:) @options = options @file_name = options.fetch(:config_file, '.misspelling.yml') @params = base_params end def included_files patterns = @params['Files']['Include'] ...
Rails.application.routes.draw do root 'articles#index' get '/favorites', to: 'articles#favorites' resources :articles, only: [:index, :create] end
require_relative '../test_helper' class UserSeesAllRobotsTest < FeatureTest def test_user_sees_all_robots robot_id = robot_world.create({ :name => "Ilana", :city => "Denver", :avatar => "bunny", :birthdate => "07-12-83", :date_hired => "today", :department => "legal" }) robot_wor...
class CreateDiscounts < ActiveRecord::Migration def change create_table :discounts do |t| t.string :name, default: '' t.string :key, default: '' t.integer :prerequisite, default: 0 t.integer :discount_type, default: 0 t.float :factor, default: 0.0 t.date :date_from, default: Ti...
require_dependency "help/application_controller" module Help class HelpOfferedsController < ApplicationController before_action :set_help_offered, only: [:show, :edit, :update, :destroy] # GET /help_offereds def index @help_offereds = HelpOffered.all end # GET /help_offereds/1 def sho...
class CreateIndices < ActiveRecord::Migration def change create_table :indices do |t| t.belongs_to :films, index: true t.belongs_to :actors, index: true t.belongs_to :articles, index: true t.timestamps null: false end end end
require 'rails_helper' describe Level do let(:cardset) { create(:cardset) } let(:card) { cardset.cards.create(question: "Question", answer: "Answer") } let(:level) { card.levels.build(status: 0, user_id: card.cardset.author_id) } subject { level } it { should respond_to(:status) } it { should respond_to...
class NoticeMailer < ApplicationMailer default from: "logiccshosoya@gmail.com" def deliver_email(user, thread, post) @access_url = "https://" + ENV['MY_HOSTNAME'] + access_path + "?apid=" + thread.seed @user = user mail(:to => user.email, :subject => "Logipost Notice") end # Subject can b...
class AddAttachmentUploadToTranscripts < ActiveRecord::Migration def self.up change_table :transcripts do |t| t.attachment :upload end end def self.down remove_attachment :transcripts, :upload end end
require 'spec_helper' describe "Dog pages" do subject { page } describe "profile page" do let(:dog) { FactoryGirl.create(:dog) } before { visit dog_path(dog) } describe "should list the dog name" do it { should have_content(dog.name) } end describe "should list the dog breed" do it { should have_c...
class CreateAdPosts < ActiveRecord::Migration[6.1] def change create_table :ad_posts do |t| t.string :title t.string :description t.timestamps end end
class Trade < ActiveRecord::Base has_many :messages, class_name: "MessageTrade" has_many :bottle_trades belongs_to :negotiator, class_name: "User" belongs_to :negotiant, class_name: "User" validates_presence_of :negotiator, :negotiant accepts_nested_attributes_for :bottle_trades, :allow_destroy => true en...
class ApplicationHelper::Button::GenericObjectDefinitionButtonEdit < ApplicationHelper::Button::Basic def visible? !(@display == 'generic_objects' || !@record.kind_of?(GenericObjectDefinition) || @actions_node) end end
class AddDecimalsToRealEstates < ActiveRecord::Migration[6.0] def change add_column :real_estates, :bathroom, :decimal, precision: 3, scale: 1 add_column :real_estates, :price, :decimal, precision: 11, scale: 2 end end
# Chris Durtschi # CS 4820 # David Hart # MicroCom - Lexical Phase class LexicalScanner def initialize(mic_path, lex_path, lis_path, lexemes, symbol_table, int_literal_table) @mic_path = mic_path @lex_path = lex_path @lis_path = lis_path # this will store this individual lexe...
class AddColumnTypeToConceptValorizations < ActiveRecord::Migration def change add_column :concept_valorizations, :type_worker, :string end end
json.array!(@games) do |game| json.extract! game, :id, :level, :player1, :player2, :objective_count, :winner json.url game_url(game, format: :json) end
# **************************************************************************** # # Copyright (c) Microsoft Corporation. # # This source code is subject to terms and conditions of the Apache License, Version 2.0. A # copy of the license can be found in the License.html file at the root of this distribution. If # you ...
require "rails_helper" RSpec.describe AdjustmentDetail, type: :model do it { should belong_to(:adjustment) } it { should belong_to(:user) } it { should validate_inclusion_of(:adjustment_type).in_array(["Refund", "Actual"]) } end
class AddNameToUsers < ActiveRecord::Migration[5.0] def change add_column :users, :name, :string add_column :users, :address, :string add_column :users, :tel, :integer add_column :users, :website, :string add_column :users, :category, :string add_column :users, :about, :string add_column :...
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :configure_permitted_parameters, if: :devise_controller? protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit(:name, :email, :user_type, :password)} ...
require 'rails_helper' RSpec.describe PropertyHelper, type: :helper do it '#lists clients' do client_create id: 1, human_ref: '8008', entities: [Entity.new(title: 'Mr', name: 'Bell')] expect(client_list.first).to eq ['8008 Mr Bell', 1] end end
require "./lib/mappings" module Stringifier include Mappings def stringify(input) array = [] p_stringify(input, array) return array.join(' ').sub(' ', ' ').rstrip end private def stringify_two_digit_number(input_string) return if input_string.length > 2 || input_string.to_i == 0 # nu...
# Copyright (c) 2015 Vault12, Inc. # MIT License https://opensource.org/licenses/MIT require File.expand_path('../boot', __FILE__) # require 'rails/all' # removed active record until we need DB (if ever) # uncomment #### lines when putting active_record back (or 'rails/all') require 'action_controller/railtie' requir...
require 'rails_helper' feature 'Admin register valid subsidiary' do scenario 'must be sign in' do visit root_path click_on 'Filiais' expect(current_path).to eq new_user_session_path end scenario 'and name and cnpj must be unique' do Subsidiary.create!(name: 'Campus Code', cnpj: '03.791.144...
require "spec_helper" describe Notifications do describe "membership" do let(:product) { mock(Product, :name => 'foo') } let(:items) { [ mock(OrderItem, :quantity => 1, :product => product) ] } let(:owner) { 'email@example.com' } let(:mail) { Notifications.membership(owner, items) } it "renders ...
class CreateClubRegistrations < ActiveRecord::Migration def change create_table :club_registrations do |t| t.string :name t.string :fb_link t.string :calendar_link t.string :website_link t.string :rss_feed t.timestamps end end end
require_relative '../test_helper' class AbilityTest < ActiveSupport::TestCase def teardown super puts('If permissions changed, please remember to update config/permissions_info.yml') unless passed? end # Verify comman permisions for all roles ('collaborator', 'editor', 'admin') ['collaborator', 'edit...