text
stringlengths
10
2.61M
FactoryGirl.define do factory :experience do company_name "MyString" job_title "MyString" location "MyString" description "MyText" applicant_detail nil end end
class << ActiveRecord::Base # Re-sorts results to match input. def find_in_order(ids, *args) ids.flatten! records = find ids, *args ids.map { |id| records.find { |record| record.id == id.to_i }} end end
Facter.add("iis_status") do confine :kernel => :windows setcode do iis_status = Facter::Util::Resolution.exec("powershell.exe -ExecutionPolicy Unrestricted -Command (Get-Service -ErrorAction SilentlyContinue 'W3SVC').Status") if iis_status == nil or iis_status == '' iis_status = 'Not installed' en...
describe Metacrunch::ULBD::Transformations::AlephMabNormalization::AddSuperorder do transformation = transformation_factory(described_class) # check for superorders of secondary forms (mab 623 and 629) define_field_test '000806191', superorder: 'HT006670284' define_field_test '000844686', superorder: 'HT007082...
require 'rails_helper' RSpec.describe "User registration form" do it "can create new user" do visit registration_path expect(current_path).to eq(registration_path) email = "hi@here.com" password = "hello" password_confirmation = "hello" fill_in 'user[email]', with: email fill_in 'u...
# frozen_string_literal: true module CmeFixListener # Make HTTP requests to CME. # Given the username, password, and url from the account it will POST to CME with the correct header and body. # If the requests fails it will retry twice and then bail. class TradeCaptureReportRequester include HTTParty ...
module IControl::LocalLB ## # The ProfileAuth interface enables you to manipulate a local load balancer's authentication # profile. class ProfileAuth < IControl::Base set_id_name "profile_names" class ProfileAuthStatisticEntry < IControl::Base::Struct; end class ProfileAuthStatistics < IControl::B...
class Api::V3::Models class << self def patient {type: :object, properties: { id: {"$ref" => "#/definitions/uuid"}, gender: {type: :string, enum: Patient::GENDERS}, full_name: {"$ref" => "#/definitions/non_empty_string"}, status: {type: :string, enum: Patient::STAT...
FactoryGirl.define do sequence :section_name do |n| "section_#{n}" end factory :section do active true name { Factory.next(:section_name) } end sequence :product_name do |n| "product_#{n}" end factory :product do active {true} name { Factory.next(:product_name) } end factory :discount do start...
class DtEmpresaRequestSerializer < ActiveModel::Serializer attributes :id, :usuario, :fecha, :titulo, :estado, :DT_RowAttr, :bg_color, :state_color, :rating def usuario object.user.decorate.full_name end def titulo object.request.title || "" end def fecha object.date.strftime("%d/%m/%y ...
class AddCoordinatesToKebabShops < ActiveRecord::Migration[5.2] def change add_column :kebab_shops, :latitude, :float add_column :kebab_shops, :longitude, :float end end
class SessionsController < ApplicationController def new end def create @user = User.find_by(email: params[:session][:email].downcase) if @user && User.authenticate(@user.id, params[:session][:password]) if log_in(@user) flash[:notice] = "Welcome #{@user.name if @user.name} !" re...
# == Schema Information # # Table name: todos # # id :integer not null, primary key # title :string # is_complete :boolean default(FALSE), not null # created_at :datetime not null # updated_at :datetime not null # class TodoSerializer < ApplicationSerializer at...
module Spider class Rules attr_reader :accept attr_reader :reject def initialize(options={}) @accept = [] @reject = [] @accept += options[:accept] if options[:accept] @reject += options[:reject] if options[:reject] end def accept?(data) ...
# Define field validators for our various dynamic field types. DynamicAnnotation::Field.class_eval do def field_validator_type_geojson errormsg = I18n.t(:geolocation_invalid_value) begin json = JSON.parse(self.value) geojson = Geojsonlint.validate(json) errors.add(:base, errormsg) unless ge...
class AddOrderToPosts < ActiveRecord::Migration[5.0] def change add_column :posts, :order, :integer, default: 0 end end
# frozen_string_literal: true # == Schema Information # # Table name: students # # id :integer not null, primary key # country_of_nationality :text # deleted_at :datetime # dob :date not null # estimated_dob :boolean default...
module ApplicationHelper def flash_class(level) case level when :notice then "info" when :error then "error" when :alert then "warning" end end def icon(icon_type) content_tag(:i, '', :class => "icon-#{icon_type}") end def search_conditions_count(search_hash = {}) co...
require 'pry' require 'rest-client' require 'json' def get_api_equip all_equip = RestClient.get('http://www.dnd5eapi.co/api/equipment/') all_equip_hash = JSON.parse(all_equip) all_equip_hash["results"] end def inner_url(hash) info_string = RestClient.get("#{hash["url"]}") info_hash = JSON.parse(in...
class Reaction < ApplicationRecord SENTIMENTS = %w( Like Love Sad Confuse Angry ) belongs_to :idea end
class ConstructionsController < ApplicationController before_action :set_construction, only: [:show, :edit, :update, :destroy] # GET /constructions # GET /constructions.json def index @constructions = Construction.all end # GET /constructions/1 # GET /constructions/1.json def show end # GET /...
class Api::TokensController < ApplicationController protect_from_forgery :except => :create def create @user = User.find_by_email params[:email] if @user.nil? render json: {message: "Invalid email or password"} else if @user.valid_password? params[:password] if !@user.authentication...
# -*- coding: utf-8 -*- ############################################################################### # # Stock - A class for writing Excel Stock charts. # # Used in conjunction with Chart. # # See formatting note in Chart. # # Copyright 2000-2011, John McNamara, jmcnamara@cpan.org # Convert to ruby by Hideo NAKAMURA...
class User < ApplicationRecord has_paper_trail # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :recoverable, :trackable has_one :personel_detail has_one :professional_detail accepts_nested_att...
# 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...
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{has_inherited} s.version = "2.2.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_...
require "rufus/tokyo" require "mongo" class Hash def hash_with(keys) Hash[keys.zip values_at(*keys)] end def force_unicode() k = keys Hash[k.zip values_at(*k).collect{ |v| v.force_encoding "UTF-8"}] end def tokyo_to_mongo unicode = force_unicode { _id: unicode[:pk], userna...
class PhotoSerializer include FastJsonapi::ObjectSerializer attributes :id, :caption, :url def url object.photo.url end end
class GigsController < ApplicationController before_action :authenticate_user!, except: [:index, :search, :show] #user to edit this own gig def index @gigs = Gig.all.order_list(params[:sort_by]).page(params[:page]).per(10) @users = User.all end def new @gig = Gig.new end def create @gig = Gig.new(gig_params)...
class AnswerUser < ActiveRecord::Migration[5.1] def change add_reference :answers, :user end end
require 'rm_vx_data' if false =begin ============================================================================== ■ Add-on Opzioni di Holy87 versione 1.0.01 Difficoltà utente: ★ Licenza: CC. Chiunque può scaricare, modificare, distribuire e utilizzare lo script nei propri progetti, sia amat...
# # $Id: utils.rb,v 1.12 2003/06/03 18:46:47 mneumann Exp $ # module DBI module Utils module ConvParam def conv_param(*params) params.collect do |p| case p when ::Date DBI::Date.new(p) when ::Time DBI::Timestamp.new(p) else p end ...
class RemoveOptionDescriptions < ActiveRecord::Migration def self.up remove_column :options, :description end def self.down add_column :options, :description, :string, :null => true, :default => nil end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :product do sequence :name do |n| "Product #{n}" end shopify_product_id {rand(10000000)} last_shopify_sync {DateTime.now - rand(5).days} end end
require 'minitest' require 'minitest/autorun' require 'minitest/pride' require './lib/credit_check' require 'pry' class CreditCheckTest < Minitest::Test def test_it_exists check = CreditCheck.new("5541808923795240") assert_instance_of CreditCheck, check end def test_it_can_accept_number check = Cr...
module Haenawa module Commands class Window < Command def validate; end def render ensure_capture do <<-EOF last_handle = page.driver.browser.window_handles.last page.driver.browser.switch_to.window(last_handle) EOF end end end end end
# -*- mode: ruby -*- # vi: set ft=ruby : VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.ssh.username = "vagrant" config.ssh.forward_agent = true config.vm.provision :ansible do |ansible| ansible.playbook = "provisioning/playbook.yml" end name = "VIRTPWN" ...
# encoding: utf-8 require "net/http" require "feedzirra" # # Module must be named "Api" # module Api # # Class must be named "Deals" # # Below functions are all required, feel free to add any other functions you need. # class Deals attr_accessor :url, :deals # # REQUIRED ...
# frozen_string_literal: true module PgTagsOn module ActiveRecord # ActiveRecord::Base extension module Base extend ActiveSupport::Concern class_methods do def pg_tags_on(name, options = {}) raise PgTagsOn::ColumnNotFoundError, "#{name} column not found" unless column_names.inc...
namespace :import do desc "Import teams from csv" task teams: :environment do filename = File.join Rails.root, "csv_files/teams.csv" CSV.foreach(filename, {col_sep: ";", headers: true}) do |row| team_hash = row.to_h team_hash["conference_id"] = team_hash["conference_id"].to_i team = Team....
class Tutorial def ruby print("Ruby") puts "Which Framework you want to learn in ruby ?" framework = gets.chomp self.class.send(:define_method, framework) do puts "Welcome to #{framework} of Ruby" end end def java print("Java") puts "Which Framework you want to learn in Java ?" ...
# String is generally pretty functional, but sometimes you need # a couple of small convienence methods to make working with really # long or really funky strings easier. This will indent all lines # to the margin of the first line, preserving sunsequent indentation # while still helping reign in HEREDOCS. class String...
#! /usr/bin/env ruby # coding: utf-8 # # colorz # Complex domain coloring # Usage: colorz [options] FUNCTION # Options: # -i INPUT_FILE # -o OUTPUT_FILE # -r MIN,MAX # -s XxY require "cmath" require "chunky_png" require "rgb" require "optparse" include Math class DomainColoring attr_accessor :width, :h...
module DynaForm class Submission def initialize(model, variables, attributes) @model = parse_model(model) @variables = variables.map(&:to_sym) @attributes = attributes.clone end def submit attrs = @attributes.select { |k, _| @variables.include?(k.to_sym) } class_name =...
class Api::UsersController < ApplicationController skip_before_action :authenticate_user!, only: [:create, :show] def create perform User::CreateAction do return render json: @action.record end render_action_error @action end def show perform User::ShowAction do return render json:...
module Tact class Contact < ActiveRecord::Base has_many :phone_numbers, dependent: :destroy has_many :emails, dependent: :destroy validates :last_name, uniqueness: { scope: :first_name } before_validation do first_name.upcase! last_name.upcase! end def full_name first_name ...
# frozen_string_literal: true module Api module V1 class CommentsController < ApiController before_action :verify_authenticity_token, only: %i[create destroy] def create validate Comments::Create.run(photopost_id: params[:photopost_id], user: @api_user, ...
Pod::Spec.new do |s| s.name = "LFCommon" s.version = "1.0.0" s.summary = "A Common Library on iOS." s.homepage = "https://github.com/lifei321/LFCommon" s.license = 'MIT' s.author = { "lifei" => "924906515@163.com" } s.source ...
class YoutubeAutomator < Formula desc "watches youtube for new videos" homepage "https://gitlab.com/lukasdanckwerth/youtube-automator" url "git@gitlab.com:lukasdanckwerth/youtube-automator.git", :using => :git, :tag => "0.0.7" version "0.0.7" depends_on "youtube-dl" depends_on "jq" depends_on "imagemagi...
class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.integer :user_id # User ID, primary key. Every tournament has user_key which points to this. t.string :first_name # First name t.string :sur_name # Surname / last name #t.string :email ...
class RmDay1PickupFromUsers < ActiveRecord::Migration[6.0] def change remove_column :users, :day1_pickup, :boolean, null: false end end
namespace :db do namespace :migrate do desc "Preview table updates" task :preview => :environment do if File.exists?('db/models.yml') EZ::DomainModeler.update_tables(false, true) else puts "Nothing to preview." end end end end namespace :ez do desc "Generate mode...
require 'spec_helper' describe Puppet::Type.type(:boot_environment) do # Modify params inline to tests to change the resource # before it is generated let(:params) do { :name => "be1", :ensure => :present, :description => 'new be', } end # Modify the resource inline to tests w...
class RenameImageColumnToArticles < ActiveRecord::Migration[5.0] def change rename_column :articles, :image, :thumbnamil end end
class AddAboutFormattedToUsers < ActiveRecord::Migration def change add_column :users, :about_formatted, :text add_column :groups, :about_formatted, :text end end
class Fiber begin require 'logg' include Logg::Machine log.as(:debug) do |msg| if $DEBUG puts "[DEBUG] #{msg}" end end log.debug 'output ready' rescue LoadError def self.log Object.new.extend( Module.new do def debug(*args, &block) # do nothing ...
require 'rails_helper' feature 'creates user ink' do let!(:my_ink) { FactoryGirl.create(:ink) } let!(:user) { FactoryGirl.create(:user) } let!(:another_user) { FactoryGirl.create(:user) } scenario "inauthenticated user can't add ink to collection" do visit ink_path(my_ink) expect(page).not_to have_co...
class Category < ApplicationRecord validates :title, :presence => true, :uniqueness => true has_many :boards, dependent: :destroy end
class Api::ResponsesController < ApplicationController def create @response = Response.new(response_params) if @response.save Pusher.trigger('response_' + @response.poll_id.to_s, 'response_submitted', {}) render :show else render json: @response.errors.full_messages end end def...
class List < ApplicationRecord include PublicActivity::Model tracked owner: :user has_many :book_lists, :dependent => :destroy has_many :books, -> { distinct }, through: :book_lists belongs_to :user end
require 'open-uri' module Tr4n5l4te class Translator START_PAGE = 'https://translate.google.com'.freeze attr_reader :sleep_time, :agent def initialize(args = {}) @sleep_time = args.fetch(:sleep_time, 2) @agent = Agent.new end def translate(text, from_lang, to_lang) puts "Tran...
class AddColumnOrderOfServiceIdToOrderOfServiceDetails < ActiveRecord::Migration def change add_column :order_of_service_details, :order_of_service_id, :integer end end
require 'rails_helper' RSpec.describe Vote, type: :model do it { should have_valid(:rating).when(true, false) } it { should_not have_valid(:rating).when(nil, '') } it { should have_valid(:user_id).when(1, 2) } it { should_not have_valid(:user_id).when(nil, '') } it { should have_valid(:review_id).when(1, 2...
class Api::V1::ColorsController < ApplicationController def index @colors = Color.all render json: @colors end def create @color = Color.new(color_params) if @color.save render json: @color, status: 201 else render json: {error: @color.errors.full_messages}, status: 500 end ...
FactoryBot.define do factory :todo do title 'Sample title' text 'Sample text' end end
class CreateLocations < ActiveRecord::Migration def change create_table :locations do |t| t.string :address, null: false t.string :city, limit: 120 t.string :state, limit: 2 t.string :zip, null: false, index: true t.decimal :latitude t.decimal :longitude t.references :res...
class Genre extend Concerns::Findable # extends the Concerns::Findable module attr_accessor :name @@all = [] # is initialized as an empty array def initialize(name) # accepts a name for the new artist / retrieves the name...
class CreateUserTransactions < ActiveRecord::Migration[6.1] def change create_table :user_transactions do |t| t.decimal :net_amount, null: false t.decimal :fees, null: false t.decimal :exchange_rate, null: false t.string :country_from, null: fals...
require 'net/http' require 'uri' require 'optparse' class Vm < Linkbot::Plugin Linkbot::Plugin.register('vm', self, { :message => {:regex => /\A!vm (.+)/, :handler => :on_message, :help => :help} } ) create_log(:vm) def self.on_message(message, matches) if Linkbot::Config["plugins"]["vm"]....
require 'spec_helper' describe Version do it "has a valid factory" do FactoryGirl.build(:version).should be_valid end before :each do @version = FactoryGirl.build(:version) end it { should belong_to(:campaign) } it { should have_many(:demographics) } it { should have_many(:audiences).throu...
# encoding: UTF-8 module OmniSearch #Indexes::Trigram class Indexes::Trigram < Indexes::Base STORAGE_ENGINE = Indexes::Storage::Trigram def build_index(collection) values = collection.map { |x| x[:value] } Trigram.build_index(values) end end end
class Charla < ActiveRecord::Base belongs_to :author has_many :participantes end
class Polyml < Formula desc "Standard ML implementation" homepage "http://www.polyml.org" url "https://github.com/polyml/polyml/archive/v5.7.tar.gz" sha256 "19340d8e9cea15c3fd786dde27028cd2947608955a376d1317a20268c8a19279" head "https://github.com/polyml/polyml.git" bottle do sha256 "e533dc791e3583ad45...
lane :carthage do # carthage must run with --no-use-binaries to avoid this lldb crash # https://github.com/Carthage/Carthage/issues/924 carthage(platform: 'iOS', use_binaries: false) end
class AddLockVersionToSourcesAndDynamic < ActiveRecord::Migration def change add_column :annotations, :lock_version, :integer, default: 0, null: false add_column :sources, :lock_version, :integer, default: 0, null: false end end
class CommentsController < ApplicationController def new # Pull in ID and find photo @id = params[:id] @photo = Photo.find(@id) # Specify to post errors to html & to use _header partial @user = User.new if session["user_id"] == -1 then return else @current_user = User.find(sessi...
#tag: skill #============================================================================== # +++ MOG - Active Chain Commands (v3.3) +++ #============================================================================== # By Moghunter # https://atelierrgss.wordpress.com/ #=====================================...
class StructureDeclaration < ASTNode def declare "class #{normalized_class_name} < IControl::Base::Struct; end" end def members children_filtered(:of_class => StructureMember) end def compile(buffer = nil) if parent.properties[:klass] == ModuleDeclaration module_file = parent.normalized_f...
require 'rubygems' require 'simplecov' SimpleCov.start require 'bundler' Bundler.require require 'pry' # This file is copied to spec/ when you run 'rails generate rspec:install' ENV["RAILS_ENV"] ||= 'test' # require File.expand_path("../../config/environment", __FILE__) require 'webmock/rspec' require 'vcr_setup' #req...
module Exceptions class InvalidMoveException < Exception end class NotYourTurnException < Exception end end
require 'rails_helper' RSpec.describe EventsController, type: :controller do =begin context 'GET #edit' do it 'returns a success response' do event = Event.create!(title: 'Title', start_date: DateTime.now, end_date: DateTime.now + 10.days ) get :edit, params: {id: event.id} ...
# blueprint.rb require 'yaml' require 'succ/hash/merge' require 'succ/object' module ARTML def self.prefix @@prefix ||= '' end def self.prefix=(prefix) @@prefix = prefix end ### ## ##### #### ## # ## ##### ## # # ## # ## # ## # ## ## ## # ## # ## # ## # ## ...
class UsersClubsController < ApplicationController layout 'bootstrap' before_action :find_club def index @users_clubs = UsersClub.joins(:club, :user, :user_type).all end def show @users_club = UsersClub.joins(:club, :user, :user_type).find(params[:id]) end def new @users_club = UsersClub...
=begin Given("I am on the Ferguson desktop site") do visit "https://ferguson.com" @login_page.logon('test_123@mailinator.com', 'Admin123') end When("I type ccc on the search field") do @header_page.Find_Search("CCC") end When("I click on Enter button") do @header_page.ClickFind_Button end Then("I should...
require 'spec_helper' describe ExamRoom::Practice::McqStem do before :each do setup_for_models end it "must have a stem" do practice_stem = ExamRoom::Practice::McqStem.new practice_stem.valid? practice_stem.errors.should include(:stem) end describe "checks is correct" do befor...
class MultiStalker def initialize(search_terms, num_pages = 10) @search_terms = search_terms @num_pages = num_pages @stalkers = [] end def run() begin release_stalkers join_threads stop_stalking rescue Exception => e p e stop_stalking end end private ...
module Api class Error attr_reader :code, :message def initialize(options = {}) %i[code message].each do |key| unless options.has_key?(key) raise MissingParameter.new(self.class, key) end end @code = options[:code] @message = options[:message] end ...
class GoalsController < ApplicationController before_action :authenticate before_action :requires_owner, only: [:edit, :update, :destroy, :complete, :reactivate] def index if current_user.id == params[:user_id].to_i @goals = Goal.where(user_id: params[:user_id]) else @goals = Goal.where(user_...
# 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...
json.array!(@infos) do |info| json.extract! info, :id, :referencia, :talla, :talla_promedio, :color, :tela, :descripcion, :especificaciones, :modulo_id, :ficha_id json.url info_url(info, format: :json) end
require 'versatile_rjs/proxy/jquery/element_set_proxy' module VersatileRJS class Proxy module Jquery class SelectorProxy < ElementSetProxy include ::VersatileRJS::Proxy::SelectorProxy private def statement_for_selector(selector) "$('#{selector}')" end end ...
class AddSlugToMinorities < ActiveRecord::Migration def up add_column :minorities, :slug, :string, :null => false end def down remove_column :minorities, :slug end end
class CreateEntityBanks < ActiveRecord::Migration def change create_table :entity_banks do |t| t.integer :entity_id t.integer :bank_id t.integer :money_id t.string :account_type t.string :account_number t.string :account_detraction t.string :cci t.timestamps en...
require 'test_helper' class TaskTest < ActiveSupport::TestCase test 'a completed task is complete' do task = Task.new refute(task.complete?) task.mark_completed assert(task.complete?) end test 'an uncompleted task does not count towards velocity' do task = Task.new(size: 3) refute(task....
class UserSerializer < ActiveModel::Serializer attributes :id, :created_at, :avatar, :gov_approved_id, :first_name, :last_name # attribute :avatar_url do |user| # Rails.application.routes.url_helpers.rails_blob_path(user.avatar) if user.avatar.attached? # end # attribute :rooms do |user| # ...
class Answer < ApplicationRecord MAX_BEST_ANSWERS_COUNT = 1 include Commentable include Likable belongs_to :question, touch: true belongs_to :user has_many_attached :files has_many :links, dependent: :destroy, as: :linkable accepts_nested_attributes_for :links, reject_if: :all_blank validates :bod...
require "tinify" require "pathname" task :img do Tinify.key = ENV["TINIFY_API_KEY"] pn = Pathname.new(ARGV[1]) dest_filename = pn.dirname().join(pn.basename(".*").to_s() + "-compressed.jpg") tinify_source = Tinify.from_file(pn.realpath()) tinify_source.to_file(dest_filename) puts "Written fi...
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "asciify/version" Gem::Specification.new do |s| s.name = "asciify" s.version = Asciify::VERSION s.authors = ["Brian Rose", "Anthony Navarre"] s.email = ["brian@heimidal.net", "me@anthonynavarre.com"] s.homepag...
class GamesController < ApplicationController def index @category = Category.find(params[:category_id]) @games = @category.games respond_to do |f| f.html f.json { render json: { category: @category,games: @games } } end end def show @category = Category.find(params[:category_id])...
class StudentsController < ApplicationController before_action :set_student, only: [:show, :edit, :update, :destroy] before_action :set_lop, only: [:show, :create, new, :edit, :update, :destroy] # GET /students # GET /students.json def index @lop = Lop.find(params[:lop_id]) end # GET /students/1 # ...