text stringlengths 10 2.61M |
|---|
require "helper"
describe Bridge::Points::Duplicate do
it "maximum points with unique values" do
maximum = Bridge::Points::Duplicate.new(-200, -100, 620, 630, 660, 690).maximum
assert_equal 10, maximum[690]
assert_equal 8, maximum[660]
assert_equal 6, maximum[630]
assert_equal 4, maximum[620]
assert_equal 2, maximum[-100]
assert_equal 0, maximum[-200]
end
it "maximum points with non-unique values" do
maximum = Bridge::Points::Duplicate.new(420, 420, 400, 400, -50, -100).maximum
assert_equal 9, maximum[420]
assert_equal 5, maximum[400]
assert_equal 2, maximum[-50]
assert_equal 0, maximum[-100]
end
it "maximum points with non-unique values, without zero value" do
maximum = Bridge::Points::Duplicate.new(430, 420, 420, 420, 300, 300).maximum
assert_equal 10, maximum[430]
assert_equal 6, maximum[420]
assert_equal 1, maximum[300]
end
it "maximum percents with non-unique values" do
maximum_in_percents = Bridge::Points::Duplicate.new(-630, 100, 100, -600, 200, -600, 100, 100, 100, -600, 100, 100, 100, 100).maximum_in_percents
assert_in_delta 100.0, maximum_in_percents[200], 0.05
assert_in_delta 61.5, maximum_in_percents[100], 0.05
assert_in_delta 15.4, maximum_in_percents[-600], 0.05
assert_in_delta 0.0, maximum_in_percents[-630], 0.05
end
it "maximum percents with unique-values" do
maximum_in_percents = Bridge::Points::Duplicate.new(200, 170, 500, 430, 550, 420).maximum_in_percents
assert_in_delta 100.0, maximum_in_percents[550], 0.005
assert_in_delta 80.0, maximum_in_percents[500], 0.005
assert_in_delta 60.0, maximum_in_percents[430], 0.005
assert_in_delta 40.0, maximum_in_percents[420], 0.005
assert_in_delta 20.0, maximum_in_percents[200], 0.005
assert_in_delta 0.0, maximum_in_percents[170], 0.005
end
it "butler with skipping the highest and the lowest score" do
butler = Bridge::Points::Duplicate.new(690, 660, 630, 620, -100, -200).butler
assert_equal 6, butler[690]
assert_equal 5, butler[660]
assert_equal 5, butler[630]
assert_equal 5, butler[620]
assert_equal -11, butler[-100]
assert_equal -12, butler[-200]
end
it "cavendish with unique values" do
cavendish = Bridge::Points::Duplicate.new(690, 660, 630, 620, -100, -200).cavendish
assert_in_delta 6.2, cavendish[690], 0.05
assert_in_delta 5.4, cavendish[660], 0.05
assert_in_delta 4.4, cavendish[630], 0.05
assert_in_delta 4.4, cavendish[620], 0.05
assert_in_delta -9.4, cavendish[-100], 0.05
assert_in_delta -11.0, cavendish[-200], 0.05
end
it "cavendish with non-unique values" do
cavendish = Bridge::Points::Duplicate.new(100, 100, 110, 140).cavendish
assert_in_delta 1.0, cavendish[140], 0.05
assert_in_delta -0.3, cavendish[110], 0.05
assert_in_delta -0.3, cavendish[100], 0.05
end
end
|
def source
<<eos
protocol MyAwesomeProtocol {
func foo(i:Bool)->String
func bar(k:String)->Int
func baz(w:Int)->Bool
}
eos
end
def expected_tokens
[
T_PROTOCOL,
T_WHITESPACES(' '),
T_IDENTIFIER('MyAwesomeProtocol'),
T_WHITESPACES(' '),
T_OPEN_CURLY_BRACKET,
T_WHITESPACES("\n "),
T_FUNCTION,
T_WHITESPACES(' '),
T_IDENTIFIER('foo'),
T_OPEN_ROUND_BRACKET,
T_IDENTIFIER('i'),
T_COLON,
T_IDENTIFIER('Bool'),
T_CLOSE_ROUND_BRACKET,
T_RETURN_TYPE_ARROW,
T_IDENTIFIER('String'),
T_WHITESPACES("\n "),
T_FUNCTION,
T_WHITESPACES(' '),
T_IDENTIFIER('bar'),
T_OPEN_ROUND_BRACKET,
T_IDENTIFIER('k'),
T_COLON,
T_IDENTIFIER('String'),
T_CLOSE_ROUND_BRACKET,
T_RETURN_TYPE_ARROW,
T_IDENTIFIER('Int'),
T_WHITESPACES("\n "),
T_FUNCTION,
T_WHITESPACES(' '),
T_IDENTIFIER('baz'),
T_OPEN_ROUND_BRACKET,
T_IDENTIFIER('w'),
T_COLON,
T_IDENTIFIER('Int'),
T_CLOSE_ROUND_BRACKET,
T_RETURN_TYPE_ARROW,
T_IDENTIFIER('Bool'),
T_WHITESPACES("\n"),
T_CLOSE_CURLY_BRACKET,
T_WHITESPACES("\n")
]
end
def expected_ast
{
__type: 'program',
body: [
{
__type: 'protocol-declaration',
name: {
__type: 'identifier',
value: 'MyAwesomeProtocol'
},
inheritances: [],
declarations: [
{
__type: 'function-declaration',
name: {
__type: 'identifier',
value: 'foo'
},
parameters: [
{
__type: 'function-declaration-parameter',
type: {
__type: 'identifier',
value: 'Bool'
},
local: {
__type: 'identifier',
value: 'i'
},
external: nil,
default: nil
}
],
return_type: {
__type: 'identifier',
value: 'String'
}
},
{
__type: 'function-declaration',
name: {
__type: 'identifier',
value: 'bar'
},
parameters: [
{
__type: 'function-declaration-parameter',
type: {
__type: 'identifier',
value: 'String'
},
local: {
__type: 'identifier',
value: 'k'
},
external: nil,
default: nil
}
],
return_type: {
__type: 'identifier',
value: 'Int'
}
},
{
__type: 'function-declaration',
name: {
__type: 'identifier',
value: 'baz'
},
parameters: [
{
__type: 'function-declaration-parameter',
type: {
__type: 'identifier',
value: 'Int'
},
local: {
__type: 'identifier',
value: 'w'
},
external: nil,
default: nil
}
],
return_type: {
__type: 'identifier',
value: 'Bool'
}
}
]
}
]
}
end
load 'spec_builder.rb'
|
=begin
doctest: hash_string_to_pairs(string) separates a string with a key/value pair into separate strings
>> key = ':id'
>> value = rand(10).to_i.to_s
>> test_string = "#{key}=#{value}"
>> arr = hash_string_to_pairs( test_string )
>> arr == [key, value]
=> true
=end
def hash_string_to_pairs( hash_string )
key, value = hash_string.split( '=' )
if key && value then return key, value end
raise "invalid input (hash_string = '#{hash_string}') should follow key=value format"
end
|
class TasksController < ApplicationController
def index
@task = Task.new
@tasks = Task.all
end
def create
@task = Task.new(params[:task])
if @task.save
redirect_to :back, :notice => "New task added successfully"
else
redirect_to :back, :notice => "Task cannot be empty!"
end
end
def edit
@task = Task.find(params[:id])
end
def update
@task = Task.find(params[:id])
if @task.update_attributes(params[:task])
redirect_to tasks_path, :notice => 'Your task has been updated successfully!'
else
redirect_to :back, :notice => 'There was an error updating your task'
end
end
def destroy
@task = Task.find(params[:id])
if @task.destroy
redirect_to tasks_path, :notice => "Task Deleted successfully"
else
redirect_to tasks_path, :notice => "There was an error deleting your task"
end
end
end
|
class Api::V1::SusuInvitesController < Api::V1::BaseController
before_action :set_susu_invite, only: [:show, :update, :destroy]
def_param_group :susu_invite do
param :susu_invite, Hash, required: true, action_aware: true do
param :accepted, [true, false], required: true, allow_nil: false
param :sender_id, Integer, required: true, allow_nil: false
param :recipient_id, Integer, required: true, allow_nil: false
param :susu_id, Integer, required: true, allow_nil: false
end
end
#api :GET, '/susu_invites', 'List Susu Invites'
def index
@susu_invites = SusuInvite.page(params[:page]).per(params[:per])
render json: @susu_invites
end
#api :GET, '/susu_invites/:id', 'Show Susu Invite'
def show
render json: @susu_invite
end
#api :POST, '/susu_invites', 'Create Susu Invite'
param_group :susu_invite
def create
@susu_invite = SusuInvite.new(susu_invite_params)
if @susu_invite.save
render json: @susu_invite, status: :created, location: @susu_invite
else
render json: @susu_invite.errors, status: :unprocessable_entity
end
end
#api :PUT, '/susu_invites/:id', 'Update Susu Invite'
param_group :susu_invite
def update
if @susu_invite.update(susu_invite_params)
render json: @susu_invite
else
render json: @susu_invite.errors, status: :unprocessable_entity
end
end
#api :DELETE, '/susu_invites/:id', 'Destroy Susu Invite'
def destroy
@susu_invite.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_susu_invite
@susu_invite = SusuInvite.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def susu_invite_params
params.require(:susu_invite).permit(:accepted, :sender_id, :recipient_id, :susu_id)
end
end
|
module JrubyMahout
java_package 'org.apache.mahout.cf.taste.recommender'
class CustomRescorer
include org.apache.mahout.cf.taste.recommender.IDRescorer
def initialize(is_filtered_block, re_score_block)
@is_filtered_block = is_filtered_block
@re_score_block = re_score_block
end
def isFiltered(id)
@is_filtered_block.call(id)
end
def rescore(id, original_score)
@re_score_block.call(id, original_score)
end
end
end |
class RootController < ActionController::Base
def root
render file: 'public/index.html'
end
end
|
Polycloud::Application.routes.draw do
root 'welcome#index'
scope module: 'api' do
api_version(1) do
scope module: 'users' do
resources :users, controller: 'main', only: [:show, :create]
resources :sessions, only: :create
end
scope module: 'snippets' do
resources :snippets, controller: 'main'
resources :languages
end
end
end
end
|
Rails.application.routes.draw do
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
namespace :admin do
resources :users
end
root 'home#new'
resources :books, except: [:destroy]
resources :cards do
resources :books, only: [:index, :show]
end
resources :histories, except: [:destroy, :update]
end
|
Gem::Specification.new do |s|
s.name = 'cartodb-utils'
s.version = '0.0.10'
s.date = '2015-04-20'
s.summary = "Ruby CartoDB utils"
s.description = "Ruby CartoDB utils"
s.authors = ["Luis Bosque"]
s.email = 'luisico@gmail.com'
s.files = [
"lib/cartodb-utils.rb",
"lib/cartodb-utils/metrics.rb",
"lib/cartodb-utils/metrics/elasticsearch.rb",
"lib/cartodb-utils/metrics/sqlapi.rb",
"lib/cartodb-utils/mail.rb",
"lib/cartodb-utils/mail/mandrill.rb"
]
s.add_dependency 'typhoeus', '>= 0.6.9'
s.homepage =
'https://github.com/lbosque/cartodb-utils'
s.license = 'MIT'
end
|
$LOAD_PATH.unshift(".")
require 'env'
require 'shopify'
require 'sqlite3'
require 'ostruct'
def main
find_series.each do |series|
upload_series(series)
end
end
def db
@db ||= SQLite3::Database.new("wfth.db")
end
def shop
@shop ||= ShopifyAPI::Shop.current
end
def upload_series(series)
series_product = ShopifyAPI::Product.new
series_product.title = series.title
series_product.product_type = "Series"
series_product.handle = product_handle(series.title)
series_product.body_html = series_body_html(series)
series_product.variants = [
ShopifyAPI::Variant.new(
sku: "series-#{series.id}",
price: series.price
)
]
series_product.save
series.sermons.each do |sermon|
upload_sermon(series, sermon)
end
end
def upload_sermon(series, sermon)
sermon_product = ShopifyAPI::Product.new
sermon_product.title = sermon.title
sermon_product.product_type = "Sermon"
sermon_product.handle = product_handle(sermon.title)
sermon_product.body_html = sermon_body_html(series, sermon)
sermon_product.variants = [
ShopifyAPI::Variant.new(
sku: "sermon-#{sermon.id}",
price: sermon.price
)
]
sermon_product.save
end
def find_series
rows = db.execute2("select * from sermon_series")
columns = rows.shift
raise "Unexpected columns: #{columns}" unless columns == ["series_id", "title", "description", "released_on", "graphic_key", "buy_graphic_key", "price"]
rows.map do |row|
OpenStruct.new(
id: row[0],
title: row[1],
description: row[2],
price: row[6],
sermons: find_sermons(row[0])
)
end
end
def find_sermons(series_id)
rows = db.execute2("select * from sermons where sermon_series_id = ?", [series_id])
columns = rows.shift
raise "Unexpected columns: #{columns}" unless columns == ["sermon_id", "title", "passage", "sermon_series_id", "audio_key", "transcript_key", "buy_graphic_key", "price"]
rows.map do |row|
OpenStruct.new(
id: row[0],
title: row[1],
price: row[7]
)
end
end
def product_handle(title)
title.gsub(/[^A-Za-z0-9]/, '-').gsub(/[-]{2,}/, '-').sub(/-$/, '').downcase
end
def series_body_html(series)
%Q{<p class="description">#{series.description}</p>
<p class="series-sermons">Sermons in this series:
<ol>#{series_sermons_body_html(series.sermons)}</ol>
</p>}
end
def series_sermons_body_html(sermons)
sermons.map do |sermon|
%Q{<li class="sermon">#{product_link(sermon.title)}</li>}
end.join("\n")
end
def sermon_body_html(series, sermon)
%Q{<p class="description">#{sermon.description}</p>
<p>This sermon is a part of the series #{product_link(series.title)}.</p>}
end
def product_link(title)
%Q{<a href="#{product_url(title)}">#{title}</a>}
end
def product_url(title)
"https://#{WFTH_SHOPIFY_SHOP_NAME}.myshopify.com/products/#{product_handle(title)}"
end
main()
|
class SearchSubscriptionItem
include Mongoid::Document
include Mongoid::Timestamps
field :raw_plane_id
field :search_subscription_id
field :content
field :item_type
field :sent_at
end |
class SessionsController < ApplicationController
def authenticate_user
auth_hash = request.env['omniauth.auth']
unless auth_hash.present?
redirect_to request.env['omniauth.origin'] || root_path,
status: 301,
alert: "Sorry, we were not able to authenticate you using your chosen sign on method" and return
end
sign_in_and_persist_new_or_existing_user(auth_hash)
redirect_to root_path, status: 301, notice: "You have successfully been authenticated through Facebook"
end
def failure
redirect_to session[:return_uri] || root_path,
status: 301,
alert: "Sorry, we were not able to authenticate you using your chosen sign on method"
end
def destroy
session[:user] = nil
redirect_to root_path, status: 301, notice: "You are now signed out"
end
end
|
require 'sqlite3'
require_relative 'questions'
class Reply
attr_accessor :id, :subject_question_id, :parent_reply_id, :user_id, :body
def self.find_by_id(id)
reply = QuestionsDatabase.instance.execute(<<-SQL, id)
SELECT
*
FROM
replies
WHERE
id = ?
SQL
return nil if reply.empty?
Reply.new(reply.first)
end
def self.find_by_user_id(user_id)
replies = QuestionsDatabase.instance.execute(<<-SQL, user_id)
SELECT
*
FROM
replies
WHERE
user_id = ?
SQL
return nil if replies.empty?
replies.map { |reply| Reply.new(reply) }
end
def self.find_by_question_id(subject_question_id)
replies = QuestionsDatabase.instance.execute(<<-SQL, subject_question_id)
SELECT
*
FROM
replies
WHERE
subject_question_id = ?
SQL
return nil if replies.empty?
replies.map { |reply| Reply.new(reply) }
end
def initialize(options)
@id = options['id']
@subject_question_id = options['subject_question_id']
@parent_reply_id = options['parent_reply_id']
@user_id = options['user_id']
@body = options['body']
end
def author
user = User.find_by_id(@user_id)
return nil if user.nil?
user
end
def question
question = Question.find_by_id(@subject_question_id)
return nil if question.nil?
question
end
def parent_reply
reply = Reply.find_by_id(@parent_reply_id)
return nil if reply.nil?
reply
end
def child_replies
reply = QuestionsDatabase.instance.execute(<<-SQL, @id, @subject_question_id)
SELECT
*
FROM
replies
WHERE
parent_reply_id = ? AND subject_question_id = ?
SQL
return nil if reply.empty?
Reply.new(reply.first)
end
end
|
require 'rubocop/git'
require 'optparse'
module RuboCop
module Git
class CLI
def run(args = ARGV)
@options = Options.new
parse_arguments(args)
Runner.new.run(@options)
end
private
def parse_arguments(args)
@options.commits = option_parser.parse(args)
rescue OptionParser::InvalidOption, Options::Invalid => ex
warn "ERROR: #{ex.message}"
$stderr.puts
warn option_parser
exit 1
end
def option_parser
@option_parser ||= OptionParser.new do |opt|
opt.banner << ' [[commit] commit]'
opt.on('-c', '--config FILE',
'Specify configuration file') do |config|
@options.config = config
end
opt.on('-r', '--require FILE',
'Require Ruby file') do |file|
require file
end
opt.on('-d', '--debug', 'Display debug info') do
@options.rubocop[:debug] = true
end
opt.on('-D', '--display-cop-names',
'Display cop names in offense messages') do
@options.rubocop[:display_cop_names] = true
end
opt.on('--cached', 'git diff --cached') do
@options.cached = true
end
opt.on('--staged', 'synonym of --cached') do
@options.cached = true
end
opt.on('--hound', 'Hound compatibility mode') do
@options.hound = true
end
opt.on('--version', 'Display version') do
puts RuboCop::Git::VERSION
exit 0
end
end
end
end
end
end
|
class Section < ActiveRecord::Base
belongs_to :state
belongs_to :area
belongs_to :subarea
belongs_to :crag
has_many :faces
has_many :walls
has_many :climbs
end
|
# -*- encoding: utf-8 -*-
$:.push File.expand_path('../lib', __FILE__)
require 'shrink/version'
Gem::Specification.new do |s|
s.name = 'shrink'
s.version = Shrink::VERSION
s.authors = ['Jacob Gillespie']
s.email = 'me@jacobwg.com'
s.homepage = 'https://github.com/jacobwg/shrink'
s.summary = 'A simple command-line interface to the Google closure compiler'
s.description = 'Shrink is a CLI for minifing assets - shrink currently supports Javascript through the Google Closure Compiler'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
# s.add_development_dependency 'rspec'
s.add_runtime_dependency 'closure-compiler'
s.add_runtime_dependency 'trollop'
end |
require "aethyr/core/actions/commands/command_action"
module Aethyr
module Core
module Actions
module Unwield
class UnwieldCommand < Aethyr::Extend::CommandAction
def initialize(actor, **data)
super(actor, **data)
end
def action
event = @data
room = $manager.get_object(@player.container)
player = @player
if event[:weapon] == "right" || event[:weapon] == "left"
weapon = player.equipment.get_wielded(event[:weapon])
if weapon.nil?
player.output "You are not wielding anything in your #{event[:weapon]} hand."
return
end
elsif event[:weapon].nil?
weapon = player.equipment.get_wielded
if weapon.nil?
player.output "You are not wielding anything."
return
end
else
weapon = player.equipment.find(event[:weapon])
if weapon.nil?
player.output "What are you trying to unwield?"
return
end
if not [:left_wield, :right_wield, :dual_wield].include? player.equipment.position_of(weapon)
player.output "You are not wielding #{weapon.name}."
return
end
end
if player.equipment.remove(weapon)
player.inventory << weapon
event[:to_player] = "You unwield #{weapon.name}."
event[:to_other] = "#{player.name} unwields #{weapon.name}."
room.out_event(event)
else
player.output "Could not unwield #{weapon.name}."
end
end
end
end
end
end
end
|
class Doccex::Base
attr_accessor :path_prefix
def path_to_tmp
path_prefix.nil? ? 'tmp' : "tmp/#{path_prefix}"
end
def tmp_file
Rails.application.root.join("#{path_to_tmp}/tmp_file.docx")
end
def zip_package(dir)
FileUtils.cd(dir) do
system "zip -qr #{tmp_file} . -x \*.DS_Store \*.git/\* \*.gitignore \*.gitkeep"
end
cleanup(dir)
end
def read_zipfile
string = File.read(tmp_file)
cleanup(tmp_file)
cleanup(path_to_tmp)
string
end
def cleanup(*files)
files.each do |f|
FileUtils.send(File.directory?(File.new(f)) ? "rm_r" : "rm",f)
end
end
end
|
module Engine
module Map
class Layer
attr_reader :index, :layer
def initialize(layer, options)
@index = layer.properties["index"]
@layer = layer
@options = options
end
def draw(x, y, tilesets)
draw_tiles(x, y, tilesets)
end
def screen_width_in_tiles
($window.width / tile_width.to_f).ceil
end
def screen_height_in_tiles
($window.height / tile_height.to_f).ceil
end
private
def offset_x_in_tiles(x)
x / tile_width
end
def offset_y_in_tiles(y)
y / tile_height
end
def draw_tiles(x, y, tilesets)
off_x = offset_x_in_tiles(x)
off_y = offset_y_in_tiles(y)
tile_range_x = (off_x..screen_width_in_tiles + off_x)
tile_range_y = (off_y..screen_height_in_tiles + off_y)
tile_range_x.each do |xx|
tile_range_y.each do |yy|
target_x = transpose_tile_x(xx, x)
target_y = transpose_tile_y(yy, y)
if within_map_range(x + target_x, y + target_y)
tilesets.get(tile_at(xx, yy)).draw(target_x, target_y, 0)
end
end
end
end
def within_map_range(x, y)
x.between?(0, map_width - 1) && y.between?(0, map_height - 1)
end
def within_screen_range(x, y)
x.between?(x - tile_width, $window.width + x + tile_width) && y.between?(y, $window.height + y + tile_height)
end
def transpose_tile_x(x, off_x)
x * tile_width - off_x
end
def transpose_tile_y(y, off_y)
y * tile_height - off_y
end
def tile_at(x, y)
@layer.data[y * @layer.width + x]
end
def tile_width
@options.tilewidth
end
def tile_height
@options.tileheight
end
def map_width
@options.width * tile_width
end
def map_height
@options.height * tile_height
end
end
end
end |
require 'set'
module OAuth2Provider
class AccessValidator
attr_accessor :driver, :request, :scope
def initialize(request, driver)
@request, @driver = request, driver
end
def halt klass, *args
line = caller.first
driver.logger.fatal(klass){ line }
throw CATCH_SYMBOL, klass.new(*args).to_a
end
def verify!(*required_scope)
# Errors defined in http://tools.ietf.org/html/rfc6750#section-3.1
realm = driver.realm
if signature = request.authorization('Bearer')
begin
@owner_id, @client_key, @scope, created_at, expires_in =
Tokens::Bearer.unserialize(driver.token_signer.unsign(signature))
rescue driver.unsign_error
halt InvalidTokenErrorResponse, realm: realm
end
# Check if not expired (if expires_in = 0, it means it doesn't expire)
if expires_in > 0 && Time.now.utc > created_at + expires_in
halt InvalidTokenErrorResponse, realm: realm
end
# Required scope should be included in provided scope
# TODO: token scope should be validated with owner<->client
# provided scope too
if driver.validate_scope(required_scope, scope, @client_key, @owner_id)
self
else
halt InsufficientScopeErrorResponse, required_scope, realm: realm
end
else
halt AccessRequiredResponse, realm: realm
end
end
def owner
@owner ||= driver.find_owner @owner_id
end
def client
@client ||= driver.find_client @client_key
end
def to_json
{
owner_id: @owner_id,
client_key: @client_key,
scope: @scope,
}.to_json
end
# == Unauthorized access responses
class AuthFailureResponse
def initialize(realm: realm)
@realm = realm
end
def to_a
[code, headers, body]
end
def code
401
end
def headers
{ 'WWW-Authenticate' => auth_failure_message }
end
def body
[]
end
def auth_failure_message
"Bearer realm=\"#{@realm}\""
end
end
class AccessRequiredResponse < AuthFailureResponse
end
class InvalidTokenErrorResponse < AuthFailureResponse
def auth_failure_message
super + ', error="invalid_token", error_description="Invalid token"'
end
end
class InsufficientScopeErrorResponse < AuthFailureResponse
def initialize(required_scope, **opts)
super(opts)
@required_scope = required_scope.join(' ')
end
def code
403
end
def auth_failure_message
super + ", error=\"insufficient_scope\", error_description=\"Insufficient scope\", scope=\"#{@required_scope}\""
end
end
end
end
|
require "rubygems"
require "selenium-webdriver"
require "rspec"
require "library"
describe "Prime Credit Card Transactions" do
before(:all) do
Configuration.config_path = File.dirname(__FILE__) + "/../../config/config.yml"
@config = Configuration.new
end
before(:each) do
Browser.type = @config.browser['browser']
@browser = Browser.new
@time = CustomTime.new
@time = @time.get_int_time/2
end
after(:each) do
@browser.shutdown()
end
###########################################
# BEGIN ANNUAL SUBSCRIPTION SUITE #
###########################################
it "should allow an Annual Visa transaction" do
subscribe_page = VindiciaSubscribePage.new
subscribe_page.client = @browser.client
payment_page = VindiciaPrimePayment.new
payment_page.client = @browser.client
receipt_page = VindiciaReceiptPage.new
receipt_page.client = @browser.client
subscribe_page.visit(@config.options['baseurl'])
#subscribe_page.logout
subscribe_page.select_subscription(@config.options['annual_name'])
subscribe_page.register_account({
:email => "fk-auto-#{@time}@ign.com",
:password => "boxofass",
:nickname => "fk-auto-#{@time}"
})
subscribe_page.continue
payment_page.choose_card_type("Visa")
payment_page.fill_cc_details({
:card_num => payment_page.generate_card_num("Visa"),
:card_cvv => payment_page.generate_random_cvv,
:name => 'Frank Klun',
:street_address => '625 2nd Street',
:city => 'San Francisco',
:state => 'CA',
:zip_code => payment_page.generate_random_zip,
:card_month => payment_page.generate_random_month,
:card_year => payment_page.generate_random_year
})
payment_page.submit_order
receipt_page.is_displayed.should be_true
receipt_page.order_date.should be_true
receipt_page.account_name("fk-auto-#{@time}").should be_true
receipt_page.package_name(@config.options['annual_name']).should be_true
receipt_page.package_price(@config.options['annual_price']).should be_true
vindicia = VindiciaAPI.new
vindicia.verify_transaction(vindicia.get_autobill_desc("fk-auto-#{@time}@ign.com"), @config.options['annual_autobill'])
topaz = Topaz.new
topaz.client = @browser.client
entitlements = TopazEntitlements.new
entitlements.client = @browser.client
entitlements.is_user_entitled(topaz.get_topaz_id("fk-auto-#{@time}"))
@@report.suite_end()
end
it "should allow an Annual MasterCard transaction" do
subscribe_page = VindiciaSubscribePage.new
subscribe_page.client = @browser.client
payment_page = VindiciaPrimePayment.new
payment_page.client = @browser.client
receipt_page = VindiciaReceiptPage.new
receipt_page.client = @browser.client
subscribe_page.visit(@config.options['baseurl'])
#subscribe_page.logout
subscribe_page.select_subscription(@config.options['annual_name'])
subscribe_page.register_account({
:email => "fk-auto-#{@time}@ign.com",
:password => "boxofass",
:nickname => "fk-auto-#{@time}"
})
subscribe_page.continue
payment_page.choose_card_type("MasterCard")
payment_page.fill_cc_details({
:card_num => payment_page.generate_card_num("MasterCard"),
:card_cvv => payment_page.generate_random_cvv,
:name => 'Frank Klun',
:street_address => '625 2nd Street',
:city => 'San Francisco',
:state => 'CA',
:zip_code => payment_page.generate_random_zip,
:card_month => payment_page.generate_random_month,
:card_year => payment_page.generate_random_year
})
payment_page.submit_order
receipt_page.is_displayed.should be_true
receipt_page.order_date.should be_true
receipt_page.account_name("fk-auto-#{@time}").should be_true
receipt_page.package_name(@config.options['annual_name']).should be_true
receipt_page.package_price(@config.options['annual_price']).should be_true
vindicia = VindiciaAPI.new
vindicia.verify_transaction(vindicia.get_autobill_desc("fk-auto-#{@time}@ign.com"), @config.options['annual_autobill'])
topaz = Topaz.new
topaz.client = @browser.client
entitlements = TopazEntitlements.new
entitlements.client = @browser.client
entitlements.is_user_entitled(topaz.get_topaz_id("fk-auto-#{@time}"))
@@report.suite_end()
end
it "should allow an Annual American Express transaction" do
subscribe_page = VindiciaSubscribePage.new
subscribe_page.client = @browser.client
payment_page = VindiciaPrimePayment.new
payment_page.client = @browser.client
receipt_page = VindiciaReceiptPage.new
receipt_page.client = @browser.client
subscribe_page.visit(@config.options['baseurl'])
#subscribe_page.logout
subscribe_page.select_subscription(@config.options['annual_name'])
subscribe_page.register_account({
:email => "fk-auto-#{@time}@ign.com",
:password => "boxofass",
:nickname => "fk-auto-#{@time}"
})
subscribe_page.continue
payment_page.choose_card_type("American Express")
payment_page.fill_cc_details({
:card_num => payment_page.generate_card_num("American Express"),
:card_cvv => payment_page.generate_random_cvv,
:name => 'Frank Klun',
:street_address => '625 2nd Street',
:city => 'San Francisco',
:state => 'CA',
:zip_code => payment_page.generate_random_zip,
:card_month => payment_page.generate_random_month,
:card_year => payment_page.generate_random_year
})
payment_page.submit_order
receipt_page.is_displayed.should be_true
receipt_page.order_date.should be_true
receipt_page.account_name("fk-auto-#{@time}").should be_true
receipt_page.package_name(@config.options['annual_name']).should be_true
receipt_page.package_price(@config.options['annual_price']).should be_true
vindicia = VindiciaAPI.new
vindicia.verify_transaction(vindicia.get_autobill_desc("fk-auto-#{@time}@ign.com"), @config.options['annual_autobill'])
topaz = Topaz.new
topaz.client = @browser.client
entitlements = TopazEntitlements.new
entitlements.client = @browser.client
entitlements.is_user_entitled(topaz.get_topaz_id("fk-auto-#{@time}"))
@@report.suite_end()
end
it "should allow an Annual Discover transaction" do
subscribe_page = VindiciaSubscribePage.new
subscribe_page.client = @browser.client
payment_page = VindiciaPrimePayment.new
payment_page.client = @browser.client
receipt_page = VindiciaReceiptPage.new
receipt_page.client = @browser.client
subscribe_page.visit(@config.options['baseurl'])
#subscribe_page.logout
subscribe_page.select_subscription(@config.options['annual_name'])
subscribe_page.register_account({
:email => "fk-auto-#{@time}@ign.com",
:password => "boxofass",
:nickname => "fk-auto-#{@time}"
})
subscribe_page.continue
payment_page.choose_card_type("Discover")
payment_page.fill_cc_details({
:card_num => payment_page.generate_card_num("Discover"),
:card_cvv => payment_page.generate_random_cvv,
:name => 'Frank Klun',
:street_address => '625 2nd Street',
:city => 'San Francisco',
:state => 'CA',
:zip_code => payment_page.generate_random_zip,
:card_month => payment_page.generate_random_month,
:card_year => payment_page.generate_random_year
})
payment_page.submit_order
receipt_page.is_displayed.should be_true
receipt_page.order_date.should be_true
receipt_page.account_name("fk-auto-#{@time}").should be_true
receipt_page.package_name(@config.options['annual_name']).should be_true
receipt_page.package_price(@config.options['annual_price']).should be_true
vindicia = VindiciaAPI.new
vindicia.verify_transaction(vindicia.get_autobill_desc("fk-auto-#{@time}@ign.com"), @config.options['annual_autobill'])
topaz = Topaz.new
topaz.client = @browser.client
entitlements = TopazEntitlements.new
entitlements.client = @browser.client
entitlements.is_user_entitled(topaz.get_topaz_id("fk-auto-#{@time}"))
@@report.suite_end()
end
###########################################
# BEGIN 2 YEAR SUBSCRIPTION SUITE #
###########################################
it "should allow a 2 Year Visa transaction" do
subscribe_page = VindiciaSubscribePage.new
subscribe_page.client = @browser.client
payment_page = VindiciaPrimePayment.new
payment_page.client = @browser.client
receipt_page = VindiciaReceiptPage.new
receipt_page.client = @browser.client
subscribe_page.visit(@config.options['baseurl'])
#subscribe_page.logout
subscribe_page.select_subscription(@config.options['2year_name'])
subscribe_page.register_account({
:email => "fk-auto-#{@time}@ign.com",
:password => "boxofass",
:nickname => "fk-auto-#{@time}"
})
subscribe_page.continue
payment_page.choose_card_type("Visa")
payment_page.fill_cc_details({
:card_num => payment_page.generate_card_num("Visa"),
:card_cvv => payment_page.generate_random_cvv,
:name => 'Frank Klun',
:street_address => '625 2nd Street',
:city => 'San Francisco',
:state => 'CA',
:zip_code => payment_page.generate_random_zip,
:card_month => payment_page.generate_random_month,
:card_year => payment_page.generate_random_year
})
payment_page.submit_order
receipt_page.is_displayed.should be_true
receipt_page.order_date.should be_true
receipt_page.account_name("fk-auto-#{@time}").should be_true
receipt_page.package_name(@config.options['2year_name']).should be_true
receipt_page.package_price(@config.options['2year_price']).should be_true
vindicia = VindiciaAPI.new
vindicia.verify_transaction(vindicia.get_autobill_desc("fk-auto-#{@time}@ign.com"), @config.options['2year_autobill'])
topaz = Topaz.new
topaz.client = @browser.client
entitlements = TopazEntitlements.new
entitlements.client = @browser.client
entitlements.is_user_entitled(topaz.get_topaz_id("fk-auto-#{@time}"))
@@report.suite_end()
end
it "should allow a 2 Year MasterCard transaction" do
subscribe_page = VindiciaSubscribePage.new
subscribe_page.client = @browser.client
payment_page = VindiciaPrimePayment.new
payment_page.client = @browser.client
receipt_page = VindiciaReceiptPage.new
receipt_page.client = @browser.client
subscribe_page.visit(@config.options['baseurl'])
#subscribe_page.logout
subscribe_page.select_subscription(@config.options['2year_name'])
subscribe_page.register_account({
:email => "fk-auto-#{@time}@ign.com",
:password => "boxofass",
:nickname => "fk-auto-#{@time}"
})
subscribe_page.continue
payment_page.choose_card_type("MasterCard")
payment_page.fill_cc_details({
:card_num => payment_page.generate_card_num("MasterCard"),
:card_cvv => payment_page.generate_random_cvv,
:name => 'Frank Klun',
:street_address => '625 2nd Street',
:city => 'San Francisco',
:state => 'CA',
:zip_code => payment_page.generate_random_zip,
:card_month => payment_page.generate_random_month,
:card_year => payment_page.generate_random_year
})
payment_page.submit_order
receipt_page.is_displayed.should be_true
receipt_page.order_date.should be_true
receipt_page.account_name("fk-auto-#{@time}").should be_true
receipt_page.package_name(@config.options['2year_name']).should be_true
receipt_page.package_price(@config.options['2year_price']).should be_true
vindicia = VindiciaAPI.new
vindicia.verify_transaction(vindicia.get_autobill_desc("fk-auto-#{@time}@ign.com"), @config.options['2year_autobill'])
topaz = Topaz.new
topaz.client = @browser.client
entitlements = TopazEntitlements.new
entitlements.client = @browser.client
entitlements.is_user_entitled(topaz.get_topaz_id("fk-auto-#{@time}"))
@@report.suite_end()
end
it "should allow an 2 Year American Express transaction" do
subscribe_page = VindiciaSubscribePage.new
subscribe_page.client = @browser.client
payment_page = VindiciaPrimePayment.new
payment_page.client = @browser.client
receipt_page = VindiciaReceiptPage.new
receipt_page.client = @browser.client
subscribe_page.visit(@config.options['baseurl'])
#subscribe_page.logout
subscribe_page.select_subscription(@config.options['2year_name'])
subscribe_page.register_account({
:email => "fk-auto-#{@time}@ign.com",
:password => "boxofass",
:nickname => "fk-auto-#{@time}"
})
subscribe_page.continue
payment_page.choose_card_type("American Express")
payment_page.fill_cc_details({
:card_num => payment_page.generate_card_num("American Express"),
:card_cvv => payment_page.generate_random_cvv,
:name => 'Frank Klun',
:street_address => '625 2nd Street',
:city => 'San Francisco',
:state => 'CA',
:zip_code => payment_page.generate_random_zip,
:card_month => payment_page.generate_random_month,
:card_year => payment_page.generate_random_year
})
payment_page.submit_order
receipt_page.is_displayed.should be_true
receipt_page.order_date.should be_true
receipt_page.account_name("fk-auto-#{@time}").should be_true
receipt_page.package_name(@config.options['2year_name']).should be_true
receipt_page.package_price(@config.options['2year_price']).should be_true
vindicia = VindiciaAPI.new
vindicia.verify_transaction(vindicia.get_autobill_desc("fk-auto-#{@time}@ign.com"), @config.options['2year_autobill'])
topaz = Topaz.new
topaz.client = @browser.client
entitlements = TopazEntitlements.new
entitlements.client = @browser.client
entitlements.is_user_entitled(topaz.get_topaz_id("fk-auto-#{@time}"))
@@report.suite_end()
end
it "should allow an 2 Year Discover transaction" do
subscribe_page = VindiciaSubscribePage.new
subscribe_page.client = @browser.client
payment_page = VindiciaPrimePayment.new
payment_page.client = @browser.client
receipt_page = VindiciaReceiptPage.new
receipt_page.client = @browser.client
subscribe_page.visit(@config.options['baseurl'])
#subscribe_page.logout
subscribe_page.select_subscription(@config.options['2year_name'])
subscribe_page.register_account({
:email => "fk-auto-#{@time}@ign.com",
:password => "boxofass",
:nickname => "fk-auto-#{@time}"
})
subscribe_page.continue
payment_page.choose_card_type("Discover")
payment_page.fill_cc_details({
:card_num => payment_page.generate_card_num("Discover"),
:card_cvv => payment_page.generate_random_cvv,
:name => 'Frank Klun',
:street_address => '625 2nd Street',
:city => 'San Francisco',
:state => 'CA',
:zip_code => payment_page.generate_random_zip,
:card_month => payment_page.generate_random_month,
:card_year => payment_page.generate_random_year
})
payment_page.submit_order
receipt_page.is_displayed.should be_true
receipt_page.order_date.should be_true
receipt_page.account_name("fk-auto-#{@time}").should be_true
receipt_page.package_name(@config.options['2year_name']).should be_true
receipt_page.package_price(@config.options['2year_price']).should be_true
vindicia = VindiciaAPI.new
vindicia.verify_transaction(vindicia.get_autobill_desc("fk-auto-#{@time}@ign.com"), @config.options['2year_autobill'])
topaz = Topaz.new
topaz.client = @browser.client
entitlements = TopazEntitlements.new
entitlements.client = @browser.client
entitlements.is_user_entitled(topaz.get_topaz_id("fk-auto-#{@time}"))
@@report.suite_end()
end
###########################################
# BEGIN TRIAL SUBSCRIPTION SUITE #
###########################################
# it "should allow a Free Trial Visa transaction" do
# subscribe_page = VindiciaSubscribePage.new
# subscribe_page.client = @browser.client
# payment_page = VindiciaPrimePayment.new
# payment_page.client = @browser.client
# receipt_page = VindiciaReceiptPage.new
# receipt_page.client = @browser.client
#
# subscribe_page.visit(@config.options['baseurl'])
# #subscribe_page.logout
# subscribe_page.select_subscription(@config.options['trial_name'])
# subscribe_page.register_account({
# :email => "fk-auto-#{@time}@ign.com",
# :password => "boxofass",
# :nickname => "fk-auto-#{@time}"
# })
# subscribe_page.continue
# payment_page.choose_card_type("Visa")
# payment_page.fill_cc_details({
# :card_num => payment_page.generate_card_num("Visa"),
# :card_cvv => payment_page.generate_random_cvv,
# :name => 'Frank Klun',
# :street_address => '625 2nd Street',
# :city => 'San Francisco',
# :state => 'CA',
# :zip_code => payment_page.generate_random_zip,
# :card_month => payment_page.generate_random_month,
# :card_year => payment_page.generate_random_year
# })
# payment_page.submit_order
# receipt_page.is_displayed.should be_true
# receipt_page.order_date.should be_true
# receipt_page.account_name("fk-auto-#{@time}").should be_true
# receipt_page.package_name(@config.options['trial_name']).should be_true
# receipt_page.package_price(@config.options['trial_price']).should be_true
#
# vindicia = VindiciaAPI.new
# vindicia.verify_transaction(vindicia.get_autobill_desc("fk-auto-#{@time}@ign.com"), @config.options['trial_autobill'])
# end
#
# it "should allow a Free Trial MasterCard transaction" do
# subscribe_page = VindiciaSubscribePage.new
# subscribe_page.client = @browser.client
# payment_page = VindiciaPrimePayment.new
# payment_page.client = @browser.client
# receipt_page = VindiciaReceiptPage.new
# receipt_page.client = @browser.client
#
# subscribe_page.visit(@config.options['baseurl'])
# #subscribe_page.logout
# subscribe_page.select_subscription(@config.options['trial_name'])
# subscribe_page.register_account({
# :email => "fk-auto-#{@time}@ign.com",
# :password => "boxofass",
# :nickname => "fk-auto-#{@time}"
# })
# subscribe_page.continue
# payment_page.choose_card_type("MasterCard")
# payment_page.fill_cc_details({
# :card_num => payment_page.generate_card_num("MasterCard"),
# :card_cvv => payment_page.generate_random_cvv,
# :name => 'Frank Klun',
# :street_address => '625 2nd Street',
# :city => 'San Francisco',
# :state => 'CA',
# :zip_code => payment_page.generate_random_zip,
# :card_month => payment_page.generate_random_month,
# :card_year => payment_page.generate_random_year
# })
# payment_page.submit_order
# receipt_page.is_displayed.should be_true
# receipt_page.order_date.should be_true
# receipt_page.account_name("fk-auto-#{@time}").should be_true
# receipt_page.package_name(@config.options['trial_name']).should be_true
# receipt_page.package_price(@config.options['trial_price']).should be_true
#
# vindicia = VindiciaAPI.new
# vindicia.verify_transaction(vindicia.get_autobill_desc("fk-auto-#{@time}@ign.com"), @config.options['trial_autobill'])
# end
#
# it "should allow a Free Trial American Express transaction" do
# subscribe_page = VindiciaSubscribePage.new
# subscribe_page.client = @browser.client
# payment_page = VindiciaPrimePayment.new
# payment_page.client = @browser.client
# receipt_page = VindiciaReceiptPage.new
# receipt_page.client = @browser.client
#
# subscribe_page.visit(@config.options['baseurl'])
# #subscribe_page.logout
# subscribe_page.select_subscription(@config.options['trial_name'])
# subscribe_page.register_account({
# :email => "fk-auto-#{@time}@ign.com",
# :password => "boxofass",
# :nickname => "fk-auto-#{@time}"
# })
# subscribe_page.continue
# payment_page.choose_card_type("American Express")
# payment_page.fill_cc_details({
# :card_num => payment_page.generate_card_num("American Express"),
# :card_cvv => payment_page.generate_random_cvv,
# :name => 'Frank Klun',
# :street_address => '625 2nd Street',
# :city => 'San Francisco',
# :state => 'CA',
# :zip_code => payment_page.generate_random_zip,
# :card_month => payment_page.generate_random_month,
# :card_year => payment_page.generate_random_year
# })
# payment_page.submit_order
# receipt_page.is_displayed.should be_true
# receipt_page.order_date.should be_true
# receipt_page.account_name("fk-auto-#{@time}").should be_true
# receipt_page.package_name(@config.options['trial_name']).should be_true
# receipt_page.package_price(@config.options['trial_price']).should be_true
#
# vindicia = VindiciaAPI.new
# vindicia.verify_transaction(vindicia.get_autobill_desc("fk-auto-#{@time}@ign.com"), @config.options['trial_autobill'])
# end
#
# it "should allow a Free Trial Discover transaction" do
# subscribe_page = VindiciaSubscribePage.new
# subscribe_page.client = @browser.client
# payment_page = VindiciaPrimePayment.new
# payment_page.client = @browser.client
# receipt_page = VindiciaReceiptPage.new
# receipt_page.client = @browser.client
#
# subscribe_page.visit(@config.options['baseurl'])
# #subscribe_page.logout
# subscribe_page.select_subscription(@config.options['trial_name'])
# subscribe_page.register_account({
# :email => "fk-auto-#{@time}@ign.com",
# :password => "boxofass",
# :nickname => "fk-auto-#{@time}"
# })
# subscribe_page.continue
# payment_page.choose_card_type("Discover")
# payment_page.fill_cc_details({
# :card_num => payment_page.generate_card_num("Discover"),
# :card_cvv => payment_page.generate_random_cvv,
# :name => 'Frank Klun',
# :street_address => '625 2nd Street',
# :city => 'San Francisco',
# :state => 'CA',
# :zip_code => payment_page.generate_random_zip,
# :card_month => payment_page.generate_random_month,
# :card_year => payment_page.generate_random_year
# })
# payment_page.submit_order
# receipt_page.is_displayed.should be_true
# receipt_page.order_date.should be_true
# receipt_page.account_name("fk-auto-#{@time}").should be_true
# receipt_page.package_name(@config.options['trial_name']).should be_true
# receipt_page.package_price(@config.options['trial_price']).should be_true
#
# vindicia = VindiciaAPI.new
# vindicia.verify_transaction(vindicia.get_autobill_desc("fk-auto-#{@time}@ign.com"), @config.options['trial_autobill'])
# end
end |
Vagrant.configure("2") do |config|
config.vm.define "w10" do |m|
m.vm.provider "virtualbox" do |v|
v.name = "swarm_w10"
v.linked_clone = true
end
m.vm.box = "centos/7"
m.vm.network "private_network",
virtualbox__intnet: "swarm",
nic_type: "virtio"
m.vm.provision "shell",
path: "https://raw.githubusercontent.com/secobau/linux/master/Vagrant/Swarm/Virtualbox/Wx2/setup.network.w10"
m.vm.provision "shell",
path: "https://raw.githubusercontent.com/secobau/linux/master/Vagrant/Swarm/Virtualbox/Wx2/setup.docker"
end
config.vm.define "w11" do |m|
m.vm.provider "virtualbox" do |v|
v.name = "swarm_w11"
v.linked_clone = true
end
m.vm.box = "centos/7"
m.vm.network "private_network",
virtualbox__intnet: "swarm",
nic_type: "virtio"
m.vm.provision "shell",
path: "https://raw.githubusercontent.com/secobau/linux/master/Vagrant/Swarm/Virtualbox/Wx2/setup.network.w11"
m.vm.provision "shell",
path: "https://raw.githubusercontent.com/secobau/linux/master/Vagrant/Swarm/Virtualbox/Wx2/setup.docker"
end
config.vm.define "w12" do |m|
m.vm.provider "virtualbox" do |v|
v.name = "swarm_w12"
v.linked_clone = true
end
m.vm.box = "centos/7"
m.vm.network "private_network",
virtualbox__intnet: "swarm",
nic_type: "virtio"
m.vm.provision "shell",
path: "https://raw.githubusercontent.com/secobau/linux/master/Vagrant/Swarm/Virtualbox/Wx2/setup.network.w12"
m.vm.provision "shell",
path: "https://raw.githubusercontent.com/secobau/linux/master/Vagrant/Swarm/Virtualbox/Wx2/setup.docker"
end
# config.vm.define "w13" do |m|
# m.vm.provider "virtualbox" do |v|
# v.name = "swarm_w13"
# v.linked_clone = true
# end
# m.vm.box = "centos/7"
# m.vm.network "private_network",
# virtualbox__intnet: "swarm",
# nic_type: "virtio"
# m.vm.provision "shell",
# path: "https://raw.githubusercontent.com/secobau/linux/master/Vagrant/Swarm/Virtualbox/Wx2/setup.network.w13"
# m.vm.provision "shell",
# path: "https://raw.githubusercontent.com/secobau/linux/master/Vagrant/Swarm/Virtualbox/Wx2/setup.docker"
# end
# config.vm.define "w14" do |m|
# m.vm.provider "virtualbox" do |v|
# v.name = "swarm_w14"
# v.linked_clone = true
# end
# m.vm.box = "centos/7"
# m.vm.network "private_network",
# virtualbox__intnet: "swarm",
# nic_type: "virtio"
# m.vm.provision "shell",
# path: "https://raw.githubusercontent.com/secobau/linux/master/Vagrant/Swarm/Virtualbox/Wx2/setup.network.w14"
# m.vm.provision "shell",
# path: "https://raw.githubusercontent.com/secobau/linux/master/Vagrant/Swarm/Virtualbox/Wx2/setup.docker"
# end
# config.vm.define "w15" do |m|
# m.vm.provider "virtualbox" do |v|
# v.name = "swarm_w15"
# v.linked_clone = true
# end
# m.vm.box = "centos/7"
# m.vm.network "private_network",
# virtualbox__intnet: "swarm",
# nic_type: "virtio"
# m.vm.provision "shell",
# path: "https://raw.githubusercontent.com/secobau/linux/master/Vagrant/Swarm/Virtualbox/Wx2/setup.network.w15"
# m.vm.provision "shell",
# path: "https://raw.githubusercontent.com/secobau/linux/master/Vagrant/Swarm/Virtualbox/Wx2/setup.docker"
# end
# config.vm.define "w16" do |m|
# m.vm.provider "virtualbox" do |v|
# v.name = "swarm_w16"
# v.linked_clone = true
# end
# m.vm.box = "centos/7"
# m.vm.network "private_network",
# virtualbox__intnet: "swarm",
# nic_type: "virtio"
# m.vm.provision "shell",
# path: "https://raw.githubusercontent.com/secobau/linux/master/Vagrant/Swarm/Virtualbox/Wx2/setup.network.w16"
# m.vm.provision "shell",
# path: "https://raw.githubusercontent.com/secobau/linux/master/Vagrant/Swarm/Virtualbox/Wx2/setup.docker"
# end
# config.vm.define "w17" do |m|
# m.vm.provider "virtualbox" do |v|
# v.name = "swarm_w17"
# v.linked_clone = true
# end
# m.vm.box = "centos/7"
# m.vm.network "private_network",
# virtualbox__intnet: "swarm",
# nic_type: "virtio"
# m.vm.provision "shell",
# path: "https://raw.githubusercontent.com/secobau/linux/master/Vagrant/Swarm/Virtualbox/Wx2/setup.network.w17"
# m.vm.provision "shell",
# path: "https://raw.githubusercontent.com/secobau/linux/master/Vagrant/Swarm/Virtualbox/Wx2/setup.docker"
# end
# config.vm.define "w18" do |m|
# m.vm.provider "virtualbox" do |v|
# v.name = "swarm_w18"
# v.linked_clone = true
# end
# m.vm.box = "centos/7"
# m.vm.network "private_network",
# virtualbox__intnet: "swarm",
# nic_type: "virtio"
# m.vm.provision "shell",
# path: "https://raw.githubusercontent.com/secobau/linux/master/Vagrant/Swarm/Virtualbox/Wx2/setup.network.w18"
# m.vm.provision "shell",
# path: "https://raw.githubusercontent.com/secobau/linux/master/Vagrant/Swarm/Virtualbox/Wx2/setup.docker"
# end
# config.vm.define "w19" do |m|
# m.vm.provider "virtualbox" do |v|
# v.name = "swarm_w19"
# v.linked_clone = true
# end
# m.vm.box = "centos/7"
# m.vm.network "private_network",
# virtualbox__intnet: "swarm",
# nic_type: "virtio"
# m.vm.provision "shell",
# path: "https://raw.githubusercontent.com/secobau/linux/master/Vagrant/Swarm/Virtualbox/Wx2/setup.network.w19"
# m.vm.provision "shell",
# path: "https://raw.githubusercontent.com/secobau/linux/master/Vagrant/Swarm/Virtualbox/Wx2/setup.docker"
# end
end
|
require 'tempfile'
require 'spec_helper'
describe CsvImporter, :database_integration => true do
describe "actually performing the import" do
before do
any_instance_of(CsvImporter) { |importer| stub(importer).destination_dataset { datasets(:table) } }
end
after do
schema.with_gpdb_connection(account) do |connection|
connection.exec_query("DROP TABLE IF EXISTS another_new_table_from_csv,new_table_from_csv,new_table_from_csv_2,table_to_append_to,table_to_replace,test_import_existing_2")
end
end
let(:database) { GpdbDatabase.find_by_name_and_gpdb_instance_id(GpdbIntegration.database_name, GpdbIntegration.real_gpdb_instance)}
let(:schema) { database.schemas.find_by_name('test_schema') }
let(:user) { account.owner }
let(:account) { GpdbIntegration.real_gpdb_account }
let(:workspace) { Workspace.create({:sandbox => schema, :owner => user, :name => "TestCsvWorkspace"}, :without_protection => true) }
let(:file_import_created_event) { Events::FileImportCreated.last }
def fetch_from_gpdb(sql)
schema.with_gpdb_connection(account) do |connection|
result = connection.exec_query(sql)
yield result
end
end
def create_csv_file(options = {})
defaults = {
:contents => tempfile_with_contents("1,foo\n2,bar\n3,baz\n"),
:column_names => [:id, :name],
:types => [:integer, :varchar],
:delimiter => ',',
:file_contains_header => false,
:new_table => true,
:to_table => "new_table_from_csv",
:truncate => false
}
csv_file = CsvFile.new(defaults.merge(options))
csv_file.user = user
csv_file.workspace = workspace
csv_file.save!
csv_file
end
def tempfile_with_contents(str)
f = Tempfile.new("test_csv")
f.puts str
f.close
f
end
it "refuses to import a csv file that is not completely populated" do
csv_file = create_csv_file
csv_file.update_attribute(:delimiter, nil)
expect do
CsvImporter.import_file(csv_file.id, file_import_created_event.id)
end.to raise_error(Exception)
end
it "imports a basic csv file as a new table" do
csv_file = create_csv_file
CsvImporter.import_file(csv_file.id, file_import_created_event.id)
schema.with_gpdb_connection(account) do |connection|
result = connection.exec_query("select * from new_table_from_csv order by ID asc;")
result[0].should == {"id" => 1, "name" => "foo"}
result[1].should == {"id" => 2, "name" => "bar"}
result[2].should == {"id" => 3, "name" => "baz"}
end
end
it "import a basic csv file into an existing table" do
csv_file = create_csv_file(:new_table => true, :to_table => "table_to_append_to")
CsvImporter.import_file(csv_file.id, file_import_created_event.id)
csv_file = create_csv_file(:new_table => false, :to_table => "table_to_append_to")
CsvImporter.import_file(csv_file.id, file_import_created_event.id)
fetch_from_gpdb("select count(*) from table_to_append_to;") do |result|
result[0]["count"].should == 6
end
end
it "should truncate the existing table when truncate=true" do
csv_file = create_csv_file(:new_table => true, :to_table => "table_to_replace")
CsvImporter.import_file(csv_file.id, file_import_created_event.id)
csv_file = create_csv_file(:new_table => false,
:truncate => true,
:to_table => "table_to_replace",
:contents => tempfile_with_contents("1,larry\n2,barry\n"))
CsvImporter.import_file(csv_file.id, file_import_created_event.id)
fetch_from_gpdb("select * from table_to_replace order by id asc;") do |result|
result[0]["name"].should == "larry"
result[1]["name"].should == "barry"
result.count.should == 2
end
end
it "import a csv file into an existing table with different column order" do
first_csv_file = create_csv_file(:contents => tempfile_with_contents("1,foo\n2,bar\n3,baz\n"),
:column_names => [:id, :name],
:types => [:integer, :varchar],
:file_contains_header => false,
:new_table => true,
:to_table => "new_table_from_csv_2")
CsvImporter.import_file(first_csv_file.id, file_import_created_event.id)
second_csv_file = create_csv_file(:contents => tempfile_with_contents("dig,4\ndug,5\ndag,6\n"),
:column_names => [:name, :id],
:types => [:varchar, :integer],
:file_contains_header => false,
:new_table => false,
:to_table => "new_table_from_csv_2")
CsvImporter.import_file(second_csv_file.id, file_import_created_event.id)
fetch_from_gpdb("select * from new_table_from_csv_2 order by id asc;") do |result|
result[0]["id"].should == 1
result[0]["name"].should == "foo"
result[1]["id"].should == 2
result[1]["name"].should == "bar"
result[2]["id"].should == 3
result[2]["name"].should == "baz"
result[3]["id"].should == 4
result[3]["name"].should == "dig"
result[4]["id"].should == 5
result[4]["name"].should == "dug"
result[5]["id"].should == 6
result[5]["name"].should == "dag"
end
end
it "import a csv file that has fewer columns than destination table" do
tablename = "test_import_existing_2"
first_csv_file = create_csv_file(:contents => tempfile_with_contents("1,a,snickers\n2,b,kitkat\n"),
:column_names => [:id, :name, :candy_type],
:types => [:integer, :varchar, :varchar],
:file_contains_header => false,
:new_table => true,
:to_table => tablename)
CsvImporter.import_file(first_csv_file.id, file_import_created_event.id)
second_csv_file = create_csv_file(:contents => tempfile_with_contents("marsbar,3\nhersheys,4\n"),
:column_names => [:candy_type, :id],
:types => [:varchar, :integer],
:file_contains_header => false,
:new_table => false,
:to_table => tablename)
CsvImporter.import_file(second_csv_file.id, file_import_created_event.id)
fetch_from_gpdb("select * from #{tablename} order by id asc;") do |result|
result[0]["id"].should == 1
result[0]["name"].should == "a"
result[0]["candy_type"].should == "snickers"
result[1]["id"].should == 2
result[1]["name"].should == "b"
result[1]["candy_type"].should == "kitkat"
result[2]["id"].should == 3
result[2]["name"].should == nil
result[2]["candy_type"].should == "marsbar"
result[3]["id"].should == 4
result[3]["name"].should == nil
result[3]["candy_type"].should == "hersheys"
end
end
it "imports a file with different column names, header rows and a different delimiter" do
csv_file = create_csv_file(:contents => tempfile_with_contents("ignore\tme\n1\tfoo\n2\tbar\n3\tbaz\n"),
:column_names => [:id, :dog],
:types => [:integer, :varchar],
:delimiter => "\t",
:file_contains_header => true,
:new_table => true,
:to_table => "another_new_table_from_csv")
CsvImporter.import_file(csv_file.id, file_import_created_event.id)
fetch_from_gpdb("select * from another_new_table_from_csv order by ID asc;") do |result|
result[0].should == {"id" => 1, "dog" => "foo"}
result[1].should == {"id" => 2, "dog" => "bar"}
result[2].should == {"id" => 3, "dog" => "baz"}
end
end
context "when import fails" do
it "removes import table when new_table is true" do
any_instance_of(CsvImporter) { |importer|
stub(importer).check_if_table_exists.with_any_args { false }
}
csv_file = create_csv_file(:contents => tempfile_with_contents("1,hi,three"),
:column_names => [:id, :name],
:types => [:integer, :varchar],
:file_contains_header => false,
:new_table => true)
table_name = csv_file.to_table
CsvImporter.import_file(csv_file.id, file_import_created_event.id)
schema.with_gpdb_connection(account) do |connection|
expect { connection.exec_query("select * from #{table_name}") }.to raise_error(ActiveRecord::StatementInvalid)
end
end
it "does not remove import table when new_table is false" do
table_name = "test_import_existing_2"
first_csv_file = create_csv_file(:contents => tempfile_with_contents("1,hi"),
:column_names => [:id, :name],
:types => [:integer, :varchar],
:file_contains_header => false,
:new_table => true,
:to_table => table_name)
CsvImporter.import_file(first_csv_file.id, file_import_created_event.id)
second_csv_file = create_csv_file(:contents => tempfile_with_contents("1,hi,three"),
:column_names => [:id, :name],
:types => [:integer, :varchar],
:file_contains_header => false,
:new_table => false,
:to_table => table_name)
CsvImporter.import_file(second_csv_file.id, file_import_created_event.id)
schema.with_gpdb_connection(account) do |connection|
expect { connection.exec_query("select * from #{table_name}") }.not_to raise_error
end
end
it "does not remove the table if new_table is true, but the table already existed" do
any_instance_of(CsvImporter) { |importer|
stub(importer).check_if_table_exists.with_any_args { true }
}
csv_file = create_csv_file(:contents => tempfile_with_contents("1,hi,three"),
:column_names => [:id, :name],
:types => [:integer, :varchar],
:file_contains_header => false,
:new_table => true)
table_name = csv_file.to_table
CsvImporter.import_file(csv_file.id, file_import_created_event.id)
schema.with_gpdb_connection(account) do |connection|
expect { connection.exec_query("select * from #{table_name}") }.not_to raise_error(ActiveRecord::StatementInvalid)
end
end
end
end
describe "without connecting to GPDB" do
let(:csv_file) { CsvFile.first }
let(:user) { csv_file.user }
let(:dataset) { datasets(:table) }
let(:instance_account) { csv_file.workspace.sandbox.gpdb_instance.account_for_user!(csv_file.user) }
let(:file_import_created_event) { Events::FileImportCreated.last }
describe "destination_dataset" do
before do
mock(Dataset).refresh(instance_account, csv_file.workspace.sandbox)
end
it "performs a refresh and returns the dataset matching the import table name" do
importer = CsvImporter.new(csv_file.id, file_import_created_event.id)
importer.destination_dataset.name.should == csv_file.to_table
end
end
describe "when the import is successful" do
before do
any_instance_of(GpdbSchema) { |schema| stub(schema).with_gpdb_connection }
any_instance_of(CsvImporter) { |importer| stub(importer).destination_dataset { dataset } }
CsvImporter.import_file(csv_file.id, file_import_created_event.id)
end
it "makes a IMPORT_SUCCESS event" do
event = Events::FileImportSuccess.last
event.actor.should == user
event.dataset.should == dataset
event.workspace.should == csv_file.workspace
event.file_name.should == csv_file.contents_file_name
event.import_type.should == 'file'
end
it "makes sure the FileImportSuccess event object is linked to the dataset" do
dataset = datasets(:table)
file_import_created_event.reload
file_import_created_event.dataset.should == dataset
file_import_created_event.target2_type.should == "Dataset"
file_import_created_event.target2_id.should == dataset.id
end
it "deletes the file" do
expect { CsvFile.find(csv_file.id) }.to raise_error(ActiveRecord::RecordNotFound)
end
it "generates notification to import actor" do
notification = Notification.last
notification.recipient_id.should == user.id
notification.event_id.should == Events::FileImportSuccess.last.id
end
end
describe "when the import fails" do
before do
@error = 'ActiveRecord::JDBCError: ERROR: relation "test" already exists: CREATE TABLE test(a float, b float, c float);'
exception = ActiveRecord::StatementInvalid.new(@error)
any_instance_of(GpdbSchema) { |schema| stub(schema).with_gpdb_connection { raise exception } }
CsvImporter.import_file(csv_file.id, file_import_created_event.id)
end
it "makes a IMPORT_FAILED event" do
event = Events::FileImportFailed.last
event.actor.should == user
event.destination_table.should == dataset.name
event.workspace.should == csv_file.workspace
event.file_name.should == csv_file.contents_file_name
event.import_type.should == 'file'
event.error_message.should == @error
end
it "deletes the file" do
expect { CsvFile.find(csv_file.id) }.to raise_error(ActiveRecord::RecordNotFound)
end
it "generates notification to import actor" do
notification = Notification.last
notification.recipient_id.should == user.id
notification.event_id.should == Events::FileImportFailed.last.id
end
end
end
end |
# frozen_string_literal: true
class Ability
include CanCan::Ability
def initialize(user)
can :manage, Recipe, user_id: user.id
end
end
|
# encoding: utf-8
module ApplicationHelper
def controller?(*names)
names.include?(params[:controller])
end
def link_to_player_result(player, selected_player, stage = nil)
if player == selected_player
badge, text = ' badge-success', 'Getoond'
else
badge, text = '', 'Bekijk'
end
if params[:controller] == "summary"
path = summary_path(:player_id => player.id, :anchor => "ranking")
elsif params[:controller] == "rankings"
path = rankings_path(:player_id => player.id, :anchor => "player_ranking")
else
path = stage_path(stage, :player_id => player.id, :anchor => "player_ranking")
end
link_to text, path, :class => "badge #{badge}"
end
def number_to_euro(number)
number_to_currency(number.to_f, :unit => "€ ", :precision => 0, :separator => ".")
end
def bool_icon(bool)
content_tag("i", "", :class => (bool ? "icon-ok" : "icon-remove"))
end
def badge(content, type, show_badge = false)
if show_badge
content_tag("span", content, :class => "badge badge-#{type}")
else
content
end
end
def flash_messages
messages = flash.collect do |key, message|
content_tag("div", message, :class => "alert alert-#{key}")
end
messages.join("\n").html_safe
end
def error_messages_for(model)
return "" if model.errors.empty?
messages = model.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
sentence = I18n.t("errors.template.header",
:count => model.errors.count,
:model => model.class.model_name.human.capitalize)
html = <<-HTML
<div class="alert alert-warning">
<h3>#{sentence}</h3>
<p>#{I18n.t("errors.template.body")}</p>
<ul>#{messages}</ul>
</div>
HTML
html.html_safe
end
end
|
class Lesson < ApplicationRecord
has_many :reviews
has_many :users, through: :reviews
has_many :ratings, through: :reviews
has_many :tags, through: :reviews
validates :name, presence: { scope: true, message: "must be entered" }
validates :description, presence: { scope: true, message: "must be entered" }
validates :url, presence: { scope: true, message: "must be entered" }
validates_format_of :unit_location, :with => /\d{2}-\d{2}-\d{2}-\d{2}/, message: "must be formatted as ##-##-##-##"
def average_time_taken
time = Rating.where(review: self.reviews).average(:time_taken).to_f.round(0)
to_hours_minutes_readout(time)
end
def average_helpfulness
Rating.where(review: self.reviews).average(:helpfulness).to_f.round(0)
end
def average_frustration
Rating.where(review: self.reviews).average(:frustration).to_f.round(0)
end
def average_quality
Rating.where(review: self.reviews).average(:quality).to_f.round(0)
end
def to_hours_minutes_readout(time)
"#{time/60} Hours #{time%60} Minutes"
end
end
|
module Disbursements
class Processor
def initialize(merchant:, start_date:, end_date:)
@merchant = merchant
@start_date = start_date
@end_date = end_date
end
def call
merchant.orders.completed_in(start_date, end_date).find_in_batches(batch_size: 50) do |orders|
orders.each do |order|
Disbursements::Creator.new(
merchant_id: merchant.id,
order_id: order.id,
fee_calculator: FeeCalculator.new(amount: order.amount)
).call
end
end
end
private
attr_reader :merchant, :start_date, :end_date
end
end
|
module MessageCenter
class MailDispatcher
attr_reader :mailable, :recipients
def initialize(mailable, recipients)
@mailable, @recipients = mailable, Array.wrap(recipients)
end
def call
return false unless MessageCenter.uses_emails
if MessageCenter.mailer_wants_array
send_email(filtered_recipients)
else
filtered_recipients.each do |recipient|
email_to = recipient.send(MessageCenter.email_method, mailable)
send_email(recipient) if email_to.present?
end
end
end
private
def mailer
klass = mailable.class.name.demodulize
method = "#{klass.downcase}_mailer".to_sym
MessageCenter.send(method) || "#{mailable.class}Mailer".constantize
end
# recipients can be filtered on a conversation basis
def filtered_recipients
return recipients unless mailable.respond_to?(:conversation)
recipients.each_with_object([]) do |recipient, array|
array << recipient if mailable.conversation.has_subscriber?(recipient)
end
end
def send_email(recipient)
if MessageCenter.custom_deliver_proc
MessageCenter.custom_deliver_proc.call(mailer, mailable, recipient)
else
mailer.send_email(mailable, recipient).deliver_now
end
end
end
end
|
require "application_system_test_case"
class ShoesTest < ApplicationSystemTestCase
setup do
@shoe = shoes(:one)
end
test "visiting the index" do
visit shoes_url
assert_selector "h1", text: "Shoes"
end
test "creating a Shoe" do
visit shoes_url
click_on "New Shoe"
fill_in "Brand", with: @shoe.brand
fill_in "Description", with: @shoe.description
fill_in "Price", with: @shoe.price
fill_in "Release date", with: @shoe.release_date
fill_in "Seller", with: @shoe.seller_id
fill_in "Size", with: @shoe.size
click_on "Create Shoe"
assert_text "Shoe was successfully created"
click_on "Back"
end
test "updating a Shoe" do
visit shoes_url
click_on "Edit", match: :first
fill_in "Brand", with: @shoe.brand
fill_in "Description", with: @shoe.description
fill_in "Price", with: @shoe.price
fill_in "Release date", with: @shoe.release_date
fill_in "Seller", with: @shoe.seller_id
fill_in "Size", with: @shoe.size
click_on "Update Shoe"
assert_text "Shoe was successfully updated"
click_on "Back"
end
test "destroying a Shoe" do
visit shoes_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Shoe was successfully destroyed"
end
end
|
cities = {
"toronto" => '416',
"waterloo" => '519',
'ottawa' => '613',
'ajax' => '905',
'huntsville' => '705',
'vancouver' => '604',
'montreal' => '514',
"calgary" => '403',
'halifax' => '782',
'quebec city' => '418'
}
def get_city_names(cities)
cities.keys
end
def get_area_code(cities, selected_city)
cities[selected_city]
end
loop do
puts "Do you want to look up an area code by city name? (Y/N)"
input = gets.chomp.downcase
break if input != "y"
puts "which city do you want an area code for?"
puts get_city_names(cities)
puts "enter your selection"
city = gets.chomp.downcase
if(cities.include?(city))
puts "The area code of #{city} is #{get_area_code(cities, city)}"
else
puts "Unable to find an area code for #{city}. Please enter a valid city to look up."
end
end |
class TipCalc
attr_accessor :amount, :tip, :num_people
def initialize(amount, tip, num_people)
@amount = amount.to_f
@tip = tip.to_f
@num_people = num_people.to_f
end
def tip_amount
return amount * (tip/100)
end
def final_with_tip
return amount + amount * (tip/100)
end
def per_person
return final_with_tip/num_people
end
end
|
class AddPickupTimeAndTravellerNumberToPurchases < ActiveRecord::Migration
def change
add_column Purchase, :pickup_time, :datetime
add_column Purchase, :traveller_number, :integer
end
end
|
Dotenv.load
module Twirloc
class GoogleLocation
attr_reader :api_key, :coords, :conn
def initialize(opts)
@api_key = opts[:api_key] || ENV["GOOGLE_GEO_KEY"]
@coords = stringify(opts[:coords])
end
def to_s
results = response["results"]
formatted_addresses = results.collect { |r| r["formatted_address"] }
addresses = formatted_addresses.select { |a| a.split(",").count == 3 }
addresses.first
end
def host
"https://maps.googleapis.com/"
end
def params
"maps/api/geocode/json?latlng=#{coords}&key=#{api_key}"
end
def make_request
conn.get params
end
def response
JSON.parse(make_request.body)
end
def stringify(coordinates)
coordinates.join(",")
end
def conn
@_conn = Faraday.new(:url => host) do |faraday|
faraday.request :url_encoded
faraday.adapter Faraday.default_adapter
end
end
end
end
|
# Euler's Totient function, φ(n) [sometimes called the phi function], is used to determine the number of
# numbers less than n which are relatively prime to n.
# For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to nine, φ(9)=6.
# It can be seen that n=6 produces a maximum n/wφ(n) for n ≤ 10.
# Find the value of n ≤ 1,000,000 for which n/φ(n) is a maximum.
def divisors(n)
(1..n).select do |num|
n % num == 0
end
end
def greatest_n_over_phi(lim)
max = 0
3.upto(lim).map do |num|
puts num
div = divisors(num)
phi = 1.upto(num-1).select { |x| (div & divisors(x)) == [1] }.length # number of coprimes less than num
n_phi = (num/phi.to_f).round(4)
#puts "num: #{num} -- phi: #{phi} -- n/phi: #{n_phi}"
n_phi
end
end
puts greatest_n_over_phi(10000).each_with_index.max[1] + 3 # + 3 undoes the offset above |
require 'rails_helper'
RSpec.describe 'Posts', type: :request do
before do
@user = FactoryBot.create(:user)
sign_in @user
@post = FactoryBot.create(:post, image: fixture_file_upload('public/images/test_image.png'))
end
describe "GET #top" do
it "topアクションにリクエストすると正常にレスポンスが返ってくる" do
get top_posts_path
expect(response.status).to eq 200
end
it "topアクションにリクエストするとレスポンスに投稿済みのクチコミの商品名が存在する" do
get top_posts_path
expect(response.body).to include @post.name
end
it "topアクションにリクエストするとレスポンスに投稿済みのクチコミの更新日が存在する" do
get top_posts_path
expect(response.body).to include @post.created_at.strftime("%Y.%m.%d")
end
it "topアクションにリクエストするとレスポンスに投稿済みのクチコミの投稿者名が存在する" do
get top_posts_path
expect(response.body).to include @post.user.nickname
end
it "topアクションにリクエストするとレスポンスに投稿済みのクチコミの評価が存在する" do
get top_posts_path
expect(response.body).to include "#{@post.evaluation}"
end
it "topアクションにリクエストするとレスポンスに投稿済みのクチコミ商品購入額が存在する" do
get top_posts_path
expect(response.body).to include "#{@post.price}"
end
it "topアクションにリクエストするとレスポンスに投稿済みのクチコミの画像が存在する" do
get top_posts_path
expect(response.body).to include 'test_image.png'
end
it "topアクションにリクエストするとレスポンスに投稿検索フォームが存在する" do
get top_posts_path
expect(response.body).to include '商品名から探す'
end
it "topアクションにリクエストするとレスポンスにカテゴリーから探すが存在する" do
get top_posts_path
expect(response.body).to include 'カテゴリーから探す'
end
it "topアクションにリクエストするとレスポンスに投稿一覧を見るが存在する" do
get top_posts_path
expect(response.body).to include '投稿一覧を見る'
end
end
describe "GET #show" do
it "showアクションにリクエストすると正常にレスポンスが返ってくる" do
get post_path(@post)
expect(response.status).to eq 200
end
it "showアクションにリクエストするとレスポンスに投稿済みのクチコミの商品名が存在する" do
get post_path(@post)
expect(response.body).to include @post.name
end
it "showアクションにリクエストするとレスポンスに投稿済みのクチコミのカテゴリーが存在する" do
get post_path(@post)
expect(response.body).to include @post.category.name
end
it "showアクションにリクエストするとレスポンスに投稿済みのクチコミの更新日が存在する" do
get post_path(@post)
expect(response.body).to include @post.created_at.strftime("%Y.%m.%d")
end
it "showアクションにリクエストするとレスポンスに投稿済みのクチコミの投稿者名が存在する" do
get post_path(@post)
expect(response.body).to include @post.user.nickname
end
it "showアクションにリクエストするとレスポンスに投稿済みのクチコミの評価が存在する" do
get post_path(@post)
expect(response.body).to include "#{@post.evaluation}"
end
it "showアクションにリクエストするとレスポンスに投稿済みのクチコミ商品購入額が存在する" do
get post_path(@post)
expect(response.body).to include "#{@post.price}"
end
it "showアクションにリクエストするとレスポンスに投稿済みのクチコミ商品購入店が存在する" do
get post_path(@post)
expect(response.body).to include @post.shop_name
end
it "showアクションにリクエストするとレスポンスに投稿済みのクチコミレビュー文が存在する" do
get post_path(@post)
expect(response.body).to include @post.description
end
it "showアクションにリクエストするとレスポンスに投稿済みのクチコミの画像が存在する" do
get post_path(@post)
expect(response.body).to include 'test_image.png'
end
it "showアクションにリクエストするとレスポンスに投稿済みのクチコミのお気に入り数が存在する" do
get post_path(@post)
expect(response.body).to include "#{@post.likes.count}"
end
it "showアクションにリクエストするとレスポンスに関連商品のクチコミ表示部分が存在する" do
get post_path(@post)
expect(response.body).to include '関連商品のクチコミ'
end
end
end
|
# -*- coding: utf-8 -*-
# frozen_string_literal: true
require "rails_helper"
describe CensusActionAuthorizer do
subject { described_class.new(authorization, options, nil, nil).authorize }
let(:user) { create(:user, nickname: 'authorizing_user') }
let(:authorization) {}
let(:options) { {} }
context "when there is no authorization" do
it "does not grant authorization" do
expect(subject).to eq([:missing, {action: :authorize}])
end
end
context "when authorization is pending" do
let(:authorization) { create(:authorization, :pending, user: user) }
it "does not grant authorization" do
expect(subject).to eq([:pending, action: :resume])
end
end
describe "when authorization is valid" do
context "without options" do
let(:authorization) { create(:authorization, :granted, user: user) }
it "grants authorization" do
expect(subject).to eq([:ok, {}])
end
end
context "with district option" do
context "when a single value has been setted" do
let(:options) { {'district' => '1'} }
context "when the selected district matches with authorization" do
let(:authorization) { create(:authorization, :granted, user: user, metadata: {'district' => '1'}) }
it "grants authorization" do
expect(subject).to eq([:ok, {}])
end
end
context "when the selected district does not match authorization" do
let(:authorization) { create(:authorization, :granted, user: user, metadata: {'district' => '2'}) }
it "doesn't grant authorization" do
expected_data= {
:extra_explanation=> [{
:key=>"extra_explanation.districts",
:params=> {:count=>1, :districts=>"1", :scope=>"decidim.verifications.census_authorization"}
}],
fields: {'district'=>'2'}
}
expect(subject).to eq([:unauthorized, expected_data])
end
end
end
context "when multiples values have been setted" do
let(:options) { {'district' => '1, 2,3; 4'} }
context "when any of the listed districts matches with authorization" do
let(:authorization) { create(:authorization, :granted, user: user, metadata: {'district' => '2'}) }
it "grants authorization" do
expect(subject).to eq([:ok, {}])
end
end
context "when none of the listed districts match with the authorization" do
let(:authorization) { create(:authorization, :granted, user: user, metadata: {'district' => '5'}) }
it "doesn't grant authorization" do
expected_data= {
:extra_explanation=> [{
:key=>"extra_explanation.districts",
:params=> {:count=>4, :districts=>"1, 2, 3, 4", :scope=>"decidim.verifications.census_authorization"}
}],
:fields=>{"district"=>"5"}
}
expect(subject).to eq([:unauthorized, expected_data])
end
end
end
end
context "with district_council option" do
context "when a single value has been setted" do
let(:options) { {'district_council' => '1'} }
context "when the selected district_council matches with authorization" do
let(:authorization) { create(:authorization, :granted, user: user, metadata: {'district_council' => '1'}) }
it "grants authorization" do
expect(subject).to eq([:ok, {}])
end
end
context "when the selected district_council does not match authorization" do
let(:authorization) { create(:authorization, :granted, user: user, metadata: {'district_council' => '2'}) }
it "doesn't grant authorization" do
expected_data= {
:extra_explanation=> [{
:key=>"extra_explanation.district_councils",
:params=> {:count=>1, :districts=>"1", :scope=>"decidim.verifications.census_authorization"}
}],
fields: {'district_council'=>'2'}
}
expect(subject).to eq([:unauthorized, expected_data])
end
end
end
context "when multiples values have been setted" do
let(:options) { {'district_council' => '1, 2,3; 4'} }
context "when any of the listed districts matches with authorization" do
let(:authorization) { create(:authorization, :granted, user: user, metadata: {'district_council' => '2'}) }
it "grants authorization" do
expect(subject).to eq([:ok, {}])
end
end
context "when none of the listed districts match with the authorization" do
let(:authorization) { create(:authorization, :granted, user: user, metadata: {'district_council' => '7'}) }
it "doesn't grant authorization" do
expected_data= {
:extra_explanation=> [{
:key=>"extra_explanation.district_councils",
:params=> {:count=>4, :districts=>"1, 2, 3, 4", :scope=>"decidim.verifications.census_authorization"}
}],
fields: {'district_council'=>'7'}
}
expect(subject).to eq([:unauthorized, expected_data])
end
end
end
end
context "with both district and district_council options" do
let(:options) { {'district' => '1,2,3,4', 'district_council' => '5,6,7,8'} }
context "when authorization matches with the listed district and district_council" do
let(:authorization) { create(:authorization, :granted, user: user, metadata: {'district' => '1', 'district_council' => '8'}) }
it "grants authorization" do
expect(subject).to eq([:ok, {}])
end
end
end
end
end
|
class CreateGames < ActiveRecord::Migration
def change
create_table(:games) do |t|
t.integer :user_id
t.datetime :current_time
t.integer :location_id
t.string :home_name
t.timestamps
end
end
end
|
module Middleman
module Smusher
class << self
def registered(app, options={})
require "smusher"
# options[:service] ||= "SmushIt"
options[:quiet] = true
app.after_configuration do
smush_dir = if options.has_key?(:path)
options.delete(:path)
else
File.join(build_dir, images_dir)
end
prefix = build_dir + File::SEPARATOR
after_build do |builder|
files = ::Smusher.class_eval do
images_in_folder(smush_dir)
end
files.each do |file|
::Smusher.optimize_image(
[file],
options
)
builder.say_status :smushed, file.sub(prefix, "")
end
end
end
end
alias :included :registered
end
end
end |
class AttendeeDatum < ActiveRecord::Base
attr_accessible :attendee_id, :sub_item_id, :answer
belongs_to :attendee
validates :attendee_id, presence: true
validates :sub_item_id, presence: true
end |
module Enginery
class Generator
include Helpers
attr_reader :boot_file, :dst_root, :setups
def initialize dst_root, setups
@dst_root, @setups = dst_root, setups
end
def generate_project name
name = name.to_s
if name.empty?
name = '.'
else
name =~ /\.\.|\// && fail('Project name can not contain "/" nor ".."')
@dst_root, @dst_path_map = File.join(@dst_root, name, ''), nil
end
Dir[dst_path(:root, '*')].any? && fail('"%s" should be a empty folder' % dst_path.root)
o
o '=== Generating "%s" project ===' % name
folders, files = Dir[src_path(:base, '**/{*,.[a-z]*}')].partition do |entry|
File.directory?(entry)
end
FileUtils.mkdir_p dst_path.root
o "#{name}/"
folders.each do |folder|
path = unrootify(folder, src_path.base)
o " D #{path}/"
FileUtils.mkdir_p dst_path(:root, path)
end
files.reject {|f| File.basename(f) == '.gitkeep'}.each do |file|
path = unrootify(file, src_path.base)
o " F #{path}"
FileUtils.cp file, dst_path(:root, path)
end
Configurator.new dst_root, setups do
update_gemfile
update_rakefile
update_boot_rb
update_config_yml
update_database_rb
end
end
def generate_controller name
name.nil? || name.empty? && fail("Please provide controller name via second argument")
before, ctrl_name, after = namespace_to_source_code(name)
source_code, i = [], INDENT * before.size
before.each {|s| source_code << s}
source_code << "#{i}class #{ctrl_name} < E"
source_code << "#{i + INDENT}# controller-wide setups"
if route = setups[:route]
source_code << "#{i + INDENT}map '#{route}'"
end
if engine = setups[:engine]
source_code << "#{i + INDENT}engine :#{engine}"
Configurator.new(dst_root, engine: engine).update_gemfile
end
if format = setups[:format]
source_code << "#{i + INDENT}format '#{format}'"
end
source_code << INDENT
source_code << "#{i}end"
after.each {|s| source_code << s}
path = dst_path(:controllers, class_to_route(name))
File.exists?(path) && fail("#{name} controller already exists")
o
o '=== Generating "%s" controller ===' % name
o '*** Creating "%s/" ***' % unrootify(path)
FileUtils.mkdir_p(path)
file = path + '_controller.rb'
write_file file, source_code.join("\n")
output_source_code source_code
end
def generate_route ctrl_name, name
action_file, action = valid_action?(ctrl_name, name)
File.exists?(action_file) && fail("#{name} action/route already exists")
before, ctrl_name, after = namespace_to_source_code(ctrl_name, false)
source_code, i = [], ' ' * before.size
before.each {|s| source_code << s}
source_code << "#{i}class #{ctrl_name}"
source_code << "#{i + INDENT}# action-specific setups"
source_code << ''
if format = setups[:format]
source_code << "#{i + INDENT}format_for :#{action}, '#{format}'"
end
if setups.any?
source_code << "#{i + INDENT}before :#{action} do"
if engine = setups[:engine]
source_code << "#{i + INDENT*2}engine :#{engine}"
Configurator.new(dst_root, engine: engine).update_gemfile
end
source_code << "#{i + INDENT}end"
source_code << ""
end
source_code << (i + INDENT + "def #{action}")
action_source_code = ["render"]
if block_given?
action_source_code = yield
action_source_code.is_a?(Array) || action_source_code = [action_source_code]
end
action_source_code.each do |line|
source_code << (i + INDENT*2 + line.to_s)
end
source_code << (i + INDENT + "end")
source_code << ''
source_code << "#{i}end"
after.each {|s| source_code << s}
o
o '=== Generating "%s" route ===' % name
write_file action_file, source_code.join("\n")
output_source_code source_code
end
def generate_view ctrl_name, name
action_file, action = valid_action?(ctrl_name, name)
_, ctrl = valid_controller?(ctrl_name)
App.boot!
ctrl_instance = ctrl.new
ctrl_instance.respond_to?(action.to_sym) ||
fail("#{action} action does not exists. Please create it first")
action_name, request_method = deRESTify_action(action)
ctrl_instance.action_setup = ctrl.action_setup[action_name][request_method]
ctrl_instance.call_setups!
path = File.join(ctrl_instance.view_path?, ctrl_instance.view_prefix?)
o
o '=== Generating "%s" view ===' % name
if File.exists?(path)
File.directory?(path) || fail("#{unrootify path} should be a directory")
else
o '*** Creating "%s/" ***' % unrootify(path)
FileUtils.mkdir_p(path)
end
file = File.join(path, action + ctrl_instance.engine_ext?)
o '*** Touching "%s" ***' % unrootify(file)
FileUtils.touch file
end
def generate_model name
name.nil? || name.empty? && fail("Please provide model name via second argument")
before, model_name, after = namespace_to_source_code(name)
superclass, insertions = '', []
if orm = setups[:orm] || Cfg[:orm]
Configurator.new(dst_root, orm: orm).update_gemfile
orm =~ /\Aa/i && superclass = ' < ActiveRecord::Base'
orm =~ /\As/i && superclass = ' < Sequel::Model'
if orm =~ /\Ad/i
insertions << 'include DataMapper::Resource'
insertions << ''
insertions << 'property :id, Serial'
end
end
insertions << ''
source_code, i = [], INDENT * before.size
before.each {|s| source_code << s}
source_code << "#{i}class #{model_name + superclass}"
insertions.each do |line|
source_code << (i + INDENT + line.to_s)
end
source_code << "#{i}end"
after.each {|s| source_code << s}
source_code = source_code.join("\n")
path = dst_path(:models, class_to_route(name))
File.exists?(path) && fail("#{name} model already exists")
o
o '=== Generating "%s" model ===' % name
dir = File.dirname(path)
if File.exists?(dir)
File.directory?(dir) || fail("#{unrootify dir} should be a directory")
else
o '*** Creating "%s/" ***' % unrootify(dir)
FileUtils.mkdir_p(dir)
end
write_file path + '.rb', source_code
output_source_code source_code.split("\n")
end
def generate_spec ctrl_name, name
context = {}
_, context[:controller] = valid_controller?(ctrl_name)
_, context[:action] = valid_action?(ctrl_name, name)
context[:spec] = [ctrl_name, context[:action]]*'#'
o
o '=== Generating "%s#%s" spec ===' % [ctrl_name, name]
path = dst_path(:specs, class_to_route(ctrl_name), '/')
if File.exists?(path)
File.directory?(path) || fail("#{path} should be a directory")
else
o '*** Creating "%s" ***' % unrootify(path)
FileUtils.mkdir_p(path)
end
file = path + context[:action] + '_spec.rb'
File.exists?(file) && fail('%s already exists' % unrootify(file))
test_framework = setups[:test_framework] || DEFAULT_TEST_FRAMEWORK
engine = Tenjin::Engine.new(path: [src_path.specfiles], cache: false)
source_code = engine.render(test_framework.to_s + '.erb', context)
write_file file, source_code
output_source_code source_code.split("\n")
end
end
end
|
class Domain
def initialize(request, domains_file = nil)
@host = request.host
@domains_file = domains_file
end
def key
domain['key']
end
def host
@host
end
private
def domain
@domain ||= find_domain
end
def find_domain
domain_key_value = domains.detect { |_key, domain|
domain['host'] == @host
}
unless domain_key_value
raise ArgumentError, "host is not part of the domain file"
end
domain_key_value.last # last returns attributes
end
def domains
@domains ||= load_file
end
def load_file
unless File.exists?(domains_file)
raise ArgumentError, 'web_sites.yml file not found'
end
YAML::load(File.read(domains_file))
end
def domains_file
@domains_file ||= "#{Rails.root}/config/web_sites.yml"
end
end
|
class CreateEntityCostCenterDetails < ActiveRecord::Migration
def change
create_table :entity_cost_center_details do |t|
t.integer :cost_center_detail_id
t.integer :entity_id
t.integer :participation
t.timestamps
end
end
end
|
require "rails_helper"
RSpec.describe "GET /api/standards" do
context "with valid type and name" do
it "returns the standard document" do
standard = create(:standard, :with_document, code: "ISO 19115")
stub_relaton_document(standard.code, standard.year)
get_api api_standard_path(
code: standard.code,
year: standard.year,
document_format: "xml",
)
content = JSON.parse(response.body)
expect(content["updated_at"]).not_to be_nil
expect(content["code"]).to eq(standard.code)
expect(content["type"]).to eq(standard.standard_type.upcase)
expect(content["document"]).to include('<bibitem id="ISO19115-2003" type')
end
end
context "with invalid type and name" do
it "returns not found status" do
_standard = build(:standard)
get_api api_standard_path("invalid standard", year: 2019)
content = JSON.parse(response.body)
expect(response.status).to eq(422)
expect(content["error"]).to eq(I18n.t("standards.unprocessable_entity"))
end
end
end
|
module TwoFactorSettingsHelper
def qr_code_as_svg(uri)
RQRCode::QRCode.new(uri).as_svg(
offset: 0,
use_path: true,
color: "000",
shape_rendering: "crispEdges",
module_size: 4,
standalone: true
).html_safe
end
end
|
# frozen_string_literal: true
# rubocop:todo all
# Copyright (C) 2019-2020 MongoDB 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 Mongo
# The run!, running? and stop! methods used to be part of the public API
# in some of the classes which now include this module. Therefore these
# methods must be considered part of the driver's public API for backwards
# compatibility reasons. However using these methods outside of the driver
# is deprecated.
#
# @note Do not start or stop background threads in finalizers. See
# https://jira.mongodb.org/browse/RUBY-2453 and
# https://bugs.ruby-lang.org/issues/16288. When interpreter exits,
# background threads are stopped first and finalizers are invoked next,
# and MRI's internal data structures are basically corrupt at this point
# if threads are being referenced. Prior to interpreter shutdown this
# means threads cannot be stopped by objects going out of scope, but
# most likely the threads hold references to said objects anyway if
# work is being performed thus the objects wouldn't go out of scope in
# the first place.
#
# @api private
module BackgroundThread
include Loggable
# Start the background thread.
#
# If the thread is already running, this method does nothing.
#
# @api public for backwards compatibility only
def run!
if @stop_requested && @thread
wait_for_stop
if @thread.alive?
log_warn("Starting a new background thread in #{self}, but the previous background thread is still running")
@thread = nil
end
@stop_requested = false
end
if running?
@thread
else
start!
end
end
# @api public for backwards compatibility only
def running?
if @thread
@thread.alive?
else
false
end
end
# Stop the background thread and wait for to terminate for a reasonable
# amount of time.
#
# @return [ true | false ] Whether the thread was terminated.
#
# @api public for backwards compatibility only
def stop!
# If the thread was not started, there is nothing to stop.
#
# Classes including this module may want to perform additional
# cleanup, which they can do by overriding this method.
return true unless @thread
# Background threads generally perform operations in a loop.
# This flag is meant to be checked on each iteration of the
# working loops and the thread should stop working when this flag
# is set.
@stop_requested = true
# Besides setting the flag, a particular class may have additional
# ways of signaling the background thread to either stop working or
# wake up to check the stop flag, for example, setting a semaphore.
# This can be accomplished by providing the pre_stop method.
pre_stop
# Now we have requested the graceful termination, and we could wait
# for the thread to exit on its own accord. A future version of the
# driver may allow a certain amount of time for the thread to quit.
# For now, we additionally use the Ruby machinery to request the thread
# be terminated, and do so immediately.
#
# Note that this may cause the background thread to terminate in
# the middle of an operation.
@thread.kill
wait_for_stop
end
private
def start!
@thread = Thread.new do
catch(:done) do
until @stop_requested
do_work
end
end
end
end
# Waits for the thread to die, with a timeout.
#
# Returns true if the thread died, false otherwise.
def wait_for_stop
# Wait for the thread to die. This is important in order to reliably
# clean up resources like connections knowing that no background
# thread will reconnect because it is still working.
#
# However, we do not want to wait indefinitely because in theory
# a background thread could be performing, say, network I/O and if
# the network is no longer available that could take a long time.
start_time = Utils.monotonic_time
([0.1, 0.15] + [0.2] * 5 + [0.3] * 20).each do |interval|
begin
Timeout.timeout(interval) do
@thread.join
end
break
rescue ::Timeout::Error
end
end
# Some driver objects can be reconnected, for backwards compatibiilty
# reasons. Clear the thread instance variable to support this cleanly.
if @thread.alive?
log_warn("Failed to stop the background thread in #{self} in #{(Utils.monotonic_time - start_time).to_i} seconds: #{@thread.inspect} (thread status: #{@thread.status})")
# On JRuby the thread may be stuck in aborting state
# seemingly indefinitely. If the thread is aborting, consider it dead
# for our purposes (we will create a new thread if needed, and
# the background thread monitor will not detect the aborting thread
# as being alive).
if @thread.status == 'aborting'
@thread = nil
@stop_requested = false
end
false
else
@thread = nil
@stop_requested = false
true
end
end
# Override this method to do the work in the background thread.
def do_work
end
# Override this method to perform additional signaling for the background
# thread to stop.
def pre_stop
end
end
end
|
module Sapphire
# So far we aren't differentiating between a token and an ATOM. Some tokens become SEXPs
class Token
attr_accessor :type,
:string,
:pos,
:line,
:file,
:parent_id
def initialize(t,s,pos)
@type = t
@string = s
@pos = pos
end
def to_s
return "<#{self.string} type=#{self.real_type} file=#{self.file} line=#{self.line} pos=#{self.pos}>"
end
def real_type
case @string
when "("
return :lparen
when ")"
return :rparen
when "{"
return :lbrace
when "}"
return :rbrace
when "["
return :lbracket
when "]"
return :rbracket
when /^[\+\-]{0,1}[0-9]+\.[0-9]+/
return :float
else
return @type
end
end
end
end |
# creates Orders table
class CreateOrders < ActiveRecord::Migration[5.0]
def change
create_join_table :products, :users, table_name: :orders do |t|
t.integer :quantity, null: false
t.boolean :is_completed
t.text :delivery_address
t.index :product_id
t.index :user_id
t.timestamps
end
say 'Orders table is created.'
end
end
|
class Pdfjob < ActiveRecord::Base
#include Reportable
# class << self
# def reporter_class
# #DamperInspectionReporter
# #PdfGenerationReporter
# PdfjobReporter
# end
# end
# def full_report_path
# File.join(pdf_path, 'inspection_report.pdf')
# end
# private
# def pdf_path
# File.join(Rails.root, %w(public content pdfjobs pdf_reports), "#{id}")
# end
end
|
require 'rails_helper'
RSpec.describe 'AccountActivationsController', type: :request do
let(:user) { create :user }
describe 'POST/sessions' do
subject { post login_path, params: { session: { email: user.email, password: user.password }}}
context 'when account is not activated' do
it 'redirect to main page with warning' do
expect(subject).to redirect_to root_path
follow_redirect!
expect(response.body).to include('Account not activated.Check your email for the activation link')
end
end
context 'when account is activated' do
it 'redirect to user profile' do
user.update_columns(activated: true, activated_at: Time.zone.now)
expect(subject).to redirect_to "/users/#{user.id}"
end
end
end
end
|
require_relative 'line_items'
require_relative 'receipt'
require_relative 'logging'
class Register
attr_reader :total
attr_reader :line_items
def initialize
@line_items = LineItems.new
end
def total
@line_items.total
end
def add(product_code)
Logging.log.info("adding #{product_code} to line items")
@line_items.add(product_code)
end
def print_receipt
Receipt.print(@line_items.line_items, @line_items.total)
end
end
|
class Glider
def lift
puts "Rising"
end
def bank
puts "Turning"
end
end
class Nomad
def initialize(glider)
@glider = glider
end
=begin
def do(action)
if action == 'lift'
@glider.lift
elsif action == 'bank'
@glider.bank
else
raise NoMethodError.new(action)
end
end
=end
def do(action)
@glider.send(action)
end
end
nomad = Nomad.new(Glider.new)
nomad.do("lift")
nomad.do("bank")
# puts is private method on Object
nomad.send("puts", "Hello World")
|
module ApplicationHelper
def edit_and_destroy_buttons(item)
if signed_in?
edit = link_to('edit', url_for([:edit, item]), class: "btn")
del = link_to('Destroy', item, method: :delete,
data: {confirm: 'Are you sure?'}, class: "btn btn-danger")
raw("#{edit} #{del}")
end
end
def round(decimal)
with_precision = number_with_precision(decimal, precision: 1)
raw("#{with_precision}")
end
end
|
class Answer < ActiveRecord::Base
# Remember to create a migration!
belongs_to :answerer, class_name: "User", foreign_key: :user_id
belongs_to :question
has_many :comments, as: :commentable
has_many :votes, as: :votable
validates :description, :user_id, :question_id, presence: true
def points
votes.sum(:value)
end
end
|
class PhotoSerializer < ActiveModel::Serializer
attributes :id, :description, :filename, :date_taken, :aws_filename, :original_url, :grid_url, :huge_url, :large_url, :thumbnail_url, :upload_user_id, :upload_user_email, :created_at
has_one :upload_user
end
|
#!/usr/bin/env ruby
#
require 'optparse'
require 'fileutils'
@options = {
:cluster => nil,
:az => nil,
:ca => {
:key => 'ca.key',
:key_bits => 4096,
:config => 'ca.conf',
:validity_days => 999999,
:cert => 'ca.crt',
},
:certs => {
:key_bits => 2048,
:key => 'sidecar-injector.key',
:csr => 'sidecar-injector.csr',
:cert => 'sidecar-injector.crt',
:validity_days => 999999,
:csr_config => 'csr-prod.conf',
}
}
def gen_new_certs(az, cluster)
puts "Generating certs for #{az}-#{cluster}"
workdir = "./#{az}/#{cluster}"
# gen new ca key
puts "Generating a new CA key..."
if !Kernel.system(%[
openssl \
genrsa \
-out #{File.join(workdir, @options[:ca][:key])} \
#{@options[:ca][:key_bits]} \
])
abort "unable to generate ca key"
end
# # Create and self sign the Root Certificate
puts "Creating and signing the ca.crt (press enter when prompted for input)"
if !Kernel.system(%[openssl req -x509 \
-config #{@options[:ca][:config]} \
-new -nodes \
-key #{File.join(workdir,@options[:ca][:key])} \
-sha256 -days #{@options[:ca][:validity_days]} \
-out #{File.join(workdir,@options[:ca][:cert])} \
])
abort "unable to generate and sign ca.crt"
# <press enter a bunch>
end
# ### Create the certificate key
puts "Creating the certificate key"
if !Kernel.system(%[
openssl genrsa \
-out #{File.join(workdir, @options[:certs][:key])} \
#{@options[:certs][:key_bits]} \
])
abort "unable to create certificate key"
end
# #create signing request
puts "Creating signing request (press enter when prompted for input)"
if !Kernel.system(%[
openssl req -new \
-key #{File.join(workdir,@options[:certs][:key])} \
-out #{File.join(workdir,@options[:certs][:csr])} \
-config #{@options[:certs][:csr_config]} \
])
abort "unable to create CSR"
end
# ### Check the signing request
# openssl req -text -noout -in sidecar-injector.csr|grep -A4 "Requested Extensions"
#
# ### Generate the certificate using the mydomain csr and key along with the CA Root key
puts "Generate the cert"
if !Kernel.system(%[
openssl x509 -req \
-in #{File.join(workdir,@options[:certs][:csr])} \
-CA #{File.join(workdir, @options[:ca][:cert])} \
-CAkey #{File.join(workdir, @options[:ca][:key])} \
-CAcreateserial \
-out #{File.join(workdir, @options[:certs][:cert])} \
-days #{@options[:certs][:validity_days]} \
-sha256 -extensions req_ext \
-extfile #{@options[:certs][:csr_config]} \
])
abort "Unable to generate and sign the cert!"
end
end
def main
Dir.chdir(File.dirname(__FILE__))
if ENV['DEPLOYMENT'].nil?
abort "You must pass DEPLOYMENT= in the environment (i.e. us-east-1 or dc01) for what DEPLOYMENT we are generating a cert for"
end
if ENV['CLUSTER'].nil?
abort "You must pass CLUSTER= in the environment (i.e. PRODUCTION) for what CLUSTER we are generating a cert for"
end
az = ENV['DEPLOYMENT'].downcase
cluster = ENV['CLUSTER'].upcase
if !Dir.exist?("./#{az}/#{cluster}")
puts "Creating ./#{az}/#{cluster}"
FileUtils.mkdir_p("./#{az}/#{cluster}")
end
gen_new_certs(az, cluster)
puts "\n\n\nAll done!\n\nHere are your certs for #{az}-#{cluster}\n\n"
Kernel.system(%[git status])
puts "Generated new certs for #{az}-#{cluster} for k8s-sidecar-injector"
puts "Please commit these!"
end
main
|
require 'rails_helper'
RSpec.describe Ranking, type: :model do
it "has valid factory" do
expect(FactoryGirl.create(:ranking)).to be_valid
end
it "able to find current ladderboard" do
expect(Ranking.ladder.length).to be > 0
end
end
|
module TagMutations
MUTATION_TARGET = 'tag'.freeze
PARENTS = [
'source',
'project_media',
'team',
{ tag_text_object: TagTextType },
].freeze
module SharedCreateAndUpdateFields
extend ActiveSupport::Concern
include Mutations::Inclusions::AnnotationBehaviors
end
class Create < Mutations::CreateMutation
include SharedCreateAndUpdateFields
argument :tag, GraphQL::Types::String, required: true
end
class Update < Mutations::UpdateMutation
include SharedCreateAndUpdateFields
argument :tag, GraphQL::Types::String, required: false
end
class Destroy < Mutations::DestroyMutation; end
class CreateTagsBulkInput < BaseInputObject
include SharedCreateAndUpdateFields
argument :tag, GraphQL::Types::String, required: true
end
module Bulk
PARENTS = [
'team',
{ check_search_team: CheckSearchType }
].freeze
class Create < Mutations::BulkCreateMutation
argument :inputs, [CreateTagsBulkInput, null: true], required: false
def resolve(inputs: [])
if inputs.size > 10_000
raise I18n.t(:bulk_operation_limit_error, limit: 10_000)
end
ability = context[:ability] || Ability.new
if ability.can?(:bulk_create, Tag.new(team: Team.current))
Tag.bulk_create(inputs, Team.current)
else
raise CheckPermissions::AccessDenied, I18n.t(:permission_error)
end
end
end
end
end
|
class AddProductProvider < ActiveRecord::Migration[6.0]
def change
create_table :product_providers do |t|
t.references :external_entity, index: true, null: false
t.references :product, index: true, null: false
t.string :brand
t.decimal :price, precision: 10, scale: 3
t.decimal :discount, precision: 10, scale: 3
t.integer :stock
t.string :notes
end
end
end
|
require_relative "piece.rb"
require_relative "rook.rb"
require_relative "knight.rb"
require_relative "bishop.rb"
require_relative "queen.rb"
require_relative "king.rb"
require_relative "pawn.rb"
require_relative "null.rb"
require_relative "stepable.rb"
require_relative "slideable.rb"
class Board
attr_reader :rows
def initialize
@rows = Array.new(8) {Array.new()}
@rows.each_with_index do |row, row_idx|
if row_idx == 0
row << Rook.new(:white, self, [0,0])
row << Knight.new(:white, self, [0,1])
row << Bishop.new(:white, self, [0,2])
row << Queen.new(:white, self, [0,3])
row << King.new(:white, self, [0,4])
row << Bishop.new(:white, self, [0,5])
row << Knight.new(:white, self, [0,6])
row << Rook.new(:white, self, [0,7])
elsif row_idx == 1
row << Pawn.new(:white, self, [1,0])
row << Pawn.new(:white, self, [1,1])
row << Pawn.new(:white, self, [1,2])
row << Pawn.new(:white, self, [1,3])
row << Pawn.new(:white, self, [1,4])
row << Pawn.new(:white, self, [1,5])
row << Pawn.new(:white, self, [1,6])
row << Pawn.new(:white, self, [1,7])
elsif row_idx == 6
row << Pawn.new(:black, self, [6,0])
row << Pawn.new(:black, self, [6,1])
row << Pawn.new(:black, self, [6,2])
row << Pawn.new(:black, self, [6,3])
row << Pawn.new(:black, self, [6,4])
row << Pawn.new(:black, self, [6,5])
row << Pawn.new(:black, self, [6,6])
row << Pawn.new(:black, self, [6,7])
elsif row_idx == 7
row << Rook.new(:black, self, [7,0])
row << Knight.new(:black, self, [7,1])
row << Bishop.new(:black, self, [7,2])
row << Queen.new(:black, self, [7,3])
row << King.new(:black, self, [7,4])
row << Bishop.new(:black, self, [7,5])
row << Knight.new(:black, self, [7,6])
row << Rook.new(:black, self, [7,7])
else
row << NullPiece.instance
row << NullPiece.instance
row << NullPiece.instance
row << NullPiece.instance
row << NullPiece.instance
row << NullPiece.instance
row << NullPiece.instance
row << NullPiece.instance
end
end
end
def [](pos)
row, col = pos
@rows[row][col]
end
def []=(pos, val)
row, col = pos
@rows[row][col] = val
end
def move_piece(start_pos, end_pos)
piece = self[start_pos]
raise " there is no piece at start_pos " if self[start_pos] == NullPiece.instance
unless end_pos[0] >= 0 && end_pos[0] < 8 && end_pos[1] >= 0 && end_pos[1] < 8
raise " the piece cannot move to end_pos"
end
raise "you can't move there" if !piece.moves.include?(end_pos)
self[start_pos] = self[end_pos]
self[end_pos] = piece
piece.pos = end_pos
puts " your move was successful"
end
end
chess = Board.new
# chess.rows[0][0].symbol
p chess.move_piece([1,0],[4,0])
# chess.rows[2][0].symbol
# p chess.rows[0][0]
# p chess.rows[4][4]
# chess.move_piece([0, 0], [4,4])
# p chess.rows[0][0]
# p chess.rows[4][4]
|
class AddColumnsToEvents < ActiveRecord::Migration[5.1]
def change
add_column :events, :commentor, :boolean
add_column :events, :phone, :boolean
add_column :events, :email, :boolean
add_column :events, :comment_type, :string
end
end
|
class Person < ActiveRecord::Base
scope :search_with_like, ->(query) { where("name like '%#{query}%'") }
scope :search_with_paragraph_like, ->(query) { joins(:paragraphs).merge(Paragraph.search_with_like(query)) }
scope :search_with_index, ->(query) { where("to_tsvector('english', name) @@ plainto_tsquery('english', ?)", query) }
scope :search_with_paragraph_index, ->(query) { joins(:paragraphs).merge(Paragraph.search_with_index(query)) }
scope :search_with_combined_like, ->(query) { where("id in (#{search_with_like(query).select('people.id').to_sql}) or id in (#{search_with_paragraph_like(query).select('people.id').to_sql})") }
scope :search_with_combined_index, ->(query) { where("id in (#{search_with_index(query).select('people.id').to_sql}) or id in (#{search_with_paragraph_index(query).select('people.id').to_sql})") }
scope :search_with_view, ->(query) { joins(:searchable_people).merge(SearchablePeople.search_with_index(query)) }
scope :search_with_trigrams, ->(query) { where("name % ?", query) }
scope :search_with_view_trigrams, ->(query) { joins(:searchable_people).merge(SearchablePeople.search_with_trigrams(query)) }
scope :ordered_by_levenshtein, ->(query) { order("levenshtein(name, '#{query}') asc") }
has_many :paragraphs
has_one :searchable_people, foreign_key: :id
def self.search(query)
search_with_like(query)#.ordered_by_levenshtein(query)
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
# The most common configuration options are documented and commented below.
# For a complete reference, please see the online documentation at
# https://docs.vagrantup.com.
# Every Vagrant development environment requires a box. You can search for
# boxes at https://vagrantcloud.com/search.
config.vm.box = "zhaoyunxing/centos-docker"
config.vm.box_version = "1.0"
# docker compose配置
config.vm.provision:docker
config.vm.provision:docker_compose,
yml:[
"/cherry/docker-compose.yml"
],
rebuild: true,
run:"always"
config.vm.network "forwarded_port", guest: 22, host: 2222
config.vm.network "forwarded_port", guest: 8848, host: 8848
config.vm.network "forwarded_port", guest: 3306, host: 3306
config.vm.network "forwarded_port", guest: 8180, host: 8180
config.vm.network "forwarded_port", guest: 9876, host: 9876
config.vm.network "forwarded_port", guest: 10909, host: 10909
config.vm.network "forwarded_port", guest: 10911, host: 10911
# 同步目录
config.vm.synced_folder ".", "/cherry",type: "virtualbox"
# windows
#config.vm.synced_folder ".", "/cherry", type: "rsync"
#config.ssh.username = "vagrant"
#config.ssh.password = "vagrant"
#virtualbox
config.vm.provider "virtualbox" do |vb|
vb.memory = "4096"
vb.cpus=2
vb.name="spring-dtx-server"
end
end
|
require 'minitest/spec'
require 'minitest/autorun'
require 'external_media'
describe ExternalMedia do
it "must add has_external_media method" do
class Foo
include ExternalMedia
end
Foo.methods.must_include :has_external_media
end
it "has_external_media adds external_media attribute" do
class Foo
include ExternalMedia
has_external_media
end
Foo.new.methods.must_include :external_media
end
end
|
require_relative './post'
require_relative './post_decorator'
class BlogIndex
def initialize(max_per_page = 10, current_page = 0)
@posts = []
@max_per_page = max_per_page
@current_page = current_page
end
def load(index_file)
collection = YAML.load_file(index_file)
collection.each do |post_data|
post = Post.new(post_data[:title], nil, post_data[:date], post_data[:source], post_data[:href])
@posts << PostDecorator.new(post)
end
end
def find_by_uri(uri)
@posts.find { |post| post.href == uri }
end
def page_posts
newest = @max_per_page * @current_page
oldest = newest + @max_per_page
@posts[newest...oldest] or []
end
def has_next?
@posts.count > @current_page*@max_per_page + @max_per_page
end
def has_previous?
@current_page > 0
end
def next_page
@current_page + 1
end
def current_page
@current_page
end
def previous_page
if @current_page == 0
return 0
end
@current_page-1
end
def pages
if @posts == 0
return 1
end
(@posts.count.to_f / @max_per_page).ceil
end
end
|
class CreateRinventors < ActiveRecord::Migration
def change
create_table :rinventors do |t|
t.date :update_date
t.integer :rproductid
t.decimal :starting_amount
t.decimal :added_amount
t.decimal :threshold
t.decimal :sold_amount
t.decimal :actual_amount
t.decimal :theoretical_ending_inventory
t.timestamps
end
end
end
|
abort('Please run this using `bundle exec rake`') unless ENV["BUNDLE_BIN_PATH"]
require 'html-proofer'
require 'rszr'
task :default => ["test"]
task :test => [:spellcheck, :htmlproofer] do
puts "Tests complete."
end
task :resize240 do
sh "mkdir -p assets/images/articles/240"
files = FileList['assets/images/articles/original/*.jpg']
files.each do |file|
puts "Resizing #{file}..."
target = file.gsub("original", "240")
Rszr::Image.load(file).resize!(240, 180).save(target)
end
puts "Image resize complete."
end
task :resize600 do
sh "mkdir -p assets/images/articles/600"
files = FileList['assets/images/articles/original/*.jpg']
files.each do |file|
puts "Resizing #{file}..."
target = file.gsub("original", "600")
Rszr::Image.load(file).resize!(600, 450).save(target)
end
puts "Image resize complete."
end
task :resize => [:resize240, :resize600] do
puts "Tests complete."
end
desc "Test for broken internal links"
task :checklinksinternal => :jekyll do
options = {
:assume_extension => true,
:disable_external => true,
:empty_alt_ignore => true,
:alt_ignore => [ /.*/ ],
:url_ignore => [ "https://github.com//issues", "https://www.uka.org.uk/EasysiteWeb/getresource.axd?AssetID=169662" ],
:internal_domains => [ "genderkit.github.io", "127.0.0.1", "genderkit.org.uk" ],
:url_swap => {
/https?\:\/\/genderkit\.github\.io\/genderkit\// => "/",
/\/?genderkit\// => "/"
},
:typhoeus => {
:ssl_verifypeer => false,
:ssl_verifyhost => 0,
:timeout => 60
}
}
HTMLProofer.check_directory("./_site", options).run
end
desc "Test for broken external links"
task :checklinks => :jekyll do
options = {
:assume_extension => true,
:disable_external => false,
:empty_alt_ignore => true,
:alt_ignore => [ /.*/ ],
:internal_domains => [ "genderkit.github.io", "127.0.0.1", "genderkit.org.uk" ],
:url_ignore => [ "https://github.com//issues", "https://qtipcic.co.uk" ],
:url_swap => {
/https?\:\/\/genderkit\.github\.io\/genderkit\// => "/",
/\/?genderkit\// => "/"
},
:typhoeus => {
:ssl_verifypeer => false,
:ssl_verifyhost => 0,
:timeout => 60,
:headers => {
"User-Agent" => "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148",
"Accept" => '*/*'
}
}
}
HTMLProofer.check_directory("./_site", options).run
end
desc "Rewrite URLs in bibliography sections to be real links"
task :referencelinks do
# Update bibliography sections to include real HTML links to sources
files = FileList['_site/article/*/*.html','_site/resources/*/*.html']
files.each do |file_name|
text = File.open(file_name, 'r'){ |file| file.read }
if text.gsub!(/\[online\] Available from: ([^\s<]*)/, '<a href="\1">Link</a>')
puts "rewriting #{file_name}..."
File.open(file_name, 'w'){|file| file.write(text)}
end
end
end
desc "Convert icons from SVG to PNG"
task :converticons do
files = FileList['assets/images/icons/svg/*.svg']
files.each do |file|
puts "Converting #{file}..."
target = file.gsub("icons/svg/", "icons/")
target = target.gsub(".svg", ".png")
sh "inkscape --export-png=#{target} --export-width=128 --export-height=128 #{file}"
end
end
desc "Convert illustrations from SVG to PNG"
task :convertillustrations do
files = FileList['assets/images/clothes/svg/*.svg']
files.each do |file|
puts "Converting #{file}..."
target = file.gsub("clothes/svg/", "clothes/")
target = target.gsub(".svg", ".png")
sh "inkscape --export-png=#{target} --export-area-drawing -y 0 #{file}"
end
end
desc "Build the site using Jekyll"
task :jekyll => :resize do
sh "bundle exec jekyll build"
Rake::Task["referencelinks"].invoke
end
desc "Test using proselint"
task :proselint => :jekyll do
files = FileList['_articles/*.md', '_identities/*.md']
files.each do |file|
results = `proselint #{file}`
if (results.length > 0)
puts "In #{file}:"
puts "#{results}"
end
end
end
desc "Test the built html"
task :htmlproofer => :jekyll do
options = {
:assume_extension => true,
:disable_external => true,
:check_html => true,
:validation => {
:report_missing_names => true
},
:url_swap => {
/(genderkit\.github\.io)?\/genderkit\// => "genderkit.github.io"
},
:internal_domains => [ "genderkit.github.io", "127.0.0.1", "genderkit.org.uk" ],
}
HTMLProofer.check_directory("./_site", options).run
end
def run_spellcheck(file)
cmd = "cat #{file} | aspell -p './whitelist' -H -d en_GB --encoding utf-8 --lset-html-skip ol:script:style list | cat"
result = `#{cmd}`
result
end
def run_spellcheck_markdown(file)
cmd = "cat #{file} | sed 's/image:.*//g' | sed 's/{%[^%]*%}//g' | aspell -p './whitelist' -M -d en_GB --encoding utf-8 list | cat"
result = `#{cmd}`
result
end
desc "Spellcheck using Aspell"
task :spellcheck => [:spellcheckmarkdown, :jekyll] do
errors = 0
files = FileList['_site/**/*.html']
files.exclude("_site/books/*.html")
files.exclude("_site/organisations/*.html")
files.exclude("_site/publications/*.html")
files.exclude("_site/studies/*.html")
files.exclude("_site/credits/*.html")
files.exclude("_site/tools/*")
files.exclude("_site/explore/names-*/*.html")
files.exclude("_site/resources/national/*.html")
files.exclude("_site/resources/local/*.html")
files.exclude("_site/resources/research/*.html")
files.each do |file|
results = run_spellcheck(file)
if (results.length > 0)
puts "Found spelling errors in #{file}:"
puts results
errors = errors + 1
end
end
if errors > 0
puts "Spelling errors found! If you believe these words are spelled correctly, add them to the file called 'whitelist'."
exit 1
else
puts "No spelling errors found in built site."
end
end
desc "Spellcheck markdown files using Aspell"
task :spellcheckmarkdown do
errors = 0
files = FileList['**/*.md']
files.exclude("CONTRIBUTING.md")
files.exclude("credits.md")
files.each do |file|
results = run_spellcheck_markdown(file)
if (results.length > 0)
puts "Found spelling errors in #{file}:"
puts results
errors = errors + 1
end
end
if errors > 0
puts "Spelling errors found! If you believe these words are spelled correctly, add them to the file called 'whitelist'."
exit 1
else
puts "No spelling errors found in Markdown sources."
end
end
|
class SocialMediaPostsController < ApplicationController
before_action :set_social_media_post, only: [:show, :update, :destroy]
# GET /social_media_posts
def index
if (params.has_key?(:topic_id))
@social_media_posts = SocialMediaPost.where(topic_id: params[:topic_id])
else
@social_media_posts = SocialMediaPost.all
end
paginate json: @social_media_posts
end
# GET /social_media_posts/1
def show
render json: @social_media_post
end
# POST /social_media_posts
def create
@social_media_post = SocialMediaPost.new(social_media_post_params)
if @social_media_post.save
render json: @social_media_post, status: :created, location: @social_media_post
else
render json: @social_media_post.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /social_media_posts/1
def update
if @social_media_post.update(social_media_post_params)
render json: @social_media_post
else
render json: @social_media_post.errors, status: :unprocessable_entity
end
end
# DELETE /social_media_posts/1
def destroy
@social_media_post.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_social_media_post
@social_media_post = SocialMediaPost.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def social_media_post_params
params.require(:social_media_post).permit(:text_content, :topic_id, :social_medium_id)
end
end
|
class CreatePapers < ActiveRecord::Migration
def change
create_table :papers do |t|
t.float :paper_height
t.float :paper_width
t.string :chain_lines
t.string :format
t.string :name
t.text :result
t.timestamps null: false
end
end
end
|
require 'rails_helper'
describe "find many merchants with params" do
context "search using valid params" do
before :each do
@merchant1, @merchant2, @merchant3 = create_list(:merchant, 3)
end
it "can find an merchant with id params" do
get '/api/v1/merchants/find_all', params: {id: @merchant1.id}
expect(response).to be_success
merchants = JSON.parse(response.body)
merchant = merchants.first
expect(merchants.count).to eq(1)
expect(merchant["id"]).to eq(@merchant1.id)
expect(merchant["name"]).to eq(@merchant1.name)
end
it "can find an merchant with name params" do
@merchant1.update(name: "Test")
@merchant2.update(name: "Test")
get '/api/v1/merchants/find_all', params: {name: @merchant1.name}
expect(response).to be_success
merchants = JSON.parse(response.body)
merchant1 = merchants.first
merchant2 = merchants.last
expect(merchants.count).to eq(2)
expect(merchant1["id"]).to eq(@merchant1.id)
expect(merchant2["id"]).to eq(@merchant2.id)
end
it "can find an merchant with created_at param" do
@merchant1.update(created_at: "2012-03-27T14:54:03.000Z")
@merchant2.update(created_at: "2012-03-27T14:54:03.000Z")
get '/api/v1/merchants/find_all', params: {created_at: @merchant1.created_at}
expect(response).to be_success
merchants = JSON.parse(response.body)
merchant1 = merchants.first
merchant2 = merchants.last
expect(merchants.count).to eq(2)
expect(merchant1["id"]).to eq(@merchant1.id)
expect(merchant2["id"]).to eq(@merchant2.id)
end
it "can find an merchant with updated_at param" do
@merchant1.update(updated_at: "2012-03-27T14:54:03.000Z")
@merchant2.update(updated_at: "2012-03-27T14:54:03.000Z")
@merchant3.update(updated_at: "2012-03-27T14:54:03.000Z")
get '/api/v1/merchants/find_all', params: {updated_at: @merchant1.updated_at}
expect(response).to be_success
merchants = JSON.parse(response.body)
merchant1 = merchants.first
merchant2 = merchants.last
expect(merchants.count).to eq(3)
expect(merchant1["id"]).to eq(@merchant1.id)
expect(merchant2["id"]).to eq(@merchant3.id)
end
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :null_session, :if => Proc.new { |c| c.request.format == 'application/json' && c.request.fullpath.match(/^api/)}
acts_as_token_authentication_handler_for User
# This is our new function that comes before Devise's one
before_filter :authenticate_user_from_token!
before_filter :populate_roles
before_action :authenticate_user!
before_action :configure_permitted_parameters, if: :devise_controller?
rescue_from CanCan::AccessDenied do |exception|
Rails.logger.debug "Access denied on #{exception.action} #{exception.subject.inspect}"
#respond_to do |format|
#format.json { render :json=> exception.to_json, :status => :forbidden }
#format.html { render :html=> exception.to_s, :status => :forbidden }
#end
redirect_to "/dashboard/#{current_user.role.name.downcase}", :alert => exception.message
end
protected
# allow strong params for custom devise forms
def configure_permitted_parameters
devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:first_name,:last_name, :email, :password,:password_confirmation,:current_password,:role_id,
{address_attributes: [ :id, :street, :city, :city_code, :country ]}, :organization_id )
}
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:first_name,:last_name, :email, :password,:password_confirmation,:current_password,:role_id,
{address_attributes: [ :id, :street, :city, :city_code, :country ]}, :organization_id )
}
end
def populate_roles
@user = @user || current_user
@role = @role || @user.role unless @user.nil?
end
private
# Overwriting the sign_out redirect path method
def after_sign_out_path_for(resource_or_scope)
welcome_index_path
end
def after_sign_in_path_for(resource_or_scope)
return nil if request.format == 'application/json'
"/dashboard/#{current_user.role.name.downcase}"
end
def authenticate_user_from_token!
user_token = params[:user_token].presence
user = user_token && User.find_by_authentication_token(user_token.to_s)
if user
if user.timedout?(user.current_sign_in_at)
return
end
sign_in user, store: false
end
end
end
|
require File.dirname(__FILE__) + '/../../spec_helper.rb'
include Rugalytics
describe Profile do
describe "being initialized" do
it "should accept :name as key" do
profile = Profile.new(:name => 'test', :profile_id => '12341234')
profile.name.should == 'test'
end
it "should accept :account_id as key" do
profile = Profile.new(:account_id => '12341234', :profile_id => '12341234')
profile.account_id.should == '12341234'
end
it "should accept :profile_id as key" do
profile = Profile.new(:profile_id => '12341234')
profile.profile_id.should == '12341234'
end
end
describe "finding by account id and profile id" do
it 'should find account and find profile' do
account_id = 1254221
profile_id = 12341234
account = mock('account')
profile = mock('profile')
Account.should_receive(:find).with(1254221).and_return account
account.should_receive(:find_profile).with(profile_id).and_return profile
Profile.find(account_id, profile_id).should == profile
end
end
describe 'finding pageviews' do
before do
@profile = Profile.new :profile_id=>123
@report = mock('report',:pageviews_total=>100)
end
it 'should return total from loaded "Pageviews" report' do
@profile.should_receive(:pageviews_report).with({}).and_return @report
@profile.pageviews.should == @report.pageviews_total
end
describe 'when from and to dates are specified' do
it 'should return total from "Pageviews" report for given dates' do
options = {:from=>'2008-05-01', :to=>'2008-05-03'}
@profile.should_receive(:pageviews_report).with(options).and_return @report
@profile.pageviews(options).should == @report.pageviews_total
end
end
end
describe 'finding visits' do
before do
@profile = Profile.new :profile_id=>123
@report = mock('report', :visits_total=>100)
end
it 'should return total from loaded "Visits" report' do
@profile.should_receive(:visits_report).with({}).and_return @report
@profile.visits.should == @report.visits_total
end
describe 'when from and to dates are specified' do
it 'should return total from "Visits" report for given dates' do
options = {:from=>'2008-05-01', :to=>'2008-05-03'}
@profile.should_receive(:visits_report).with(options).and_return @report
@profile.visits(options).should == @report.visits_total
end
end
end
describe 'finding report when called with method ending in _report' do
before do
@profile = Profile.new :profile_id=>123
@report = mock('report', :visits_total=>100)
end
it 'should find report using create_report method' do
@profile.should_receive(:create_report).with('Visits',{}).and_return @report
@profile.visits_report.should == @report
end
it 'should find instantiate report with report csv' do
csv = 'csv'
@profile.should_receive(:get_report_csv).with({:report=>'Visits'}).and_return csv
@report.stub!(:attribute_names).and_return ''
Report.should_receive(:new).with(csv).and_return @report
@profile.visits_report.should == @report
end
describe 'when report name is two words' do
it 'should find report using create_report method' do
@profile.should_receive(:create_report).with('VisitorsOverview',{}).and_return @report
@profile.visitors_overview_report.should == @report
end
end
describe 'when dates are given' do
it 'should find report using create_report method passing date options' do
options = {:from=>'2008-05-01', :to=>'2008-05-03'}
@profile.should_receive(:create_report).with('Visits', options).and_return @report
@profile.visits_report(options).should == @report
end
end
end
describe 'when asked to set default options when no options specified' do
before do
@profile = Profile.new :profile_id=>123
end
def self.it_should_default option, value
eval %Q|it 'should set :#{option} to #{value}' do
@profile.set_default_options({})[:#{option}].should == #{value}
end|
end
it_should_default :report, '"Dashboard"'
it_should_default :tab, '0'
it_should_default :format, 'Rugalytics::FORMAT_CSV'
it_should_default :rows, '50'
it_should_default :compute, '"average"'
it_should_default :gdfmt, '"nth_day"'
it_should_default :view, '0'
it 'should default :from to a month ago, and :to to today' do
@month_ago = mock('month_ago')
@today = mock('today')
@profile.should_receive(:a_month_ago).and_return @month_ago
@profile.should_receive(:today).and_return @today
@profile.should_receive(:ensure_datetime_in_google_format).with(@month_ago).and_return @month_ago
@profile.should_receive(:ensure_datetime_in_google_format).with(@today).and_return @today
options = @profile.set_default_options({})
options[:from].should == @month_ago
options[:to].should == @today
end
end
describe 'when asked to convert option keys to uri parameter keys' do
before do
@profile = Profile.new :profile_id=>123
end
def self.it_should_convert option_key, param_key, value_addition=''
eval %Q|it 'should convert :#{option_key} to :#{param_key}' do
params = @profile.convert_options_to_uri_params({:#{option_key} => 'value'})
params[:#{param_key}].should == 'value#{value_addition}'
end|
end
it_should_convert :report, :rpt, 'Report'
it_should_convert :compute, :cmp
it_should_convert :format, :fmt
it_should_convert :view, :view
it_should_convert :rows, :trows
it_should_convert :gdfmt, :gdfmt
it_should_convert :url, :d1
it_should_convert :page_title,:d1
it 'should convert from and to dates into the period param' do
from = '20080801'
to = '20080808'
params = @profile.convert_options_to_uri_params :from=>from, :to=>to
params[:pdr].should == "#{from}-#{to}"
end
it 'should set param id to be the profile id' do
@profile.convert_options_to_uri_params({})[:id].should == 123
end
end
it "should be able to find all profiles for an account" do
html = fixture('analytics_profile_find_all.html')
Profile.should_receive(:get).and_return(html)
accounts = Profile.find_all('1254221')
accounts.collect(&:name).should == ["blog.your_site.com"]
end
describe "finding by account name and profile name" do
it 'should find account and find profile' do
account_name = 'your_site.com'
profile_name = 'blog.your_site.com'
account = mock('account')
profile = mock('profile')
Account.should_receive(:find).with(account_name).and_return account
account.should_receive(:find_profile).with(profile_name).and_return profile
Profile.find(account_name, profile_name).should == profile
end
end
describe "finding a profile by passing single name when account and profile name are the same" do
it 'should find account and find profile' do
name = 'your_site.com'
account = mock('account')
profile = mock('profile')
Account.should_receive(:find).with(name).and_return account
account.should_receive(:find_profile).with(name).and_return profile
Profile.find(name).should == profile
end
end
end |
class LendersController < ApplicationController
def show
@lender = Lender.find(params[:id])
@borrowers = Borrower.all
@transactions = History.includes(:borrower).where(lender_id: session[:user_id])
end
def create
@lender = Lender.new(lender_params)
if @lender.save
session[:user_id] = @lender.id
session[:type] = "lender"
redirect_to @lender
else
flash[:errors] = @lender.errors.full_messages
redirect_to :back
end
end
def transaction
@lender = Lender.find(session[:user_id])
if @lender.money < params[:amount].to_i
flash[:errors] = ["You have insufficient funds"]
redirect_to :back
else
@borrower = Borrower.find(params[:id])
if History.exists?(lender_id: session[:user_id], borrower_id: params[:id])
if @borrower.money - @borrower.raised < params[:amount].to_i
flash[:errors] = ["You cannot lend more than the borrower needs"]
redirect_to :back
else
history = History.where(lender_id: session[:user_id], borrower_id: params[:id]).first
history.amount += params[:amount].to_i
if history.save
@lender.money -= params[:amount].to_i
@lender.save
@borrower.raised += params[:amount].to_i
@borrower.save
redirect_to "/lenders/#{session[:user_id]}"
end
end
else
if @borrower.money - @borrower.raised < params[:amount].to_i
flash[:errors] = ["You cannot lend more than the borrower needs"]
redirect_to :back
else
history = History.new(lender_id: session[:user_id], borrower_id: params[:id], amount: params[:amount])
if history.save
@lender.money -= params[:amount].to_i
@lender.save
@borrower.raised += params[:amount].to_i
@borrower.save
redirect_to "/lenders/#{session[:user_id]}"
else
flash[:errors] = history.errors.full_messages
redirect_to :back
end
end
end
end
end
private
def lender_params
params.require(:lender).permit(:first_name, :last_name, :email, :password, :password_confirmation, :money)
end
end
|
def what_was_that_one_with(those_actors)
# Find the movies starring all `those_actors` (an array of actor names).
# Show each movie's title and id.
#Movie.select(:title, :id).joins(:actors).group('movies.id').having('actors.name = (?)', those_actors)
end
def golden_age
# Find the decade with the highest average movie score.
# Movie
# .select('(movies.yr / 10 ) * 10 AS decades')
# .group('((movies.yr / 10 )* 10)')
# .limit(1)
# .pluck(:id)
Movie
.group('decade')
.having('AVG(movies.score) > 0')
.order('AVG(movies.score) DESC')
.limit(1)
.pluck('((movies.yr / 10) * 10) as decade')
.first
end
def costars(name)
# List the names of the actors that the named actor has ever
# appeared with.
# Hint: use a subquery
Actor
.joins(:castings)
.where('castings.movie_id IN
(
SELECT
movies.id
FROM
movies
JOIN
castings ON castings.movie_id = movies.id
JOIN
actors ON castings.actor_id = actors.id
WHERE
actors.name = (?)
) AND actors.name != (?)', name, name)
.pluck('DISTINCT actors.name')
end
def actor_out_of_work
# Find the number of actors in the database who have not appeared in a movie
Actor
.select('count(actors.*)')
.join(:castings)
.where('actors.id NOT IN castings.actor_id')
# SELECT
# COUNT(*)
# FROM
# actors
# WHERE
# id NOT IN (
# SELECT
# actor_id
# FROM
# castings
# )
# SELECT COUNT(actors.id)
# FROM actors
# RIGHT OUTER JOIN castings on castings.actor_id = actors.id
# Group.includes(:user_group_cmb).where(user_group_cmbs: { user_id: 1 })
# Group.left_outer_joins(:user_group_cmb)
end
def starring(whazzername)
# Find the movies with an actor who had a name like `whazzername`.
# A name is like whazzername if the actor's name contains all of the
# letters in whazzername, ignoring case, in order.
# ex. "Sylvester Stallone" is like "sylvester" and "lester stone" but
# not like "stallone sylvester" or "zylvester ztallone"
Movie
.select(:title)
.joins(:actors)
.where('actors.name LIKE (?)', whazzername)
end
def longest_career
# Find the 3 actors who had the longest careers
# (the greatest time between first and last movie).
# Order by actor names. Show each actor's id, name, and the length of
# their career.
end
|
module ManageIQ
module PostgresHaAdmin
VERSION = '3.1.2'.freeze
end
end
|
class EntriesController < ApplicationController
before_filter :find_collection
def new
@entry = @collection.entries.build
end
def create
@entry = @collection.entries.build(params[:entry])
if @entry.save
@entry.collection.update_number!
flash[:notice] = "Total updated."
redirect_to @collection.root
else
flash.now[:alert] = "Total not updated."
render 'collections/show'
end
end
private
def find_collection
@collection = Collection.find(params[:collection_id])
end
end
|
Rails.application.routes.draw do
# Application root
root 'main#index'
# Path for leaving messages
post '/leave_message' => 'main#leave_message'
# Main dasboard index
get 'main_webapp/index'
get 'dashboard' => 'main_webapp#dashboard'
get 'evangelio' => 'main_webapp#evangelio'
get 'staff' => 'main_webapp#staff'
# Devise configuration
devise_for :users
# Semesters and enrollment
resources :semesters do
member do
post 'current'
end
end
resources :group_enrollments
resources :group_offerings do
collection do
get 'lectures'
get 'workshops'
get 'commissions'
get 'shepperdings'
end
end
resources :child_semesters do
member do
delete 'sweet_destroy'
end
collection do
get 'current'
end
member do
get 'receipt'
put 'pay'
put 'unpay'
end
end
resources :coordinator_semesters do
collection do
get 'current'
end
end
# Resources configurations
resources :notifications do
collection do
get 'read'
post 'mark_as_read'
end
end
resources :notices do
collection do
get 'view'
end
end
resources :users do
member do
post 'assign_to_workshop'
post 'assign_to_shepperding'
post 'assign_to_lecture'
post 'assign_to_commission'
post 'assign_child'
delete 'unassign_from_workshop'
delete 'unassign_from_shepperding'
delete 'unassign_from_lecture'
delete 'unassign_from_commission'
delete 'unassign_child'
post 'assign_child'
delete 'unassign_child'
delete 'unshare_task'
post 'toggle_sidebar'
post 'add_email'
post 'add_phone'
get 'edit_tutor'
get 'edit_coordinator'
get 'show_tutor'
get 'show_coordinator'
end
collection do
get 'tutors'
get 'coordinators'
get 'new_coordinator'
get 'new_tutor'
get 'typeaheaddata'
get 'profile'
patch 'update_password'
patch 'update_profile'
end
end
resources :emails
resources :phones
resources :events do
collection do
get 'edit_all'
end
end
resources :workshops do
member do
post 'assign_coordinator'
delete 'unassign_coordinator'
post 'enroll_child'
delete 'unenroll_child'
end
collection do
get 'typeaheaddata'
end
end
resources :lectures do
member do
post 'assign_coordinator'
delete 'unassign_coordinator'
post 'enroll_child'
delete 'unenroll_child'
end
collection do
get 'typeaheaddata'
end
end
resources :children do
member do
post 'assign_to_tutor'
delete 'unassign_from_tutor'
post 'enroll_in_workshop'
post 'enroll_in_lecture'
post 'enroll_in_shepperding'
delete 'unenroll_from_workshop'
delete 'unenroll_from_lecture'
delete 'unenroll_from_shepperding'
end
collection do
get 'typeaheaddata'
end
end
resources :visitor_messages
resources :shepperdings do
member do
post 'assign_coordinator'
delete 'unassign_coordinator'
post 'enroll_child'
delete 'unenroll_child'
end
collection do
get 'typeaheaddata'
end
end
resources :commissions do
member do
post 'assign_coordinator'
delete 'unassign_coordinator'
end
collection do
get 'typeaheaddata'
end
end
resources :tasks do
member do
post 'assign_to_coordinator'
delete 'unassign_from_coordinator'
post 'share_to_coordinator'
post 'mark_as_completed'
delete 'unmark_as_completed'
end
end
resources :projects do
member do
post 'assign_to_coordinator'
delete 'unassign_from_coordinator'
post 'share_to_coordinator'
post 'mark_as_completed'
delete 'unmark_as_completed'
end
end
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
|
require 'open-uri'
require 'addressable/uri'
class FeedsController < ApplicationController
def index
group = params[:group] || 'dev'
recent_days = 10.days
if group == 'all'
feeds = Rails.configuration.feeds.inject([]) do |array, e|
array + e.second
end
else
feeds = Rails.configuration.feeds[group]
if group == 'dev'
recent_days = 7.days
elsif group == 'insightful'
recent_days = 21.days
end
end
now = Time.zone.now
@rss = RSS::Maker.make('atom') do |maker|
maker.channel.author = '어썸블로그'.freeze
maker.channel.about = '국내의 좋은 블로그 글들을 매일 배달해줍니다.'.freeze
maker.channel.title = channel_title(group)
Parallel.each(feeds, in_threads: 30) do |feed_h|
begin
feed_url = feed_h[:feed_url]
Rails.logger.debug("FEED_URL: #{feed_url}")
feed = Rails.cache.fetch(feed_url, expires_in: cache_expiring_time) do
Rails.logger.debug "cache missed: #{feed_url}"
Timeout::timeout(3) {
xml = HTTParty.get(feed_url).body
Feedjira.parse(xml)
#Feedjira::Feed.fetch_and_parse(feed_url)
}
end
next if feed.nil?
feed.entries.each do |entry|
# Rails.logger.debug "ENTRY: #{entry.inspect}"
if entry.published < now - recent_days || entry.published.localtime > Time.now
next
end
maker.items.new_item do |item|
link_uri = entry.url || entry.entry_id
if link_uri.blank?
Rails.logger.error("ERROR - url shouldn't be null: #{entry.inspect}")
next
end
begin
uri = Addressable::URI.parse(link_uri)
uri.host ||= Addressable::URI.parse(feed_url).host
uri.scheme ||= Addressable::URI.parse(feed_url).scheme
item.link = add_footprint(uri).to_s
Rails.logger.debug item.link
rescue Exception => e
Rails.logger.error("ERROR!: #{item.link} #{e}")
item.link = link_uri
end
item.title = entry.title || '제목 없음'
item.updated = entry.published.localtime
item.summary = entry.content || entry.summary
item.summary = replace_relative_image_url(item.summary, item.link)
item.author = entry.author || feed_h[:author_name] || feed.title
end
end
rescue => e
Rails.logger.error "ERROR: #{e.inspect} #{feed_url}"
next
end
end
maker.channel.updated = maker.items.max_by { |x| x.updated.to_i }&.updated&.localtime || Time.now
end
respond_to do |format|
format.xml { render xml: @rss.to_xml }
format.json
end
end
private
def channel_title(category)
case category
when 'dev'
'개발자 어썸블로그'.freeze
when 'company'
'테크회사 어썸블로그'.freeze
when 'insightful'
'인싸이트가 있는 어썸블로그'.freeze
when 'all'
'어썸블로그'.freeze
else
raise ArgumentError.new
end
end
def cache_expiring_time
if Rails.env.production?
[20, 60, 180].sample.minutes
else
2.minutes
end
end
def replace_relative_image_url(html_string, site_url)
doc = Nokogiri::HTML(html_string)
tags = {
'img' => 'src',
'script' => 'src',
'a' => 'href'
}
base_uri = Addressable::URI.parse(site_url)
doc.search(tags.keys.join(',')).each do |node|
url_param = tags[node.name]
src = node[url_param]
unless src.blank?
begin
uri = Addressable::URI.parse(src)
if uri.host.blank? || uri.scheme.blank?
uri.scheme = base_uri.scheme
uri.host = base_uri.host
node[url_param] = uri.to_s
end
rescue Addressable::URI::InvalidURIError => _e
Rails.logger.debug "ERROR: Uri #{_e.inspect} #{site_url}"
end
end
end
doc.to_html
rescue Exception => e
Rails.logger.error "ERROR: #{e.inspect} #{site_url}"
end
def add_footprint(uri)
previous_h = uri.query_values || {}
uri.query_values = previous_h.merge(
utm_source: footprint_source,
utm_medium: 'blog',
utm_campaign: 'asb',
)
uri
end
def footprint_source
respond_to do |format|
format.xml { return "awesome-blogs.petabytes.org" }
format.json { return "awesome-blogs-app" }
end
end
end |
require 'spec_helper'
describe Navigation do
before do
config.reset
config.path ='spec/fixtures/nav'
end
describe '#initialize' do
let(:nav) { Navigation.new docroot }
it "sets an array of links" do
expect(nav.links).to be_an Array
end
it "sets proper link properties for folders" do
subject = nav.links.first
expect(subject.label).to eq 'Folder'
expect(subject.href).to eq '/Folder'
expect(subject.type).to eq :dir
end
it "sets proper link properties for files" do
subject = nav.links.last
expect(subject.label).to eq 'XFile'
expect(subject.href).to eq '/XFile'
expect(subject.type).to eq :file
end
it "omits _folders" do
result = nav.links.select { |f| f.label[0] == '_' }
expect(result.count).to eq 0
end
it "omits the public folder" do
result = nav.links.select { |f| f.label == 'public' }
expect(result.count).to eq 0
end
context "at docroot" do
it "sets caption to 'Index'" do
expect(nav.caption).to eq "Index"
end
end
context "at deeper folder" do
let(:nav) { Navigation.new "#{docroot}/Folder" }
it "sets a caption" do
expect(nav.caption).to eq 'Folder'
end
end
end
end |
require 'artoo/robot'
class KeyboardRobot < Artoo::Robot
# artoo setup
connection :keyboard, adaptor: :keyboard
device :keyboard, driver: :keyboard, connection: :keyboard
work do
on keyboard, :key => :keypress
end
# class
attr_accessor :handlers
def initialize
@handlers = {}
super
end
def add_handler key, logic
handlers[key] = logic
end
def keypress sender, key
handlers[key].call if handlers.has_key? key
end
end |
class AddResubmittedToApprovalState < ActiveRecord::Migration
def change
add_column :approval_states, :resubmitted, :integer, :default => 0
end
end
|
class OppsNoCustomers < ActiveRecord::Migration
def change
add_column :employee_job_orders, :company_id, :integer
remove_column :employee_job_orders, :customer_id
end
end
|
class RemoveUnnecessaryTagFields < ActiveRecord::Migration
def change
remove_column :tags, :abstract_id
remove_column :tags, :abstract_tag_id
end
end
|
class StreamUser < ActiveRecord::Base
belongs_to :stream_message
belongs_to :user
validates_presence_of :stream_message_id, :user_id
validates_uniqueness_of :stream_message_id, :scope => [:user_id, :source]
scope :followed, where(:source => 'followed')
scope :owned, where(:source => 'owned')
end
|
json.url store_product_url(p)
json.name p.name
json.description p.description
json.qty p.qty
json.price p.price
json.created_at p.created_at
json.updated_at p.updated_at |
require_relative '../config'
class ChangeActiveType < ActiveRecord::Migration
def change
change_column :politician_infos, :active?, :integer
end
end
|
module Mahjong
class Board
include ActiveModel::Model
include ActiveModel::Serialization
attr_accessor :seats, :wall, :wind, :round_number, :bonus_count
delegate :east?, :south?, :west?, :north?, to: :wind
end
end
|
require 'spec_helper'
feature "Gmail" do
let!(:alice) { FactoryGirl.create(:user) }
let!(:me) { FactoryGirl.create(:user, email: "no-reply@willinteractive.com") }
let!(:project) { FactoryGirl.create(:project) }
let!(:issue) { FactoryGirl.create(:issue, project: project, user: me) }
before do
ActionMailer::Base.delivery_method = :smtp
define_permission!(alice, "view", project)
define_permission!(me, "view", project)
end
after do
ActionMailer::Base.delivery_method = :test
end
scenario "Receiving a real-world email" do
sign_in_as!(alice)
visit project_issue_path(project, issue)
fill_in "Comment", :with => "Posting a comment!"
click_button "Add Comment"
expect(page).to have_content("Comment added.")
expect(tracker_emails.count).to eql(1)
email = tracker_emails.first
subject = "[tracker] #{project.name} - #{issue.title}"
expect(email).to have_subject(subject)
clear_tracker_emails!
end
end |
class Santa
attr_reader :ethnicity, :age
attr_accessor :gender, :reindeer_ranking
def initialize(attrs)#I wanted to try instanciation with a hash since I've already done it with a string
@gender = attrs[:gender]
@name = attrs[:name]
@ethnicity = attrs[:ethnicity]
@age = 0
@reindeer_ranking = ["Rudolph", "Dasher", "Dancer", "Prancer", "Vixen", "Comet", "Cupid", "Donner", "Blitzen"]
puts "Initializing Santa instance ..."
puts "Initializing Santa instance: Name is #{@name}, a #{@gender} with a background of #{@ethnicity}"
end
def speak
puts "HO ho ho! Haaaappy Holidays"
end
def eat_milk_and_cookies(cookie)
puts "That was a good #{cookie}"
end
def celebrate_birthday
@age += 1
end
def get_mad_at(reindeer) # take a reindeer's name as an argument,
@reindeer_ranking.delete_at(@reindeer_ranking.index(reindeer)) #get index of entered reindeer.
@reindeer_ranking << reindeer # move that reindeer in last place in the reindeer rankings.
end
def change_gender(identify)
@gender = identify
puts "#{@name} is changing genders..."
puts "#{@name} is now #{@gender}"
end
end
sam = Santa.new(:name =>"Sam", :ethnicity =>"German", :gender => "female")
sam.speak
sam.eat_milk_and_cookies("snickerdoodle")
sam.get_mad_at("Dancer")
sam.change_gender("Ooloi")
exgenders = ["agender", "female", "bigender", "male", "female", "gender fluid", "N/A", "demi", "bi", "onkali"]
exethnicities = ["black", "Latino", "white", "Japanese-African", "prefer not to say", "Mystical Creature (unicorn)", "N/A", "Korean", "Latina", "Parisian"]
names = ["amy", "ted", "sara", "rach", "ed", "bo", "al", "monica", "alisa", "jeff", "sammy"]
10.times do #method to: sample array and turn into a hash key value
santa = Santa.new(:name => names.sample.upcase, :ethnicity => exethnicities.sample, :gender => exgenders.sample)
number = Random.new.rand(140) + 1
number.times {santa.celebrate_birthday}
puts "This is #{santa.age} years old. "
end
|
require 'test_helper'
class RLanguagesControllerTest < ActionController::TestCase
setup do
@r_language = r_languages(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:r_languages)
end
test "should get new" do
get :new
assert_response :success
end
test "should create r_language" do
assert_difference('RLanguage.count') do
post :create, r_language: { language: @r_language.language, properties: @r_language.properties }
end
assert_redirected_to r_language_path(assigns(:r_language))
end
test "should show r_language" do
get :show, id: @r_language
assert_response :success
end
test "should get edit" do
get :edit, id: @r_language
assert_response :success
end
test "should update r_language" do
patch :update, id: @r_language, r_language: { language: @r_language.language, properties: @r_language.properties }
assert_redirected_to r_language_path(assigns(:r_language))
end
test "should destroy r_language" do
assert_difference('RLanguage.count', -1) do
delete :destroy, id: @r_language
end
assert_redirected_to r_languages_path
end
end
|
module MeetupSync
class Venue
attr_accessor :name,
:latitude,
:longitude,
:address,
:city,
:country
def initialize(name, latitude, longitude, address, city, country)
self.name = name
self.latitude = latitude
self.longitude = longitude
self.address = address
self.city = city
self.country = country
end
end
end |
require 'singleton'
module Ginatra
# A singleton class that lets us make and use a constantly updating
# list of repositories.
class RepoList
include Logger
include Singleton
attr_accessor :list
# This creates the list, then does the first refresh to
# populate it.
#
# It returns what refresh returns.
def initialize
self.list = []
self.refresh
end
# The preferred way to access the list publicly.
#
# @return [Array<Ginatra::Repo>] a list of ginatra repos.
def self.list
self.instance.refresh
self.instance.list
end
# searches through the configured directory globs to find all the repositories
# and adds them if they're not already there.
def refresh
list.clear
Ginatra.load_config["git_dirs"].map do |git_dir|
if Dir.exist?(git_dir.chop)
dirs = Dir.glob(git_dir).sort
else
dir = File.expand_path("../../../#{git_dir}", __FILE__)
dirs = Dir.glob(dir).sort
end
dirs = dirs.select {|f| File.directory? f }
dirs.each {|d| add(d) }
end
list
end
# adds a Repo corresponding to the path it found a git repo at in the configured
# globs. Checks to see that it's not there first
#
# @param [String] path the path of the git repo
# @param [String] param the param of the repo if it differs,
# for looking to see if it's already on the list
def add(path, param=File.split(path).last)
unless self.has_repo?(param)
begin
list << Repo.new(path)
rescue Rugged::RepositoryError
logger.warn "SKIPPING '#{path}' - not a git repository"
end
end
list
end
# checks to see if the list contains a repo with a param
# matching the one passed in.
#
# @param [String] local_param param to check.
#
# @return [true, false]
def has_repo?(local_param)
!list.find { |r| r.param == local_param }.nil?
end
# quick way to look up if there is a repo with a given param in the list.
# If not, it refreshes the list and tries again.
#
# @param [String] local_param the param to lookup
#
# @return [Ginatra::Repo] the repository corresponding to that param.
def find(local_param)
if repo = list.find { |r| r.param == local_param }
repo
else
refresh
repo = list.find { |r| r.param == local_param }
raise Ginatra::RepoNotFound if repo.nil?
repo
end
end
# This just brings up the find method to the class scope.
#
# @see Ginatra::RepoList#find
def self.find(local_param)
self.instance.find(local_param)
end
# allows missing methods to cascade to the instance,
def self.method_missing(sym, *args, &block)
instance.send(sym, *args, &block)
end
# updated to correspond to the method_missing definition
def self.respond_to?(sym)
instance.respond_to?(sym) || super
end
end
end
|
class Like < ActiveRecord::Base
belongs_to :user
belongs_to :idea
validates_uniqueness_of :user_id, scope: :idea_id
end
|
class ProductsController < ApplicationController
before_action :authenticate_user!, except: :show
before_action :only_admin, only: :index
before_action :load_category, except: [:index, :show, :destroy]
before_action :load_product, except: [:index, :new, :create]
before_action :allow_destroy, only: :destroy
before_action :load_evaluates, only: :show
load_and_authorize_resource
def index
@search = Product.includes(:category).ransack params[:q]
@products = @search.result.page params[:page]
@products = @products.per_page params[:item].to_i if params[:item].present?
end
def show
@evaluate = Evaluate.new
end
def new
@product = Product.new
end
def edit; end
def create
@product = Product.new product_params
if @product.save
flash[:success] = t ".success"
redirect_to products_path
else
render :new
end
end
def update
if @product.update product_params
flash[:success] = t ".success"
redirect_to products_path
else
flash.now[:danger] = t ".fail"
render :edit
end
end
def destroy
if @product.destroy
flash[:success] = t ".success"
else
flash[:danger] = t ".fail"
end
redirect_to products_path
end
def restore
if @product.restore recursive: true
flash[:success] = t ".restored"
else
flash[:danger] = t ".fail"
end
redirect_to trash_admin_index_path
end
def hard_destroy
if @product.really_destroy!
flash[:success] = t ".deleted"
else
flash[:danger] = t ".fail"
end
redirect_to trash_admin_index_path
end
private
def load_product
@product = Product.with_deleted.find_by id: params[:id]
return if @product
flash[:danger] = t ".not_found"
redirect_to products_path
end
def product_params
params.require(:product).permit :name, :image, :price, :discount,
:sold_many, :description, :category_id, :close_discount_at
end
def allow_destroy
exist_order_item = @product.order_items
return if exist_order_item.empty?
flash[:danger] = t ".fail"
redirect_to products_path
end
def load_evaluates
@evaluates = @product.evaluates.recently.paginate page: params[:page],
per_page: Settings.items
@count_rating = @evaluates.size
@avg_star = @product.evaluates.average(:star).to_f.round(1)
end
end
|
#!/usr/bin/env ruby
#
# ruby-aws-microservice
#
# ./main.rb -h (for usage)
#
# Author: Cody Tubbs (codytubbs@gmail.com) 2017-05-07
# https://github.com/codytubbs
#
############################################################################
# Ruby Syntax attempts to follows strict Ruby Style Guidelines
# rubocop:disable LineLength # Comment to rid length warnings from `rubocop'
# rubocop:disable Metrics/ParameterLists
require 'aws-sdk'
require 'aws-sdk-core'
require 'aws-sdk-resources'
require 'optparse'
require 'base64'
require_relative '00_print_options'
require_relative '01_create_vpc'
require_relative '02_create_subnets'
require_relative '03_create_igw'
require_relative '04_create_rtbl_and_routes'
require_relative '05_create_and_setup_SGs'
require_relative '06_launch_nat_instances'
require_relative '07_create_CLB_and_ALB'
require_relative '08_launchconfig_and_asg'
require_relative '99_vpc_complete_cleanup'
credentials_file = "#{ENV['HOME']}/.aws/credentials"
# Updated as of May 2017
ubuntu_ami_map = Hash['ap-northeast-1' => 'ami-afb09dc8',
'ap-northeast-2' => 'ami-66e33108',
'ap-south-1' => 'ami-c2ee9dad',
'ap-southeast-1' => 'ami-8fcc75ec',
'ap-southeast-2' => 'ami-96666ff5',
'ca-central-1' => 'ami-b3d965d7',
'eu-central-1' => 'ami-060cde69',
'eu-west-1' => 'ami-a8d2d7ce',
'eu-west-2' => 'ami-f1d7c395',
'sa-east-1' => 'ami-4090f22c',
'us-east-1' => 'ami-80861296',
'us-east-2' => 'ami-618fab04',
'us-west-1' => 'ami-2afbde4a',
'us-west-2' => 'ami-efd0428f']
# Updated as of April 2017
region_az_map = Hash['us-east-1' => %w[a b c d e],
'us-east-2' => %w[a b c],
'us-west-1' => %w[b c],
'us-west-2' => %w[a b c],
'ca-central-1' => %w[a b],
'eu-west-1' => %w[a b c],
'eu-central-1' => %w[a b],
'eu-west-2' => %w[a b],
'ap-southeast-1' => %w[a b],
'ap-southeast-2' => %w[a b c],
'ap-northeast-2' => %w[a c],
'ap-northeast-1' => %w[a c],
'ap-south-1' => %w[a b],
'sa-east-1' => %w[a b c]]
response, exec_type = get_opts(credentials_file, ubuntu_ami_map)
creds_profile = response[:creds_profile]
vpc_id = response[:vpc_id]
region = response[:region]
# lb_type = response[:lb_type]
# nat_type = response[:nat_type]
# bastion_host = response[:bastion_host]
# ssh_access = response[:ssh_access]
ami = ubuntu_ami_map[region]
instance_type = 't2.micro' # Free tier suffices for this exercise
availability_zones = [region_az_map[region][0], region_az_map[region][1]]
az1 = region + region_az_map[region][0]
az2 = region + region_az_map[region][1]
creds = Aws::SharedCredentials.new(profile_name: creds_profile)
ec2 = Aws::EC2::Client.new(credentials: creds, region: region)
asg = Aws::AutoScaling::Client.new(credentials: creds, region: region)
elbv1 = Aws::ElasticLoadBalancing::Client.new(credentials: creds, region: region)
elbv2 = Aws::ElasticLoadBalancingV2::Client.new(credentials: creds, region: region)
if exec_type == 'launch'
# Create new, empty VPC
vpc = create_vpc(ec2)
# Create private and public subnets and receive the IDs
pub_net1, pub_net2, priv_net1, priv_net2 = create_subnets(ec2, region, availability_zones, vpc)
# Create the Internet Gateway and receive the ID
igw_id = create_igw(ec2, vpc)
# Create the private and public route tables, create proper routes and receive the private tbl ID
priv_rtbl_id = create_rtbl_and_routes(ec2, vpc, igw_id, pub_net1, pub_net2, priv_net1, priv_net2)
# Create and receive security groups for webservers, nat instances and load balancers
sg80_priv, sg22_priv, sg22_pub, sg80_nat, sg80_lb = create_and_setup_SGs(ec2, vpc)
# Launch nat instances in both AZs for private subnet webservers to use for bootstrapping/updates
launch_nat_instances(ec2, pub_net1, pub_net2, sg22_pub, sg80_nat, priv_rtbl_id, instance_type, ami)
# Create Classic Load Balancer and define listener and receive the dns name
clb_dns_name = createCLB(elbv1, sg80_lb, pub_net1, pub_net2)
# Create Application Load Balancer, listener, and target groups
# Receive dns name. Also receive the target group arn for building the ASG
alb_dns_name, alb_target_group_arn = createALB(elbv2, vpc, sg80_lb, pub_net1, pub_net2)
# Create launch configuration for nginx service
launch_configuration(asg, sg80_priv, sg22_priv, instance_type, ami)
# Create auto scaling group for nginx service
autoscalinggroup(asg, az1, az2, priv_net1, priv_net2, alb_target_group_arn)
puts "VPC: #{vpc}"
puts "\n\n\nPlease wait ~3 minutes for the nginx service to become active.\n"
puts "Application LoadBalancer DNS: #{alb_dns_name}"
puts " Classic LoadBalancer DNS: #{clb_dns_name}"
puts
end
if exec_type == 'cleanup'
cleanup(vpc_id, ec2, asg, elbv1, elbv2, region)
end
exit 0
|
class RemoveStateFromSipAccount < ActiveRecord::Migration
def up
remove_column :sip_accounts, :state
end
def down
add_column :sip_accounts, :state, :string
end
end
|
class Certificate < ApplicationRecord
belongs_to :user
validates :name, presence: true, length: {maximum: Settings.certificate.maximum}
validates :majors, presence: true, length: {maximum: Settings.certificate.maximum}
validates :organization, presence: true, length: {maximum: Settings.certificate.maximum}
validates :classification, length: {maximum: Settings.certificate.maximum}
validates :received_time, presence: true
end
|
require 'spec_helper'
describe BaseProtectedService do
let(:endpoint_url) { 'http://endpoint.com' }
let(:user) { 'foo_user' }
let(:password) { 'bar_password' }
let(:ca_cert) { 'cacertificate' }
subject do
Class.new(described_class) do
def connection_tester
with_ssl_connection do |connection|
yield connection if block_given?
connection
end
end
def request_tester
with_ssl_connection do |connection|
connection.get '/foo'
end
end
end.new(endpoint_url: endpoint_url, user: user, password: password, ca_cert: ca_cert)
end
describe '#with_ssl_connection' do
context 'configuring ssl' do
it 'sets-up the CA certificate with the correct contents' do
subject.connection_tester do |connection|
expect(File.read(connection.ssl[:ca_file])).to eq ca_cert
end
end
it 'cleans-up the certificate file' do
connection = subject.connection_tester
expect(File.exist?(connection.ssl[:ca_file])).to be_falsey
end
it 'verifies the server SSL certificate' do
connection = subject.connection_tester
expect(connection.ssl[:verify]).to be_truthy
end
end
context 'when sending a request' do
let(:response_body) { '{ "message": "authenticated" }' }
before do
endpoint_host = URI.parse(endpoint_url).host
stub_request(:get, "#{user}:#{password}@#{endpoint_host}/foo")
.to_return(body: response_body, status: 200)
end
it 'sends an authenticated request to the proper endpoint' do
response = subject.request_tester
expect(response.body).to eq(JSON.parse(response_body))
end
end
end
end
|
require 'test_helper'
class ArticleTest < ActiveSupport::TestCase
def setup
@article = Article.new(title: "title", text: "text content")
end
test "title should be present" do
@article.title = ""
assert_not @article.valid?
end
test "text should be present" do
@article.text = " "
assert_not @article.valid?
end
end
|
require 'test_helper'
class LabsControllerTest < ActionDispatch::IntegrationTest
setup do
@lab = labs(:one)
end
test "should get index" do
get labs_url
assert_response :success
end
test "should get new" do
get new_lab_url
assert_response :success
end
test "should create lab" do
assert_difference('Lab.count') do
post labs_url, params: { lab: { about_us: @lab.about_us, access: @lab.access, address: @lab.address, email: @lab.email, facility: @lab.facility, fax: @lab.fax, lat: @lab.lat, lon: @lab.lon, majar: @lab.majar, message: @lab.message, name: @lab.name, purpose: @lab.purpose, tel: @lab.tel } }
end
assert_redirected_to lab_url(Lab.last)
end
test "should show lab" do
get lab_url(@lab)
assert_response :success
end
test "should get edit" do
get edit_lab_url(@lab)
assert_response :success
end
test "should update lab" do
patch lab_url(@lab), params: { lab: { about_us: @lab.about_us, access: @lab.access, address: @lab.address, email: @lab.email, facility: @lab.facility, fax: @lab.fax, lat: @lab.lat, lon: @lab.lon, majar: @lab.majar, message: @lab.message, name: @lab.name, purpose: @lab.purpose, tel: @lab.tel } }
assert_redirected_to lab_url(@lab)
end
test "should destroy lab" do
assert_difference('Lab.count', -1) do
delete lab_url(@lab)
end
assert_redirected_to labs_url
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.