text stringlengths 10 2.61M |
|---|
class AddAddressToUsers < ActiveRecord::Migration
def change
add_column :users, :address1, :string
add_column :users, :address2, :string
add_column :users, :city, :string
add_column :users, :state_or_province, :string
add_column :users, :postal_code, :string
add_column :users, :country, :strin... |
class Movie < ApplicationRecord
belongs_to :category
belongs_to :user
has_many :ratings, :dependent => :delete_all
scope :full_text_search, ->(text) { where('movies.title LIKE ? OR movies.text LIKE ?', "%#{text}%", "%#{text}%") }
scope :by_category, ->(category_id) { joins(:category).where(categories: { id:... |
require 'nokogiri'
class RTesseract
module Box
extend RTesseract::Base
def self.run(source, options)
options.tessedit_create_hocr = 1
RTesseract::Command.new(source, temp_file, options).run
parse(File.read(temp_file('.hocr')))
end
def self.parse(content)
html = Nokogiri::H... |
class Client < ActiveRecord::Base
before_create :create_api_key
attr_accessible :api_key, :last_accessed
def accessed!
self.last_accessed = DateTime.now
save
end
protected
def create_api_key
self.api_key = loop do
api_key = SecureRandom.urlsafe_base64(nil, false)
break api_key unle... |
class Processable < ActiveRecord::Base
belongs_to :procable, polymorphic: true
has_many :processable_processes
has_many :processes, through: :processable_processes
end
|
When /^I try to build nfsroot base$/ do
@messenger = StringIO.new
NfsrootBase.configure do | n |
n.arch = @arch
n.http_proxy = "http://localhost:8123/"
n.include = [ "emacs23" ]
n.package_repository = "http://myrepos/debian"
n.suite = @suite
n.messenger = @messenger
n.dry_run = true
... |
{
city: {
aliases: [:town, :town_city, :towncity],
values: %w(
Aberdeen Armagh Bangor Bath Belfast Birmingham Bradford Bristol Cambridge
Canterbury Cardiff Carlisle Chester Chichester London Coventry Derby Dundee
Durham Edinburgh Ely Exeter Glasgow Glo... |
# frozen_string_literal: true
RSpec.describe Storages::GoogleSheets::Worksheet, type: :storage do
subject(:storage) do
described_class.new(worksheet: worksheet)
end
let(:worksheet) { instance_spy(GoogleDrive::Worksheet) }
context '.save' do
subject(:save) { storage.save(result) }
context 'when th... |
Gem::Specification.new do |s|
s.name = 'ruby_log_reveal'
s.version = '0.0.1'
s.date = Time.now
s.summary = 'LogReveal helper for Ruby applications'
s.description = 'Wraps the LogReveal HTTPS API in a Ruby logging framework in order to ease Ruby application logging'
s.authors = ["Michael Halls-Moore"]
s.em... |
class User < ApplicationRecord
has_many :posts
has_many :projects, through: :posts
has_many :projects
has_many :comments
has_many :posts, through: :comments
end |
class Preference < ActiveRecord::Base
def to_s
"#{key}: #{value}"
end
end |
class ShipImagesController < ApplicationController
skip_before_action :authenticate_request
before_action :set_ship_image, only: [:show, :update, :destroy]
# GET /ship_images
def index
@ship_images = ShipImage.all
render json: @ship_images
end
# GET /ship_images/1
def show
render json: @s... |
RSpec.shared_examples 'feature-helpers' do
def response_json
JSON.parse(response.body)
end
end
|
# Find whether a string contains unique items. The string contains only lower case letters.
def uniq_chars?(str)
str.downcase
a = ("a".."z").all? {|c| str.count(c) <= 1}
end
puts uniq_chars?("abcde")
|
require_relative 'player'
class Game
attr_reader :player1, :player2, :current_turn
def initialize(player1 = Player.new, player2 = Player.new)
@player1 = player1
@player2 = player2
@current_turn = @player1
end
def switch_round
@current_turn = opposite(@current_turn)
end
def attack(player... |
class ArtistsController < ApplicationController
before_action :find_artist, only: [:show, :edit, :update]
def index
@artists = Artist.all
end
def show
end
def new
@artist = Artist.new
end
def create
@artist = Artist.create(artist_params)
redirect_to artist_path(@artist)
end
def edit
end
d... |
#!/usr/bin/env ruby
# -------------------------------------------------------------------------- #
# Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org) #
# #
# Licensed under the Apache License, Version 2.0 (the "License... |
#Yeah, filters are great! A quick rundown:
#You have a hpf, lpf, and bpf.
#hpf is a high pass filter, it will remove frequencies below the cutoff while keeping frequencies above.
#lpf is a low pass filter, the knob twiddler’s bread and butter. It will cut frequencies above the cutoff while allowing ones below.
#bpf is ... |
class Api::FavoriteController < ApplicationController
protect_from_forgery with: :null_session
respond_to :json
#Metodo que muestra todos los favoritos de un usuario
def index
@user = get_user(params[:user_id])
@favorites = get_favorites(@user)
respond_with @favorites
end
##Metodo para crear un favorito n... |
class User < ApplicationRecord
has_secure_password
has_many :haikus, dependent: :destroy
has_many :favorites
has_many :chat
has_many :chat_comment
has_many :favorite_haikus, through: :favorites,source: :haiku
# has_many :haikus, dependent: :destroy
validates :name , presence:true,
length: {maximum: 2... |
module MoneyMover
module Dwolla
class VerifiedBusinessCustomerController < BaseModel
attr_accessor :firstName, :lastName, :title, :dateOfBirth, :ssn
attr_reader :passport, :address
validates_presence_of :firstName, :lastName, :title, :dateOfBirth, :address
validate :validate_associated_ad... |
class LessonPayment < ApplicationRecord
belongs_to :account, optional: true
accepts_nested_attributes_for :account
belongs_to :booking, optional: true
accepts_nested_attributes_for :booking
end
|
# Class interprets Piglatin
class PigLatin
def self.set_class_vars
@@word_status = {}
@@word_ary = []
end
def self.default_word_status(str)
str.split.each { |wd| @@word_status[wd] = :not_mutated }
end
def self.append_ay(mutated_wd, wrd)
@@word_status[wrd] = :mutated
@@word_ary << (mutate... |
class TasksController < ApplicationController
def new
@task = Task.new
end
def create
@task = Task.new(task_params.merge(user_id: current_user.id))
respond_to do |format|
if @task.save
format.html {redirect_to user_path}
format.json {render action: 'users#show', status: :creat... |
# frozen_string_literal: true
class Admin::SessionsController < Devise::SessionsController
layout 'admin'
def after_sign_in_path_for(resource_or_scope)
admin_root_path
end
def after_sign_out_path_for(resource_or_scope)
new_admin_user_session_path
end
end
|
class UserRateLimiter < ApplicationRecord
validates :user_id, presence: true
class RateLimitExceeded < StandardError
def initialize(threshold_limit_minus_now)
super(
I18n.t('rate_limit_exceeded',
seconds: threshold_limit_minus_now.to_i)
)
end
end
def check_if_rat... |
class Indocker::Volumes::Repository
attr_reader :name, :repository_name, :path
def initialize(name, repository_alias_name, path)
@name = name
@repository_name = repository_alias_name
@path = path
end
end |
class ApplicationView
def make_tags_for_one_image(image)
ret = 'Tags: '
array = %w[]
image.tags.each do |tag|
array = array.push(ActionController::Base.helpers.link_to(
tag.name, Rails.application.routes.url_helpers.images_path(
searc... |
# frozen_string_literal: true
module Readings
# This class is used in Api:ReadingsController
class Stats < Mutations::Command
required do
string :household_token
end
def execute
{
avg_temperature: Rails.configuration.redis.get("#{household_token}.temperature_sum").to_f / count,
... |
#fog of learning
#sideloaded learning
#bruteforce
p "True has an object id of " + true.object_id.to_s
p "False has an object id of " + false.object_id.to_s
p "Nil has an object id of " + nil.object_id.to_s
# Introduction
p "What is an object? In Ruby, an object is a construct that holds data and behavior."
p "L... |
class JsSolutionsController < ApplicationController
def create
user_id = current_user.id
challenge_id = params["challenge_id"]
method_string = params["method_string"]
success = (params["success"] == "true")
language = "JavaScript"
@solution = Solution.new(
user_id: user_id,
ch... |
require 'rails_helper'
RSpec.describe 'Notification', type: :system do
let!(:user) { create(:user) }
let!(:other_user) { create(:user) }
let!(:tweet) { create(:tweet, user: other_user) }
describe '通知一覧ページ' do
context '通知生成' do
before do
sign_in user
end
context '自分以外のユーザーのtweetに対... |
class ComPropertyMatcher
def initialize(prop, *values)
@property = prop
@values = values
end
def matches?(com_obj)
@com_obj = com_obj
getter = @property.to_sym
setter = "#{@property}=".to_sym
@failed = []
@values.each do |value|
begin
@com_obj.send(getter)
@com... |
#!/usr/bin/env ruby
SWITCHING_COST=5
class Bread
def initialize(name, prep, rise_1, rise_2, bake)
@name = name
@prep = prep
@rise_1 = rise_1
@rise_2 = rise_2
@bake = bake
end
attr_reader :name, :prep, :rise_1, :rise_2, :bake
end
class Vertex
def initialize(name)
@name = name
#@vi... |
class Sbt
attr_reader :base_dir, :sbt_args, :assembly_jar, :package_jar, :output_dir
def initialize
@base_dir = Dir.pwd
@sbt_args = sbt_args
@output_dir = "target/scala-#{@sbt_args[:scalaVersion].sub(/\.\d+$/, '')}"
@assembly_jar = "#{@sbt_args[:name]}-assembly-#{@sbt_args[:version]}.jar"
@pack... |
require 'spec_helper'
describe 'yum-webtatic::default' do
context 'with default attributes' do
let(:chef_run) { ChefSpec::SoloRunner.new.converge(described_recipe) }
%w(
webtatic
).each do |repo|
it "creates yum_repository[#{repo}]" do
expect(chef_run).to create_yum_repository(repo).... |
class CreateOrders < ActiveRecord::Migration
def change
create_table :orders do |t|
t.string :order_type
t.references :project, index: true, null: false
t.string :state, null: false, default: 'submitted'
t.string :title, null: false
t.text :description
t.... |
#class for Model1 goes here
#Feel free to change the name of the class
class Teacher
attr_accessor :name, :subject, :age
@@all = []
def initialize(name, subject, :age)
@name = name
@subject = subject
@age = age
@@all << self
end
def self.all
@@all
end
... |
module Qubole::Commands
describe Spark do
describe "initialize" do
it "sets correct command type" do
command = Qubole::Commands::Spark.new
command.command_type = 'SparkCommand'
end
end
end
end
|
module ManageIQ::Providers
class Vmware::CloudManager::OrchestrationServiceOptionConverter < ::ServiceOrchestration::OptionConverter
include Vmdb::Logging
def stack_create_options
options = {
:deploy => stack_parameters['deploy'] == 't',
:powerOn => stack_parameters['powerOn'] == 't'
... |
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :lists
has_many :listnames
... |
# Der Controller wird fuer die Kommentarfunktion vom Schwarzen Brett benoetigt
class CommentsController < ApplicationController
load_and_authorize_resource
# POST /messages
def create
@message = Message.find(params[:message_id])
@comment = @message.comments.create(params[:comment].permit(:message_id,
... |
class RemoveStartDateFromMealPlan < ActiveRecord::Migration[6.0]
def change
remove_column :meal_plans, :start_date, :datetime
remove_column :meal_plans, :number_of_days, :int
end
end
|
require 'spec_helper'
describe Mongoid::Scribe do
describe "the authenticate_with setting" do
after { subject.configure { authenticate_with Mongoid::Scribe::DEFAULT_AUTHENTICATION_FILTER } }
it "should have a default filter that returns true" do
expect(subject.authentication_filter).to be_nil
end
... |
require_relative "../spec_helper.rb"
require_relative "../../lib/gather_environment.rb"
require_relative "../../components.rb"
#Specs for Environment Gathering Methods
describe "Gathers Working Environment Variables" do
context "When detecting current user info..." do
GetEnvVariables.kick_off
it "\n -Detec... |
class Boundaries
def initialize(origin:, dimensions:)
@origin = origin
@dimensions = dimensions
end
def collection
@collection ||= build_collection
end
def has_outside_or_overlapping?(faces)
planes = [collection, faces.collection].transpose
planes.any? { |dim| outside_or_not_inside_of?(d... |
# coding: utf-8
FactoryGirl.define do
factory :artist_larc, :class => Artist do
id 1
name "L'Arc~en~Ciel"
show_flg TRUE
created_at Time.now
updated_at Time.now
image_searched_at Time.now
end
end |
class Subcontract < ActiveRecord::Base
self.inheritance_column = nil
has_many :subcontract_details
has_many :subcontract_advances
belongs_to :cost_center
belongs_to :entity
accepts_nested_attributes_for :subcontract_details, :allow_destroy => true
accepts_nested_attributes_for :subcontract_advances, :allo... |
require_relative '../minitest_helper'
describe NakkitypeInfosController do
def json_response
ActiveSupport::JSON.decode @response.body
end
def login_as(user)
@request.session[:user_id] = user ? user.id : nil
end
before do
FactoryGirl.create_list(:nakkitype_info, 2)
test_user = FactoryGirl.c... |
include DataMagic
require 'rubygems'
require 'json'
When(/^I am using the default responses for Manage Payment Accounts$/) do
default_responses = data_for(:mpa_default_data)
default_responses.each do |mock_uri, json_file|
url = "/" + mock_uri.gsub("-", "/")
mock_response = File.open("#{Dir.pwd}/features/mo... |
require 'rails_helper'
describe 'the static page display' do
it "will show the home page" do
visit root_path
expect(page).to have_content "Welcome to Flakr"
end
end
|
require 'spec_helper'
describe Puppet::Type.type(:vnic).provider(:solaris) do
let(:params) do
{
:name => "vnic1",
:lower_link => "net1",
:ensure => :present,
}
end
let(:resource) { Puppet::Type.type(:vnic).new(params) }
let(:provider) { described_class.new(resource) }
before(:eac... |
#
# Copyright 2011-2013, Dell
# Copyright 2013-2014, SUSE LINUX Products GmbH
#
# 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-2.0
#
# Unless requi... |
require 'travis/github_sync/api/user/education'
require 'travis/github_sync/support/logger'
describe Travis::GithubSync::Api::User::Education do
let(:user) { model(:user).create(name: 'user', login: 'user', github_id: 2208, github_oauth_token: '123') }
subject { described_class.new(user.id) }
describe 'f... |
require 'test_helper'
class LeadsBookingModifyTest < ActionDispatch::IntegrationTest
test "Modify an existing booking" do
get '/sign_in'
post '/sign_in', params: { lead: { email: leads(:lead).email, password: '123456789'} }
follow_redirect!
post '/update_booking?id=1'
assert_template 'leads/book... |
class QuestionVotesController < ApplicationController
before_action :set_question
before_action :set_question_vote, only: [:show, :edit, :update, :destroy]
skip_after_action :set_return_to
# POST /question_votes
# POST /question_votes.json
def create
if user_signed_in?
@question_vote = current_us... |
require 'rails_helper'
RSpec.describe User, type: :model do
before :each do
@user = User.new
end
describe 'when user is saved' do
it 'should have email and password' do
@user.valid?
expect(@user.errors[:email]).to include('can\'t be blank')
expect(@user.errors[:password]).to include(... |
class GamesController < ApplicationController
before_action :set_game, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
before_action :only_current_user
before_action :user_needs_name
# GET /games
# GET /games.json
def index
@games = Game.all
end
# GET /games/1
# GET /... |
require File.dirname(__FILE__) + '/../../spec_helper.rb'
if ActiveRecord::Base.instance_methods.include?('changed?')
describe "OracleEnhancedAdapter dirty object tracking" do
before(:all) do
ActiveRecord::Base.establish_connection(CONNECTION_PARAMS)
@conn = ActiveRecord::Base.connection
@conn... |
class OrdersController < ApplicationController
before_action :set_order, only: [:show, :edit, :update, :destroy]
def index
@orders = Order.all
# display price as 2 decimal places and append zeroes on the decimal
@total_purchase_order = '%.2f' % Order.where(order_type: "purchase").sum(:price)
@total... |
class Task < ActiveRecord::Base
validates :title, presence: true
belongs_to :list
has_and_belongs_to_many :tags
end
|
class AddEmailToContactInformations < ActiveRecord::Migration
def change
add_column :contact_informations, :emailAddress, :string
end
end
|
module GeneratorSpecHelpers
def provide_routes_file
create_file_from_template('templates/routes.rb', 'config')
end
def provide_application_js_file
create_file_from_template('templates/application.js',
'app/assets/javascripts')
end
private
def create_file_from_templat... |
FactoryGirl.define do
factory :project_member do
user
project
master
trait :guest do
access_level ProjectMember::GUEST
end
trait :reporter do
access_level ProjectMember::REPORTER
end
trait :developer do
access_level ProjectMember::DEVELOPER
end
trait :mast... |
class TagsController < ApplicationController
def index
tags = Tag.all
render json: { tags: tags }, status: 200
end
end
|
module Pantograph
module Actions
class BundleInstallAction < Action
# rubocop:disable Metrics/PerceivedComplexity
def self.run(params)
if gemfile_exists?(params)
cmd = ['bundle install']
cmd << "--binstubs #{params[:binstubs]}" if params[:binstubs]
cmd << "--clea... |
class CardSerializer < ActiveModel::Serializer
attributes :id, :suit, :value, :code, :image
end
|
require 'spec_helper'
describe ImgCLI::EXIF do
let(:subject) { ImgCLI::EXIF.call(File.expand_path('support/test', __dir__)) }
it 'returns file count' do
expect(subject.count).to eq(5)
end
it 'returns heading' do
expect(subject.headings).to match_array(ImgCLI::EXIF::TABLE_HEADINGS)
end
it 'stores... |
class SportsTeam
attr_reader :players
attr_accessor :name, :coach, :points
def initialize(name, players, coach, points = 0)
@name = name
@players = players
@coach = coach
@points = points
end
# Before refactoring
# def get_name
# return @name
# end
#
# def get_players
# retur... |
class Festival < ActiveRecord::Base
belongs_to:user
has_many:artists, dependent: :destroy
validates :user_id, presence: true
validates :fes_name, presence: true, length:{ maximum:50}
validates :fes_place, presence: true, length:{ maximum:50}
end
|
module Visualization
class BoxplotPresenter < Presenter
include DbTypesToChorus
delegate :type, :bins, :values, :category, :rows, :type, :filters, :to => :model
def to_hash
{
:type => type,
:bins => bins,
:x_axis => category,
:y_axis => values,
... |
class Compra < ActiveRecord::Base
attr_accessible :estado_compra_id, :fecha_solicitud, :numero_orden, :observacion, :numero_factura, :fecha_inicio_timbrado, :fecha_fin_timbrado, :forma_pago_id, :cuenta_corriente_id, :numero_cheque, :fecha_factura
scope :ordenado_01, -> {order("fecha_solicitud desc")}
scope :or... |
require 'test_helper'
class ReporPeopleControllerTest < ActionDispatch::IntegrationTest
setup do
@repor_person = repor_people(:one)
end
test "should get index" do
get repor_people_url, as: :json
assert_response :success
end
test "should create repor_person" do
assert_difference('ReporPerson... |
# 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
class ContractsController < ApplicationController
before_action :autheticate_user
before_action :set_contract, only: [:edit, :update]
def index
@contracts = @current_user.contracts
end
def new
@contract = Contract.new
end
def create
@contract = Contract.new(co... |
class AddDueOutToPallets < ActiveRecord::Migration[5.1]
def change
add_column :pallets, :due_out, :date
end
end
|
module PryIb
module Command
module Alert
def self.build(commands)
commands.create_command "alert" do
description "Setup an alert"
banner <<-BANNER
Usage: alert symbol | { |bar| bar.close > 42 }
Example:
alert aapl | { |bar| bar.close > 42 }... |
class GroupRanking < ActiveRecord::Base
START_DATE = '2013-11-01'
END_DATE = '2013-12-01'
def self.ranking_list
records = ActiveRecord::Base.connection.execute <<-SQL
SELECT g.id as id, g.name as name, sum(r.steps) as steps, sum(r.distance) as distance
FROM groups g
JOIN group_users gu ON (... |
Vagrant.configure("2") do |config|
config.vm.define "docker" do |docker|
docker.vm.provider "virtualbox" do |v|
v.name = "vagrant_docker"
v.linked_clone = true
end
docker.vm.box = "centos/6"
docker.vm.network "private_network",
virtualbox__intnet: "mgmt_net",
nic_type: "virtio"... |
ResetPasswordMutation = GraphQL::Relay::Mutation.define do
name 'ResetPassword'
input_field :email, !types.String
return_field :success, types.Boolean
return_field :expiry, types.Int
resolve -> (_root, inputs, _ctx) {
user = User.where(email: inputs[:email]).last
if user.nil?
raise ActiveReco... |
namespace :kuhsaft do
namespace :db do
desc "Load kuhsaft seeds"
task :seed => :environment do
Kuhsaft::Engine.load_seed
end
end
end
Rake::Task['db:seed'].enhance ['kuhsaft:db:seed']
desc "Create nondigest versions of all ckeditor digest assets"
task "assets:precompile" do
fingerprint = /\-[0-... |
class Ghost
def initialize
colors = ["white", "yellow", "purple", "red"]
random_color = colors[rand(4)]
puts "Ghost color is #{random_color}"
end
end
ghost = Ghost.new
#Create a class Ghost
#Ghost objects are instantiated without any arguments.
#Ghost objects are given a random color attribute... |
#! /usr/bin/env ruby
# -*- encoding: UTF-8 -*-
require 'thor'
require 'json'
require 'yaml'
module Pingdom
module Cli
class CLI < Thor
include Thor::Actions
map '-l' => :checks
class_option :config, aliases: '--config', type: :string, default: "#{ENV['HOME']}/.pingdomrc", desc: 'config file'
... |
# The beginning of a set of tools to make working with Rally easier.
require './errors.rb'
require './preset.rb'
require 'http'
require 'json'
require 'pry'
require 'yaml'
class HTTPRequestError < StandardError
attr_reader :msg
@msg = nil
def initialize(resp)
@msg = "Bad response from HTTP Request, status co... |
RSpec::Matchers.define :be_cacheable do
match do |response|
response.headers['Cache-Control'] &&
response.headers['Cache-Control'].match(/public/)
end
# Optional failure messages
failure_message_for_should do |actual|
"expected response headers to include correct Cache-Control"
end
failure_mes... |
class Section < ActiveRecord::Base
attr_accessible :average_price, :std_dev, :team_id, :name, :seat_view_url
belongs_to :team
has_many :tickets, :inverse_of => :section
validates :name, :uniqueness => {:scope => :team_id }
validates :average_price, :std_dev, :presence => true, :numericality => true, :on => :u... |
class Contact < ActiveRecord::Base
belongs_to :"projects"
belongs_to :"users"
has_many :usercontacts, dependent: :destroy
validates_presence_of :contact_name
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
namespace :api do
namespace :v1 do
get '/hands', to: 'hands#index'
post '/hands', to: 'hands#create'
get '/hands/:id', to: 'hands#show'
get '/heads', to... |
class AddressesController < ApplicationController
before_filter :find_user, :find_customer
before_filter :find_address, :except => [:new, :create]
def new
@address = @customer.addresses.build(:country_code_alpha2 => 'US', :region => 'California')
end
def edit; end
def create
@address = @cus... |
class OrderItemsController < ApplicationController
def create
#current order is fetched or created from Order class in app controller
#if an order already exists then it just uses the id in session to fetch the order from the db
#if an order is new then it creates the order.
@order = current_order
@order... |
class CreateOrderItems < ActiveRecord::Migration[6.1]
def change
create_table :order_items do |t|
t.references :order, index: true, foreign_key: true
t.references :variant, index: true, foreign_key: true
t.integer :quantity
t.integer :item_price_cents
t.integer :total_price_cents
... |
class InventoryItem < ApplicationRecord
belongs_to :item
belongs_to :location
belongs_to :inventory_item_state
belongs_to :inventory_item_condition
validates :item, presence: true, length: { minimum: 3 }
validates :location, presence: true, length: { minimum: 3 }
validates :inventory_item_state, presence: true... |
require 'spec_helper'
describe 'user profile' do
it 'updates users' do
sign_in_as_a_user
visit edit_my_profile_path(f: 's')
page.find("select#user_state_id")
page.find("input[type=text]#city-autocomplete")
page.find("input[type=hidden]#user_city_id")
within("#edit_user_#{@current_user.id}")... |
module Commentable
extend ActiveSupport::Concern
included do
has_many :comments, as: :commentable
after_initialize { self.rating = 5 if self.new_record? }
end
end |
class MachinesController < ApplicationController
def index
@machines = current_user.machines
end
def show
set_machine
end
def new
@machine = current_user.machines.new
end
def create
@machine = current_user.machines.new(machine_params)
return false unless upload_public_key
if @ma... |
module EnrollmentHelper
def enrolled(user, section_code, course_name)
enrolled_sections = user.sections.pluck(:code)
enrolled_courses = user.courses.pluck(:number)
enrolled_sections.include?(section_code) || enrolled_courses.include?(course_name)
end
def period_conflict(user, section_period)
enr... |
class ChangeDatatypeBankCodeOfBankAccounts < ActiveRecord::Migration[5.0]
def change
change_column :bank_accounts, :bank_code, :string
end
end
|
class AddScoreToPlayers < ActiveRecord::Migration
def change
add_column :players, :score, :integer, limit: 2, after: :position
end
end
|
require 'set'
require 'active_support/core_ext/class/attribute_accessors'
class NotifierManager
cattr_accessor(:notifiers) { Set.new }
def self.add_notifier(notifier)
notifiers.add(notifier)
end
def self.notify_all(build)
notifiers.each { |n| n.notify(build) }
end
end
|
require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Schemas::Responses do
describe 'correct init' do
subject { operation.responses }
let(:root) { OpenAPIParser.parse(petstore_schema, {}) }
let(:paths) { root.paths }
let(:path_item) { paths.path['/pets'] }
let(:operation) { path_i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.