text
stringlengths
10
2.61M
module CDI module V1 class SimpleChatMessageSerializer < ActiveModel::Serializer root false attributes :id, :user_id, :chat_room_id, :content, :created_at, :updated_at end end end
class EducatorStudentRelationship < ApplicationRecord belongs_to :student belongs_to :educator end
class Object class << self alias_method :old_new, :new def new(*args, &blk) old_new(*args, &blk) end end end
# -*- encoding : utf-8 -*- # The business logic for realtime communication between synchronized clients. # # This code is part of the Stoffi Music Player Project. # Visit our website at: stoffiplayer.com # # Author:: Christoffer Brodd-Reijer (christoffer@stoffiplayer.com) # Copyright:: Copyright (c) 2013 Simplare # Li...
def palindrome?(string) return string.gsub(/\W*/i, '').downcase == string.gsub(/\W*/i, '').downcase.reverse end def count_words(string) words = string.downcase.gsub(/\b\w+\b/) frequencies=Hash.new(0) words.each { |word| frequencies[word] += 1 } frequencies.each {|wrd, freq| puts wrd+' '+freq.to_s} end
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
require "rb_heap" require "set" class Valve MATCHER = /Valve (?<id>[A-Z]+) has flow rate=(?<flow>\d+); tunnels? leads? to valves? (?<connections>[A-Z, ]+)/ attr_reader :id, :flow, :connections def initialize(description) data = MATCHER.match(description) @id = data[:id] @flow = data[:flow].to_i ...
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Ch...
class CreateProjects < ActiveRecord::Migration def change create_table :projects do |t| t.string :title t.decimal :budget, precision: 8, scale: 2 t.boolean :published t.boolean :closed t.date :target_date t.string :category t.text :description t.timestamps end ...
require 'rails_helper' RSpec.describe PagesController, type: :controller do let(:valid_attributes) do { title: 'About', slug: 'about', content: 'blah blah blah' } end let(:invalid_attributes) do { title: nil } end let!(:existing_user) { create :user } context 'wit...
module Jobs::Loggable def self.included(base) base.class_eval do alias_method_chain :perform, :logging end end def perform_with_logging started_at = Time.now begin perform_without_logging rescue => e raise e ensure stopped_at = Time.now estimation_error_seco...
=begin #=============================================================================== Title: Random Event Positions Author: Hime Date: Apr 6, 2014 -------------------------------------------------------------------------------- ** Change log Apr 6, 2014 - fixed bug where "page" randomization was not working ...
BlogManagement::Engine.routes.draw do root to: 'susanoo/blogs#index' # Susanoo コア機能 namespace :susanoo do # ブログ管理機能 resources :blogs do collection do get :select_genre get :treeview end end # ジャンル管理機能 resources :genres do end # ページ管理機能 resources :pag...
# frozen_string_literal: true # == Schema Information # # Table name: profiles # # id :bigint(8) not null, primary key # birth_date :date # first_name :string # last_name :string # created_at :datetime not null # updated_at :datetime not null # user_id :bigint(8) # # Indexes #...
class Booking include DataMapper::Resource belongs_to :user belongs_to :place property :id, Serial property :date, Date property :status, Enum[:pending, :confirmed, :rejected, :cancelled], default: :pending validates_presence_of :date def self.requests_made(user_id) Booking.all(user_id: user_id)...
# frozen_string_literal: true require "spec_helper" describe GraphQL::Tracing::StatsdTracing do module MockStatsd class << self def time(key) self.timings << key yield end def timings @timings end def clear @timings = [] end end end c...
module Api::Helpers module OauthJsonSerializer def self.as_json(resource = "", status = "") Result.new(resource, OauthsError.new(status)).to_json end end end
# # Cookbook Name:: frog-cookbook # Attributes:: database # # Copyright (C) 2014 Nick Downs # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitati...
class RacecardsController < ApplicationController before_action :authenticate_user! def new @racecard = Racecard.new @meetings = Meeting.all end def create @racecard = Racecard.new(racecard_params) @racecard.save redirect_to @racecard end def index @racecards = Racecard.all end...
class Admin::EventsController < AdminController skip_before_filter :admin_user_required def index @events = Event.paginate :page => params[:page], :per_page => 20, :order => "created_at desc" end def new @event = Event.new end def edit @event = Event.find(params[:id]) end def update ...
class VoteMailer < ActionMailer::Base default from: "no-reply@redditclone.com" def notification(vote, post) @vote = vote @post = post @user = post.user mail(to: @user.email, subject: 'You got a vote') end end
# Path to root of plugin dir PLUGIN_ROOT = File.join(File.dirname(__FILE__), '..', '..', '..') $:.unshift(File.join(PLUGIN_ROOT, 'lib')) RAILS_ENV = 'test' RAILS_ROOT = File.join(PLUGIN_ROOT, 'test', 'iq', 'upload', 'rails_root') # Use vendor rails if possible if File.directory?(rails_dir = File.join(PLUGIN_ROOT, '.....
class ReadFile private def read_file file = File.open(@path, 'r') file_data if file file_data = file.readlines { |i| file_data << i } else puts 'Unable to open file!' end file.close file_data end public attr_reader :file_data def initialize(path) @path = path ...
Sandwhich = Struct.new(:taste, :toppings) RSpec.describe 'An ideal sandwhich' do let(:sandwhich) { Sandwhich.new('delicious', []) } it 'is delicious' do expect(sandwhich.taste).to eq('delicious') end it 'lets me add toppings' do sandwhich.toppings << 'cheese' expect(sandwhich.toppings).not_to be...
class AddPathToAdBox < ActiveRecord::Migration[5.2] def change add_column :ad_boxes, :path, :string add_column :ad_boxes, :date, :date add_column :ad_boxes, :page_heading_margin_in_lines, :integer add_column :ad_boxes, :page_number, :integer add_column :ad_boxes, :grid_width, :float add_column...
<div><p><strong>I &lt;3 Cookies</strong> is a bakery that makes delicious cookies. They are growing rapidly, and they need some software to help them manage their kitchen.</p> <p>Your job is to build a program that will help them manage their cookie baking. Here are a few user stories to help get you started:</p> <ul> ...
require 'spec_helper' describe 'docker::group' do let(:chef_run) do ChefSpec::SoloRunner.new.converge(described_recipe) end it 'creates the docker group' do expect(chef_run).to create_group('docker') end it 'manages the docker group' do expect(chef_run).to manage_group('docker') end contex...
class Purse < ActiveRecord::Base attr_accessor :money belongs_to :user belongs_to :currency validates :user_id, :presence => true validates :currency_id, :presence => true validates :money, :numericality => {:greater_than => 0}, :allow_nil => true validate :content_v...
# This model caches yahoo finance stock data class FinanceCache < ActiveRecord::Base belongs_to :company enum category: [:historic, :current] end
class ProductBundle attr_reader :name, :code def initialize(name, code) @name = name @code = code.upcase @bundles = {} end def add_bundle(count, price) @bundles[count] = price end def get_bundles @bundles.keys end def get_price(count) price = 0 if @bundles.keys.include?...
class SessoesController < ApplicationController def new end def create usuario = Usuario.atenticar(params[:email] , params[:senha]) if usuario session[:usuario_id] = usuario.id #verifica se os dados estão atualizados if usuario.cpf.blank? flash[:info] = "Você precisa atualizar algumas informaç...
require 'spec_helper' describe Aws::Broker::Config do subject { described_class.new } it { should have_attr_accessor(:enabled) } it { should have_attr_accessor(:queue_prefix) } it { should have_attr_accessor(:topic_prefix) } it { should have_attr_accessor(:sns) } it { should have_attr_accessor(:sqs) } ...
class AddFiloToExemplare < ActiveRecord::Migration def change add_column :exemplares, :filo_id, :integer end end
module Rails module Sh class Command class << self def commands @commands ||= {} end def define(name, &block) commands[name.to_sym] = block end def find(line) if name = line[/\w+/] commands[name.to_sym] else ...
INDICES = { de: [ 'https://www.finanzen.net/index/dax/30-werte', 'https://www.finanzen.net/index/tecdax/werte', 'https://www.finanzen.net/index/mdax/werte', 'https://www.finanzen.net/index/sdax/werte' ], us: [ 'https://www.finanzen.net/index/s&p_500/werte', 'https://www.finanzen.net/index/...
# frozen_string_literal: true $LOAD_PATH.push File.expand_path("../lib", __FILE__) # Maintain your gem"s version: require "waste_exemptions_shared/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "waste_exemptions_shared" s.version = WasteExemptionsShar...
class UpdateColumnsInSpecialRequests < ActiveRecord::Migration def change add_column :special_requests, :song_name, :string add_column :special_requests, :song_artist, :string remove_column :special_requests, :song_id end end
require "spec_helper" describe AuthenticationHelper do let(:user_params) do { name: 'foo', email: 'foo@bar.com', org: 'foo inc', password: 'foo', password_confirmation: 'foo' } end describe "#current_user" do it "returns current user" do user = User.create!(user_p...
require 'pry' class Anagram attr_accessor :word @@test_words = [] def initialize(word) @word = word end def match(test_words) test_words.select do |testing| sort_words(testing) end end def sort_words(word) word.chars.sort == @word.chars.sort end end
Given /I am using a tablet/ do Capybara.page.driver.header('user-agent', 'Mozilla/5.0 (iPad; CPU OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13G36 Safari/601.1') end Given /I am using a mobile phone/ do Capybara.page.driver.header('user-agent', 'Mozilla/5.0 (iPhone; CPU iPho...
feature "User#confirm" do background(:each) do visit '/' within('#sign-up') do fill_in "Email", with: "sam.iam@example.com" click_button "Submit" end open_email 'sam.iam@example.com' current_email.click_link 'activate' end scenario "unsuccessful -- disallowed characters in userna...
# # Cookbook Name:: monit # Recipe:: default # # Copyright 2013, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # case node['platform_family'] when 'rhel', 'centos' %w(monit).each do |pkg| package pkg end template "/etc/logrotate.d/monit" do source "monit.logrotate.erb" owner "root"...
Rails.application.routes.draw do devise_for :admin_users, ActiveAdmin::Devise.config ActiveAdmin.routes(self) resources :boards, path: "/" do resources :topics do resources :comments end end resources :comments, only: [ :show ] root "boards#index" end
#! /usr/bin/env ruby require 'thor' require 'syncy' require 'fileutils' class SyncyCLI < Thor desc "init", "Setup syncy" def init home_dir = Dir.new(ENV["HOME"]) unless home_dir.include? ".syncy" File.new("#{ENV["HOME"]}/.syncy", 'w').write("# This is your Syncy config file, define all dynamic vars ...
require './lib/visitor.rb' require 'date' describe Visitor do it 'can checkout book' do expected_output = {:item => {:title => "A Game of Thrones", :author => "George R.R. Martin"}, :available => false, :return_date => Date.today.next_month.strftime('%d/%m/%y') } expect(subject.checkout_book).to e...
Rails.application.routes.draw do devise_for :users # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". resources :posts # You can have the root of your site routed with "root" root 'home#index' # Example of regular route...
module Issues class SaveIssue prepend SimpleCommand attr_reader :id, :title, :description, :severity, :issue_type, :task, :location_id, :location_type, :cultivation_batch, ...
module Yito module Model module Booking module BookingExternalInvoice def self.included(model) if model.respond_to?(:property) model.property :external_invoice_number, String, :length => 40 model.property :external_invoice_date, DateTime end ...
class LogSerializer < ActiveModel::Serializer attributes :daily_overview, :user_id, :created_at end
require 'test_helper' class PlayersControllerTest < ActionController::TestCase def setup Preference.path_to_server = "#{Rails.root}/tmp" end def test_routings assert_routing({ method: 'get', path: '/' }, controller: 'players', action: 'index') end def test_index def Server.up? true ...
require "rhq/base_object" require "rhq/version" require "rhq/resource" require "rhq/resource_types" require "rhq/operation" require "rhq/alert" require "client/resource_api" require "client/operation_api" require "client/status_api" require "client/metrics_api" require "client/alert_api" require "json" require "rest_...
module CloudDns VERSION = '0.1.3'.freeze unless defined?(CloudDns::VERSION) end
require 'rails_helper' RSpec.describe Nuts1Region, type: :model do subject(:region) { described_class.find_by(code: 'UKM') } let(:all_codes) { described_class.all.map(&:code) } it 'has a code and a name' do expect(region) .to have_attributes(code: 'UKM', name: 'Scotland') end it 'only has unique...
require File.dirname(__FILE__) + '/spec_helper' describe "DeviseSuspendable" do it 'cannot run tests here' do pending "copy this file to your project as /spec/models/suspendable_user_spec.rb and run as part of your project's specs. The spec code depends on FactoryGirl gem and a valid :user factory defined." en...
class ClientService attr_reader :connection def initialize(auth_hash) @connection = Faraday.new(url: url, headers: auth_hash) end def list response = connection.get(url + 'api/clients') JSON.parse(response.body)["data"] end def url ApiConnectionService::BASE_URL end end
require_relative '../src/tool' describe 'Tool' do describe '#getCustomerType' do it 'should return customer type is regular' do inputInformation = 'Regular:16Mar2009(mon),17Mar2009(tues),18Mar2009(wed)' tool = Tool.new(inputInformation) result = tool.getCustomerType() expect(result).to eq...
require 'httparty' module YoutubeEmbed class VideoDetails < VideoObject include HTTParty format :xml VALID_METHODS = [:comments, :id, :published, :updated, :category, :title, :content, :link, :where, {:group => [:category, :content, :description, :keywords, ...
require "airport" require "plane" describe "airport:" do let(:airport) {Airport.new} let(:plane) {Plane.new} it "should have empty hangers" do expect(airport.storage).to eq [] end it "should approve planes for landing" do allow(airport).to receive(:conditions) {'sunny'} airport.approved_for_landing(plane...
module Topographer class Importer module Input class DelimitedSpreadsheet < Topographer::Importer::Input::Base include Enumerable # Creates a new DelimitedSpreadsheet input wrapper. NOTE: Since Topographer relies on headers # to map from input to output columns, you should enable h...
require 'maws/instance' class Command attr_accessor :maws, :connection def description "command - does nothing" end def instances maws.instances end def initialize(config) @config = config @maws = nil end def connection @maws.connection end def run! puts "generic comma...
class CustomersController < ApplicationController def show @customer = Customer.find(params["id"]) render :show end end
class SlackJobs class InviterJob < SlackJobs include Sidekiq::Worker sidekiq_options retry: 5 def perform(email) Raven.user_context email: email Raven.tags_context slack_invite: 'yes' SlackService::Client.new.invite(email) end end end
# encoding: UTF-8 module API module V1 class UsersHome < API::V1::Base before do authenticate_user end get :home do if current_user.backoffice_profile? presenter = presenter('home/home_for_multiplier').new(current_user) serialized_object(presenter, serializ...
class PlayerRushingStatsController < ApplicationController def index @player_rushing_stats = PlayerRushingStat if params[:player_name].present? @player_rushing_stats = @player_rushing_stats.where('player_name like ?', "%#{params[:player_name]}%") else @player_rushing_stats = @player_rushing_s...
# == Schema Information # # Table name: circles # # id :integer not null, primary key # name :string(255) # created_at :datetime # updated_at :datetime # require 'spec_helper' describe Circle do before { @circle = Circle.new(name: "Example Circle") } subject { @circle } it { should...
Doorkeeper.configure do orm :active_record resource_owner_authenticator do clearance_session = env[:clearance] # session = Clearance::Session.new(env) user = clearance_session && clearance_session.current_user if user user else session[:return_to] = request.fullpath redirect_to(s...
module SplunkMan class Search def initialize(splunk_server, user, password) @splunk_server = splunk_server @user = user @password = password end def search(search_query) @splunk_search = search_query search_id = initiate_splunk_search @splunk_search wait_for_splunk_...
module Votable extend ActiveSupport::Concern def rating votes.sum(:rating) end def has_vote?(user, rating) votes.where(user_id: user.id, rating: rating).count > 0 end module ClassMethods end end
class Round attr_reader :deck, :turns, :turn_counter def initialize(deck) @deck = deck @turns = [] @turn_counter = 1 end def current_card deck.cards.first end def take_turn(guess) card = current_card turn = Turn.new(guess, card) end def store_turn(tur...
class ApplicationController < ActionController::Base protect_from_forgery helper_method :current_company rescue_from CanCan::AccessDenied do |exception| redirect_to root_url, :alert => exception.message end def logged_in? user_signed_in? end def login_required unless logged_in? flash...
class AddGalleryReferenceToProduct< ActiveRecord::Migration[6.0] def change add_reference :refinery_caststone_products, :gallery, null: true, to_table: 'refinery_pages', index: false, if_not_exists: true end end
desc "Create dummy material use for selected tasks" task seed_task_material_use: :environment do facility = Facility.find_by(name: 'DEMO F15') products = Inventory::Product.all batches = Cultivation::Batch.where(facility_id: facility.id) batches.each do |batch| batch.tasks.each do |task| selected = [...
class IdeaChangeDescriptionType < ActiveRecord::Migration[5.1] def change change_column(:ideas, :description, :text) end end
require 'test_helper' class UserTest < ActiveSupport::TestCase test "not be able to create User account without password" do user = User.new(:email => "tester@gmail.com") user.save assert !user.valid?, user.errors.to_s end test "not be able to create User account without e-mail" do ...
Lotus::Model.migration do change do create_table :children do primary_key :id column :name, String, null: false column :birthdate, Date column :age, Integer column :grade, String end end end
class AddBrandItemToGouCategories < ActiveRecord::Migration def self.up add_column :gou_categories, :brand_item, :string end def self.down remove_column :gou_categories, :brand_item end end
class EmployeesController < GroupBase before_action :set_employee, only: [:show, :edit, :update, :destroy] before_action :set_groups # カレントユーザの所有する団体を@groupsとする load_and_authorize_resource # for cancancan # GET /employees # GET /employees.json def index @employees = Employee.where(group_id: @groups) ...
class AddIndexToEmail < ActiveRecord::Migration def change add_column :schools, :remember_token, :string add_index :schools, :remember_token add_column :schools, :password, :string add_column :schools, :email, :string end end
require 'spec_helper' describe 'Duplicate Service Options', reset: false do downloadable_collection_id = 'C179003030-ORNL_DAAC' downloadable_collection_title = '15 Minute Stream Flow Data: USGS (FIFE)' non_downloadable_collection_id = 'C179001887-SEDAC' non_downloadable_collection_title = '2000 Pilot Environm...
# *************************************************************************** * # Description: A simple command line Rock, Paper, and Scissors style game * # Author: Gui Weinmann * # *************************************************************************** * ...
def i_have_user @user = FactoryGirl.create(:user) @user.activate! end def fill_in_fields(elements) elements.each_pair do |key, val| page.has_field?(key) fill_in key, :with => val end end def visit_sign_in_page i_have_user visit root_path click_link "Log in" page.has_selector?('fo...
class RecipeCommentsSerializer < ActiveModel::Serializer attributes :id, :user_id, :recipe_id, :content end
class AddOwnerAndMachine < ActiveRecord::Migration def change create_table :owners do |t| t.integer :supplier_id t.integer :machine_id t.timestamps end create_table :machines do |t| t.integer :supplier_id t.string :manufacturer t.string :name t.timestamps end ...
class AddImageDataToCategories < ActiveRecord::Migration def change add_column :categories, :image_file_name, :string add_column :categories, :image_content_type, :string add_column :categories, :image_file_size, :string add_column :categories, :image_updated_at, :string end end
#!/usr/bin/env ruby require 'rubygems' require 'choice' require 'pictate' include Pictate # # Command line parsing # Choice.options do banner "Usage: <image> [options]" option :server do long "--server=SERVER" short "-s" desc "Location of selenium standalone server jar" desc "If this isn't specif...
require 'narp/basic_extensions.rb' module Narp class NumericTerminal < Treetop::Runtime::SyntaxNode end class ArithmeticOperator < TerminalNode end class NumericOperator < TerminalNode def value case text_value.downcase.strip when '=', 'eq' '=' when '!=', 'ne' ...
class IncidentReport < ApplicationRecord belongs_to :incident_type belongs_to :guard has_many :incident_participants has_many :prisoners, through: :incident_participants validates :content, presence: true def defendants instance_records = self.incident_participants.select do |incident_participant_reco...
VALID_CHOICES = { 'r': 'rock', 'p': 'paper', 'sc': 'scissors', 'l': 'lizard', 'sp': 'spock' } def prompt(message) Kernel.puts("=> #{message}") end def print_choices(hash) hash.each do |abbreviation, choice| prompt("Type '#{abbreviation}' for '#{choice}'") end end def win?(first, second, hash) h...
module CDI module V1 module ServiceConcerns module GameQuestionOptionsParams extend ActiveSupport::Concern WHITELIST_ATTRIBUTES = [ :text, :description, :correct ] included do def game_question_option_params @game_question...
require 'rails/generators/active_record' module BootswatchRails module Generators class CleditorGenerator < ActiveRecord::Generators::Base desc "Turn text_area(s) into rich edit fields with CLEditor" argument :name, type: :string, desc: "The resource with textareas to be enhanced" ...
class Note < ActiveRecord::Base belongs_to :user has_many :viewers has_many :readers, through: :viewers, source: :user before_save :give_owner_permission def visible_to self.readers.collect{|user| user.name}.join(", ") end def visible_to=(visible_to) self.readers = visible_to.split(",").collect...
module Humi class Middleware::Authentication < Humi::Middleware autoload :Token, "humi/middleware/authentication/token" autoload :Code, "humi/middleware/authentication/code" autoload :Password, "humi/middleware/authentication/password" def call(env) @app.call(env) rescue Humi::Unauth...
require 'dbconnect' require 'java' import "eu.webtoolkit.jwt.WApplication" # define a TenantKeeper class to keep track of the tenants class TenantKeeper < ActiveRecord::Base # prevent AR from complaining self.abstract_class = true # before_validation hook to set the shop_id for new records before_validation(...
require 'factory_girl_extensions' require 'faker' require 'populator' #AVATAR = File.join(Rails.root, "public", "images", "avatar_sample.jpg") #================================= Factory.sequence :login do |n| "user#{n}" end Factory.sequence :email do |n| "user#{n}@example.com" end Factory.define :user do |user| ...
require "uri" class Promise attr_reader :path, :props def initialize(path, props, resource_dirs=[]) @props = props @dir = resource_dirs.find {|dir| File.exists?(File.join(dir, path)) } @path = path end def exists? ; @dir ; end def headers type = case @props["as"] when "style" then "text...
require 'uri' class SitesController < ApplicationController before_action :require_login, only: [:upload] ############################################################## # Create a new site # # As the UI is on the front home page for site creation, # and login is required for site creation, # and only a...
class AstaporApiError < StandardError attr_reader :msg def initialize(msg = 'api connection error') @msg = msg end end
require File.dirname(__FILE__) + "/../spec_helper" describe "CommentClosing from Test::Unit; no I don't know why it's in article_closing_spec.rb" do def an_article(options = {}) Article.create(options.reverse_merge(:user_id => 1, :body => 'Foo', :title => 'Bar')) end before(:each) do @blog = blogs(:defa...
#!/usr/bin/ruby # -*- coding: utf-8 -*- # Retina Language Interpreter # :Main function # # Author: Jonathan Reyes (Alias: Jay Kozatt) # require_relative 'retina_parser' def main # Check extension ARGV[0] =~ /\w+\.rtn/; if $&.nil?; puts "Extensión de archivo desconocida."; return; end; # Open file as a s...
class AddMoreFildesToProject < ActiveRecord::Migration def change add_column :projects, :professor_city, :string add_column :projects, :professor_state, :string end end