text stringlengths 10 2.61M |
|---|
require 'test_helper'
class DequeuedMessagesControllerTest < ActionController::TestCase
setup do
@dequeued_message = dequeued_messages(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:dequeued_messages)
end
test "should get new" do
get :new
assert_response :success
end
test "should create dequeued_message" do
assert_difference('DequeuedMessage.count') do
post :create, dequeued_message: { body: @dequeued_message.body }
end
assert_redirected_to dequeued_message_path(assigns(:dequeued_message))
end
test "should show dequeued_message" do
get :show, id: @dequeued_message
assert_response :success
end
test "should get edit" do
get :edit, id: @dequeued_message
assert_response :success
end
test "should update dequeued_message" do
put :update, id: @dequeued_message, dequeued_message: { body: @dequeued_message.body }
assert_redirected_to dequeued_message_path(assigns(:dequeued_message))
end
test "should destroy dequeued_message" do
assert_difference('DequeuedMessage.count', -1) do
delete :destroy, id: @dequeued_message
end
assert_redirected_to dequeued_messages_path
end
end
|
class Place < ApplicationRecord
belongs_to :neighborhood
belongs_to :user, foreign_key: 'creator_id', counter_cache: true
has_many :shared_places
has_many :friends, through: :shared_places, class_name: 'User'
has_one :address, inverse_of: :place
accepts_nested_attributes_for :address
validates_presence_of :name, :neighborhood
def comments
if !shared_places
return []
elsif shared_places
shared_places.collect do |shared_place|
if shared_place.comment != nil && shared_place.comment != ""
shared_place.comment
end
end
end
end
def current_user_shared_place(current_user)
if friends.include?(current_user)
s = shared_places.where(friend_id: current_user.id)
s.first
end
end
def add_comment_to_place(comment, current_user)
s = current_user_shared_place(current_user)
s.comment = comment
s.save
end
def creator
User.where(id: creator_id).first
end
end |
class ForceExecutiveFalse < ActiveRecord::Migration
def up
change_column_default :organization_admins, :executive, false
end
def down
change_column_default :organization_admins, :executive, nil
end
end
|
class Vanagon
class Platform
class OSX < Vanagon::Platform
# Because homebrew does not support being run by root
# we need to have this method to run it in the context of another user
#
# @param build_dependencies [Array] list of all build dependencies to install
# @return [String] a command to install all of the build dependencies
def install_build_dependencies(list_build_dependencies)
<<-HERE.undent
mkdir -p /etc/homebrew
cd /etc/homebrew
su test -c '#{@brew} install #{list_build_dependencies.join(' ')}'
HERE
end
# The specific bits used to generate a osx package for a given project
#
# @param project [Vanagon::Project] project to build a osx package of
# @return [Array] list of commands required to build a osx package for the given project from a tarball
def generate_package(project) # rubocop:disable Metrics/AbcSize
target_dir = project.repo ? output_dir(project.repo) : output_dir
# Here we maintain backward compatibility with older vanagon versions
# that did this by default. This shim should get removed at some point
# in favor of just letting the makefile deliver the bill-of-materials
# to the correct directory. This shouldn't be required at all then.
if project.bill_of_materials.nil?
bom_install = [
# Move bill-of-materials into a docdir
"mkdir -p $(tempdir)/osx/build/root/#{project.name}-#{project.version}/usr/local/share/doc/#{project.name}",
"mv $(tempdir)/osx/build/root/#{project.name}-#{project.version}/bill-of-materials $(tempdir)/osx/build/root/#{project.name}-#{project.version}/usr/local/share/doc/#{project.name}/bill-of-materials",
]
else
bom_install = []
end
if project.extra_files_to_sign.any?
sign_commands = Vanagon::Utilities::ExtraFilesSigner.commands(project, @mktemp, "/osx/build/root/#{project.name}-#{project.version}")
else
sign_commands = []
end
# Setup build directories
["bash -c 'mkdir -p $(tempdir)/osx/build/{dmg,pkg,scripts,resources,root,payload,plugins}'",
"mkdir -p $(tempdir)/osx/build/root/#{project.name}-#{project.version}",
"mkdir -p $(tempdir)/osx/build/pkg",
# Grab distribution xml, scripts and other external resources
"cp #{project.name}-installer.xml $(tempdir)/osx/build/",
#copy the uninstaller to the pkg dir, where eventually the installer will go too
"cp #{project.name}-uninstaller.tool $(tempdir)/osx/build/pkg/",
"cp scripts/* $(tempdir)/osx/build/scripts/",
"if [ -d resources/osx/productbuild ] ; then cp -r resources/osx/productbuild/* $(tempdir)/osx/build/; fi",
# Unpack the project
"gunzip -c #{project.name}-#{project.version}.tar.gz | '#{@tar}' -C '$(tempdir)/osx/build/root/#{project.name}-#{project.version}' --strip-components 1 -xf -",
bom_install,
# Sign extra files
sign_commands,
# Package the project
"(cd $(tempdir)/osx/build/; #{@pkgbuild} --root root/#{project.name}-#{project.version} \
--scripts $(tempdir)/osx/build/scripts \
--identifier #{project.identifier}.#{project.name} \
--version #{project.version} \
--preserve-xattr \
--install-location / \
payload/#{project.name}-#{project.version}-#{project.release}.pkg)",
# Create a custom installer using the pkg above
"(cd $(tempdir)/osx/build/; #{@productbuild} --distribution #{project.name}-installer.xml \
--identifier #{project.identifier}.#{project.name}-installer \
--package-path payload/ \
--resources $(tempdir)/osx/build/resources \
--plugins $(tempdir)/osx/build/plugins \
pkg/#{project.name}-#{project.version}-#{project.release}-installer.pkg)",
# Create a dmg and ship it to the output directory
"(cd $(tempdir)/osx/build; \
#{@hdiutil} create \
-volname #{project.name}-#{project.version} \
-fs JHFS+ \
-format UDBZ \
-srcfolder pkg \
dmg/#{project.package_name})",
"mkdir -p output/#{target_dir}",
"cp $(tempdir)/osx/build/dmg/#{project.package_name} ./output/#{target_dir}"].flatten.compact
end
# Method to generate the files required to build a osx package for the project
#
# @param workdir [String] working directory to stage the evaluated templates in
# @param name [String] name of the project
# @param binding [Binding] binding to use in evaluating the packaging templates
# @param project [Vanagon::Project] Vanagon::Project we are building for
def generate_packaging_artifacts(workdir, name, binding, project) # rubocop:disable Metrics/AbcSize
resources_dir = File.join(workdir, "resources", "osx")
FileUtils.mkdir_p(resources_dir)
script_dir = File.join(workdir, "scripts")
FileUtils.mkdir_p(script_dir)
erb_file(File.join(VANAGON_ROOT, "resources/osx/project-installer.xml.erb"), File.join(workdir, "#{name}-installer.xml"), false, { :binding => binding })
["postinstall", "preinstall"].each do |script_file|
erb_file(File.join(VANAGON_ROOT, "resources/osx/#{script_file}.erb"), File.join(script_dir, script_file), false, { :binding => binding })
FileUtils.chmod 0755, File.join(script_dir, script_file)
end
erb_file(File.join(VANAGON_ROOT, 'resources', 'osx', 'uninstaller.tool.erb'), File.join(workdir, "#{name}-uninstaller.tool"), false, { :binding => binding })
FileUtils.chmod 0755, File.join(workdir, "#{name}-uninstaller.tool")
# Probably a better way to do this, but OSX tends to need some extra stuff
FileUtils.cp_r("resources/osx/.", resources_dir) if File.exist?("resources/osx/")
end
# Method to derive the package name for the project
#
# @param project [Vanagon::Project] project to name
# @return [String] name of the osx package for this project
def package_name(project)
"#{project.name}-#{project.version}-#{project.release}.#{@os_name}#{@os_version}.dmg"
end
# Constructor. Sets up some defaults for the osx platform and calls the parent constructor
#
# @param name [String] name of the platform
# @return [Vanagon::Platform::OSX] the osx derived platform with the given name
def initialize(name)
@name = name
@make = "/usr/bin/make"
@tar = "tar"
@shasum = "/usr/bin/shasum"
@pkgbuild = "/usr/bin/pkgbuild"
@productbuild = "/usr/bin/productbuild"
@hdiutil = "/usr/bin/hdiutil"
@patch = "/usr/bin/patch"
@num_cores = "/usr/sbin/sysctl -n hw.physicalcpu"
@mktemp = "mktemp -d -t 'tmp'"
@brew = '/usr/local/bin/brew'
super(name)
end
end
end
end
|
=begin
Write your code for the 'Clock' exercise in this file. Make the tests in
`clock_test.rb` pass.
To get started with TDD, see the `README.md` file in your
`ruby/clock` directory.
=end
class Clock
HOURS_PER_DAY = 24
MINUTES_PER_HOUR = 60
MINUTES_PER_DAY = MINUTES_PER_HOUR * HOURS_PER_DAY
private_constant :HOURS_PER_DAY, :MINUTES_PER_HOUR, :MINUTES_PER_DAY
def initialize(hour: 0, minute: 0)
@minutes = (hour * MINUTES_PER_HOUR + minute).modulo(MINUTES_PER_DAY)
end
def +(other)
Clock.new(minute: minutes + other.minutes)
end
def -(other)
Clock.new(minute: minutes - other.minutes)
end
def ==(other)
other.class == self.class && other.minutes == minutes
end
def to_s
hour, minute = minutes.divmod(MINUTES_PER_HOUR)
format('%02d:%02d', hour, minute)
end
protected
attr_reader :minutes
end
|
class DockingStation
DEFAULT_CAPACITY = 20
def initialize(options = {})
@capacity = options.fetch(:capacity, DEFAULT_CAPACITY)
@bikes = []
end
def bike_count
@bikes.count
end
def dock bike
@bikes << bike
end
def remove bike
@bikes.delete bike
end
def full?
bike_count == @capacity
end
def available_bikes
@bikes.reject { |bike| bike.broken?}
end
def broken_bikes
@bikes.reject { |bike| bike.okay}
end
end |
require_relative "../tenki.rb"
module Ruboty module Handlers
class Tenki < Base
on(
Ruboty::Tenki.query_matcher,
name: "weather",
description: "天気"
)
def weather message
message.reply(Ruboty::Tenki.get message.body)
end
end
end end
|
class Attendee < ActiveRecord::Base
attr_accessible :status, :invitor
belongs_to :event
belongs_to :user
def self.send_invitations(invitor,receiver,event)
if event.is_approved
Notifier.delay.invited_for_event_email(receiver,event)
event.users << receiver
x = Attendee.where(:user_id => receiver.id).where(:event_id => event.id).first
x.status = "invitation_sent"
x.invitor = invitor.id
return x.save
else
event.users << receiver
x = Attendee.where(:user_id => receiver.id).where(:event_id => event.id).first
x.invitor = invitor.id
return x.save
end
end
def self.accept_invitation(user,event)
transaction do
temp = Attendee.where(:user_id => user.id).where(:event_id => event.id).first
temp.status = "confirmed"
temp.save
event.count_confirmed_people = event.count_confirmed_people.to_i + 1
return event.save
end
end
def self.reject_invitation(user,event)
temp =Attendee.where(:user_id => user.id).where(:event_id => event.id).first
temp.status = "rejected"
return temp.save
end
def self.maybe_invitation(user,event)
temp = Attendee.where(:user_id => user.id).where(:event_id => event.id).first
temp.status = "maybe"
return temp.save
end
def self.get_event_status_count(event,status) #status = ['confirmed','maybe','rejected']
return Attendee.where(:event_id => event.id).where(:status => status).count
end
def self.get_event_status_list(event,status) #status = ['confirmed','maybe','rejected']
attendees_list = Attendee.where(:event_id => event.id).where(:status => status)
results = attendees_list.collect do |x|
User.find(x.user_id)
end
return results
end
def self.attend_event(user,event)
transaction do
x = event.users << user
attendees = Attendee.where(:event_id => event.id).where(:user_id => user.id).first
attendees.status = "confirmed"
attendees.save
event.count_confirmed_people = event.count_confirmed_people.to_i + 1
return event.save
end
end
end
|
class CarsController < ApplicationController
before_action :logged_in_user, only: [:new, :edit, :create, :destroy, :update]
def index
@cars = Car.all
end
def show
@car = Car.find(params[:id])
end
def new
@car = Car.new
end
def create
@car = Car.new(car_params)
if @car.save
flash[:success] = "Car added"
redirect_to cars_path
else
render 'new'
end
end
def destroy
Car.find(params[:id]).destroy
flash[:success] = "Car deleted"
redirect_to cars_path
end
def edit
@car = Car.find(params[:id])
end
def update
@car = Car.find(params[:id])
if @car.update_attributes(car_params)
flash[:sucess] = "Car updated"
redirect_to car_path(@car)
else
render 'edit'
end
end
private
def car_params
params.require(:car).permit(:picture, :make, :model, :year, :miles, :price, :description)
end
end
|
class Theme < ApplicationRecord
has_many :arts
def to_s
"#{title}"
end
end
|
class DropJoinTableFriendUser < ActiveRecord::Migration[5.2]
def change
drop_join_table :friends, :users
end
end
|
require 'spec_helper'
describe 'template repos routes' do
it 'routes GET to the template repos controller index action' do
expect(get: '/template_repos').to route_to(
controller: 'template_repos',
action: 'index'
)
end
it 'routes POST to the template repos controller create action' do
expect(post: '/template_repos').to route_to(
controller: 'template_repos',
action: 'create'
)
end
it 'routes DELETE to the template repos controller destroy action' do
expect(delete: '/template_repos/1').to route_to(
controller: 'template_repos',
id: '1',
action: 'destroy'
)
end
it 'routes POST to a specific repo /reload to the reload action' do
expect(post: 'template_repos/1/reload').to route_to(
controller: 'template_repos',
id: '1',
action: 'reload'
)
end
end
|
require 'minitest'
require 'minitest/autorun'
require 'minitest/pride'
require './lib/guess.rb'
require './lib/deck.rb'
require './lib/card.rb'
require './lib/round.rb'
class RoundTest < Minitest::Test
def setup
@card_1 = Card.new("What is the capital of Alaska?", "Juneau")
@card_2 = Card.new("The Viking spacecraft sent back to Earth photographs and reports about the surface of which planet?", "Mars")
@card_3 = Card.new("Describe in words the exact direction that is 697.5° clockwise from due north?", "North north west")
@deck = Deck.new([@card_1, @card_2, @card_3])
end
def test_round_class
round = Round.new(@deck)
assert_instance_of Round, round
end
def test_deck_method
round = Round.new(@deck)
assert_equal @deck, round.deck
end
def test_guesses_storage
round = Round.new(@deck)
assert_equal [], round.guesses
end
def test_current_card_method
round = Round.new(@deck)
assert_equal @card_1, round.current_card
end
def test_record_guess_method
round = Round.new(@deck)
guess = Guess.new("Juneau", @card_1)
recorded_guess = round.record_guess("Juneau")
assert_instance_of Guess, recorded_guess
assert_equal "Juneau", recorded_guess.response
end
def test_guesses_storage_increases
round = Round.new(@deck)
recorded_guess = round.record_guess("Juneau")
assert_equal 1, round.guesses.count
end
def test_feedback_method
round = Round.new(@deck)
recorded_guess = round.record_guess("Juneau")
assert_equal "Correct!", round.guesses.first.feedback
end
def test_number_correct_method
skip
round = Round.new(@deck)
number_correct = round.number_correct
assert_equal 0, number_correct
end
def test_current_card_changes
skip
round = Round.new(deck)
end
def test_record_guess_method_again
skip
round = Round.new(deck)
end
def test_guesses_storage_still_increases
skip
round = Round.new(deck)
end
def test_feedback_method_again
skip
round = Round.new(deck)
end
def test_number_correct_method_again
skip
round = Round.new(deck)
end
def test_percent_correct_method
skip
round = Round.new(deck)
end
end
|
require 'rails_helper'
RSpec.describe AnswersController, type: :controller do
it_behaves_like 'voted'
let(:user) { create(:user) }
let(:question) { create(:question) }
let(:answer_author) { create(:user) }
describe 'POST #create' do
describe 'Authorized user' do
before { login(answer_author) }
context 'with valid attributes' do
let(:params) do
{ question_id: question, answer: attributes_for(:answer), format: :js }
end
it 'save new answer in DB' do
expect{ post :create, params: params }.to change(Answer, :count).by(1)
end
it 'check @answer.question is a assigned question' do
post :create, params: params
expect(assigns(:answer).question).to eq(question)
end
it 'check @answer.user is a user' do
post :create, params: params
expect(assigns(:answer).user).to eq(answer_author)
end
it 'render create' do
post :create, params: params
expect(response).to render_template :create
end
it 'returns status :ok' do
post :create, params: params
expect(response).to have_http_status(:ok)
end
end
context 'with invalid attributes' do
let(:params) do
{
question_id: question,
answer: attributes_for(:answer, :invalid_answer),
format: :js
}
end
it 'does not save the answer' do
expect{ post :create, params: params }.to_not change(Answer, :count)
end
it 'render create' do
post :create, params: params
expect(response).to render_template :create
end
it 'returns status :ok' do
post :create, params: params
expect(response).to have_http_status(:ok)
end
end
end
describe 'Unauthorized user' do
context 'with valid attributes' do
let(:params) do
{ question_id: question, answer: attributes_for(:answer), format: :js }
end
it 'does not save new answer in DB' do
expect{ post :create, params: params }.to_not change(Answer, :count)
end
it 'does not redirect to @question' do
post :create, params: params
expect(response).to_not redirect_to assigns(:question)
end
it 'returns status :unauthorized' do
post :create, params: params
expect(response).to have_http_status(:unauthorized)
end
end
context 'with invalid attributes' do
let(:params) do
{
question_id: question,
answer: attributes_for(:answer),
format: :js
}
end
it 'does not save the answer' do
expect{ post :create, params: params }.to_not change(Answer, :count)
end
it 'does not render questions/show view' do
post :create, params: params
expect(response).to_not render_template :create
end
it 'returns status :unauthorized' do
post :create, params: params
expect(response).to have_http_status(:unauthorized)
end
end
end
end
describe 'PATCH #update' do
let!(:answer) do
create(:answer, question: question, user: answer_author)
end
describe 'Authorized answer author' do
before { login(answer_author) }
context 'with valid attributes' do
before do
patch :update, params: {
id: answer, answer: { body: 'Edited answer' },
format: :js
}
end
it 'change answer attributes' do
expect{answer.reload}.to change(answer, :body)
end
it 'render update view' do
expect(response).to render_template :update
end
it 'returns status :ok' do
expect(response).to have_http_status(:ok)
end
end
context 'with invalid attributes' do
before do
patch :update, params: {
id: answer,
answer: attributes_for(:answer, :invalid_answer),
format: :js
}
end
it 'does not change answer attributes' do
expect{answer.reload}.to_not change(answer, :body)
end
it 'render update view' do
expect(response).to render_template :update
end
it 'returns status :ok' do
expect(response).to have_http_status(:ok)
end
end
end
describe 'Authorized not answer author' do
before { login(user) }
context 'with valid attributes' do
before do
patch :update, params: {
id: answer,
answer: { body: 'Edited answer' },
format: :js
}
end
it 'does not change answer attributes' do
expect{answer.reload}.to_not change(answer, :body)
end
it 'does not render update view' do
expect(response).to have_http_status(:forbidden)
end
it 'returns status :forbidden' do
expect(response).to have_http_status(:forbidden)
end
end
context 'with invalid attributes' do
before do
patch :update, params: {
id: answer,
answer: attributes_for(:answer, :invalid_answer),
format: :js
}
end
it 'does not change answer attributes' do
expect{answer.reload}.to_not change(answer, :body)
end
it 'returns status :forbidden' do
expect(response).to have_http_status(:forbidden)
end
end
end
describe 'Unauthorized user' do
context 'with valid attributes' do
before do
patch :update, params: {
id: answer,
answer: { body: 'Edited answer' },
format: :js
}
end
it 'does not change answer attributes' do
expect{answer.reload}.to_not change(answer, :body)
end
it 'does not render update view' do
expect(response).to have_http_status(:unauthorized)
end
it 'returns status :unauthorized' do
expect(response).to have_http_status(:unauthorized)
end
end
context 'with invalid attributes' do
before do
patch :update, params: {
id: answer,
answer: attributes_for(:answer, :invalid_answer),
format: :js
}
end
it 'does not change answer attributes' do
expect{answer.reload}.to_not change(answer, :body)
end
it 'does not render update view' do
expect(response).to have_http_status(:unauthorized)
end
it 'returns status :unauthorized' do
expect(response).to have_http_status(:unauthorized)
end
end
end
end
describe 'PATCH #mark_best' do
let!(:answer) { create(:answer, question: question, user: answer_author) }
let(:params) { { id: answer, format: :js } }
describe 'Authorized question author' do
before do
login(question.user)
patch :mark_best, params: params
end
it 'change answer best attribute' do
expect{answer.reload}.to change(answer, :best).from(false).to(true)
end
it 'render mark_best view' do
expect(response).to render_template :mark_best
end
it 'returns status :ok' do
expect(response).to have_http_status(:ok)
end
end
describe 'Authorized not question author' do
before do
login(user)
patch :mark_best, params: params
end
it 'does not change answer best attribute' do
expect{answer.reload}.to_not change(answer, :best)
end
it 'does not render mark_best view' do
expect(response).to have_http_status(:forbidden)
end
it 'returns status :forbidden' do
expect(response).to have_http_status(:forbidden)
end
end
describe 'Unauthorized user' do
before do
patch :mark_best, params: params
end
it 'does not change answer best attribute' do
expect{answer.reload}.to_not change(answer, :best)
end
it 'does not render mark_best view' do
expect(response).to_not render_template :mark_best
end
it 'returns status :unauthorized' do
expect(response).to have_http_status(:unauthorized)
end
end
end
describe 'DELETE #destroy' do
let!(:answer) { create(:answer, question: question) }
let(:params) { { id: answer, format: :js } }
describe 'Authorized answer author' do
before { login(answer.user) }
it 'deletes answer from DB' do
expect{ delete :destroy, params: params }
.to change(Answer, :count).by(-1)
end
it 'render destroy view' do
delete :destroy, params: params
expect(response).to render_template :destroy
end
it 'returns status :ok' do
delete :destroy, params: params
expect(response).to have_http_status(:ok)
end
end
describe 'Authorized not answer author' do
before { login(user) }
it 'does not deletes answer from DB' do
expect{ delete :destroy, params: params }.to_not change(Answer, :count)
end
it 'does not render destroy view' do
delete :destroy, params: params
expect(response).to have_http_status(:forbidden)
end
it 'returns status :forbidden' do
delete :destroy, params: params
expect(response).to have_http_status(:forbidden)
end
end
describe 'Unauthorized user' do
it 'does not deletes answer from DB' do
expect{ delete :destroy, params: params }.to_not change(Answer, :count)
end
it 'does not render destroy view' do
delete :destroy, params: params
expect(response).to_not render_template :destroy
end
it 'returns status :unauthorized' do
delete :destroy, params: params
expect(response).to have_http_status(:unauthorized)
end
end
end
end
|
######################################################################
# Copyright (c) 2008-2014, Alliance for Sustainable Energy.
# All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
######################################################################
# Converts a custom Excel spreadsheet format to BCL components for upload
# Format of the Excel spreadsheet is documented in /doc/ComponentSpreadsheet.docx
if RUBY_PLATFORM =~ /mswin|mingw|cygwin/
begin
# apparently this is not a gem (todo: need to remove and replace with roo)
require 'win32ole'
mod = WIN32OLE
$have_win32ole = true
rescue NameError
# do not have win32ole
end
end
module BCL
class ComponentSpreadsheet
public
# WINDOWS ONLY SECTION BECAUSE THIS USES WIN32OLE
if $have_win32ole
# initialize with Excel spreadsheet to read
def initialize(xlsx_path, worksheet_names = ['all'])
@xlsx_path = Pathname.new(xlsx_path).realpath.to_s
@worksheets = []
begin
excel = WIN32OLE.new('Excel.Application')
xlsx = excel.Workbooks.Open(@xlsx_path)
# by default, operate on all worksheets
if worksheet_names == ['all']
xlsx.Worksheets.each do |xlsx_worksheet|
parse_xlsx_worksheet(xlsx_worksheet)
end
else # if specific worksheets are specified, operate on them
worksheet_names.each do |worksheet_name|
parse_xlsx_worksheet(xlsx.Worksheets(worksheet_name))
end
end
# save spreadsheet if changes have been made
if xlsx.saved == true
# puts "[ComponentSpreadsheet] Spreadsheet unchanged; not saving"
else
xlsx.Save
puts '[ComponentSpreadsheet] Spreadsheet changes saved'
end
ensure
excel.Quit
WIN32OLE.ole_free(excel)
excel.ole_free
xlsx = nil
excel = nil
GC.start
end
end
else # if $have_win32ole
# parse the master taxonomy document
def initialize(_xlsx_path)
puts "ComponentSpreadsheet class requires 'win32ole' to parse the component spreadsheet."
puts 'ComponentSpreadsheet may also be stored and loaded from JSON if your platform does not support win32ole.'
end
end # if $have_win32ole
def save(save_path, chunk_size = 1000, delete_old_gather = false)
# load master taxonomy to validate components
taxonomy = BCL::MasterTaxonomy.new
# FileUtils.rm_rf(save_path) if File.exists?(save_path) and File.directory?(save_path)
@worksheets.each do |worksheet|
worksheet.components.each do |component|
component_xml = Component.new("#{save_path}/components")
component_xml.name = component.name
component_xml.uid = component.uid
component_xml.comp_version_id = component.version_id
# this tag is how we know where this goes in the taxonomy
component_xml.add_tag(worksheet.name)
values = component.values[0]
component.headers.each do |header|
if /description/i.match(header.name)
name = values.delete_at(0)
uid = values.delete_at(0)
version_id = values.delete_at(0)
description = values.delete_at(0)
fidelity_level = values.delete_at(0).to_int
# name, uid, and version_id already processed
component_xml.description = description
component_xml.fidelity_level = fidelity_level
elsif /provenance/i.match(header.name)
author = values.delete_at(0)
datetime = values.delete_at(0)
if datetime.nil?
# puts "[ComponentSpreadsheet] WARNING missing the date in the datetime column in the spreadsheet - assuming today"
datetime = DateTime.new
else
datetime = DateTime.parse(datetime)
end
comment = values.delete_at(0)
component_xml.add_provenance(author.to_s, datetime.to_s, comment.to_s)
elsif /tag/i.match(header.name)
value = values.delete_at(0)
component_xml.add_tag(value)
elsif /attribute/i.match(header.name)
value = values.delete_at(0)
name = header.children[0]
units = ''
if match_data = /(.*)\((.*)\)/.match(name)
name = match_data[1].strip
units = match_data[2].strip
end
component_xml.add_attribute(name, value, units)
elsif /source/i.match(header.name)
manufacturer = values.delete_at(0)
model = values.delete_at(0)
serial_no = values.delete_at(0)
year = values.delete_at(0)
url = values.delete_at(0)
component_xml.source_manufacturer = manufacturer
component_xml.source_model = model
component_xml.source_serial_no = serial_no
component_xml.source_year = year
component_xml.source_url = url
elsif /file/i.match(header.name)
software_program = values.delete_at(0)
version = values.delete_at(0)
filename = values.delete_at(0)
filetype = values.delete_at(0)
filepath = values.delete_at(0)
# not all components(rows) have all files; skip if filename "" or nil
next if filename == '' || filename.nil?
# skip the file if it doesn't exist at the specified location
unless File.exist?(filepath)
puts "[ComponentSpreadsheet] ERROR #{filepath} -> File does not exist, will not be included in component xml"
next # go to the next file
end
component_xml.add_file(software_program, version, filepath, filename, filetype)
else
fail "Unknown section #{header.name}"
end
end
taxonomy.check_component(component_xml)
component_xml.save_tar_gz(false)
end
end
BCL.gather_components(save_path, chunk_size, delete_old_gather)
end
private
def parse_xlsx_worksheet(xlsx_worksheet)
worksheet = WorksheetStruct.new
worksheet.name = xlsx_worksheet.Range('A1').Value
worksheet.components = []
puts "[ComponentSpreadsheet] Starting parsing components of type #{worksheet.name}"
# find number of rows, first column should be name, should not be empty
num_rows = 1
loop do
test = xlsx_worksheet.Range("A#{num_rows}").Value
if test.nil? || test.empty?
num_rows -= 1
break
end
num_rows += 1
end
# scan number of columns
headers = []
header = nil
max_col = nil
xlsx_worksheet.Columns.each do |col|
value1 = col.Rows('1').Value
value2 = col.Rows('2').Value
if !value1.nil? && !value1.empty?
unless header.nil?
headers << header
end
header = HeaderStruct.new
header.name = value1
header.children = []
end
if !value2.nil? && !value2.empty?
unless header.nil?
header.children << value2
end
end
if (value1.nil? || value1.empty?) && (value2.nil? || value2.empty?)
break
end
matchdata = /^\$(.+):/.match(col.Address)
max_col = matchdata[1]
end
unless header.nil?
headers << header
end
unless headers.empty?
headers[0].name = 'description'
end
puts " Found #{num_rows - 2} components"
components = []
for i in 3..num_rows do
component = ComponentStruct.new
component.row = i
# get name
component.name = xlsx_worksheet.Range("A#{i}").value
# get uid, if empty set it
component.uid = xlsx_worksheet.Range("B#{i}").value
if component.uid.nil? || component.uid.empty?
component.uid = UUID.new.generate
puts "#{component.name} uid missing; creating new one"
xlsx_worksheet.Range("B#{i}").value = component.uid
end
# get version_id, if empty set it
component.version_id = xlsx_worksheet.Range("C#{i}").value
if component.version_id.nil? || component.version_id.empty?
component.version_id = UUID.new.generate
puts "#{component.name} version id missing; creating new one"
xlsx_worksheet.Range("C#{i}").value = component.version_id
end
component.headers = headers
component.values = xlsx_worksheet.Range("A#{i}:#{max_col}#{i}").value
worksheet.components << component
end
@worksheets << worksheet
puts "[ComponentSpreadsheet] Finished parsing components of type #{worksheet.name}"
end
end
end # module BCL
|
class Alimento
include Comparable
attr_reader :nombre, :kgco2eq, :m2anio, :proteinas, :valor_energetico, :carbohidratos, :lipidos
# Constructor de la clase Alimento
def initialize( nombre, informacion)
@nombre,@kgco2eq,@m2anio, @carbohidratos, @lipidos, @proteinas = nombre, informacion[0].round(4), informacion[1].round(4), informacion[2].round(4), informacion[3].round(4), informacion[4].round(4)
@valor_energetico = calculatevalorenergetico
end
# Aplica la formula para calcular el valor energetico y lo devuelve
def calculatevalorenergetico
4*@carbohidratos+9*@lipidos+4*@proteinas
end
# Metodo que devuelve una representacion del Alimento en string
def to_s
"Nombre del alimento: #{@nombre}\nKilogramos de CO2: #{@kgco2eq}\nMetros cuadrados año utilizados: #{@m2anio}\nCarbohidratos: #{@carbohidratos}\nLipidos: #{@lipidos}\nProteinas: #{@proteinas}\nValor Energético: #{@valor_energetico}cal"
end
# Definicion del metodo + para poder sumar los diferentes alimentos
def +(other)
raise "Se debe sumar con otro alimento" unless other.instance_of?Alimento
informacion = [@kgco2eq+other.kgco2eq, @m2anio+other.m2anio, @carbohidratos+other.carbohidratos, @lipidos+other.lipidos, @proteinas+other.proteinas ]
nombre = @nombre + ", " + other.nombre
Alimento.new(nombre,informacion)
end
# Definicion del metodo <=> para que sea Comparable
def <=>(other)
if other == nil
return nil
end
raise "Error no se puede comparar" unless (other.instance_of?Alimento)
(@valor_energetico) <=> (other.valor_energetico)
end
end
|
class Supplier < ApplicationRecord
has_many :products, primary_key: :code, foreign_key: :supplier_code
end
|
class PasswordResetsController < ApplicationController
before_filter :load_user_using_perishable_token, :only => [:edit, :update]
before_filter :set_mailer_url_defaults
layout 'login'
def create
if @user = current_account.users.find_by_email(params[:user][:email])
@user.reset_perishable_token!
UserMailer.deliver_password_reset_instructions(@user)
flash[:notice] = I18n.t('authorizer.password_reset_intructions_mailed')
redirect_to login_url
else
flash[:alert] = I18n.t('authorizer.no_user_on_account')
render :action => :new
end
end
def update
@user.password = params[:user][:password]
@user.password_confirmation = params[:user][:password_confirmation]
if @user.save
flash[:notice] = I18n.t('authorizer.password_updated')
redirect_to root_url
else
render :action => :edit
end
end
private
def load_user_using_perishable_token
token = params[:user] ? params[:user][:perishable_token] : params[:id]
unless @user = current_account.users.find_using_perishable_token(token)
flash[:alert] = I18n.t('authorizer.no_user_on_account')
redirect_to login_path
end
end
end |
Rails.application.routes.draw do
# Routes for the Like resource:
# CREATE
get "/likes/new", :controller => "likes", :action => "new"
post "/create_like", :controller => "likes", :action => "create"
# READ
get "/likes", :controller => "likes", :action => "index"
get "/likes/:id", :controller => "likes", :action => "show"
# UPDATE
get "/likes/:id/edit", :controller => "likes", :action => "edit"
post "/update_like/:id", :controller => "likes", :action => "update"
# DELETE
get "/delete_like/:id", :controller => "likes", :action => "destroy"
#------------------------------
# Routes for the Comment resource:
# CREATE
get "/comments/new", :controller => "comments", :action => "new"
post "/create_comment", :controller => "comments", :action => "create"
# READ
get "/comments", :controller => "comments", :action => "index"
get "/comments/:id", :controller => "comments", :action => "show"
# UPDATE
get "/comments/:id/edit", :controller => "comments", :action => "edit"
post "/update_comment/:id", :controller => "comments", :action => "update"
# DELETE
get "/delete_comment/:id", :controller => "comments", :action => "destroy"
#------------------------------
# Routes for the Video resource:
# CREATE
get "/videos/new", :controller => "videos", :action => "new"
post "/create_video", :controller => "videos", :action => "create"
# READ
get "/videos", :controller => "videos", :action => "index"
get "/videos/:id", :controller => "videos", :action => "show"
# UPDATE
get "/videos/:id/edit", :controller => "videos", :action => "edit"
post "/update_video/:id", :controller => "videos", :action => "update"
# DELETE
get "/delete_video/:id", :controller => "videos", :action => "destroy"
#------------------------------
devise_for :users
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
# READ
get "/users", :controller => "users", :action => "index"
get "/users/:id", :controller => "users", :action => "show"
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root to: "videos#index"
# READ
get "/my_likes", :controller => "mylikes", :action => "index"
end
|
class RemoveUserNameFromApiUser < ActiveRecord::Migration[5.1]
def change
remove_column :api_users, :user_name
end
end
|
class AddReviewToRestaurant < ActiveRecord::Migration[5.1]
def change
add_column :reviews, :restaurant_id, :integer, references: :restaurants
end
end
|
require 'test_helper'
class TwitterTest < Test::Unit::TestCase
should "default User Agent to 'Ruby Twitter Gem'" do
assert_equal 'Ruby Twitter Gem', Twitter.user_agent
end
context 'when overriding the user agent' do
should "be able to specify the User Agent" do
Twitter.user_agent = 'My Twitter Gem'
assert_equal 'My Twitter Gem', Twitter.user_agent
end
end
should "have firehose method for public timeline" do
stub_get('http://api.twitter.com/1/statuses/public_timeline.json', 'firehose.json')
hose = Twitter.firehose
assert_equal 20, hose.size
first = hose.first
assert_equal '#torrents Ultimativer Flirt Guide - In 10 Minuten jede Frau erobern: Ultimativer Flirt Guide - In 10 Mi.. http://tinyurl.com/d3okh4', first.text
assert_equal 'P2P Torrents', first.user.name
end
should "have user method for unauthenticated calls to get a user's information" do
stub_get('http://api.twitter.com/1/users/show/jnunemaker.json', 'user.json')
user = Twitter.user('jnunemaker')
assert_equal 'John Nunemaker', user.name
assert_equal 'Loves his wife, ruby, notre dame football and iu basketball', user.description
end
should "have status method for unauthenticated calls to get a status" do
stub_get('http://api.twitter.com/1/statuses/show/1533815199.json', 'status_show.json')
status = Twitter.status(1533815199)
assert_equal 1533815199, status.id
assert_equal 'Eating some oatmeal and butterscotch cookies with a cold glass of milk for breakfast. Tasty!', status.text
end
should "raise NotFound for unauthenticated calls to get a deleted or nonexistent status" do
stub_get('http://api.twitter.com/1/statuses/show/1.json', 'not_found.json', 404)
assert_raise Twitter::NotFound do
Twitter.status(1)
end
end
should "have a timeline method for unauthenticated calls to get a user's timeline" do
stub_get('http://api.twitter.com/1/statuses/user_timeline/jnunemaker.json', 'user_timeline.json')
statuses = Twitter.timeline('jnunemaker')
assert_equal 1445986256, statuses.first.id
assert_equal 'jnunemaker', statuses.first.user.screen_name
end
should "raise Unauthorized for unauthenticated calls to get a protected user's timeline" do
stub_get('http://api.twitter.com/1/statuses/user_timeline/protected.json', 'unauthorized.json', 401)
assert_raise Twitter::Unauthorized do
Twitter.timeline('protected')
end
end
should "have friend_ids method" do
stub_get('http://api.twitter.com/1/friends/ids/jnunemaker.json', 'friend_ids.json')
ids = Twitter.friend_ids('jnunemaker')
assert_equal 161, ids.size
end
should "raise Unauthorized for unauthenticated calls to get a protected user's friend_ids" do
stub_get('http://api.twitter.com/1/friends/ids/protected.json', 'unauthorized.json', 401)
assert_raise Twitter::Unauthorized do
Twitter.friend_ids('protected')
end
end
should "have follower_ids method" do
stub_get('http://api.twitter.com/1/followers/ids/jnunemaker.json', 'follower_ids.json')
ids = Twitter.follower_ids('jnunemaker')
assert_equal 1252, ids.size
end
should "raise Unauthorized for unauthenticated calls to get a protected user's follower_ids" do
stub_get('http://api.twitter.com/1/followers/ids/protected.json', 'unauthorized.json', 401)
assert_raise Twitter::Unauthorized do
Twitter.follower_ids('protected')
end
end
context "when using lists" do
should "be able to view list timeline" do
stub_get('http://api.twitter.com/1/pengwynn/lists/rubyists/statuses.json', 'list_statuses.json')
tweets = Twitter.list_timeline('pengwynn', 'rubyists')
assert_equal 20, tweets.size
assert_equal 5272535583, tweets.first.id
assert_equal 'John Nunemaker', tweets.first.user.name
end
should "be able to limit number of tweets in list timeline" do
stub_get('http://api.twitter.com/1/pengwynn/lists/rubyists/statuses.json?per_page=1', 'list_statuses_1_1.json')
tweets = Twitter.list_timeline('pengwynn', 'rubyists', :per_page => 1)
assert_equal 1, tweets.size
assert_equal 5272535583, tweets.first.id
assert_equal 'John Nunemaker', tweets.first.user.name
end
should "be able to paginate through the timeline" do
stub_get('http://api.twitter.com/1/pengwynn/lists/rubyists/statuses.json?page=1&per_page=1', 'list_statuses_1_1.json')
stub_get('http://api.twitter.com/1/pengwynn/lists/rubyists/statuses.json?page=2&per_page=1', 'list_statuses_2_1.json')
tweets = Twitter.list_timeline('pengwynn', 'rubyists', { :page => 1, :per_page => 1 })
assert_equal 1, tweets.size
assert_equal 5272535583, tweets.first.id
assert_equal 'John Nunemaker', tweets.first.user.name
tweets = Twitter.list_timeline('pengwynn', 'rubyists', { :page => 2, :per_page => 1 })
assert_equal 1, tweets.size
assert_equal 5264324712, tweets.first.id
assert_equal 'John Nunemaker', tweets.first.user.name
end
end
end
|
require 'rails_helper'
RSpec.describe 'students/index.html.erb', type: :view do
describe 'populate page and links' do
before do
assign(:can_edit, true)
@students = [create(:student, first_name: 'Joe', last_name: 'Lally',
gender: 'male'),
create(:student, first_name: 'Tim', last_name: 'Bradley',
gender: 'male')]
render
end
describe 'title' do
it 'checks for title' do
expect(rendered).to match(/Students/)
end
end
describe 'student list' do
it 'shows the first student' do
expect(rendered).to match(/Joe/)
end
it 'shows the second student' do
expect(rendered).to match(/Tim/)
end
end
end
end
|
class Record
include Mongoid::Document
extend DocumentMethods
belongs_to :entity
field :data, type: Hash
end
|
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/date_time_precision/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["David Butler"]
gem.email = ["dwbutler@ucla.edu"]
gem.description = %q{Patches Date, Time, and DateTime ruby classes to keep track of precision}
gem.summary = %q{Patches Date, Time, and DateTime ruby classes to keep track of precision}
gem.homepage = "http://github.com/Spokeo/date_time_precision"
gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "date_time_precision"
gem.require_paths = ["lib"]
gem.version = DateTimePrecision::VERSION
gem.license = 'MIT'
gem.add_development_dependency 'rake'
gem.add_development_dependency 'rspec', '> 3'
gem.add_development_dependency 'appraisal'
gem.add_development_dependency 'activesupport'
gem.add_development_dependency 'json'
gem.add_development_dependency 'virtus', '0.5.4'
gem.add_development_dependency 'coercible', '0.0.1'
end
|
class CreateSysAdMessages < ActiveRecord::Migration
def change
create_table :sys_ad_messages, options: 'ENGINE=InnoDB, CHARSET=utf8' do |t|
# 群发的系统消息表
t.text :message # 系统消息
t.integer :m_type, :default => '0' # 是管理员添加还是客户端推送(0管理员添加,1客户端推送)
t.string :user_rule # 可以接收系统消息的用户规则
t.timestamp :start_time, :default => '0000-00-00 00:00:00' # 系统消息有效期开始时间
t.timestamp :end_time, :default => '0000-00-00 00:00:00' # 系统消息有效期结束时间
t.boolean :deleted, :default => '0' # 是否删除(0没有删除,1已经删除)
t.timestamps
end
end
end
|
RSpec.describe "shared/activities/_activity" do
let(:policy_stub) { ActivityPolicy.new(user, activity) }
let(:activity) { build(:programme_activity) }
let(:activity_presenter) { ActivityPresenter.new(activity) }
let(:country_partner_orgs) { ["ACME Inc"] }
let(:body) { Capybara.string(rendered) }
let(:oda_programme) {
create(:programme_activity,
:ispf_funded,
is_oda: true,
extending_organisation: user.organisation)
}
let(:non_oda_programme) {
create(:programme_activity,
:ispf_funded,
is_oda: false,
extending_organisation: user.organisation)
}
let(:oda_project) {
create(:project_activity,
:ispf_funded,
is_oda: true,
extending_organisation: user.organisation,
organisation: user.organisation,
parent: oda_programme)
}
let(:non_oda_project) {
create(:project_activity,
:ispf_funded,
is_oda: false,
extending_organisation: user.organisation,
organisation: user.organisation,
parent: non_oda_programme)
}
let(:oda_third_party_project) {
create(:third_party_project_activity,
:ispf_funded,
is_oda: true,
extending_organisation: user.organisation,
organisation: user.organisation,
parent: oda_project)
}
let(:non_oda_third_party_project) {
create(:third_party_project_activity,
:ispf_funded,
is_oda: false,
extending_organisation: user.organisation,
organisation: user.organisation,
parent: non_oda_project)
}
before do
without_partial_double_verification do
allow(view).to receive(:activity_presenter).and_return(activity_presenter)
allow(view).to receive(:current_user).and_return(user)
allow(view).to receive(:policy).with(any_args).and_return(policy_stub)
allow(view).to receive(:activity_step_path).and_return("This path isn't important")
allow(view).to receive(:edit_activity_redaction_path).and_return("This path isn't important")
allow(view).to receive(:organisation_activity_path).and_return("This path isn't important")
end
end
context "when signed in as a Partner organisation user" do
let(:user) { build(:partner_organisation_user) }
context "when the fund is GCRF" do
before { render }
context "when the activity is a programme activity" do
let(:activity) { build(:programme_activity, :gcrf_funded) }
it { is_expected.to show_basic_details }
it { is_expected.to show_gcrf_specific_details }
end
context "when the activity is a project activity" do
let(:activity) { build(:project_activity, :gcrf_funded) }
it { is_expected.to show_basic_details }
it { is_expected.to show_project_details }
it { is_expected.to show_gcrf_specific_details }
end
context "when the activity is a third party project activity" do
let(:activity) { build(:third_party_project_activity, :gcrf_funded) }
it { is_expected.to show_basic_details }
it { is_expected.to show_project_details }
it { is_expected.to show_gcrf_specific_details }
end
end
context "when the fund is Newton" do
before { render }
context "when the activity is a programme activity" do
let(:activity) { build(:programme_activity, :newton_funded, country_partner_organisations: country_partner_orgs) }
it { is_expected.to show_basic_details }
end
context "when the activity is a project activity" do
let(:activity) { build(:project_activity, :newton_funded, country_partner_organisations: country_partner_orgs) }
it { is_expected.to show_basic_details }
it { is_expected.to show_project_details }
it { is_expected.to show_newton_specific_details }
end
context "when the activity is a third party project activity" do
let(:activity) { build(:third_party_project_activity, :newton_funded, country_partner_organisations: country_partner_orgs) }
it { is_expected.to show_basic_details }
it { is_expected.to show_project_details }
it { is_expected.to show_newton_specific_details }
end
end
context "when the fund is ISPF" do
context "when the activity is a programme activity" do
let(:activity) {
build(
:programme_activity,
:ispf_funded,
ispf_themes: [1],
ispf_oda_partner_countries: ["IN"],
ispf_non_oda_partner_countries: ["CA"]
)
}
before { render }
it { is_expected.to show_basic_details }
it { is_expected.to show_ispf_specific_details }
it "doesn't show fields irrelevant to all ISPF programmes" do
expect(rendered).not_to have_content(t("activerecord.attributes.activity.collaboration_type"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.fstc_applies"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.covid19_related"))
end
context "when the `activity_linking` feature flag is not active" do
it "does not show the Linked Activities row" do
expect(rendered).to_not have_css(".govuk-summary-list__row.linked_activity")
end
end
context "when the `activity_linking` feature flag is active" do
before do
allow(ROLLOUT).to receive(:active?).with(:activity_linking).and_return(true)
render
end
it "shows the Linked Activities row" do
expect(rendered).to have_css(".govuk-summary-list__row.linked_activity")
end
context "when the programme has a linked programme" do
let(:linked_activity) { build(:programme_activity, :ispf_funded) }
let(:activity) {
build(
:programme_activity,
:ispf_funded,
ispf_themes: [1],
ispf_oda_partner_countries: ["IN"],
ispf_non_oda_partner_countries: ["CA"],
linked_activity: linked_activity
)
}
it "shows the linked programme" do
expect(rendered).to have_content(activity_presenter.linked_activity.title)
end
it "does not show a link to edit the linked programme" do
expect(body.find(".linked_activity .govuk-summary-list__actions")).to_not have_content(t("default.link.edit"))
end
end
end
context "when the activity is ODA" do
context "and has no ISPF non-ODA partner countries" do
let(:activity) {
build(
:programme_activity,
:ispf_funded,
ispf_themes: [1],
ispf_oda_partner_countries: ["IN"],
ispf_non_oda_partner_countries: []
)
}
it "doesn't show the ISPF non-ODA partner countries field" do
activity.update(ispf_non_oda_partner_countries: [])
expect(rendered).not_to have_css(".govuk-summary-list__row.ispf_non_oda_partner_countries")
end
end
end
context "when the activity is non-ODA" do
let(:activity) { build(:programme_activity, :ispf_funded, ispf_themes: [1], ispf_non_oda_partner_countries: ["IN"], is_oda: false) }
it { is_expected.to show_ispf_specific_details }
it "doesn't show fields irrelevant to ISPF non-ODA programmes" do
expect(rendered).not_to have_content(t("activerecord.attributes.activity.objectives"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.benefitting_countries"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.gdi"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.sustainable_development_goals"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.aid_type"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.oda_eligibility"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.transparency_identifier"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.publish_to_iati"))
end
end
end
context "when the activity is a project" do
let(:activity) {
create(
:project_activity,
:ispf_funded,
is_oda: true,
extending_organisation: user.organisation,
organisation: user.organisation,
parent: oda_programme,
ispf_themes: [1],
ispf_oda_partner_countries: ["IN"],
ispf_non_oda_partner_countries: ["CA"]
)
}
let(:non_oda_activity) { non_oda_project }
before do
activity.parent.linked_activity = non_oda_activity.parent
activity.parent.save
create(:report, :active, fund: activity.associated_fund, organisation: user.organisation)
end
context "when the activity is ODA" do
before { render }
it { is_expected.to show_basic_details }
it { is_expected.to show_project_details }
it { is_expected.to show_ispf_specific_details }
it "shows ISPF ODA fields" do
expect(rendered).to have_content(t("activerecord.attributes.activity.collaboration_type"))
expect(rendered).to have_content(t("activerecord.attributes.activity.fstc_applies"))
expect(rendered).to have_content(t("activerecord.attributes.activity.covid19_related"))
end
it "doesn't allow editing the ODA / non-ODA field" do
expect(body.find(".is_oda .govuk-summary-list__actions")).to_not have_content(t("default.link.edit"))
end
context "and has no ISPF non-ODA partner countries" do
let(:activity) {
create(
:project_activity,
:ispf_funded,
is_oda: true,
extending_organisation: user.organisation,
organisation: user.organisation,
parent: oda_programme,
ispf_themes: [1],
ispf_oda_partner_countries: ["IN"],
ispf_non_oda_partner_countries: []
)
}
it "doesn't show the ISPF non-ODA partner countries field" do
expect(rendered).not_to have_css(".govuk-summary-list__row.ispf_non_oda_partner_countries")
end
end
end
context "when the activity is non-ODA" do
let(:activity) { non_oda_project }
before { render }
it { is_expected.to show_ispf_specific_details }
it "doesn't show fields that are irrelevant to non-ODA ISPF activities" do
expect(rendered).not_to have_content(t("activerecord.attributes.activity.objectives"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.benefitting_countries"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.gdi"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.collaboration_type"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.sustainable_development_goals"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.aid_type"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.fstc_applies"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.policy_marker_gender"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.policy_marker_climate_change_adaptation"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.policy_marker_climate_change_mitigation"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.policy_marker_biodiversity"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.policy_marker_desertification"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.policy_marker_disability"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.policy_marker_disaster_risk_reduction"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.covid19_related"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.channel_of_delivery_code"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.oda_eligibility"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.oda_eligibility_lead"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.transparency_identifier"))
expect(rendered).not_to have_content(t("activerecord.attributes.activity.publish_to_iati"))
end
it "doesn't allow editing the ODA / non-ODA field" do
expect(body.find(".is_oda .govuk-summary-list__actions")).to_not have_content(t("default.link.edit"))
end
end
context "when the `activity_linking` feature flag is not active" do
it "does not show the Linked Activities row" do
expect(rendered).to_not have_css(".govuk-summary-list__row.linked_activity")
end
end
context "when the `activity_linking` feature flag is active" do
before { allow(ROLLOUT).to receive(:active?).with(:activity_linking).and_return(true) }
context "and it doesn't have a linked activity" do
before { render }
it "shows a link to add a linked activity" do
expect(body.find(".linked_activity .govuk-summary-list__actions a")).to have_content(t("default.link.add"))
end
end
context "and it has a linked activity" do
before do
activity.linked_activity = non_oda_activity
activity.save
render
end
it "shows the linked activity" do
expect(rendered).to have_content(activity_presenter.linked_activity.title)
end
it "shows a link to edit the linked activity" do
expect(body.find(".linked_activity .govuk-summary-list__actions a")).to have_content(t("default.link.edit"))
end
end
context "and it has child projects that are linked" do
let(:activity) { oda_project }
before do
oda_programme.linked_activity = non_oda_programme
oda_programme.save
oda_project.linked_activity = non_oda_project
oda_project.save
oda_third_party_project.linked_activity = non_oda_third_party_project
oda_third_party_project.save
render
end
it "does not show an edit link for the linked project" do
expect(body.find(".linked_activity .govuk-summary-list__actions")).to_not have_content(t("default.link.edit"))
end
end
end
end
end
context "showing the publish to iati field" do
before { render }
context "when redact_from_iati is false" do
let(:policy_stub) { double("policy", update?: true, set_commitment?: true, redact_from_iati?: false) }
it { is_expected.to_not show_the_publish_to_iati_field }
end
context "when redact_from_iati is true" do
let(:policy_stub) { double("policy", update?: true, set_commitment?: true, redact_from_iati?: true) }
it { is_expected.to show_the_publish_to_iati_field }
context "when the activity is non-ODA" do
let(:activity) { build(:programme_activity, is_oda: false) }
it { is_expected.not_to show_the_publish_to_iati_field }
end
end
end
context "when the activity is a programme level activity" do
let(:activity) { build(:programme_activity) }
before { render }
it "does not show the Channel of delivery code field" do
expect(rendered).to_not have_content(t("activerecord.attributes.activity.channel_of_delivery_code"))
end
it { is_expected.to_not show_the_edit_add_actions }
end
context "when the activity is a project level activity" do
let(:activity) { build(:project_activity, organisation: user.organisation) }
before { render }
it { is_expected.to_not show_the_edit_add_actions }
context "and the policy allows a user to update" do
let(:policy_stub) { double("policy", update?: true, set_commitment?: true, redact_from_iati?: false) }
it { is_expected.to show_the_edit_add_actions }
it "does not show an edit link for the partner organisation identifier" do
expect(body.find(".identifier")).to_not have_content(t("default.link.edit"))
end
context "when the project does not have a partner organisation identifier" do
let(:activity) { build(:project_activity, partner_organisation_identifier: nil, organisation: user.organisation) }
scenario "shows an edit link for the partner organisation identifier" do
expect(body.find(".identifier")).to have_content(t("default.link.add"))
end
end
context "when the project has a RODA identifier" do
let(:activity) { build(:project_activity, organisation: user.organisation, roda_identifier: "A-RODA-ID") }
it "does not show an edit or add link for the RODA identifier" do
expect(body.find(".roda_identifier")).to_not have_content(t("default.link.add"))
expect(body.find(".roda_identifier")).to_not have_content(t("default.link.add"))
end
end
it "shows a link to edit the UK PO named contact" do
expect(body.find(".uk_po_named_contact")).to have_content(t("default.link.edit"))
end
end
end
describe "Benefitting region" do
let(:activity) { build(:programme_activity, benefitting_countries: benefitting_countries) }
before { render }
context "when the activity has benefitting countries" do
subject { body.find(".benefitting_region") }
let(:benefitting_countries) { ["DZ", "LY"] }
let(:expected_region) { BenefittingCountry.find_by_code("DZ").regions.last }
it { is_expected.to have_content(expected_region.name) }
it { is_expected.to_not show_the_edit_add_actions }
end
context "when the activity has no benefitting countries" do
subject { body }
let(:benefitting_countries) { [] }
it { is_expected.to have_css(".benefitting_region") }
end
end
describe "legacy geography recipient_region, recipient_country and intended_beneficiaries" do
context "when there is a value" do
let(:activity) {
build(
:programme_activity,
recipient_region: "298",
recipient_country: "UG",
intended_beneficiaries: ["UG"]
)
}
before { render }
it "is shown at all times and has a helpful 'read only' label" do
expect(body.find(".recipient_region .govuk-summary-list__value")).to have_content("Africa, regional")
expect(body.find(".recipient_region .govuk-summary-list__key")).to have_content("Legacy field: not editable")
expect(body.find(".recipient_country .govuk-summary-list__value")).to have_content("Uganda")
expect(body.find(".recipient_country .govuk-summary-list__key")).to have_content("Legacy field: not editable")
expect(body.find(".intended_beneficiaries .govuk-summary-list__value")).to have_content("Uganda")
expect(body.find(".intended_beneficiaries .govuk-summary-list__key")).to have_content("Legacy field: not editable")
end
context "when the activity is ISPF funded" do
let(:activity) { build(:programme_activity, :ispf_funded) }
it "does not show the legacy fields" do
expect(body).not_to have_css(".recipient_region .govuk-summary-list__value")
expect(body).not_to have_css(".recipient_country .govuk-summary-list__value")
expect(body).not_to have_css(".intended_beneficiaries .govuk-summary-list__value")
end
end
end
context "when there is NOT a value" do
let(:activity) {
build(
:programme_activity,
recipient_region: nil,
recipient_country: nil,
intended_beneficiaries: []
)
}
before { render }
it "is shown at all times and has a helpful 'read only' label" do
expect(body.find(".recipient_region .govuk-summary-list__key")).to have_content("Legacy field: not editable")
expect(body.find(".recipient_country .govuk-summary-list__key")).to have_content("Legacy field: not editable")
expect(body.find(".intended_beneficiaries .govuk-summary-list__key")).to have_content("Legacy field: not editable")
end
end
end
describe "setting the commitment value" do
before do
create(:report, :active, fund: activity.associated_fund, organisation: user.organisation)
render
end
context "when there is a commitment on the activity" do
let(:activity) { create(:project_activity, :with_commitment, organisation: user.organisation) }
it "does not show an edit button next to the commitment" do
expect(body.find(".commitment")).not_to have_link
end
end
context "when there is no commitment on the activity" do
let(:activity) { create(:project_activity, commitment: nil, organisation: user.organisation) }
it "shows an add button next to the commitment" do
expect(body.find(".commitment a")).to have_content("Add")
end
end
end
end
context "when signed in as a BEIS user" do
let(:user) { build(:beis_user) }
context "when the activity is a fund activity" do
let(:activity) { build(:fund_activity, organisation: user.organisation) }
before { render }
it "does not show the parent field" do
expect(rendered).not_to have_content(t("activerecord.attributes.activity.parent"))
end
context "when a title attribute is present" do
let(:activity) { build(:fund_activity, title: "Some title", organisation: user.organisation) }
it "the call to action is 'Edit'" do
expect(body.find(".title a")).to have_content(t("default.link.edit"))
end
end
context "when an activity attribute is not present" do
let(:activity) { build(:fund_activity, title: nil, organisation: user.organisation) }
it "the call to action is 'Add'" do
expect(body.find(".title a")).to have_content(t("default.link.add"))
end
end
context "when the activity only has an identifier" do
let(:activity) { build(:fund_activity, :at_purpose_step, organisation: user.organisation) }
it "only shows the add link on the next step" do
expect(body.find(".identifier")).to_not have_content(t("default.link.edit"))
expect(body.find(".sector")).to_not have_content(t("default.link.add"))
expect(body.find(".title a")).to have_content(t("default.link.add"))
end
end
end
context "when the activity is an ISPF programme" do
let(:activity) { build(:programme_activity, :ispf_funded, is_oda: true, extending_organisation: user.organisation) }
let(:non_oda_programme) {
build(:programme_activity,
:ispf_funded,
is_oda: false,
extending_organisation: user.organisation,
linked_activity: activity)
}
context "when the `activity_linking` feature flag is not active" do
it "does not show the Linked Activities row" do
expect(rendered).to_not have_css(".govuk-summary-list__row.linked_activity")
end
end
context "when the `activity_linking` feature flag is active" do
before { allow(ROLLOUT).to receive(:active?).with(:activity_linking).and_return(true) }
context "and it doesn't have a linked activity" do
before { render }
it "shows a link to add a linked activity" do
expect(body.find(".linked_activity .govuk-summary-list__actions a")).to have_content(t("default.link.add"))
end
end
context "and it has a linked activity" do
before {
activity.linked_activity = non_oda_programme
activity.save
render
}
it "shows a link to edit the linked activity" do
expect(body.find(".linked_activity .govuk-summary-list__actions a")).to have_content(t("default.link.edit"))
end
end
context "when the programme has any child projects that are linked" do
let!(:project) {
create(:project_activity,
:ispf_funded,
is_oda: true,
extending_organisation: user.organisation,
parent: activity)
}
let!(:linked_project) {
create(:project_activity,
:ispf_funded,
is_oda: false,
extending_organisation: user.organisation,
parent: non_oda_programme,
linked_activity: project)
}
before {
activity.linked_activity = non_oda_programme
activity.save
render
}
it "does not show an edit link for the linked programme" do
expect(body.find(".linked_activity .govuk-summary-list__actions")).to_not have_content(t("default.link.edit"))
end
end
end
end
describe "setting the commitment value" do
before { render }
context "when there is a commitment on the activity" do
let(:activity) { create(:project_activity, :with_commitment) }
it "shows an edit button next to the commitment" do
expect(body.find(".commitment a")).to have_content("Edit")
end
end
context "when there is no commitment on the activity" do
let(:activity) { create(:project_activity, commitment: nil) }
it "shows an add button next to the commitment" do
expect(body.find(".commitment a")).to have_content("Add")
end
end
end
end
RSpec::Matchers.define :show_the_edit_add_actions do
match do
expect(rendered).to have_link(t("default.link.edit"))
expect(rendered).to have_link(t("default.link.add"))
end
end
RSpec::Matchers.define :show_the_publish_to_iati_field do
match do |actual|
expect(rendered).to have_content(t("summary.label.activity.publish_to_iati.label"))
end
end
RSpec::Matchers.define :show_basic_details do
match do |actual|
expect(rendered).to have_content activity_presenter.partner_organisation_identifier
expect(rendered).to have_content activity_presenter.title
expect(rendered).to have_content activity_presenter.description
expect(rendered).to have_content activity_presenter.sector
expect(rendered).to have_content activity_presenter.programme_status
expect(rendered).to have_content activity_presenter.objectives
within(".govuk-summary-list__row.collaboration_type") do
expect(rendered).to have_content activity_presenter.collaboration_type
end
expect(rendered).to have_content activity_presenter.gdi
expect(rendered).to have_content activity_presenter.aid_type
expect(rendered).to have_content activity_presenter.aid_type
expect(rendered).to have_content activity_presenter.oda_eligibility
expect(rendered).to have_content activity_presenter.planned_start_date
expect(rendered).to have_content activity_presenter.planned_end_date
end
description do
"show basic details for an activity"
end
end
RSpec::Matchers.define :show_project_details do
match do |actual|
expect(rendered).to have_content activity_presenter.call_present
expect(rendered).to have_content activity_presenter.total_applications
expect(rendered).to have_content activity_presenter.total_awards
within(".policy_marker_gender") do
expect(rendered).to have_content activity_presenter.policy_marker_gender
end
within(".policy_marker_climate_change_adaptation") do
expect(rendered).to have_content activity_presenter.policy_marker_climate_change_adaptation
end
within(".policy_marker_climate_change_mitigation") do
expect(rendered).to have_content activity_presenter.policy_marker_climate_change_mitigation
end
within(".policy_marker_biodiversity") do
expect(rendered).to have_content activity_presenter.policy_marker_biodiversity
end
within(".policy_marker_desertification") do
expect(rendered).to have_content activity_presenter.policy_marker_desertification
end
within(".policy_marker_disability") do
expect(rendered).to have_content activity_presenter.policy_marker_disability
end
within(".policy_marker_disaster_risk_reduction") do
expect(rendered).to have_content activity_presenter.policy_marker_disaster_risk_reduction
end
within(".policy_marker_nutrition") do
expect(rendered).to have_content activity_presenter.policy_marker_nutrition
end
expect(rendered).to have_content t("activerecord.attributes.activity.channel_of_delivery_code")
expect(rendered).to have_content activity_presenter.channel_of_delivery_code
expect(rendered).to have_content activity_presenter.oda_eligibility_lead
expect(rendered).to have_content activity_presenter.uk_po_named_contact
expect(rendered).to have_content activity_presenter.call_open_date
expect(rendered).to have_content activity_presenter.call_close_date
end
description do
"show project-specific details for an activity"
end
end
RSpec::Matchers.define :show_newton_specific_details do
match do |actual|
expect(rendered).to have_css(".govuk-summary-list__row.country_partner_organisations")
activity_presenter.country_partner_organisations.each do |partner_organisation|
expect(rendered).to have_content(partner_organisation)
end
expect(rendered).to have_content activity_presenter.fund_pillar
end
description do
"show Newton activity specific details for an activity"
end
end
RSpec::Matchers.define :show_gcrf_specific_details do
match do |actual|
expect(rendered).to have_css(".govuk-summary-list__row.gcrf_strategic_area")
expect(rendered).to have_css(".govuk-summary-list__row.gcrf_challenge_area")
expect(rendered).to have_content(activity_presenter.gcrf_strategic_area)
expect(rendered).to have_content(activity_presenter.gcrf_challenge_area)
end
description do
"show GCRF activity specific details for an activity"
end
end
RSpec::Matchers.define :show_ispf_specific_details do
match do |actual|
expect(rendered).to have_css(".govuk-summary-list__row.is_oda")
expect(rendered).to have_css(".govuk-summary-list__row.ispf_themes")
expect(rendered).to have_content(activity_presenter.ispf_themes)
if activity_presenter.is_oda
expect(rendered).to have_css(".govuk-summary-list__row.ispf_oda_partner_countries")
expect(rendered).to have_content(activity_presenter.ispf_oda_partner_countries)
end
if activity_presenter.is_non_oda? || activity_presenter.ispf_non_oda_partner_countries.present?
expect(rendered).to have_css(".govuk-summary-list__row.ispf_non_oda_partner_countries")
expect(rendered).to have_content(activity_presenter.ispf_non_oda_partner_countries)
end
end
description do
"show ISPF activity specific details for an activity"
end
end
end
|
class User < ApplicationRecord
has_many :products, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :commented_products, through: :comments, source: :product
has_many :conversations, :foreign_key => :sender_id
has_secure_password
validates :email, :username, :password, :presence => true
validates :email, :username, :uniqueness => true
validates :password, :length => { :in => 6..20 }
end
|
# we remove all the anonymous users
class Tasks::Bloodbath::RemoveAllAnonymous
def initialize
puts "Task initialized."
User.where(role: :anonymous).destroy_all
end
def perform
puts "Task performed."
end
private
end
|
module SqlMigrations
class Database
SCHEMA_TABLE = :sqlmigrations_schema
attr_reader :db
def initialize(options)
@name = options[:name] || :default
begin
@db = Sequel.connect(adapter: options['adapter'],
host: options['host'],
database: options['database'],
user: options['username'],
password: options['password'],
test: true)
rescue
puts "[-] Could not connect to database using #{options['adapter']} adapter"
raise
else
puts "[+] Connected to database using #{options['adapter']} adapter"
end
install_table
end
def execute_migrations
puts "[i] Executing migrations"
Migration.find(@name).each { |migration| migration.execute(self) }
end
def seed_database
puts "[i] Seeding database"
Seed.find(@name).each { |seed| seed.execute(self) }
end
def seed_with_fixtures
puts "[i] Seeding test database with fixtures"
Fixture.find(@name).each { |fixture| fixture.execute(self) }
end
def schema_dataset
@db[SCHEMA_TABLE]
end
private
def install_table
# Check if we have migrations_schema table present
unless @db.table_exists?(SCHEMA_TABLE)
puts "[!] Installing `#{SCHEMA_TABLE}`"
@db.create_table(SCHEMA_TABLE) do
primary_key :id
Bignum :time
DateTime :executed
String :name
String :type
index [ :time, :type ]
end
end
end
end
end
|
require 'rails_helper'
feature "Manage Posts" do
def create_post
Post.create!(#capybara creates a test database it should clear out when test runs
subject: 'this is my subject',
body: 'blah blah blogy blog',
published_at: '2014-10-21'
)
end
scenario "See list of blog posts" do
create_post
visit posts_path
expect(page).to have_content("this is my subject")
end
scenario "User can click the create new button and be directed to a new page with a form" do
create_post
visit posts_path
click_on('Create New Post')
visit new_post_path
end
end
# scenario "List all Posts" do
# create_posts
# visit posts_path
# expect(page.find('.subject')).to have_content(/Test Post/)
# expect(page.find('.body')).to have_content(/Test Post/)
# expect(page.find('.published_at')).to have_content(/Test Post/)
# end
# scenario "Edit Posts"
# end
# scenario "Delete post and redirect to index" do
# post = create_post
# cisit post_path(post)
# click_on 'Destroy'
# expect(current_path).to eq(posts_path)
# expect(posts_path).to_not have_content("blah")
# end
|
# frozen_string_literal: true
module Features
module TableHelpers
def find_horizontal_table_cell(node, ref_header, ref_value, header, options = {})
node.find(:xpath, horizontal_table_cell_xpath(ref_header, ref_value, header).to_s, options)
end
def assert_horizontal_table_cell(node, ref_header, ref_value, header, options = {})
node.assert_selector(:xpath, horizontal_table_cell_xpath(ref_header, ref_value, header).to_s, options)
end
def assert_horizontal_table_row(node, header, value)
assert_horizontal_table_cell(node, header, value, header, text: value)
end
def horizontal_table_xpath(labels, rows_data)
XPath.generate do |x|
cell_offset = 'count(preceding-sibling::*[td or th])'
rows_data.inject(x.css('table').child(:tbody)) do |body, row_data|
body.where(row_data.inject(x.child(:tr)) do |row, (attribute, value)|
header = labels[attribute] || raise("No label defined for key #{attribute}")
th = "ancestor::table/thead/tr/th[normalize-space(.) = \"#{header}\"]"
matches_value = "normalize-space(.) = \"#{value}\""
head_offset = "count(#{th}/preceding-sibling::*[td or th])"
row.where(th.to_sym).where(:"./td[#{matches_value} and #{cell_offset} = #{head_offset}]")
end)
end
end
end
def horizontal_table_cell_xpath(ref_header, ref_value, header)
ref_th = "ancestor::table/thead/tr/th[normalize-space(.) = \"#{ref_header}\"]"
matches_ref_value = "normalize-space(.) = \"#{ref_value}\""
ref_head_offset = "count(#{ref_th}/preceding-sibling::*[self::td or self::th])"
th = "ancestor::table/thead/tr/th[normalize-space(.) = \"#{header}\"]"
head_offset = "count(#{th}/preceding-sibling::*[self::td or self::th])"
cell_offset = 'count(preceding-sibling::*[self::td or self::th])'
XPath.css('table').child(:tbody).child(:tr)
.where(ref_th.to_sym)
.where(:"./td[#{matches_ref_value} and #{cell_offset} = #{ref_head_offset}]")
.where(th.to_sym)
.child(:"td[#{cell_offset} = #{head_offset}]")
end
end
end
|
class UsersController < ApplicationController
before_action :set_company
before_action :set_user, only: [:show, :edit, :update, :destroy, :calendar]
# GET /users/1
# GET /users/1.json
def show
end
# GET /users/1/edit
def edit
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
if @user.update_attributes(user_params)
redirect_to company_user_path(@company, @user), notice: 'User was successfully updated.'
else
render :edit
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
@user.inactive!
redirect_to root_path, notice: "We've successfully removed your account."
end
def calendar
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = current_user
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :company_name)
end
def set_company
@company = Company.friendly.find params[:company_id]
end
end
|
require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Expandable do
let(:root) { OpenAPIParser.parse(normal_schema, {}) }
describe 'expand_reference' do
subject { root }
it do
subject
expect(subject.find_object('#/paths/~1reference/get/parameters/0').class).to eq OpenAPIParser::Schemas::Parameter
expect(subject.find_object('#/paths/~1reference/get/responses/default').class).to eq OpenAPIParser::Schemas::Response
expect(subject.find_object('#/paths/~1reference/post/responses/default').class).to eq OpenAPIParser::Schemas::Response
path = '#/paths/~1string_params_coercer/post/requestBody/content/application~1json/schema/properties/nested_array'
expect(subject.find_object(path).class).to eq OpenAPIParser::Schemas::Schema
end
context 'undefined spec references' do
let(:invalid_reference) { '#/paths/~1ref-sample~1broken_reference/get/requestBody' }
let(:not_configured) { {} }
let(:raise_on_invalid_reference) { { strict_reference_validation: true } }
let(:misconfiguration) {
{
expand_reference: false,
strict_reference_validation: true
}
}
it 'raises when configured to do so' do
raise_message = "'#/components/requestBodies/foobar' was referenced but could not be found"
expect { OpenAPIParser.parse(broken_reference_schema, raise_on_invalid_reference) }.to(
raise_error(OpenAPIParser::MissingReferenceError) { |error| expect(error.message).to eq(raise_message) }
)
end
it 'does not raise when not configured, returns nil reference' do
subject = OpenAPIParser.parse(broken_reference_schema, not_configured)
expect(subject.find_object(invalid_reference)).to be_nil
end
it 'does not raise when configured, but expand_reference is false' do
subject = OpenAPIParser.parse(broken_reference_schema, misconfiguration)
expect(subject.find_object(invalid_reference)).to be_nil
end
end
end
end
|
class AddFieldNextPhoneNumberAndnextEmailToContactInformations < ActiveRecord::Migration[6.0]
def change
add_column :users, :new_email, :string
add_column :contact_informations, :new_phone_number, :string
add_column :users, :email_code, :integer
add_column :contact_informations, :sms_code, :integer
remove_column :users, :sms_code, :integer
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
has_mobile_fu false
decent_configuration do
strategy DecentExposure::StrongParametersStrategy
end
expose(:subscriber) { NewsletterSubscriber.new }
protected
def current_site
language = session[:language] || "en"
@current_site ||= Site.with_language(language.upcase).first
end
helper_method :current_site
def antispam!
if cookies[:antispam]
cookies.delete :antispam
else
return redirect_to(:back)
end
end
end
|
class Post < ActiveRecord::Base
belongs_to :author
has_many :images
has_many :comments
has_many :post_tags
has_many :tags, :through => :post_tags
validates :title, presence: true
validates :body , presence: true, length: {
minimum: 20,
tokenizer: lambda { |str| str.split(/\s+/) },
too_short: "must have at least 20 words",
}
end |
# frozen_string_literal: true
# == Schema Information
#
# Table name: purchases
#
# id :bigint not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
# product_id :bigint
# slot_id :bigint
#
# Indexes
#
# index_purchases_on_product_id (product_id)
# index_purchases_on_slot_id (slot_id)
#
# Foreign Keys
#
# fk_rails_... (product_id => products.id)
# fk_rails_... (slot_id => slots.id)
#
class Purchase < ApplicationRecord
belongs_to :product
belongs_to :slot
end
|
Given /^I generate a new rails application$/ do
steps %{
When I successfully run `rails new #{APP_NAME} --skip-bundle`
And I cd to "#{APP_NAME}"
}
FileUtils.chdir("tmp/aruba/testapp/")
steps %{
And I turn off class caching
And I write to "Gemfile" with:
"""
source "http://rubygems.org"
gem "rails", "#{framework_version}"
gem "sqlite3", :platform => [:ruby, :rbx]
gem "activerecord-jdbcsqlite3-adapter", :platform => :jruby
gem "jruby-openssl", :platform => :jruby
gem "capybara"
gem "gherkin"
gem "aws-sdk-s3"
gem "racc", :platform => :rbx
gem "rubysl", :platform => :rbx
"""
And I remove turbolinks
And I comment out lines that contain "action_mailer" in "config/environments/*.rb"
And I empty the application.js file
And I configure the application to use "paperclip" from this project
}
FileUtils.chdir("../../..")
end
Given /^I generate a "([^"]*)" model:$/ do |model_name|
step %[I successfully run `rails generate model #{model_name}`]
end
Given /^I run a paperclip migration to add a paperclip "([^"]*)" to the "([^"]*)" model$/ do |attachment_name, model_name|
step %[I successfully run `rails generate paperclip #{model_name} #{attachment_name}`]
end
Given "I allow the attachment to be submitted" do
cd(".") do
transform_file("app/controllers/users_controller.rb") do |content|
content.gsub("params.require(:user).permit(:name)",
"params.require(:user).permit!")
end
end
end
Given "I remove turbolinks" do
cd(".") do
transform_file("app/assets/javascripts/application.js") do |content|
content.gsub("//= require turbolinks", "")
end
transform_file("app/views/layouts/application.html.erb") do |content|
content.gsub(', "data-turbolinks-track" => true', "")
end
end
end
Given /^I comment out lines that contain "([^"]+)" in "([^"]+)"$/ do |contains, glob|
cd(".") do
Dir.glob(glob).each do |file|
transform_file(file) do |content|
content.gsub(/^(.*?#{contains}.*?)$/) { |line| "# #{line}" }
end
end
end
end
Given /^I attach :attachment$/ do
attach_attachment("attachment")
end
Given /^I attach :attachment with:$/ do |definition|
attach_attachment("attachment", definition)
end
def attach_attachment(name, definition = nil)
snippet = "has_attached_file :#{name}"
if definition
snippet += ", \n"
snippet += definition
end
snippet += "\ndo_not_validate_attachment_file_type :#{name}\n"
cd(".") do
transform_file("app/models/user.rb") do |content|
content.sub(/end\Z/, "#{snippet}\nend")
end
end
end
Given "I empty the application.js file" do
cd(".") do
transform_file("app/assets/javascripts/application.js") do |_content|
""
end
end
end
Given /^I run a rails generator to generate a "([^"]*)" scaffold with "([^"]*)"$/ do |model_name, attributes|
step %[I successfully run `rails generate scaffold #{model_name} #{attributes}`]
end
Given /^I run a paperclip generator to add a paperclip "([^"]*)" to the "([^"]*)" model$/ do |attachment_name, model_name|
step %[I successfully run `rails generate paperclip #{model_name} #{attachment_name}`]
end
Given /^I run a migration$/ do
step %[I successfully run `rake db:migrate --trace`]
end
When /^I rollback a migration$/ do
step %[I successfully run `rake db:rollback STEPS=1 --trace`]
end
Given /^I update my new user view to include the file upload field$/ do
steps %{
Given I overwrite "app/views/users/new.html.erb" with:
"""
<%= form_for @user, :html => { :multipart => true } do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :attachment %>
<%= f.file_field :attachment %>
<%= submit_tag "Submit" %>
<% end %>
"""
}
end
Given /^I update my user view to include the attachment$/ do
steps %{
Given I overwrite "app/views/users/show.html.erb" with:
"""
<p>Name: <%= @user.name %></p>
<p>Attachment: <%= image_tag @user.attachment.url %></p>
"""
}
end
Given /^I add this snippet to the User model:$/ do |snippet|
file_name = "app/models/user.rb"
cd(".") do
content = File.read(file_name)
File.open(file_name, "w") { |f| f << content.sub(/end\Z/, "#{snippet}\nend") }
end
end
Given /^I add this snippet to config\/application.rb:$/ do |snippet|
file_name = "config/application.rb"
cd(".") do
content = File.read(file_name)
File.open(file_name, "w") do |f|
f << content.sub(/class Application < Rails::Application.*$/,
"class Application < Rails::Application\n#{snippet}\n")
end
end
end
Given /^I replace this snippet to app\/views\/layouts\/application.html.erb:$/ do |snippet|
file_name = "app/views/layouts/application.html.erb"
cd(".") do
content = File.read(file_name)
File.open(file_name, "w") do |f|
f << content.sub(/<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>$/,
"#{snippet}")
end
end
end
Given /^I start the rails application$/ do
cd(".") do
require "rails"
require "./config/environment"
require "capybara"
Capybara.app = Rails.application
end
end
Given /^I reload my application$/ do
Rails::Application.reload!
end
When /^I turn off class caching$/ do
cd(".") do
file = "config/environments/test.rb"
config = IO.read(file)
config.gsub!(%r{^\s*config.cache_classes.*$},
"config.cache_classes = false")
File.open(file, "w") { |f| f.write(config) }
end
end
Then /^the file at "([^"]*)" should be the same as "([^"]*)"$/ do |web_file, path|
expected = IO.read(path)
actual = read_from_web(web_file)
expect(actual).to eq(expected)
end
When /^I configure the application to use "([^\"]+)" from this project$/ do |name|
append_to_gemfile "gem '#{name}', :path => '#{PROJECT_ROOT}'"
steps %{And I successfully run `bundle install --local`}
end
When /^I configure the application to use "([^\"]+)"$/ do |gem_name|
append_to_gemfile "gem '#{gem_name}'"
end
When /^I append gems from Appraisal Gemfile$/ do
File.read(ENV["BUNDLE_GEMFILE"]).split(/\n/).each do |line|
append_to_gemfile line.strip if line =~ /^gem "(?!rails|appraisal)/
end
end
When /^I comment out the gem "([^"]*)" from the Gemfile$/ do |gemname|
comment_out_gem_in_gemfile gemname
end
Given(/^I add a "(.*?)" processor in "(.*?)"$/) do |processor, directory|
filename = "#{directory}/#{processor}.rb"
cd(".") do
FileUtils.mkdir_p directory
File.open(filename, "w") do |f|
f.write(<<-CLASS)
module Paperclip
class #{processor.capitalize} < Processor
def make
basename = File.basename(file.path, File.extname(file.path))
dst_format = options[:format] ? ".\#{options[:format]}" : ''
dst = Tempfile.new([basename, dst_format])
dst.binmode
convert(':src :dst',
src: File.expand_path(file.path),
dst: File.expand_path(dst.path)
)
dst
end
end
end
CLASS
end
end
end
def transform_file(filename)
if File.exist?(filename)
content = File.read(filename)
File.open(filename, "w") do |f|
content = yield(content)
f.write(content)
end
end
end
|
require 'test_helper'
class AccountsControllerTest < ActionController::TestCase
setup do
@account = accounts(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:accounts)
end
test "should get new" do
get :new
assert_response :success
end
test "should create account" do
assert_difference('Account.count') do
post :create, account: { address_line1: @account.address_line1, address_line2: @account.address_line2, billing_first_name: @account.billing_first_name, billing_last_name: @account.billing_last_name, card_number: @account.card_number, city: @account.city, condition_id: @account.condition_id, country: @account.country, expiration_month: @account.expiration_month, expiration_year: @account.expiration_year, name_on_card: @account.name_on_card, phone_number: @account.phone_number, security_code: @account.security_code, state: @account.state, user_id: @account.user_id, zip_code: @account.zip_code }
end
assert_redirected_to account_path(assigns(:account))
end
test "should show account" do
get :show, id: @account
assert_response :success
end
test "should get edit" do
get :edit, id: @account
assert_response :success
end
test "should update account" do
patch :update, id: @account, account: { address_line1: @account.address_line1, address_line2: @account.address_line2, billing_first_name: @account.billing_first_name, billing_last_name: @account.billing_last_name, card_number: @account.card_number, city: @account.city, condition_id: @account.condition_id, country: @account.country, expiration_month: @account.expiration_month, expiration_year: @account.expiration_year, name_on_card: @account.name_on_card, phone_number: @account.phone_number, security_code: @account.security_code, state: @account.state, user_id: @account.user_id, zip_code: @account.zip_code }
assert_redirected_to account_path(assigns(:account))
end
test "should destroy account" do
assert_difference('Account.count', -1) do
delete :destroy, id: @account
end
assert_redirected_to accounts_path
end
end
|
class SearchEngiensController < ApplicationController
before_action :set_search_engien, only: [:show, :edit, :update, :destroy]
# GET /search_engiens
# GET /search_engiens.json
def index
@search_engiens = SearchEngien.all
end
# GET /search_engiens/1
# GET /search_engiens/1.json
def show
end
# GET /search_engiens/new
def new
@search_engien = SearchEngien.new
end
# GET /search_engiens/1/edit
def edit
end
# POST /search_engiens
# POST /search_engiens.json
def create
@search_engien = SearchEngien.new(search_engien_params)
respond_to do |format|
if @search_engien.save
format.html { redirect_to @search_engien, notice: 'Search engien was successfully created.' }
format.json { render :show, status: :created, location: @search_engien }
else
format.html { render :new }
format.json { render json: @search_engien.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /search_engiens/1
# PATCH/PUT /search_engiens/1.json
def update
respond_to do |format|
if @search_engien.update(search_engien_params)
format.html { redirect_to @search_engien, notice: 'Search engien was successfully updated.' }
format.json { render :show, status: :ok, location: @search_engien }
else
format.html { render :edit }
format.json { render json: @search_engien.errors, status: :unprocessable_entity }
end
end
end
# DELETE /search_engiens/1
# DELETE /search_engiens/1.json
def destroy
@search_engien.destroy
respond_to do |format|
format.html { redirect_to search_engiens_url, notice: 'Search engien was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_search_engien
@search_engien = SearchEngien.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def search_engien_params
params.require(:search_engien).permit(:title, :head, :footer)
end
end
|
Gem::Specification.new do |s|
s.name = "prediction"
s.version = "1.0"
s.description = "A gem for calculate prediction algorithm"
s.summary = "Calculate Prediction Algorithm"
s.author = "Victor Antoniazzi"
s.email = "vgsantoniazzi@gmail.com"
s.homepage = "http://victorantoniazzi.com.br"
s.files = Dir["{lib/**/*.rb,README.rdoc,tests/**/*.rb,Rakefile,*.gemspec}"]
end
|
# frozen_string_literal: true
class SplitPresenter < BasePresenter
attr_reader :split
delegate :id, :course, :course_id, :base_name, :description, :distance_from_start, :vert_gain_from_start,
:vert_loss_from_start, :latitude, :longitude, :elevation, :to_param, to: :split
delegate :track_points, to: :course
delegate :organization, to: :event
def initialize(split, params, current_user)
@split = split
@params = params
@current_user = current_user
end
def event
@event ||= course.events.visible.latest
end
def course_splits
@course_splits ||= split.course.ordered_splits
end
private
attr_reader :params, :current_user
end
|
require 'time'
require 'date'
require 'numerizer'
require 'chronic/version'
require 'tzinfo'
require 'timezone_parser'
require 'chronic/parser'
require 'chronic/date'
require 'chronic/time'
require 'chronic/time_zone'
require 'chronic/arrow'
require 'chronic/handler'
require 'chronic/span'
require 'chronic/token'
require 'chronic/token_group'
require 'chronic/tokenizer'
require 'chronic/tag'
require 'chronic/tags/day_name'
require 'chronic/tags/day_portion'
require 'chronic/tags/day_special'
require 'chronic/tags/grabber'
require 'chronic/tags/keyword'
require 'chronic/tags/month_name'
require 'chronic/tags/ordinal'
require 'chronic/tags/pointer'
require 'chronic/tags/rational'
require 'chronic/tags/scalar'
require 'chronic/tags/season_name'
require 'chronic/tags/separator'
require 'chronic/tags/sign'
require 'chronic/tags/time_special'
require 'chronic/tags/time_zone'
require 'chronic/tags/unit'
# Parse natural language dates and times into Time or Chronic::Span objects.
#
# Examples:
#
# require 'chronic'
#
# Time.now #=> Sun Aug 27 23:18:25 PDT 2006
#
# Chronic.parse('tomorrow')
# #=> Mon Aug 28 12:00:00 PDT 2006
#
# Chronic.parse('monday', :context => :past)
# #=> Mon Aug 21 12:00:00 PDT 2006
module Chronic
class << self
# Returns true when debug mode is enabled.
attr_accessor :debug
# Examples:
#
# require 'chronic'
# require 'active_support/time'
#
# Time.zone = 'UTC'
# Chronic.time_class = Time.zone
# Chronic.parse('June 15 2006 at 5:54 AM')
# # => Thu, 15 Jun 2006 05:45:00 UTC +00:00
#
# Returns The Time class Chronic uses internally.
attr_accessor :time_class
end
self.debug = false
self.time_class = ::Time
# Parses a string containing a natural language date or time.
#
# If the parser can find a date or time, either a Time or Chronic::Span
# will be returned (depending on the value of `:guess`). If no
# date or time can be found, `nil` will be returned.
#
# text - The String text to parse.
# opts - An optional Hash of configuration options passed to Parser::new.
def self.parse(text, options = {})
Parser.new(options).parse(text)
end
# Construct a new time object determining possible month overflows
# and leap years.
#
# year - Integer year.
# month - Integer month.
# day - Integer day.
# hour - Integer hour.
# minute - Integer minute.
# second - Integer second.
#
# Returns a new Time object constructed from these params.
def self.construct(year, month = 1, day = 1, hour = 0, minute = 0, second = 0, timezone = nil)
day, hour, minute, second = Time::normalize(day, hour, minute, second)
year, month, day = Date::add_day(year, month, day, 0) if day > 28
year, month = Date::add_month(year, month, 0) if month > 12
if Chronic.time_class.name == 'Date'
Chronic.time_class.new(year, month, day)
elsif not Chronic.time_class.respond_to?(:new) or (RUBY_VERSION.to_f < 1.9 and Chronic.time_class.name == 'Time')
Chronic.time_class.local(year, month, day, hour, minute, second)
else
if timezone and timezone.respond_to?(:to_offset)
offset = timezone.to_offset(year, month, day, hour, minute, second)
else
offset = timezone
end
offset = TimeZone::normalize_offset(offset) if Chronic.time_class.name == 'DateTime'
Chronic.time_class.new(year, month, day, hour, minute, second, offset)
end
end
end
|
class AddUuidToSoftkeys < ActiveRecord::Migration
def change
add_column :softkeys, :uuid, :string
end
end
|
class QuizzesController < ApplicationController
before_action :signed_in_user, only: [:create, :index, :show]
def index
@quiz = Quizzes.order(created_at: :desc).find_by(user_id: params[:id])
end
def create
user = current_user
# Get user quizzes. If one is unfinished redirect
unfinished_quiz = user.quizzes.order(created_at: :desc).where("total_answers IS NULL").take(1)
if (unfinished_quiz.empty?) then
quiz = user.quizzes.create!(number_correct: 0)
# If question hasn't been answered in a week. Halve the weight
adjust_weight = UserQuestion.where("user_id = #{current_user.id}")
adjust_weight.each do |a|
if (a.updated_at < Date.today-7.days) then
a.weight /= 2
end
end
# Order by descending weight
worst_questions = UserQuestion.order(:weight).where("user_id = #{current_user.id}").take(10)
worst_questions.each do |w|
quiz.quiz_question.create!(question_id: w.question_id)
Question.find(w.question_id)
end
else
quiz = unfinished_quiz.first
end
redirect_to "/quizzes/show/#{quiz.id}"
end
def show
@user = current_user
@quiz = Quiz.find(params[:id])
@quiz.quiz_question.each do |q|
if q.answered_correctly == nil
@question = Question.find_by(id: q.question_id)
@quiz_question = q
break
end
end
# If all questions are answered
if (@question.nil?) then
redirect_to "/quizzes/results/#{@quiz.id}"
else
@answers = Answer.where("question_id = #{@question.id}")
correct = @answers.where("correct_answer = true").shuffle.take(1)
incorrect = @answers.where("correct_answer = false").shuffle.take(3)
final = correct + incorrect
@answers = final.shuffle
end
end
def results
@user = current_user
@quiz = Quiz.find(params[:id])
@quiz_question = @quiz.quiz_question
@question = Question.where(id: @quiz_question.first.question_id)
end
def update
user = current_user
selected_answer = Answer.find(params[:answerid])
quiz_question = QuizQuestion.find(params[:quizquestionid])
user_question = user.user_questions.find_by(question_id: quiz_question.question_id)
# Determine if correct
if (selected_answer.correct_answer) then
# Update quiz question
quiz_question.answered_correctly = true
# Update user question
user_question.correct_answers += 1
user_question.total_answers += 1
else
# Update quiz question
quiz_question.answered_correctly = false
# Update user question
user_question.total_answers += 1
end
user_question.weight = user_question.correct_answers / user_question.total_answers.to_f
# Save Quiz Question
quiz_question.save
# Save User Question
user_question.save
# Check if quiz is done
quiz = Quiz.find(quiz_question.quiz_id)
complete = true
quiz.quiz_question.each do |q|
if q.answered_correctly == nil
complete = false
break
end
end
# Update quiz
if (complete)
quiz.quiz_question.each do |q|
if (q.answered_correctly)
quiz.number_correct += 1
end
end
quiz.total_answers = quiz.quiz_question.count
quiz.save
end
# Redirect to quiz
redirect_to "/quizzes/show/#{quiz_question.quiz_id}"
end
end |
module Concerns
module Taggable
extend ActiveSupport::Concern
included do
attr_accessor :tag_names
has_many :taggings, as: :taggable, class_name: 'Tagging'
has_many :tags, through: :taggings, class_name: 'Tag'
before_save :save_tag_names
def tag_names
@tag_names || tags.pluck(:name).join(" ")
end
def save_tag_names
self.tags = @tag_names.split.map { |name| Tag.where(name: name).first_or_create! } if @tag_names
end
end
end
end |
class CreateRepresentationalValues < ActiveRecord::Migration
def self.up
create_table "pas_representational_values" do |t|
t.column :model_activity_modelrun_id, :integer
t.column :representational_attribute_id, :integer
t.column :time, :float
end
add_index "pas_representational_values", :model_activity_modelrun_id, :name => "rv_model_activity_modelrun_id_index"
add_index "pas_representational_values", :representational_attribute_id, :name => "representational_attribute_id_index"
end
def self.down
drop_table "pas_representational_values"
end
end
|
class Admin::ExamRoom::QuestionsController < AdminController
before_filter :get_question, :except => [:index]
def index
@questions = ExamRoom::Question.scoped.paginate(:per_page => 20, :page => params[:page])
end
def update
@question.update_attributes(params[:question])
unless @question.valid?
raise @question.errors.map{|x,y|"#{x}:#{y}"}.join(",")
end
redirect_to @question
end
def show
redirect_to @question
end
def graph
@stats = if params[:friends]
@question.calculate_stats(:user_ids => current_user.friend_ids)
elsif params[:community_id] && current_user.community_memberships.where(:community_id => params[:community_id]).exists?
@question.calculate_stats(:community_ids => [params[:community_id]])
else
@question.calculate_stats
end
@practice_question = ExamRoom::Practice::Question.find(params[:practice_question_id]) if params[:practice_question_id]
end
def make_live
@question.make_live!
end
private
def get_question
@question = ExamRoom::Question.find(params[:id])
end
end
|
require 'rails_helper'
describe User do
let(:user){ build(:user) }
it "is valid with name, email and password" do
expect(user).to be_valid
end
it "responds to secrets" do
expect(user).to respond_to(:secrets)
end
it "saves with default values" do
expect{ user.save! }.not_to raise_error
end
context "name with" do
it "2 charecters is not valid" do
new_user = build(:user, name: "12")
expect(new_user).not_to be_valid
end
it "21 charecters is not valid" do
new_user = build(:user, name: "1" * 21 )
expect(new_user).not_to be_valid
end
it "is valid with 6 charecters" do
new_user = build(:user, name: "1" * 6)
expect(new_user).to be_valid
end
it "nil value is invalid" do
new_user = build(:user, name: nil)
expect(new_user).not_to be_valid
end
end
context "password with" do
it "7 charecters is valid" do
new_user = build(:user, password: "1" * 7)
expect(new_user).to be_valid
end
it "5 charecters is invalid" do
new_user = build(:user, password: "1" * 5)
expect(new_user).not_to be_valid
end
it "17 charecters is invalid" do
new_user = build(:user, password: "1" * 17)
expect(new_user).not_to be_valid
end
end
end
|
# frozen_string_literal: true
Then('I can get the text values for the group of links') do
expect(@test_site.home.lots_of_links.map(&:text)).to eq(%w[a b c])
end
Then('the page does not have a group of elements') do
expect(@test_site.home.has_no_nonexistent_elements?).to be true
expect(@test_site.home).to have_no_nonexistent_elements
end
Then('I can see individual people in the people list') do
expect(@test_site.home.people.individuals.size).to eq(4)
expect(@test_site.home.people).to have_individuals(count: 4)
end
Then('I can see optioned individual people in the people list') do
expect(@test_site.home.people.optioned_individuals.size).to eq(4)
expect(@test_site.home.people).to have_optioned_individuals(count: 4)
end
Then('I can wait a variable time and pass specific parameters') do
@test_site.home.wait_for_lots_of_links(0.1, count: 2)
Capybara.using_wait_time(0.3) do
# intentionally wait and pass nil to force this to cycle
expect(@test_site.home.wait_for_lots_of_links(nil, count: 198_108_14))
.to be_falsey
end
end
Then('I can wait a variable time for elements to disappear and pass specific parameters') do
expect do
@test_site.home.wait_for_no_removing_links(0.1, text: 'wibble')
end.not_to raise_error(SitePrism::TimeoutException)
end
|
class EventsController < ApplicationController
before_action :set_event, only: [:edit, :update]
# GET /events
# GET /events.json
def index
@users = User.all
end
# GET /events/1/edit
def edit
end
# PATCH/PUT /events/1
# PATCH/PUT /events/1.json
def update
respond_to do |format|
if @event.update(event_params)
format.html { redirect_to @event, notice: 'Event was successfully updated.' }
format.json { render :show, status: :ok, location: @event }
else
format.html { render :edit }
format.json { render json: @event.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_event
@event = Event.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def event_params
params.require(:event).permit(:user_id, :checkin_at, :checkout_at)
end
end
|
class ActiveRecordFiles::NoRootFolderError < StandardError
def initialize(msg = "No root folder defined. Please define ActiveRecordFiles::Base.configurations = {root: Pathname.new('/custome/folder')}")
super
end
end
|
require 'test_helper'
class BibliosControllerTest < ActionController::TestCase
setup do
@biblio = biblios(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:biblios)
end
test "should get new" do
get :new
assert_response :success
end
test "should create biblio" do
assert_difference('Biblio.count') do
post :create, biblio: { alugado: @biblio.alugado, autor: @biblio.autor, disponivel: @biblio.disponivel, editora: @biblio.editora, sinopse: @biblio.sinopse, titulo: @biblio.titulo }
end
assert_redirected_to biblio_path(assigns(:biblio))
end
test "should show biblio" do
get :show, id: @biblio
assert_response :success
end
test "should get edit" do
get :edit, id: @biblio
assert_response :success
end
test "should update biblio" do
put :update, id: @biblio, biblio: { alugado: @biblio.alugado, autor: @biblio.autor, disponivel: @biblio.disponivel, editora: @biblio.editora, sinopse: @biblio.sinopse, titulo: @biblio.titulo }
assert_redirected_to biblio_path(assigns(:biblio))
end
test "should destroy biblio" do
assert_difference('Biblio.count', -1) do
delete :destroy, id: @biblio
end
assert_redirected_to biblios_path
end
end
|
require './file_record'
class FileCollection
attr_reader :options, :contents
def initialize(options)
@options = options
@contents = {}
end
def add(record)
name = record.name
unless contents[name]
contents[name] = []
end
contents[name] << record
# puts "Adding #{name} to Collection" if options.verbose?
end
def find(record)
name = record.name
matching_set = contents[name]
return(false) if matching_set.nil?
matching_set.find { |element| element == record }
end
def each
contents.each do |key, matches|
matches.each do |record|
yield(record)
end
end
end
def to_s
contents.each do |key, matches|
puts "Name: #{key}"
matches.each { |record| puts " #{record}" }
end
end
end
|
module Importer
class UnitImport < ::Importer::Base
include Importer::MediaImport
def initialize(import)
super
@imported_units = Set.new
@date_format ='%Y%m%d'
end
def before
end
def map_unit(unit)
if sanitize_unit(unit_hash(unit))
import(Unit::Rank, unit_finder_hash(unit), unit_hash(unit))
@imported_units << unit.key
print '.'
end
end
def unit_hash(unit)
images = @unit_images[unit.key]
{
name: unit.name,
key: unit.key,
size: unit.size,
pop_cost: unit.population.to_f,
resource_1: unit.minerals,
resource_2: unit.gas,
resource_3: nil,
hitpoints: unit.hp.to_f,
shield: unit.shield.to_f,
armor_value: unit.armor,
g_attack: unit.g_attack,
g_attack_dps: nil,
a_attack: unit.a_attack,
a_attack_dps: nil,
attack_cd: unit.cooldown,
attack_mod_1: unit.attack_mod,
attack_mod_2: nil,
ground_attack_range: unit.range.to_f,
air_attack_range: unit.range.to_f,
sight: unit.sight.to_f,
notes: unit.notes,
build_time: unit.build_time,
max_level: 3,
# abilities: nil,
game: find_or_create_game(unit.game),
species: find_or_create_species(unit.species),
armor: find_or_create_armor(unit.armor_type),
images: get_image_hash(images)
}
end
def find_or_create_game(game_key)
return nil unless game_key.present?
if Game.where(key: game_key).first.blank?
Game.create!(key: game_key)
end
Game.where(key: game_key).first
end
def find_or_create_species(species_key)
return nil unless species_key.present?
if Species.where(key: species_key).first.blank?
Species.create!(key: species_key)
end
Species.where(key: species_key).first
end
def find_or_create_armor(armor_key)
return nil unless armor_key.present?
if Armor.where(key: armor_key).first.blank?
Armor.create!(key: armor_key)
end
Armor.where(key: armor_key).first
end
def unit_finder_hash(unit)
{
key: unit.key
}
end
def sanitize_unit(record)
required_s = [:key, :name]
sanitize_record(record, required_s, @import, :"Unit::Base")
end
def after
missings = []
Unit::Base.all.only(:_id, :key).entries.each do |unit_model|
missings << unit_model.id unless @imported_units.include?(unit_model.key.to_s)
end
Unit::Base.where(:_id.in => missings).update_all(:deleted_at => Time.now)
if Rails.env.development?
tmp_dir = File.join(Rails.root, 'tmp', 'import', 'images', 'processed', '*')
dst_dir = File.join(Rails.root, 'public', 'images', 'unit_images')
FileUtils.mkdir_p dst_dir unless File.exist? dst_dir
Dir.glob(tmp_dir) {|image| FileUtils.mv(image, dst_dir)}
end
end
end
end |
class Task < ActiveRecord::Base
belongs_to :project
enum status: [:active, :completed]
validates :content, presence: true
validates :status, presence: true
validates :project_id, presence: true
end
|
class CreateWorks < ActiveRecord::Migration
def change
create_table :works do |t|
t.references :user
t.string :title
t.text :authors
t.integer :work_type
t.string :event_name
t.string :event_organizer
t.string :event_location
t.references :country
t.boolean :is_international
t.date :start_date
t.date :end_date
t.date :sent_date
t.date :accepted_date
t.date :published_date
t.integer :status
t.integer :last_updated_by
t.integer :validation_status
t.timestamps
end
add_index(:works, :user_id)
add_index(:works, :country_id)
end
end
|
require "rspec"
require_relative "account"
describe Account do
let(:acct_number) { '1234567890' }
let(:starting_balance) { 1000 }
let(:account) { Account.new(acct_number, starting_balance)}
describe "#initialize" do
context "with valid input" do
it "create a new Account" do
acct_number = '1234567890'
starting_balance = 1000
expect(Account.new(acct_number, starting_balance)).to be_a_kind_of(Account)
end
end
context "with invalid acct_number argument" do
it "throws an argument error" do
acct_number = '123'
starting_balance = 1000
expect {Account.new(acct_number, starting_balance)}.to raise_error(InvalidAccountNumberError)
end
end
end
describe "#transactions" do
it "returns the transactions history" do
expect(account.transactions).to be_a_kind_of(Array)
end
end
describe "#balance" do
it "returns the account balance" do
expect(account.balance).to eql(1000)
end
end
describe "#account_number" do
it "returns the censored user account number" do
expect(account.acct_number).to eql("******7890")
end
end
describe "deposit!" do
context "amount > 0" do
it "returns the updated balance" do
amount = 1000
expect(account.deposit!(amount)).to eql(2000)
end
end
context "amount < 0" do
it "throws the error" do
amount = -1000
expect { account.deposit!(amount) }.to raise_error(NegativeDepositError)
end
end
end
describe "#withdraw!" do
context "amount > 0" do
it "deducts the amount from account balance" do
amount = 100
expect(account.withdraw!(amount)).to eql(900)
end
end
context "amount > balance" do
it "throws OverdraftError" do
amount = 1200
expect {account.withdraw!(amount)}.to raise_error(OverdraftError)
end
end
end
end
|
require 'rubygems'
require 'bundler'
Bundler.require
$: << settings.root
require 'sinatra'
require 'active_support/json'
require 'app/abba'
configure do
ActiveSupport.escape_html_entities_in_json = true
MongoMapper.setup({
'production' => {'uri' => ENV['MONGOHQ_URL']},
'development' => {'uri' => 'mongodb://localhost:27017/abba-development'}
}, settings.environment.to_s)
env = Sprockets::Environment.new(settings.root)
env.append_path('app/assets/javascripts')
set :sprockets, env
end
helpers do
def prevent_caching
headers['Cache-Control'] = 'no-cache, no-store'
end
def send_blank
send_file './public/blank.gif'
end
def required(*atts)
atts.each do |a|
if !params[a] || params[a].empty?
halt 406, "#{a} required"
end
end
end
end
get '/v1/abba.js', :provides => 'application/javascript' do
settings.sprockets['client/index'].to_s
end
get '/start', :provides => 'image/gif' do
required :experiment, :variant
experiment = Abba::Experiment.find_or_create_by_name(params[:experiment])
variant = experiment.variants.find_by_name(params[:variant])
variant ||= experiment.variants.create!(:name => params[:variant], :control => params[:control])
variant.start!(request) if experiment.running?
prevent_caching
send_blank
end
get '/complete', :provides => 'image/gif' do
required :experiment, :variant
experiment = Abba::Experiment.find_or_create_by_name(params[:experiment])
variant = experiment.variants.find_by_name(params[:variant])
variant.complete!(request) if variant && experiment.running?
prevent_caching
send_blank
end |
require 'docking_station'
describe DockingStation do
subject(:station) { DockingStation.new }
let(:bike) { double :bike, working?: true }
let(:broken_bike) { double :bike, working?: false, report_broken: false}
let(:van) { double :van, load: broken_bike }
describe '#release_bike' do
it 'subject responds to release_bike' do
expect(station).to respond_to(:release_bike)
end
it 'returns a Bike' do
station.dock(bike)
expect(station.release_bike).to eq(bike)
end
it 'check dock wont release broken bike' do
broken_bike.report_broken
station.dock(broken_bike)
expect{ station.release_bike }.to raise_error 'bike broken'
end
it 'raises error if no bikes in dock' do
expect { station.release_bike }.to raise_error 'No bike available'
end
end
describe '#working?' do
it 'returns true' do
expect(bike.working?).to eq(true)
end
it 'check a broken bike' do
broken_bike.report_broken
expect(broken_bike.working?).to eq(false)
end
end
describe '#dock' do
it 'docking station can dock bike' do
expect(station).to respond_to(:dock)
end
it 'docking station returns bikes' do
station.dock(bike)
expect(station.bikes[:working]).to eq([bike])
end
it 'check dock accepts broken biked' do
broken_bike.report_broken
expect(station).to respond_to(:dock)
end
it 'separates broken and working bikes in dock' do
broken_bike.report_broken
station.dock(broken_bike)
expect(station.bikes[:broken]).to include broken_bike
end
it 'raises error if dock hits capacity' do
DockingStation::DEFAULT_CAPACITY.times { station.dock(bike) }
expect { station.dock(bike) }.to raise_error 'Dock full'
end
it 'works with a variable capacity' do
station_2 = DockingStation.new(72)
72.times { station_2.dock(bike) }
expect { station_2.dock(bike) }.to raise_error 'Dock full'
end
end
describe '#load_van' do
it 'loads van' do
station.dock(broken_bike)
station.load_van
expect(van.load).to eq(broken_bike)
end
it 'removes broken bikes from docking station' do
station.dock(broken_bike)
station.load_van
expect(station.bikes[:broken]).to eq []
end
end
end
|
array = (1..99).to_a
array.each do |number|
if number.odd?
puts number
end
end |
module PgSlice
class CLI
desc "prep TABLE [COLUMN] [PERIOD]", "Create an intermediate table for partitioning"
option :partition, type: :boolean, default: true, desc: "Partition the table"
option :trigger_based, type: :boolean, default: false, desc: "Use trigger-based partitioning"
option :test_version, type: :numeric, hide: true
def prep(table, column=nil, period=nil)
table = create_table(table)
intermediate_table = table.intermediate_table
trigger_name = table.trigger_name
unless options[:partition]
abort "Usage: \"pgslice prep TABLE --no-partition\"" if column || period
abort "Can't use --trigger-based and --no-partition" if options[:trigger_based]
end
assert_table(table)
assert_no_table(intermediate_table)
if options[:partition]
abort "Usage: \"pgslice prep TABLE COLUMN PERIOD\"" if !(column && period)
abort "Column not found: #{column}" unless table.columns.include?(column)
abort "Invalid period: #{period}" unless SQL_FORMAT[period.to_sym]
end
queries = []
# version summary
# 1. trigger-based (pg9)
# 2. declarative, with indexes and foreign keys on child tables (pg10)
# 3. declarative, with indexes and foreign keys on parent table (pg11+)
version = options[:test_version] || (options[:trigger_based] ? 1 : 3)
declarative = version > 1
if declarative && options[:partition]
including = ["DEFAULTS", "CONSTRAINTS", "STORAGE", "COMMENTS", "STATISTICS"]
if server_version_num >= 120000
including << "GENERATED"
end
if server_version_num >= 140000
including << "COMPRESSION"
end
queries << <<-SQL
CREATE TABLE #{quote_table(intermediate_table)} (LIKE #{quote_table(table)} #{including.map { |v| "INCLUDING #{v}" }.join(" ")}) PARTITION BY RANGE (#{quote_ident(column)});
SQL
if version == 3
index_defs = table.index_defs
index_defs.each do |index_def|
queries << make_index_def(index_def, intermediate_table)
end
table.foreign_keys.each do |fk_def|
queries << make_fk_def(fk_def, intermediate_table)
end
end
# add comment
cast = table.column_cast(column)
queries << <<-SQL
COMMENT ON TABLE #{quote_table(intermediate_table)} IS 'column:#{column},period:#{period},cast:#{cast},version:#{version}';
SQL
else
queries << <<-SQL
CREATE TABLE #{quote_table(intermediate_table)} (LIKE #{quote_table(table)} INCLUDING ALL);
SQL
table.foreign_keys.each do |fk_def|
queries << make_fk_def(fk_def, intermediate_table)
end
end
if options[:partition] && !declarative
queries << <<-SQL
CREATE FUNCTION #{quote_ident(trigger_name)}()
RETURNS trigger AS $$
BEGIN
RAISE EXCEPTION 'Create partitions first.';
END;
$$ LANGUAGE plpgsql;
SQL
queries << <<-SQL
CREATE TRIGGER #{quote_ident(trigger_name)}
BEFORE INSERT ON #{quote_table(intermediate_table)}
FOR EACH ROW EXECUTE PROCEDURE #{quote_ident(trigger_name)}();
SQL
cast = table.column_cast(column)
queries << <<-SQL
COMMENT ON TRIGGER #{quote_ident(trigger_name)} ON #{quote_table(intermediate_table)} IS 'column:#{column},period:#{period},cast:#{cast}';
SQL
end
run_queries(queries)
end
end
end
|
# frozen_string_literal: true
module HelpScout
class Mailbox < HelpScout::Base
extend Getable
extend Listable
BASIC_ATTRIBUTES = %i[
id
name
slug
email
created_at
updated_at
].freeze
attr_reader(*BASIC_ATTRIBUTES)
attr_reader :hrefs
def initialize(params)
BASIC_ATTRIBUTES.each do |attribute|
next unless params[attribute]
instance_variable_set("@#{attribute}", params[attribute])
end
@hrefs = HelpScout::Util.map_links(params[:_links])
end
def fields
@_fields ||= HelpScout.api.get(fields_path).embedded[:fields]
end
def folders
@_folders ||= HelpScout::Folder.list(id: id)
end
private
def fields_path
hrefs[:fields]
end
end
end
|
require 'six_degrees'
describe SocialGraph do
before do
@graph = SocialGraph.new
@graph.add_interaction 'alberta', ['bob']
@graph.add_interaction 'bob', ['alberta']
@graph.add_interaction 'alberta', ['christie']
@graph.add_interaction 'christie', ['alberta', 'bob']
@graph.add_interaction 'bob', ['duncan', 'christie']
@graph.add_interaction 'duncan', ['bob']
@graph.add_interaction 'alberta', ['duncan']
@graph.add_interaction 'emily', ['duncan']
@graph.add_interaction 'duncan', ['emily']
@graph.add_interaction 'christie', ['emily']
@graph.add_interaction 'emily', ['christie']
@graph.add_interaction 'duncan', ['farid']
@graph.add_interaction 'farid', ['duncan']
end
it "should sort users" do
@graph.users.should == ["alberta", "bob", "christie", "duncan", "emily", "farid"]
end
it "should discover 1st order connections" do
@graph.connections('alberta')[0].should == ['bob', 'christie']
@graph.connections('bob')[0].should == ['alberta', 'christie', 'duncan']
@graph.connections('christie')[0].should == ['alberta', 'bob', 'emily']
@graph.connections('duncan')[0].should == ['bob', 'emily', 'farid']
@graph.connections('emily')[0].should == ['christie', 'duncan']
@graph.connections('farid')[0].should == ['duncan']
end
it "should discover 2nd order connections" do
@graph.connections('alberta')[1].should == ['duncan', 'emily']
@graph.connections('bob')[1].should == ['emily', 'farid']
@graph.connections('christie')[1].should == ['duncan']
@graph.connections('duncan')[1].should == ['alberta', 'christie']
@graph.connections('emily')[1].should == ['alberta', 'bob', 'farid']
@graph.connections('farid')[1].should == ['bob', 'emily']
end
it "should discover 3rd order connections" do
@graph.connections('alberta')[2].should == ['farid']
@graph.connections('christie')[2].should == ['farid']
@graph.connections('farid')[2].should == ['alberta', 'christie']
end
end
|
module Spree
class ProductCustomizationType < ActiveRecord::Base
include Spree::CalculatedAdjustments
has_and_belongs_to_many :products
has_many :customizable_product_options, dependent: :destroy
accepts_nested_attributes_for :customizable_product_options, allow_destroy: true
#attr_accessible :name, :presentation, :description, :customizable_product_options_attributes
validates :name, :presentation, presence: true
end
end
|
require 'discordrb'
require_relative '../commands/score_leaderboard'
require_relative '../commands/exp_leaderboard'
module LeaderboardCommands
extend Discordrb::Commands::CommandContainer
command(:leaderboard, aliases: [:lb], description: 'View player leaderboard') do |event, *args|
ScoreLeaderboard.new(event, *args).response
end
command(:exp_leaderboard, aliases: [:xp_lb], description: 'View Discord exp leaderboard') do |event, *args|
ExpLeaderboard.new(event, *args).response
end
end
|
class StockReturn < ActiveRecord::Base
validates :user_id, uniqueness: { scope: [:stock_id,:date, :sku, :asin, :goods_name, :unit_price, :number, :pay_date, :purchase_from] }
validates :unit_price, numericality: true
validates :number, numericality: {only_integer: true, greater_than_or_equal_to: 1 }
belongs_to :user
has_many :general_ledgers, dependent: :destroy
has_many :stock_ledgers, dependent: :destroy
has_one :stock_ledger_stock, through: :stock_ledgers, source: :stock
def self.to_download
headers = %w(仕入ID 日付 SKU ASIN 商品名 単価 個数 レート 小計(円貨) 支払日 購入先 通貨 総額 消費税)
csv_data = CSV.generate(headers: headers, write_headers: true, force_quotes: true) do |csv|
all.each do |row|
csv_column_values = [
row.stock_id,
row.date,
row.sku,
row.asin,
row.goods_name,
row.unit_price,
row.number,
row.rate,
row.goods_amount,
row.pay_date,
row.purchase_from,
row.currency,
row.grandtotal,
row.tax
]
csv << csv_column_values
end
end
csv_data.encode(Encoding::SJIS, :invalid => :replace, :undef => :replace, :replace => "?")
end
def self.admin_download
headers = %w(ID user_id 仕入ID 日付 SKU ASIN 商品名 単価 個数 レート 小計(円貨) 支払日 購入先 通貨 総額)
csv_data = CSV.generate(headers: headers, write_headers: true, force_quotes: true) do |csv|
all.each do |row|
csv_column_values = [
row.id,
row.user_id,
row.stock_id,
row.date,
row.sku,
row.asin,
row.goods_name,
row.unit_price,
row.number,
row.rate,
row.goods_amount,
row.pay_date,
row.purchase_from,
row.currency,
row.grandtotal,
row.tax
]
csv << csv_column_values
end
end
csv_data.encode(Encoding::SJIS, :invalid => :replace, :undef => :replace, :replace => "?")
end
end
|
class AddRoleToUsers < ActiveRecord::Migration
def change
add_column :users, :role, :integer, default: 0
end # 0 = user, 1 = admin
end
|
# Helper user in all views to check if someone is logged
module SessionsHelper
# Check if someone is logged in
#
# @return [Boolean] as true if someone is logged
def signed_in?
return current_user
end
# Check if the curentuser correspond to one user
#
# @param user [User] as user to compare at current user
# @return [Boolean] as true if given user correspond to current user
def current_user? user
user == current_user
end
# Only for the redirection in case of try to access on bad sheets
def deny_access
store_location
redirect_to signin_path, :notice => "Please login to access on this sheet."
end
end
|
module ForemanHostnameGenerator
#Inherit from the Rails module of the parent app (Foreman), not the plugin.
#Thus, inhereits from ::Rails::Engine and not from Rails::Engine
class Engine < ::Rails::Engine
#Include extenstions to models in this config.to_prepare block
config.to_prepare do
# Example: Include host extenstions
# ::Host.send :include, ForemanHostnameGenerator::HostExtensions
end
end
end
|
# == Schema Information
#
# Table name: registrations
#
# id :bigint(8) not null, primary key
# event_id :integer
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Registration < ApplicationRecord
belongs_to :user, class_name: :User, foreign_key: "user_id"
belongs_to :event, class_name: :Event, foreign_key: "event_id"
end
|
class User < ActiveRecord::Base
has_one :authorization, dependent: :destroy
has_one :preference, dependent: :destroy
has_many :tweets, dependent: :destroy
validates :name, :user_name, :user_id, :presence => true
validates :user_id, uniqueness: true
end
|
class RemoveAttemptsFromSolutions < ActiveRecord::Migration
def change
remove_column :solutions, :attempts, :integer
end
end
|
#encoding: UTF-8
class Rating
include Mongoid::Document
include Mongoid::Timestamps
field :rating, type: Integer, default: 0
field :review, type: String
field :invalid_rating, type: Boolean, default: false
belongs_to :user, class_name: "User", index: true
belongs_to :dish, class_name: "Dish", index: true
belongs_to :restaurant, class_name: "Restaurant", index: true
has_one :dishcoin, class_name: "Dishcoin", inverse_of: :rating, validate: false
after_save :cache_job
default_scope -> {ne(invalid_rating:true)}
def cache_job
self.dish.recalculate_rating
self.restaurant.cache_job
end
def serializable_hash options = {}
hash = super()
hash[:id] = self.id
return hash
end
end
|
module Hydramata
module Works
# Responsible for finding the appropriate predicate parser based on the
# input context, then calling the found parser.
#
# See lib/hydramata/works/linters.rb for the interface definition of a
# datastream parser.
module PredicateParser
module_function
def call(options = {}, &block)
parser = parser_for(options)
value = options.fetch(:value)
parser.call(value, &block)
end
def parser_for(options = {})
parser_finder = options.fetch(:parser_finder) { default_parser_finder }
parser_finder.call(options)
end
def default_parser_finder
proc do
require 'hydramata/works/predicate_parsers/simple_parser'
PredicateParsers::SimpleParser
end
end
private_class_method :default_parser_finder
end
end
end
|
describe Authenticator do
describe '.for' do
it "instantiates the matching class" do
expect(Authenticator.for(:mode => 'amazon')).to be_a(Authenticator::Amazon)
end
end
end
|
class AnimalsController < ApplicationController
def index
get_charity_info
@animals = @charity.animals
end
def show
get_charity_info
@animal = @charity.animals.find_by_name( get_animal_name )
end
def new
get_charity_info
@animal = @charity.animals.build
end
def create
get_charity_info
if is_auth
@animal = @charity.animals.create( get_animal_params )
if @animal.valid?
@animal.save!
redirect_to charity_animal_path( @charity, @animal ), flash: { overhead: "Animal saved successfully" }
else
render 'new'
end
else
redirect_to animals_path, flash: { overhead: "You are not permitted for that." }
end
end
def edit
get_charity_info
if is_auth
@animal = @charity.animals.find_by_name( get_animal_name )
else
redirect_to animals_path, flash: { overhead: "You are not permitted for that." }
end
end
def update
@charity = Charity.find_by_domain( params[ :charity_id ] )
if is_auth
@animal = @charity.animals.find_by_name( get_animal_name ).update_attributes( get_animal_params )
flash[ :overhead ] = "Successfully updated animal"
else
flash[ :overhead ] = "You are not permitted for that."
end
redirect_to charity_animals_path( @charity )
end
def destroy
@charity = Charity.find_by_domain( params[ :charity_id ] )
@animal = @charity.animals.find_by_name( get_animal_name )
if @animal.destroy
redirect_to charity_animals_path( @charity ), flash: { overhead: "Deletion successful" }
else
redirect_to charity_animal_path( @charity, @animal ), flash: { overhead: "Deletion failed" }
end
end
# adopt an animal
def adopt
get_charity_info
@animal = @charity.animals.find_by_name( params[ :animal_id ].capitalize )
unless @animal.can_adopt?
redirect_to charity_animal_path( @charity, @animal ), flash: { overhead: "This animal cannot be adopted" }
end
end
private
def is_auth
( session[ :auth ] and session[ :user_id ] == @charity.user_id )
end
def get_charity_info
@charity = Charity.find_by_domain( params[ :charity_id ] )
@pages = @charity.pages
end
def get_animal_params
params.require( :animal ).permit( :avatar, :name, :species, :breed, :can_adopt, :can_sponsor, :description, :owner_email )
end
def get_animal_name
params[ :id ].capitalize
end
end
|
# Ruby Crash Course
# classes.rb
# Created by Mauro José Pappaterra on 07 April 2017.
############################################ CLASSES
class Animal # class names begin with a Capital letter
def initialize(name, age)
# classes instance variables/attributes/fields go below
@name = name
@age = age # the @ is important to define an object variable as such
end
def name=new_name # setters method uses =
@name = new_name
end
def name #getter
@name # returns @ instance
end
def age=new_age
@age = new_age
end
def age
@age
end
def print_info # all class methods are written below
puts "#{@name} is #{@age} years old" # attributes (fields) are called using expression substitution
end
def moves (destination)
puts "#{@name} runs towards the #{destination}."
end
end
dog = Animal.new('Bobby',4)
dog.print_info
dog.moves("garden")
dog.name = "Golfo" # arguments are sent for setter's methods using =
dog.age = 2
dog.print_info
dog.moves("food bowl") # arguments for other methods use conventional way ()
bird = Animal.new("Polly",1)
bird.print_info
bird.moves("tree")
class Book
attr_writer :title # creates only setter and instance @title
attr_reader :author # creates only getter and instance @author
attr_accessor :year # creates both getter and setter and instance @year
# :name defines a symbol in ruby
def initialize (title = "", author = "", year = "") # constructor method, notice default values!
@title = title
@author = author
@year = year
end
def title # @title getter must be defined manually
@title
end
def author=new_author # @author setter must be defined manually
@author = new_author
end
# both getter and setter for @ have been defined on line 58
# use this wisely, this shortcute is not useful when encapsulation is needed
def print_info
puts "'#{@title}' was written by #{@author} in the year #{@year}."
end
end
book_1 = Book.new
book_1.title = "A Hundred Years of Solitude"
book_1.author = "Gabriel Garcia Marquez"
book_1.year = 1967
book_2 = Book.new("Dracula","Bram Stoker", 1897) # initialize method let us do this
book_3 = Book.new("L'Etranger", "Alber Camos",1942)
book_3.title = "The Stranger"
book_3.author = "Albert Camus"
book_1.print_info
book_2.print_info
book_3.print_info
############################################ INHERITANCE
class Vehicle # a superclass is no different from a regular class
attr_accessor :type, :model, :make, :year, :capacity
def initialize (type="",model="",make="",year="",capacity=1)
@type = type
@model = model
@make = make
@year = year
@capacity = capacity
end
def start
puts "#{@make} #{@model} starting the engine..."
end
def speed_up
puts "#{@make} #{@model} stepping on gas pedal"
end
def steer (direction)
puts "#{@make} #{@model} steering the wheel to the #{direction}"
end
def break
puts "#{@make} #{@model} stepping on brake pedal"
end
def print_info
plural = "people"
if capacity == 1
plural = "person"
end
puts "\nThis #{@type} is a #{@model} made by #{@make}. It first appeared on #{@year} and has capacity for #{@capacity} #{plural}"
end
end
class Car < Vehicle # a subclass inherits from a superclass (child < parent)
def initialize (model="",make="",year="",capacity=2) # overrides existing method in superclass
@type = "car"
@model = model
@make = make # assign values directly to object variables, ok but not recommended!
@year = year
@capacity = capacity
end
end
class Bus < Vehicle
def initialize (model="",make="",year="",capacity=15) # overrides existing method in superclass
self.type = "bus"
self.model = model
self.make = make # calling the setters inside the class to itself
self.year = year # better option when encapsulation is necessary!
self.capacity = capacity
end
end
class Lorry < Vehicle
def initialize (model="",make="",year="",capacity=2) # overrides existing method in superclass
super("lorry", model, make, year, capacity) # super sends to initialize in superclass with giver parameters, again little encapsulation here!
end
end
class Bicycle < Vehicle
def initialize (model="",make="",year="") # notice the reduction of parameters for the constructor of the subclass Bicycles
@type = "bicycle"
@model = model
@make = make
@year = year
@capacity = 1 # this is the only capacity possible for bicycles
end
def start # overrides existing method in superclass
puts "#{@make} #{@model} starting to pedal..."
end
def speed_up # overrides existing method in superclass
puts "#{@make} #{@model} pedalling full tilt"
end
def steer (direction) # overrides existing method in superclass
puts "#{@make} #{@model} steering the bicycle to the #{direction}"
end
def break # overrides existing method in superclass
puts "#{@make} #{@model} pressing the breaks"
end
def print_info # overrides existing method in superclass BUT
super # super does exactly as the original method
puts "Bicycles are also a much more ecological vehicle!" # but new code is added here!
end
end
car_01 = Car.new
car_01.model = "Corolla"
car_01.make = "Toyota"
car_01.year = 2010
car_01.capacity = 5
car_02 = Car.new("Gallardo","Lamborghini",2014,4)
car_03 = Car.new("600","Fiat",1984,3)
car_01.print_info
car_01.speed_up
car_01.steer("rigth")
car_01.break
car_02.print_info
car_02.speed_up
car_02.steer("left")
car_02.break
car_03.print_info
car_03.speed_up
car_03.steer("left")
car_03.break
bicycle_01 = Bicycle.new("V256", "Mountain Bike", 2007)
bicycle_02 = Bicycle.new("xTreme 2004", "Volt", 2004)
bicycle_03 = Bicycle.new("xxx", "Adventurer", 2016)
bicycle_01.print_info
bicycle_01.speed_up
bicycle_01.steer("left")
bicycle_01.break
bicycle_01.print_info
bicycle_02.speed_up
bicycle_02.steer("left")
bicycle_02.break
bicycle_01.print_info
bicycle_03.speed_up
bicycle_03.steer("left")
bicycle_03.break
bus_01 = Bus.new("Schoolie","Mercedes Benz", 2000, 25)
lorry_01 = Lorry.new("FX3500", "Scania", 2015)
bus_01.print_info
lorry_01.print_info |
describe Travis::Config::Heroku, :Database do
let(:config) { Travis::Test::Config.load(:heroku) }
let(:vars) { %w(DATABASE_URL DB_POOL DATABASE_POOL_SIZE LOGS_DATABASE_URL LOGS_DB_POOL LOGS_DATABASE_POOL_SIZE) }
after { vars.each { |key| ENV.delete(key) } }
it 'loads a DATABASE_URL with a port' do
ENV['DATABASE_URL'] = 'postgres://username:password@hostname:1234/database'
expect(config.database.to_h).to eq(
adapter: 'postgresql',
host: 'hostname',
port: 1234,
database: 'database',
username: 'username',
password: 'password',
encoding: 'unicode'
)
end
it 'loads a DATABASE_URL without a port' do
ENV['DATABASE_URL'] = 'postgres://username:password@hostname/database'
expect(config.database.to_h).to eq(
adapter: 'postgresql',
host: 'hostname',
database: 'database',
username: 'username',
password: 'password',
encoding: 'unicode'
)
end
it 'loads DB_POOL' do
ENV['DATABASE_URL'] = 'postgres://username:password@hostname:1234/database'
ENV['DB_POOL'] = '25'
expect(config.database.to_h).to eq(
adapter: 'postgresql',
host: 'hostname',
port: 1234,
database: 'database',
username: 'username',
password: 'password',
encoding: 'unicode',
pool: 25
)
end
it 'loads DATABASE_POOL_SIZE' do
ENV['DATABASE_URL'] = 'postgres://username:password@hostname:1234/database'
ENV['DATABASE_POOL_SIZE'] = '25'
expect(config.database.to_h).to eq(
adapter: 'postgresql',
host: 'hostname',
port: 1234,
database: 'database',
username: 'username',
password: 'password',
encoding: 'unicode',
pool: 25
)
end
it 'loads a LOGS_DATABASE_URL with a port' do
ENV['LOGS_DATABASE_URL'] = 'postgres://username:password@hostname:1234/logs_database'
expect(config.logs_database.to_h).to eq(
adapter: 'postgresql',
host: 'hostname',
port: 1234,
database: 'logs_database',
username: 'username',
password: 'password',
encoding: 'unicode'
)
end
it 'loads a LOGS_DATABASE_URL without a port' do
ENV['LOGS_DATABASE_URL'] = 'postgres://username:password@hostname/logs_database'
expect(config.logs_database.to_h).to eq(
adapter: 'postgresql',
host: 'hostname',
database: 'logs_database',
username: 'username',
password: 'password',
encoding: 'unicode'
)
end
it 'loads LOGS_DB_POOL' do
ENV['LOGS_DATABASE_URL'] = 'postgres://username:password@hostname:1234/logs_database'
ENV['LOGS_DB_POOL'] = '25'
expect(config.logs_database.to_h).to eq(
adapter: 'postgresql',
host: 'hostname',
port: 1234,
database: 'logs_database',
username: 'username',
password: 'password',
encoding: 'unicode',
pool: 25
)
end
it 'loads LOGS_DATABASE_POOL_SIZE' do
ENV['LOGS_DATABASE_URL'] = 'postgres://username:password@hostname:1234/logs_database'
ENV['LOGS_DATABASE_POOL_SIZE'] = '25'
expect(config.logs_database.to_h).to eq(
adapter: 'postgresql',
host: 'hostname',
port: 1234,
database: 'logs_database',
username: 'username',
password: 'password',
encoding: 'unicode',
pool: 25
)
end
it 'sets logs_database to nil if no logs db url given' do
expect(config.logs_database).to be_nil
end
end
|
class TimeTable
YEAR = 1
MONTH = 1
DAY = 1
def self.parse_time(str)
Time.local(YEAR, MONTH, DAY, *(str.split(':')))
end
START_TIME = parse_time('10:00')
NOON_BREAK_TIME = parse_time('12:00')
SEC_BREAK = 10 * 60
SEC_LUNCH_BREAK = 60 * 60
def initialize(names_and_minutes)
@names_and_minutes = names_and_minutes.map do |name_and_minute|
name, minute = name_and_minute.chomp.split
[name, minute.to_i]
end
end
def create
t = START_TIME
is_lunch_break_yet_to_take = true
@names_and_minutes.each_with_index do |name_and_minute, index|
name, minute = name_and_minute
next_minute = 0
next_minute = @names_and_minutes[index + 1][1] if index < @names_and_minutes.size - 1
start_time = t
end_time = t + minute * 60
min_break = \
if end_time + SEC_BREAK + next_minute * 60 > NOON_BREAK_TIME && is_lunch_break_yet_to_take
is_lunch_break_yet_to_take = false
SEC_LUNCH_BREAK
else
SEC_BREAK
end
puts "#{format_time(start_time)} - #{format_time(end_time)} #{name}"
t = end_time + min_break
end
end
private
def format_time(time)
time.strftime('%H:%M')
end
end
if __FILE__ == $0
num_entries = gets.to_i
names_and_minutes = Array.new(num_entries)
num_entries.times do |i|
names_and_minutes[i] = gets.chomp
end
tt = TimeTable.new(names_and_minutes)
tt.create
end
|
module RemoteService
module Errors
class ConnectionFailedError < StandardError; end
class RemoteCallError < StandardError
attr_accessor :name, :message, :backtrace
def initialize(name, message, backtrace)
@name = name
@message = message
@backtrace = backtrace
end
end
end
end |
# encoding: UTF-8
require 'debugger'
require 'colorize'
class Checkers
def initialize
@board = Board.new
end
def play
puts "Welcome to Rashi's Rocking Checkers Game"
puts
puts "Para espanol, oprima el dos"
puts "Too late."
loop do
puts @board
begin
from_pt = ask_for_pts("Where from? enter an ordered pair, ex: 07")
to_pts = ask_for_pts(\
"Where to? Enter as many moves as you like, separated by spaces")
@board[*from_pt[0]].perform_moves(to_pts)
rescue RuntimeError => e
puts "Error: #{e.message}"
retry
end
end
end
def ask_for_pts(prompt_str)
print "#{prompt_str} "
gets.split.map{ |str| str.match(/\D*(\d)\D*(\d)\D*/)[1..2].map(&:to_i) }
raise ""
end
end
class Board
include Enumerable
def initialize
@board = Array.new(8) { Array.new(8) { nil } }
setup_pieces
end
def [](x, y)
@board[y][x]
end
def []=(x, y, piece)
@board[y][x] = piece
end
def to_s
res = ""
res << " " + (0..7).to_a * " " + "\n"
@board.each_with_index do |row, idx|
res << "#{idx} " << row_to_s(row) * " | "\
<< "\n--------------------------------\n"
end
res << "\n"
end
def row_to_s (row)
row.map do |cell|
cell ? cell : " "
end
end
def dup
b = Board.new
@board.each do |row|
row.each do |cell|
Piece.new(cell.location, b, cell.color) if cell
nil if !cell
end
end
b
end
def each
@board.each do |row|
row.each do |cell|
yield(cell)
end
end
end
def jump_pos_available?
self.any? do |item|
(item) ? item.jump_pos_available? : false
end
end
private
def setup_pieces
4.times do |col|
2.times do |row|
Piece.new([col * 2 + 1, row * 2], self, :red)
Piece.new([col * 2, 7 - (row * 2)], self, :black)
end
Piece.new([col * 2 + 1, 6], self, :black)
Piece.new([col * 2, 1], self, :red)
end
end
end
class Piece
attr_accessor :king
attr_reader :color, :location
def initialize(location, board, color)
@king = false
@board = board
@color = color
self.location = location
end
def to_s
case @color
when :red
"⬤".red
when :black
"⬤".black
else
raise "Invalid color in @color in Piece"
end
end
def slide_moves
if @king
new_locs([[-1, 1], [1, 1]] + [[-1, -1], [1, -1]], @location)
else
case @color
when :red
# when red move down board
# check spots up and left and up and right
new_locs([[-1, 1], [1, 1]], @location)
when :black
new_locs([[-1, -1], [1, -1]], @location)
else
raise "@color has invalid color"
end
end
end
def jump_moves
if @king
new_locs([[-2, 2], [2, 2]] + [[-2, -2], [2, -2]], @location)
else
case @color
when :red
# when red move down board
# check spots up and left and up and right
new_locs([[-2, 2], [2, 2]], @location)
when :black
new_locs([[-2, -2], [2, -2]], @location)
else
raise "@color has invalid color"
end
end
end
def perform_slide(new_pos)
possible_moves = slide_moves
raise InvalidMoveError.new("Not a valid move.")\
unless possible_moves.include?(new_pos)
self.location = new_pos
check_king
end
def perform_jump(new_pos)
possible_moves = jump_moves
#check_pos calculates the position between the possible jump place
check_pos = \
[(new_pos.first - @location.first) / 2 + @location.first,\
(new_pos.last - @location.last) / 2 + @location.last]
raise InvalidMoveError.new("Not a valid move.")\
unless possible_moves.include?(new_pos) && @board[*check_pos]
@board[*check_pos] = nil
self.location = new_pos
check_king
end
def check_king
if (@color == :black && @location.last == 0) || \
(@color == :white && @location.last == 7)
@king = true
end
end
def perform_moves(move_seq)
if valid_move_seq?(move_seq)
perform_moves!(move_seq)
else
raise InvalidMoveError.new("Not even close to a valid move.")
end
end
def jump_pos_available?
possible_moves = jump_moves
# debugger if possible_moves.length > 0
possible_moves.map! do |move|
check_pos = \
[(move.first - @location.first) / 2 + @location.first,\
(move.last - @location.last) / 2 + @location.last]
if @board[*check_pos] && @board[*check_pos].color != @color
move
else
nil
end
end
debugger if possible_moves.compact.length > 0
possible_moves.compact.length > 0
end
protected
def perform_moves!(move_sequence)
move_sequence.each do |move|
unless @board.jump_pos_available?
begin
perform_slide(move)
rescue InvalidMoveError
perform_jump(move)
end
else
perform_jump(move)
end
end
end
private
def valid_move_seq?(move_sequence)
duped_board = @board.dup
begin
duped_board[*@location].perform_moves!(move_sequence)
rescue InvalidMoveError
return false
else
return true
end
end
def new_locs(relative_moves, position)
return relative_moves.map do |rel_move|
rel_move.map.with_index { |itm, idx| @location[idx] + itm }
end.select do |itm|
itm.all? { |loc| loc >= 0 && loc < 8 } &&
@board[*itm].nil?
end
end
def location=(loc)
@location && @board[*@location] = nil
@board[*loc] = self
@location = loc
end
end
class InvalidMoveError < RuntimeError
end
if __FILE__ == $PROGRAM_NAME
Checkers.new.play
end
|
class Tempuser < ActiveRecord::Base
has_many :comments
before_create { generate_token(:auth_token) }
def generate_token(column)
begin
self[column] = SecureRandom.urlsafe_base64
end while Tempuser.exists?(column => self[column])
end
def like?(something)
something.score.liker.include? pku_id
end
def like(something)
@score = something.score
@score.liker += [pku_id]
@score.liker.uniq!
@score.score = @score.generate_score
@score.save
end
def unlike(something)
@score = something.score
@score.liker -= [pku_id]
@score.liker.uniq!
@score.score = @score.generate_score
@score.save
end
end
|
require 'bundler'
begin
Bundler.setup(:default, :development)
rescue Bundler::BundlerError => e
$stderr.puts e.message
$stderr.puts "Run `bundle install` to install missing gems"
exit e.status_code
end
require 'rake/rdoctask'
require 'rake/testtask'
$LOAD_PATH.unshift('lib')
require 'css'
desc 'Run code coverage'
task :coverage do |t|
puts `rcov -T #{Dir.glob('spec/**/*_spec.rb').join(' ')}`
end
desc 'Generate documentation.'
Rake::RDocTask.new(:rdoc) do |rdoc|
rdoc.rdoc_dir = 'doc'
rdoc.title = 'AWSum'
rdoc.options << '--line-numbers' << '--inline-source'
rdoc.rdoc_files.include('README*')
rdoc.rdoc_files.include('lib/**/*.rb')
end
desc 'Clean up files.'
task :clean do |t|
FileUtils.rm_rf "doc"
FileUtils.rm_rf "tmp"
FileUtils.rm_rf "pkg"
end
require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new do |t|
t.pattern = "./spec/**/*_spec.rb"
end
|
#Developer: Marius
#one company got many departments and if you delete the company, you delete the dependencies as well
class Company < ActiveRecord::Base
# === Associations ===
has_many :departments, dependent: :destroy
has_many :employees, through: :departments
#a company must have a name
# === Validations ===
validates :name, presence: true
end
|
class Todo < ActiveRecord::Base
default_scope { order('created_at DESC') }
attr_accessible :title, :duration
belongs_to :user
validates :title, presence: true
validates :duration, presence: true
end
|
#!/usr/bin/env ruby
#
# Sensu Twitter Handler
# ===
#
# This handler reports alerts to a configured twitter handler.
# Map a twitter handle to a sensusub value in the twitter.json to get going!
# sensusub == subscription in the client object, not check..
# see twitter.json for required values
#
# Copyright 2011 Joe Crim <josephcrim@gmail.com>
#
# Released under the same terms as Sensu (the MIT license); see LICENSE
# for details.
require 'rubygems' if RUBY_VERSION < '1.9.0'
require 'sensu-handler'
require 'twitter'
class TwitterHandler < Sensu::Handler
def event_name
@event['client']['name'] + '/' + @event['check']['name']
end
def handle
# #YELLOW
twitter_clients.each do |client|
if @event['action'].eql?('resolve')
client.update("RESOLVED - #{event_name}: #{@event['check']['notification']} Time: #{Time.now} ")
else
client.update("ALERT - #{event_name}: #{@event['check']['notification']} Time: #{Time.now} ")
end
end
end
private
def twitter_clients
@twitter_clients ||= settings['twitter'].map do |account|
next unless @event['client']['subscriptions'].include?(account[1]['sensusub'])
Twitter::REST::Client.new do |config|
config.consumer_key = account[1]['consumer_key']
config.consumer_secret = account[1]['consumer_secret']
config.access_token = account[1]['oauth_token']
config.access_token_secret = account[1]['oauth_token_secret']
end
end.compact
end
end
|
require 'spec_helper'
describe ShareActiveRecordModels::ExpensiveProduct, type: :model do
let!(:product) { create(:product, price: 101, name: 'so expensive') }
describe 'expensive products' do
it 'returns expensive ones!' do
described_class.refresh
expect(described_class.all).not_to be_empty
end
end
end
|
# frozen_string_literal: true
require 'test_helper'
class ArticlesControllerTest < ActionDispatch::IntegrationTest
setup do
@article = articles(:one)
end
test 'should get index' do
get articles_path
assert_response :success
end
test 'should new article' do
get new_article_path, params: { article: { body: 'Rails is awesome!', title: 'Hello Rails' } },
headers: { Authorization: ActionController::HttpAuthentication::Basic.encode_credentials('dhh', 'secret') }
assert_response :success
end
test 'should get show' do
get articles_path(@article.id)
assert_response :success
end
test 'should get edit' do
get edit_article_path(@article.id),
headers: { Authorization: ActionController::HttpAuthentication::Basic.encode_credentials('dhh', 'secret') }
assert_response :success
end
test 'should create article' do
post articles_path, params: { article: { body: 'Rails is awesome!', title: 'Hello Rails' } },
headers: { Authorization: ActionController::HttpAuthentication::Basic.encode_credentials('dhh', 'secret') }
new_article = Article.find_by title: 'Hello Rails'
assert new_article.present?
end
test 'should update article' do
patch article_path(@article.id), params: { article: { body: 'Rails is do awesome!', title: 'Hello Rails also' } },
headers: { Authorization: ActionController::HttpAuthentication::Basic.encode_credentials('dhh', 'secret') }
@article.reload
assert @article.title.eql?('Hello Rails also')
end
test 'should destroy article' do
delete article_path(@article.id),
headers: { Authorization: ActionController::HttpAuthentication::Basic.encode_credentials('dhh', 'secret') }
assert !Article.exists?(id: @article.id)
end
end
|
module LDAPAuthentication
extend ActiveSupport::Concern
protected
def update_resource(resource, params)
if ENV['ldap.on'].eql?('true') && authenticate(params[:current_password])
params.delete(:current_password)
resource.update_without_password(params)
else
super
end
end
private
def authenticate(pwd)
require './lib/ldap/ldap_authentication'
user = if resource_name == :academic
"a#{current_academic.ra}"
else
current_professor.username
end
base = resource_name.to_s.pluralize
return false unless SGTCC::LDAP.authenticate(user, pwd, base)
true
end
end
|
class Pin < ActiveRecord::Base
acts_as_votable
belongs_to :user
has_attached_file :image, styles: { medium: "300x300" }
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
# Search Functionality
def self.search(query)
# where(:title, query) Would return an exact match, when we just want like-matches.
where("title like ?", "%#{query}%")
end
end
|
class StubVhost < OpenStruct; end
Fabricator(:vhost, from: :stub_vhost) do
virtual_domain 'domain1'
external_host 'host1'
service
after_create { |vhost| vhost.service.vhosts << vhost }
end
|
class ChallengesController < ApplicationController
before_action :set_challenge, only: [:show]
before_action :new_audio_quiz_answer, only: [:show]
before_action :new_pub_quiz_answer, only: [:show]
def show
if @challenge.accessible?
render @challenge.route
else
redirect_to root_path
end
end
private
def set_challenge
@challenge ||= ChallengeService.new(params[:id].to_i)
end
def new_audio_quiz_answer()
@audio_quiz_answer = AudioQuizAnswer.new if @challenge.day_of_month === 6
end
def new_pub_quiz_answer()
@pub_quiz_answer = PubQuizAnswer.new if @challenge.day_of_month === 23
end
end
|
class UnitsController < ApplicationController
before_action :authenticate_user!
before_action :find_location
before_action :find_unit, only: [:show, :edit, :update, :destroy]
def index
@units = Unit.all
@locations = Location.all
end
def show
end
def new
@unit = Unit.new
end
def create
@unit = @location.units.create unit_params
if @unit.save == true
redirect_to location_path(@location)
else
render :new
end
end
def edit
end
def update
@unit.update_attributes unit_params
redirect_to location_path(@location)
end
def destroy
@unit.delete
redirect_to location_path(@location)
end
private
def unit_params
params.require(:unit).permit(:name, :date)
end
def find_location
@location = Location.find params[:location_id]
end
def find_unit
@unit = Unit.find params[:id]
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
config.vm.define "vbu" do |vbu|
vbu.vm.box = "bento/ubuntu-18.04"
vbu.vm.network "private_network", ip: "192.168.10.10"
vbu.vm.box_check_update = false
vbu.vm.network "forwarded_port", guest: 8080, host: 8888
vbu.vm.synced_folder ".", "/vbu_mac"
vbu.vm.provider "virtualbox" do |vb|
vb.customize ["modifyvm", :id, "--name", "vbu-test1"]
vb.memory = "1024"
end
vbu.vm.provision "shell", inline: <<-SHELL
sudo apt-get update -y
sudo apt-get install software-properties-common -y
sudo apt-add-repository --yes ppa:ansible/ansible -y
sudo apt-get install ansible -y
cd /vbu_mac
ansible-playbook playbook.yml
SHELL
end
end
|
require 'rails_helper'
describe User do
describe "validations" do
it { is_expected.to have_many(:company_users) }
end
end
|
class AddColumnsToUserProfile < ActiveRecord::Migration
def change
add_column :user_profiles, :offer_category_1, :integer
add_column :user_profiles, :offer_category_2, :integer
add_column :user_profiles, :offer_category_3, :integer
add_column :user_profiles, :suggestion_category_1, :integer
add_column :user_profiles, :suggestion_category_2, :integer
add_column :user_profiles, :suggestion_category_3, :integer
add_column :user_profiles, :you_deserve_it_category, :integer
add_column :user_profiles, :repeat_experiences, :boolean, :default => false
add_column :user_profiles, :lifestyle_on_sidekick, :boolean, :default => false
add_column :user_profiles, :shopping_on_sidekick, :boolean, :default => false
add_column :user_profiles, :food_on_sidekick, :boolean, :default => false
add_column :user_profiles, :business_on_sidekick, :boolean, :default => false
add_column :user_profiles, :travel_on_sidekick, :boolean, :default => false
add_column :user_profiles, :friends_on_sidekick, :boolean, :default => false
add_column :user_profiles, :question_1, :string
add_column :user_profiles, :question_2, :string
add_column :user_profiles, :question_3, :string
add_column :user_profiles, :question_4, :string
add_column :user_profiles, :question_5, :string
add_column :user_profiles, :landing_page_id, :integer
end
end |
# :nodoc:
class Car
include Producer
attr_reader :free_space, :size, :filled_space
def initialize(size = nil)
@size = size || default_size
@free_space = size
post_initialize
end
def filled_space
@size - @free_space
end
protected
def default_size
raise NotImplementedError unless defined? DEFAULT_SIZE
DEFAULT_SIZE
end
def post_initialize
nil
end
end
|
Rails.application.routes.draw do
root 'welcome#index'
get '/terms' => 'terms#terms'
get '/about' => 'about#about'
get '/faq' => 'common_questions#common_questions'
get '/sign-up' => 'registrations#new', as: :signup
post '/sign-up' => 'registrations#create'
get '/sign-in' => 'authentication#new', as: :signin
post '/sign-in' => 'authentication#create'
get '/sign-out' => 'authentication#destroy', as: :signout
#get "/tasks" => "tasks#tasks"
# resources :tracker_stories, only: [:show, :index]
get '/tracker_stories/:project_id' => 'projects#tracker_stories', as: :tracker_stories
# resources :tracker_stories, only: [:index, :show]
resources :users
resources :projects do
resources :memberships
resources :tasks do
resources :comments, only: [:create]
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.