text stringlengths 10 2.61M |
|---|
# frozen_string_literal: true
module Recruiterbox
# All of the methods that target candidates are in this class
class Base
require 'rest-client'
require 'json'
class << self
# Returns all objects that have the specified (optional) parameters
def where(params = {})
response = RestCl... |
# +GridGenerator+ generates a grid for the passed in array of integers.
#
# Usage: GridGenerator.new(primes: [2, 3, 5]).generate
# Output: [[nil, 2, 3, 5], [2, 4, 6, 10], [3, 6, 9, 15], [5, 10, 15, 25]]
class GridGenerator
attr_reader :primes
def initialize(primes:)
@primes = primes
end
def generate
... |
require "test_helper"
class ChildModelsControllerTest < ActionDispatch::IntegrationTest
setup do
@child_model = child_models(:one)
end
test "should get index" do
get child_models_url
assert_response :success
end
test "should get new" do
get new_child_model_url
assert_response :success
... |
namespace :fedena_transport do
desc "Install Fedena Transport Module"
task :install do
system "rsync --exclude=.svn -ruv vendor/plugins/fedena_transport/public ."
end
end
|
require 'test_helper'
class OrderTest < ActiveSupport::TestCase
def setup
@order = Order.create
@order_dave = orders(:dave)
@order_erica = orders(:erica)
@order_cameron = orders(:cameron)
@cart = Cart.create
@book_one = products(:ruby)
@book_two = products(:two)
end
test "order att... |
require 'rails_helper'
RSpec.feature "Signing out signed-in users" do
before do
@john=User.create!(email: "john@example.com",password: "password")
visit '/'
click_link "Sign in"
fill_in "Email" , with: @john.email
fill_in "Password", with: @john.password
click_button "Log in"
end
scenario do
visi... |
FactoryBot.define do
factory :admin_user, class: AdminUser do
sequence(:email){ |n| "admin-#{n}@kairos.mx" }
password "password"
password_confirmation "password"
end
end
|
#!/usr/bin/ruby
# This example demonstrates the abstract factory pattern in the Ruby language.
class AbstractProduct; end
class ConcreteProduct < AbstractProduct
def initialize
@type = "Concrete"
end
end
class AbstractFactory
def get_product
return AbstractProduct.new
end
end
class ConcreteFactory < Abstrac... |
require 'pry'
require 'protobuf'
require 'google/transit/gtfs-realtime.pb'
require 'net/http'
require 'uri'
require 'influxdb'
DATABASE = 'ripta_vehicles'
influxdb = InfluxDB::Client.new
# influxdb.delete_database(DATABASE)
influxdb.create_database(DATABASE)
influxdb = InfluxDB::Client.new(DATABASE, async: true)
#... |
class MarketResearch
include Indexable
self.settings = {
index: {
analysis: {
analyzer:
{ custom_analyzer: {
tokenizer: 'standard',
filter: %w(standard asciifolding lowercase snowball) },
title_keyword_analyze... |
class FetchThermostatReadingFromQueue
include Interactor
def call
queued_items =
Sidekiq::Queue.new(context.queue).map(&:item).pluck('args').flatten
reading = queued_items.find { |item| item['token'] == context.token }
if reading.present?
context.reading = reading
else
context.fa... |
class Decimal < ActiveRecord::Migration
def change
change_column :bank_registers, :transaction_amount, :decimal, precision: 10, scale: 2
end
end
|
class Refine::Reconcile < Grape::API
# before do
# error!("401 Unauthorized", 401) unless authorized?
# end
helpers do
# Types which our API can reconcile.
def services
[ 'Grade', 'Language', 'Identity', 'ResourceType', 'Subject', 'Standard' ]
end
# Service metadata requests inform Re... |
=begin
#Rakam API Documentation
#An analytics platform API that lets you create your own analytics services.
OpenAPI spec version: 0.5
Contact: contact@rakam.io
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file e... |
module Campaigns
module Show
module Charts
module Daily
class FundingEvolutionPresenter < BasePresenter
def daily_funding_evolution_data
@data
end
private
def build_data
@data = {
datasets: [
{
... |
class CircleController < ApplicationController
before_action :authenticate_user
before_action :authorize_user
def index
end
private
def authorize_user
unless @current_user.admin? || @current_user.circle?
redirect_to root_path
end
end
end
|
class Eodiv < ActiveRecord::Base
validates :name, :presence => true, :uniqueness => true
belongs_to :eopartial
belongs_to :eoview
end
|
class Restaurant < ActiveRecord::Base
has_many :reviews
has_many :restaurant_categories
has_many :categories, through: :restaurant_categories
validates :name, presence: :true
validates :address, presence: :true
validates :city, presence: :true
validates :state, presence: :true
validates :zip, presence:... |
require 'rails_helper'
RSpec.describe Actor do
describe 'relationships' do
it {should have_many :roles}
it {should have_many(:movies).through(:roles)}
end
describe 'class methods' do
before :each do
@actor_1 = Actor.create!(name: "Taylor Swift", age: 31)
@actor_2 = Actor.create!(name: "J... |
class Goal < ApplicationRecord
belongs_to :user
has_many :goal_entries
def ensure_entry(options)
start = options[:base_date].beginning_of_day
finish = options[:base_date].end_of_day
goal_entries.ensure(start, finish)
end
def entry_meta
meta[:entry_meta] || {}
end
end
|
require "rails_helper"
module Clockface
RSpec.describe "clockface/application/_nav.html.erb", type: :view do
before { stub_params_controller("clockface/events") }
it "renders the app icon, name, and version" do
render_partial
header = page.find(".navbar-header")
expect(header.find(".appl... |
# frozen_string_literal: true
module FileReaderTest
module Seek
def test_seek_to_absolute_pos
file = file_containing("takahē")
file.seek 3
assert_equal 3, file.pos
assert_equal "ahē", file.read
end
def test_explicitly_seek_to_absolute_pos_with_constant
file = file_contain... |
class Api::V1::TicketsController < Api::V1::BaseController
before_action :load_ticket, :except => [:index, :create]
def index
authorize Ticket
# TODO - this needs be scoped by user
render :json => Ticket.all
end
def show
authorize @ticket
render :json => @ticket
end
def create
... |
# frozen_string_literal: true
class Movie < ApplicationRecord
has_many :ratings
has_many :movie_catalogs
end
|
# Rubyからjsonファイルの読み込み、書き込みをする
# JSONとcsvの違いについて議論する(nest)
# https://docs.ruby-lang.org/ja/latest/class/JSON.html
require "json"
# 映画を管理するけど、キャスト情報も入れてみる
# 書き込み
movies = {
movies: [
{
title: "Titaic",
release_year: 1997,
review: 5,
casts: [
"Leonardo Wilhelm DiCaprio",
"K... |
module Intent
class ActivateTarget < ActivateSelf
attr_accessor :target_entity
def initialize(entity, target_entity, target, effect = nil)
super entity, target
add_cost :location_check, self.method(:location_check)
@target_entity = target_entity
unless effect === nil
effect.activate_target_intent s... |
require 'timeout'
require 'faraday'
require 'json'
require './lib/message'
require './lib/room'
time = 0
choice = nil
puts "Enter 'r' to create a new chat room."
puts "Enter 'c' to create a new post."
puts "Enter 's' to select a chat room."
puts "Enter 'x' to exit."
room = nil
loop do
puts "Welcome to the Chatty C... |
# vim: tabstop=2:shiftwidth=2:softtabstop=2
# Cookbook Name : bcpc-hadoop
# Recipe Name : hbase_config
# Description : To setup habse related configuration only
directory "/etc/hbase/conf.#{node.chef_environment}" do
owner "root"
group "root"
mode 00755
action :create
recursive true
end
bash "update-hbase-c... |
require_relative "helper"
class TestElementPairing < TestCase
def setup
@pairing = Pairing.init_from_param_str(TYPE_A_PARAM)
@e1 = Element.new(@pairing, ElementType_G1)
@e2 = Element.new(@pairing, ElementType_G2)
@z = Element.new(@pairing, ElementType_Zr)
@e1.random
@e2.random
@z.random
... |
class List
attr_reader :x, :xs
def self.[]
List.new(nil, nil)
end
def initialize(x, xs = List[])
@x = x
@xs = xs
end
# Extract the first element of a list, which must be non-empty.
# head :: [a] -> a
def head
raise EmptyErrorList.new("head") if empty?
@x
end
# Extract the ele... |
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "spree_skrill_recurring/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = "spree_skrill_recurring"
s.version = SpreeSkrillRecurring::... |
# == Schema Information
#
# Table name: servers
#
# id :bigint not null, primary key
# name :string not null
# owner_id :integer not null
# created_at :datetime not null
# updated_at :datetime not null
# invite_link :string not null
#
cl... |
module OpenAgent
class SIF
def timestamps()
@timenow = Time.now
return @timenow.strftime("%Y-%m-%d") + "T" + @timenow.strftime("%H:%M:%S")
end
def guuid ()
return UUID.generate(:compact).upcase
end
def sif_register (agent_obj = nil, zone_obj = nil)
... |
require_relative '../base'
module Examples
module Checkout
class SwitchingAddressRecalculatesTaxes
def self.run(client)
if Clients::JSON === client
client.pending "SwitchingAddressRecalculatesTaxes does not work with JSON client."
return
end
# Create the order ... |
def count_elements(array)
new_hash = Hash.new(0)
array.each do |string|
new_hash[string] += 1
end
new_hash
end
|
class Gig < ApplicationRecord
belongs_to :club
belongs_to :user
validate :gig_available
validates :price, :club, :user, :date, presence: true
validates :price, numericality: {greater_than: 0, less_than_or_equal_to: 30}
def gig_available
if self.user.featured_jokes == nil
self.errors.add(:user_id... |
FactoryGirl.define do
factory :observation do
user_id { create(:user).id }
proposal_id { create(:proposal).id }
role_id { Role.find_by!(name: ROLE_OBSERVER).id }
end
end
|
class Category < ApplicationRecord
has_and_belongs_to_many :blogs
default_scope { order(name: :ASC) }
def checked?(blog)
self.blogs.any? && (self.blogs.first.id == blog.id)
end
end |
require "./lib/event"
require "./lib/feed"
# event1 = Event.new("Programming", "some fastive events about programming scince", "Tambov", "10.02.2005", "12.02.2005", "tambov@fastive.ru", "google", ["programming", "science", "tambov"])
event1 = Event.new("Programming", "some ruby fastive events about programming scince"... |
# == Schema Information
#
# Table name: gear_items
#
# id :integer not null, primary key
# parent_id :integer
# image_id :integer
# gear_type :string(255) default(""), not null
# name :string(255) default(""), not null
# created_at :datetime not null
# updated_at :dat... |
class AddEducationlevelQualification < ActiveRecord::Migration[5.1]
def change
add_column :qualifications, :education_attainment, :string
add_column :jobs, :salary_offered, :string
add_column :jobs, :requisition_number, :string, unique: true
end
end
|
# frozen_string_literal: true
module ActiveAny
class Relation
MULTI_VALUE_METHODS = %i[group includes join].freeze
SINGLE_VALUE_METHODS = %i[limit].freeze
CLAUSE_METHODS = %i[where order].freeze
VALUE_METHODS = (MULTI_VALUE_METHODS + SINGLE_VALUE_METHODS + CLAUSE_METHODS).freeze
module QueryMet... |
class ConfigurationManager
# Expects the environment to load.
# Second argument is path to a YAML file (defaults to RAILS_ROOT/config/configuration_manager.yml).
#
def self.new_manager(environment=RAILS_ENV, yaml_file=File.join(RAILS_ROOT,"/config/configuration_manager.yml"))
yaml_file = File.expand_path(ya... |
class Translator
def initialize
@stemmer = StemmerApi.new
@dictionary = {}
path = "#{File.dirname(__FILE__)}/../../data/word_dictionary.txt"
File.readlines(path).each do |line|
line.chomp!
line = line.split("\t")
@dictionary[line[0]] = line[1]
end
end
def translate text... |
class ChangeKidsMeal < ActiveRecord::Migration
def change
remove_column :guests, :kids_menu_choice
add_column :guests, :kids_menu_choices, :string
end
end
|
#
#=== コールバックをスキップするためのモジュール
#
module ActiveRecord::SkipCallbacks
extend ActiveSupport::Concern
included do
#
#=== コールバックをスキップするかどうか判定する
# デフォルトの状態ではコールバックをスキップしない
#
def skip_callbacks?
@skip_callbacks.nil? ? false : @skip_callbacks
end
#
#=== コールバックをスキップする
#
d... |
require File.dirname(__FILE__) + '/test_helper.rb'
class TcWddxCoreextTest < Test::Unit::TestCase
def test_true
assert_equal("<boolean value='true'/>", true.wddx_serialize)
end
def test_false
assert_equal("<boolean value='false'/>", false.wddx_serialize)
end
def test_symbol
assert_equal... |
module ApplicationHelper
def full_title(page_title = '')
if page_title.empty?
application_title
else
application_title + ' | ' + page_title
end
end
def application_title
ENV['APPLICATION_TITLE'] || 'Gamarch'
end
def current_year
Time.zone.today.year
end
def available_loc... |
class Contract < ActiveRecord::Base
VALID_CONTRACT_TYPES = %w(call future long put short)
belongs_to :player
belongs_to :ticker
delegate :name, to: :ticker, prefix: true, allow_nil: true
def self.from_file_for_player(file, player)
config = YAML::load(file.read)
config.each do |ticker, type|
ne... |
# Copyright (c) 2009-2011 VMware, Inc.
module VCAP
module Services
module Echo
class EchoError < VCAP::Services::Base::Error::ServiceError
ECHO_SAVE_INSTANCE_FAILED = [32100, HTTP_INTERNAL, "Could not save instance: %s"]
ECHO_DESTORY_INSTANCE_FAILED = [32101, HTTP_INTERNAL, "Could... |
module VCAP
module Services
module Mysql
module WithWarden
end
end
end
end
module VCAP::Services::Mysql::WithWarden
def mysqlProvisionedService
VCAP::Services::Mysql::Node::WardenProvisionedService
end
def init_internal(options)
@service_start_timeout = @options[:service_start_ti... |
class CreateApplicationInstructions < ActiveRecord::Migration
def self.up
create_table :application_instructions do |t|
t.integer :registration_course_id
t.text :description
t.boolean :skip_instructions, :default=>false
t.integer :school_id
t.timestamps
end
end
def self.dow... |
class TestFormula < Formula
desc "Test Formula"
homepage "https://gist.github.com/587f0d317a94d8b687e12fe21c164147"
url "https://gist.github.com/sidneys/587f0d317a94d8b687e12fe21c164147/archive/bec84e6112fde4fe4021a9c377f73338e7f03130.tar.gz"
sha256 "bbbf2181d256687d4f76d3b2145d3bb6cce2324a33f79d93b30140e8f4ff4... |
module Echo
class EchoClient < BaseClient
def get_echo_availability
get("rest/availability.json")
end
def create_token(username, password)
auth = {
username: username,
password: password,
client_id: client_id,
user_ip_address: '127.0.0.1'
}
post("re... |
class Tickets::OptionsSerializer < ApplicationSerializer
object_as :ticket
attributes :id, :subject
end
|
module Cutaneous
# Converts a template path or Proc into a Template instance for a particular format
class FileLoader
attr_accessor :syntax
attr_writer :template_class
attr_reader :format
def initialize(template_roots, format, extension = Cutaneous.extension)
@roots, @format, @extension =... |
require_relative '../../../../spec_helper'
describe 'govuk::app::envvar', :type => :define do
let(:title) { "robert-burns" }
context 'with a value that has no newlines' do
let(:params) {
{
:app => 'burns',
:varname => 'GOVUK_POET_FULL_NAME',
:value => 'Robert Burns'
}
}... |
json.challenge do
json.partial! 'api/v1/challenges/show', challenge: @challenge
end
|
Rails.application.routes.draw do
post '/signin' => 'users#signin'
post '/signup' => 'users#signup'
resources :lists, only: %i[index create show update]
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
|
# frozen_string_literal: true
require "rails_helper"
RSpec.describe NotesController, type: :routing do
before do
user = FactoryBot.create(:user)
sign_in user
end
describe "routing" do
it "routes to #edit" do
expect(get: "/subjects/1/courses/1/notes/1/edit").to route_to("notes#edit", id: "1", ... |
<<-EOF
This is a little bit late (wednesday), and doesn't behave as I originally thought it ought
to behave, because I don't have time to do the different-operations-choose-types-differently properly.
(The basic idea is to coerce integers to a class that wraps an integer and does coercions in different
ways when presen... |
source 'https://rubygems.org'
ruby '2.2.2' # used by Heroku
#-------------------------------------------------
# Rails default gems
#-------------------------------------------------
gem 'rails', '4.2.1' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'uglifier', '>= 1... |
class CheckoutController < ApplicationController
include UserAddress
include Wicked::Wizard
include Rectify::ControllerHelpers
before_action :checkout_login
before_action -> { set_addresses current_user }, :set_payment, only: [:show, :update]
steps :address, :delivery, :payment, :confirm, :complete
def... |
GRID = INPUT.split("\n").each_with_object({}).with_index do |(line, field), y|
line.chars.each_with_index { |c, x| field[[x, y]] = (c == "#") }
end
class AsteroidField
def initialize(field)
@field = field.dup
end
def asteroids
@field.keys.select { |coords| @field[coords] }
end
def visible_from(x,... |
class AddPhoneToTenants < ActiveRecord::Migration
def change
add_column :tenants, :phone, :string
end
end
|
class FixsContextsColumnName < ActiveRecord::Migration[5.1]
def change
rename_column :contexts, :context, :context_id
end
end
|
# frozen_string_literal: true
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :films, only: :index
resources :purchases, only: :create
resource :library, only: :show
end
end
end
|
require 'cisco_decrypt/cisco_decrypt'
require 'inifile'
module CiscoDecrypt
def self.from_pcf(file)
config_file = IniFile.new(File.expand_path(file))
main_config = config_file['main']
encrypted_password = main_config['enc_GroupPwd']
group_name = main_config['GroupName']
host = main_config['Host']... |
namespace :fedena_task do
desc "Install Fedena Task Module"
task :install do
system "rsync --exclude=.svn -ruv vendor/plugins/fedena_task/public ."
end
desc "Update Paths for Task Module"
task :update_plugins_paths => :environment do
models = [Task,TaskComment]
sub_paths = {
"Task" => "up... |
require 'spec_helper'
RSpec.describe InfluencersGroup, :type => :model do
it { should validate_presence_of :name }
it { should validate_uniqueness_of :name }
it "should have and belongs to many influencers" do
group = InfluencersGroup.make!
influencer = Influencer.make!
influencer.influencers_groups... |
require 'spec_helper'
describe "api", type: :integration do
describe "v1" do
let(:task) { FactoryGirl.create(:task_with_task_items) }
let(:task_item_1) { task.task_items[0] }
let(:task_item_2) { task.task_items[1] }
let(:link_1) { Link.create(name: "Groovy test link 1", url: "http://some/url/1", tas... |
#encoding: utf-8
require 'spec_helper'
describe "sign up and login", :type => :feature do
it "let user sign up and login to the site with name" do
visit new_user_session_path
click_link '注册'
fill_in '用户名', :with => 'example'
fill_in 'Email', :with => 'example@caok1231.com'
fill_in '* 密码', :with =... |
=begin
Sympathetic lies, mrs Robinon wo wo wo, Heaven hold a place for those to break
=end
class Sequence
def initialize(from,to,by)
@from, @to, @by - from, to, by
end
def each
x=@from
while x <= @to
yield x
x += @by
end
end
def length
return 0 if @from > @to
Integer((@to-@from)/@by) + 1
end
... |
FactoryGirl.define do
factory :client, class: Client do
name Faker::GameOfThrones.character
cpf Faker::Number.unique.number(11)
address Faker::Address.street_name
birthday Faker::Date.birthday(18, 65)
fone Faker::Number.number(11)
email Fake... |
require 'test_helper'
class DayTypesControllerTest < ActionDispatch::IntegrationTest
setup do
@day_type = day_types(:one)
end
test "should get index" do
get day_types_url
assert_response :success
end
test "should get new" do
get new_day_type_url
assert_response :success
end
test "s... |
class SeasonParse < Struct.new(:file)
def read_file
`./node/season-parser #{file}`
end
def to_json
JSON.parse read_file
end
end
|
class CreateUserGameScores < ActiveRecord::Migration
def change
create_table :user_game_scores do |t|
t.belongs_to :user, index: true
t.belongs_to :game, index: true
t.integer :wins
t.integer :losses
t.integer :times_played
t.timestamps null: false
end
end
end |
class CreateOffers < ActiveRecord::Migration[5.0]
def change
create_table :offers do |t|
t.integer :clasificacion
t.string :actividad
t.integer :estado
t.string :ciudad
t.string :localidad
t.integer :cantidad_vancant
t.integer :duracion_hora
t.integer :valorxhora
... |
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable
include DeviseTokenAuth::Concerns::User
has_many :apps, dependent: :destroy
has_many :devices, dependent: :destroy
# Quotas
APPS_MAX_NUM... |
# frozen_string_literal: true
require "spec_helper"
RSpec.describe Capwatch::Coin do
let(:btc_coin) {
Capwatch::Coin.new do |coin|
coin.name = 'Bitcoin'
coin.symbol = 'BTC'
coin.price_fiat = 5_000
coin.price_btc = 1
coin.percent_change_1h ... |
# frozen_string_literal: true
class Location < ApplicationRecord
has_many :events, dependent: :destroy
has_many :prayers, dependent: :destroy
has_many :services, dependent: :destroy
has_many :location_connection_steps, dependent: :destroy, class_name: 'Location::Connection::Step'
has_one_attached :banner
v... |
# encoding: UTF-8
module ApplicationHelper
def list_classes(object, collection)
classes = []
classes << cycle('odd', 'even')
classes << 'first' if object == collection.first
classes << 'last' if object == collection.last
classes.join(' ')
end
def truncate(text, options = {})
options[:s... |
require 'json'
require 'digest/md5'
require 'hmac-sha2'
module Socky
class Authenticator
DEFAULT_RIGHTS = {
:read => true,
:write => false,
:hide => false
}
class << self
attr_accessor :secret
def authenticate(params, opts = {})
self.new(params, opts).res... |
class CirclesTestAnalyzer
attr_reader :start_time, :end_time, :circles, :radii, :start_coords, :self_circle
def initialize(events)
process_events events
end
def calculate_result
@results = []
return @results if @circles.nil?
self_circle_radius = @self_circle['size'] / 2.0
self_circle... |
module PubSub
class MessagesPublisher < BaseRedisService
def publish(data, client_id)
message = message_builder(data[:message], data[:action])
redis.publish("#{client_id}?#{data[:message].conversation_id}", message)
end
private
def message_builder(message, action)
{
type... |
require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = User.new(name: "Manuel")
end
test "it should be valid" do
assert @user.valid?
end
test "it should have a name, not too long" do
@user.name = " "
assert_not @user.valid?
@user.name = "a" * 20
assert_not @user.valid?
... |
class Survey::Ans < ActiveRecord::Base
has_many :ans_choices, class_name: "Survey::AnsChoice",
dependent: :destroy
belongs_to :quest, class_name: "Survey::Quest"
belongs_to :ans_set, class_name: "Survey::AnsSet"
counter_culture :ans_set, column_name: "ans_count"
accepts_nested_attributes_for :ans_choic... |
class Admins::SettingsController < Admins::ApplicationController
def index
add_crumb "Settings", "settings"
end
end
|
# Source: https://launchschool.com/exercises/f9cb9ad5
def drop_while(arr)
drop_flag = false
out = []
arr.each do |el|
if drop_flag == false
drop_flag = yield(el) ? drop_flag = false : drop_flag = true
end
out << el if drop_flag
end
out
end
puts drop_while([1, 3, 5, 6]) { |value| value.odd... |
require 'rails_helper'
RSpec.describe Party do
describe 'relationships' do
it {should have_many :invitations}
it {should have_many(:users).through(:invitations)}
end
describe 'instance methods' do
describe 'hosted_parties(host_id)' do
it 'returns all parties created by the user' do
... |
class AddSessionIdFields < ActiveRecord::Migration
def change
add_column :agendas, :session_number1_id, :integer
add_column :agendas, :session_number2_id, :integer
end
end
|
require 'spec_helper'
describe SwimWorkout do
before do
@swim = SwimWorkout.new( :user_id => 1, :workout_date => "2010-01-01", :time_of_day => "00:00:00",
:duration => "00:30:00", :distance => 1300, :plan_type => "a")
end
it "should have user id assigned" do
@swim.user_id = ... |
require 'spec_helper'
RSpec.describe GitBumper::Git do
use_temporary_cwd
subject { described_class }
describe '.repo?' do
context 'not a git repo' do
it 'returns false' do
expect(subject.repo?).to be false
end
end
context 'inside a git repo' do
it 'returns true' do
... |
class Checkout
PRICES = { "001" => 9.25, "002" => 45.0, "003" => 19.95}
def initialize(promotional_rules)
@promotional_rules = promotional_rules
@customer_invoice = []
@sum = 0.0
end
def scan(item)
#Check for valid Product Code
if PRICES[item]
@customer_invoice << item
else
... |
class Gadget < ActiveRecord::Base
belongs_to :user
has_many :images, dependent: :destroy
accepts_nested_attributes_for :images, allow_destroy: true
validates :name, :user, presence: true
end
|
class Feedback < ApplicationRecord
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
index_name "feedbacks"
settings do
mapping do
indexes :company_token
indexes :content
end
end
enum priority: [:minor, :major, :critical]
validates :content, presence: true
has_o... |
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
def capitalize_input(input)
input.downcase.split(' ').map(&:capitalize).join(' ')
end
rescue_from CanCan::AccessDe... |
require "rubygems"
require "json"
require "zaru"
require "youtube-dl.rb"
require "redd"
require "sequel"
require "date"
require "optparse"
# Pulls links from the subreddit.
def fetch(dataset)
# Read our configuration from the json file.
config_filename = "reddit_config.json"
puts "Loading config from #{con... |
##
# This class represents Match and contains all the database transaction code related to it.
# encoding: utf-8
class Match < Sequel::Model
def self.all
DB.fetch('SELECT * FROM match ORDER BY updated_at DESC').all
end
def self.find_by_id(match_id)
DB.fetch('SELECT * FROM match WHERE match_id = ?',match... |
require 'rails_helper'
describe "Customers BI API" do
describe "Customer class" do
it '.favorite_merchant' do
customer = create(:customer)
merchant1 = create(:merchant)
merchant2 = create(:merchant)
merchant3 = create(:merchant)
invoice1 = create(:invoice, customer: customer, mercha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.