text
stringlengths
10
2.61M
ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) abort("The Rails environment is running in production mode!") if Rails.env.production? Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } require 'spec_helper' require 'rspec/rails' require 'capybara/poltergeist...
require 'test_helper' class MedicamentOrdersControllerTest < ActionDispatch::IntegrationTest setup do @medicament_order = medicament_orders(:one) end test "should get index" do get medicament_orders_url assert_response :success end test "should get new" do get new_medicament_order_url a...
class InputFilesController < ApplicationController before_action :set_input_file, only: [:update, :destroy, :download] before_action :set_project, only: [:index, :new, :edit, :create, :update, :destroy] before_action :set_project_download, only: [:download] before_action :check_company before_action :check_au...
module ValidationHelper # Creates a couple of useful constants and a validation rule for a text field. # # * SYM_MIN_LENGTH # * SYM_MAX_LENGTH # * SYM_VALIDATION_MESSAGE # # Params: # * sym - the symbol representing the text field # * min - minimum number of characters # * max - maximum ...
module RailsAdmin module Extensions module PunditNested # This adapter is for the Pundit[https://github.com/elabs/pundit] authorization library. # You can create another adapter for different authorization behavior, just be certain it # responds to each of the public methods here. class Au...
module EricWeixin class AccessToken < ActiveRecord::Base belongs_to :public_account, :class_name => '::EricWeixin::PublicAccount', foreign_key: :public_account_id self.table_name = "weixin_access_tokens" #设定最初的腾讯微信服务器列表 $ip_list = {"no-ip" => true} # 获取 AccessToken 方法一。根据 APPID 查到微信公众号 Pu...
# Back in the good old days, you used to be able to write a darn near # uncrackable code by simply taking each letter of a message and incrementing it # by a fixed number, so "abc" by 2 would look like "cde", wrapping around back # to "a" when you pass "z". Write a function, `caesar_cipher(str, shift)` which # will ta...
class Participation < ActiveRecord::Base # Remember to create a migration! has_many :responses belongs_to :survey belongs_to :taker, class_name: "User" end
require 'spec_helper' RSpec.describe Viberroo::Message do describe '#text' do subject { Viberroo::Message.plain(text_params) } it { is_expected.to include({ type: :text }) } end describe '#rich' do subject { Viberroo::Message.rich(rich_params) } it { is_expected.to include({ type: :rich_media ...
require 'symbol' module Noel class BaseScope attr_reader :scope_name, :parent def initialize(scope_name, parent) @scope_name = scope_name @parent = parent @table = {} end def define(symbol) @table[symbol.name] = symbol end ...
require 'enumerator_ex/generators' require 'enumerable_lz/enumerable_ex' require File.join( File.dirname(__FILE__) , 'generators') require File.join(File.dirname(__FILE__),'..','enumerator_ex') module Enumerable extend EnumeratorEx::Generators #Intersperse several enumerator/enumerables, until all are #exha...
class WifiPage attr_accessor :driver def initialize(driver) @driver = driver end def wifitextisdisplayed @driver.find_element(:uiautomator, 'new UiSelector().className("android.widget.TextView").text("WiFi")').displayed? end def tickwificheckbox @driver.find_element(:id, 'android:id/checkbox...
class AdminsController < ApplicationController before_action :get_admin, only: [:show, :edit, :update, :destroy, :admin_profile] before_action :authorized_to_see_page_admin skip_before_action :authorized_to_see_page_admin, only: [:login, :handle_login, :new, :create] def login @error = flash[:er...
require 'docman/commands/command' module Docman module Builders class Builder < Docman::Command @@builders = {} @@build_results = {} def self.create(params = nil, context = nil, caller = nil) c = @@builders[params['handler']] if c c.new(params, context, caller, 'buil...
require 'validation' class Striuct class << self alias_method :new_instance, :new private :new_instance # @group Constructors for Subclassies # @param [Symbol, String] autonyms # @yieldreturn [Class] # @return [Class] def new(*autonyms, &block) # warning for Ruby's Stru...
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe AccountsController do ActionController::Integration::Session describe "on create affiliate account post" do describe "with required parameters" do def required_params {:email => Faker::Internet.email} end ...
Drinkster::Application.routes.draw do root to: 'main#index' scope 'api' do resources :users, only: [:create, :show] do resources :ingredients, only: [:create, :destroy, :index] resources :drinks, only: [:index] end resource :session, only: [:create, :destroy] end match '*path', to:...
class Types::FormSectionType < Types::BaseObject field :id, Int, null: false field :title, String, null: true field :form, Types::FormType, null: false, camelize: false field :position, Int, null: true field :form_items, [Types::FormItemType], null: false, camelize: false association_loaders FormSection, :...
class ArticleTag < ActiveRecord::Base belongs_to :tag, counter_cache: true belongs_to :article # validates :article, :tag, presence: true delegate :name, to: :tag end
class AddSkillsheetToUsers < ActiveRecord::Migration[5.0] def change add_column :users, :skillsheet, :binary add_column :users, :skillsheet_name, :string, default: '未登録' end end
FUNCTIONS = { '+' => Proc.new { |args| args.reduce(&:+)}, '*' => Proc.new { |args| args.reduce(&:*)}, 'if' => Proc.new { |args| args[0] ? args[1] : args[2] }, 'def' => Proc.new { |args| VALUES[args[0]] = args[1] }, 'progn' => Proc.new { |args| args.last }, 'let' => Proc.new { |args| # ["(x 3)...
FactoryBot.define do factory :message_tag do title {Faker::Lorem.sentence} message {Faker::Lorem.sentence} whom {Faker::Name.name} open_plan {Faker::Date.between(from: 1.day.from_now, to: 100.years.from_now).strftime('%Y-%m-%d')} name {Faker::Lorem.sentence} end end
class Product < ActiveRecord::Base if Rails.env.production? has_attached_file :picture, :styles => { :medium => "300x400", :thumb => "150x250" }, :storage => :s3, :s3_credentials => "#{Rails.root}/config/s3.yml", :path => ":a...
require_relative './spec_helper' require_relative '../helpers/language_helper' describe GitHubLanguage do include LanguageHelper context 'when a username has been provided' do it 'receives a response containing langauge data from the GitHub API', :vcr do user = "hamchapman" uri = "https://api.gi...
require 'spec_helper' class MockController attr_accessor :request, :user def initialize(request, user) @request, @user = request, user end end class MockNoUserController attr_accessor :request def initialize(request) @request = request end end describe Arcane do let(:user) { double(name:...
class AdminUser < ApplicationRecord has_secure_password has_and_belongs_to_many :pages has_many :section_edits has_many :sections, :through => :section_edits EMAIL_REGEX = /\A[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}\Z/i FORBIDDEN_USERNAMES = ['littlebopeep', 'humptydumpty', 'marymary'] # "sexy" validations...
module Ign class Search attr_accessor :query def initialize(query) self.query = query.strip end def game same_name = games.select{|game| game.name.downcase == query.downcase} if same_name.count == 0 games.first elsif same_name.count == 1 same_name.first ...
#!/usr/bin/env ruby # frozen_string_literal: true require 'sinatra' require 'fileutils' get '/:name/:md5/index' do result = '[' seperator = '' dir = File.join('public', params[:name], params[:md5]) halt 400, 'File not found' unless File.directory?(dir) Dir.glob(File.join(dir, '*.dep')) do |x| result += ...
class Deck < ApplicationRecord belongs_to :hashtag has_many :card end
class Download < ApplicationRecord belongs_to :user belongs_to :movie validates :user_id, :movie_id, presence: :true end
require "net/ftp" module Podflow module Uploader def self.perform(path, opts) remote_size = 0 local_size = File.size(path) STDOUT.sync = true STDOUT.print "#{path} uploading to #{opts['host']}:#{opts['path']} - this may take a while... " Net::FTP.open(opts["host"]) do |ftp| ...
class User < ApplicationRecord enum role: [:user, :vip, :admin] after_initialize :set_default_role, :if => :new_record? devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :galleries, dependent: :destroy has_many :images, dependent: :destr...
class Comment include Mongoid::Document field :name field :email field :text field :approved, type: Boolean, default: false end
class UsersController < ApplicationController def show @videos = Video.all @transactions = current_user.transactions @user = User.find(params[:id]) authorize @user end end
class HappeningsForDisciplinesDatatable < BaseDatatable def columns { 'happenings.id': { hide: true }, 'happenings.name': {}, 'happenings.start_date': {}, 'venues.name': { title: Venue.model_name.human }, 'clubs.name': { title: Club.model_name.human }, 'clubs.id': { hide: true ...
module Sortable extend ActiveSupport::Concern module ClassMethods def sort_columns_for(model, default_column, default_direction=nil) return if method_defined? "sort_column" or method_defined? "sort_direction" define_method "sort_column" do model.column_names.include?(params[:sort]) ? param...
# Copyright (c) 2015 - 2020 Ana-Cristina Turlea <turleaana@gmail.com> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS...
class Carnival attr_reader :name, :rides, :attendees def initialize(name) @name = name @rides = [] @attendees = [] end def add_ride(ride) @rides << ride end def recommend_rides(attendee) @rides.find_all do |ride| attendee.interests.any? do |interest| ...
require 'test_helper' class ContactsControllerTest < ActionDispatch::IntegrationTest def setup @admin = users(:admin) @standard_user = users(:standard) @contact = contacts(:bill) end test 'users should be able to visit contact pages' do # Admin user log_in_as @admin get contacts_path ...
class Ability include CanCan::Ability def initialize(user) user ||= User.new alias_action :index, :sign_in, :sign_out, :to => :nav can :nav, User can :show, User, :id => user.id if user.admin? can :manage, Post can :manage, User elsif user.vip? can :read, :update, Post ...
load "waveguide.rb" class Eam_Lump include MyBasic include RBA attr_accessor :mesa_width_in, :mesa_width_hybrid, :mqw_width_in,:mqw_width_hybrid, :nInP_width, :nInP_length, :taper1, :taper2, :nmetal_gap, :lay_mesa, :lay_mqw, :lay_nInP...
class RequestMailer < ApplicationMailer # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.request_mailer.email_confirmation.subject # def email_confirmation(request) @request = request mail(to: @request.email, subject: 'Welcome to our Coworking p...
class AddColumnPinyinToProducts < ActiveRecord::Migration def change add_column :products, :pinyin, :string end end
Given /^I have the following transactions$/ do |transaction_table| transaction_table.hashes.each do |hash| hash['transaction_datetime'] = eval(hash['transaction_datetime']) FactoryGirl.create(:transaction, hash.merge(user: @user)) end end Then /^I should see all transactions within (.*?)$/ do |type| case...
module Dictionary def self.included(base) base.extend ClassMethods end module ClassMethods #builds a set of constants like: KEY = 'KEY' #as well as a method self.dict that returns all of those constants' values def build_dictionary *keys keys.each do |key| const_set key.to_s.upcase...
class TeamSerializer < ActiveModel::Serializer attributes :id, :name, :player1, :player2 end
class SurnameFieldForOwnerhistories < ActiveRecord::Migration[5.0] def change change_column :flats, :phone, :string add_column :ownerhistories, :surname, :string end end
class CreateFlights < ActiveRecord::Migration[5.2] def change create_table :flights do |t| t.string :departure_city t.string :arrival_city t.string :departure_date t.integer :departure_time_1 t.integer :departure_time_2 t.integer :departure_time_3 t.integer :departure_tim...
module Boxzooka class ProductListResponse < BaseResponse collection :results, entry_node_name: 'Item', entry_field_type: :entity, entry_type: Boxzooka::Item end end
require 'rubygems' require 'rubygems/package' require 'open3' require 'tempfile' # Exception for this class class Gem::OpenPGPException < RuntimeError; end # A wrapper that shells out the real OpenPGP crypto work # to gpg. module Gem::OpenPGP # Given a string of data, generate and return a detached # signature. ...
module MiW class TableView class DataCache DEFAULT_PAGE_SIZE = 4096 def initialize(query, page_size = DEFAULT_PAGE_SIZE) @query = query @pages = {} @page_size = page_size end attr_reader :dataset def reset @pages = {} end def count ...
class AddRelationshipsBetweenModels < ActiveRecord::Migration def change add_column :tasks, :list_id, :integer, :null => false, :default => "0" add_column :tasks, :user_id, :integer, :null => false, :default => "0" add_column :lists, :user_id, :integer, :null => false, :default => "0" end end
@songs.each do |song| json.partial! "api/songs/song", song: song end
# encoding: UTF-8 module OmniSearch # Builds a named index # ---------------------------------- # index_class - like DoctorIndex # index_type - like PlainText # # it stores DoctorIndex.records, # formatted the way thay PlainText needs them # # # Usage: # =========================================...
class JobsController < ApplicationController before_action :set_job, only: %i[ show edit update destroy ] # GET /companies or /companies.json def index @jobs = Job.all end # GET /companies/1 or /companies/1.json def show @job = Job.find(params[:id]) @company = Company.fin...
require 'rails_helper' describe DevsController, type: :request do let!(:devs) { create_list(:dev, 10) } context 'index route' do let(:result) { JSON.parse(response.body) } before { get '/devs' } it 'request index and return 200 OK' do expect(response.code).to eq('200') expect(response).to...
# == Schema Information # # Table name: engineers # # id :bigint not null, primary key # name :string not null # created_at :datetime not null # updated_at :datetime not null # require 'rails_helper' RSpec.describe Engineer, type: :model do describe 'association...
class CharacterSerializer < BaseSerializer attributes :id, :name, :level, :achievement_points, :created_at, :updated_at has_one :clazz, key: :class has_one :race has_one :realm has_one :faction end
unless defined? Thread fail "Thread not available for this ruby interpreter" end
class HasAndBelongsToManyIssuesUser < ActiveRecord::Migration def change create_table :got_fixed_issues_users do |t| t.belongs_to :user t.belongs_to :issue end end end
@string = "hello world" describe 'string methods' do context 'chop' do it 'returns a new string with the last char removed (also has a permanent version)' do end end context 'clear' do it '(pointlessly given reassignment?) removes all chars in the string' do expect("hello".clear).to be_empty end ...
require('minitest/autorun') require_relative('../warehouse_picker') class TestWarehouse <Minitest::Test def setup @a_row = { a10: "rubber band", a9: "glow stick", a8: "model car", a7: "bookmark", a6: "shovel", a5: "rubber duck", a4: "hanger", a3: "bl...
cask 'sonos-s1' do version '11.2' sha256 '1a98300bd16bb2f727eb1921db80777cc23178a483d56b44a9bb5d95d9ea6602' # 1a98300bd16bb2f727eb1921db80777cc23178a483d56b44a9bb5d95d9ea6602 SonosDesktopController112.dmg # download page: https://support.sonos.com/s/downloads?language=en_US url "https://update-sof...
lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'sinatra/shopified/version' Gem::Specification.new do |spec| spec.name = 'sinatra-shopified' spec.version = Sinatra::Shopified::VERSION spec.authors = ['Tyler King'] spec.email ...
# == Schema Information # # Table name: courts # # id :integer not null, primary key # name :string # address :text # longitude :string # latitude :string # summary :string # google_map_link :string # phone :string # indoor_courts :integ...
class CommentsController < ApplicationController before_action :set_user before_action :set_post before_action :set_comment, only: [:destroy, :edit, :update] before_action :signed_in_user, only: [:create] def create @comment = @post.comments.new(comment_params) @comment.user_id = current_user.id ...
# frozen_string_literal: true require 'pry' class Cult attr_reader :name, :location, :founding_year, :slogan attr_accessor :follower @@all = [] def initialize(name, location, founding_year, slogan) @name = name @location = location @founding_year = founding_year @slogan = slogan @@all <<...
# Create a 2-Player math game where players take turns to # answer simple math addition problems. # A new math question is generated for each turn by # picking two numbers between 1 and 20. # The player whose turn it is is prompted the question # and must answer correctly or lose a life. # Both players start with 3 li...
#### # # A charge that is applied to a property's account. # # A charge represents the type, amount and, through due_ons, the date that # a property should become due a charge. # # The code is part of the charge system in the accounts. Charges are # associated with a property's account. When an operator decides they wa...
json.array!(@stores) do |store| json.extract! store, :id, :name, :email, :open, :image, :photos, :tags, :description, :lat, :lng, :votes, :props json.url store_url(store, format: :json) end
class Persons::StoragesController < ApplicationController before_filter :authenticate_user! before_action :set_storage, only: [:show, :edit, :update, :destroy] layout "user_dashboard" load_and_authorize_resource def index @per_page = params[:per_page] || 10; @storages = current_user.company.storages....
module Sdc3 module StructHelper def members_to_b(*names) return unless names names.each do |mem| val = self[mem].downcase if self[mem] self[mem] = (val == '1' || val == 'yes' || val == 'true') end end def members_to_i(*names) return unless names ...
class ApplicationController < ActionController::Base protect_from_forgery helper_method :current_user, :medusa_user?, :safe_can? def route_not_found render file: Rails.public_path.join('404.html'), status: :not_found, layout: false end protected def set_current_user(user) @current_user = user ...
# Namespace that maps to `Mdm::Module` and `Metasploit::Framework::Module` and contains constants and mixins to # DRY the implementation of the in-memory and in-database models in those namespaces. module Metasploit::Model::Module extend ActiveSupport::Autoload autoload :Action autoload :Ancestor autoload :Arc...
class AddFieldLabelToConfigurationDefinitions < ActiveRecord::Migration def change add_column :configuration_definitions, :field_label, :string end end
# frozen_string_literal: true # == Schema Information # # Table name: authentication_tokens # # id :integer not null, primary key # body :string # expires_in :integer # ip_address :string # last_used_at :datetime # user_agent :string # created_at :datetime not null # ...
# Controller handling admin activities class AdminController < ApplicationController require_dependency 'RMagick' before_filter :authorize def index end def news @news = NewsItem.find(:all, :order => "created_at desc", :limit => 10) end def new_news @news = NewsItem.new end def create_...
class Beer require 'csv' attr_reader :name, :manf def initialize name, manf @name = name @manf = manf end def == another_beer return (@name == another_beer.name and @manf == another_beer.manf) end def self.all_beers $client.query("SELECT * FROM `beers`").map do |beer| Beer.new(bee...
# -*- coding: utf-8 -*- module Mushikago # Mushikago SDK for Ruby のバージョン VERSION = '2.4.2' end
module Pantograph module Actions class GitPullTagsAction < Action def self.run(params) Actions.sh('git fetch --tags') end def self.description 'Executes a simple `git fetch --tags` command' end def self.authors ['johnknapprs'] end def self.is_su...
class CreateMutableSettings < ActiveRecord::Migration def self.up create_table :mutable_settings do |t| t.belongs_to :cobrand t.string :key t.text :value t.timestamps end add_index :mutable_settings, :cobrand_id add_index :mutable_settings, [:cobrand_id, :key], :un...
# Dado el siguiente string y caracter, crear un método que reciba como parámetro el string # y el caracter. Luego debe buscar si existe ese caracter dentro del string. # hint: El método .include? de un string busca si un caracter # o string dado está contenido en éste. cadena = 'Hola Mundo!' caracter = 'o' def inclu...
FactoryGirl.define do factory :model do sequence(:name) {|n| "#{Faker::Name.name} #{n}"} make end end
class AccTest def pub puts "pub is a public method." end public :pub def priv puts "private is a private method." end private :priv end #=> AccTest p acc = AccTest.new #=> #<AccTest:0x007fec0a367380> p acc.pub #=> pub is a public method. p acc.priv #=> NoMethodError: private method `priv' called ...
# frozen_string_literal: true # typed: strict module WorkOS module Types # This DirectoryStruct acts as a typed interface # for the Directory class class DirectoryStruct < T::Struct const :id, String const :name, String const :domain, String const :type, String const :state,...
class CreateIssuedLettersTypeOfIssuedLetters < ActiveRecord::Migration def change if !table_exists? :issued_letters_type_of_issued_letters create_table :issued_letters_type_of_issued_letters do |t| t.integer :issued_letter_id t.integer :type_of_issued_letter_id t.timestamps end e...
require "test_helper" describe CustomersController do it "must get index" do # Act get customers_path body = JSON.parse(response.body) # Assert expect(body).must_be_instance_of Array expect(body.length).must_equal Customer.count # Check that each customer has the proper keys fields ...
require 'rails_helper' require 'swagger_helper' RSpec.describe Api::V1::ConsumersController, type: :request do include AuthHelper CONSUMER_ROOT = 'consumer'.freeze CONSUMER_TAG = 'Consumers'.freeze describe 'Consumers API', swagger_doc: 'v1/swagger.json' do let!(:user_one) { create(:user, :consumer_user) ...
RSpec.describe 'OrderGroup' do let(:order_group) { ::RSpec::Mocks::OrderGroup.new } describe '#consume' do let(:ordered_1) { double :ordered? => true } let(:ordered_2) { double :ordered? => true } let(:unordered) { double :ordered? => false } before do order_group.register unordered or...
class DNAarray attr_reader :height #******************* #Initialization of a DNA array #******************* #4 modes: takes an array (of strings or of DNAsequences), takes a string (path to a file) or take a single DNA sequence def initialize(info, data = 0) return _fastinit(info) if $exec == 'real' #In...
module Reciter class Parser def parse(sequence) return [] if sequence.nil? || sequence.empty? validate_format(sequence) sequence. split(';'). map {|subsequence| if subsequence.include?('-') r = Range.new(*subsequence.split('-').map(&:to_i)) raise InvalidIn...
class PackagesController < ApplicationController before_action :set_user, only: [:new, :create] def new @package = Package.new end def create @package = Package.new(params_package) @booking = current_user.bookings.find_by(status: "pending") @package.booking = @booking @package.user = curre...
class ModeloAgenda::Contacto attr_accessor :dni,:nombre,:apellidos,:email,:telefono,:direccion def initialize (dni,nombre,apellidos,email,telefono,direccion) @dni = dni @nombre = nombre @apellidos = apellidos @email = email @telefono = telefono @direccion = direccion #también se ...
require 'nokogiri' require 'open-uri' require 'openssl' class Scraper attr_accessor :source, :name def initialize(source, name) @source = source @name = name @AppRoot = File.join(Dir.pwd, name) end def open(*args) super *args, allow_redirections: :safe, ssl_verify_mode: OpenSSL::SSL::VERIFY_N...
# 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' feature 'User view recipe list' do scenario 'successfully' do user = User.create!(email: 'carinha@mail.com', password: '123456') recipe_list = RecipeList.create(user: user, name: 'coisas gostosas') other_user = User.create!(email: 'carinho@mail.com', password: '123456') oth...
class CreateRestaurants < ActiveRecord::Migration def change create_table :restaurants do |t| t.string :name t.string :address t.text :description t.string :phone t.string :email t.integer :user_id t.boolean :deliverable t.boolean :shisha_allow t.boolean :disa...
require 'spec_helper' require 'vcr_helper' describe "Parking" do before(:each) do CentreServiceNoticeService.stub(:fetch) end describe "a centre without parking" do before(:each) do VCR.use_cassette('knox_without_parking') do get centre_info_path(centre_id: 'knox') end end ...
class CreateAcentros < ActiveRecord::Migration[5.1] def change create_table :acentros do |t| t.references :aempresa, foreign_key: true t.string :nombre t.string :descripcion t.string :direccion t.integer :numero t.string :comuna t.string :region t.string :lat ...
class My::BooksController < ApplicationController def index @newbook = Book.new end def show @book = Book.find(params[:id]) respond_to do |format| format.html format.pdf do render pdf: @book.title, show_as_html: params.key?('debug'), margin: { top...