text stringlengths 10 2.61M |
|---|
class BenchHost
include Sanford::Host
port 59284
pid_file File.expand_path("../../tmp/bench_host.pid", __FILE__)
logger Logger.new(STDOUT)
verbose_logging false
version 'v1' do
service 'simple', 'BenchHost::Simple'
end
class Simple
include Sanford::ServiceHandler
def run!... |
# 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 rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel... |
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_filter :configure_permitted_parameters, if: :devise_controller?
before_action :set_current_user
def set_current_user
if logininfo_signed_in?
@current_user = current_logininfo.user
end
end
def... |
require 'kimurai'
$filename = "tournament_titles.csv";
class ATPTourSpider < Kimurai::Base
@name = "ATP Tour Spider"
@engine = :selenium_chrome
@config = {
before_request: { delay: 1..4 }
}
@start_urls = []
(4180..10000).each do |n|
@start_urls << "https://www.atptour.com/en/scores/archive/pickle... |
module Ripley
module Configuration
attr_accessor :logger
attr_accessor :logger_formatter, :object_formatter, :variable_formatter, :value_formatter
def configure(&block)
block.call(self)
self
end
def track_all_exceptions!
require 'ripley/ext'
end
end
end
|
class AddColumnsToUsers < ActiveRecord::Migration
def change
add_column :users, :iduser, :string
add_column :users, :name, :string
add_column :users, :lastname, :string
add_column :users, :typeuser, :integer
add_column :users, :birthday, :date
add_column :users, :address, :string
end
end
|
class CreateAgents < ActiveRecord::Migration
def change
create_table :agents do |t|
t.string :name,:unique=>true,:null => false
t.integer :team_id,:null => false
t.timestamps
end
add_index :agents, :name
add_index :agents, :team_id
end
end
|
class Fixnum
ONE_SECOND = 1
ONE_MINUTE = ONE_SECOND * 60
ONE_HOUR = ONE_MINUTE * 60
ONE_DAY = ONE_HOUR * 24
def days
self * ONE_DAY
end
def day
days
end
def ago
Time.now - self
end
end
|
hashed_events = @events.group_by {|item| item.start_at.strftime("%Y年%m月")}
json.array! hashed_events.keys do |month|
json.month month
json.events do
json.array! hashed_events[month] do |event|
json.(event, :id, :start_at, :stop_at, :desc, :address, :price)
json.weekday I18n.l(event.start_at, format:... |
class Book < ApplicationRecord
belongs_to :author
belongs_to :category
has_many :likes, dependent: :destroy
has_many :rates, dependent: :destroy
end
|
require 'brew_sparkling/action/recipe/base'
require 'brew_sparkling/action/recipe/search'
module BrewSparkling
module Handler
class Recipe < Base
command :search, :list
def search
args.each do |name|
Action::Recipe::Search.new.call(name)
end
end
def list
... |
class FontRighteous < Formula
head "https://github.com/google/fonts/raw/main/ofl/righteous/Righteous-Regular.ttf", verified: "github.com/google/fonts/"
desc "Righteous"
homepage "https://fonts.google.com/specimen/Righteous"
def install
(share/"fonts").install "Righteous-Regular.ttf"
end
test do
end
en... |
class Raindrops
VERSION = 1
SOUNDS = {
3 => "Pling",
5 => "Plang",
7 => "Plong"
}
def self.convert(number)
primes = SOUNDS.keys.select { |n| number % n == 0 }.map { |pn| SOUNDS[pn] }.join
primes.empty? ? number.to_s : primes
end
end
|
class Follow < ActiveRecord::Base
validates_uniqueness_of :user_id, :scope => :follower
belongs_to :users
def to_json
super()
end
end
|
class User < ActiveRecord::Base
# Include default devise modules.
include DeviseTokenAuth::Concerns::User
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable, :omniauthable
validates :name, presence: true
has_many... |
$:.push File.expand_path("../lib", __FILE__)
require "codegraph/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "ruby-codegraph"
s.version = CodeGraph::VERSION
s.authors = ["Jan Xie"]
s.email = ["jan.h.xie@gmail.com"]
s.homepage = "ht... |
class User < ActiveRecord::Base
has_many :microposts, dependent: :destroy
has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :followed_users, through: :relationships, source: :followed
has_many :reverse_relationships, foreign_key: "followed_id",
clas... |
# Copyright 2019 The inspec-gcp-cis-benchmark Authors
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
require 'active_support/inflector'
require 'telegram/errors/controller/block_not_given_error'
#WIP move to ...::Controller, продумать
module Telegram
module Utils
class Responder
class << self
private
def register_type type
instance_eval do
define_method type do |&b... |
module Locators
class PropertyFinder
attr_accessor :CATEGORY_SEARCH
attr_accessor :PROPERTY_SEARCH
attr_accessor :MIN_BED
attr_accessor :MAX_BED
attr_accessor :KEY_WORD
attr_accessor :SORT_DROPDOWN
attr_accessor :TITLE_LIST
attr_accessor :PRICE_LIST
attr_accessor :FIND_AGENT
... |
class Song < ActiveRecord::Base
belongs_to :artist
belongs_to :genre
has_many :notes
def artist_name=(name)
self.artist = Artist.find_or_create_by(name: name)
end
def artist_name
self.try(:artist).try(:name)
end
def genre_name=(name)
self.genre = Genre.find_by(name: name)
end
def gen... |
class TaskController < ApplicationController
skip_before_action :authenticate_user!, :only => [:check_if_select_client]
def new
@task = Task.new
end
def create
@gym = current_user.gym
@task = @gym.tasks.new(task_params)
begin
@task.save!
flash[:notice] = "Task #{@task.name} was succ... |
class GameRank < ApplicationRecord
belongs_to :game, touch: true, optional: true
belongs_to :player
has_one :user, :through => :player
validates_numericality_of :position, greater_than: 0, only_integer: true, if: -> game_rank { game_rank.game.try(:challenged?) }
def self.not_confirmed
where(:confirmed_... |
=begin
#For this practice problem, write a one-line program that creates the following output 10 times, with the subsequent line indented 1 space to the right:
#The Flintstones Rock!
#The Flintstones Rock!
#The Flintstones Rock!
10.times { |number| puts (' ' * number) + "The Flintstones Rock!"}
=end
=begin
#The re... |
require_relative 'graph'
# Implementing topological sort using both Khan's and Tarian's algorithms
def topological_sort(vertices)
sorted = []
top_queue = []
vertices.each { |v| top_queue << v if v.in_edges.empty? }
until top_queue.empty?
curr_vertex = top_queue.shift
sorted << curr_vertex
until ... |
module Inventory
class SearchPlants
prepend SimpleCommand
attr_reader :facility_strain_id,
:current_growth_stage,
:search
def initialize(facility_strain_id, current_growth_stage, search)
@facility_strain_id = facility_strain_id
@current_growth_stage = current_growth_stage
@s... |
pg_ver = input('pg_version')
pg_dba = input('pg_dba')
pg_dba_password = input('pg_dba_password')
pg_db = input('pg_db')
pg_host = input('pg_host')
pg_data_dir = input('pg_data_dir')
pg_hba_conf_file = input('pg_hba_conf_file')
control "V-72979" do
title "PostgreSQL, when utilizing PKI-based authentication, mus... |
require 'spec_helper'
describe ::Outcome do
let(:outcome) { create :outcome, title: 'Test outcome 1', points_to: 2}
it 'has a valid factory' do
expect(outcome.title).to eq('Test outcome 1')
end
it 'should require a title' do
outcome.title = ''
outcome.valid?
expect(outcome.errors[:title].size).... |
class SettingsAccountsController < ApplicationController
require 'aws-sdk-s3'
require 'base64'
def show
redirect_to '/' and return unless current_user
render_for_react
end
def update
@user = current_user
image = user_params[:profile_image_url]
if image
image_new_name = "#{SecureR... |
# -*- coding: utf-8 -*-
class Homework < ActiveRecord::Base
HOMEWORK_ATTACHMENTS_DIR = '/MINDPIN_MRS_DATA/attachments/homework_attachments'
KINDS = ['Homework', 'Practice']
# --- 模型关联
belongs_to :creator,
:class_name => 'User',
:foreign_key => 'creator_id'
belongs_to :cou... |
OperatorError = Class.new(StandardError)
class Operator
private
def argument_error
raise OperatorError, $language.errors.wrong_arguments_number
end
end |
class Connection < ApplicationRecord
belongs_to :journey
has_many :poi_bookings
validates :name, presence: true
validates :origin_city, presence: true, allow_blank: false
validates :destination_city, presence: true, allow_blank: false
validates :transport_type, presence: true
validates :provider, presenc... |
require 'spec_helper'
require 'rack/requestash/log4r'
require 'json'
describe Rack::Requestash::Log4r::Formatter do
subject(:formatter) { described_class.new }
before :all do
# Ensure Log4r::LNAMES gets seeded
Log4r::RootLogger.instance
end
describe '#format' do
let(:logevent) { ::Log4r::LogEvent... |
require 'openssl'
require 'digest/sha2'
require 'base64'
module ActiveUrl
module Crypto
CipherError = OpenSSL::Cipher.const_defined?(:CipherError) ? OpenSSL::Cipher::CipherError : OpenSSL::CipherError
PADDING = { 2 => "==", 3 => "=" }
def self.encrypt(clear)
crypto = start(:encrypt)
ci... |
class AvailabilityScraper
PAGE_DAYS_SCOPE = 14
LAST_RESERVATION_DATE = Date.parse('Nov 30, 2014')
class << self
def scrape_page(start_date)
page = Nokogiri::HTML(get_page_contents(start_date))
previous_open_rooms = Opening.where('open_date >= ? AND open_date <= ? AND discovered_closed is null',... |
class NoteController < ApplicationController
def notes(user)
course_id = params[:course_id].to_i
notifications = Moodle::Api.core_notes_get_course_notes(courseid: course_id, userid: user.moodle_user_id)
if notifications.blank?
{type: :error, message: "No notes."}
else
{data: notifications}... |
class Et < AbstractReport
has_one :report, as: :specific, dependent: :destroy
has_many :et_probes, dependent: :destroy
has_many :et_defects, dependent: :destroy
default_scope order("updated_at DESC")
attr_accessible :equipment,
:serial,
:calibration_due,
:coating,
:calibration_block,
:et_probes_at... |
require_relative "../spec_helper"
require "omnimutant/file_iterator"
describe Omnimutant::FileIterator do
before do
@iterator = Omnimutant::FileIterator.new(files:["test1.rb", "test2.rb"])
end
it "should understand when it is at the end" do
assert !@iterator.is_at_end?
@iterator.move_next()
as... |
# 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 rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel... |
require 'spec_helper'
RSpec.describe MarkdownMetrics::LowElementsParser do
describe '#parse' do
let(:value) { "Some text **bold** and `code` now. Also *italic* is supported. Check ([link](http://google.pl)) also." }
let(:parser) { described_class.new(value: value) }
it 'returns string elements' do
... |
class CreateStandards < ActiveRecord::Migration
def up
create_table :standards do |t|
t.string :code
t.string :property
t.decimal :min_tolerance, precision: 7, scale: 2
t.integer :min_tolerance_action_id
t.decimal :max_tolerance, precision: 7, scale: 2
t.integer :max_tolerance_... |
class TimeCardsController < ApplicationController
before_action :logged_in_user
def index
today = Date.today
@year = today.year
@month = today.month
@time_cards = monthly_time_cards(current_user, @year, @month)
end
def show
@time_card = TimeCard.today(current_user)
end
def create
... |
# frozen_string_literal: true
require "spec_helper"
RSpec.describe(Jekyll::GitHubMetadata::RepositoryCompat) do
let(:repo) { Jekyll::GitHubMetadata::Repository.new(nwo) }
let(:repo_compat) { repo.repo_compat }
context "hubot.github.com" do
let(:nwo) { "github/hubot.github.com" }
before(:each) { allow(r... |
require 'stringio'
require 'shellwords'
require 'net/ssh'
require 'net/scp/errors'
require 'net/scp/upload'
require 'net/scp/download'
module Net
# Net::SCP implements the SCP (Secure CoPy) client protocol, allowing Ruby
# programs to securely and programmatically transfer individual files or
# entire director... |
# frozen_string_literal: true
class Chat < ApplicationRecord
validates :name, presence: true, uniqueness: true, length: { maximum: 15 }, if: :name_required?
validates_presence_of :privacy
validates_inclusion_of :privacy, in: %w[public private protected direct_message]
has_secure_password validations: false
v... |
feature "Homepage" do
scenario "a user can see the text 'The Expense Tracker'" do
visit "/"
expect(page).to have_content "The Expense Tracker"
end
end
|
# Controller for User
class UsersController < ApplicationController
before_action :require_admin, only: %i[index, destroy]
before_action :require_user, only: %i[new, show, edit, destroy]
def index
@page_title = "Subscribed Users"
@users = User.all.paginate(page: params[:page], per_page: 5)
end
def n... |
class CreateRelationships < ActiveRecord::Migration[5.0]
def change
create_table :relationships do |t|
t.references :follower, references: :users, index: true
t.references :followed, references: :users, index: true
t.timestamps
end
add_foreign_key :relationships, :users, column: :follo... |
class CreateBeers < ActiveRecord::Migration
def self.up
create_table :beers do |t|
t.string "name"
t.integer "brewery_id"
t.text "description"
t.decimal "abv"
t.decimal "ibu"
t.decimal "original_gravity"
t.integer "style_id"
t.string "website"
t.timestam... |
class BlogPostScoper
attr_reader :blog
def initialize(blog)
@blog = blog
end
def find(params = {}, options = {})
blog_show_params = (params[:blog_show_params] || {})
scope = default_scope
if options[:completed] == false
scope = scope.where(blog_posts: { is_complete: false })
else
... |
require "spec_helper"
describe Slickr::Generators::Behavior do
let!(:generator) { described_class.new("spatial") }
before do
generator.start
end
it "has a name" do
generator.name.should == "spatial"
end
it "generates a new component file" do
build.join("lib", "behaviors", "spatial.rb").shoul... |
class ChangeAirports < ActiveRecord::Migration
def change
change_table :airports do |t|
t.remove :short
end
end
end
|
module ConfigurationHelper
def configure(&block)
SharedWorkforce.configure(&block)
end
def with_configuration(&block)
old_configuration = SharedWorkforce.configuration
SharedWorkforce.configuration = SharedWorkforce::Configuration.new
yield(SharedWorkforce.configuration)
ensure
SharedWorkfo... |
puts """Hello, and thank you for taking time to
help me with this experiment. My experiment
has to do with the way people feel about
Mexican food. Just think about Mexican food
and try to answer every question honestly,
with either a \"yes\" or a \"no\". My experiment
has nothing to do with bed-wetting.
"""
# We ask t... |
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe Publication do
before { Patento.stub(:download_html).and_return(File.read("#{$LOAD_PATH[0]}/data/US20100268739.html"))}
let(:publication) { Publication.new(20100268739) }
subject { publication }
it { should respond_to(:number) }
... |
require 'rails_helper'
RSpec.describe User, type: :model do
context 'ActiveRecord associations' do
it 'Should have many posts' do
expect(User.reflect_on_association(:posts).macro).to be(:has_many)
end
it 'Should have many comments' do
expect(User.reflect_on_association(:comments).macro).to b... |
class CreateGamesGenres < ActiveRecord::Migration
def change
create_table :games_genres, :id => false do |t|
t.references :game
t.references :genre
end
add_index :games_genres, :game_id
add_index :games_genres, :genre_id
end
end
|
Then /the following messages should exist/ do |messages_table|
messages_table.hashes.each do |message|
assert Message.exist(message)
end
end |
class AddOomycetesStrandsCmBigInt < ActiveRecord::Migration[5.0]
def change
add_column :samples, :oomycetes_strands_cm, :bigint
end
end
|
require 'spec_helper'
module Belafonte
describe Parser do
let(:switches) {
[
Belafonte::Switch.new(name: :switch1, long: 'switch1'),
Belafonte::Switch.new(name: :switch2, long: 'switch2')
]
}
let(:options) {
[
Belafonte::Option.new(name: :option1, long: 'option1... |
class AdultValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors.add(attribute, '未成年の方は登録することができません') if value.present? && value > 20.years.ago
end
end |
# categorize articles
class Category
# TODO: this is a nightmare to test, since I can't seem to alter the hash of keys and values before Article loads it.
# Basically bad idea bites me in the ass #192312.
def self.category_collection
# make sure all key values are strings.
{ blog: { en: 'blog', ro: '... |
class TestpatsController < ApplicationController
before_action :set_testpat, only: [:show, :edit, :update, :destroy]
# GET /testpats
# GET /testpats.json
def index
@testpats = Testpat.all
end
# GET /testpats/1
# GET /testpats/1.json
def show
end
# GET /testpats/new
def new
@testpat = Te... |
require 'rubygems'
require 'date'
require 'selenium-webdriver'
require "rspec"
require 'two_captcha'
require 'headless'
def time
Time.now.strftime('%Y %b %d %H:%M:%S')
end
def driver_setup
@headless = Headless.new
@headless.start
Selenium::WebDriver::Chrome::Service.executable_path = File.join(Dir.pwd, '.... |
# typed: strong
# frozen_string_literal: true
module Ffprober
module Ffmpeg
class Finder
extend T::Sig
SEARCH_PATHS = T.let(ENV.fetch('PATH', nil), T.nilable(String))
sig { returns(String) }
attr_reader :executable_name
sig { void }
def initialize
@executable_path = ... |
class ChildrenController < ApplicationController
before_action :load_application
def new
@child = @application.children.build
end
def create
@child = @application.children.new(child_params)
respond_to do |format|
if @child.save
format.html { redirect_to new_application_employment_p... |
require 'json'
class ConfigGenerator < Rails::Generators::Base
source_root File.expand_path('../templates', __FILE__)
# General Config
class_option :cache, type: :boolean,
default: true,
desc: 'Whether to use cached config in ".esaas-engagements-config.yml" if present.
... |
# IconPasswordFieldInput prefixes a supplied icon before the password field
class IconEmailFieldInput < SimpleForm::Inputs::Base
# Generates the HTML output for the input
#
# @param wrapper_options [Hash] options for the wrapper
# @return [String] HTML markup of the input
def input(wrapper_options)
merge... |
class CategoriesSerializer < ActiveModel::ArraySerializer
include Rails.application.routes.url_helpers
delegate :default_url_options, :to => "ActionController::Base"
def as_json(*args)
hash = super
hash[:_embedded] = { :categories => hash.delete("categories") }
hash[:_links] = {
"curies" => [{... |
class CreateInvites < ActiveRecord::Migration
def change
create_table :invites do |t|
t.belongs_to :user
t.belongs_to :tournament
t.string :code, :null => false
t.string :email, :null => false
t.datetime :expires_at, :null => false
t.timestamps
end
add_index :invites, ... |
require "rails_helper"
RSpec.describe Comment, type: :model do
it "is invalid without content" do
subject.content = ""
expect(subject).to_not be_valid
end
describe "Association" do
it { is_expected.to belong_to :user }
end
end
|
Rails.application.routes.draw do
root to: "fantasy_leagues#index"
resources :fantasy_leagues, only: :show
resources :fantasy_players, only: :index
resources :fantasy_teams, only: :show
resources :roster_positions, only: :index
resources :roster_transactions, only: :index
resources :sports_leagues, only: ... |
require 'test_helper'
class AddressTest < ActiveSupport::TestCase
test "Delivery address correct relations" do
da = Address.find(1)
assert_not_nil da, "Should exist delivery address"
assert_not_nil da.delivery_address,
"Should exist delivery_addresses relation"
end
test "Meal Event Address corr... |
module Smtp
class ContentTransferEncoding
EIGHT_BIT = '8bit'.freeze
BASE_64 = 'base64'.freeze
def initialize(value)
@value = value
end
def as_header
@header ||= Header.new(Header::CONTENT_TRANSFER_ENCODING, @value)
end
end
end
|
# frozen_string_literal: true
class Category::Topic < ApplicationRecord
extend FriendlyId
friendly_id :name, use: :slugged
has_many :connection_topics, class_name: 'Resource::Connection::Topic', dependent: :destroy
has_many :resources, through: :connection_topics
belongs_to :category
validates :name, pre... |
module RotaHelper
def present_organisations(organisations_with_solicitors)
tags = organisations_with_solicitors.map do |org_hsh|
org_colour = organisation_colour(org_hsh[:organisation_uid])
content_tag(:span, org_and_solicitor(org_hsh),
class: "rota-slot-organisation #{organisation_... |
require 'station'
describe Station do
let(:station_name) { :station_name }
let(:station_zone) { :station_zone }
subject { Station.new(:station_name, :station_zone) }
it 'has a name' do
expect(subject.station_name).to eq(:station_name)
end
it 'has a zone' do
expect(subject.station_zone).to eq(:sta... |
require 'csv'
require 'json'
class EngagementsController < ApplicationController
before_action :set_app
before_action :set_engagement, only: [:edit, :update, :destroy, :export]
before_action :auth_user?, only: [:new, :create, :edit, :update, :destroy]
# GET /engagements/new
def new
@engagement = Engag... |
class ChatBoxesController < ApplicationController
before_action :set_chat_box, only: [:show, :edit, :update, :destroy]
# GET /chat_boxes
# GET /chat_boxes.json
def index
Rails.logger.info params
if params.has_key?('flight_id')
flight_id = params['flight_id']
@chat_boxes = ChatBox.where(... |
class EventsController < ApplicationController
def index
@events = Event.all.order("date ASC")
@users = User.all
@joins = Join.all
@today = Date.today
end
def create
@user = User.find(session[:user_id])
@event = Event.new( event_params )
if @event.save
@join = Join.new(user: @... |
class CreateDeviceCarriers < ActiveRecord::Migration
def change
create_table :device_carriers do |t|
t.string :device_carrier
t.timestamps
end
end
end
|
require "spec_helper"
describe FeaturedCommentBucket do
describe "associations" do
it { should have_many(:comments).class_name("FeaturedComment") }
end
describe "validations" do
it { should validate_presence_of(:title) }
end
end
|
class AddMasterFeeParticularIdToHostelFeeCollection < ActiveRecord::Migration
def self.up
add_column :hostel_fee_collections, :master_fee_particular_id, :integer
add_index :hostel_fee_collections, :master_fee_particular_id, :name => "by_master_particular_id"
end
def self.down
remove_index :hostel_fee... |
#!/usr/bin/env ruby
require 'yaml'
project_name = ARGV[0]
path = File.expand_path("~/Projects/launchers/#{project_name}.yml")
if not File.exists?(path)
puts "Project #{project_name} not found."
abort
end
begin
project_yaml = YAML.load_file(path)
rescue Exception
puts "Cannot read YAML file."
end
puts pro... |
# frozen_string_literal: true
module Api
class QuestionsController < ApplicationController
def filter
@result = QConcursos::QuestionsFetcher.perform(date_params)
render json: {data: @result}
rescue => e
Rails.logger.warn("#{e}: #{e.backtrace.join "\n\t"}")
end
private
def date... |
# frozen_string_literal: true
class CreateSubscription
include Sidekiq::Worker
sidekiq_options retry: false
def perform(uid, url, category)
user = User.find uid
feeds = Feed.safe_create url
subscription = user.subscriptions.create! feed: feeds.first,
ca... |
class PlantImage < ApplicationRecord
belongs_to :plant, inverse_of: :plant_images
mount_uploader :image_upload, PlantImageUploader
has_one :image_upload
accepts_nested_attributes_for :image_upload
def get_display_title
self.plant.display_title
end
end
|
Spree::StockMovement.class_eval do
after_create :check_no_active_variant
def check_no_active_variant
CheckNotActiveVariantsWorker.perform_async(stock_item.variant.id)
end
end
|
require_relative '../spec_helper'
class SomeController < ActionController::Base
include JumpIn
end
describe SomeController do
context "JumpIn.configure not run" do
it "has @conf with default values" do
expect(JumpIn.conf.expires).to eq(20.years)
expect(JumpIn.conf.expiration_time).to eq(2.hours)
... |
class RemoveGameIdAndUserIdIndexOnGameRanks < ActiveRecord::Migration
def up
remove_index :game_ranks, [:game_id, :user_id]
end
def down
add_index :game_ranks, [:game_id, :user_id], unique: true
end
end
|
class Customer < ActiveRecord::Base
belongs_to :company
has_many :comments # 追加
validates :family_name,
presence: true, length: {maximum: 20 }
validates :given_name,
presence: true, length: {maximum: 20 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email,
presence: true,... |
FactoryGirl.define do
factory :story do
sequence(:title) { |n| "Google #{n.to_i}" }
sequence(:url) { |n| "http://google.com/q=#{n.to_i}" }
end
factory :comment do
body "This is the comment body."
association :commentable, factory: :story
end
end
|
require 'json'
require 'open-uri'
class GamesController < ApplicationController
self.per_form_csrf_tokens = true
def new
@letters = (0...8).map { (65 + rand(26)).chr }
end
def score
@word = params[:word]
@letters = params[:grid]
if is_included_in_grid?(@word, @letters) == false
@re... |
require 'test_helper'
class UsersControllerTest < ActionController::TestCase
setup do
@user = Fabricate(:user)
end
context "GET /edit" do
should "render the edit template and respond with a 200" do
login_user(@user)
get :edit, id: @user.id
assert_response :success
assert_templat... |
class Familiar < ApplicationRecord
belongs_to :animal
has_many :reviews
end
|
# Threads Ain’t Free
# The improved performance with multiple threads might lead one to believe that we can just keep adding more threads –
# basically infinitely – to keep making our code run faster and faster. That would indeed be nice if it were true,
# but the reality is that threads are not free and so, sooner or... |
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
has_many :evaluations, class_name: "ReputationSystem::Evaluation", as: :source
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, ... |
class Movie < ActiveRecord::Base
def self.get_ratings
Movie.select(:rating).map(&:rating).uniq
end
end
|
class CategoriaPost < ActiveRecord::Base
belongs_to :categoria
belongs_to :post
end
|
include_recipe 'chef-openstack::common'
service "rabbitmq-server" do
supports :status => true, :restart => true, :reload => true
action :nothing
end
package "rabbitmq-server" do
action :install
notifies :restart, resources(:service => "rabbitmq-server"), :immediately
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.