text stringlengths 10 2.61M |
|---|
class Location < ActiveRecord::Base
has_many :job_posts
attr_accessible :name
#validations
validates :name,:presence=>true
def self.all_for_select
self.all.map do| a|
[a.name,a.id]
end
end
end
|
class ClinicsController < ApplicationController
before_action :set_clinic, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
load_and_authorize_resource
respond_to :html
def index
@clinics = Clinic.all
end
def show
end
def new
@clinic = Clinic.new
end
def edit
... |
require 'rails_helper'
RSpec.describe "API::V1::PartnerApprovals", type: :request do
describe "POST /api/v1/partner_approvals" do
let!(:partner) { create(:partner) }
context "with a valid API key" do
subject do
headers = {
"ACCEPT" => "application/json",
"X-Api-Key" => ENV[... |
Rails.application.routes.draw do
resources :albums, only: :index
root to: 'albums#index'
end
|
require "rails_helper"
describe QueueItemsController do
describe "GET index" do
it "sets the @queue_items to the queue items of the logged in user" do
abby = Fabricate(:user)
session[:user_id] = abby.id
queue_item1 = Fabricate(:queue_item, user: abby)
queue_item2 = Fabricate(:queue_item, user: abby)
... |
# -*- encoding : utf-8 -*-
module DslUtil
class AdminDriver
include Capybara::DSL
include ::RSpec::Matchers
include DslUtil
def add_person_field(options = {})
params = parse_params(options, {
name: nil,
type: 'String',
required: false
})
edit_people_fields
... |
require 'spec_helper'
module Fakes
describe ArgMatchFactory do
context 'when creating an argument matcher' do
context 'and none of the arguments are matchers themselves' do
before(:each) do
@result = ArgMatchFactory.create_arg_matcher_using([2, 3, 4])
end
it 'should creat... |
require "mime_type_list/version"
module MimeTypeList
class BaseType
class << self
def append_non_standard_extensions(non_standard_extensions, extensions)
extensions_to_add = non_standard_extensions.select { |ext| !extensions.include?(ext) }
extensions.concat(extensions_to_add)
end
... |
module Refinery
module Caststone
class Engine < Rails::Engine
include Refinery::Engine
isolate_namespace Refinery::Caststone
engine_name :refinery_caststone
paths = {
shared: Pathname.new('refinery/admin'),
fields: Pathname.new('refinery/caststone/admin/product_groups/fie... |
# frozen_string_literal: true
require_relative 'benchmark_base'
# Lotus benchmark class
class LotusBenchmark < BenchmarkBase
def default_config
toml_str = syscall(target, 'config', 'default')
Tomlrb.parse(toml_str)
end
def db_dir
lotus_path = ENV.fetch('LOTUS_PATH', nil)
"#{lotus_path}/datastor... |
# A method to reverse the words in a sentence, in place.
# Time complexity: linear O(n) where n is the number of elements in the sentence
# Space complexity: Constant O(1) as we only use a couple of spaces like start-index or i and they wont change.
def reverse_sentence(my_sentence)
return nil if my_sentence == nil
... |
########################################################
#
# Synonym
#
# From Basic Computer Games (1978)
#
# A synonym of a word is another word (in the English language) which has the same,
# or very nearly the same, meaning. This program tests your knowledge of synonyms
# of a few common words.
#
# The computer choo... |
# T1 and T2 are two very large binary trees, with T1 much bigger than T2, Create an
# algorithm to determine if T2 is a subtree of T1.
def check_subtree(tree1, tree2)
# due to the depth of T1 being much larger than T2 a BFS seems more logical
bfs(tree1.head, tree2,head)
end
def bfs(head, node)
queue = head.child... |
class RegistrationsController < ApplicationController
def new
end
def create
user = User.create!(create_params)
if user.save!
redirect_to log_in_path
else
flash.now[:danger] = "Invalid combination"
redirect_to registrations_path
end
end
private
def create_params
params.require... |
require 'spec_helper'
require 'testdata'
require 'topicz/commands/list_command'
describe Topicz::Commands::ListCommand do
it 'produces no output in case of 0 matches' do
with_testdata do
expect { Topicz::Commands::ListCommand.new(nil, ['zzz']).execute }.to output('').to_stdout
end
end
it 'produce... |
require 'backup/connection/cloudfiles'
module Backup
module Storage
class CloudFiles < Base
# Stores the backup file on the remote server using Rackspace Cloud Files
def initialize(adapter)
cf = Backup::Connection::CloudFiles.new(adapter)
cf.connect
cf.store
end
en... |
class NewsController < ApplicationController
before_action :require_user, except: [:index, :show]
before_action :find_news , only: [:show, :edit, :update, :destroy]
def index
@newses = News.order('created_at DESC').page params[:page].per(3)
end
def show
end
def new
@news = News.new
end
de... |
$LOAD_PATH.push File.expand_path('../lib', __FILE__)
# Maintain your gem's version:
require 'collection_north/version'
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = 'collection_north'
s.version = CollectionNorth::VERSION
s.authors = ['Matt Barnett', 'Sha... |
class CreateQsheets < ActiveRecord::Migration
def change
create_table :qsheets do |t|
t.references :division, foreign_key: true
# t.references :questions, foreign_key: true
t.timestamps null: false
end
end
end
|
class User < ActiveRecord::Base
has_one :session
validates :name, length: { in: 4..25, message: "must be between 4 and 25 characters" }, if: :name_entered
# TODO: Get better regex for email validation
validates_format_of :email,
:with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
validates :email, ... |
require "spec_helper"
RSpec.describe Veeqo::Request do
describe "#run" do
context "with 2xx response" do
it "retrieves a resource via specified http verb" do
stub_ping_request_via_get
response = Veeqo::Request.new(:get, "ping").run
expect(response.code.to_i).to eq(200)
end
... |
begin
require 'rubygems'
require 'rake'
require 'rspec/core/rake_task'
task :default => [:spec]
desc 'Run the code in specs'
RSpec::Core::RakeTask.new(:spec) do |t|
t.pattern = "spec/**/*_spec.rb"
end
rescue LoadError
end
# Local Variables:
# mode: ruby
# indent-tabs-mode: t
# tab-width: 3
# ruby-indent-l... |
require 'spec_helper'
describe Mappable do
let(:src_class_name) { 'Src' + SecureRandom.hex(10) }
let(:src_class) do
kls = Struct.new(:first_name,
:last_name,
:email
) do
include Mappable
def name
"#{first_name} #{last_name}"
... |
class Conversation < ActiveRecord::Base
has_many :messages, dependent: :destroy
validates_uniqueness_of :sender_id, :scope => :recipient_id
scope :involving, -> (user) do
where("conversations.sender_id =? OR conversations.recipient_id =?", user.id, user.id)
end
scope :between, -> (sender_id, reci... |
class ThanhviensController < ApplicationController
def new
flash.clear
@thanhvien = Thanhvien.new
end
def edit
end
def create
@thanhvien = Thanhvien.new(thanhvien_params)
if params[:thanhvien][:password] == params[:thanhvien][:confirm_password]
if Tha... |
class Review < ApplicationRecord
belongs_to :restaurant
validates :content, :rating, presence: true
validates :rating, inclusion: {
in: [0, 1, 2, 3, 4, 5], message: 'must be from 0 to 5.'
}
validates :rating, numericality: true
end
|
FactoryGirl.define do
factory :profile do
user
sequence(:first_name) { |n| "FirstName#{n}" }
sequence(:last_name) { |n| "LastName#{n}" }
sequence(:nickname) { |n| "Nickname#{n}" }
end
end
|
require 'spec_helper'
describe "clusters/new.html.erb" do
let(:cluster) do
mock_model("Cluster").as_new_record.as_null_object
end
before do
assign(:cluster, cluster)
end
it "renders a form to create a cluster" do
render
rendered.should have_selector("form",
:method => "post",
... |
class UserSerializer < ActiveModel::Serializer
attributes :id, :user_name
has_many :workstations
has_many :message_routes
end
|
class AddUserToApis < ActiveRecord::Migration[5.2]
def change
add_reference :apis, :user, foreign_key: true
end
end
|
class Issue < ActiveRecord::Base
validates :description, :db_name, :sql_dml, :sql_rollback, :presence => true
has_many :tickets
end
|
Rails.application.routes.draw do
get 'shop/index'
get 'shop/search'
get 'sessions/new'
get 'static_pages/home'
get 'static_pages/help'
get '/signup', to: 'users#new'
resources :users
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#d... |
class ProductsController < ApplicationController
skip_before_action :authenticate_user!, only: [ :index ]
def new
@product = Product.new
end
def create
@product = Product.new(product_params)
@product.user = current_user
if @product.save
redirect_to products_path(@product)
else
... |
class Roster < SuperModel::Base
include SuperModel::Redis::Model
include SuperModel::Timestamp::Model
attributes :count
belongs_to :user
validates_presence_of :user_id
belongs_to :room
indexes :user_id
class << self
def subscribe
Juggernaut.subscribe do |event, data|
data.def... |
### ARRAY ORGANIZER
# Instructions:
# Count elements in an Array by returning a hash with keys of the elements and values of the amount of times they occur.
# test = ['cat', 'dog', 'fish', 'fish']
# def count(array)
# ___
# end
# count(test) #=> { 'cat' => 1, 'dog' => 1, 'fish' => 2 })
def count(array)
uniq... |
# frozen_string_literal: true
# Financial Transaction Model
class Transaction
include Mongoid::Document
include Mongoid::Timestamps
attr_accessor :destination_account_id
before_create :build_transfer_destination, if: :destination_account_id
before_update :change_transfer_associated_attributes, if: :transfe... |
class Vote < ActiveRecord::Base
belongs_to :user
belongs_to :votable, polymorphic: :true
validates :user, uniqueness: {scope: [:votable_id, :votable_type]},
presence: :true
validate :is_not_own_votable?
protected
def is_not_own_votable?
if self.votable.user == self.user
err... |
# Class connecting to mongo
class Record
def find_nested(nested_collection, query)
# TODO: Improve querying on Mongoid sub-collections
(send(nested_collection).select do |record|
(query.to_a - record.attributes.keys.reduce({}) do |prev, k|
prev.merge(k => record.attributes[k].to_s)
end.to_... |
class CreateStoreLinks < ActiveRecord::Migration
def change
create_table :store_links do |t|
t.string :name
t.string :source
t.string :url
t.belongs_to :pant
t.timestamps
end
end
end
|
require "spec_helper"
describe UserTeamsController do
describe "routing" do
it "routes to #create" do
post("/users/1/user_teams").should route_to("user_teams#create", :user_id => "1")
end
it "routes to #destroy" do
delete("/users/2/user_teams/1").should route_to("user_teams#destroy", :id =>... |
require 'rails_helper'
require 'spec_helper'
RSpec.describe StaticPagesController, :type => :controller do
render_views
before :each do
@base_title = "Bijal's App with Ruby on Rails"
end
it "should get home" do
get :home
expect(response).to have_http_status(200)
expect(response.body).to have_... |
class AddRatingToProfile < ActiveRecord::Migration[5.2]
def change
add_column :profiles, :user_rating, :decimal, default: 5.0
end
end
|
class Point < ActiveRecord::Base
attr_accessible :content, :pro, :weight, :list_id, :position
belongs_to :list
scope :ispro, where(:pro => true)
scope :iscon, where(:pro => false)
validates :list_id, presence: true
validates :content, presence: true
end
|
class ShopService::SlackResponder
attr_reader :shop
def initialize(shop)
@shop = shop
end
def attachments
"[{
'fallback': 'Daily Report - #{format_date(DateTime.current)}',
'pretext': 'Daily Report - #{format_date(DateTime.current)}',
'color': '#7AB55C',
'mrkdwn_in': ['text', '... |
require_relative "movie"
class NewMovie < Movie
def to_s
"Movie(2000-2021): The title - #{@title} - old movie (#{@date} year)"
end
end
|
class User < ActiveRecord::Base
include BCrypt
validates :email, :password, presence: true
validates :email, uniqueness: true
# def password
# @password ||= Password.new(password_hash)
# end
# def password=(new_password)
# @password = Password.create(new_password)
# self.password_hash = @passwo... |
class Diocese < ActiveRecord::Base
has_many :churches
validates :name, presence: true, uniqueness: true, case_sensitive: false
end
|
class Company < ApplicationRecord
has_many :cpus
has_many :vgas
end
|
require "spec_helper"
describe RawMotionDataController do
describe "routing" do
it "routes to #index" do
get("/raw_motion_data").should route_to("raw_motion_data#index")
end
it "routes to #new" do
get("/raw_motion_data/new").should route_to("raw_motion_data#new")
end
it "routes to ... |
class Bullet
attr_accessor :x, :y, :alive
def initialize(window)
@window = window
@icon = Gosu::Image.new(@window,"H:/Ruby file/picture/bce.jpg",true)#if change file place here must change either.
@y = 0
@x = rand(@window.width)
@alive = true
end
def update(laser)
@y = @y + 10
if @y ... |
class KnowledgeEntry < ActiveRecord::Base
validates_presence_of :title, :content
acts_as_taggable_on :tags
named_scope :recent, {
:limit => 15,
:order => 'created_at DESC'
}
define_index do
indexes title
indexes content
has created_at
end
def after_destroy()
check_tagging... |
class DeliveryOrder < ApplicationRecord
acts_as_paranoid
validates_as_paranoid
has_paper_trail
validates :sequence_input, :sequence_output, presence: true
end
# == Schema Information
#
# Table name: delivery_orders
#
# id :bigint(8) not null, primary key
# deleted_at :datetime
# ... |
class PracticesController < ApplicationController
load_and_authorize_resource
# GET /practices
# GET /practices.json
def index
@practices = Practice.order("practice_name").paginate(:page => params[:page], :per_page => 20)
respond_to do |format|
format.html # index.html.erb
format.json { re... |
class Tag < ActiveRecord::Base
has_many :linkers
has_many :posts, :through => :linkers
end
|
Given %r(на уровне "(.*)" следующие подсказки:$)i do |level_name, hints_table|
level = Level.find_by_name(level_name)
hints_table.hashes.each do |hash|
text = hash['Текст']
delay = hash['Через'].match(/(\d+) минут.?/)[1]
Given %{админ добавил подсказку "#{text}" через #{delay} минут на уровне "#{level_... |
require "pry"
class School
attr_accessor :roster, :name
@student_hash = {}
def initialize(roster)
@roster = {}
@name = name
end
def add_student(student_name, grade)
roster[grade] ||= []
roster[grade] << student_name
end
# def add_student(student_name, grade)
# if ... |
# Update and read user preferences, which are arbitrayr key/val pairs
class UserPreferenceController < ApplicationController
before_filter :authorize
before_filter :require_allow_read_prefs, :only => [:read_one, :read]
before_filter :require_allow_write_prefs, :except => [:read_one, :read]
def read_one
pre... |
class FetchCoordinatesFromAddressService
URL_BASE = "https://maps.googleapis.com/maps/api/geocode/json?key=#{ENV['GOOGLE_MAPS_API_KEY']}"
def self.call(address)
encoded_address = URI.encode(address)
url = URL_BASE + "&address=" + encoded_address
response = response = HTTParty.get(url)
coordinate... |
require 'byebug/command'
module Byebug
#
# Edit a file from byebug's prompt.
#
class EditCommand < Command
self.allow_in_control = true
def regexp
/^\s* ed(?:it)? (?:\s+(\S+))? \s*$/x
end
def execute
if !@match[1]
return errmsg(pr('edit.errors.state')) unless @state.file
... |
require 'test_helper'
class PelecardTest < Test::Unit::TestCase
def setup
@gateway = PelecardGateway.new(
login: 'login',
password: 'password',
terminal_no: '12345'
)
@credit_card = credit_card
@token = '1477499800'
@amount = 100
@options = {
id: "1234567"
}
en... |
class ListsController < ApplicationController
before_action :require_login, only: [:new]
def index
@list = List.all
end
def show
@list = List.find(params[:id])
@user = @list.user
@not = []
@not_end =[]
@list.not_avail.each do |key, item|
@not << item
@not_end << item
@... |
require 'spec_helper'
require 'json'
describe TestdroidAPI::DeviceRun do
before :all do
VCR.use_cassette('dr_oauth2_auth_device_runs') do
@user = client.authorize
end
end
it 'get device runs' do
VCR.use_cassette('dr_run_33044722_device_runs') do
expect(@user.projects.get(33... |
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :zaim_id
t.string :mode
t.string :name
t.integer :sort
t.string :active
t.date :modified
t.string :zaim_parent_category_id
t.string :zaim_local_id
t.timestamp... |
require "spec_helper"
RSpec.describe "Day 14: Chocolate Charts" do
let(:runner) { Runner.new("2018/14") }
describe "Part One" do
it "calculates the scores of the recipes after improvement" do
expect(runner.execute!("9", part: 1)).to eq("5158916779")
expect(runner.execute!("5", part: 1)).to eq("012... |
namespace :fund_categories do
desc "batch load sina fund categories"
task :batch_load => :environment do
categories = eval(File.read(File.expand_path("../fund_categories.json", __FILE__)))
categories.each do |category_attributes|
category = FundCategory.find_or_initialize_by(name: category_attributes[... |
class CreateCampsites < ActiveRecord::Migration
def self.up
create_table :campsites do |t|
t.integer :length
t.integer :width
t.integer :amps
t.boolean :water
t.boolean :sewer
t.boolean :cable
t.references :campground
t.timestamps
end
end
def self.down
... |
require 'rails_helper'
describe User, type: :model do
context '有効な情報を入力したとき' do
it '正常に登録される' do
user = FactoryBot.build(:user)
expect(user.valid?).to eq(true)
end
end
context '無効な情報を入力したとき' do
it 'ユーザー名が存在しないためエラーとなる' do
user = FactoryBot.build(:user, name: nil)
expect(user.... |
class FontGohufontNerdFont < Formula
version "2.3.3"
sha256 "056c70455743518b92634eef24ee762ee58f9c18449400854d2dff89226d6e33"
url "https://github.com/ryanoasis/nerd-fonts/releases/download/v#{version}/Gohu.zip"
desc "GohuFont Nerd Font (Gohu)"
desc "Developer targeted fonts with a high number of glyphs"
ho... |
require 'board'
describe Board do
let(:board) {Board.new}
it 'has a grid' do
expect(board.grid).to_not eq nil
end
it 'returns SEA when asked a coordinate' do
x = 1
y = :A
expect(board.cell(x,y)).to eq :SEA
end
it "returns nil when passed an incorrect coordinate" do
x = 3
y = :A... |
class StatisticsController < ApplicationController
def show
stats = MonthlyStats.new(current_user.id).generate
render json: { data: stats }
end
end
|
=begin
Equipment Skills System Script
by Fomar0153
Version 1.1
----------------------
Notes
----------------------
Requires an AP System if you want characters to
learn skills pernamently.
If using my Custom Equipment Slots script then
make sure this script is above the Equipment Slots Script
and make sure you have the... |
# Read about factories at http://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :feature do
name "The feature name"
description "My description text"
project
sprint
priority "High"
actor "user"
points 8
end
end
|
require 'test_helper'
class EnquitsControllerTest < ActionController::TestCase
setup do
@enquit = enquits(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:enquits)
end
test "should get new" do
get :new
assert_response :success
end
... |
class CreateStudents < ActiveRecord::Migration
def change
create_table :students do |t|
t.integer :nr_matricol
t.string :nume
t.string :prenume
t.boolean :bursa
t.integer :camin
t.timestamps null: false
end
end
end
|
require 'test_helper'
class CommentTest < ActiveSupport::TestCase
def setup
@user = users(:mysize1)
@kickspost = kicksposts(:orange)
@comment = @user.comments.build( kickspost_id: @kickspost.id,
reply_id: 0,
content: "Nice shoes... |
class ChangeOmelettesToUseRegusers < ActiveRecord::Migration[5.0]
def change
rename_column(:omelettes, :user_id, :reg_user_id)
end
end
|
# frozen_string_literal: true
module ZoomSlack
class Syncer
def initialize(config,
profile_updater: ProfileUpdater.new(token: config.token),
process_detector: ProcessDetector.for_platform)
self.config = config
self.profile_updater = profile_updater
self.pro... |
require 'rails_helper'
RSpec.describe EventPresenter, type: :presenter do
describe '#initialize' do
it 'sets instance variables' do
time = Time.new(2016, 03, 25, 13, 37, 00)
allow(Time).to receive(:current) { time }
events = [build_stubbed(:event), build_stubbed(:event)]
presenter = Event... |
# frozen_string_literal: true
require 'rails_helper'
describe 'Login' do
let(:email) { 'some@email.com' }
let(:password) { 'password' }
scenario 'user can sign up', js: true do
visit '/'
click_link 'Sign Up'
fill_in 'email', with: email
fill_in 'password', with: password
fill_in 'password-c... |
class Job < ApplicationRecord
belongs_to :category, optional: true
validates :title, :company, :description, :requirements, :url, :category_id, :location, :min_salary, :max_salary, :access_key, presence:true
validates :min_salary, :max_salary, numericality: {
greater_than_or_equal_to: 0
}
validates :url, ... |
=begin
#===============================================================================
Title: Class Graphics
Author: Hime
Date: Aug 12, 2013
--------------------------------------------------------------------------------
** Change log
Aug 12, 2013
- Does not refresh graphics if actor is not finished initializ... |
class Student < ActiveRecord::Base
belongs_to :school
belongs_to :referral
has_and_belongs_to_many :guardians
end |
class Label < ActiveRecord::Base
attr_accessible :name
has_many :label_tags
has_many :recipes, :through => :label_tags
end
|
class Flash < Fighter
def initialize
@name = "Flash"
@opening_line = "Hey, what's that?!?!"
@moves = [
Move.new('looky here', EFFECT_TYPES::STUN, 10),
Move.new('over here', EFFECT_TYPES::STUN, 40),
Move.new('eye poke', EFFECT_TYPES::STUN, 80)
]
@special_move = SpecialMove.new(... |
# 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 TestsController < ApplicationController
before_action :set_test, only: [:show]
def show
end
def index
@q = Test.includes([:user_answers, :translations, publisher: [:owners], comments: [:author]]).search
@order = 'created_at desc'
if params[:q] && params[:q][:s]
@order = params[:q][:s]
end
i... |
require 'rails_helper'
RSpec.describe "StaticPages" do
describe "Home page" do
it "works! (now write some real specs)" do
visit '/static_pages/home'
expect(page).to have_content('Sample App')
end
end
end
|
class TestimoniesController < ApplicationController
def index
@testimonies = Testimony.all
end
def new
@testimony = Testimony.new
end
def edit
@testimony = Testimony.find(params[:id])
end
def create
@testimony = Testimony.new(testimony_params)
... |
# coding: utf-8
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "tech_docs_gem/version"
Gem::Specification.new do |spec|
spec.name = "tech_docs_gem"
spec.version = TechDocsGem::VERSION
spec.authors = ["Tijmen Brommet"]
spec.email ... |
class Status < ActiveRecord::Base
acts_as_authorizable
acts_as_audited
named_scope :def_scope
acts_as_reportable
acts_as_commentable
has_many :nodes
validates_presence_of :name
validates_uniqueness_of :name
def self.default_search_attribute
'name'
end
def before_destroy
unles... |
# Copyright (c) 2009-2011 VMware, Inc.
$:.unshift(File.dirname(__FILE__))
require 'spec_helper'
describe BackupSnapshotCleanerTests do
before :all do
@options = {
:max_days => BackupSnapshotCleanerTests::MAX_DAYS
}
end
it "should do nothing with an empty directory (no snapshot directory )" do
... |
require 'rails_helper'
RSpec.describe ReportsController, type: :controller do
login_user
describe "POST #create" do
context 'format: :js' do
before :each do
create(:protocol)
end
it 'should respond with: :success' do
do_post
expect(response).to be_success
en... |
class Knight < ChessPiece
VALID_MOVE_DISTANCES = [[1, 2], [2, 1]]
def valid_move?(coordinates)
return false if out_of_bounds?(coordinates)
return false unless VALID_MOVE_DISTANCES.include? [diff_in_x(coordinates.x), diff_in_y(coordinates.y)]
!(friendly_piece_at?(coordinates))
end
end
|
class CreateHolidaySundays < ActiveRecord::Migration[5.0]
def change
create_table :holiday_sundays, id: false do |t|
t.date :date
t.string :reason
t.timestamps
end
execute "ALTER TABLE holiday_sundays ADD PRIMARY KEY (date);"
end
end
|
class User < ActiveRecord::Base
attr_accessible :username, :email
has_many :user_challenges
has_many :challenges, :through => :user_challenges
validates_presence_of :username
validates_uniqueness_of :email
#not using default find_or_create_by since it requires
#both name and email to match. Code below... |
# abstract
class CondimentDecorator < Beverage
def get_description
# abstract
raise "# abstract: (get_description) Should be defined in subclasses!"
end
end
|
require 'spec_helper'
describe Post do
it {should respond_to(:body)}
it {should respond_to(:title)}
it {should validate_presence_of(:body)}
it {should validate_presence_of(:title)}
it {should have_db_column(:title).of_type(:string)}
it {should have_db_column(:body).of_type(:text)}
it {should have_many(:c... |
require_relative '../views/meals_view'
require_relative '../models/meal'
class MealsController
def initialize(meal_repository)
@meal_repository = meal_repository
@view = MealsView.new
end
def add
name = @view.ask_for("nome")
price = @view.ask_for("preço").to_i
meal = Meal.new(name: name, ... |
require File.expand_path('../test_helper', __FILE__)
require 'config_parser'
class ReadmeTest < Test::Unit::TestCase
def test_documentation
parser = ConfigParser.new
parser.add :option, 'default' # regular option with a default value
parser.add :switch, true # true makes a --[no-]switch
... |
require 'yaml'
require 'socket'
require 'kytoon/server_group'
module Kytoon
module Util
SSH_OPTS="-o StrictHostKeyChecking=no"
@@configs=nil
def self.hostname
Socket.gethostname
end
def self.load_configs
return @@configs if not @@configs.nil?
config_file=ENV['KYTOON_CONFIG_FILE']
if co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.