text stringlengths 10 2.61M |
|---|
require 'json'
require 'rack/app'
class MyApp < Rack::App
headers 'Access-Control-Allow-Origin' => '*',
'Access-Control-Expose-Headers' => 'X-My-Custom-Header, X-Another-Custom-Header'
serializer do |obj|
if obj.is_a?(String)
obj
else
JSON.dump(obj)
end
end
error StandardErr... |
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
has_many :likes, as: :likeable
has_one :device_inf, dependent: :destroy
has_many :notifications, as: :notificable
end
|
Rails.application.routes.draw do
# Routes for the Product_at_store resource:
# CREATE
get '/product_at_stores/new', :controller => 'product_at_stores', :action => 'new', :as => 'new_product_at_store'
post '/product_at_stores', :controller => 'product_at_stores', :action => 'create', :as => 'prod... |
#clase padre
#Parent
class Appointment
attr_accessor :location, :purpose, :hour, :min
def initialize(location, purpose, hour, min)
@location = location
@purpose = purpose
@hour = hour
@min = min
end
end
#clases hijo
#child
class MonthlyAppointment < Appointment
attr_acc... |
class CreatePatients < ActiveRecord::Migration
def change
create_table :patients do |t|
t.string :species
t.string :race
t.string :gender
t.string :bloodtype
t.string :sterilized
t.string :size
t.string :activity
t.float :weight
t.date :birthday
t.refere... |
class RoomController < ApplicationController
before_action :authenticate_user!
respond_to :json
protect_from_forgery unless: -> { request.format.json? }
def index
respond_to do |format|
format.json { render json: Room.where(hotel_id: params[:hotel_id]) }
format.html
end
end
def create
... |
# This class is for managing user model
# class user
require 'digest'
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable
# and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :remember... |
require 'rubygems'
require 'active_support/inflector'
require 'need'
require 'yaml'
need{'sweet_generator'}
module TestSweet
class ConfigGenerator < SweetGenerator
def initialize(*args)
@site,@name = args
unless @site && @name
raise ArgumentError, 'please provide a site and config name... |
require 'spec_helper'
describe LitmusGem do
it 'has a version number' do
expect(LitmusGem::VERSION).not_to be nil
end
end
|
require "spec_helper"
require "patient"
describe Patient do
it "is not valid without a full name" do
p = Patient.new
p.should_not be_valid
p.should have(1).errors # TEMP: used to deprecate first/last validations
p.should have(1).error_on(:name_full)
end
end |
# frozen_string_literal: true
# Advent of Code 2020
#
# Robert Haines
#
# Public Domain
require 'test_helper'
require 'aoc2020/passport_processing'
class AOC2020::PassportProcessingTest < MiniTest::Test
PASSPORTS = <<~EOPASS
ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
byr:1937 iyr:2017 cid:147 hgt:183cm
... |
class UsersController < ApplicationController
before_action :authenticate_user!, except: [:new, :create]
def new
@user = User.new
end
def create
@user = User.new user_params
if @user.save
sign_in(@user)
redirect_to index_path, notice: "User successfully created"
else
rende... |
#!/usr/bin/env ruby
Autotest.add_hook :initialize do |autotest|
%w{.git .DS_Store Gemfile bin doc html}.each do |exception|
autotest.add_exception(exception)
end
autotest.clear_mappings
autotest.add_mapping(/^test.*\/.*_test\.rb$/) { |filename, _| filename }
autotest.add_mapping(/test_helper.rb/) { |f, _|... |
class Dude
DIRECTIONS = %w[N E S W].freeze
attr_reader :visited
def initialize
@visited = []
@facing = "N"
@x = 0
@y = 0
end
def turn(direction)
pos = DIRECTIONS.index(@facing)
pos += ((direction == "L") ? -1 : 1)
@facing = DIRECTIONS[pos % DIRECTIONS.length]
end
def move(b... |
require_relative '../../automated_init'
context "Output" do
context "Error Summary" do
context "Exit File" do
path = "some_test.rb"
result = Controls::Result.example
context "Per-File Error Counter is Non-Zero" do
file_error_counter = 11
output = Output.new
assert(out... |
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or pr... |
class ChangeSeatTypetoQuizzes < ActiveRecord::Migration[5.0]
def change
remove_column :quizzes, :seat_number
add_column :quizzes, :seat_number, :integer
end
end
|
module JobPacks
class JobPackItem < ::ActiveRecord::Base
belongs_to :job_pack
belongs_to :job, polymorphic: true
WAITING = 0
RUNNING = 1
ERROR = 2
DONE = 3
attr_accessor :old_status
scope :done, -> {
where(status: DONE)
}
scope :running, -> {
where(status: RUNNI... |
describe 'Storefront routing' do
before do
@storefront = mock_storefront!(:foo)
end
describe 'based on storefront parameter' do
before do
Backstage::Core::Engine.register_routes(:foo) do
resources :products
end
class Foo::ProductsController < ApplicationController
def... |
module Rool
class Send < Basic
attr_accessor :method_name, :rule_type
def process(dataset, method_name, rule_type)
super
@key = dataset[@data_key].clone
@new_key = @key.public_send(method_name) if @key.respond_to? method_name
@new_data = { @data_key => @new_key }
rule_type.ne... |
# == Schema Information
#
# Table name: organization_locations
#
# id :integer not null, primary key
# organization_id :integer
# location_id :integer
# location_type :string(255)
# created_at :datetime
# updated_at :datetime
#
class OrganizationLocation < ActiveRecord::Base... |
# Etat d'une case
# @attr_reader etat [String] etat entre BLANC, NOIR ou POINT
# @attr BLANC [String] chaine correspondant à l'état blanc
# @attr NOIR [String] chaine correspondant à l'état noir
# @attr POINT [String] chaine correspondant à l'état point
class Etat
attr_reader :etat
BLANC ||= 'b'
NOIR ||= 'n... |
require 'spec_helper'
describe Twitch::Chat::Client do
let(:client) { Twitch::Chat::Client.new(password: 'password', nickname: 'enotpoloskun') }
describe '#on' do
context 'There is one message callback' do
before { client.on(:message) { 'callback1' } }
it { client.callbacks[:message].count.should... |
require 'rails_helper'
describe "Themes to items relationship" do
before(:all) do
@avrail = FactoryGirl.create(:item, :title => 'Les Aventuriers du rail')
@wonders = FactoryGirl.create(:item, :title => '7 Wonders')
@dow = FactoryGirl.create(:theme, :name => 'Building')
end
it "should recognise when... |
class Store < ActiveRecord::Base
attr_accessible :name, :user_id, :visits
belongs_to :user
has_many :links
end
|
class AddGradeRefToBoulders < ActiveRecord::Migration
def change
add_reference :boulders, :grade, index: true
end
end
|
n = gets.strip.to_i
a = Array.new(n)
min_heap = []
max_heap = []
def balanced?(array1, array2)
(array1.length - array2.length).abs <= 1
end
def get_parent(index)
return nil if index == 0
(index - 1) / 2
end
def get_child(index, heap, &prc)
left = index * 2 + 1
return nil if left >= heap.length
right = in... |
require 'spec_helper'
RSpec.describe Ultron::Event::Receiver do
let(:serial) { double(RubySerial::Posix::Termios) }
let(:mqtt) { MQTT::Client.new(host: 'localhost', port: 1883) }
let(:instance) { described_class.new(serial, mqtt) }
describe '#parse_and_publish' do
let(:message) { '{"topic":"receiver/tempe... |
module Sinatra
module ContentFor2
VERSION = '0.3'.freeze
end
end
|
require "fluent_plugin_kinesis_firehose/version"
class Fluent::KinesisFirehoseOutput < Fluent::BufferedOutput
Fluent::Plugin.register_output('kinesis_firehose', self)
include Fluent::SetTimeKeyMixin
include Fluent::SetTagKeyMixin
USER_AGENT_SUFFIX = "fluent-plugin-kinesis-firehose/#{FluentPluginKinesisFireho... |
include ActionDispatch::TestProcess
FactoryGirl.define do
factory :job do
title { Faker::Name.title }
employed_from { Faker::Business.credit_card_expiry_date }
employed_to { Faker::Business.credit_card_expiry_date }
# associations
user
restaurant
trait :with_reviews do
ignore do
... |
require_relative('../db/sql_runner.rb')
class Movie
attr_reader :id
attr_accessor :title, :genre
def initialize(options)
@title = options["title"]
@genre = options["genre"]
@id = options["id"].to_i if options["id"]
@budget = options["budget"].to_i
end
def save()
sql = "INSERT INTO movie... |
# Die Class 1: Numeric
# I worked on this challenge by myself
# I spent [] hours on this challenge.
# 0. Pseudocode
# make a new class called die
# sets number of sides based on user input
# if user input is less than one, error
# rolling the die returns random number between 1 and 6 (or whatever)
# Input: 6
# Outp... |
module Goodreads
module Shelves
# Get books from a user's shelf
def shelf(user_id, shelf_name, options={})
options = options.merge(:shelf => shelf_name, :v =>2)
data = request("/review/list/#{user_id}.xml", options)
reviews = data['reviews']['review']
books = []
unless reviews.... |
#==============================================================================
# [VXACE] Advance Text Reader EX by Estriole
#-------------------------------------------------------------------------
# EST - Advance Text Reader
# Version: 1.2
# Released on: 26/07/2012
# Author : Estriole (yin_estriole@yahoo.com)
# also... |
# encoding : utf-8
require "minitest/unit"
require_relative "../ondl"
MiniTest::Unit.autorun
class TestOndl < MiniTest::Unit::TestCase
def setup
@ondl=Ondl.new
end
#def test_translate
# assert_equal "オンドゥルルラギッタンディスカ",@ondl.translate("本当に裏切ったんですか")
#end
def test_word
assert_equal "ジャ",@ondl.t... |
# frozen_string_literal: true
module EasyMonitor
module Util
module Connectors
class ActiverecordConnector
attr_accessor :base
def initialize(base = ActiveRecord::Base)
self.base = base
end
def database_alive?
raise StandardError unless EasyMonitor::Eng... |
require 'test_helper'
class PasswordBlurTest < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers
setup do
Settings.pw.enable_blur = true
end
teardown do
Settings.pw.enable_blur = true
end
def test_blur_enabled
post passwords_path, params: { password: { payload: 'testpw... |
# frozen_string_literal: true
require 'base64'
module V0
class SessionsController < ApplicationController
include Accountable
skip_before_action :authenticate, only: %i[new logout saml_callback saml_logout_callback]
REDIRECT_URLS = %w[mhv dslogon idme mfa verify slo].freeze
STATSD_SSO_CALLBACK_KE... |
# Problem 155: Counting Capacitor Circuits.
# http://projecteuler.net/problem=155
# An electric circuit uses exclusively identical capacitors of the same value C.
#
# The capacitors can be connected in series or in parallel to form sub-units, which can then be connected in series or in parallel with other capacitors ... |
ActiveAdmin.register Product do
# See permitted parameters documentation:
# https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
#
# permit_params :list, :of, :attributes, :on, :model
#
# or
#
# permit_params do
# permitted = [:permitted, :attributes]
# ... |
class Gutenberg < Formula
desc "A template and scaffolding utility."
homepage "https://github.com/sourcefoundryus/gutenberg"
url "https://github.com/sourcefoundryus/gutenberg/releases/download/1.0.0/gutenberg-1.0.0.zip"
sha256 "db6941effc6e83bea2be18283fa7758fdbcfdd36348747c6e628f344bc98668e"
vers... |
# == Schema Information
#
# Table name: invoice_lines
#
# id :integer not null, primary key
# quantity :integer
# unit_price :float
# created_at :datetime
# updated_at :datetime
# invoice_id :integer
# track_id :integer
#
class InvoiceLine < ApplicationRecord
belongs_to :invoice,
... |
require 'spec_helper.rb'
require 'helper.rb'
require 'service/lookup_service'
require 'service/authorized_service'
require 'service/returned_service'
RSpec.configure do |c|
c.include Helper
end
describe "Returned Service" do
before(:all) do
variable_init
end
it "should allow an item to be returned" do
... |
require 'rspec/core/rake_task'
require 'rake'
# RSpec::Core::RakeTask.new('spec')
# task :default => :spec
namespace :pulumi do
desc "setup pulumi"
task :setup do
sh 'virtualenv -p python3 venv'
sh 'source venv/bin/activate'
sh 'pip3 install -r requirements.txt'
end
end
namesp... |
require "byebug"
class Player
attr_reader :name
attr_accessor :hand, :points
def initialize(name, deck)
@name = name
@hand = Hand.deal_from(deck)
@points = 0
end
def play_hand(board)
until won? || hand.next_move?(board) == false
self.hand.play(board)
board.render
end
if... |
class AddingUserRefToMemberships < ActiveRecord::Migration
def change
add_column :memberships, :user_id, :integer
add_index :memberships, :user_id
add_column :memberships, :project_id, :integer
add_index :memberships, :project_id
end
end
|
When(/^node "(.*?)" finds enough blocks for her park rate vote to become the median park rate$/) do |arg1|
step "node \"#{arg1}\" finds 3 blocks received by all nodes"
end
When(/^node "(.*?)" finds enough blocks for the voted park rate to become effective$/) do |arg1|
node = @nodes[arg1]
protocol = node.info["pr... |
module PUBG
class Telemetry
class LogPlayerAttack
require "pubg/telemetry/shared/attacker"
require "pubg/telemetry/shared/weapon"
require "pubg/telemetry/shared/vehicle"
attr_reader :data, :attackid, :attacker, :attacktype, :weapon, :vehicle, :_V, :_D, :_T
def initialize(args)
... |
class Location < ActiveRecord::Base
validates :lat, :lng, presence: true
validates :address1, :presence => { :message => "STREET ADDRESS is required" }
validates :city, :presence => { :message => "CITY is required" }
validates :state, :presence => { :message => "STATE is required" }
validates :country, :pre... |
require 'omniauth-oauth2'
module OmniAuth
module Strategies
class PeentarID < OmniAuth::Strategies::OAuth2
option :name, 'peentar_id'
option :client_options, {
site: ::PeentarID.auth_site,
authorize_url: ::PeentarID.auth_url,
token_url: ::PeentarID.token_url,
... |
require File.join(File.dirname(__FILE__), "test_helper")
require 'ctime_classifier'
class TestCTimeClassifier < Test::Unit::TestCase
def setup
@target_dir = 'test_target'
end
context "when the target directory is found" do
setup do
FileUtils.mkdir_p @target_dir
end
should "be able to ins... |
require 'rails_helper'
require 'web_helpers'
feature 'jobs' do
context 'no jobs have been added' do
scenario 'should display a prompt to add a job' do
visit '/jobs'
expect(page).to have_content 'No jobs yet'
expect(page).to have_link 'Add a job'
end
end
context 'creating jobs' do
sc... |
class Status < ActiveHash::Base
self.data = [
{ id: 1, name: '-----' },
{ id: 2, name: 'その他補正なし' },
{ id: 3, name: '×2.0 (おいかぜ)' },
{ id: 4, name: '×0.5 (まひ状態)' }
]
include ActiveHash::Associations
has_many :calculations
end |
require 'rails_helper'
RSpec.describe Fact, type: :model do
let!(:fact) { create(:fact) }
describe "#set_defaults" do
context "when creating a new fact" do
it "returns the expected default fact score value of 0" do
expect(fact.score).to eq 0
end
end
end
describe "#supporting_evi... |
#! /usr/bin/ruby
$LOAD_PATH << File.dirname(__FILE__)
module AnalyzeSchedule
def self.team_name(schedule, tnum)
if schedule.has_key?(:team_names)
return schedule[:team_names][tnum - 1]
end
return tnum.to_s
end
def self.analyze_schedule(schedule, html)
all_game... |
class Song
attr_accessor :name,:artist,:genre
@@all=[]
def initialize(name,artist,genre)
@name = name
@artist=artist
@genre=genre
@@all << self
end
def self.all
@@all
end
end
|
require 'rails_helper'
RSpec.describe Product, type: :model do
context 'fields' do
it { is_expected.to have_field(:title).of_type(String) }
it { is_expected.to have_field(:description).of_type(String) }
it { is_expected.to have_field(:image_url).of_type(String) }
it { is_expected.to have_field(:date... |
# Preview all emails at http://localhost:3000/rails/mailers/marketing_mailer
class MarketingMailerPreview < ActionMailer::Preview
# Preview this email at http://localhost:3000/rails/mailers/marketing_mailer/promotion
def promotion
MarketingMailer.with(
user: User.first,
message: "Lorem ipsum dolor ... |
require 'spec_helper'
describe "StaticPages" do
describe "Home page" do
it "should have the h1 'Sample App'" do
visit '/static_pages/home'
page.should have_selector('h1', :text => 'Test App')
end
it "should have the title 'Test App'" do
visit '/static_pages/home'
page.should ... |
# == Schema Information
#
# Table name: avatars
#
# id :integer not null, primary key
# user_id :integer
# image_file_name :string(255)
# image_content_type :string(255)
# image_file_size :integer
# image_updated_at :datetime
# title :string(255)
# create... |
# == Schema Information
#
# Table name: bills
#
# id :integer not null, primary key
# name :string(255)
# total :float
# finished :boolean
# created_at :datetime
# updated_at :datetime
# user_id :text
#
class Bill < ActiveRecord::Base
has_and_belongs_to_many :user
ha... |
class CellGenerator
attr_reader :width, :height, :living_cell_locations, :number_random_living_cells
def initialize(args = {})
@width = args[:width]
@height = args[:height]
@number_random_living_cells = args.fetch(:number_random_living_cells, default_random_living_cells)
@living_cell_locations = a... |
require_relative 'test_helper'
class RequestValidatorTest < Minitest::Test
def setup
@app = lambda { |env| [200, {}, []] }
@validator = Superintendent::Request::Validator.new(
@app,
monitored_content_types: ['application/json', 'application/vnd.api+json'],
forms_path: File.expand_path('../f... |
require 'test_helper'
class ArticleTest < ActiveSupport::TestCase
test "should create article" do
article = Article.new
article.user = users(:eugene)
article.title = "Test article"
article.body = "Test body"
assert article.save
end
test "should find article" do
article_id = articles(:we... |
class AddTsToDiscussion < ActiveRecord::Migration
def self.up
add_column :discussions, :ts, :string
end
def self.down
remove_column :discussions, :ts
end
end
|
class UserSerializer < ActiveModel::Serializer
attributes :username, :email, :id
has_many :comments
end
|
module SuccessionDatesValidation
def self.included(base)
base.extend(ClassMethods)
end
def update_from_json(json, extra_values = {}, apply_nested_records = true)
obj = super
obj.validate_succession_date!
obj
end
def validate_succession_date!
my_relationships('series_system_agent_relatio... |
class RemoveReportsTable < ActiveRecord::Migration
def change
drop_table :reports if ActiveRecord::Base.connection.table_exists? 'reports'
end
end |
class DataParent < ApplicationRecord
has_many :children, -> { order 'id ASC' }, class_name: 'DataChild', foreign_key: 'data_parent_id'
accepts_nested_attributes_for :children
end
|
class Contest::TaskSerializer < ActiveModel::Serializer
root false
cached
attributes :id, :title, :body, :quest, :kind
attributes :skip, :timespan
has_many :choices, serializer: Contest::ChoiceSerializer
def kind
"single"
end
def skip
0
end
def timespan
0
end
end
|
class Image < ApplicationRecord
belongs_to :user
mount_uploader :picture, PictureUploader
validate :picture_size
private
def picture_size
if picture.size > 5.megabytes
errors.add(:picture, "should be less than 5MB")
end
end
end
|
FactoryGirl.define do
factory :library_category do
name {Faker::Name.name}
end
end
|
class Certificate < ActiveRecord::Base
include AASM
extend FriendlyId
friendly_id :code
CODE_LENGTH = 8
belongs_to :merchant
belongs_to :customer
belongs_to :charity
belongs_to :deal
before_validation :create_code, :on => :create
validates :merchant_id, :charity_id, :presence => true
validates... |
# frozen_string_literal: true
require 'rails_helper'
describe UserMailer do
describe '#basic' do
subject(:mailer) do
described_class.basic(user.username, user.email, user.instance_variable_get('@generated_password'))
end
let(:user) { create(:user) }
its(:body) do
is_expected.to eq("Use... |
require 'test_helper'
class Sims::SimsResearchesControllerTest < ActionDispatch::IntegrationTest
setup do
@postgresql_view_person = postgresql_view_people(:one)
end
test "should get index" do
get postgresql_view_people_url
assert_response :success
end
test "should get new" do
get new_postgr... |
class Location < ActiveRecord::Base
validates_uniqueness_of :name, :normalized_name
validates_presence_of :name, :normalized_name
before_validation :set_normalized_name, on: :create
has_many :script_lines
def self.find_or_create_by_name(name)
normalized_name = TextNormalizer.remove_apostrophes_and_norm... |
class MembersController < ApplicationController
def new
@company = Company.find(params[:company_id])
@member= Member.new
end
def create
@company = Company.find(params[:company_id])
@member= Member.new(member_params)
if @member.save
redirect_to company_path(@company.id)
else
re... |
class Tag < ApplicationModel
has_many :post_tags, :dependent => :destroy
has_many :user_tags, :dependent => :destroy
has_many :store_tags, :dependent => :destroy
validates_presence_of :tag
validates_uniqueness_of :tag
def self.generate(arg = {:tags => nil, :user_id => nil, :post_id => nil})
tags =... |
class Iteration < ActiveRecord::Base
belongs_to :engagement
validates_presence_of :engagement_id
validates_associated :engagement
validates_presence_of :end_date
default_scope { order('end_date ASC') }
def customer_feedback_to_hash
JSON.parse customer_feedback rescue Hash.new
end
def customer_ra... |
class Tag
PROPERTIES = [:timestamp, :id, :name]
attr_accessor *PROPERTIES
def initialize(hash = {})
hash.each do |key, value|
if PROPERTIES.member? key.to_sym
self.send("#{key}=", value)
end
end
end
end
|
# include_recipe 'build-essential::default'
python_runtime '2'
python_virtualenv "#{node[:project_dir]}venv"
python_package 'uwsgi'
python_package 'pypiserver'
python_package 'passlib'
template "/etc/init.d/pypid" do
source 'pypid.erb'
variables(
:app_dir => node[:project_dir]
)
end
file "/etc/in... |
class Booking < ApplicationRecord
belongs_to :client, class_name: 'User', foreign_key: 'user_id'
belongs_to :bathroom
has_one :owner, through: :bathroom
validates :date, presence: true
validates :duration, presence: true, inclusion: { in: [15, 20, 25, 30, 35, 40, 45] }
validates :bathroom, presence: true
... |
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'application#home'
namespace :api do
resources :jobs, only: [:index] do
resources :tasks, only: [:update]
end
end
end
|
require 'check_item_status'
require 'add_categories'
class MembersController < ApplicationController
include ::CheckItemStatus
include ::AddCategories
before_filter :authenticate, :only => [:edit, :update, :show, :destroy, :index]
before_filter :correct_user, :only => [:edit, :update, :show]
def index
... |
namespace :fedena_inventory do
desc "Install Fedena Inventory Module"
task :install do
system "rsync --exclude=.svn -ruv vendor/plugins/fedena_inventory/public ."
end
end
|
require 'minitest/autorun'
require "#{Dir.pwd}/app/app"
class TestSinatraHelpers < MiniTest::Unit::TestCase
include Sinatra::Helpers
def test_shorter_track_should_cut
longy = open("#{Dir.pwd}/tmp/input.mp3")
shorty = shorter_track longy
assert_equal "#{Dir.pwd}/tmp/output.mp3", shorty.path
shorty... |
require 'rails_helper'
RSpec.describe 'Visits API', type: :request do
let!(:visits) { create_list(:visit, 10) }
let(:visit) { visits.first }
let(:visit_id) { visit.id }
describe 'GET /visits' do
before { get '/visits' }
it 'returns active visits' do
expect(json).not_to be_empty
expect(jso... |
class Pub
attr_reader :name, :till
def initialize(name, drinks = {})
@name = name
@till = 0
@drinks = drinks
end
def sell_drink(drink, customer)
if customer.age >= 18 && customer.drunk_level <= 5
@till += drink.price
elsif customer.age < 18... |
# frozen_string_literal: true
# @param {String} j
# @param {String} s
# @return {Integer}
def num_jewels_in_stones(j, s)
count = 0
j.split('').each do |jewel|
s.split('').each do |stone|
jewel == stone ? count += 1 : count
end
end
count
end
|
class AddResultToApnMessage < ActiveRecord::Migration
def self.up
add_column :apn_messages, :result, :string
end
def self.down
end
end
|
module Fog
module Parsers
module Vcloud
module Terremark
module Vcloud
class GetVdc < Fog::Parsers::Vcloud::Base
def reset
@target = nil
@response = Struct::TmrkVcloudVdc.new([],[],[])
end
def start_element(name, attributes... |
class Credit < ActiveRecord::Base
validates :amount_cents, :member, :presence => true
belongs_to :member, :inverse_of => :credits
belongs_to :transaction
scope :active, where(:active => true)
def as_json(options={})
[self.member.id, self.amount_cents]
end
end
|
class PhotoPostsController < ApplicationController
def index
end
def create
c = Tumblr::Client.new
post = PhotoPost.new(photo_post_params)
c.photo('doomy.tumblr.com', {data: post.data, caption: post.caption})
redirect_to root_path
end
private
def photo_post_params
params.require(:photo_pos... |
require "rails_helper"
describe "Session test" do
before(:each) do
visit root_path
@user = create(:user)
@user = User.load_from_activation_token(@user.activation_token)
@user.activate!
end
it "opens login page" do
click_link "Войти"
expect(page).to have_content "Вход"
end
it "activa... |
class Space
attr_reader :description, :exits, :related_rooms, :items, :actions, :necessary_item
def initialize(description, exits, items, actions, necessary_item)
@description = description
@exits = exits
@related_rooms = {}
@items = items
@actions = actions
... |
module ShoesHelper
def paid_for_checkbox(f, shoe)
if payment_options_disabled?(shoe)
f.check_box :paid_for, disabled: "disabled"
else
f.check_box :paid_for
end
end
def payment_options_button(f, shoe, payment_type)
if payment_options_disabled?(shoe)
f.radio_button :type_of_paymen... |
{
:schema => {
"$schema" => "http://www.archivesspace.org/archivesspace.json",
"version" => 1,
"type" => "object",
"parent" => "abstract_archival_object",
"uri" => "/repositories/:repo_id/resources",
"properties" => {
"id_0" => {"type" => "string", "ifmissing" => "error", "maxLength" =>... |
require 'spec_helper'
describe Task do
let(:user) { FactoryGirl.create(:user) }
before do
@list = user.lists.build( name: "test" )
@task = @list.tasks.build( name: "test_task" )
end
subject { @task }
it { should be_valid }
its(:finished) { should be_false }
end
|
class Board
attr_accessor :cells
def initialize
reset!
end
def reset!
@cells = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
end
def display
puts " #{@cells[0]} | #{@cells[1]} | #{@cells[2]} "
puts "-----------"
puts " #{@cells[3]} | #{@cells[4]} | #{@cells[5]} "
puts "-----------"
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.