text stringlengths 10 2.61M |
|---|
require './game'
describe Game do
let(:game) { Game.new }
# perfect game
it 'can roll all strikes' do
12.times { game.roll(10) }
expect(game.scorecard).to eq 300
end
# guttter game
it 'can roll all 0s ' do
20.times { game.roll(0) }
expect(game.scorecard).to eq 0
end
# spares game
it 'can roll all spares ' do
21.times { game.roll(5) }
expect(game.scorecard).to eq 150
end
# rolling a strike
it 'can roll a strike ' do
game.roll(10)
game.roll(1)
game.roll(1)
16.times { game.roll(0) }
expect(game.scorecard).to eq 14
end
# rolling a spare
it 'can roll a spare ' do
game.roll(5)
game.roll(5)
game.roll(2)
17.times { game.roll(0) }
expect(game.scorecard).to eq 14
end
# normal game
it ' can roll a normal game' do
game.roll(3)
game.roll(5)
18.times { game.roll(0) }
expect(game.scorecard).to eq 8
end
end
|
class Category
attr_accessor :name, :min, :max, :avg, :ranking
def initialize(name)
@name = name
@min = 100000
@max = 0
@avg = 0
@ranking = []
end
def to_s
"#{@name} (#{@min} to #{@max}, avg: #{@avg})"
end
end |
require 'rails_helper'
RSpec.describe Doctor, type: :model do
context 'associations' do
it { should have_and_belong_to_many(:teams) }
it { should have_many(:patients) }
end
end
|
class Image < ApplicationRecord
has_many :images_users
has_many :users, through: :images_users
validates :url, format: {
with: /https?:\/\/(www\.)?\w+\.\w{2,}(\/\w*)*/,
}
end
|
require 'test_helper'
class ChefsEditTest < ActionDispatch::IntegrationTest
def setup
@chef = Chef.create!(chefname: "mashrur", email: "vincent@example.com",
password: "password", password_confirmation: "password")
@chef2 = Chef.create!(chefname: "vincent2", email: "vincent2@example.com",
password: "password", password_confirmation: "password")
@admin_user = Chef.create!(chefname: "vincent3", email: "vincent3@example.com",
password: "password", password_confirmation: "password", admin: true)
end
test "reject an invalid edit" do
sign_in_as(@chef, "password")
get edit_chef_path(@chef)
assert_template "chefs/edit"
#patch chef_path(@chef), params: { chef: {chefname: " ", email: " ", password: "password",
# password_confirmation: "password confirmation" }}
patch chef_path(@chef), params: { chef: {chefname: " ", email: " " }}
#Although This above test wil not require a password test, you will still get an error when you run rails test
#To resolve go to models/chef.rb line11 validates :password.. at the end add "allow_nil: true"
assert_template "chefs/edit"
assert_select "h2.panel-title" #These are both error messages..
#assert_select "div.panel.body"
end
test "accept a valid edit" do
sign_in_as(@chef, "password")
get edit_chef_path(@chef)
assert_template "chefs/edit"
patch chef_path(@chef), params: { chef: {chefname: "vincent1", email: "vincent1@example.com" }}
assert_redirected_to @chef # This is another way of pointing to - "chefs/show"
assert_not flash.empty?
@chef.reload # nned to reload @chef instance variable, once reloaded must match line 26, see below:
assert_match "vincent1", @chef.chefname
assert_match "vincent1@example.com", @chef.email
end
#Tests below createted to tesst Admin functionality
test "accept edit attempt by admin user" do
sign_in_as(@admin_user, "password")
get edit_chef_path(@chef)
assert_template "chefs/edit"
patch chef_path(@chef), params: { chef: {chefname: "vincethewalker", email: "vincethewalker@example.com" }} #These names I want to edit to in the test must match both the "assert_match" below
assert_redirected_to @chef # This is another way of pointing to - "chefs/show"
assert_not flash.empty?
@chef.reload # need to reload @chef instance variable, once reloaded must match line 26, see below:
assert_match "vincethewalker", @chef.chefname #must match patch chef_path name
assert_match "vincethewalker@example.com", @chef.email #must match patch chef_path email
end
test "redirect edit attempt by another non-admin user" do
sign_in_as(@chef2, "password")
updated_name = "vinnie"
updated_email = "vinnie@example.com"
patch chef_path(@chef), params: { chef: {chefname: updated_name, email: updated_email }}
assert_redirected_to chefs_path # Ref chefs_controller line65 equire_same_user = requires: chefs_path
assert_not flash.empty?
@chef.reload # nned to reload @chef instance variable, once reloaded must match line 26, see below:
assert_match "mashrur", @chef.chefname #as per @chef details
assert_match "vincent@example.com", @chef.email #as per @chef details
end
end
|
require 'spec_helper'
describe RegistrationsController do
before(:each) do
@u1 = create(:user,
:password => '11111111', :password_confirmation => '11111111'
)
@u2 = create(:user)
@request.env["devise.mapping"] = Devise.mappings[:user]
sign_in(@u1)
end
context "when editing own account" do
it "should update name" do
put :update, :id => @u1.id, :user => {
:email => @u1.email, :name => 'ZZ'
}
response.should redirect_to(admin_root_url)
end
it "should update password" do
put :update, :id => @u1.id, :user => {
:email => @u1.email, :name => @u1.name,
:password => '22222222', :password_confirmation => '22222222',
:current_password => '11111111'
}
response.should redirect_to(admin_root_url)
end
it "should not update that account if not valid" do
put :update, :id => @u1.id, :user => {
:email => @u1.email, :name => nil
}
response.should render_template("edit")
end
end
context "when editing another user's account" do
it "should not update that account" do
put :update, :id => @u2.id, :user => {
:email => @u1.email, :name => 'ZZ'
}
@u2.reload.name.should_not == 'ZZ'
end
end
end |
class Song < ActiveRecord::Base
include PublicActivity::Model
tracked owner: Proc.new{ |controller, model| controller.current_user }, only: :create
after_save :parse_notes
before_save :set_creator
has_many :notes
has_many :posts
has_many :user_song_preferences
belongs_to :origin_church, :class_name => "Church", :foreign_key => "origin_church_id"
belongs_to :creator, :class_name => "User", :foreign_key => "created_by"
validates :key, :title, :content, :presence => true
def Song.match_note
match_note = /\[([A-Za-z].*?)\]/
end
def set_creator
self.creator ||= User.current
if u = User.current and u.church.present?
self.origin_church ||= u.church
end
end
def user_song_preference(user)
if user
any_song_preference = self.user_song_preferences.where(:user_id => user.id).first
unless any_song_preference
any_song_preference = UserSongPreference.create({
:user_id => user.id,
:prefered_key => self.key,
:song_id => self.id
})
end
any_song_preference
end
end
def prefered_key(user)
prefered_key = key
usp = user_song_preference(user)
if usp
prefered_key = usp.prefered_key
end
prefered_key
end
def prefered_capo(user)
prefered_capo = 0
usp = user_song_preference(user)
if usp and usp.prefered_capo
prefered_capo = usp.prefered_capo
end
prefered_capo
end
def parse_notes
unless @disable_callback
theContent = self.content
rows = theContent.split("\n")
rows = rows.map{|line| line.gsub(/\r\n|\r|\n/, '')}.reject{|line| line.blank?}.compact
notes = []
rows.each_with_index do |row, row_index|
notes[row_index] = {}
previous_to_remove_caracters_length = 0
row.scan(Song.match_note) do
if $1
positions = $~.offset(1)[0] - previous_to_remove_caracters_length
notes[row_index][positions] = $1
previous_to_remove_caracters_length += $1.size + 2
end
end
end
# Destroy previous notes
Note.where(song_id: self.id).delete_all
notes.each_with_index do |row_notes, row_index|
row_notes.each do |note_offset, note|
Note.create({
:song_id => self.id,
:note => note,
:offset => note_offset,
:line => (row_index + 1)
})
end
end
@disable_callback = true
Song.public_activity_off
self.update_attribute('clean_content', self.content.gsub(Song.match_note,''))
Song.public_activity_on
@disable_callback = false
end
end
def onsong_clean_content(usp=nil)
onsong_content = "{t:#{self.title}}\n"
onsong_content += "{a:#{self.author} | extrait de burnup.fr}\n"
if usp
onsong_content += "{k:#{usp.prefered_key}}\n"
onsong_content += "{capo:#{usp.prefered_capo}}\n"
else
onsong_content += "{k:#{self.key}}\n"
end
onsong_content += "{tempo:#{self.bpm}}\n"
onsong_content += content
#onsong_content = onsong_content.gsub(/^(\s)*\n/,'')
onsong_content = onsong_content.gsub(/(Couplet [1-9]:)/,'{c:\1}')
onsong_content = onsong_content.gsub(/(Refrain:)/,'{c:\1}')
onsong_content = onsong_content.gsub(/(Pre-refrain:)/,'{c:\1}')
onsong_content = onsong_content.gsub(/(Pre-Refrain:)/,'{c:\1}')
onsong_content = onsong_content.gsub(/(Choeur:)/,'{c:\1}')
onsong_content = onsong_content.gsub(/(Pont:)/,'{c:\1}')
#onsong_content = onsong_content.gsub(/^(\s)*\n/,'<span class="section-padder"> </span><br/>')
# # Remove empty lines
# onsong_content = onsong_content.split("\n")
# onsong_content = onsong_content.map{|line| line.gsub(/\r\n|\r|\n/, '')}.reject{|line| line.blank?}.compact
#
# onsong_content = onsong_content.map{|line| "<div class=\'song-line\'>#{line}</div>"}.join("")
# # onsong_content = onsong_content.gsub("\n","<br/><br/>")
#
# onsong_content = onsong_content.gsub(Song.match_note,'<span class="content-note" data-note="\1"> </span>')
onsong_content
end
def clean_html_content
html_content = content
#html_content = html_content.gsub(/^(\s)*\n/,'')
html_content = html_content.gsub(" "," ")
html_content = html_content.gsub(/(Couplet [1-9]:)/,'<span class="song-section-title">\1</span>')
html_content = html_content.gsub(/(Refrain:)/,'<span class="song-section-title">\1</span>')
html_content = html_content.gsub(/(Pre-refrain:)/,'<span class="song-section-title">\1</span>')
html_content = html_content.gsub(/(Pre-Refrain:)/,'<span class="song-section-title">\1</span>')
html_content = html_content.gsub(/(Choeur:)/,'<span class="song-section-title">\1</span>')
html_content = html_content.gsub(/(Pont:)/,'<span class="song-section-title">\1</span>')
#html_content = html_content.gsub(/^(\s)*\n/,'<span class="section-padder"> </span><br/>')
# Remove empty lines
html_content = html_content.split("\n")
html_content = html_content.map{|line| line.gsub(/\r\n|\r|\n/, '')}.reject{|line| line.blank?}.compact
html_content = html_content.map{|line| "<div class=\'song-line\'>#{line}</div>"}.join("")
# html_content = html_content.gsub("\n","<br/><br/>")
html_content = html_content.gsub(Song.match_note,'<span class="content-note" data-note="\1"> </span>')
html_content
end
def self.notes
[
["B"],
["A#", "Bb"],
["A"],
["G#", "Ab"],
["G"],
["F#", "Gb"],
["F"],
["E"],
["D#", "Eb"],
["D"],
["C#", "Db"],
["C"]
].reverse
end
def self.base_notes
["A", "B", "C", "D", "E", "F", "G"]
end
def self.chords
[
["C"],
["B"],
["A#", "Bb"],
["A"],
["G#", "Ab"],
["G"],
["F#", "Gb"],
["F"],
["E"],
["D#", "Eb"],
["D"],
["C#", "Db"]
]
end
def self.sharp_notes
self.base_notes - ["E", "B"]
end
def self.flat_notes
self.base_notes - ["C", "F"]
end
def available_keys
first_key = self.key.present? ? self.key : "C"
available_keys = [first_key]
initial_key_index = Song.reverse_chord_index(first_key)
key_index = initial_key_index + 1
while key_index != initial_key_index
key_value = Song.chord_value(key_index,first_key, {:reverse => true})
available_keys << key_value
if key_index < (Song.chords.size - 1)
key_index += 1
else
key_index = 0
end
end
available_keys
end
def self.chord_index(chord)
chord_index = 0
chords.each_with_index do |c, i|
chord_index = i
break if c.include? chord
end
chord_index
end
def self.reverse_chord_index(chord)
chord_index = 0
self.notes.each_with_index do |c, i|
chord_index = i
break if c.include? chord
end
chord_index
end
def self.chord_value(chord_index, key, options = {})
chord_value = ""
pitch = Song.pitch(key)
chords = Song.chords
if options[:reverse].present? and options[:reverse]
chords = notes
end
if chords[chord_index]
chord_value = chords[chord_index][0]
if chord_value.size > 1 && pitch == "flat"
chord_value = chords[chord_index][1]
end
end
chord_value
end
def self.note_offsets(from_note, to_note)
offset = 0
from_note_index = Song.reverse_chord_index(from_note)
to_note_index = Song.reverse_chord_index(to_note)
# Direct distance
direct_offset = to_note_index - from_note_index
# Indirect distance
top_offset = Song.chords.size - to_note_index
bottom_offset = from_note_index
indirect_offset = top_offset + bottom_offset
offset = direct_offset
if indirect_offset < direct_offset
#offset = indirect_offset
end
offset
end
def transpose_to(chord, aimed_chord)
offset = Song.note_offsets(self.key, aimed_chord)
transpose(chord, offset)
end
def capose(chord, offset)
base_chord, extra_chord = Song.clean(chord)
final_chord = nil
# Find current chord index
chord_index = Song.chord_index(base_chord)
current_key_index = Song.chord_index(self.key)
if offset == 0
return chord
elsif offset > 0
chord_index += 1
current_key_index += 1
else
chord_index -= 1
current_key_index -= 1
end
initial_index = chord_index
full_index = initial_index
while (full_index != (initial_index + offset)) do
new_key = Song.chord_value(current_key_index, self.key)
if final_chord = Song.chord_value(chord_index, new_key) and final_chord.present?
else
if chord_index > (Song.chords.size - 1)
chord_index -= Song.chords.size
else
chord_index -= Song.chords.size
end
final_chord = Song.chord_value(chord_index, new_key)
end
if offset > 0
chord_index += 1
full_index += 1
current_key_index += 1
else
chord_index -= 1
full_index -= 1
current_key_index -= 1
end
end
final_chord += extra_chord
final_chord
end
def self.clean(note)
pitch = Song.pitch(note)
base_note = note[0]
if pitch == "flat"
base_note += "b"
elsif pitch == "sharp"
base_note += "#"
end
extra_note = note[1..note.size]
# Remove extra sharp or flat
extra_note = extra_note.gsub("b", "")
extra_note = extra_note.gsub("#", "")
[base_note, extra_note]
end
def self.pitch(note)
base_note = note[0]
is_flat = note[/b/].present? and (Song.flat_notes.include?(base_note))
is_sharp = note[/#/].present? and (Song.sharp_notes.include?(base_note))
if is_flat and !is_sharp
pitch = "flat"
elsif is_sharp and !is_flat
pitch = "sharp"
else
pitch = ""
end
pitch
end
def transpose(chord, offset)
capose(chord, offset * -1)
end
# RIGHTS
def can_be_updated_by?(user)
end
end
|
def app_path
ENV['APP_BUNDLE_PATH'] || (defined?(APP_BUNDLE_PATH) && APP_BUNDLE_PATH)
end
def fill_in_on_screen(field, text: null)
text_field_selector = "view marked:'#{field}'"
check_element_exists(text_field_selector)
frankly_map(text_field_selector, 'becomeFirstResponder')
frankly_map(text_field_selector, 'setText:', text)
frankly_map(text_field_selector, 'endEditing:', true)
end
def touch_button(field)
text_field_selector = "view marked:'#{field}'"
check_element_exists(text_field_selector)
touch(text_field_selector)
end
Given(/^I launch the app$/) do
launch_app app_path
end
Then(/^I should see hello world$/) do
text_field_selector = "label marked:'Hello World'"
check_element_exists(text_field_selector)
end |
require 'test_helper'
class AppTest < ActiveSupport::TestCase
setup do
@app = apps(:one)
end
test_fixtures
test_dependent_associations(destroy: Token)
test 'name should be present' do
@app.name = ' '
assert_not @app.valid?
end
test 'name should not be too long' do
@app.name = 'a' * 256
assert_not @app.valid?
end
test 'level should be present' do
@app.level = nil
assert_not @app.valid?
end
test 'redirect_uri allowed to be nil' do
@app.redirect_uri = nil
assert @app.valid?
end
test 'redirect_uri should be present' do
@app.redirect_uri = ' '
assert_not @app.valid?
end
test 'redirect_uri should be valid' do
@app.redirect_uri = '0://'
assert_not @app.valid?
end
test 'redirect_uri should has no query' do
@app.redirect_uri = 'http://www.example.com?query'
assert_not @app.valid?
end
test 'invalid tokens should be destroyed when level changed' do
assert_difference('Token.where("level > 0", app: @app).count', -1) do
@app.update_attribute(:level, 0)
end
end
end
|
# frozen_string_literal: true
class UserMessagesController < ApplicationController
before_action :authenticate_user
before_action :set_user_message, only: %i[show edit update destroy]
before_action do |_request|
access_denied if @user_message && !admin? && @user_message.user_id != current_user.id
end
def index
query = UserMessage.includes(user: :member).order(created_at: :desc)
query = query.where(user_id: current_user.id) unless admin?
@user_messages = query.limit(1000).to_a
end
def show
return unless @user_message.read_at.nil? && @user_message.user_id == current_user.id
@user_message.update! read_at: Time.current
end
def new
@user_message ||= UserMessage.new(params[:user_message])
load_form_data
render :new
end
def edit
load_form_data
end
def create
@user_message = UserMessage.new(user_message_params)
if @user_message.save
UserMessageSenderJob.perform_later
flash.notice = 'User message was successfully created.'
return_page =
if @user_message.tag == 'membership_signup'
signup_path(Signup.find_by(user_id: @user_message.user_id))
else
@user_message
end
redirect_to return_page
else
new
end
end
def update
if @user_message.update(user_message_params)
redirect_to @user_message, notice: 'User message was successfully updated.'
else
render :edit
end
end
def destroy
@user_message.destroy
redirect_to user_messages_url, notice: 'User message was successfully destroyed.'
end
private
def load_form_data
@users = User.order(:first_name, :last_name).to_a
@tags = UserMessage.order(:tag).distinct.pluck(:tag)
@tags.prepend @user_message.tag if @user_message.tag.present? && @tags.exclude?(@user_message.tag)
@senders = UserMessage.distinct.pluck(:from).flatten.uniq.sort
end
# Use callbacks to share common setup or constraints between actions.
def set_user_message
@user_message = UserMessage.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_message_params
params.require(:user_message).permit(:user_id, :tag, :from, :subject, :key, :html_body, :plain_body,
:sent_at, :read_at, :channel)
end
end
|
class LiveCell
def self.lives?(live_neighbours)
if(live_neighbours > 3)
false
elsif(live_neighbours == 1)
false
else
true
end
end
end
describe "A live cell" do
it "dies when it has more than 3 live neighbours" do
LiveCell.lives?(4).should == false
end
it "dies when it has 1 live neighbour" do
LiveCell.lives?(1).should == false
end
it "lives when it has 2 live neighbours" do
LiveCell.lives?(2).should == true
end
it "lives when it has 3 live neighbours" do
LiveCell.lives?(3).should == true
end
end
describe "A dead cell" do
def lives?(live_neighbours)
true
end
it "lives when it has 3 neighbours" do
lives?(3).should == true
end
end |
require 'minitest/autorun'
require 'minitest/pride'
require './lib/turn'
require './lib/sequence'
require './lib/round'
require 'pry'
class RoundTest < Minitest::Test
def setup
@beginner_round = Round.new('b')
@intermediate_round = Round.new('i')
@advanced_round = Round.new('a')
end
def test_it_exists
assert_instance_of Round, @beginner_round
assert_instance_of Round, @intermediate_round
assert_instance_of Round, @advanced_round
end
def test_attributes_at_init
assert_instance_of String, @beginner_round.sequence
assert [], @beginner_round.turns
end
def test_take_turn
new_turn = @beginner_round.take_turn('rggb')
assert_instance_of Turn, new_turn
end
def test_turns_array
@beginner_round.take_turn("rggb")
assert_equal 1, @beginner_round.turns.length
end
#
# def test_number_correct_collection
# @round.take_turn("Juneau")
# @round.take_turn("WAZZAP")
# @round.take_turn("North north west")
# @round.take_turn("John Rock")
#
# assert_equal 3, @round.number_correct
#
# end
end
|
class TasksController < ApplicationController
def create
@task = Task.new(params[:task])
@task.save
flash[:notice] = t(:task_created)
redirect_to params[:return_url]
end
def update
@task = Task.find params[:id]
unless @task.complete?
@task.complete!
else
@task.incomplete!
end
if @task.list.completed_at.present?
flash[:notice] = t(:list_completed)
end
render :partial => "tasks/task", :locals => { :task => @task }
end
def destroy
@task = Task.find params[:id]
@task.deleted = true
@task.save
flash[:notice] = t(:task_deleted)
redirect_to params[:return_url]
end
def show
@task = Task.find params[:id]
render_404 if @task.list.blank?
end
end
|
class SlackApi
USER_NAME = 'Slack Voter'
POST_PARAMS = { username: USER_NAME }
def initialize(url)
@url = url
end
def post_message(action, *args)
json = send(action, *args)
RestClient.post @url, json, content_type: :json, accept: :json
end
def new_survey(survey)
POST_PARAMS.merge({
text: survey.full_description
}).to_json
end
end
|
class ModelMailer < ActionMailer::Base
default from: "Leboncoin@ensiie.fr"
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.model_mailer.signal_annonce.subject
#
def signal_annonce(admin)
@admins = admin
@greeting = "Hi"
mail to: @admins[0]["email"], subject: "Success! You dit it."
end
def newsletter(user)
@user = user
mail to: @user[0]["email"], subject: "Newsletter Leboncoin !"
end
end
|
class Championship < ApplicationRecord
class InvalidParticipantsNumber < StandardError; end;
class InvalidChampionshipType < StandardError; end;
belongs_to :championship_type
belongs_to :user
has_many :participants
has_many :users, through: :participants
has_many :pontoscorridos_partidas
has_many :brackets
accepts_nested_attributes_for :participants
def brackets?
self.championship_type_id == 2
end
def finished?
self.winner.present?
end
def ranking
ranks = Array.new
self.participants.each do |participante|
r = Ranking.new(user_id: participante.user_id, played_games: 0, victories: 0, draws: 0, defeats: 0, points: 0)
ranks << r
end
self.pontoscorridos_partidas.where({finished: true}).includes(:player1, :player2).each do |partida|
rank1 = ranks.find {|s| s.user_id == partida.player1.user.id }
rank1.update_by_match(partida)
rank2 = ranks.find {|s| s.user_id == partida.player2.user.id }
rank2.update_by_match(partida)
end
sorted_ranking = ranks.sort_by {|obj| [obj.points * -1, obj.victories * -1, obj.draws * -1, obj.user_id]}
end
def full_loaded_final(relations_to_include = {})
all_brackets = brackets.order(created_at: :desc).includes(relations_to_include).to_a
all_brackets.each do |bracket|
bracket.children = all_brackets.select { |b| b.parent_id == bracket.id}
end
all_brackets.find { |bracket| bracket.parent_id.nil? }
end
def generate_brackets!
raise InvalidParticipantsNumber if Math.log2(participants.count) != Math.log2(participants.count).to_i
raise InvalidChampionshipType unless self.brackets?
current_participants = participants.to_a.clone
brackets = []
while current_participants.present?
bracket = Bracket.new(championship_id: self.id)
bracket.player_1 = current_participants.delete(current_participants.sample)
bracket.player_2 = current_participants.delete(current_participants.sample)
bracket.save!
brackets << bracket
end
current_round = brackets
while current_round.size > 1
next_round = []
while current_round.present?
parent = Bracket.create!(championship_id: self.id)
bracket1 = current_round.pop
bracket1.parent = parent
bracket1.save!
bracket2 = current_round.pop
bracket2.parent = parent
bracket2.save!
next_round << parent
end
current_round = next_round
end
end
end
|
class AddcolomMorimoris < ActiveRecord::Migration[5.0]
def change
add_column :morimoris, :mainsub_id, :integer
add_column :morimoris, :mainsub_name, :string
end
end
|
module Kafkat
module Command
class CleanIndexes < Base
register_as 'clean-indexes'
usage 'clean-indexes',
'Delete untruncated Kafka log indexes from the filesystem.'
def run
print "This operation will remove any untruncated index files.\n"
begin
print "\nStarted.\n"
count = kafka_logs.clean_indexes!
print "\nDone (#{count} index file(s) removed).\n"
rescue Interface::KafkaLogs::NoLogsError => e
print "ERROR: Kakfa log directory doesn't exist.\n"
exit 1
rescue Interface::KafkaLogs::KafkaRunningError => e
print "ERROR: Kafka is still running.\n"
exit 1
rescue => e
print "ERROR: #{e}\n"
exit 1
end
end
end
end
end
|
require 'collins/state/mixin'
require 'escape'
module Collins
# Provides state management via collins tags
class PersistentState
include ::Collins::State::Mixin
include ::Collins::Util
attr_reader :collins_client, :path, :exec_type, :logger
def initialize collins_client, options = {}
@collins_client = collins_client
@exec_type = :client
@logger = get_logger({:logger => collins_client.logger}.merge(options).merge(:progname => 'Collins_PersistentState'))
end
def run
self.class.managed_state(collins_client)
self
end
# @deprecated Use {#use_netcat} instead. Replace in 0.3.0
def use_curl path = nil
use_netcat(path)
end
def use_client
@path = nil
@exec_type = :client
self
end
def use_netcat path = nil
@path = Collins::Option(path).get_or_else("nc")
@exec_type = :netcat
self
end
# @override update_asset(asset, key, spec)
def update_asset asset, key, spec
username = collins_client.username
password = collins_client.password
host = collins_client.host
tag = ::Collins::Util.get_asset_or_tag(asset).tag
case @exec_type
when :netcat
netcat_command = [path, '-i', '1'] + get_hostname_port(host)
timestamp_padding, json = format_spec_for_netcat spec
body = "attribute=#{key};#{json}"
length = body.size + timestamp_padding
request = [request_line(tag)] + request_headers(username, password, length)
request_string = request.join("\\r\\n") + "\\r\\n\\r\\n" + body
current_time = 'TIMESTAMP=$(' + get_time_cmds(host).join(' | ') + ')'
args = ['printf', request_string]
"#{current_time}\n" + Escape.shell_command(args) + ' $TIMESTAMP | ' + Escape.shell_command(netcat_command)
else
super(asset, key, spec)
end
end
def get_time_cmds host
hostname, port = get_hostname_port host
get_cmd = %q{printf 'GET /api/timestamp HTTP/1.0\r\n\r\n'}
nc = sprintf('%s -i 1 %s %d', path, hostname, port)
only_time = %q{grep -e '^[0-9]'}
last_line = %q{tail -n 1}
[get_cmd, nc, only_time, last_line]
end
def request_line tag
"POST /api/asset/#{tag} HTTP/1.0"
end
def request_headers username, password, length
[
"User-Agent: collins_state",
auth_header(username, password),
"Content-Type: application/x-www-form-urlencoded",
"Content-Length: #{length}",
"Connection: Close"
]
end
def auth_header username, password
auth = Base64.strict_encode64("#{username}:#{password}")
"Authorization: Basic #{auth}"
end
# @return [Array<Fixnum,String>] padding for format string and json to use
def format_spec_for_netcat spec
expected_timestamp_size = Time.now.utc.to_i.to_s.size
spec.timestamp = '%s'
actual_timestamp_size = spec.timestamp.to_s.size
timestamp_padding = (expected_timestamp_size - actual_timestamp_size).abs
json = spec.to_json
[timestamp_padding, json]
end
# @return [Array<String,String>] hostname and port
def get_hostname_port host
host = URI.parse(host)
[host.host, host.port.to_s]
end
end
end
|
require 'osc'
class LightRemote::Light
attr_accessor :host, :port, :osc
def initialize(host, options={})
options = { :port => 2222 }.merge(options)
@host = host
@port = options[:port]
@osc = OSC::UDPSocket.new
end
# Sends RGB value in range [0, 1] to light.
def send_light(r, g, b)
#puts "sending #{r}, #{g}, #{b}"
m = OSC::Message.new('/light/color/set', 'fff', r, g, b)
@osc.send(m, 0, @host, @port)
end
# Fades light linearly between two RGB values.
def fade(r1, g1, b1, r2, g2, b2, steps=10)
raise "steps must be greater than zero" unless steps > 0
d_r = (r2 - r1).to_f / steps
d_g = (g2 - g1).to_f / steps
d_b = (b2 - b1).to_f / steps
(steps - 1).times do |s|
r = r1 + d_r * s
g = g1 + d_g * s
b = b1 + d_b * s
send_light(r, g, b)
sleep(0.02)
end
# Do last step separately so that rounding errors don't prevent us from
# ending on the correct RGB.
send_light(r2, g2, b2)
sleep(0.02)
end
end
|
class PlaceReservationsController < ApplicationController
before_action :set_place_reservation, only: [:destroy]
def index
#@place_reservations = current_user.place_reservations.paginate(page: params[:page], per_page: 8)
@place_reservations = PlaceReservation.joins(:user, :place).where("cast(users.id as text) = cast(#{current_user.id} as text)")
end
def new
@place = Place.find(params[:place_id])
@place_reservation = @place.place_reservations.new
end
def create
@reservation = PlaceReservation.new(place_reservation_params)
if @reservation.data_entrada > Date.today && @reservation.data_entrada < @reservation.data_saida
@reservation.save
redirect_to root_path
flash[:success] = "cadastrado com sucesso:D"
else
flash[:danger] = "Tente novamente com uma data valida."
redirect_to place_path(@reservation.place)
end
end
def destroy
@place_reservation.destroy
redirect_to place_reservations_path
end
private
def place_reservation_params
params.require(:place_reservation).permit(:data_entrada, :data_saida, :place_id, :user_id,)
end
def set_place_reservation
@place_reservation = PlaceReservation.find(params[:id])
end
end |
describe Sulfuras do
let(:sulfuras) {Sulfuras.new(Item.new("Sulfuras, Hand of Ragnaros", 0, 80))}
it 'inherits from Item' do
expect(Sulfuras).to be < Item
end
it 'initializes with a name, sell_in, and quality' do
expect(sulfuras.name).to eq("Sulfuras, Hand of Ragnaros")
expect(sulfuras.sell_in).to eq(0)
expect(sulfuras.quality).to eq(80)
end
context '#update_item_quality' do
it 'does nothing to the legendary sulfuras' do
sulfuras_quality = sulfuras.quality
sulfuras.update_item_quality
expect(sulfuras.quality).to eq(sulfuras_quality)
end
end
context '#update_item_sell_in' do
it 'does nothing to the legendary sulfuras' do
sulfuras_sell_in = sulfuras.sell_in
sulfuras.update_item_sell_in
expect(sulfuras.sell_in).to eq(sulfuras_sell_in)
end
end
context '#update_expired_item' do
it 'does nothing to the legendary sulfuras' do
sulfuras_quality = sulfuras.quality
sulfuras.update_expired_item
expect(sulfuras.quality).to eq(sulfuras_quality)
end
end
context '#expired?' do
it 'returns false because Sulfuras never expires' do
sulfuras.sell_in = 0
expect(sulfuras.expired?).to eq(false)
sulfuras.sell_in = 50
expect(sulfuras.expired?).to eq(false)
end
end
end
|
class TicketController < ApplicationController
def index
@departments = []
Department.all.each do |dep|
@departments << [dep.title, dep.id]
end
end
def create_ticket_post
wait_for_staff_status = TicketStatus.where(title: 'Waiting for Staff Response').first.try(:id)
if params[:departments].blank? || params[:name].blank? || params[:email].blank?
flash[:danger] = "Fill in all fields please!"
redirect_to root_path and return
else
ticket = Ticket.create!(department_id: params[:departments], ticket_status_id: wait_for_staff_status,
creator_name: params[:name], creator_email: params[:email])
if ticket
TicketMessage.create!(ticket_id: ticket.id, text: params[:text])
redirect_to ticket_path :reference => ticket.title
else
flash[:danger] = "Something went wrong!"
redirect_to root_path and return
end
end
end
def search_ticket
ticket = Ticket.where(title: params[:ticket_reference]).first
if ticket
redirect_to ticket_path :reference => params[:ticket_reference]
else
flash[:danger] = "Ticket with given reference is not exists!"
redirect_to root_path and return
end
end
def ticket
@ticket = Ticket.joins(:ticket_messages).where(title: params[:reference]).first
@statuses = []
TicketStatus.all.each do |t_s|
@statuses << [t_s.title, t_s.id]
end
end
def ticket_add_message_post
if params[:ticket_message].blank?
flash[:info] = 'Blank message. Please fill in the field.'
redirect_to ticket_path :reference => params[:ticket_reference]
else
ticket = Ticket.where(title: params[:ticket_reference]).first
if ticket
if User.current
if params[:ticket_status].to_i != 0
begin
ticket.ticket_status_id = params[:ticket_status].to_i
ticket.save!
CustomerMailSender.ticket_change_mail(ticket.creator_name, ticket.creator_email, ticket.title).deliver
rescue Exception => e
flash[:danger] = e
redirect_to ticket_path :reference => params[:ticket_reference] and return
end
else
flash[:danger] = "Something went wrong! Message does not saved!"
redirect_to ticket_path :reference => params[:ticket_reference] and return
end
else
begin
wait_for_staff_status = TicketStatus.where(title: 'Waiting for Staff Response').first.try(:id)
wait_for_customer_status = TicketStatus.where(title: 'Waiting for Customer').first.try(:id)
if ticket.ticket_status_id == wait_for_customer_status
ticket.ticket_status_id = wait_for_staff_status
ticket.save!
end
rescue Exception => e
flash[:danger] = e
redirect_to ticket_path :reference => params[:ticket_reference] and return
end
end
begin
message = TicketMessage.new(text: params[:ticket_message], ticket_id: ticket.id)
message.user_id = session[:user].to_i if session[:user] && session[:user].to_i != 0
message.save!
rescue Exception => e
flash[:danger] = e
redirect_to ticket_path :reference => params[:ticket_reference] and return
end
redirect_to ticket_path :reference => params[:ticket_reference] and return
else
flash[:danger] = "Something went wrong! Ticket not found"
redirect_to root_path and return
end
end
end
def get_ownership
ticket = Ticket.where(id: params[:ticket_id]).first
if ticket
begin
ticket.user_id = params[:user_id].to_i
ticket.skip_callbacks = true
ticket.save!
rescue Exception => e
flash[:danger] = e
redirect_to tickets_path and return
end
end
redirect_to ticket_path :reference => params[:ticket_reference] and return
end
end |
module Riskified
class Configuration
attr_accessor :sandbox_mode, :sync_mode, :auth_token, :default_referrer, :shop_domain
def initialize
@sync_mode = true # pre-configured by default, since the async mode is not supported.
@sandbox_mode = nil
@auth_token = nil
@default_referrer = nil
@shop_domain = nil
end
def validate
raise Riskified::Exceptions::ConfigurationError.new('The "Auth Token" configuration is not found.') if @auth_token.nil? || @auth_token.empty?
raise Riskified::Exceptions::ConfigurationError.new('The "Shop Domain" configuration is not found.') if @shop_domain.nil? || @shop_domain.empty?
raise Riskified::Exceptions::ConfigurationError.new('The "Default Referrer" configuration is not found.') if @default_referrer.nil? || @default_referrer.empty?
end
end
end
|
require 'test/unit'
require 'yaml'
class Load_tests < Test::Unit::TestCase
# def setup
# end
# def teardown
# end
def test_load_from_string
foo = YAML::load('answer: 42')
assert(foo.size == 1)
assert(foo['answer'] == 42)
end
def test_repetitive_loads
test_load_from_string
test_load_from_string
end
def test_load_from_file
foo = YAML::load(File.open('yaml/rails_database.yml'))
assert(foo['production']['timeout'] == 5000)
end
def test_load_from_file_with_block
File.open('yaml/rails_database.yml') do |y|
foo = YAML::load(y)
assert(foo['production']['timeout'] == 5000)
end
end
def test_load_symbol
assert(YAML.load("--- :foo") == :foo)
end
def test_load_mapping_with_symbols
$t = {:one => "one val", :two => { :nested_first => "nested val" } }
$y = YAML::dump $t
$r = YAML::load $y
assert($r == $t)
assert($r[:one] == "one val")
end
end
|
require "test_helper"
require 'date'
describe VideosController do
describe "index" do
it "must get index" do
# Act
get videos_path
body = JSON.parse(response.body)
# Assert
expect(body).must_be_instance_of Array
expect(body.length).must_equal Video.count
# Check that each customer has the proper keys
fields = ["id", "title", "release_date", "available_inventory"].sort
body.each do |customer|
expect(customer.keys.sort).must_equal fields
end
must_respond_with :ok
end
it "works even with no videos" do
# Arrange
Video.destroy_all
# Act
get videos_path
body = JSON.parse(response.body)
# Assert
expect(body).must_be_instance_of Array
expect(body.length).must_equal 0
must_respond_with :ok
end
end
describe "show" do
it "can get a video" do
# Arrange
wonder_woman = videos(:wonder_woman)
# Act
get video_path(wonder_woman.id)
body = JSON.parse(response.body)
# Assert
fields = ["title", "overview", "release_date", "total_inventory", "available_inventory"].sort
expect(body.keys.sort).must_equal fields
expect(body["title"]).must_equal "Wonder Woman 2"
expect(body["release_date"]).must_equal "2020-12-25"
expect(body["available_inventory"]).must_equal 100
expect(body["overview"]).must_equal "Wonder Woman squares off against Maxwell Lord and the Cheetah, a villainess who possesses superhuman strength and agility."
expect(body["total_inventory"]).must_equal 100
must_respond_with :ok
end
it "responds with a 404 for non-existant videos" do
# Act
get video_path(-1)
# Assert
must_respond_with :not_found
body = JSON.parse(response.body)
expect(body).must_be_instance_of Hash
expect(body["ok"]).must_equal false
expect(body["message"]).must_equal "Not found"
end
end
describe "create" do
it "can create a valid video" do
# Arrange
video_hash = {
title: "Alf the movie",
overview: "The most early 90s movie of all time",
release_date: "December 16th 2025",
total_inventory: 6,
available_inventory: 6
}
# Assert
expect {
post videos_path, params: video_hash
}.must_change "Video.count", 1
must_respond_with :created
end
it "will respond with bad request and errors for an invalid movie" do
# Arrange
video_hash = {
title: "Alf the movie",
overview: "The most early 90s movie of all time",
release_date: "December 16th 2025",
total_inventory: 6,
available_inventory: 6
}
video_hash[:title] = nil
# Assert
expect {
post videos_path, params: video_hash
}.wont_change "Video.count"
body = JSON.parse(response.body)
expect(body.keys).must_include "errors"
expect(body["errors"].keys).must_include "title"
expect(body["errors"]["title"]).must_include "can't be blank"
must_respond_with :bad_request
end
end
describe "checkout" do
before do
@video = videos(:wonder_woman)
@customer = customers(:customer_one)
@rental_hash = {
video_id: @video.id,
customer_id: @customer.id,
due_date: Date.today + 7
}
end
it "will checkout a video to a customer with valid ids" do
expect{post checkout_path, params: @rental_hash}.must_change "Rental.count", 1
must_respond_with :ok
body = JSON.parse(response.body)
expect(body["customer_id"]).must_equal @customer.id
expect(body["video_id"]).must_equal @video.id
end
it "will respond with 404 with invalid ids" do
@rental_hash[:video_id] = -1
expect{post checkout_path, params: @rental_hash}.wont_change "Rental.count"
must_respond_with :not_found
end
it "will increase the customer's videos_checked_out_count by one" do
count = @customer.videos_checked_out_count
post checkout_path, params: @rental_hash
must_respond_with :ok
body = JSON.parse(response.body)
expect(body["videos_checked_out_count"]).must_equal count + 1
end
it "will decrease the video's available_inventory by one" do
count = @video.available_inventory
post checkout_path, params: @rental_hash
must_respond_with :ok
body = JSON.parse(response.body)
expect(body["available_inventory"]).must_equal count - 1
end
it "create a due date" do
post checkout_path, params: @rental_hash
must_respond_with :ok
body = JSON.parse(response.body)
expect(body["due_date"]).wont_be_nil
end
it "will respond with 200 with valid ids" do
post checkout_path, params: @rental_hash
must_respond_with :ok
end
end
describe "checkin" do
before do
@customer = customers(:customer_one)
@video = videos(:wonder_woman)
rental_hash = {
video_id: @video.id,
customer_id: @customer.id,
due_date: Date.today + 7
}
post checkout_path, params: rental_hash
@customer.reload
@video.reload
@checkin_hash = {
video_id: @video.id,
customer_id: @customer.id,
}
end
it "will respond with 404 with invalid customer id" do
@checkin_hash[:customer_id] = -1
count = @customer.videos_checked_out_count
post checkin_path, params: @checkin_hash
must_respond_with :not_found
expect(@customer.videos_checked_out_count).must_equal count
end
it "will respond with 404 with invalid video id" do
@checkin_hash[:video_id] = -1
count = @customer.videos_checked_out_count
post checkin_path, params: @checkin_hash
must_respond_with :not_found
expect(@customer.videos_checked_out_count).must_equal count
end
it "will decrease customer.videos_checked_out_count by one" do
count = @customer.videos_checked_out_count
post checkin_path, params: @checkin_hash
@customer.reload
must_respond_with :ok
expect(@customer.videos_checked_out_count).must_equal count - 1
end
it "will increase video.available_inventory by one" do
count = @video.available_inventory
post checkin_path, params: @checkin_hash
@video.reload
must_respond_with :ok
expect(@video.available_inventory).must_equal count + 1
end
end
end
|
class EmployerDemographicsImportProcess
include Sidekiq::Worker
sidekiq_options queue: :employer_demographics_import_process, retry: 1
def perform(file_path)
require 'open-uri'
file = open(file_path, encoding: 'utf-16')
headers = file&.first&.split("\t").map(&:parameterize).map(&:underscore).map(&:to_sym)
until file&.eof?
split_line = file.readline.split("\t")
EmployerDemographicsImport.perform_async(Hash[headers.map.with_index { |header, index| [header, split_line[index]] }])
end
end
end
|
require 'sinatra'
require 'sinatra/activerecord'
require './models'
require 'bundler/setup'
require 'sinatra/flash'
set :database, 'sqlite3:winter.sqlite3'
set :sessions, true
def current_user
if session[:user_id]
User.find(session[:user_id])
end
end
get "/" do
@user = User.new
erb :home
end
get "/user" do
@users = User.all
erb :user
end
post '/new-user' do
@user = User.new(first_name: params[:first_name], last_name: params[:last_name],password: params[:password], email: params[:email]);
if @user.save
redirect '/logged-in'
end
end
get '/logged-in' do
@user = User.last
erb :user
end
post '/sign-in' do
@user = User.where(email: params[:email]).first
if @user && @user.password == params[:password]
session[:user_id] = @user.id #logging in the user
flash[:notice] = 'Signed In Successfully!'
redirect '/logged-in'
else
flash[:alert] = "Either your email or password is wrong"
erb :home
end
end
|
module ApplicationHelper
# Return a transformed text in HTML through markdown
def markdown(text)
renderer = Redcarpet::Render::HTML.new(render_options = {
:prettify => true
})
markdown = Redcarpet::Markdown.new(renderer, extensions = {
:strikethrough => true,
:no_intra_emphasis => true,
:tables => true,
:fenced_code_blocks => true,
:disable_indented_code_blocks => true,
:highlight => true,
:space_after_headers => true,
:autolink => true
})
markdown.render(text).html_safe
end
end
|
class AddCoverToEmpresa < ActiveRecord::Migration[5.0]
def change
add_attachment :empresas,:cover
end
end
|
class FantasyTeamsController < ApplicationController
before_action :authenticate_user!
before_action :set_fantasy_team, only: [:show, :edit, :update, :destroy]
before_action :set_fantasy_league
def index
@fantasy_teams = FantasyTeam.all
end
def new
@fantasy_team = @fantasy_league.fantasy_teams.new
end
def create
@fantasy_team = @fantasy_league.fantasy_teams.new(fantasy_team_params)
@fantasy_team.save!
redirect_to(@fantasy_league)
end
def show
end
def destroy
@fantasy_team.destroy
redirect_to(fantasy_league_fantasy_teams_path)
end
def edit
end
def update
@fantasy_team.update(fantasy_team_params)
redirect_to(fantasy_league_fantasy_teams_path)
end
private
def set_fantasy_team
@fantasy_team = FantasyTeam.find(params[:id])
end
def set_fantasy_league
@fantasy_league = FantasyLeague.find(params[:fantasy_league_id])
end
def fantasy_team_params
params.require(:fantasy_team).permit(:name, :user_id)
end
end |
require 'test_helper'
class ResponseMailerTest < ActionMailer::TestCase
def setup
@writer = create(:writer)
@submission = create(:submission, writer: @writer)
@desc = create(:description, submission: @submission)
@response = create(:response, description: @desc)
end
test "response_notification" do
mail = ResponseMailer.response_notification @response
assert_equal "Review for Mysubmission", mail.subject
assert_equal [@writer.email], mail.to
assert_equal ["teambbarters@gmail.com"], mail.from
end
end
|
FactoryGirl.define do
factory :deal_confirmation, class: IGMarkets::DealConfirmation do
affected_deals []
deal_id 'id'
deal_reference 'reference'
deal_status 'ACCEPTED'
direction 'BUY'
epic 'CS.D.EURUSD.CFD.IP'
expiry '20-DEC-40'
guaranteed_stop false
level 100.0
limit_distance 10.0
limit_level 110.0
reason 'SUCCESS'
size 1
stop_distance 10.0
stop_level 90.0
trailing_stop false
end
end
|
class RemoveTimeFromLogin < ActiveRecord::Migration
def up
remove_column :logins, :time
end
def down
add_column :logins, :time, :datetime
end
end
|
require './board'
RSpec.describe Board do
describe "#positions" do
it "return total board positions" do
board = Board.new(3,4)
board.totalPositions
expect(board.totalPositions).to eq 12
end
end
end
|
require_relative 'test_helper'
require_relative '../lib/cpu_player'
require_relative '../lib/player'
require_relative '../lib/ship'
class PlayerTest < MiniTest::Test
def setup
@cpu = CpuPlayer.new("1")
@player = Player.new("1")
@c_cruiser = Ship.new("Cruiser", 3)
@c_submarine = Ship.new("Submarine", 2)
@p_cruiser = Ship.new("Cruiser", 3)
@p_submarine = Ship.new("Submarine", 2)
end
def test_it_exists
assert_instance_of Player, @player
end
def test_it_has_starting_attributes
assert_instance_of Board, @player.board
assert_equal [], @player.ships
assert_equal [], @player.shots
assert_nil @player.cpu
end
def test_it_can_take_a_cpu_as_oppent
@player.add_cpu_target(@cpu)
assert_instance_of CpuPlayer, @player.cpu
end
def test_it_can_add_ships
@player.add_ships(@p_cruiser)
@player.add_ships(@p_submarine)
assert_equal [@p_cruiser, @p_submarine], @player.ships
end
end
|
class ConvertWikiNotesToHtml < ActiveRecord::Migration
def self.up
say_with_time "Converting Wiki pages to HTML" do
WikiRevision.find(:all).each do |rev|
rev.body = RedCloth.new(rev.body).to_html(:block_textile_table, :block_textile_lists, :block_textile_prefix, :inline_textile_image, :inline_textile_link, :inline_textile_span)
rev.save
end
end
say_with_time "Converting Notes to HTML" do
Page.find(:all).each do |page|
page.body = RedCloth.new(page.body).to_html(:block_textile_table, :block_textile_lists, :block_textile_prefix, :inline_textile_image, :inline_textile_link, :inline_textile_span)
page.save
end
end
end
def self.down
end
end
|
class Game < ActiveRecord::Base
has_many :players
def self.authenticate(id, password)
game = Game.find(id)
if game.blank? || password != game.password
return nil
else
return game
end
end
def other_player(this_player)
(self.players - [this_player]).first
end
end
# == Schema Information
#
# Table name: games
#
# id :integer not null, primary key
# password :string(255)
# whose_turn :integer
#
|
require 'spec_helper'
describe SqlResultPresenter, :type => :view do
let(:schema) { gpdb_schemas(:default) }
let(:result) do
SqlResult.new.tap do |result|
result.add_column("size", "real")
result.add_column("is_cool", "boolean")
result.add_row(["11", "t"])
result.add_row(["21", "f"])
result.add_row(["31", "f"])
result.schema = schema
result.warnings = ['warning1', 'warning2']
end
end
let(:hash) { subject.to_hash }
before do
stub(ActiveRecord::Base).current_user { users(:owner) }
end
subject { SqlResultPresenter.new(result, view) }
describe "#to_hash" do
it "presents the columns" do
hash[:columns].should == [
GpdbColumnPresenter.new(GpdbColumn.new({:name => "size", :data_type => "real"}), view).presentation_hash,
GpdbColumnPresenter.new(GpdbColumn.new({:name => "is_cool", :data_type => "boolean"}), view).presentation_hash
]
end
it "presents the rows" do
hash[:rows].should == [
["11", "t"],
["21", "f"],
["31", "f"]
]
end
it "presents the execution schema" do
hash[:execution_schema].should == GpdbSchemaPresenter.new(schema, view).presentation_hash
end
it "presents the warnings" do
hash[:warnings].should == ['warning1', 'warning2']
end
end
end
|
class Video < ActiveRecord::Base
paginates_per 50
belongs_to :video_category
belongs_to :image
def image_link
image = self.image
image && image.filename ? ActionController::Base.helpers.asset_path(image.filename) : ActionController::Base.helpers.asset_path("placeholders/videogame-placeholder.png")
end
end
|
class AddDaysPlayedToPlayerIds < ActiveRecord::Migration
def change
add_column :player_ids, :days_played, :string
end
end
|
require 'tmpdir'
require 'minitest/autorun'
require 'minitest/spec'
require 'apt_control'
require 'inifile'
module CLIHelper
def self.included(other_mod)
other_mod.instance_eval do
after do
FileUtils.rm_r(@working_dir) if File.directory?(@working_dir)
end
let :build_archive_dir do
@build_archive_dir ||= begin
File.join(@working_dir, 'builds')
end
end
let :apt_site_dir do
File.join(@working_dir, 'apt')
end
let :apt_config_file do
File.join(apt_site_dir, 'conf', 'distributions')
end
let :control_file do
File.join(@working_dir, 'control.ini')
end
end
end
def setup_dirs
@working_dir = Dir.mktmpdir
Dir.mkdir(apt_site_dir)
Dir.mkdir(File.join(apt_site_dir, 'conf'))
Dir.mkdir(build_archive_dir)
end
def write_reprepro_config(string)
File.open(apt_config_file, 'w') {|f| f.write(string) }
end
def write_control_ini(string)
File.open(control_file, 'w') {|f| f.write(string) }
end
def build(package, version)
builds_by_blob "#{package}*#{version}*"
end
def control(hash)
# weird escaping problem with inifile writing
hash.each do |s, h|
h.each do |k, v|
h[k] = '"' + v + '"'
end
end
IniFile.new.tap do |inifile|
inifile.merge!(hash)
# apply filename after new to stop it reading old contents
inifile.filename = control_file
inifile.write
end
end
def builds_by_blob(blob)
Dir["data/packages/#{blob}"].each do |fname|
FileUtils.cp(fname, build_archive_dir)
end
end
def include(codename, package, version)
@exec = AptControl::Exec.new
changes_file = "data/packages/#{package}_#{version}_amd64.changes"
raise "#{changes_file} does not exist" unless File.exists?(changes_file)
begin
@exec.exec("reprepro -b #{apt_site_dir} --ignore=wrongdistribution include #{codename} #{changes_file}")
rescue AptControl::Exec::UnexpectedExitStatus => e
puts e.stderr
raise
end
end
def run_apt_control(cmd, options={})
@exec = AptControl::Exec.new(options)
opts = {
build_archive_dir: build_archive_dir,
control_file: control_file,
apt_site_dir: apt_site_dir,
# there is some problem with inotify under tests - the events don't seem
# to be fired - maybe because the (original) parent process made the
# changes?
disable_inotify: true,
log_file: '/dev/null'
}.map {|k,v| "-o #{k}=#{v}" }.join(' ')
begin
cmd = "ruby -rrubygems -Ilib bin/apt_control #{opts} " + cmd
@exec.exec(cmd, options)
rescue AptControl::Exec::UnexpectedExitStatus => e
fail(e.message + "\n" + e.stderr)
end
end
def assert_last_stdout_include(line)
assert @exec.last_stdout.include?(line), "line:#{line}\n not in \n#{@exec.last_stdout}"
end
def assert_last_stderr_include(line)
assert @exec.last_stderr.include?(line), "line:#{line}\n not in \n#{@exec.last_stderr}"
end
def with_default_reprepro_config
write_reprepro_config %Q{
Codename: production
Architectures: amd64 source
Components: misc
Codename: staging
Architectures: amd64 source
Components: misc
Codename: testing
Architectures: amd64 source
Components: misc
}
end
end
|
module TmuxStatus
module Wrappers
class AcpiBattery
def percentage
return 100 if charged?
output.scan(/(\d{1,3})%/).flatten.first.to_i
end
def charged?
output.include? 'Full'
end
def charging?
output.include? 'Charging'
end
def discharging?
output.include? 'Discharging'
end
def output
@output ||= %x[ acpi --battery 2>&1 ]
end
end
end
end
|
# coding: utf-8
class Word
attr_accessor :id, :position, :form, :lexeme_id, :inflection, :tags, :greek_note, :english_note
def initialize(id, position, form, lexeme_id, inflection, tags)
@id = id
@position = position
@form = form
@lexeme_id = lexeme_id
@inflection = inflection
@tags = tags
if note = tags.detect { |tag| tag[0, 6] == 'gnote:' }
@greek_note = note[6..-1].gsub('+', ' ')
end
if note = tags.detect { |tag| tag[0, 6] == 'enote:' }
@english_note = note[6..-1].gsub('+', ' ')
end
end
def lexeme
@lexeme ||= Lexicon[lexeme_id] if lexeme_id
end
def mt(inf = nil)
return pt unless lexeme_id
Inflector.inflect lexeme.translation, lexeme.pos, inf || inflection
end
def rmt
return pt unless lexeme_id
x = mt(process_inflection_tags)
process_gsubs! x
process_post_tags! x
collapse_affixes! x
x
end
private
def pt
form.tr ';·', '?;'
end
def process_inflection_tags
if inf = inflection && inflection.dup
tags.each do |tag|
case tag
when /^I[123][sp]$/
inf[2, 3] = tag.downcase
tags << '-'
when 'N'
inf[0] = 'n'
end
end
inf[1] = 'a' if lexeme.tags.include?(:deponent)
inf
end
end
def process_gsubs!(x)
lexeme.gsubs.each do |rule|
tag, pattern, text, condition = rule
next unless tag.nil? || tags.include?(tag)
next unless condition.nil? || inflection =~ condition
x.gsub! pattern, text
end
end
def process_post_tags!(x)
tags.each do |tag|
case tag
when '-'
x.sub! /^[a-z>@]+~/, ''
when /^\+\(.*\)$/
x << tag.tr('+', ' ')
when /^\(.*\)\+$/
x[0, 0] = tag.tr('+', ' ')
when /^\+".*"$/
x << tag[2..-2].tr('+', ' ')
when /^".*"\+$/
x[0, 0] = tag[1..-3].tr('+', ' ')
when 'should'
x.sub! 'might', 'should'
when 'U'
x.capitalize!
end
end
end
def collapse_affixes!(x)
x.sub! /(^|~| )[>@]~/, '\1'
x.sub!(/~s(~|$)/, '\1') if [:a, :ra, :rd, :rp, :rr].include?(lexeme.pos)
x.sub! /([^aeiouy][jsxz])~s(~|$)/, '\1es\2'
x.sub! /([aeiouy])([jsxz])~s(~|$)/, '\1\2\2es\3'
x.sub! /~s(~|$)/, 's\1'
x.sub! /([aeiouy][^aeiouy])e~(ing|ed|er|est)(~|$)/, '\1\2\3'
x.sub! /(en|er)~(ing|ed|er|est)(~|$)/, '\1\2\3'
x.sub! /([^aeiouy][aeiouy])([^aeiouwy])~(ing|ed|er|est)(~|$)/, '\1\2\2\3\4'
x.sub! /~(ing|ed|er|est)(~|$)/, '\1\2'
x.tr! '~', ' '
end
end
|
class Api::V1::UsersController < ApplicationController
respond_to :json
skip_before_action :verify_authenticity_token, :if => Proc.new { |c| c.request.format == 'application/json' }
before_action :authenticate_request!
def create
user = User.new(user_params)
if user.save
render :json => { :status => 'success', :user => user.as_json() ,:message => 'user saved successfully' ,:code => '200'}
else
render json: { errors: user.errors}, status: 500 , message: 'failed'
end
end
def show
user = User.find(params[:id])
render :json => { :status => 'success', :user => user.as_json() ,:message => 'user fetched successfully' ,:code => '200'}
end
def update
user = User.find(params[:id])
if user.update(user_params)
render :json => { :status => 'success', :user => user.as_json() ,:message => 'user updated successfully' ,:code => '200'}
else
render json: { errors: user.errors }, status: 500
end
end
def destroy
user = User.find(params[:id])
if user.destroy
render :json => { :status => 'success',:message => 'user deleted successfully' ,:code => '200'}
else
render json: { errors: user.errors }, status: 500
end
end
private
def user_params
params.permit(:email, :password, :password_confirmation)
end
end
|
# frozen_string_literal: true
class SettingsController < ApplicationController
def signin
return unless params["settingType"] == "account"
store_location_for(:user, "account_details")
end
def signup; end
def signout; end
def mln_banner_message
unless ENV.fetch('SHOW_MAINTENANCE_BANNER',
nil) && ENV['SHOW_MAINTENANCE_BANNER'].to_s.casecmp("true").zero? && ENV['MAINTENANCE_BANNER_TEXT'].present?
return
end
render json: { bannerText: ENV['MAINTENANCE_BANNER_TEXT'].html_safe, bannerTextFound: true }
end
def page_not_found; end
def activeadmin_redirect_to_login
if Devise.sign_out_all_scopes
sign_out
redirect_to "/admin/login"
else
redirect_to "/admin/dashboard"
end
end
def reset_admin_password_message
if params["admin_user"]["email"].present?
if AdminUser.valid_email?(params["admin_user"]["email"]).present?
flash[:notice] = "You will receive an email with instructions about how to reset your password in a few minutes."
redirect_to "/admin/login"
else
flash[:error] = "Invalid email"
redirect_to "/admin/password/new"
end
else
flash[:error] = "Email can not be blank"
redirect_to "/admin/password/new"
end
end
def index
unless logged_in?
flash[:error] = "You must be logged in to access this page"
# 2019-08-08: I think this is now ignored. Commenting out for now, until make sure.
# session[:redirect_after_login] = "/users/edit"
store_location_for(:user, "/signin")
render json: { accountdetails: {}, ordersNotPresentMsg: "", errorMessage: "You must be logged in to access this page" }
redirect_to new_user_session_path
return
end
unless params[:settings].nil?
current_user.update({
:alt_email => params[:settings][:contact_email],
:school_id => params[:settings][:school][:id]
})
end
resp = {}
#Active schools from school table.
@schools = School.active_schools_data
if current_user.present?
@email = current_user.email
@alt_email = current_user.alt_email || current_user.email
@contact_email = current_user.contact_email
@school = current_user.school
per_page = 15
offset = params[:page].present? ? params[:page].to_i - 1 : 0
request_offset = per_page.to_i * offset.to_i
@holds = current_user.holds.order("created_at DESC").limit(per_page).offset(request_offset)
#If school is inactive for current user still need to show in school drop down.
@schools << @school.name_id unless @school.active
resp = {:id => current_user.id, current_user: current_user, :contact_email => @contact_email, :school => @school, :email => @email,
:alt_email => @alt_email, :schools => @schools.to_h, :total_pages => (current_user.holds.length / per_page.to_f).ceil,
:holds => @holds.filter_map do |i|
next if i.teacher_set.blank?
[created_at: i["created_at"].strftime("%b %-d, %Y"), quantity: i["quantity"],
access_key: i["access_key"], title: i.teacher_set.title, status_label: i.status_label, status: i.status,
teacher_set_id: i.teacher_set_id]
end.flatten, :current_password => User.default_password.to_s}
end
orders_not_present_msg = @holds.length <= 0 ? "You have not yet placed any orders." : ""
render json: { accountdetails: resp, ordersNotPresentMsg: orders_not_present_msg }
end
def acccount_details
return if logged_in?
redirect_to "/signin"
end
def sign_up_details
render json: { activeSchools: School.active_schools_data.to_h,
emailMasks: AllowedUserEmailMasks.where(active: true).pluck(:email_pattern) }
end
end
|
require 'open-uri'
require 'json'
class GamesController < ApplicationController
def new
@letters = ('a'..'z').to_a.sample(10)
end
def score
@letters = params[:letters].split('')
@answer = params[:answer].upcase
@score = @answer.length
@exist = exist?(@letters, @answer)
@english = english_word?(@answer)
end
private
def exist?(letters, answer)
p letters
p answer
p answer.chars.all? { |letter| answer.count(letter) <= letters.count(letter) }
answer.chars.all? { |letter| answer.count(letter.downcase) <= letters.count(letter) }
end
def english_word?(answer)
response = open("https://wagon-dictionary.herokuapp.com/#{answer}")
json = JSON.parse(response.read)
return json['found']
end
end
|
module FlexUtils
class Adl < AbstractTool
attr_writer :swf,
:title,
:visible,
:transparent,
:width,
:height,
:x,
:y,
:system_chrome,
:arguments,
:descriptor
def initialize( swf )
@swf = swf
@title = "Temporary AIR application"
@visible = true
@transparent = false
@width = 1024
@height = 768
@x = 100
@y = 100
@system_chrome = "standard"
@arguments = []
end
def generate_descriptor
return <<-stop
<?xml version="1.0"?>
<application xmlns="http://ns.adobe.com/air/application/1.5">
<id>net.iconara.tmp</id>
<version>1.0</version>
<filename>#{@title}</filename>
<initialWindow>
<title>#{@title}</title>
<content>#{File.basename(@swf)}</content>
<systemChrome>#{@system_chrome}</systemChrome>
<transparent>#{@transparent}</transparent>
<visible>#{@visible}</visible>
<width>#{@width}</width>
<height>#{@height}</height>
<x>#{@x}</x>
<y>#{@y}</y>
</initialWindow>
</application>
stop
end
def self.run( *args )
c = self.new(*args)
yield c
c.run!
end
def command_string
@extra_args ||= [ ]
args = (@arguments + @extra_args).join(" ")
"#{command_path 'adl'} #{@descriptor} -- #{args}"
end
def run!( extra_args=[], &block )
@extra_args = extra_args
current_dir = Dir.pwd
dir = File.dirname(@swf)
Dir.chdir(dir)
temporary_descriptor = @descriptor == nil
if temporary_descriptor
@descriptor = "temporary-application.xml"
descriptor = File.new(@descriptor, "w")
descriptor.puts(generate_descriptor)
descriptor.close
end
execute_command
yield($?) if block_given?
File.delete(@descriptor) if temporary_descriptor
Dir.chdir(current_dir)
end
end
end |
class CreateChapters < ActiveRecord::Migration[5.0]
def change
create_table :chapters do |t|
t.time :duracion
t.text :resumen
t.integer :numero
t.integer :temporada
t.string :nombre
t.timestamps
end
end
end
|
require "webstop-api/rest/consumer_sessions"
require "webstop-api/models/consumer"
module WebstopApi
module Interfaces
module ConsumerSessions
include WebstopApi::REST::ConsumerSessions
def login(credentials)
response = _login(credentials.merge(retailer_id: WebstopApi.retailer_id))
webstop_id = response.dig("consumer", "id")
token = response.dig("consumer", "consumer_credentials")
errors = response.dig("errors")
@token = token
Consumer.new(response[:consumer])
end
def logout
if _logout(token: token)
true
end
end
end
end
end
|
class User < ApplicationRecord
devise :two_factor_authenticatable, :rememberable, :secure_validatable, :recoverable,
otp_secret_encryption_key: ENV["SECRET_KEY_BASE"]
belongs_to :organisation
has_many :historical_events
validates_presence_of :name, :email
validates :email, with: :email_cannot_be_changed_after_create, on: :update
before_save :ensure_otp_secret!, if: -> { otp_required_for_login && otp_secret.nil? }
FORM_FIELD_TRANSLATIONS = {
organisation_id: :organisation
}.freeze
scope :active, -> { where(active: true) }
delegate :service_owner?, :partner_organisation?, to: :organisation
def active_for_authentication?
active
end
def confirmed_for_mfa?
mobile_number.present? && mobile_number_confirmed_at.present?
end
private
def ensure_otp_secret!
self.otp_secret = User.generate_otp_secret
end
def email_cannot_be_changed_after_create
if email.to_s.squish.downcase != email_was.to_s.squish.downcase
errors.add(:email, :cannot_be_changed)
end
end
end
|
%w( rubygems rack/test ).each {|lib| require lib }
require File.dirname(__FILE__) + '/../examples/sinatra-app'
describe 'Example Sinatra app' do
include Rack::Test::Methods
def app
Sinatra::Application
end
before do
# because we keep resetting Page.dir in the specs,
# we need to point it to the right dir for these
Page.dir = File.dirname(__FILE__) + '/../examples/pages'
end
it 'home page should work' do
get '/'
last_response.status.should == 200
last_response.body.should include('Our Pages')
last_response.body.should include("<a href='/foo'>")
end
it 'example other page should work' do
get '/foo'
last_response.status.should == 200
last_response.body.should include('<em>Hello</em> <strong>from</strong> <code>foo</code>')
end
end
|
require 'rails_helper'
describe Api::V1::FormulationsController do
before do
@formulation = FactoryBot.create(:formulation)
end
describe '#index' do
it 'successfully renders list of Formulations with Ingredients' do
get :index, params: {format: :json}
expect(response).to have_http_status(:ok)
expect(json_response).to be_kind_of(Array)
expect(json_response.length).to eq(1)
formulation_hash = json_response[0]
expect(formulation_hash['name']).to start_with('Formulation #')
expect(formulation_hash['ingredients']).to be_kind_of(Array)
expect(formulation_hash['ingredients'].length).to eq(1)
ingredient_hash = formulation_hash['ingredients'][0]
expect(ingredient_hash['name']).to start_with('Ingredient #')
end
end
end
|
require 'spec_helper'
describe Boxzooka::Endpoint do
let(:endpoint) { boxzooka_endpoint }
let(:response) { endpoint.execute(request) }
end
|
desc "Enviar correos de mantenimientos pendientes."
task enviar_pendientes: :environment do
users = User.distinct.joins(owner: {cars: :maintenance_histories}).where("maintenance_histories.status = 'Pendiente'")
users.each do |user|
UserNotifierMailer.send_pending_reviews(user).deliver
end
end
desc "Reiniciar dismiss_car_updates en propietarios"
task reset_dismiss_car_updates: :environment do
Owner.update_all(dismiss_car_updates: false)
end |
class MessagesController < ApplicationController
def new
@message = Message.new
end
def create
@message = Message.new(message_params)
if @message.save
flash[:notice] = 'Mensagem criada com sucesso'
ContactMailer.new(@message.id).deliver
else
flash[:alert] = 'Por favor, preencha corretamente os campos para o envio.'
end
respond_with @message, location: new_message_path
end
private
def message_params
params.require(:message).permit!
end
end
|
class AddEndingTimeToProposals < ActiveRecord::Migration
def change
add_column :proposals, :end_time, :datetime
end
end
|
class ApplicationController < ActionController::Base
def forem_user
current_user
end
helper_method :forem_user
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_filter :configure_permitted_parameters, if: :devise_controller?
def authenticate_admin_user!
redirect_to new_user_session_path unless current_user[:role] == 3
end
protected
def redirect_to_previous(*args)
unless request.referer.nil?
send( :redirect_to, request.referer, *args )
else
send( :redirect_to, root_path, *args )
end
end
# Devise customisations
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) do |u|
u.permit(:username, :gender, :birthday, :email, :current_password, :password, :password_confirmation)
end
devise_parameter_sanitizer.for(:account_update) do |u|
u.permit(:gender, :birthday, :status, :about_me, :avatar, :country, :email, :current_password, :password, :password_confirmation)
end
end
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :blogs
# 基本の7つのルーティングを定義するため
# ここに記載はされないが、GET blogs#new 等は設定されている
# 確認したい場合は $ rake routes
# また、_pathのURL用ヘルパー?も自動で追加されている
end
|
RESULT_FILE = 'results.txt'.freeze
LOG_FILE = 'general.log'
TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
def handle_exception(method_name, exception)
log_event method_name, exception.message
log_event method_name, exception.backtrace.inspect
puts exception.message
end
def log_event(method_name, message)
# YYYY-MM-DD HH:MM:SS METHOD STRING
File.open(LOG_FILE, 'a') {|f| f.puts "#{Time.now.strftime TIME_FORMAT} #{method_name}: #{message}"}
end
def write_result(method_name, result)
# variants of reporting strings:
# tc_01 (firefox): passed
# tc_01 (chrome): failed
File.open(RESULT_FILE, 'a') {|f| f.puts "#{method_name}: #{result}"}
end
def evaluate_result(method_name, result)
log_event __method__, 'Evaluating result'
if result
write_result method_name, :passed
'PASSED'
else
write_result method_name, :failed
'FAILED'
end
end |
require 'spec_helper'
describe EssayDetail::AuthorBiography do
let(:essay) { double(Essay, author: 'author', author_biography: double(MarkdownContent, content: 'biography'), author_image: double(Image, url: 'url')) }
subject { described_class.new(essay) }
describe 'self_render' do
it "instanciates itself and renders" do
described_class.any_instance.should_receive(:render)
described_class.render(essay)
end
end
it "has an essay " do
expect(subject.essay).to eq(essay)
end
it "reutrns the author name" do
expect(subject.name).to eq("author")
end
it "returns the markdown" do
expect(subject.markdown).to match "<p>biography</p>"
end
it "returns the image" do
expect(subject.image).to eq("<img alt=\"author\" src=\"/images/url\" />")
end
describe 'render' do
context 'has_discussion_questions' do
it "renders the template " do
expect(subject).to receive(:render_to_string).with('/essays/author_biography', { object: subject })
subject.render
end
it "renders with out error " do
expect { subject.render }.to_not raise_error
end
end
context 'no_work_cited' do
let(:essay) { double(Essay, author_biography: double(MarkdownContent, content: nil), author: 'author') }
it "does not render the template" do
expect(subject).to_not receive(:render_to_string)
subject.render
end
end
end
end
|
module Airplay
class Player
class Media
attr_reader :url
def initialize(file_or_url)
@url = case true
when File.exists?(file_or_url)
Airplay.server.serve(File.expand_path(file_or_url))
when !!(file_or_url =~ URI::regexp)
file_or_url
else
raise Errno::ENOENT, file_or_url
end
end
def to_s
@url
end
end
end
end
|
require 'rake'
require 'rspec/core/rake_task'
namespace :new_recipe do
desc 'add new folder and default.rb'
task :create, ['name'] do |tasks,args|
name = args[:name]
command = ''
command << "mkdir ./cookbooks/#{name} &&"
command << "touch ./cookbooks/#{name}/default.rb"
sh command
end
end
namespace :action_resipe do
desc 'recipeを実行する'
task :action,[:name] do| task,args|
name = args[:name]
recipe = []
Dir.glob("./cookbooks/#{name}/*").each do| dir|
#next unless File.directory?(dir)
tmp = File.basename(dir)
recipe << tmp
end
recipe.each do |tmp|
command = 'itamae local '
command << "./cookbooks/#{name}/#{tmp}"
sh command
end
end
end
|
class Account < ApplicationRecord
has_many :movements
belongs_to :user
end |
require 'spec_helper'
describe Metasploit::Model::Search::Operator::Group::Union do
it { should be_a Metasploit::Model::Search::Operator::Group::Base }
context 'operation_class_name' do
subject(:operation_class_name) {
described_class.operation_class_name
}
it { should == 'Metasploit::Model::Search::Operation::Group::Union' }
end
end |
require 'rails_helper'
RSpec.describe GamesController, :type => :controller do
describe "GET index" do
fixtures :games
it "returns http success" do
get :index
expect(response).to have_http_status(:success)
end
it "creates a new game when index page is loaded" do
#change matcher expects a block to be passed to it
expect{ get :index }.to change{ Game.count }.by(1)
end
end
describe "GET show" do
fixtures :games
it "returns http success" do
get :show, id: games(:sample)
expect(response).to have_http_status(:success)
end
it "assigns requested game to @game" do
game = games(:played)
get :show, id: games(:played)
# check whether @game instace variable assigned by controller is as expected
expect(assigns(:game)).to eq(game)
end
it "retains state of game, so that visitor can come back to it" do
game = games(:played)
get :show, id: games(:played)
expect(assigns(:game).flipped).to eq(game.flipped)
end
end
describe "PUT update" do
fixtures :games
let(:game_progress) {["1","2"]}
it "updates the user progress of the game" do
get :update, id: games(:sample), progress: ["1","2"]
expect(assigns(:game).flipped).to eq(game_progress)
end
it "updates the pairs_found attribute based on user progress of the game" do
get :update, id: games(:sample), progress: ["1","2"]
expect(assigns(:game).pairs_found).to eq(1)
end
end
describe "#notify_user" do
it "sends an email to emails address passed as parameter" do
post :notify_user, {:email => "test@test.com", :url => "http://memorygame-demo.herokuapp.com/games/a1243-123123-asd1233fasdef"}
expect(response).to have_http_status(:success)
end
it "returns 422 for invalid parameters" do
post :notify_user, {:email => "testtest.com", :url => "http://memorygame-demo.herokuapp.com/games/a1243-123123-asd1233fasdef"}
expect(response.status).to eq(422)
end
end
end
|
Given /^(provider "[^"]*") requires cinstances to be approved before use$/ do |provider|
provider.application_plans.each do |plan|
plan.approval_required = true
plan.save!
end
end
Then /^(buyer "[^"]*") should have (\d+) cinstances?$/ do |buyer_account, number|
assert_equal number.to_i, buyer_account.bought_cinstances.count
end
|
class UsersCourseRating < ApplicationRecord
belongs_to :user
belongs_to :course_rating
end
|
# frozen_string_literal: true
RSpec.describe ChatRoom, type: :model do
context 'Model Associations' do
it { is_expected.to belong_to(:user) }
it { is_expected.to have_many(:messages) }
end
end
|
class RenameColumnType < ActiveRecord::Migration
def up
rename_column :projects, :type, :project_type
end
def down
end
end
|
MRuby::Gem::Specification.new('mruby-sample') do |spec|
spec.license = 'MIT'
spec.authors = 'Yohei Kawahara'
spec.add_test_dependency 'mruby-httprequest'
spec.add_test_dependency 'mruby-json'
end
|
class Service < ActiveRecord::Base
belongs_to :user
has_many :orders
has_many :reviews
has_attached_file :image, { styles: { medium: "300x300",
small: "230x140",
thumb: "100x100" },
preserve_files: true
}
validates :title, presence: true, length: { maximum: 80 }
validates :description, presence: true, length: { maximum: 1200 }
validates :price, presence: true
validates :delivery_time, presence: false
validates :revisions, presence: false
validates :requirements, presence: true, length: { maximum: 250 }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
def average_rating
reviews.count == 0 ? 0 : reviews.average(:star).round(2)
end
def self.search(query)
where("title LIKE ? OR description LIKE ? OR requirements LIKE ?", "%#{query}%", "%#{query}%", "%#{query}%")
end
end
|
require 'rails_helper'
describe Message, :vcr => true do
it "will create a message" do
visit new_message_path
fill_in :To, :with => '9876543210'
fill_in :From, :with => '0123456789'
fill_in :Body, :with => 'TESTING IN PROGRESS'
click_on "Create Message"
expect(page).to have_content('Your message was sent!')
end
it "will render a new message" do
visit new_message_path
fill_in :To, :with => '9876543210'
fill_in :From, :with => '0123456789'
click_on "Create Message"
expect(page).to have_content(:new)
end
it "will sent to multiple numbers" do
visit new_message_path
fill_in :To, :with => '9876543210,1234958193,7727013776'
fill_in :From, :with => '0123456789'
fill_in :Body, :with => 'TESTING IN PROGRESS'
click_on "Create Message"
expect(page).to have_content('Your message was sent!')
end
it "will show individual page for message sent" do
message = create(:message)
visit messages_path
click_link 1
expect(page).to have_content("1111111111")
end
end
|
# lib/robot.rb
class Robot
attr_reader :placement, :placed
def initialize(table)
@table = table
@placed = false
end
def place(placement)
set_placement(placement)
end
def move
if @placed
position = @placement.position
orientation = @placement.orientation
case orientation
when Orientation::NORTH
new_position = Position.new(position.x, position.y + 1)
when Orientation::SOUTH
new_position = Position.new(position.x, position.y - 1)
when Orientation::WEST
new_position = Position.new(position.x - 1 , position.y)
when Orientation::EAST
new_position = Position.new(position.x + 1, position.y)
end
new_placement = Placement.new(@table, new_position, orientation)
set_placement(new_placement)
end
end
def right
set_placement(@placement.right)
end
def left
set_placement(@placement.left)
end
def report(output)
output << @placement.to_s + "\n"
end
private
def set_placement(placement)
if(placement.is_valid)
@placement = placement
@placed = true
end
end
end |
class AttachmentsController < ApplicationController
before_action :require_medusa_user
before_action :find_attachment_and_attachable, only: [:destroy, :show, :edit, :update, :download]
def destroy
authorize! :destroy_attachment, @attachable
@attachment.destroy
redirect_to @attachable
end
def show
end
def edit
authorize! :update_attachment, @attachable
end
#For unknown reasons trying to do this the straightforward way fails. Hence this.
def update
authorize! :update_attachment, @attachable
description = params[:attachment].delete(:description)
@attachment.description = description
@attachment.attachment = params[:attachment][:attachment] if params[:attachment][:attachment]
@attachment.author = current_user.person
if @attachment.save
redirect_to polymorphic_path(@attachable)
else
render 'edit'
end
end
def download
@attachment = Attachment.find(params[:id])
send_file(@attachment.attachment.path, disposition: 'inline')
end
def new
klass = attachable_class(params)
@attachable = klass.find(params[:attachable_id])
authorize! :create_attachment, @attachable
@attachment = Attachment.new(author: current_user.person, attachable: @attachable)
end
def create
klass = attachable_class(params[:attachment])
@attachable = klass.find(params[:attachment].delete(:attachable_id))
authorize! :create_attachment, @attachable
@attachment = Attachment.new(allowed_params)
@attachment.attachable = @attachable
@attachment.author ||= current_user.person
if @attachment.save
redirect_to polymorphic_path(@attachable)
else
render 'new'
end
end
protected
def find_attachment_and_attachable
@attachment = Attachment.find(params[:id])
@attachable = @attachment.attachable
end
def attachable_class(hash)
attachable_type_name = hash.delete(:attachable_type)
case attachable_type_name
when 'Collection'
Collection
when 'FileGroup', 'ExternalFileGroup', 'BitLevelFileGroup'
FileGroup
when 'Project'
Project
when 'FileFormat'
FileFormat
else
raise RuntimeError, "Unrecognized attachable type #{attachable_type_name}"
end
end
def allowed_params
params.require(:attachment).permit(:attachable_id, :attachable_type, :attachment_content_type,
:attachment_file_name, :attachment_file_size, :attachment, :description)
end
end
|
create_table "deploys", unsigned: true, force: :cascade do |t|
t.integer :application_id, null: false
t.integer :revision_id, null: false
t.boolean :current, default: false
t.timestamps
end
|
module Fog
module Compute
class Google
class Mock
def get_zone_operation(_zone_name, _operation)
# :no-coverage:
Fog::Mock.not_implemented
# :no-coverage:
end
end
class Real
# Get the updated status of a zone operation
# @see https://developers.google.com/compute/docs/reference/latest/zoneOperations/get
#
# @param zone_name [String] Zone the operation was peformed in
# @param operation [Google::Apis::ComputeV1::Operation] Return value from asynchronous actions
def get_zone_operation(zone_name, operation)
zone_name = zone_name.split("/")[-1] if zone_name.start_with? "http"
@compute.get_zone_operation(@project, zone_name, operation)
end
end
end
end
end
|
# frozen_string_literal: true
require 'csv'
require 'json'
require_relative 'models/all'
def lambda_handler(event:, context:) # rubocop:disable Lint/UnusedMethodArgument
output = CSV.generate do |csv|
csv << Product::FB_HEADERS
Product.with_type.each do |product|
csv << Product::FB_HEADERS.map do |header|
method = product.respond_to?("fb_#{header}") ? "fb_#{header}" : header
product.send(method)
end
end
end
{
statusCode: 200,
body: output,
headers: {
'Content-Type' => 'application/CSV',
},
}
end
|
require "test_helper"
require "integration_test_case"
module ActionClient
class ClientTestCase < ActionClient::IntegrationTestCase
Article = Struct.new(:id, :title)
class BaseClient < ActionClient::Base
default url: "https://example.com"
end
setup do
BaseClient.defaults.headers = {}
end
end
class RequestsTest < ClientTestCase
test "constructs a POST request with a JSON body declared with instance variables" do
class ArticleClient < BaseClient
def create(article:)
@article = article
post path: "/articles"
end
end
declare_template ArticleClient, "create.json.erb", <<~ERB
<%= { title: @article.title }.to_json %>
ERB
article = Article.new(nil, "Article Title")
request = ArticleClient.create(article: article)
assert_equal "POST", request.method
assert_equal "https://example.com/articles", request.original_url
assert_equal({ "title" => "Article Title" }, JSON.parse(request.body.read))
assert_equal "application/json", request.headers["Content-Type"]
end
test "constructs a GET request without declaring a body template" do
class ArticleClient < BaseClient
default headers: { "Content-Type": "application/json" }
def all
get path: "/articles"
end
end
request = ArticleClient.all
assert_equal "GET", request.method
assert_equal "https://example.com/articles", request.original_url
assert_predicate request.body.read, :blank?
assert_equal "application/json", request.headers["Content-Type"]
end
test "constructs an OPTIONS request without declaring a body template" do
class ArticleClient < BaseClient
def status
options path: "/status"
end
end
request = ArticleClient.status
assert_equal "OPTIONS", request.method
assert_equal "https://example.com/status", request.original_url
assert_predicate request.body.read, :blank?
end
test "constructs a HEAD request without declaring a body template" do
class ArticleClient < BaseClient
def status
head path: "/status"
end
end
request = ArticleClient.status
assert_equal "HEAD", request.method
assert_equal "https://example.com/status", request.original_url
assert_predicate request.body.read, :blank?
end
test "constructs a TRACE request without declaring a body template" do
class ArticleClient < BaseClient
def status
trace path: "/status"
end
end
request = ArticleClient.status
assert_equal "TRACE", request.method
assert_equal "https://example.com/status", request.original_url
assert_predicate request.body.read, :blank?
end
test "constructs a DELETE request without declaring a body template" do
class ArticleClient < BaseClient
default headers: {
"Content-Type": "application/json",
}
def destroy(article:)
delete path: "/articles/#{article.id}"
end
end
article = Article.new("1", nil)
request = ArticleClient.destroy(article: article)
assert_equal "DELETE", request.method
assert_equal "https://example.com/articles/1", request.original_url
assert_predicate request.body.read, :blank?
assert_equal "application/json", request.headers["Content-Type"]
end
test "constructs a DELETE request with a JSON body template" do
class ArticleClient < BaseClient
def destroy(article:)
delete path: "/articles/#{article.id}"
end
end
article = Article.new("1", nil)
declare_template ArticleClient, "destroy.json", <<~JS
{"confirm": true}
JS
request = ArticleClient.destroy(article: article)
assert_equal "DELETE", request.method
assert_equal "https://example.com/articles/1", request.original_url
assert_equal({ "confirm"=> true }, JSON.parse(request.body.read))
assert_equal "application/json", request.headers["Content-Type"]
end
test "constructs a PUT request with a JSON body declared with locals" do
class ArticleClient < BaseClient
def update(article:)
put path: "/articles/#{article.id}", locals: {
article: article,
}
end
end
declare_template ArticleClient, "update.json.erb", <<~ERB
<%= { title: article.title }.to_json %>
ERB
article = Article.new("1", "Article Title")
request = ArticleClient.update(article: article)
assert_equal "PUT", request.method
assert_equal "https://example.com/articles/1", request.original_url
assert_equal({ "title" => "Article Title" }, JSON.parse(request.body.read))
assert_equal "application/json", request.headers["Content-Type"]
end
test "constructs a PATCH request with an XML body declared with locals" do
class ArticleClient < BaseClient
def update(article:)
patch path: "/articles/#{article.id}", locals: {
article: article,
}
end
end
declare_template ArticleClient, "update.xml.erb", <<~ERB
<xml><%= article.title %></xml>
ERB
article = Article.new("1", "Article Title")
request = ArticleClient.update(article: article)
assert_equal "PATCH", request.method
assert_equal "https://example.com/articles/1", request.original_url
assert_equal "<xml>Article Title</xml>", request.body.read.strip
assert_equal "application/xml", request.headers["Content-Type"]
end
test "constructs a request with a body wrapped by a layout" do
class ArticleClient < BaseClient
def create(article:)
post \
layout: "article_client",
locals: { article: article },
url: "https://example.com/special/articles"
end
end
declare_layout "article_client.json.erb", <<~ERB
{ "response": <%= yield %> }
ERB
declare_template ArticleClient, "create.json.erb", <<~ERB
{ "title": "<%= article.title %>" }
ERB
article = Article.new(nil, "From Layout")
request = ArticleClient.create(article: article)
assert_equal(
{ "response" => { "title" => "From Layout" } },
JSON.parse(request.body.read)
)
end
test "constructs a request with the full URL passed as an option" do
class ArticleClient < BaseClient
def create(article:)
post url: "https://example.com/special/articles"
end
end
request = ArticleClient.create(article: nil)
assert_equal "https://example.com/special/articles", request.original_url
end
test "constructs a request with additional headers" do
class ArticleClient < BaseClient
default headers: {
"Content-Type": "application/json",
}
def create(article:)
post path: "/articles", headers: {
"X-My-Header": "hello!",
}
end
end
request = ArticleClient.create(article: nil)
assert_equal "application/json", request.headers["Content-Type"]
assert_equal "hello!", request.headers["X-My-Header"]
end
test "constructs a request with overridden headers" do
class ArticleClient < BaseClient
default headers: {
"Content-Type": "application/json",
}
def create(article:)
post path: "/articles", headers: {
"Content-Type": "application/xml",
}
end
end
request = ArticleClient.create(article: nil)
assert_equal "application/xml", request.headers["Content-Type"]
end
test "raises an ArgumentError when both url: and path: are provided" do
class ArticleClient < BaseClient
def create(article:)
post url: "ignored", path: "ignored"
end
end
assert_raises ArgumentError do
ArticleClient.create(article: nil)
end
end
end
class ResponsesTest < ClientTestCase
test "#submit makes an appropriate HTTP request" do
class ArticleClient < BaseClient
def create(article:)
post path: "/articles", locals: { article: article }
end
end
declare_template ArticleClient, "create.json.erb", <<~ERB
<%= { title: article.title }.to_json %>
ERB
article = Article.new(nil, "Article Title")
stub_request(:any, Regexp.new("example.com")).and_return(
body: %({"responded": true}),
headers: {"Content-Type": "application/json"},
status: 201,
)
code, headers, body = ArticleClient.create(article: article).submit
assert_equal code, 201
assert_equal body, {"responded" => true}
assert_requested :post, "https://example.com/articles", {
body: {"title": "Article Title"},
headers: { "Content-Type" => "application/json" },
}
end
test "#submit parses a JSON response based on the `Content-Type`" do
class ArticleClient < BaseClient
def create(article:)
post path: "/articles", locals: { article: article }
end
end
declare_template ArticleClient, "create.json.erb", <<~ERB
{"title": "<%= article.title %>"}
ERB
article = Article.new(nil, "Encoded as JSON")
stub_request(:post, %r{example.com}).and_return(
body: {"title": article.title, id: 1}.to_json,
headers: {"Content-Type": "application/json;charset=UTF-8"},
status: 201,
)
status, headers, body = ArticleClient.create(article: article).submit
assert_equal 201, status
assert_equal "application/json;charset=UTF-8", headers["Content-Type"]
assert_equal({"title" => article.title, "id" => 1}, body)
end
test "#submit parses an XML response based on the `Content-Type`" do
class ArticleClient < BaseClient
def create(article:)
post path: "/articles", locals: { article: article }
end
end
declare_template ArticleClient, "create.xml.erb", <<~ERB
<article title="<%= article.title %>"></article>
ERB
article = Article.new(nil, "Encoded as XML")
stub_request(:post, %r{example.com}).and_return(
body: %(<article title="#{article.title}" id="1"></article>),
headers: {"Content-Type": "application/xml"},
status: 201,
)
status, headers, body = ArticleClient.create(article: article).submit
assert_equal 201, status
assert_equal "application/xml", headers["Content-Type"]
assert_equal article.title, body.root["title"]
assert_equal "1", body.root["id"]
end
end
end
|
require_relative 'repository'
require 'time'
class MerchantRepository
include Repository
def initialize(merchants)
@list = merchants
end
def find_all_by_name(name)
@list.find_all do |merchant|
merchant.name.downcase.include?(name)
end
end
def create(attributes)
highest_merchant_id = find_highest_id
attributes[:id] = highest_merchant_id.id + 1
@list << Merchant.new(attributes)
end
def update(id, attributes)
if find_by_id(id)
find_by_id(id).name = attributes[:name]
end
attributes[:updated_at] = Time.now
end
end
|
class App < ActiveRecord::Base
attr_accessible :name, :url, :description, :location, :logo,
:enabled, :app_pictures_attributes
validates_presence_of :name, :url, :description, :location, :logo
has_many :app_pictures
accepts_nested_attributes_for :app_pictures, allow_destroy: true
scope :active, lambda { |*obj| where(:enabled => true) }
mount_uploader :logo, LogoUploader
def has_app_pictures?
app_pictures.length > 0
end
def calculate_frames
if app_pictures.length % 2 == 0
app_pictures.length / 2
else
(app_pictures.length / 2) + 1
end
end
def no_of_frames
has_app_pictures? ? calculate_frames : 0
end
end
|
# Calculate the mode Pairing Challenge
# I worked on this challenge [by myself, with: ]
# I spent [] hours on this challenge.
# Complete each step below according to the challenge directions and
# include it in this file. Also make sure everything that isn't code
# is commented.
# 0. Pseudocode
# What is the input?
# What is the output? (i.e. What should the code return?)
# What are the steps needed to solve the problem?
# Initial
def counting(mode)
counts = Hash.new 0
mode.each do |word|
counts[word] += 1
end
answer = Hash.new
answer = counts.sort_by {|k,v| v}.last.to_a
return answer[0]
end
# Refactor
def counting(mode)
counts = Hash.new 0
mode.each do |word|
counts[word] += 1
end
answer = Hash.new
answer = counts.sort_by {|k,v| v}.last.to_a
return answer[0]
end
# Reflection
# Which data structure did you and your pair decide to implement and why?
# We decided to use a hash because in order to preform the operations that we wanted we need to place the values in an unordered collection and
# also some of the sorting methods we wanted to use were available with hashes but not with arrays.
# Were you more successful breaking this problem down into implementable pseudocode than the last with a pair?
# Yes we were more successful at breaking this problem down into psedocode than with the last challenge because the concepts seemed easier to implement. But once we got
# started the actual coding proved to be alot harder then the last challenge.
# What issues/successes did you run into when translating your pseudocode to code?
# We ran into several issues with breaking down how we would actually grab the most frequent sets of numbers in the collection. Also becuse we couldnt find the right method to get the
# job done we had to pretty much create a solution based on our limited knowledge.
# What methods did you use to iterate through the content? Did you find any good ones when you were refactoring? Were they difficult to implement?
# we used sort_by and a basic incrementor to iterate through the problem. We had difficulty in finding the right methods to get the job done, and eventually we just ran out of time.
|
class AddReferencesToStoreAuth < ActiveRecord::Migration[6.1]
def change
add_reference :stores, :store_auth, foreign_key: true
end
end
|
class CreateComplaints < ActiveRecord::Migration
def change
create_table :complaints do |t|
t.string :title
t.text :desc
t.integer :status, default: 0
t.integer :random, default: 0
t.boolean :view_publically, default: false
t.integer :user_id, null: false
t.timestamps null: false
end
add_index :complaints, :status, using: :btree
add_index :complaints, :title, using: :btree
end
end
|
# Documentation: https://docs.brew.sh/Formula-Cookbook
# https://rubydoc.brew.sh/Formula
class Tser < Formula
desc "A TypeScript virtual machine."
homepage "https://github.com/tser-project/tser"
version "0.0.2"
url "https://github.com/tser-project/tser/releases/download/v#{version}/mac64_#{version}.tar.xz"
sha256 "b0e85fafeb5466d54229e672c9a516c456cdcdf0e2f4fc9c4da7bcd400908f48"
def install
bin.install "bin/tser"
lib.install Dir["lib/*"]
end
end
|
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :deal_site_category
t.string :major_category
t.string :sg_category
t.text :description
t.string :photo
t.timestamps
end
end
end
|
FactoryBot.define do
factory :list do
description { Faker::Lorem.sentence }
is_private { false }
sublist_max_level { 0 }
user
trait :has_parent do
user { nil }
parent_list { association :list }
end
factory :sublist, traits: %i[has_parent]
end
end
|
ActiveAdmin.register Purchase do
controller do
def permitted_params
params.permit!
end
end
form do |f|
f.inputs do
input :email
input :price
input :purchasable_id
input :status
input :start_date
input :contact
input :phone_number
input :pickup
# input :driver_id
# input :vehicle_id
input :reference_id
end
f.actions
end
index do
selectable_column
column :price
column :email
# column :vehicle_id
# column :driver_id
column :purchasable
column :reference_id
column :status
column :start_date
actions
end
show do
attributes_table do
row :id
row :purchasable_id
row :purchasable_type
row :price
row :buyer_id
row :created_at
row :updated_at
row :status
row :email
row :start_date
row :country
row :contact
row :driver_id
row :vehicle_id
row :comments
row :email_confirmation
row :country_code
row :phone_number
row :pickup
row :reference_id
row :address_id
row :tour_id
row :pickup_time
row :traveller_number
row :first_name
row :last_name
row :passport_number
row :nationality
row :vehicle_type
row 'Location', :latlng do |obj|
div id:'map', "data-latlng": obj.latlng do
end
end
end
end
end
|
class Team < ApplicationRecord
belongs_to :tournament
validates :name, presence: true, uniqueness: { scope: :tournament_id }
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
helper :all
layout "application"
rescue_from Exception, :with => :my_log_error
rescue_from ActiveRecord::RecordNotFound, :with => :my_log_error
rescue_from ActionController::UnknownController, :with => :my_log_error
rescue_from ActionController::UnknownAction, :with => :my_log_error
RECORDS_PER_PAGE = 20
def is_administrator?
unless current_user and current_user.admin?
flash[:error] = "You do not have permission for that page."
redirect_to root_path
end
end
def setup_session_defaults_for_controller(controller_sym, default_field = :name)
session[:sorters] ||= {}
session[:sorters][controller_sym] ||= {}
session[:sorters][controller_sym][:field] ||= default_field
session[:sorters][controller_sym][:order] ||= 'ASC'
session[controller_sym] ||= {}
session[controller_sym][:property_id] ||= 0
session[controller_sym][:name] ||= ""
session[controller_sym][:page_id] ||= 1
if params[:name_restrict]
session[controller_sym][:name] = params[:name_restrict]
end
if params[:property_id]
session[controller_sym][:property_id] = params[:property_id].to_i
end
if params[:sort_by]
session[:sorters][controller_sym][:field] = params[:sort_by].to_sym
session[:sorters][controller_sym][:order] = params[:sort_order]
end
if params[:page]
session[controller_sym][:page_id] = params[:page].to_i
end
end
def build_query(model, controller_sym)
build_it = model.order("#{session[:sorters][controller_sym][:field]} #{session[:sorters][controller_sym][:order]}")
unless session[controller_sym][:name].blank?
if session[controller_sym][:name].match(/%/)
build_it = build_it.where(["LOWER(#{model.search_field}) like ?", session[controller_sym][:name].downcase])
else
build_it = build_it.where(["LOWER(#{model.search_field}) like ?", "%#{session[controller_sym][:name].downcase}%"])
end
end
if model == Client
build_it = build_it.joins(:company)
end
build_it = build_it.joins(:property)
unless session[controller_sym][:property_id] == 0
if current_user.admin? or current_user.all_properties.collect{|r| r.id}.include?(session[controller_sym][:property_id])
build_it = build_it.where({:property_id => session[controller_sym][:property_id]})
else
build_it = build_it.where({:property_id => current_user.all_properties.collect{|c| c.id}})
end
else
unless current_user.admin?
build_it = build_it.where({:property_id => current_user.all_properties.collect{|c| c.id}})
end
end
if session[controller_sym][:page_id] == 0
session[controller_sym][:page_id] = 1
elsif session[controller_sym][:page_id] > 1
if (session[controller_sym][:page_id] - 1) * RECORDS_PER_PAGE > build_it.size
session[controller_sym][:page_id] = 1
end
end
build_it = build_it.page(session[controller_sym][:page_id])
build_it
end
private
def my_log_error(exception)
SurveyMailer.error_message(exception,
ActiveSupport::BacktraceCleaner.new.clean(exception.backtrace),
session.instance_variable_get("@data"),
params,
request.env,
current_user,
request.env['HTTP_HOST'].match(/survey\.vaecorp\.com/)
).deliver
#redirect_to '/500.html'
render :file => "public/500.html", :layout => false, :status => 500
end
end
|
# frozen_string_literal: true
require 'rspec/sleeping_king_studios/concerns/shared_example_group'
require 'stannum/rspec/match_errors'
require 'support/examples'
module Spec::Support::Examples
module ConstraintExamples
extend RSpec::SleepingKingStudios::Concerns::SharedExampleGroup
include Stannum::RSpec::Matchers
shared_examples 'should implement the Constraint interface' do
describe '#does_not_match?' do
it 'should define the method' do
expect(subject).to respond_to(:does_not_match?).with(1).argument
end
end
describe '#errors_for' do
it 'should define the method' do
expect(subject)
.to respond_to(:errors_for)
.with(1).argument
.and_keywords(:errors)
end
end
describe '#match' do
it { expect(subject).to respond_to(:match).with(1).argument }
end
describe '#matches?' do
it { expect(subject).to respond_to(:matches?).with(1).argument }
it { expect(subject).to have_aliased_method(:matches?).as(:match?) }
end
describe '#message' do
include_examples 'should have reader', :message
end
describe '#negated_errors_for' do
let(:actual) { Object.new.freeze }
it 'should define the method' do
expect(subject)
.to respond_to(:negated_errors_for)
.with(1).argument
.and_keywords(:errors)
end
end
describe '#negated_match' do
it 'should define the method' do
expect(subject).to respond_to(:negated_match).with(1).argument
end
end
describe '#negated_message' do
include_examples 'should have reader', :negated_message
end
describe '#negated_type' do
include_examples 'should have reader', :negated_type
end
describe '#options' do
include_examples 'should have reader', :options
end
describe '#type' do
include_examples 'should have reader', :type
end
describe '#with_options' do
it { expect(subject).to respond_to(:with_options).with_any_keywords }
end
end
shared_examples 'should implement the Constraint methods' do
describe '#clone' do
let(:copy) { subject.clone }
it { expect(copy).not_to be subject }
it { expect(copy).to be_a described_class }
it { expect(copy.options).to be == subject.options }
it 'should duplicate the options' do
expect { copy.options.update(key: 'value') }
.not_to change(subject, :options)
end
end
describe '#dup' do
let(:copy) { subject.dup }
it { expect(copy).not_to be subject }
it { expect(copy).to be_a described_class }
it { expect(copy.options).to be == subject.options }
it 'should duplicate the options' do
expect { copy.options.update(key: 'value') }
.not_to change(subject, :options)
end
end
describe '#errors_for' do
it { expect(subject.errors_for nil).to be_a Stannum::Errors }
end
describe '#match' do
it 'should return an array with two items' do
expect(subject.match(nil))
.to be_a(Array)
.and(have_attributes(size: 2))
end
it { expect(subject.match(nil).first).to be_boolean }
it { expect(subject.match(nil).last).to be_a(Stannum::Errors) }
end
describe '#negated_errors_for' do
it { expect(subject.negated_errors_for nil).to be_a Stannum::Errors }
end
describe '#negated_match' do
it 'should return an array with two items' do
expect(subject.negated_match(nil))
.to be_a(Array)
.and(have_attributes(size: 2))
end
it { expect(subject.negated_match(nil).first).to be_boolean }
it { expect(subject.negated_match(nil).last).to be_a(Stannum::Errors) }
end
describe '#negated_type' do
it { expect(subject.type).to be == described_class::TYPE }
context 'when initialized with negated_type: value' do
let(:constructor_options) do
super().merge(negated_type: 'spec.negated_type')
end
it { expect(subject.negated_type).to be == 'spec.negated_type' }
end
end
describe '#options' do
let(:expected_options) do
defined?(super()) ? super() : constructor_options
end
it { expect(subject.options).to deep_match expected_options }
context 'when initialized with options' do
let(:constructor_options) { super().merge(key: 'value') }
let(:expected_options) { super().merge(key: 'value') }
it { expect(subject.options).to deep_match expected_options }
end
end
describe '#type' do
it { expect(subject.type).to be == described_class::TYPE }
context 'when initialized with type: value' do
let(:constructor_options) { super().merge(type: 'spec.type') }
it { expect(subject.type).to be == 'spec.type' }
end
end
describe '#with_options' do
let(:options) { {} }
let(:copy) { subject.with_options(**options) }
it { expect(copy).not_to be subject }
it { expect(copy).to be_a described_class }
it { expect(copy.options).to be == subject.options }
it 'should duplicate the options' do
expect { copy.options.update(key: 'value') }
.not_to change(subject, :options)
end
describe 'with options' do
let(:options) { { key: 'value' } }
let(:expected_options) { subject.options.merge(options) }
it { expect(copy.options).to be == expected_options }
end
end
end
shared_examples 'should match the constraint' do
let(:actual_status) do
status, _ = subject.send(match_method, actual)
status
end
let(:actual_errors) do
_, errors = subject.send(match_method, actual)
errors
end
it { expect(actual_status).to be true }
it { expect(actual_errors).to match_errors(Stannum::Errors.new) }
end
shared_examples 'should not match the constraint' do
let(:actual_status) do
status, _ = subject.send(match_method, actual)
status
end
let(:actual_errors) do
_, errors = subject.send(match_method, actual)
errors
end
let(:wrapped_errors) do
errors =
if expected_errors.is_a?(Array)
expected_errors
else
[expected_errors]
end
errors
.map do |error|
{
data: {},
message: nil,
path: []
}.merge(error)
end
end
let(:wrapped_messages) do
# :nocov:
errors =
if expected_messages.is_a?(Array)
expected_messages
else
[expected_messages]
end
# :nocov:
errors
.map do |error|
{
data: {},
message: nil,
path: []
}.merge(error)
end
end
it { expect(actual_status).to be false }
it { expect(actual_errors).to match_errors wrapped_errors }
if instance_methods.include?(:expected_messages)
it 'should generate the error messages' do
expect(actual_errors.with_messages).to match_errors wrapped_messages
end
end
end
shared_examples 'should match the type constraint' do
describe 'with nil' do
let(:actual) { nil }
include_examples 'should not match the constraint'
end
describe 'with a non-matching object' do
let(:actual) { Object.new.freeze }
include_examples 'should not match the constraint'
end
describe 'with a matching object' do
let(:actual) { matching }
include_examples 'should match the constraint'
end
context 'when the constraint is optional' do
let(:constructor_options) { super().merge(required: false) }
describe 'with nil' do
let(:actual) { nil }
include_examples 'should match the constraint'
end
describe 'with a non-matching object' do
let(:actual) { Object.new.freeze }
include_examples 'should not match the constraint'
end
describe 'with a matching object' do
let(:actual) { matching }
include_examples 'should match the constraint'
end
end
end
shared_examples 'should match the negated type constraint' do
describe 'with nil' do
let(:actual) { nil }
include_examples 'should match the constraint'
end
describe 'with a non-matching object' do
let(:actual) { Object.new.freeze }
include_examples 'should match the constraint'
end
describe 'with a matching object' do
let(:actual) { matching }
include_examples 'should not match the constraint'
end
context 'when the constraint is optional' do
let(:constructor_options) { super().merge(required: false) }
describe 'with nil' do
let(:actual) { nil }
include_examples 'should not match the constraint'
end
describe 'with a non-matching object' do
let(:actual) { Object.new.freeze }
include_examples 'should match the constraint'
end
describe 'with a matching object' do
let(:actual) { matching }
include_examples 'should not match the constraint'
end
end
end
end
end
|
require 'test_helper'
class TranslatableTest < ActiveSupport::TestCase
test 'not update phraseapp translation if force flag is not set' do
orga = build(:orga)
orga.expects(:update_or_create_translations).never
orga.save
end
test 'not upload translation if no attributes are changed' do
orga = create(:orga)
PhraseAppClient.any_instance.expects(:upload_translation_file_for_locale).never
orga.update_or_create_translations
end
test 'build json for phraseapp' do
VCR.use_cassette('generate_json_for_phraseapp') do
orga = create(:orga)
Orga::translatable_attributes.each do |attribute|
orga.send("#{attribute}=", "#{Time.current.to_s} change xyz")
end
hash = orga.send(:create_json_for_translation_file)
assert_equal ['orga'], hash.keys
rendered_orgas = hash.values
assert_equal 1, rendered_orgas.count
rendered_orga = rendered_orgas.first
assert_equal 1, rendered_orga.keys.count
assert_equal orga.id.to_s, rendered_orga.keys.first
attributes = rendered_orga.values.first
assert_equal Orga::translatable_attributes.map(&:to_s), attributes.keys
attributes.each do |attribute, value|
assert_equal orga.send(attribute), value
end
end
end
test 'create translation on entry create' do
orga = build(:orga, title: 'testorga')
orga.force_translation_after_save = true
PhraseAppClient.any_instance.expects(:upload_translation_file_for_locale).with do |file, phraseapp_locale_id, tags_hash|
orga_id = Orga.last.id.to_s
file = File.read(file)
json = JSON.parse(file)
assert_not_nil json['orga']
assert_not_nil json['orga'][orga_id]
assert_equal 'testorga', json['orga'][orga_id]['title']
assert_equal 'this is the short description', json['orga'][orga_id]['short_description']
assert_equal Translatable::DEFAULT_LOCALE, phraseapp_locale_id
assert_equal 'dresden', tags_hash[:tags]
end
assert orga.save
end
test 'create translation on facet_item create' do
facet_item = build(:facet_item, title: 'New Category')
facet_item.force_translation_after_save = true
facet_item.facet.save!
PhraseAppClient.any_instance.expects(:upload_translation_file_for_locale).with do |file, phraseapp_locale_id, tags_hash|
facet_item_id = DataPlugins::Facet::FacetItem.last.id.to_s
file = File.read(file)
json = JSON.parse(file)
assert_not_nil json['facet_item']
assert_not_nil json['facet_item'][facet_item_id]
assert_equal 'New Category', json['facet_item'][facet_item_id]['title']
assert_equal Translatable::DEFAULT_LOCALE, phraseapp_locale_id
assert_nil tags_hash
end
facet_item.save!
end
test 'create translation on navigation_item create' do
navigation_item = build(:fe_navigation_item, title: 'New Navigation Item')
navigation_item.force_translation_after_save = true
navigation_item.navigation.save!
PhraseAppClient.any_instance.expects(:upload_translation_file_for_locale).with do |file, phraseapp_locale_id, tags_hash|
navigation_item_id = DataModules::FeNavigation::FeNavigationItem.last.id.to_s
file = File.read(file)
json = JSON.parse(file)
assert_not_nil json['navigation_item']
assert_not_nil json['navigation_item'][navigation_item_id]
assert_equal 'New Navigation Item', json['navigation_item'][navigation_item_id]['title']
assert_equal Translatable::DEFAULT_LOCALE, phraseapp_locale_id
assert_equal 'dresden', tags_hash[:tags]
end
navigation_item.save!
end
test 'not create translation on entry create if related attributes are empty' do
orga = build(:orga)
orga.force_translation_after_save = true
orga.title = ''
orga.short_description = ''
PhraseAppClient.any_instance.expects(:upload_translation_file_for_locale).never
assert orga.save(validate: false)
end
test 'only create translation for nonempty attributes on entry create' do
orga = build(:orga)
orga.force_translation_after_save = true
orga.title = ''
PhraseAppClient.any_instance.expects(:upload_translation_file_for_locale).with do |file, phraseapp_locale_id, tags_hash|
orga_id = Orga.last.id.to_s
file = File.read(file)
json = JSON.parse(file)
assert_not_nil json['orga']
assert_not_nil json['orga'][orga_id]
assert_nil json['orga'][orga_id]['title']
assert_equal 'this is the short description', json['orga'][orga_id]['short_description']
assert_equal Translatable::DEFAULT_LOCALE, phraseapp_locale_id
assert_equal 'dresden', tags_hash[:tags]
end
assert orga.save(validate: false)
end
test 'set area tag on create translation' do
orga = build(:orga)
orga.area = 'heinz_landkreis'
orga.force_translation_after_save = true
PhraseAppClient.any_instance.expects(:upload_translation_file_for_locale).with do |file, phraseapp_locale_id, tags_hash|
assert_equal 'heinz_landkreis', tags_hash[:tags]
end
assert orga.save
end
test 'update translation on entry update' do
orga = create(:orga)
orga_id = orga.id.to_s
orga.force_translation_after_save = true
PhraseAppClient.any_instance.expects(:upload_translation_file_for_locale).with do |file, phraseapp_locale_id, tags_hash|
file = File.read(file)
json = JSON.parse(file)
assert_not_nil json['orga']
assert_not_nil json['orga'][orga_id]
assert_equal 'foo-bar', json['orga'][orga_id]['title']
assert_equal 'short-fo-ba', json['orga'][orga_id]['short_description']
assert_equal Translatable::DEFAULT_LOCALE, phraseapp_locale_id
assert_equal 'dresden', tags_hash[:tags]
end
assert orga.update(title: 'foo-bar', short_description: 'short-fo-ba')
end
test 'update translation on facet_item update' do
facet_item = create(:facet_item, title: 'New Category')
facet_item_id = facet_item.id.to_s
facet_item.force_translation_after_save = true
PhraseAppClient.any_instance.expects(:upload_translation_file_for_locale).with do |file, phraseapp_locale_id, tags_hash|
file = File.read(file)
json = JSON.parse(file)
assert_not_nil json['facet_item']
assert_not_nil json['facet_item'][facet_item_id]
assert_equal 'Super Category', json['facet_item'][facet_item_id]['title']
assert_equal Translatable::DEFAULT_LOCALE, phraseapp_locale_id
assert_nil tags_hash
end
assert facet_item.update(title: 'Super Category')
end
test 'update translation on navigation_item update' do
navigation_item = create(:fe_navigation_item, title: 'New Navigation Entry')
navigation_item_id = navigation_item.id.to_s
navigation_item.force_translation_after_save = true
PhraseAppClient.any_instance.expects(:upload_translation_file_for_locale).with do |file, phraseapp_locale_id, tags_hash|
file = File.read(file)
json = JSON.parse(file)
assert_not_nil json['navigation_item']
assert_not_nil json['navigation_item'][navigation_item_id]
assert_equal 'Homepage', json['navigation_item'][navigation_item_id]['title']
assert_equal Translatable::DEFAULT_LOCALE, phraseapp_locale_id
assert_equal 'dresden', tags_hash[:tags]
end
assert navigation_item.update(title: 'Homepage')
end
test 'set area tag on update translation' do
orga = create(:orga)
orga.area = 'heinz_landkreis'
orga.force_translation_after_save = true
PhraseAppClient.any_instance.expects(:upload_translation_file_for_locale).with do |file, phraseapp_locale_id, tags_hash|
assert_equal 'heinz_landkreis', tags_hash[:tags]
end
assert orga.update(title: 'foo-bar', short_description: 'short-fo-ba')
end
test 'update translation on entry update only once' do
orga = create(:orga)
orga.force_translation_after_save = true
PhraseAppClient.any_instance.expects(:upload_translation_file_for_locale).once.with do |file, phraseapp_locale_id, tags_hash|
assert true
end
assert orga.update(title: 'foo-bar', short_description: 'short-fo-ba')
assert orga.update(title: 'foo-bar', short_description: 'short-fo-ba')
end
test 'not update translation on entry update if all related attributes are empty' do
orga = create(:orga)
orga.force_translation_after_save = true
PhraseAppClient.any_instance.expects(:upload_translation_file_for_locale).never
orga.assign_attributes(title: '', short_description: '')
assert orga.save(validate: false)
end
test 'only update translation for nonempty attributes on entry update' do
orga = create(:orga)
orga.force_translation_after_save = true
PhraseAppClient.any_instance.expects(:upload_translation_file_for_locale).with do |file, phraseapp_locale_id, tags_hash|
orga_id = Orga.last.id.to_s
file = File.read(file)
json = JSON.parse(file)
assert_not_nil json['orga']
assert_not_nil json['orga'][orga_id]
assert_nil json['orga'][orga_id]['title']
assert_equal 'short-fo-ba', json['orga'][orga_id]['short_description']
assert_equal Translatable::DEFAULT_LOCALE, phraseapp_locale_id
assert_equal 'dresden', tags_hash[:tags]
end
orga.assign_attributes(title: '', short_description: 'short-fo-ba')
assert orga.save(validate: false)
end
test 'remove translations of all attributes on entry delete' do
orga = create(:orga)
orga.force_translation_after_save = true
PhraseAppClient.any_instance.expects(:delete_translation).with do |orga_to_delete|
assert_equal orga, orga_to_delete
end
assert orga.destroy
end
test 'remove translations of all attributes on facet_item delete' do
facet_item = create(:facet_item, title: 'New Category')
facet_item.force_translation_after_save = true
PhraseAppClient.any_instance.expects(:delete_translation).with do |facet_item_to_delete|
assert_equal facet_item, facet_item_to_delete
end
assert facet_item.destroy
end
test 'remove translations of all attributes on navigation_item delete' do
navigation_item = create(:fe_navigation_item, title: 'Best Page')
navigation_item.force_translation_after_save = true
PhraseAppClient.any_instance.expects(:delete_translation).with do |navigation_item_to_delete|
assert_equal navigation_item, navigation_item_to_delete
end
assert navigation_item.destroy
end
# fapi cache integration
[:orga, :event, :offer].each do |entry_factory|
should "create fapi cache job on entry create for #{entry_factory}" do
entry = build(entry_factory)
FapiCacheJob.any_instance.expects(:update_entry_translation).never
entry.save!
end
end
test 'create fapi cache job if facet item is created' do
facet_item = build(:facet_item, title: 'New Category')
facet_item.facet.save!
FapiCacheJob.any_instance.expects(:update_entry_translation).never
facet_item.save!
end
test 'create fapi cache job if navigation item is created' do
navigation_item = build(:fe_navigation_item, title: 'New Entry')
navigation_item.navigation.save!
FapiCacheJob.any_instance.expects(:update_entry_translation).never
navigation_item.save!
end
[:orga, :event, :offer].each do |entry_factory|
should "create fapi cache job on entry update for #{entry_factory}" do
entry = create(entry_factory)
FapiCacheJob.any_instance.expects(:update_entry_translation).with(entry, 'de')
entry.update!(title: 'new title')
end
end
test 'create fapi cache job if facet item is updated' do
facet_item = create(:facet_item, title: 'New Category')
FapiCacheJob.any_instance.expects(:update_entry_translation).with(facet_item, 'de')
facet_item.update!(title: 'new title')
end
test 'create fapi cache job if navigation item is updated' do
navigation_item = create(:fe_navigation_item, title: 'New Entry')
FapiCacheJob.any_instance.expects(:update_entry_translation).with(navigation_item, 'de')
navigation_item.update!(title: 'new title')
end
[:orga, :event, :offer].each do |entry_factory|
should "create fapi cache job on entry delete for #{entry_factory}" do
entry = create(entry_factory)
FapiCacheJob.any_instance.expects(:update_entry_translation).never
entry.destroy
end
end
test 'create fapi cache job if facet item is deleted' do
facet_item = create(:facet_item, title: 'New Category')
FapiCacheJob.any_instance.expects(:update_entry_translation).never
facet_item.destroy
end
test 'create fapi cache job if navigation item is deleted' do
navigation_item = create(:fe_navigation_item, title: 'New Entry')
FapiCacheJob.any_instance.expects(:update_entry_translation).never
navigation_item.destroy
end
end
|
require 'legacy_migration_spec_helper'
require 'base64'
TYPE_MAP = {
"image/png" => "PNG",
"image/jpeg" => "JPEG",
"image/gif" => "GIF"
}
describe ImageMigrator do
describe ".migrate" do
before :all do
ImageMigrator.migrate
end
describe "copying the data" do
it "gives an image attachment to all users who had profile images" do
legacy_users_with_images = Legacy.connection.select_all("select * from edc_user where image_id is not null")
User.where("image_file_name is not null").count.should == legacy_users_with_images.length
legacy_users_with_images.each do |legacy_user|
new_user = User.find_by_legacy_id(legacy_user["id"])
image_id = legacy_user["image_id"]
image_instance_row = Legacy.connection.select_one("select * from edc_image_instance where image_id = '#{image_id}' and type = 'original'")
image_row = Legacy.connection.select_one("select * from edc_image where id = '#{image_id}'")
type = TYPE_MAP[image_row["type"]]
width = image_instance_row["width"]
height = image_instance_row["length"]
g = Paperclip::Geometry.from_file(new_user.image.path(:original))
g.width.should == width
g.height.should == height
end
end
it "gives an image attachment to all workspaces which had icons" do
legacy_workspaces_with_images = Legacy.connection.select_all("select * from edc_workspace where icon_id is not null")
Workspace.where("image_file_name is not null").count.should == legacy_workspaces_with_images.length
legacy_workspaces_with_images.each do |legacy_workspace|
new_workspace = Workspace.find_by_legacy_id(legacy_workspace["id"])
icon_id = legacy_workspace["icon_id"]
image_instance_row = Legacy.connection.select_one("select * from edc_image_instance where image_id = '#{icon_id}' and type = 'original'")
image_row = Legacy.connection.select_one("select * from edc_image where id = '#{icon_id}'")
type = TYPE_MAP[image_row["type"]]
width = image_instance_row["width"]
height = image_instance_row["length"]
g = Paperclip::Geometry.from_file(new_workspace.image.path(:original))
g.width.should == width
g.height.should == height
end
end
end
end
end
|
class LocationSerializer < ActiveModel::Serializer
attributes :name, :external_id
end
|
# Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
Rails.backtrace_cleaner.remove_silencers!
# Add backtrace silencer
# Default silencer is removing backtrace involving engines files
# Our silencer also checks for engines directory
# Ref: https://github.com/rails/rails/blob/master/railties/lib/rails/backtrace_cleaner.rb
Rails.backtrace_cleaner.add_silencer do |line|
!(Rails::BacktraceCleaner::APP_DIRS_PATTERN.match?(line) || /^engines/.match?(line))
end
|
# add class for each move
class Move
VALUES = ['rock', 'paper', 'scissors', 'lizard', 'spock'].freeze
def initialize(value)
@value = value
end
def to_s
@value
end
end
class Rock < Move
def >(other_move)
other_move == 'scissors' || other_move == 'lizard'
end
def <(other_move)
other_move == 'spock' || other_move == 'paper'
end
end
class Paper < Move
def >(other_move)
other_move == 'spock' || other_move == 'rock'
end
def <(other_move)
other_move == 'scissors' || other_move == 'lizard'
end
end
class Scissors < Move
def >(other_move)
other_move == 'lizard' || other_move == 'paper'
end
def <(other_move)
other_move == 'spock' || other_move == 'rock'
end
end
class Lizard < Move
def >(other_move)
other_move == 'paper' || other_move == 'spock'
end
def <(other_move)
other_move == 'rock' || other_move == 'scissors'
end
end
class Spock < Move
def >(other_move)
other_move == 'rock' || other_move == 'scissors'
end
def <(other_move)
other_move == 'paper' || other_move == 'lizard'
end
end
class Player
attr_accessor :move, :name, :score
def initialize
set_name
self.score = 0
end
def increase_score
self.score += 1
end
end
class Human < Player
def set_name
n = nil
loop do
puts "=================="
print "Please introduce yourself to your opponent. \nWhat is your name: "
n = gets.chomp
break unless n.empty?
puts "Sorry, must enter a value."
end
self.name = n
end
def choose
puts "=================="
puts "#{name}, please choose rock, paper, scissors, lizard, or spock:"
choice = nil
loop do
choice = gets.chomp.downcase
break if Move::VALUES.include? choice
puts "Sorry, invalid choice."
end
self.move = Move.new(choice)
end
end
class Computer < Player
def set_name
self.name = ['R2D2', 'Hal', 'Chappie', 'Sarah', 'Beth'].sample
puts "You will be playing against #{name}."
end
def choose
self.move = Move.new(Move::VALUES.sample)
end
end
class RPSGame
attr_accessor :human, :computer
def initialize
@human = Human.new
@computer = Computer.new
@@game_over = false
end
def display_moves
puts "--------"
puts "#{human.name} chose #{human.move}."
puts "#{computer.name} chose #{computer.move}."
puts "--------"
end
def display_winner
if get_result(human.move.to_s) > computer.move.to_s
puts "#{human.name} won!"
human.increase_score
elsif get_result(human.move.to_s) < computer.move.to_s
puts "#{computer.name} won!"
computer.increase_score
else
puts "It's a tie!"
end
display_scoreboard
end
def display_scoreboard
puts "--------"
puts "#{human.name}: #{human.score}"
puts "#{computer.name}: #{computer.score}"
puts "--------"
if human.score == 3
puts "#{human.name} won 'Best of Three'."
@@game_over = true
elsif computer.score == 3
puts "#{computer.name} won 'Best of Three'."
@@game_over = true
end
end
def play
loop do
human.choose
computer.choose
display_moves
display_winner
break if @@game_over
play_again?
end
end
end
def get_result(human_move)
case human_move
when 'rock' then Rock.new('rock')
when 'paper' then Paper.new('paper')
when 'scissors' then Scissors.new('scissors')
when 'lizard' then Lizard.new('lizard')
when 'spock' then Spock.new('spock')
end
end
def display_welcome_message
puts "Welcome to Rock, Paper, Scissors, Lizard, Spock!"
end
def display_goodbye_message
puts "=================="
puts "Thanks for playing Rock, Paper, Scissors, Lizard, Spock. Goodbye!"
exit
end
def play_again?
answer = nil
loop do
puts "Would you like to play again? (y/n)"
answer = gets.chomp.downcase
break if ['y', 'n'].include? answer
puts "Sorry, must be 'y' or 'n'."
end
return true if answer == 'y'
if answer == 'n'
display_goodbye_message
end
end
display_welcome_message
loop do
RPSGame.new.play
break unless play_again?
end
# In the code, the comparison logic moved into each individual move class, a new method called get_result was added, and the values for the comparison statements needed to be accessed differently. As was pointed out in the walk through, having each move be a class is not necessarily intuitive. I felt like I had to hack my way through this one in order to make it work. Nonetheless, the pros of this design is the behaviors for each move type are spearated out. The cons of this design are the > and < methods for each move is repetitive, there is more indirection, and harder to reach code with the added helper method get_result. With such cons, I think the the first design is better.
|
class WorksheetProblem < ActiveRecord::Base
belongs_to :worksheet
belongs_to :math_problem
has_one :problem_level, :through => :math_problem
accepts_nested_attributes_for :math_problem
validates_uniqueness_of :problem_number, :scope => :worksheet_id
validate :worksheet_exists, :math_problem_exists
after_destroy :renumber_remaining_worksheet_problems!
def sibling_count
siblings.count
end
def siblings
worksheet.worksheet_problems - Array(self)
end
def problem_level
math_problem.nil? ? nil : math_problem.problem_level
end
def problem_type_title
problem_level.nil? ? RightRabbitErrors::UNCLASSFIED_PROBLEM : problem_level.problem_type_title
end
def level_number
problem_level.nil? ? nil : problem_level.level_number
end
def instruction
math_problem.instruction
end
def instruction_description
math_problem.instruction_description
end
def classified?
math_problem.nil? ? false : math_problem.classified?
end
def worksheet_title
worksheet.title
end
def replace_math_problem(options = {:exclude => []})
current_problem = self.math_problem
options[:exclude] = options[:exclude].map { |worksheet_problem| worksheet_problem.math_problem } || []
self.math_problem = current_problem.find_problem_from_same_level(options)
save
end
def replacement_available?
similar_worksheet_problems = worksheet.similar_problems_on_worksheet(self)
math_problem.sibling_available?(:exclude => similar_worksheet_problems.map {|wp| wp.math_problem })
end
private
def worksheet_exists
begin
errors.add(:worksheet_id, "doesn't exist") unless (!worksheet.nil? || (worksheet_id && Worksheet.exists?(worksheet_id)))
rescue
errors.add(:worksheet_id, "not found in db")
end
end
def math_problem_exists
begin
errors.add(:math_problem_id, "doesn't exist") unless (!math_problem.nil? || (math_problem_id && MathProblem.exists?(math_problem_id)))
rescue
errors.add(:math_problem_id, "not found in db")
end
end
def renumber_remaining_worksheet_problems!
worksheet.renumber_worksheet_problems!
worksheet.reload
end
end
|
class MoviesController < ApplicationController
def index
@movie = Movie.new
end
def search
@search_word = params[:movie][:title]
@movies = Movie.where("title LIKE ?", "%#{@search_word}%")
if @movies.count > 0
render "search"
else
results = Imdb::Search.new(@search_word)
@movies = results.movies.first(20)
render "search_imdb"
end
end
def create
@movie = Movie.new(movie_params)
if @movie.save
redirect_to movie_path(@movie)
else
flash.now[:alert] = "ERROR!"
render "new"
end
end
def show
@movie = Movie.find_by(id: params[:id])
@comments = @movie.comments
@comment_new = Comment.new
end
private
def movie_params
params.require(:movie).permit(:title, :poster, :year, :synopsis)
end
end
|
class CreateMountains < ActiveRecord::Migration[6.0]
def change
create_table :mountains do |t|
t.text :name
t.integer :height_metres
t.text :country
t.integer :first_ascent
t.timestamps
end
end
end
|
# Exercise 19: Functions and Variables
# https://learnrubythehardway.org/book/ex19.html
# Creates a function with two parameters: cheese_count which is an integer that is the amount of cheese and boxes of cracker which is how many crackers we'll need. The function prints those values into a few strings
def cheese_and_crackers(cheese_count, boxes_of_crackers)
puts "You have #{cheese_count} cheeses!"
puts "You have #{boxes_of_crackers} boxes of crackers"
puts "Man that's enough for a party"
puts "Get a blanket. \n"
end
# Call the function with predefined arguments
puts "We can just give the functions numbers directly:"
cheese_and_crackers(20, 30)
# create two variables that store the arguments and pass the variables into the function
puts "OR, we can use the variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
# call the function by passing some calculations as arguments
puts "We can even do math inside too"
cheese_and_crackers(10 + 20, 5 + 6)
# call the function by pasing some calculations taking into account global variables
puts "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
# The following code is based on study drill 3
# I will create a function an run 10 times in different ways
def to_run_ten_times(say_something, number)
puts "This function will be executed 10 times"
puts "This is the #{number} time"
puts "I am going to say #{say_something}"
end
to_run_ten_times("Well, let's start", 1)
variable_with_sentence = "Hello"
variable_with_number = 2
to_run_ten_times(variable_with_sentence, variable_with_number)
variable_with_sentence = "Hello"*3
to_run_ten_times(variable_with_sentence, variable_with_number + 1)
variable_with_number += 2
to_run_ten_times("Why did I add 2 if I only have to count 1 more?", variable_with_number)
answer = "because by adding a variable plus 1 as an argument does not mean that the variable will store the plus one"
variable_with_number += 1
to_run_ten_times(answer, variable_with_number)
to_run_ten_times(6, "let's swap")
variable_with_sentence = "Getting bored"
variable_with_number += 2
#let's pass only the first argument
to_run_ten_times(variable_with_sentence, nil)
variable_with_number += 1
#let's pass only the second
to_run_ten_times(nil ,variable_with_number)
#let's do it with any argument
to_run_ten_times(nil, nil)
to_run_ten_times("Finally!!!!", "Ten")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.