text stringlengths 10 2.61M |
|---|
require 'json'
module Gateway
class Result
include Errors
def handle_query_result(response)
if(response.status.to_i == 200)
result = JSON.parse(response.body)
if result["Fault"]
error_message = ""
result["Fault"]["Error"].each{|error|
error_message = "#{error["Message"]}. #{error["Detail"]}"
}
raise GatewayError, error_message
end
return result["QueryResponse"] if result["QueryResponse"]
return result
else
raise GatewayError, response.body
end
end
end
end |
class CompaniesController < CompanyController
before_action :set_company, only: [:show, :edit, :update, :destroy]
# GET /companies
def index
if !current_user.gces? && current_user.owned_company.present?
redirect_to company_path(current_user.owned_company)
end
@companies = policy_scope(Company.all)
end
# GET /companies/1
def show
end
# GET /companies/new
def new
@company = Company.new
@company.build_owner
authorize @company
end
# GET /companies/1/edit
def edit
end
# POST /companies
def create
@company = Company.new(company_create_params)
authorize @company
if @company.save
redirect_to @company, notice: t('controllers.company.create.success')
else
render :new
end
end
# PATCH/PUT /companies/1
def update
if @company.update(company_update_params)
redirect_to @company, notice: t('controllers.company.update.success')
else
render :edit
end
end
# DELETE /companies/1
def destroy
@company.destroy
redirect_to companies_url, notice: t('controllers.company.destroy.success')
end
private
# Use callbacks to share common setup or constraints between actions.
def set_company
@company = Company.find(params[:id])
authorize @company
end
# Only allow a trusted parameter "white list" through.
def company_create_params
params.require(:company).permit(:company_name, owner_attributes: [:first_name, :last_name,
:email])
end
def company_update_params
params.require(:company).permit(:company_name, :owner_id)
end
end
|
# frozen_string_literal: true
# Released under the MIT License.
# Copyright, 2019-2022, by Samuel Williams.
module MyModule
extend Console
def self.argument_error
raise ArgumentError, "It broken!"
end
def self.nested_error
argument_error
rescue
raise RuntimeError, "Magic smoke escaped!"
end
def self.log_error
self.nested_error
rescue
logger.error(self, $!)
end
def self.test_logger
logger.debug "1: GOTO LINE 2", "2: GOTO LINE 1"
logger.info "Dear maintainer:" do |buffer|
buffer.puts "Once you are done trying to 'optimize' this routine, and have realized what a terrible mistake that was, please increment the following counter as a warning to the next guy:"
buffer.puts "total_hours_wasted_here = 42"
end
logger.warn "Something didn't work as expected!"
logger.error "There be the dragons!", (raise RuntimeError, "Bits have been rotated incorrectly!" rescue $!)
logger.info(self) {Console::Shell.for({LDFLAGS: "-lm"}, "gcc", "-o", "stuff.o", "stuff.c", chdir: "/tmp/compile")}
logger.info(Object.new) {"Where would we be without Object.new?"}
end
# test_logger
end
|
# Generated via
# `rails generate hyrax:work Dataset`
require File.expand_path('../../scholar/scholar_work_form.rb', __FILE__)
module Hyrax
# Generated form for Dataset
class DatasetForm < Scholar::GeneralWorkForm
self.model_class = ::Dataset
# subtract self.terms
self.terms -= [:conference_location,:conference_name,:event_date,:has_journal,:has_number,:has_volume,:issn]
self.required_fields = [:title, :creator,:academic_affiliation, :resource_type, :rights_statement]
end
end |
require_relative '../spec/spec_helper.rb'
require_relative './reverse_integer.rb'
describe 'reverse_integer' do
test = Solution.new
it "takes a positive integer and reverses its digits" do
expect(test.reverse(123)).to eq(321), "expected 321"
end
it "takes a negative integer and reverses its digits" do
expect(test.reverse(-123)).to eq(-321)
end
it "properly removes zeroes" do
expect(test.reverse(120)).to eq(21)
end
it "properly reverses 0" do
expect(test.reverse(0)).to eq(0)
end
end
|
require 'helper'
class Asset
include MongoMapper::Document
plugin Joint
key :title, String
attachment :image
attachment :file
end
class BaseModel
include MongoMapper::Document
plugin Joint
attachment :file
end
class Image < BaseModel; attachment :image end
class Video < BaseModel; attachment :video end
module JointTestHelpers
def all_files
[@file, @image, @image2, @test1, @test2]
end
def rewind_files
all_files.each { |file| file.rewind }
end
def open_file(name)
File.open(File.join(File.dirname(__FILE__), 'fixtures', name), 'r')
end
def grid
@grid ||= Mongo::Grid.new(MongoMapper.database)
end
def key_names
[:id, :name, :type, :size]
end
end
class JointTest < Test::Unit::TestCase
include JointTestHelpers
def setup
super
@file = open_file('unixref.pdf')
@image = open_file('mr_t.jpg')
@image2 = open_file('harmony.png')
@test1 = open_file('test1.txt')
@test2 = open_file('test2.txt')
end
def teardown
all_files.each { |file| file.close }
end
context "Using Joint plugin" do
should "add each attachment to attachment_names" do
Asset.attachment_names.should == Set.new([:image, :file])
end
should "add keys for each attachment" do
key_names.each do |key|
Asset.keys.should include("image_#{key}")
Asset.keys.should include("file_#{key}")
end
end
context "with inheritance" do
should "add attachment to attachment_names" do
BaseModel.attachment_names.should == Set.new([:file])
end
should "inherit attachments from superclass, but not share other inherited class attachments" do
Image.attachment_names.should == Set.new([:file, :image])
Video.attachment_names.should == Set.new([:file, :video])
end
should "add inherit keys from superclass" do
key_names.each do |key|
BaseModel.keys.should include("file_#{key}")
Image.keys.should include("file_#{key}")
Image.keys.should include("image_#{key}")
Video.keys.should include("file_#{key}")
Video.keys.should include("video_#{key}")
end
end
end
end
context "Assigning new attachments to document" do
setup do
@doc = Asset.create(:image => @image, :file => @file)
rewind_files
end
subject { @doc }
should "assign GridFS content_type" do
grid.get(subject.image_id).content_type.should == 'image/jpeg'
grid.get(subject.file_id).content_type.should == 'application/pdf'
end
should "assign joint keys" do
subject.image_size.should == 13661
subject.file_size.should == 68926
subject.image_type.should == "image/jpeg"
subject.file_type.should == "application/pdf"
subject.image_id.should_not be_nil
subject.file_id.should_not be_nil
subject.image_id.should be_instance_of(BSON::ObjectID)
subject.file_id.should be_instance_of(BSON::ObjectID)
end
should "allow accessing keys through attachment proxy" do
subject.image.size.should == 13661
subject.file.size.should == 68926
subject.image.type.should == "image/jpeg"
subject.file.type.should == "application/pdf"
subject.image.id.should_not be_nil
subject.file.id.should_not be_nil
subject.image.id.should be_instance_of(BSON::ObjectID)
subject.file.id.should be_instance_of(BSON::ObjectID)
end
should "proxy unknown methods to GridIO object" do
subject.image.files_id.should == subject.image_id
subject.image.content_type.should == 'image/jpeg'
subject.image.filename.should == 'mr_t.jpg'
subject.image.file_length.should == 13661
end
should "assign file name from path if original file name not available" do
subject.image_name.should == 'mr_t.jpg'
subject.file_name.should == 'unixref.pdf'
end
should "save attachment contents correctly" do
subject.file.read.should == @file.read
subject.image.read.should == @image.read
end
should "know that attachment exists" do
subject.image?.should be(true)
subject.file?.should be(true)
end
should "respond with false when asked if the attachment is nil?" do
subject.image.nil?.should be(false)
subject.file.nil?.should be(false)
end
should "clear assigned attachments so they don't get uploaded twice" do
Mongo::Grid.any_instance.expects(:put).never
subject.save
end
end
context "Updating existing attachment" do
setup do
@doc = Asset.create(:file => @test1)
assert_no_grid_difference do
@doc.file = @test2
@doc.save!
end
rewind_files
end
subject { @doc }
should "not change attachment id" do
subject.file_id_changed?.should be(false)
end
should "update keys" do
subject.file_name.should == 'test2.txt'
subject.file_type.should == "text/plain"
subject.file_size.should == 5
end
should "update GridFS" do
grid.get(subject.file_id).filename.should == 'test2.txt'
grid.get(subject.file_id).content_type.should == 'text/plain'
grid.get(subject.file_id).file_length.should == 5
grid.get(subject.file_id).read.should == @test2.read
end
end
context "Updating document but not attachments" do
setup do
@doc = Asset.create(:image => @image)
@doc.update_attributes(:title => 'Updated')
@doc.reload
rewind_files
end
subject { @doc }
should "not affect attachment" do
subject.image.read.should == @image.read
end
should "update document attributes" do
subject.title.should == 'Updated'
end
end
context "Assigning file where file pointer is not at beginning" do
setup do
@image.read
@doc = Asset.create(:image => @image)
@doc.reload
rewind_files
end
subject { @doc }
should "rewind and correctly store contents" do
subject.image.read.should == @image.read
end
end
context "Setting attachment to nil" do
setup do
@doc = Asset.create(:image => @image)
rewind_files
end
subject { @doc }
should "delete attachment after save" do
assert_no_grid_difference { subject.image = nil }
assert_grid_difference(-1) { subject.save }
end
should "know that the attachment has been nullified" do
subject.image = nil
subject.image?.should be(false)
end
should "respond with true when asked if the attachment is nil?" do
subject.image = nil
subject.image.nil?.should be(true)
end
should "clear nil attachments after save and not attempt to delete again" do
Mongo::Grid.any_instance.expects(:delete).once
subject.image = nil
subject.save
Mongo::Grid.any_instance.expects(:delete).never
subject.save
end
should "clear id, name, type, size" do
subject.image = nil
subject.save
assert_nil subject.image_id
assert_nil subject.image_name
assert_nil subject.image_type
assert_nil subject.image_size
subject.reload
assert_nil subject.image_id
assert_nil subject.image_name
assert_nil subject.image_type
assert_nil subject.image_size
end
end
context "Retrieving attachment that does not exist" do
setup do
@doc = Asset.create
rewind_files
end
subject { @doc }
should "know that the attachment is not present" do
subject.image?.should be(false)
end
should "respond with true when asked if the attachment is nil?" do
subject.image.nil?.should be(true)
end
should "raise Mongo::GridFileNotFound" do
assert_raises(Mongo::GridFileNotFound) { subject.image.read }
end
end
context "Destroying a document" do
setup do
@doc = Asset.create(:image => @image)
rewind_files
end
subject { @doc }
should "remove files from grid fs as well" do
assert_grid_difference(-1) { subject.destroy }
end
end
context "Assigning file name" do
should "default to path" do
Asset.create(:image => @image).image.name.should == 'mr_t.jpg'
end
should "use original_filename if available" do
def @image.original_filename
'testing.txt'
end
doc = Asset.create(:image => @image)
assert_equal 'testing.txt', doc.image_name
end
end
context "Validating attachment presence" do
setup do
@model_class = Class.new do
include MongoMapper::Document
plugin Joint
attachment :file, :required => true
end
end
should "work" do
model = @model_class.new
model.should_not be_valid
model.file = @file
model.should be_valid
model.file = nil
model.should_not be_valid
model.file = @image
model.should be_valid
end
end
end |
require 'rspec'
require_relative '../circular_linked_list'
RSpec.describe CircularLinkedList do
def n_item_list(n)
list = CircularLinkedList.new
for i in 1..n do
list.insert(i)
end
list
end
context 'initialization' do
it 'is initialized with length 0' do
list = CircularLinkedList.new
expect(list.length).to eq(0)
end
it 'is initialized with head nil' do
list = CircularLinkedList.new
expect(list.head).to be(nil)
end
it 'is initialized with current nil' do
list = CircularLinkedList.new
expect(list.current).to be(nil)
end
end
context 'insert' do
it 'allows a new node to become the head and head.next values of an empty list' do
list = n_item_list(1)
expect(list.head).to have_attributes(data: 1, next: list.head)
end
it 'allows new nodes to be added to the "end" of the circle' do
list = n_item_list(2)
expect(list.last_node).to have_attributes(data: 2, next: list.head)
end
it 'increases length correctly as the list grows' do
list = n_item_list(2)
expect(list.length).to eq(2)
end
end
context 'delete' do
it 'deletes body nodes' do
list = n_item_list(2)
list.delete(list.head.next)
expect(list.length).to eq(1)
end
it 'deletes head node' do
list = n_item_list(2)
original_tail = list.last_node
list.delete(list.head)
expect(list.head).to eq(original_tail)
end
it 'correctly connects previous node to next node on deletion' do
list = CircularLinkedList.new
node1 = list.insert(1)
node2 = list.insert(2)
node3 = list.insert(3)
list.delete(node2)
expect(node1.next).to eq(node3)
end
end
context 'concat' do
it 'concatenates two linked lists' do
list = n_item_list(2)
list.concat(n_item_list(3))
expect(list.length).to eq(5)
end
it 'joins the second list between the last node and the head of the receiver' do
list1 = n_item_list(2)
original_list1_tail = list1.last_node
list2 = n_item_list(2)
original_list2_head = list2.head
original_list2_tail = list2.last_node
list1.concat(list2)
expect(original_list1_tail.next).to eq(original_list2_head)
expect(original_list2_tail.next).to eq(list1.head)
end
it 'raises an ArgumentError if the argument is not a CircularLinkedList' do
list = n_item_list(2)
expect { list.concat(1) }.to raise_error(ArgumentError)
end
end
context 'clear' do
it 'deletes all nodes from the list' do
list = n_item_list(10)
list.clear
expect(list.length).to eq(0)
end
end
context 'find' do
it 'returns a node for which the block evaluates to true' do
list = n_item_list(2)
expect(list.find { |node| node.data == 2 }).to eq(list.last_node)
end
it 'returns the first node for which the block evaluates to true' do
list = CircularLinkedList.new
2.times { list.insert(1) }
expect(list.find { |node| node.data == 1}).to eq(list.head)
end
it 'returns nil if a matching node is not found' do
list = n_item_list(5)
expect(list.find { |node| node.data == 6 }).to be(nil)
end
it 'raises a LocalJumpError if no block is given' do
list = n_item_list(2)
expect { list.find }.to raise_error(LocalJumpError)
end
end
context 'each' do
it 'iterates over each node in the list' do
list = n_item_list(5)
tracker = []
list.each { |node| tracker << node.data }
expect(tracker).to eq([1, 2, 3, 4, 5])
end
it 'raises a LocalJumpError if no block is given' do
list = n_item_list(1)
expect { list.each }.to raise_error(LocalJumpError)
end
end
context 'to_a' do
it 'returns the list\'s values in an array' do
list = n_item_list(3)
expect(list.to_a).to eq([1, 2, 3])
end
end
context 'map' do
it 'returns a copy of the list if no block is given' do
list1 = n_item_list(3)
list2 = list1.map
expect(list2.to_a).to eq(list1.to_a)
expect(list2).not_to eq(list1)
end
it 'returns a new list derived from the receiver and the given block' do
list1 = n_item_list(3)
list2 = list1.map { |value| value * 2 }
expect(list2.to_a).to eq([2, 4, 6])
end
end
end |
class UsersController < ApplicationController
before_action :admin_user, only: :destroy
before_action :authenticate_user!, only: %i[show index]
#
# @param [Array]
#
#
#
#
def show
@user = User.find(params[:id])
@feed = @user.microposts.page(params[:page])
@liking_posts = @user.like_microposts.page(params[:page])
@user_post = Micropost.where(user_id: @user.id,exif_is_valid: true).where.not(latitude: nil).or \
(Micropost.where(user_id: @user.id).where.not(address: nil).where.not(latitude: nil))
@post_json_data = @user_post.to_json(only: %i[id title picture latitude longitude])
@following_users = @user.following.page(params[:page])
@followers = @user.followers.page(params[:page])
# jsリクエストで通過
return unless request.xhr?
# renderするファイルの振り分け
case params[:type]
when 'post_list', 'follower_list', 'following_list', 'liking_list'
render "shared/#{params[:type]}"
end
end
def destroy
User.find(params[:id]).destroy
redirect_to current_user
end
def index
# jsリクエストで通過
return unless request.xhr?
case params[:type]
when 'user_list'
render "shared/#{params[:type]}"
end
end
private
def admin_user
redirect_to(root_path) unless current_user.admin?
end
end
|
class ReviewsController < ApplicationController
def show
@movie = Movie.find(params[:movie_id])
@review = @movie.reviews.find(params[:id])
end
def new
@movie = Movie.find(params[:movie_id])
@review = @movie.reviews.new
end
def create
@movie = Movie.find(params[:movie_id])
@reviews = @movie.reviews
@review = @movie.reviews.new(reviews_params)
@review.save
flash[:notice] = "Successfully added"
respond_to do |format|
format.html { redirect_to movie_path(@movie), notice: "Successfully added"}
format.js
end
end
def destroy
@movie = Movie.find(params[:movie_id])
@reviews = Review.find(params[:id])
@reviews.destroy
flash[:notice] = "Successfully deleted"
respond_to do |format|
format.html { redirect_to movies_path(@movie), notice: "Successfully deleted"}
format.js
end
end
private
def reviews_params
params.require(:review).permit(:author, :text, :rating)
end
end
|
require 'rails_helper'
RSpec.describe HomeController, type: :controller do
describe "GET about" do
it "renders about template" do
get :about
expect(response).to render_template("about")
end
end
describe "GET faq" do
it "renders faq template" do
get :faq
expect(response).to render_template("faq")
end
end
describe "GET contact" do
it "renders contact template" do
get :contact
expect(response).to render_template("contact")
end
end
end
|
class SwfAsset < ActiveRecord::Base
attr_accessible :swf_asset_content_type, :swf_asset_file_name, :swf_asset_file_size, :swf_asset_updated_at, :si_swf_id, :swf_asset
belongs_to :si_swf
has_attached_file :swf_asset,
:styles => { :large => "640x480", :medium => "300x300>", :thumb => "100x100>" },
:storage => :s3,
:s3_credentials => "#{Rails.root}/config/s3.yml",
:path => "swf/:style/:id/:filename"
before_post_process :is_image?
def is_image?
!(swf_asset_content_type =~ /^image/).nil?
end
end |
require 'swagger_helper'
describe 'Auth API' do
# Create a user
let(:user) {create(:user)}
path '/auth/login' do
post 'Login' do
tags 'Auth'
consumes 'application/json'
parameter name: :body, in: :body, schema: {
type: :object,
properties: {
email: {type: :string},
password: {type: :string}
},
required: ['email', 'password']
}
response '200', 'Successful login' do
let(:body) {{email: user.email, password: user.password}}
run_test!
end
response '401', 'Invalid credentials' do
let (:body) {{email: Faker::Internet.email, password: Faker::Internet.password}}
run_test!
end
end
end
end |
require 'codily/elements/service_belongging_base'
require 'codily/elements/condition'
require 'codily/elements/file_loadable'
module Codily
module Elements
class ResponseObject < ServiceBelonggingBase
include FileLoadable
def_attr *%i(
content_type
status
response
cache_condtiion
request_condition
)
defaults(
content: "",
content_type: "",
response: "",
)
def setup
delete_if_empty! *%i(
content
content_type
response
cache_condition
request_condition
)
force_integer! *%i(
status
)
end
def content(obj = nil)
getset :content, file_loadable(obj)
end
def cache_condition(name = nil, &block)
set_refer_element(:cache_condition, Condition, {name: name, type: 'CACHE', _service_name: self.service_name}, &block)
end
def request_condition(name = nil, &block)
set_refer_element(:request_condition, Condition, {name: name, type: 'REQUEST', _service_name: self.service_name}, &block)
end
def fastly_class
Fastly::ResponseObject
end
end
end
end
|
# oop_rps_design_choice_1.rb
# game flow:
# 1. the user makes a choice
# 2. the computer makes a choice
# 3. the winner is displayed
# The Classical appraoch to object oriented programming is:
# 1. Write a textual description of the problem or exercise
# 2. Extract the major nouns and verbs from the description.
# 3. Organize and associate the verbs with the nouns.
# 4. The nouns are the classes and the verbs are the behaviors or methods
# Rock, Paper, Scissors is a two-player game where each player chooses one of three
# possible moves: rock, paper, or scissors. The chosen moves will then be compared
# to see who wins, according to the following rules:
# - rock beats scissors
# - scissors beats paper
# - paper beats rock
# If the players chose the same move, then it's a tie.
# Nouns: player, move, rule
# verbs: choose, compare
# player - choose
# move
# rule
# - compare
# first attempt at outline
# class Player
# def initialize
# # maybe a "name"? what about a "move"
# end
# def choose
# end
# end
# class Move
# def initialize
# # seems like we need something to keep track
# # of the choice... a move object can be "papr", "rock", or "scissors"
# end
# end
# class Rule
# def initialize
# end
# end
# def compare(move1, move2)
# end
# # Game Orchestration Engine
# class RPSGame
# def initialize
# @human = Player.new
# @computer = Player.new
# end
# def play
# display_welcome_message
# human_choose_move
# computer_choose_move
# display_winner
# display_goodbye_message
# end
# end
# RPSGame.new.play
# player class
class Player
attr_accessor :move, :name
def initialize
set_name
end
end
# human_player
class Human < Player
def set_name
n = ""
loop do
puts "What's your name?"
n = gets.chomp
break unless n.empty?
puts "Sorry, must enter a value."
end
self.name = n
end
def choose
choice = nil
loop do
puts "Please choose rock, paper, or scissors:"
choice = gets.chomp
break if ['rock', 'paper', 'scissors'].include? choice
puts "Sorry, invalid choice."
end
self.move = choice
end
end
# computer_player
class Computer < Player
def set_name
self.name = ['bobby', 'jim', 'Darth Vader'].sample
end
def choose
self.move = ['rock', 'paper', 'scissors'].sample
end
end
# Game Orchestration Engine
class RPSGame
attr_accessor :human, :computer
def initialize
@human = Human.new
@computer = Computer.new
end
def display_welcome_message
puts "Welcome to Rock, Paper, Scissors!"
end
def display_goodbye_message
puts "Thanks for playing Rock, Paper, Scissors. Good Bye!"
end
def display_winner
puts "#{human.name} chose #{human.move}."
puts "#{computer.name} chose #{computer.move}."
case human.move
when 'rock'
puts "It's a tie!" if computer.move == 'rock'
puts "#{human.name} won!" if computer.move == 'scissors'
puts "#{computer.name} won!" if computer.move == 'paper'
when 'paper'
puts "It's a tie!" if computer.move == 'paper'
puts "#{human.name} won!" if computer.move == 'rock'
puts "#{computer.name} won!" if computer.move == 'scissors'
when 'scissors'
puts "It's a tie!" if computer.move == 'scissors'
puts "#{human.name} won!" if computer.move == 'paper'
puts "#{computer.name} won!" if computer.move == 'rock'
end
end
def play_again?
answer = nil
loop do
puts "Would you like to play again? (y/n)"
answer = gets.chomp
break if ['y', 'n'].include? answer.downcase
puts "Sorry, must be y or n."
end
return true if answer == 'y'
return false
end
def play
display_welcome_message
loop do
human.choose
computer.choose
display_winner
break unless play_again?
end
display_goodbye_message
end
end
RPSGame.new.play
|
class CreateClassis < ActiveRecord::Migration
def change
create_table :classis do |t|
t.date :dateof
t.time :timeof
t.references :group
t.timestamps
end
end
end
|
require 'spec_helper'
require 'harvest/domain' # Because the aggregate roots store EventTypes in Harvest::Domain::Events
require 'harvest/event_handlers/read_models/fishing_business_statistics'
module Harvest
module EventHandlers
module ReadModels
describe FishingBusinessStatistics do
let(:database) {
double(
"ReadModelDatabase",
save: nil,
delete: nil,
update: nil,
records: [
{ uuid: :uuid_1, data: "data 1a" },
{ uuid: :uuid_1, data: "data 1b" },
{ uuid: :uuid_2, data: "data 2a" }
],
count: 3
)
}
let(:event_bus) { Realm::Messaging::Bus::SimpleMessageBus.new }
subject(:view) { FishingBusinessStatistics.new(database) }
before(:each) do
event_bus.register(:unhandled_event, Realm::Messaging::Bus::UnhandledMessageSentinel.new)
end
describe "#handle_new_fishing_business_opened" do
before(:each) do
event_bus.register(:new_fishing_business_opened, view)
end
it "saves the view info" do
event_bus.publish(
Domain::Events.build(
:new_fishing_business_opened,
uuid: :fishing_ground_uuid,
fishing_business_uuid: :fishing_business_uuid,
fishing_business_name: "Fishing Company Ltd"
)
)
expect(database).to have_received(:save).with(
fishing_ground_uuid: :fishing_ground_uuid,
fishing_business_uuid: :fishing_business_uuid,
lifetime_fish_caught: 0,
lifetime_profit: Harvest::Domain::Currency.dollar(0)
)
end
end
describe "#handle_fishing_order_fulfilled" do
before(:each) do
event_bus.register(:fishing_order_fulfilled, view)
end
before(:each) do
database.stub(
records: [
{
fishing_ground_uuid: :fishing_ground_uuid,
fishing_business_uuid: :fishing_business_uuid,
lifetime_fish_caught: 3,
lifetime_profit: Harvest::Domain::Currency.dollar(15)
},
{
fishing_ground_uuid: :fishing_ground_uuid,
fishing_business_uuid: :wrong_business_uuid,
lifetime_fish_caught: 10,
lifetime_profit: Harvest::Domain::Currency.dollar(50)
},
{
fishing_ground_uuid: :wrong_fishing_ground_uuid,
fishing_business_uuid: :fishing_business_uuid,
lifetime_fish_caught: 0,
lifetime_profit: Harvest::Domain::Currency.dollar(0)
}
]
)
end
it "updates the view info" do
event_bus.publish(
Domain::Events.build(
:fishing_order_fulfilled,
uuid: :fishing_ground_uuid,
fishing_business_uuid: :fishing_business_uuid,
number_of_fish_caught: 5
)
)
expect(database).to have_received(:update).with(
[:fishing_ground_uuid, :fishing_business_uuid],
fishing_ground_uuid: :fishing_ground_uuid,
fishing_business_uuid: :fishing_business_uuid,
lifetime_fish_caught: 8,
lifetime_profit: Harvest::Domain::Currency.dollar(40)
)
end
end
describe "#count" do
it "is the number of records in the database" do
expect(view.count).to be == 3
end
end
describe "#records" do
it "is the database records" do
expect(view.records).to be == [
{ uuid: :uuid_1, data: "data 1a" },
{ uuid: :uuid_1, data: "data 1b" },
{ uuid: :uuid_2, data: "data 2a" }
]
end
end
describe "querying" do
before(:each) do
database.stub(
records: [
{ uuid: :uuid_1, data: "data a", extra: "extra data" },
{ uuid: :uuid_1, data: "data b", extra: "extra data" },
{ uuid: :uuid_2, data: "data b", extra: "extra data" }
]
)
end
describe "#record_for" do
it "returns the record for the query" do
expect(
view.record_for(uuid: :uuid_1, data: "data b")
).to be == { uuid: :uuid_1, data: "data b", extra: "extra data" }
end
it "returns only the first record" do
expect(
view.record_for(data: "data b")
).to be == { uuid: :uuid_1, data: "data b", extra: "extra data" }
end
end
describe "#records_for" do
it "returns all the records for the query" do
expect(
view.records_for(uuid: :uuid_1)
).to be == [
{ uuid: :uuid_1, data: "data a", extra: "extra data" },
{ uuid: :uuid_1, data: "data b", extra: "extra data" }
]
end
end
end
end
end
end
end |
# Write a method that binary searches an array for a target and returns its
# index if found. Assume a sorted array.
# NB: YOU MUST WRITE THIS RECURSIVELY (searching half of the array every time).
# We will not give you points if you visit every element in the array every time
# you search.
# For example, given the array [1, 2, 3, 4], you should NOT be checking
# 1 first, then 2, then 3, then 4.
def binary_search(arr, target)
return nil if arr.length == 0
pivot = arr.size / 2
case arr[pivot] <=> target
when 0
return pivot
when 1
return binary_search(arr.take(pivot), target)
else
search = binary_search(arr.drop(pivot + 1), target)
search.nil? ? nil : pivot + 1 + search
end
end
class Array
# Write a new `Array#pair_sum(target)` method that finds all pairs of
# positions where the elements at those positions sum to the target.
# NB: ordering matters. I want each of the pairs to be sorted
# smaller index before bigger index. I want the array of pairs to be
# sorted "dictionary-wise":
# [0, 2] before [1, 2] (smaller first elements come first)
# [0, 1] before [0, 2] (then smaller second elements come first)
def pair_sum(target = 0)
ans = []
self.each_with_index do |ele, idx|
self.each_with_index do |ele2, idx2|
if idx2 > idx && ele + ele2 == target
ans << [idx, idx2]
end
end
end
ans
end
end
# Write a method called 'sum_rec' that
# recursively calculates the sum of an array of values
def sum_rec(nums)
return 0 if nums.empty?
return nums[0] if nums.length < 2
nums[0] + sum_rec(nums[1..-1])
end
class String
# Write a method that finds all the unique substrings for a word
def uniq_subs
ans = []
(0...self.length).each do |i|
(0...self.length).each do |j|
if j >= i
subs = self[i..j]
ans << subs if !ans.include?(subs)
end
end
end
ans
end
end
#"s", "st", "str", "", "t", "tr", "r"]
# 00 01 02 10
def prime?(num)
return true if num == 2
(num-1).downto(2).each do |i|
return false if num % i == 0
end
true
end
# Write a method that sums the first n prime numbers starting with 2.
def sum_n_primes(n)
return 0 if n == 0
return 2 if n == 1
sum = 0
i = 2
count = n #2
while count >= 1
if prime?(i)
count -= 1
sum += i
end
i += 1
end
sum
end
#3
class Array
# Write a method that calls a passed block for each element of the array
def my_each(&prc)
i = 0
while i < self.length
prc.call(self[i])
i += 1
end
self
end
end
class Array
# Write a method that calls a block for each element of the array
# and returns a new array made up of the results
def my_map(&prc)
ans = []
self.each { |ele| ans << prc.call(ele)}
ans
end
end
|
class EventsController < ApplicationController
respond_to :html, :json
def index
@events = Event.all
respond_with @events
end
def new
@event = Event.new
respond_with @event
end
def show
@event = Event.find_by(id: params[:id])
not_found unless @event
respond_with @event
end
def create
return head :forbidden unless admin_signed_in? and current_admin.approved?
event = Event.new(event_parameters_create)
if event.save
head :created, location: event_path(event)
else
render json: {error: event.errors}, status: :bad_request
end
end
def destroy
event = Event.find_by(id: params[:id])
return head :not_found unless event
return head :forbidden unless admin_signed_in? and current_admin.approved?
event.destroy
head :ok
end
private
def event_parameters_create
parameters = params.require(:event).permit(:title, :description, :location, :start_time, :end_time)
parameters
end
def not_found
raise ActionController::RoutingError.new('Not Found')
end
end
|
class VehiclesController < ApplicationController
before_action :authenticate_user!, except: [:index]
def index
@vehicles = Vehicle.all
end
def new
@vehicle = Vehicle.new
@models = []
load_brands
end
def edit
@vehicle = Vehicle.find(params[:id])
load_brands
@models = HTTParty.get("http://fipeapi.appspot.com/api/1/carros/veiculos/#{@vehicle.brand}.json").parsed_response
end
def create
Vehicle.create(vehicle_params)
redirect_to vehicles_path
end
def update
@vehicle = Vehicle.find(params[:id])
if @vehicle.update(vehicle_params)
redirect_to vehicles_path
else
render 'edit'
end
end
private
def vehicle_params
params.require(:vehicle).permit(:license_plate, :brand, :model, :year_model, :year_manufacture)
end
def load_brands
@brands = HTTParty.get('http://fipeapi.appspot.com/api/1/carros/marcas.json').parsed_response
end
end
|
class TimeSlot < ActiveRecord::Base
attr_accessible :end_time, :start_time
has_many :speakers
validates_uniqueness_of :start_time, :scope => :end_time
def to_s
return self.start_time.strftime("%H:%M") + "-" + self.end_time.strftime("%H:%M")
end
end
|
class AddTrialsAndSites < ActiveRecord::Migration
def change
create_table :trials do |t|
t.string :title
t.text :description
t.string :sponsor
t.string :country
t.string :focus
t.string :nct_id
t.string :official_title
t.string :agency_class
t.text :detailed_description
t.string :overall_status
t.string :phase
t.string :study_type
t.string :condition
t.string :inclusion
t.string :exclusion
t.string :gender
t.integer :minimum_age, null: false, default: 0
t.integer :maximum_age, null: false, default: 120
t.string :healthy_volunteers
t.string :overall_contact_name
t.timestamps
end
create_table :sites do |t|
t.belongs_to :trial, index: true, foreign_key: true
t.text :facility
t.text :street_address
t.text :street_address2
t.text :city
t.text :state
t.text :country
t.text :zip_code
t.timestamps
end
end
end
|
class MenuCategoryController < ApplicationController
before_action :ensure_admin_in, only: %i[create edit statusupdate update destroy]
before_action :set_menu_category, only: %i[ show edit update destroy ]
before_action :set_cart_items, only: %i[index search]
def index
@pagy, @categories = pagy(MenuCategory.where("archived_on is NULL").order(:status => :desc, :id => :asc), items: 10)
end
def search
name = params[:name]
unless name.nil?
@pagy, @categories = pagy(MenuCategory.where("lower(name) Like '" + "#{name.downcase}%' and archived_on is NULL").order(:status => :desc, :id => :asc), items: 10)
else
@pagy, @categories = pagy(MenuCategory.where("archived_on is NULL").order(:status => :desc, :id => :asc), items: 10)
end
render "index"
end
def create
name = params[:name]
@menu_category = MenuCategory.new(name: name, status: true)
unless @menu_category.save
flash[:error] = @menu_category.errors.full_messages.join(", ")
end
redirect_to "/menu_category"
end
def edit
end
def statusupdate
id = params[:id]
status = params[:status] ? true : false
menu_category = MenuCategory.find(id)
menu_category.status = status
menuitems = MenuItem.where("menu_category_id = ?", id)
if (status)
setMenuitemstatus(menuitems, "Active")
else
setMenuitemstatus(menuitems, "InActive")
end
menu_category.save!
redirect_back(fallback_location: "/")
end
def update
@menu_category.name = menu_category_params["name"]
@menu_category.save
redirect_to menu_category_index_path
end
def destroy
menuItemcount = MenuItem.where("menu_category_id = ? and archived_on is NULL", params[:id]).count
if menuItemcount == 0
@menu_category.archived_on = Time.zone.now
unless @menu_category.save
flash[error] = @menu_category.errors.full_messages.join(", ")
end
else
flash[:error] = "Not allowed first delete all the menu Items"
end
redirect_back(fallback_location: "/")
end
private
# Use callbacks to share common setup or constraints between actions.
def set_menu_category
@menu_category = MenuCategory.find(params[:id])
end
def menu_category_params
params.require(:menu_category).permit(:name)
end
def setMenuitemstatus(menuitems, status)
menuitems.each do |item|
item.status = status
item.save
end
end
end
|
# encoding: utf-8
require 'nokogiri'
require 'open-uri'
class RssItem
include Mongoid::Document
include Mongoid::Timestamps::Created
# You will change to like rss xml field.
# Example like this:
# field :title, type: String
# field :description, type: String
# field :body, type: String
# field :link, type: String
# field :guid, type: String
# field :pub_date, as: :pubDate, type: Time
# validates :title, :description, :body, :link, :pub_date, presence: true
before_validation :extract_body
def self.extract_xml_item
rss_url = YAML.load_file(File.expand_path("../../config/app_configs.yml", __FILE__))['rss_url']
Nokogiri::XML(open(rss_url)).css('item')
end
def extract(xml_item)
# You will get text from rss xml file.
# Example like this:
## self.title = h(xml_item.css('title'))
## self.description = h(xml_item.css('description'))
## self.link = h(xml_item.css('link'))
## self.guid = h(xml_item.css('guid'))
## self.pub_date = Time.parse(h(xml_item.css('pubDate')))
end
def valid(today)
# You will valid rss item data in here.
# Example like this:
## RssItem.where(link: link).exists? || (today - rss_item.pubDate.to_date).to_i <= 7
end
def extract_body
# You will get rss content data in here.
# Example like this:
## self.body = Nokogiri::HTML(open(link)).css('div#content').inner_html.strip
end
def h(dom)
Nokogiri::HTML(dom.inner_text.strip).inner_text.strip
end
end
|
require 'rails_helper'
require 'parsers'
describe Parsers::Table do
let(:fixture) { "#{Rails.root}/spec/fixtures/schema.rb" }
let(:code) { File.open(fixture).read }
it 'parsers a schema.rb file into tables' do
parser = Parsers::Table.new(code)
expect(parser.tables).to eq([
{
title: 'repo_followings',
columns: [
'id',
'repo_owner',
'repo_name',
'follower'
],
},
{
title: 'repos',
columns: [
'id',
'owner',
'name'
],
},
{
title: 'users',
columns: [
'id',
'email',
'encrypted_password',
'reset_password_token',
'reset_password_sent_at',
'remember_created_at',
'sign_in_count',
'current_sign_in_at',
'last_sign_in_at',
'current_sign_in_ip',
'last_sign_in_ip',
'oauth_provider',
'oauth_uid',
'auth_token',
'created_at',
'updated_at',
'github_username'
]
},
{
title: 'no_columns',
columns: ['id']
},
{
title: 'one_column',
columns: ['id', 'single_column']
}
])
end
end
|
require 'spec_helper'
describe GemPolish::CLI::GemManipulator do
let(:cli) do
Class.new(Thor) do
include Thor::Actions
end.new
end
let(:gem_manipulator) do
gm = GemPolish::CLI::GemManipulator.new(cli)
gm.stub(gemfile: testfile('Gemfile'))
gm
end
before :all do
string_io = StringIO.new
@stdout = $stdout
$stdout = string_io
end
before :each do
create_testfile('Gemfile')
end
def gemfile
read_testfile('Gemfile')
end
describe "#add" do
context "with a single gem" do
it "adds a gem to the Gemfile" do
gem_manipulator.add('gp')
read_testfile('Gemfile').should =~ /gem 'gp'/
end
context "with options" do
it "can specify a version" do
gem_manipulator.add('gp', version: '1.7')
gemfile.should =~ /gem 'gp', '~> 1\.7'/
end
it "can specify a local path" do
gem_manipulator.add('gp', path: '/home/code/gp')
gemfile.should =~ /gem 'gp', path: '\/home\/code\/gp'/
end
it "can specify a git path - only the repository needs to be given" do
gem_manipulator.add('gp', github: 'LFDM/gp')
gemfile.should =~ /gem 'gp', git: 'git@github\.com:LFDM\/gp\.git'/
end
it "can specify the name to require" do
gem_manipulator.add('gp', require: 'pg')
gemfile.should =~ /gem 'gp', require: 'pg'/
end
it "can specify a plaform" do
gem_manipulator.add('gp', platform: 'jruby')
gemfile.should =~ /gem 'gp', platform: :jruby/
end
it "can specify a group" do
gem_manipulator.add('gp', group: 'assets')
gemfile.should =~ /gem 'gp', group: :assets/
end
it "takes multiple options" do
gem_manipulator.add('gp', platform: 'jruby', version: '1.0')
gemfile.should =~ /gem 'gp', '~> 1\.0', platform: :jruby/
end
end
end
context "with multiple gems" do
it "adds multiple gems at once" do
gem_manipulator.add(%w{ gp pg })
gemfile.should =~ /gem 'gp'\ngem 'pg'/
end
context "with options" do
it "places gems in ruby blocks" do
gem_manipulator.add(%w{ gp pg }, platform: 'jruby')
gemfile.should =~ /platform :jruby do\n gem 'gp'\n gem 'pg'\nend/
end
it "takes multiple blocks as well (group and platform)" do
gem_manipulator.add(%w{ gp pg }, group: 'test', platform: 'jruby')
gemfile.should =~ /group :test do\n platform :jruby do\n gem 'gp'\n gem 'pg'\n end\nend/
end
end
end
end
after :all do
$stdout = @stdout
end
after :each do
remove_testfiles
end
end
|
# coding: UTF-8
rootdir = File.dirname(File.dirname(__FILE__))
$LOAD_PATH.unshift "#{rootdir}/lib"
if defined? Encoding
Encoding.default_internal = 'UTF-8'
end
require 'test/unit'
require 'redcarpet'
require 'redcarpet/render/hiki'
class HikiTest < Test::Unit::TestCase
def setup
@markdown = Redcarpet::Markdown.new(Redcarpet::Render::Hiki.new({}))
end
def render_with(flags, text)
Redcarpet::Markdown.new(Redcarpet::Render::Hiki, flags).render(text)
end
def test_that_simple_one_liner_goes_to_review
assert_respond_to @markdown, :render
assert_equal "\n\nHello World.\n", @markdown.render("Hello World.")
end
def test_href
assert_respond_to @markdown, :render
assert_equal "\n\n[[example|http://exmaple.com]]\n", @markdown.render("[example](http://exmaple.com)\n")
end
def test_header
assert_respond_to @markdown, :render
assert_equal "\n! AAA\n\n\nBBB\n\n!! ccc\n\n\nddd\n", @markdown.render("#AAA\nBBB\n\n##ccc\n\nddd\n")
end
end
|
require 'rails_helper'
RSpec.describe "project_reports/edit", type: :view do
before(:each) do
@project_report = assign(:project_report, ProjectReport.create!(
:project_id => "",
:status_cd => "MyText"
))
end
it "renders the edit project_report form" do
render
assert_select "form[action=?][method=?]", project_report_path(@project_report), "post" do
assert_select "input[name=?]", "project_report[project_id]"
assert_select "textarea[name=?]", "project_report[status_cd]"
end
end
end
|
class Api::ListsController < ApplicationController
def initialize
super
@words = []
end
def index
@lists = current_user.lists.includes(:list_words)
render :index
end
def show
load_list(params[:id])
if @list.empty?
render :show_error, status: 404
else
render :show
end
end
def create
@list = List.new(list_params)
if List.create_list(current_user, words_params[:words], @list)
load_list(@list.id)
render :show
else
render :create_error, status: 422
end
end
def destroy
@list = List.find_by(id: params[:id])
@list.destroy if @list
end
def update
load_list(params[:id])
if @list.empty?
render :show_error, status: 404
return
end
toggle_active_status
render :show
end
private
# grabs the list and preloads associated data for JBuilder; no n+1!
def load_list(id)
@list = List.includes(:words)
.includes(:definitions)
.includes(:examples)
.where(id: id)
end
def list_params
params.require(:list).permit(:title, :description, :active)
end
def words_params
params.require(:list).permit(words: [])
end
def toggle_active_status
@list.first.active = !@list.first.active
@list.first.save
end
end
|
require 'helper'
class TestSite < Test::Unit::TestCase
def test_array_of_items
assert_equal Array, @site.items.class
assert @site.items.size > 0
end
def test_generate!
@site.generate!
assert File.exists?(site_file('public/test.html'))
end
def test_generate_creates_subdirectories
@site.generate!
assert Dir.exists?(File.join(@site.root,'public','subdirectory'))
end
def test_copies_files_in_subdirectories
@site.generate!
assert File.exists?(File.join(@site.root,'public','subdirectory','test.png'))
end
def test_creates_items_in_subdirectories
@site.generate!
assert File.exists?(File.join(@site.root,'public','subdirectory','subfile.html'))
end
def test_underscored_items_dont_get_copied
@site.generate!
assert !File.exists?(site_file('public/_hidden.html'))
end
def test_generates_sass
@site.generate!
assert File.exists?(site_file("public/test.css"))
assert_equal "body {\n background-color: blue; }\n", File.read(site_file("public/test.css"), encoding: "US-ASCII")
end
def test_asset_files
assert @site.asset_files.include? site_file('_site/test.scss')
end
def test_tag_names
assert_equal ['one',"three","two"], @site.tag_names.sort
end
def test_tags
assert @site.tags.first.is_a? Jenner::Tag
end
end
|
require 'rails_helper'
describe Tagging do
it 'is instantiable' do
expect{ tagging = Tagging.new }.not_to raise_error
end
it 'defaults attributes to nil' do
tagging = Tagging.new
expect(tagging.goal_id).to be_nil
expect(tagging.tag_id).to be_nil
end
end
|
class CreatePaymentTokens < ActiveRecord::Migration
def change
create_table :payment_tokens do |t|
t.references :user, index: true
t.string :code
t.string :status, default: 'active'
t.string :note
t.integer :actived_by
t.integer :actived_site_id
t.timestamps
end
add_index :payment_tokens, :code, unique: true
add_index :payment_tokens, :actived_by
add_index :payment_tokens, :actived_site_id
end
end
|
class InvestigationcausesController < ApplicationController
before_action :set_investigationcause, only: [:show, :edit, :update, :destroy]
# GET /investigationcauses
# GET /investigationcauses.json
def index
@investigationcauses = Investigationcause.all
end
# GET /investigationcauses/1
# GET /investigationcauses/1.json
def show
end
# GET /investigationcauses/new
def new
@investigationcause = Investigationcause.new
end
# GET /investigationcauses/1/edit
def edit
end
# POST /investigationcauses
# POST /investigationcauses.json
def create
@investigationcause = Investigationcause.new(investigationcause_params)
respond_to do |format|
if @investigationcause.save
format.html { redirect_to @investigationcause.investigation, notice: 'Investigationcause was successfully created.' }
format.json { render :show, status: :created, location: @investigationcause }
else
format.html { render :new }
format.json { render json: @investigationcause.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /investigationcauses/1
# PATCH/PUT /investigationcauses/1.json
def update
respond_to do |format|
if @investigationcause.update(investigationcause_params)
format.html { redirect_to @investigationcause.investigation, notice: 'Investigationcause was successfully updated.' }
format.json { render :show, status: :ok, location: @investigationcause }
else
format.html { render :edit }
format.json { render json: @investigationcause.errors, status: :unprocessable_entity }
end
end
end
# DELETE /investigationcauses/1
# DELETE /investigationcauses/1.json
def destroy
@investigationcause.destroy
respond_to do |format|
format.html { redirect_to investigationcauses_url, notice: 'Investigationcause was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_investigationcause
@investigationcause = Investigationcause.find(params[:id])
end
# Only allow a list of trusted parameters through.
def investigationcause_params
params.require(:investigationcause).permit(:investigation_id, :cause_id)
end
end
|
require 'net/https'
require 'uri'
require 'json'
# namespace :appertas do
desc "Fill database with images'info"
task :importMedia => :environment do
response = callService()
photos = extractMedia(JSON.parse response.body)
saveMedia(photos)
end
def callService()
uri = URI.parse('https://api.instagram.com/v1/users/self/media/liked?access_token='+APPERTASUSER_TOKEN)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
return response
end
def extractMedia(res)
photos = Array.new
res['data'].each do |image|
photo = Hash.new
photo['id'] = image['id']
photo['sources'] = image['images']['standard_resolution']['url']
comments = retrieve_comments(image)
photo['answer'] = find_anwser(comments, image['id'])
photos << photo
end
return photos
end
def retrieve_comments(image)
uri = URI.parse('https://api.instagram.com/v1/media/'+image['id']+'/comments?access_token='+APPERTASUSER_TOKEN)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
res = JSON.parse response.body
return res['data']
end
def find_anwser(comments, idImage)
answer = Hash.new
comments.each do |comment|
if comment['from']['username'] == 'appertas'
answer['comment'] = comment['text']
answer['word'] = /#itl_(\S*)/.match(comment['text'])[1]
answer['level'] = 0
break
end
end
return answer
end
def saveMedia(photos)
photos.each do |photo|
# puts "#{photo}"
p = Photo.find(:all, :conditions => "idImage = '"+photo['id']+"'")
if p.blank?
p = Photo.create(:idImage => photo['id'])
p.sr_url = photo['sources']
p.comment = photo['answer']['comment']
p.answer = photo['answer']['word']
p.level = photo['answer']['level']
p.save
end
end
end
# end
|
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :invoice do
invoice_date "2014-08-03"
description "MyString"
customer nil
status "MyString"
revision 1
end
end
|
require "money_exchange_gem/version"
require 'money_exchange_gem/exchange'
class Money
include Comparable
def <=>(other)
@amount <=> other.exchange_to(@currency)
end
attr_reader :amount, :currency
def initialize(amount, currency)
@amount = amount
@currency = currency
end
def to_s
"#{format('%.2f', @amount)} #{@currency}"
end
def inspect
"#<Money #{to_s}>"
end
class << self
["usd", "eur", "gbp"].each do |currency|
define_method "from_#{currency}" do |amount|
Money.new(amount, currency.upcase)
end
end
end
def self.exchange
Exchange.new
end
def exchange_to(currency)
Money.exchange.convert(self, currency)
end
def to_int
@currency == "USD" ? @amount.to_int : exchange_to("USD").to_int
end
def method_missing(method, *arguments, &block)
method.to_s =~ /^to_(.*)$/ && Exchange.currencies.include?($1.upcase) ? exchange_to($1.upcase) : super
end
def respond_to?(method)
method.to_s =~ /^to_(.*)$/ && Exchange.currencies.include?($1.upcase) ? true : super
end
end
|
class DemoController < ApplicationController
layout 'application'
# Override the behavior by filling the index method
def index
render('index')
# These are also possible
# render(:template => 'demo/index')
# render('demo/index')
end
# This is an action
def hello
@array = [1, 2, 3, 4, 5]
# For params[] array to work, symbol and string does not matter
# If the route matches, Ruby adds these params as query parameters
@id = params['id']
@page = params[:page]
render('hello') # This will render a template
end
# Redirection takes two http requests: One for the original action.
# Then Rails sends a status code '302 Found' message to the browser to send a new
# request for the page that will be redirected to. That's the second.
def other_hello
redirect_to(:action => 'index')
# Since it will redirect to the same controller, no need to specify the controller
# redirect_to(:controller => 'demo', :action => 'index')
end
def lynda
redirect_to('http://lynda.com')
end
def escape_output
end
end
|
# frozen_string_literal: true
module Sapo
class DataExtension
extend Savon::Model
client wsdl: Client::WSDL_URI,
endpoint: Client::SOAP_ENDPOINT_URI,
log_level: :debug,
log: true
operations :create,
:retrieve,
:update,
:delete,
:query,
:describe,
:execute,
:perform,
:configure,
:schedule,
:version_info,
:extract,
:get_system_status
def authorize
access_token = Client.new.authorize
client.globals[:soap_header] = { fueloauth: access_token }
end
def all
query(message: { QueryRequest: { Query: { Object: { ObjectType: 'DataExtension', Properties: ["Name"] }}}}).body
end
end
end
|
class RemoveConstraintsFromSpeaker < ActiveRecord::Migration
def up
remove_index :speakers, :column => :name
end
def down
add_index :speakers, :name, :unique => true
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
private
def authenticate
# raise 'hello'
@current_user = User.find_by :id => session[:user_id] if session[:user_id]
session[:user_id] = nil unless @current_user
if !@current_user
respond_to do |format|
format.html { redirect_to login_path, notice: 'Please log in to access Drawsome.' }
end
end
end
end
|
require 'spec_helper'
describe "User Profile" do
subject { page }
describe "edit" do
let(:user) { FactoryGirl.create(:user) }
before do
sign_in user
visit edit_user_path(user)
end
describe "page" do
it { should have_title(user.name) }
it { should have_title("Edit") }
it { should have_link('Users', href: users_path) }
it { should have_link('Profile', href: user_path(user)) }
it { should have_link('Settings', href: edit_user_path(user)) }
it { should have_link('Sign out', href: signout_path) }
it { should_not have_link('Sign in', href: signin_path) }
it { should have_content("Update your profile") }
it { should have_content("Name") }
it { should have_content("Email") }
it { should have_content("Password") }
it { should have_content("Confirm password") }
it { should have_link('change', href: 'http://gravatar.com/emails') }
end
describe "with invalid information" do
before { click_button "Save changes" }
it { should have_content('error') }
end
describe "with valid information" do
let(:new_name) {"New Name"}
let(:new_email) {"New@Nosuch.Example.com"}
before do
fill_in "Name", with: new_name
fill_in "Email", with: new_email
fill_in "Password", with: user.password
fill_in "Confirm password", with: user.password
click_button "Save changes"
end
it { should have_title(new_name) }
it { should have_selector('div.alert.alert-success') }
it { should have_link('Sign out') }
specify { expect(user.reload.name).to eq new_name }
specify { expect(user.reload.email).to eq new_email }
specify { expect(user.reload.lc_email).to eq new_email.downcase }
end
describe "as wrong user" do
let(:user) { FactoryGirl.create :user }
let(:wrong_user) { FactoryGirl.create :user, email: "MrWong@Over.there" }
before { sign_in user, no_capybara: true }
describe "submitting GET request to the Users#edit action" do
before { get edit_user_path(wrong_user) }
specify { expect(response.body).not_to match("Edit") }
specify { expect(response).to redirect_to(root_url) }
end
describe "submitting a PATCH request to Users#update action" do
before { patch user_path(wrong_user) }
specify { expect(response).to redirect_to(root_url) }
end
end
describe "forbidden attributes" do
# Admin is not an attribute that can be changed
let(:params) do
{ user: { admin: true,
password: user.password,
password_confirmation: user.password } }
end
before do
sign_in user, no_capybara: true
patch user_path(user), params
end
specify { expect(user.reload).not_to be_admin }
end
end
end
|
class VideoValidation
attr_reader :video
def initialize(video)
@video = video
end
def validate
max_pos = @video.tutorial.videos.maximum(:position)
if video.position.nil?
video.update_attributes(position: max_pos + 1)
end
end
end |
# frozen_string_literal: true
class TestNoTitle < SitePrism::Page
set_url '/no_title.htm'
set_url_matcher(/no_title\.htm$/)
element :element_without_selector
elements :elements_without_selector
end
|
class AddDestroyAttemptOnToStructureImages < ActiveRecord::Migration
def change
add_column :structure_images, :destroy_attempt_on, :datetime
end
end
|
require 'test_helper'
class MenuposrventadiaactualtsControllerTest < ActionDispatch::IntegrationTest
setup do
@menuposrventadiaactualt = menuposrventadiaactualts(:one)
end
test "should get index" do
get menuposrventadiaactualts_url
assert_response :success
end
test "should get new" do
get new_menuposrventadiaactualt_url
assert_response :success
end
test "should create menuposrventadiaactualt" do
assert_difference('Menuposrventadiaactualt.count') do
post menuposrventadiaactualts_url, params: { menuposrventadiaactualt: { fecha: @menuposrventadiaactualt.fecha, sucursal: @menuposrventadiaactualt.sucursal, venta: @menuposrventadiaactualt.venta } }
end
assert_redirected_to menuposrventadiaactualt_url(Menuposrventadiaactualt.last)
end
test "should show menuposrventadiaactualt" do
get menuposrventadiaactualt_url(@menuposrventadiaactualt)
assert_response :success
end
test "should get edit" do
get edit_menuposrventadiaactualt_url(@menuposrventadiaactualt)
assert_response :success
end
test "should update menuposrventadiaactualt" do
patch menuposrventadiaactualt_url(@menuposrventadiaactualt), params: { menuposrventadiaactualt: { fecha: @menuposrventadiaactualt.fecha, sucursal: @menuposrventadiaactualt.sucursal, venta: @menuposrventadiaactualt.venta } }
assert_redirected_to menuposrventadiaactualt_url(@menuposrventadiaactualt)
end
test "should destroy menuposrventadiaactualt" do
assert_difference('Menuposrventadiaactualt.count', -1) do
delete menuposrventadiaactualt_url(@menuposrventadiaactualt)
end
assert_redirected_to menuposrventadiaactualts_url
end
end
|
# == Schema Information
#
# Table name: reservations
#
# id :bigint not null, primary key
# num_guests :integer not null
# date :date not null
# time :time not null
# special_request :text
# reserved :boolean default(FALSE)
# user_id :integer not null
# restaurant_id :integer not null
# created_at :datetime not null
# updated_at :datetime not null
#
class Reservation < ApplicationRecord
validates :num_guests, :date, :time, :user_id, :restaurant_id, presence: true
belongs_to :user,
foreign_key: :user_id,
class_name: :User
belongs_to :restaurant,
foreign_key: :restaurant_id,
class_name: :Restaurant
end
|
# This migration comes from atomic_tenant (originally 20220816174344)
class CreateAtomicTenantPinnedPlatformGuids < ActiveRecord::Migration[7.0]
def change
create_table :atomic_tenant_pinned_platform_guids do |t|
t.string :iss, null: false
t.string :platform_guid, null: false
t.bigint :application_id, null: false
t.bigint :application_instance_id, null: false
t.timestamps
end
add_index :atomic_tenant_pinned_platform_guids, [:iss, :platform_guid, :application_id], unique: true, name: 'index_pinned_platform_guids'
end
end
|
class ClearCmsContentService < CivilService::Service
attr_reader :convention
def initialize(convention:)
@convention = convention
end
private
def inner_call
convention.update!(
root_page: nil,
default_layout: nil,
user_con_profile_form: nil
)
convention.cms_navigation_items.destroy_all
convention.pages.destroy_all
convention.cms_partials.destroy_all
convention.cms_layouts.destroy_all
convention.cms_files.destroy_all
convention.forms.destroy_all
success
end
end
|
require 'spec_helper'
describe Gnip::InstanceRegistrar do
let(:owner) { users(:owner) }
let(:instance_attributes) do
{
:name => "new_gnip_instance",
:description => "some description",
:stream_url => "https://historical.gnip.com/fake",
:username => "gnip_username",
:password => "gnip_password",
:owner => owner
}
end
describe ".create!" do
context "with Valid credentials" do
before do
any_instance_of(ChorusGnip) do |c|
mock(c).auth { true }
end
end
it "save the instance" do
instance = Gnip::InstanceRegistrar.create!(instance_attributes, owner)
instance.should be_persisted
instance.name.should == "new_gnip_instance"
instance.description.should == "some description"
instance.stream_url.should == "https://historical.gnip.com/fake"
instance.username.should == "gnip_username"
instance.password.should == "gnip_password"
instance.id.should_not be_nil
instance.should be_valid
end
it "makes a GnipInstanceCreated event" do
instance = Gnip::InstanceRegistrar.create!(instance_attributes, owner)
event = Events::GnipInstanceCreated.last
event.gnip_instance.should == instance
event.actor.should == owner
end
end
context "With Invalid credentials" do
before do
any_instance_of(ChorusGnip) do |c|
mock(c).auth { false }
end
end
it "raise an error" do
expect {
Gnip::InstanceRegistrar.create!(instance_attributes, owner)
}.to raise_error(ApiValidationError)
end
end
end
describe ".update!" do
let(:gnip_instance) { gnip_instances(:default) }
context "with Valid credentials" do
let(:new_owner) { users(:not_a_member) }
before do
instance_attributes.merge!({:owner => JSON.parse(new_owner.to_json)})
any_instance_of(ChorusGnip) do |c|
mock(c).auth { true }
end
end
it "save the instance" do
instance = Gnip::InstanceRegistrar.update!(gnip_instance.id, instance_attributes)
instance.should be_persisted
instance.name.should == "new_gnip_instance"
instance.description.should == "some description"
instance.stream_url.should == "https://historical.gnip.com/fake"
instance.username.should == "gnip_username"
instance.password.should == "gnip_password"
instance.id.should_not be_nil
instance.should be_valid
end
it "should ignore an empty password" do
instance_attributes[:password] = ""
instance = Gnip::InstanceRegistrar.update!(gnip_instance.id, instance_attributes)
instance.reload
instance.password.should_not be_blank
end
it "should strip out the owner" do
instance = Gnip::InstanceRegistrar.update!(gnip_instance.id, instance_attributes)
instance.owner.should_not == new_owner
end
end
context "With Invalid credentials" do
before do
any_instance_of(ChorusGnip) do |c|
mock(c).auth { false }
end
end
it "raise an error" do
expect {
Gnip::InstanceRegistrar.update!(gnip_instance.id, instance_attributes)
}.to raise_error(ApiValidationError)
end
end
end
end |
class CreateCars < ActiveRecord::Migration
def change
create_table :cars do |t|
t.string :category
t.string :make
t.string :model_name
t.string :model_code
t.string :fuel
t.string :colour
t.integer :doors
t.decimal :price, :precision => 8, :scale => 2
t.timestamps
end
end
end
|
# frozen_string_literal: true
module Dynflow
class World
module Invalidation
# Invalidate another world, that left some data in the runtime,
# but it's not really running
#
# @param world [Coordinator::ClientWorld, Coordinator::ExecutorWorld] coordinator record
# left behind by the world we're trying to invalidate
# @return [void]
def invalidate(world)
Type! world, Coordinator::ClientWorld, Coordinator::ExecutorWorld
coordinator.acquire(Coordinator::WorldInvalidationLock.new(self, world)) do
coordinator.find_locks(class: Coordinator::PlanningLock.name,
owner_id: 'world:' + world.id).each do |lock|
invalidate_planning_lock lock
end
if world.is_a? Coordinator::ExecutorWorld
old_execution_locks = coordinator.find_locks(class: Coordinator::ExecutionLock.name,
owner_id: "world:#{world.id}")
coordinator.deactivate_world(world)
old_execution_locks.each do |execution_lock|
invalidate_execution_lock(execution_lock)
end
end
pruned = persistence.prune_envelopes(world.id)
logger.error("Pruned #{pruned} envelopes for invalidated world #{world.id}") unless pruned.zero?
coordinator.delete_world(world)
end
end
def invalidate_planning_lock(planning_lock)
with_valid_execution_plan_for_lock(planning_lock) do |plan|
plan.steps.values.each { |step| invalidate_step step }
state = if plan.plan_steps.any? && plan.plan_steps.all? { |step| step.state == :success }
:planned
else
:stopped
end
plan.update_state(state) if plan.state != state
coordinator.release(planning_lock)
execute(plan.id) if plan.state == :planned
end
end
# Invalidate an execution lock, left behind by a executor that
# was executing an execution plan when it was terminated.
#
# @param execution_lock [Coordinator::ExecutionLock] the lock to invalidate
# @return [void]
def invalidate_execution_lock(execution_lock)
with_valid_execution_plan_for_lock(execution_lock) do |plan|
plan.steps.values.each { |step| invalidate_step step }
plan.execution_history.add('terminate execution', execution_lock.world_id)
plan.update_state(:paused, history_notice: false) if plan.state == :running
plan.save
coordinator.release(execution_lock)
if plan.error?
new_state = plan.prepare_for_rescue
execute(plan.id) if new_state == :running
else
if coordinator.find_worlds(true).any? # Check if there are any executors
client_dispatcher.tell([:dispatch_request,
Dispatcher::Execution[execution_lock.execution_plan_id],
execution_lock.client_world_id,
execution_lock.request_id])
end
end
end
rescue Errors::PersistenceError
logger.error "failed to write data while invalidating execution lock #{execution_lock}"
end
# Tries to load an execution plan using id stored in the
# lock. If the execution plan cannot be loaded or is invalid,
# the lock is released. If the plan gets loaded successfully, it
# is yielded to a given block.
#
# @param execution_lock [Coordinator::ExecutionLock] the lock for which we're trying
# to load the execution plan
# @yieldparam [ExecutionPlan] execution_plan the successfully loaded execution plan
# @return [void]
def with_valid_execution_plan_for_lock(execution_lock)
begin
plan = persistence.load_execution_plan(execution_lock.execution_plan_id)
rescue => e
if e.is_a?(KeyError)
logger.error "invalidated execution plan #{execution_lock.execution_plan_id} missing, skipping"
else
logger.error e
logger.error "unexpected error when invalidating execution plan #{execution_lock.execution_plan_id}, skipping"
end
coordinator.release(execution_lock)
coordinator.release_by_owner(execution_lock.id)
return
end
unless plan.valid?
logger.error "invalid plan #{plan.id}, skipping"
coordinator.release(execution_lock)
coordinator.release_by_owner(execution_lock.id)
return
end
yield plan
end
# Performs world validity checks
#
# @return [Integer] number of invalidated worlds
def perform_validity_checks
world_invalidation_result = worlds_validity_check
locks_validity_check
pruned = connector.prune_undeliverable_envelopes(self)
logger.error("Pruned #{pruned} undeliverable envelopes") unless pruned.zero?
world_invalidation_result.values.select { |result| result == :invalidated }.size
end
# Checks if all worlds are valid and optionally invalidates them
#
# @param auto_invalidate [Boolean] whether automatic invalidation should be performed
# @param worlds_filter [Hash] hash of filters to select only matching worlds
# @return [Hash{String=>Symbol}] hash containg validation results, mapping world id to a result
def worlds_validity_check(auto_invalidate = true, worlds_filter = {})
worlds = coordinator.find_worlds(false, worlds_filter)
world_checks = worlds.reduce({}) do |hash, world|
hash.update(world => ping_without_cache(world.id, self.validity_check_timeout))
end
world_checks.values.each(&:wait)
results = {}
world_checks.each do |world, check|
if check.fulfilled?
result = :valid
else
if auto_invalidate
begin
invalidate(world)
result = :invalidated
rescue => e
logger.error e
result = e.message
end
else
result = :invalid
end
end
results[world.id] = result
end
unless results.values.all? { |result| result == :valid }
logger.error "invalid worlds found #{results.inspect}"
end
return results
end
# Cleans up locks which don't have a resource
#
# @return [Array<Coordinator::Lock>] the removed locks
def locks_validity_check
orphaned_locks = coordinator.clean_orphaned_locks
unless orphaned_locks.empty?
logger.error "invalid coordinator locks found and invalidated: #{orphaned_locks.inspect}"
end
return orphaned_locks
end
private
def invalidate_step(step)
if step.state == :running
step.error = ExecutionPlan::Steps::Error.new("Abnormal termination (previous state: #{step.state})")
step.state = :error
step.save
end
end
end
end
end
|
require 'asciidoctor'
require 'asciidoctor/extensions'
module Perf
module Documentation
class LinkPerfProcessor < Asciidoctor::Extensions::InlineMacroProcessor
use_dsl
named :chrome
def process(parent, target, attrs)
if parent.document.basebackend? 'html'
%(<a href="#{target}.html">#{target}(#{attrs[1]})</a>\n)
elsif parent.document.basebackend? 'manpage'
"#{target}(#{attrs[1]})"
elsif parent.document.basebackend? 'docbook'
"<citerefentry>\n" \
"<refentrytitle>#{target}</refentrytitle>" \
"<manvolnum>#{attrs[1]}</manvolnum>\n" \
"</citerefentry>\n"
end
end
end
end
end
Asciidoctor::Extensions.register do
inline_macro Perf::Documentation::LinkPerfProcessor, :linkperf
end
|
# Using the multiply method from the "Multiplying Two Numbers" problem, write a method that computes the square of its argument (the square is the result of multiplying a number by itself).
# Question:
# Write a method that takes in an integer and returns its square
# Explicit vs Implicit
# Explicit:
# 1. use multiply method
# 2. return the square
# Implicit
# 1. square is **
# Input vs output
# Input:
# 1. integer
# 2. integer
# Algorithm:
# square method
def product(num1, num2)
num1 * num2
end
def square(num)
product(num, num)
end
p square(5) |
class GameSerializer < ActiveModel::Serializer
attributes :id, :opposing_team, :oppsoing_game_id, :goalie_id,
:home_bool, :period, :cons_saves, :pass, :left_crease, :waved_icing, :date
belongs_to :goalie
has_many :goals
has_many :blocks
end
|
module BqStream
module Archive
# Gathers record between earliest BigQuery record and given back date
def old_records_full_archive(back_date, verify_oldest = false, override_dataset = nil)
log(:info, "#{Time.now}: ***** Start Full Archive Process *****")
initialize_bq(override_dataset)
log(:info, "#{Time.now}: ***** Start Update Oldest Record Rows *****")
update_oldest_records
verify_oldest_records if verify_oldest
# Reset all rows archived status to false to run through all tables
OldestRecord.where.not(table_name: '! revision !').update_all(archived: false)
log(:info, "#{Time.now}: ***** End Update Oldest Record Rows *****")
process_archiving_tables(back_date)
log(:info, "#{Time.now}: ***** End Full Archive Process *****")
end
# Selectively send given Table's attributes to BigQuery
# attrs should be sent as an array of symbols
def partial_archive(back_date, table, attrs, override_dataset = nil)
log(:info, "#{Time.now}: ***** Start Partial Archive Process *****")
initialize_bq(override_dataset)
verify_oldest_records
assign_earliest_record_id(table)
assign_back_date_id(table.constantize, back_date)
oldest_attr_recs = []
attrs.each do |a|
record = OldestRecord.where(table_name: table, attr: a.to_s).try(:first)
oldest_attr_recs << record if record
end
oldest_attr_recs.each { |rec| rec.update(archived: false) }
archive_table(table, oldest_attr_recs)
log(:info, "#{Time.now}: ***** End Partial Archive Process *****")
end
private
# Sets up BigQuery and means to write records to it
def initialize_bq(override_dataset)
# Create BigQuery client connection
create_bq_writer(override_dataset)
# Create dataset if not present in BigQuery
@bq_writer.create_dataset(@bq_writer.dataset) unless @bq_writer.datasets_formatted.include?(@bq_writer.dataset)
# Create table in dataset if not present in BigQuery
unless @bq_writer.tables_formatted.include?(bq_table_name)
bq_table_schema = { table_name: { type: 'STRING', mode: 'REQUIRED' },
record_id: { type: 'INTEGER', mode: 'REQUIRED' },
attr: { type: 'STRING', mode: 'NULLABLE' },
new_value: { type: 'STRING', mode: 'NULLABLE' },
updated_at: { type: 'TIMESTAMP', mode: 'REQUIRED' } }
@bq_writer.create_table(bq_table_name, bq_table_schema)
end
end
# Check to make sure all attributes that are in BigQuery and bq_attributes are represented in OldestRecord table
def update_oldest_records
old_records = @bq_writer.query('SELECT table_name, attr FROM '\
"[#{project_id}:#{@bq_writer.dataset}.#{bq_table_name}] "\
'GROUP BY table_name, attr')
if old_records['rows']
old_records['rows'].each do |r|
table = r['f'][0]['v']
trait = r['f'][1]['v']
next unless trait && bq_attributes[table]
if bq_attributes[table].include?(trait.to_sym)
OldestRecord.find_or_create_by(table_name: table, attr: trait)
else
log(:info, "#{Time.now}: No longer tracking: #{table}: #{trait}")
end
end
end
end
# Add and Remove bq_attributes based on current bq_attributes
def verify_oldest_records
log(:info, "#{Time.now}: ***** Start Verifying Oldest Records *****")
current_deploy =
if (`cat #{File.expand_path ''}/REVISION`).blank?
'None'
else
`cat #{File.expand_path ''}/REVISION`
end
bq_attributes.each do |model, attrs|
# add any records to oldest_records that are new (Or more simply make sure that that there is a record using find_by_or_create)
attrs.each do |attr|
OldestRecord.find_or_create_by(table_name: model, attr: attr)
end
# delete any records that are not in bq_attributes
OldestRecord.where(table_name: model).each do |record|
record.destroy unless attrs.include?(record.attr.to_sym)
end
end
update_revision = OldestRecord.find_or_create_by(table_name: '! revision !')
update_revision.update(attr: current_deploy, archived: true)
log(:info, "#{Time.now}: ***** End Verifying Oldest Records *****")
end
# Run through all tables one at a time
def process_archiving_tables(back_date)
# Initialize an empty buffer for records that will be sent to BigQuery
@buffer = []
# Stop processing when all tables are archived
until OldestRecord.where(archived: false).empty? && @buffer.empty?
OldestRecord.table_names.each do |table|
log(:info, "#{Time.now}: ***** Cycle Table: #{table} *****")
@oldest_attr_recs = OldestRecord.where(table_name: table)
assign_earliest_record_id(table)
assign_back_date_id(table.constantize, back_date)
# Continue to work on one table until all records to back date are sent to BigQuery
until OldestRecord.where(table_name: table, archived: false).empty?
gather_records_for_buffer(table)
# Only write to BigQuery if we have rows set in the buffer
write_buffer_to_bq(table) unless @buffer.empty?
end
end
end
end
# Set id of the earliest record in BigQuery or first record (desc) from the database
def assign_earliest_record_id(table)
# See if there are any records for given table in BigQuery
record_id_query = @bq_writer.query('SELECT table_name, attr, min(record_id) as earliest_record_id '\
"FROM [#{project_id}:#{@bq_writer.dataset}.#{bq_table_name}] "\
"WHERE table_name = '#{table}' AND attr = 'id' "\
'GROUP BY table_name, attr')
# Set earliest record id based on rows in BigQuery or the latest record in the database
@earliest_record_id =
if record_id_query['rows']
record_id_query['rows'].first['f'].last['v'].to_i
else
table.constantize.unscoped.order(id: :desc).limit(1).first.try(:id)
end
log(:info, "#{Time.now}: ***** earliest_record_id: #{@earliest_record_id} *****")
end
# Set id of the first record from back date from the database
def assign_back_date_id(table_class, back_date)
@back_date_id =
# See if the given table has a created_at column
if table_class.column_names.include?('created_at')
table_class.unscoped.order(id: :asc).where('created_at >= ?', back_date).limit(1).first.try(:id)
else
# Grab very first id if there is no created_at column
table_class.unscoped.order(id: :asc).limit(1).first.try(:id)
end
log(:info, "#{Time.now}: ***** back_date_record_id: #{@back_date_id} *****")
end
def gather_records_for_buffer(table)
# Grab records between earliest written id and back date idea
# limited to the number of records we can grab, keeping under 10_000 rows
@next_batch = table.constantize.unscoped.order(id: :desc).where('id > ? AND id <= ?', @back_date_id, @earliest_record_id).limit(10_000 / (@oldest_attr_recs.count.zero? ? 1 : @oldest_attr_recs.count)) rescue []
log(:info, "#{Time.now}: ***** Next Batch Count for #{table}: #{@next_batch.count} *****")
if @next_batch.empty?
# If there are no records in range mark the table's attributes as archived
OldestRecord.where(table_name: table).update_all(archived: true)
else
# Write rows from records for BigQuery and place them into the buffer
@oldest_attr_recs.uniq.each do |oldest_attr_rec|
@next_batch.each do |record|
new_val = record[oldest_attr_rec.attr] && table.constantize.type_for_attribute(oldest_attr_rec.attr).type == :datetime ? record[oldest_attr_rec.attr].in_time_zone(timezone) : record[oldest_attr_rec.attr].to_s
@buffer << { table_name: table,
record_id: record.id,
attr: oldest_attr_rec.attr,
new_value: new_val,
updated_at: record.try(:created_at) || Time.now } # Using Time.now if no created_at (shows when put into BigQuery)
end
end
end
end
def write_buffer_to_bq(table)
log(:info, "#{Time.now}: ***** Start data pack and insert *****")
# Create data object for BigQuery insert
data = @buffer.collect do |i|
new_val = encode_value(i[:new_value]) rescue nil
{ table_name: i[:table_name], record_id: i[:record_id], attr: i[:attr],
new_value: new_val ? new_val : i[:new_value], updated_at: i[:updated_at] }
end
log(:info, "#{Time.now}: ***** Insert #{@buffer.count} Records for #{table} to BigQuery *****")
# Insert rows into BigQuery in one call, if there is data
insertion = data.empty? ? false : @bq_writer.insert(bq_table_name, data) rescue nil
# Check if insertion was successful
if insertion.nil?
log(:info, "#{Time.now}: ***** BigQuery Insertion to #{project_id}:#{dataset}.#{bq_table_name} Failed *****")
Rollbar.error("BigQuery Insertion to #{project_id}:#{dataset}.#{bq_table_name} Failed") if report_to_rollbar
else
# Lower earliest written id by one to get the next record to be written
@earliest_record_id = @next_batch.map(&:id).min - 1
log(:info, "#{Time.now}: ***** updated earliest_record_id: #{@earliest_record_id} *****")
end
# Clear the buffer for next cycle through the table
@buffer = []
log(:info, "#{Time.now}: ***** End data pack and insert *****")
end
def archive_table(table, oldest_attr_recs)
@buffer = []
until BqStream::OldestRecord.where(table_name: table, archived: false).empty?
@next_batch =
table.constantize.unscoped.order(id: :desc).where('id > ? AND id <= ?', @back_date_id, @earliest_record_id)
.limit(10_000 / (oldest_attr_recs.count.zero? ? 1 : oldest_attr_recs.count)) rescue []
if @next_batch.empty?
OldestRecord.where(table_name: table).update_all(archived: true)
else
oldest_attr_recs.uniq.each do |oldest_attr_rec|
@next_batch.each do |record|
new_val = record[oldest_attr_rec.attr] && table.constantize.type_for_attribute(oldest_attr_rec.attr).type == :datetime ? record[oldest_attr_rec.attr].in_time_zone(time_zone) : record[oldest_attr_rec.attr].to_s
@buffer << { table_name: table,
record_id: record.id,
attr: oldest_attr_rec.attr,
new_value: new_val,
updated_at: record.try(:created_at) || Time.now }
end
end
end
write_buffer_to_bq(table) unless @buffer.empty?
end
end
end
end
|
# frozen_string_literal: true
require 'aocp'
require 'time'
require 'zlib'
require 'yaml'
require 'msgpack'
require 'ostruct'
require 'fileutils'
require 'iop/file'
require 'iop/zlib'
require 'iop/digest'
require 'iop/string'
module Rockup
class Registry < Hash
def <<(x)
self[x.to_s] = x
self
end
def to_ext(mth = __callee__)
transform_values {|x| x.send(mth)}
end
alias to_h to_ext
alias to_yaml to_ext
end
class Project
class Registry < Rockup::Registry
def initialize(project)
super()
@project = project
end
def [](id = nil)
if id.nil?
Metadata.new(@project)
else
(x = super).nil? ? Metadata.read(@project, id) : x
end
end
end
attr_reader :repository
attr_reader :metadata
def initialize(url)
@repository = Repository.provider(url)
@metadata = Registry.new(self)
end
end
class Repository
def self.provider(url)
Local.new(url) # TODO
end
attr_reader :url
def initialize(url)
@url = url
end
def metadata
entries.collect {|x| Metadata.entry2id(x)}.compact
end
end
class Repository::Local < Repository
include IOP
attr_reader :root_dir
def initialize(url)
super(@root_dir = url)
end
def entries
Dir.entries(root_dir).delete_if { |x| /^\.{1,2}$/ =~ x }
end
def reader(entry)
FileReader.new(File.join(root_dir, entry))
end
def writer(entry)
unless @root_created
FileUtils.mkdir_p(root_dir)
@root_created = true
end
FileWriter.new(File.join(root_dir, entry))
end
end
class Metadata
include IOP
extend AOCP
attr_reader :project
attr_reader :sources
def initialize(project)
@project = project
@time = Time.now
@sources = Registry.new
@root_s = to_s
project.metadata << self
end
def_ctor :read, :read do |project, id|
@id = id
( project.repository.reader(entry) | GzipDecompressor.new | (packed = StringMerger.new) ).process!
hash = MessagePack.unpack(packed.to_s)
initialize(project)
@readonly = true
@time = Time.at(hash['ctime'])
@head_s = hash['head']
@root_s = hash['root']
read_sources(hash['sources'])
end
def_ctor :adopt, :adopt do |metadata|
initialize(metadata.project)
@head_s = metadata.to_s
@root_s = metadata.root_s
read_sources(metadata.sources.to_h)
end
private def read_sources(hash)
hash.each {|id, hash| Source.read(self, id, hash)}
end
def eql?(other)
self.class == other.class && to_s == other.to_s
end
def hash
to_s.hash
end
def to_ext(mth = __callee__)
{
'rockup' => 0,
'repository' => project.repository.url,
'root' => @root_s,
'head' => @head_s,
'ctime' => @time.to_i,
'sources' => sources.send(mth)
}.compact
end
alias to_h to_ext
def to_yaml
to_ext(__callee__).update('ctime' => @time)
end
def to_s
@id ||= (@time.to_f*1000).to_i.to_s(36)
end
def write
raise "refuse to write read-only metadata `#{self}`" if @readonly
( StringSplitter.new(MessagePack.pack(to_h)) | GzipCompressor.new | (d = DigestComputer.new(Digest::MD5.new)) | project.repository.writer(entry)).process!
( StringSplitter.new("#{d.digest.hexdigest} #{entry}") | GzipCompressor.new | project.repository.writer("#{self}.md5.gz") ).process!
@readonly = true
end
def entry
@entry ||= "#{self}.meta.gz"
end
def self.entry2id(entry)
/(.*)\.meta.gz$/ =~ entry
$1
end
protected
attr_reader :root_s
attr_reader :head_s
end
class Source
extend AOCP
attr_reader :metadata
attr_reader :root_dir
attr_reader :files
def initialize(metadata, root_dir)
@metadata = metadata
@root_dir = root_dir
@files = Registry.new
metadata.sources << self
end
def_ctor :read, :read do |metadata, id, hash|
initialize(metadata, id)
hash['files'].each {|file, hash| File.read(self, file, hash)}
end
def eql?(other)
self.class == other.class && root_dir == other.root_dir
end
def hash
root_dir.hash
end
def to_s
root_dir
end
def to_ext(mth = __callee__)
{
'files' => files.send(mth)
}
end
alias to_h to_ext
alias to_yaml to_ext
def warning(msg)
puts msg # TODO
end
def update
local_files.each {|f| File.new(self, f)}
files.keep_if {|k,v| v.live?}
end
def local_files(path = nil, files = [])
Dir.entries(path.nil? ? root_dir : ::File.join(root_dir, path)).each do |entry|
next if entry == '.' || entry == '..'
relative = path.nil? ? entry : ::File.join(path, entry)
full = ::File.join(root_dir, relative)
if ::File.directory?(full)
::File.readable?(full) ? local_files(relative, files) : warning("insufficient permissions to scan directory `#{full}`")
else
::File.readable?(full) ? files << relative : warning("insufficient permissions to read file `#{full}`")
end
end
files
end
end
class Source::File
extend AOCP
attr_reader :file
attr_reader :source
def live?; @live end
protected def revive; @live = true end
def initialize(source, file)
@source = source
@file = file
@live = true
if (existing = source.files[file]).nil?
source.files << self
else
unless existing.stat.mtime == self.mtime && existing.size == self.size
source.files << self
else
existing.revive
end
end
end
def_ctor :read, :read do |source, file, hash|
initialize(source, file)
@live = false
@stat = OpenStruct.new(hash)
stat.mtime = Time.at(stat.mtime)
@sha256 = DigestStruct.new(hash['sha256'])
end
def stat
@stat ||= File::Stat.new(File.join(source.root_dir, file))
end
def sha256
@sha256 ||= Digest::SHA256.file(File.join(source.root_dir, file))
end
def eql?(other)
self.class == other.class && file == other.file
end
def hash
file.hash
end
def to_s
file
end
def to_ext(mth = __callee__)
hash = {
'mtime' => stat.mtime.to_i,
'mode' => stat.mode,
'uid' => stat.uid,
'gid' => stat.gid
}
unless stat.size.nil? || stat.size.zero?
hash['size'] = stat.size
hash['sha256'] = sha256.digest
end
hash.compact
end
alias to_h to_ext
def to_yaml
hash = to_ext(__callee__)
hash.update('mtime' => stat.mtime, 'mode' => Octal.new(stat.mode))
hash.update('sha256' => sha256.hexdigest) unless hash['sha256'].nil?
end
# @private
class Octal
def initialize(value)
@value = value
end
def encode_with(coder)
coder.scalar = '0'+@value.to_s(8)
coder.tag = nil
end
end
# @private
class DigestStruct
attr_reader :digest
def hexdigest; @hexdigest ||= @digest.unpack('H*').first end
def initialize(digest) @digest = digest end
end
end
class Volume
attr_reader :project
attr_reader :to_s
attr_reader :files
end
class Volume::Dir < Volume
end
class Volume::Cat < Volume
end
end
|
###################################################################
# If you haven't already, clone down the lecture repo #
# git clone https://github.com/learn-co-students/dc-web-051319 #
# (this will be the repo for your entire time at Flatiron) #
###################################################################
# For each of the following examples, write two methods that solve the
# problem: One that uses `.each` and one that uses one of the higher level
# iterator methods
# Remember:
# map/collect: Returns an array where each value of the original array
# corresponds to an element in the new array
# find/detect: Returns the first element for which the statement in the block
# evaluates as True
# select/find_all: Returns an array of _all_ elements for which the statement in
# the block evaluates as True
nums = (1..20).to_a #creates an array of all numbers from 1-20
# 1. Create an array of numbers where each new number is three times as big as
# its original number (e.g., [3, 6, 9])
def triple(nums)
nums.map {|num| num * 3}
end
# print triple(nums)
# 2. Find the first number that is divisible by 7
def each_divisible(nums)
nums.each do |entry|
if entry % 7 == 0
return entry
end
end
end
def find_divisible(nums)
return nums.find {|i| i % 7 == 0}
end
# 3. Find all numbers that are divisible by 7
def find_all_divisible(nums)
return nums.select {|i| i % 7 == 0}
end
# puts find_all_divisible(nums)
# 4. Find the first number that is divisible by 7 AND greater than 10
fun_number = nums.find {|x| x % 7 == 0 && x > 10}
# print fun_number * 2
# Bonus:
# 5. Create an array of the squares (the number times itself) of all numbers
# that are divisible by 7
squares = nums.select do |i|
i % 7 == 0
end.map do |i|
i * i
end
print squares |
class BanksController < ApplicationController
def index
render json: Bank.all
end
def create
@bank = Bank.new(bank_params)
if @bank.save
render json: {status: "SUCCESS", message: "Loaded Data", data: @bank}
else
render json: @bank.errors, status: 422
end
end
def update
@bank = Bank.find(params[:id])
if @bank.update(bank_params)
render json: {status: "SUCCESS", message: "Updated Data", data: @bank}
else
render json: @bank.errors, status: 422
end
end
private
def bank_params
params.require(:bank).permit(:name, :cash)
end
end
|
class Movie < ApplicationRecord
belongs_to :genre
validates :title, :release_year, :description, :image_url, :starring_actors, :genre_id, presence: true
end
|
require 'spec_helper'
describe Rule do
let(:user) { User.make! }
before(:all) do
@pattern = Pattern.make!(:user => user)
end
context "invalid rules" do
it "should be invalid without a pattern, year, variation and value" do
rule = Rule.new()
rule.should have(1).error_on(:pattern_id)
rule.should have(1).error_on(:rule_type)
rule.should have(1).error_on(:year)
rule.should have(1).error_on(:variation)
rule.should have(1).error_on(:value)
rule.errors.count.should == 5
rule.should_not be_valid
end
it "should reject invalid values" do
rule_params = {:rule_type => 'temporary', :year => '2015', :variation =>'+'}
rule = @pattern.rules.create(rule_params.merge(:value => '-1'))
rule.should_not be_valid
rule = @pattern.rules.create(rule_params.merge(:value => 'abc'))
rule.should_not be_valid
end
it "should reject rules with invalid ranges or single values" do
rule_params = {:rule_type => 'temporary', :variation =>'+', :value => '1'}
rule = @pattern.rules.create(rule_params.merge(:year => 'every.0.years'))
rule.should_not be_valid
rule = @pattern.rules.create(rule_params.merge(:year => 'year.0'))
rule.should_not be_valid
rule = @pattern.rules.create(rule_params.merge(:year => 'year.2-year.0'))
rule.should_not be_valid
rule = @pattern.rules.create(rule_params.merge(:year => 'year.0-year.2'))
rule.should_not be_valid
rule = @pattern.rules.create(rule_params.merge(:year => 'year.5-year.1'))
rule.should_not be_valid
rule = @pattern.rules.create(rule_params.merge(:year => '1800'))
rule.should_not be_valid
rule = @pattern.rules.create(rule_params.merge(:year => '2010-2009'))
rule.should_not be_valid
rule = @pattern.rules.create(rule_params.merge(:year => '2010-2009'))
rule.should_not be_valid
rule = @pattern.rules.create(rule_params.merge(:year => '2010', :month => 'dec-dec'))
rule.should_not be_valid
rule = @pattern.rules.create(rule_params.merge(:year => '2010', :month => 'dec-mar'))
rule.should_not be_valid
rule = @pattern.rules.create(rule_params.merge(:year => '2010', :day => '32'))
rule.should_not be_valid
rule = @pattern.rules.create(rule_params.merge(:year => '2010', :day => '10-9'))
rule.should_not be_valid
rule = @pattern.rules.create(rule_params.merge(:year => '2010', :hour => '24'))
rule.should_not be_valid
rule = @pattern.rules.create(rule_params.merge(:year => '2010', :hour => '2-1'))
rule.should_not be_valid
end
end
context "valid rules" do
it "should allow valid rule_types" do
rule_params = {:year => '2015', :variation =>'+', :value => '1'}
rule = @pattern.rules.create(rule_params.merge(:rule_type => 'temporary'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:rule_type => 'permanent'))
rule.should be_valid
end
it "should allow valid years" do
rule_params = {:rule_type => 'temporary', :variation =>'+', :value => '1'}
rule = @pattern.rules.create(rule_params.merge(:year => 'every.1.year'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:year => 'every.2.years'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:year => 'year.1'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:year => 'year.4'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:year => 'year.4-year.6'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:year => 'year.1-year.4'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:year => '2015'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:year => '2015-2020'))
rule.should be_valid
end
it "should allow valid months" do
rule_params = {:rule_type => 'temporary', :year => '2015', :variation =>'+', :value => '1'}
rule = @pattern.rules.create(rule_params.merge(:month => 'every.1.month'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:month => 'every.2.months'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:month => 'jun'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:month => 'jun-sep'))
rule.should be_valid
end
it "should allow valid days" do
rule_params = {:rule_type => 'temporary', :year => '2015', :variation =>'+', :value => '1'}
rule = @pattern.rules.create(rule_params.merge(:day => 'every.1.day'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:day => 'every.2.days'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:day => 'every.mon'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:day => 'every.mon-thu'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:day => '15'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:day => '15-20'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:day => 'last.fri'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:day => 'last.sat-sun'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:day => 'first.mon'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:day => 'first.sat-sun'))
rule.should be_valid
end
it "should allow valid hours" do
rule_params = {:rule_type => 'temporary', :year => '2015', :variation =>'+', :value => '1'}
rule = @pattern.rules.create(rule_params.merge(:hour => 'every.1.hour'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:hour => 'every.2.hours'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:hour => '20'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:hour => '9-17'))
rule.should be_valid
end
it "should allow valid variations" do
rule_params = {:rule_type => 'temporary', :year => '2015', :value => '1'}
rule = @pattern.rules.create(rule_params.merge(:variation => '+'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:variation => '-'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:variation => '*'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:variation => '/'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:variation => '^'))
rule.should be_valid
rule = @pattern.rules.create(rule_params.merge(:variation => '='))
rule.should be_valid
end
end
it "should be deep cloned" do
rule = user.rules.create(:rule_type => 'temporary', :year => '2015', :variation =>'+', :value => '1')
rule.pattern = @pattern
rule.should be_valid
new_rule = rule.deep_clone
new_rule.user.should == rule.user
new_rule.pattern.should == rule.pattern
new_rule.rule_type.should == 'temporary'
new_rule.year.should == '2015'
new_rule.variation.should == '+'
new_rule.value.should == 1
end
end |
# encoding: utf-8
control "V-92679" do
title "Cookies exchanged between the Apache web server and client, such as session cookies, must have security settings that disallow cookie access outside the originating Apache web server and hosted application."
desc "Cookies are used to exchange data between the web server and the client. Cookies, such as a session cookie, may contain session information and user credentials used to maintain a persistent connection between the user and the hosted application since HTTP/HTTPS is a stateless protocol.
When the cookie parameters are not set properly (i.e., domain and path parameters), cookies can be shared within hosted applications residing on the same web server or to applications hosted on different web servers residing on the same domain.false"
impact 0.5
tag "check": "Review the web server documentation and configuration to determine if cookies between the web server and client are accessible by applications or web servers other than the originating pair.
grep SessionCookieName <'INSTALL LOCATION'>/mod_session.conf
Confirm that the 'HttpOnly' and 'Secure' settings are present in the line returned.
Confirm that the line does not contain the 'Domain' cookie setting.
Verify the 'headers_module (shared)' module is loaded in the web server:
'# httpd -M
Verify ' headers_module (shared)' is returned in the list of Loaded Modules from the above command.'
If the 'headers_module (shared)' is not loaded, this is a finding.
"
tag "fix": "Edit the 'mod_session.conf' file and find the 'SessionCookieName' directive.
Set the 'SessionCookieName' to 'session path=/; HttpOnly; Secure; '
Example:
SessionCookieName session path=/; HttpOnly; Secure;
Restart Apache: apachectl restart"
# Write Check Logic Here
describe apache_conf() do
its('SessionCookieName') { should include 'HttpOnly', 'Secure' }
its('SessionCookieName') { should_not include 'Domain' }
end
describe command('httpd -M | grep -i "headers_module"' ) do
its('stdout') { should eq ' headers_module (shared)' }
end
end
|
# frozen_string_literal: true
module KBE
module CLI
class EnterCommand < Clamp::Command
option ['-h', '--help'], :flag, "help" do
puts "kbe enter myapp"
puts "kbe enter myapp -c first"
puts "kbe enter myapp -c first -- uptime -h"
puts "kbe enter app=myapp -c first -- uptime -h"
exit 0
end
option ['-c', '--container'], 'CONTAINER', 'container', default: :first
parameter "SELECTOR_OR_POD", "selector or pod name"
parameter "[CMD] ...", "cmd"
def execute
cmds = if cmd_list.nil? || cmd_list.empty?
["sh"]
else
cmd_list
end
pod = KBE.pod_by selector_or_pod
args = []
args << "exec -it #{pod}"
unless container == :first
args << "-c #{container}"
end
args << "--"
args << cmds.join(" ")
KBE.kubectl args
end
end
end
end
|
require 'pry'
class Order
def initialize(animals)
if animals.join('').match(/[^SMRH]/)
throw ArgumentError.new('wrong animal!')
end
@animals = consolidate(animals)
end
def boxes
required_boxes = []
@animals[:snakes][:quantity].times {required_boxes.push('B3')}
unallocated_area = (
(@animals[:small_animals][:area]) + (@animals[:mongeese][:area])
)
while (unallocated_area > 0)
if (unallocated_area > BOX_SIZES[:B2])
required_boxes.push('B3')
unallocated_area -= BOX_SIZES[:B3]
elsif (unallocated_area >= BOX_SIZES[:B2])
required_boxes.push('B2')
unallocated_area -= BOX_SIZES[:B2]
elsif (unallocated_area = BOX_SIZES[:B1])
required_boxes.push('B1')
unallocated_area -= BOX_SIZES[:B1]
end
end
required_boxes.sort
end
end
def consolidate(animals)
zeroes = {H: 0, R: 0, M: 0, S: 0}
animals = animals.reduce(zeroes) do |result, animal|
result[animal.to_sym] = result[animal.to_sym] + 1
result
end
snakes = animals[:S]
mongeese = animals[:M]
small_animals = animals[:H] + animals[:R]
remaining_small_animals = small_animals > snakes ? small_animals - snakes : 0
{
snakes: {
quantity: snakes, area: snakes * 1200
},
mongeese: {
quantity: mongeese, area: mongeese * 800
},
small_animals: {
quantity: remaining_small_animals,
area: remaining_small_animals * 400
}
}
end
BOX_SIZES = {
B1: 400,
B2: 800,
B3: 1600
}.freeze
|
require 'rails_helper'
RSpec.describe CollectivesController, type: :controller do
let(:user) { create(:user) }
let(:file) { fixture_file_upload('files/image.png')}
before do
sign_in_as(user)
end
let(:valid_attributes) { {name: "collective name" , email: "collective@email.com",
address: "Street XXX, 192", phone: "123 1234 1234", about: "collective about",
facebook_link: "facebook.com/collective" , responsible: "collective responsible",
user_id: user.id, avatar: file, cover: file } }
let(:invalid_attributes) { {address: "Street XXX, 192",
phone: "123 1234 1234", about: "collective about", facebook_link: "facebook.com/collective" , responsible: "collective responsible" } }
let(:valid_session) { {} }
describe 'GET index' do
let!(:collectives) { create_list(:collective, 3).sort_by(&:created_at) }
it 'assigns collectives' do
get :index, { locale: 'pt-BR' }
expect(assigns(:collectives)).to match_array(collectives)
end
it 'comes paginated' do
get :index, { locale: 'pt-BR', page: 1, per_page: 2 }
expect(assigns(:collectives)).to match_array(collectives.last(2))
end
end
describe "GET #show" do
it "assigns the requested collective as @collective" do
collective = Collective.create! valid_attributes
get :show, {locale: 'pt-BR', :id => collective.to_param}, valid_session
expect(assigns(:collective)).to eq(collective)
end
end
describe "GET #new" do
it "assigns a new collective as @collective" do
get :new, {locale: 'pt-BR'}, valid_session
expect(assigns(:collective)).to be_a_new(Collective)
end
end
describe "GET #edit" do
it "assigns the requested collective as @collective" do
collective = Collective.create! valid_attributes
get :edit, {locale: 'pt-BR', :id => collective.to_param}, valid_session
expect(assigns(:collective)).to eq(collective)
end
end
describe "POST #create" do
context "with valid params" do
it "creates a new Collective" do
expect {
post :create, {locale: 'pt-BR', :collective => valid_attributes}, valid_session
}.to change(Collective, :count).by(1)
end
it "assigns a newly created collective as @collective" do
post :create, {locale: 'pt-BR', :collective => valid_attributes}, valid_session
expect(assigns(:collective)).to be_a(Collective)
expect(assigns(:collective)).to be_persisted
end
it "redirects to the created collective" do
post :create, {locale: 'pt-BR', :collective => valid_attributes}, valid_session
expect(response).to redirect_to(Collective.last)
end
end
context "with invalid params" do
it "assigns a newly created but unsaved collective as @collective" do
post :create, {locale: 'pt-BR', :collective => invalid_attributes}, valid_session
expect(assigns(:collective)).to be_a_new(Collective)
end
it "re-renders the 'new' template" do
post :create, {locale: 'pt-BR', :collective => invalid_attributes}, valid_session
expect(response).to render_template("new")
end
end
end
describe "PUT #update" do
context "with valid params" do
let(:new_attributes) { {name: "valid" , email: "collective@email.com",
address: "Street XXX, 192", phone: "123 1234 1234", about: "collective about",
facebook_link: "facebook.com/collective" , responsible: "collective responsible" } }
it "assigns the requested collective as @collective" do
collective = Collective.create! valid_attributes
put :update, {locale: 'pt-BR', :id => collective.to_param, :collective => valid_attributes}, valid_session
expect(assigns(:collective)).to eq(collective)
end
it "redirects to the collective" do
collective = Collective.create! valid_attributes
put :update, {locale: 'pt-BR', :id => collective.to_param, :collective => valid_attributes}, valid_session
expect(response).to redirect_to(collective)
end
end
context "with invalid params" do
it "assigns the collective as @collective" do
collective = Collective.create! valid_attributes
put :update, {locale: 'pt-BR', :id => collective.to_param, :collective => invalid_attributes}, valid_session
expect(assigns(:collective)).to eq(collective)
end
end
end
end
|
# loops_and_iterators.rb
# exercise answers to the chapter 'loops and iterators'
# exercise 1
puts 'It returns the array the same as it started: [1, 2, 3, 4, 5]'
# exercise 2
x = ''
while x != 'STOP' do
puts 'Do you want to stop?'
x = gets.chomp
end
# exercise 3
x = [2, 4, 6, 8]
x.each_with_index { |v, i| puts "#{i}: #{v}" }
# exercise 4
def countdown(number)
puts number
if number < 1
puts 'done'
else
countdown(number - 1)
end
end
countdown(9) |
class Visit < ActiveRecord::Base
belongs_to :page
#:location to store for example
#:parameters to store any parameters of the user ex utm
#:technology to store for example device, browser info, etc.
end
|
class QuickSort
# Quick sort has average case time complexity O(nlogn), but worst
# case O(n**2).
# Not in-place. Uses O(n) memory.
def self.sort1(array)
return array if array.length <= 1
pivot_idx = rand(array.length)
pivot = array[pivot_idx]
right = []
left = []
array.each_with_index do |el, idx|
if idx != pivot_idx
if array[idx] >= pivot
right.push(array[idx])
else
left.push(array[idx])
end
end
end
return self.sort1(left).push(pivot).concat(self.sort1(right))
end
# In-place.
def self.sort2!(array, start = 0, length = array.length, &prc)
prc ||= Proc.new{|x, y| x <=> y}
return array if length <= 1
barrier = self.partition(array, start, length, &prc)
self.sort2!(array, start, barrier - start, &prc)
self.sort2!(array, barrier + 1, length - barrier - 1, &prc)
end
def self.partition(array, start, length, &prc)
prc ||= Proc.new{|x, y| x <=> y}
pivot = array[start]
barrier = start
(start + 1...start + length).each do |idx|
if prc.call(pivot, array[idx]) == 1
barrier += 1
array[barrier], array[idx] = array[idx], array[barrier]
end
end
array[start], array[barrier] = array[barrier], array[start]
barrier
end
end
|
require 'rails_helper'
RSpec.describe SessionsController, type: :controller do
fixtures :users
fixtures :addresses
let(:user) { users(:user) }
describe 'GET #new' do
context 'when user is already logged in' do
before do
session[:user_id] = user.id
get :new
end
it 'redirects to logged in users page' do
expect(response).to redirect_to(user)
end
end
context 'when user is not logged in' do
before do
session[:user_id] = nil
get :new
end
it 'does not redirect' do
expect(response).to have_http_status(:ok)
end
end
end
describe 'POST #create' do
let(:email) { user.email }
let(:password) { 'password' }
let(:users_count) { User.count }
context 'when a user is already logged in' do
before do
session[:user_id] = user.id
post :create, params: { session: { email: email, password: password } }
end
it 'redirects to the users page' do
expect(response).to redirect_to(user)
end
end
context 'when a user is not logged in' do
let(:email) { user.email }
let(:password) { 'password' }
before do
session[:user_id] = nil
post :create, params: { session: { email: email, password: password } }
end
context 'when non-matching credentials are submitted' do
let(:password) { 'invalid' }
it 'redirects to login page' do
expect(response).to redirect_to(login_url)
end
it 'adds error to flash' do
expect(flash[:error]).to eq 'Login credentials did not match'
end
end
context 'when matching credentials are submitted' do
it 'redirects to user page' do
expect(response).to redirect_to(user)
end
it 'does not add error to flash' do
expect(flash[:error]).not_to eq 'Login credentials did not match'
end
it 'sets the current user' do
expect(session[:user_id]).to eq user.id
end
end
end
end
describe 'DELETE #destroy' do
before do
delete :destroy
end
context 'when a user logs out' do
it 'sets the logged in user to none' do
expect(session[:user_id]).to eq nil
end
it 'redirects to the login page' do
expect(response).to redirect_to(login_path)
end
end
end
end
|
class SellersController < ApplicationController
before_action :set_seller, only: [:edit, :update]
def new
if current_user.seller.present?
redirect_to action: :edit, id: current_user.seller
else
@seller = Seller.new
end
# @seller.bank_account.build
end
def create
@seller = Seller.new(seller_params)
if @seller.save
# 支払い受け取り用のStripeアカウント作成
account = Stripe::Account.create(
type: "custom",
country: "JP",
email: @seller.user.email,
legal_entity: {
address_kana: {
state: @seller.address_kana_state,
city: @seller.address_kana_city,
town: @seller.address_kana_town,
line1: @seller.address_kana_line,
postal_code: @seller.postal_code
},
address_kanji: {
state: @seller.address_kanji_state,
city: @seller.address_kanji_city,
town: @seller.address_kanji_town,
line1: @seller.address_kanji_line,
postal_code: @seller.postal_code
},
dob: {
day: @seller.date_of_birth.day,
month: @seller.date_of_birth.month,
year: @seller.date_of_birth.year
},
first_name_kana: @seller.first_name_kana,
first_name_kanji: @seller.first_name_kanji,
last_name_kana: @seller.last_name_kana,
last_name_kanji: @seller.last_name_kanji,
phone_number: @seller.phone_number,
gender: @seller.gender,
type: "individual",
},
tos_acceptance: {
date: Time.now.to_i,
ip: request.remote_ip
}
) unless @seller.stripe_account_id.present?
@seller.stripe_account_id = account.id
@seller.save
# Stbank_account = @seller.bank_account
# bank = account.external_accounts.create({
# external_account: {
# account_number: @seller.bank_account.account_number.to_s,
# country: "JP",
# currency: "JPY",
# account_holder_name: @seller.bank_account.name,
# account_holder_type: "individual",
# routing_number: @seller.bank_account.bank_code + @seller.bank_account.branch_code,
# object: "bank_account"
# }
# })
# @seller.bank_account.bank_account_id = bank.id
# bank_account.save
redirect_back_or new_ticket_path
else
render 'new'
end
rescue Stripe::InvalidRequestError,
Stripe::AuthenticationError,
Stripe::APIConnectionError,
Stripe::StripeError ,
Stripe::CardError => e
#stripe側でNGなので@sellerを削除
@seller.delete
flash[:alert] = e.message
render 'new'
end
def edit
# @seller.photo.cache! unless @seller.photo.blank?
end
def update
if @seller.update_attributes(seller_params)
flash[:success] = "プロフィールが更新されました"
redirect_to user_path(current_user)
else
render 'edit'
end
end
private
def set_seller
@seller = Seller.find(current_user.seller.id)
end
def seller_params
params.require(:seller).permit(
:photo,
:photo_cache,
:self_introduction,
:sns_info,
:address_kana_state,
:address_kana_city,
:address_kana_town,
:address_kana_line,
:postal_code,
:address_kanji_state,
:address_kanji_city,
:address_kanji_town,
:address_kanji_line,
:date_of_birth,
:date_of_birth,
:date_of_birth,
:first_name_kana,
:first_name_kanji,
:last_name_kana,
:last_name_kanji,
:phone_number,
:gender
).merge(user_id: current_user.id)
end
end
|
# frozen_string_literal: true
require 'test_helper'
class FactTest < ActiveSupport::TestCase
test 'valid from factory' do
assert build(:fact).valid?
end
### Associations
test 'has many happenings' do
f = create(:fact)
create(:happening)
create(:happening, fact: f)
assert_equal 1, f.happenings.count
end
### Validonions
test 'title are required' do
assert_not build(:fact, title: nil).valid?
end
test 'start_on are required' do
assert_not build(:fact, start_on: nil).valid?
end
test 'stop_on are required' do
assert_not build(:fact, stop_on: nil).valid?
end
### scope
test 'future scope' do
create :fact, start_on: Time.zone.today - 2.days, stop_on: Time.zone.today - 1.day
f2 = create :fact, start_on: Time.zone.today - 1.day, stop_on: Time.zone.today + 1.day
f3 = create :fact, start_on: Time.zone.today + 2.days, stop_on: Time.zone.today + 3.days
create :fact, start_on: Time.zone.today - 4.days, stop_on: Time.zone.today - 3.days
assert_equal 2, Fact.future.count
assert_equal f2, Fact.future.first
assert_equal f3, Fact.future.last
f3.update pinned: true
assert_equal f3, Fact.future.first
end
test 'history scope' do
f1 = create :fact, start_on: Time.zone.today - 2.days, stop_on: Time.zone.today - 1.day
create :fact, start_on: Time.zone.today - 1.day, stop_on: Time.zone.today + 1.day
create :fact, start_on: Time.zone.today + 2.days, stop_on: Time.zone.today + 3.days
f4 = create :fact, start_on: Time.zone.today - 4.days, stop_on: Time.zone.today - 3.days
assert_equal 2, Fact.history.count
assert_equal f1, Fact.history.first
assert_equal f4, Fact.history.last
end
end
|
class PusherController < ApplicationController
protect_from_forgery except: :auth
def auth
if current_user
response = Pusher[params[:channel_name]].authenticate(params[:socket_id])
render json: response
else
render json: {"Pusher don't do it" => "it's a trap!"}
end
end
end
|
require_relative 'svn'
module SVN
class Revision
attr_accessor :author,:date,:message,:revision_no
def self.make_from_xml_doc(doc)
revisions=[]
doc.css("logentry").each do |logentry|
revision=SVN::Revision.new
revision.revision_no=logentry.attributes["revision"].content
revision.author= logentry.at_css("author").content
revision.date= logentry.at_css("date").content
revision.message= logentry.at_css("msg").content
revisions <<revision
end
return revisions
end
def self.find_by_revision_number(revision_no)
xml=SVN.get_log(revision_no)
doc = Nokogiri::XML(xml)
SVN::Revision.make_from_xml_doc(doc).first
end
def self.search(search_term)
xml=SVN.search(search_term)
doc = Nokogiri::XML(xml)
SVN::Revision.make_from_xml_doc(doc)
end
def to_verified
SVN.merge_revision_from_verified(self.revision_no)
end
end
end
|
def nyc_pigeon_organizer(data)
hash = {}
data.each {|key, value|
key1 = key
value.each {|key, value|
key2 = key
value.each {|element|
if !hash.has_key?(element)
hash[element] = {}
end
if !hash[element].has_key?(key1)
hash[element][key1] = []
hash[element][key1] << "#{key2}"
else
hash[element][key1] << "#{key2}"
end
}
}
}
hash
end |
class NasaDayPresenter
attr_reader :start_date, :end_date
def initialize(dates)
@start_date = dates[:start_date].to_time.strftime('%B%e, %Y')
@end_date = dates[:end_date].to_time.strftime('%B%e, %Y')
dates = dates.transform_values do |date|
date.to_time.to_s.split(' ').first
end
@days = NasaDay.all_in_range(dates)
end
def most_dangerous
days.max do |a, b|
a.near_earth_objects.count <=> b.near_earth_objects.count
end
end
private
attr_reader :days
end
|
class OneToOnesController < ApplicationController
before_action :load_one_to_one
def show
if @one_to_one.attrs.present?
objects = [@one_to_one, @one_to_one.other_user(current_user).account, *@one_to_one.members]
objects += @one_to_one.paginate_messages(message_pagination_params) unless @one_to_one.pending?(current_user)
render_json objects
else
render_json @one_to_one.members
end
end
def update
update_params.each do |k,v|
@one_to_one.send("#{k}=", v)
end
# Reload the 1-1
@one_to_one = OneToOne.new(id: params[:id])
@one_to_one.viewer = current_user
if @one_to_one.valid? && @one_to_one.authorized?(current_user)
publish_updated_one_to_one
render_json @one_to_one
else
render_json []
end
end
private
def load_one_to_one
@one_to_one = OneToOne.new(id: params[:id])
@one_to_one.viewer = current_user
raise Peanut::Redis::RecordNotFound unless @one_to_one.valid? && @one_to_one.authorized?(current_user)
end
def update_params
params.permit(:last_seen_rank, :last_deleted_rank, :hidden, :request_status)
end
def publish_updated_one_to_one
faye_publisher.publish_one_to_one_to_user(current_user, OneToOneSerializer.new(@one_to_one, scope: current_user).as_json)
end
end
|
class V2::ObjectSerializer
include FastJsonapi::ObjectSerializer
set_key_transform :camel_lower
set_type :objects
attributes :subtype, :name, :author, :publisher, :periodical, :includedInDataCatalog, :version, :datePublished, :dateModified, :funder, :proxyIdentifiers, :registrantId
attribute :subtype do |object|
object["@type"]
end
attribute :datePublished do |object|
object.date_published
end
attribute :registrantId do |object|
object.registrant_id
end
end
|
class AuthorDecorator < ApplicationDecorator
def first_name
object.first_name * 3
end
def full_name
"#{object.first_name} #{object.last_name}"
end
end
|
class ProgramQuotasController < ApplicationController
before_action :authenticate_user!
load_and_authorize_resource
before_action :set_program_quota, only: [:show, :edit, :update, :destroy]
# GET /program_quotas
# GET /program_quotas.json
def index
@academic_year = AcademicYear.current
@program_quotas = @academic_year.program_quotas
end
# GET /program_quotas/1
# GET /program_quotas/1.json
def show
end
# GET /program_quotas/new
def new
@program_quota = ProgramQuota.new
end
# GET /program_quotas/1/edit
def edit
end
# POST /program_quotas
# POST /program_quotas.json
def create
@program_quota = ProgramQuota.new(program_quota_params)
respond_to do |format|
if @program_quota.save
format.html { redirect_to program_quotas_path, notice: 'Program quota was successfully created.' }
format.json { render :show, status: :created, location: @program_quota }
else
format.html { render :new }
format.json { render json: @program_quota.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /program_quotas/1
# PATCH/PUT /program_quotas/1.json
def update
respond_to do |format|
if @program_quota.update(program_quota_params)
format.html { redirect_to program_quotas_path, notice: 'Program quota was successfully updated.' }
format.json { render :show, status: :ok, location: @program_quota }
else
format.html { render :edit }
format.json { render json: @program_quota.errors, status: :unprocessable_entity }
end
end
end
# DELETE /program_quotas/1
# DELETE /program_quotas/1.json
def destroy
@program_quota.destroy
respond_to do |format|
format.html { redirect_to program_quotas_url, notice: 'Program quota was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_program_quota
@program_quota = ProgramQuota.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def program_quota_params
params.require(:program_quota).permit(:academic_year_id, :program_id, :university_id, :quota)
end
end
|
class AddFieldsToDevices < ActiveRecord::Migration
def change
add_column :devices, :token, :string, unique: true # The Apple or Google generated token used to deliver messages to the APNs or GCM push networks
add_column :devices, :type, :string # e.g. 'ios', 'android', 'winrt', 'winphone', or 'dotnet'
end
end
|
(1..99).each do |num|
next if num.even?
puts num
end |
require_relative 'game_board'
class DisplayBoard
attr_reader :board_layout, :row_label, :column_label, :board
def initialize(board)
@board_layout = Array.new(4, " ").map{|row| Array.new(4, " ")}
@row_label = ["A", "B", "C", "D"]
@column_label = ["1", "2", "3", "4"]
@board = board
end
def render_board
print "\t"
print @column_label.join("\t")
print "\n"
puts
@board_layout.each_with_index do |row, index|
print @row_label[index]
print "\t"
print row.join("\t")
print "\n"
puts
end
end
def render_shot(coordinate)
shots = @board.all_shots.sort
#require "pry"; binding.pry
shots.each do |coordinate|
row = @row_label.index(coordinate[0])
column = @column_label.index(coordinate[1])
if @board.winning_coordinates.flatten.include?(coordinate)
@board_layout[row][column] = 'H'
render_board
else
@board_layout[row][column] = 'M'
render_board
end
end
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
include Pundit
force_ssl if: :staging_or_production_or_sales?
before_action :create_search
def after_sign_in_path_for(resource)
if resource.respond_to?(:wizard_step) && resource.wizard_step != Wicked::FINISH_STEP
create_profile_path(resource.wizard_step || Wicked::FIRST_STEP)
else
stored_location_for(resource) || signed_in_root_path(resource)
end
end
protected
def staging_or_production_or_sales?
(Rails.env.staging? || Rails.env.production? || Rails.env.sales?) && action_name !=
'health_check'
end
def create_search
@search = Search.new search_params
end
def search_params
sanitize_array_param :position_ids
sanitize_array_param :project_type_ids
sanitize_array_param :customer_name_ids
sanitize_array_param :certification_ids
sanitize_param :clearance_level_id
sanitize_param :address
sanitize_param :q
params.permit(search: [:address, :q, :clearance_level_id, position_ids: [],
customer_name_ids: [], project_type_ids: [],
certification_ids: []])[:search]
end
def sanitize_array_param(key)
return unless params.key? :search
params[:search][key] ||= []
params[:search][key].delete ''
end
def sanitize_param(key)
params[:search][key] = nil if params[:search] && params[:search][key].blank?
end
def pundit_user
current_consultant || current_user
end
def auth_a_user!
if consultant_signed_in?
authenticate_consultant!
else
authenticate_user!
end
end
end
|
module CsvRowModel
module Import
# Abstraction of Ruby's CSV library. Keeps current row and line_number, skips empty rows, handles errors.
class Csv
# @return [String] the file path of the CSV
attr_reader :file_path
# @return [Integer, nil] return `0` at start of file, `1 to infinity` is line_number of row_model, `nil` is end of file (row is also `nil`)
attr_reader :line_number
# @return [Array, nil] the current row, or nil at the beginning or end of file
attr_reader :current_row
include ActiveModel::Validations
validate { begin; _ruby_csv; rescue => e; errors.add(:csv, e.message) end }
def initialize(file_path)
@file_path = file_path
reset
end
# http://stackoverflow.com/questions/2650517/count-the-number-of-lines-in-a-file-without-reading-entire-file-into-memory
# @return [Integer] the number of rows in the file, including empty new lines
def size
@size ||= `wc -l #{file_path}`.split[0].to_i + 1
end
# If the current position is at the headers, skip it and return it. Otherwise, only return false.
# @return [Boolean, Array] returns false, if header is already skipped, otherwise returns the header
def skip_headers
start_of_file? ? (@headers = read_row) : false
end
# Returns the header __without__ changing the position of the CSV
# @return [Array, nil] the header
def headers
@headers ||= next_row
end
# Resets the file to the start of file
def reset
return false unless valid?
@line_number = 0
@headers = @current_row = @next_row = @skipped_rows = @next_skipped_rows = nil
@ruby_csv.try(:close)
@ruby_csv = _ruby_csv
true
end
# @return [Boolean] true, if the current position is at the start of the file
def start_of_file?
line_number == 0
end
# @return [Boolean] true, if the current position is at the end of the file
def end_of_file?
line_number.nil?
end
# Returns the next row __without__ changing the position of the CSV
# @return [Array, nil] the next row, or `nil` at the end of file
def next_row
@next_row ||= _read_row
end
# Returns the next row, while changing the position of the CSV
# @return [Array, nil] the changed current row, or `nil` at the end of file
def read_row
return if end_of_file?
@current_row = @next_row || _read_row
@line_number = current_row.nil? ? nil : @line_number + 1
@next_row = nil
current_row
end
protected
def _ruby_csv
CSV.open(file_path)
end
def _read_row
return unless valid?
@ruby_csv.readline.tap { |row| @headers ||= row }
rescue Exception => e
changed = e.exception(e.message.gsub(/line \d+\.?/, "line #{line_number + 1}.")) # line numbers are usually off
changed.set_backtrace(e.backtrace)
changed
end
end
end
end
|
# frozen_string_literal: true
FactoryGirl.define do
factory :game do
transient do
number_of_users 0
end
after(:create) do |game, evaluator|
create_list(:user, evaluator.number_of_users).each do |user|
create(:games_users, game: game, user: user)
end
end
end
end
|
class TagsController < ApplicationController
def show
@tag = Tag.find_by(name: params[:id])
@tutorials = @tag.tutorials
end
end |
module AdminArea::People::Cell
class Show < Show.superclass
# Takes the person, shows their card accounts. Has a header that says
# 'Accounts' and a link to add a new CA for the person. If there aren't any
# CAs, there'll be a <p> that tells you so. If there are CAs, they'll be
# listed in a <table>.
#
# @!method self.call(person, options = {})
# @param person [Person] make sure that card_accounts => product => bank
# is eager-loaded.
class CardAccounts < Abroaders::Cell::Base
property :card_accounts
private
def link_to_add_new
link_to raw('+ Add'), new_admin_person_card_account_path(model)
end
def table_rows
cell(Row, collection: card_accounts)
end
def table_tag(&block)
content_tag(
:table,
class: 'table table-striped tablesorter',
id: 'admin_person_card_accounts_table',
&block
)
end
# @!method self.call(card_account)
# @param card [CardAccount]
class Row < Abroaders::Cell::Base
include Escaped
property :id
property :card_product
property :closed_on
property :offer
property :opened_on
property :recommended?
private
delegate :bp, to: :card_product, prefix: true
def card_product_name
cell(CardProduct::Cell::FullName, card_product, with_bank: true)
end
def link_to_edit
link_to 'Edit', edit_admin_card_account_path(model)
end
def link_to_offer
if offer.nil?
'-'
else
link_to offer_identifier, admin_offer_path(offer)
end
end
# If the card was opened/closed after being recommended by an admin,
# we know the exact date it was opened closed. If they added the card
# themselves (e.g. when onboarding), they only provide the month
# and year, and we save the date as the 1st of thet month. So if the
# card was added as a recommendation, show the the full date, otherwise
# show e.g. "Jan 2016". If the date is blank, show '-'
#
# TODO rethink how we know whether a card was added in the survey
%i[closed_on opened_on].each do |date_attr|
define_method date_attr do
if model.recommended?
super()&.strftime('%D') || '-' # 12/01/2015
else
super()&.strftime('%b %Y') || '-' # Dec 2015
end
end
end
def tr_tag(&block)
content_tag(
:tr,
id: "card_account_#{id}",
class: 'card_account',
'data-bp': card_product.bp,
'data-bank': card_product.bank_id,
&block
)
end
def offer_identifier
cell(AdminArea::Offers::Cell::Identifier, offer, with_partner: true)
end
end
end
end
end
|
#!/usr/bin/env ruby
require('base64')
require('resque')
# This adds a characterize job to the queue for every id on stdin
# (ids are separated by newlines)
class CharacterizeJob
def initialize(pid)
@pid = pid
end
def queue_name
:characterize
end
end
module Sufia
module Resque
class Queue
def push(job)
queue = job.queue_name
::Resque.enqueue_to queue, MarshaledJob, Base64.encode64(Marshal.dump(job))
end
end
class MarshaledJob
end
end
end
redis_host_port = ENV['REDIS_HOST_PORT']
if redis_host_port.nil?
abort("REDIS_HOST_PORT unset")
end
Resque.redis = redis_host_port
queue = Sufia::Resque::Queue.new
STDIN.each do |line|
queue.push(CharacterizeJob.new(line.strip))
end
|
module ApplicationHelper
def hidden_div_if(condition, attributes = {}, &block)
if condition
attributes["style"] = "display: none"
end
content_tag("div", attributes, &block)
end
def full_title(page_title = '')
base_title = "AK Smart GSM"
if page_title.empty?
base_title
else
page_title + " | " + base_title
end
end
def dynamically_update_products
@products = Product.paginate(:page => params[:page], :per_page => 9).order(:title)
ActionCable.server.broadcast 'products',
html: render_to_string('store/index', layout: false)
ActionCable.server.broadcast 'products',
html: render_to_string('store/smartphones', layout: false)
end
end |
class PurchasesCart
attr_accessor :user, :purchase_amount_cents,
:purchase_amount, :success,
:payment, :expected_ticket_ids,
:stripe_token, :stripe_charge
def initialize(user:, stripe_token:, purchase_amount_cents:,
expected_ticket_ids:)
@user = user
@purchase_amount = Money.new(purchase_amount_cents)
@success = false
@continue = true
@expected_ticket_ids = expected_ticket_ids.split(" ").map(&:to_i).sort
@stripe_token = stripe_token
end
def run
Payment.transaction do
pre_purchase
purchase
post_purchase
@success = @continue
end
rescue ActiveRecord::ActiveRecordError => e
Rails.logger.error("ACTIVE RECORD ERROR IN TRANSACTION")
Rails.logger.error(e)
end
def pre_purchase
unless pre_purchase_valid?
@continue = false
return
end
purchase_tickets
create_payment
@continue = true
end
def pre_purchase_valid?
purchase_amount == tickets.map(&:price).sum &&
expected_ticket_ids == tickets.map(&:id).sort
end
def tickets
@tickets ||= @user.tickets_in_cart
end
def purchase_tickets
tickets.each(&:purchased!)
end
def create_payment
self.payment = Payment.create!(payment_attributes)
payment.create_line_items(tickets)
end
def payment_attributes
{user_id: user.id, price_cents: purchase_amount.cents,
status: "created", reference: Payment.generate_reference,
payment_method: "stripe"}
end
def purchase
return unless @continue
@stripe_charge = StripeCharge.new(token: stripe_token, payment: payment)
@stripe_charge.charge
payment.update!(@stripe_charge.payment_attributes)
reverse_purchase if payment.failed?
end
def charge
charge = StripeCharge.charge(token: stripe_token, payment: payment)
payment.update!(
status: charge.status, response_id: charge.id,
full_response: charge.to_json)
end
def calculate_success
payment.succeeded?
end
def post_purchase
return unless @continue
@continue = calculate_success
end
def calculate_success
payment.succeeded?
end
def post_purchase
return unless @continue
@continue = calculate_success
end
def unpurchase_tickets
tickets.each(&:waiting!)
end
def reverse_purchase
unpurchase_tickets
@continue = false
end
end
|
class CustomerAccount < Plutus::Liability
has_one :user
validates_presence_of :user
# Force the name of this customer account.
before_validation do
self.name = "Customer #{user.id} Account"
end
def transaction_count
credit_entries.count + debit_entries.count
end
def sale_entries
credit_entries.where(type: PurchaseEntry)
end
def withdrawal_entries
debit_entries.where(type: WithdrawalEntry)
end
end
|
class Post
include Mongoid::Document
field :title, type: String
field :body, type: String
field :author, type: String
field :created_at, type: Time
field :updated_at, type: Time
validates_presence_of :title
validates_uniqueness_of :title
validates_presence_of :author
validates_presence_of :body
belongs_to :user
end
|
# frozen_string_literal: true
require "test_helper"
module TTY
class Fzy
class SearchTest < Minitest::Test
ChoiceMock = Struct.new(:text) do
alias returns text
end
def test_push
search.push("a")
assert_equal ["a"], search.query
end
def test_push_in_different_spot
search.query = %w(a b c d e)
search.right
search.right
assert_equal 2, search.position
search.push("f")
assert_equal %w(a b f c d e), search.query
end
def test_delete
search.query = %w(a)
search.left
search.delete
assert_empty search.query
end
def test_delete_in_different_spot
search.query = %w(a b c d e)
search.right
search.right
search.delete
assert_equal %w(a b d e), search.query
end
def test_backspace
search.query = %w(a)
search.right
search.backspace
assert_empty search.query
end
def test_backspace_in_different_spot
search.query = %w(a b c d e)
search.right
search.right
search.backspace
assert_equal %w(a c d e), search.query
end
def test_clear
search.push("a")
search.clear
assert_empty search.query
end
def test_autocomplete
search.autocomplete(ChoiceMock.new("thing"))
assert_equal %w(t h i n g), search.query
end
def test_backspace_word
search.autocomplete(ChoiceMock.new("ab cd"))
search.backspace_word
assert_equal %w(a b), search.query
end
def test_right_when_empty
search.right
assert_equal 0, search.position
end
def test_right
search.autocomplete(ChoiceMock.new("ab"))
search.left
assert_equal 1, search.position
search.right
assert_equal 2, search.position
end
def test_left_when_empty
search.left
assert_equal 0, search.position
end
def test_left
search.autocomplete(ChoiceMock.new("ab"))
search.left
assert_equal 1, search.position
end
def test_render
search.autocomplete(ChoiceMock.new("a"))
output.rewind
assert_equal(
"#{TTY::Cursor.clear_line}❯ a#{TTY::Cursor.column(4)}", output.read
)
end
private
def search
@search ||= begin
TTY::Fzy.configure do |config|
config.output = StringIO.new
end
TTY::Fzy::Search.new
end
end
def output
TTY::Fzy.config.output
end
end
end
end
|
module Api
class SessionsController < ApplicationController
skip_before_filter :authorize, :only => [:login]
def login
if params[:email] && params[:password]
email = params[:email].downcase
password = params[:password]
user = User.find_by_email(email.downcase)
if user && user.authenticate(password)
render :json => { :api_token => user.remember_token }
else
render :json => { :message => "Could not authenticate the user" }, :status => 401
end
else
render :json => { :message => "You have to provide email and password" }, :status => 401
end
end
end
end
|
module ActiveRecord
class Base
class << self
def each(limit = 1000)
rows = find(:all, :conditions => ["id > ?", 0], :limit => limit)
until rows.blank?
rows.each { |record| yield record }
rows = find(:all, :conditions => ["id > ?", rows.last.id], :limit => limit)
end
self
end
# Skips given callbacks for the duration of the passed block
def skip_callback(*callbacks, &block)
callbacks.extract_options!
callback_methods = {}
callbacks.each do |callback|
if respond_to?(callback)
callback_methods[callback] = instance_method(callback)
remove_method(callback)
end
define_method(callback){ true }
end
yield
callbacks.each do |callback|
remove_method(callback)
define_method(callback, callback_methods[callback]) if respond_to?(callback)
end
end
alias_method :skip_callbacks, :skip_callback
# List of internally used attributes. Used as a way of privatising attributes.
def attr_internal(*attributes)
write_inheritable_attribute(:attr_internal, Set.new(attributes.map(&:to_s)) + (internal_attributes || []))
end
def internal_attributes
read_inheritable_attribute(:attr_internal)
end
# attributes and instance methods to be included as attributes in #public_attributes
def attr_definable(*attributes)
new_attributes = attributes.extract_options!
write_inheritable_attribute(:attr_definable, Set.new(attributes.map(&:to_s)) + (defined_attributes || []))
write_inheritable_hash(:attr_definable_method, new_attributes.merge(defined_method_attributes || {}))
end
def defined_method_attributes
read_inheritable_attribute(:attr_definable_method) || {}
end
def defined_attributes
read_inheritable_attribute(:attr_definable) || []
end
end
# Returns all public model attributes, without internal_attributes and with attribute_methods
def public_attributes
attrs = attributes.except *self.class.internal_attributes
attrs.merge self.class.defined_attributes.collect { |method| { method => send(method) } }.first
self.class.defined_method_attributes.each { |key,val| attrs[key] = instance_eval(val) }
attrs
end
# Overrides AR::clone, so that we can optional specify an array of keys to clone
# or pass a hash with ability to include (:only) or exclude (:except) specific
# attributes
def clone(*args)
options = args.extract_options!
options[:only] ||= args
attrs = clone_attributes(:read_attribute_before_type_cast)
attrs.delete(self.class.primary_key)
unless options[:only].blank?
attrs.delete_if do |key, value|
!options[:only].include? key.to_sym
end
end
unless options[:except].blank?
attrs.delete_if do |key, value|
options[:except].include? key.to_sym
end
end
record = self.class.new
record.send :instance_variable_set, '@attributes', attrs
record
end
end
module Timestamp
# Overwrites touch and uses +update_all+ to ensure no callbacks are called
def touch(attribute = nil)
current_time = current_time_from_proper_timezone
if attribute
self.class.update_all({ attribute => current_time }, { :id => self.id })
write_attribute(attribute, current_time)
else
self.class.update_all({ 'updated_at' => current_time }, { :id => self.id }) if respond_to?(:updated_at)
self.class.update_all({ 'updated_on' => current_time }, { :id => self.id }) if respond_to?(:updated_on)
end
end
end
module ConnectionAdapters
class TableDefinition
def counter_cache(*args)
args.each { |col| column("#{col}_count", :integer, :default => 0) }
end
alias :counter_caches :counter_cache
alias :refs :references
alias :bool :boolean
end
module SchemaStatements
def create_table(table_name, options = {})
table_definition = TableDefinition.new(self)
table_definition.primary_key(options[:primary_key] || Base.get_primary_key(table_name)) unless options[:id] == false
yield table_definition
# this is what we've added, so we don't have to specify t.timestamps every time
table_definition.timestamps unless options[:timestamps] == false
if options[:force] && table_exists?(table_name)
drop_table(table_name, options)
end
create_sql = "CREATE#{' TEMPORARY' if options[:temporary]} TABLE "
create_sql << "#{quote_table_name(table_name)} ("
create_sql << table_definition.to_sql
create_sql << ") #{options[:options]}"
execute create_sql
end
def load_fixture(*filename)
Fixtures.create_fixtures(File.join(RAILS_ROOT, 'test/fixtures'), filename)
end
def load_data(*filename)
Fixtures.create_fixtures(File.join(RAILS_ROOT, 'db/data'), filename)
end
end
end
end
# require 'active_record/fixtures' |
Rails.application.routes.draw do
resources :countdowns, only: [:new, :create, :show]
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
root 'countdowns#new'
end
|
module EtCms
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
# attr_accessible :title, :body
after_create { |user| user.send_reset_password_instructions if user.password.nil? } unless ['test'].include? Rails.env
def password_required?
new_record? ? false : super
end
end
end
|
# == Schema Information
#
# Table name: suggested_surfspots
#
# id :integer(4) not null, primary key
# user_id :integer(4) not null
# name :string(255)
# city :string(255)
# state :string(255)
# tag :string(255)
# comments :text
# processed :boolean(1) default(FALSE)
# created_at :datetime
# updated_at :datetime
#
class SuggestedSurfspot < ActiveRecord::Base
belongs_to :user
STRING_FIELDS = %w(name city state comments)
validates_presence_of :name, :city, :state
validates_length_of STRING_FIELDS, :maximum => Surftrottr::Application.config.db_string_max_length
# Return the full name of a location.
def full_name
[name, city, state].join(", ")
end
# Archive a suggested surfspot, i.e. mark it as processed.
def archive!
self.processed = true
self.save
end
end
|
class DashBoard < ApplicationRecord
has_many :link_details
end
|
module MaterializeComponents
class Base
include ActionView::Helpers::TagHelper
attr_accessor :css_class
# Sets the style of an element
#
# @param [String] css_style The Style rule to add
# @return [self] Returns a reference to self
def style(css_style = '')
@style = css_style
return self
end
# Adds HTML Attributes
#
# @param [Hash] attributes A hash of HTML Attributes
# @return [self] Returns a reference to self
def attr(attributes = {})
@attr = @attr || {}
(attributes.is_a?(Hash)) ? @attr.merge!(attributes) : raise(InvalidInput.new(:hash, 'attr'))
return self
end
# Sets the ID of the generated element
#
# @param [String] id The ID for the element
# @return [self] Returns a reference to self
def id(id)
attr(id: id)
return self
end
# Adds a class
#
# @param [String] c The class to add to the element
# @return [self] Returns a reference to self
def add_class(c = "")
@css_class << c
return self
end
def remove_class c
@css_class.delete(c)
return self
end
# Sets the content
#
# @param [String] content The content to be placed in the element
# @return [self] Returns a reference to self
def content(content = "")
@content = content
return self
end
# Prints the actual element
#
# @return [self] Returns the HTML for the element
def to_s
content_tag(@tag, output.html_safe, html_attributes)
end
def reset
@style = ""
@css_class = []
self
end
private
def html_attributes
@attr = (!@attr.is_a?(Hash) ? {} : @attr)
@attr.merge(style: @style, class: @css_class.delete_if(&:blank?).join(' ').strip)
end
def output
@content.blank? ? "" : @content.to_s
end
end
end
|
class Resources::ArticlesController < ResourcesController
def index
@articles = Restful::Article.all options.merge({:conditions => ['status = ?', 'published']})
return unless stale? :etag => @articles, :public => true
respond_to do |format|
format.json { render :json => @articles }
format.xml { render :xml => @articles }
end
end
def show
@article = Restful::Article.find params[:id]
return unless stale? :etag => @article, :public => true
respond_to do |format|
format.json { render :json => @article }
format.xml { render :xml => @article }
end
end
end
|
require 'spec_helper'
require 'camify'
describe Camify do
subject {described_class.new}
describe '#process' do
let(:input) do
%q{my first ruby gem.}
end
let(:lower_case) do
%q{abcdefghijklmnopqrstuvwxyz}
end
let(:output) { subject.process(input) }
it 'converts conventional letters to letters with weird accents' do
expected = "m̃ɏ ᶂįřšť řǔᶀɏ ǧěm̃."
expect(output). to eq expected
end
let(:lower_output) { subject.process(lower_case) }
it 'can convert any lowercase letter to an accented letter' do
expected = "ǎᶀčďěᶂǧȟįǰǩľm̃ňǒp̃ʠřšťǔṽẘx̌ɏž"
expect(lower_output). to eq expected
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.