text stringlengths 10 2.61M |
|---|
class DNA
attr_accessor :strand
def initialize(strand)
@strand = strand
end
def hamming_distance(distance)
return 0 if @strand == '' || distance == ''
sizes = [strand, distance].map {|wrd| wrd.size}
small_idx, big_idx = sizes.find_index(sizes.min), sizes.find_index(sizes.max)
if distance.size == strand.size
shorter_str, longer_str = strand, distance
else
shorter_str, longer_str = [strand, distance][small_idx], [strand, distance][big_idx]
end
differences = []
shorter_str.each_char.with_index do |char, index|
differences << char if char != longer_str[index]
end
differences.size
end
end
|
require 'test_helper'
class SubscriptionTest < ActiveSupport::TestCase
def setup
@cposting = cpostings(:one) #has one spot
@customer = users(:customer)
@customer2 = users(:customer2)
@subscription = Subscription.new(post_id: @cposting.id, subscriber_id: @customer.id)
end
test "should be valid" do
assert @subscription.valid?
end
test "should require a post_id" do
@subscription.post_id = nil
assert_not @subscription.valid?
end
test "should require subscriber_id" do
@subscription.subscriber_id = nil
assert_not @subscription.valid?
end
test "post_id and subscriber_id pair should be unique" do
assert @subscription.valid?
@subscription.save
@subscription2 = Subscription.new(post_id: @subscription.post_id, subscriber_id: @subscription.subscriber_id)
assert_not @subscription2.valid?
end
test "subscriptions cannot exceed spots" do
@subscription.save
assert @cposting.subscriptions.count == @cposting.spots
@cposting.build_subscription(subscriber: @customer2)
assert_not @subscription2.valid?
end
end
|
class EntriesController < ApplicationController
before_filter :authorize, only: [:edit, :update, :destroy]
def new
@user = User.find(params[:user_id])
@entry = Entry.new
end
def create
@user = User.find(params[:user_id])
@entry = Entry.new(entry_params)
if @entry.save
session[:entry_id] = @entry.id
flash[:notice] = "#{@entry.title} has been created!"
redirect_to user_path(@user)
else
render 'new'
end
end
def show
@entry = Entry.find(params[:id])
@user = User.find(params[:user_id])
@comment = Comment.new
end
def edit
@entry = Entry.find(params[:id])
@user = User.find(params[:user_id])
end
def update
@entry = Entry.find(params[:id])
@user = User.find(params[:user_id])
@entry.update(entry_params)
if @user.valid?
flash[:notice] = "#{@entry.title} has been updated"
redirect_to user_entry_path(@user, @entry)
else
render 'edit'
end
end
def destroy
@entry = Entry.find(params[:id])
@user = User.find(params[:user_id])
@entry.destroy
flash[:notice] = "#{@entry.title} has been deleted"
redirect_to user_path(@user)
end
private
def entry_params
params.require(:entry).permit(:title, :content, :entry_id).merge(:user_id => current_user.id)
end
end
|
class Clock < ApplicationRecord
has_secure_token
has_secure_token :slug
attribute :public, :boolean, default: true
attribute :human_time, :string, default: '24 hours from now'
before_save :parse_human_time
after_initialize :set_human_time
def duration
begin
raise CountdownEndedError if (DateTime.now > countdown_to)
DurTool::Duration.new((countdown_to - DateTime.now).to_i)
rescue CountdownEndedError
DurTool::Duration.new(0)
end
end
def self.find(param)
find_by_slug(param)
end
def to_param
slug
end
def user
if user_id
User.find(user_id)
else
nil
end
end
private
def parse_human_time
Chronic.time_class = Time.zone
self.countdown_to = Chronic.
parse(human_time).
to_datetime.
in_time_zone(time_zone)
end
def set_human_time
if persisted?
self.human_time = countdown_to.to_s
end
end
class CountdownEndedError < StandardError; end
end
|
class PopraviKrvneGrupe < ActiveRecord::Migration
def change
add_column :blood_groups, :group, :text
end
end
|
require_relative '../spec_helper'
describe Tournament do
let :positions do
[ Position.new(1,'Joao', 0, 30),
Position.new(2,'Jose', 1, 0),
Position.new(3,'Pedro', 0, 0) ]
end
subject { Tournament.new(positions) }
it 'assigns 1 point of strength to the first one on a game of three players ' do
expect(subject.strength('Joao')).to eq(1)
end
it 'assigns -1 point of strength to the last one on a game of three players ' do
expect(subject.strength('Pedro')).to eq(-1)
end
it 'determinates which player is the winner' do
expect(subject.winner.rank).to eq(1)
end
end |
def find_number(num, high)
raise ArgumentError.new("First argument must be less than second argument") if high < num
raise ArgumentError.new("First argument must be between 0 and #{high}") if num < 0 || num > high
low = 0
calc = ->(x,y) { (x + y) / 2 }
mid = calc.call(low, high)
while low <= high
if mid == num
return mid
elsif num < mid
high = mid -1
mid = calc.call(low, high)
elsif num > mid
low = mid + 1
mid = calc.call(low, high)
end
end
end
|
require 'rails_helper'
RSpec.describe "using the contact form" do
it "accepts valid input" do
visit '/'
fill_in 'Name', :with => 'Napa Artist'
fill_in 'Email', :with => 'iloveart@gmail.com'
fill_in 'Subject', with: 'Interest in joining'
fill_in 'Message', with: 'I would like to join Napa Valley Arts Council'
click_button 'Send Note'
expect(page).to have_content('Thanks!')
end
end
|
class AddColumnsToCustomerSets < ActiveRecord::Migration
def change
add_column :customer_sets, :field, :string
add_column :customer_sets, :comparison, :string
add_column :customer_sets, :value, :int
end
end
|
class HouseSerializer < ActiveModel::Serializer
attributes :id, :name, :address
has_many :users, serializer: HouseUsersSerializer
end
|
namespace 'test:db' do
def target_database_servers
TestSupport::TargetDatabaseServers.instance
end
desc 'Create test databases'
task 'create' do
target_database_servers.create_databases
end
desc 'Drop test databases'
task 'drop' do
target_database_servers.drop_databases
end
end
|
class AddCategoryCareToUser < ActiveRecord::Migration[5.2]
def change
add_column :users, :category_care, :string
end
end
|
require "google/apis/calendar_v3"
require "googleauth"
require "googleauth/stores/file_token_store"
require "date"
require "fileutils"
module GoogleCalendar
extend ActiveSupport::Concern
OOB_URI = "urn:ietf:wg:oauth:2.0:oob".freeze
APPLICATION_NAME = "rainify".freeze
CREDENTIALS_PATH = "config/credentials.json".freeze
TOKEN_PATH = "token.yaml".freeze
SCOPE = Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY
def authorize
client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH
token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH
authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store
user_id = "default"
credentials = authorizer.get_credentials user_id
if credentials.nil?
url = authorizer.get_authorization_url base_url: OOB_URI
puts "Open the following URL in the browser and enter the " \
"resulting code after authorization:\n" + url
code = gets
credentials = authorizer.get_and_store_credentials_from_code(
user_id: user_id, code: code, base_url: OOB_URI
)
end
credentials
end
def activate_service
service = Google::Apis::CalendarV3::CalendarService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize
service
end
end
|
require 'spec_helper'
describe User do
describe 'validations' do
context 'when all attributes are valid' do
it 'is valid' do
expect(FactoryGirl.build(:user)).to be_valid
end
end
context 'when username is missing' do
it 'is not valid' do
user = FactoryGirl.build(:user, username: nil)
expect(user).to have(1).errors_on(:username)
end
end
context 'when avatar is missing' do
it 'is not valid' do
user = FactoryGirl.build(:user, avatar: nil)
expect(user).to have(1).errors_on(:avatar)
end
end
end
end
|
# frozen_string_literal: true
RSpec.describe Dry::Logic::Operations::Key do
subject(:operation) { described_class.new(predicate, name: :user) }
include_context "predicates"
let(:predicate) do
Dry::Logic::Rule::Predicate.build(key?).curry(:age)
end
describe "#call" do
context "with a plain predicate" do
it "returns a success for valid input" do
expect(operation.(user: {age: 18})).to be_success
end
it "returns a failure for invalid input" do
result = operation.(user: {})
expect(result).to be_failure
expect(result.to_ast).to eql(
[:failure, [:user, [:key, [:user,
[:predicate, [:key?, [[:name, :age], [:input, {}]]]]]]]]
)
end
end
context "with a set rule as predicate" do
subject(:operation) do
described_class.new(predicate, name: :address)
end
let(:predicate) do
Dry::Logic::Operations::Set.new(
Dry::Logic::Rule::Predicate.build(key?).curry(:city),
Dry::Logic::Rule::Predicate.build(key?).curry(:zipcode)
)
end
it "applies set rule to the value that passes" do
result = operation.(address: {city: "NYC", zipcode: "123"})
expect(result).to be_success
end
it "applies set rule to the value that fails" do
result = operation.(address: {city: "NYC"})
expect(result).to be_failure
expect(result.to_ast).to eql(
[:failure, [:address, [:key, [:address, [:set, [
[:predicate, [:key?, [[:name, :zipcode], [:input, {city: "NYC"}]]]]
]]]]]]
)
end
end
context "with an each rule as predicate" do
subject(:operation) do
described_class.new(predicate, name: :nums)
end
let(:predicate) do
Dry::Logic::Operations::Each.new(Dry::Logic::Rule::Predicate.build(str?))
end
it "applies each rule to the value that passses" do
result = operation.(nums: %w[1 2 3])
expect(result).to be_success
end
it "applies each rule to the value that fails" do
failure = operation.(nums: [1, "3", 3])
expect(failure).to be_failure
expect(failure.to_ast).to eql(
[:failure, [:nums, [:key, [:nums, [:set, [
[:key, [0, [:predicate, [:str?, [[:input, 1]]]]]],
[:key, [2, [:predicate, [:str?, [[:input, 3]]]]]]
]]]]]]
)
end
end
end
describe "#to_ast" do
it "returns ast" do
expect(operation.to_ast).to eql(
[:key, [:user, [:predicate, [:key?, [[:name, :age], [:input, undefined]]]]]]
)
end
end
describe "#ast" do
it "returns ast without the input" do
expect(operation.ast).to eql(
[:key, [:user, [:predicate, [:key?, [[:name, :age], [:input, undefined]]]]]]
)
end
it "returns ast with the input" do
expect(operation.ast(user: "jane")).to eql(
[:key, [:user, [:predicate, [:key?, [[:name, :age], [:input, "jane"]]]]]]
)
end
end
describe "#and" do
subject(:operation) do
described_class.new(Dry::Logic::Rule::Predicate.build(str?), name: [:user, :name])
end
let(:other) do
described_class.new(Dry::Logic::Rule::Predicate.build(filled?), name: [:user, :name])
end
it "returns and rule where value is passed to the right" do
present_and_string = operation.and(other)
expect(present_and_string.(user: {name: "Jane"})).to be_success
expect(present_and_string.(user: {})).to be_failure
expect(present_and_string.(user: {name: 1})).to be_failure
end
end
describe "#to_s" do
it "returns string representation" do
expect(operation.to_s).to eql("key[user](key?(:age))")
end
end
end
|
# Capistrano Deploy Recipe for Git and Phusion Passenger
#
# After issuing cap deploy:setup. Place server specific config files in
# /home/#{user}/site/[staging|production]/shared
# Set :config_files variable to specify config files that should be
# copied to config/ directory (i.e. database.yml)
#
# To deploy to staging server:
# => cap deploy
# => Deploys application to /home/#{user}/site/staging from master branch
#
# To deploy to production server:
# => cap deploy DEPLOY=PRODUCTION
# => Deploys application to /home/#{user}/site/production from production branch
### CONFIG: Change ALL of following
set :application, "studentsknow"
set :staging_server, "-- YOUR STAGING SERVER URL --"
set :production_server, "-- YOUR PRODUCTION SERVER URL --"
set :user, "studentsknow"
set :repository, "git@github.com:codeninja/StudentsKnow.git"
set :config_files, %w( database.yml )
###################################
# System Options
set :use_sudo, false
default_run_options[:pty] = true
set :keep_releases, 3
ssh_options[:forward_agent] = true
# Git Options
set :scm, :git
set :deploy_via, :remote_cache
set :git_shallow_clone, 1
set :git_enable_submodules, 1
set :scm_verbose, true
# Deploy type-specific options
if ENV['DEPLOY'] == 'PRODUCTION'
puts "Deploying to PRODUCTION..."
server production_server, :app, :web, :db, :primary => true
set :deploy_target, "production"
set :branch, "master"
else
puts "Deploying to STAGING..."
server staging_server, :app, :web, :db, :primary => true
set :deploy_target, 'staging'
set :branch, "master"
end
# Set Deploy path
set :deploy_to, "/home/#{user}/site/#{deploy_target}"
# Deploy Tasks
namespace :deploy do
desc "Copy app config"
task :after_symlink do
deploy.config
deploy.cleanup
end
desc "Restarting Passenger"
task :restart, :roles => :app do
run "touch #{deploy_to}/current/tmp/restart.txt"
end
# Stub the Start and Stop Tasks
[:start, :stop].each do |t|
desc "#{t} is a no-op with mod_rails"
task t, :roles => :app do ; end
end
desc "Copy Config"
task :config do
config_files.each do |c|
run "touch #{deploy_to}/shared/#{c}"
run "cp #{deploy_to}/shared/#{c} #{deploy_to}/current/config/"
end
end
end
namespace :watch do
desc "Tail the production log"
task :log do
stream "tail -f #{deploy_to}/shared/log/production.log"
end
end
|
WIN_COMBINATIONS = [
[0, 1, 2],
[0, 4, 8],
[0, 3, 6],
[3, 4, 5],
[6, 4, 2],
[1, 4, 7],
[6, 7, 8],
[2, 5, 8]
]
board = ["X", "X", "X", "X", "X", "X", "X", "X", "X"]
def display_board(board)
puts " #{board[0]} | #{board[1]} | #{board[2]} "
puts "-----------"
puts " #{board[3]} | #{board[4]} | #{board[5]} "
puts "-----------"
puts " #{board[6]} | #{board[7]} | #{board[8]} "
end
def input_to_index(input)
input.to_i - 1
end
def move(board, index, value)
board[index] = value
end
def position_taken?(board, index)
if board[index] == "" || board[index] == " " || board[index] == nil
false
elsif
board[index] == "X" || board[index] == "O"
true
else
nil
end
end
def valid_move?(board, index)
!position_taken?(board, index) && index.between?(0,8)
end
def position_taken?(board, index)
if board[index] == "" || board[index] == " " || board[index] == nil
false
elsif
board[index] == "X" || board[index] == "O"
true
else
nil
end
end
def turn(board)
puts "Please enter 1-9:"
input = gets.strip
index = input_to_index(input)
if valid_move?(board,index) == true
move(board, index, current_player(board))
display_board(board)
else
turn(board)
end
end
def turn_count(board)
turn=0
board.each do |token|
if(token=="X" || token=="O")
turn+=1
end
end
turn
end
def current_player(board)
turn_count(board) % 2 == 0? "X": "O"
end
def won?(board)
winning_combination = WIN_COMBINATIONS.detect do |combination|
board[combination[0]] != " " && board[combination[0]] == board[combination[1]] && board[combination[1]] == board[combination[2]]
end
end
def full?(board)
(board).none?{|i| i == " "}
end
def draw?(board)
full?(board) && !won?(board)
end
def over?(board)
full?(board) || won?(board) || draw?(board)
end
def winner(board)
winning_combination = won?(board)
if winning_combination
board[winning_combination[0]]
else
nil
end
end
def play(board)
until over?(board)
turn(board)
end
if won?(board)
if value = "X"
puts "Congratulations X!"
end
if value = "O"
puts "Congratulations O!"
end
else draw?(board)
puts "Cat's Game!"
end
end
|
class Game < ApplicationRecord
has_many :guesses
validates :number, presence: true, numericality: true
end
|
require_relative('../db/sql_runner')
# require('pry')
require 'pry-byebug'
class Lease
attr_reader :id, :equipment_id, :customer_id, :start_date, :end_date, :number_leased
def initialize(options)
# binding.pry
@id = options['id'].to_i if options['id']
@equipment_id = options['equipment_id'].to_i
@customer_id = options['customer_id'].to_i
@start_date = options['start_date']
@end_date = options['end_date']
@number_leased = options['number_leased']
end
def save
equipment = Equipment.find(@equipment_id)
# binding.pry
# finds all leases with ID and puts into ARRAY
leases_by_id_array = Lease.find_all_leases_by_id(@equipment_id)
# creates array of dates from start to end date
proposed_lease_date_range = date_range_array(@start_date, @end_date)
# binding.pry
# checks each date in date range for matching dates in leases with the same equipment_id
counter_array = [0] # empty array to be filled by matching instances for each date
proposed_lease_date_range.each do |date|
counter = 0
leases_by_id_array.each do |lease|
lease_date_range = date_range_array(lease.start_date, lease.end_date)
lease_date_range.each do |date_lease_object|
counter += lease.number_leased.to_i if date == date_lease_object # if proposed date matches other lease date then count
end
end
counter_array.push(counter) # adds counted instances to counter array
end
available = Equipment.find(@equipment_id).total_quantity.to_i - counter_array.max
# check if difference in stock and leased is greater or equal to requested amount:
if available >= @number_leased.to_i
# if true then save lease and return string reservation successful
sql = "INSERT INTO leases
(
equipment_id,
customer_id,
start_date,
end_date,
number_leased
)
VALUES
(
$1, $2, $3, $4, $5
)
RETURNING id"
values = [@equipment_id, @customer_id, @start_date, @end_date, @number_leased]
result = SqlRunner.run(sql, values)
id = result.first['id']
@id = id
return "Reservation of #{equipment.type} size - #{equipment.size} was successful"
else
# if there was insufficient stock on any day in the duration then return string:
return "Insufficient stock for selected dates for #{equipment.type} size - #{equipment.size}."
end
end
def self.total_leased_equipment_id(e_id, date)
sql = "SELECT SUM(number_leased)
FROM leases
WHERE equipment_id = $1
AND
$2 BETWEEN start_date AND "
values = [e_id, date]
result = SqlRunner.run(sql, values)
total_leased_equipment = result.first
total_leased_equipment['sum'].to_i
end
def self.find_all_leases_by_id(id)
sql = "SELECT *
FROM leases
WHERE equipment_id = $1"
values = [id]
result = SqlRunner.run(sql, values)
result.map { |lease| Lease.new(lease) }
end
def date_range_array(start_d, end_d)
date_start = Date.strptime(start_d)
date_end = Date.strptime(end_d)
date_range = date_start..date_end
date_range_array = date_range.to_a
date_range_array
end
def self.end_lease(id)
sql = "SELECT * FROM leases
WHERE id = $1"
values = [id]
result = SqlRunner.run(sql, values).first
lease = Lease.new(result)
sql = "SELECT * FROM equipment
WHERE id = $1"
values = [lease.equipment_id]
result = SqlRunner.run(sql, values).first
equipment = Equipment.new(result)
sql = "SELECT * FROM customers
WHERE id = $1"
values = [lease.customer_id]
result = SqlRunner.run(sql, values).first
customer = Customer.new(result)
sql = "INSERT INTO leases_log
(
lease_id,
equipment_type,
equipment_size,
equipment_cost,
customer_first_name,
customer_surname,
customer_contact_number,
customer_contact_email,
start_date,
end_date,
number_leased
)
VALUES
(
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11
)"
values = [lease.id, equipment.type, equipment.size, equipment.cost, customer.first_name, customer.surname, customer.contact_number, customer.contact_email, lease.start_date, lease.end_date, lease.number_leased]
SqlRunner.run(sql, values)
delete_by_id(lease.id)
end
def self.find(id)
sql = "SELECT * FROM leases
WHERE id = $1"
values = [id]
result = SqlRunner.run(sql, values).first
lease = Lease.new(result)
lease
end
def delete
sql = "DELETE FROM leases
WHERE id = $1"
values = [@id]
SqlRunner.run(sql, values)
end
def self.delete_by_id(id)
sql = "DELETE FROM leases
WHERE id = $1"
values = [id]
SqlRunner.run(sql, values)
end
def self.delete_all
sql = 'DELETE FROM leases'
SqlRunner.run(sql)
end
# def self.all()
# sql = "SELECT customers.first_name,
# customers.surname,
# customers.contact_number,
# customers.contact_email,
# equipment.type,
# equipment.size,
# equipment.cost,
# leases.start_date,
# leases.end_date
# FROM leases
# INNER JOIN customers
# ON leases.customer_id = customers.id
# INNER JOIN equipment
# ON leases.equipment_id = equipment.id"
# lease_data = SqlRunner.run(sql)
# leases = map_items(lease_data)
# return leases
# end
#
# def self.map_items(lease_data)
# return lease_data.map { |lese| Lease.new(lese) }
# end
end
|
json.array!(@skill_relations) do |skill_relation|
json.extract! skill_relation, :id, :skill_id, :student_id
json.url skill_relation_url(skill_relation, format: :json)
end
|
require 'spec_helper'
RSpec.describe 'time' do
subject(:a1) { [1,2,3].timed("2014") }
describe 'year_changed?' do
it "is true" do
expect(Time.new(2015,1,1,0,20).year_changed?).to be true
end
it "is false" do
expect(Time.new(2015,1,1,1,0).year_changed?).to be false
expect(Time.new(2015,1,2,0,20).year_changed?).to be false
expect(Time.new(2015,2,1,0,20).year_changed?).to be false
end
end
describe 'month_changed?' do
it "is true" do
expect(Time.new(2015,1,1,0,20).month_changed?).to be true
expect(Time.new(2015,2,1,0,20).month_changed?).to be true
end
it "is false" do
expect(Time.new(2015,1,1,1,0).month_changed?).to be false
expect(Time.new(2015,1,2,0,20).month_changed?).to be false
end
end
describe 'day_changed?' do
it "is true" do
expect(Time.new(2015,1,1,0,20).day_changed?).to be true
expect(Time.new(2015,1,2,0,20).day_changed?).to be true
expect(Time.new(2015,2,1,0,20).day_changed?).to be true
end
it "is false" do
expect(Time.new(2015,1,1,1,0).day_changed?).to be false
end
end
end |
class Truck
class Destroy < Trailblazer::Operation
step Model(::Truck, :find)
step TrailblazerHelpers::Steps::Destroy
end
end
|
class Constant < Expression
attr_accessible :name, :value
def to_s
name
end
def to_html
name
end
end
|
Pod::Spec.new do |s|
s.name = 'CEPubnub'
s.version = '0.0.1'
s.license = 'MIT'
s.summary = 'iOS objective-c wrapper for Pubnub real-time messaging service.'
s.homepage = 'https://github.com/jazzychad/CEPubnub'
s.author = { 'Chad Etzel' => 'http://jazzychad.net/' }
s.source = { :git => 'git://github.com/jeanregisser/CEPubnub.git' }
s.platform = :ios
s.source_files = 'CEPubnub/*.{h,m}'
s.clean_paths = FileList['*'].exclude(/(CEPubnub|README\.md|LICENSE|.*\.podspec)$/)
s.dependency 'JSONKit'
end |
# frozen_string_literal: true
RSpec.describe ProcessVideoDataJob do
describe '.perform' do
let(:video) { create(:video) }
subject(:perform) do
described_class.perform_now(video_id: video.id)
end
it 'calls service' do
expect_any_instance_of(ProcessVideoDataService).to receive(:call).with(video)
perform
end
end
end
|
class Meme < ApplicationRecord
belongs_to :user
has_many :tag_taggables, as: :taggable, dependent: :destroy
has_many :tags, through: :tag_taggables
def tags=(tags_or_tags_attributes)
tags_ids = if tags_or_tags_attributes.is_a? Array
tags_or_tags_attributes.each do |tag|
tag_taggables.where(tag_id: tag.id).first_or_create
end
tags_or_tags_attributes.map(&:id)
else
self.tags_by_attributes tags_or_tags_attributes
end
tag_taggables.where('tag_id NOT IN (?)', tags_ids).destroy_all
end
def tags_by_attributes(tags_attrs)
tags_attrs = tags_attrs.to_h.deep_symbolize_keys
tags_attrs.values.map do |tag_attrs|
tag_taggables.where(tag_id: tag_attrs[:id]).first_or_create
tag_attrs[:id]
end
end
def tag_id=(_param); end
end
|
class EditColumnPaymentTypeToTransferIns < ActiveRecord::Migration[5.1]
def change
rename_column :transfer_ins, :payment_type, :transfer_type
end
end
|
#unique instances
require 'date'
require_relative '../../mongo_conn'
require_relative '../../filter'
require_relative '../../../../src/lib/splice_reports/report_query'
#setup the db
db = MongoConn.new()
mpu = db.get_coll_marketing_report_data()
Given(/^there is a populated database with one instance where the last checkin is Current "(.*?)"$/) do |arg1|
mpu.drop()
load_db = system("mongorestore data/dump")
load_db.should == true
arg1.to_i.should == mpu.distinct('instance_identifier').count
end
When(/^I define a filter "(.*?)" starting at "(.*?)" ending at "(.*?)" with entitlement_status "(.*?)" and inactive "(.*?)"$/) do |name, f_start, f_end, status, inactive|
#When(/^I define a filter "(.*?)"$/) do |name, start|
#
@filter = Filter.new(name, nil, f_start, f_end, status.split(","), inactive)
#
end
Then(/^when I execute the filter, the report should have this number of rows "(.*?)"$/) do |arg1|
@result = 0
params = {}
q = ReportQuery.new(mpu)
#result = q.get_marketing_product_results(f, params, nil, nil, page_size)
@result = q.get_marketing_product_results(@filter, params, nil, nil, 25)
@result.count.to_s.should == arg1
end
##################
Given(/^there is a populated database with three instances each with a different status "(.*?)"$/) do |arg1|
create_checkins = system("../create_sample_data/create.py -u #{arg1} -p ../create_sample_data/")
create_checkins.should == true
load_db = system("../create_sample_data/load_data.py -d -p ../create_sample_data/")
load_db.should == true
end
When(/^I define a filter called each_status "(.*?)" starting at "(.*?)" ending at "(.*?)" with entitlement_status "(.*?)" and inactive "(.*?)"$/) do |name, f_start, f_end, status, inactive|
#double check that yesterday and tomorrow were passed in.
f_start.should == "yesterday"
f_end.should == "tomorrow"
today = DateTime.now
yesterday = today - 1
tomorrow = today + 1
inactive = false if inactive == "false"
inactive = true if inactive == "true"
@filter = Filter.new(name, nil, yesterday.to_time, tomorrow.to_time, status.split(","), inactive)
end
Then(/^when I execute each_status, the report should have this number of rows "(.*?)"$/) do |arg1|
@result = 0
params = {}
q = ReportQuery.new(mpu)
#result = q.get_marketing_product_results(f, params, nil, nil, page_size)
@result = q.get_marketing_product_results(@filter, params, nil, nil, 25)
@result.count.to_s.should == arg1
end
|
require 'spec_helper'
describe Station do
it 'initializes an instance of Station with a location name' do
test_station = Station.new({'location' => 'Rose Quarter'})
test_station.should be_an_instance_of Station
end
it 'gives us the location and id' do
test_station = Station.new({'location' => 'Rose Quarter', 'id' => 2})
test_station.location.should eq 'Rose Quarter'
test_station.id.should be_an_instance_of Fixnum
end
describe '.create' do
it 'creates and saves a location' do
test_station = Station.create({'location' => 'Rose Quarter', 'id' => 2})
Station.all.should eq [test_station]
end
end
describe '.all' do
it 'starts empty' do
Station.all.should eq []
end
end
describe '#save' do
it 'saves the station into the database' do
test_station = Station.new({'location' => 'Rose Quarter', 'id' => 2})
test_station.save
Station.all.should eq [test_station]
end
end
describe '#==' do
it 'recognizes that two locations are equal if their location and id are the same' do
test_station1 = Station.new({'location' => 'Rose Quarter', 'id' => 2})
test_station2 = Station.new({'location' => 'Rose Quarter', 'id' => 2})
test_station1.should eq test_station2
end
end
describe '.lines_serving_station' do
it 'shows the lines for a station' do
test_station = Station.create({'location' => 'Rose Quarter', 'id' => 2})
test_line = Line.create({'name' => 'blue', 'id' => 1})
test_station.create_stop(test_line.id)
Station.lines_serving_station(test_station.id)[0].should be_an_instance_of Line
end
end
describe '#create_stop' do
it 'assigns lines to a station' do
test_station = Station.new({'location' => 'Rose Quarter', 'id' => 2})
test_station.create_stop(1)
result = DB.exec("SELECT * FROM stops WHERE station_id = #{test_station.id};")
result[0]['line_id'].to_i.should eq 1
end
end
describe '.update' do
it 'updates the location of a station' do
test_station = Station.create({'location' => 'Rose Quarter', 'id' => 2})
Station.update(test_station.id, "Garden Quarter")
result = DB.exec("SELECT * FROM stations WHERE id = #{test_station.id};")
result[0]['location'].should eq "Garden Quarter"
end
end
describe '.delete' do
it 'deletes a station' do
test_station1 = Station.create({'location' => 'Rose Quarter', 'id' => 2})
test_station2 = Station.create({'location' => 'Garden Quarter', 'id' => 3})
Station.delete(test_station1.id)
result = DB.exec("SELECT * FROM stations;")
result[0]['location'].should eq 'Garden Quarter'
end
end
end
|
module DocumentsHelper
def render_markdown(document)
body = document.body
# Show signatures
employee_signature = document.signatures.employee.first
if employee_signature
body.gsub!(/(\[%)signature_employee_date(\])/, employee_signature.signed_on.strftime('%d/%m/%Y'))
body.gsub!(/(\[%)signature_employee(\])/, "")
end
employer_signature = document.signatures.employer.first
if employer_signature
body.gsub!(/(\[%)signature_employer_date(\])/, employer_signature.signed_on.strftime('%d/%m/%Y'))
body.gsub!(/(\[%)signature_employer(\])/, "")
end
# Don't show unfilled fields
body.gsub!(/(\[%)(.*)(\])/, "<pre>#{'_' * 20}</pre>")
renderer = Redcarpet::Render::HTML.new
markdown = Redcarpet::Markdown.new(renderer, tables: true)
markdown.render(body).html_safe
end
end
|
require 'json'
require_relative './tfc'
require_relative './delivery'
module CallObserver
class StackRecorder
def initialize(ruler)
@ruler = ruler
end
def log_file
@log ||= make_new_log_file
end
def make_new_log_file
File.join(Dir.mktmpdir, 'calls.log')
end
def log(record)
open(log_file, 'a'){|f| f.puts JSON.dump(record.to_h) }
end
def dump(records)
fl = make_new_log_file
open(fl, 'w') do |f|
records.each do |record|
f.puts JSON.dump(record.to_h)
end
end
fl
end
def record!(&blk)
main = caller.first.split(':').first
puts 'MAIN: ' + main
records = []
set_trace_func proc { |event, filename, line, oid, bindingg, klass|
missing_method = if oid == :method_missing
first_local_var = bindingg.eval('local_variables').first
missing_method = bindingg.eval("#{first_local_var}")
end
voodoo = if oid == :new && filename =~ /call_observer\/ext/
slf = bindingg.eval('self')
v = slf.instance_methods(false).map{ |m| Array(slf.instance_method(m).source_location).first }.uniq
v.empty? ? nil : v
end
records << TFC.new(event, filename, oid, klass, bindingg.eval("self"), missing_method, stack: bindingg.eval('caller'), voodoo: voodoo, line: line)
}
blk.call
set_trace_func nil
puts records.size
puts dump(records)
###################
events = []
records.each do |r|
if !!r.other[:voodoo] && @ruler.allow(r)
events << r
end
end
events
end
end
end
|
Gem::Specification.new do |s|
s.name = 'malware_api'
s.version = '0.1'
s.date = '2009-12-26'
s.summary = "Google Safe Browsing API for Rails"
s.author = 'Jorge Bernal'
s.email = 'koke@amedias.org'
s.homepage = 'http://github.com/koke/malware_api'
s.has_rdoc = false
s.extra_rdoc_files = ['README.markdown']
s.files = %w(MIT-LICENSE README.markdown Rakefile generators/malware_migration/USAGE generators/malware_migration/malware_migration_generator.rb generators/malware_migration/templates/migration.rb install.rb lib/app/models/malware.rb lib/app/models/malware_hash.rb lib/db/migrate/20091225014508_create_malwares.rb lib/db/migrate/20091225014608_create_malware_hashes.rb lib/malware_api.rb rails/init.rb tasks/malware_tasks.rake test/database.yml test/malware_test.rb test/schema.rb test/test_helper.rb uninstall.rb)
s.test_files = %w(test/database.yml test/malware_test.rb test/schema.rb test/test_helper.rb)
end
|
require './spec/support/file_helpers'
RSpec.configure do |c|
c.include FileHelpers
end
describe ManageIQ::Providers::Kubevirt::Inventory::Parser do
describe '#process_vms' do
it 'parses a vm' do
storage_collection = double("storage_collection")
storage = FactoryBot.create(:storage)
allow(storage_collection).to receive(:lazy_find).and_return(storage)
hw_collection = double("hw_collection")
hardware = FactoryBot.create(:hardware)
allow(hw_collection).to receive(:find_or_build).and_return(hardware)
network_collection = double("network_collection")
network = FactoryBot.create(:network, :hardware => hardware)
allow(network_collection).to receive(:find_or_build_by).and_return(network)
allow(hardware).to receive(:networks).and_return([network])
vm_collection = double("vm_collection")
vm = FactoryBot.create(:vm_kubevirt, :hardware => hardware)
allow(vm_collection).to receive(:find_or_build).and_return(vm)
parser = described_class.new
parser.instance_variable_set(:@storage_collection, storage_collection)
parser.instance_variable_set(:@vm_collection, vm_collection)
parser.instance_variable_set(:@hw_collection, hw_collection)
parser.instance_variable_set(:@network_collection, network_collection)
source = double(
:uid => "9f3a8f56-1bc8-11e8-a746-001a4a23138b",
:name => "demo-vm",
:namespace => "my-project",
:memory => "64M",
:cpu_cores => "2",
:ip_address => "10.128.0.18",
:node_name => "vm-17-235.eng.lab.tlv.redhat.com",
:owner_name => nil,
:status => "Running"
)
parser.send(:process_vm_instance, source)
expect(vm).to have_attributes(
:name => "demo-vm",
:template => false,
:ems_ref => "9f3a8f56-1bc8-11e8-a746-001a4a23138b",
:uid_ems => "9f3a8f56-1bc8-11e8-a746-001a4a23138b",
:vendor => ManageIQ::Providers::Kubevirt::Constants::VENDOR,
:power_state => "on",
:location => "my-project",
:connection_state => "connected",
)
net = vm.hardware.networks.first
expect(net).to_not be_nil
expect(net.ipaddress).to eq("10.128.0.18")
expect(net.hostname).to eq("vm-17-235.eng.lab.tlv.redhat.com")
end
end
end
|
Rails.application.routes.draw do
resources :about, only: :index
root "about#index"
end
|
class GrFosphor < Formula
homepage "http://sdr.osmocom.org/trac/wiki/fosphor"
url "git://git.osmocom.org/gr-fosphor.git", :revision => "3fdfe7cf812238804f25f5cdfe39f848fd657b33"
revision 2
depends_on "cmake" => :build
depends_on "gnuradio"
depends_on "glfw3"
def install
mkdir "build" do
python_prefix = `python-config --prefix`.strip
system 'cmake', '..',
*std_cmake_args,
"-DPYTHON_LIBRARY=#{python_prefix}/Python",
'-DPYTHON_INCLUDE_DIRS="/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/include/python2.7,/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/include/python2.7"',
"-DCMAKE_INSTALL_PREFIX=#{Formula['gnuradio'].prefix}"
system "make"
system "make", "install"
end
end
end
|
require 'rails_helper'
describe SendComplaintJob, type: :job do
describe '#perform_later' do
it 'queues a job' do
expect do
described_class.perform_later
end.to have_enqueued_job.on_queue('send_complaints').exactly(:once)
end
end
describe '#perform' do
subject(:jobs) { described_class.new }
let(:create_token) { instance_spy(Usecase::Optics::GenerateJwtToken) }
let(:get_bearer_token) { instance_spy(Usecase::Optics::GetBearerToken) }
let(:create_case) { instance_spy(Usecase::Optics::CreateCase) }
let(:spawn_attachments) { instance_spy(Usecase::SpawnAttachments) }
let(:presenter) { instance_spy(Presenter::Complaint) }
let(:gateway) { instance_spy(Gateway::Optics) }
let(:input) { { 'submissionAnswers': {} } }
let(:attachments) do
[
Attachment.new,
Attachment.new
]
end
before do
allow(Presenter::Complaint).to receive(:new).and_return(presenter).with(form_builder_payload: input, attachments: attachments, api_version: 'v1')
allow(Usecase::Optics::GenerateJwtToken).to receive(:new).and_return(create_token).with(
endpoint: Rails.configuration.x.optics.endpoint,
api_key: Rails.configuration.x.optics.api_key,
hmac_secret: Rails.configuration.x.optics.secret_key
)
allow(Usecase::Optics::GetBearerToken).to receive(:new).and_return(get_bearer_token).with(
optics_gateway: gateway,
generate_jwt_token: create_token
)
allow(Usecase::Optics::CreateCase).to receive(:new).and_return(create_case).with(
optics_gateway: gateway,
presenter: presenter,
get_bearer_token: get_bearer_token
)
allow(Usecase::SpawnAttachments).to receive(:new).and_return(spawn_attachments).with(
form_builder_payload: input
)
allow(spawn_attachments).to receive(:call).and_return(attachments)
allow(Gateway::Optics).to receive(:new).and_return(gateway)
end
it 'calls the spawn attachments usecase' do
jobs.perform(form_builder_payload: input, api_version:'v1')
expect(spawn_attachments).to have_received(:call).once
end
context 'when the a submission was submitted to Optics' do
it 'creates a new entry' do
jobs.perform(form_builder_payload: input, api_version:'v1')
expect(ProcessedSubmission.count).to eq(1)
end
end
end
end
|
# 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', city: cities.first)
[
{first_name: "Abraham", last_name: "Oshel",
email: "fake@faker.com", password: "password",
password_confirmation: "password",},
{first_name: "Paolo", last_name: "Cosentino",
email: "fake2@faker.com", password: "password",
password_confirmation: "password",}
{first_name: "Brett", last_name: "Lischalk",
email: "brett@brettlischalk.com", password: "password",
password_confirmation: "password",}
].each do |hash|
u = User.find_or_initialize_by(email: hash[:email])
u.update_attributes(first_name: hash[:first_name],
last_name: hash[:last_name],
email: hash[:email], password: hash[:password],
password_confirmation: hash[:password_confirmation],
confirmed_at: Date.today
)
u.save
end |
class Voucher
attr_reader :discount
def initialize()
@discount = 10
end
end |
require 'test_helper'
class NonCampusSchoolTotalsControllerTest < ActionDispatch::IntegrationTest
setup do
@non_campus_school_total = non_campus_school_totals(:one)
end
test "should get index" do
get non_campus_school_totals_url
assert_response :success
end
test "should get new" do
get new_non_campus_school_total_url
assert_response :success
end
test "should create non_campus_school_total" do
assert_difference('NonCampusSchoolTotal.count') do
post non_campus_school_totals_url, params: { non_campus_school_total: { } }
end
assert_redirected_to non_campus_school_total_url(NonCampusSchoolTotal.last)
end
test "should show non_campus_school_total" do
get non_campus_school_total_url(@non_campus_school_total)
assert_response :success
end
test "should get edit" do
get edit_non_campus_school_total_url(@non_campus_school_total)
assert_response :success
end
test "should update non_campus_school_total" do
patch non_campus_school_total_url(@non_campus_school_total), params: { non_campus_school_total: { } }
assert_redirected_to non_campus_school_total_url(@non_campus_school_total)
end
test "should destroy non_campus_school_total" do
assert_difference('NonCampusSchoolTotal.count', -1) do
delete non_campus_school_total_url(@non_campus_school_total)
end
assert_redirected_to non_campus_school_totals_url
end
end
|
class CreateAlunos < ActiveRecord::Migration
def change
create_table :alunos do |t|
t.string :nome
t.string :link_html
t.string :link_github
t.text :mini_curriculo
t.timestamps
end
end
end
|
#!/usr/bin/env ruby -W0
require "yaml"
require File.join(File.dirname(__FILE__), '..', 'lib', "rails_bundle_tools")
require File.join(File.dirname(__FILE__), '..', 'lib', "search_utilities")
require File.join(ENV['TM_SUPPORT_PATH'], 'lib', 'progress')
require File.join(ENV['TM_SUPPORT_PATH'], 'lib', 'current_word')
module TextMate
class ListMethods
CACHE_DIR = File.join(TextMate.project_directory, "tmp", "textmate")
CACHE_FILE = File.join(CACHE_DIR, "methods_cache.yml")
TEMP_CACHE_FILE = File.join(CACHE_DIR, "temp_methods_cache.yml")
RELOAD_MESSAGE = "Reload database schema..."
RAILS_REGEX = /^Rails (\d\.?){3}(\w+)?$/
def run!(current_word=current_word)
TextMate.exit_show_tool_tip("Place cursor on class name (or variation) to show its schema") if current_word.nil? || current_word.empty?
# TextMate.exit_show_tool_tip("You don't have Rails installed in this gemset.") unless rails_present?
if caller == caller.downcase
klass = Inflector.singularize(Inflector.underscore(caller))
else
klass = Inflector.classify(caller)
end
if cache[klass]
display_menu(klass, method_search_term)
elsif cache[klass_without_undescore = klass.split('_').last]
display_menu(klass_without_undescore, method_search_term)
else
initials_matchs = cache.keys.select { |word| first_letter_of_each_word(word) == caller }
if initials_matchs.size == 1
display_menu(initials_matchs.first, method_search_term)
else
options = [
@error || "'#{Inflector.camelize(klass)}' is not an Active Record derived class or was not recognized as a class. Pick one below instead:",
nil,
array_sorted_search(cache.keys, caller),
nil,
RELOAD_MESSAGE
].flatten
selected = TextMate::UI.menu(options)
return if selected.nil?
case options[selected]
when options.first
if @error && @error =~ /^#{TextMate.project_directory}(.+?)[:]?(\d+)/
TextMate.open(File.join(TextMate.project_directory, $1), $2.to_i)
else
klass_file = File.join(TextMate.project_directory, "/app/models/#{klass}.rb")
TextMate.open(klass_file) if File.exist?(klass_file)
end
when RELOAD_MESSAGE
cache_attributes and run!
else
klass = options[selected]
display_menu(klass, method_search_term)
end
end
end
end
def cache_attributes
_cache = {}
reset_cache
TextMate.call_with_progress(:title => "Contacting database", :message => "Fetching database schema...") do
self.update_cache(_cache)
end
_cache
end
def cache_attributes_in_background
_cache = {}
reset_cache
self.update_cache(_cache)
_cache
end
protected
def reset_cache
FileUtils.mkdir_p(CACHE_DIR)
File.delete(TEMP_CACHE_FILE) if File.exists?(TEMP_CACHE_FILE)
end
def first_letter_of_each_word(string)
string.split('_').map { |word| word[0,1] }.join("")
end
def update_cache(_cache)
begin
require "#{TextMate.project_directory}/config/environment"
Dir.glob(File.join(Rails.root, "app/models/**/**/*.rb")) do |file|
klass = nil
begin
klass = File.basename(file, '.*').camelize.constantize
rescue Exception => e
end
if klass and klass.class.is_a?(Class) and klass.ancestors.include?(ActiveRecord::Base)
_cache[klass.name] = { :variables => class_variables_for_class(klass), :constants => constants_for_class(klass), :methods => class_methods_for_class(klass) }
_cache[klass.name.underscore] = { :associations => associations_for_class(klass), :columns => klass.column_names, :methods => methods_for_class(klass) }
end
end
File.open(TEMP_CACHE_FILE, 'w') { |out| YAML.dump(_cache, out ) }
rescue Exception => e
puts e
puts e.backtrace
@error_message = "Fix it: #{e.message}"
else
`cp -f #{TEMP_CACHE_FILE} #{CACHE_FILE}`
end
end
def class_methods_for_class(klass)
out = klass.methods
out -= klass.instance_methods
out -= Object.methods
out -= ActiveRecord::Base.methods
klass.included_modules.each do |m|
out -= m.methods
out -= m::InstanceMethods.instance_methods if defined?(m::InstanceMethods)
out -= m::ClassMethods.instance_methods if defined?(m::ClassMethods)
end
out
end
def methods_for_class(klass)
out = klass.instance_methods
out -= Object.methods
out -= ActiveRecord::Base.instance_methods
out -= klass.column_names.map { |e| ["#{e}=", e, "#{e}?"]}.flatten
out -= associations_for_class(klass).map { |e| ["create_#{e}", "build_#{e}", "validate_associated_records_for_#{e}", "#{e}=", "autosave_associated_records_for_#{e}", e, "#{Inflector.singularize(e)}_ids", "#{Inflector.singularize(e)}_ids="] }.flatten
out -= class_variables_for_class(klass).map { |e| e.gsub('@@', '') }
out
end
def constants_for_class(klass)
klass.constants - ActiveRecord::Base.constants
end
def associations_for_class(klass)
klass.reflections.stringify_keys.keys
end
def class_variables_for_class(klass)
klass.class_variables - ActiveRecord::Base.class_variables
end
def clone_cache(klass, new_word)
cached_model = cache[klass]
cache[new_word] = cached_model
File.open(CACHE_FILE, 'w') { |out| YAML.dump(cache, out ) }
end
def display_menu(klass, search_term=nil)
columns = cache[klass][:columns]
associations = cache[klass][:associations]
variables = cache[klass][:variables]
constants = cache[klass][:constants]
methods = cache[klass][:methods]
options = []
options += columns + [nil] if columns
options += associations.empty? ? [] : associations + [nil] if associations
options += constants.map { |constant| "::#{constant}" } + [nil] if constants
options += variables.map { |variable| variable.gsub('@@', '') } + [nil] if variables
options += methods + [nil] if methods
search_term = TextMate::UI.request_string(:title => "Find a method", :prompt => "Find method for: '#{klass}'") if search_term.nil?
options = array_sorted_search(options, search_term) unless search_term.nil? or search_term == ''
matching_class_message = "(Listing attributes for #{Inflector.classify(klass)})"
options += [nil, RELOAD_MESSAGE, nil, matching_class_message]
valid_options = options.select { |e| !e.nil? and e != RELOAD_MESSAGE and e != matching_class_message }
if(valid_options.size == 1)
out = valid_options.first
elsif valid_options.size == 0
TextMate.exit_show_tool_tip("No matching results")
else
# TextMate.exit_show_tool_tip(options.join("\n"))
selected = TextMate::UI.menu(options)
return if selected.nil?
if options[selected] == RELOAD_MESSAGE
cache_attributes and run!
end
out = options[selected]
end
insert_selection_into_file(out)
end
def insert_selection_into_file(selected_method)
if current_word =~ /\.|(::)$/ or method_search_term
TextMate.exit_replace_text(selected_method)
else
operator = selected_method =~ /^::/ ? '' : '.'
TextMate.exit_replace_text("#{caller}#{operator}#{selected_method}")
end
end
def cache
FileUtils.mkdir_p(CACHE_DIR)
@cache ||= File.exist?(CACHE_FILE) ? YAML.load(File.read(CACHE_FILE)) : cache_attributes
end
def caller
caller_and_method_search_term.first
end
def method_search_term
caller_and_method_search_term.last
end
def caller_and_method_search_term
@caller_and_method ||= (
parts = current_word.split(/\.|(::)/)
if parts.size == 1
caller = parts.first
method_search_term = nil
elsif current_word =~ /\.|(::)$/
caller = parts[-1]
method_search_term = nil
else
caller = parts[-2]
method_search_term = parts[-1]
end
[caller, method_search_term]
)
end
def current_word
@current_word ||= input_text
end
def input_text
Word.current_word(':_a-zA-Z0-9.', :left)
end
def rails_present?
rails_version_command = "rails -v 2> /dev/null"
return `#{rails_version_command}` =~ RAILS_REGEX || `bundle exec #{rails_version_command}` =~ RAILS_REGEX
end
end
end
TextMate::ListMethods.new.cache_attributes_in_background if ENV['TM_CACHE_IN_BACKGROUND'] |
class PartiesController < ApplicationController
before_action :authorize_user!
def index
party = Party.find_by(user_id: @current_user.id)
if party
serialized_data = ActiveModelSerializers::Adapter::Json.new(PartySerializer.new(party)).serializable_hash
maps = party.party_maps.map { |map| {map: map.map, info: map} }
general_info = {characters: Character.all, equipment: Equipment.all, maps: maps}
json_return = serialized_data.merge(general_info)
end
render json: json_return
end
def create
party = Party.create(name: params[:party][:name], user_id: params[:party][:user_id], gold: 1000)
char = Character.find_by(role: params[:member][:role])
PartyCharacter.create(party_id: party.id, character_id: char.id, color: params[:member][:color], armor_color: params[:member][:armor_color], name: params[:member][:name], role: params[:member][:role], health: char.health, max_health: char.health)
serialized_data = ActiveModelSerializers::Adapter::Json.new(PartySerializer.new(party)).serializable_hash
general_info = {characters: Character.all, equipment: Equipment.all}
render json: serialized_data.merge(general_info)
end
def update
party = Party.find(params[:id])
if party_params
party.update(party_params)
end
if recruit_params
pc = PartyCharacter.new(recruit_params)
char = Character.find_by(role: recruit_params[:role])
pc.party = party
pc.character = char
pc.save
end
if map_params
pm = PartyMap.find(map_params[:id])
if map_params[:delete]
pm.destroy
else
pm.update(map_params)
end
end
if item_params
if item_params[:update]
# find one with old owner id, reset it
oldEquip = PartyEquipment.find_by(owner_id: item_params[:owner_id], party_id: item_params[:party_id])
if oldEquip
oldEquip.owner_id = 0
oldEquip.save
end
# find current equip, switch owner id
if item_params[:id] > 0
newEquip = PartyEquipment.find(item_params[:id])
newEquip.owner_id = item_params[:owner_id]
newEquip.save
end
else
party.equipments << Equipment.find(item_params[:equipment_id])
end
end
maps = party.party_maps.map { |map| {map: map.map, info: map} }
serialized_data = ActiveModelSerializers::Adapter::Json.new(PartySerializer.new(party)).serializable_hash
general_info = {characters: Character.all, equipment: Equipment.all, maps: maps}
json_return = serialized_data.merge(general_info)
render json: json_return
end
def show
json_return = {}
party = Party.find_by(user_id: params[:id])
if party
serialized_data = ActiveModelSerializers::Adapter::Json.new(PartySerializer.new(party)).serializable_hash
maps = party.party_maps.map { |map| {map: map.map, info: map} }
general_info = {characters: Character.all, equipment: Equipment.all, maps: maps}
json_return = serialized_data.merge(general_info)
end
render json: json_return
end
def destroy
party = Party.find(params[:id])
party.destroy
render json: {alert: "party deleted"}
end
private
def party_params
params.require(:party).permit(:gold, :name)
end
def recruit_params
if params[:recruit]
params.require(:recruit).permit(:name, :role, :health, :max_health, :mana, :armor_color, :armor, :color)
end
end
def map_params
if params[:map]
params.require(:map).permit(:current_square, :moves, :complete, :visited, :id, :delete)
end
end
def item_params
if params[:item]
params.require(:item).permit(:id, :owner_id, :equipment_id, :update, :party_id)
end
end
# t.string :visited
# t.boolean :complete, default: false
# t.integer :moves, default: 0
# t.string :current_square, default: "00"
end
|
require 'tem_ruby'
require 'test/unit'
# Helper methods for TEM tests.
#
# This module implements setup and teardown methods that provide an initialized
# @tem instance variable holding a Tem::Session. Just the right thing for
# testing :)
class TemTestCase < Test::Unit::TestCase
def setup
@tem = Tem.auto_tem
@tem.kill
@tem.activate
end
def teardown
@tem.disconnect if defined?(@tem) && @tem
end
def default_test
# NOTE: Without this, test/unit will complain that the class does not have
# test cases.
end
end
|
require 'docking_station'
RSpec.describe DockingStation do
bike = Bike.new
describe '#release_bike' do
it {is_expected.to respond_to(:release_bike)}
it "returns an existing bike object" do
subject.dock(bike)
expect(subject.release_bike).to be_instance_of(Bike)
end
it "raises an error when no bikes available" do
expect {(subject.release_bike)}.to raise_error("No bikes available")
end
end
it "When new bike object created checks the bike is working" do
expect(bike).to be_working
end
describe '#dock' do
it {is_expected.to respond_to(:dock).with(1).argument}
it "expects a bike to be docked" do
expect(subject.dock(bike)).to eq ([bike])
end
it {is_expected.to respond_to(:bikes)}
it "raises an error when docking station is full" do
DockingStation::DEFAULT_CAPACITY.times {subject.dock(bike)}
expect {subject.dock(bike)}.to raise_error("Docking station full")
end
end
end
|
Rails.application.routes.draw do
root "series#index"
resources :series do
resources :game
end
end
|
# Question 11
# What will the following code output?
class Animal
def initialize(name)
@name = name
end
def speak
puts sound
end
def sound
"#{@name} says "
end
end
class Cow < Animal
def sound
super + "moooooooooooo!"
end
end
daisy = Cow.new("Daisy")
daisy.speak
# Answer
# Cow inherets #speak from Animal. When daisy calls #speak, it calls
# #sound and passes the return value to puts. SInce an instance of
# Cow calls #speak, #speak calls Cow#sound. Cow#sounds uses super
# to call Animal#sound, which returns the interpolated string
# "Daisy says ". Cow#sound then concatenates the return value with
# the string "mooooooooooooo!" and returns the new result, which is
# output by puts. |
class Post < ActiveRecord::Base
acts_as_votable
belongs_to :user
has_many :comments, dependent: :destroy
belongs_to :category
default_scope -> { order(created_at: :desc) }
self.per_page = 4
#This method removes the default scope before the query
def self.random_top_story
Post.unscoped {
Post.order("RANDOM()")
}
end
def self.top_story
Post.unscoped {
Post.order(cached_votes_up: :desc)
}
end
def self.search(params)
posts = Post.where("title like ? or content like ?", "%#{params[:search]}%", "%#{params[:search]}%") if params[:search].present?
posts
# ['name like ?', "%#{search}%"]
end
end
|
# write your reps here
# makes sure to either `p my_output` or `puts my_output`.
# `p _variablename_` prints the full Object
# `puts _variablename_` prints the Object.to_s (.toString())
# to run, just `ruby reps.rb`
#Write a function `lengths` that accepts a single parameter as an argument, namely an array of strings. The function should return an array of numbers. Each number in the array should be the length of the corresponding string.
#{}```ruby
words = ["hello", "what", "is", "up", "dude"]
def lengths(words)
words.map{|words| words.length}
end
#2
def transmogrifier(a,b,c)
puts(a*b)**c
end
#3
puts toonify ("daffy", "so you smell like sausage")
puts toonifty ("elmer", " rascal rabbits")
def toonify(accent, sentence)
if accent == "daffy"
return sentence.gsub(/s/, 'th')
else ==
return sentence.gsub(/r/, 'w')
end
#4
def wordReverse(strings)
string = " Now I know what a TV dinner feels like"
string.split(" ").reverse.join(" ")
end
#5letterReverse("Now I know what a TV dinner feels like")
def letterReverse(string)
string = " Now I know what a TV dinner feels like"
"Now I know what a TV dinner feels like".reverse
end
#6
def longest (longestArray)
longestArray=(["oh", "good", "grief"])
longestArray.max_by(&:length)
end
|
# -*- encoding : utf-8 -*-
require 'rails_helper'
RSpec.describe Completion, type: :model do
describe 'sorted_certificates' do
let!(:completion) { FactoryGirl.create(:completion) }
let!(:certificate) { FactoryGirl.create(:certificate, completion: completion) }
let!(:record_of_achievement) { FactoryGirl.create(:record_of_achievement, completion: completion) }
let!(:confirmation_of_participation) { FactoryGirl.create(:confirmation_of_participation, completion: completion) }
it 'sorts the certificates with the type' do
expect(completion.sorted_certificates).to match [confirmation_of_participation, record_of_achievement, certificate]
end
end
end
|
class Word < ActiveRecord::Base
has_many :game_words
has_many :games, :through => :game_words
end
|
class EARMMS::UserSettingsGroupController < EARMMS::ApplicationController
helpers EARMMS::GroupHelpers
get '/' do
unless logged_in?
flash(:error, "You must be logged in to access this page.")
next redirect('/auth')
end
@user = current_user
@profile = EARMMS::Profile.for_user(@user)
@group_ids = get_group_ids_user_is_member(@user)
if @group_ids.empty?
@groups = {}
else
@groups = get_groups_hash_by_type(@group_ids, {
:user => @user,
:only_user_joined => true,
:link_to_edit => :user
})
end
@title = "Your groups"
haml :'user_settings/group/index'
end
end
|
module E9Crm::PageViewsHelper
def page_view_campaign_select_options
@_page_view_campaign_select_options ||= begin
opts = Campaign.all.map {|campaign| [campaign.name, campaign.id] }
opts.unshift ['Any', nil]
options_for_select(opts)
end
end
def page_view_new_visit_select_options
options_for_select([
['Any', nil],
['New Visits', true],
['Repeat Visits', false]
])
end
def page_view_date_select_options(options = {})
@_first_date ||= PageView.order(:created_at).first.try(:created_at) || Date.today
date, cdate = @_first_date, Date.today
sel_options = []
if options[:type] == :until
prefix = 'Up to '
label = prefix + ' Now'
elsif options[:type] == :in_month
prefix = 'Closed in '
label = 'Since Inception'
else
prefix = 'Since '
label = prefix + ' Inception'
end
begin
sel_options << [date.strftime("#{prefix}%B %Y"), date.strftime('%Y/%m')]
date += 1.month
end while date.year <= cdate.year && date.month <= cdate.month
sel_options.reverse!
sel_options.unshift([label, nil])
options_for_select(sel_options)
end
end
|
require 'spec_helper'
describe Factual::Query::Monetize do
include TestHelpers
before(:each) do
@token = get_token
@api = get_api(@token)
@monetize = Factual::Query::Monetize.new(@api)
@base = "http://api.v3.factual.com/places/monetize?"
end
it "should be able to use filters" do
@monetize.filters("place_country" => "US").rows
expected_url = @base + "filters={\"place_country\":\"US\"}"
CGI::unescape(@token.last_url).should == expected_url
end
it "should be able to search" do
@monetize.search("suchi", "sashimi").rows
expected_url = @base + "q=suchi,sashimi"
CGI::unescape(@token.last_url).should == expected_url
end
end
|
class Artist
extend Memorable::ClassMethods
extend Findable::ClassMethods
extend Createable::ClassMethods
attr_accessor :name, :songs, :genres
@@instances = []
def initialize(name = nil)
@name = name
@@instances << self
@songs = []
@genres = []
end
def self.all
@@instances
end
def add_song(song)
self.songs << song
self.genres << song.genre
song.genre.artists << self if song.genre
end
def add_songs(songs)
songs.each { |song| add_song(song) }
end
end
|
# 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', city: cities.first)
user = User.first
if (user.nil?)
user = User.create(:email => "lxkuznetsov@ya.ru", :name => "Admin",
:password => "123qwe", :password_confirmation => "123qwe")
end
Space.create :user => user, :name => "Math" unless Space.find_by_name("Math")
Space.create :user => user, :name => "Phisic" unless Space.find_by_name("Phisic")
Space.create :user => user, :name => "Statistic" unless Space.find_by_name("Statistic")
FUNCTIONS.each do |func|
Function.find_or_create_by_name(func)
end
REQUEST_OPERATORS.each do |ro|
RequestOperator.find_or_create_by_name(ro)
end |
# Settings specified here will take precedence over those in config/environment.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.action_view.debug_rjs = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Open Id Registration URL
CLICKPASS_REGISTRATION_URL = "http://www.clickpass.com/process_new_openid?site_key=rj1JItenyg&process_openid_registration_url=http%3A%2F%2Flocalhost%3A3000%2Fopenid%2Fprocess_openid_registration&requested_fields=family-name%2Cnickname%2Cgiven-name%2Cphoto-url%2Cemail&required_fields=family-name%2Cnickname%2Cgiven-name%2Cphoto-url%2Cemail&family-name_label=Family%20name&nickname_label=Nickname&given-name_label=Given%20name&photo-url_label=Profile%20photo&email_label=Email" |
module Jsonapi
class UserResource < JSONAPI::Resource
attributes :avatar_url, :email, :first_name, :last_name,
:middle_name, :password
has_many :scorecards
has_many :courses
filter :id_not, apply: lambda { |records, value, _options|
# TODO: Is there a way to filter without this?
records.where.not(id: value)
}
filter :name, apply: lambda { |records, value, _options|
# TODO: this can be cleaned up
filtered_record_ids = records.select do |user|
user.full_name.downcase.include? value[0].downcase
end.map(&:id)
records.where(id: filtered_record_ids)
}
# def self.apply_sort(records, _order_options, _context = {})
# records.by_name
# end
def fetchable_fields
super - [:password]
end
end
end
|
# frozen_string_literal: true
RSpec.describe Api::V1::UserSerializer, type: :serializer do
let(:user) { build_stubbed(:user) }
subject(:result) { serialize_entity(user, class: {User: described_class}) }
describe 'type' do
it 'returns proper type' do
expect(result.dig(:data, :type)).to eq :users
end
end
describe 'attributes' do
context 'when user is not current user' do
context 'when current user is not admin' do
it 'returns proper attributes' do
expect(result.dig(:data, :attributes).keys).to match_array(
%i[
email
avatar
firstName
lastName
]
)
end
end
context 'when current user is admin' do
let(:admin) { create(:user, :admin) }
subject(:result) { serialize_entity(user, class: {User: described_class}, expose: {current_user: admin}) }
it 'returns proper attributes' do
expect(result.dig(:data, :attributes).keys).to match_array(
%i[
email
avatar
admin
firstName
lastName
privacyPolicyAccepted
deletedAt
planType
city
country
]
)
end
it 'returns proper relationships' do
expect(result.dig(:data, :relationships).keys).to match_array(
%i[
favoriteCoaches
subscriptions
]
)
end
end
end
context 'when user is current_user' do
subject(:result) { serialize_entity(user, class: {User: described_class}, expose: {current_user: user}) }
it 'returns proper attributes' do
expect(result.dig(:data, :attributes).keys).to match_array(
%i[
email
avatar
admin
firstName
lastName
privacyPolicyAccepted
deletedAt
]
)
end
it 'returns proper relationships' do
expect(result.dig(:data, :relationships).keys).to match_array(
%i[
favoriteCoaches
paymentSources
defaultPaymentSource
subscriptions
]
)
end
end
end
end
|
require './utils/string'
class Inventory
# E.g. F123245, F123245Q, F123245Q12
def self.anonymize_inventory_number(inventory_number)
return "" if (inventory_number || "").blank?
prefix = inventory_number.scan(/^[A-Za-z]/).join
prefix = "X" if prefix.blank?
suffix = inventory_number.scan(/[Qq]{1}\d*/).join
srand(inventory_number.hash)
prefix + ("%06d" % rand(1..999999).to_s) + suffix
end
# e.g. L12324, S1234, GC-12345, Dec2018Stock -> becomes GC-12345
def self.anonymize_designation_name(designation_name)
return "" if (designation_name || "").blank?
prefix = designation_name.scan(/^[L,S,C,GC-]*/)[0]
prefix = "GC-" if prefix.blank?
srand(designation_name.hash)
prefix + ("%05d" % rand(1..99999).to_s)
end
# +85261234567
def self.random_hk_mobile
"+852" + %w(5 6 7 8 9).sample + rand(10**6..10**7-1).to_s
end
# CAS-12345
def self.random_case_number
"CAS-" + rand(10**4..10**5-1).to_s
end
end |
# author: Kevin M
# Teacher model, validates the presence of various properties, but nothing else
# right now.
class Teacher < ApplicationRecord
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :user_name, presence: true
validates :teacher_icon_name, presence: true, length: { maximum: 8 }
validates :teacher_name, presence: true, length: { maximum: 8 }
validates :teacher_email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :color, presence: true
validates :school_id, presence: true
end
|
require_relative '../db/sql_runner.rb'
class Item
attr_accessor :type, :id
def initialize(options)
@id = options['id'].to_i if options['id']
@type = options['type']
end
def save()
sql = "INSERT INTO items (type) VALUES ('#{@type}') RETURNING * ;"
result = SqlRunner.run(sql)
@id = result[0]['id'].to_i()
end
def update(options)
sql = "UPDATE items SET (type) = (
'#{options['type']}')
WHERE id = #{@id};"
SqlRunner.run(sql)
end
def delete()
sql = "DELETE FROM items WHERE id = #{@id};"
SqlRunner.run(sql)
end
def self.find(id)
sql = "SELECT * FROM items WHERE id = #{id};"
options = SqlRunner.run( sql )
item = Item.new( options.first )
return item
end
def self.all()
sql = "SELECT * FROM items;"
items = SqlRunner.run(sql)
return items.map { |options| Item.new(options)}
end
def self.delete_all()
sql = "DELETE FROM items;"
SqlRunner.run(sql)
end
end
|
class RemoveCachedDetailsFromWants < ActiveRecord::Migration
def change
remove_column :wants, :seller, :string
remove_column :wants, :game_id, :integer
end
end
|
class Notification < ApplicationRecord
belongs_to :user
after_create :att_saw_notifications
enum kind: [ :bell, :ticket, :cash]
def att_saw_notifications
self.user.sawnotifications = false
self.user.save
end
end
|
require 'zlib'
require 'rack/request'
require 'rack/response'
require 'rack/utils'
require 'redis'
require 'time'
require 'fileutils'
require 'scrolls'
module Sokoban
class Receiver
include Scrolls
ROUTES =
[["POST", :service_rpc, /(.*?)\/git-upload-pack$/, 'upload-pack'],
["POST", :service_rpc, /(.*?)\/git-receive-pack$/, 'receive-pack'],
["GET", :get_info_refs, /(.*?)\/info\/refs$/],
["GET", :get_text_file, /(.*?)\/HEAD$/],
["GET", :get_text_file, /(.*?)\/objects\/info\/alternates$/],
["GET", :get_text_file, /(.*?)\/objects\/info\/http-alternates$/],
["GET", :get_info_packs, /(.*?)\/objects\/info\/packs$/],
["GET", :get_text_file, /(.*?)\/objects\/info\/[^\/]*$/],
["GET", :get_loose_object, /(.*?)\/objects\/[0-9a-f]{2}\/[0-9a-f]{38}$/],
["GET", :get_pack_file, /(.*?)\/objects\/pack\/pack-[0-9a-f]{40}\\.pack$/],
["GET", :get_idx_file, /(.*?)\/objects\/pack\/pack-[0-9a-f]{40}\\.idx$/],
]
def initialize(repo_url, user, token, app_name, buildpack_url,
slug_put_url, slug_url, repo_put_url)
Scrolls.global_context(app: "sokoban", receiver: true)
bundle = File.join("/tmp", "repo.bundle")
@repo_dir = File.join("/tmp", "repo")
FileUtils.rm_rf(@repo_dir)
log(action: "fetch") do
if(repo_url =~ /^http/)
system("curl", "--retry", "3", "--max-time", "90", repo_url,
:out => bundle)
else # local repo for testing
FileUtils.cp(repo_url, bundle)
end
if(system("git", "bundle", "verify", bundle))
system("git", "clone", "--bare", bundle, @repo_dir)
else # repo doesn't exist or was corrupt
log(action: "init-repo")
system("git", "init", "--bare", @repo_dir)
end
File.delete(bundle)
end
install_hooks(user, token, app_name, buildpack_url,
slug_put_url, slug_url, repo_put_url)
# TODO: do the right thing here
ifconfig = `/sbin/ifconfig eth0 | grep inet | awk '{print $2}'`
host = ifconfig.gsub("addr:", "").strip
puts("Started on #{host}:#{ENV['PORT']}")
end
def install_hooks(user, token, app_name, buildpack_url,
slug_put_url, slug_url, repo_put_url)
log(action: "install-hooks") do
hooks_dir = File.join(@repo_dir, "hooks")
FileUtils.rm_rf(hooks_dir)
FileUtils.mkdir_p(hooks_dir)
sokoban = File.join(File.dirname(__FILE__), "..", "..", "bin", "sokoban")
File.open(File.join(hooks_dir, "post-receive"), "w") do |f|
f.puts("ruby -I #{$LOAD_PATH.join(':')} #{sokoban} post_receive_hook " \
"'#{user}' '#{token}' '#{app_name}' '#{buildpack_url}' " \
"'#{slug_put_url}' '#{slug_url}' '#{repo_put_url}'")
end
FileUtils.chmod_R(0755, hooks_dir)
end
end
def call(env)
@env = env
@req = Rack::Request.new(env)
method, *args = route(@req.request_method, @req.path_info)
Dir.chdir(@repo_dir) do
self.send(method, *args)
end
end
def route(req_method, req_path)
ROUTES.each do |method, handler, matcher, rpc|
if m = matcher.match(req_path)
if method == req_method
file = req_path.sub(m[1] + '/', '')
return [handler, rpc || file]
else
return [:not_allowed]
end
end
end
[:not_found]
end
def reply
host = UDPSocket.open { |s| s.connect("64.233.187.99", 1); s.addr.last }
url = "http://#{host}:#{ENV["PORT"]}"
log(fn: "reply", url: url)
Redis.new(:url => ENV["REDIS_URL"]).lpush(ENV["REPLY_KEY"], url)
end
# ---------------------------------
# actual command handling functions
# ---------------------------------
def service_rpc(rpc)
if content_type_matches?(rpc)
input = read_body
@res = Rack::Response.new
@res.status = 200
@res["Content-Type"] = "application/x-git-%s-result" % rpc
@res.finish do
command = "git #{rpc} --stateless-rpc #{@repo_dir}"
IO.popen(command, File::RDWR) do |pipe|
pipe.write(input)
while !pipe.eof?
block = pipe.read(16) # 16B at a time
@res.write block # steam it to the client
end
end
end
else
not_allowed
end
end
def get_info_refs(reqfile)
service_name = get_service_type
if service_name == 'upload-pack' or service_name == 'receive-pack'
refs = `git #{service_name} --stateless-rpc --advertise-refs .`
@res = Rack::Response.new
@res.status = 200
@res["Content-Type"] = "application/x-git-%s-advertisement" % service_name
hdr_nocache
@res.write(pkt_write("# service=git-#{service_name}\n"))
@res.write(pkt_flush)
@res.write(refs)
@res.finish
else
dumb_info_refs(reqfile)
end
end
def dumb_info_refs(reqfile)
`git update-server-info`
send_file(reqfile, "text/plain; charset=utf-8") do
hdr_nocache
end
end
def get_info_packs(reqfile)
# objects/info/packs
send_file(reqfile, "text/plain; charset=utf-8") do
hdr_nocache
end
end
def get_loose_object(reqfile)
send_file(reqfile, "application/x-git-loose-object") do
hdr_cache_forever
end
end
def get_pack_file(reqfile)
send_file(reqfile, "application/x-git-packed-objects") do
hdr_cache_forever
end
end
def get_idx_file(reqfile)
send_file(reqfile, "application/x-git-packed-objects-toc") do
hdr_cache_forever
end
end
def get_text_file(reqfile)
send_file(reqfile, "text/plain") do
hdr_nocache
end
end
# ------------------------
# logic helping functions
# ------------------------
# some of this borrowed from the Rack::File implementation
def send_file(reqfile, content_type)
reqfile = File.join(@repo_dir, reqfile)
return render_not_found if !File.exists?(reqfile)
@res = Rack::Response.new
@res.status = 200
@res["Content-Type"] = content_type
@res["Last-Modified"] = File.mtime(reqfile).httpdate
yield
if size = File.size?(reqfile)
@res["Content-Length"] = size.to_s
@res.finish do
File.open(reqfile, "rb") do |file|
while part = file.read(8192)
@res.write part
end
end
end
else
body = [File.read(reqfile)]
size = Rack::Utils.bytesize(body.first)
@res["Content-Length"] = size
@res.write body
@res.finish
end
end
def get_service_type
service_type = @req.params['service']
return false if !service_type
return false if service_type[0, 4] != 'git-'
service_type.gsub('git-', '')
end
def content_type_matches?(rpc)
@req.content_type == "application/x-git-%s-request" % rpc
end
def get_git_config(config_name)
`git config #{config_name}`.chomp
end
def read_body
if @env["HTTP_CONTENT_ENCODING"] =~ /gzip/
input = Zlib::GzipReader.new(@req.body).read
else
input = @req.body.read
end
end
# --------------------------------------
# HTTP error response handling functions
# --------------------------------------
PLAIN_TYPE = {"Content-Type" => "text/plain"}
def not_allowed
if @env['SERVER_PROTOCOL'] == "HTTP/1.1"
[405, PLAIN_TYPE, ["Method Not Allowed"]]
else
[400, PLAIN_TYPE, ["Bad Request"]]
end
end
def not_found
[404, PLAIN_TYPE, ["Not Found"]]
end
def no_access
[403, PLAIN_TYPE, ["Forbidden"]]
end
# ------------------------------
# packet-line handling functions
# ------------------------------
def pkt_flush
'0000'
end
def pkt_write(str)
(str.size + 4).to_s(base=16).rjust(4, '0') + str
end
# ------------------------
# header writing functions
# ------------------------
def hdr_nocache
@res["Expires"] = "Fri, 01 Jan 1980 00:00:00 GMT"
@res["Pragma"] = "no-cache"
@res["Cache-Control"] = "no-cache, max-age=0, must-revalidate"
end
def hdr_cache_forever
now = Time.now().to_i
@res["Date"] = now.to_s
@res["Expires"] = (now + 31536000).to_s;
@res["Cache-Control"] = "public, max-age=31536000";
end
end
end
|
# cd /var/www/test/headfirstpatterns/ch03/Starbuzz02
# ruby -I lib starbuzz_coffee.rb
Beverages = ['beverage', 'espresso', 'dark_roast', 'house_blend', 'decaf']
Condiments = ['condiment_decorator', 'mocha_decorator', 'whip_decorator', 'soy_decorator']
(Beverages + Condiments).each do |lib_file|
require lib_file
end
class StarbuzzCoffee
def main
beverage = Espresso.new :big
puts_beverage(beverage)
beverage2 = DarkRoast.new
beverage2.set_size :small
# Decoration
# - Кофе темной обжарки (DarkRoast)
# + с двойным шоколадом (Mocha) и взбитыми сливками (Whip)
beverage2 = Mocha.new(beverage2)
beverage2 = Mocha.new(beverage2)
beverage2 = Whip.new(beverage2)
puts_beverage(beverage2)
# Decoration((Beverage))
beverage3 = Whip.new( Mocha.new( Soy.new(HouseBlend.new) ))
puts_beverage(beverage3)
end
private
def puts_beverage(beverage)
puts "#{beverage.get_description} $#{format("%0.2f", beverage.cost)}"
end
end
# Run
starbuzz_coffee = StarbuzzCoffee.new
starbuzz_coffee.main
|
class BooksController < ApplicationController
def index
@book = Book.get_random
if current_user
@favorite_books = current_user.books
end
end
def show
@book = Book.find(params[:book_id])
end
def new
if current_user && current_user.admin
@book = Book.new
else
redirect_to '/books'
end
end
def create
@book = Book.create(book_params)
if @book.save
redirect_to "/books/#{@book.id}/admin"
else
render :new
end
end
def edit
if current_user && current_user.admin
set_book
else
redirect_to '/books'
end
end
def update
set_book
@book.update(book_params)
redirect_to "/books/#{@book.id}/admin"
end
def admin
set_book
end
def all
@books = Book.all
end
private
def book_params
params.require(:book).permit(:title, :author, :text, :img_link, :amazon_link, :genre)
end
def set_book
@book = Book.find(params[:id])
end
end |
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'middleman-google_drive/version'
Gem::Specification.new do |spec|
spec.name = 'middleman-google_drive'
spec.version = Middleman::GoogleDrive::VERSION
spec.platform = Gem::Platform::RUBY
spec.authors = ['Ryan Mark', 'Pablo Mercado']
spec.email = ['ryan@mrk.cc', 'pablo@voxmedia.com']
spec.summary = 'Pull content from a google spreadsheet to use in your middleman site.'
#spec.description = %q(TODO: Write a longer description. Optional.)
spec.homepage = 'https://github.com/voxmedia/middleman-google_drive'
spec.license = 'BSD'
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.required_ruby_version = '~> 2.1'
spec.add_runtime_dependency 'middleman-core', '~> 3'
spec.add_runtime_dependency 'retriable', '~> 1.4'
spec.add_runtime_dependency 'google-api-client', '< 0.8'
spec.add_runtime_dependency 'rubyXL', '~> 3.3'
spec.add_runtime_dependency 'archieml', '~> 0.1'
spec.add_runtime_dependency 'mime-types', '~> 2.4'
spec.add_development_dependency 'bundler', '~> 1.6'
spec.add_development_dependency 'rake', '~> 10.3'
spec.add_development_dependency 'minitest', '~> 5.4'
spec.add_development_dependency 'yard', '~> 0.8'
end
|
module Api
module V1
class SessionsController < Devise::SessionsController
respond_to :json
protected
def sign_in_params
params.require(:user).permit(:email, :password)
end
end
end
end
|
require 'test_helper'
class WheelDeflectionsControllerTest < ActionDispatch::IntegrationTest
setup do
@wheel_deflection = wheel_deflections(:one)
end
test "should get index" do
get wheel_deflections_url
assert_response :success
end
test "should get new" do
get new_wheel_deflection_url
assert_response :success
end
test "should create wheel_deflection" do
assert_difference('WheelDeflection.count') do
post wheel_deflections_url, params: { wheel_deflection: { description: @wheel_deflection.description, name: @wheel_deflection.name } }
end
assert_redirected_to wheel_deflection_url(WheelDeflection.last)
end
test "should show wheel_deflection" do
get wheel_deflection_url(@wheel_deflection)
assert_response :success
end
test "should get edit" do
get edit_wheel_deflection_url(@wheel_deflection)
assert_response :success
end
test "should update wheel_deflection" do
patch wheel_deflection_url(@wheel_deflection), params: { wheel_deflection: { description: @wheel_deflection.description, name: @wheel_deflection.name } }
assert_redirected_to wheel_deflection_url(@wheel_deflection)
end
test "should destroy wheel_deflection" do
assert_difference('WheelDeflection.count', -1) do
delete wheel_deflection_url(@wheel_deflection)
end
assert_redirected_to wheel_deflections_url
end
end
|
class TimeCard < ApplicationRecord
belongs_to :user
validates :year, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 1 }
validates :month, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 1 }
validates :day, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 1 }
validate :valid_date # このバリデーションは year, month, day のバリーデーションの下に定義しないと有効でない
validates :in_at, presence: true, if: lambda { |m| !m.out_at.nil? }
validate :out_at_is_later_than_in_at
class << self
# 今日のタイムカードを取得する
def today(user)
date = Date.today
condition = { user: user, year: date.year, month: date.month, day: date.day }
self.find_by(condition) || self.new(condition)
end
# 指定年月のタイムカードを取得する
def monthly(user, year, month)
self.where(user: user, year: year, month: month).order(:day).all
end
end
# 勤務状況を取得する
def working_status
case [!!in_at, !!out_at]
when [false, false]
:not_arrived # 未出社
when [true, false]
:working # 勤務中
when [true, true]
:left # 退社済
end
end
# タイムカードの日付を返す
def date
Date.new(year, month, day)
end
# 勤務時間を返す(単位は秒)
def work_hours_in_seconds
if in_at && out_at
out_at - in_at
else
0
end
end
private
# カスタムバリデーション(正しい日付か?)
def valid_date
return if errors[:year].any? || errors[:month].any? || errors[:day].any?
if !Date.valid_date?(year, month, day)
errors[:base] << '不正な日付です'
end
end
# カスタムバリデーション(退社時間が出社時間より後か?)
def out_at_is_later_than_in_at
return if in_at.nil? || out_at.nil?
if in_at > out_at
errors[:base] << '退社時間は、出社時間より後の時間である必要があります'
end
end
end
|
module MotionBuild ; module Rules
class LipoRule < MultifileRule
def input_extension
'.o'
end
def output_extension
'.o'
end
def run
project.builder.notify('lipo', sources, destination)
project.builder.run('lipo', ['-create', *sources, '-output', destination])
end
end
end ; end
|
class PriceSerializer < ActiveModel::Serializer
attributes :id, :currency, :value
end
|
class Api::EvaluationsController < Api::BaseController
skip_before_action :authenticate_user!, only: [ :index, :show, :specified, :aggregate ]
include EvaluationsConcern
def specified
@evaluations = Evaluation.where(evaluationable_type: params[:evaluationable_type], evaluationable_id: params[:evaluationable_id])
@evaluations =
case params[:type]
when nil, "ALL"
@evaluations
when "GOOD"
@evaluations.where("(CAST(items ->> 'good' as integer) + CAST(items ->> 'delivery' AS integer) + CAST(items ->> 'customer_service' AS integer)) > 12")
when "MEDIUM"
@evaluations.where("(CAST(items ->> 'good' as integer) + CAST(items ->> 'delivery' AS integer) + CAST(items ->> 'customer_service' AS integer)) BETWEEN 9 AND 12")
when "BAD"
@evaluations.where("(CAST(items ->> 'good' as integer) + CAST(items ->> 'delivery' AS integer) + CAST(items ->> 'customer_service' AS integer)) < 9")
when "IMAGES"
@evaluations
end
@total = @evaluations.count
@evaluations = @evaluations.page(params[:page])
.per(params[:per])
render :index
end
def aggregate
result = Evaluation
.where(evaluationable_type: params[:evaluationable_type], evaluationable_id: params[:evaluationable_id])
.select("CASE WHEN CAST(items ->> 'good' as integer) + CAST(items ->> 'delivery' AS integer) + CAST(items ->> 'customer_service' AS integer) > 12 THEN 'GOOD' WHEN CAST(items ->> 'good' as integer) + CAST(items ->> 'delivery' AS integer) + CAST(items ->> 'customer_service' AS integer) > 9 THEN 'MEDIUM' ELSE 'BAD' END AS score_label, COUNT(*) AS count")
.group("score_label")
hash = result.to_a.map { |i| [i.score_label, i.count] }.to_h
render json: hash
end
end
|
require 'oauth2'
require 'cortex/connection'
require 'cortex/request'
require 'cortex/resource'
require 'cortex/content_items'
require 'cortex/posts'
require 'cortex/users'
require 'cortex/webpages'
require 'cortex/result'
module Cortex
class Client
attr_reader :posts, :users, :webpages, :content_items
attr_accessor :access_token, :base_url, :auth_method
@key = ''
@secret = ''
@scopes = ''
include Cortex::Connection
include Cortex::Request
def initialize(hasharg)
@base_url = hasharg[:base_url] || 'http://cortex.dev/api/v1'
if hasharg.has_key? :access_token
@access_token = hasharg[:access_token]
else
@key = hasharg[:key]
@secret = hasharg[:secret]
@scopes ||= hasharg[:scopes]
@access_token = get_cc_token
end
@posts = Cortex::Posts.new(self)
@users = Cortex::Users.new(self)
@webpages = Cortex::Webpages.new(self)
@content_items = Cortex::ContentItems.new(self)
end
def get_cc_token
begin
client = OAuth2::Client.new(@key, @secret, site: @base_url)
client.client_credentials.get_token({scope: @scopes})
rescue Faraday::ConnectionFailed
raise Cortex::Exceptions::ConnectionFailed.new(base_url: @base_url)
end
end
end
end
|
class AuditProblem::MissingAgency < AuditProblem::EntrySpecific
def self.run(options={})
field :agency_names, :type => String
problems = []
Entry.find_each(:joins => "JOIN agency_name_assignments ON agency_name_assignments.assignable_id = entries.id AND agency_name_assignments.assignable_type = 'Entry' LEFT OUTER JOIN agency_assignments ON agency_assignments.assignable_id = entries.id AND agency_assignments.assignable_type = 'Entry'", :conditions => "agency_assignments.id IS NULL") do |entry|
problems << build_from_entry(entry, :agency_names => entry.agency_names.map(&:name).to_sentence)
end
problems
end
end
|
# frozen_string_literal: true
class LocationsController < ApplicationController
include Locations::Refresh
include Concerns::Application::RedirectWithStatus
secure!(:event, :course, :seminar)
title!('Locations')
before_action :update_form_data, only: %i[edit update]
def list
@locations = Location.all.map(&:display)
end
def new
@location = Location.new
@edit_action = 'Add'
@submit_path = create_location_path
end
def edit
@location = Location.find_by(id: update_params[:id])
render :new
end
def create
redirect_with_status(locations_path, object: 'location', verb: 'create') do
@location = Location.create(location_params)
end
end
def update
@location = Location.find_by(id: update_params[:id])
redirect_or_render_error(
locations_path, render_method: :new, object: 'location', verb: 'update'
) do
@location.update(location_params)
end
end
def remove
redirect_with_status(locations_path, object: 'location', verb: 'remove') do
Location.find_by(id: update_params[:id])&.destroy
end
end
private
def location_params
params.require(:location).permit(
:address, :map_link, :details, :favorite, :virtual, :price_comment, :picture,
:delete_attachment
)
end
def update_params
params.permit(:id)
end
def update_form_data
@edit_action = 'Modify'
@submit_path = update_location_path
end
end
|
require_relative 'spec_helper.rb'
describe ChefAB::BaseUpgrader do
it 'should have an integer hash' do
up = ChefAB::BaseUpgrader.new(node_id: 5)
expect(up.hash).to be_a_kind_of(Integer)
end
it 'should have an integer hash in any case' do
up = ChefAB::BaseUpgrader.new(node_id: "testing node")
expect(up.hash).to be_a_kind_of(Integer)
end
end
|
class Team < ApplicationRecord
has_many :home_games, foreign_key: "home_team_id", class_name: "Game"
has_many :away_games, foreign_key: "away_team_id", class_name: "Game"
def total_points
home_games.sum(:team1points) + away_games.sum(:team2points)
end
end
|
describe "Datoki.db Schema_Conflict" do
before {
CACHE[:schema_conflict] ||= begin
reset_db <<-EOF
CREATE TABLE "datoki_test" (
id serial NOT NULL PRIMARY KEY,
title varchar(123),
body varchar(255) NOT NULL,
created_at timestamp with time zone NOT NULL DEFAULT timezone('UTC'::text, now())
);
EOF
end
}
it "raises Schema_Conflict when specified to allow nil, but db doesn not" do
should.raise(Datoki::Schema_Conflict) {
Class.new {
include Datoki
table :datoki_test
field(:body) { varchar nil, 1, 255 }
}
}.message.should.match /:allow_null: false != true/i
end
it "raises Schema_Conflict when there is a :max_length conflict" do
should.raise(Datoki::Schema_Conflict) {
Class.new {
include Datoki
table :datoki_test
field(:title) { varchar nil, 1, 200 }
}
}.message.should.match /:max: 123 != 200/i
end
end # === describe Datoki.db
|
class GameEvent < ApplicationRecord
belongs_to :game, touch: true, optional: true
validates_inclusion_of :state, in: Game::STATES
def self.latest_state(state)
where("game_events.id IN (SELECT MAX(id) FROM game_events GROUP BY game_id)").where(:state => state)
end
end
|
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
module TwitterCldr
module Localized
class LocalizedString < LocalizedObject
include Enumerable
# Uses wrapped string object as a format specification and returns the result of applying it to +args+ (see
# standard String#% method documentation for interpolation syntax).
#
# If +args+ is a Hash than pluralization is performed before interpolation (see +PluralFormatter+ class for
# pluralization specification).
#
def %(args)
pluralized = args.is_a?(Hash) ? formatter.format(@base_obj, args) : @base_obj
escape_plural_interpolation(pluralized) % args
end
def normalize(options = {})
TwitterCldr::Normalization.normalize(@base_obj, options).localize(locale)
end
def casefold(options = {})
unless options.include?(:t)
# Turkish and azerbaijani use the dotless i and therefore have a few
# special casefolding rules. Note "az" is not actually supported yet.
options[:t] = [:tr, :az].include?(locale)
end
TwitterCldr::Shared::Casefolder.
casefold(@base_obj, options[:t]).
localize(locale)
end
def downcase
self.class.new(
TwitterCldr::Shared::Caser.downcase(@base_obj), locale
)
end
def upcase
self.class.new(
TwitterCldr::Shared::Caser.upcase(@base_obj), locale
)
end
def titlecase
self.class.new(
TwitterCldr::Shared::Caser.titlecase(@base_obj), locale
)
end
def each_sentence
if block_given?
break_iterator.each_sentence(@base_obj) do |sentence|
yield sentence.localize(locale)
end
else
to_enum(__method__)
end
end
def each_word
if block_given?
break_iterator.each_word(@base_obj) do |word|
yield word.localize(locale)
end
else
to_enum(__method__)
end
end
def hyphenate(delimiter = nil)
hyphenated_str = @base_obj.dup
break_iterator.each_word(@base_obj).reverse_each do |word, start, stop|
hyphenated_str[start...stop] = hyphenator.hyphenate(word, delimiter)
end
hyphenated_str.localize(locale)
end
def code_points
TwitterCldr::Utils::CodePoints.from_string(@base_obj)
end
def to_s
@base_obj.dup
end
def to_i(options = {})
to_f(options).to_i
end
def to_f(options = {})
if number_parser.class.is_numeric?(@base_obj)
number_parser.try_parse(@base_obj, options) do |result|
result || @base_obj.to_f
end
else
@base_obj.to_f
end
end
def size
code_points.size
end
alias :length :size
def bytesize
@base_obj.bytesize
end
def [](index)
if index.is_a?(Range)
TwitterCldr::Utils::CodePoints.to_string(code_points[index])
else
TwitterCldr::Utils::CodePoints.to_char(code_points[index])
end
end
def each_char
if block_given?
code_points.each do |code_point|
yield TwitterCldr::Utils::CodePoints.to_char(code_point)
end
@base_obj
else
code_points.map { |code_point| TwitterCldr::Utils::CodePoints.to_char(code_point) }.to_enum
end
end
alias :each :each_char
def to_yaml(options = {})
TwitterCldr::Utils::YAML.dump(@base_obj, options)
end
def to_bidi(options = {})
TwitterCldr::Shared::Bidi.from_string(@base_obj, options)
end
def to_reordered_s(options = {})
to_bidi(options).reorder_visually!.to_s
end
def to_territory
TwitterCldr::Shared::Territory.new(@base_obj)
end
def scripts
TwitterCldr::Utils::ScriptDetector.detect_scripts(@base_obj).scripts
end
def script
TwitterCldr::Utils::ScriptDetector.detect_scripts(@base_obj).best_guess
end
def transliterate_into(target_locale)
TwitterCldr::Transforms::Transliterator.transliterate(@base_obj, locale, target_locale)
end
private
def escape_plural_interpolation(string)
# escape plural interpolation patterns (see PluralFormatter)
string.gsub(TwitterCldr::Formatters::PluralFormatter::PLURALIZATION_REGEXP, '%\0')
end
def formatter
@formatter ||=
TwitterCldr::Formatters::PluralFormatter.for_locale(locale)
end
def break_iterator
@break_iterator ||= TwitterCldr::Segmentation::BreakIterator.new(locale)
end
def number_parser
@number_parser ||= TwitterCldr::Parsers::NumberParser.new(locale)
end
def hyphenator
@hyphenator ||= TwitterCldr::Shared::Hyphenator.get(locale)
end
end
end
end
|
require "minitest/autorun"
require "nidyx"
require "nidyx/parse_constants"
require "nidyx/property"
require "nidyx/objc/property"
include Nidyx::ParseConstants
class TestObjCProperty < Minitest::Test
def test_is_obj
assert_equal(true, simple_property("array").is_obj?)
assert_equal(false, simple_property("boolean").is_obj?)
assert_equal(false, simple_property("integer").is_obj?)
assert_equal(false, simple_property("number").is_obj?)
assert_equal(true, simple_property(%w(boolean null)).is_obj?)
assert_equal(true, simple_property(%w(integer null)).is_obj?)
assert_equal(true, simple_property(%w(number null)).is_obj?)
assert_equal(true, simple_property("string").is_obj?)
assert_equal(true, simple_property("object").is_obj?)
assert_equal(true, simple_property("null").is_obj?)
end
def test_simple_array
obj = { TYPE_KEY => "array" }
p = property(obj, false)
assert_equal(:array, p.type)
assert_equal(nil, p.getter_override)
assert_equal([], p.protocols)
assert_equal(false, p.has_protocols?)
# optional array
p = property(obj, true)
assert_equal(:array, p.type)
assert_equal(["Optional"], p.protocols)
assert_equal(true, p.has_protocols?)
end
def test_typed_optional_array
obj = { TYPE_KEY => ["array", "null"] }
p = property(obj, false)
assert_equal(:array, p.type)
assert_equal(["Optional"], p.protocols)
end
def test_typed_array_with_protocls
obj = { TYPE_KEY => ["array" ], COLLECTION_TYPES_KEY => ["aClass", "string"] }
p = property(obj, false)
assert_equal(:array, p.type)
assert_equal(["aClass"], p.protocols)
end
def test_boolean
obj = { TYPE_KEY => "boolean" }
p = property(obj, false)
assert_equal(:boolean, p.type)
# optional boolean
p = property(obj, true)
assert_equal(:number_obj, p.type)
end
def test_typed_optional_boolean
obj = { TYPE_KEY => ["boolean", "null"] }
p = property(obj, false)
assert_equal(:number_obj, p.type)
end
def test_integer
obj = { TYPE_KEY => "integer" }
p = property(obj, false)
assert_equal(:integer, p.type)
p = property(obj, true)
assert_equal(:number_obj, p.type)
assert_equal(["Optional"], p.protocols)
end
def test_unsigned_integer
obj = { TYPE_KEY => "integer", "minimum" => 0 }
p = property(obj, false)
assert_equal(:unsigned, p.type)
end
def test_typed_optional_integer
obj = { TYPE_KEY => ["integer", "null"] }
p = property(obj, false)
assert_equal(:number_obj, p.type)
assert_equal(["Optional"], p.protocols)
end
def test_number
obj = { TYPE_KEY => "number" }
p = property(obj, false)
assert_equal(:number, p.type)
p = property(obj, true)
assert_equal(:number_obj, p.type)
end
def test_typed_optional_number
obj = { TYPE_KEY => ["number", "null"] }
p = property(obj, false)
assert_equal(:number_obj, p.type)
end
def test_string
obj = { TYPE_KEY => "string" }
p = property(obj, false)
assert_equal(:string, p.type)
p = property(obj, true)
assert_equal(:string, p.type)
end
def test_typed_optional_string
obj = { TYPE_KEY => ["string", "null"] }
p = property(obj, false)
assert_equal(:string, p.type)
end
def test_object
obj = {
TYPE_KEY => "object",
PROPERTIES_KEY => {}
}
p = property(obj, false)
assert_equal(:object, p.type)
end
def test_multiple_numeric_types
obj = { TYPE_KEY => ["number", "integer", "boolean"] }
p = property(obj, false)
assert_equal(:number_obj, p.type)
end
def test_typed_optional_multiple_numeric_types
obj = { TYPE_KEY => ["number", "integer", "boolean", "null"] }
p = property(obj, false)
assert_equal(:number_obj, p.type)
assert_equal(["Optional"], p.protocols)
end
def test_multiple_disparate_types
obj = { TYPE_KEY => ["object", "number"] }
p = property(obj, false)
assert_equal(:id, p.type)
end
def test_typed_optional_multiple_disparate_types
obj = { TYPE_KEY => ["object", "number", "null"] }
p = property(obj, false)
assert_equal(:id, p.type)
end
def test_simple_numbers
obj = { TYPE_KEY => [ "integer", "number" ] }
p = property(obj, false)
assert_equal(:number, p.type)
p = property(obj, true)
assert_equal(:number_obj, p.type)
end
def test_typed_optional_simple_numbers
obj = { TYPE_KEY => [ "integer", "number", "null" ] }
p = property(obj, false)
assert_equal(:number_obj, p.type)
end
def test_integer_enum
obj = { ENUM_KEY => [1, 2] }
p = property(obj, false)
assert_equal(:integer, p.type)
p = property(obj, true)
assert_equal(:number_obj, p.type)
assert_equal(["Optional"], p.protocols)
end
def test_string_enum
obj = { ENUM_KEY => ["a", "b"] }
p = property(obj, false)
assert_equal(:string, p.type)
end
def test_typed_optional_enum
obj = { ENUM_KEY => [1, 2, nil] }
p = property(obj, false)
assert_equal(:number_obj, p.type)
assert_equal(["Optional"], p.protocols)
end
def test_single_element_array_type
obj = { TYPE_KEY => ["integer"] }
p = property(obj, false)
assert_equal(:integer, p.type)
end
def test_anonymous_object
obj = { TYPE_KEY => "object" }
p = property(obj, false)
assert_equal(:id, p.type)
end
def test_unsafe_getter
obj = { TYPE_KEY => "integer" }
p = Nidyx::ObjCProperty.new(Nidyx::Property.new("newInt", nil, false, obj))
assert_equal(", getter=getNewInt", p.getter_override)
end
def test_protocols
obj = {
TYPE_KEY => "array",
COLLECTION_TYPES_KEY => ["SomeModel", "OtherModel"]
}
p = property(obj, false)
assert_equal(true, p.has_protocols?)
assert_equal("SomeModel, OtherModel", p.protocols_string)
assert_equal(%w(SomeModel OtherModel), p.protocols)
p = property(obj, true)
assert_equal(true, p.has_protocols?)
assert_equal("SomeModel, OtherModel, Optional", p.protocols_string)
assert_equal(%w(SomeModel OtherModel Optional), p.protocols)
end
def test_unsupported_types_enum
assert_raises(Nidyx::ObjCProperty::UnsupportedEnumTypeError) do
obj = { ENUM_KEY => ["a", {}] }
Nidyx::ObjCProperty.new(Nidyx::Property.new("i", nil, false, obj))
end
end
private
def simple_property(type)
obj = { TYPE_KEY => type }
Nidyx::ObjCProperty.new(Nidyx::Property.new("p", nil, false, obj))
end
def property(obj, optional, class_name = nil)
Nidyx::ObjCProperty.new(Nidyx::Property.new("name", class_name, optional, obj))
end
end
|
class Room < ActiveRecord::Base
belongs_to :sponsor, class_name: "User", foreign_key: "sponsor_id"
belongs_to :audience, class_name: "User", foreign_key: "audience_id"
has_many :talks, dependent: :destroy
end
|
class MessageBroadcastJob < ApplicationJob
include ActionView::RecordIdentifier
queue_as :default
def perform(message:)
channel = "messages_#{message.user.id}_#{message.client.id}"
message_html = render_message_partial(message)
status_html = render_message_status_partial(message)
message_dom_id = "message_#{message.id}"
ActionCable.server.broadcast(
channel,
message_html: message_html,
message_status_html: status_html,
message_status: message.twilio_status,
message_dom_id: message_dom_id,
message_id: message.id
)
ActionCable.server.broadcast("clients_#{message.user.id}", {})
message_json = message.as_json(include: { reporting_relationship: { include: :client } })
message_json['type'] = message.type
ActionCable.server.broadcast("events_#{message.user.id}", type: 'message', data: message_json)
end
def render_message_partial(message)
MessagesController.render(
partial: "#{message.class.to_s.tableize}/#{message.class.to_s.tableize.singularize}",
locals: { "#{message.class.to_s.tableize.singularize}": message }
)
end
def render_message_status_partial(message)
return nil unless message.class.to_s == 'TextMessage'
MessagesController.render(
partial: 'text_messages/text_message_status', locals: { text_message: message }
)
end
end
|
require 'rails_helper'
RSpec.describe Task, type: :model do
describe "#toggle_complete!" do
it "should switch complete to false if it began as true" do
task = Task.new(complete: true)
task.toggle_complete!
expect(task.complete).to eq(false)
end
it "should switch complete to true if it began as false" do
task = Task.new(complete: false)
task.toggle_complete!
expect(task.complete).to eq(true)
end
end
describe "#toggle_favorite!" do
it "should switch favorite to false if it began as true" do
task = Task.new(favorite: true)
task.toggle_favorite!
expect(task.favorite).to eq(false)
end
it "should switch favorite to true if it began as false" do
task = Task.new(favorite: false)
task.toggle_favorite!
expect(task.favorite).to eq(true)
end
end
describe "overdue?" do
it "should return true if deadline is earlier than now" do
task = Task.new(deadline: 1.day.ago)
expect(task.overdue?).to eq(true)
end
end
describe "increment_priority!" do
it "should add one to the priority if it is less than 10" do
task = Task.new(priority: 5)
task.increment_priority!
expect(task.priority).to eq(6)
end
it "should not add one to the priority if it is 10" do
task = Task.new(priority: 10)
task.increment_priority!
expect(task.priority).to eq(10)
end
end
describe "decrement_priority!" do
it "should subtract one to the priority if it is greater than 1" do
task = Task.new(priority: 5)
task.decrement_priority!
expect(task.priority).to eq(4)
end
it "should not subtract one to the priority if it is 1" do
task = Task.new(priority: 1)
task.decrement_priority!
expect(task.priority).to eq(1)
end
end
end
|
class AddUuidToMessages < ActiveRecord::Migration[5.0]
enable_extension 'uuid-ossp'
def change
drop_table :messages
create_table :messages, id: :uuid do |t|
t.text :content
t.string :location
t.string :password
t.float :latitude
t.float :longitude
t.timestamps
end
end
end
|
class CartItem < ApplicationRecord
belongs_to :item
belongs_to :customer
end
|
class AssignmentCollectionsController < ApplicationController
before_action :set_assignment_collection, only: [:edit, :edit_api, :update, :destroy]
before_action :require_admin, only:[:edit, :create, :destroy]
# INDEX [HTTP GET]
#=================================================================================================================
def index
@new_assignment_collection = AssignmentCollection.new
@assignment_collections = AssignmentCollection.all.order(:delivery_date).reverse_order
end
# EDIT [HTTP GET]
#=================================================================================================================
def edit
end
def edit_api
available_stores = ['Costco', 'Loblaws']
ordersResponse = OrdersService.get_orders_for_date(@assignment_collection.delivery_date)
render json: {
assignment_collection: @assignment_collection.convert_to_json,
available_shoppers: Shopper.all.collect{|x| x.username},
available_orders: ordersResponse.orders.collect{|x| x.name}, #['Order #1414', 'Order #2323'],
available_stores: available_stores
}.to_json
end
# GET SHOPPER ASSIGNMENT FOR DATE [HTTP GET -> JSON]
#=================================================================================================================
def get_assignment
if !params[:shopper_name].nil?
delivery_date = params[:delivery_date].nil? ? Date.today : DateTime.strptime(params[:delivery_date], '%d-%b-%Y')
delivery_date ||= Date.today
shopper_name = params[:shopper_name]
assignment_collection = AssignmentCollection.find_by(delivery_date: delivery_date) || AssignmentCollection.new
render json: assignment_collection.assignment_for_shopper(shopper_name)
else
render json: {status: 'failure'}, status: :not_found
end
end
# UPDATE [HTTP POST]
#=================================================================================================================
def update
if params.has_key?(:shopper_assignments)
@assignment_collection.update_shopper_assignments(params[:shopper_assignments])
end
if @assignment_collection.save
render json: {status: 'success'}, status: :ok
else
render json: {status: 'failure'}, status: :unprocessable_entity
end
end
# CREATE [HTTP POST]
#=================================================================================================================
def create
target_date = new_assignment_params[:delivery_date].to_date
if target_date.nil?
flash[:warning] = 'Delivery date required for making new shopper assignments.'
redirect_to assignments_path
return
end
@new_assignment_collection = AssignmentCollection.new(delivery_date: target_date.in_time_zone('EST'))
if @new_assignment_collection.save
flash[:success] = "New shopper assignments list for #{@new_assignment_collection.delivery_date} created."
redirect_to assignment_path(@new_assignment_collection)
else
render 'index'
end
end
# DESTROY [HTTP DELETE]
#=================================================================================================================
def destroy
if @assignment_collection.destroy
flash[:success] = 'Shopper assignments for day deleted.'
else
flash[:danger] = 'Failed to delete shopper assignments for day.'
end
redirect_to assignments_path
end
private
def set_assignment_collection
@assignment_collection = AssignmentCollection.find(params[:id])
if @assignment_collection.nil?
#raise ActionController::RoutingError.new('Not Found')
flash[:danger] = 'Shopper assignments not found'
redirect_to root_path
end
end
def new_assignment_params
params.require(:assignment_collection).permit(:delivery_date)
end
def require_admin
unless is_admin?
flash[:danger] = 'That action requires admin access'
redirect_to assignments_path
end
end
end |
class CreateNvsDepts < ActiveRecord::Migration
def change
create_table :nvs_depts do |t|
t.string :name, :limit => 50, :default => "", :null => false
t.string :email, :limit => 300, :default => "", :null => false
t.integer :project_id, :null => false
t.timestamps
end
end
end
|
require_relative 'spec_helper.rb'
describe RPS::Session do
it "exists" do
expect(RPS::Session).to be_a(Class)
end
describe ".initialize" do
it "generates a unique id for each session" do
RPS::Session.class_variable_set :@@counter, 0
expect(RPS::Session.new(1).id).to eq(1)
expect(RPS::Session.new(1).id).to eq(2)
expect(RPS::Session.new(1).id).to eq(3)
end
it "has a user id" do
session = RPS::Session.new(1)
expect(session.user_id).to eq(1)
end
end
end |
class BananaStand
def initialize (colour, mr_manager, opened_in=1988, accepts_credit_cards=true)
@color = colour
@mr_manager = mr_manager
@opened_in = opened_in
@accepts_credit_cards = accepts_credit_cards
end
attr_accessor :color, :mr_manager #gets and sets
# attr_reader :color #can only read and not write (in terminal)
attr_reader :opened_in #can write but can't read/access(in terminal)
attr_reader :accepts_credit_cards
# def color
# @color
# end
# def color= color_name
# @color = color_name
# end
end
bs = BananaStand.new "orange", "GM", 1988
# my_banana_stand = {
# color: "yellow",
# opened_in: 1953,
# mr_manager: "George Michael",
# accepts_credit_cards: true
# } |
##
# This file adapted from activerecord gem
#
module Pools
class Handler
attr_reader :pools
def initialize(pools = {})
@pools = pools
end
# Add a new connection pool to the mix
def add(pool, name = nil)
key = name || pool.object_id
raise(%Q(Pool "#{name}" already exists)) if @pools[name]
@pools[name] = pool
end
# Returns any connections in use by the current thread back to the
# pool, and also returns connections to the pool cached by threads
# that are no longer alive.
def clear_active_connections!
@pools.each_value {|pool| pool.release_connection }
end
def clear_all_connections!
@pools.each_value {|pool| pool.disconnect! }
end
# Verify active connections.
def verify_active_connections! #:nodoc:
@pools.each_value {|pool| pool.verify_active_connections! }
end
# Returns true if a connection that's accessible to this class has
# already been opened.
def connected?(name)
conn = retrieve_connection_pool(name)
conn && conn.connected?
end
# Remove the connection for this class. This will close the active
# connection and the defined connection (if they exist). The result
# can be used as an argument for establish_connection, for easily
# re-establishing the connection.
def remove_connection(name)
pool = retrieve_connection_pool(name)
return nil unless pool
@pools.delete_if { |key, value| value == pool }
pool.disconnect!
end
def retrieve_connection_pool(name)
pool = @pools[name]
return pool if pool
end
end
def self.handler
@@pool_handler ||= Handler.new
end
end
|
class Couriers::OrdersController < Couriers::BaseController
def index
@orders = Order.unassigned
end
end |
# == Schema Information
#
# Table name: taggings
#
# id :integer not null, primary key
# taggable_type :string
# taggable_id :integer
# tag_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_taggings_on_tag_id (tag_id)
# index_taggings_on_taggable_type_and_taggable_id (taggable_type,taggable_id)
#
FactoryGirl.define do
factory :album_tagging, class: Tagging do
association :tag, factory: :tag
association :taggable, factory: :album
end
factory :photo_tagging, class: Tagging do
association :tag, factory: :tag
association :taggable, factory: :photo
end
end
|
class Comment
include DataMapper::Resource
property :id, Serial
end |
# spec/requests/requests_spec.rb
RSpec.describe 'Requests API' do
# Initialize the test data
let!(:template) { create(:template) }
let!(:workflow) { create(:workflow, :template_id => template.id) }
let(:workflow_id) { workflow.id }
let!(:requests) { create_list(:request, 2, :workflow_id => workflow.id) }
let(:id) { requests.first.id }
let!(:requests_with_same_state) { create_list(:request, 2, :state => 'notified', :workflow_id => workflow.id) }
let!(:requests_with_same_decision) { create_list(:request, 2, :decision => 'approved', :workflow_id => workflow.id) }
# Test suite for GET /workflows/:workflow_id/requests
describe 'GET /workflows/:workflow_id/requests' do
before { get "#{api_version}/workflows/#{workflow_id}/requests" }
context 'when workflow exists' do
it 'returns status code 200' do
expect(response).to have_http_status(200)
end
it 'returns all workflow requests' do
expect(json.size).to eq(6)
end
end
context 'when workflow does not exist' do
let!(:workflow_id) { 0 }
it 'returns status code 404' do
expect(response).to have_http_status(404)
end
it 'returns a not found message' do
expect(response.body).to match(/Couldn't find Workflow/)
end
end
end
# Test suite for GET /requests
describe 'GET /requests' do
before { get "#{api_version}/requests" }
it 'returns requests' do
expect(json).not_to be_empty
expect(json.size).to eq(6)
end
it 'returns status code 200' do
expect(response).to have_http_status(200)
end
end
# Test suite for GET /requests?state=
describe 'GET /requests?state=notified' do
before { get "#{api_version}/requests?state=notified" }
it 'returns requests' do
expect(json).not_to be_empty
expect(json.size).to eq(2)
end
it 'returns status code 200' do
expect(response).to have_http_status(200)
end
end
# Test suite for GET /requests?decision=
describe 'GET /requests?decision=approved' do
before { get "#{api_version}/requests?decision=approved" }
it 'returns requests' do
expect(json).not_to be_empty
expect(json.size).to eq(2)
end
it 'returns status code 200' do
expect(response).to have_http_status(200)
end
end
# Test suite for GET /requests/:id
describe 'GET /requests/:id' do
before { get "#{api_version}/requests/#{id}" }
context 'when the record exist' do
it 'returns the request' do
expect(json).not_to be_empty
expect(json['id']).to eq(id)
end
it 'returns status code 200' do
expect(response).to have_http_status(200)
end
end
context 'when request does not exist' do
let!(:id) { 0 }
it 'returns status code 404' do
expect(response).to have_http_status(404)
end
it 'returns a not found message' do
expect(response.body).to match(/Couldn't find Request/)
end
end
end
# Test suite for POST /workflows/:workflow_id/requests
describe 'POST /workflows/:workflow_id/requests' do
let(:item) { { 'disk' => '100GB' } }
let(:valid_attributes) { { :requester => '1234', :name => 'Visit Narnia', :content => JSON.generate(item) } }
context 'when request attributes are valid' do
before { post "#{api_version}/workflows/#{workflow_id}/requests", :params => valid_attributes }
it 'returns status code 201' do
expect(response).to have_http_status(201)
end
end
end
end
|
class Ability
include CanCan::Ability
def initialize(user)
can :read, :all
if user
can :create, :all
can [:update, :destroy], Post do |post|
post.nil? ? false : post.user == user
end
end
end
end
|
class AddBodyWeightToSports < ActiveRecord::Migration[5.1]
def change
add_column :sports, :body_weight, :string
end
end
|
class AddColumnToStockHolds < ActiveRecord::Migration[5.0]
def change
add_column :stock_holds, :stock_type, :string
add_column :stock_holds, :stock_name, :string
end
end
|
# Author: Hiroshi Ichikawa <http://gimite.net/>
# The license of this source is "New BSD Licence"
require "rubygems"
require "oauth2"
module GoogleDrive
class OAuth2Fetcher #:nodoc:
class Response
def initialize(raw_res)
@raw_res = raw_res
end
def code
return @raw_res.status.to_s()
end
def body
return @raw_res.body
end
def [](name)
return @raw_res.headers[name]
end
end
def initialize(oauth2_token)
@oauth2_token = oauth2_token
end
def request_raw(method, url, data, extra_header, auth)
if method == :delete || method == :get
raw_res = @oauth2_token.request(method, url, {:headers => extra_header})
else
raw_res = @oauth2_token.request(method, url, {:headers => extra_header, :body => data})
end
return Response.new(raw_res)
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.