text stringlengths 10 2.61M |
|---|
class ProductCategory < ActiveHash::Base
self.data = [
{ id: 0, date: '--' },
{ id: 1, date: 'レディース' },
{ id: 2, date: 'メンズ' },
{ id: 3, date: 'ベビィ・キッズ' },
{ id: 4, date: 'インテリア・住まい・小物' },
{ id: 5, date: '本・音楽・ゲーム' },
{ id: 6, date: 'おもちゃ・ボビー・グッズ' },
{ id: 7, date: '家電・スマホ・カメラ' },
{ id: 8, date: 'スポーツ・メジャー' },
{ id: 9, date: 'ハンドメイド' },
{ id: 10, date: 'その他' }
]
include ActiveHash::Associations
has_many :items
end
|
# frozen_string_literal: true
require 'csv'
require 'pry'
namespace :sync_users do
# Check how many accounts needed to be fixed in the last month.
# Iterate through the users in the Sierra CSV.
# For each user, see if they exist in the MLN database.
# If they do, and if the MLN user was created within the last month, while the Sierra user has been there for longer than that,
# then this is a user account manually fixed by the Library Outreach team.
# call like this: RAILS_ENV=local rake check_user_fixes:check_mismatch['data/private/20181128_sierra_mln_user_accounts.csv',2,1,'23333090060508']
desc "Check manually made account fixes"
task :check_user_fixes, [:file_name, :start, :limit, :barcode] => :environment do |t, args|
# if barcode is set, then only checks that barcode for Sierra-MLN mismatch
args.with_defaults(:file_name => nil, :start=> 0, :limit => 0, :barcode => nil)
csv_start = args.start.to_i
csv_limit = args.limit.to_i
csv_barcode = args.barcode
# Example: 'data/private/20181128_sierra_mln_user_accounts.csv'
csv_path = args.file_name
# \u03EA is a unicode character that will never happen in our Sierra output file.
# we need this, because the Sierra output has some junk data that's making the CSV gem trip up.
# however, this means that we'll now need to strip the double quotes from around the ingested field values ourselves.
CSV.foreach(csv_path, col_sep: "|", quote_char: "\u03EA") do |line|
# don't process the header row
next if $. == 1
# if we're only reading a few lines of the csv, then see if we can stop, before reading any further
next if (csv_start.positive? && $. < csv_start)
break if (csv_limit.positive? && $. >= (csv_start + csv_limit))
# "P BARCODE"|"EMAIL ADDR"|"PIN"|"EXP DATE"|"PCODE3"|"P TYPE"|"TOT CHKOUT"|"HOME LIBR"|"MBLOCK"|"PCODE4"|"PATRN NAME"|"ADDRESS"|
# "CREATED(PATRON)"|"UPDATED(PATRON)"
# Example: "23333106701234"|"name@gmail.com"|"Tn/jC7sHXQpfw"|"10-01-2018"|"1"|"153"|"4"|"ea "|"-"|"895"|"LASTNAME, FIRSTNAME"|"123
# MAIN ST, NY 10001"|"05-20-2009 15:23"|"07-02-2018"
(barcode, email, pin, expiration, pcode3, ptype, total_checkouts, home_library, manual_block, pcode4, name, address, sierra_created,
sierra_updated) = line
# inore bad data, and move on to the next line
next if (barcode.nil?)
# clean off any leading/trailing spaces and double quotes
barcode = barcode.strip.downcase
barcode = barcode.chomp('"').reverse.chomp('"').reverse
sierra_created = sierra_created.chomp('"').reverse.chomp('"').reverse
# if a barcode was passed, we're looking for that barcode, and should stop processing once we find it.
if (!csv_barcode.present? && csv_barcode == barcode)
csv_start = $.
csv_limit = 1
end
# is there a user in the mln database that matches this user from Sierra?
mln_user = User.find_by_barcode(barcode)
# Yes, there is. Now see if the user was created in MLN over the last month, while being old in Sierra.
# was the user created after a month ago in mln database?
if !mln_user.present? && (mln_user.created_at > 1.month.ago)
begin
date_sierra_created = DateTime.strptime(sierra_created, '%m-%d-%Y %H:%M')
# was the user created before a month ago in Sierra?
if (date_sierra_created < 1.month.ago)
puts "manually repaired user=#{barcode}, mln_user.id=#{mln_user.id}, mln_user.created_at=#{mln_user.created_at},
mln_user.updated_at=#{mln_user.updated_at}, sierra_created=#{sierra_created}, sierra_updated=#{sierra_updated}"
end
rescue => e
puts "broke: #{e}"
end
end
end #foreach sierra row
end #check_user_fixes
## NOTE: This method is not complete. We're abandoning the task, until we can be sure it's warranted.
# We think it may not be warranted, based on the output of the check_user_fixes task.
#
# Check how many accounts are in Sierra, but not in MLN.
# Iterate through the users in the Sierra CSV.
# For each user, see if they exist in the MLN database.
# If they do not, then output the user, so we can review them later.
# TODO: later functionality -- write to db a new user.
# call like this: RAILS_ENV=local rake sync_users:ingest_mismatched_sierra_users['data/private/20181128_sierra_mln_user_accounts.csv',2,1,
# '23333090060508']
# @param safetyoff -- manually set this in the task call, to really truly write to the DB (a destructive change)
desc "Check and Automatically Fix Sierra-MLN mismatch"
task :ingest_mismatched_sierra_users, [:file_name, :start, :limit, :barcode, :safetyoff] => :environment do |t, args|
puts "ingest_mismatched_sierra_users begin"
# if barcode is set, then only checks that barcode for Sierra-MLN mismatch
args.with_defaults(:file_name => nil, :start=> 0, :limit => 0, :barcode => nil, :safetyoff => false)
safetyoff = args.safetyoff
csv_start = args.start.to_i
#start = 1 if start == 0 # don't think I have to do this, since I have defaults
csv_limit = args.limit.to_i
#limit = 1 if limit == 0
csv_barcode = args.barcode
# Example: 'data/private/20181128_sierra_mln_user_accounts.csv'
csv_path = args.file_name
mln_fixed_users = []
# \u03EA is a unicode character that will never happen in our Sierra output file.
# we need this, because the Sierra output has some junk data that's making the CSV gem trip up.
# however, this means that we'll now need to strip the double quotes from around the ingested field values ourselves.
CSV.foreach(csv_path, col_sep: "|", quote_char: "\u03EA") do |line|
#puts "current_line_num=#{$.}, csv_start=#{csv_start}, limit=#{csv_limit}"
# don't process the header row
next if $. == 1
# if we're only reading a few lines of the csv, then see if we can stop, before reading any further
next if (csv_start.positive? && $. < csv_start)
break if (csv_limit.positive? && $. >= (csv_start + csv_limit))
# "P BARCODE"|"EMAIL ADDR"|"PIN"|"EXP DATE"|"PCODE3"|"P TYPE"|"TOT CHKOUT"|"HOME LIBR"|"MBLOCK"|"PCODE4"|"PATRN NAME"
# |"ADDRESS"|"CREATED(PATRON)"|"UPDATED(PATRON)"
# Example: "23333106701234"|"name@gmail.com"|"Tn/jC7sHXQpfw"|"10-01-2018"|"1"|"153"|"4"|"ea "|"-"|"895"|"LASTNAME,
# FIRSTNAME"|"123 MAIN ST, NY 10001"|"05-20-2009 15:23"|"07-02-2018"
(barcode, email, pin, expiration, pcode3, ptype, total_checkouts, home_library, manual_block, pcode4, name, address, sierra_created,
sierra_updated) = line
# inore bad data, and move on to the next line
next if (barcode.nil?)
# clean off any leading/trailing spaces and double quotes
barcode = barcode.strip.downcase
barcode = barcode.chomp('"').reverse.chomp('"').reverse
sierra_created = sierra_created.chomp('"').reverse.chomp('"').reverse
# if a barcode was passed, we're looking for that barcode, and should stop processing once we find it.
if (!csv_barcode.nil? && csv_barcode == barcode)
csv_start = $.
csv_limit = 1
end
# is there a user in the mln database that matches this user from Sierra?
mln_user = User.find_by_barcode(barcode)
if mln_user.nil?
# there isn't. now then, we might not be finding this user because of garbled or bad data in the Sierra
# output csv. output the user, and let the human investigate.
puts "user=#{barcode}, sierra_created=#{sierra_created}, sierra_updated=#{sierra_updated}, email=#{email}"
# Create a user in the MLN db to match the user from Sierra
end
end #for each Sierra row
end #check_mismatch task
end #namespace
|
require '../lib/reqs'
# 1
#Given any state, first print out the senators for that state (sorted by last name)
#then print out the representatives (also sorted by last name).
#Include the party affiliation next to the name.
STATE = 'MN'
senators = CongressMember.where({:state => STATE, :title => 'Sen'})
reps = CongressMember.where({:state => STATE, :title => 'Rep'})
puts 'Senators:'
senators.sort{|a,b| a.lastname <=> b.lastname}.each do |sen|
puts "#{sen.firstname} #{sen.lastname} (#{sen.party})"
end
puts 'Representatives:'
reps.sort{|a,b| a.lastname <=> b.lastname}.each do |rep|
puts "#{rep.firstname} #{rep.lastname} (#{rep.party})"
end
# 2
# Given a gender, print out what number and percentage of the senators are of that gender
# as well as what number and percentage of the representatives
# being sure to include only those congresspeople who are actively in office
GENDER = 'F'
all_sen_in_office = CongressMember.where({:in_office => true, :title => 'Sen'})
all_sen_in_office_of_gender = all_sen_in_office.select{|s| s.gender == GENDER}
num_sen = all_sen_in_office.length
num_sen_gender = all_sen_in_office_of_gender.length
puts "#{GENDER} Senators: #{num_sen_gender} (#{(num_sen_gender.to_f / num_sen.to_f * 100).to_i}%)"
all_rep_in_office = CongressMember.where({:in_office => true, :title => 'Rep'})
all_rep_in_office_of_gender = all_rep_in_office.select{|s| s.gender == GENDER}
num_rep = all_rep_in_office.length
num_rep_gender = all_rep_in_office_of_gender.length
puts "#{GENDER} Representatives: #{num_rep_gender} (#{(num_rep_gender.to_f / num_rep.to_f * 100).to_i}%)"
# 3
# Print out the list of states along with how many active senators and representatives,
# in descending order
states = CongressMember.all.map{|c| c.state}.uniq
states_and_nums = states.map do |s|
[
s,
CongressMember.where({:state => s, :title => 'Sen', :in_office => true}).length,
CongressMember.where({:state => s, :title => 'Rep', :in_office => true}).length
]
end
states_and_nums.sort!{|b,a| a[1]+a[2] <=> b[1]+b[2]}
states_and_nums.each do |s_a_n|
puts "#{s_a_n[0]}: #{s_a_n[1]} Senators, #{s_a_n[2]} Representative(s)"
end
# 4
# For Senators and Representatives, count the total number of each
# (regardless of whether or not they are actively in office).
puts "Senators: #{CongressMember.where({:title => 'Sen'}).length}"
puts "Representatives: #{CongressMember.where({:title => 'Rep'}).length}"
# 5
# Now use ActiveRecord to delete from your database any congresspeople
# who are not actively in office,
# then re-run your count to make sure that those rows were deleted
CongressMember.delete_all(["in_office = ?", false])
|
class CreateRoleRankDetails < ActiveRecord::Migration[5.2]
def up
create_table :role_rank_details do |t|
t.integer "role_rank_id" #Role Rank ID
t.integer "role_id" #Role ID
t.integer "sort_order" #Ranking order of the roles
t.timestamps #audit
end
end
def down
drop_table :role_rank_details
end
end
|
Rails.application.routes.draw do
get 'shifts/index'
devise_for :users
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :teams do
member do
post :add_member
get :remove_member
end
end
resources :shifts do
collection do
get :get_users
end
end
root 'teams#index'
end
|
module ContactsHelper
def initialize_contact(contact)
@contact = contact || current_account.contacts.build
@contact.emails.build if @contact.emails.empty?
@contact.websites.build if @contact.websites.empty?
@contact.phones.build if @contact.phones.empty?
@contact.addresses.build if @contact.addresses.empty?
@contact
end
def phone_icon(phone)
icon = image_tag("/images/icons/" + case phone.kind
when 'cell' then 'phone.png'
when 'skype' then 'skype.png'
else 'telephone.png'
end, :class => :icon)
end
def contacts
@contacts = (@contacts || @people || @organizations)
end
end
|
require 'integration_helper'
require_relative 'classic_app.rb'
RSpec.describe 'Sinatra Classic app integration', type: :integration do
include Yaks::Sinatra::Test::ClassicApp::Helpers
::Yaks::Format.all.each do |format|
context "For #{format.format_name}" do
it "returns 200" do
make_req(format.media_type)
expect(last_response).to be_ok
end
it "respects the Accept header" do
make_req(format.media_type)
expect(last_content_type.type).to eq(format.media_type)
end
it "returns an explicit charset" do
make_req(format.media_type)
expect(last_content_type.charset).to eq('utf-8')
end
end
end
end
|
require 'data_magic/standard_translation'
require 'faker'
module AddressBook
module Data
class Base < WatirModel
attr_accessor :id
end
class Defaults
include DataMagic::StandardTranslation
def self.translate(key)
return new.send(:characters, 10) if key == :password
new.send(key)
end
end
end
end
|
class RemoveDefaultStatusFromParticipant < ActiveRecord::Migration
def change
change_column_default :participants, :status, nil
end
end
|
=begin
3. Build-a-Quiz
1.) Build a quiz program that gets a few inputs from the user including:
1-number of questions
2-questions
3-answers
2.) Then clear the screen and begin the quiz. Keep score!
--------------------------------------------------------------------------------
def quiz_function
puts "How many questions would you like your quiz to have?"
puts "Please print a list like this e.g: 1,2,3,4"
questions = Array.new
user_input = gets.chomp.to_a
questions.insert(user_input)
end
puts "Would you like to make a quiz?"
answer = gets.chomp.downcase
if answer == "yes" || "yep"
quiz_function
else
puts "Oh well, maybe next time!"
end
--------------------------------------------------------------------------------
=end
def create_quiz
score = 0
quiz_hash = {}
puts "How many questions would you like?"
number = gets.chomp.to_i
number.times do
puts "Type your question"
q = gets.chomp
puts "Type your answer"
a = gets.chomp
quiz_hash[a] = q
end
system "clear"
quiz_hash.each do |answer, question|
puts question
response = gets.chomp
if response == answer
score += 1
puts "correct"
else puts "incorrect"
end
end
puts "You got #{score} out of #{number}"
end
create_quiz |
describe RunPlaybookService do
let(:release_order) { ReleaseOrder.first }
before(:each) do
allow(release_order.release).to receive(:playbook_dir).and_return './spec/services/temp_files'
allow(IO).to receive(:popen)
release_order.approved!
end
it 'should set release order status to deployed after proper deployment' do
service = RunPlaybookService.new(release_order, STDOUT)
service.run!
expect(release_order.deployed?).to be true
end
describe 'Release order result' do
it 'should create ReleaseOrderResult for every env' do
service = RunPlaybookService.new(release_order, STDOUT)
service.run!
expect(release_order.release_order_results.length).to eq 3
end
it 'should create ReleaseOrderResut with status :success' do
service = RunPlaybookService.new(release_order, STDOUT)
service.run!
results = release_order.release_order_results
expect(results.map(&:status)).to eq %w[failure failure success]
end
it 'should create ReleaseOrderResut with status :failure' do
allow(IO).to receive(:popen).and_raise(Exception)
service = RunPlaybookService.new(release_order, ['dev'], STDOUT)
service.run!
results = release_order.release_order_results
expect(results[0].status).to eq 'failure'
end
end
end
|
require_relative './client_generator.rb'
module Rockauth
class InstallGenerator < Rails::Generators::Base
source_root File.expand_path('../../templates', __FILE__)
desc 'Installs Rockauth'
def copy_initializer
template 'rockauth_full_initializer.rb', 'config/initializers/rockauth.rb'
end
def copy_locales
copy_file '../../../config/locales/en.yml', 'config/locales/rockauth.en.yml'
end
def copy_clients
copy_file 'rockauth_clients.yml', 'config/rockauth_clients.yml'
end
def generate_models
invoke 'rockauth:models'
end
def generate_migrations
invoke 'rockauth:migrations'
end
def generate_admin_pages
invoke 'rockauth:admin'
end
def generate_serializers
puts File.expand_path('../../../app/serializers/rockauth/*.rb', File.dirname(__FILE__))
Dir[File.expand_path('../../../app/serializers/rockauth/*.rb', File.dirname(__FILE__))].each do |f|
basename = File.basename(f)
copy_file f, "app/serializers/#{basename}"
gsub_file "app/serializers/#{basename}", 'module Rockauth', ''
gsub_file "app/serializers/#{basename}", /^end$/, ''
gsub_file "app/serializers/#{basename}", /^\s\s/, ''
end
end
def install_route
route <<ROUTE
scope '/api' do
rockauth 'User', registration: false, password_reset: true
end
ROUTE
end
def generate_development_client
invoke 'rockauth:client', ['Default Client'], environment: 'development'
end
def declare_dependencies
gem 'fb_graph2'
gem 'twitter'
gem 'google_plus'
gem 'instagram'
gem 'active_model_serializers', '~> 0.8.3'
end
end
end
|
require "attr_immutable/version"
module AttrImmutable
def self.included (base)
base.extend(ClassMethods)
end
module ClassMethods
def attr_immutable (*args)
args.each do |arg|
setter = "#{arg}=".to_sym
define_method(arg) do
self.attr_immutable(arg)
self.send(arg)
end
define_method(setter) do |value|
self.attr_immutable(arg)
self.send(setter, value)
end
end
end
end
def attr_immutable (arg)
attribute_set = false
attribute = nil
singleton_class = class << self
self
end
singleton_class.send(:define_method, arg) do
attribute
end
singleton_class.send(:define_method, "#{arg.to_s}=") do |value|
raise "ERROR: Attempt to modify an immutable attribute" if attribute_set
attribute_set = true
attribute = value
end
end
end
|
class ChangeTypeFieldCodeColor < ActiveRecord::Migration[6.1]
def change
change_column :colors, :code_color, :string
end
end
|
class AnnoncesController < ApplicationController
before_action :set_annonce, only: [:show, :edit, :update, :destroy]
# GET /annonces
# GET /annonces.json
def index
if current_user.email == "nohchi.eu@gmail.com"
@annonces = Annonce.all
else
redirect_to root_path, notice: 'Vam nelzya na etu stranicu'
end
end
# GET /annonces/1
# GET /annonces/1.json
def show
end
# GET /annonces/new
def new
if user_signed_in?
@annonce = Annonce.new
else
redirect_to new_user_session_path, notice: 'Для того чтобы создать объявление необходимо зарегистрироваться'
end
end
# GET /annonces/1/edit
def edit
end
# POST /annonces
# POST /annonces.json
def create
@annonce = current_user.annonces.build(annonce_params)
respond_to do |format|
if @annonce.save
format.html { redirect_to root_path :flash => {:notice => "объявление создано" }}
format.json { render :show, status: :created, location: @annonce }
else
format.html { render :new }
format.json { render json: @annonce.errors, status: :unprocessable_entity }
end
end
end
def mesannonces
@mesannonces = Kaminari.paginate_array(current_user.annonces).page(params[:page]).per(6)
end
# PATCH/PUT /annonces/1
# PATCH/PUT /annonces/1.json
def update
respond_to do |format|
if @annonce.update(annonce_params)
format.html { redirect_to @annonce,:flash => { :notice => "объявление обновлен" } }
format.json { render :show, status: :ok, location: @annonce }
else
format.html { render :edit }
format.json { render json: @annonce.errors, status: :unprocessable_entity }
end
end
end
# DELETE /annonces/1
# DELETE /annonces/1.json
def destroy
@annonce.destroy
respond_to do |format|
format.html { redirect_to annonces_moiobyavlenie_path, notice: 'объявление удалено' }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_annonce
@annonce = Annonce.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def annonce_params
params.require(:annonce).permit(:ville_depart, :ville_arrive, :date_depart, :nombre_chauffeurs, :nombre_place, :telephones, :marque_vehicule, :annee_vehicule, :prix_passager, :poid_max_passager, :accept_colis, :accept_colis_valeur, :prix_kg_colis, :poid_max_colis, :poid_min_colis, :arrets_chaque, :description, :image, :image2, :image3, :villeinter1, :villeinter2, :villeinter3, :villeinter4, :villeinter5, :villeinter6, :villeinter7, :villeinter8, :villeinter9, :villeinter10, :telephones2, :telephones3, :telephones4, :telephones5, :telephones_type1, :telephones_type2, :telephones_type3, :telephones_type4, :telephones_type5, :telephone_type1, :telephone_type2, :telephone_type3, :telephone_type4, :wifi, :chay)
end
end
|
class AddUserIdtoSpaces < ActiveRecord::Migration[5.0]
def change
remove_reference :spaces, :host, index: true
add_reference :spaces, :user, index: true
end
end
|
class Admin::GroupsController < ApplicationController
layout "admin"
def index
@groups = Group.all
respond_to do |format|
format.html # index.html.erb
format.js
end
end
def show
@group = Group.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.js
end
end
def new
@group = Group.new
respond_to do |format|
format.html # new.html.erb
format.js
end
end
def edit
@group = Group.find(params[:id])
respond_to do |format|
format.html # new.html.erb
format.js
end
end
def create
@group = Group.create(params[:group])
respond_to do |format|
if @group.save
format.html { redirect_to admin_groups_path, :notice=> 'Group was successfully created.' }
format.js
else
format.html { render :action=> "new" }
format.js
end
end
end
def update
@group = Group.find(params[:id])
respond_to do |format|
if @group.update_attributes(params[:group])
format.html { redirect_to admin_groups_path, :notice=> 'Group was successfully updated.' }
else
format.html { render :action=> "edit" }
format.js
end
end
end
def destroy
@group = Group.find(params[:id])
@group.destroy
@groups = Group.all
respond_to do |format|
format.html { redirect_to admin_groups_path }
format.js
end
end
end
|
require "sinatra"
require "json"
require_relative "model/enviador_de_mails"
configure do
set :bind, '0.0.0.0'
end
post '/' do
begin
entrada = request.body.read
if(entrada == "")
raise ExcepcionArchivoNoEncontrado
end
hash_entrada = JSON.parse(entrada)
sender = Enviador.new
sender.enviar(hash_entrada)
status 200
{"resultado" => "ok"}.to_json
rescue JSON::ParserError => e
status 400
{"resultado" => "La estructura del JSON pasado es incorrecta"}.to_json
rescue ExcepcionJSONIncompleto => e
status 400
{"resultado" => "Error en el JSON pasado"}.to_json
rescue ExcepcionServidorSMTPNoLevantado => e
status 500
{"resultado" => "Error, el servidor SMTP esta caido"}.to_json
rescue Encoding::CompatibilityError => e
status 400
{"resultado" => "Error de compatibilidad"}.to_json
rescue ExcepcionArchivoNoEncontrado
status 400
{"resultado" => "El archivo no pudo encontrarse"}.to_json
end
end
|
describe "NdcTree::Node#output" do
it "returns true when output format is not String" do
tree = NdcTree << %w{ 913.6 400 713 }
tree.print_image(:png=>"test.png").should == true
end
it "returns binary data when output format is String" do
tree = NdcTree << %w{ 913.6 400 713 }
tree.print_image(:png=>String).should be_instance_of String
end
end
|
class Garage < ApplicationRecord
has_many :vehicles, dependent: :destroy
validates :name, presence: true,
length: { minimum: 3 }
end
|
class MemberAbility < BaseAbility
def initialize(user)
can :manage, User, id: user.id
cannot :show, :admin_controllers
cannot :show, :admin_dashboard
can :show, :member_dashboard
can :manage, List, user_id: user.id
can :manage, Santa
end
end
|
class RemoveContentAttributeFromBundleModel < ActiveRecord::Migration
def self.up
remove_column "bundles", :content
end
def self.down
add_column "bundles", :content, :text, :limit => 16777215 # 16MB
end
end
|
class DownloadsController < ApplicationController
require 'ntpumis_logger'
before_action :authenticate_user!, only: [:new, :index, :show, :edit, :create, :update, :destroy]
before_action :find_download, only:[:edit, :update, :destroy]
DOWNLOAD_TYPE={
:enrollment => "招生簡介",
:newspaper => "資管所通訊",
:examination => "歷屆考題",
:domestic => "常用表單",
:course => "課程資訊"
}
def index
NTPUMIS_Logger.log(NTPUMIS_Logger::LOG_INFO, "#{self.controller_name}##{self.action_name}", nil)
@downloads_enrollment = []
@downloads_newspaper = []
@downloads_examination = []
@downloads_domestic = []
@downloads_course = []
downloads = Download.order("created_at DESC").all
downloads.each do |d|
if d.file_type == "enrollment"
@downloads_enrollment << d
elsif d.file_type == "newspaper"
@downloads_newspaper << d
elsif d.file_type == "examination"
@downloads_examination << d
elsif d.file_type == "domestic"
@downloads_domestic << d
elsif d.file_type == "course"
@downloads_course << d
end
end
end
def new
NTPUMIS_Logger.log(NTPUMIS_Logger::LOG_INFO, "#{self.controller_name}##{self.action_name}", nil)
@download = Download.new
@download_type = DOWNLOAD_TYPE.as_json
end
def create
NTPUMIS_Logger.log(NTPUMIS_Logger::LOG_INFO, "#{self.controller_name}##{self.action_name}", nil)
@download = Download.new(download_params)
@download.save
redirect_to :action => :index
flash[:notice] = "成功新增連結 [#{DOWNLOAD_TYPE.as_json[@download.file_type]}] #{@download.title}"
end
def edit
NTPUMIS_Logger.log(NTPUMIS_Logger::LOG_INFO, "#{self.controller_name}##{self.action_name}", nil)
@download_type = DOWNLOAD_TYPE.as_json
end
def update
NTPUMIS_Logger.log(NTPUMIS_Logger::LOG_INFO, "#{self.controller_name}##{self.action_name}", nil)
@download.update(download_params)
redirect_to :action => :index
flash[:notice] = "成功更新連結 [#{DOWNLOAD_TYPE.as_json[@download.file_type]}] #{@download.title}"
end
def destroy
NTPUMIS_Logger.log(NTPUMIS_Logger::LOG_INFO, "#{self.controller_name}##{self.action_name}", nil)
@download.destroy
redirect_to :action => :index
flash[:alert] = "成功刪除連結 #{@download.title}"
end
def list
NTPUMIS_Logger.log(NTPUMIS_Logger::LOG_INFO, "#{self.controller_name}##{self.action_name}", nil)
enrollment_arr = []
newspaper_arr=[]
examination_arr=[]
domestic_arr=[]
course_arr=[]
downloads = Download.order('created_at DESC').where("isShow = ?",true)
downloads.each do |d|
if d.file_type == "enrollment"
enrollment_arr << d
elsif d.file_type == "newspaper"
newspaper_arr << d
elsif d.file_type == "examination"
examination_arr << d
elsif d.file_type == "domestic"
domestic_arr << d
elsif d.file_type == "course"
course_arr << d
end
end
result={
:enrollment => enrollment_arr,
:newspaper => newspaper_arr,
:examination => examination_arr,
:domestic => domestic_arr,
:course => course_arr
}
render :json => result
end
private
def download_params
params.require(:download).permit(:file_type, :title, :link, :isShow)
end
def find_download
@download = Download.find(params[:id])
end
end
|
$: << File.join(File.dirname(__FILE__), 'lib')
require 'router'
CONFIG_FILE = File.join('config', 'config.rb')
CONFIG = eval(File.read(CONFIG_FILE), binding, CONFIG_FILE, 1) rescue \
raise(::ArgumentError, "Failed to read #{CONFIG_FILE}: #{$!}")
unless CONFIG[:session_secret] then
raise(::ArgumentError, "Set a :session_secret in #{CONFIG_FILE}")
end
unless CONFIG[:backend] then
raise(::ArgumentError, "Set a :backend in #{CONFIG_FILE}")
end
use Rack::Session::Cookie, :secret => CONFIG[:session_secret]
use Rack::ContentType, "text/html"
run ::Router.new(CONFIG)
|
require 'colorize'
namespace :git do
desc 'Update all git submodules to their current master tip'
task :update do
system('git submodule update --remote')
system(%{git submodule foreach -q --recursive 'branch="$(git config -f $toplevel/.gitmodules submodule.$name.branch)"; git checkout $branch' >/dev/null 2>&1})
end
end
namespace :gems do
desc "Run all examples of extracted gems indepently within their Bundler context"
task :spec do
results = llt_dirs.map do |dir|
run_in_directory(dir)
end
if results.all?
puts "#{results.count} tasks - All GREEN".colorize(:green)
else
failed = results.count { |result| result == false }
puts "#{failed} of #{results.count} tasks FAILED".colorize(:red)
end
end
desc 'Bundle update all gems'
task :bu do
llt_dirs.map do |dir|
run_in_directory(dir, 'bundle update')
end
end
desc 'Bundle install all gems'
task :bi do
llt_dirs.map do |dir|
run_in_directory(dir, 'bundle install')
end
end
end
desc 'Run a nailgun server as background job'
task :ng do
# nailgun falls when there are jruby opts defined
exec 'JRUBY_OPTS= jruby --ng-server'
end
task default: 'gems:spec'
class SpecFailed < StandardError; end
def run_in_directory(dir, command = 'rake')
res = Dir.chdir(dir) do
Bundler.with_clean_env do
system(command)
end
end
raise SpecFailed.new unless res
end
def llt_dirs
Dir.glob("llt*")
end
# One hidden rake task for every gem, used by guard-rake
llt_dirs.each do |dir|
task dir.to_sym do
run_in_directory(dir)
end
end
|
class Student
attr_reader :first_namem :last_name
@@all = []
def initialize(first_name)
@first_name = first_name
@@all << self
end
def self.all
@@all
end
def add_boating_test(test_name, status, instructor)
BoatingTest.new(self, test_name, status, instructor)
end
def self.find_student(first_name)
Student.all.select do |student|
student.first_name == self
end
end
def grade_percentage
passed_arrray = BoatingTest.all.select do |test|
test.test_status == 'passed'
end
failed_array = BoatingTest.all.select do |test|
test.test_status == 'failed'
end
total_array =
end
end
|
# frozen_string_literal: true
class CreateHoldChanges < ActiveRecord::Migration[4.2]
def change
create_table :hold_changes do |t|
t.integer :hold_id, :limit => 8
t.integer :admin_user_id, :limit => 8
t.string :status, :limit => 9
t.text :comment
t.timestamps
end
end
end
|
# frozen_string_literal: true
class ProfileController < ApplicationController
before_action :authenticate_user
def index
@user ||= current_user
load_form_data
render :index
end
def show
index
end
def photo
@user = current_user
@return_path = profile_index_path
render 'users/photo'
end
def save_image
@user = current_user
params.require(:imgBase64) =~ /^data:([^;]+);base64,(.*)$/
content = Base64.decode64(Regexp.last_match(2))
content_type = Regexp.last_match(1)
UserImage.transaction do
image = Image.create! user_id: current_user.id, name: "Foto #{Date.current}",
content_type: content_type, content_data: content, content_length: content.length,
width: params[:width], height: params[:height]
@user.user_images.create! image: image, rel_type: :profile
end
render plain: content.hash
end
def update
@user = current_user
if @user.update user_params
flash.notice = 'Profilen din er oppdatert.'
redirect_to edit_user_path(@user)
else
flash.now.alert = "En feil oppsto ved lagring av brukeren: #{@user.errors.full_messages.join("\n")}"
edit
end
end
private
def load_form_data
@groups =
Group.includes(:martial_art).order('martial_arts.name, groups.name').where(closed_on: nil).to_a
@groups |= @user.groups
@users = User.order(:first_name, :last_name, :email, :phone).to_a if admin?
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:name, :email, :phone, :first_name, :last_name, :address, :postal_code,
:male, :locale, :group_ids)
end
end
|
# frozen_string_literal: true
require_relative 'msgpack_migration_helper'
Sequel.migration do
helper = MsgpackMigrationHelper.new({
:dynflow_execution_plans => [:data],
:dynflow_steps => [:data]
})
up do
helper.up(self)
end
down do
helper.down(self)
end
end
|
class SessionController < ApplicationController
def new
redirect_to root_url if session[:user_id]
end
def create
if params[:username].empty? || params[:password].empty?
flash.now.alert = 'Username or password is empty'
render :new
else
user = User.find_by(username: params[:username])
if user
if user.fail_counter == 3
flash.now.alert = 'User is Bloqued'
render :new
else
if user.authenticate(params[:password])
session[:user_id] = user.id
user.update( fail_counter: 0)
redirect_to root_url
else
user.fail_counter += 1
user.save
flash.now.alert = 'Username or password is invalid'
render :new
end
end
else
flash.now.alert = 'Username or password is invalid'
render :new
end
end
end
def destroy
session[:user_id] = nil
redirect_to login_url, notice: 'Logged out!'
end
end
|
class Offer < ActiveRecord::Base
belongs_to :merchant
attr_accessible :name, :merchant_id
validates :name, presence: true, length: { minimum: 5 }
validates :merchant_id, presence: true
end
|
class Activity < ActiveRecord::Base
KINDS = %w(feed_entry mailing status_update)
belongs_to :team
has_many :comments, -> { ordered }, as: :commentable, dependent: :destroy
validates :content, :title, :team, presence: { if: ->(act) { act.kind == 'status_update' } }
delegate :students, to: :team
class << self
def with_kind(kind)
where(kind: kind)
end
def by_team(team_id)
where(team_id: team_id)
end
def ordered
order('published_at DESC, id DESC')
end
end
def to_param
"#{id}-#{title.to_s.parameterize}"
end
end
|
require File.expand_path('./lib/delve/version', File.dirname(__FILE__))
Gem::Specification.new do |g|
g.name = 'delve'
g.version = Delve.version
g.date = '2014-03-24'
g.summary = 'Roguelike library inspired by rot.js and libtcod'
g.description = 'Roguelike library inspired by rot.js and libtcod. Allows developers to get a jumpstart on their roguelike development, by running a single command to get started with an "@ walking around the world" demo.'
g.authors = ['Benny Hallett']
g.files = `git ls-files`.split($/)
g.bindir = 'bin'
g.executables << 'delve'
g.homepage = 'https://github.com/BennyHallett/delve'
g.license = 'BSD'
g.add_development_dependency('rake', '10.1.1')
g.add_development_dependency('minitest', '5.2.2')
g.add_development_dependency('mocha', '1.0.0')
g.add_runtime_dependency('perlin_noise', '0.1.2')
end
|
module Apohypaton
class ConfigException < StandardError
end
class Config
attr_accessor :url, :token, :enabled, :app_name, :deploy_env, :scheme
# tls also takes: client_cert: '', client_key: '', ca_file: ''
def initialize()
@url = URI(ENV['APOHYPATON_URL'] || 'consul://localhost')
@token = ENV['APOHYPATON_CONSUL_TOKEN']
@options = { ssl: { version: :TLSv1_2, verify: false } }
@enabled = true
@scheme = 'https'
configure_diplomat
end
def configure_diplomat
begin
Diplomat.configure do |c|
c.url = "#{@scheme}://#{@url.host}:#{@url.port}"
c.acl_token = @token
c.options = @options
end
rescue => e
raise Apohypaton::ConfigException.new(e.message)
end
end
def chroot(requested_env=nil)
requested_env ||= deploy_env
raise Apohypaton::ConfigException.new("Application name unspecified") if app_name.nil?
raise Apohypaton::ConfigException.new("Deployment environment unspecified") if requested_env.nil?
@app_name + "/" + requested_env
end
def deploy_env
@deploy_env ||= ENV['DEPLOY_ENV'] || ENV['RAILS_ENV']
end
def enabled?
@enabled
end
end
end
|
class Ability
include CanCan::Ability
def initialize user
user ||= User.new
can :manage, User
can :manage, Game
can :manage, Version
can :manage, Message
end
end
|
require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
class StorageTest < Test::Unit::TestCase
def test_basic_operations
@storage = Storage.instance(true)
@storage.flushdb
assert_nil @storage.get('foo')
@storage.set('foo', 'bar')
assert_equal 'bar', @storage.get('foo')
end
def test_redis_host_and_port
storage = Storage.send :new, url('127.0.0.1:6379')
assert_connection(storage)
end
def test_redis_url
storage = Storage.send :new, url('redis://127.0.0.1:6379/0')
assert_connection(storage)
end
def test_redis_unix
storage = Storage.send :new, url('unix:///tmp/redis_unix.6379.sock')
assert_connection(storage)
end
def test_redis_protected_url
assert_nothing_raised do
Storage.send :new, url('redis://user:passwd@127.0.0.1:6379/0')
end
end
def test_redis_malformed_url
assert_raise Storage::InvalidURI do
Storage.send :new, url('a_malformed_url:1:10')
end
end
def test_redis_url_without_scheme
assert_nothing_raised do
Storage.send :new, url('foo')
end
end
def test_redis_no_scheme
assert_nothing_raised do
Storage.send :new, url('backend-redis:6379')
end
end
def test_redis_unknown_scheme
assert_raise ArgumentError do
Storage.send :new, url('myscheme://127.0.0.1:6379')
end
end
def test_sentinels_connection_string
config_obj = {
url: 'redis://127.0.0.1:6379/0',
sentinels: ',redis://127.0.0.1:26379, , , 127.0.0.1:36379,'
}
conn = Storage.send :orig_new, Storage::Helpers.config_with(config_obj)
assert_sentinel_connector(conn.client)
assert_client_config(conn.client, url: config_obj[:url],
sentinels: [{ host: '127.0.0.1', port: 26379 },
{ host: '127.0.0.1', port: 36379 }])
end
def test_sentinels_connection_string_escaped
config_obj = {
url: 'redis://127.0.0.1:6379/0',
sentinels: 'redis://user:passw\,ord@127.0.0.1:26379 ,127.0.0.1:36379, ,'
}
conn = Storage.send :orig_new, Storage::Helpers.config_with(config_obj)
assert_sentinel_connector(conn.client)
assert_client_config(conn.client, url: config_obj[:url],
sentinels: [{ host: '127.0.0.1', port: 26379 },
{ host: '127.0.0.1', port: 36379 }])
end
def test_sentinels_connection_array_strings
config_obj = {
url: 'redis://127.0.0.1:6379/0',
sentinels: ['redis://127.0.0.1:26379 ', ' 127.0.0.1:36379', nil]
}
conn = Storage.send :orig_new, Storage::Helpers.config_with(config_obj)
assert_sentinel_connector(conn.client)
assert_client_config(conn.client, url: config_obj[:url],
sentinels: [{ host: '127.0.0.1', port: 26379 },
{ host: '127.0.0.1', port: 36379 }])
end
def test_sentinels_connection_array_hashes
config_obj = {
url: 'redis://127.0.1.1:6379/0',
sentinels: [ { host: '127.0.0.1', port: 26379 },
{},
{ host: '127.0.0.1', port: 36379 },
nil]
}
conn = Storage.send :orig_new, Storage::Helpers.config_with(config_obj)
assert_sentinel_connector(conn.client)
assert_client_config(conn.client, url: config_obj[:url],
sentinels: config_obj[:sentinels].compact.reject(&:empty?))
end
def test_sentinels_malformed_url
config_obj = {
url: 'redis://127.0.0.1:6379/0',
sentinels: 'redis://127.0.0.1:26379,a_malformed_url:1:10'
}
assert_raise Storage::InvalidURI do
Storage.send :new, Storage::Helpers.config_with(config_obj)
end
end
def test_sentinels_empty
['', []].each do |sentinels_val|
config_obj = {
url: 'redis://127.0.0.1:6379/0',
sentinels: sentinels_val
}
redis_cfg = Storage::Helpers.config_with(config_obj)
assert !redis_cfg.key?(:sentinels)
end
end
private
def assert_connection(client)
client.flushdb
client.set('foo', 'bar')
assert_equal 'bar', client.get('foo')
end
def assert_sentinel_connector(client)
connector = client.instance_variable_get(:@connector)
assert_instance_of Redis::Client::Connector::Sentinel, connector
end
def assert_client_config(client, host: nil, port: nil, url: nil, sentinels: nil)
raise "bad usage of #{__method__}" unless host || port || url
assert_equal client.port, port if port
assert_equal client.host, host if host
assert_equal client.options[:url], url if url
assert_equal client.options[:sentinels], sentinels if sentinels
end
def url(url)
Storage::Helpers.config_with(url: url)
end
end
|
class UserInvitationCode < ApplicationRecord
belongs_to :user
before_create :set_unique_code
def another_user_code?(user)
user_id != user.id
end
private
def set_unique_code
self.code = self.class.unique_code
end
def self.unique_code
code = generate_code
while exists?(code: code)
code = generate_code
end
code
end
def self.generate_code
"mogu-#{SecureRandom.hex(3)}"
end
end
|
require 'text/format'
require 'featurist/config'
class TextFormatter
def initialize output_filename, spec
@output_filename = output_filename
@spec = spec
@level = 0
@formatter = Text::Format.new
@formatter.columns = 60
@formatter.first_indent = 0
end
def run
# open the file
File::open @output_filename, 'w' do |file|
@output_file = file
# Deal with cover page -- nasty POC hack
if Featurist::Config.config.cover_page
10.times { @output_file << "\n" }
@output_file << " " + Featurist::Config.config.cover_page_project_name + "\n "
Featurist::Config.config.cover_page_project_name.length.times { @output_file << "-" }
@output_file << "\n\n "
@output_file << Featurist::Config.config.cover_page_narrative
10.times { @output_file << "\n" }
end
unwrap @spec.root
end
end
private
def unwrap section
render section
section.ordered_sections.each do |sub_node|
@level += 1
unwrap sub_node
end
@level -= 1
end
def render node
return if @level == 0
@level.times { @output_file << " " }
@output_file << "#{node.fully_qualified_id}. #{node.title}" unless @level == 0 #ignore root
@output_file << "\n" unless node.title.match /\n$/ #sometimes we need to force a newline after title
@formatter.left_margin = ( @level * 2 ) + node.fully_qualified_id.size + 3
@formatter.text = node.narrative
@output_file << @formatter.paragraphs
@output_file << "\n\n" # TODO: configurable section separator???
end
end
|
class Credential < ActiveRecord::Base
acts_as_paranoid
belongs_to :provider, inverse_of: :credentials
end
|
class TeachersController < ApplicationController
def index
@teachers = Teacher.all
render 'index.json.jbuilder'
end
#class Teacher has_many :courses, dependent: :destroy
#删除老师后,老师对应的课程也将删除
def destroy
begin
teacher = Teacher.find(params[:id])
teacher.destroy!
message = "删除成功"
rescue
message = "删除失败"
end
render json: {message: message}
end
end
|
module JsonSpec
module Matchers
class HaveJsonType
include JsonSpec::Helpers
include JsonSpec::Messages
def initialize(type)
@classes = type_to_classes(type)
end
def matches?(json)
@ruby = parse_json(json, @path)
@classes.any?{|c| c === @ruby }
end
def at_path(path)
@path = path
self
end
def failure_message_for_should
message_with_path("Expected JSON value type to be #{@classes.join(", ")}, got #{@ruby.class}")
end
def failure_message_for_should_not
message_with_path("Expected JSON value type to not be #{@classes.join(", ")}, got #{@ruby.class}")
end
def description
message_with_path(%(have JSON type "#{@classes.join(", ")}"))
end
private
def type_to_classes(type)
case type
when Class then [type]
when Array then type.map{|t| type_to_classes(t) }.flatten
else
case type.to_s.downcase
when "boolean" then [TrueClass, FalseClass]
when "object" then [Hash]
when "nil", "null" then [NilClass]
else [Module.const_get(type.to_s.capitalize)]
end
end
end
end
end
end
|
class AddIndexesToGcache < ActiveRecord::Migration
def change
add_index :gcaches, :input
end
end
|
# The Jak namespace
module Jak
# The MyAbility Class which is the child of JakAbility
class MyAbility < Jak::JakAbility
def initialize(resource, &block)
# Invoke Jak Ability methods
super do
instance_eval(&block) if block_given?
end
# This is the dynamic permission functionality
if resource.present?
@yielded_skopes.each do |skope|
if resource.respond_to?(:permissions, skope)
my_skope = Jak.skope_manager.find(skope)
if my_skope
if my_skope.limited
# Limited by Jak.tenant_id_column
tenant_id_column = "#{Jak.tenant_id_column}_id"
# Unrestricted Permissions
resource.permissions(skope).select { |k| k.restricted == false }.each do |permission|
# Check the resources permissions
if permission.klass.constantize.column_names.include?(tenant_id_column)
# Does this model have a tenant_id column in it...
can permission.action.to_sym, permission.klass.constantize, tenant_id_column.to_sym => resource.send(tenant_id_column)
else
# Is it the tenant itself?
can permission.action.to_sym, permission.klass.constantize, id: resource.send(tenant_id_column)
end
end
# Restricted Permissions
resource.permissions(skope).select { |k| k.restricted == true }.each do |permission|
# Check the resources permissions
if permission.klass.constantize.column_names.include?(tenant_id_column)
# Does this model have a tenant_id column in it...
can permission.action.to_sym, permission.klass.constantize, tenant_id_column.to_sym => resource.send(tenant_id_column), permission.klass.constantize.my_frontend_restrictions.to_sym => resource.id
else
# Is it the tenant itself?
can permission.action.to_sym, permission.klass.constantize, id: resource.send(tenant_id_column)
end
end
else
# Unlimited power!
resource.permissions(skope).each do |permission|
can permission.action.to_sym, permission.klass.constantize
end
end
else
# 360 no skope
raise NotImplementedError, "Skope: #{skope} was not found!"
end
end
end
end # end resource.present?
end # end initialize
end
end
|
class Api::Admin::StatisticsController < Api::BaseController
def show
statistics = StatisticsService.new({current_user: current_user}).call
json_response({ data: statistics})
end
end
|
require 'rubygems'
require File.join(File.dirname(__FILE__), '../lib/isotope')
describe Isotope do
before :all do
@articles = dummy_articles
@template_file = File.join(File.dirname(__FILE__), "article.ejs")
end
it "should output a js template" do
s = Isotope.render_template(@template_file, :id => "hello")
s.should_not be_nil
s.strip.gsub(/\t| {2,}/, "").should eql('
<script type="text/x-isotope" id="hello"><h2><%=item.title%></h2>
<div class="content">
<%=item.content%>
</div>
<ul class="tags">
<%item.tags.forEach(function (tag) {%>
<li><%=tag.name%></li>
<%});%>
</ul></script>'.strip.gsub(/\t| {2,}/, "")
)
end
it "should render articles" do
evaluated_content = Isotope.render_partial(@template_file, :locals => { :item => @articles[0] })
expected_content = '
<h2>Hello!</h2>
<div class="content">
World!
</div>
<ul class="tags">
<li>tag 1</li>
<li>tag 2</li>
<li>tag 3</li>
<li>tag 4</li>
</ul>
'
# white spaces are not important to equalize
evaluated_content.gsub(/\s/, "").should eql(expected_content.gsub(/\s/, ""))
end
it "should render an array of articles" do
evaluated_content = Isotope.render_partial(@template_file, :collection => @articles, :delimeter => "<hr/>")
expected_content = '
<h2>Hello!</h2>
<div class="content">
World!
</div>
<ul class="tags">
<li>tag 1</li>
<li>tag 2</li>
<li>tag 3</li>
<li>tag 4</li>
</ul>
<hr/>
<h2>Hello 2!</h2>
<div class="content">
World 2!
</div>
<ul class="tags">
<li>tag 5</li>
<li>tag 6</li>
<li>tag 7</li>
<li>tag 8</li>
</ul>
'
evaluated_content.gsub(/\s/, "").should eql(expected_content.gsub(/\s/, ""))
end
end
def dummy_articles
[
{
:title => "Hello!",
:content => "World!",
:tags => [
{:name => "tag 1"},
{:name => "tag 2"},
{:name => "tag 3"},
{:name => "tag 4"}
]
},
{
:title => "Hello 2!",
:content => "World 2!",
:tags => [
{:name => "tag 5"},
{:name => "tag 6"},
{:name => "tag 7"},
{:name => "tag 8"}
]
}
]
end |
module Ricer::Plugins::Channel
class Kick < Ricer::Plugin
trigger_is :kick
scope_is :channel
permission_is :halfop
has_setting name: :kickjoin, type: :boolean, scope: :channel, permission: :operator, default: false
has_usage :execute, '<user>'
def execute(user)
reply "Trying to kick #{user.name}"
server.send_kick(user)
end
def on_kick
if get_setting(:kickjoin)
server.connection.send_join(current_message, channel.name)
end
end
end
end |
# frozen_string_literal: true
require 'entities/product'
require 'services/application_service'
module Services
module Products
class UpdateProductStock < ApplicationService
include Import[
'contracts.products.update_product_stock_contract',
'repos.product_repo',
]
option :product, Dry::Types().Instance(Entities::Product)
option :quantity_to_stock, Dry::Types['strict.integer']
def call
validation_result = validate
if validation_result.success?
product_repo.update(product.id, validation_result.to_h)
else
validation_result
end
end
private
def unvalidated_params
{ quantity_in_stock: product.quantity_in_stock + quantity_to_stock }
end
def validate
update_product_stock_contract.call(unvalidated_params)
end
end
end
end
|
class ChangeFieldsToEvent < ActiveRecord::Migration
def change
change_column :events, :price, :decimal
end
end
|
class MassObject
def self.set_attrs(*attributes)
@attributes = []
attributes.each do |att|
attr_accessor att
@attributes << att
end
end
def self.attributes
@attributes
end
def self.parse_all(results)
results.map do|row_hash|
new(row_hash)
end
end
def initialize(params = {})
params.each do |attr_name, value|
if self.class.attributes.include?(attr_name.to_sym)
send("#{attr_name}=",value)
else
raise "mass assignment to unregistered attribute #{attr_name}!"
end
end
end
private
def self.new_attr_accessor(*attrs)
attrs.each do |attr|
define_method(attr) do
instance_variable_get(:@attr)
end
define_method("#{attr.to_s}=") do |new_val|
instance_variable_set(:@attr, new_val)
end
end
end
end
class NewClass < MassObject
set_attrs :x, :y
end
|
# == Schema Information
#
# Table name: structure_profiles
#
# id :bigint not null, primary key
# structure_id :bigint
# profile_id :bigint
# status :string
# created_at :datetime not null
# updated_at :datetime not null
#
class StructureProfile < ApplicationRecord
belongs_to :structure
belongs_to :profile
end
|
RSpec.describe Yaks::Mapper::Association do
include_context 'yaks context'
let(:association_class) {
Class.new(described_class) do
def map_resource(_object, _context)
end
end
}
subject(:association) do
association_class.new(
name: name,
item_mapper: mapper,
rel: rel,
href: href,
link_if: link_if,
if: self.if
)
end
let(:name) { :shoes }
let(:mapper) { Yaks::Mapper }
let(:rel) { Yaks::Undefined }
let(:href) { Yaks::Undefined }
let(:link_if) { Yaks::Undefined }
let(:if) { Yaks::Undefined }
its(:name) { should equal :shoes }
its(:item_mapper) { should equal Yaks::Mapper }
context 'with a minimal constructor' do
subject(:association) { association_class.new(name: :foo) }
its(:name) { should be :foo }
its(:item_mapper) { should be Yaks::Undefined }
its(:rel) { should be Yaks::Undefined }
its(:href) { should be Yaks::Undefined }
its(:link_if) { should be Yaks::Undefined }
end
let(:parent_mapper_class) { Yaks::Mapper }
let(:parent_mapper) { parent_mapper_class.new(yaks_context) }
describe '#add_to_resource' do
let(:object) { fake(shoes: []) }
let(:rel) { 'rel:shoes' }
before do
parent_mapper.call(object)
stub(association).map_resource(any_args) { Yaks::Resource.new }
end
it 'should delegate to AssociationMapper' do
expect(association.add_to_resource(Yaks::Resource.new, parent_mapper, yaks_context)).to eql Yaks::Resource.new(subresources: [Yaks::Resource.new(rels: ['rel:shoes'])])
end
context 'with a truthy condition' do
let(:if) { ->{ true } }
it 'should add the association' do
expect(association.add_to_resource(Yaks::Resource.new, parent_mapper, yaks_context).subresources.length).to be 1
end
end
context 'without a condition' do
it 'should add the association' do
expect(association.add_to_resource(Yaks::Resource.new, parent_mapper, yaks_context).subresources.length).to be 1
end
end
context 'with a falsey condition' do
let(:if) { ->{ false } }
it 'should not add the association' do
expect(association.add_to_resource(Yaks::Resource.new, parent_mapper, yaks_context).subresources.length).to be 0
end
end
end
describe '#render_as_link?' do
let(:href) { '/foo/{bar}/baz' }
let(:link_if) { -> { env.fetch('env_entry') == 123 } }
let(:rack_env) { {'env_entry' => 123} }
let(:render_as_link?) { association.render_as_link?(parent_mapper) }
context 'when evaluating to true' do
it 'should resolve :link_if in the context of the mapper' do
expect(render_as_link?).to be true
end
end
context 'when evaluating to false' do
let(:rack_env) { {'env_entry' => 0} }
it 'should resolve :link_if in the context of the mapper' do
expect(render_as_link?).to be false
end
end
context 'with an Undefined href' do
let(:href) { Yaks::Undefined }
it 'should return falsey' do
expect(render_as_link?).to be_falsey
end
end
context 'with an Undefined link_if' do
let(:link_if) { Yaks::Undefined }
it 'should return falsey' do
expect(render_as_link?).to be_falsey
end
end
end
describe '#map_rel' do
let(:association_rel) { association.map_rel(policy) }
context 'with a rel specified' do
let(:rel) { 'http://api.com/rels/shoes' }
it 'should use the specified rel' do
expect(association_rel).to eql 'http://api.com/rels/shoes'
end
end
context 'without a rel specified' do
before do
stub(policy).derive_rel_from_association(association) {
'http://api.com/rel/derived'
}
end
it 'should infer a rel based on policy' do
expect(association_rel).to eql 'http://api.com/rel/derived'
end
end
end
describe '#resolve_association_mapper' do
context 'with a specified mapper' do
let(:mapper) { :a_specific_mapper_class }
it 'should return the mapper' do
expect(association.resolve_association_mapper(nil)).to equal :a_specific_mapper_class
end
end
context 'with the mapper undefined' do
let(:mapper) { Yaks::Undefined }
before do
stub(policy).derive_mapper_from_association(association) {
:a_derived_mapper_class
}
end
it 'should derive a mapper based on policy' do
expect(association.resolve_association_mapper(policy)).to equal :a_derived_mapper_class
end
end
end
describe '.create' do
it 'should take a name' do
expect(association_class.create(:foo).name).to be :foo
end
it 'should optionally take a mapper' do
expect(association_class.create(:foo, mapper: :bar).item_mapper).to be :bar
end
it 'should take other options' do
expect(association_class.create(:foo, mapper: :bar, href: 'xxx').href).to eql 'xxx'
end
it 'should respect attribute defaults' do
expect(association_class.create(:foo, href: 'xxx').item_mapper).to be Yaks::Undefined
end
it 'should not munge the options hash' do
opts = {mapper: :foo}
association_class.create(:foo, opts)
expect(opts).to eql(mapper: :foo)
end
end
end
|
require 'rails_helper'
RSpec.describe Package, type: :model do
let (:shipment_item) { FactoryGirl.create(:shipment_item) }
let (:attributes) do
{
shipment_item_id: shipment_item.id,
package_id: 'ABC123',
tracking_number: 'DEF456',
quantity: 1,
weight: 5.23
}
end
it 'can be created with valid attributes' do
package = Package.new attributes
expect(package).to be_valid
end
describe '#shipment_item_id' do
it 'is required' do
package = Package.new attributes.except(:shipment_item_id)
expect(package).to have_at_least(1).error_on :shipment_item_id
end
end
describe '#shipment_item' do
it 'is a reference to the shipment item to which the package belongs' do
package = Package.new attributes
expect(package.shipment_item).to eq shipment_item
end
end
end
|
class TransfersController < ApplicationController
before_action :set_transfer, only: [:show]
# GET /transfers
# GET /transfers.json
def index
@transfers = Transfer.all
end
# GET /transfers/1
# GET /transfers/1.json
def show
if @transfer.transferaccounts[1].account_id != current_account.id
redirecionar_usuario_logado
end
end
# GET /transfers/new
def new
@transfer = Transfer.new
@transfer.transferaccounts.build
end
# POST /transfers
# POST /transfers.json
def create
ActiveRecord::Base.transaction do
@transfer = Transfer.new(transfer_params)
@transfer = Transfer.new(transfer_params)
@transferaccount = @transfer.transferaccounts.build
@transferaccount.account_id = current_account.id
respond_to do |format|
if @transfer.save
format.html { redirect_to @transfer }
format.json { render :show, status: :created, location: @transfer }
else
format.html { render :new }
format.json { render json: @transfer.errors, status: :unprocessable_entity }
end
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_transfer
@transfer = Transfer.find(params[:id])
end
# Only allow a list of trusted parameters through.
def transfer_params
params.require(:transfer).permit(:valor, :taxa, transferaccounts_attributes: [:id, :operacao, :account_id, :_destroy])
end
end
|
# Create an ATM Application
# Create a class called Account
# Initialize should take on 3 attributes: name, balance, pin
# Create 4 additional methods: display_balance, withdraw, deposit, and pin_error.
# The user should be prompted to enter their pin anytime they call display_balance, withdraw, or deposit.
# pin_error should contain "Access denied: incorrect PIN." and be puts when the user types the wrong pin.
class Account
def initialize(name, balance, pin)
@name = name
@balance = balance
@pin = pin
end
# not sure if I have to define these methods (line 18-28)
def name
@name
end
def balance
@balance
end
def pin
@pin
end
def display_balance
puts @balance
end
def withdraw(wd)
@balance -= wd
end
def deposit(dep)
@balance += dep
end
def pin_error(pn)
@pin != pn # might not need this if it's determined in if statements that it does not match
puts 'Access denied: incorrect PIN.'
end
end
# all_customers = []
customer = Account.new('Bill Jones', 10000, '1234')
# all_customers.push(customer)
# customer = Account.new('Sally Reynolds', 55000, '4321')
# all_customers.push(customer)
# customer = Account.new('Fred Thomas', 249000, '1965')
# all_customers.push(customer)
puts "Hello. What is your name?" # not sure how to compare name to what's on file
# could not figure out how to ask and verify PIN before individual transactions so trying to get PIN first
puts "Welcome, #{customer.name}. Please enter your PIN."
pn = gets.chomp.to_s
if pn == pin
puts 'What would you like to do? To receive your balance, type balance.
To make a deposit, type deposit. To make a withdrawal, type withdraw.'
else
pin_error
end
transaction = gets.chomp.downcase
if transaction == 'balance'
display_balance
elsif transaction == 'deposit'
puts 'How much would you like to deposit today?'
dep = gets.chomp
puts "Your balance after today's deposit is $#{deposit}."
elsif transaction == 'withdraw'
puts 'How much would you like to withdraw today?'
wd = gets.chomp
puts "Your balance after today's withdrawal is $#{withdraw}."
else
puts 'I\'m sorry that was not one of your options.'
end
end
|
class Course < ActiveRecord::Base
has_many :enrollments
end
|
# The useful lovely Class Attr Accessor <3
class Square
attr_accessor :side_length
def initialize(side_length)
@side_length = side_length
end
# There was a getter and a setter here!
def perimeter
return @side_length * 4
end
def area
return @side_length * @side_length
end
def to_s
return "The Side Length = #{side_length}\nThe Perimeter = #{perimeter}\nThe Area = #{area}"
end
end
my_square = Square.new(10)
puts my_square.side_length
# Changing it to test the setter from the attr!
my_square.side_length = 20
puts my_square.side_length
|
include Java
require "solrmarc_wrapper/version"
require 'logger'
# a way to use SolrMarc objects,
# such as using SolrReIndexer to get a SolrInputDocument from a marc record stored in the Solr index.
class SolrmarcWrapper
attr_accessor :logger
# @param solrmarc_dist_dir distribution directory of SolrMarc build
# @param solrmarc_conf_props_fname the name of the xx_config.properties file for SolrMarc, relative to solrmarc_dist_dir
# @param solr_url the base url of a running Solr server
# @param log_level level of Logger messages to output; defaults to Logger::INFO
# @param log_file file to receive Logger output; defaults to STDERR
# solr_url base url of the solr instance
def initialize(solrmarc_dist_dir, config_props_fname, solr_url, log_level=Logger::INFO, log_file=STDERR)
if not defined? JRUBY_VERSION
raise "SolrmarcWrapper only runs under jruby"
end
@logger = Logger.new(log_file)
@logger.level = log_level
load_solrmarc(solrmarc_dist_dir)
setup_solr_reindexer(solr_url, config_props_fname)
end
# retrieves the full marc rec
# ord stored in the Solr index, runs it through SolrMarc indexing to get a SolrInputDocument
# note that it identifies Solr documents by the "id" field, and expects the marc to be stored in a Solr field "marcxml"
# if there is no single document matching the id, an error is logged and nil is returned
# @param doc_id the value of the "id" Solr field for the record to be retrieved
# @return a SolrInputDocument for the doc_id, populated via marcxml and SolrMarc
def get_solr_input_doc_from_marcxml(doc_id)
begin
@solr_input_doc = @solrmarc_reindexer.getSolrInputDoc("id", doc_id, "marcxml")
rescue java.lang.NullPointerException
@logger.error("Can't find single Solr document with id #{doc_id}")
return nil
end
@solr_input_doc
end
protected
# require all the necessary jars to use SolrMarc classes
def load_solrmarc(solr_marc_dir)
Dir["#{solr_marc_dir}/**/*.jar"].each {|jar_file| require File.expand_path(jar_file) }
end
# initialize the @solrmarc_reindexer object
# @param solr_url the url of the Solr server
# @param config_props_fname the name of the xx_config.properties file relative to the solr_marc_dir used in initialize method
def setup_solr_reindexer(solr_url, config_props_fname)
solr_core_loader = org.solrmarc.solr.SolrCoreLoader.loadRemoteSolrServer(solr_url, false, false)
@solrmarc_reindexer = org.solrmarc.marc.SolrReIndexer.new(solr_core_loader)
@solrmarc_reindexer.init([config_props_fname])
end
end # module SolrmarcWrapper
|
class ApplicationController < ActionController::API
# something to do with what formats are acceptable if Content-Type: 'application/json' is not specified in the request?
respond_to :json
# rescue_from ActiveRecord::RecordInvalid, with: :record_invalid
# rescue_from ActiveRecord::RecordNotUnique, with: :record_not_unique
# rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
# rescue_from JWT::VerificationError, with: :verification_error
# private
# def record_invalid(exception)
# render json: { errors: exception.record.errors }, status: :unprocessable_entity
# end
# def record_not_unique(exception)
# render json: { errors: exception.message }, status: :unprocessable_entity
# end
# def record_not_found(exception)
# render json: { errors: exception.message }, status: :not_found
# end
# def verification_error(exception)
# render json: { errors: exception.message }, status: :internal_server_error
# end
end
|
class PasswordResetMailer < ActionMailer::Base
default from: "admin@example.com"
def password_reset_email(password_reset)
@password_reset = password_reset
@user = @password_reset.user
mail(to: @user.email,
subject: "Reset Your Password")
end
end
|
# frozen_string_literal: true
RSpec.describe CollectWorker, type: :worker do
subject(:worker) { described_class.new(operation: operation) }
let(:operation) { instance_spy(SourceOperation) }
context '.perform' do
subject(:perform) { worker.perform }
before do
allow(worker).to receive(:operation).and_return(operation)
end
it do
perform
expect(operation).to have_received(:call).with(
source_names: ['b3', 'status_invest', 'fundamentos'],
storage_names: ['google_sheets', 'mongo_db']
)
end
end
end
|
#
# Class Token - Encapsulates the tokens in TINY
#
# @type - the type of token
# @text - the text the token represents
#
class Token
attr_accessor :type
attr_accessor :text
EOF = "eof"
LPAREN = "("
RPAREN = ")"
WS = "whitespace"
ADDOP = "+"
MINUSOP = "-"
MULTOP = "*"
DIVOP = "/"
EQUALOP = "="
NUMBER = "number"
ALPHABET = "letter"
PRINT = "print"
ID = "unassigned"
#add the rest of the tokens needed based on the grammar
#specified in the Scanner class "TinyScanner.rb"
def initialize(type,text)
@type = type
@text = text
end
def get_type
return @type
end
def get_text
return @text
end
def to_s
# return "[Type: #{@type} || Text: #{@text}]"
return "#{@text}"
end
end
|
module BoardsHelper
def check_sidebar_log_in
it "should display", :spam => true do
@selenium.find_elements(:css => "div.sidebar a[class='inner authReturnUrl']").count.should == 1
@selenium.find_element(:css => "div.sidebar a[class='inner authReturnUrl']").displayed?.should be_true
end
it 'should link to the sign-in page with a proper redirect back' do
@selenium.find_element(:css => "div.sidebar a[class='inner authReturnUrl']").attribute('href').to_s.match(/s.ign.com\/login?r=#{@selenium.current_url}/)
end
end
def check_main_section_list
it 'should correctly display each category' do
list = return_boards_list
categories = @selenium.find_elements(:css => "ol#forums div.categoryText")
categories.count.should == list.length
n = 0
categories.each do |cat|
cat.text.downcase.should == list[n].keys[0].to_s
n = n+1
end
end
it 'should correctly display each sub-category' do
list = return_boards_list
n = 0
@selenium.find_elements(:css => "ol#forums li.category ol.nodeList").length.should > 1
@selenium.find_elements(:css => "ol#forums li.category ol.nodeList").each do |cat|
x = 0
cat.find_elements(:css => 'h3.nodeTitle').length.should > 1
cat.find_elements(:css => 'h3.nodeTitle').each do |sub|
sub.text.downcase.should == list[n][list[n].keys[0]][x].to_s
x = x+1
end
n = n+1
end
end
end
def return_boards_list
[
{
:'ign clubhouse' => [
:'the vestibule',
:'the gcb',
]
},
{
:'the vault' => [
:acfriends,
:darktide,
:outpost
]
},
{
:'gaming boards' => [
:xbox,
:playstation,
:nintendo,
:pc,
:'ios gaming',
:gamespy,
:'all game boards'
]
},
{
:'entertainment boards' => [
:movies,
:television,
:comics,
:anime,
:music
]
},
{
:'sports boards' => [
:'sports community board',
:baseball,
:soccer,
:basketball,
:'college basketball',
:football,
:'college football',
:hockey,
:'pro wrestling',
:'other sports'
]
},
{
:'technology boards' => [
:'apple board',
:'android board',
:'tech board',
:'cars lobby'
]
},
{
:'other community boards' => [
:'current events',
:international,
:'sex, health and dating',
:'my ign',
:'feature and board requests',
:'wikis discussion',
:'issues & bug reports',
:'announcements'
]
},
{
:'ign prime vip board' => [
:gaming,
:'movies, tv, and tech'
]
}
]
end
end
|
LabelGen.configure do |config|
config.qr_url = "http://qr.somedomain.com/items/abc-%{number}/"
config.number_label = "%<number>.05d"
end
|
class CreateSystemMetrics < ActiveRecord::Migration[5.2]
def change
create_table :system_metrics do |t|
t.float :cpu_average_minute
t.integer :memory_used
t.integer :swap_used
t.integer :descriptors_used
t.datetime :get_time
t.references :hot_catch_app, index: true, foreign_key: true
t.timestamps
end
end
end
|
require 'spec_helper'
describe Immutable::List do
describe '#delete' do
it 'removes elements that are #== to the argument' do
L[1,2,3].delete(1).should eql(L[2,3])
L[1,2,3].delete(2).should eql(L[1,3])
L[1,2,3].delete(3).should eql(L[1,2])
L[1,2,3].delete(0).should eql(L[1,2,3])
L['a','b','a','c','a','a','d'].delete('a').should eql(L['b','c','d'])
L[EqualNotEql.new, EqualNotEql.new].delete(:something).should eql(L[])
L[EqlNotEqual.new, EqlNotEqual.new].delete(:something).should_not be_empty
end
end
end
|
class User < ActiveRecord::Base
has_secure_password
validates :email, presence: true, uniqueness: {case_sensitive: false}
has_many :items
has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end
|
FactoryBot.define do
factory :fpl_team, class: FplTeam do
name { Faker::Name.unique.name }
association :user, factory: :user
association :league, factory: :league
end
end
|
class AddLevelToCompetitions < ActiveRecord::Migration[5.0]
def change
add_column :competitions, :level, :string, :limit => 3
end
end
|
class Api::V3::EncounterPayloadValidator < Api::V3::PayloadValidator
attr_accessor(
:id,
:patient_id,
:created_at,
:updated_at,
:deleted_at,
:notes,
:encountered_on,
:observations
)
validate :validate_schema
validate :observables_belong_to_single_facility
def schema
Api::V3::Models.encounter
end
def observables_belong_to_single_facility
observation_facility_ids = observations.values.flatten.map { |r| r[:facility_id] }.uniq
if observation_facility_ids.count > 1
errors.add(:schema, "Encounter observations belong to more than one facility")
end
end
end
|
class IngredientsController < ApplicationController
before_action :authenticate_admin!
def create
@ingredient = Ingredient.new(name: params["ingredient"]["name"])
if @ingredient.save
redirect_to home_path
else
render 'new'
end
end
def new
@ingredient = Ingredient.new
end
def authenticate_admin!
super
raise "Fuck outta here you are not an admin" if (current_admin.email != "bagiotto@brothers.com")
end
end |
require 'spec_helper'
MARLA_USERNAME = 'marla.singer@gmail.com'
MARLA_PASSWORD = 'cancer'
def register_marla
visit new_user_url
fill_in 'user_username', with: MARLA_USERNAME
fill_in 'user_password', with: MARLA_PASSWORD
click_on 'Create User'
end
def sign_in_as_marla
visit new_user_url
fill_in 'session_username', with: MARLA_USERNAME
fill_in 'session_password', with: MARLA_PASSWORD
click_on 'Sign In'
end
def create_marla
create(:user, username: MARLA_USERNAME, password: MARLA_PASSWORD)
end
feature "the signup process" do
scenario "has a new user page" do
visit new_user_url
expect(page).to have_content "New User"
end
feature "signing up a user" do
before(:each) do
register_marla
end
scenario "shows username on the homepage after signup" do
expect(page).to have_content MARLA_USERNAME
end
end
end
feature "logging in" do
before(:each) do
create_marla
sign_in_as_marla
end
scenario "shows username on the homepage after login" do
expect(page).to have_content 'marla.singer@gmail.com'
end
end
feature "logging out" do
scenario "begins with logged out state" do
visit new_user_url
expect(page).to have_content 'Sign In'
end
scenario "doesn't show username on the homepage after logout" do
create_marla
sign_in_as_marla
click_on 'Sign Out'
expect(page).to_not have_content MARLA_USERNAME
end
end
feature "editing user" do
let!(:user) { create_marla }
before(:each) do
sign_in_as_marla
end
scenario "edit user page exists" do
expect(page).to have_content "Edit User"
end
scenario "can change password" do
visit edit_user_url(user)
fill_in 'user_password', with: 'brain parasites'
click_on 'Update User'
expect(User.find(user.id).password).to eq('brain parasites')
end
end
|
require 'pry'
require './rule_based_translator.rb'
require './simple_equation_solver.rb'
class Student
extend RuleBasedTranslator
class << self
attr_accessor :student_rules
def format_symbols(string)
string = string.dup
symbols = [".", ",", "%", "$", "+", "-", "*", "/"]
symbols.each { |sym| string.gsub!(sym, " #{sym} ") }
string
end
def remove_noise_words(words)
words = format_as_array(words.dup)
noise_words = ["a", "an", "the", "this", "number", "of"]
words.reject! { |word| noise_words.include?(word) }
words
end
def format_as_array(words)
return words if words.is_a?(Array)
words.scan(/\S+/)
end
def string_to_words(string)
return if string.nil?
remove_noise_words(format_symbols(string.downcase))
end
def make_variable(words)
words = words.dup
if [words].flatten(1).first =~ /^\d+(\.\d+)?$/
[words].flatten.first.to_f
else
words.join("_")
end
end
def translate_to_expression(input)
translate(input: input, rules: student_rules, action_func: action_func) ||
make_variable(input)
end
def action_func
Proc.new do |response, variable_map|
variable_map.each do |variable, value|
response = replace_sym(response, variable, translate_to_expression(value))
end
response
end
end
def string_translate_to_expression(input)
translate_to_expression(string_to_words(input))
end
def create_list_of_equations(biexp)
if biexp.nil?
[]
elsif biexp.class != Array || %w(+ - * / =).include?(biexp[1])
[biexp]
else
create_list_of_equations(biexp[0]) + create_list_of_equations(biexp[1])
end
end
def biexp_to_string(biexp)
EquationParser.biexp_to_string(biexp)
end
def solve_worded_question(string)
expressions = create_list_of_equations(string_translate_to_expression(string))
solutions = SimpleEquationSolver.solve_equation(expressions)
puts "The equations to solve are:"
expressions.each { |exp| puts biexp_to_string(exp) }
p "The solutions are:"
solutions.each { |exp| puts exp }
nil
end
end
@student_rules = expand_pattern([
{
pattern: [%w(?X+ .), %w(?X+ ,)],
responses: "?X"
},
{
pattern: [%w(?X+ . ?Y+), %w(?X+ then ?Y+), %w(?X+ , ?Y+)], #"?X+, ?Y+" put last because other phrase contain ','
responses: %w(?X ?Y)
},
{
pattern: [%w(then ?X+), %w(if ?X+), %w(and ?X+)],
responses: "?X"
},
{
pattern: [ ["find", ["?+", "?X", "(?X - %w(difference sum product)).size == ?X.size"], "and", "?Y+"] ],
responses: [%w(to_find_1 = ?X), %w(to_find_2 = ?Y)]
},
{
pattern: [%w(find ?X+)],
responses: %w(to_find = ?X)
},
{
pattern: [ [["?+", "?X", "(?X - %w(difference sum product)).size == ?X.size"], 'and', "?Y+" ] ],
responses: %w(?X ?Y)
},
{
pattern: [%w(?X+ = ?Y+), %w(?X+ equals ?Y+), %w(?X+ is same as ?Y+), %w(?X+ same as ?Y+), %w(?X+ is equal to ?Y+), %w(?X+ is ?Y+)],
responses: %w(?X = ?Y)
},
{
pattern: [["?X+", "-", ["?+", "?Y", " !(?Y.include?('-') || ?Y.include?('minus')) "]], ["?X+", "minus", ["?+", "?Y", " !(?Y.include?('-') || ?Y.include?('minus')) "]]],
responses: %w(?X - ?Y)
},
{
pattern: [%w(difference between ?X+ and ?Y+), %w(difference ?X+ and ?Y+), %w(?X+ less than ?Y+)],
responses: %w(?Y - ?X)
},
{
pattern: [%w(?X+ + ?Y+), %w(?X+ plus ?Y+), %w(sum ?X+ and ?Y+), %w(?X+ greater than ?Y+)],
responses: %w(?X + ?Y)
},
{
pattern: [%w(?X+ * ?Y+), %w(product ?X+ and ?Y+), %w(?X+ times ?Y+)],
responses: %w(?X * ?Y)
},
{
pattern: [%w(?X+ / ?Y+), %w(?X+ per ?Y+), %w(?X+ divided by ?Y+)],
responses: %w(?X / ?Y)
},
{
pattern: [%w(half ?X+), %w(one half ?X+)],
responses: ["?X", "/", 2.0]
},
{
pattern: [%w(twice ?X+)],
responses: ["?X", "*", 2.0]
},
{
pattern: [%w(square ?X+), %w(?X+ squared)],
responses: ["?X", "*", "?X"]
},
{
pattern: [%w(?X+ % less than ?Y+), %w(?X+ % smaller than ?Y+)],
responses: ["?Y", "*", [[100.0, "-", "?X"], "/", 100.0]]
},
{
pattern: [%w(?X+ % more than ?Y+), %w(?X+ % greater than ?Y+)],
responses: ["?Y", "*", [[100.0, "+", "?X"], "/", 100.0]]
},
{
pattern: [%w(?X+ % ?Y+)],
responses: [["?X", "/", 100.0], "*", "?Y"]
},
])
end
# p Student.string_translate_to_expression("x is 5, y is 10, find x and y")
# p Student.string_translate_to_expression("x is 5 and y is 10")
# p Student.string_translate_to_expression("x is the sum of 5 and 3, y")
# puts Student.solve_worded_question("If the number of customers Tom gets is twice the square of 20% of the number of his advertisements, and the number of advertisements is 45, then what is the amount of customers?")
# puts Student.solve_worded_question("If the number of Tom's apples is 3, and Mary's is 5, what is the sum of Mary and Tom's apples?")
# p Student.string_translate_to_expression("x is 3 - 2 - 1")
|
require File.expand_path(File.dirname(__FILE__) + "/../lib/simple_record")
class MyModel < SimpleRecord::Base
has_attributes :created, :updated, :name, :age, :cool, :birthday
are_ints :age
are_booleans :cool
are_dates :created, :updated, :birthday
end |
require './spec/spec_helper.rb'
RSpec.describe RPNCalculator do
before :all do
@calculator = RPNCalculator.new
end
it "zeroes out invalid input" do
allow($stdin).to receive(:gets).and_return('ok', 'q')
expect { @calculator.run }.to output(/0/).to_stdout
end
it "allows integer input" do
allow($stdin).to receive(:gets).and_return('10', 'q')
expect { @calculator.run }.to output(/10/).to_stdout
end
it "allows negative numeric input" do
allow($stdin).to receive(:gets).and_return('-22', 'q')
expect { @calculator.run }.to output(/-22/).to_stdout
end
it "allows decimal input" do
allow($stdin).to receive(:gets).and_return('8.6', 'q')
expect { @calculator.run }.to output(/8.6/).to_stdout
end
it "supports addition" do
allow($stdin).to receive(:gets).and_return('7', '8', '+', 'q')
expect { @calculator.run }.to output(/15/).to_stdout
end
it "supports subtraction" do
allow($stdin).to receive(:gets).and_return('15', '5', '-', 'q')
expect { @calculator.run }.to output(/10/).to_stdout
end
it "supports multiplication" do
allow($stdin).to receive(:gets).and_return('2', '6', '*', 'q')
expect { @calculator.run }.to output(/12/).to_stdout
end
it "supports division" do
allow($stdin).to receive(:gets).and_return('4', '2', '/', 'q')
expect { @calculator.run }.to output(/2/).to_stdout
end
it "does not support zero division" do
allow($stdin).to receive(:gets).and_return('8', '0', '/', 'q')
expect { @calculator.run }.to raise_error(ZeroDivisionError)
end
it "quits when the input is q" do
allow($stdin).to receive(:gets).and_return('q', '9', 'bob')
expect { @calculator.run }.to output(nil).to_stdout
end
end
|
class Cuba
include Headers
include Cors # cors helper methods (headers)
attr_accessor :content_type
# some handy methods to use inside Cuba.define
def logfile
@logfile ||= File.open(File.join(APP_ROOT, 'logs', 'proxy.log'), 'a+')
end
def logger
@logger ||= Logger.new logfile
end
# extra matchers
def options
req.options?
end
def proxy_to
/proxy_to\/(.+)/
end
end
|
#Day3.rb
#Ruby - Chapter 2, Day 3 Self-Study
puts "Task: Modify the CSV application to support an each method to return a CsvRow object."
class CsvRow
attr_accessor :headers, :values
def initialize(headers, values)
@headers = headers
@values = values
end
def method_missing(name, *args)
index = @headers.index(name.to_s)
if index
@values[index]
else
"Invalid method or column name."
end
end
end
module ActsAsCsv
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def acts_as_csv
include InstanceMethods
end
end
module InstanceMethods
def read
@csv_contents = []
filename = self.class.to_s.downcase + '.txt'
file = File.new(filename)
@headers = file.gets.chomp.split(', ')
file.each do |row|
@csv_contents << row.chomp.split(', ')
end
end
attr_accessor :headers, :csv_contents
def initialize
read
end
def each
@csv_contents.each do |values|
yield CsvRow.new(@headers, values)
end
end
end
end
class RubyCsv # no inheritance! You can mix it in
include ActsAsCsv
acts_as_csv
end
#Test
puts
puts "Testing RubyCsv..."
csv = RubyCsv.new
csv.each {|row| puts "#{row.fname} #{row.lname} is from #{row.city}"}
puts
puts "Testing RubyCsv - Invalid column name..."
csv.each {|row| puts row.state} |
#
# This file is a stand-in that allows for the generation of rdoc documentation
# for the IBRuby extension for the Ruby programming language. The extension
# is coded in C and documented with Doxygen comments, so this file is used to
# generate the native Ruby documentation instead.
#
#
# This module contains all of the classes and definitions relating to the
# IBRuby extension for the Ruby language.
#
module IBRuby
#
# This class provides the exception type used by the IBRuby library.
#
class IBRubyException
#
# This is the constructor for the IBRubyError class.
#
# ==== Parameters
# message:: A string containing the error message for the object.
#
def initialize(message)
end
#
# This is the accessor for the error message attribute
#
def message
end
#
# This is the accessor for the SQL code attribute.
#
def sql_code
end
#
# This is the accessor for the database code attribute.
#
def db_code
end
#
# This function generates a simple description string for a IBRubyError
# object.
#
def to_s
end
end
#
# This class represents an existing database that can be connected to. It
# also provides functionality to allow for the creation of new databases.
#
class Database
#
# This is the constructor for the Database class.
#
# ==== Parameters
# file:: A string containing the database file specifier. This can
# include details for a remote server if needed.
# set:: A string containing the name of the character set to be
# used with the database. Defaults to nil.
#
def initialize(file, set=nil)
end
#
# This is the accessor for the database file specification attribute.
#
def file
end
#
# This method attempts to establish a connection to a database. If
# successful then a Connection instance is returned. If a block is
# provided to the method then the connection is closed after the
# block completes. If a block is specified the connection is provided
# as a parameter to the block.
#
# ==== Parameters
# user:: The user name to be used in making the connection. This
# defaults to nil.
# password:: The password to be used in making the connection. This
# defaults to nil.
# options:: A Hash of connection options. This should be made up of
# key/setting pairs where the keys are from the list that
# is defined within the Connection class. The settings are
# particular to the key, see the documentation for the
# Connection class for more details.
#
# ==== Exceptions
# Exception:: Thrown whenever a problem occurs connecting with the
# database.
#
def connect(user=nil, password=nil, options=nil)
yield(connection)
end
#
# This method attempts to drop the database referred to by the details
# in a Database object.
#
# ==== Parameters
# user:: The user name to be used in dropping the database.
# password:: The password to be used in dropping the database.
#
# ==== Exceptions
# IBRubyError:: Thrown whenever a problem occurs dropping the database
# instance.
#
def drop(user, password)
end
#
# This method can be used to programmatically created a database file.
# If successful this method returns a Database object.
#
# ==== Parameters
# file:: A string containing the path and name of the database file
# to be created.
# user:: A string containing the user name that will be used in
# creating the file.
# password:: A string containing the user password that will be used in
# creating the file.
# size:: The page size setting to be used with the new database file.
# This should be 1024, 2048, 4096 or 8192. Defaults to 1024.
# set:: The name of the default character set to be assigned to the
# new database file. If this parameter is specifed then the
# Database object created by the call will use it to whenever
# a connection request is made. Defaults to nil.
#
# ==== Exceptions
# Exception:: Generated whenever an invalid parameter is specified or a
# problem occurs creating the database file.
#
def Database.create(file, user, password, size=1024, set=nil)
end
#
# This method fetches the name of the character set currently assigned
# to a Database object. This can return nil to indicate that a explicit
# character set has not been assigned.
#
def character_set
end
#
# This method allows the specification of a database character set that
# will be used when creating connections to a database. The value set by
# this method can be overridden by providing an alternative in the connect
# call. To remove a character set specification from a Database object
# pass nil to this method.
#
# ==== Parameters
# set:: A string containing the name of the database character set.
#
def character_set=(set)
end
end
#
# This class represents a connection with a InterBase database.
#
class Connection
# A definition for a connection option. This option should be given a
# setting of either true or false.
MARK_DATABASE_DAMAGED = 17
# A definition for a connection option. This option should be given a
# setting of Connection::WRITE_ASYNCHRONOUS or
# Connection::WRITE_SYNCHRONOUS
WRITE_POLICY = 24
# A definition for a connection option. This option should be given a
# string setting which should be the name of the character set to be
# used by the connection.
CHARACTER_SET = 48
# A definition for a connection option. This option should be given a
# string setting which should be the name of the message file to be used
# by the connection.
MESSAGE_FILE = 47
# A definition for a connection option. This option should be given a
# an integer setting. Values between 1 and 255 are valid, with 75 being
# the default.
NUMBER_OF_CACHE_BUFFERS = 5
# A definition for a connection option. This option should be given a
# string value which should be the database DBA user name.
DBA_USER_NAME = 19
# A definition for a possible setting to accompany the WRITE_POLICY
# connection setting.
WRITE_ASYNCHONOUS = 0
# A definition for a possible setting to accompany the WRITE_POLICY
# connection setting.
WRITE_SYNCHONOUS = 1
#
# This is the constructor for the Connection class.
#
# ==== Parameters
# database:: A reference to the Database object to be connected to.
# user:: A reference to the user name to be used in making the
# database connection. Defaults to nil.
# password:: A reference to the user password to be used in making the
# connection. Defaults to nil.
# options:: A Hash containing the options to be applied to the new
# connection. The hash will contain key/setting values, with
# the keys being based on the option constants defined within
# the Connection class. Individual options have differing
# value requirements. See the option documentation entries
# for further details. Defaults to nil.
#
# ==== Exceptions
# Exception:: Generated whenever an invalid database is specified to
# the method or an issue occurs establishing the database
# connection.
#
def initialize(database, user, password, options)
end
#
# This method is used to determine whether a Connection object represents
# an active database connection.
#
def open?
end
#
# This method is used to determine whether a Connection object represents
# an inactive database connection.
#
def closed?
end
#
# This method detaches a Connection object from a database. The object
# may not be used for database functionality following a successful call
# to this method. The close method will fail if there are outstanding
# transactions for a connection.
#
# ==== Exceptions
# Exception:: Generated whenever the connection has at least one open
# transaction or an error occurs closing the connection.
#
def close
end
#
# This is the accessor method for the database attribute.
#
def database
end
#
# This method retrieves the user name that was used in creating a
# Connection object.
#
def user
end
#
# This method generates a simple descriptive string for a Connection
# object.
#
def to_s
end
#
# This method starts a new transaction against a connection. A successful
# call to this method returns a Transaction object. The transaction that
# is started relates to the Connection it was called upon only. To start
# a transaction that covers multiple connections use the Transaction
# class. This method accepts a block, taking a single parameter which
# will be the transaction created. This transaction is committed if the
# block completes normally or rolls back if an exception is thrown from
# the block.
#
# ==== Exceptions
# Exception:: Thrown whenever a problem occurs starting the transaction.
#
def start_transaction
yield transaction
end
#
# This function executes a SQL statement against a connection. If the
# statement represented a SQL query then a ResultSet object is returned.
# If the statement was a non-query SQL statement then an Integer is
# returned indicating the number of rows affected by the statement. For
# all other types of statement the method returns nil. The method also
# accepts a block that takes a single parameter. This block will be
# executed once for each row in any result set generated.
#
# ==== Parameters
# sql:: The SQL statement to be executed.
# transaction:: The transaction to execute the SQL statement within.
#
# ==== Exceptions
# Exception:: Generated if an error occurs executing the SQL statement.
#
def execute(sql, transaction)
yield(row)
end
#
# This function executes a SQL statement against a connection. This
# differs from the execute method in that an anonymous transaction is
# used in executing the statement. The output from this method is the
# same as for the execute method. The method also accepts a block that
# takes a single parameter. This block will be executed once for each
# row in any result set generated.
#
# ==== Parameters
# sql:: The SQL statement to be executed.
#
# ==== Exceptions
# Exception:: Generated whenever a problem occurs executing the SQL
# statement.
#
def execute_immediate(sql)
yield(row)
end
end
#
# This class represents an InterBase database transaction. There may be
# multiple transaction outstanding against a connection at any one time.
#
class Transaction
TPB_VERSION_1 = 1
TPB_VERSION_3 = 3
TPB_CONSISTENCY = 1
TPB_CONCURRENCY = 2
TPB_SHARED = 3
TPB_PROTECTED = 4
TPB_EXCLUSIVE = 5
TPB_WAIT = 6
TPB_NO_WAIT = 7
TPB_READ = 8
TPB_WRITE = 9
TPB_LOCK_READ = 10
TPB_LOCK_WRITE = 11
TPB_VERB_TIME = 12
TPB_COMMIT_TIME = 13
TPB_IGNORE_LIMBO = 14
TPB_READ_COMMITTED = 15
TPB_AUTO_COMMIT = 16
TPB_REC_VERSION = 17
TPB_NO_REC_VERSION = 18
TPB_RESTART_REQUESTS = 19
# Transaction parameter buffer value constants.
TPB_NO_AUTO_UNDO = 20
#
# This is the constructor for the Transaction class.
#
# ==== Parameters
# connections:: Either a single instance of the Connection class or
# an array of Connection instances to specify a
# multi-database transaction.
#
# ==== Exceptions
# Exception:: Generated whenever the method is passed an invalid
# parameter or a problem occurs creating the transaction.
#
def initialize(connections)
end
#
# This method is used to determine whether a Transaction object is still
# valid for use (i.e. commit or rollback has not been called for the
# Transaction).
#
def active?
end
#
# This is the accessor for the connections attribute. This method returns
# an array of the connections that the transaction applies to.
#
def connections
end
#
# This method is used to determine whether a given Transaction applies to
# a specified Connection.
#
# ==== Parameters
# connection:: A reference to the Connection object to perform the test
# for.
#
def for_connection?(connection)
end
#
# This method commits the details outstanding against a Transaction
# object. The Transaction object may not be reused after a successful
# call to this method.
#
# ==== Exceptions
# Exception:: Generated whenever a problem occurs committing the details
# of the transaction.
#
def commit
end
#
# This method rolls back the details outstanding against a Transaction
# object. The Transaction object may not be reused after a successful
# call to this method.
#
# ==== Exceptions
# Exception:: Generated whenever a problem occurs rolling back the
# details of the transaction.
#
def rollback
end
#
# This method executes a SQL statement using a Transaction object. This
# method will only work whenever a Transaction object applies to a
# single Connection as it would otherwise be impossible to determine
# which connection to execute against. If the statement executed was a
# SQL query then the method returns a ResultSet object. For non-query SQL
# statements (insert, update or delete) the method returns an Integer that
# contains the number of rows affected by the statement. For all other
# statements the method returns nil. The method also accepts a block that
# takes a single parameter. If the SQL statement was a query the block
# will be invoked and passed each row retrieved.
#
# ==== Parameters
# sql:: A string containing the SQL statement to be executed.
#
# ==== Exceptions
# Exception:: Generated whenever the Transaction object represents more
# than one connection or a problem occurs executing the SQL
# statement.
#
def execute(sql)
yield(row)
end
#
# This method allows for the creation of a Transaction object with
# non-standard settings.
#
# ==== Parameters
# connections:: Either a single Connection object or an array of
# Connection objects that the new Transaction will
# be associated with.
# parameters:: An array of the parameters to be used in creating
# the new constants. Populate this from the TPB
# constants defined within the class.
#
# ==== Exceptions
# IBRubyError:: Generated whenever a problem occurs creating the
# transaction.
#
def Transaction.create(connections, parameters)
end
end
#
# This class represents a prepared SQL statement that may be executed more
# than once.
#
class Statement
# A definition for a SQL statement type constant.
SELECT_STATEMENT = 1
# A definition for a SQL statement type constant.
INSERT_STATEMENT = 2
# A definition for a SQL statement type constant.
UPDATE_STATEMENT = 3
# A definition for a SQL statement type constant.
DELETE_STATEMENT = 4
# A definition for a SQL statement type constant.
DDL_STATEMENT = 5
# A definition for a SQL statement type constant.
GET_SEGMENT_STATEMENT = 6
# A definition for a SQL statement type constant.
PUT_SEGMENT_STATEMENT = 7
# A definition for a SQL statement type constant.
EXECUTE_PROCEDURE_STATEMENT = 8
# A definition for a SQL statement type constant.
START_TRANSACTION_STATEMENT = 9
# A definition for a SQL statement type constant.
COMMIT_STATEMENT = 10
# A definition for a SQL statement type constant.
ROLLBACK_STATEMENT = 11
# A definition for a SQL statement type constant.
SELECT_FOR_UPDATE_STATEMENT = 12
# A definition for a SQL statement type constant.
SET_GENERATOR_STATEMENT = 13
# A definition for a SQL statement type constant.
SAVE_POINT_STATEMENT = 14
#
# This is the constructor for the Statement class.
#
# ==== Parameters
# connection:: The Connection object that the SQL statement will be
# executed through.
# transaction:: The Transaction object that the SQL statement will be
# executed under.
# sql:: The SQL statement to be prepared for execution.
# dialect:: The InterBase dialect to be used in preparing the SQL
# statement.
#
def initialize(connection, transaction, sql, dialect)
end
#
# This is the accessor for the connection attribute.
#
def connection
end
#
# This is the accessor for the transaction attribute.
#
def transaction
end
#
# This is the accessor for the SQL statement attribute.
#
def sql
end
#
# This is the accessor for the dialect attribute.
#
def dialect
end
#
# This method is used to determine the type of a SQL statement. The method
# will return one of the constant SQL types defined within the class.
#
def type
end
#
# This method fetches a count of the number of dynamic parameters for
# a statement object (i.e. the number of parameters that must be provided
# with values before the SQL statement can be executed).
#
def parameter_count
end
#
# This method executes the SQL statement within a Statement object. This
# method returns a ResultSet object if the statement executed was a SQL
# query. For non-query SQL statements (insert, update or delete) it
# returns an Integer indicating the number of affected rows. For all other
# statements the method returns nil. This method accepts a block taking a
# single parameter. If this block is provided and the statement is a query
# then the rows returned by the query will be passed, one at a time, to
# the block.
#
# ==== Exception
# Exception:: Generated if the Statement object actual requires some
# parameters or a problem occurs executing the SQL statement.
#
def execute
yield row
end
#
# This method executes the SQL statement within a Statement object and
# passes it a set of parameters. Parameterized statements use question
# marks as place holders for values that may change between calls to
# execute the statement. This method returns a ResultSet object if the
# statement executed was a SQL query. If the statement was a non-query SQL
# statement (insert, update or delete) then the method returns a count of
# the number of rows affected. For all other types of statement the method
# returns nil. This method accepts a block taking a single parameter. If
# this block is provided and the statement is a query then the rows
# returned by the query will be passed, one at a time, to the block.
#
# ==== Parameters
# parameters:: An array of the parameters for the statement. An effort
# will be made to convert the values passed in to the
# appropriate types but no guarantees are made (especially
# in the case of text fields, which will simply use to_s
# if the object passed is not a String).
#
# ==== Exception
# Exception:: Generated whenever a problem occurs translating one of the
# input parameters or executing the SQL statement.
#
def execute_for(parameters)
yield row
end
#
# This method releases the database resources associated with a Statement
# object and should be explicitly called when a Statement object is of
# no further use.
#
# ==== Exceptions
# IBRubyError:: Generated whenever a problem occurs closing the
# statement object.
#
def close
end
end
#
# This class represents the results of a SQL query executed against a
# database. The viable lifespan of a ResultSet object is limited by the
# transaction that was used in it's creation. Once this transaction has
# been committed or rolled back all related ResultSet object are invalidated
# and can no longer be used.
#
class ResultSet
include Enumerable
#
# This is the constructor for the ResultSet object.
#
# ==== Parameters
# connection:: A reference to the Connection object that will be used
# to execute the SQL query.
# transaction:: A reference to the Transaction object that will be used
# in executing the SQL query.
# sql:: A reference to a String containing the SQL query that
# will be executed.
# dialect:: A reference to an integer containing the InterBase dialect
# to be used in executing the SQL statement.
#
# ==== Exceptions
# IBRubyException:: Generated whenever a non-query SQL statement is
# specified, an invalid connection or transaction is
# provided or a problem occurs executing the SQL
# against the database.
#
def initialize(connection, transaction, sql, dialect)
end
#
# This is the accessor for the connection attribute.
#
def connection
end
#
# This is the accessor for the transaction attribute.
#
def transaction
end
#
# This is the accessor for the sql attribute.
#
def sql
end
#
# This is the accessor for the dialect attribute.
#
def dialect
end
#
# This method fetches a count of the number of columns in a row of data
# that the ResultSet can fetch.
#
def column_count
end
#
# This method fetches the name associated with a specified column for a
# ResultSet object.
#
# ==== Parameters
# column:: A reference to the column number to fetch the details for.
# Column numbers start at zero.
#
def column_name(column)
end
#
# This method fetches the alias associated with a specified column for a
# ResultSet object.
#
# ==== Parameters
# column:: A reference to the column number to fetch the details for.
# Column numbers start at zero.
#
def column_alias(column)
end
#
# This method fetches the table name associated with a specified column
# for a ResultSet object.
#
# ==== Parameters
# column:: A reference to the column number to fetch the details for.
# Column numbers start at zero.
#
def column_table(column)
end
#
# This method fetches a single rows worth of data from the ResultSet
# object. If the set contains more rows then an array containing the
# row data will be retrieved. If the ResultSet is exhausted (i.e. all
# rows have been fetched) then nil is returned. Translation of the row
# data into an appropriate Ruby type is performed on the row data that
# is extracted.
#
def fetch
end
#
# This method is used to determine if all of the rows have been retrieved
# from a ResultSet object. This method will always return false until
# the fetch method has been called at least once so it cannot be used to
# detect a result set that returns no rows.
#
def exhausted?
end
#
# This method fetches a count of the total number of rows retrieved
# from a result set.
#
def row_count
end
#
# This method provides an iterator for the (remaining) rows contained in
# a ResultSet object.
#
# ==== Parameters
# block:: A block that takes a single parameter. This will be called for
# and passed each remaining row (as per the fetch method) from
# the ResultSet.
#
def each(&block)
end
#
# This method releases the database resources associated with a ResultSet
# object and should be explicitly called when a ResultSet object is of
# no further use. The method is implicitly called if the rows available
# from a ResultSet are exhausted but calling this method at that time
# will not cause an error.
#
# ==== Exceptions
# IBRubyError:: Generated whenever a problem occurs closing the result
# set object.
#
def close
end
#
# This method retrieves the base SQL type for a column of data within a
# ResultSet object. The method returns one of the base types defined in
# the SQLType class but does not return an actual SQLType object.
#
# ==== Parameters
# index:: The offset from the ResultSet first column of the column to
# return the type information for.
#
def get_base_type(index)
end
end
#
# This class models a row of data fetched as part of a SQL query.
#
class Row
include Enumerable
#
# This is the constructor for the Row class. This method shouldn't really
# be used as Row objects are automatically created by ResultSets.
#
# ==== Parameters
# results:: The ResultSet object that the row relates to.
# data:: An array containing the row data values.
# number:: The row number for the new row.
#
def initialize(results, data, number)
end
#
# This is the accessor for the row number attribute. This will generally
# reflect the order the row was fetched from the result set in, with 1
# being the first row retrieved.
#
def number
end
#
# This method fetches a count of the number of columns of data that are
# available from a row.
#
def column_count
end
#
# This method fetches the name of a column within a row of data.
#
# ==== Parameters
# index:: The index of the column to fetch the name for. The first
# column in the row is at offset zero.
#
def column_name(index)
end
#
# This method fetches the alias of a column within a row of data.
#
# ==== Parameters
# index:: The index of the column to fetch the alias for. The first
# column in the row is at offset zero.
#
def column_alias(index)
end
#
# This method fetches the value associated with a column within a Row
# object.
#
# ==== Parameters
# index:: Either the offset of the column to retrieve the value of or
# the alias of the column to retrieve the value of (column alias
# comparisons are case sensitive).
#
def [](index)
end
#
# This method iterates over the contents of a Row object. The block
# specified for the method should accept two parameters; one for the
# column alias and one for the column value.
#
def each
yield column, vlaue
end
#
# This method iterates over the column names for a Row class.
#
def each_key
yield column
end
#
# This method iterators over the column values for a Row class.
#
def each_value
yield value
end
#
# An implementation of the Hash#fetch method for the Row class. The
# method accepts a block but this should not be specified if a value
# for the alternative parameter is specified.
#
# ==== Parameters
# key:: A string containing the column alias to retrieve.
# alternative:: A reference to the alternative value to be returned if
# the keyed value is not found. Defaults to nil.
#
def fetch(key, alternative=nil)
yield key
end
#
# This method is used to determine whether a Row object contains a given
# column alias.
#
# ==== Parameters
# name:: A String containing the column name to check for.
#
def has_key?(name)
end
#
# This method is used to determine whether a Row object contains a given
# column name.
#
# ==== Parameters
# name:: A String containing the column name to check for.
#
def has_column?(name)
end
#
# This method is used to determine whether a Row object contains a given
# column alias.
#
# ==== Parameters
# name:: A String containing the column alias to check for.
#
def has_alias?(name)
end
#
# This method is used to determine whether a Row object contains a given
# column value.
#
# ==== Parameters
# value:: A reference to an object value to be checked for.
#
def has_value?(value)
end
#
# This method retrieves an array of column aliases for a Row object.
#
def keys
end
#
# This method retrieves an array of column names for a Row object.
#
def names
end
#
# This method retrieves an array of column aliases for a Row object.
#
def aliases
end
#
# This method retrieves an array of column values for a Row object.
#
def values
end
#
# This method returns an array of the Row elements for which the specified
# block returns true.
#
def select
yield column, value
end
#
# This method retrieves an Array containing the values from a Row object.
# Each value is represented as an Array containing a column name and the
# associated column value.
#
def to_a
end
#
# This method retrieves a Hash created from a Row objects values. The Row
# objects column names will be used as a key on to the column values.
#
def to_hash
end
#
# This method returns an array of column values based on a list of column
# aliases.
#
# ==== Parameters
# names:: One or more Strings containing the names of the columns to
# retrieve values for.
#
def values_at(*names)
end
#
# This method retrieves the base SQL type for a column of data within a
# Row object. The method returns one of the base types defined in the
# SQLType class but does not return an actual SQLType object.
#
# ==== Parameters
# index:: The offset from the Row first column of the column to return
# the type information for.
#
def get_base_type(index)
end
end
#
# This class represents Blob data fetched from the database. The class defers
# the actual loading of the blob until requested. The class is somewhat basic
# and maybe expanded upon in later releases.
#
class Blob
#
# This is the constructor for the Blob class. This shouldn't really be
# used outside of the IBRuby library.
#
def initialize
end
#
# This method loads the entire data set for a blob as a string.
#
def to_s
end
#
# This method closes a blob, freeing any resources associated with it.
#
def close
end
#
# This method loads the segments of a blob one after another. The blob
# segments are passed as strings to the block passed to the method.
#
def each
yield segment
end
end
#
# This class represents a InterBase generator entity.
#
class Generator
#
# This is the constructor for the Generator class. Note, this method
# assumes that the named generator already exists. If it doesn't then
# the object will be constructed but will fail during use.
#
# ==== Parameters
# name:: A string containing the generator name.
# connection:: A reference to the Connection object that will be used
# to access the generator.
#
def initialize(name, connection)
end
#
# This is the accessor for the name attribute.
#
def name
end
#
# This is the accessor for the connection attribute.
#
def connection
end
#
# This method fetches the last value generator from a generator.
#
# ==== Exceptions
# Exception:: Generated whenever a problem occurs accessing the
# database generator.
#
def last
end
#
# This method drops a generator from the database. After a successful
# call to this method the Generator object may not be used to obtain
# values unless it is recreated.
#
# ==== Exceptions
# Exception:: Generated whenever a problem occurs dropping the generator
# from the database.
#
def drop
end
#
# This method fetches the next value, depending on a specified increment,
# from a generator.
#
# ==== Parameters
# step:: The step interval to be applied to the generator to obtain the
# next value.
#
# ==== Exceptions
# Exception:: Generated whenever a problem occurs accessing the
# database generator.
#
def next(step)
end
#
# This method is used to determine whether a named generator exists
# within a database.
#
# ==== Parameters
# name:: A string containing the generator name to check for.
# connection:: A reference to the Connection object to be used in
# performing the check.
#
# ==== Exceptions
# Exception:: Generated whenever a problem occurs determining the
# existence of the generator.
#
def Generator.exists?(name, connection)
end
#
# This method creates a new generator within a database. This method
# returns a Generator object is successful.
#
# ==== Parameters
# name:: A string containing the name for the new generator.
# connection:: A reference to the Connection object that will be used to
# create the generator.
#
# ==== Exceptions
# Exception:: Generated whenever a problem occurs creating the new
# generator in the database.
#
def Generator.create(name, connection)
end
end
#
# This class represents a connection to the service manager for a InterBase
# database server instance.
#
class ServiceManager
#
# This is the constructor for the ServiceManager class.
#
# ==== Parameters
# host:: The name of the host supporting the service manager to be
# connected with.
#
def initialize(host)
end
#
# This method attaches a ServiceManager object to its host service. The
# user name used to connect with can affect which services can be accessed
# on the server.
#
# ==== Parameters
# user:: A string containing the user name to connect with.
# password:: A string containing the user password to connect with.
#
def connect(user, password)
end
#
# This method disconnects a previously connected ServiceManager object.
#
def disconnect
end
#
# This method is used to determine whether a ServiceManager object has
# been connected.
#
def connected?
end
#
# This method is used to batch execute a collection of task objects.
#
# ==== Parameters
# tasks:: One or more task objects to be executed by the service manager.
#
# ==== Exceptions
# IBRubyException:: Generated whenever this method is called on a
# disconnected service manager or is a problem
# occurs executing one of the tasks.
#
def execute(*tasks)
end
end
#
# This class represents a service manager task to add a new user to a
# database instance. NOTE: This class does not currently work on the
# Mac OS X platform.
#
class AddUser
# Attribute accessor.
attr_reader :user_name, :password, :first_name, :middle_name, :last_name
# Attribute mutator.
attr_writer :user_name, :password, :first_name, :middle_name, :last_name
#
# This is a constructor for the AddUser class.
#
# ==== Parameters
# user_name:: A String containing the user name to be assigned to the
# new user.
# password:: A String containing the password to be assigned to the
# new user.
# first_name:: A String containing the first name to be associated with
# the new user. Defaults to nil.
# middle_name:: A String containing the middle name to be associated
# with the new user. Defaults to nil.
# last_name:: A String containing the last name to be associated with
# the new user. Defaults to nil.
#
def initialize(user_name, password, firsts_name=nil, middle_name=nil,
last_name=nil)
end
#
# This method executes the add user task against a service manager.
#
# ==== Parameters
# manager:: A reference to the ServiceManager object to execute the task
# on.
#
# ==== Exceptions
# IBRubyException:: Generated whenever a disconnected service manager
# is specified or an error occurs executing the
# task.
#
def execute(manager)
end
end
#
# This class represents a service manager task to remove an existing user
# from a database instance. NOTE: This class does not currently work on the
# Mac OS X platform.
#
class RemoveUser
# Attribute accessor.
attr_reader :user_name
# Attribute mutator.
attr_writer :user_name
#
# This is a constructor for the RemoveUser class.
#
# ==== Parameters
# user_name:: A String containing the user name to be assigned to the
# new user.
#
def initialize(user_name)
end
#
# This method executes the remove user task against a service manager.
#
# ==== Parameters
# manager:: A reference to the ServiceManager object to execute the task
# on.
#
# ==== Exceptions
# IBRubyException:: Generated whenever a disconnected service manager
# is specified or an error occurs executing the
# task.
#
def execute(manager)
end
end
#
# This class represents a service manager task to backup an existing database
# on the InterBase server. NOTE: This class does not currently work on the
# Mac OS X platform.
#
class Backup
# Attribute accessor.
attr_reader :backup_file, :database
# Attribute mutator.
attr_writer :backup_file, :database
#
# This is the constructor for the Backup class.
#
# ==== Parameters
# database:: A String or File giving the path and name (relative to the
# database server) of the main database file for the database
# to be backed up.
# file:: A String or File giving the path and name (relative to the
# database server) of the back up file to be generated.
#
def initialize(database, file)
end
#
# This method fetches the blocking factor to be used in generating the
# back up. This will return nil until it has been explicitly set.
#
def blocking_factor
end
#
# This method sets the blocking factor to be used in generating the
# back up.
#
# ==== Parameters
# size:: A reference to an integer containing the new back up blocking
# factor setting.
#
def blocking_factor=(size)
end
#
# This method fetches the ignore checksums setting for a Backup object.
#
def ignore_checksums
end
#
# This method is used to set the indicator for whether checksum values
# should be ignored in performing a backup.
#
# ==== Parameters
# setting:: True to ignore checksums, false otherwise.
#
def ignore_checksums=(setting)
end
#
# This method fetches the ignore limbo setting for a Backup object.
#
def ignore_limbo
end
#
# This method is used to set the indicator for whether limbo transactions
# should be ignored in performing a backup.
#
# ==== Parameters
# setting:: True to ignore limbo transactions, false otherwise.
#
def ignore_limbo=(setting)
end
#
# This method fetches the metadata only setting for a Backup object.
#
def metadata_only
end
#
# This method is used to set the indicator for whether a backup stores
# only the database metadata.
#
# ==== Parameters
# setting:: True to store only metadata, false otherwise.
#
def metadata_only=(setting)
end
#
# This method fetches the garbage collect setting for a Backup object.
#
def garbage_collect
end
#
# This method is used to set the indicator for whether the backup will
# undertake garbage collection.
#
# ==== Parameters
# setting:: True to perform garbage collection, false otherwise.
#
def garbage_collect=(setting)
end
#
# This method fetches the non-transportable setting for a Backup object.
#
def non_transportable
end
#
# This method is used to set the indicator for whether backup generated
# by the task will be platform specific.
#
# ==== Parameters
# setting:: True to generate a platform specific backup, false otherwise.
#
def non_transportable=(setting)
end
#
# This method fetches the convert tables setting for a Backup object.
#
def convert_tables
end
#
# This method is used to set the indicator for whether external tables
# will be converted to internal tables as part of the backup.
#
# ==== Parameters
# setting:: True to convert external tables, false otherwise.
#
def convert_tables=(setting)
end
#
# This method is used to execute a backup task against a service manager.
#
# ==== Parameters
# manager:: A reference to the service manager to execute the backup
# task against.
#
# ==== Exceptions
# IBRubyException:: Generated whenever a disconnected service manager
# is specified or a problem occurs executing the
# task.
#
def execute(manager)
end
#
# This method fetches the log value for a Backup task. This value will
# always be nil until the task has been executed. After a successful
# execution the log value should contain output from the backup task
# generated on the server.
#
def log
end
end
#
# This class represents a service manager task to restore a previously
# created database backup on the InterBase server. NOTE: This class does not
# currently work on the Mac OS X platform.
#
class Restore
# Attribute accessor.
attr_reader :backup_file, :database
# Attribute mutator.
attr_writer :backup_file, :database
# Access mode constant definition.
ACCESS_READ_ONLY = 39
# Access mode constant definition.
ACCESS_READ_WRITE = 40
# Restore mode constant definition.
MODE_CREATE = 0x1000
# Restore mode constant definition.
MODE_REPLACE = 0x2000
#
# This is the constructor for the Restore class.
#
# ==== Parameters
# file:: A String or File containing the path and name (relative to
# the server) of the backup file to be used in the restore.
# database:: A String or File containing the path and name (relative to
# the server) of the database file to be restored.
#
def initialize(file, database)
end
#
# This method retrieves the cache buffers setting for a Restore object.
# This will be nil until a value is actual set.
#
def cache_buffers
end
#
# This method updates the cache buffers setting for a Restore object.
#
# ==== Parameters
# setting:: The new value for the object setting. Should be an integer.
#
def cache_buffers=(setting)
end
#
# This method retrieves the page size setting for a Restore object.
# This will be nil until a value is actual set.
#
def page_size
end
#
# This method updates the page size setting for a Restore object.
#
# ==== Parameters
# setting:: The new value for the object setting. Should be an integer.
#
def page_size=(setting)
end
#
# This method retrieves the access mode setting for a Restore object.
# This will be nil until a value is actual set.
#
def access_mode
end
#
# This method updates the access mode setting for a Restore object.
#
# ==== Parameters
# setting:: The new value for the object setting. This should be one
# of Restore::ACCESS_READ_ONLY or Restore::ACCESS_READ_WRITE.
#
def access_mode=(setting)
end
#
# This method retrieves the build indices setting for a Restore object.
#
def build_indices
end
#
# This method updates the build indices setting for a Restore object.
# This value affects whether the various indexes for a database are
# restored with the restore task.
#
# ==== Parameters
# setting:: True to rebuild the database indices, false otherwise.
#
def build_indices=(setting)
end
#
# This method retrieves the no shadows setting for a Restore object.
#
def no_shadows
end
#
# This method updates the no shadows setting for a Restore object.
# This value affects whether shadow databases are recreated as part of a
# restore.
#
# ==== Parameters
# setting:: True to recreate shadow files, false otherwise.
#
def no_shadows=(setting)
end
#
# This method retrieves the validity checks setting for a Restore object.
#
def check_validity
end
#
# This method updates the validity checks setting for a Restore object.
# This value affects whether the restore performs validity checks on the
# database as it is restored.
#
# ==== Parameters
# setting:: True to perform validity checks, false otherwise.
#
def check_validity=(setting)
end
#
# This method retrieves the commit tables setting for a Restore object.
#
def commit_tables
end
#
# This method updates the commit tables setting for a Restore object.
# This value affects whether the restore commits tables as they are
# restored.
#
# ==== Parameters
# setting:: True to commit tables as they are restored, false otherwise.
#
def commit_tables=(setting)
end
#
# This method retrieves the restore mode setting for a Restore object.
#
def restore_mode
end
#
# This method updates the restore mode setting for a Restore object.
# This value affects whether the restore will overwrite an existing
# database.
#
# ==== Parameters
# setting:: Either Restore::MODE_CREATE (default) or
# Restore::MODE_REPLACE.
#
def restore_mode=(setting)
end
#
# This method retrieves the use all space setting for a Restore object.
#
def use_all_space
end
#
# This method updates the use all space setting for a Restore object.
# This value affects whether restore leaves space within the database
# file for expansion. This can be switched on for read only databases.
#
# ==== Parameters
# setting:: True leave no default expansion space within the restored
# database file, false otherwise.
#
def use_all_space=(setting)
end
#
# This method is used to execute a restore task against a service manager.
#
# ==== Parameters
# manager:: A reference to the service manager to execute the restore
# task against.
#
# ==== Exceptions
# IBRubyException:: Generated whenever a disconnected service manager
# is specified or a problem occurs executing the
# task.
#
def execute(manager)
end
#
# This method fetches the log value for a Restore task. This value will
# always be nil until the task has been executed. After a successful
# execution the log value should contain output from the restore task
# generated on the server.
#
def log
end
end
end
|
class IsValidUrlValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
begin
endpoint = URI.parse(value)
rescue URI::Error
record.errors.add(attribute, 'Malformed URI')
return false
end
unless endpoint.scheme
record.errors.add(attribute, 'Please specify either http or https')
end
unless endpoint.host
record.errors.add(attribute, 'Endpoint is invalid')
end
end
end
|
require 'rails_helper'
RSpec.describe Artist, type: :model do
it { should validate_presence_of :name }
it { should have_many :tracks }
it "is valid after creation" do
artist = build :artist
expect(artist.valid?).to be true
end
end
|
class RemindersController < ApplicationController
before_filter :authenticate_user!
def new
@kid = Kid.find(params[:kid_id])
@reminder = @kid.reminders.build
end
def create
@kid = Kid.find(params[:kid_id])
@reminder = @kid.reminders.create(reminder_params)
if @reminder.save
redirect_to user_path, notice: "#{@reminder.name} added for #{@kid.name}!"
else
render :new
end
end
def update
@reminder = Reminder.find(params[:id])
@reminder.touch
redirect_to user_path, notice: "#{@reminder.name} reminder was updated!"
end
def destroy
@reminder = Reminder.find(params[:id])
@reminder.destroy
redirect_to user_path, notice: "#{@reminder.name} reminder was deleted!"
end
private
def reminder_params
params.require(:reminder).permit(:name, :kid_id)
end
end
|
require 'bundler/gem_tasks'
require 'github/markup'
require 'redcarpet'
require 'rspec'
require 'rspec/core/rake_task'
require 'rubocop/rake_task'
require 'yard'
require 'yard/rake/yardoc_task'
require 'colorize'
args = [:spec, :make_bin_executable, :yard, :rubocop, :check_binstubs]
YARD::Rake::YardocTask.new do |t|
OTHER_PATHS = %w().freeze
t.files = ['lib/**/*.rb', 'bin/**/*.rb', OTHER_PATHS]
t.options = %w(--markup-provider=redcarpet --markup=markdown
--main=README.md)
end
RuboCop::RakeTask.new(:rubocop)
RSpec::Core::RakeTask.new(:spec)
desc 'Make all plugins executable'
task :make_bin_executable do
puts "make plugins executable\n\n"
`chmod -R +x bin/*`
end
desc 'Test for binstubs'
task :check_binstubs do
puts "\nTest for binstubs"
spec = Gem::Specification.load('sensu-plugins-xmatters.gemspec')
bin_list = spec.executables
bin_list.each do |b|
`which #{ b }`
unless $CHILD_STATUS.success?
puts "#{b} was not a binstub"
exit
end
end
puts "binstub check passes\n".green
end
task default: args
|
# coding: utf-8
Gem::Specification.new do |s|
s.name = 'simple-currency-converter'
s.version = '0.0.6'
s.authors = ['RETAILCOMMON DEV (Scott Chu, Justine Jones, Jeff Li, Greg Ward)']
s.email = ['dev@retailcommon.com']
s.summary = 'Web client to retrieve currency exchange rates'
s.description = 'Web client to retrieve currency exchange rates'
s.homepage = 'http://yroo.com'
s.license = 'MIT'
s.files = `git ls-files -z`.split("\x0")
s.executables = s.files.grep(%r{^bin/}) { |f| File.basename(f) }
s.test_files = s.files.grep(%r{^(test|spec|features)/})
s.require_paths = ['lib']
s.add_development_dependency 'bundler', '~> 1.6'
s.add_development_dependency 'rake'
s.add_development_dependency 'guard-rspec'
s.add_development_dependency 'guard-shell'
s.add_development_dependency 'rspec-rails'
s.add_development_dependency 'rspec-mocks'
s.add_development_dependency 'rspec-its'
end
|
class User < ApplicationRecord
has_many :microposts
validates :email, presence:true
validates :name, presence:true
end
|
require 'test_helper'
class D2L::MeasurementTest < Minitest::Unit::TestCase
def valid_measurement
D2L::Measurement.new(dataclip_reference: 'ref',
librato_base_name: 'default',
run_interval: 50)
end
def test_validations
assert valid_measurement.valid?
end
def test_dataclip_reference_presence
no_dataclip = valid_measurement
no_dataclip.dataclip_reference = nil
refute no_dataclip.valid?
assert_includes no_dataclip.errors, :dataclip_reference
end
def test_librato_base_name_presence
no_librato = valid_measurement
no_librato.librato_base_name = nil
refute no_librato.valid?
assert_includes no_librato.errors, :librato_base_name
end
def test_run_interval_presence
no_run_interval = valid_measurement
no_run_interval.run_interval = nil
# We set a default value in before_validation
assert no_run_interval.valid?
end
def test_dataclip_reference_uniqueness
DB.transaction(rollback: :always) do
valid_measurement.save
duplicate_dataclip_reference = valid_measurement
refute duplicate_dataclip_reference.valid?
# I do not understand why here it is an array...
assert_includes duplicate_dataclip_reference.errors, [:dataclip_reference]
end
end
def test_to_json
json = "{\"dataclip_reference\":\"ref\",\"librato_base_name\":\"default\",\"run_interval\":50}"
assert_equal valid_measurement.to_json, json
end
def test_outdated
DB.transaction(rollback: :always) do
outdated = D2L::Measurement.create(dataclip_reference: 'down',
librato_base_name: 'd')
up_to_date = D2L::Measurement.create(dataclip_reference: 'up',
librato_base_name: 'd',
run_at: Time.now)
assert_includes D2L::Measurement.outdated, outdated
refute_includes D2L::Measurement.outdated, up_to_date
end
end
def test_just_run!
DB.transaction(rollback: :always) do
now = Time.now
Time.stub :now, now do
m = D2L::Measurement.create(dataclip_reference: 'down',
librato_base_name: 'd')
D2L::Measurement.just_run!(m.id)
assert_equal m.reload.run_at, Time.now
end
end
end
def test_has_dataclip?
DB.transaction(rollback: :always) do
m = D2L::Measurement.create(dataclip_reference: 'down',
librato_base_name: 'd')
assert D2L::Measurement.has_dataclip?(m.dataclip_reference)
refute D2L::Measurement.has_dataclip?('fake_id')
end
end
end
|
require 'fog'
module Migrant
module Clouds
# Base class for cloud service providers.
# All service providers use Fog to handle bootstrapping servers and running stuff
# Cloud service providers are responsible for starting up the server, setting up ssh
# access with the provided keypair, and (eventually) disabling the root user.
class Base
# Register a provider
def self.register(shortcut)
@@clouds ||= {}
@@clouds[shortcut] = self
end
# Get a registered provider
def self.registered(shortcut)
@@clouds[shortcut]
end
def initialize(env)
@environment = env
@server_def = {:private_key_path => @environment.setting('ssh.private_key'),
:public_key_path => @environment.setting('ssh.public_key')}
flavor_id = @environment.setting('provider.flavor_id')
@server_def[:flavor_id] = flavor_id unless flavor_id.nil?
image_id = @environment.setting('provider.image_id')
@server_def[:image_id] = image_id unless image_id.nil?
end
attr_accessor :connection
def connect
raise "Invalid Action for Base Class"
end
def bootstrap_server
@environment.ui.info "Launching Server..."
@environment.server = @connection.servers.bootstrap(@server_def)
@environment.ui.notice "Server Launched!"
ip_address = @environment.setting('provider.ip_address')
unless ip_address.nil?
@connection.associate_address(@environment.server.id,ip_address)
end
log_server_info
end
def log_server_info
@environment.ui.notice " ID: #{@environment.server.id}"
end
# Set up connection information for a server and set up SSH keypair access
#
# box - Migrant::Box object with information about the server to connect to
#
# Does not return anything but sets up @environment.server
def connect_to_server(box)
@environment.ui.notice "Connecting to #{box.provider.to_s} server: #{box.id}"
@environment.server = @connection.servers.get(box.id)
if (@environment.server.nil?)
@environment.ui.error "Cannot connect to server!"
raise "Cannot find server"
end
@environment.server.merge_attributes(@server_def)
end
def execute(commands)
server = @environment.server
commands.each do |cmd|
@environment.ui.info("$ #{cmd}")
result = server.ssh cmd
if (result[0].status != 0)
@environment.ui.info(result[0].stdout)
@environment.ui.error "Error executing command: #{cmd}\n#{result.inspect}"
raise "Remote Script Error"
end
@environment.ui.info(result[0].stdout)
@environment.ui.warn(result[0].stderr) if result[0].stderr
end
end
# Asks the user if they want to shut down a box
#
# box - A Migrant::Box with information about the box
#
# returns true if the user decided to shut down the box
def destroy(box)
if (@environment.ui.yes?("Are you sure you want to shut down box #{box.name}?",:red))
@environment.ui.notice "Shutting down box #{box.name} id: #{box.id}"
connect
@connection.servers.get(box.id).destroy
return true
end
return false
end
end
end
end
|
require 'test_helper'
class TaskTest < ActiveSupport::TestCase
fixtures :teamcommitments, :employees
def test_empty
tsk = Task.new()
assert !tsk.valid?
assert tsk.errors.invalid?(:teamcommitment_id)
assert tsk.errors.invalid?(:employee_id)
assert !tsk.save
end
def test_create_bogus_commitment
tsk=Task.new(:teamcommitment_id => 1000, :employee_id => 1)
assert !tsk.valid?
assert tsk.errors.invalid?(:teamcommitment_id)
end
def test_create_bogus_ee
tsk=Task.new(:teamcommitment_id => 2, :employee_id => 1234)
assert !tsk.valid?
assert tsk.errors.invalid?(:employee_id)
end
def test_duplicate
tsk=Task.new(:teamcommitment_id => 2, :employee_id => 2)
assert !tsk.valid?
assert !tsk.save
end
def test_create_ok
tsk=Task.new(:teamcommitment_id => 2, :employee_id => 1)
assert tsk.valid?
assert tsk.save!
end
end
|
class CpsController < ApplicationController
def index
@sort_by = params[:sort_by] || 'name'
order_by = @sort_by.downcase
order_by = 'created_at' if order_by == 'created'
@cps = Cp.order(order_by)
@cpDetails = Cp.getNumLeaves
respond_to do |format|
format.html # index.html.erb
format.json { render json: @cps }
format.csv { send_data Cp.order(:name).to_csv }
end
end
def show
@cp = Cp.find(params[:id])
@deposits = Deposit.find_all_by_cp_id(@cp.id)
end
def new
@cp = Cp.new
end
def edit
@cp = Cp.find(params[:id])
end
def create
@cp = Cp.create!(params[:cp])
flash[:notice] = "#{@cp.name} was successfully created."
redirect_to cps_path
end
def update
@cp = Cp.find params[:id]
@cp.update_attributes!(params[:cp])
flash[:notice] = "#{@cp.name} was successfully updated."
redirect_to cp_path(@cp)
end
def destroy
@cp = Cp.find(params[:id])
@cp.destroy
flash[:notice] = "Collection Point '#{@cp.name}' deleted."
redirect_to cps_path
end
def import
if params[:file]
Cp.import(params[:file])
redirect_to cps_path, notice: "Products imported."
else
flash[:notice] = "No file selected to import"
redirect_to cps_path
end
end
end
|
if defined?(ChefSpec)
def create_dnsimple_record(name)
ChefSpec::Matchers::ResourceMatcher.new(:dnsimple_record, :create, name)
end
def delete_dnsimple_record(name)
ChefSpec::Matchers::ResourceMatcher.new(:dnsimple_record, :delete, name)
end
def update_dnsimple_record(name)
ChefSpec::Matchers::ResourceMatcher.new(:dnsimple_record, :update, name)
end
end
|
require 'showbuilder/builders/model_list_builder'
module Showbuilder
module ShowModelList
#
# show_model_list @products do |list|
# list.show_column :x_field
# list.show_text_column :x_field
# list.show_currency_column :x_field
# list.show_percent_column :x_field
# list.show_date_column :x_field
# list.show_time_column :x_field
# list.show_text_link_column :x_field
# list.show_currency_link_column :x_field
# list.show_percent_link_column :x_field
# list.show_date_link_column :x_field
# list.show_time_link_column :x_field
# end
#
def show_model_list(models, text_group = nil, &block)
builder = Showbuilder::Builders::ModelListBuilder.new(self, text_group)
builder.build_model_list(models, &block)
end
end
end
|
class Api::V1::TiporeporteController < Api::V1::BaseController
respond_to :json
def index
tiporeporte = Tiporeporte.all
render json: tiporeporte
end
def show
respond_with Tiporeporte.find(params[:id])
end
# Creando tipo reporte
def create
tiporeporte=Tiporeporte.new(tiporeporte_params)
if tiporeporte.save
render json: tiporeporte, status: 201
else
render json: { errors: tiporeporte.errors}, status: 422
end
end
# Actualizando tipo reporte
def update
tiporeporte = Tiporeporte.find(params[:id])
if tiporeporte.update(tiporeporte_params)
render json: tiporeporte, status: 201
else
render json: { errors: tiporeporte.errors }, status: 422
end
end
private
def tiporeporte_params
params.require(:tiporeporte).permit(:nombre)
end
end |
# frozen_string_literal: true
class NewsItemLikesController < ApplicationController
before_action :set_news_item_like, only: %i[show edit update destroy]
def index
@news_item_likes = NewsItemLike.all
end
def show; end
def new
@news_item_like = NewsItemLike.new
end
def edit; end
def create
@news_item_like = NewsItemLike.new(news_item_like_params)
if @news_item_like.save
redirect_to @news_item_like, notice: 'News item like was successfully created.'
else
render :new
end
end
def update
if @news_item_like.update(news_item_like_params)
redirect_to @news_item_like, notice: 'News item like was successfully updated.'
else
render :edit
end
end
def destroy
@news_item_like.destroy
redirect_to news_item_likes_url, notice: 'News item like was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_news_item_like
@news_item_like = NewsItemLike.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def news_item_like_params
params.require(:news_item_like).permit(:news_item_id, :user_id)
end
end
|
class ContactoSerializer < MongoidSerializer
attributes :nombre, :email, :telefono
end
|
require 'couchrest_model'
class Audit < CouchRest::Model::Base
use_database "audit"
before_save :set_site_type, :set_user_id
def audit_id=(value)
self['_id']=value.to_s
end
def audit_id
self['_id']
end
property :record_id, String # Certificate/Child id
property :audit_type, String # Quality Control | Reprint | Audit | Deduplication | Incomplete Record | DC Record Rejection | HQ Record Rejection | HQ Void | HQ Re-Open | Potential Duplicate
property :level, String # Child | User
property :reason, String
property :user_id, String # User id
property :site_id, String
property :site_type, String #FACILITY, DC, HQ
property :change_log, [], :default => []
property :voided, TrueClass, :default => false
timestamps!
design do
view :by__id
view :by_record_id
view :by_record_id_and_audit_type
view :by_audit_type
view :by_level
view :by_reason
view :by_record_id_and_reason
view :by_user_id
view :by_site_id
view :by_site_type
view :by_voided
view :by_created_at
view :by_updated_at
view :by_level_and_created_at
view :by_level_and_user_id
filter :facility_sync, "function(doc,req) {return req.query.site_id == doc.site_id}"
end
def set_user_id
self.user_id = User.current_user.id rescue 'admin'
end
def set_site_type
self.site_type = "HQ"
end
end
|
class ConditionIsXmage < ConditionSimple
def match?(card)
card.xmage?(@time)
end
def metadata!(key, value)
super
@time = value if key == :time
end
def to_s
timify_to_s "game:xmage"
end
end
|
class Post < ApplicationRecord
belongs_to :city
validates :title, presence: true
validates :text, presence: true
end
|
##########################################################################
# Copyright 2016 ThoughtWorks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##########################################################################
module ApiV3
class AgentsController < ApiV3::BaseController
before_action :check_user_and_404
before_action :check_admin_user_and_401, except: [:index, :show]
before_action :set_default_values_if_not_present, only: [:bulk_update]
before_action :load_agent, only: [:show, :edit, :update, :destroy, :enable, :disable]
def index
presenters = AgentsRepresenter.new(agent_service.agentEnvironmentMap)
response_hash = presenters.to_hash(url_builder: self)
if stale?(etag: Digest::MD5.hexdigest(JSON.generate(response_hash)))
render DEFAULT_FORMAT => response_hash
end
end
def show
render DEFAULT_FORMAT => agent_presenter.to_hash(url_builder: self)
end
def update
result = HttpOperationResult.new
@agent_instance = agent_service.updateAgentAttributes(current_user, result, params[:uuid], params[:hostname], maybe_join(params[:resources]), maybe_join(params[:environments]), to_enabled_tristate)
if result.isSuccess
load_agent
render DEFAULT_FORMAT => agent_presenter.to_hash(url_builder: self)
else
json = agent_presenter.to_hash(url_builder: self)
render_http_operation_result(result, { data: json })
end
end
def destroy
result = HttpOperationResult.new
agent_service.deleteAgents(current_user, result, [params[:uuid]])
render_http_operation_result(result)
end
def bulk_update
result = HttpLocalizedOperationResult.new
uuids = params[:uuids]
resources_to_add = params[:operations][:resources][:add]
resources_to_remove = params[:operations][:resources][:remove]
environments_to_add = params[:operations][:environments][:add]
environment_to_remove = params[:operations][:environments][:remove]
agent_service.bulkUpdateAgentAttributes(current_user, result, uuids, resources_to_add, resources_to_remove, environments_to_add, environment_to_remove, to_enabled_tristate)
render_http_operation_result(result)
end
def bulk_destroy
result = HttpOperationResult.new
agent_service.deleteAgents(current_user, result, Array.wrap(params[:uuids]))
render_http_operation_result(result)
end
private
def set_default_values_if_not_present
params[:uuids] = params[:uuids] || []
params[:operations] = params[:operations] || {}
params[:operations][:resources] = params[:operations][:resources] || {}
params[:operations][:environments] = params[:operations][:environments] || {}
params[:operations][:resources][:add] = params[:operations][:resources][:add] || []
params[:operations][:resources][:remove] = params[:operations][:resources][:remove] || []
params[:operations][:environments][:add] = params[:operations][:environments][:add] || []
params[:operations][:environments][:remove] = params[:operations][:environments][:remove] || []
end
def maybe_join(obj)
if obj.is_a?(Array)
obj.join(',')
else
obj
end
end
private
attr_reader :agent_instance
def to_enabled_tristate
enabled = params[:agent_config_state]
if enabled.blank?
TriState.UNSET
elsif enabled =~ /\Aenabled\Z/i
TriState.TRUE
elsif enabled =~ /\Adisabled\Z/i
TriState.FALSE
else
raise BadRequest.new('The value of `agent_config_state` can be one of `Enabled`, `Disabled` or null.')
end
end
def load_agent
@agent_instance = agent_service.findAgent(params[:uuid])
raise RecordNotFound if @agent_instance.nil? || @agent_instance.isNullAgent()
end
def agent_presenter
AgentRepresenter.new([@agent_instance, environment_config_service.environmentsFor(@agent_instance.getUuid())])
end
end
end
|
require 'rails_helper'
require 'capybara/rails'
require 'capybara/rspec'
describe 'Item Manipulation', type: :feature do
around(:each) do |example|
DatabaseCleaner.start
example.run
DatabaseCleaner.clean
end
context 'as an unauthenticated user' do
let(:item) { FactoryGirl.build(:item) }
let(:category) { FactoryGirl.build(:category) }
let(:supplier) { FactoryGirl.create(:supplier) }
before do
item.supplier = supplier
category.supplier = supplier
category.save!(validate: false)
item.categories << category
item.save!
end
end
context 'when logged in as an admin' do
let(:admin) { FactoryGirl.create(:admin) }
let(:item) { FactoryGirl.build(:item) }
let(:category) { FactoryGirl.create(:category) }
let(:supplier) { FactoryGirl.create(:supplier) }
let(:user) {FactoryGirl.create(:user)}
before(:each) do
user.supplier = supplier
supplier.users << user
supplier.categories << category
visit login_path
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
click_button 'Login'
end
it 'can add a new item' do
visit new_supplier_item_path(slug: supplier.slug)
fill_in 'Title', with: 'Coffee'
fill_in 'Description', with: 'Black gold'
fill_in 'Price', with: 2.99
select(category.name, :from => 'category-select')
click_button 'Submit'
expect(page).to have_content('Item successfully created')
end
it 'can edit an existing item' do
item.categories << category
item.save
supplier.items << item
visit supplier_items_path(slug: supplier.slug)
click_link 'Edit'
expect(current_path).to eq(edit_supplier_item_path(id: item, slug: supplier.slug))
fill_in 'Title', with: 'Lemur Juice'
click_button 'Submit'
expect(page).to have_content('Item was successfully updated.')
end
end
end
|
require_relative '../../../spec_helper'
describe ::Composer::Package::AliasPackage do
let(:package){ build :complete_package, name: 'foo', version: '1.0' }
let(:alias_package){ build :alias_package, alias_of: package, version: '2.0' }
[
:type,
:target_dir,
:extra,
:installation_source,
:source_type,
:source_url,
:source_urls,
:source_reference,
:source_mirrors,
:dist_type,
:dist_url,
:dist_urls,
:dist_reference,
:dist_sha1_checksum,
:transport_options,
:dist_mirrors,
:scripts,
:license,
:autoload,
:dev_autoload,
:include_paths,
:repositories,
:release_date,
:binaries,
:keywords,
:description,
:homepage,
:suggests,
:authors,
:support,
:notification_url,
:archive_excludes,
:abandoned?,
:replacement_package
].each do |method|
context ".#{method}" do
it 'forwards all calls to the aliased package' do
allow(package).to receive(method).twice.and_return(true)
expect( alias_package.send(method) ).to be == package.send(method)
end
end
# {
#
# :installation_source= => type,
# :source_reference= => reference,
# :source_mirrors= => mirrors,
# :dist_reference= => reference,
# :transport_options= => options,
# :dist_mirrors= => mirrors,
#
# }.each do |method|
#
# end
end
end
|
require 'io/console'
class Move
MOVE_VALUES = { 'r' => 'rock',
'p' => 'paper',
'sc' => 'scissors',
'sp' => 'spock',
'l' => 'lizard' }
WHAT_BEATS_WHAT = { 'rock' => ['scissors', 'lizard'],
'paper' => ['spock', 'rock'],
'scissors' => ['lizard', 'paper'],
'spock' => ['rock', 'scissors'],
'lizard' => ['paper', 'spock'] }
attr_reader :value
def initialize(val)
@value = val
end
def >(other_move)
WHAT_BEATS_WHAT[value].include?(other_move.value)
end
def to_s
@value
end
end
class Player
attr_accessor :move, :name, :score, :move_history
def initialize
@move_history = { 'rock' => 0,
'paper' => 0,
'scissors' => 0,
'spock' => 0,
'lizard' => 0 }
@score = 0
set_name
end
def to_s
@name
end
end
class Human < Player
def set_name
n = nil
print "What's your name? "
loop do
n = gets.chomp
break if n !~ /\s/ && n =~ /\w/
print "You must enter a valid name " \
"(must have a letter or digit, no spaces): "
end
self.name = n
end
def display_choices
message = <<-MSG
Please choose one of the following:
'r' for rock
'p' for paper
'sc' for scissors
'sp' for spock
'l' for lizard
MSG
puts message
end
def choose(game)
choice = nil
loop do
display_choices
choice = gets.chomp.downcase
break if Move::MOVE_VALUES.keys.include?(choice)
game.display_score
puts "Sorry, invalid choice."
end
game.display_score
update_move(choice)
end
def update_move(choice)
final_move = Move::MOVE_VALUES[choice]
self.move = Move.new(final_move)
move_history[final_move] += 1
end
end
class Computer < Player
COMPUTER_MOVES = { 'R2D2' => { 'rock' => 5, 'scissors' => 5 },
'Wallie' => { 'paper' => 3, 'spock' => 3, 'lizard' => 3 },
'C3PO' => { 'paper' => 10 },
'Chappie' => { 'spock' => 7, 'lizard' => 3 },
'Eva' => { 'lizard' => 10 } }
def set_name
self.name = ['R2D2', 'Wallie', 'C3PO', 'Chappie', 'Eva'].sample
end
def choose
possible_moves = []
COMPUTER_MOVES[name].each do |move, counts|
counts.times { possible_moves << move }
end
update_move(possible_moves)
end
def update_move(possible_moves)
final_move = possible_moves.sample
self.move = Move.new(final_move)
move_history[final_move] += 1
end
end
class RPSGame
SCORE_TO_WIN = 10
attr_accessor :human, :computer
def initialize
clear
@human = Human.new
@computer = Computer.new
end
def clear
system('clear')
end
def continue_game
puts "(Press any button to continue)"
STDIN.getch
print " \r"
end
def display_welcome_message
clear
puts "Welcome to Rock, Paper, Scissors, Spock, Lizard!"
puts "First to win #{SCORE_TO_WIN} games will be the grand winner!"
continue_game
end
def display_score
clear
puts "The score is #{human.name} - #{human.score} : " \
"#{computer.name} - #{computer.score}"
end
def display_moves
puts "#{human.name} chose #{human.move}."
puts "#{computer.name} chose #{computer.move}."
end
def calculate_winner
if human.move > computer.move
human
elsif computer.move > human.move
computer
else
"tie"
end
end
def show_move_history?
puts "Display move history?"
puts "(Y to display, any other key to continue)"
answer = gets.chomp.downcase
answer == 'y'
end
def display_game_winner(winner)
case winner
when human
puts "#{human.name} wins!"
when computer
puts "#{computer.name} wins!"
else
puts "It's a tie!"
end
puts
calculate_move_history unless grand_winner? || !show_move_history?
end
def calculate_move_history
length = [human.name, computer.name].max_by(&:length).length + 6
[human, computer].each do |player|
move_list = []
player.move_history.each do |move, count|
move_list << "#{move}: #{count}"
end
display_move_history(player, move_list, length)
end
continue_game
end
def display_move_history(player, move_list, length)
puts "#{player.name} moves".ljust(length) +
" - #{move_list.join(', ')}"
end
def update_score(winner)
return unless [human, computer].include?(winner)
winner.score += 1
end
def grand_winner?
human.score == SCORE_TO_WIN || computer.score == SCORE_TO_WIN
end
def display_grand_winner
if human.score == SCORE_TO_WIN
puts "#{human.name} is the first to #{SCORE_TO_WIN} games!"
else
puts "#{computer.name} is the first to #{SCORE_TO_WIN} games!"
end
end
def display_goodbye_message
puts "Thanks for playing Rock, Paper, Scissors, Spock, Lizard. Good bye!"
end
def play_again?
answer = nil
loop do
puts "Would you like to play again? (Y/N)"
answer = gets.chomp.downcase
break if ['y', 'n'].include?(answer)
puts "Invalid answer. Please enter y or n."
end
reset_score
answer == 'y'
end
def reset_score
human.score = 0
computer.score = 0
end
def play_individual_games
loop do
display_score
human.choose(self)
computer.choose
update_score(calculate_winner)
return if grand_winner?
display_moves
display_game_winner(calculate_winner)
end
end
def display_final_results
display_score
display_moves
display_game_winner(calculate_winner)
display_grand_winner
end
def play
display_welcome_message
loop do
play_individual_games
display_final_results
break unless play_again?
end
display_goodbye_message
end
end
RPSGame.new.play
|
Rails.application.routes.draw do
get 'test/search'
get 'test/index'
get 'test/test'
root 'movies#search'
post '/search', to: 'movies#find'
get '/search', to: 'movies#search'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.