text stringlengths 10 2.61M |
|---|
#!/usr/bin/env ruby
#
# 10001st prime
# http://projecteuler.net/problem=7
#
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that
# the 6th prime is 13.
#
# What is the 10,001st prime number?
#
class Numeric
def prime?
return true if self == 2
return false if self <= 1 or self % 2 == 0
(3..Float::INFINITY).step(2) do |x|
return true if x**2 > self
return false if self % x == 0
end
end
end
def prime_index_of(n)
(7..Float::INFINITY).step(2).inject(3) do |sum, x|
return x.to_i-2 if sum == n
sum + (x.to_i.prime? ? 1 : 0)
end
end
p prime_index_of(10001)
# => 104743
|
class Gui < GuiElement
attr_accessor :menu, :shown
def initialize player
super()
@player = player
#we don't need all the space left and right
self.sx = 3/8
self.center
# add a vertical menu as a child to self
@menu = GuiMenuV.new
self << @menu
# some content
@menu << GuiButton.new
@menu << GuiButton.new
@menu << GuiButton.new
@menu.vp_align_span
# -> Gui[MenuV].control_hook
player.control << self
player.control << @menu
# other parameters
@player = player
@shown = false
@cross_id = player.sprite "std", "cross"
@pointer_timeout = 0
@pointer_x,@pointer_y = 0.5,0.5
end
def draw_impl
self.fill_rect 0,0,1,1, 200,180,160
dm = -10
self.decorate dm,dm,dm,dm, 255,0,0, 5
end
def draw
super #draw children, then paint over them
if @player.frame_counter < @pointer_timeout
graphics.draw_sprite_frac_c @cross_id, @pointer_x,@pointer_y,100,100
end
end
def control_hook ci_t, ci_v
super
# as the root of the menu tree, work with these cases:
if ci_t==CiType::PRESS && ci_v==CiButton::ESCAPE
self.shown = !self.shown
self.each_element proc { |e|
e.focussed = false
}
#give focus to @menu, or remove it all together
@menu.focussed = self.shown
end
if ci_t == CiType::MOUSE && self.shown
@pointer_timeout = @player.frame_counter+12
@pointer_x = ci_v[0]
@pointer_y = ci_v[1]
end
end
def graphics
@player.graphics
end
end
|
require_relative '../lib/strategy'
class Upczilla < Strategy
def scrape(code)
begin
description = image_url = ''
valid = false
url = "https://www.upczilla.com/item/#{code}/"
html = HTTParty.get(url, :verify => false)
doc = Nokogiri::HTML(html)
description = doc.css('.producttitle').text
unless description.empty?
item_featured = doc.css('.item.featured')
imgdiv = item_featured.css('.imgdiv')
imgs = imgdiv.css('img')
img = imgs[0]
image_url = img.attributes['src'].value
valid = true;
end
rescue => error
p "ERROR "*5
p url
p error
pp error.backtrace
end
ret = {code:code, valid:valid, description: description, image_url: image_url,provider: File.basename(__FILE__)}
return ret
end
end
|
# frozen_string_literal: true
module Auths
module Error
class Forbidden < AuthError
def http_status
:forbidden
end
end
end
end
|
Gem::Specification.new do |s|
s.name = %q{todo_api}
s.version = "0.0.1"
s.date = %q{2018-10-13}
s.summary = %q{CLI to interact with the todo app api}
s.files = [
"lib/todo_api.rb"
]
s.require_paths = ["lib"]
s.authors = ['Eduardo Poleo']
end |
module TruncateHtmlHelper
def truncate_html(html, options={})
return '' if html.nil?
html_string = TruncateHtml::HtmlString.new(html)
TruncateHtml::HtmlTruncator.new(html_string).truncate(options).html_safe
end
def count_html(html)
return 0 if html.nil?
html_string = TruncateHtml::HtmlString.new(html)
TruncateHtml::HtmlCounter.new(html_string).count
end
end
|
class Shows < ActiveRecord::Migration
def self.up
create_table :shows do |t|
t.integer :theater_id
t.integer :movie_id
t.datetime :start
end
end
def self.down
drop_table :shows
end
end
|
# return any unique integer in an array that contains integers
# between 1 and n and has a length n + 1. The array cannot be
# copied or manipulated.
# run time O(n * log(n))
# memory O(n)
def find_duplicate(array, min=1, max=nil)
max = max || array.length - 1
# if the max and min have a difference of one, return whichever is the duplicate
if max - min == 1
min_count = array.inject(0) { |count, int| int == min ? count + 1 : count }
min_count > 1 ? ( return min ) : ( return max )
end
# count all the integers in the array in range min to max / 2
ints_in_range_count = 0
array.each do |int|
if int >= min && int <= max / 2
ints_in_range_count += 1
end
end
# find the number of possible unique integers in that range
possible_unique_ints = max / 2 - min + 1
if ints_in_range_count > possible_unique_ints
# there's a duplicate in the range min to max / 2
find_duplicate(array, min, max / 2)
else
# there's a duplicate in the range max / 2 + 1 to max
find_duplicate(array, max / 2 + 1, max)
end
end |
require 'rails_helper'
RSpec.describe "Api::Readers", type: :request do
describe "GET /api/readers" do
it "should list all readers" do
FactoryBot.create(:reader)
get api_readers_path
expect(response).to have_http_status(200)
json = JSON.parse(response.body)
expect(json.length).to eq 1
expect(json[0]["name"]).to eq('Reader 1')
end
end
describe "GET /api/readers/:id" do
before(:each) do
@reader = FactoryBot.create :reader
end
it "should get a reader by id" do
get api_reader_path(@reader.id)
expect(response).to have_http_status(200)
json = JSON.parse(response.body)
expect(json["name"]).to eq('Reader 1')
expect(json["email"]).to eq('reader1@mail.com')
end
end
describe "POST /api/readers/" do
before(:each) do
@reader = FactoryBot.build :reader
end
it "should create a reader" do
post api_readers_path, params: {
reader: {
name: @reader.name,
email: @reader.email
}
}
expect(response).to have_http_status(201)
json = JSON.parse(response.body)
expect(json["name"]).to eq('Reader 1')
end
end
describe "PUT /api/readers/:id" do
before(:each) do
@reader = FactoryBot.create :reader
end
it "should update a reader" do
put api_reader_path(@reader.id), params: {
reader: {
name: 'Reader 1 updated'
}
}
expect(response).to have_http_status(200)
json = JSON.parse(response.body)
expect(json["name"]).to eq('Reader 1 updated')
end
end
describe "DELETE /api/readers/:id" do
before(:each) do
@reader = FactoryBot.create :reader
end
it "should delete a reader" do
delete api_reader_path(@reader.id)
expect(response).to have_http_status(204)
end
end
end
|
module Bramipsum
class Paragraph < Sentence
def self.paragraph
self.sentences(5).join(" ")
end
def self.html_paragraph
"<p>" << self.paragraph << "</p>"
end
end
end
|
require 'spec_helper'
describe HomeController do
let(:user) { FactoryGirl.build(:user) }
context 'user is logged in' do
it 'forwards user to dashboard' do
pending 'to be added'
end
end
end
|
class SmsService
def initialize(delivery)
@delivery = delivery
end
def deliver_to(clients)
clients.each { |client| send_sms_to(client) }
end
private
def send_sms_to(client)
twilio_client = Twilio::REST::Client.new(TWILIO_CONFIG['sid'], TWILIO_CONFIG['token'])
twilio_client.account.sms.messages.create(
from: TWILIO_CONFIG['from'],
to: client.phone,
body: @delivery.message_text
)
end
end |
class CreateApplicationsGroups < ActiveRecord::Migration
def change
create_table :applications_groups, :id => false do |t|
t.integer :application_id
t.integer :group_id
end
end
end
|
# frozen_string_literal: true
# rubocop:todo all
require 'spec_helper'
describe 'Command monitoring' do
let(:subscriber) { Mrss::EventSubscriber.new }
let(:client) do
authorized_client.with(app_name: 'command monitoring spec').tap do |client|
client.subscribe(Mongo::Monitoring::COMMAND, subscriber)
end
end
context 'pre 3.6 servers' do
max_server_fcv '3.5'
it 'notifies on successful commands' do
result = client.database.command('ismaster' => 1)
expect(result.documents.first['ismaster']).to be true
started_events = subscriber.started_events.select do |event|
event.command_name == 'ismaster'
end
expect(started_events.length).to eql(1)
started_event = started_events.first
expect(started_event.command_name).to eql('ismaster')
expect(started_event.address).to be_a(Mongo::Address)
expect(started_event.command).to have_key('$db')
succeeded_events = subscriber.succeeded_events.select do |event|
event.command_name == 'ismaster'
end
expect(succeeded_events.length).to eql(1)
succeeded_event = succeeded_events.first
expect(succeeded_event.command_name).to eql('ismaster')
expect(succeeded_event.reply).to be_a(BSON::Document)
expect(succeeded_event.reply['ismaster']).to eql(true)
expect(succeeded_event.reply['ok']).to eq(1)
expect(succeeded_event.address).to be_a(Mongo::Address)
expect(succeeded_event.duration).to be_a(Float)
expect(subscriber.failed_events.length).to eql(0)
end
end
context '3.6+ servers' do
min_server_fcv '3.6'
it 'notifies on successful commands' do
result = client.database.command(hello: 1)
expect(result.documents.first['isWritablePrimary']).to be true
started_events = subscriber.started_events.select do |event|
event.command_name == 'hello'
end
expect(started_events.length).to eql(1)
started_event = started_events.first
expect(started_event.command_name).to eql('hello')
expect(started_event.address).to be_a(Mongo::Address)
expect(started_event.command).to have_key('$db')
succeeded_events = subscriber.succeeded_events.select do |event|
event.command_name == 'hello'
end
expect(succeeded_events.length).to eql(1)
succeeded_event = succeeded_events.first
expect(succeeded_event.command_name).to eql('hello')
expect(succeeded_event.reply).to be_a(BSON::Document)
expect(succeeded_event.reply['isWritablePrimary']).to eql(true)
expect(succeeded_event.reply['ok']).to eq(1)
expect(succeeded_event.address).to be_a(Mongo::Address)
expect(succeeded_event.duration).to be_a(Float)
expect(subscriber.failed_events.length).to eql(0)
end
end
it 'notifies on failed commands' do
expect do
result = client.database.command(:bogus => 1)
end.to raise_error(Mongo::Error::OperationFailure, /no such c(om)?m(an)?d/)
started_events = subscriber.started_events.select do |event|
event.command_name == 'bogus'
end
expect(started_events.length).to eql(1)
started_event = started_events.first
expect(started_event.command_name).to eql('bogus')
expect(started_event.address).to be_a(Mongo::Address)
succeeded_events = subscriber.succeeded_events.select do |event|
event.command_name == 'hello'
end
expect(succeeded_events.length).to eql(0)
failed_events = subscriber.failed_events.select do |event|
event.command_name == 'bogus'
end
expect(failed_events.length).to eql(1)
failed_event = failed_events.first
expect(failed_event.command_name).to eql('bogus')
expect(failed_event.message).to match(/no such c(om)?m(an)?d/)
expect(failed_event.address).to be_a(Mongo::Address)
expect(failed_event.duration).to be_a(Float)
end
context 'client with no established connections' do
# For simplicity use 3.6+ servers only, then we can assert
# scram auth commands
min_server_fcv '3.6'
# X.509 auth uses authenticate instead of sasl* commands
require_no_external_user
shared_examples_for 'does not nest auth and find' do
it 'does not nest auth and find' do
expect(subscriber.started_events.length).to eq 0
client['test-collection'].find(a: 1).first
command_names = subscriber.started_events.map(&:command_name)
command_names.should == expected_command_names
end
end
context 'pre-4.4 servers' do
max_server_version '4.2'
let(:expected_command_names) do
# Long SCRAM conversation.
%w(saslStart saslContinue saslContinue find)
end
it_behaves_like 'does not nest auth and find'
end
context '4.4+ servers' do
min_server_fcv '4.4'
let(:expected_command_names) do
# Speculative auth + short SCRAM conversation.
%w(saslContinue find)
end
it_behaves_like 'does not nest auth and find'
end
end
context 'when write concern is specified outside of command document' do
require_wired_tiger
require_topology :replica_set
min_server_fcv '4.0'
let(:collection) do
client['command-monitoring-test']
end
let(:write_concern) { Mongo::WriteConcern.get({w: 42}) }
let(:session) { client.start_session }
let(:command) do
Mongo::Operation::Command.new(
selector: { commitTransaction: 1 },
db_name: 'admin',
session: session,
txn_num: 123,
write_concern: write_concern,
)
end
it 'includes write concern in notified command document' do
server = client.cluster.next_primary
collection.insert_one(a: 1)
session.start_transaction
collection.insert_one({a: 1}, session: session)
subscriber.clear_events!
expect do
command.execute(server, context: Mongo::Operation::Context.new(session: session))
end.to raise_error(Mongo::Error::OperationFailure, /100\b.*Not enough data-bearing nodes/)
expect(subscriber.started_events.length).to eq(1)
event = subscriber.started_events.first
expect(event.command['writeConcern']['w']).to eq(42)
end
end
end
|
class MessageMailerWorker < BaseWorker
def self.category; :notification end
def self.metric; :email end
def perform(notification_type, user_id, message_id, data)
perform_with_tracking(notification_type, user_id, message_id, data) do
user = User.find(user_id)
message = Message.new(id: message_id)
user.email_notifier.send_snap_notification!(notification_type, message, data) if user.away_idle_or_unavailable?
true
end
end
statsd_measure :perform, metric_prefix
end
|
class Api::V1::NotificationsController < Api::V1::BaseController
before_action :set_notification, only: [:show, :update, :destroy]
def_param_group :notification1 do
param :notification1, Hash, required: true, action_aware: true do
param :offset, Integer, required: true, allow_nil: false
param :count, Integer, required: true, allow_nil: false
end
end
def_param_group :notification2 do
param :notification2, Hash, required: true, action_aware: true do
param :id, Integer, required: true, allow_nil: false
param :notice, String, required: true, allow_nil: false
param :notice_type, String, required: true, allow_nil: false
param :option, String, required: true, allow_nil: false
end
end
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Get Notifications
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
api :GET, '/notifications','List of notifications for the users'
param_group :notification1
def index
resp = []
#Get the notifications than have not been queried before ("read" is still false)
#and those that have been queried less than 2 days ago ("read" updated to true 2 days ago)
notification_list = @user.notifications#.page(params[:page]).per(params[:per])
# temp = notification_list.where("read = ? AND updated_at >= ?", true, DateTime.now - 2.day)
# temp += notification_list.where(read: false)
notifications = notification_list.where("read = ? AND created_at >= ?", false, DateTime.now - 30.day)
notifications = notifications.uniq.sort_by(&:created_at).reverse
#Set http return status and notifications
#This returns entries sorted from first to last according to created_at time
if @user.email_verified == false
resp = [{
id: 0,
notice: "Your email account is not verified. Please verify your email",
date: DateTime.now.to_formatted_s(:short),
notice_type: "account_status_"
}]
render status: 200, json: {status: 200, notifications: resp, total_count: 1 }
else
@notifications = set_status_and_list_limit notifications
if @notifications.present?
#@notifications = @notifications.as_json(only: [:id, :notice, :created_at])
@notifications.each do |notification|
#Transfer notification type
if notification['noticeable_type'] == 'TransferNotification'
#Only marked 'read' to true to 'send_' notifications
if (notification[:read] == false) && (notification.noticeable[:notice_type] == "send_")
notification[:read] = true
notification.save
end
notif = get_transfer_notification notification
if notif
resp << notif
end
#Susu notification type - Not implemented
elsif notification['noticeable_type'] == 'SusuNotification'
notif = get_susu_notification notification
if notif
resp << notif
end
#Invite notification type - Not implemented
elsif notification['noticeable_type'] == 'InviteNotification'
notif = get_invite_notification notification
if notif
resp << notif
end
end
end
if resp.present?
render status: @status, json: { notifications: resp, total_count: notifications.count }
else
render json: { message: "You have no notification at this moment.", total_count: notifications.count }
end
else
render json: { message: "You have no notification at this moment.", total_count: notifications.count }
end
end
end
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Update Notificatons
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
api :PUT, '/notifications/update_notification','Update user notification'
param_group :notification2
def update_notification
id = notification_params[:id]
notice_type = notification_params[:notice_type]
option = notification_params[:option]
notification = @user.notifications.find_by_id(id)
if notification
if notice_type == 'request_'
if option == "Pay"
notification[:read] = true
notification.save
puts "Notification marked read without being paid."
render status: 200, json: {message: "Request declined!"}
elsif option == "Decline"
notification[:read] = true
notification.save
puts "Request declined!"
render status: 200, json: {message: "Request declined!"}
end
end
else
puts "Notification does not exists."
render status: 500, json: {error: "Oops! Something went wrong. Try again later"}
end
end
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Get Notificatons Count
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
api :GET, '/notifications_count','Total count of unread notifications for the last 30 days'
def notifications_count
count = @user.notifications.where("read = ? AND created_at >= ?", false, DateTime.now - 30.day).uniq.count
render status: 200, json: { status: 200, count: count }
end
# # GET /notifications/1
# def show
# render json: @notification
# end
# # POST /notifications
# def create
# @notification = Notification.new(notification_params)
# if @notification.save
# render json: @notification, status: :created, location: @notification
# else
# render json: @notification.errors, status: :unprocessable_entity
# end
# end
# # PATCH/PUT /notifications/1
# def update
# if @notification.update(notification_params)
# render json: @notification
# else
# render json: @notification.errors, status: :unprocessable_entity
# end
# end
# # DELETE /notifications/1
# def destroy
# @notification.destroy
# end
private
def set_status_and_list_limit list
if list.count > params[:offset].to_i + params[:count].to_i
@status = 206
else
@status = 200
end
list.drop(params[:offset].to_i).first(params[:count].to_i)
end
def get_transfer_notification notification
options = []
notice_type = notification.noticeable.notice_type
if notice_type == "request_"
options << "Pay"
options << "Decline"
{
id: notification[:id],
notice: notification[:notice],
date: notification[:created_at].to_formatted_s(:short),
notice_type: notice_type,
amount: @user.get_formatted_amount_display(notification.noticeable.amount),
recipient_id: notification.noticeable.notified_by.id,
recipient_first_name: notification.noticeable.notified_by.first_name,
recipient_last_name: notification.noticeable.notified_by.last_name,
recipient_username: notification.noticeable.notified_by.username,
notification_date: notification.created_at,
picture: notification.noticeable.notified_by.present? ? notification.noticeable.notified_by.picture.avatar.url(:thumb) : '',
options: options
}
elsif notice_type == "send_"
{
id: notification[:id],
notice: notification[:notice],
date: notification[:created_at].to_formatted_s(:short),
notification_date: notification.created_at,
notice_type: notice_type
}
end
end
def get_susu_notification notification
#trans_type = SmxTransaction.find_by_id(notification.noticeable.smx_transaction_id).transactionable.trans_type
end
def get_invite_notification notification
end
# Use callbacks to share common setup or constraints between actions.
def set_notification
@notification = Notification.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def notification_params
params.require(:notification).permit(:id, :notice, :notice_type, :option)
end
end
|
class CreateAbsenceScheduleBlocks < ActiveRecord::Migration
def change
create_table :absence_schedule_blocks do |t|
t.integer :absence_id, :null => :false, :default => 0
t.integer :schedule_block_id, :null => false, :default => 0
t.timestamps
end
end
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
describe "#new" do
context 'can save' do
it "is valid with nickname, email, password, password_confirmation, last_name, first_name, last_name_kana, first_name_kana, birthday" do
expect(build(:user, avatar: nil, profile: nil, sex: nil)).to be_valid
end
it "is valid with a password that has more than 7 letters" do
expect(build(:user, password: "1234567", password_confirmation: "1234567")).to be_valid
end
end
context 'cannot save' do
it "is invalid without nickname" do
user = build(:user, nickname: nil)
user.valid?
expect(user.errors[:nickname]).to include("を入力してください")
end
it "is invalid without email" do
user = build(:user, email: nil)
user.valid?
expect(user.errors[:email]).to include("を入力してください")
end
it "is invalid without password" do
user = build(:user, password: nil)
user.valid?
expect(user.errors[:password]).to include("を入力してください")
end
it "is invalid with a password_confirmation that is different from password" do
user = build(:user, password: "0000000", password_confirmation: "1111111")
user.valid?
expect(user.errors[:password_confirmation]).to include("とパスワードの入力が一致しません")
end
it "is invalid without last_name" do
user = build(:user, last_name: nil)
user.valid?
expect(user.errors[:last_name]).to include("を入力してください")
end
it "is invalid with a last_name that does not have ZENKAKU moji" do
user = build(:user, last_name: "カアサン")
user.valid?
expect(user.errors[:last_name]).to include("は不正な値です")
end
it "is invalid without first_name" do
user = build(:user, first_name: nil)
user.valid?
expect(user.errors[:first_name]).to include("を入力してください")
end
it "is invalid with a first_name that does not have ZENKAKU moji" do
user = build(:user, first_name: "トオサン")
user.valid?
expect(user.errors[:first_name]).to include("は不正な値です")
end
it "is invalid without last_name_kana" do
user = build(:user, last_name_kana: nil)
user.valid?
expect(user.errors[:last_name_kana]).to include("を入力してください")
end
it "is invalid with a last_name_kana that does not have ZENKAKU moji" do
user = build(:user, last_name_kana: "カアサン")
user.valid?
expect(user.errors[:last_name_kana]).to include("は不正な値です")
end
it "is invalid without first_name_kana" do
user = build(:user, first_name_kana: nil)
user.valid?
expect(user.errors[:first_name_kana]).to include("を入力してください")
end
it "is invalid with a first_name_kana that does not have ZENKAKU moji" do
user = build(:user, first_name_kana: "トオサン")
user.valid?
expect(user.errors[:first_name_kana]).to include("は不正な値です")
end
it "is invalid without birthday" do
user = build(:user, birthday: nil)
user.valid?
expect(user.errors[:birthday]).to include("を入力してください")
end
it "is invalid with a password that has less than 6 letters" do
user = build(:user, password: "123456", password_confirmation: "123456")
user.invalid?
expect(user.errors[:password]).to include("は7文字以上で入力してください")
end
it "is invalid with an email that doesn't have @" do
user = build(:user, email: "kkkgmail.com")
user.invalid?
expect(user.errors[:email]).to include("は不正な値です")
end
end
end
end
|
class RouteOutgoingCall
def initialize(call:, status:, adapter: TwilioAdapter.new)
@outgoing_call = call
@status = status
@adapter = adapter
end
def call
if status.no_answer?
status.apply(outgoing_call)
adapter.end_call(outgoing_call.sid)
elsif status.answered?
connect_call_to_conference
end
end
private
attr_reader :outgoing_call, :status, :adapter
def connect_call_to_conference
ConnectCallToConference.new(call: outgoing_call, sids: [outgoing_call.sid]).call
end
end
|
module Media
module Command
class Progress
attr_reader :duration, :time
def initialize(duration = 0, time = 0)
@duration = duration
@time = time
end
def parse(str, &block)
str.split("\n").each do |line|
d = Parser.new(line, DURATION)
t = Parser.new(line, TIME)
@duration = d.to_seconds if d.match? and d.to_seconds > @duration
@time = t.to_seconds if t.match? and t.to_seconds > @time
block.call(self) if t.match?
end
end
def to_f
return 0.0 if duration == 0
[time / duration, 1.0].min.round(2)
end
def to_s
to_f.to_s
end
private
DURATION = /Duration: (\d+):(\d+):(\d+.\d+), start: (\d+.\d+)/
TIME = /time=(\d+):(\d+):(\d+.\d+)/
class Parser
def initialize(str, regex)
@match = regex.match(str)
_, @hours, @minutes, @seconds = @match.to_a if @match
end
def match?
!!@match
end
def to_seconds
return unless match?
result = 0.0
result += @hours.to_i * 3600
result += @minutes.to_i * 60
result += @seconds.to_f
end
end
end
end
end
|
module ApplicationHelper
def display_base_errors resource
return '' if (resource.errors.empty?) or (resource.errors[:base].empty?)
messages = resource.errors[:base].map { |msg| content_tag(:p, msg) }.join
html = <<-HTML
<div class="alert alert-error alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
#{messages}
</div>
HTML
html.html_safe
end
def bootstrap_class_for(flash_type)
case flash_type
when "success", :success
"alert-success" # Green
when "error", :error
"alert-danger" # Red
when "alert", :alert
"alert-warning" # Yellow
when "notice", :notice
"alert-info" # Blue
else
flash_type.to_s
end
end
end
|
require 'spec_helper'
describe "/questions/edit.html.erb" do
include QuestionsHelper
before(:each) do
assigns[:question] = @question = stub_model(Question,
:new_record? => false,
:prompt => "value for prompt",
:activity_id => 1
)
end
it "renders the edit question form" do
render
response.should have_tag("form[action=#{question_path(@question)}][method=post]") do
with_tag('textarea#question_prompt[name=?]', "question[prompt]")
with_tag('input#question_activity_id[name=?]', "question[activity_id]")
end
end
end
|
class User < ApplicationRecord
has_and_belongs_to_many :gradeworks
has_and_belongs_to_many :roles
accepts_nested_attributes_for :roles
validates :firstname, :lastname, :phone, presence: true
validates :email, :identification, presence: true, uniqueness: true
default_scope {order("users.firstname ASC")}
scope :order_by_firstname,-> (ord) {order("users.firstname #{ord}")}
scope :order_by_lastname, -> (ord) {order("users.lastname #{ord}")}
scope :order_by_email, -> (ord) {order("users.email #{ord}")}
scope :order_by_identification, -> (ord) {order("users.identification #{ord}")}
def full_name
"#{firstname} #{lastname}"
end
def self.users_by_id(id)
find_by_id(id)
end
def self.users_by_firtsname(firstname)
find_by_firstname(firstname)
end
def self.users_by_email(email)
find_by_email(email)
end
def self.users_by_identification(identification)
find_by_identification(identification)
end
def self.users_jury()
joins(:roles).select("users.firstname, users.lastname, users.id")
.where({ roles: { name: "Jury" } })
end
def self.users_student()
joins(:roles).select("users.firstname, users.lastname, users.id")
.where({ roles: { name: "Student" } })
end
def self.users_director()
joins(:roles).select("users.firstname, users.lastname, users.id")
.where({ roles: { name: "Director" } })
end
def self.users_administrator()
joins(:roles).select("users.firstname, users.lastname, users.id")
.where({ roles: { name: "Administrator" } })
end
def self.users_gradework_qualified()
joins(:gradeworks).select("users.firstname, users.id")
.where({ gradeworks: { status: "calificado" } })
end
def self.users_gradework_unrated()
joins(:gradeworks).select("users.firstname, users.id")
.where({ gradeworks: { status: "sin calificar" } })
end
def self.users_gradework_qualifying()
joins(:gradeworks).select("users.firstname, users.id")
.where({ gradeworks: { status: "calificando" } })
end
end
|
describe Rfm::Config do
subject {Rfm::Config}
let(:config) {subject.instance_variable_get :@config}
let(:klass) {Class.new{extend Rfm::Config}}
describe "#config" do
before(:each){klass.config :group1, :layout=>'lay1'}
it "sets @config with arguments & options" do
expect(klass.instance_variable_get(:@config)).to eq({:use=>:group1, :layout=>'lay1'})
end
it "returns @config" do
expect(klass.config).to eq(klass.instance_variable_get(:@config))
end
it "passes strings to block if block given" do
string_test = []
klass.config('string1', 'string2', :group1, :group2, :layout=>'lay5'){|params| string_test = params[:strings]}
expect(string_test).to eq(['string1', 'string2'])
end
end
describe "#get_config" do
context "with no arguments" do
it "returns upstream config" do
expect(klass.get_config).to eq({:host=>'host1', :strings=>[], :ignore_bad_data => true, :using=>[], :parents=>["file", "RFM_CONFIG"], :objects=>[]})
end
end
context "with preset filters but no arguments" do
it "returns upstream config, merged with filtered groups" do
klass.config :group1
expect(klass.get_config).to eq({:host=>'host1', :strings=>[], :database=>'db1', :using=>[:group1], :ignore_bad_data => true, :parents=>["file", "RFM_CONFIG"], :objects=>[]})
end
end
context "with array of symbols and hash of options" do
it "returns upstream config, merged with filtered groups, merged with options, merged with preset filters" do
klass.config :group1
expect(klass.get_config(:group2, :ssl=>true)).to eq({:host=>'host1', :strings=>[], :database=>'db2', :ssl=>true, :using=>[:group1, :group2], :ignore_bad_data => true, :parents=>["file", "RFM_CONFIG"], :objects=>[]})
end
it "returns config including :strings parameter, if passed array of strings as first n arguments" do
klass.config :group1
expect(klass.get_config('test-string-one', 'test-string-two', :group2, :ssl=>true)[:strings][1]).to eq('test-string-two')
end
end
end
end # Rfm::Config
|
#
# Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands.
#
# This file is part of New Women Writers.
#
# New Women Writers is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# New Women Writers is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with New Women Writers. If not, see <http://www.gnu.org/licenses/>.
#
require 'date'
require 'tzinfo/time_or_datetime'
module TZInfo
# Represents an offset defined in a Timezone data file.
class TimezoneTransitionInfo #:nodoc:
# The offset this transition changes to (a TimezoneOffsetInfo instance).
attr_reader :offset
# The offset this transition changes from (a TimezoneOffsetInfo instance).
attr_reader :previous_offset
# The numerator of the DateTime if the transition time is defined as a
# DateTime, otherwise the transition time as a timestamp.
attr_reader :numerator_or_time
protected :numerator_or_time
# Either the denominotor of the DateTime if the transition time is defined
# as a DateTime, otherwise nil.
attr_reader :denominator
protected :denominator
# Creates a new TimezoneTransitionInfo with the given offset,
# previous_offset (both TimezoneOffsetInfo instances) and UTC time.
# if denominator is nil, numerator_or_time is treated as a number of
# seconds since the epoch. If denominator is specified numerator_or_time
# and denominator are used to create a DateTime as follows:
#
# DateTime.new!(Rational.send(:new!, numerator_or_time, denominator), 0, Date::ITALY)
#
# For performance reasons, the numerator and denominator must be specified
# in their lowest form.
def initialize(offset, previous_offset, numerator_or_time, denominator = nil)
@offset = offset
@previous_offset = previous_offset
@numerator_or_time = numerator_or_time
@denominator = denominator
@at = nil
@local_end = nil
@local_start = nil
end
# A TimeOrDateTime instance representing the UTC time when this transition
# occurs.
def at
unless @at
unless @denominator
@at = TimeOrDateTime.new(@numerator_or_time)
else
r = RubyCoreSupport.rational_new!(@numerator_or_time, @denominator)
dt = RubyCoreSupport.datetime_new!(r, 0, Date::ITALY)
@at = TimeOrDateTime.new(dt)
end
end
@at
end
# A TimeOrDateTime instance representing the local time when this transition
# causes the previous observance to end (calculated from at using
# previous_offset).
def local_end
@local_end = at.add_with_convert(@previous_offset.utc_total_offset) unless @local_end
@local_end
end
# A TimeOrDateTime instance representing the local time when this transition
# causes the next observance to start (calculated from at using offset).
def local_start
@local_start = at.add_with_convert(@offset.utc_total_offset) unless @local_start
@local_start
end
# Returns true if this TimezoneTransitionInfo is equal to the given
# TimezoneTransitionInfo. Two TimezoneTransitionInfo instances are
# considered to be equal by == if offset, previous_offset and at are all
# equal.
def ==(tti)
tti.respond_to?(:offset) && tti.respond_to?(:previous_offset) && tti.respond_to?(:at) &&
offset == tti.offset && previous_offset == tti.previous_offset && at == tti.at
end
# Returns true if this TimezoneTransitionInfo is equal to the given
# TimezoneTransitionInfo. Two TimezoneTransitionInfo instances are
# considered to be equal by eql? if offset, previous_offset,
# numerator_or_time and denominator are all equal. This is stronger than ==,
# which just requires the at times to be equal regardless of how they were
# originally specified.
def eql?(tti)
tti.respond_to?(:offset) && tti.respond_to?(:previous_offset) &&
tti.respond_to?(:numerator_or_time) && tti.respond_to?(:denominator) &&
offset == tti.offset && previous_offset == tti.previous_offset &&
numerator_or_time == tti.numerator_or_time && denominator == tti.denominator
end
# Returns a hash of this TimezoneTransitionInfo instance.
def hash
@offset.hash ^ @previous_offset.hash ^ @numerator_or_time.hash ^ @denominator.hash
end
# Returns internal object state as a programmer-readable string.
def inspect
"#<#{self.class}: #{at.inspect},#{@offset.inspect}>"
end
end
end
|
# -*- encoding : utf-8 -*-
module Retailigence #:nodoc:
# A location result from the Retailigence API
#
# === Attributes
# * <tt>id</tt> - Unique identifier for the location
# * <tt>timezone</tt> - Timezone of the location
# * <tt>distance</tt> - Distance object calculated based off the <tt>userlocation</tt> param
# * <tt>phone</tt> - Location's phone number
# * <tt>t_nav_link</tt> - URL to get directions from your current position to the location's position
# * <tt>location</tt> - Contains the latitude and longitude for the location. Using the <tt>latitude</tt> and <tt>longitude</tt> attributes are preferred
# * <tt>address</tt> - An Address object containing the physical postal address
# * <tt>hours</tt> - Colon separated operating hours
# * <tt>map_link</tt> - Google Maps URL for the location's address
# * <tt>name</tt> - Name of the location
# * <tt>retailer</tt> - Retailer
# * <tt>retlocationid</tt> - External location ID provided by the Retailer
# * <tt>latitude</tt> - The location's latitude
# * <tt>longitide</tt> - The location's longitude
class Location < Model
attributes :id, :timezone, :distance, :phone, :tNavLink, :location,
:address, :hours, :mapLink, :name, :retailer, :retlocationid,
:latitude, :longitude
# Search locations and retailers based on the <tt>params</tt> passed.
#
# === Params
# See the documentation from Retailigence for all possible parameters
#
# === Returns
# SearchResult with <tt>results</tt> being an array of Retailer
def self.search(params = {})
results = get('locations', params)
retailers =
if results['RetailigenceAPIResult']['count'] == 0
[]
else
results['RetailigenceAPIResult']['results'].map do |result|
Retailer.new(result['Retailer'])
end
end
SearchResult.new(retailers)
end
def retailer=(retailer) #:nodoc:
@retailer = Retailer.new(retailer)
end
def distance=(distance) #:nodoc:
@distance = Distance.new(distance)
end
def address=(address) #:nodoc:
@address = Address.new(address)
end
# Convert the locations hash to latitude and longitude
def location=(location) #:nodoc:
@latitude = location['latitude']
@longitude = location['longitude']
@location = location
end
end
end
|
describe PersonDecorator do
describe "#introduction" do
subject(:introduction) { person.decorate.introduction }
let!(:person) do
build(:person,
name: "Anakin",
height: "188",
mass: "84",
homeworld: build(:planet, name: "Tatooine"),
birth_year: "41.9BBY",
species: species,
starships: starships)
end
let(:species) { [build(:specie, name: "Human")] }
let(:starships) { [build(:starship, name: "Jedi interceptor")] }
it "returns person introduction" do
expect(introduction).to eq "Hello! I'm Anakin. I'm a Human, my weight is 84 kg and my height is 188 cm. "\
"My homeworld is Tatooine, I was born in the year 41.9BBY and "\
"I've piloted Jedi interceptor."
end
context "when person doesn't have species" do
let(:species) { [] }
it "returns person introduction" do
expect(introduction).to eq "Hello! I'm Anakin. My weight is 84 kg and my height is 188 cm. My homeworld "\
"is Tatooine, I was born in the year 41.9BBY and I've piloted Jedi interceptor."
end
end
context "when person doesn't have starships" do
let(:starships) { [] }
it "returns person introduction" do
expect(introduction).to eq "Hello! I'm Anakin. I'm a Human, my weight is 84 kg and my height is 188 cm. "\
"My homeworld is Tatooine, I was born in the year 41.9BBY."
end
end
end
describe "#wookie_introduction" do
subject(:wookie_introduction) { person.decorate.wookie_introduction }
let(:person) { build(:person) }
it "changes intro with wookie words" do
expect(wookie_introduction.split & PersonDecorator::WOOKIE_WORDS).to be_present
end
end
end
|
require "ostruct"
require "optparse"
require "fileutils"
require "tmpdir"
require "minitar"
module Gaudi
class GemError < RuntimeError
end
class Gem
MAIN_CONFIG = "system.cfg".freeze
REPO = "https://github.com/damphyr/gaudi".freeze
attr_reader :project_root, :gaudi_home
# :nodoc:
def self.options(arguments)
options = OpenStruct.new
options.project_root = Dir.pwd
options.verbose = false
options.scaffold = false
options.update = false
options.library = false
options.version = "HEAD"
opt_parser = OptionParser.new do |opts|
opts.banner = "Usage: gaudi [options]"
opts.separator "Make sure GitHub is accessible via https and git is on the PATH environment"
opts.separator ""
opts.separator "Commands:"
opts.on("-s", "--scaffold PROJECT_PATH", "Create a Gaudi scaffold in PROJECT_PATH") do |proot|
options.project_root = File.expand_path(proot)
options.scaffold = true
options.update = false
end
opts.on("-u", "--update PROJECT_PATH", "Update Gaudi core from GitHub on project at PROJECT_PATH") do |proot|
options.project_root = File.expand_path(proot)
options.update = true
options.scaffold = false
end
opts.on("-l", "--lib NAME URL PROJECT_PATH", "Pull/Update Gaudi library from URL on project at PROJECT_PATH") do |name|
options.library = true
options.update = false
options.scaffold = false
options.lib = name
raise GemError, "Missing parameters!" if ARGV.size < 2
url = ARGV.shift
proot = ARGV.shift
options.url = url
options.project_root = File.expand_path(proot)
end
opts.separator ""
opts.separator "Common options:"
# Boolean switch.
opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
options.verbose = v
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
opts.on_tail("--version", "Show version") do
puts "Gaudi Gem v#{Gaudi::Gem::Version::STRING}"
exit
end
end
begin
opt_parser.parse!(arguments)
rescue GemError
puts $!.message
exit 1
end
return options
end
# :nodoc:
def self.run(args)
opts = options(args)
begin
if opts.scaffold
Gaudi::Gem.new(opts.project_root).project(opts.version)
elsif opts.update
Gaudi::Gem.new(opts.project_root).update(opts.version)
elsif opts.library
Gaudi::Gem.new(opts.project_root).library(opts.lib, opts.url, opts.version)
end
rescue Gaudi::GemError
puts $!.message
exit 1
end
end
def initialize(project_root)
@project_root = project_root
@gaudi_home = File.join(project_root, "tools", "build")
end
def project(version)
raise GemError, "#{project_root} already exists!" if File.exist?(project_root) && project_root != Dir.pwd
check_for_git
directory_structure
rakefile
main_config
api_doc
core(REPO, version, ["lib/gaudi.rb lib/gaudi"])
end
def update(version)
raise GemError, "#{gaudi_home} is missing! Try creating a new Gaudi project first." unless File.exist?(gaudi_home)
check_for_git
puts "Removing old gaudi installation"
FileUtils.rm_rf(File.join(gaudi_home, "lib/gaudi"))
core(REPO, version, ["lib/gaudi lib/gaudi.rb"])
end
def library(lib, source_url, version)
raise GemError, "#{gaudi_home} is missing! Try creating a new Gaudi project first." unless File.exist?(gaudi_home)
puts "Removing old #{lib} installation"
FileUtils.rm_rf(File.join(gaudi_home, "lib/#{lib}"))
puts "Pulling #{version} from #{source_url}"
core(source_url, version, ["lib/#{lib}", "tools/build/lib/#{lib}"])
end
# :stopdoc:
def check_for_git
raise GemError, "Could not find git. Make sure it is in the PATH" unless system("git --version")
end
def directory_structure
puts "Creating Gaudi filesystem structure at #{project_root}"
structure = ["doc", "tools/build/config", "tools/templates"]
structure.each do |dir|
FileUtils.mkdir_p File.join(project_root, dir), :verbose => false
end
end
def rakefile
puts "Generating main Rakefile"
rakefile = File.join(project_root, "Rakefile")
if File.exist?(rakefile)
puts "Rakefile exists, skipping generation"
else
rakefile_content = File.read(File.join(File.dirname(__FILE__), "templates/rakefile.rb.template"))
File.open(rakefile, "wb") { |f| f.write(rakefile_content) }
end
end
def main_config
puts "Generating initial configuration file"
config_file = File.join(project_root, "tools/build/#{MAIN_CONFIG}")
if File.exist?(config_file)
puts "#{MAIN_CONFIG} exists, skipping generation"
else
configuration_content = File.read(File.join(File.dirname(__FILE__), "templates/main.cfg.template"))
File.open(config_file, "wb") { |f| f.write(configuration_content) }
end
end
def api_doc
puts "Generating build system API doc"
config_file = File.join(project_root, "doc/BUILDSYSTEM.md")
if File.exist?(config_file)
puts "BUILDSYSTEM.md exists, skipping generation"
else
configuration_content = File.read(File.join(File.dirname(__FILE__), "templates/doc.md.template"))
File.open(config_file, "wb") { |f| f.write(configuration_content) }
end
end
def core(url, version, lib_items)
Dir.mktmpdir do |tmp|
raise GemError, "Cloning the Gaudi repo failed. Check that git is on the PATH and that #{REPO} is accessible" unless pull_from_repo(url, tmp)
lib_items.each do |items|
unpack_target = gaudi_home
unpack_target = File.expand_path(File.join(gaudi_home, "../..")) if /tools\/build/ =~ items
pkg = archive(version, File.join(tmp, "gaudi"), project_root, items)
unpack(pkg, unpack_target)
rescue GemError
next
end
end
end
def pull_from_repo(repository, tmp)
tmp_dir = File.join(tmp, "gaudi")
FileUtils.rm_rf(tmp_dir) if File.exist?(tmp_dir)
system "git clone #{repository} \"#{tmp_dir}\""
end
def archive(version, clone_path, prj_root, lib_items)
pkg = File.expand_path(File.join(prj_root, "gaudipkg.tar"))
Dir.chdir(clone_path) do |d|
puts "Packing #{version} gaudi version in #{pkg}"
cmdline = "git archive --format=tar -o \"#{pkg}\" #{version} #{lib_items}"
raise GemError, "Failed to extract library from git" unless system(cmdline)
end
return pkg
end
def unpack(pkg, home)
puts "Unpacking in #{home}"
Dir.chdir(home) do |d|
Minitar.unpack(pkg, home)
end
FileUtils.rm_rf(pkg)
FileUtils.rm_rf(File.join(home, "pax_global_header"))
end
# :startdoc:
end
end
|
require 'spec_helper'
describe WorkfileVersionPresenter, :type => :view do
let(:workfile) { workfiles(:public) }
let(:owner) { workfile.owner }
let(:version) { workfile.latest_workfile_version }
let(:presenter) { WorkfileVersionPresenter.new(version, view, options) }
let(:options) { {} }
before(:each) do
stub(ActiveRecord::Base).current_user { owner }
end
describe "#to_hash" do
let(:workfile_hash) { presenter.to_hash }
let(:hash) { workfile_hash[:version_info] }
it "includes the right keys" do
hash.should have_key(:id)
hash.should have_key(:version_num)
hash.should have_key(:commit_message)
hash.should have_key(:owner)
hash.should have_key(:modifier)
hash.should have_key(:created_at)
hash.should have_key(:updated_at)
workfile_hash.should have_key(:execution_schema)
end
it "uses the user presenter to serialize the owner and modifier" do
hash[:owner].to_hash.should == UserPresenter.new(owner, view).presentation_hash
hash[:modifier].to_hash.should == UserPresenter.new(owner, view).presentation_hash
end
it "sanitizes values" do
bad_value = "<script>alert('got your cookie')</script>"
workfile_version = FactoryGirl.build :workfile_version, :commit_message => bad_value
workfile_version.contents = test_file('small1.gif')
workfile_version.workfile = workfile
json = WorkfileVersionPresenter.new(workfile_version, view).to_hash[:version_info]
json[:commit_message].should_not match "<"
end
context "when not on the workfile page" do
let(:workfile) { workfiles(:'text.txt') }
it "should not include the :contents key" do
hash[:content].should be_nil
end
end
context "when rendering a single workfile version (the contents option is true)" do
let(:options) { {contents: true} }
context "when the file is an image" do
let(:workfile) { workfiles(:'image.png') }
it "includes the url of the original file" do
hash[:content_url].should == version.contents.url
end
it "uses the thumbnail of the original file for the icon" do
hash[:icon_url].should == version.contents.url(:icon)
end
it "does not include the file's content" do
hash[:content].should be_nil
end
end
context "when the file is binary" do
let(:workfile) { workfiles(:'binary.tar.gz') }
it "includes the url of the file" do
hash[:content_url].should == version.contents.url
end
it "uses a static image for the icon (based on the filetype)" do
hash[:icon_url].should be_nil
end
it "does not include the file's content" do
hash[:content].should be_nil
end
end
context "when the file is text" do
let(:workfile) { workfiles(:'text.txt') }
it "includes the url of the file" do
hash[:content_url].should == version.contents.url
end
it "uses a static image for the icon (based on the filetype)" do
hash[:icon_url].should be_nil
end
it "includes the text of the file" do
hash[:content].should == File.read(version.contents.path)
end
end
context "when the file is sql" do
let(:workfile) { workfiles(:'sql.sql') }
it "includes the url of the file" do
hash[:content_url].should == version.contents.url
end
it "uses a static image for the icon (based on the filetype)" do
hash[:icon_url].should be_nil
end
it "includes the text of the file" do
hash[:content].should == File.read(version.contents.path)
end
end
end
context "when rendering the activity stream" do
let(:options) { {:activity_stream => true} }
it "does not render the owner or modifier" do
hash[:owner][:id].should == owner.id
hash[:modifier][:id].should == owner.id
hash[:owner].keys.size.should == 1
hash[:modifier].keys.size.should == 1
end
end
end
describe "complete_json?" do
context "when rendering activities" do
let(:options) { {:activity_stream => true, :contents => true} }
it "is not true" do
presenter.complete_json?.should_not be_true
end
end
context "when not including the contents" do
it "is not true" do
presenter.complete_json?.should_not be_true
end
end
context "when not rendering activities and including the contents" do
let(:options) { {:contents => true} }
it "is true" do
presenter.complete_json?.should be_true
end
end
end
end
|
### Collections Basics ####
def palindrome?(word)
if word.size >=2
word == word.reverse
else
false
end
end
def change_me(sentence)
sentence_arr = sentence.split(" ")
pali_sentence = sentence_arr.map{|word| palindrome?(word) ? word.upcase : word}
pali_sentence.join(" ")
end
def palindrome_substrings(str)
j = str.size
pali_arr = []
for i in 0...j
for e in 2...j
if palindrome?(str[i,e])
pali_arr << str[i,e]
end
end
end
pali_arr
end
def select_fruit(hash)
result_hash = Hash.new
keys = hash.keys
for i in keys
if hash[i] == 'Fruit'
result_hash[i] = 'Fruit'
end
end
result_hash
end
def double_numbers(numbers)
counter = 0
loop do
break if counter == numbers.size
numbers[counter] *= 2
counter += 1
end
numbers
end
def double_odd_numbers(numbers)
doubled_numbers = []
counter = 0
loop do
break if counter == numbers.size
current_number = numbers[counter]
current_number *= 2 if current_number.odd?
doubled_numbers << current_number
counter += 1
end
doubled_numbers
end
munsters.map do |k,v|
if v['age'] > 65
v['age_group'] = 'senior'
elsif v['age'] <= 64 && v['age'] >= 18
v['age_group'] = 'adult'
else
v['age_group'] = 'kid'
end
end
|
class AddIfPaidToUtilityCharges < ActiveRecord::Migration
def change
add_column :utility_charges, :is_paid, :boolean, null: false, default: false
end
end
|
require "test_helper"
describe UsersController do
describe "index" do
it "responds with success when there is at least one user saved" do
user = users(:ada)
get users_path
expect(User.count > 0).must_equal true
must_respond_with :success
end
end
describe "login" do
it "logs in an existing user and redirects to the root route" do
start_count = User.count
user = users(:grace)
perform_login(user)
expect(flash[:success]).must_equal "Logged in as returning user #{user.name}"
session[:user_id].must_equal user.id
must_redirect_to root_path
User.count.must_equal start_count
end
it "creates an account for a new user and redirects to the root route" do
start_count = User.count
user = User.new(provider: "github", uid: 99999, username: "test_user", email: "test@user.com", name: "Tester")
perform_login(user)
expect(flash[:success]).must_equal "Logged in as new user #{user.name}"
session[:user_id].must_equal User.last.id
must_redirect_to root_path
User.count.must_equal start_count + 1
end
it "redirects to the login route if given invalid user data" do
start_count = User.count
bad_user = User.create(provider: "github", uid: 99999)
perform_login(bad_user)
expect(flash[:error]).must_include "Could not create new user account: "
must_redirect_to root_path
assert_nil(session[:user_id])
User.count.must_equal start_count
end
end
describe "show" do
it "responds with success when showing a valid user" do
test_user = users(:grace)
get user_path(test_user.id)
must_respond_with :success
end
it "redirects to users path if given invalid user id" do
invalid_id = -1
get user_path(invalid_id)
must_respond_with :not_found
end
end
describe "logout" do
it "can log out a valid user and redirects to root" do
start_count = User.count
user = users(:ada)
perform_login(user)
delete logout_path
assert_nil(session[:user_id])
expect(flash[:success]).must_equal "Successfully logged out!"
must_redirect_to root_path
User.count.must_equal start_count
end
it "redirects to root if you try to log out, but nobody is logged in" do
start_count = User.count
delete logout_path
assert_nil(session[:user_id])
assert_nil(flash[:success])
must_redirect_to root_path
User.count.must_equal start_count
end
end
end
|
class DevisesessionController < Devise::SessionsController
def create
Rails.logger.debug(params[:user][:email])
user = User.find_by_email(params[:user][:email])
if(!user.nil?)
Rails.logger.debug(user.is_approved)
Rails.logger.debug(user.is_approved == 1)
if(user.is_approved == 1)
super
else
respond_to do| format |
format.html { redirect_to new_user_session_path, notice: 'Unauthorized User'}
end
end
else
respond_to do| format |
format.html { redirect_to new_user_session_path, notice: 'Invalid username'}
end
end
end
end
|
class Address < ActiveRecord::Base
attr_accessible :street1, :street2, :city, :state, :zip, :household_id
validates_presence_of :street1, :city, :state, :zip
validates_numericality_of :zip
#validates_length_of :zip, :is => 5, :message => "must be 5 digits long."
belongs_to :household
end
|
require 'OptimizerService.rb'
require 'OptimizerServiceMappingRegistry.rb'
require 'soap/rpc/driver'
module AdCenterWrapper
class IOptimizerService < ::SOAP::RPC::Driver
DefaultEndpointUrl = "https://adcenterapi.microsoft.com/Api/Advertiser/V8/Optimizer/OptimizerService.svc"
Methods = [
[ "GetBudgetOpportunities",
"getBudgetOpportunities",
[ ["in", "parameters", ["::SOAP::SOAPElement", "https://adcenter.microsoft.com/v8", "GetBudgetOpportunitiesRequest"]],
["out", "parameters", ["::SOAP::SOAPElement", "https://adcenter.microsoft.com/v8", "GetBudgetOpportunitiesResponse"]] ],
{ :request_style => :document, :request_use => :literal,
:response_style => :document, :response_use => :literal,
:faults => {"AdCenterWrapper::AdApiFaultDetailFault"=>{:encodingstyle=>"document", :use=>"literal", :ns=>"https://adcenter.microsoft.com/v8", :namespace=>nil, :name=>"AdApiFaultDetailFault"}, "AdCenterWrapper::ApiFaultDetailFault"=>{:encodingstyle=>"document", :use=>"literal", :ns=>"https://adcenter.microsoft.com/v8", :namespace=>nil, :name=>"ApiFaultDetailFault"}} }
],
[ "ApplyBudgetOpportunities",
"applyBudgetOpportunities",
[ ["in", "parameters", ["::SOAP::SOAPElement", "https://adcenter.microsoft.com/v8", "ApplyBudgetOpportunitiesRequest"]],
["out", "parameters", ["::SOAP::SOAPElement", "https://adcenter.microsoft.com/v8", "ApplyBudgetOpportunitiesResponse"]] ],
{ :request_style => :document, :request_use => :literal,
:response_style => :document, :response_use => :literal,
:faults => {"AdCenterWrapper::AdApiFaultDetailFault"=>{:encodingstyle=>"document", :use=>"literal", :ns=>"https://adcenter.microsoft.com/v8", :namespace=>nil, :name=>"AdApiFaultDetailFault"}, "AdCenterWrapper::ApiFaultDetailFault"=>{:encodingstyle=>"document", :use=>"literal", :ns=>"https://adcenter.microsoft.com/v8", :namespace=>nil, :name=>"ApiFaultDetailFault"}} }
]
]
def initialize(endpoint_url = nil)
endpoint_url ||= DefaultEndpointUrl
super(endpoint_url, nil)
self.mapping_registry = OptimizerServiceMappingRegistry::EncodedRegistry
self.literal_mapping_registry = OptimizerServiceMappingRegistry::LiteralRegistry
init_methods
end
private
def init_methods
Methods.each do |definitions|
opt = definitions.last
if opt[:request_style] == :document
add_document_operation(*definitions)
else
add_rpc_operation(*definitions)
qname = definitions[0]
name = definitions[2]
if qname.name != name and qname.name.capitalize == name.capitalize
::SOAP::Mapping.define_singleton_method(self, qname.name) do |*arg|
__send__(name, *arg)
end
end
end
end
end
end
end
|
class Weapon < Item
attr_reader :damage, :range
def initialize(name, weight, damage)
@name = name
@weight = weight
@damage = damage
end
def hit(recipient)
recipient.wound(@damage)
end
end
|
require('minitest/autorun')
require('minitest/rg')
require_relative('../river.rb')
require_relative('../fish.rb')
require_relative('../bear.rb')
class RiverTest < MiniTest::Test
def setup()
@amazon = River.new("Amazon", @fish)
@george = Bear.new("George", "Black Bear")
@tuna = Fish.new("Tuna")
@salmon = Fish.new("Salmon")
@pike = Fish.new("Pike")
@fish = [@tuna, @salmon, @pike]
end
def test_count_fish()
assert_equal(3, @amazon.count_fish())
end
def test_remove_fish()
remove_fish(@salmon)
assert_equal(2, @amazon.fish.length())
end
end
|
class CreatePurchaseOrderDetails < ActiveRecord::Migration
def change
create_table :purchase_order_details do |t|
t.integer :delivery_order_detail_id
t.float :unit_price
t.boolean :igv
t.float :unit_price_igv
t.text :description
t.timestamps
end
end
end
|
class WorkgroupRegionSelection < ActiveRecord::Base
belongs_to :workgroup
belongs_to :region
end
|
shared_examples_for GroupDocs::Signature::DocumentMethods do
describe '#documents!' do
before(:each) do
mock_api_server(load_json('template_get_documents'))
end
it 'accepts access credentials hash' do
lambda do
subject.documents!(:client_id => 'client_id', :private_key => 'private_key')
end.should_not raise_error()
end
it 'returns array of GroupDocs::Document objects' do
documents = subject.documents!
documents.should be_an(Array)
documents.each do |document|
document.should be_a(GroupDocs::Document)
end
end
end
describe '#add_document!' do
let(:document) do
GroupDocs::Document.new(:file => GroupDocs::Storage::File.new)
end
before(:each) do
mock_api_server('{ "status": "Ok", "result": {}}')
end
it 'accepts access credentials hash' do
lambda do
subject.add_document!(document, {}, :client_id => 'client_id', :private_key => 'private_key')
end.should_not raise_error()
end
it 'accepts options hash' do
lambda do
subject.add_document!(document, :order => 1)
end.should_not raise_error()
end
it 'raises error if document is not GroupDocs::Document object' do
lambda { subject.add_document!('Document') }.should raise_error(ArgumentError)
end
end
describe '#remove_document!' do
let(:document) do
GroupDocs::Document.new(:file => GroupDocs::Storage::File.new)
end
before(:each) do
mock_api_server('{ "status": "Ok", "result": {}}')
end
it 'accepts access credentials hash' do
lambda do
subject.remove_document!(document, :client_id => 'client_id', :private_key => 'private_key')
end.should_not raise_error()
end
it 'raises error if document is not GroupDocs::Document object' do
lambda { subject.remove_document!('Document') }.should raise_error(ArgumentError)
end
end
end
|
class ClickScoresController < ApplicationController
before_action :set_click_score, only: [:show, :edit, :update, :destroy]
# GET /click_scores
# GET /click_scores.json
def index
@click_scores = ClickScore.all
end
# GET /top-five-rapid-clicks.json
def top_five
@top_five = ClickScore.top_five
end
# GET /click_scores/1
# GET /click_scores/1.json
def show
end
# GET /click_scores/new
def new
@click_score = ClickScore.new
end
# GET /click_scores/1/edit
def edit
end
# POST /click_scores
# POST /click_scores.json
def create
@click_score = ClickScore.new(click_score_params)
respond_to do |format|
if @click_score.save
format.html { redirect_to @click_score, notice: 'Click score was successfully created.' }
format.json { render :show, status: :created, location: @click_score }
else
puts @click_score.errors.full_messages
format.html { render :new }
format.json { render json: @click_score.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /click_scores/1
# PATCH/PUT /click_scores/1.json
def update
respond_to do |format|
if @click_score.update(click_score_params)
format.html { redirect_to @click_score, notice: 'Click score was successfully updated.' }
format.json { render :show, status: :ok, location: @click_score }
else
format.html { render :edit }
format.json { render json: @click_score.errors, status: :unprocessable_entity }
end
end
end
# DELETE /click_scores/1
# DELETE /click_scores/1.json
def destroy
@click_score.destroy
respond_to do |format|
format.html { redirect_to click_scores_url, notice: 'Click score was successfully destroyed.' }
format.json { head :no_content }
end
end
def destroy_all
ClickScore.all.destroy_all
end
private
# Use callbacks to share common setup or constraints between actions.
def set_click_score
@click_score = ClickScore.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def click_score_params
params.require(:click_score).permit(:name, :score)
end
end
|
# Build a program that asks a user for the length and width of a room in meters and then displays
# the area of the room in both square meters and square feet.
# Note: 1 square meter == 10.7639 square feet
# Do not worry about validating the input at this time.
# Example outputs:
=begin
Enter the length of the room in meters:
10
Enter the width of the room in meters:
7
The area of the room is 70.0 square meters (753.47 square feet).
=end
CONVERSION = 10.7639 # better to explain what this number is/does, so use a name like SQMETERS_TO_SQFEET instead
puts "Enter the length of the room in meters: "
length = gets.to_f
puts "Enter the width of the room in meters: "
width = gets.to_f
area_square_meters = length * width
area_square_feet = (area_square_meters * CONVERSION).round(2)
puts "The area of the room is #{area_square_meters} square meters (#{area_square_feet} square feet)."
# Modify this program to ask for the input measurements in feet, and display the results in square feet,
# square inches, and square centimeters.
SQFEET_TO_SQINCHES = 144
SQFEET_TO_SQCM = 929.03
puts "Enter the length of the room in feet: "
length = gets.to_f
puts "Enter the width of the room in feet: "
width = gets.to_f
area_square_feet = length * width
area_square_inches = (area_square_feet * SQFEET_TO_SQINCHES).round(2)
area_square_cm = (area_square_feet * SQFEET_TO_SQCM).round(2)
puts "The area of the room is #{area_square_feet} square feet (#{area_square_inches} square inches, or #{area_square_cm} square centimeters)."
|
# cross the desert the smart way
# keep only directions that aren't cancelled out
# [NORTH, SOUTH, EAST] = [EAST] as north and south cancel each other
PAIRS = {
'NORTH' => 'SOUTH', 'SOUTH' => 'NORTH',
'EAST' => 'WEST', 'WEST' => 'EAST'
}
def reduce_directions(arr)
stack = []
arr.each do |cardinal|
PAIRS[cardinal] == stack.last ? stack.pop : stack.push(cardinal)
end
stack
end
|
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :email, null: false
t.string :password_digest, null: false
t.string :first_name, null: false
t.string :last_name, null: false
t.string :plaid_id
t.string :stripe_account
t.decimal :bucket, null: false, default: 0.00, precision: 10, scale: 2
t.string :current_charity_ein
t.string :current_charity_name
t.string :last_purchase
t.timestamps null: false
end
end
end |
require 'digest'
class Block
attr_reader :content, :previous_hash
def initialize(content:, previous_hash: 'Vazio')
@content = content
@previous_hash = previous_hash
end
def hash
Digest::SHA256.hexdigest content
end
def print
<<~HEREDOC
#{content}
Hash: #{hash}
Hash Anterior: #{previous_hash}
HEREDOC
end
end
|
require 'rails_helper'
describe 'CRUD for reviews' do
before(:each) do
Product.destroy_all
Review.destroy_all
@user = FactoryGirl.create(:user)
@product = FactoryGirl.create(:product)
@review = FactoryGirl.create(:review, :user_id => @user.id, :product_id => @product.id)
login_as(@user, :scope => :user)
end
it 'adds a new review' do
visit product_path(@product)
click_on 'Add a Review'
fill_in 'Content', :with => 'This product is great!'
fill_in 'Rating', :with => 5
click_button 'Create Review'
expect(page).to have_content 'This product is great!'
end
it 'updates an existing review' do
visit product_path(@product)
click_on 'Edit'
fill_in 'Content', :with => 'This product is okay.'
click_button 'Update Review'
expect(page).to have_content 'This product is okay.'
end
end
|
require 'echoe'
Echoe.new('sshkeyproof') do |p|
p.author = "Andrew Snow"
p.email = 'andrew@modulus.org'
p.summary = 'Ruby gem to prove client has the other half of a keypair'
p.url = 'https://github.com/andys/sshkeyproof'
p.runtime_dependencies = ['sshkey']
end
|
require 'rails_helper'
RSpec.describe Product, type: :model do
describe "商品(product)的規格" do
let(:product) { Product.create!( :name => "book", :is_alive => true, :count => 1) }
it "新建一個商品時,有name,預設數量==1,商品狀態為在庫中" do
expect(product.name).to eq("book")
expect(product.count) == (1)
expect(product.status) == ("在庫中")
end
it "當商品數量為零時,商品狀態為已售完" do
product.count = 0
expect(product.is_alive) == false
end
end
end
|
class LanguageUsersController < ApplicationController
before_action :set_language_user, only: [:show, :edit, :update, :destroy]
before_action :check_language, only: [:update, :create]
before_action :authenticate_user!, only: [:update, :create, :destroy]
before_action :check_user, only: [:create]
before_action :convert_to_number, only: [:update]
# GET /language_users
# # GET /language_users.json
# def index
# @language_users = LanguageUser.all
# end
#
# # GET /language_users/1
# # GET /language_users/1.json
# def show
# end
#
# # GET /language_users/new
# def new
# @language_user = LanguageUser.new
# end
#
# # GET /language_users/1/edit
# def edit
# end
# POST /language_users
# POST /language_users.json
def create
@language_user = LanguageUser.new(language_user_params.except(:language,:language_user_id))
if @language_user.save
render json: { id: @language_user[:id] }
else
render json: { errors: @language_user.errors }
end
end
# PATCH/PUT /language_users/1
# PATCH/PUT /language_users/1.json
def update
if @language_user.update_attributes(language_user_params.except(:language_user_id, :language, :user_id))
render json: { status: :ok }
else
render json: { errors: @language_user.errors }
end
end
# DELETE /language_users/1
# DELETE /language_users/1.json
def destroy
@language_user.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_language_user
@language_user = LanguageUser.find(language_user_params[:language_user_id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def language_user_params
@language_user_params ||= params.require(:language_user).permit(:language, :language_id , :user_id, :level, :language_user_id)
end
def check_language
@language_id = Language.find_by(name: language_user_params[:language])
@language_user_params[:language_id] = @language_id[:id]
end
def check_user
@user_id = session["warden.user.user.key"][0][0]
@language_user_params[:user_id] = @user_id
end
def convert_to_number
hash=LanguageUser.levels
level=hash[language_user_params[:level]]
@language_user_params[:level] = level
end
end
|
class AddAverageWordCountToProductStat < ActiveRecord::Migration
def self.up
ProductStat.reset_column_information
unless ProductStat.columns.map(&:name).include?('average_word_count')
add_column :product_stats, :average_word_count, :integer, :default => 0
end
end
def self.down
ProductStat.reset_column_information
if ProductStat.columns.map(&:name).include?('average_word_count')
remove_column :product_stats, :average_word_count
end
end
end
|
# Mostrar 1-255
# Escriba un programa que muestre todos los números del 1 al 255.
def printRange
(1..255).each { |n| puts n }
end
printRange()
# Mostrar números impares entre 1 y 255
# Escriba un programa que muestre todos los números impares del 1 al 255.
def printEven
(1..255).each { |n| puts n if n % 2 != 0 }
end
printEven()
# Muestre la suma
# Escriba un programa que muestre los números del 0 al 255, pero esta vez, muestre también la suma de los números que se han mostrado hasta el momento.
def showSuma
sum = 0
(0..255).each { |n|
sum = sum + n
puts "Nuevo numero: #{n} Suma: #{sum}"
}
end
showSuma()
# Recorriendo un arreglo
# Dado un arreglo X, digamos [1, 3, 5, 7, 9, 13], escriba un programa que recorra cada elemento del arreglo y muestre su valor. Ser capaz de recorrer cada elemento de un arreglo es sumamente importante.
def showArrayItems(array)
array.each { |item| puts item }
end
showArrayItems([1, 3, 5, 7, 9, 13])
# Encontrar el máximo
# Escriba un programa (un conjunto de instrucciones) que tome cualquier arreglo y muestre el valor máximo del arreglo. Tu programa debe funcionar también con arreglos que tengan todos los números negativos (ejemplo [-3, -5, -7]), o incluso una combinación con números positivos, negativos y cero.
def findMax (array)
max = array.max
puts max
end
findMax([1, 3, 5, 7, 9, 13])
findMax([-3, -5, -7])
# Promedio
# Escriba un programa que tome un arreglo y muestre el PROMEDIO de los valores del arreglo. Por ejemplo para el arreglo [2, 10, 3] tu programa debe mostrar un promedio de 5. De nuevo, asegúrate de crear un caso base y escribe las instrucciones para resolver este caso primero, luego ejecuta tus instrucciones para otros casos más complicados. Puedes utilizar la función length para esta actividad.
def findAvrg(array)
sum = 0
array.each { |item| sum = sum + item }
return sum / array.length
end
puts findAvrg([2, 10, 3])
# Arreglo con números impares
# Escriba un programa que cree un arreglo "y" que contenga todos los números impares entre 1 y 255. Cuando el programa se complete, "y" debe tener los valores de [1, 3, 5, 7, ... 255].
def getEvenNumbersFrom
return (1..255).select(&:odd?)
end
puts getEvenNumbersFrom
# Mayor que Y
# Escriba un programa que tome un arreglo y devuelva la cantidad de números que son mayores a un valor dado Y. Por ejemplo si el arreglo es [1, 3, 5, 7] y Y = 3, después de ejecutar tu programa debe mostrar 2 (debido a que hay 2 valores en el arreglo que son mayores a 3).
def getNumberOfMajorsFrom(array, number)
majors = 0
array.each do |item|
majors += 1 if item>number
end
return majors
end
p getNumberOfMajorsFrom([1, 3, 5, 7], 3)
# Elevar al cuadrado
# Dado un arreglo x, digamos [1, 5, 10, -2], cree un algoritmo (un conjunto e instrucciones) que multiplique cada valor en el arreglo por si mismo. Cuando el programa termine, el arreglo x debe tener valores que han sido elevados al cuadrado, es decir [1, 25, 100, 4].
def transformItemsToSquares(array)
array.each_with_index do |item, index|
array[index] = item * item
end
return array
end
p transformItemsToSquares([1, 5, 10, -2])
# Eliminar números negativos
# Dado un arreglo x, digamos [1, 5, 10, -2], cree un algoritmo que reemplace cualquier número negativo con 0. Cuando el programa termine, x no debe tener valores negativos, es decir [1, 5, 10, 0].
def transforNegativeItemsToCero(array)
array.each_with_index do |item, index|
array[index]=0 if item<0
end
return array
end
p transforNegativeItemsToCero([1, 5, 10, -2])
# Max, Min, y Promedio
# Dado un arreglo x, digamos [1, 5, 10, -2], cree un algoritmo que devuelva un hash con el valor máximo, el valor mínimo y el promedio de los valores en el arreglo.
def getMaxMinAvgFrom(array)
max = array.max
min = array.min
avg = array.inject{ |sum, el| sum + el }.to_f / array.size
return [max, min, avg]
end
p getMaxMinAvgFrom([1, 5, 10, -2])
p getMaxMinAvgFrom([2, 4, 6, 8])
# Cambiar los valores en el arreglo
# Dado un arreglo x, cree un algoritmo que cambie cada número del arreglo por el número que hay en la siguiente posición. Por ejemplo, dado el arreglo [1, 5, 10, 7, -2], cuando el programa termine, este arreglo debe ser [5, 10, 7, -2, 0].
def changeValuesForNexItem(array)
newArray = []
array.each_with_index do |item, index|
array[index+1] != nil ? newArray[index]=array[index+1] : newArray[index]=0
end
return newArray
end
p changeValuesForNexItem([1, 5, 10, 7, -2])
# Números a cadenas
# Escriba un programa que tome un arreglo de números y reemplace cualquier número negativo con la palabra "Dojo". Por ejemplo, dado el arreglo x = [-1, -3, 2], después que el programa haya terminado, ese arreglo debe ser ['Dojo', 'Dojo', 2].
def changeNegativesToDojo(array)
array.each_with_index do |item, index|
array[index] = 'Dojo' if array[index] < 0
end
return array
end
p changeNegativesToDojo([-1, -3, 2])
|
module DataMapper
module Model
class DescendantSet
include Enumerable
# Append a model as a descendant
#
# @param [Model] model
# the descendant model
#
# @return [DescendantSet]
# self
#
# @api private
def <<(model)
@descendants << model unless @descendants.include?(model)
@ancestors << model if @ancestors
self
end
# Iterate over each descendant
#
# @yield [model]
# iterate over each descendant
# @yieldparam [Model] model
# the descendant model
#
# @return [DescendantSet]
# self
#
# @api private
def each
@descendants.each { |model| yield model }
self
end
# Remove a descendant
#
# Also removed the descendant from the ancestors.
#
# @param [Model] model
# the model to remove
#
# @return [Model, NilClass]
# the model is return if it is a descendant
#
# @api private
def delete(model)
@ancestors.delete(model) if @ancestors
@descendants.delete(model)
end
# Return an Array representation of descendants
#
# @return [Array]
# the descendants
#
# @api private
def to_ary
@descendants.dup
end
private
# Initialize a DescendantSet instance
#
# @param [Model] model
# the base model
# @param [DescendantSet] ancestors
# the ancestors to notify when a descendant is added
#
# @api private
def initialize(model = nil, ancestors = nil)
@descendants = []
@ancestors = ancestors
@descendants << model if model
end
end
end
end
|
class RenameLatLongToFlat < ActiveRecord::Migration[5.2]
def change
rename_column :flats, :lat, :latitude
rename_column :flats, :long, :longitude
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
# Part.destroy_all
# Employee.destroy_all
# Warehouse.destroy_all
warehouse = Warehouse.create(city: "Seattle", location_code: "SEA-00002")
Warehouse.create(city: "Denver", location_code: "DEN-00002")
Warehouse.create(city: "Chicago", location_code: "CHI-00002")
Warehouse.create(city: "Portland", location_code: "POR-00002")
Warehouse.create(city: "Phoenix", location_code: "PHO-00001")
Warehouse.create(city: "Williamsburg", location_code: "WIL-00001")
Warehouse.create(city: "Northport", location_code: "NOR-00001")
Employee.create(first_name: "Dr. Barnaby", last_name: "Van Nostram", employee_id: 1, password: "password", is_manager: true, warehouse: warehouse)
manager = Employee.create(first_name: "Dr", last_name: "Rutherford", employee_id: 0000, password: "commissioner", is_manager: true, warehouse: warehouse)
manager2 = Employee.create(first_name: "Manager Rubenstein", last_name: "Smith", employee_id: 0005, password: "rubes", is_manager: true, warehouse: warehouse)
Employee.create(first_name: "Jules", last_name: "Dr", employee_id: 0001, password: "propulsion", is_manager: false, warehouse: warehouse)
Part.create!(name: "o-ring", part_no: 35466, warehouse_id: 1, received_by_id: 2, removed: false)
20.times { Part.create!(name: "beaker", part_no: 20001, warehouse_id: [1,2,3,4,5,6,7].sample, received_by_id: [1,2].sample, removed: false) }
20.times { Part.create!(name: "thruster", part_no: 69021, warehouse_id: [1,2,3,4,5,6,7].sample, received_by_id: [1,2].sample, removed: false) }
20.times { Part.create!(name: "fan", part_no: 86951, warehouse_id: [1,2,3,4,5,6,7].sample, received_by_id: [1,2].sample, removed: false) }
20.times { Part.create!(name: "cooling unit", part_no: 45862, warehouse_id: [1,2,3,4,5,6,7].sample, received_by_id: [1,2].sample, removed: false) }
20.times { Part.create!(name: "safety blanket", part_no: 35486, warehouse_id: [1,2,3,4,5,6,7].sample, received_by_id: [1,2].sample, removed: false) }
20.times { Part.create!(name: "oxygen tank", part_no: 57114, warehouse_id: [1,2,3,4,5,6,7].sample, received_by_id: [1,2].sample, removed: false) }
20.times { Part.create!(name: "liquid nitrogen", part_no: 96587, warehouse_id: [1,2,3,4,5,6,7].sample, received_by_id: [1,2].sample, removed: false) }
order1 = Order.create(description: "new parts for rocket", warehouse_id: 1, employee: manager)
order2 = Order.create(description: "new parts for superloop", warehouse_id: 2, employee: manager2)
order3 = Order.create(description: "Jules private experiment", warehouse_id: 1, employee: manager)
order1.parts << Part.create!(name: "beaker", part_no: 20001, removed: false, warehouse_id: 1)
order1.parts << Part.create!(name: "thruster", part_no: 69021, removed: false, warehouse_id: 1)
order1.parts << Part.create!(name: "oxygen tank", part_no: 57114, removed: false, warehouse_id: 1)
order2.parts << Part.create!(name: "beaker", part_no: 20001, removed: false, warehouse_id: 1)
order2.parts << Part.create!(name: "fan", part_no: 86951, removed: false, warehouse_id: 1)
order2.parts << Part.create!(name: "safety blanket", part_no: 35486, removed: false, warehouse_id: 1)
order3.parts << Part.create!(name: "safety blanket", part_no: 35486, removed: false, warehouse_id: 1)
order3.parts << Part.create!(name: "goggles", part_no: 20034, removed: false, warehouse_id: 1)
order3.parts << Part.create!(name: "tubes", part_no: 77001, removed: false, warehouse_id: 1)
|
class ApplicationController < ActionController::Base
layout :layout_method
private
def layout_method
if login_user_signed_in?
"layout1"
else
"layout2"
end
end
end |
class Calculator::WeightRate < Calculator
preference :base_weight, :decimal, :default => 0
preference :base_cost, :decimal, :default => 0
preference :rate_per_unit, :decimal, :default => 0
def self.description
"Weigh based"
#I18n.t("weight_based")
end
def self.unit
"Weight Unit"
#I18n.t('weight_unit')
end
def self.register
super
Coupon.register_calculator(self)
ShippingMethod.register_calculator(self)
ShippingRate.register_calculator(self)
end
# as object we always get line items, as calculable we have Coupon, ShippingMethod or ShippingRate fixed
def compute(order_or_line_items)
line_items = order_or_line_items.is_a?(Order) ? order_or_line_items.line_items : order_or_line_items
total_weight = line_items.map{|li|
(li.variant.weight || self.preferred_default_weight) * li.quantity
}.sum
get_rate(total_weight) || self.preferred_default_amount
end
def get_rate(value)
if value <= self.preferred_base_weight
self.preferred_base_cost
else
base_cost = self.preferred_base_cost
extra_weight = value - self.preferred_base_weight
base_cost + (extra_weight.ceil * self.preferred_rate_per_unit)
end
end
def available?(order_or_line_items)
line_items = order_or_line_items.is_a?(Order) ? order_or_line_items.line_items : order_or_line_items
total_weight = line_items.map{|li|
(li.variant.weight || self.preferred_default_weight) * li.quantity
}.sum
if total_weight <= 1.5 then
return false
else
return true
end
end
end |
class Vote < ApplicationRecord
belongs_to :post
belongs_to :user
enum direction: {down: 0, up: 1}
validates:user_id, uniqueness: {scrope: :post_id}
end
|
# Create a person class with at least 2 attributes and 2 behaviors.
# Call all person methods below the class and print results
# to the terminal that show the methods in action.
class Person
attr_accessor :name, :hair_color, :eye_color
def initialize(n, h, e)
@name = n
@hair_color = h
@eye_color = e
end
def color_contacts(c)
self.eye_color = c
end
def description
puts "#{name.capitalize} has #{hair_color} hair, and #{eye_color} eyes"
end
end
erika = Person.new("erika", "brown", "green")
erika.description
erika.color_contacts("purple")
puts erika.eye_color
erika.description
|
Given(/^I am on an article page$/) do
step 'I view an article in English'
end
When(/^I scroll to the bottom of the page$/) do
page.execute_script "window.scrollBy(0,10000)"
end
When(/^I dismiss the newsletter$/) do
home_page.sticky_newsletter.close_button.trigger('click')
page.driver.set_cookie('_cookie_dismiss_newsletter', 'hide')
end
When(/^user subscribes to receive newsletters$/) do
allow_any_instance_of(Core::NewsletterSubscriptionCreator).to receive(:call).and_return( true )
article_page.sticky_newsletter.subscription_email.set 'test@example.com'
article_page.sticky_newsletter.send_me_money_advice.click
page.driver.browser.set_cookie('_cookie_submit_newsletter = hide')
expect(page).to have_content I18n.t('newsletter_subscriptions.success')
end
Then(/^I should see the newsletter form$/) do
expect(home_page).to have_sticky_newsletter
end
Then(/^I should not see the newsletter form$/) do
step 'I visit the website'
expect(home_page).to have_no_sticky_newsletter
end
|
require 'spec_helper'
module Oauth2Provider
describe Client do
before { @client = FactoryGirl.create(:client) }
subject { @client }
it { should validate_presence_of(:name) }
it { should validate_presence_of(:uri) }
it { VALID_URIS.each{|uri| should allow_value(uri).for(:uri) } }
it { should validate_presence_of(:created_from) }
it { VALID_URIS.each{|uri| should allow_value(uri).for(:created_from) } }
it { should validate_presence_of(:redirect_uri) }
it { VALID_URIS.each{|uri| should allow_value(uri).for(:redirect_uri) } }
its(:secret) { should_not be_nil }
it ".granted!" do
lambda{ subject.granted! }.should change{ subject.granted_times }.by(1)
end
it ".revoked!" do
lambda{ subject.revoked! }.should change{ subject.revoked_times }.by(1)
end
it { should_not be_blocked }
context "#block!" do
before { @authorization = FactoryGirl.create(:oauth_authorization) }
before { @another_authorization = FactoryGirl.create(:oauth_authorization, client_uri: ANOTHER_CLIENT_URI) }
before { @token = FactoryGirl.create(:oauth_token) }
before { @another_token = FactoryGirl.create(:oauth_token, client_uri: ANOTHER_CLIENT_URI) }
before { subject.block! }
it { should be_blocked }
it { @authorization.reload.should be_blocked }
it { @another_authorization.reload.should_not be_blocked }
it { @token.reload.should be_blocked }
it { @another_token.reload.should_not be_blocked }
context "#unblock!" do
before { subject.unblock! }
it { should_not be_blocked }
it { @authorization.reload.should be_blocked }
it { @token.reload.should be_blocked }
end
end
context "#destroy" do
subject { FactoryGirl.create(:client) }
before do
Authorization.destroy_all
3.times { FactoryGirl.create(:oauth_authorization) }
Token.destroy_all
3.times { FactoryGirl.create(:oauth_token) }
end
it "should remove related authorizations" do
lambda{ subject.destroy }.should change{
Authorization.all.size
}.by(-3)
end
it "should remove related tokens" do
lambda{ subject.destroy }.should change{
Token.all.size
}.by(-3)
end
end
context ".sync_clients_with_scope" do
before { Client.destroy_all }
before { Scope.destroy_all }
before { @client = FactoryGirl.create(:client) }
before { @read_client = FactoryGirl.create(:client_read) }
before { @scope = FactoryGirl.create(:scope_pizzas_all) }
before { @scope_read = FactoryGirl.create(:scope_pizzas_read, values: ["pizzas/show"]) }
before { Client.sync_clients_with_scope("pizzas/read") }
context "with indirect scope" do
subject { @client.reload.scope_values }
it { should include "pizzas/show" }
it { should include "pizzas/create" }
it { should include "pizzas/update" }
it { should include "pizzas/destroy" }
it { should_not include "pizzas/index" }
end
context "with direct scope" do
subject { @read_client.reload.scope_values }
it { should include "pizzas/show" }
it { should_not include "pizzas/index" }
end
end
end
end
|
class AddModerationStatusToEducations < ActiveRecord::Migration
def change
add_column :educations, :moderation_status, :integer, default: 1
end
end
|
class RemoveMeritFieldsFrom<%= table_name.camelize %> < ActiveRecord::Migration<%= migration_version %>
def self.up
remove_column :<%= table_name %>, :sash_id
remove_column :<%= table_name %>, :level
end
end
|
# frozen_string_literal: true
require "rails_helper"
RSpec.describe RideCreator do
shared_examples_for "creates valid ride" do
it "calls #create_ride" do
expect_any_instance_of(described_class).to receive(:create_ride)
subject
end
it "creates a ride" do
expect { subject }.to change { Ride.count }.by(1)
end
it "creates the valid ride", :aggregate_failures do
subject
ride = Ride.last
expect(ride.car).to eq(car)
expect(ride.driver).to eq(user)
expect(ride.start_date).to be_within(2.seconds).of(params[:start_date].to_datetime)
expect(ride.price).to eq(params[:price])
expect(ride.currency).to eq(params[:currency])
expect(ride.places).to eq(params[:places])
end
end
shared_examples_for "returns ride" do
it { is_expected.to be_instance_of(Ride) }
end
let(:valid_params) do
{
start_location_country: "Poland",
start_location_address: "Wrocław, Poland",
start_location_latitude: 51.1078852,
start_location_longitude: 17.0385376,
destination_location_country: "Poland",
destination_location_address: "Opole, Poland",
destination_location_latitude: 50.6751067,
destination_location_longitude: 17.9212976,
places: 5,
start_date: 10.days.from_now.to_s,
price: 12,
currency: "pln",
car_id: car.id,
}
end
let(:user) { create(:user) }
let(:car) { create(:car, user: user) }
describe "#call" do
subject { described_class.new(user, params).call }
context "when params are valid" do
let(:params) { valid_params }
context "when start location and destination location exist" do
let!(:location1) do
create(:location, latitude: valid_params[:start_location_latitude],
longitude: valid_params[:start_location_longitude])
end
let!(:location2) do
create(:location, latitude: valid_params[:destination_location_latitude],
longitude: valid_params[:destination_location_longitude])
end
it_behaves_like "creates valid ride"
it_behaves_like "returns ride"
it "does NOT create locations" do
expect { subject }.not_to change { Location.count }
end
it "creates ride with valid locations", :aggregate_failures do
subject
ride = Ride.last
expect(ride.start_location).to eq(location1)
expect(ride.destination_location).to eq(location2)
end
end
context "when start location and destination location do NOT exist" do
it_behaves_like "creates valid ride"
it_behaves_like "returns ride"
it "creates 2 new locations" do
expect { subject }.to change { Location.count }.by(2)
end
it "creates ride with valid locations", :aggregate_failures do
subject
ride = Ride.last
expect(ride.start_location.longitude).to eq(params[:start_location_longitude])
expect(ride.destination_location.longitude).to eq(params[:destination_location_longitude])
end
end
end
context "when params are NOT valid" do
let(:params) { valid_params.except(:start_date) }
it_behaves_like "returns ride"
it "does NOT create a ride" do
expect { subject }.not_to change { Ride.count }
end
end
context "when user is not present" do
let(:params) { valid_params }
let(:user) { nil }
it "does NOT call #create_ride" do
expect_any_instance_of(described_class).not_to receive(:create_ride)
subject
end
it { is_expected.to be(nil) }
end
end
end
|
class AddOnestopIdToStops < ActiveRecord::Migration[5.0]
def change
add_column :stops, :onestop_id, :string
add_index :stops, :onestop_id
end
end
|
class AddArchivalFieldsToItems < ActiveRecord::Migration
def change
add_column :items, :creator, :string
add_column :items, :date, :date
add_column :items, :rights_information, :text
end
end
|
# == Schema Information
#
# Table name: evaluations
#
# id :integer not null, primary key
# thought_morals :text
# upright_incorruptiable :text
# duties :text
# created_at :datetime not null
# updated_at :datetime not null
# evaluation_totality :integer
# self_evaluation_id :integer
# user_id :integer
# already_edited :boolean default(FALSE)
# evaluating_user_type :string
# activity_id :integer
#
FactoryGirl.define do
# factory :evaluation do
# thought_morals "thought_morals"
# upright_incorruptiable "upright_incorruptiable"
# duties "duties"
# evaluation_totality 90
# created_at '2016-10-2 15:29:57'
# updated_at '2016-11-2 15:29:57'
# end
factory :evaluation do
thought_morals '思想政治态度*,*95*;*道德作风品行*,*85*;*团结协调合作*,*75'
upright_incorruptiable '廉洁从政*,*65*;*执行党风廉政建设责任制*,*55'
duties '项目1*,*80*;*项目2*,*70*;*项目3*,*60*;*项目4*,*90'
evaluation_totality 90
created_at '2016-10-2 15:29:57'
updated_at '2016-11-2 15:29:57'
end
end
|
class UsersController < ApplicationController
before_filter :signed_in_user, only: [:edit, :update]
before_filter :correct_user, only: [:edit, :update]
# GET /users
# GET /users.json
def index
@exercise_types = ExerciseType.all
@users = User.all
@goals = Goal.order("progress DESC").where(completed_date: nil)
respond_to do |format|
format.html # index.html.erb
format.json { render json: @users }
end
end
# GET /users.json
def list
@users = User.all(:order => 'name ASC')
respond_to do |format|
format.html # index.html.erb
format.json { render json: @users }
end
end
# GET /users/1
# GET /users/1.json
def show
@user = User.find(params[:id])
@exercise_types = ExerciseType.all
@exercises = @user.exercises.paginate(page: params[:page]).order("exercise_date DESC")
respond_to do |format|
format.html # show.html.erb
format.json { render json: @user }
end
end
# GET /users/new
# GET /users/new.json
def new
@user = User.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @user }
end
end
# GET /users/1/edit
def edit
@user = User.find(params[:id])
end
# POST /users
# POST /users.json
def create
@user = User.new(params[:user])
respond_to do |format|
if @user.save
sign_in @user
format.html { redirect_to @user, notice: 'Welcome to RunKeeper Challenge!' }
format.json { render json: @user, status: :created, location: @user }
else
format.html { render action: "new" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# PUT /users/1
# PUT /users/1.json
def update
@user = User.find(params[:id])
params[:user].delete(:password) if params[:user][:password].blank?
params[:user].delete(:avatar) if params[:user][:avatar].blank?
respond_to do |format|
if @user.update_attributes(params[:user])
format.html { redirect_to @user, notice: 'Profile updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# PUT /users
# PUT /users
def update_multiple
User.update(params[:user].keys, params[:user].values)
flash[:notice] = 'Users successfully updated'
redirect_to :action => "list"
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
@user = User.find(params[:id])
@user.destroy
respond_to do |format|
format.html { redirect_to users_url }
format.json { head :no_content }
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
# Before filters
def correct_user
@user = User.find(params[:id])
redirect_to(root_url) unless current_user?(@user)
end
end
|
FactoryGirl.define do
factory :experience do
location_id 1
name 'Barbecue at Mom\'s'
description 'It\'s not very far away, so you won\'t need the Airstream.'
location
user
distance 30.00
end
end
|
class CreateSwProjectCustomerQnaxUserRoles < ActiveRecord::Migration
def change
create_table :sw_project_customer_qnax_user_roles do |t|
t.integer :project_info_id
t.string :name
t.text :brief_note
t.integer :last_updated_by_id
t.string :for_department
t.timestamps
end
add_index :sw_project_customer_qnax_user_roles, :project_info_id
add_index :sw_project_customer_qnax_user_roles, :name
end
end
|
# ActsAsLoggable
module Acts #:nodoc:
module Loggable #:nodoc:
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def acts_as_loggable
has_many :logs, :as => :loggable, :dependent => :destroy, :order => 'created_at DESC, id DESC'
include Acts::Loggable::InstanceMethods
extend Acts::Loggable::SingletonMethods
end
end
# This module contains class methods
module SingletonMethods
# Helper method to lookup for loggable_types for a given object.
# This method is equivalent to obj.logs.
def find_logs_for(obj)
loggable = ActiveRecord::Base.send(:class_name_of_active_record_descendant, self).to_s
Log.find(:all,
:conditions => ["loggable_id = ? and loggable_type = ?", obj.id, loggable],
:order => "created_at DESC, id DESC"
)
end
#finds all logs related to this obj. checks loggable, and owner, and user (if obj is a user class)
# Helper class method to lookup logs for
# the mixin loggable type written by a given user.
# This method is NOT equivalent to Log.find_logs_for_user
def find_logs_by_user(user)
loggable = ActiveRecord::Base.send(:class_name_of_active_record_descendant, self).to_s
Log.find(:all,
:conditions => ["user_id = ? and loggable_type = ?", user.id, loggable],
:order => "created_at DESC, id DESC"
)
end
end
# This module contains instance methods
module InstanceMethods
# Helper method to sort logs by date
def logs_ordered_by_submitted
Log.find(:all,
:conditions => ["loggable_id = ? and loggable_type = ?", id, self.type.name],
:order => "created_at DESC, id DESC"
)
end
# Helper method that defaults the submitted time.
def add_log(log)
logs << log
end
def related_logs(limit=nil, order="created_at DESC, id DESC")
type = ActiveRecord::Base.send(:class_name_of_active_record_descendant, self.class).to_s
conditions = "(loggable_id=#{self.id} and loggable_type='#{type}') or (owner_id=#{self.id} and owner_type='#{type}')"
conditions << " or user_id=#{self.id}" if type == "User"
Log.find(:all, :conditions => conditions, :order => order, :limit => limit)
end
end
end
end
|
class WorkspaceChannel < ApplicationCable::Channel
def subscribed
stream_for "workspace_channel"
end
def speak(data)
new_message = data["message"]
@socket_message = Message.create(new_message)
WorkspaceChannel.broadcast_to("workspace_channel", @socket_message)
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
|
class JoinCartItemsController < ApplicationController
before_action :set_cart, only: [:create, :destroy]
before_action :authenticate_user!, only: [:create, :destroy]
def create
chosen_item = Item.find(params[:item_id])
current_cart = @current_cart
if !current_cart.items.include?(chosen_item)
@join_cart_item = JoinCartItem.new
@join_cart_item.cart = current_cart
@join_cart_item.item = chosen_item
end
@join_cart_item.save
redirect_to root_path
flash[:success] = "L'article a bien été ajouté au panier"
end
def destroy
@join_cart_item = JoinCartItem.find(params[:id])
@join_cart_item.destroy
redirect_to cart_path(@current_cart)
end
private
def join_cart_item_params
params.require(:join_cart_item_params).permit(:item_id, :cart_id)
end
end
|
class JobPostsController < ApplicationController
skip_before_filter :authorize
# GET /job_posts
def index
@job_posts = JobPost.all
end
# GET /job_posts/1
def show
@job_post = JobPost.find(params[:id])
end
# GET /job_posts/new
def new
@job_post = JobPost.new
end
# GET /job_posts/1/edit
def edit
@job_post = JobPost.find(params[:id])
end
# POST /job_posts
def create
@job_post = JobPost.new(params[:job_post])
# logger.info @job_post.inspect
# logger.info @job_post.valid?
# logger.info @job_post.errors.inspect
if @job_post.save
redirect_to(@job_post, :notice => 'Your job post was successfully created.')
else
render :action => "new"
end
end
# PUT /job_posts/1
def update
@job_post = JobPost.find(params[:id])
if @job_post.update_attributes(params[:job_post])
redirect_to(@job_post, :notice => 'Your job post was successfully updated.')
else
render :action => "edit"
end
end
# DELETE /job_posts/1
def destroy
@job_post = JobPost.find(params[:id])
@job_post.destroy
redirect_to(job_posts_url)
end
end |
module ManageIQ
module Providers
module Kubernetes
module ContainerManager::RefresherMixin
KUBERNETES_ENTITIES = [
{:name => 'pods'}, {:name => 'services'}, {:name => 'replication_controllers'}, {:name => 'nodes'},
{:name => 'endpoints'}, {:name => 'namespaces'}, {:name => 'resource_quotas'}, {:name => 'limit_ranges'},
{:name => 'persistent_volumes'}, {:name => 'persistent_volume_claims'},
# workaround for: https://github.com/openshift/origin/issues/5865
{:name => 'component_statuses', :default => []}
]
def fetch_entities(client, entities)
entities.each_with_object({}) do |entity, h|
begin
h[entity[:name].singularize] = client.send("get_#{entity[:name]}")
rescue KubeException => e
raise e if entity[:default].nil?
$log.warn("Unexpected Exception during refresh: #{e}")
h[entity[:name].singularize] = entity[:default]
end
end
end
def manager_refresh_post_processing(_ems, _target, inventory_collections)
indexed = inventory_collections.index_by(&:name)
container_images_post_processing(indexed[:container_images])
end
def container_images_post_processing(container_images)
# We want this post processing job only for batches, for the rest it's after_create hook on the Model
return unless container_images.saver_strategy == :batch
# TODO extract the batch size to Settings
batch_size = 100
container_images.created_records.each_slice(batch_size) do |batch|
container_images_ids = batch.collect { |x| x[:id] }
MiqQueue.submit_job(
:class_name => "ContainerImage",
:method_name => 'raise_creation_events',
:args => [container_images_ids],
:priority => MiqQueue::HIGH_PRIORITY
)
end
end
end
end
end
end
|
require 'http'
class Api::V1::ChaptersController < Api::V1::ApiBasicsController
include DeviseTokenAuth::Concerns::SetUserByToken
include NoCaching
include ChaptersApi
skip_before_action :authenticate_api_v1_user!, only: :show
def index
chapter_ids =
AreaChapterConfig.active.by_area(current_api_v1_user.area).pluck(:chapter_id)
if chapter_ids.present?
response = HTTP.get("#{base_path}?ids=#{chapter_ids.join(',')}")
render status: response.status, json: response.body.to_s
else
render json: []
end
end
def show
response = HTTP.get("#{base_path}/#{params[:id]}")
render status: response.status, json: response.body.to_s
end
def create
response =
HTTP.post(base_path,
headers: { 'Content-Type' => 'application/json' },
body: params.permit!.to_json)
if 201 == response.status
chapter = JSON.parse(response.body.to_s)
config =
ChapterConfig.new(
chapter_id: chapter['id'],
creator_id: current_api_v1_user.id,
last_modifier_id: current_api_v1_user.id,
active: true)
if config.save
area_config = AreaChapterConfig.new(area: current_api_v1_user.area, chapter_config_id: config.id)
if area_config.save
render status: response.status, json: chapter
return
end
end
end
# TODO: Handle errors!
render status: :unprocessable_entity
end
def update
response =
HTTP.patch("#{base_path}/#{params[:id]}",
headers: { 'Content-Type' => 'application/json' },
body: params.permit!.to_json)
if 200 == response.status
config = ChapterConfig.find_by(chapter_id: params[:id])
# TODO: Should we update the area on chapter update?
if config.update(last_modifier_id: current_api_v1_user.id)
render status: response.status, json: response.body.to_s
return
end
end
# TODO: Handle errors!
render status: :unprocessable_entity
end
def destroy
response = HTTP.delete("#{base_path}/#{params[:id]}")
if 204 == response.status
config = ChapterConfig.find_by(chapter_id: params[:id])
area_config = AreaChapterConfig.find_by(chapter_config_id: config.id)
if config.destroy && area_config.destroy
render status: response.status, json: response.body.to_s
return
end
# TODO: Handle errors!
end
# TODO: Handle errors!
render status: :unprocessable_entity
end
end
|
describe "GenreSelect" do
include ActionView::Helpers::TagHelper
include ActionView::Helpers::FormOptionsHelper
class Album
attr_accessor :genre
end
let(:album) { Album.new }
let!(:template) { ActionView::Base.new }
let(:builder) do
if defined?(ActionView::Helpers::Tags::Base)
ActionView::Helpers::FormBuilder.new(:album, album, template, {})
else
ActionView::Helpers::FormBuilder.new(:album, album, template, {}, Proc.new { })
end
end
let(:select_tag) do
<<-EOS.chomp.strip
<select id="genre" name="album[genre]">
EOS
end
it "finds and selects the genre value from the Model object" do
selected_tag = "selected=\"selected\">blues"
album.genre = "blues"
view = builder.genre_select(:genre)
expect(view).to include(selected_tag)
end
it "supports the select prompt" do
tag = '<option value="">Select genre</option>'
view = builder.genre_select(:genre, prompt: 'Select genre')
expect(view).to include(tag)
end
it "supports the include_blank option" do
tag = '<option value=""></option>'
view = builder.genre_select(:genre, include_blank: true)
expect(view).to include(tag)
end
end
|
class Contact < ActiveRecord::Base
attr_accessible :email, :name, :message
validates_presence_of :email, :message
end
|
module SchoolfinderApi
module Models
# GBD data
class Gbd < Base
# @return [String] The education.com logo image linking to www.education.com/schoolfinder.
attr_accessor :logosrc
# @return [String] Disclaimer text.
attr_accessor :disclaimer
# @return [String] A link to the corresponding school profile on education.com.
attr_accessor :lsp
# @return [String] A link to school search results page on education.com for the corresponding city and state.
attr_accessor :lsc
# @return [String] A link to the corresponding school profile on education.com.
attr_accessor :lsrs
# @return [String] A link to the corresponding school profile on education.com.
attr_accessor :lsr
# @return [String] A link to a district profile page when the optional parameter, districtid, is in use.
attr_accessor :lsd
protected
def parse
super
return if !success?
@logosrc = @parser.xpath('//logosrc').text
@disclaimer = @parser.xpath('//disclaimer').text
@lsp = @parser.xpath('//lsp').text
@lsc = @parser.xpath('//lsc').text
@lsrs = @parser.xpath('//lsrs').text
@lsr = @parser.xpath('//lsr').text
@lsd = @parser.xpath('//lsd').text
end
end
end
end |
class Car
attr_accessor :speed
def initialize
@speed = 0
end
def accelerate(speed)
@speed += speed
end
#write Car class code here
end
|
class Session < ActiveRecord::Base
attr_accessible :date, :number
has_many :votes, dependent: :destroy
has_many :assistances, dependent: :destroy
def name
I18n.t("sessions.name", number: self.number)
end
def generate_assistances!
Party.official_ids.each do |official_id|
scraper = Scraper::Assistances.new(self.number, official_id)
scraper.deputies.each do |deputy_assistance|
Assistance.create_from_scraper(self, deputy_assistance)
end
end
end
end |
class Room
def initialize(name, desc)
@name = name
@desc = desc
@exits = {}
@verbs = {}
@objects = {}
end
def update_exits(exitlist)
@exits.update(exitlist)
end
def update_verbs(verblist)
@verbs.update(verblist)
end
def update_objects(objlist)
@objects.update(objlist)
end
def get_exit(name)
return @exits[name]
end
def try_verb(verb)
@verbs.each do |verbKey, value|
if verbKey == verb then
return value
end
end
@objects.each do |oKey, obj|
if obj.try_verb(verb) then
return obj.try_verb(verb)
end
end
return false
end
def item_exists?(name)
@objects.has_key? name
end
def try_item_verb(verb, itemname)
end
attr_reader :name
attr_reader :desc
end |
class Plug::Nowplaying
include Virtus.model
attribute :dj, Plug::User
attribute :history_id, String
attribute :media, Plug::Media
attribute :playlist_id, Integer
attribute :timestamp, DateTime
attribute :votes, Hash[Integer => Integer]
attribute :grabs, Set[Integer]
def woot_count
votes.values.select { |x| x == 1 }.length
end
def meh_count
votes.values.select { |x| x == -1 }.length
end
def grab_count
grabs.length
end
def to_s
"#{media} djed by user #{dj}"
end
end
|
class Customer < ActiveRecord::Base
has_many :bills
has_many :review_books
has_many :orders
has_one :users
validates :lastname, presence: true
end
|
class AddReadersToCheckouts < ActiveRecord::Migration
def up
add_column :checkouts, :reader_id, :integer
Checkout.all.each do |checkout|
name = checkout.borrower
reader = Reader.find_by(full_name: name)
checkout.reader = reader
checkout.save!
end
change_column :checkouts, :reader_id, :integer, null: false
remove_column :checkouts, :borrower
end
def down
add_column :checkouts, :borrower, :string
Checkout.all.each do |checkout|
reader = checkout.reader
name = reader.full_name
checkout.borrower = name
checkout.save!
end
change_column :checkouts, :borrower, :string, null: false
remove_column :checkouts, :reader_id
end
end
|
require "singleton"
module Collmex
#
# Represents the configuration as an singleton object
# for your Collmex environment.
#
class Configuration
include Singleton
DEFAULTS = {
user: ENV["COLLMEX_USER"],
password: ENV["COLLMEX_PASSWORD"],
customer_id: ENV["COLLMEX_CUSTOMER_ID"],
csv_options: { col_sep: ";" }
}.freeze
attr_accessor(*DEFAULTS.keys)
def initialize
self.class::DEFAULTS.each do |key, val|
public_send("#{key}=", val)
end
end
end
end
|
require 'rails_helper'
RSpec.describe Rating, type: :model do
context "#validation" do
it "rate is from 1 to 5" do
rating = build(:rating)
rating.rate = 6
expect{rating.save!}.to raise_error(ActiveRecord::RecordInvalid)
end
it "user and movie combination is unique" do
existing_rating = create(:rating)
rating = Rating.new
rating.rate = 2
rating.user_id = existing_rating.user_id
rating.movie_id = existing_rating.movie_id
expect{rating.save!}.to raise_error(ActiveRecord::RecordInvalid)
end
end
end
|
include_recipe "php-fpm::prepare"
php_installed_version = `which php >> /dev/null && php -v|grep #{node["php-fpm"][:version]}|awk '{ print substr($2,1,5) }'`
php_prefix = node["php-fpm"][:prefix]
php_already_installed = lambda do
php_installed_version == node["php-fpm"][:version]
end
remote_file "/tmp/php-#{node["php-fpm"][:version]}.tgz" do
source "http://www.php.net/get/php-#{node["php-fpm"][:version]}.tar.gz/from/www.php.net/mirror"
checksum node["php-fpm"][:checksum]
not_if &php_already_installed
end
execute "PHP: unpack" do
command "cd /tmp && tar -xzf php-#{node["php-fpm"][:version]}.tgz"
not_if &php_already_installed
end
execute "PHP: ./configure" do
php_opts = []
php_opts << "--with-config-file-path=#{php_prefix}/etc"
php_opts << "--with-config-file-scan-dir=#{php_prefix}/etc/php"
php_opts << "--prefix=#{php_prefix}"
php_opts << "--with-pear=#{php_prefix}/pear"
php_exts = []
php_exts << "--enable-sockets"
php_exts << "--enable-soap"
php_exts << "--with-openssl"
php_exts << "--disable-posix"
php_exts << "--without-sqlite"
php_exts << "--without-sqlite3"
php_exts << "--with-mysqli=mysqlnd"
php_exts << "--disable-posix"
php_exts << "--disable-phar"
php_exts << "--disable-pdo"
php_exts << "--enable-pcntl"
php_exts << "--with-curl"
php_exts << "--with-tidy"
php_fpm = []
php_fpm << "--enable-fpm"
php_fpm << "--with-fpm-user=#{node["php-fpm"][:user]}"
php_fpm << "--with-fpm-group=#{node["php-fpm"][:group]}"
cwd "/tmp/php-#{node["php-fpm"][:version]}"
environment "HOME" => "/root"
command "./configure #{php_opts.join(' ')} #{php_exts.join(' ')} #{php_fpm.join(' ')}"
not_if &php_already_installed
end
# run with make -j4 cause we have 4 ec2 compute units
execute "PHP: make, make install" do
cwd "/tmp/php-#{node["php-fpm"][:version]}"
environment "HOME" => "/root"
command "make -j4 && make install"
not_if &php_already_installed
end
template "#{php_prefix}/etc/php.ini" do
mode "0755"
source "php.ini.erb"
owner node["php-fpm"][:user]
group node["php-fpm"][:group]
end
template "#{php_prefix}/etc/php-cli.ini" do
mode "0755"
source "php.ini.erb"
owner node["php-fpm"][:user]
group node["php-fpm"][:group]
end
template "/usr/local/etc/php-fpm.conf" do
mode "0755"
source "php-fpm.conf.erb"
owner node["php-fpm"][:user]
group node["php-fpm"][:group]
end
directory "#{php_prefix}/etc/php" do
owner "root"
group "root"
mode "0755"
action :create
end
template "/etc/init.d/php-fpm" do
mode "0755"
source "init.d.php-fpm.erb"
owner node["php-fpm"][:user]
group node["php-fpm"][:group]
end
service "php-fpm" do
service_name "php-fpm"
supports [:start, :status, :restart]
action :restart
end
template "/etc/logrotate.d/php" do
source "logrotate.erb"
mode "0644"
owner "root"
group "root"
end
include_recipe "php-fpm::apc"
include_recipe "php-fpm::xhprof"
|
require "rails_helper"
RSpec.describe Webview::DrugStocksController, type: :controller do
before do
Flipper.enable(:drug_stocks)
end
after do
Flipper.disable(:drug_stocks)
end
describe "GET #new" do
let(:facility) { create(:facility) }
it "renders 404 for anonymous users" do
expect {
get :new
}.to raise_error(ActiveRecord::RecordNotFound)
end
it "denies access for users without sync approval" do
user = create(:user, sync_approval_status: :denied)
params = {
access_token: user.access_token,
facility_id: facility.id,
user_id: user.id
}
get :new, params: params
expect(response).to be_forbidden
end
it "denies access for users with incorrect access token" do
user = create(:user)
params = {
access_token: SecureRandom.hex(20),
facility_id: facility.id,
user_id: user.id
}
get :new, params: params
expect(response).to be_unauthorized
end
end
describe "POST #create" do
let(:power_user) { create(:user) }
let(:facility_group) { create(:facility_group) }
it "denies access for users with incorrect access token" do
facility = create(:facility, facility_group: power_user.facility.facility_group)
protocol_drug = create(:protocol_drug, stock_tracked: true, protocol: facility.facility_group.protocol)
params = {
access_token: SecureRandom.hex(24),
facility_id: facility.id,
user_id: power_user.id,
for_end_of_month: Date.today.strftime("%b-%Y"),
drug_stocks: [{
protocol_drug_id: protocol_drug.id,
received: 10,
in_stock: 30
}],
redistributed_drugs: [{
protocol_drug_id: protocol_drug.id,
redistributed: 10
}]
}
expect {
post :create, params: params
}.to change { DrugStock.count }.by(0)
expect(response).to be_unauthorized
end
it "works with empty drug stock params" do
facility = create(:facility, facility_group: power_user.facility.facility_group)
_protocol_drug = create(:protocol_drug, stock_tracked: true, protocol: facility.facility_group.protocol)
params = {
access_token: power_user.access_token,
facility_id: facility.id,
user_id: power_user.id,
for_end_of_month: Date.today.strftime("%b-%Y")
}
expect {
post :create, params: params
expect(response).to be_redirect
}.to change { DrugStock.count }.by(0)
end
it "creates drug stock records and sends JSON success response" do
facility = create(:facility, facility_group: power_user.facility.facility_group)
protocol_drug = create(:protocol_drug, stock_tracked: true, protocol: facility.facility_group.protocol)
params = {
access_token: power_user.access_token,
facility_id: facility.id,
user_id: power_user.id,
for_end_of_month: Date.today.strftime("%b-%Y"),
drug_stocks: {
"0" => {
protocol_drug_id: protocol_drug.id,
received: 10,
in_stock: 30,
redistributed: 10
}
}
}
expect {
post :create, params: params
expect(response).to be_redirect
}.to change { DrugStock.count }.by(1)
stock = DrugStock.find_by!(protocol_drug: protocol_drug)
expect(stock.received).to eq(10)
end
it "sends error messages for invalid saves" do
facility = create(:facility, facility_group: power_user.facility.facility_group)
protocol_drug = create(:protocol_drug, stock_tracked: true, protocol: facility.facility_group.protocol)
params = {
access_token: power_user.access_token,
facility_id: facility.id,
user_id: power_user.id,
for_end_of_month: Date.today.strftime("%b-%Y"),
drug_stocks: {
"0" => {
protocol_drug_id: protocol_drug.id,
received: "invalid",
in_stock: "invalid",
redistributed: "invalid"
}
}
}
expect {
post :create, params: params
expect(response.status).to eq(422)
}.to change { DrugStock.count }.by(0)
expected = {
"status" => "invalid",
"errors" => "Validation failed: In stock is not a number, Received is not a number"
}
expect(JSON.parse(response.body)).to eq(expected)
end
end
end
|
require 'set'
class SpiralMovers
attr_reader :t
def initialize(initial_coordinates)
@movers = initial_coordinates.map { |x, y| Mover.new(Point.new(x, y)) }
@points_occupied = Set.new
record_positions
@t = 0
end
def move
loop do
@movers.each { |mover| mover.move }
remove_movers_moving_into_occupied_point
remove_movers_colliding_each_other
break if @movers.empty?
record_positions
@t += 1
end
end
private
def remove_movers_moving_into_occupied_point
@movers.delete_if { |mover| @points_occupied.include?(mover.position) }
end
def remove_movers_colliding_each_other
return if @movers.size <= 1
indexes_to_remove = []
0.upto(@movers.size - 1 - 1).each do |i|
(i + 1).upto(@movers.size - 1) do |j|
indexes_to_remove << i << j if @movers[i].position == @movers[j].position
end
end
indexes_to_remove.sort.reverse.each { |index| @movers.delete_at(index) }
end
def record_positions
@movers.each { |mover| @points_occupied << mover.position }
end
class Point
attr_reader :x, :y
def initialize(x, y)
@x = x
@y = y
end
def move_by(dx, dy)
Point.new(x + dx, y + dy)
end
def ==(other)
self.x == other.x && self.y == other.y
end
def eql?(other)
self.==(other)
end
def hash
[x, y].hash
end
def to_s
"(#{x},#{y})"
end
end
class Mover
def initialize(initial_point)
@point = initial_point
@spiral_movement = SpiralMovement.new
end
def position
@point
end
def move
@point = @point.move_by(*@spiral_movement.next_move)
end
def to_s
"@#{@point}"
end
end
# 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
# 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 ...
#-------------------------------------------------------
# R U L L D D R R R U U U L L L L D D D D R R R R R ...
# 1 1 1 2 1 2 1 2 3 1 2 3 1 2 3 4 1 2 3 4 1 2 3 4 5 ...
class SpiralMovement
RIGHT = [ 1, 0]
UP = [ 0, -1]
LEFT = [-1, 0]
DOWN = [ 0, 1]
def initialize
@next_steps = [1, 1, 2, 2]
@steps = 0
@direction = RIGHT
end
def next_move
if @steps == 0
@steps = @next_steps.shift
@next_steps << @steps + 2
end
@steps -= 1
@direction.tap { change_direction if @steps == 0 }
end
DIRECTION_ORDERS = [RIGHT, UP, LEFT, DOWN, RIGHT]
def change_direction
index = DIRECTION_ORDERS.index(@direction) + 1
@direction = DIRECTION_ORDERS[index]
end
end
end
if __FILE__ == $0
num_movers = gets.to_i
initial_coordinates = []
num_movers.times do
initial_coordinates << gets.split.map(&:to_i)
end
sm = SpiralMovers.new(initial_coordinates)
sm.move
puts sm.t
end
|
require 'test_helper'
class ShortUrlsShowTest < ActionDispatch::IntegrationTest
def setup
@admin = users(:cthulhu)
@short_url = short_urls(:hits_test)
log_in_as(@admin)
end
test 'shows slug as heading' do
get short_url_path(@short_url)
assert_select 'h2', @short_url.slug
end
test 'shows edit and delete buttons' do
get short_url_path(@short_url)
assert_select 'a[href=?]', edit_short_url_path(@short_url)
assert_select 'a[href=?]', delete_short_url_path(@short_url)
end
test 'shows stats' do
get short_url_path(@short_url)
assert_select 'div.short-url-stats', 1
assert_select 'div.short-url-stat', 2
assert_select 'span.stat-gloss', 2
assert_select 'span.stat-entry', 2
end
end
|
Rails.application.routes.draw do
resources :orders
mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
devise_for :users, skip: [:show], controllers: {
sessions: 'users/sessions',
passwords: 'users/passwords',
registrations: 'users/registrations'
}
root :to => 'products#index'
resources :order_items
resources :products
resource :cart, only: [:show]
resource :user, only: [:show, :index]
resources :categories
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
require File.expand_path(File.join(File.dirname(__FILE__), 'test_helper'))
class JSRegularExpressionLiteralTest < Test::Unit::TestCase
include TestHelper
def setup
@parser = JSRegularExpressionLiteralParser.new
end
def test_basic_regexp
assert_parsed '/foo/'
end
def test_basic_regexp_with_flag
assert_parsed '/foo/u'
end
def test_basic_regexp_with_flags
assert_parsed '/foo/ug'
end
def test_regexp_with_asterisk
assert_parsed '/.*/'
end
def test_regexp_with_backslash_sequences
assert_parsed '/\//'
assert_parsed '/\\\/'
assert_parsed '/\\\\/'
end
end
|
FactoryGirl.define do
factory :hyperlink do
url "http://guides.rubyonrails.org/"
body "*the* best rails resource"
end
end
|
class RemoteUsdtStandardOrder
attr_reader :id, :user_id, :order_price_type, :contract_code, :lever_rate, :volume, :direction
def initialize(id:, user_id:, contract_code:, lever_rate:, volume:, direction:)
@id = id
@user_id = user_id
@order_price_type = order_price_type
@contract_code = contract_code
@lever_rate = lever_rate
@volume = volume
@direction = direction
end
end |
#!/usr/bin/env ruby
# Script from Brandon to prefix a commit message with first part of the branch name you are on which should be the JIRA card ID
`git rev-parse --abbrev-ref HEAD`.strip =~ /^\S+\/(\w+?\-\w+)\-?.*/
system "commit -m '#{$1} #{ARGV[0]}'"
|
# frozen_string_literal: true
# rubocop:todo all
require 'lite_spec_helper'
describe Mongo::Srv::Result do
let(:result) do
described_class.new('bar.com')
end
describe '#add_record' do
context 'when incoming hostname is in mixed case' do
let(:record) do
double('record').tap do |record|
allow(record).to receive(:target).and_return('FOO.bar.COM')
allow(record).to receive(:port).and_return(42)
allow(record).to receive(:ttl).and_return(1)
end
end
it 'stores hostname in lower case' do
result.add_record(record)
expect(result.address_strs).to eq(['foo.bar.com:42'])
end
end
end
describe '#normalize_hostname' do
let(:actual) do
result.send(:normalize_hostname, hostname)
end
context 'when hostname is in mixed case' do
let(:hostname) { 'FOO.bar.COM' }
it 'converts to lower case' do
expect(actual).to eq('foo.bar.com')
end
end
context 'when hostname has one trailing dot' do
let(:hostname) { 'foo.' }
it 'removes the trailing dot' do
expect(actual).to eq('foo')
end
end
context 'when hostname has multiple trailing dots' do
let(:hostname) { 'foo..' }
it 'returns hostname unchanged' do
expect(actual).to eq('foo..')
end
end
end
end
|
FactoryGirl.define do
factory :destination do
name do
raise "don't call 'destination' factory directly, use one of the "\
"sub-factories"
end
end
trait :two_letter_code do
sequence(:code) do |n|
str = "AA"
(n - 1).times { str.next! }
str
end
end
trait :three_letter_code do
sequence(:code) do |n|
str = "AAA"
(n - 1).times { str.next! }
str
end
end
factory :region do
sequence(:name) { |n| "Region #{n}" }
# this will break if you try to create more than Region::CODES.length
# regions (because region codes must be unique), but we should be fine for now:
sequence(:code) { |n| Region::CODES[n % Region::CODES.length] }
end
factory :country do
sequence(:name) { |n| "Country #{n}" }
two_letter_code
association :parent, factory: :region
end
factory :city do
sequence(:name) { |n| "City #{n}" }
two_letter_code
association :parent, factory: :country
end
factory :airport do
name { Faker::Address.city }
three_letter_code
association :parent, factory: :city
end
end
|
class Store::Manager::Products::ReviewsController < ApplicationController
# GET /store/manager/products/reviews
# GET /store/manager/products/reviews.json
def index
@store_manager_products_reviews = Store::Manager::Products::Review.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @store_manager_products_reviews }
end
end
# GET /store/manager/products/reviews/1
# GET /store/manager/products/reviews/1.json
def show
@store_manager_products_review = Store::Manager::Products::Review.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @store_manager_products_review }
end
end
# GET /store/manager/products/reviews/new
# GET /store/manager/products/reviews/new.json
def new
@store_manager_products_review = Store::Manager::Products::Review.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @store_manager_products_review }
end
end
# GET /store/manager/products/reviews/1/edit
def edit
@store_manager_products_review = Store::Manager::Products::Review.find(params[:id])
end
# POST /store/manager/products/reviews
# POST /store/manager/products/reviews.json
def create
@store_manager_products_review = Store::Manager::Products::Review.new(params[:store_manager_products_review])
respond_to do |format|
if @store_manager_products_review.save
format.html { redirect_to @store_manager_products_review, notice: 'Review was successfully created.' }
format.json { render json: @store_manager_products_review, status: :created, location: @store_manager_products_review }
else
format.html { render action: "new" }
format.json { render json: @store_manager_products_review.errors, status: :unprocessable_entity }
end
end
end
# PUT /store/manager/products/reviews/1
# PUT /store/manager/products/reviews/1.json
def update
@store_manager_products_review = Store::Manager::Products::Review.find(params[:id])
respond_to do |format|
if @store_manager_products_review.update_attributes(params[:store_manager_products_review])
format.html { redirect_to @store_manager_products_review, notice: 'Review was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @store_manager_products_review.errors, status: :unprocessable_entity }
end
end
end
# DELETE /store/manager/products/reviews/1
# DELETE /store/manager/products/reviews/1.json
def destroy
@store_manager_products_review = Store::Manager::Products::Review.find(params[:id])
@store_manager_products_review.destroy
respond_to do |format|
format.html { redirect_to store_manager_products_reviews_url }
format.json { head :no_content }
end
end
end
|
require 'spec_helper'
require 'net/http'
describe AmberbitConfig do
describe "GET '/'" do
it 'environments from HTML content and settings should be equal' do
port = '5555'
envs = %w(test development production)
envs.each do |x|
ENV['RAILS_ENV'] = ENV['RACK_ENV'] = x
`rails s -d -p #{port} -e #{x}`
sleep 0.1
url = URI.parse("http://127.0.0.1:#{port}")
source = Net::HTTP.start(url.host, url.port) { |html| html.get('/').body }.split()[7]
pid = `lsof -i :#{port} | cut -d' ' -f 5`
pid = pid.strip.to_i
Process.kill(9, pid)
expect(source).to be == x.capitalize
end
ENV['RAILS_ENV'] = ENV['RACK_ENV'] = 'test'
end
end
end
|
class Spree::Page < ActiveRecord::Base
#Note: Attempted as decorator but default scope sorting messed up Page.rebuild!
#so had to override model completely
#Added the following
acts_as_nested_set
#Changed this for proper order
default_scope :order => "spree_pages.position ASC"
validates_presence_of :title
validates_presence_of [:slug, :body], :if => :not_using_foreign_link?
#Updated this to only show the root level items in header_links
scope :header_links, where(["show_in_header = ? and parent_id is NULL", true])
scope :footer_links, where(["show_in_footer = ? and parent_id is NULL", true])
scope :sidebar_links, where(["show_in_sidebar = ? and parent_id is NULL", true])
scope :visible, where(:visible => true)
before_save :update_positions_and_slug
attr_accessible :show_in_footer, :foreign_link, :parent_id, :show_in_sidebar, :body, :layout, :visible, :position, :slug, :meta_keywords, :show_in_header, :meta_title, :meta_description, :title
def initialize(*args)
super(*args)
last_page = Spree::Page.last
self.position = last_page ? last_page.position + 1 : 0
end
def link
foreign_link.blank? ? slug_link : foreign_link
end
def self.by_slug(slug)
slug = StaticPage::remove_spree_mount_point(slug) unless Rails.application.routes.url_helpers.spree_path == "/"
pages = self.arel_table
query = pages[:slug].eq(slug).or(pages[:slug].eq("/#{slug}"))
self.where(query)
end
private
def update_positions_and_slug
unless new_record?
return unless prev_position = Spree::Page.find(self.id).position
if prev_position > self.position
Spree::Page.update_all("position = position + 1", ["? <= position AND position < ?", self.position, prev_position])
elsif prev_position < self.position
Spree::Page.update_all("position = position - 1", ["? < position AND position <= ?", prev_position, self.position])
end
end
if not_using_foreign_link?
self.slug = slug_link
Rails.cache.delete('page_not_exist/' + self.slug)
end
return true
end
def not_using_foreign_link?
foreign_link.blank?
end
def slug_link
ensure_slash_prefix slug
end
def ensure_slash_prefix(str)
str.index('/') == 0 ? str : '/' + str
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.