text stringlengths 10 2.61M |
|---|
class ReviewsController < ApplicationController
def index
reviews = Review.all
render json: reviews
end
def show
review = Review.find_by(id: params[:id])
render json: review
end
def create
review = Review.new(review_params)
if review.save
render json: review
else
rend... |
module Gpx
class Exporter
def self.export(ride, path)
file = File.open(path, 'w')
file.write "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>"
file.write "<gpx xmlns=\"http://www.topografix.com/GPX/1/1\" xmlns:gpxx=\"http://www.garmin.com/xmlschemas/GpxExtensions/v3\" xmlns:wptx1=\... |
class RaffleCategoriesController < ApplicationController
before_action :set_raffle_category, only: [:show, :edit, :update, :destroy]
before_action :admin_user, only: [:new, :create, :edit, :update, :destroy]
# GET /raffle_categories
# GET /raffle_categories.json
def index
@raffle_categories = RaffleCate... |
class AreaPolicy < PlacePolicy
def geocode?
user.present?
end
def mappable?
true
end
end
|
class PlateSetPlate < ActiveRecord::Base
belongs_to :plate_set
validates_presence_of :plate_name
end
|
class CreateStudents < ActiveRecord::Migration[5.0]
def change
create_table :students do |t|
t.string :name, limit: 45, required: true
t.string :register_number, limit: 45, required: true, unique: true, index: true
t.integer :status, index: true
t.timestamps
end
end
end
|
class BiblioCommonsTitleContentMatch < ActiveRecord::Base
include ContentMatch
belongs_to :tweet
belongs_to :biblio_commons_title_content_item
attr_accessible :tweet,
:biblio_commons_title_content_item
validates :tweet,
:biblio_commons_title_content_item,
:presence... |
require 'spec_helper'
module ChefSpec
module Matchers
describe :log do
describe "#match" do
let(:matcher) { log('Hello World') }
it "should not match when no resources exist" do
matcher.matches?({:resources => []}).should be false
end
it "should match when the log ... |
# require_relative is requiring a file that starts in the same directory as the file you are coding in. require is the same but it starts looking in other predefined directories
# require_relative does not change its behavior whereever you are and require does
# I worked on this challenge [by myself, with: ].
# We spen... |
require 'cloudformation_mapper/resource'
class CloudformationMapper::Resource::AwsPropertiesEc2EbsVolumeattachment < CloudformationMapper::Resource
register_type 'AWS::EC2::VolumeAttachment'
type 'Template'
parameter do
type 'Template'
name :Properties
parameter do
type 'String'
name... |
class CreateDeadlines < ActiveRecord::Migration
def change
create_table :deadlines do |t|
t.string :deadline_info
t.date :date
t.integer :phase_id
t.integer :delegate_fee
t.integer :delegation_fee
t.references :category
t.boolean :is_active, default: true
t.t... |
class Comment < ApplicationRecord
belongs_to :user
belongs_to :article
validates :body,
:presence => {:message => " can't be blank." }
end
|
class BankAccount
@@interest_rate = 1.01
@@accounts = []
def initialize
@balance = 0
end
# CLASS METHODS
def self.create
new_account = BankAccount.new
@@accounts << new_account
return new_account
end
def self.total_funds
sum = 0
@@accounts.each do |object|
sum += object.balance... |
require 'librarian/puppet/util'
require 'librarian/puppet/source/rpm/repo'
require 'librarian/source/basic_api'
module Librarian
module Puppet
module Source
class RPM
include Librarian::Puppet::Util
include BasicApi
lock_name 'RPM'
spec_options [:version, :release]
... |
# encoding: utf-8
#!/usr/bin/env ruby
class Cadastro < SitePrism::Page
element :endereco_email, "input[id='email']"
element :nome_usuario, "input[id='username']"
element :senha, "input[id='password']"
element :confirmar_senha, "input[id='password-confirm']"
end
|
class Feature < ActiveRecord::Base
belongs_to :item
has_attached_file :image, styles: { original: '450x205#' },
convert_options: {
original: '-strip -interlace Plane -quality 80%'
},
default_url: '/images/:style/missing.png'
val... |
class CreatePhotos < ActiveRecord::Migration
def self.up
create_table :photos do |t|
t.belongs_to :gallery
t.boolean :default, :default => false
t.string :ru_caption
t.string :en_caption
t.text :ru_description
t.text :en_description
end
end
... |
class AddWeightToCritters < ActiveRecord::Migration
def change
add_column :critters, :weight, :integer
end
end
|
require 'tax_cloud/response/response_base'
require 'tax_cloud/response/response_type'
require 'tax_cloud/response/response_message'
module TaxCloud
class ResponseBase
include TaxCloud::ResponseType
def initialize(attrs={})
@response_type = attrs[:response_type]
@raw_messages = attrs[:messages]
... |
#! /usr/bin/env ruby
require 'digest'
@input = STDIN.read.chomp
def lowest_positive_number(number_of_leading_zeros = 5)
i = 0
zeroes = '0' * number_of_leading_zeros
loop do
md5 = Digest::MD5.hexdigest("#{@input}#{i}")
break if md5.start_with?(zeroes)
i = i + 1
end
i
end
p lowest_positive_numb... |
require_relative "apple_tree"
RSpec.describe AppleTree do
before(:each) do
@tree = AppleTree.new
end
it "should have an age attribute with getter and setter methods" do
@tree.age = 4
expect(@tree.age).to eq(4)
end
it "should have height and apple_count attributes with only a... |
#!/usr/bin/env ruby
# This works similarly
# except it uses the same price
# for both young and old customers
puts "Enter the customer's age: "
age = gets.to_i
if ((age <= 12) or (age >= 65))
cost = 9
else
cost = 18
end
puts "Ticket cost: " + cost.to_s
|
#
# Be sure to run `pod lib lint LYLeaksInspector.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = "LYL... |
require_relative('../db/sql_runner')
class Team
attr_reader(:id, :name, :location)
def initialize(options)
@id = options['id'].to_i
@name = options['name']
@location = options['location']
end
def save()
sql = "INSERT INTO teams (name, location) VALUES ('#{@name}', '#{@location}') RETURNING *... |
require 'spec_helper'
describe ReversePolishCalculator::Calculator do
subject(:calculator) { described_class.new }
describe '#calculate' do
before :each do
ReversePolishCalculator::MathEngine.any_instance.stub(:process_tokens => nil, :stack => [])
ReversePolishCalculator::Operator.stub(:new => stu... |
class EditPickup < ActiveRecord::Migration
def change
add_column :pickups, :delivery_datetime, :datetime;
add_column :pickups, :delivery_type, :string;
add_column :pickups, :request_id, :string;
add_column :pickups, :totle_cost, :decimal;
change_column :pickups, :number, :string;
end
end
|
require "rake"
require 'cucumber/rake/task'
require "colorize"
Cucumber::Rake::Task.new do |t|
t.cucumber_opts = %w{--format pretty}
end
desc "Start the application"
task :start do
start_application
end
def start_application
prompt_to_install_node unless has_node_installed?
prompt_to_install_coffeesc... |
module Restfulie::Client
module Formatter
module Xml
class Driver
def marshal(obj, options = {})
if obj.kind_of?(String)
obj
elsif obj.kind_of?(Hash) && obj.size==1
root = obj.values.first
unless root.respond_to?(:to_xml)
raise "T... |
# frozen_string_literal: true
module BPS
module PDF
class Roster < Base
include BPS::PDF::Roster::Shared
include BPS::PDF::Roster::Simple::CoverPage
include BPS::PDF::Roster::Simple::RosterPages
def self.create_pdf(orientation = :portrait, include_blank: false)
@orientation = ... |
require 'cf_spec_helper'
describe 'JRuby App' do
before(:all) do
@app = Machete.deploy_app('sinatra_jruby_web_app')
expect(@app).to be_running
end
after(:all) do
Machete::CF::DeleteApp.new.execute(@app)
end
specify 'the buildpack logged it installed a specific version of JRuby' do
expect(@a... |
class User < ActiveRecord::Base
include Common::Uuid, Users::LoginAuthenticatable
extend FriendlyId
friendly_id :uuid, use: :slugged
devise :database_authenticatable, :confirmable, :registerable, :recoverable, :validatable,
authentication_keys: [:email]
has_many :price_notifications
end |
class BoardShare < ApplicationRecord
validates_uniqueness_of :contributor_id, :scope => [:board_id]
belongs_to :user,
primary_key: :id,
foreign_key: :contributor_id,
class_name: :User
belongs_to :board,
primary_key: :id,
foreign_key: :board_id,
class_name: :Board
end
|
require 'rails_helper'
describe 'creating a new tournament' do
let!(:club) { FactoryBot.create :club, member_count: 5 }
let(:players) { club.players.sort_by(&:rating).reverse }
let(:player_1) { players[0] }
let(:player_2) { players[1] }
let(:player_3) { players[2] }
let(:player_4) { players[3] }
let(:ne... |
class RemoveColumnsFromSceneCollections < ActiveRecord::Migration
def change
remove_column :scene_collections, :font
remove_column :scene_collections, :music
remove_column :scene_collections, :color
remove_column :scene_collections, :callback_url
end
end
|
#
# Class TestController (QUI NE DOIT SERVIR QUE POUR LES TESTS)
#
class TestController < Controller
before_filter :filtre_avant
after_filter :filtre_apres, :except => :une_methode
after_filter :autre_filtre_apres, :only => :autre_methode
@trace = nil
def une_methode
add_to_trace "dans une mé... |
class ColorPalettesController < ApplicationController
before_filter :require_admin
def index
@color_palettes = ColorPalette.ordered
end
def new
@color_palette = ColorPalette.new
end
def edit
@color_palette = ColorPalette.find params[:id]
end
def create
@color_palette = ColorPalette.n... |
class JobsController < ApplicationController
before_action :confirm_logged_in
def index
if authorize([:all])
pages = 10
@jobs = Job.all
@current_user = current_user
end
end
def new
authorize([:company])
end
def create
if authorize([:company])
... |
require 'mechanize'
require 'vcr'
require 'yaml'
require 'fileutils'
VCR.configure do |c|
c.cassette_library_dir = 'cached'
c.hook_into :webmock
end
class Scraper
attr_accessor :root
attr_accessor :agent
attr_accessor :pages
def initialize
@root = "http://web.archive.org/web/20030820233527/http://by... |
class Playground
attr_reader :top, :right
def initialize(top,right)
@top = top
@right = right
end
#settle a car down on the playground
#TODO jude whether the car's position is in palyground
def settle_car(car)
car.outOfRange = true if(car.x<0 || car.x>@right || car.y < 0 || car.y > @top)
car.playground... |
def fizzbuzz in1, in2
while in1 <= in2
if in1 % 3 == 0 && in1 % 5 == 0
print 'FizzBuzz'
elsif in1 % 3 == 0
print 'Fizz'
elsif in1 % 5 == 0
print 'Buzz'
else
print in1
end
print ', ' unless in1 == in2
print "\n" if in1 == in2
in1 += 1
end
end
fizzbuzz(1, 15) ... |
def echo (word)
return word
end
def shout(word)
return word.upcase
end
def repeat(word, n=2)
answer = ""
while n>1
answer << word + " "
n-=1
end
return answer + word
end
def start_of_word(word, n=1)
return word[0,n]
end
def first_word(string)
string.split[0].to_s
end
def titleize(str)
lit... |
# frozen_string_literal: true
# == Schema Information
#
# Table name: modifiers
#
# id :bigint(8) not null, primary key
# description :text
# name :text
# percent :integer
# start :date
# stop :date
# created_at :datetime not null
# updated_at :datetime ... |
class ChangeColumnsInReports < ActiveRecord::Migration
def up
change_column :reports, :meter, :integer, :default => 0
change_column :reports, :mileage, :integer, :default => 0
change_column :reports, :riding_mileage, :integer, :default => 0
change_column :reports, :riding_count, :integer, :default => ... |
# for compliance
module Compliance
# for dd and poo
class SupplementaryElement < ActiveRecord::Base
self.table_name = 'supplementary_elements'
attr_accessible :audit_id, :audit_type, :auditor_id, :auditor_manager_id,
:compliance_encounter_id, :orig_id, :orig_type
# Associations
b... |
input = File.open("#{File.dirname(__FILE__)}/input", 'rb').read
class Solution
attr_reader :input, :order_history
def initialize(input)
@input = formatted_input(input)
@order_history = []
end
def part_1
count = 0
bank = input.dup
until order_history.include? stri... |
class PrivatePlaceTypesController < ApplicationController
before_action :set_private_place_type, only: [:show, :edit, :update, :destroy]
# GET /private_place_types
# GET /private_place_types.json
def index
@private_place_types = PrivatePlaceType.all.order("name")
end
# GET /private_place_types/1
# G... |
require 'rails_helper'
RSpec.describe 'the agreements list' do
around(:each) do |example|
ClimateControl.modify AWS_S3_BUCKET: 'bucket-name', AWS_S3_REGION: 'zz-north-1' do
example.run
end
end
it 'refuses users that are not signed in' do
get agreements_path
expect(response).to redirect_to... |
class SaveRole
prepend SimpleCommand
attr_reader :args
def initialize(args = {}, current_user)
@args = args
end
def call
if args[:id].present?
role = Common::Role.find(args[:id])
return role if role.readonly?
else
role = Common::Role.new
end
role.name = args[:name]
... |
# == Informacion de la tabla
#
# Nombre de la tabla: *dbm_nota_destacadas*
#
# id :integer(11) not null, primary key
# titulo :string(255)
# resumen :text
# fuente :string(255)
# archivo :string(255)
# enlace :string(255)
# imagen :string(255)
# created_at :datetime
# updated_... |
class RentfilesController < ApplicationController
def new
@apply = Apply.find(params[:apply_id])
redirect_to new_apply_rentfile_path(@apply, optional: "true") if params[:count].to_i > Rentfile::MANDATORY_RENTFILES.size - 1
if params[:optional] == "true"
@type = Rentfile::OPTIONAL_RENTFILES
elsi... |
require 'cgi'
require 'timeout'
require 'capybara'
require 'capybara/dsl'
require 'capybara/poltergeist'
require 'phantomjs'
class CompetitiveProductInformation
include Capybara::DSL
def initialize
puts 'initializing'
options = {
debug: false,
js_errors: false,
phantomjs: ... |
class AddBlockUsersToProfile < ActiveRecord::Migration[5.2]
def change
add_column :profiles, :blocked_user, :string, array:true, default: []
end
end
|
module Enjoy::News
module Models
module Mongoid
module Category
extend ActiveSupport::Concern
include Enjoy::HtmlField
included do
field :name, type: String, localize: Enjoy::News.configuration.localize, default: ""
scope :sorted, -> { order_by([:lft, :asc]) }
... |
# Thanks to Jesse Farmer [https://github.com/jfarmer] for showing me this concept,
# as I was looking for ways to accurately calculate high powers of "phi",
# which is the furtherest thing from a rational number...
# Defining a custom class to represent "phi" AKA the golden ratio
# (1 + sqrt(5))/2 ~= 1.618...
# Using ... |
class QueriesController < ApplicationController
protect_from_forgery
# GET /
def index
end
# in light of the unavailability of an easy way to connect to sqlite in a read-only state,
# we filter the destructive commands out of the query and run it to return the results as
# a partial to show the u... |
require 'rails_helper'
describe Item do
describe '#create' do
it "item_imageが無い場合は登録できないこと" do
item = build(:item)
item.valid?
expect(item.errors[:item_images]).to include("を入力してください")
end
it "nameが無い場合は登録できないこと" do
item = build(:item, name: nil)
item.valid?
expect(it... |
class ProgressBar
module Format
class Molecule
MOLECULES = {
:t => :title,
:T => :title,
:c => :progress,
:C => :total,
:p => :percentage,
:P => :percentage_with_precision,
:a => :elapsed_time,
:e => :estimated_time_with_unknown_oob,
:E... |
ActiveAdmin.register_page "Invited User" do
content title: "Invited User" do
columns do
column do
panel "#{User.where(:invite_user => true).count} Invited User" do
table do
th do
"Email ID"
end
User.where(:invite_user => true).map do |post|... |
require_relative './utils'
module Oyaspirateur
class File
class << self
def name_of(node)
node.content
end
def url_of(node)
Utils.href_of(node)
end
def from_node(node, root_url)
new(name_of(node), url_of(node), root_url)
end
end
attr_reader :... |
require 'rails_helper'
RSpec.describe ManagementConsultancy::SupplierSpreadsheetCreator do
let(:supplier) { create(:management_consultancy_supplier) }
let(:suppliers) { ManagementConsultancy::Supplier.where(id: supplier.id) }
let(:lot_number) { 'MCF1.2' }
let(:lot) { ManagementConsultancy::Lot.find_by(number: ... |
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
module TwitterCldr
module Shared
class UnsupportedNumberingSystemError < StandardError; end
class NumberingSystem
class << self
def for_name(name)
name_cache[name] ||= begin
if... |
module Yegor
class Img
def initialize(src, ctx)
if src.index('/') == 0
@url = src
raise "file doesn't exist: #{src}" unless
File.exists?('./_site' + src) ||
File.exists?('.' + src) ||
src =~ /gnuplot/
else
@url = src
end
end
def to_s
... |
# require "rails_helper"
# RSpec.describe ExpressTemplatesController, type: :routing do
# describe "routing" do
# it "routes to #index" do
# expect(:get => "/express_templates").to route_to("express_templates#index")
# end
# it "routes to #new" do
# expect(:get => "/express_templates/new").... |
class LibWalker < Walker
def search(first_page = 1)
current_page = first_page
set_search_parameters
page.click_link 'View Results'
# @form.debug.set_text(page.html)
begin
while true
wait_for_search_results
wait_for_origin_loading
ResultsPage.new(noko_page, @sear... |
require 'rails_helper'
RSpec.describe Goal, type: :model do
#has a user id
#has compeleted column
#has body
#private or public
#has a title
describe "validations of Goal object" do
it {should validate_presence_of(:user_id) }
it {should validate_inclusion_of(:completed).in_array([true, false])} #... |
class MainAuthorizer < ApplicationAuthorizer
authorizer(
name: 'ScribbleCognito',
identity_source: 'Authorization',
type: :cognito_user_pools,
provider_arns: [
ENV['COGNITO_ARN']
]
)
end
|
class BrewSparkling < Formula
homepage "https://github.com/codefirst/homebrew-sparkling/"
url "https://github.com/codefirst/homebrew-sparkling.git", tag: "v0.1.0"
head "https://github.com/codefirst/homebrew-sparkling.git", branch: "master"
skip_clean "bin"
depends_on "mobiledevice" => :build
depends_on "c... |
# encoding: utf-8
class EntryPreviewUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"assets/media/contest_detail/#{model.contest.created_... |
FactoryGirl.define do
factory :restaurant do
name { FFaker::Lorem.word }
last_visit { Date.today }
end
end |
require 'uri'
Puppet::Type.newtype(:nexus_crowd_settings) do
@doc = 'Manage the crowd settings.'
newparam(:name, :namevar => true) do
desc 'Name of the configuration (i.e. current).'
end
newproperty(:application_name) do
desc 'The username of the crowd application.'
validate do |value|
rai... |
class ListPartnerSerializer < ActiveModel::Serializer
include Rails.application.routes.url_helpers
attr_reader :object
attributes :partners, :links
def initialize(object)
@object = object
end
def partners
object.map do |partner|
profile = partner.profile_only_fetch_preview
next if prof... |
# comparison.rb
# Chapter 7 Flow Control - starts on page 41
# In the past, we made programs that said different things
# depending on your keyboard input, but after this chapter they will actually
# do different things. But how will we determine when to do one thing instead
# of another? We need...
# 7.1 Comparison ... |
class DomainsController < ApplicationController
hobo_model_controller
auto_actions :all
def show
@domain = find_instance # Hobo needs @domain defined
@paginated_docs = @domain.docs.paginate(:page => params[:page])
end
end
|
class CategoriesController < ApplicationController
def index
@categories = Category.where('name LIKE ?', "%#{params[:q]}%")
respond_to do |format|
format.json
end
end
end
|
module Roglew
module GL
DEPTH_STENCIL_EXT ||= 0x84F9
DEPTH24_STENCIL8_EXT ||= 0x88F0
TEXTURE_STENCIL_SIZE_EXT ||= 0x88F1
UNSIGNED_INT_24_8_EXT ||= 0x84FA
end
end |
require 'position'
class Weapon
attr_accessor :bearing, :aim, :status, :ammo
STEP_TURN = 12
def initialize(options = {})
@bearing = options[:bearing] || 0 # Weapon bearing in 360 degrees.
@aim = options[:aim] || Position.new # Weapon aim in an XY coordinate system.
@statu... |
module SpriteEdit
class SpritePart < Chingu::GameObject
trait :bounding_box, debug: DEBUG
attr_reader :part, :frame, :rx, :ry
def initialize options = {}
raise 'SpritePart created without :part option' unless options.has_key?(:part)
raise 'SpritePart created without :rx or :ry' unless options.has_key?(:rx... |
=begin
Equipment Level Requirements
by Fomar0153
Version 1.0
----------------------
Notes
----------------------
Adds a level requirement to equipment.
----------------------
Instructions
----------------------
Notetag the weapons/armors like so:
<levelreq x>
----------------------
Known bugs
----------------------
Non... |
class ChangeColumnForMessages < ActiveRecord::Migration[5.2]
def change
change_column :messages, :receiver_id, :integer
change_column :messages, :sender_id, :integer
end
end
|
class Chemical < ApplicationRecord
validates :name, :formula, :package, :company, :agent, :storage_place, :remain, presence: true
belongs_to :user
scope :recent_update, -> { includes(:user).order("updated_at DESC") }
end
|
class Api::V1::StudentsController < ApplicationController
def index
@students = Student.all
render json: @students
end
def show
@student = Student.find(params[:id])
render json: @student
end
def create
@student = Student.new(student_params)
if @stude... |
class ImagesIndicesController < ApplicationController
# GET /images_indices
# GET /images_indices.xml
layout "admin"
def index
@images_indices = ImagesIndex.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @images_indices }
end
end
# GET /images_... |
class CharacterOrigin < ApplicationRecord
belongs_to :character, inverse_of: :character_origins
belongs_to :origin, inverse_of: :character_origins, counter_cache: :characters_count
accepts_nested_attributes_for :origin, allow_destroy: true
def display_name
"#{self.character.display_name}'s #{self.origin.d... |
require "spec_helper"
RSpec.describe "Day 9: Sensor Boost" do
let(:runner) { Runner.new("2019/09") }
describe "Part One" do
it "generates the expected outputs" do
expect(runner.execute!("109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99", part: 1))
.to eq([109, 1, 204, -1, 1_001, 100, 1,... |
require_relative '../../repository/users'
require_relative '../../repository/sessions'
require_relative '../../repository/identities'
class SessionDetail
def initialize(session_id)
@session_id = session_id
end
def user
session.empty? ? empty : Users.find(where(id:equals(session.get.head.user_id))).get_... |
class WallPlatesController < ApplicationController
before_action :set_wall_plate, only: [:show, :edit, :update, :destroy]
# GET /wall_plates
# GET /wall_plates.json
def index
@wall_plates = WallPlate.all
end
# GET /wall_plates/1
# GET /wall_plates/1.json
def show
end
# GET /wall_plates/new
... |
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Ordinateur
def self.redis_url
secrets.redis_url.present? ? URI(secrets.redis_url) : nil
end
def self.redis
... |
package "openjdk-6-jdk"
directory "/opt/cloudwatch" do
owner "root"
group "root"
mode "0755"
action :create
end
execute "download cloudwatch tools" do
cwd "/opt/cloudwatch"
user "root"
command "wget http://ec2-downloads.s3.amazonaws.com/CloudWatch-2010-08-01.zip"
action :run
end
package "unzip" do
... |
FactoryGirl.define do
factory :admin do
sequence(:email) { |n| "email#{n}@idrivealot.com" }
password "password123"
end
end
|
require 'test_helper'
class OddEventTest < SexyPgConstraintsTest
def test_odd
ActiveRecord::Migration.constrain :books, :quantity, :odd => true
assert_prohibits Book, :quantity, :odd do |book|
book.quantity = 2
end
assert_allows Book do |book|
book.quantity = 1
end
ActiveRecord... |
class ArrayValidator
ARRAY_NEXT_RULE = {
"value" => ["[", ","],
"," => ["value"],
"]" => ["value","[", ","]
}
SKIP = [" ", "\n", "\t", "\s"]
attr_accessor :i, :j, :char_matrix, :stack
def initialize(i,j,char_matrix)
@i = i
@j = j
@char_matrix = char_matrix
@stack = Stack.new
end
def... |
=begin
#==============================================================================
Title: Event Wrapper
Author: Hime
Date: Feb 14, 2015
------------------------------------------------------------------------------
** Change log
Feb 14, 2015
- added support for deleting custom events by event designation
D... |
class CreateProfiles < ActiveRecord::Migration[5.0]
def change
create_table :profiles do |t|
t.string :cust_number
t.string :firstname
t.string :lastname
t.string :phone_number
t.string :street1
t.string :street2
t.string :city
t.string :state
t.string :zip
... |
module Task
module RelationMethods
extend ActiveSupport::Concern
module ClassMethods
def has_relation(type, params)
supers = params.fetch :supers
subs = params.fetch :subs
opts = {type: type}
relation_opts[supers] = opts.merge relation: :super
relation_opts[subs]... |
class ChangeRatingToRatingInfoInSchools < ActiveRecord::Migration[5.2]
def change
rename_column :schools, :rating, :rating_info
end
end |
require('pry')
class Train
attr_reader(:id, :reg_no, :name)
define_method(:initialize) do |attributes|
@id = attributes.fetch(:id)
@reg_no = attributes.fetch(:reg_no)
@name = attributes.fetch(:name)
end
define_singleton_method(:all) do
result = DB.exec('SELECT * FROM trains;')
trains = []
... |
# encoding: UTF-8
module API
module V1
class SubscribersGroupMembers < API::V1::Base
before do
authenticate_user
end
namespace :subscribers_groups do
route_param :id do
namespace :members do
paginated_endpoint do
desc 'List all members of ... |
feature "Official Diary - Edit" do
context 'Visitor' do
scenario "Access invalid" do
official_diary = create :official_diary
visit edit_official_diary_path official_diary
expect(current_path).to eq new_session_path
end
end
context 'Admin' do
let(... |
class GiveTagTimesDefaultValue < ActiveRecord::Migration
def change
change_column :tags,:tag_times,:integer,default:1
end
end
|
require 'spec_helper'
RSpec.describe "apress/images/api/v1/images/image.json.jbuilder", type: :view do
let(:schema) do
{
type: "object",
required: ::Swagger::V1::Models::Apress::Images::Image.attributes
}.with_indifferent_access
end
let(:styles_schema) do
{
type: 'array',
ite... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.