text
stringlengths
10
2.61M
class Story < ApplicationRecord has_and_belongs_to_many :character has_many :stories_sequence has_many :stories_note belongs_to :universe belongs_to :user belongs_to :genre end
cask 'sonos-s2' do version :latest # I could get a version from the url but this app is auto update so why bother? sha256 :no_check # 7dcab807a75f9faef5941f96eff3e823771187e9f6fea3892d2674f192c0a02f SonosDesktopController120.dmg # download page: https://support.sonos.com/s/downloads?language=en_US ...
class PastExam < ApplicationRecord belongs_to :course belongs_to :uploader, class_name: :User mount_base64_uploader :file, PastExamUploader def serializable_hash(options = nil) options = options.try(:dup) || {} super({ **options, except: [:uploader_id, :course_id] }).tap do |result| result[:uploa...
class DeleteColumnOnComments < ActiveRecord::Migration[6.0] def change remove_column :comments, :user_park_id, :integer end end
module Exercise module Fp class << self # Обратиться к параметрам фильма можно так: # film["name"], film["rating_kinopoisk"], film["rating_imdb"], # film["genres"], film["year"], film["access_level"], film["country"] def rating(array) filtered_ratings = array.reject { |film| film['...
# EventHub module module EventHub # Message class class Message include Helper VERSION = "1.0.0".freeze # Headers that are required (value can be nil) in order to pass valid? REQUIRED_HEADERS = [ "message_id", "version", "created_at", "origin.module_id", "origin.type"...
task :guard => :"guard:default" namespace :guard do desc "Run guard with the default adapter" task :default do system "guard" end desc "Run guard in WIP mode with the default adapter" task :wip do system "GUARD_MODE=wip guard" end desc "Run guard with the HTTP adapter" task :http do syste...
#!/usr/bin/env ruby require 'bundler/setup' require 'rubygems' require 'sinatra' require 'json' require 'logger' CONFIG_LOCATION = '/etc/nagios/conf.d/'.freeze # Initialize logger class Mylog def self.log if @logger.nil? @logger = Logger.new STDOUT @logger.level = Logger::DEBUG @logger.dateti...
require 'spec_helper' describe 'bluepill' do let(:facts) do { :operatingsystem => 'CentOS', :operatingsystemrelease => '6.3' } end context 'default parameters' do it do should contain_bluepill__rsyslog should contain_package('activesupport').with({ :provider => 'gem' }) ...
class CreateConcepts < ActiveRecord::Migration def change create_table :concepts do |t| t.string :name t.float :percentage t.float :amount t.string :code t.float :top t.timestamps end end end
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundat...
class User < ApplicationRecord # Include default users modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable belongs_to :creator, foreign_key: :creator_id, class_na...
class ChatRoomsController < ApplicationController def index @user = current_user # @me = User.find(params[:user_id]) @profile = current_user.profile @chat_rooms = @user.owned_chatrooms + @user.chat_rooms # @chat_room = @me.user_chat_rooms # @user_name = @user.profile.fname if params...
class ActsAsLoggable::UserAction < ActiveRecord::Base attr_accessible :action has_many :logs def to_s self.action end end
class AddFromShareToSharePrizes < ActiveRecord::Migration def change add_column :share_prizes, :from_share, :string end end
require "libblacklist/version" require 'ffi' module Libblacklist module Action AUTH_OK = 0 AUTH_FAIL = 1 ABUSIVE_BEHAVIOUR = 2 BAD_USER = 3 end module LibBlacklist extend FFI::Library ffi_lib 'blacklist' attach_variable :errno, :int # struct blacklist...
=begin AUTOSALVATAGGIO v1.0 Questo script serve per salvare automaticamente il gioco in determinate occasioni. =end #============================================================================== # ** Vocab #============================================================================== module Vocab def self.autosave...
class CheckInput def initialize(inp) begin inp = inp.downcase if inp.empty? puts 'Entry was empty.'.red puts ' ' RepeatLetters.new end rescue end case inp.to_s when 'quit', 'q', 'exit' puts 'Quitting, thank you come again.'.light_blue exit end end end
def source '"Here are some beers \u{1f37a} \u{1f37a} \u{1f37a} and pizzas \u{1f355} \u{1f355} \u{1f355}"' end def expected_tokens [ { type: 'T_DOUBLE_QUOTE', value: '"' }, { type: 'T_LITERAL_STRING', value: 'Here are some beers ' }, { type: 'T_QUOTED_UNICODE_CHAR_O...
RESPONSE = '{"gladiator":{"personal_data":{"name": "Staros", "gender":"male", "age":27}, "skills":["swordsman","spearman","bowmen"], "amunition": {"weapon": {"trident":{"damage":"7", ...
require_relative 'servo' class Agent attr_accessor :Q def initialize(servo_1, servo_2, nb_actions, alpha, epsilon, gamma) @Q = Array.new(servo_1.steps*servo_2.steps){Array.new(nb_actions) {rand}} @initial_state = state servo_1, servo_2 @alpha = alpha @epsilon = epsilon @gamma = gamma end ...
class Api::V1::MerchantItemsController < ApplicationController def index merchant = Merchant.find(params[:id]) render json: ItemSerializer.new(merchant.items) end def show item = Item.find(params[:id]) merchant = item.merchant.id render json: MerchantSerializer.new(Merchant.find(merchant)) ...
require_relative 'internal' require_relative 'twitter' require_relative 'rss' require_relative 'configuration' module Noizee class Gestalt def listen if events.empty? then sources.each do |source| events.concat source.get end end events.sort_by!(&:created_at).reverse!...
#! /usr/bin/env ruby-rvm-env 2.1 require 'pathname' require_relative '../utility/lib/executor' require_relative '../utility/lib/ruby_version' class AllProjectPuller def call root_dir = "#{Dir.home}/Sites" all_directories = Pathname.glob("#{root_dir}/apps/*") + Pathname.glob("#{root_dir}/gems/*").reve...
class RStoriesController < ApplicationController # GET /r_stories/new def new @r_story = RStory.new end # POST /r_stories def create #story = RStory.new(params[:story]) story = RStory.new(story_params) story.tags = params[:tags].join(', ') story.save! render plain: story.inspect en...
#!/usr/bin/env ruby require 'rubygems' require 'bundler/setup' require 'optparse' require 'daemons' require 'fileutils' require File.expand_path(File.join(File.dirname(__FILE__), 'lib/hubspot_config')) PWD = File.expand_path(File.dirname(__FILE__)) PIDS_DIR_PATH = File.join(PWD, 'pids') CURRENT_MODE_FILE_PATH = Fi...
class Event < ApplicationRecord validates :name, :location, presence: true validates :description, length: { minimum: 10 } validates :price, numericality: { greater_than_or_equal_to: 0 } validates :capacity, numericality: { only_integer: true, greater_than: 0 } has_many :registrations, dependent: :destroy ...
class BrandsController < ApplicationController layout 'dashboard' def index @brands = Brand.all end def new @brand = Brand.new end def show @brand = Brand.all end def edit @brand = Brand.find(params[:id]) end def update @brand = Brand.find(params[:id]) if @brand.update(...
require_relative "card.rb" class CardDeck attr_accessor :cards, :count def initialize @cards = [] suits = [:Diamonds, :Spades, :Clubs, :Hearts] suits.each do |s| (1..13).each do |r| cards << Card.new(s,r) end end end def count() @cards.length end end
class Address < ApplicationRecord # 購入者住所 belongs_to :purchase end
module Merit # Points are a simple integer value which are given to "meritable" resources # according to rules in +app/models/merit/point_rules.rb+. They are given on # actions-triggered. module PointRulesMethods # Define rules on certaing actions for giving points def score(points, *args, &block) ...
# frozen_string_literal: true # Helper functions for the RSS viewer module RssAppHelpers # It's a utility function so it has :reek:FeatureEnvy def linkify(text) return '' unless !text.nil? && text.is_a?(String) # return the text unchanged if links are already embedded return text if text =~ /<a/ ...
#!/usr/bin/env ruby # $Id$ require 'test/unit' require 'fileutils' require 'tempfile' SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__ # Test TestLineNumbers module class TestLineNumbers1 < Test::Unit::TestCase @@TEST_DIR = File.expand_path(File.dirname(__FILE__)) @@TOP_SRC_DIR = File.join(@@TEST_DIR, '..', 'li...
require 'test_helper' class PortfolioCommentsControllerTest < ActionDispatch::IntegrationTest def setup @comment = comments(:orange) end test "should redirect create when not logged in" do assert_no_difference 'Comment.count' do post comments_path, params: { comment: { content: "Lorem ipsum" } ...
class Api::V1::ApiController < ApplicationController skip_before_action :verify_authenticity_token skip_before_action :redirect_to_new_version! before_action :authenticate! include ActionController::HttpAuthentication::Token::ControllerMethods def array_json(collection, serializer) ActiveModel::Serializ...
class Country < ActiveRecord::Base belongs_to :panel_provider has_many :location_groups, dependent: :destroy has_and_belongs_to_many :target_groups, -> (country) { where(parent_id: nil, panel_provider_id: country.panel_provider_id) } has_many :locations, through: :location_groups end
class Teacher::HomeController < TeachersController before_action :set_university def index @courses = Course.where(teacher_name: current_teacher.name) end private def set_university @university = University.find(current_teacher.university_id) end end
class ApplicationController < ActionController::Base protect_from_forgery before_filter :authenticate_account! def current_character @current_character ||= current_account.character end def current_room @current_room ||= current_account.character.current_room end def current_morph @current...
require_relative 'item' class StandardItem < Item QUALITY_REDUCTION_BEFORE_SELL_IN = 1 QUALITY_REDUCTION_AFTER_SELL_IN = 2 SELL_IN_REDUCTION = 1 def update_quality self.sell_in <= 0 ? past_sell_by_date : within_sell_by_date prevent_quality_from_going_below_zero end def within_sell_by_date sel...
require 'spec_helper' # This spec was generated by rspec-rails when you ran the scaffold generator. # It demonstrates how one might use RSpec to specify the controller code that # was generated by Rails when you ran the scaffold generator. # # It assumes that the implementation code is generated by the rails scaffold ...
require 'spec_helper' describe Admin::CourtsController do render_views before :each do controller.should_receive(:enable_varnish).never sign_in User.create!(name: 'hello', admin: true, email: 'lol@biz.info', password: 'irrelevant') end it "displays a list of courts" do get :index response.sho...
# == Schema Information # # Table name: notifications # # id :integer not null, primary key # user_id :integer # status :integer # created_at :datetime not null # updated_at :datetime not null # notification_type :integer # data ...
class AddPriceIdsToSection < ActiveRecord::Migration def change add_column :sections, :dayof_price_id, :integer add_column :sections, :presale_price_id, :integer remove_column :prices, :section_id end end
# Undo a commit or range of commits. # # This reverse-merges one or more revision into the current working copy. # # > svn undo 45 # > svn undo 45:50 # # This will merge in 45:44 and 50:45 respectively. The source to merge from # is the current working copy URL by default, but you may specify your own: # # > svn ...
class NotAnInt < ArgumentError end class NotPositiveInt < ArgumentError end def put_n(text, times) raise NotAnInt if !times.is_a? Integer raise NotPositiveInt if !times.positive? times.times { puts text } end def echo puts "What do you want to echo?" text = gets.strip puts "How many times do you want to r...
class TranslateDeliveryTypes < ActiveRecord::Migration def up remove_column :delivery_types, :name DeliveryType.create_translation_table!({ :name => :string }, { :migrate_d...
class Api::V1::BackgroundsController < ApplicationController def show background = Background.new(params[:location]) render json: BackgroundsSerializer.new(background) end end
FactoryBot.define do factory :link do name { "Thinknetica" } url { "http://thinknetica.com" } end trait :gist_link do name { "Gist" } url { "https://gist.github.com/jezman/a6c9a6c93f651b8b84ac6e08303e82ed" } end end
# frozen_string_literal: true # This controller contain the methods shared for all admin controller class Admin::ApplicationController < ApplicationController before_action :authenticate_admin! # Set nav for editor's section def nav 'nav_admin' end private # deny access unless current_user is an edi...
class RenameColumn < ActiveRecord::Migration def change rename_column :workunits, :performed_by_id, :performed_by_user_id rename_column :workunits, :confirmed_by_id, :confirmed_by_user_id end end
require 'spec_helper' describe Robot do before :each do @robot = Robot.new end it "should have 50 shield points" do expect(@robot.shield_points).to eq(50) end describe "#wound" do it "should first drain the shield" do @robot.wound(20) expect(@robot.health).to eq(100) ...
require 'csv' require_relative 'base' require_relative 'base_repository' require_relative 'merchant' require_relative 'merchant_repository' require_relative 'invoice' require_relative 'invoice_repository' require_relative 'item' require_relative 'item_repository' require_relative 'invoice_item' require_relative 'invoic...
# -*- encoding : utf-8 -*- require File.dirname(__FILE__) + '/test_helper.rb' require 'module_handler' class Module_First end class Module_Second end describe 'ModuleHandler' do before(:each) do @bot = double() end context "ModuleHandler" do before(:each) do @handler = ModuleHandler.new end...
class LogsController < ApplicationController # def new # @log =Log.new # end def create end ## #Author:Sarah #Creates a new instance of the log # * *Args* : # -+@task+ -> the current task # -+@log+ -> the new instance of the log # * *Returns* : # - nothing # def new @task_result=TaskResul...
class AddIdToAlumno < ActiveRecord::Migration def change add_column :alumnos, :id_carrera, :int end end
require 'rails_helper' RSpec.describe Search do describe '#initialize' do subject { Search.new } context 'when object is created' do it 'should create new object' do expect(subject).to be_kind_of(Search) end it 'should have the correct attrbitus' do expect(subject).to have...
# # useful methods for cleaning the _ dictionary terms # namespace :dictionary do namespace :clean do def argf_file begin STDERR.puts "Found file - #{ARGF.filename}" rescue STDERR.puts $! end end def skip argf_file ARGF.skip # skip clean:proper param argf_file end desc "John Smi...
# Below are the declarations for constants that will be used in various code # files in this gem. module ApplePicker GEM_NAME = 'apple-picker' VERSION = '0.0.0' end
class CouponsController < ApplicationController before_action :authenticate_user! before_action :set_coupon, only: [:show, :disable, :active] def show end def disable @coupon.disabled! # redirect_to @coupon.promotion, notice: "Cupom #{@coupon.code} desabilitado com sucesso" redirect_to @coupon.p...
class Language < ApplicationRecord validates :name, inclusion: { in: %w(ruby css js html), message: "%{name} is not a valid Language" } end
class RemoveRoomsFromUsers < ActiveRecord::Migration def change remove_column :users, :rooms, :string end end
module Jobs class ReceiveMessageJob < Struct.new(:reception_id) def perform @reception = Reception.find(reception_id) receive if @reception.just_arrived? end def receive if @reception.process Notifier.queue_all_notifications else raise "Message could not be receive...
class CreateMultiChannels < ActiveRecord::Migration def change create_table :multi_channels do |t| t.references :user, index: true, foreign_key: true t.references :amazon, index: true, foreign_key: true t.date :date t.string :time t.string :order_num t.string :sku ...
require File.dirname(__FILE__) + '/../../../../spec/spec_helper' require 'haisyo_listener' describe HaisyoListener do before do @room = Room.new(title: 'test room').tap{|x| x.save! } @user = User.new(name: 'test user', screen_name: 'test').tap{|x| x.save! } @message = Message.create(body: "引用元メッセージ", use...
require "formula" require "language/go" class Forego < Formula homepage "https://github.com/ddollar/forego" url "https://github.com/ddollar/forego/archive/v0.13.1.tar.gz" sha1 "63ed315ef06159438e3501512a5b307486d49d5c" head "https://github.com/ddollar/forego.git" bottle do sha1 "9eac8ca38f6a4557b307375...
class TransactionsController < ApplicationController def index @transactions = current_user.transactions.page(params[:page]) end def show end def new @transaction = current_user.transactions.new @categories = current_user.categories end def create @transaction = current_user.transaction...
#!/usr/bin/env ruby # frozen_string_literal: true # Created by Paul A.Gureghian in May 2020. # # This Ruby program keeps track of movie ratings. # # Start of script. # # Create a hash to hold movies / ratings. # movies = { Alien: 10.0, Aliens: 9.0 } puts "\n" puts 'This program allows you to add, update, dis...
module Github class Importer def import!(options = {}) Github::User.each(options) do |user| begin GithubResourcesImportingJob.perform_later(user.login) rescue => e RailsShowcase::ExceptionNotifier.notify(e) end end end end end
module ActiveRecord class Base def self.before_update_filter(callback_method, options = {}) self.set_callback :save, :before do if options[:or_params].nil? && options[:and_params].nil? send callback_method elsif !options[:or_params].nil? && ...
class League < ActiveRecord::Base has_many :teams belongs_to :sheet end
require 'rails_helper' describe StructuredEventSerializer do describe '#to_json' do it 'renders out a string' do event = { description: { text: 'desc' }, name: { text: 'event name' }, start: { local: 'start' }, venue: { ...
require_relative '../lib/cash_register_class' require_relative '../lib/transaction_class' require 'minitest/autorun' require "minitest/reporters" Minitest::Reporters.use! =begin S - set up the necessary objects E - execute the code against the object being tested A - assert the results of the execution T - tea...
RSpec.feature 'Users can edit a post that has been created', type: :feature, js: true do scenario 'User edits a post' do visit('/') click_on('Signup') fill_in('user[username]', with: 'user1') fill_in('user[email]', with: 'test@example.com') fill_in('user[password]', with: 'password') click_on(...
# See GitHubV3API documentation in lib/github_v3_api.rb class GitHubV3API # Provides access to the GitHub Users API (http://developer.github.com/v3/users/) # # example: # # api = GitHubV3API.new(ACCESS_TOKEN) # # # get list of logged-in user # a_user = api.current # #=> returns an instance of ...
require 'roar/decorator' require 'roar/json' module UserRepresenter include Roar::JSON property :first_name property :last_name property :full_name property :email def full_name "#{first_name} #{last_name}" end end
class Resetter < ActionMailer::Base default from: 'admin@po-it.com' def reset(user) @token = user.token mail(to: user.email, subject: 'Password Reset Link') end end
class CreateLimitFees < ActiveRecord::Migration def change create_table :limit_fees do |t| t.integer :period_id t.integer :person_id t.decimal :limit_fee t.timestamp :created_on t.timestamp :updated_on t.string :remark end end end
class Click include RecordData include Mongoid::Document include Mongoid::Timestamps::Created include Geocoder::Model::Mongoid field :ip, type: String field :url, type: String field :article_id, type: String field :user_id, type: String field :country, type: String field :city, type: String field...
module AdminPage module Protocols class Edit < ApplicationPage MEDICATION_LIST_NAME = {id: "medication_list_name"}.freeze MEDICATION_LIST_FOLLOWUP_DAYS = {id: "medication_list_follow_up_days"}.freeze UPDATE_MEDICATION_LIST_BUTTON = {css: "input.btn-primary"}.freeze def update_medication_l...
require 'rubygems' require 'mtest' require File.join(File.dirname(__FILE__), '..', 'lib', 'dicelib') class String def match?(rxp) !match(rxp).nil? end end class Array def each_is?(arg) meth, param = case arg when Class [:is_a?, arg] when Symbol [arg, nil] end ans...
module Brower class Install def initialize(pack) @pack = "../../packages/#{pack}" @outname = pack + ".zip" @name = pack self.get self.install end def get p = open(@pack) packurl = p.gets system("curl #{packurl} -o #{@outname}") p.close end de...
require './spec/spec_helper.rb' def new_connection_url Orientdb::ORM.connection_uri.tap { |uri| uri.database = 'brand_spanking_new' }.to_s end def existing_connection_url Orientdb::ORM.connection_uri.to_s end describe Orientdb::ORM::Database do describe '.exists?', :with_database do it "does not find the...
class CreateItems < ActiveRecord::Migration def change create_table :items do |t| t.references :partida, index: true t.references :unidad_medida, index: true t.string :codigo t.string :nombre t.string :unidad_medida t.string :foto_file_name t.timestamps end end end...
class CreateArticleRelations < ActiveRecord::Migration def change create_table :article_relations do |t| t.integer :kind t.belongs_to :article, foreign_key: true t.integer :related_article_id end end end
class VisitorInfo < ActiveRecord::Base include GeoKit::Geocoders def self.update_analytics(business_card, request, geo_location) user_agent = UserAgent.parse(request.user_agent) if user_agent[0].product == 'Opera' browser = 'Opera' elsif !user_agent[2].nil? && user_agent[2].product == '...
Rails.application.routes.draw do devise_for :doctors, :controllers => { registrations: 'doctor/registrations' } devise_for :patients, :controllers => { registrations: 'patient/registrations' } get 'home/index' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routin...
class Garment < ActiveRecord::Base serialize :properties serialize :options # Used when a garment is not built from random like in the seeded characters. def self.forge! data type = data[:garment_type] data = data.except :garment_type "Garment::#{type.camelize}".constantize.forge! data end d...
class AddColumnDeliveryOrderIdToDeliveryOrderDetails < ActiveRecord::Migration def change add_column :delivery_order_details, :delivery_order_id, :integer end end
class Types::UserType < Types::BaseObject field :id, ID, null: true field :name, String, null: true end
module Events class NoteOnHadoopInstance < Note has_targets :hadoop_instance has_activities :actor, :hadoop_instance, :global end end
class ChangeIdsToIntegers < ActiveRecord::Migration def change change_column :user_events, :user_id, 'integer USING CAST(user_id AS integer)' change_column :user_events, :event_id, 'integer USING CAST(event_id AS integer)' change_column :user_groups, :user_id, 'integer USING CAST(user_id AS integer)' ...
class AddInterstateRebateFields < ActiveRecord::Migration def change add_column :jobs, :interstate_rebate_confirmed, :boolean, :default => true add_column :jobs, :interstate_invoice_confirmed, :boolean, :default => true add_column :jobs, :interstate_rebate_amount, :decimal, :scale => 2, :precision => 12, :d...
class Education < ApplicationRecord belongs_to :website validates :location, :start, :end, :description, presence: true end
require "./script.rb" require "test/unit" class TestTheScript < Test::Unit::TestCase def test_basic expected_hash = { :firstname => "Tony", :lastname => "Soprano" } assert_equal expected_hash, hashify([:firstname, :lastname], ["Tony", "Soprano"]) end def test_bonus expected_keys = [:firstname, ...
class Varietal < ApplicationRecord has_and_belongs_to_many :appellations end
#!/usr/bin/env ruby # encoding: UTF-8 require_relative 'TreasureKind.rb' module NapakalakiGame class Treasure attr_reader :name, :bonus, :type def initialize(n, bon, t) @name=n @bonus=bon @type=t end def to_s "\n\tTesoro: " + @name + "\n\t\tBonus: " + @bonus.to_s + "\n\t\tTreasure...
# -*- mode: ruby -*- # vi: set ft=ruby : VAGRANTFILE_API_VERSION = "2" # NODE_COUNT = 4 SUBNET="172.3.4" # puts "------------------------------" NODE_COUNT = ENV['NODE_COUNT'].to_i > 0 ? ENV['NODE_COUNT'].to_i : 4 sPath=ENV['SHARE_PATH'] # if sPath.to_s.length > 0 # puts "Shared folder is #{sPath}" # else # ...
# frozen_string_literal: true module KepplerFrontend module Editor # CodeHandler class FileFormat def initialize; end def validate(file) content_type = File.extname(file) result = false utils_files.formats.each do |_key, value| result = true if value.include?(co...
class Timesheet < ApplicationRecord validates :start, presence: true validates :finish, presence: true validates :date, presence: true validate :start_must_be_before_finish validate :date_cannot_be_in_future validate :timesheet_entries_must_not_overlap def date_cannot_be_in_future if date.present? ...
require 'omniauth-oauth2' module OmniAuth module Strategies class YammerStaging < OmniAuth::Strategies::Yammer option :name, 'yammer_staging' option :client_options, { site: 'https://www.staging.yammer.com', authorize_url: '/dialog/oauth', token_url: '/oauth2/access_token.jso...