text stringlengths 10 2.61M |
|---|
require 'rails_helper'
RSpec.describe OfficialDiary, type: :model do
it 'has a valid factory' do
expect(create :official_diary).to be_valid
end
describe 'Validations' do
it { should validate_presence_of :name }
it { should validate_presence_of :social_name }
it { should validate_presence_of :cnpj }
end
... |
class User < ActiveRecord::Base
has_many :user_songs
has_many :songs, through: :user_songs
end
|
module Ekidata
class Station < ActiveRecord::Base
attr_accessible :code, :group_code,
:name, :name_kana, :name_latin,
:line_code, :pref_code, :postal_code,
:address, :lon, :lat,
:opened_at, :closed_at,
:status, :so... |
# -*- coding: utf-8 -*-
#
# Author:: lnznt
# Copyright:: (C) 2011 lnznt.
# License:: Ruby's
#
require 'gmrw/extension/all'
require 'gmrw/ssh2/loggable'
require 'gmrw/ssh2/server/connection/channel'
require 'gmrw/ssh2/server/connection/session/program'
class GMRW::SSH2::Server::Connection
class Session
include G... |
module RegexGenerator
class TargetNotFoundError < StandardError
def message
'The target was not found in the provided text'
end
end
class TitleNotFoundError < StandardError
def message
'The title was not found in the provided text'
end
end
class InvalidOption < StandardError
... |
class AddSubdomainToGym < ActiveRecord::Migration[5.2]
def change
add_column :gyms, :subdomain, :string
end
end
|
FactoryGirl.define do
factory :heat do
round 'Round'
position 0
round_position 0
event_division
factory :heat_with_athletes do
transient do
athletes_count 6
end
after(:create) do |heat, evaluator|
create_list(:athlete_heat, evaluator.athletes_count, heat: heat)
... |
class AssignmentsController < ApplicationController
before_filter :authorize_only_for_admin, except: [:deletegroup, :delete_rejected, :disinvite_member, :invite_member,
:creategroup, :join_group, :decline_invitation, :index, :student_interface]
before_filter :authorize_for_student, only: [:student_inter... |
class PieValue < OpenFlashChart
def initialize(value, text)
@value = value
@text = text
end
end
class Pie < OpenFlashChart
def initialize
@type = "pie"
@colors = ["#d01f3c","#356aa0","#C79810"]
@alpha = 0.6
@border = 2
@values = [2,3,PieValue(6.5,"hello (6.5)")]
end
end
|
require "game"
describe Game do
let(:bob) { instance_double(Player, :name => "Bob", :hp => 100) }
let(:jack) { instance_double(Player, :name => "Jack", :hp => 100) }
let(:game) { described_class.new(bob, jack) }
describe "#initialize" do
it "takes two players" do
expect(game.player_1).to eq bob
... |
Rails.application.routes.draw do
resources :jobs
root 'jobs#index'
end
|
class Notice < ActiveRecord::Base
has_many :messages
attr_accessible :close_at, :messages, :messages_attributes
accepts_nested_attributes_for :messages
def self.open(now = Time.now)
where("close_at IS NULL OR ? < close_at", now)
end
def self.locale(locales)
if locales.empty?
where("1 = 1")
... |
#!/usr/bin/ruby
require "tinytable"
require "date"
NUM_SHIFTS = `cat shifts.lp | wc -l`.to_i
NUM_DAYS = `cat dates.lp | wc -l`.to_i
NUM_FIRMS = `cat firms.lp | wc -l`.to_i
NUM_SLOTS = NUM_DAYS * NUM_SHIFTS
SHIFT_NAMES = (1..NUM_SHIFTS).map { |i| "s#{i}" }
def process_allocations(allocate_clauses)
puts <<-EOM
+... |
desc "Package TinyCI for distribution"
task :dist do
require File.dirname(__FILE__) + '/../../config/version'
sh "rake rails:freeze:gems"
sh "rake gems:unpack:dependencies"
FileUtils.rm_rf "dist"
FileUtils.mkdir_p "dist"
files = ["app", "config/*.rb", "config/*/*", "config/background.yml", "config/... |
class SubscriptionsController < ApplicationController
before_action :check_user, only: [:subscribe]
skip_before_action :verify_authenticity_token, only: [:webhook]
def check_user
return if user_signed_in?
redirect_to new_user_session_path, alert: 'You need to sign in or sign up before conti... |
class List
attr_accessor :items
FOOD_TAX = 0.06
def initialize(items = {})
unless items.is_a? Hash
return 'items must be a hash with item keys and amount values'
end
@items = items
end
def add(item, amount = 1)
item = item.to_sym
@items[item] = @items[item].to_i
@items[item] +... |
class Section < ActiveRecord::Base
belongs_to :schedule
validates :name, :location, :start_time, :end_time, presence: true
end
|
# This is the shared codebase for the compliance_markup hiera
# backend. Each calling object (either the hiera backend class
# or the puppet lookup function) uses instance_eval to add these
# functions to the object.
#
# Then the object can call enforcement like so:
# enforcement('key::name') do |key, default|
# look... |
class Trail < ApplicationRecord
has_many :hikes
has_many :trips, through: :hikes
def hike_counter
trips.count
end
end
|
require 'spec_helper'
describe "consultations/new" do
before(:each) do
assign(:consultation, stub_model(Consultation,
:data => "MyString",
:hora => "MyString",
:medico => nil,
:paciente => nil
).as_new_record)
end
it "renders new consultation form" do
render
# Run the ge... |
class AddSaltToHeards < ActiveRecord::Migration
def self.up
add_column :heards, :salt, :integer
end
def self.down
remove_column :heards, :salt
end
end
|
# encoding: utf-8
require 'rubygems'
require 'bundler'
begin
Bundler.setup(:default, :development)
rescue Bundler::BundlerError => e
$stderr.puts e.message
$stderr.puts "Run `bundle install` to install missing gems"
exit e.status_code
end
require 'rake'
require 'rspec/core/rake_task'
require File.expand_path('... |
module Libv8
module Compiler
module_function
def compiler
unless defined?(@compiler)
cc = check_gcc_compiler "g++"
# Check alternative GCC names
# These are common on BSD's after
# GCC has been installed by a port
cc ||= check_gcc_compiler "g++44"
cc |... |
# -------------------------------------------------------------------------- #
# Copyright 2002-2018, OpenNebula Project, OpenNebula Systems #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may #
# no... |
# Source: https://launchschool.com/exercises/6990f3dc
def rot_13(str)
alpha_lower = ('a'..'z').to_a
alpha_upper = alpha_lower.map(&:upcase)
rot_lower = alpha_lower.rotate(13)
rot_upper = alpha_upper.rotate(13)
str.chars.map do |char|
if alpha_lower.include?(char)
rot_lower[alpha_lower.find_index(c... |
# frozen_string_literal: true
class Types::Location::ServiceType < Types::BaseObject
field :id, ID, null: false
field :start_at, String, null: false
field :end_at, String, null: false
field :elvanto_form_id, String, null: true
field :location, Types::LocationType, null: false
end
|
require 'rails_helper'
describe AccountPresenter do
subject { described_class.new account, nil }
context "presenting LendLayer accounts" do
let(:account) { Account.wells_fargo_cash }
its(:customer_name) { should be_nil }
its(:customer_type) { should be_nil }
end
context "presenting customer acco... |
class Countries
def self.country_list
codes = [
["Antigua and Barbuda", "AG"],
["Argentina", "AR"],
["Aruba", "AW"],
["Australia", "AU"],
["Austria", "AT"],
["Bahamas", "BS"],
["Bahrain", "BH"],
["Bangladesh", "BD"],
["Barbados", "BB"],
["Belgium", "BE"]... |
class CartItemsController < ApplicationController
before_action :set_cart_item, only: [:show, :destroy, :update]
def index
@items = current_cart.items
render json: @items
end
def show
@item = current_cart.items.find(params[:id])
render json: @item
end
def create
exsited_item = current... |
##################################################################################
################################### Important! ###################################
##################################################################################
#
# WordPress is available at https://localhost:8081/ and http://localh... |
class Doctor < ApplicationRecord
has_many :appointments
has_many :patients, through: :appointments
belongs_to :city
has_many :middle
has_many :specialties, through: :middle
end
# rails generate migration AddPartNumberToProducts part_number:string
# class AddPartNumberToProducts < ActiveRecord::Migration[5.0]
# ... |
# -*- encoding : utf-8 -*-
# The model of the OAuth access token resource.
#
# 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
# License:: GNU General Public Li... |
# frozen_string_literal: true
module Validators
class Tickets < Base
include TicketsValidatorHelper
def initialize(fields)
@fields = fields
end
def validate(ticket)
@ticket = ticket
fields.each { |field| send(field) }
end
private
attr_reader :fields, :ticket
de... |
class TripsController < ApplicationController
def show
@trip = Trip.includes({ guest: :profile_image }, { lair: :images }).find(params[:id])
end
def create
@trip = Trip.new(trip_params)
@trip.guest_id = current_user.id if current_user
if @trip.save
render json: { success: 'Reservation request placed' }
... |
class Api::ReviewsController < ApplicationController
before_action :require_login
before_action :ensure_current_user_is_authorized, only: [:destroy, :update]
def create
@review = Review.new(review_params)
@review.user = current_user
if @review.save
render :show
else
render json: @rev... |
class RecipeMenuItemsController < ApplicationController
before_action :set_recipe_menu_item, only: [:show, :edit, :update, :destroy]
# GET /recipe_menu_items
# GET /recipe_menu_items.json
def index
@recipe_menu_items = RecipeMenuItem.all
end
# GET /recipe_menu_items/1
# GET /recipe_menu_items/1.json... |
RSpec.describe Controllers::Rights do
before do
DatabaseCleaner.clean
end
let!(:group) { create(:group) }
let!(:category) { create(:category) }
let!(:account) { create(:account) }
let!(:right) { create(:right, groups: [group], category: category) }
let!(:application) { create(:application, creator: ... |
require 'securerandom'
require 'digest'
require 'redis'
class UserSessionsController < ApplicationController
before_action :set_page_title, only: [:new]
skip_before_filter :require_login, except: [:destroy]
skip_before_filter :require_profile, only: [:destroy]
# GET /login
def new
@user = User.new
end... |
class CreateKatoRooms < ActiveRecord::Migration
def change
create_table :kato_rooms do |t|
t.string :Get
t.timestamps
end
end
end
|
# Print text with colors
module Colorizer
VERSION = 1.0
COLORS = {
# Text Effects
:normal => "\33[0m",
:bold => "\33[1m",
:bright => "\33[1m",
:underline => "\33[4m",
:reverse_video => "\33[7m",
:inverse => "\33[7m",
# Foreground Colors
:black ... |
class LoginAudit < ActiveRecord::Base
unloadable
validates :user_id, :presence => true
belongs_to :user
end
|
# encoding: UTF-8
require 'json'
fun_facts = {
"Alison Jones" => "In a previous job, I fed poisonous snakes.",
"Andrew Hyder" => "Apps, maps and raps.",
"Ariel Kennan" => "I once designed a small city in China.",
"Lou Huang" => "I was once kicked out of the SFMOMA for pretend... |
class Hub < ActiveRecord::Base
has_and_belongs_to_many :destinations
attr_accessible :name, :passengers, :destinations, :destination_ids
validates_numericality_of :passengers, :only_integer => true
def self.find_destination(hub_id, destination_1)
if hub_id
hub = Hub.find(hub_id)
if destinat... |
class Author < ApplicationRecord
belongs_to :authorable, polymorphic: true
end
|
class RectanglesController < ApplicationController
before_action :set_rectangle, only: [:update, :destroy]
def index
render json: Rectangle.all
end
def show
render json: Rectangle.find(params[:id])
end
def create
@rectangle = Rectangle.create(rectangle_params)
status = @rectangle.errors.p... |
class CreateMessages < ActiveRecord::Migration
def self.up
create_table :messages do |t|
t.text :subject
t.text :message
t.string :sender
t.string :message_type
t.integer :agency_id
t.integer :department_id
t.integer :unit_id
t.string :attachment
t.string :fi... |
# Displays the status of the current open sprint
require 'net/http'
require 'json'
require 'time'
# Loads configuration file
config = YAML.load_file('config.yml')
USERNAME = config['jira']['username']
PASSWORD = config['jira']['api-key']
JIRA_URI = URI.parse(config['jira']['url'])
STORY_POINTS_CUSTOMFIELD_CODE = conf... |
class IpAddressNetworkPortAssignment < ActiveRecord::Base
acts_as_authorizable
acts_as_reportable
named_scope :def_scope
belongs_to :ip_address
belongs_to :network_port
validates_presence_of :ip_address_id, :network_port_id
validates_uniqueness_of :network_port_id, :scope => [:ip_address_id]
def self... |
require "minitest_helper"
describe "routes acceptance test" do
test "root" do
assert_routing '/', controller: 'home', action: 'index'
end
test "memberships" do
assert_routing({method: :post, path: '/memberships'}, {controller: 'memberships', action: 'create'})
assert_routing({method: :delete, path... |
require 'spec_helper'
describe Job::SendBreakingNewsMobileNotification do
before :each do
stub_request(:post, %r|api\.parse\.com|).to_return(body: { result: true }.to_json)
end
describe '::perform' do
it 'sends the mobile notification' do
alert = create :breaking_news_alert, :mobile, :published
... |
class Season < ActiveRecord::Base
has_many :weeks, dependent: :destroy
has_many :characters, dependent: :destroy
def self.current
order(:id).last
end
end
|
class FontSevillana < Formula
head "https://github.com/google/fonts/raw/main/ofl/sevillana/Sevillana-Regular.ttf", verified: "github.com/google/fonts/"
desc "Sevillana"
homepage "https://fonts.google.com/specimen/Sevillana"
def install
(share/"fonts").install "Sevillana-Regular.ttf"
end
test do
end
en... |
class UsersController < ApplicationController
# skip_authorization_check :only => [:client_home]
load_and_authorize_resource :except => [:client_home, :update_compliance, :track_missed_compliance]
def coach_home
end
def manage_clients
@coach = current_user
@client = User.new
end
def add_... |
class ChangeColumnToUnreadCount < ActiveRecord::Migration[6.0]
def change
change_column :unread_counts, :count, :integer, default: 0
end
end
|
require 'rails_helper'
RSpec.describe AdminUser, type: :model do
it 'has many requests' do
is_expected.to have_many(:requests).dependent(:nullify)
end
end
|
require 'test_helper'
class LaboratoryWorksControllerTest < ActionDispatch::IntegrationTest
setup do
@laboratory_work = laboratory_works(:one)
end
test "should get index" do
get laboratory_works_url
assert_response :success
end
test "should get new" do
get new_laboratory_work_url
assert... |
class AddSizeIdAndColorIdToQuotationLines < ActiveRecord::Migration[5.1]
def change
add_column :quotation_lines, :size_id, :integer
add_column :quotation_lines, :color_id, :integer
end
end
|
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :country
has_many :user_articles
has_... |
require 'spec_helper'
describe 'java::set_java_home' do
context 'set_java_home' do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new
runner.node.override['java']['java_home'] = '/opt/java'
runner.converge(described_recipe)
end
it 'should create the profile.d directory' do
exp... |
# frozen_string_literal: true
require 'bolt_setup_helper'
test_name "Install Bolt via git" do
extend Acceptance::BoltSetupHelper
sha = ''
version = ''
step "Clone repo" do
# Cleanup previous runs
on(bolt, "rm -rf bolt")
on(bolt, "git clone #{git_server}/#{git_fork} bolt")
if git_sha.empty?
... |
require_relative './part_1_solution.rb'
def apply_coupons(cart, coupons)
coupons.each do |element|
item = find_item_by_name_in_collection(element[:item], cart)
if item && item[:count] >= element[:num]
cart << {
:item => "#{item[:item]} W/COUPON",
:price => element[:cost]/element[:num],
... |
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
#require(File.join(File.dirname(__FILE__), 'config', 'boot'))
#
#require 'rake'
#require 'rake/testtask'
#require 'rake/rdoctask'
#
#require 'tasks/rails'
#
re... |
require "kamiyama_gem/version"
module KamiyamaGem
# 生年月日と今の年月日から年齢を計算する
def calc_years(my_birth="19880113")
day = Time.now
today_year = day.strftime("%Y")
today = day.strftime("%m%d")
my_year = my_birth[0, 4]
my_day = my_birth[4, 4]
if today.to_i >= my_day.to_i-1 then
years = (today_year.to_i) - (my_y... |
module Chanko
class ActiveIf
mattr_accessor :blocks, :files, :loaded, :definitions, :expanded_judgements
self.files = []
self.expanded_judgements = []
self.definitions = {}
def initialize(*names, &block)
@options = names.last.is_a?(Hash) ? names.pop : {}
@blocks = names.map do |name|
... |
class CreateGearItems < ActiveRecord::Migration
def change
create_table :gear_items do |t|
t.integer :photo_id
t.string :gear_type, :default => '', :null => false
t.string :name, :default => '', :null => false
t.timestamps
end
create_table :user_gear_items do |t|
t.integer... |
class Patient < ActiveRecord::Base
PHOTO_DIR = (Rails.env == "development") ? "_development/patients/:attachment/:id/:style.:extension" : "patients/:attachment/:id/:style.:extension"
attr_accessor :weight_unit, :height_unit
before_save :set_weight, :set_height
validates_presence_of :name_full
validates_inc... |
require 'test_helper'
class GardenCropsControllerTest < ActionController::TestCase
setup do
@garden_crop = garden_crops(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:garden_crops)
end
test "should get new" do
get :new
assert_respons... |
desc "Run Test::Unit Cases"
task :test do
system("testrb test/*_test.rb")
end
#namespace :test do
# desc "Run RCov analysis"
# task :rcov do
# system(%{rcov -x '.rvm' -x '/test/data/' test/*_test.rb})
# end
#end
begin
require 'jeweler'
Jeweler::Tasks.new do |s|
s.name = "minicomic-backend"
s.execu... |
class Flight
attr_reader :destination, :capacity, :code, :duration, :passengers
def initialize(destination, capacity, code, duration)
@destination = destination
@capacity = capacity
@code = code
@duration = duration
@passengers = []
end
def to_s
"Flight #{@code} to #{@destination} with a capacity #{@ca... |
class Card
attr_accessor :value, :face_up
def initialize(value)
@value = value
@face_up = false
end
def hide
@face_up = false
end
def reveal
@face_up = true
end
def to_s
self.face_up ? value.to_s : "*"
end
def ==(other_card)
value == other_card.value
end
end
class Board
attr_reader :grid, :... |
module Rackblog
class Server
# Article
# {"title"=>"I am title",
# "tags"=>["frog", "bed"],
# "body"=>"this is the body.",
# "time"=>"2015-02-08T17:04:23-08:00"}
def initialize(config)
Rackblog.Config = @config = config
@config[:url]+= "/" unless @config[:url][-1] == '/'
... |
class AssessmentPlan < ActiveRecord::Base
belongs_to :academic_year
has_many :assessment_terms, :dependent => :destroy
accepts_nested_attributes_for :assessment_terms
has_many :assessment_plans_courses
has_many :courses, :through => :assessment_plans_courses
has_many :assessment_groups, :as => :parent
... |
module Bottle
module AMQP
include RetryOnException
attr_accessor :connection, :channel, :reactor_thread
def connect
@amqp_settings.merge!({ :on_tcp_connection_failure => method(:handle_tcp_connection_failure) })
@connection = ::AMQP.connect(@amqp_settings)
puts "Connected to AMQP broke... |
$LOAD_PATH.push File.expand_path('lib', __dir__)
# Maintain your gem's version:
require 'camaleon_cms/version'
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = 'camaleon_cms'
s.version = CamaleonCms::VERSION
s.authors = ['Owen Peredo Diaz']
s.email ... |
class Deck
attr_accessor :cards
def initialize (cards)
@cards = cards
end
def count
cards.count
end
def cards_in_category(category)
current_category = []
@cards.each do|card|
if card.category == category
current_category << card.category
end
end
current_catego... |
require 'vocabularise/request_handler'
module VocabulariSe
HANDLE_MENDELEY_DOCUMENT_SEARCH_TAGGED = "mendeley:document:search_tagged"
HANDLE_MENDELEY_DOCUMENT_SEARCH_TAGGED_PAGE = "mendeley:document:search_tagged:page"
HANDLE_MENDELEY_DOCUMENT_DETAILS = "mendeley:document:details"
PRELOADED_PAGES = 3
REQUIRED... |
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :nombre_empresa, :rut_empresa, :emai... |
require 'rails_helper'
RSpec.shared_examples_for 'votable' do
let(:model) { described_class }
let(:user) { create(:user) }
let(:another_user) { create(:user) }
let(:third_user) { create(:user) }
let(:votable) do
if model.to_s == 'Answer'
question = create(:question, user: user)
create(model.t... |
class Category < ActiveHash::Base
include ActiveHash::Associations
has_many :topics
field :name
self.data = [
{id: 1, name: '無し'},
{id: 2, name: '募集'},
{id: 3, name: '情報'},
{id: 4, name: '質問'},
{id: 5, name: '雑記'},
{id: 6, name: '競売'}
]
end
|
module Tournaments
class EntriesController < ApplicationController
before_action :set_tournament
def index
end
def create
if tournament_params[:players].present?
new_player = Player.find tournament_params[:players]
@tournament.players << new_player
redirect_to tournamen... |
#TEDDIT: Strings - Student's File
# Teddit is a Ruby text based news aggregator. Think Reddit in your terminal.
# This exercise will be used throughout the ruby portion of this course.
# We will incrementally build a news aggregator (next week using API's)
# We will create a more dynamic Teddit, and pull the latest ne... |
class KanbansController < ApplicationController
before_action :set_kanban, only: [:show, :edit, :update, :destroy, :process_entities,
:create_process_entities, :destroy_process_entities,
:finish_production, :history, :release, :lock, :discard, :m... |
module ConsultManagement
class Engine < ::Rails::Engine
isolate_namespace ConsultManagement
# 階層化したlocalesの読み込み
config.paths['config/locales'].glob = "**/*.{rb,yml}"
config.assets.precompile += [config.root.basename.join('*.js'), config.root.basename.join('*.css')]
config.to_prepare do
ro... |
class UserMailer < Devise::Mailer
default from: "support@bookingsports.ru"
layout "mailer"
helper :application # gives access to all helpers defined within `application_helper`.
include Devise::Controllers::UrlHelpers # Optional. eg. `confirmation_url`
def registration_mail(user)
@user = user
mail(to... |
require 'test_helper'
class AppObjectTest < ActiveSupport::TestCase
test "requires a valid app_id" do
object = AppObject.new(app_id: 0)
assert_raises(ActiveRecord::RecordInvalid) do
object.save!
end
end
test "type defaults to 'object'" do
object = AppObject.new(app_id: App.first.id)
o... |
require 'algorithms'
require 'forwardable'
require 'tsort'
require 'shanty/graph'
module Shanty
# Public: Sorts projects using Tarjan's strongly connected components algorithm.
class GraphFactory
include TSort
# Public: Initialise a ProjectLinker.
#
# env - ...
def initialize(env)
@env ... |
class AddForeignIDsToLanguage < ActiveRecord::Migration
def self.up
add_column :phrases, :language_id, :int
add_column :stories, :language_id, :int
end
def self.down
drop_column :phrases, :language_id
drop_column :stories, :language_id
end
end
|
class GphotoUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
storage :file
def store_dir
"uploads/gallery/#{format("%03d",model.gallery_id)}"
end
# ограничение оригинальной картинки
process :resize_to_limit => [1024,1024]
version :thumb200 do
process :resize_to_fill => ... |
# frozen_string_literal: true
module Boring
module Graphql
class InstallGenerator < Rails::Generators::Base
desc "Adds GraphQL to the application"
source_root File.expand_path("templates", __dir__)
OPTIONS = %w(relay batch playground no-graphiql schema)
class_option :skip_resolver_setup... |
require "rails_helper"
RSpec.describe "Commentモデルのテスト", type: :model do
describe "バリデーションのテスト" do
let(:user){ create(:user)}
let(:tweet){ create(:tweet, user_id: user.id)}
let!(:comment){ build(:comment, tweet_id: tweet.id)}
context "tweet_commentカラム" do
it "空欄でないこと" do
comment.twe... |
# battle.rb
require 'sinatra/base'
require_relative 'player'
require_relative 'game'
class Battle < Sinatra::Base
before do
@game = Game.instance
end
get '/' do
erb(:index)
end
post '/play' do
@game = Game.create(Player.new(params[:player1]), Player.new(params[:player2]))
redirect '/play'
... |
require 'securerandom'
require 'json'
require 'matrix'
class Player
attr_accessor :current_coordinates
attr_accessor :current_direction
attr_accessor :character
attr_accessor :last_move
attr_accessor :ws
attr_accessor :id, :alive, :powered_up
attr_accessor :score
attr_accessor :powerup_ticks_left
... |
module Praxis
module RequestStages
class Response < RequestStage
WHITELIST_RESPONSES = [:validation_error]
def execute
response = controller.response
unless action.responses.include?(response.response_name) || WHITELIST_RESPONSES.include?(response.response_name)
raise Exce... |
# frozen_string_literal: true
class ReviewsController < ApplicationController
def index
@lesson = Lesson.find(params[:lesson_id])
@reviews = @lesson.reviews.where(lesson_id: @lesson.id)
end
def show
@student = current_user
@review = Review.find(params[:id])
end
def new
@lesson = Lesson.... |
# Loop through all the numbers, stopping when you encounter a number that is (a) >250 and (b) divisible by 7. Print this number down!
def loopingNumbers
i = 251
while i > 250
if i % 7 == 0
puts i.to_s
break
end
i += 1
end
end
# Print out all the factors for each of the numbers 1 through ... |
require "window"
describe Window do
let(:window) { Window.new([1, 2, 3, 4], 4) }
it "accepts an array and a frame size" do
window.array.should == [1, 2, 3, 4]
window.frame_size == 4
end
describe "#<<" do
it "pushes the last element out" do
window << 5
window.array.should == [2, 3, 4, ... |
# frozen_string_literal: true
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
def after_sign_in_path_for(_resource)
if current_user
home_user_path
elsif current_admin
companies_p... |
atom_feed do |feed|
feed.title( @feed_title )
feed.updated( @people.last.created_at )
@people.each do |person|
feed.entry(person) do |entry|
entry.title( person.name )
entry.content( person.item, :type => 'html' )
entry.content( person.quantity)
entry.content( person.price)
entry... |
=begin
Hi there. This is a slimmed down version of GitReaper. By slim I mean that there isn't a threader, there isn't any coloring, limited output
and only the exit options. Commit pools will be using only a 6 character alphanumeric id instead of "serene-something-something".
-Thanks
Viktharien Volande... |
require 'rails_helper'
RSpec.describe WebhooksController, type: :controller do
describe "POST #receive" do
context "JSON received" do
before(:each){request.headers['Content-Type'] = 'application/json'}
let(:json_file){"#{Rails.root}/spec/fixtures/push_payload.json"}
let(:data){JSON.parse(File.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.