text stringlengths 10 2.61M |
|---|
module Raft
class Goliath
class HttpJsonRpcResponder < ::Goliath::API
use ::Goliath::Rack::Render, 'json'
use ::Goliath::Rack::Validation::RequestMethod, %w[POST]
use ::Goliath::Rack::Params
def initialize(node)
@node = node
end
HEADERS = { 'Content-Type' => 'applicat... |
class HomePageController < ApplicationController
def index
@systems=System.order(:name)
@contacts=Contact.all
end
end
|
ActiveAdmin.register_page 'Dashboard' do
menu priority: 1, label: proc{ I18n.t('active_admin.dashboard') }
content title: proc{ I18n.t('active_admin.dashboard') } do
now = Time.current
day_ago = 1.day.ago
beginning_of_day = now.beginning_of_day
beginning_of_week = now.beginning_of_week
beginni... |
class CreateRepetitions < ActiveRecord::Migration[5.2]
def change
create_table :repetitions do |t|
t.integer :user_id, null: false
t.integer :question_id, null: false
t.timestamp :due_at, null: false
t.integer :iteration, null: false
t.integer :interval, null: false
t.integer :... |
module ActionView
class LookupContext
module ViewPaths
def find_all_templates(name, prefix = nil, partial = false)
templates = []
@view_paths.each do |resolver|
template = resolver.find_all(*args_for_lookup(name, prefix, partial)).first
templates << template unless templa... |
class Notifier < ActionMailer::Base
default :from => "myhanhqt96@gmail.com"
def email_friend(article, sender_name, receiver_email)
@article = article
@sender_name = sender_name
mail :to => receiver_email, :subject => "Interesting Article"
end
end |
class PhoneNumber < ApplicationRecord
paginates_per 2
def self.create_random_phone_number
flag = true
phone_number = nil
while flag do
a = [1,2,3,4,5,6].shuffle.first
if a.even?
number = Time.now.to_i.to_s
first_part = number[0..2].to_i
second_part = number[3..5].to... |
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255) default(""), not null
# encrypted_password :string(255) default(""), not null
# reset_password_token :string(255)
# reset_password_sent_at :datetime... |
# Public: Checks which one of two integers are largest.
#
# num1 - The first integer number to compare with.
# num2 - The second integer number to compare with.
#
# Examples
#
# max_of_two(1,5)
# # => 5
#
#
# Returns the largest integer number
def max_of_two(num1,num2)
return num1 if num1 > num2
return num2... |
class Student < ActiveRecord::Base
has_and_belongs_to_many(:periods)
scope(:between, lambda do |start_date, end_date|
where('birthday >= :start_date AND birthday <= :end_date',
{ :start_date => start_date, :end_date => end_date} )
end)
end
|
require 'test_helper'
class ReaderUsersControllerTest < ActionController::TestCase
setup do
@reader_user = reader_users(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:reader_users)
end
test "should get new" do
get :new
assert_respons... |
require 'spec_helper'
describe Feed do
it{ should have_many(:posts)}
it{ should belong_to(:user)}
it{ should be_public}
it{ should have_many(:allowed_users)}
it "returns posts in chronological, descending order" do
feed = FactoryGirl.create :feed
post_earlier = FactoryGirl.create :post, created_at: ... |
require 'spec_helper'
describe Department do
subject { Fabricate :department }
it { should embed_many :homepage_docs }
it { should validate_presence_of :name }
it { should validate_uniqueness_of :name }
it { should have_many :courses }
context "Fabrication" do
it "fabricates a valid department" do
... |
FactoryGirl.define do
factory :post do |f|
f.title "FactoryGirl Ttile"
f.body "Factory Girl Body"
f.category factory: :category
f.posted true
f.keywords "Factory, FactoryGirl"
end
end |
# Matchers for ChefSpec 3
if defined?(ChefSpec)
def create_monit_check(check)
ChefSpec::Matchers::ResourceMatcher.new(:monit_check, :create, check)
end
def remove_monit_check(check)
ChefSpec::Matchers::ResourceMatcher.new(:monit_check, :remove, check)
end
end
|
require 'csv'
CSV.generate do |csv|
headers = %w[PEOPLE_ID ACCT_NAME DISPLAY_DATE AMOUNT DONATION_ID DESIGNATION MOTIVATION
PAYMENT_METHOD MEMO TENDERED_AMOUNT TENDERED_CURRENCY ADJUSTMENT_TYPE]
csv << headers
@donations.each do |donation|
csv << [donation.donor_account_id,
donation... |
require 'rails_helper'
RSpec.describe Color, type: :model do
describe 'when the color index is picked by id' do
it 'is expected to return a hash of colors' do
color = Color.new.pick_by_id(1)
expect(color).to eq({ id: 1, color_name: 'gray', accent: '#f4f5f7', contrast: '#374151', })
end
end
d... |
Sequel.migration do
change do
create_table(:guests) do
primary_key :id
column :first_name, :varchar
column :last_name, :varchar
column :email, :varchar
end
end
end
|
require 'rails_helper'
describe 'Institution::create', type: :feature do
let(:responsible) { create(:responsible) }
let(:resource_name) { Institution.model_name.human }
let!(:external_member) { create(:external_member) }
before do
login_as(responsible, scope: :professor)
end
describe '#create' do
... |
module Ricer::Plugins::Quote
class Subscribe < Ricer::Plugin
is_announce_trigger "subscribe"
# Static subscribe
subscribe('ricer/quote/added') do |quote|
# Get instance and do it
bot.get_plugin('Quote/Subscribe').announce_quote(quote)
end
# Instance does it
def announce_quot... |
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'addressable'
require 'fileutils'
require 'json'
require 'net/http'
require 'uri'
# Cache handling
module Cache
@cache_dir = '/tmp/similarweb/'
def self.fetch(site)
path = "#{@cache_dir}#{site}"
File.read(path) if File.exist?(path)
end
def se... |
require 'rails_helper'
RSpec.describe LessonCategoriesController, :type => :controller do
before do
@user = FactoryGirl.create :user
sign_in :user, @user
FactoryGirl.create :course
Attending.create(user_id: 1, course_id: 1, role: 2)
end
describe "POST create" do
context 'valid' do
it 'c... |
class AddCloneColumnToStories < ActiveRecord::Migration
def change
add_column :stories, :clone, :boolean
end
end
|
class LineItemsController < Spree::BaseController
def destroy
if @order = current_order
@line_item = current_order.line_items.find(params[:id])
@line_item.destroy
redirect_to cart_path
end
end
end
|
require 'thor/actions/templater'
require 'open-uri'
class Thor
module Actions
# Gets the content at the given address and places it at the given relative
# destination. If a block is given instead of destination, the content of
# the url is yielded and used as location.
#
# ==== Parameters
#... |
require 'prawn_charts/layers/layer'
module PrawnCharts
module Layers
# Line (horizontal) graph.
class Line < Layer
def draw(pdf, coords, options={})
# Include options provided when the object was created
options.merge!(@options)
pdf.reset_text_marks
stroke_width = (o... |
require 'entity'
require 'position'
# A ship in the game.
# id: The ship ID.
# x: The ship x-coordinate.
# y: The ship y-coordinate.
# radius: The ship radius.
# owner: The player ID of the owner, if any. If nil, the ship is not owned.
# health: The ship's remaining health.
# docking_status: one of (UNDOCKED, DOCKED,... |
class Stack
def initialize #create ivar to store stack here!
@stack = []
end
def push(el) #adds an element to the stack
@stack << el
end
def pop #removes one element from the stack
@stack.pop
end
def peek #returns, but doesn't remove... |
require 'rails_helper'
RSpec.describe UserSession, type: :model do
let(:us) { build :user_session }
let(:dt) { DateTime.new(2000, 1, 1, 0, 0, 0) }
it '正常系' do
expect(us.save).to be_truthy
end
it 'tokenの存在性チェック' do
us.token = ''
expect(us.valid?).to be_falsy
end
it 'tokenの一意性チェック' ... |
class AddOnboardedStateToAccounts < ActiveRecord::Migration[5.0]
def change
add_column :accounts, :onboarding_state, :string, default: "home_airports", null: false
add_index :accounts, :onboarding_state
remove_column :accounts, :onboarded_home_airports, :boolean, default: false, null: false
remove_co... |
Spree::Order.class_eval do
after_commit :touch_shipments
private
def touch_shipments
self.shipments.update_all(updated_at: Time.now)
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :set_locale
# if Rails.env.production?
# before_filter :authenticate
# protected
#... |
class UsersController < ApplicationController
before_action :logged_in_user, only: [:index, :edit, :update, :destroy] # this 'before_filter' runs a method before the specified methods :edit and :update (ie only the owner of a profile can edit this profile).
before_action :correct_user, only: [:edit, :update] # thi... |
module CardValues
SUITS = [ "♣︎", "♦︎", "♥︎", "♠︎" ]
VALUES = {
2=>"2", 3=>"3", 4=>"4", 5=>"5", 6=>"6", 7=>"7", 8=>"8",
9=>"9", 10=>"10", 11=>"J", 12=>"Q", 13=>"K", 14=>"A"
}
HANDS = {
high_card?:0,
one_pair?:1,
two_pair?:2,
three_of_a_kind?:3,
... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe PropertiesController, type: :controller do
let(:current_user) { create(:user) }
let(:session) { { user_id: current_user.id } }
let(:landlord1) { create(:landlord) }
let(:landlord2) { create(:landlord) }
let(:tenant1) { create(:tenant) }
l... |
# $LICENSE
# Copyright 2013-2014 Spotify AB. All rights reserved.
#
# The contents of this file are licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with the
# License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-... |
class AdminsController < ApplicationController
before_action :redirect
def index
@users = User.where(approved: true)
end
def new
@admin = Admin.new
end
def create
@admin = Admin.new(admin_register_params)
if @admin.save
redirect_to admins_path, notice: 'Successfully created new Admi... |
class OrdersController < ApplicationController
before_action :set_order, except: [:new, :create, :show]
# don't want to show only current order
before_action :set_products, only: [:add_product,
:update_quantity,
:checkout]
before_action... |
name 'test'
maintainer 'Chef Software, Inc.'
maintainer_email 'cookbooks@chef.io'
license 'Apache 2.0'
description 'A test cookbook for lvm'
version '0.1.0'
depends 'lvm'
|
require 'test_helper'
require 'generators/ember/bootstrap_generator'
class BootstrapGeneratorTest < Rails::Generators::TestCase
include GeneratorTestSupport
tests Ember::Generators::BootstrapGenerator
destination File.join(Rails.root, "tmp", "generator_test_output")
setup :prepare_destination
test "Assert... |
Rails.application.routes.draw do
resources :products
# root 'welcome#index'
end
|
class WordsAndMeaningsController < ApplicationController
before_action :confirm_logged_in
def index
@words = Word.all.order("words.word ASC")
end
def show
@word = Word.find(params[:id])
@meanings = Meaning.where("word_id=?",params[:id])
end
def new
# @word = Word.new
@meaning = Meaning... |
class SightingsController < ApplicationController
def index
@sightings = Sighting.all
if params[:region_id].nil?
@sightings = Sighting.all
else
@sightings = Sighting.where(:region_id => params[:region_id])
end
end
def new
@sighting = Sighting.new(params[:sighting]) # ma... |
module CityRenderTreeHelper
class Render
class << self
attr_accessor :h, :options
def render_node(h, options)
@h, @options = h, options
node = options[:node]
node.root? ? "
<div class='span3'><div class='well well-small'>
<h2 class='no-margin'>#{ show_li... |
# @param {Integer[]} nums
# @return {Boolean}
def can_jump(nums)
size = nums.size
last_known_good = size - 1
(size-2).downto(0) do
|i|
last_known_good = i if i + nums[i] >= last_known_good
end
last_known_good == 0
end
|
class Organization < ActiveRecord::Base
validates :name, presence: true, uniqueness: true
validates :description, presence: true
has_many :locations
has_and_belongs_to_many :eligibilities
def self.filter_organizations(params = {})
@organizations = Organization.all
FilterOrganizations.new({organizati... |
require './lib/engine'
describe Engine do
before do
@e = 0
@n = Math::PI/2
@w = Math::PI
@s = Math::PI*3/2
@engine = Engine.new(6,7)
end
it 'move forward to North' do
@engine.process 'f', @n
expect(@engine.x).to eq(6)
expect(@engine.y).to eq(8)
end
it 'move backward to North... |
class TasksMailer < ApplicationMailer
def notify_task_owner(task, current_user)
@task = task
@owner = @task.user
if @owner == current_user
return
end
if @owner.email.present?
mail(to: @owner.email, subject: "You got a new comment!")
end
end
end
|
require 'test_helper'
class TestOraclesControllerTest < ActionController::TestCase
setup do
@test_oracle = test_oracles(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:test_oracles)
end
test "should get new" do
get :new
assert_respons... |
class Player < ActiveRecord::Base
belongs_to :team
belongs_to :user
has_many :score, :dependent => :destroy
scope :top_scorer_for_teams, ->(team_ids) { where(team_id: team_ids).maximum(:points) }
default_scope { order(:position) }
class << self
def for_user(game,user)
team_ids = game.teams.pluck... |
control '5_Appliance_NTP_5.1' do
title 'Validate permissions and configuration of /etc/ntp.conf file'
describe file ('/etc/ntp.conf') do
it { should be_owned_by 'root' }
it { should be_grouped_into 'root' }
its('mode') { should cmp '0640' }
end
describe ntp_conf('/etc/ntp.conf') do
its('setting_... |
require File.expand_path(File.join(File.dirname(__FILE__), *%w[.. .. spec_helper]))
describe '/customers/show' do
before :each do
assigns[:customer] = @customer = Customer.generate!(:description => 'Test Customer')
@apps = Array.new(3) { App.generate!(:customer => @customer) }
end
def do_render
rend... |
require 'spec_helper'
describe "delivery_requests/show" do
before(:each) do
@delivery_request = assign(:delivery_request, stub_model(DeliveryRequest,
:name => "Name",
:email => "Email",
:telephone => "Telephone",
:address => "Address",
:postal_code => "Postal Code",
:city => "... |
Blog::Application.routes.draw do
get 'tags/:tag', to: 'articles#index', as: :tag
resources :articles
root to: 'articles#index'
end
|
require 'rails_helper'
describe Item do
context 'attributes' do
it { is_expected.to respond_to(:name) }
it { is_expected.to respond_to(:description) }
it { is_expected.to respond_to(:unit_price) }
it { is_expected.to respond_to(:merchant_id) }
it { is_expected.to respond_to(:updated_at) }
it ... |
class LandingController < ApplicationController
def index
@message = Message.new
end
def create
@message = Message.new(params[:message])
if @message.valid?
# TODO Send message here
NotificationsMailer.new_message(@message).deliver
redirect_to root_url, notice: "Message sen... |
class User < ApplicationRecord
# So what this is saying is that a user will have a relationship with the memos and that a user can have
# many memos and that it must have a name and an email but the name does not have to be unique but the email
# does meaning if that a user signs up with the same name they... |
class Fertilizer < ActiveRecord::Base
belongs_to :user
has_many :fertilizations, dependent: :destroy
validates_presence_of :name, :n, :p, :k, :s, :ca, :mg, :b
end
|
require 'order'
describe Order do
let(:dish) { double(:dish, name: (0...8).map { (65 + rand(26)).chr }.join) }
let(:dish2) { double(:dish, name: (0...8).map { (65 + rand(26)).chr }.join) }
let(:dish3) { double(:dish, name: (0...8).map { (65 + rand(26)).chr }.join) }
let(:quant) { rand(2...10) }
let(:quant2) ... |
module ApplicationHelper
def include_css_for_controller(_controller_name)
file = Rails.root.join('app', 'assets', 'stylesheets', "#{_controller_name}.scss")
stylesheet_link_tag _controller_name if File.exist?(file)
end
end
|
# $LICENSE
# Copyright 2013-2014 Spotify AB. All rights reserved.
#
# The contents of this file are licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with the
# License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-... |
class Product < ActiveRecord::Base
has_many :order_products
has_many :product_orders, :through => :order_products
scope :visible, -> { where(:visible => true) }
validates_presence_of :name, :price, :bonus_points
validates_numericality_of :quantity, :greater_than_or_equal_to => 0
mount_uploader :product_i... |
class ApplicationController < ActionController::Base
respond_to :json
protect_from_forgery with: :exception
rescue_from ActionController::UnknownFormat, ActionController::RoutingError do
render_frontend
end
def render_frontend
render text: 'ROUND loading...', layout: true
end
def tim?
!!ses... |
panel t("reports.name.#{params[:action]}", :time_group => time_group_t, :time_period => time_period_t), :class => :table do
block do
@report = resource.visits_summary(params).sort {|a,b| a[params[:action]].to_i <=> b[params[:action]].to_i }
if @report.empty?
h3 t('reports.no_visits_recorded')
else
... |
class CreateBooksCategories < ActiveRecord::Migration[5.1]
def change
create_table :books_categories, { :primary_key => :id_category } do |t|
t.string :category_name
t.string :category_description
t.timestamps
end
end
end
|
class CreateTemplates < ActiveRecord::Migration
def change
create_table :templates do |t|
t.string :name
t.text :description
t.string :keywords
t.text :authors
t.boolean :recommended
t.string :source
t.string :type
t.text :documentation
t.timestamps
end
... |
# frozen_string_literal: true
# This version doesn't quite match Primer's third video
# In his version, the original blobs mutate into specific other "species" of blobs
# Mine individually mutates each stat.
class Simulation
def initialize(num_blobs, stats)
@blobs = []
init_blobs(num_blobs, stats)
end
... |
require 'test_helper'
class FeedbacksControllerTest < ActionController::TestCase
def setup
@admin = create(:admin)
@writer = create(:writer)
@submission = create(:submission, writer: @writer)
@desc = create(:description, submission: @submission)
@scrpi_response = create(:response, description: @... |
require 'rails_helper'
RSpec.describe 'Items Index API' do
before :each do
FactoryBot.reload
end
describe 'happy path' do
it 'fetch all items if per page is really big' do
merchant = create(:merchant)
items = create_list(:item, 50, merchant: merchant)
get '/api/v1/items?per_page=25000... |
# Zustand (state) + Configuration (params)
#SRM_KernelBased_Config = Struct.new(:tau_m, :tau_ref, :ref_weight, :const_threshold, :arp)
class SRM_KernelBased_Config
attr_reader :tau_m, :tau_ref, :ref_weight, :const_threshold, :arp
def initialize(tau_m: 0.0, tau_ref: 0.0, ref_weight: 0.0, const_threshold: 0.0, arp:... |
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :word do
name "MyString"
definition "MyText"
example "MyText"
end
end
|
class Api::QuestionsController < ApplicationController
def index
@questions = Question.all();
if topic_id
@questions = Topic.find(topic_id).questions
end
render :index
end
def create
@question = Question.new(question_params)
if (current_user)
@question.author_id = current_us... |
module ModelErrorMessages
class Configuration
attr_accessor :single_error_in_paragraph
attr_accessor :prepend_html
attr_accessor :append_html
attr_accessor :classes
attr_writer :configuration
def initialize
reset
true
end
def reset
@single_error_in_paragraph = true
... |
class Admin < ActiveRecord::Base
attr_accessible :name, :phone_number, :email
#validation
validates :name, :presence => true
validates :phone_number, :presence => true, :format => { :with => /\A[0-9]{10,14}\Z/,
:message => 'only 10 to 12 digits allowed'}, :uniqueness => true
validates :email, :presence ... |
require "spec_helper"
require "securerandom"
RSpec.describe CryptoEnvVar::Utils do
describe "JSON serialization of Hashes" do
let(:data) do
{
"ROMULUS" => SecureRandom.urlsafe_base64(100),
"NUMA_POMPILIUS" => SecureRandom.urlsafe_base64(100),
"TULLUS_HOSTILIUS" => SecureRandom.urlsa... |
class BlacklistedUsernamesController < ApplicationController
def add
usernames = split_param(:usernames)
existing_usernames = Settings.get_list(:blacklisted_usernames)
usernames = (existing_usernames | usernames).map(&:strip).reject(&:empty?).sort.join(',')
Settings.set(:blacklisted_usernames, userna... |
module Todoable
# Client for the Todoable API
class Client
API_ENDPOINT = "http://todoable.teachable.tech/api".freeze
MEDIA_TYPE = "application/json".freeze
AUTH_PATH = "/authenticate".freeze
LISTS_PATH = "/lists".freeze
attr_accessor :username, :password, :token
def initialize
@user... |
# Class to perform math on time-formatted strings.
# Only implemented method is #add, which accepts a time string of
# format '[H]H:MM {AM|PM}', adds the specified number of minutes
# and outputs a similarly formatted string with the new time.
class TimeStringCalc
HOUR_RANGE = (1..12) # Allowed range of inpu... |
require 'spec_helper'
require 'ios_toolchain/config_bootstrapper'
RSpec.describe IosToolchain::ConfigBootstrapper do
let(:project_root) { Dir.mktmpdir }
let(:project_analyzer) { double('ProjectAnalyzer') }
subject { IosToolchain::ConfigBootstrapper.new(project_analyzer) }
describe('#bootstrap!') do
let(:c... |
describe Represent::ResultsNormalized do
let(:substance1) { Substance.new(name: 'Caffeine', common_name: 'Coffee', is_dangerous: false) }
let(:test_kit1) { TestKit.new(name: 'marq', color: Color.new(name: 'red1')) }
let(:test_kit2) { TestKit.new(name: 'blob', color: Color.new(name: 'red1')) }
let(:results) {[
... |
require "tick_tock/card"
module TickTock
class Punch < Value.new(:time_now)
def self.default
with(time_now: Time.method(:now))
end
def card(subject: nil, parent_card: nil)
Card.with(
subject: subject,
parent_card: parent_card,
time_in: nil,
time_out: nil
... |
class RegionsController < ApplicationController
before_action :set_region!, except: [:create, :index, :new]
def index
@regions = Region.all
respond_to do |f|
f.json {render json: @regions}
f.html {render :index}
end
end
def show
@region = Region.find(params[:id])
end
... |
# frozen_string_literal: true
require 'singleton'
module Departments
module Intelligence
module Services
##
# Validations for the inputs / outputs of the methods in {Departments::Intelligence} module.
class Validation
include Singleton
def intelligence_query?(query)
... |
class String
def from_german_to_f
self.gsub(',', '.').to_f
end
end
class Float
def to_german_s
self.to_s.gsub('.', ',')
end
end
class CommissionsValueCombiner
KEYS = [
'Commission Value',
'ACCOUNT - Commission Value',
'CAMPAIGN - Commission Value',
'BRAND - Commission Value',
'BRAN... |
module YACCL
module RelationshipServices
def get_object_relationships(repository_id, object_id, include_sub_relationship_types, relationship_direction, type_id, filter, include_allowable_actions, max_items, skip_count, succinct=false)
required = {succinct: succinct,
cmisselector: 'relation... |
require 'csv'
namespace :test do
task :csv => :environment do
CSV.open('issues_with_orders.csv','wb') do |csv|
CSV.foreach(Rails.root.join('issues.csv')) do |line|
id = line[0]
subject = line[1]
created_on = line[2]
closed_on = line[3]
budget = line[4]
task =... |
class NotificationsMailer < ActionMailer::Base
default :from => "sales@sweepevents.com"
default :to => "sales@sweepevents.com"
def new_message(message)
@message = message
mail(:subject => "Website Contact Request",
:body => "Name: #{@message.name}\nEmail: #{@message.email}\nDescription: #{@mess... |
class Knotebook < ActiveRecord::Base
belongs_to :user
has_many :knotings, :order => :position, :dependent => :destroy
has_many :knotes, :through => :knotings, :order => 'knotings.position', :before_add => :set_knote_user
# has_many :conceptualizations
# has_many :concepts, :through => :conceptualizations, :so... |
module Paramable
module IntanceMethods
def to_param
name.downcase.gsub(' ', '-')
end
end
end
|
class Recipe < ActiveRecord::Base
belongs_to :user
has_many :ingredients, dependent: :destroy
validates :name, presence: true
validates :instruction, length: { maximum: 1000 }
validates :user_id, presence: true
end
|
require 'minitest/autorun'
require_relative '../board.rb'
class TestBoard < Minitest::Test
def test_for_3x3Board
board = Board.new(3,3)
result = [['-','-','-'],['-','-','-'],['-','-','-']]
assert_equal(result, board.board_table)
end
def test_for_4x4Board
board = Board.new(4,4)
result = Array... |
# frozen_string_literal: true
require_relative './modules/accessor.rb'
require_relative './modules/instance_counter.rb'
require_relative './modules/validation.rb'
class Station
include InstanceCounter, Accessor, Validation
attr_reader :name
attr_accessor :trains
REGEXP = /[a-z]/i.freeze
validate :name, :for... |
class CreateTerritories < ActiveRecord::Migration
def change
create_table :territories do |t|
t.string :name, uniqueness: true
t.jsonb :zips, default: '{}'
t.jsonb :zones, default: '{}'
t.timestamps null: false
end
add_index :territories, :name
end
end
|
#require "spec_helper"
describe "Viewing an individual movie" do
it "show the movie's details" do
# Arrange
movie = Movie.create(movie_attributes(image: open("#{Rails.root}/app/assets/images/movie.jpg"),
total_gross: 300_000_000.00))
# Action
visit movie_url(movie)
# Assert
expect(... |
class InstagramAuth < Authorization
def self.model_name
Authorization.model_name
end
def auth_type
return "Instagram"
end
def access_client
auth_client_obj = OAuth2::Client.new(Rails.application.config.auth["instagram"][:client_id], Rails.application.config.auth["instagram"][:client_secret], ... |
class ApiChecklistsForUserContext < ApiBaseContext
def initialize(user)
super
end
def execute
Checklist.for_user(@user).select(:id, :name, :description).all
end
end |
class RoundsController < ApplicationController
# GET /rounds
# GET /rounds.json
def index
rounds_decorator = RoundsDecorator.new(Round.all)
current_round = Round.current_round
respond_to do |format|
format.html
format.json do
render json: {
round: current_round,
... |
require 'csv'
require_relative 'order'
module Grocery
class OnlineOrder < Order
SHIPPING_COST = 10
attr_reader :customer_id, :status
def initialize(id, products, customer_id, status=:pending)
super(id, products)
@customer_id = customer_id
@status = status
end
def total
... |
require 'spec_helper'
require_relative '../../app/models/user'
module LunchZone
describe 'user' do
let(:user) { User.create(:nickname => 'hungryguy',
:email => 'a@example.com') }
let(:restaurant1) { Restaurant.create(:name => 'QQ Sushi') }
let(:restaurant2) { Res... |
require 'rack/test'
require 'bundler'
Bundler.require(:test)
require 'capybara/rspec'
ENV['RACK_ENV'] = 'test'
require File.expand_path '../../application.rb', __FILE__
# VCR.configure do |c|
# c.cassette_library_dir = 'spec/cassettes'
# c.hook_into :webmock
# end
RSpec.configure do |config|
include Rack::Test... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.