text stringlengths 10 2.61M |
|---|
# frozen_string_literal: true
class FeedArticlesSerializer < ApplicationSerializer
include Rails.application.routes.url_helpers
attributes :id,
:category_id,
:subscription_id,
:title,
:path,
:url,
:articles,
:next_path,
... |
class UsersController < ApplicationController
before_filter :authorize, except: [ :new, :create ]
respond_to :json
def index
@users = User.all
end
def show
@user = User.find(params[:id])
end
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
... |
require 'game'
describe Game do
subject(:game) { described_class.new(player1, player2) }
let(:player1) { double :player1, receive_damage: nil, hp: 100 }
let(:player2) { double :player2, receive_damage: nil, hp: 100 }
describe '#initialize' do
it 'sets player 1 as an instance variable' do
expect(game... |
module CWC
class Api < Sinatra::Base
get '/v2/:office/queue.json' do |office|
skip = params['skip'].to_i
limit = params['limit'] ? params['limit'].to_i : 10
q = Message.where(office_id: office.upcase).limit(limit).skip(skip)
res = {
totalCount: q.count,
count: ... |
class CreateAdviceRequests < ActiveRecord::Migration
def change
create_table :advice_requests do |t|
t.references :forecast, index: true
t.string :status
t.text :comments
t.decimal :hours_used, precision: 5, scale: 2
t.timestamps null: false
end
add_foreign_key :advice_reque... |
require 'open3'
require 'optparse'
require 'ostruct'
options = OpenStruct.new
options.action = nil
options.monitor = nil
options.position = "--below"
OptionParser.new do |opts|
opts.banner = "Usage: monitors.rb [options]"
opts.on('-a', '--action ACTION', 'Turn monitor on of off.', 'on | off | office | list-all |... |
require_relative 'list'
#two pointers
# @param {ListNode} head
# @return {ListNode}
def remove_nth_from_end(head, n)
if head == nil || n <= 0
return head
end
dummy = ListNode.new(-1)
dummy.next = head
fast = dummy
slow = dummy
while n>0
fast = fast.next
n -= 1
end
while fast.next != n... |
require_relative '../request_spec_helper'
feature 'Shopping' do
let!(:lat_lng) { {lat: 37.7913290, lng: -122.4005380} }
let!(:charities) { create_list(:active_charity, 6) }
let!(:offers) { create_list(:offer, 6) }
let!(:charity) { charities.sample }
let!(:offer) { offers.sample }
# Merchant obj... |
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'zulu/version'
Gem::Specification.new do |spec|
spec.name = "zulu"
spec.version = Zulu::VERSION
spec.authors = ["Dan Weinand"]
spec.email = ["dweinand@gmail.co... |
module CollectionNorth::Ability
# in this case we're expecting the include-ing class to first include CurationConcerns::Ability
# and then include this, so that we can override curationconcerns' implementation of this method
# to inject our collection and community types. Needed for the way CurationConcerns imple... |
# frozen_string_literal: true
module SnowplowRubyDuid
describe DomainUserid do
subject { described_class.new.to_s }
describe '#to_s' do
it 'generates the domain userid' do
expect(subject.length).to eq(36)
end
end
end
end
|
#! ruby
require 'test/unit'
require 'mplay/version'
class TestVersion < Test::Unit::TestCase
VERSION = '2.6.0'
def test_version
assert_nothing_raised() do
assert_equal(VERSION, Mplay::VERSION)
assert_equal(VERSION, File.read('data/VERSION').strip)
assert( system "grep version mplay.gemspec | ... |
require_dependency "webinius_cms/application_controller"
module WebiniusCms
class SessionsController < ApplicationController
def new
end
def create
user = User.where(username: params[:username]).first
if user && user.authenticate(params[:password])
session[:user_id] = user.id
... |
module MiniAether
class ScriptingContainer
# Create a new ScriptingContainer (Java object interface to a
# JRuby runtime) in SINGLETHREAD mode. #terminate must be called
# when no longer in use.
def initialize
singlethread = Java::OrgJrubyEmbed::LocalContextScope::SINGLETHREAD
persistent ... |
# encoding: utf-8
require 'bindata'
require 'ipaddr'
# noinspection RubyResolve
class SflowMacAddress < BinData::Primitive
array :bytes, :type => :uint8, :initial_length => 6
def set(val)
ints = val.split(/:/).collect { |int| int.to_i(16) }
self.bytes = ints
end
def get
self.bytes.collect { |byt... |
require 'docking_station'
describe DockingStation do
it "responds to release_bike" do
instance = DockingStation.new
expect(instance).to respond_to(:release_bike)
end
# it { is_expected.to respond_to release_bike }
describe '#release_bike' do
it "releases bike" do
bike = Bike.new
subjec... |
class AssayTypesController < ApplicationController
before_filter :find_ontology_class, :only=>[:show]
before_filter :find_and_authorize_assays, :only=>[:show]
def show
respond_to do |format|
format.html
format.xml
end
end
private
def find_ontology_class
uri = params[:uri] || Seek... |
#RELEASE 1: Write a simple module
# module Shout
# def self.angrily(words)
# words + "!!!" + " :("
# end
# def self.yelling_happily(words)
# words.upcase + "!!!!!!" + " YAY!!" + " :) :)"
# end
# end
# #driver code for release 1
# puts Shout.angrily("This sucks")
# puts Shout.yelling_happily("I am so excited")... |
#
# Cookbook Name:: bcpc
# Recipe:: rotate_chef_nginx_access_log
#
# Prevent chef-server's nginx access.log from filling up
# a partition
#
logrotate_app 'chef-server-nginx-access-log' do
path '/var/log/chef-server/nginx/access.log'
frequency 'daily'
rotate 5
maxsize '1G'
options %w(missingok notifempty comp... |
#!/usr/bin/env ruby
File.open($0) do |f|
f.readlines.each do |line|
puts line
end
end
|
# rubocop:disable Style/FrozenStringLiteralComment
WINNING_LINES = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + # rows
[[1, 4, 7], [2, 5, 8], [3, 6, 9]] + # cols
[[1, 5, 9], [3, 5, 7]] # diagonals
# rubocop:enable Style/FrozenStringLiteralComment
INITIAL_MARKER = ' '.freeze
PLAYER_MARKER = 'X'.f... |
require 'csv'
require 'yaml'
#require 'pry'
namespace :admin do
namespace :reports do
desc "Report project allocation numbers for supervisors"
task :staff_allocation => [:environment] do |t|
projects = Project.assigned
supervisors = Hash.new
puts "#{projects.count} projects allocated"
... |
require 'fileutils'
require 'active_record'
require 'csv'
# Using Active Record with an index for O(1) time for contact lookups.
class Contact < ActiveRecord::Base
end
# ContactManager module.
module ContactManager
def self.setup
ActiveRecord::Base.establish_connection("adapter" => "sqlite3","databas... |
FactoryBot.define do
factory :movie do
title 'My Movie'
runtime 100
plot 'A very interesting plot'
actors ['first actor']
directors ['first director']
poster 'screen.jpg'
press_ratings 3
user_ratings 4
end
end
|
require_relative '../../config'
# This is where you should use an ActiveRecord migration to
# HINT: checkout ActiveRecord::Migration.create_table
class CreateStudents < ActiveRecord::Migration
def up
# Code to create the table here:
create_table :students do |t|
t.string :first_name
t.string ... |
#!/usr/bin/env ruby
require 'rubygems'
require 'mechanize'
require 'active_record'
require 'mini_magick'
# Monkey patch Mechanize to include an Ubuntu Hardy Firefox user agent
WWW::Mechanize::AGENT_ALIASES['Ubuntu Firefox 3.0'] =
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.3) Gecko/2008092510 Ubuntu/8.04 (ha... |
class AddSubForToEventUsers < ActiveRecord::Migration
def change
add_column :event_users, :sub_for, :integer
end
end
|
# -*- coding: utf-8 -*-
=begin
Faça um programa que leia uma quantidade indeterminada de números positivos e
conte quantos deles estão nos seguintes intervalos: [0-25], [26-50], [51-75] e [76-
100]. A entrada de dados deverá terminar quando for lido um número negativo.
=end
puts "=====================================... |
module Ldap
module Relations
# Store a list of relations and provide methods
# to output the list as an LDAP filter string.
class RelationManager
def initialize *args
self.relations = RelationGrouping.new
end
attr_accessor :relations
# Public: convert the relations to an ... |
module AnsiArt
class Document
def initialize ansi
@ansi = ansi
end
def to_html
return convert HtmlConverter.new
end
def to_png w=800, o={}
return convert PngConverter.new(w,o)
end
def convert conv
buffer = Buffer.new
ctrl_seq = ""
high_byte = false #... |
class CreateRotativos < ActiveRecord::Migration
def self.up
create_table :rotativos do |t|
t.integer :numero_de_carros
t.date :data
t.decimal :valor_rotativo
t.decimal :valor_mensalista
t.decimal :valor_total
t.timestamps
end
end
def self.down
drop_table :rotativo... |
class Item < ApplicationRecord
belongs_to :user
has_one :order
has_one_attached :image
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to_active_hash :category
belongs_to_active_hash :status
belongs_to_active_hash :delivery_fee
belongs_to_active_hash :shipping_region
belongs_to_active... |
def prompt(msg)
puts "=> #{msg}"
end
def win?(first, second)
(first == 1 && second == 2) ||
(first == 2 && second == 3) ||
(first == 3 && second == 1)
end
def display_results(user, comp)
if win?(user, comp)
"Computer wins!"
elsif win?(comp, user)
"Player wins!"
else
"Draw."
end
end
de... |
Rails.application.routes.draw do
root to: 'static_pages#root'
namespace :api do
resources :todeauxes, except: [:new, :edit]
end
end
|
module FacilitiesManagement
module Admin
class AdminAccountController < FacilitiesManagement::Admin::FrameworkController
before_action :redirect_if_needed
before_action :authenticate_user!
before_action :authorize_user
def admin_account
@current_login_email = current_user.email.to... |
require 'pry'
def merge_sort(array)
return array if array.length <= 1
middle = (array.length / 2)
left = array[0..middle-1]
right = array[middle..array.length - 1]
return merge(merge_sort(left), merge_sort(right))
end
def merge(left, right)
result = Array.new
while left.length > 0 || right.length > 0... |
class CreateNdaRelationships < ActiveRecord::Migration
def change
create_table :nda_relationships do |t|
t.integer :new_deal_agency_id, null: false
t.integer :nda_relatable_id, null: false
t.string :nda_relatable_type, null: false
t.timestamps
end
add_index :nda_relationships, [:... |
class UsersSubsRelationshipsController < ApplicationController
before_action :set_user_subs_relationship, only: [:edit, :update]
before_action :authenticate_user!
before_action :require_to_have_no_subscription, only: [:new, :create]
def new
@users_subs_relationship = UsersSubsRelationship.new
end
def... |
module PushWoosher
class Push < PushWoosher::Base
attribute :notification
def resource_path
'createMessage'
end
def request_hash
{
notifications: [notification]
}
end
def post
post_action(
path: resource_path,
request_hash: request_hash
... |
#Description
#This excersise is from codebar.io tutorials.
#Fill in the temperature for each day of the week and prints out the result
class Celsius
#attr_reader :temperature
def initialize (temperature)
@temperature = temperature.to_i
end
def celsius_to_fahrenheit()
((@temperature * 1.8) + 32).round
e... |
=begin
#Smooch
#The Smooch API is a unified interface for powering messaging in your customer experiences across every channel. Our API speeds access to new markets, reduces time to ship, eliminates complexity, and helps you build the best experiences for your customers. For more information, visit our [official docum... |
#! /usr/bin/ruby
require 'cgi'
$LOAD_PATH << File.dirname(__FILE__)
require 'team-matchups-circular'
require 'timeslot-assignment'
require 'home-away-assignment'
require 'holidays'
require 'ice-oasis-leagues'
require 'create-ics-file'
require 'analyze-schedule'
require 'parse-ics'
puts "Content-type: text/html; chars... |
# frozen_string_literal: true
require 'jiji/test/test_configuration'
require 'jiji/test/data_builder'
describe Jiji::Model::Trading::ClosingPolicy do
describe '#should_close?' do
it 'take_profitが設定されている場合、利益が設定値を上回った時点で決済される' do
policy = Jiji::Model::Trading::ClosingPolicy.create({
take_profit: 13... |
class User < ApplicationRecord
attr_accessor :remember_token
before_save { self.email = email.downcase }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :first_name, :last_name, presence: true
validates :email, presence: true, length: { maximum: 255 },
form... |
class RemoveFirstViewFromPassword < ActiveRecord::Migration[6.1]
def change
remove_column :passwords, :first_view
end
end
|
# frozen_string_literal: true
RSpec.describe Api::V1::Sockets::Auth::CreateAction do
let!(:current_user) { create(:user) }
let(:action) { described_class.new(context: {current_user: current_user}) }
describe '#call' do
subject(:call) do
action.call(input)
end
context 'when params are invalid'... |
require 'test/unit'
require 'soap/rpc/httpserver'
require 'soap/wsdlDriver'
module SOAP
class TestCalc < Test::Unit::TestCase
class Server < ::SOAP::RPC::HTTPServer
def on_init
add_method(self, 'add', 'x', 'y')
end
def add(x, y)
x.to_f + y.to_f
end
end
DIR = File.dirname(File.e... |
class Api::ReviewsController < ApplicationController
def index
@reviews = Review.includes(:spot).all
render :index
end
def show
@review = current_user.reviews.includes(:spot).find(params[:id])
render :show
end
def create
@review = Review.new(review_params)
if @review.save
rend... |
# this class intentionally does not use metaprogramming for simplicty
# and clarity while trying to teach a workshop on metaprogramming. extra
# credit for refactoring it with metaprogramming techniques learned in
# the workshop!
class CustomerDatasource
def initialize
@nosql_database = {
:one => {
... |
RSpec.describe 'User' do
describe 'User goes to comedians page' do
it 'Sees all comedians on comedians page' do
Comedian.create(name: 'Adam', age: 26)
visit '/comedians'
expect(page).to have_content('Adam')
expect(page).to have_content(26)
end
it 'Sees a comedians specials' do
... |
class CreateMainIndustries < ActiveRecord::Migration
def change
create_table :main_industries do |t|
t.string :main_t, null: false, unique: true, limit: 20
t.timestamps null: false
end
end
end
|
class AddUniqueConstraintToAgent < ActiveRecord::Migration[5.1]
def change
add_index(:agents, [:owner_id, :agentname], unique: true)
end
end
|
# frozen_string_literal: true
module Kafka
module Protocol
# A response to a {MetadataRequest}.
#
# The response contains information on the brokers, topics, and partitions in
# the cluster.
#
# * For each broker a node id, host, and port is provided.
# * For each topic partition the nod... |
class Event < ApplicationRecord
belongs_to :creator, :class_name => "User"
has_many :event_attendees, :foreign_key => "attended_event_id", dependent: :destroy
has_many :attendees, :through => :event_attendees, :source => "attendee"
#scopes
scope :upcoming, -> { where('date >= :now', {now: Time.now }) }
scope ... |
require "fpm/package"
class FPM::Target::Rpm < FPM::Package
def architecture
case @architecture
when nil
return %x{uname -m}.chomp # default to current arch
when "native"
return %x{uname -m}.chomp # 'native' is current arch
when "all"
# Translate fpm "all" arch to wh... |
class CustomerItemsController < ApplicationController
before_action :find_item, only: [ :edit, :update, :show, :destroy]
def index
@items = current_customer.customer_items.uniq
end
def new
@item = CustomerItem.new
end
def create
if !current_customer
flash[:alert] = "Sign In to Add Items To Your... |
class CommentMailer < ActionMailer::Base
default :from => ENV['GMAIL_USERNAME']
def comment_notification(comment)
@comment = comment
@post = comment.post
mail(:to => @post.author.email, :subject => "New Comment Posted")
end
end
|
# -*- encoding : utf-8 -*-
class Admin::TranslateesController < ApplicationController
# GET /admin/translatees
# GET /admin/translatees.json
def index
@admin_translatees = Admin::Translatee.all
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @admin_translatees }
end
en... |
module BillTrap
module CLI
def set
# Grab subcommand
k = args.shift
case
when k == 'client'
id = args.shift
if e = Client.get(id)
Invoice.current.update(:client_id => e.id)
puts "SET client to #{e.name} (##{e.id})"
else
warn "Error: Can... |
# encoding: UTF-8
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :omniauthable,
:recoverable, :rememberable, :trackable, :valida... |
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update,:destroy]
before_action :check_user, only:[:edit,:update,:destroy]
before_action :authenticate_user
def index
@posts = Post.all.text_search(params.dig(:post,:text)).category_search(params.dig(:post, :categor... |
# frozen_string_literal: true
# iptables settings
# =================
include_recipe 'iptables'
file '/etc/iptables.d/prefix' do
content <<~EOF
-A INPUT -j FWR
EOF
mode '0600'
notifies :run, 'execute[rebuild-iptables]'
end
file '/etc/iptables.d/suffix' do
content <<~EOF
-A FWR -p tcp -m tcp --tcp-fl... |
# frozen_string_literal: true
RSpec.shared_context 'with more events' do
let(:event_2) do
build(:event, branch: branch, location: location, starts_at: 30.days.from_now, ends_at: 32.days.from_now)
end
let(:ticket_2) { build(:ticket, event: event_2, shift_responsibilities: 0) }
let(:cleanup_2) { build(:shift... |
class Usuario
#getters y setters
attr_accessor :nombre #getters and setters (obtener y setear)
attr_reader :apellido #getter
attr_writer :apellido, :password #setter
#def apellido=(valor)
# @apellido = valor
#end
#def apellido
# @apellido
#end
end
#i... |
Lita.configure do |config|
config.robot.name = "AWESOME-O"
config.robot.mention_name = "asimo"
config.robot.locale = 'es'
config.robot.log_level = :debug
#----------------------------------------------------------------------#
# SANDBOX #
#----... |
# == Schema Information
#
# Table name: combos
#
# id :integer not null, primary key
# supplier_id :integer
# tag_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Combo < ActiveRecord::Base
belongs_to :supplier
belongs_to :tag
val... |
# A simple document-term matrix.
module TfIdfSimilarity
class TermCountModel
include MatrixMethods
# The documents in the corpus.
attr_reader :documents
# The set of terms in the corpus.
attr_reader :terms
# The average number of tokens in a document.
attr_reader :average_document_size
... |
class BookmakersAdminController < ApplicationController
before_filter :authenticate_user!
layout "backend"
active_scaffold :bookmaker do |conf|
config.label = "Bookmakers"
config.columns = [:name, :web_site, :description]
list.sorting = {:name => 'ASC'}
end
end |
class AddSampleIdToMedicineBillRecords < ActiveRecord::Migration[5.0]
def change
add_column :medicine_bill_records, :sample_id, :integer
end
end
|
class TwitterApi
def initialize(user_id, client = nil)
@user_id = user_id
@client = client
@client ||= Twitter::REST::Client.new do |config|
config.consumer_key = ENV['TWITTER_KEY']
config.consumer_secret = ENV['TWITTER_SECRET']
config.access_token = ENV['TWITTER_ACCESS_KEY']
confi... |
class MalePostCommentsController < ApplicationController
before_action :set_male_post_comment, only: [:edit, :update, :destroy]
def new
@male = Male.find(params[:male_id])
@lady_doctor_post = LadyDoctorPost.find(params[:id])
@lady_doctor = @lady_doctor_post.lady_doctor
p "#{@lady_doctor}"
@male_po... |
# The MIT License (MIT)
# Copyright (c) 2014 Jacob Hammack
# 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 limitation the rights to
# use, copy, modif... |
require 'slightish/sandbox'
require 'slightish/test_case'
class Slightish::TestSuite
attr_reader :name, :path, :test_cases
attr_reader :sandbox_template_dir
def self.from_file(path, sandbox_template_dir: nil)
new(path, File.read(path), sandbox_template_dir: sandbox_template_dir)
end
def initialize(path... |
module Scrabble
class Scoring
LETTERS_VALUES = {
1 => %w(A E I O U L N R S T),
2 => %w(D G),
3 => %w(B C M P),
4 => %w(F H V W Y),
5 => %w(K),
8 => %w(J X),
10 => %w(Q Z)
}
def self.input_correct?(word)
#Checking word using regular expression
if word[... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
VAGRANT_FILE_VERSION = 2
Vagrant.configure(VAGRANT_FILE_VERSION) do |config|
config.vm.box = "puppetlabs/centos-7.0-64-puppet"
config.librarian_puppet.puppetfile_dir = "puppet"
config.librarian_puppet.placeholder_filename = ".gitkeep"
config.librarian_puppet... |
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable
# Setup ac... |
# This code is free software; you can redistribute it and/or modify it under
# the terms of the new BSD License.
#
# Copyright (c) 2011-2017, Sebastian Staudt
require 'rspec/core'
require 'rspec/expectations'
require 'coveralls'
Coveralls.wear!
require 'rbzip2'
include RBzip2
RSpec.configure do |config|
config.c... |
require 'spec_helper'
require 'cancan/matchers'
describe GroupsController do
describe 'GET index' do
let(:user) { FactoryGirl.create(:user) }
before(:each) do
groups = FactoryGirl.create_list(:group, 3)
groups.first(2) do |group|
user.join(group)
end
end
it 'is really werid... |
require 'test_helper'
class AgentsControllerTest < ActionDispatch::IntegrationTest
test "agent routes" do
user_id = 'admin'
agent_id = 'weather'
# Show
assert_routing({
method: 'get',
path: "agents/#{user_id}/#{agent_id}"
},
{
controller: 'agents',
action: 'show',
... |
# Problem 154: Exploring Pascal's pyramid.
# http://projecteuler.net/problem=154
# A triangular pyramid is constructed using spherical balls so that each ball rests on exactly three balls of the next lower level.
# http://projecteuler.net/project/images/p_154_pyramid.gif
# Then, we calculate the number of paths leadi... |
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :family_members, only: [:index, :show]
resources :currency_holdings, only: [:index, :show, :edit, :update]
resources :tangible_assets
end
end
end
|
require 'haystack'
class HaystackGenerator < Rails::Generators::Base
EXCLUDED_ENVIRONMENTS = ['test'].freeze
source_root File.expand_path('../templates', __FILE__)
desc 'Generate a config file for Haystack'
def copy_config_file
template_file = 'haystack.yml'
destination_file = File.join('config', tem... |
class ProjectsController < ApplicationController
before_filter :find_project, only: [:show, :edit, :update, :destroy]
def new
@project = Project.new
end
def index
@projects = current_user.projects.all
end
def create
@project = current_user.projects.create(project_params)
respond_to do |fo... |
#==============================================================================#
# ** IEX(Icy Engine Xelion) - Swordcraft Story TEC STAT
#------------------------------------------------------------------------------#
# ** Created by : IceDragon (http://www.rpgmakervx.net/)
# ** Script-Status : Addon (Actor Stat)
# ... |
# == Schema Information
#
# Table name: sections
#
# id :integer not null, primary key
# profile :string
# column :integer
# row :integer
# order :integer
# ad_type :s... |
Rails.application.routes.draw do
root 'home#show'
# get "/", to: :home
resources :sessions
resources :picture_tags
resources :users
resources :tags
resources :pictures
resources :comments
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
get "/signup",... |
require 'deck'
require 'rspec'
describe Deck do
let (:deck) { Deck.new }
describe "Deck#initialize" do
before(:each) { deck.fill_deck }
it "initializes with 52 cards" do
expect(deck.size).to eq(52)
end
it "initializes with 52 unique cards" do
other_cards = deck.cards.map { |c... |
VALID_CHOICES = %w(Rock Paper Scissors Lizard Spock)
DEFEATS = { "Scissors": ["Paper", "Lizard"],
"Paper": ["Rock", "Spock"],
"Rock": ["Lizard", "Paper"],
"Spock": ["Scissors", "Rock"],
"Lizard": ["Spock", "Paper"] }
computer_score = 0
player_score = 0
choice = ""
s_ch... |
require 'digest/md5'
module Ipizza::Provider
class Nordea::AuthenticationResponse < Ipizza::AuthenticationResponse
def initialize(params)
@params = params
end
def verify(key_path)
key = File.read(key_path).strip
@valid = @params['B02K_MAC'] == Digest::MD5.hexdigest(mac_data_string... |
require 'spec_helper'
describe Album do
describe "making an album" do
it "requires an album name" do
subject.should_not be_valid
subject.albumName = "Unknown"
subject.should be_valid
end
end
end
|
require_relative '../BinarySearchTree/binary_search_tree'
# Adds an index to a binary tree via means of the left_size property.
class IndexedNode < Node
attr_accessor :left_size
def initialize(key, value=nil)
super(key, value)
@left_size = 0
end
# left_size is calculated on insert and causes all pare... |
class CreateReviews < ActiveRecord::Migration[5.2]
def change
create_table :reviews do |t|
t.float :service_quality
t.float :interlocutor_skills
t.float :monitoring_care
t.boolean :company_recommendation
t.text :testimony, limit: 250
t.string :token
t.timestamps
end
... |
require 'rails_helper'
RSpec.feature "GuestRedirectedAndCanClickOnSignUps", type: :feature do
it 'should redirect unauthenticated user to create account' do
visit '/'
expect(current_path).to eq login_path
click_on "Sign Up"
expect(current_path).to eq new_user_path
fill_in "Email", with: "beth... |
class StudentsController < ApplicationController
before_action :authenticate_user!
before_action :is_a_student
before_action :set_quote
def show
@user = current_user
end
private
def student_params
params.require(:user).permit(:zip, :bio, :goals, :interests, :born_on, :avatar)
e... |
class StaticPagesController < ApplicationController
def home
@comics = Comic.all
end
end
|
module Babar
class Location < UserList
attr_accessor :id
attr_accessor :json_parsed
def initialize(authenticator, json_parsed)
super(authenticator, json_parsed)
@id = json_parsed["id"].to_i
end
%w(name description lat lon).each do |field|
define_method(field) do
@json... |
class User2Mailer < ApplicationMailer
default from: 'grantkazan@gmail.com'
def user2_email
@user2 = params[:user2]
mail(to: @user2.email, subject: 'Your ticket receipt')
end
end
|
module Seed::BillOfMaterials
bill_of_materials = {
flat_tire: {
bill_of_materials_item_types: [BillOfMaterialsItemType.new({
item_type: Seed::ItemTypes.get(:replacement_tire),
item_type_count: 1
... |
require 'pry'
# test if a number is prime or not
# a number is prime if it's not divisible by any number other than itself
# so you can start dividing by 2...
def prime_v1?(number)
# if a number is divisible by 2, then it's DEFINITELY not prime
if number % 2 == 0
false
else
true
end
end
divisors = ... |
class User < ActiveRecord::Base
has_many :orders
has_many :page_visits
has_many :shares
has_many :likes, :through => :shares
has_many :shares
has_many :clips, :through => :shares
has_many :shares
has_many :quotes, :through => :shares
validates :facebook_user_id, :uniqueness => true, :presence => t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.