text stringlengths 10 2.61M |
|---|
# == Schema Information
#
# Table name: profiles
#
# id :integer not null, primary key
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# first_name :string
# last_name :string
# date_of_birth :datetime
# gender :int... |
class CompanyResearchesController < ApplicationController
def index
@company_researches = CompanyResearch.all
render("company_researches/index.html.erb")
end
def show
@company_research = CompanyResearch.find(params[:id])
render("company_researches/show.html.erb")
end
def new
@company_r... |
class Hotel < ActiveRecord::Base
has_many :reviews
mount_uploader :photo, ImageUploader
validates :name, presence: true, length: {maximum: 50}
validates :rating, presence: true, length: {maximum: 5}
def self.latest
Hotel.order(:updated_at).last
end
end
|
module Services::Searchers
module Errors
ERROR_CODES = {
empty_params: 2,
empty_keywords: 4,
empty_type: 6,
unknown_type: 8
}
end
end
|
class CreateWaterReleases < ActiveRecord::Migration[5.1]
def change
create_table :water_releases do |t|
t.references :dam
t.datetime :start_at
t.datetime :stop_at
t.timestamps
end
end
end
|
# Transformation Step of ETL
class ETL
def self.transform(old_format)
old_format.each_with_object({}) do |(key, value), new_format|
value.each { |e| new_format[e.downcase] = key }
end
end
end
|
# Copyright (c) 2009-2011 VMware, Inc.
require "redis"
$LOAD_PATH.unshift File.join(File.dirname(__FILE__), ".")
require "redis_error"
# Redis client library doesn't support renamed command, so we override the functions here.
class Redis
def config(config_command_name, action, *args)
synchronize do |client|
... |
module Facter::Util::WithPuppet
def with_puppet
# This is in case this fact is running without Puppet loaded
if Module.constants.include? "Puppet"
begin
yield if block_given?
rescue Facter::Util::PuppetCertificateError => detail
# To be as un-intrusive (e.g. when running 'facter') ... |
class Stuff < ApplicationRecord
has_one_attached :image
belongs_to :user
has_many :stuff_categories
has_many :categories, through: :stuff_categories
validates :title, presence: true, length: { maximum: 20 }
validates :description, presence: true, length: {maximum: 300}
validate :image_type
after_commit ... |
class ServicesController < ApplicationController
def create
@service = service.build(params.require(:service).permit(:duration, :price, :service_name))
if @service.save
flash[:success] = "New service created."
redirect_to welcome_url
else
flash.now[:error] = "S... |
class Instructor < ApplicationRecord
has_many :courses
end |
require 'stringio'
module Zlib
# The superclass for all exceptions raised by Ruby/zlib.
class Error < StandardError; end
# constants from zlib.h as linked into Gemstone libgcilnk.so
ZLIB_VERSION = "1.2.5"
Z_NO_FLUSH = 0
# Z_PARTIAL_FLUSH = 1 # will be removed, use Z_SYNC_FLUSH instead
Z_SYNC_FLUSH... |
class CreateCollectibles < ActiveRecord::Migration[6.0]
def change
create_table :collectibles do |t|
t.string :category
t.string :brand
t.string :model
t.string :reference
t.float :retail_price
t.float :resell_value
t.string :description
t.references :user, null: fa... |
Rails.application.routes.draw do
resources :notes
resources :offers
resources :tasks
resources :projects
resources :contacts
resources :companies
root 'root#index'
end
|
require 'router'
require 'byebug'
require './lib/action_dispatch_lite/path_helper'
describe ActionDispatchLite::PathHelper do
PATHS = { edit: '/edit', new: '/new', id: '/:id' }
subject( :route ) { Route.new( Regexp.new( path ), :get, 'CakeOfTheDay', :wow ) }
describe '#method_name' do
context 'when the pa... |
require "rails_helper"
include AccommodationsHelper
RSpec.describe AccommodationsHelper do
describe ".search_reserved_rooms" do
it "finds all reserved rooms" do
room_booking = FactoryGirl.create :present_room_booking
result = search_reserved_rooms(Date.current, Date.current + 5)
expect(resu... |
describe Repositories::Workers::CheckPullRequest do
describe '#perform' do
subject(:worker_result) { described_class.new.perform(pull_request.id) }
let(:pull_request) { create :pull_request }
let(:failure) { false }
let(:error) { nil }
before do
allow(PullRequest).to receive(:find).and_ret... |
require 'gtk3'
require './Classes/boutonNbTentes.rb'
#====== La classe BoutonNbTentes représente les boutons sur le côté gauche de la grille de jeu pour remplir une ligne/colonne d'herbe
class BoutonNbTentesLigne < BoutonNbTentes
#=Variable d'instance
# @bouton : Le bouton
# @coordI, @coordJ : Coordonnées du bo... |
class HomeController < ApplicationController
before_filter :authenticate_user!
def index
@first_time = current_user.new_to_update?
current_user.update_attribute(:new_to_update, false) if @first_time
respond_to do |format|
format.html # index.html.erb
end
end
end
|
# only_even.rb
# Using `next`, modify the code below so that it only prints even numbers.
number = 0
until number == 10
number += 2
puts number
end
puts '----'
# Launch School solution:
number = 0
until number == 10
number += 1
next if number.odd?
puts number
end
|
class CellSerializer < ActiveModel::Serializer
attributes :board_index, :cell_type
end
|
json.exchanges @exchanges do |exchange|
json.extract! exchange, :id, :name, :exchange_kind
end
json.message_routes @message_routes do |message_route|
json.extract! message_route, :id, :from_exchange_id, :to_exchange_id, :routing_key
end
json.route_arguments @route_arguments do |route_argument|
json.extract! rou... |
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery
after_filter :set_csrf_cookie_for_ng, :set_access_control_header
def set_csrf_cookie_for_ng
cookies['XSRF-TOKEN'] = form_authe... |
class Calculator::Freight < Calculator
def self.description
"Freight"
end
def self.register
super
ShippingMethod.register_calculator(self)
end
def compute(shipment)
shipment.adjustment.nil? ? 0 : shipment.adjustment.amount
end
def available?(order,options)
order.weight_of_line_items... |
class NewsController < ApplicationController
include ApplicationHelper
before_filter :can_add_news, only: [:new, :create]
before_filter :can_edit_news, only: [:edit, :update]
before_filter :can_delete_news, only: [:destroy]
def index
@news = New.order('created_at DESC').page(params[:page]).per(10)
end... |
require 'spec_helper'
describe ProjectsController, :type => :controller do
# This should return the minimal set of attributes required to create a valid
# Project. As you add validations to Project, be sure to
# update the return value of this method accordingly.
def valid_attributes
{ 'name' => 'MyString... |
module Naf
class LoggerStylesController < Naf::ApplicationController
before_filter :set_cols_and_attributes
def index
@rows = Naf::LoggerStyle.all
render template: 'naf/datatable'
end
def show
@logger_style = Naf::LoggerStyle.find(params[:id])
end
def destroy
@logge... |
class ProposalFieldedSearchQuery
attr_reader :field_pairs
def initialize(field_pairs)
@field_pairs = field_pairs
end
def present?
return false unless field_pairs
to_s.present?
end
def value_for(key)
if field_pairs && field_pairs.key?(key)
field_pairs[key]
end
end
def to_s
... |
require "./Node"
class LinkedList
def initialize
@count = 0
@top = nil
end
def add(x)
if @top
tmp = @top
while tmp.next
tmp = tmp.next
end
tmp.next = Node.new(x)
else
@top = Node.new(x)
end
end
def showAll()
ary = Array.new
tmp = @top
while tmp.next
ary <<... |
# 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... |
# frozen_string_literal: true
# Challenge
# The method sqrt takes in one square number.
# Fill the method sqrt_recursive that returns the square root of a given number.
# Do not use any built in methods for calculating the square-root and don't try searching through all the numbers. Instead, use a binary-style searc... |
# 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 CreateRequisicoes < ActiveRecord::Migration
def self.up
create_table :requisicoes do |t|
t.string :pedido, :null => false
t.datetime :data, :null => false
t.string :estado, :null => false
t.boolean :emergencial, :null => false
t.boolean :transporte, :null => false
t.re... |
class Profile < ApplicationRecord
has_attachment :avatar, accept: [:jpg, :png, :gif]
has_many :posts, dependent: :destroy
belongs_to :user
def full_name
"#{first_name} #{last_name}"
end
end
|
# encoding: utf-8
module HerokuCloudBackup
VERSION = "0.3.0"
end
|
require_relative '../automated_init'
context "Error Data Equality" do
test "When attributes are equal" do
error_data_1 = ErrorData::Controls::ErrorData.example
error_data_2 = ErrorData::Controls::ErrorData.example
assert(error_data_1 == error_data_2)
end
end
|
class QuestionsController < ApplicationController
def new
@book = Book.find_by_id(params[:book_id])
render :new
end
def create
params[:question][:book_id] = params[:book_id]
@question = current_user.questions.new(params[:question])
if @question.save
flash[:alert] = ["Question ... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'OmniauthCallbacksController', type: :request do
describe 'Oauth' do
it 'should register a new client', test: true do
expect { login }.to change(ActiveStorage::Attachment, :count).by(1)
expect(User.all.count).to eq(1)
expect(r... |
module Api
class ServicesController < ApiController
before_action :authenticate_resource
def index
render json: ListServiceSerializer.new(services: BaseService.all).to_json
end
end
end
|
require './template_method_pattern/template.rb'
class HTMLMenu < Menu #inherits from the basic menu class, which contains the menu template
#contains output for HTML formatting of the menu
def output_start
puts '<html>'
end
def output_head
puts '<head>'
puts "<title> Menu for #{Time.now} </title>"
puts ... |
class Review < ActiveRecord::Base
validates :rating, presence: true
validates :description, presence: true
validates :reservation_id, presence: true
validate :reservation_accepted
belongs_to :reservation
belongs_to :guest, :class_name => "User"
def reservation_accepted
if !(reservation && self.reser... |
# frozen_string_literal: true
require 'bolt_command_helper'
test_name "C100548: \
bolt script run should execute script on remote hosts via ssh" do
extend Acceptance::BoltCommandHelper
ssh_nodes = select_hosts(roles: ['ssh'])
skip_test('no applicable nodes to test on') if ssh_nodes.empty?
script ... |
class ParticularDiscount < ActiveRecord::Base
belongs_to :particular_payment
named_scope :for_particular_payments, lambda { |tran_id| {
:conditions => ["particular_payments.finance_transaction_id = ?", tran_id],
:joins => :particul... |
require 'spec_helper'
describe SurveysController do
let(:user) { create(:user) }
let(:admin) { create(:admin) }
# create a mock model of a survey
# (will raise an error if any methods are called on it)
# this will ensure that nothing is making it past authorization
let(:survey) { mock_model(Survey, id: 1)}
c... |
# frozen_string_literal: true
class DiscordMessageShim
extend Memoist
def initialize(event, pattern, plug)
@event = event
@pattern = pattern[0]
@opts = pattern[1]
@plug = plug
end
def inner
@event
end
def message
@event.message.content
end
def params
groups = message.mat... |
class Htop < DebianFormula
homepage 'http://htop.sourceforge.net/'
url 'http://downloads.sourceforge.net/project/htop/htop/0.9/htop-0.9.tar.gz'
md5 '7c5507f35f363f3f40183a2ba3c561f8'
name 'htop'
section 'utils'
version '0.9+github1'
description 'an interactive process viewer for Linux'
build_depends '... |
require 'yaml'
require 'base_screen.rb'
require 'log.rb'
require 'constants.rb'
include Constants
class Meditation < BaseScreen
def initialize
userdata = File.join(DATA_PATH,"userdata.yml")
@loaded_data = YAML.load_file(userdata)
end
def start!
setup
meditate
reflect
save_data
end
def setup
# Set... |
class Supply < ActiveRecord::Base
belongs_to :game
belongs_to :card_pile, dependent: :destroy
has_many :piles, through: :card_pile
has_many :cards, through: :piles
def name
return card_pile.name
end
end
|
class RoleConstraint
def initialize(*roles)
@roles = roles
end
def matches?(request)
@roles.include?(current_user)
end
end |
class Admin::BaseController < ApplicationController
before_action :authorized?
def authorized?
if current_user.nil? || !current_user.admin?
flash[:warning] = "Sorry but you are not authorized to view that page"
log_out
redirect_to '/'
end
else
true
end
end
|
# frozen_string_literal: true
module AsyncHelpers
# Wait for block to return true of raise error
def wait(timeout = 1)
until yield
sleep 0.1
timeout -= 0.1
raise "Timeout error" unless timeout > 0
end
end
def concurrently(enum)
enum.map { |*x| Concurrent::Future.execute { yield(*... |
require 'test_helper'
class FreeBusyAggregateTest < ActiveSupport::TestCase
context 'aggregating a single RiCal Calendar with a single event' do
setup do
@calendar = RiCal.Calendar do |cal|
cal.event do |evt|
evt.summary = 'Private Stuff'
evt.description = "I really ... |
module Apress
module Images
# Public: джоб нарезки изображений
#
# В случае падения срабатывает retry стратегия.
# Периоды последующих попыток запуститься:
# (@backoff_strategy[номер попытки] * <случайное число от 1 до @retry_delay_multiplicand_max>) в сек.
class ProcessJob
extend Resque... |
class GameSuggester
def initialize(rating, ratings)
@rating = rating
@ratings = ratings
@rand = Random.new(Time.zone.now.beginning_of_day.to_i)
end
def suggest
return if !@rating || @ratings.empty?
closest = @ratings.select{|r| r.id != @rating.id }.sort_by {|r| (@rating.low_rank - r.low_rank... |
require 'spec_helper'
require 'csv_writer'
describe CSVWriter do
let(:user) { create(:user) }
let(:writer) { CSVWriter.new(user.id) }
describe "#generate_csv" do
it "generates a csv for a user with readings" do
reading1 = create(:reading, user: user)
reading2 = create(:reading, :violation, user:... |
class ArtworkShare < ApplicationRecord
validates :artwork_id, presence: true, uniqueness: { scope: :viewer_id, message: "Viewer may only be shared this artwork once" }
validates :viewer_id, presence: true
belongs_to :artwork,
foreign_key: :artwork_id,
class_name: :Artwork
belongs_to :viewer,
forei... |
class AddWorkstationIdsToReceipts < ActiveRecord::Migration
def change
add_column :receipts, :workstation_ids, :string
end
end
|
class Point
attr_reader :x, :y
def initialize(x, y)
@x, @y = x, y
end
def mongoize
[ x, y ]
end
class << self
def demongoize(object)
Point.new(object[0], object[1])
end
def evolve(object)
if object.is_a?(Point)
[ object.x, object.y ]
else
object
... |
class Study < ActiveRecord::Base
acts_as_cached(:version => 1, :expires_in => 1.week)
attr_accessible :title
belongs_to :user
belongs_to :subject
has_and_belongs_to_many :entries
has_many :resources, as: :resource_host, dependent: :destroy
def entries_count
CACHE.fetch(entries_count_cache_key) { self.... |
module OpsWorks
module ShellOut
extend self
# This would be your new default timeout 3Hrs.
DEFAULT_OPTIONS = { timeout: 10 }
def shellout(command, options = {})
cmd = Mixlib::ShellOut.new(command, DEFAULT_OPTIONS.merge(options))
cmd.run_command
cmd.error!
[cmd.stderr, cmd.stdout].join("\n")
end
end
end
|
# A Ruby implementation of Joshua Bloch's
# [typesafe enum pattern](http://www.oracle.com/technetwork/java/page1-139488.html#replaceenums)
module TypeIsEnum
# Base class for typesafe enum classes.
class Enum
include Comparable
class << self
# Returns an array of the enum instances in declaration ord... |
Puppet::Type.newtype(:gce_disk) do
desc 'creates a persistent disk image'
ensurable
newparam(:name, :namevar => true) do
desc 'name of disk to create'
validate do |v|
unless v =~ /[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?/
raise(Puppet::Error, "Invalid disk name: #{v}")
end
end
end
... |
class BranchesController < ApplicationController
before_action :must_be_admin!, except:[:index, :show]
before_action :set_branch, except: [:index, :create, :new]
def index
@branches = Branch.all.page(params[:page]).per(15)
respond_to do |format|
format.html # index.html.erb
format.json { re... |
class Madden18::DefensiveTackleScorer < BaseScorer
def score
case @style
when '43'
# In a 4-3 scheme your tackles primary job is to stuff runs up the middle
# but they are also expected to put pressure on the QB.
# On top of strong run stuffing stats, speed and strength are valued highly
... |
module Tramway::Admin
class RecordsController < ApplicationController
def index
@records = decorator_class.decorate model_class.active.send(params[:scope] || :all).page params[:page]
end
def show
@record = decorator_class.decorate model_class.active.find params[:id]
end
def edit
... |
class AddTimeToExercise < ActiveRecord::Migration[5.2]
def change
add_column :exercises, :timed_exercise, :boolean, default: false
add_column :exercises, :time_by_minutes, :integer, default: 30
end
end
|
require 'spec_helper'
describe Shoulda::Matchers::ActionController::SetSessionMatcher do
context 'a controller that sets a session variable' do
it 'accepts assigning to that variable' do
expect(controller_with_session(var: 'hi')).to set_session(:var)
end
it 'accepts assigning to that variable with... |
# typed: false
# frozen_string_literal: true
# This file was generated by GoReleaser. DO NOT EDIT.
class Csv2tbl < Formula
desc "`csv2tbl` is tool to convert csv to table."
homepage "https://github.com/takaishi/csv2tbl"
version "0.0.1"
on_macos do
if Hardware::CPU.arm?
url "https://github.com/takais... |
require 'rspec'
require 'recursion_problems'
describe "#sum_recur" do
#Problem 1: You have array of integers. Write a recursive solution to find
#the sum of the integers.
it "returns 0 if blank array" do
sum_recur([]) == 0
end
it "returns the sum of all numbers in array" do
sum_recur([1, 3, 5, 7,... |
# frozen_string_literal: true
require 'omniauth-oauth2'
module OmniAuth
module Strategies
class MicrosoftGraph < OmniAuth::Strategies::OAuth2
BASE_AZURE_URL = 'https://login.microsoftonline.com'
option :scopes, %w[openid profile offline_access]
option :name, :microsoft_graph
option :ten... |
json.array!(@telefone_fornecedors) do |telefone_fornecedor|
json.extract! telefone_fornecedor, :id, :ddd, :telefone, :Fornecedor_id
json.url telefone_fornecedor_url(telefone_fornecedor, format: :json)
end
|
class FriendshipsChangeColumns < ActiveRecord::Migration
def up
rename_column :friendships, :following, :user_id
rename_column :friendships, :follower, :follower_id
end
def down
rename_column :friendships, :user_id, :following
rename_column :friendships, :follower_id, :follower
end
end |
class AddPageToWebsite < ActiveRecord::Migration[5.0]
def change
add_column :pages, :is_homepage, :boolean, index: true
add_index :pages, ["is_homepage"], name: "index_pages_on_is_homepage", using: :btree
add_index :pages, ["website_id","is_homepage"], name: "index_pages_on_website_id_hp", using: :btree
... |
class Citibike
include ActiveSupport::Inflector
def search(location)
gmaps_response = GoogleMaps.new.location(location)
gmaps = JSON.parse(gmaps_response)
response = if gmaps['status'] == 'OK'
lat = gmaps['results'][0]['geometry']['location']['lat']
long = gmaps['results'][0]['geometry']['... |
# Define a configset by ENV['RAILS_CONFIGSET'] || default, then do the following:
# - if config/settings/configsets/set_name.yml exists, then add its contents to the config settings.
# This file is intended for things that may vary machine to machine, but do not contain secrets
# - if credentials.yml.enc has a config... |
=begin
#Scubawhere API Documentation
#This is the documentation for scubawhere's RMS API. This API is only to be used by authorized parties with valid auth tokens. [Learn about scubawhere](http://www.scubawhere.com) to become an authorized consumer of our API
OpenAPI spec version: 1.0.0
Contact: bryan@scubawhere.co... |
class Interface::Vlan < Interface::Base
attr_accessor :id, :vlan_raw_device
def name=(name)
@name = name.sub(/[0-9]*$/, '')
@id = name.sub(/^.*?([0-9]*)$/, '\1') if @id.blank?
end
def name
(@name ||= 'vlan') + id
end
def to_save
params = super
params[:vlan_raw_device] = vlan_raw_devic... |
class ShopperReport < ActiveRecord::Base
has_many :shop_collections, dependent: :destroy
def convert_from_json(json)
self.shopper_name = json[:shopper_name]
self.orders_count = json[:orders_count]
self.items_count = json[:items_count]
self.total_time = json[:total_time]
unless json[:shop_coll... |
# frozen_string_literal: true
require_relative "test_helper"
require "tar/header"
class HeaderTest < Minitest::Test
def test_parse
header = Tar::Header.parse(header_data("020523"))
assert_equal "path/to/file", header.name
assert_equal 0o644, header.mode
assert_equal 83, header.uid
assert_equal ... |
class Zoo
attr_reader :enclosure
def initialize(name)
@name = name
@enclosure = []
end
def add_animal(animal)
@enclosure << animal
end
def number_of_animals
return @enclosure.length
end
end
class Animal
attr_accessor :name
attr_reader :sound, :number_of_legs
def initialize(n... |
class User < Sequel::Model
plugin :validation_helpers
def validate
super
validates_presence [:email, :name, :dni, :surname, :password, :username]
validates_unique [:email, :username, :dni]
validates_format /\A.*@.*\..*\z/, :email, message: 'is not a valid email'
end
many_to_many :documents
one_... |
module Cultivation
class UpdateTaskIndent
prepend SimpleCommand
def initialize(task_id, indent_action, current_user)
@task_id = task_id&.to_bson_id
@indent_action = indent_action
@current_user = current_user
end
def call
# TODO::ANDY: Can move into update task? so that the du... |
require 'person'
require 'test/unit'
class TestPerson < Test::Unit::TestCase
def test_simple
assert_equal(1964, Person.new("Al",43).year_born)
assert_equal(15823, Person.new("Al",43).days_alive)
end
end |
# Write a function:
# def solution(a)
# that, given an array A describing N discs as explained above, returns the number of (unordered) pairs of intersecting discs. The function should return −1 if the number of intersecting pairs exceeds 10,000,000.
def solution(a)
return 0 unless a.size > 1
disc_edges = [... |
# frozen_string_literal: true
require 'mini_magick'
module Jiji::Services
class ImagingService
include Jiji::Errors
def create_icon(stream, w = 192, h = 192)
img = MiniMagick::Image.read(stream)
img.define "size=#{w}x#{h}"
img.combine_options do |cmd|
resize_to_fit_longest_edge(c... |
require 'spec_helper'
describe Bucket do
describe "::posts" do
it 'only grabs published posts' do
bucket = create :bucket
post_unpublished = create :post, status: Post::STATUS[:draft]
post_published = create :post, status: Post::STATUS[:published]
bucket.posts = [post_unpublished, post_... |
class RecipeIngredient < ApplicationRecord
belongs_to :recipe
belongs_to :ingredient
# Validations
validates :ingredient_amount, presence: true, numericality: true
validates :ingredient_unit, presence: true
end
|
require 'serverspec'
include Serverspec::Helper::Exec
include Serverspec::Helper::DetectOS
RSpec.configure do |c|
c.before :all do
c.os = backend(Serverspec::Commands::Base).check_os
c.path = '/sbin:/usr/sbin'
end
end
describe file('/srv/frog/webapp/webapp/settings.py') do
it { should be_owned_by 'frog... |
require 'optparse'
class TestRunParser
def parse_args(args)
options = {}
parser = OptionParser.new do |opts|
opts.banner = "Usage: mobcli test run [options]. It runs tests through adb based on a JUnit XML report."
opts.on("--path [PATH]", "List the JUnit tests the have failed based on JUnit XML... |
# frozen_string_literal: true
module GraphQL
module Pagination
# A Connection wraps a list of items and provides cursor-based pagination over it.
#
# Connections were introduced by Facebook's `Relay` front-end framework, but
# proved to be generally useful for GraphQL APIs. When in doubt, use connect... |
class KegTemplatesGenerator < Rails::Generators::Base
source_root File.expand_path('../templates', __FILE__)
def generate_keg_templates
files = ["_form", "show", "edit", "index", "new"]
files.each do |file|
copy_file "#{file}.html.haml", "lib/templates/haml/scaffold/#{file}.html.haml"
end
end
... |
class CourseTeacherAssignmentsController < ApplicationController
def create
@course_teacher_assignment = CourseTeacherAssignment.create(course_id: params[:course_teacher_assignment][:course_id], teacher_id: params[:course_teacher_assignment][:teacher_id])
if @course_teacher_assignment.save
flash[:notice... |
class Following < ApplicationRecord
belongs_to :client
belongs_to :artist
end
|
class CreateAnswerDetail < ActiveRecord::Migration
def change
create_table :answer_details do |t|
t.integer :topic_id
t.integer :question_id
t.integer :activity_id
t.string :answer
t.string :comment
t.timestamps
end
end
end
|
# frozen_string_literal: true
class AddWorkspaceRefsToTicketsAndFolders < ActiveRecord::Migration[5.2]
def change
add_reference :tickets, :workspace, foreign_key: true
add_reference :folders, :workspace, foreign_key: true
end
end
|
FactoryGirl.define do
factory :location do
code "dummycode"
name "dummycode"
end
end |
class Home < ActiveRecord::Base
def self.to_csv(options = {})
CSV.generate(options) do |csv|
csv << column_names
all.each do |home|
csv << home.attributes.values_at(*column_names)
end
end
end
end
|
require 'rails_helper'
RSpec.describe Position do
describe ".names" do
it "returns an array of position names" do
expect(described_class.names.size).to eq(19)
expect(described_class.names).to eq([
'Quarterback',
'Halfback',
'Wide Receiver',
'Fullback',
'Tight E... |
require 'spec_helper'
describe Dickburt::Response do
before :each do
@response = Dickburt::Response.new("beer", "Text")
end
it "should give me a hash for campfire" do
@response.to_campfire_hash.must_be_kind_of Hash
@response.to_campfire_hash.keys.must_include :message
end
it "should respond ... |
# rubocop:disable Metrics/BlockLength
require 'rails_helper'
RSpec.feature 'CreateGiftProcesses', type: :feature do
before(:each) do
user = User.create(name: 'user')
Group.create(name: 'test-group', user: user, icon: '')
visit '/sign-in'
fill_in 'session_name', with: 'user'
click_button 'Sign in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.