text stringlengths 10 2.61M |
|---|
module Verbs
class Verb
attr_reader :infinitive, :preterite, :past_participle
def initialize(infinitive, options = {}, &blk)
@infinitive = infinitive
@forms = {}
if block_given?
yield self
else
@preterite = options[:preterite]
@past_participle = options[:past_participle]
end
end
def form(word, options = {})
raise ArgumentError, 'Irregular verb specifications must identify tense and must identify either derivative or person and plurality' unless options[:tense] and (options[:derivative] or (options[:person] and options[:plurality]))
tense = options[:tense]
@forms[:present] ||= {}
@forms[:past] ||= {}
if derivative = options[:derivative]
@forms[tense][derivative] = word
elsif person = options[:person]
@forms[tense][person] ||= {}
@forms[tense][person][options[:plurality]] = word
end
end
def [](options = {})
tense, person, plurality, derivative = options[:tense], options[:person], options[:plurality], options[:derivative]
if tense and person and plurality
@forms[tense].andand[person].andand[plurality]
elsif tense and derivative
@forms[tense].andand[derivative]
end
end
end
end
|
module Jobs
module ResourceMixIn
def resource model
model.https? ? secured_resource(model.url) : plain_resource(model.url)
end
def secured_resource url
RestClient::Resource.new url,
:ssl_client_cert => Identity.certificate.certificate,
:ssl_client_key => Identity.private_key,
:ssl_ca_file => File.join( Rails.root, 'certs', "beanca.crt" ),
:verify_ssl => OpenSSL::SSL::VERIFY_PEER
end
def plain_resource url
RestClient::Resource.new(url)
end
end
end
|
class ReportsController < ApplicationController
before_filter :admin_user
def index
@posts = Post.all.sort
@users = User.all.sort_by {|user| -user.posts.length }
end
def admin_user
@user = self.current_user
if !@user
redirect_to signin_path, notice: "Please sign in."
else
if !@user.isAdmin?
redirect_to posts_path, notice: "Action not permitted"
end
end
end
end
|
module Alf
module Operator::Relational
class Restrict < Alf::Operator()
include Operator::Relational, Operator::Unary
signature do |s|
s.argument :predicate, TuplePredicate, "true"
end
protected
# (see Operator#_each)
def _each
handle = TupleHandle.new
each_input_tuple{|t| yield(t) if @predicate.evaluate(handle.set(t)) }
end
end # class Restrict
end # module Operator::Relational
end # module Alf
|
class BaseActivity < ApplicationRecord
include Searchable
searchable name: { unaccent: true }
belongs_to :base_activity_type
enum tcc: { one: 'TCC 1', two: 'TCC 2' }, _prefix: :tcc
validates :name, presence: true, uniqueness: { case_sensitive: false }
validates :tcc, presence: true
def self.human_tccs
hash = {}
tccs.each_key { |key| hash[I18n.t("enums.tcc.#{key}")] = key }
hash
end
def self.get_by_tcc(type, term)
BaseActivity.search(term)
.order(:name)
.includes(:base_activity_type)
.where(tcc: type)
end
end
|
require 'spec_helper'
describe 'CspReport index view' do
describe 'Report data headers' do
before(:each) do
visit csp_reports_path
end
it 'should display the report id' do
page.should have_content 'ID'
end
it 'should display the report document URI' do
page.should have_content 'Document URI'
end
it 'should display the report referrer' do
page.should have_content 'Referrer'
end
it 'should display the report original policy' do
page.should have_content 'Server Policy'
end
it 'should display the report violated directive' do
page.should have_content 'Violated Directive'
end
it 'should display the report blocked URI' do
page.should have_content 'Blocked URI'
end
it 'should display the report incoming IP' do
page.should have_content 'Incoming IP'
end
it 'should display the report creation timestamp' do
page.should have_content 'Reported At'
end
it 'should display an Actions column' do
page.should have_content 'Actions'
end
end
describe 'Report data content' do
before(:each) do
@local_inline = FactoryGirl.create(:local_inline)
visit csp_reports_path
end
it 'should display the report id' do
page.should have_content @local_inline.id
end
it 'should display the report document URI' do
page.should have_content @local_inline.document_uri
end
it 'should display the report referrer' do
page.should have_content @local_inline.referrer
end
it 'should display the report original policy' do
page.should have_content @local_inline.original_policy
end
it 'should display the report violated directive' do
page.should have_content @local_inline.violated_directive
end
it 'should display the report blocked URI' do
page.should have_content @local_inline.blocked_uri
end
it 'should display the report incoming IP' do
page.should have_content @local_inline.incoming_ip
end
it 'should display the report creation timestamp' do
page.should have_content @local_inline.created_at
end
it 'should display a link to delete the report' do
page.should have_link 'Delete violation',
{href: csp_report_path(@local_inline.id)}
end
end
describe 'Delete All functionnality' do
it 'should make a "delete all" button available' do
visit csp_reports_path
page.should have_link "Delete All",
{href: csp_reports_destroy_all_path}
end
end
describe 'Links to data presentation' do
it 'should have a link to the report by IP' do
visit csp_reports_path
page.should have_link 'By IP'
end
it 'should have a link to the report by Rule' do
visit csp_reports_path
page.should have_link 'By Violated Directive'
end
it 'should have a link to the report by Source' do
visit csp_reports_path
page.should have_link 'By Source Document URI'
end
end
end
|
Date::DATE_FORMATS[:day_and_month] = lambda do |date|
date.strftime("#{date.day.ordinalize} %b")
end
|
class AnnotationSerializer
include FastJsonapi::ObjectSerializer
set_type :annotations
attribute :detail
attribute :annotation_category_id
attribute :created_at, if: Proc.new { |record, params| params.blank? || !params[:public] == true }
attribute :updated_at, if: Proc.new { |record, params| params.blank? || !params[:public] == true }
end
|
# Prepare dirs for capistrano deployment, similar to running `cap deploy:setup`
directory app.path do
owner app.user.name
group app.user.group
mode 0755
end
[app.releases_path, app.shared_path, app.log_path, app.system_path, app.run_path, app.init_path].each do |dir|
directory dir do
owner app.user.name
group app.user.group
mode 0775
end
end
directory app.config_path do
owner app.user.name
group app.user.group
mode 0700
end |
require 'spec_helper'
require 'typhoeus'
require 'rack'
require 'et_azure_insights'
require 'et_azure_insights/adapters/typhoeus'
require 'random-port'
RSpec.describe 'Typhoeus Integration' do
include_context 'with stubbed insights api'
around do |example|
begin
EtAzureInsights::Adapters::Typhoeus.setup
example.run
ensure
EtAzureInsights::Adapters::Typhoeus.uninstall
end
end
include_context 'insights call collector'
context '2 service chain' do
# Here, we will configure 2 rack applications
# Our test suite calls the first rack app using net/http with the tracking disabled (as we are not testing this part)
# The first rack app will call the second using typhoeus
#
include_context 'rack servers' do
rack_servers.register(:app1) do |env|
url = rack_servers.base_url_for(:app2)
Typhoeus.get(url)
[200, {}, ['OK from rack app 1 and rack app 2']]
end
rack_servers.register(:app2) do |env|
[200, {}, ['OK from rack app 2']]
end
end
it 'inform insights of the start of the chain' do
rack_servers.get_request(:app1, '/anything')
expected = a_hash_including 'ver' => 1,
'name' => 'Microsoft.ApplicationInsights.Request',
'time' => instance_of(String),
'sampleRate' => 100.0,
'tags' => a_hash_including(
'ai.internal.sdkVersion' => "rb:#{ApplicationInsights::VERSION}",
'ai.cloud.role' => 'fakerolename',
'ai.cloud.roleInstance' => 'fakeroleinstance',
'ai.operation.id' => match(/\A|[0-9a-f]{32}\./)
),
'data' => a_hash_including(
'baseType' => 'RequestData',
'baseData' => a_hash_including(
'ver' => 2,
'id' => match(/\A|[0-9a-f]{32}\./),
'duration' => instance_of(String),
'responseCode' => '200',
'success' => true,
'url' => "#{rack_servers.base_url_for(:app1)}/anything",
'name' => 'GET /anything',
'properties' => a_hash_including(
'httpMethod' => 'GET'
)
)
)
expect { insights_call_collector.flatten }.to eventually(include expected).pause_for(0.05).within(0.5)
end
it 'informs insights of the external dependency between app1 and app2' do
rack_servers.get_request(:app1, '/anything')
# @TODO This waits for a the request for the first service to be sent (as it wont get sent until the second has responded) - makes the rest easier knowing they are all there. Needs a better way of doing it
expect { insights_call_collector.flatten }.to eventually(include a_hash_including 'data' => a_hash_including('baseData' => a_hash_including('url' => "#{rack_servers.base_url_for(:app1)}/anything"))).pause_for(0.05).within(0.5)
app1_request_record = insights_call_collector.flatten.detect { |r| r['data']['baseData']['url'] == "#{rack_servers.base_url_for(:app1)}/anything" }
original_operation_id = app1_request_record.dig('tags', 'ai.operation.id')
parent_id = app1_request_record.dig('data', 'baseData', 'id')
dep_record = insights_call_collector.flatten.detect { |r| r['data']['baseType'] == 'RemoteDependencyData' }
tags_expectation = a_hash_including(
'ai.internal.sdkVersion' => "rb:#{ApplicationInsights::VERSION}",
'ai.cloud.role' => 'fakerolename',
'ai.cloud.roleInstance' => 'fakeroleinstance',
'ai.operation.parentId' => parent_id,
'ai.operation.id' => original_operation_id,
'ai.operation.name' => 'GET /anything'
)
base_data_expectation = a_hash_including(
'ver' => 2,
'id' => match(/\A\|[0-9a-f]{32}\.[0-9a-f]{16}\.\z/),
'resultCode' => '200',
'duration' => instance_of(String),
'success' => true,
'name' => "GET #{rack_servers.base_url_for(:app2)}/",
'data' => "GET #{rack_servers.base_url_for(:app2)}/",
'target' => "localhost:#{rack_servers.port_for(:app2)}",
'type' => 'Http (tracked component)'
)
expected = a_hash_including 'ver' => 1,
'name' => 'Microsoft.ApplicationInsights.RemoteDependency',
'time' => instance_of(String),
'sampleRate' => 100.0,
'data' => a_hash_including(
'baseType' => 'RemoteDependencyData'
)
expect(dep_record).to expected
expect(dep_record['tags']).to tags_expectation
expect(dep_record.dig('data', 'baseData')).to base_data_expectation
end
it 'informs insights of the second request linked to the dependency' do
rack_servers.get_request(:app1, '/anything')
# @TODO This waits for a the request for the first service to be sent (as it wont get sent until the second has responded) - makes the rest easier knowing they are all there. Needs a better way of doing it
expect { insights_call_collector.flatten }.to eventually(include a_hash_including 'data' => a_hash_including('baseData' => a_hash_including('url' => "#{rack_servers.base_url_for(:app1)}/anything"))).pause_for(0.05).within(0.5)
dep_record = insights_call_collector.flatten.detect { |r| r['data']['baseType'] == 'RemoteDependencyData' }
original_operation_id = dep_record.dig('tags', 'ai.operation.id')
parent_dep_id = dep_record.dig('data', 'baseData', 'id')
app2_request = insights_call_collector.flatten.detect { |r| r['data']['baseType'] == 'RequestData' && r['data']['baseData']['url'] == "#{rack_servers.base_url_for(:app2)}/" }
tags_expectation = a_hash_including 'ai.internal.sdkVersion' => "rb:#{ApplicationInsights::VERSION}",
'ai.cloud.role' => 'fakerolename',
'ai.cloud.roleInstance' => 'fakeroleinstance',
'ai.operation.parentId' => parent_dep_id,
'ai.operation.id' => original_operation_id
base_data_expectation = a_hash_including 'ver' => 2,
'id' => match(/\A\|[0-9a-f]{32}\.[0-9a-f]{16}\.\z/),
'responseCode' => '200',
'duration' => instance_of(String),
'success' => true,
'name' => 'GET /',
'url' => "#{rack_servers.base_url_for(:app2)}/",
'properties' => a_hash_including('httpMethod' => 'GET')
expected = a_hash_including 'ver' => 1,
'name' => 'Microsoft.ApplicationInsights.Request',
'time' => instance_of(String),
'sampleRate' => 100.0
expect(app2_request).to expected
expect(app2_request['tags']).to tags_expectation
expect(app2_request.dig('data', 'baseData')).to base_data_expectation
end
# @TODO - What happens when another service hits us with the Request-Context set with an appId different to ours
end
context '2 service chain with the second app connected but failing' do
# Here, we will configure 2 rack applications
# Our test suite calls the first rack app using net/http with the tracking disabled (as we are not testing this part)
# The first rack app will call the second using typhoeus
#
include_context 'rack servers' do
rack_servers.register(:app1) do |env|
url = rack_servers.base_url_for(:app2)
Typhoeus.get(url)
[200, {}, ['OK from rack app 1 and rack app 2']]
end
rack_servers.register(:app2) do |env|
[500, {}, ['Internal Server Error']]
end
end
it 'informs insights of the second request linked to the dependency with the correct status' do
rack_servers.get_request(:app1, '/anything')
# @TODO This waits for a the request for the first service to be sent (as it wont get sent until the second has responded) - makes the rest easier knowing they are all there. Needs a better way of doing it
expect { insights_call_collector.flatten }.to eventually(include a_hash_including 'data' => a_hash_including('baseData' => a_hash_including('url' => "#{rack_servers.base_url_for(:app1)}/anything"))).pause_for(0.05).within(0.5)
dep_record = insights_call_collector.flatten.detect { |r| r['data']['baseType'] == 'RemoteDependencyData' }
original_operation_id = dep_record.dig('tags', 'ai.operation.id')
parent_dep_id = dep_record.dig('data', 'baseData', 'id')
app2_request = insights_call_collector.flatten.detect { |r| r['data']['baseType'] == 'RequestData' && r['data']['baseData']['url'] == "#{rack_servers.base_url_for(:app2)}/" }
tags_expectation = a_hash_including 'ai.internal.sdkVersion' => "rb:#{ApplicationInsights::VERSION}",
'ai.cloud.role' => 'fakerolename',
'ai.cloud.roleInstance' => 'fakeroleinstance',
'ai.operation.parentId' => parent_dep_id,
'ai.operation.id' => original_operation_id
base_data_expectation = a_hash_including 'ver' => 2,
'id' => match(/\A\|[0-9a-f]{32}\.[0-9a-f]{16}\.\z/),
'responseCode' => '500',
'duration' => instance_of(String),
'success' => false,
'name' => 'GET /',
'url' => "#{rack_servers.base_url_for(:app2)}/",
'properties' => a_hash_including('httpMethod' => 'GET')
expected = a_hash_including 'ver' => 1,
'name' => 'Microsoft.ApplicationInsights.Request',
'time' => instance_of(String),
'sampleRate' => 100.0
expect(app2_request).to expected
expect(app2_request['tags']).to tags_expectation
expect(app2_request.dig('data', 'baseData')).to base_data_expectation
end
end
context '2 service chain with the second app no connected' do
# Here, we will configure 2 rack applications
# Our test suite calls the first rack app using net/http with the tracking disabled (as we are not testing this part)
# The first rack app will call the second using typhoeus
#
include_context 'rack servers' do
rack_servers.register(:app1) do |env|
url = rack_servers.base_url_for(:app2)
Typhoeus.get(url, connecttimeout: 0.1)
[200, {}, ['OK from rack app 1 and rack app 2']]
end
rack_servers.register(:app2) do |env|
sleep 0.5
[200, {}, ['OK from rack app 2 if only it were connected']]
end
end
it 'informs insights of the second request linked to the dependency with the correct status' do
url = rack_servers.base_url_for(:app2)
WebMock.stub_http_request(:get, url).to_timeout
rack_servers.get_request(:app1, '/anything')
# @TODO This waits for a the request for the first service to be sent (as it wont get sent until the second has responded) - makes the rest easier knowing they are all there. Needs a better way of doing it
expect { insights_call_collector.flatten }.to eventually(include a_hash_including 'data' => a_hash_including('baseData' => a_hash_including('url' => "#{rack_servers.base_url_for(:app1)}/anything"))).pause_for(0.05).within(0.5)
dep_record = insights_call_collector.flatten.detect { |r| r['data']['baseType'] == 'RemoteDependencyData' }
tags_expectation = a_hash_including 'ai.internal.sdkVersion' => "rb:#{ApplicationInsights::VERSION}",
'ai.cloud.role' => 'fakerolename',
'ai.cloud.roleInstance' => 'fakeroleinstance',
'ai.operation.parentId' => instance_of(String),
'ai.operation.id' => instance_of(String)
base_data_expectation = a_hash_including 'ver' => 2,
'id' => match(/\A\|[0-9a-f]{32}\.[0-9a-f]{16}\.\z/),
'resultCode' => '0',
'duration' => instance_of(String),
'success' => false,
'data' => "GET #{rack_servers.base_url_for(:app2)}/",
'target' => URI.parse(rack_servers.base_url_for(:app2)).yield_self { |uri| "#{uri.host}:#{uri.port}" }
expected = a_hash_including 'ver' => 1,
'name' => 'Microsoft.ApplicationInsights.RemoteDependency',
'time' => instance_of(String),
'sampleRate' => 100.0
expect(dep_record).to expected
expect(dep_record['tags']).to tags_expectation
expect(dep_record.dig('data', 'baseData')).to base_data_expectation
end
end
end
|
#!/usr/bin/ruby
=begin
#---------------------------------------------------------------------------------------------------------
# euler12.rb- program to indicate the triangle number whose number of factors are just greater than the given threshold provided in the input file
# i/p - an ASCII txt file with a single number as threshold value (may contain multiple spaces and newline)
# o/p - the triangle number whose count of factors is > given number terminated by a single newline character
# author - Ravi Kishor Shakya
# Ruby version 1.8.7
#----------------------------------------------------------------------------------------------------------
=end
# for a tri no, generate its factors
def getfactors (initnum)
triangle = initnum;
tempfactors = Array.new;
counter = 1;
while counter <= triangle
remainder = triangle % counter;
if remainder == 0
tempfactors.push(counter);
end
counter += 1;
end
return tempfactors;
end
if ARGV.length != 1
puts "Usage: euler12.rb <infile>";
exit;
end
$ifile = ARGV[0];
$threshold = 0;
#read input file , trim spaces, new lines
File.open($ifile, "r") do |thisFile|
while line = thisFile.gets
line = line.chomp;
line = line.strip;
$threshold = line;
#puts "#{$threshold}";
#bailout after non-empty line
if line.length != 0
break;
end
end
end
#iterate and generate triangle nos
flag = 0; #indicates success if true
count = 1;
#puts "#$threshold";
while flag == 0
num = 0;
factors = Array.new;
#generate tri nos
itr = 1;
while itr <= count
num += itr;
itr += 1;
end
#get n chk factors of a triangle number
factors = getfactors(num);
#chk condition, set flag
if factors.length > $threshold.to_i
puts "#{num}";
flag = 1;
end
count += 1;
end
|
require 'easy_extensions/easy_xml_data/importables/importable'
module EasyXmlData
class IssueRelationImportable < Importable
def initialize(data)
@klass = IssueRelation
super
end
def mappable?
false
end
private
end
end |
class AddPriceToVoyages < ActiveRecord::Migration[6.0]
def change
add_column :voyages, :price, :integer
end
end
|
Rails.application.routes.draw do
root to: 'artists#index'
resources :artists, only: :show do
resources :albums, only: [:new, :create]
resources :artist_tags, as: :tags, only: [:new, :create]
end
resources :albums, only: :destroy
end
|
class EventsController < ApplicationController
before_filter :authenticate_user!, :except => [:show, :index]
def index
@events = Event.all :include => [:event_dates], :order => 'event_dates.event_date desc'
end
def new
@event = Event.new
end
def create
@event = Event.new(params[:event])
@creator = Role.new(:role_type => "creator")
current_user.roles << @creator
if @event.save
@event.roles << @creator
redirect_to(events_url, :notice => 'Event was successfully created.')
else
render :action => "new"
end
end
def edit
@event = Event.find(params[:id])
@new_admin = @event.roles.build(:role_type=>'admin')
@new_domain = @event.domains.build
end
def update
@event = Event.find(params[:id])
if @event.update_attributes(params[:event])
redirect_to(event_path, :notice => 'Event was successfully updated.')
else
render :action => "edit"
end
end
def show
if params[:id]
@event = Event.find(params[:id], :include=>:event_dates)
else
@event = Event.find_by_host(request.host)
end
if @event
@event_date = select_today_or_first(@event)
if @event_date
redirect_to(event_event_date_url(@event, @event_date))
else
redirect_to(new_event_event_date_url(@event))
end
end
end
def select_today_or_first(event)
event.event_dates.select { |d|
d.event_date == Date.today
}.first || event.event_dates.first
# considered the following:
# t = EventDate.arel_table
# EventDate.where(t[:event_date].gteq(Date.today).and(t[:event_id].eq(1))).order(:event_date)
# .union(EventDate.where(t[:event_date].lt(Date.today).and(t[:event_id].eq(1))).order(:event_date))
end
def destroy
@event = Event.find(params[:id])
if @event.creator?(current_user)
if @event.destroy
flash[:notice] = "Successfully deleted event."
else
flash[:alert] = "Failed to delete event."
end
else
flash[:alert] = "You need to be the creator of an event to delete it."
end
redirect_to(events_url)
end
end
|
require 'sinatra/base'
require 'haml'
require 'json'
module Timetable
class Application < Sinatra::Base
include TimeHelpers
# Set the parent directory of this file as the project root
set :root, File.dirname(File.dirname(File.dirname(__FILE__)))
set :haml, :format => :html5
get '/' do
@courses = Config.read("courses")
@modules = Config.read("modules")
@course_modules = Config.read("course_modules")
haml :index
end
get '/install' do
redirect '/'
end
post '/install' do
yoe = params[:yoe].to_i
year = course_year(yoe)
# Remove the values for the dropdown menus and the submit button
# from the params hash to get the modules chosen by the user
form = ["course", "yoe", "submit"]
modules = params.reject { |key, _| form.include? key }
modules = modules.keys
# Create a new Preset object with the user's choices. It is worth
# noting that if the same preset already exists, we will reuse
# that database record and will avoid creating a new one
begin
preset = Preset.new(params[:course], yoe, year, modules)
rescue RuntimeError => e
return error 500, e.message
end
# If the preset doesn't exist (e.g. because the user took all the
# modules), then give them a default url of the form course/yoe
name = preset.name || "#{params[:course]}/#{params[:yoe]}"
host = request.host
host += ":9393" if host == "localhost"
@url = "webcal://#{host}/#{name}"
@lightbox = true
haml :install
end
# Match routes corresponding to a given preset
get '/:preset' do
preset = Preset.find(params[:preset])
unless preset
return error 404, "Calendar preset not found"
end
show_ical(preset["course"], preset["yoe"], preset["ignored"])
end
# Match generic routes such as /comp/09 or /jmc/10
get %r{/([a-z]+)/([\d]{2})/?} do
course, yoe = params[:captures]
show_ical(course, yoe)
end
helpers do
# Returns a hash containing an array of valid years for every
# course ID, e.g. "comp" => [1,2,3,4], "ee" => [3,4]
def course_years
Config.read("course_ids").inject({}) do |memo, (k, v)|
memo.merge({k => v.keys})
end
end
# Given a number, return a string with the number followed
# by its ordinal suffix. E.g. 1 is "1st". Only works in the
# 0-20 range, which is more than enough for what we need
def ordinal(num)
suffixes = [nil, 'st', 'nd', 'rd', 'th']
num.to_s + (suffixes[num] || 'th')
end
# Return the year of entry corresponding to a given course
# year (as a number), so that 1 corresponds to the current
# academic year, 2 to last year, etc
def year_to_yoe(year)
academic_year - year + 1
end
# Return the URL of the install guide picture for a given
# app (iCal, GCal, etc) and a given step in the guide.
def guide_pic(app, step)
"images/#{app}/step#{step}.png"
end
end
private
# Return the iCal representation of the timetable for a given
# course and year of entry, and (optional) ignored modules
def show_ical(course, yoe, ignored = [])
begin
calendar = Calendar.new(course, yoe.to_i, ignored)
rescue ArgumentError => e
return error 404, e.message
end
headers "Content-Type" => "text/calendar"
calendar.to_ical
end
end
end
|
require 'spec_helper'
describe User do
before do
@user = User.new(email: "user@example.com",
password: "somepassword",
password_confirmation: "somepassword",
isAdmin: false)
end
subject { @user }
it { should respond_to(:email) }
it { should respond_to(:password) }
it { should respond_to(:password_confirmation) }
it { should respond_to(:isAdmin) }
it { should be_valid }
describe "when email is not present" do
before { @user.email = "" }
it { should_not be_valid }
end
describe "when email format is invalid" do
it "should be invalid" do
addresses = %w[user@foo,com user.foo.com %@foo.net. foo@bar+baz.com]
addresses.each do |invalid_addr|
@user.email = invalid_addr
@user.should_not be_valid
end
end
end
describe "when email format is valid" do
it "should be valid" do
addresses = %w[user@foo.com user@foo.COM
A_Usr-b@f.b.org first.last@foo.jp a4b2@bar.ch]
addresses.each do |valid_addr|
@user.email = valid_addr
@user.should be_valid
end
end
end
describe "when email address is already taken -identical" do
before do
user_with_same_email = @user.dup
user_with_same_email.save
end
it { should_not be_valid }
end
describe "when email address is already taken -case insensitive" do
before do
user_with_same_email = @user.dup
user_with_same_email.email = @user.email.upcase
user_with_same_email.save
end
it { should_not be_valid }
end
describe "when password is not present" do
before { @user.password = "" }
it { should_not be_valid }
end
describe "when confirmation password is not present" do
before { @user.password_confirmation = "" }
it { should_not be_valid }
end
describe "when password doesn't match confirmation" do
before { @user.password_confirmation = "mismatch" }
it { should_not be_valid }
end
describe "when password confirmation is nil" do
before { @user.password_confirmation = nil }
it {should_not be_valid }
end
end
|
Puppet::Parser::Functions.newfunction(:wreckit_scenarios, :type => :rvalue) do |args|
begin
raise(ArgumentError, 'wreckit_scenarios() expects a single optional argument') if args.size > 1
context = args.first
modpath = Puppet::Module.find('wreckit', compiler.environment.to_s).path
klasses = []
Dir.chdir("#{modpath}/manifests/scenario") do
klasses = Dir.glob("**/*.pp").collect do |path|
klass = File.basename(path, '.pp')
namespace = File.dirname(path).gsub('/', '::')
"wreckit::scenario::#{namespace}::#{klass}"
end
end
# Filter externally instead of in the Dir.glob because I was getting hangs on some platforms
klasses.select! { |klass| klass.start_with? "wreckit::scenario::#{context}" }
rescue => e
Puppet.warning "Could not resolve Wreckit scenarios for context #{context}"
Puppet.debug e.message
Puppet.debug e.backtrace
klasses = []
end
klasses
end
|
class Blog < ActiveRecord::Base
has_attached_file :eye_catch, :styles => { :small => "150x150>" },
:url => "/assets/blog_images/:id/:style/:basename.:extension",
:path => ":rails_root/public/assets/blog_images/:id/:style/:basename.:extension"
validates_attachment_content_type :eye_catch, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
validates_attachment_presence :eye_catch
validates :title, :contents, presence: true
scope :recent, -> {
order("created_at DESC")
}
end
|
# == Schema Information
#
# Table name: airports
#
# id :uuid not null, primary key
# altitude :integer
# city :string
# country :string
# country_alpha2 :string
# dst :string
# iata :string
# icao :string
# kind :string
# latitude :decimal(10, 6)
# longitude :decimal(10, 6)
# name :string
# passenger_volume :integer
# source :string
# timezone :string
# timezone_olson :string
# uid :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_airports_on_country (country)
# index_airports_on_iata (iata) UNIQUE
# index_airports_on_iata_and_icao_and_name (iata,icao,name)
# index_airports_on_icao (icao)
# index_airports_on_name (name)
#
class AirportSerializer < Blueprinter::Base
identifier :id
field :iata
field :name
field :country
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
root 'welcome#index'
devise_for :users
get 'welcome/index'
resources :projects, except: :show, param: :name do
resources :publishings, path: 'publish', only: :create
end
namespace :tasks do
resources :deployments, only: [] do
collection do
get "check"
end
end
end
namespace :pubsub do
namespace :deploy do
post "/", to: "messages#create"
end
namespace :cleanup do
post "/", to: "messages#create"
end
end
namespace :api, constraints: { format: 'json' } do
namespace :v1 do
resources :projects, only: :show
end
end
end
|
module RatingAverage
extend ActiveSupport::Concern
def average_rating
if ratings.empty?
return 0.0
else
ratings.average(:score)
end
end
end |
- Build a calculator to run with Addition, Multiplication, Subtraction, and Division.
- User needs to be able to select what they want to do with the numbers and need to be able to pass in at least 6 numbers at a time. |
# == Schema Information
#
# Table name: recipes
#
# id :integer not null, primary key
# user_id :integer
# title :string
# kitchen_of :string
# ingredients :text
# instructions :text
# public :boolean
# created_at :datetime not null
# updated_at :datetime not null
# description :text
# friendly_url :string
#
class Recipe < ApplicationRecord
belongs_to :user, optional: true
has_many :recipe_shares, dependent: :destroy
has_many :recipe_favorites, dependent: :destroy
has_many :shared_users, through: :shares, source: :shared_to
has_many :favorited_by_users, through: :favorites, source: :favorited_by
before_save :set_friendly_url
scope :viewable, lambda { |current_user=nil|
scopes = [
"(recipes.public IS true)",
"(recipes.user_id = :user_id)",
"(recipe_shares.shared_to_id = :user_id)",
]
includes(:recipe_shares).references(:recipe_shares)
.where(scopes.join(" OR "), user_id: current_user.try(:id))
}
def ingredients_list
ingredients.to_s.split("\n").map { |ingredient| ingredient.squish.presence }.compact
end
def export_to_list(list)
items = ingredients_list.map { |ingredient| {name: "#{ingredient} (#{title})"} }
list.add_items(items)
end
def to_param
friendly_url || id
end
private
def set_friendly_url
try_url = title.to_s.parameterize.first(50)
iteration = nil
self.friendly_url = loop do
iteration_url = [try_url, iteration].compact.join("-")
break iteration_url if self.class.where(friendly_url: iteration_url).where.not(id: id).none?
iteration ||= 1
iteration += 1
end
end
end
|
class OfferProductIdRename < ActiveRecord::Migration[5.0]
def change
rename_column :offers, :product_id, :card_product_id
end
end
|
class UserAuthService
class User < ActiveRecord::Base
before_create :generate_uid
def generate_uid
self.uid = SecureRandom.uuid
end
end
end
|
require 'test/unit'
require 'coderay'
class StatisticEncoderTest < Test::Unit::TestCase
def test_creation
assert CodeRay::Encoders::Statistic < CodeRay::Encoders::Encoder
stats = nil
assert_nothing_raised do
stats = CodeRay.encoder :statistic
end
assert_kind_of CodeRay::Encoders::Encoder, stats
end
TEST_INPUT = CodeRay::Tokens[
['10', :integer],
['(\\)', :operator],
[:begin_group, :string],
['test', :content],
[:end_group, :string],
[:begin_line, :test],
["\n", :space],
["\n \t", :space],
[" \n", :space],
["[]", :method],
[:end_line, :test],
]
TEST_INPUT.flatten!
TEST_OUTPUT = <<-'DEBUG'
Code Statistics
Tokens 11
Non-Whitespace 4
Bytes Total 20
Token Types (7):
type count ratio size (average)
-------------------------------------------------------------
TOTAL 11 100.00 % 1.8
space 3 27.27 % 3.0
string 2 18.18 % 0.0
test 2 18.18 % 0.0
:begin_group 1 9.09 % 0.0
:begin_line 1 9.09 % 0.0
:end_group 1 9.09 % 0.0
:end_line 1 9.09 % 0.0
content 1 9.09 % 4.0
integer 1 9.09 % 2.0
method 1 9.09 % 2.0
operator 1 9.09 % 3.0
DEBUG
def test_filtering_text_tokens
assert_equal TEST_OUTPUT, CodeRay::Encoders::Statistic.new.encode_tokens(TEST_INPUT)
assert_equal TEST_OUTPUT, TEST_INPUT.statistic
end
end
|
class Comment < ApplicationRecord
belongs_to :user
belongs_to :idea
default_scope {order({created_at: :desc}, :user_id)}
def get_user
User.find user_id
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 bin/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)
Paiement.delete_all
Apartment.delete_all
Tenant.delete_all
User.delete_all
# laod users
load Rails.root.join("db/seeds/users.rb")
#load apartments
load Rails.root.join("db/seeds/apartments.rb")
# Load tenants
load Rails.root.join("db/seeds/tenants.rb")
# Load paiements
load Rails.root.join("db/seeds/paiements.rb") |
module Fog
module DNS
class Google
##
# Atomically updates a ResourceRecordSet collection.
#
# @see https://cloud.google.com/dns/api/v1/changes/create
class Real
def create_change(zone_name_or_id, additions = [], deletions = [])
@dns.create_change(
@project, zone_name_or_id,
::Google::Apis::DnsV1::Change.new(
additions: additions,
deletions: deletions
)
)
end
end
class Mock
def create_change(_zone_name_or_id, _additions = [], _deletions = [])
# :no-coverage:
Fog::Mock.not_implemented
# :no-coverage:
end
end
end
end
end
|
module Annotable
class User < ApplicationRecord
belongs_to :organization, optional: true
validates :email, presence: true, format: { with: /@/ }
end
end
|
require 'rails_helper'
RSpec.describe UserExpenseShareValue, type: :model do
let!(:expense) { create(:expense, cost: 10, owners: [user], user: user) }
let(:user) { create(:user) }
let(:user_expense) { build(:user_expense_share_value, status: 'resolved', expense: expense) }
describe "#settle_expense" do
it 'updates expense status if there is no user_expense unresolved left' do
expect{
user_expense.save
}.to change(expense, :status).from('unresolved').to('resolved')
end
end
end
|
require 'test_helper'
module Abilities
class ForumsTest < ActiveSupport::TestCase
def setup
@provider = FactoryBot.create(:provider_account)
@forum = @provider.forum
end
def test_posts
assert_equal [], @forum.posts.to_a
assert_equal 0, @forum.posts.size
end
test 'anyone can read topic when forum is public' do
@forum.account.settings.update_attribute(:forum_public, true)
user = FactoryBot.create(:user, :account => @provider)
topic = FactoryBot.create(:topic, :forum => @forum)
ability = Ability.new(user)
assert ability.can?(:read, topic)
ability = Ability.new(nil)
assert ability.can?(:read, topic)
end
test 'just logged in users can read topic when forum is not public' do
@forum.account.settings.update_attribute(:forum_public, false)
provider_user = FactoryBot.create(:user, :account => @provider)
buyer = FactoryBot.create(:buyer_account, :provider_account => @provider)
buyer_user = FactoryBot.create(:user, :account => buyer)
topic = FactoryBot.create(:topic, :forum => @forum)
ability = Ability.new(provider_user)
assert ability.can?(:read, topic)
ability = Ability.new(buyer_user)
assert ability.can?(:read, topic)
ability = Ability.new(nil)
assert !ability.can?(:read, topic)
end
test "topic owner can update and destroy topic if it is less than one day old" do
topic = FactoryBot.create(:topic)
user = topic.user
ability = Ability.new(user)
assert ability.can?(:update, topic)
assert ability.can?(:destroy, topic)
end
test "topic owner can't update nor destroy topic if it is more than one day old" do
topic = FactoryBot.create(:topic)
user = topic.user
ability = Ability.new(user)
Timecop.travel(2.days.from_now) do
assert !ability.can?(:update, topic)
assert !ability.can?(:destroy, topic)
end
end
test "user can't update not destroy topic of other user" do
user_one = FactoryBot.create(:user_with_account)
user_two = FactoryBot.create(:user_with_account)
topic = FactoryBot.create(:topic, :user => user_one)
ability = Ability.new(user_two)
assert !ability.can?(:update, topic)
assert !ability.can?(:destroy, topic)
end
test "admin can manage any topic of his forum" do
admin = @provider.admins.first
user = FactoryBot.create(:user, :account => @provider)
ability = Ability.new(admin)
topic_one = FactoryBot.create(:topic, :forum => @forum, :user => admin)
assert ability.can?(:manage, topic_one)
topic_two = FactoryBot.create(:topic, :forum => @forum, :user => user)
assert ability.can?(:manage, topic_two)
topic_three = FactoryBot.create(:topic, :forum => @forum, :user => user)
Timecop.travel(2.days.from_now) do
assert ability.can?(:manage, topic_three)
end
end
test "admin can stick a topic" do
topic = FactoryBot.create(:topic, :forum => @forum)
ability = Ability.new(@provider.admins.first)
assert ability.can?(:stick, topic)
end
test "user can't stick a topic" do
topic = FactoryBot.create(:topic, :forum => @forum)
user = FactoryBot.create(:user, :account => @provider)
ability = Ability.new(user)
assert !ability.can?(:stick, topic)
end
test "post author can update and destroy post if it is less than one day old" do
post = FactoryBot.create(:post)
user = post.user
ability = Ability.new(user)
assert ability.can?(:update, post)
assert ability.can?(:destroy, post)
end
test "post author can't update nor destroy post if it is more than one day old" do
post = FactoryBot.create(:post)
user = post.user
ability = Ability.new(user)
Timecop.travel(2.days.from_now) do
assert !ability.can?(:update, post)
assert !ability.can?(:destroy, post)
end
end
test "user can't update not destroy post of other user" do
user_one = FactoryBot.create(:user_with_account)
user_two = FactoryBot.create(:user_with_account)
post = FactoryBot.create(:post, :user => user_one)
ability = Ability.new(user_two)
assert !ability.can?(:update, post)
assert !ability.can?(:destroy, post)
end
test "user can't destroy a post if it is the last one in the topic" do
topic = FactoryBot.create(:topic)
topic.posts[1..-1].each(&:destroy) # Just in case
ability = Ability.new(topic.user)
assert !ability.can?(:destroy, topic.posts.first)
end
test "admin can manage any post of his forum" do
topic = FactoryBot.create(:topic, :forum => @forum)
admin = @provider.admins.first
user = FactoryBot.create(:user, :account => @provider)
ability = Ability.new(admin)
post_one = FactoryBot.create(:post, :topic => topic, :user => admin)
assert ability.can?(:manage, post_one)
post_two = FactoryBot.create(:post, :topic => topic, :user => user)
assert ability.can?(:manage, post_two)
post_three = FactoryBot.create(:post, :topic => topic, :user => user)
Timecop.travel(2.days.from_now) do
assert ability.can?(:manage, post_three)
end
end
test 'anyone can read category in public forum' do
@forum.account.settings.update_attribute(:forum_public, true)
category = @forum.categories.create!(:name => 'Junk')
buyer = FactoryBot.create(:buyer_account)
buyer_user = FactoryBot.create(:user, :account => buyer)
provider_user = FactoryBot.create(:user, :account => @provider)
ability = Ability.new(buyer_user)
assert ability.can?(:read, category)
ability = Ability.new(provider_user)
assert ability.can?(:read, category)
ability = Ability.new(nil)
assert ability.can?(:read, category)
end
test 'buyer user can read category in private forum' do
@forum.account.settings.update_attribute(:forum_public, false)
account = FactoryBot.create(:buyer_account, :provider_account => @provider)
user = FactoryBot.create(:user, :account => account)
category = @forum.categories.create!(:name => 'Junk')
ability = Ability.new(user)
assert ability.can?(:read, category)
end
test 'provider user can read category in private forum' do
@forum.account.settings.update_attribute(:forum_public, false)
user = FactoryBot.create(:user, :account => @provider)
category = @forum.categories.create!(:name => 'Junk')
ability = Ability.new(user)
assert ability.can?(:read, category)
end
test "user can't manage category" do
category = @forum.categories.create!(:name => 'Stuff')
user = FactoryBot.create(:user, :account => @provider)
ability = Ability.new(user)
assert !ability.can?(:create, TopicCategory)
assert !ability.can?(:update, category)
assert !ability.can?(:destroy, category)
end
test "buyer admin can't manage category" do
category = @forum.categories.create!(:name => 'Stuff')
buyer = FactoryBot.create(:buyer_account, :provider_account => @provider)
ability = Ability.new(buyer.admins.first)
assert !ability.can?(:create, TopicCategory)
assert !ability.can?(:update, category)
assert !ability.can?(:destroy, category)
end
test "admin can manage category of his forum" do
category = @forum.categories.create!(:name => 'Stuff')
ability = Ability.new(@provider.admins.first)
assert ability.can?(:create, TopicCategory)
assert ability.can?(:update, category)
assert ability.can?(:destroy, category)
end
test "user can create anonymous post if anonymous posting is enabled" do
@forum.account.settings.update_attribute(:anonymous_posts_enabled, true)
user = FactoryBot.create(:user, :account => @provider)
topic = FactoryBot.create(:topic, :forum => @forum)
post = topic.posts.build
# logged in user
ability = Ability.new(user)
assert ability.can?(:reply, topic)
assert ability.can?(:reply, post)
# anon user
ability = Ability.new(nil)
assert ability.can?(:reply, topic)
assert ability.can?(:reply, post)
end
test "user can't create anonymous post if anonymous posting is disabled" do
@forum.account.settings.update_attribute(:anonymous_posts_enabled, false)
user = FactoryBot.create(:user, :account => @provider)
topic = FactoryBot.create(:topic, :forum => @forum)
post = topic.posts.build
# logged in users
ability = Ability.new(user)
assert ability.can?(:reply, topic)
assert ability.can?(:reply, post)
# anon users
ability = Ability.new(nil)
assert !ability.can?(:reply, topic)
assert !ability.can?(:reply, post)
end
context "Topic with category" do
should "can reply" do
@forum.account.settings.update_attribute(:anonymous_posts_enabled, false)
category = FactoryBot.create(:topic_category, :forum => @forum)
topic = category.topics.build
user = FactoryBot.create(:user, :account => @provider)
# logged in provider
ability = Ability.new(user)
assert ability.can?(:reply, topic)
buyer = FactoryBot.create(:buyer_account, :provider_account => @provider)
buyer_user = FactoryBot.create(:user, :account => buyer)
# logged in buyer
ability = Ability.new(user)
assert ability.can?(:reply, topic)
# anon user
ability = Ability.new(nil)
assert !ability.can?(:reply, topic)
@forum.account.settings.update_attribute(:anonymous_posts_enabled, true)
topic = category.reload.topics.build
assert ability.can?(:reply, topic)
end
should "be manageable by admin" do
category = FactoryBot.create(:topic_category, :forum => @forum)
admin = FactoryBot.create(:admin, :account => @provider)
ability = Ability.new(admin)
assert ability.can?(:manage, category.topics.build)
assert ability.can?(:manage, @forum.topics.build)
end
end
end
end |
require "java"
Dir["#{Dir.pwd}/.akephalos/#{ENV['htmlunit_version']}/*.jar"].each {|file| require file }
java.lang.System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog")
java.lang.System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "fatal")
java.lang.System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true")
# Container module for com.gargoylesoftware.htmlunit namespace.
module HtmlUnit
java_import "com.gargoylesoftware.htmlunit.BrowserVersion"
java_import "com.gargoylesoftware.htmlunit.History"
java_import "com.gargoylesoftware.htmlunit.HttpMethod"
java_import 'com.gargoylesoftware.htmlunit.ConfirmHandler'
java_import "com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController"
java_import "com.gargoylesoftware.htmlunit.SilentCssErrorHandler"
java_import "com.gargoylesoftware.htmlunit.WebClient"
java_import "com.gargoylesoftware.htmlunit.WebResponseData"
java_import "com.gargoylesoftware.htmlunit.WebResponse"
java_import "com.gargoylesoftware.htmlunit.WaitingRefreshHandler"
# Container module for com.gargoylesoftware.htmlunit.util namespace.
module Util
java_import "com.gargoylesoftware.htmlunit.util.NameValuePair"
java_import "com.gargoylesoftware.htmlunit.util.WebConnectionWrapper"
end
# Disable history tracking
History.field_reader :ignoreNewPages_
end
|
require 'spec_helper'
describe Rack::Utils::UrlStripper do
describe '.replace_id' do
it 'replaces BSON-like ids with ID' do
ids = %w(5005536b28330e5a8800005f 4f07931e3641417a88000002)
ids.each do |id|
Rack::Utils::UrlStripper.replace_id("/resource/#{id}").should == '/resource/ID'
end
end
it "replaces ids with sub-resources" do
Rack::Utils::UrlStripper.replace_id("/resource/4f07931e3641417a88000002/another").should == '/resource/ID/another'
end
end
end
describe Rack::Utils::UrlStripper, '.id_pattern' do
it 'has a default value' do
old_val = Rack::Utils::UrlStripper.id_pattern
Rack::Utils::UrlStripper.id_pattern.should_not be_nil
Rack::Utils::UrlStripper.id_pattern = old_val
end
it 'allows setting the id_pattern to a custom value' do
new_pattern = /my_new_pattern/
Rack::Utils::UrlStripper.id_pattern = new_pattern
Rack::Utils::UrlStripper.id_pattern.should == new_pattern
end
end |
# SAPNW is Copyright (c) 2006-2010 Piers Harding. It is free software, and
# may be redistributed under the terms specified in the README file of
# the Ruby distribution.
#
# Author:: Piers Harding <piers@ompka.net>
# Requires:: Ruby 1.8 or later
#
module SAPNW
module Functions
class Base
end
end
module RFC
# These are automatically created as a result of SAPNW::RFC::Connection#discover() -
# do not instantiate these yourself yourself!
#
class FunctionDescriptor
attr_reader :name, :parameters
attr_accessor :callback
# create a new SAPNW::RFC::FunctionCall object for this FunctionDescriptor.
#
# You must call this each time that you want to invoke() a new function call, as
# this creates a one shot container for the passing back and forth of interface parameters.
def new_function_call
return create_function_call(SAPNW::RFC::FunctionCall)
end
def make_empty_function_call
return SAPNW::RFC::FunctionCall.new(self)
end
def callback=(proc)
if proc.instance_of?(Proc)
@callback = proc
else
raise "Must pass in an instance of Proc for the callback"
end
return @callback
end
def handler(function)
begin
return @callback.call(function)
rescue SAPNW::RFC::ServerException => e
#$stderr.print "ServerException => #{e.error.inspect}\n"
return e
rescue StandardError => e
#$stderr.print "StandardError => #{e.inspect}/#{e.message}\n"
return SAPNW::RFC::ServerException.new({'code' => 3, 'key' => 'RUBY_RUNTIME', 'message' => e.message})
end
end
def method_missing(methid, *rest)
meth = methid.id2name
if @parameters.has_key?(meth)
return @parameters[meth]
else
raise NoMethodError
end
end
# internal method used to add parameters from within the C extension
#def addParameter(name = nil, direction = 0, type = 0, len = 0, ulen = 0, decimals = 0)
def addParameter(*parms)
parms = parms.first if parms.class == Array and (parms.first.class == Hash || parms.first.kind_of?(SAPNW::RFC::Parameter))
case parms
when Array
name, direction, type, len, ulen, decimals = parms
when Hash
name = parms.has_key?(:name) ? parms[:name] : nil
direction = parms.has_key?(:direction) ? parms[:direction] : nil
type = parms.has_key?(:type) ? parms[:type] : nil
len = parms.has_key?(:len) ? parms[:len] : nil
ulen = parms.has_key?(:ulen) ? parms[:ulen] : nil
decimals = parms.has_key?(:decimals) ? parms[:decimals] : nil
when SAPNW::RFC::Export, SAPNW::RFC::Import, SAPNW::RFC::Changing, SAPNW::RFC::Table
# this way happens when a function def is manually defined
self.add_parameter(parms)
@parameters[parms.name] = parms
return parms
else
raise "invalid SAPNW::RFC::FunctionDescriptor parameter supplied: #{parms.inspect}\n"
end
#$stderr.print "parm: #{name} direction: #{direction} type: #{type} len: #{len} decimals: #{decimals}\n"
case direction
when SAPNW::RFC::IMPORT
if @parameters.has_key?(name) and @parameters[name].direction == SAPNW::RFC::EXPORT
p = SAPNW::RFC::Changing.new(self, name, type, len, ulen, decimals)
else
p = SAPNW::RFC::Import.new(self, name, type, len, ulen, decimals)
end
when SAPNW::RFC::EXPORT
if @parameters.has_key?(name) and @parameters[name].direction == SAPNW::RFC::IMPORT
p = SAPNW::RFC::Changing.new(self, name, type, len, ulen, decimals)
else
p = SAPNW::RFC::Export.new(self, name, type, len, ulen, decimals)
end
when SAPNW::RFC::CHANGING
p = SAPNW::RFC::Changing.new(self, name, type, len, ulen, decimals)
when SAPNW::RFC::TABLES
p = SAPNW::RFC::Table.new(self, name, type, len, ulen, decimals)
else
raise "unknown direction (#{name}): #{direction}\n"
end
@parameters[p.name] = p
return p
end
end
class FunctionCall
attr_reader :function_descriptor, :name, :parameters
# These are automatically created as a result of SAPNW::RFC::FunctionDescriptor#new_function_call() -
# do not instantiate these yourself!
#
# SAPNW::RFC::FunctionCall objects allow dynamic method calls of parameter, and table names
# for the setting and getting of interface values eg:
# fd = conn.discover("RFC_READ_TABLE")
# f = fd.new_function_call
# f.QUERY_TABLE = "T000" # <- QUERY_TABLE is a dynamic method serviced by method_missing
#def initialize(fd=nil)
def initialize(fd=nil)
@parameters = {}
if fd == nil
@function_descriptor.parameters.each_pair do |k,v|
@parameters[k] = v.clone
end
else
fd.parameters.each_pair do |k,v|
@parameters[k] = v.clone
end
end
@parameters_list = @parameters.values || []
end
# activate a parameter - parameters are active by default so it is unlikely that this
# would ever need to be called.
def activate(parm=nil)
raise "Parameter not found: #{parm}\n" unless @parameters.has_key?(parm)
return set_active(parm, 1)
end
# deactivate a parameter - parameters can be deactivated for a function call, to reduce the
# amount of RFC traffic on the wire. This is especially important for unrequired tables, or
# parameters that are similar sources of large data transfer.
def deactivate(parm=nil)
raise "Parameter not found: #{parm}\n" unless @parameters.has_key?(parm)
return set_active(parm, 0)
end
# dynamic method calls for parameters and tables
def method_missing(methid, *rest)
meth = methid.id2name
#$stderr.print "method_missing: #{meth}\n"
#$stderr.print "parameters: #{@parameters.keys.inspect}\n"
if @parameters.has_key?(meth)
#$stderr.print "return parm obj\n"
return @parameters[meth].value
elsif mat = /^(.*?)\=$/.match(meth)
#$stderr.print "return parm val\n"
if @parameters.has_key?(mat[1])
return @parameters[mat[1]].value = rest[0]
else
raise NoMethError
end
else
raise NoMethodError
end
end
end
end
end
|
class StoresController < ApplicationController
def index
@stores = Store.find(:all, :order => :number)
respond_to do |format|
format.html
format.xml { render xml: @stores }
format.json { render json: @stores }
# format.pdf { render pdf: @stores }
end
end
def show
@store = Store.find_by_id(params[:id])
end
def new
@store = Store.new
end
def edit
@store = Store.find_by_id(params[:id])
end
def create
@store = Store.new(params[:store])
if @store.save
redirect_to new_store_path, notice: 'Store was successfully created.'
else
render action: "new"
end
end
def update
@store = Store.find(params[:id])
if @store.update_attributes(params[:store])
redirect_to @store, notice: 'Store was successfully updated.'
else
render action: "edit"
end
end
def destroy
@store = Store.find(params[:id])
@store.destroy
redirect_to stores_url
end
end
|
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
mount_uploader :profile_image, ProfileImageUploader
validates_acceptance_of :terms_accepted, allow_nil: false, accept: true
validates_acceptance_of :email_is_used_with_paypal, allow_nil: false, accept: true, :message => "must be the email you use with PayPal"
validates_presence_of :first_name, :last_name, :relationship_to_children_id, :child_configuration_id
belongs_to :relationship_to_children
belongs_to :child_configuration
has_many :auctions
def full_name
"#{first_name} #{last_name[0,1]}."
end
end
|
module ManageIQ::Providers::Amazon::ParserHelperMethods
extend ActiveSupport::Concern
#
# Helper methods
#
def filter_unused_disabled_flavors
to_delete = @data[:flavors].reject { |f| f[:enabled] || @known_flavors.include?(f[:ems_ref]) }
to_delete.each do |f|
@data_index[:flavors].delete(f[:ems_ref])
@data[:flavors].delete(f)
end
end
ARCHITECTURE_TO_BITNESS = {
:i386 => 32,
:x86_64 => 64,
}.freeze
def architecture_to_bitness(arch)
ARCHITECTURE_TO_BITNESS[arch.to_sym]
end
def get_from_tags(resource, tag_name)
tag_name = tag_name.to_s.downcase
resource.tags.detect { |tag, _| tag.key.downcase == tag_name }.try(:value).presence
end
def add_instance_disk(disks, size, location, name, controller_type = "amazon")
if size >= 0
disk = {
:device_name => name,
:device_type => "disk",
:controller_type => controller_type,
:location => location,
:size => size
}
disks << disk
return disk
end
nil
end
def add_block_device_disk(disks, name, location)
disk = {
:device_name => name,
:device_type => "disk",
:controller_type => "amazon",
:location => location,
}
disks << disk
disk
end
# Compose an ems_ref combining some existing keys
def compose_ems_ref(*keys)
keys.join('_')
end
end
|
class RemoveDbValidationFromUser < ActiveRecord::Migration[5.2]
def change
remove_column :users, :first_name
remove_column :users, :uid
remove_column :users, :provider
add_column :users, :first_name, :string
add_column :users, :uid, :string, null: false
add_column :users, :provider, :string, null: false
add_index :users, :provider
add_index :users, :uid
add_index :users, [:provider, :uid], unique: true
end
end
|
require 'rails_helper'
require File.dirname(__FILE__) + '/../../app/models/person'
describe 'Person' do
it 'should have email as required' do
cust = Person.new
expect(cust.valid?).to be(false)
expect(cust.errors.messages[:email]).to include("can't be blank")
end
it 'should only accept valid email addresses' do
cust = Person.new(email: 'Magnus')
expect(cust.valid?).to be(false)
expect(cust.errors.messages[:email]).to include("is invalid")
cust = Person.new(email: 'magnus@storyoffice.se')
expect(cust.valid?).to be(false)
expect(cust.errors.messages[:email]).to eq([])
end
it 'should only accept numbers and dashes in phone' do
cust = Person.new(phone: 'Magnus')
expect(cust.valid?).to be(false)
expect(cust.errors.messages[:phone]).to include("is invalid")
cust = Person.new(phone: '1234')
expect(cust.valid?).to be(false)
expect(cust.errors.messages[:phone]).to eq([])
cust = Person.new(phone: '12-34')
expect(cust.valid?).to be(false)
expect(cust.errors.messages[:phone]).to eq([])
cust = Person.new(phone: '12-3 4')
expect(cust.valid?).to be(false)
expect(cust.errors.messages[:phone]).to eq([])
end
it 'should only accept numbers and dashes in mobile_phone' do
cust = Person.new(mobile_phone: 'Magnus')
expect(cust.valid?).to be(false)
expect(cust.errors.messages[:mobile_phone]).to include("is invalid")
cust = Person.new(mobile_phone: '1234')
expect(cust.valid?).to be(false)
expect(cust.errors.messages[:mobile_phone]).to eq([])
cust = Person.new(mobile_phone: '12-34')
expect(cust.valid?).to be(false)
expect(cust.errors.messages[:mobile_phone]).to eq([])
cust = Person.new(mobile_phone: '12-3 4')
expect(cust.valid?).to be(false)
expect(cust.errors.messages[:mobile_phone]).to eq([])
end
end |
class Admin::ProfilesController < Puffer::Base
setup do
group :users
end
index do
field 'user.email'
field :name
field :surname
field :birth_date
end
form do
field :user, :columns => [:email, :password]
field :name
field :surname
field :birth_date
field :created_at
end
end
|
Rails.application.routes.draw do
resources :statuses
resources :questions
resources :users
root 'users#index'
end
|
class TracksController < ApplicationController
before_action :check_login
def check_login
unless logged_in?
redirect_to new_user_url
end
end
def index
render :index
end
def create
@track = Track.create(track_params)
redirect_to track_url(@track)
end
def new
@track = Track.new
end
def edit
end
def show
@track = Track.find(params[:id])
end
def update
@track = Track.find(params[:id])
Track.destroy(@track)
redirect_to bands_url
end
def destroy
end
private
def track_params
params.require(:track).permit(:album_id, :name, :track_type)
end
end
|
require "dhis2"
class Dhis2Exporter
attr_reader :facility_identifiers, :periods, :data_elements_map, :category_option_combo_ids
def initialize(facility_identifiers:, periods:, data_elements_map:, category_option_combo_ids: [])
throw "DHIS2 export not enabled in Flipper" unless Flipper.enabled?(:dhis2_export)
@facility_identifiers = facility_identifiers
@periods = periods
@data_elements_map = data_elements_map
@category_option_combo_ids = category_option_combo_ids
Dhis2.configure do |config|
config.url = ENV.fetch("DHIS2_URL")
config.user = ENV.fetch("DHIS2_USERNAME")
config.password = ENV.fetch("DHIS2_PASSWORD")
config.version = ENV.fetch("DHIS2_VERSION")
end
end
def export
@facility_identifiers.each do |facility_identifier|
data_values = []
@periods.each do |period|
facility_data = yield(facility_identifier, period)
facility_data.each do |data_element, value|
data_values << {
data_element: data_elements_map[data_element],
org_unit: facility_identifier.identifier,
period: reporting_period(period),
value: value
}
puts "Adding data for #{facility_identifier.facility.name}, #{period}, #{data_element}: #{data_values.last}"
end
end
send_data_to_dhis2(data_values)
end
end
def export_disaggregated
@facility_identifiers.each do |facility_identifier|
data_values = []
@periods.each do |period|
facility_data = yield(facility_identifier, period)
facility_data.each do |data_element, value|
results = disaggregate_data_values(data_elements_map[data_element], facility_identifier, period, value)
data_values << results
results.each { |result| puts "Adding data for #{facility_identifier.facility.name}, #{period}, #{data_element}: #{result}" }
end
end
data_values = data_values.flatten
send_data_to_dhis2(data_values)
end
end
def send_data_to_dhis2(data_values)
pp Dhis2.client.data_value_sets.bulk_create(data_values: data_values)
end
def disaggregate_data_values(data_element_id, facility_identifier, period, values)
category_option_combo_ids.map do |combo, id|
{
data_element: data_element_id,
org_unit: facility_identifier.identifier,
category_option_combo: id,
period: reporting_period(period),
value: values.with_indifferent_access[combo] || 0
}
end
end
def reporting_period(month_period)
if Flipper.enabled?(:dhis2_use_ethiopian_calendar)
EthiopiaCalendarUtilities.gregorian_month_period_to_ethiopian(month_period).to_s(:dhis2)
else
month_period.to_s(:dhis2)
end
end
end
|
class File < IO
SEPARATOR = "/"
ALT_SEPARATOR = nil
def self.file?(io)
false
end
def initialize(path, mode = "r")
STDERR.puts "File.init: #{path.inspect}"
%s(assign rpath (callm path __get_raw))
%s(assign fd (open rpath 0))
%s(perror 0)
# FIXME: Error checking
%s(if (le fd 0) (do
(printf "Failed to open '%s' got %ld\n" rpath fd)
(div 0 0)
))
%s(assign fd (__get_fixnum fd))
super(fd)
end
def self.open(path)
f = File.new(path)
end
def self.exists?(path)
%s(assign rpath (callm path __get_raw))
%s(assign fd (open rpath 0))
%s(if (le fd 0) (return false))
%s(close fd)
return true
end
def self.basename(name)
name
end
def self.dirname(dname)
i = dname.rindex(SEPARATOR)
if !i && ALT_SEPARATOR
i = dname.rindex(ALT_SEPARATOR)
end
if i
r = 0..i
d = dname[r]
return d
end
return nil
end
def self.expand_path(path)
STDERR.puts "expand_path: '#{path}'"
path
end
end
|
class ChangeDoctorDepartmentToRole < ActiveRecord::Migration
def change
rename_column :doctors, :department, :role
end
end
|
name 'oauth2_proxy'
maintainer 'Orion Labs, Inc.'
maintainer_email 'Mike Juarez <mike@orionlabs.co>'
license 'Apache License, Version 2.0'
description 'Installs/Configures oauth2_proxy'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version IO.read(File.join(File.dirname(__FILE__), 'VERSION')) rescue '2.4.0'
depends 'ark'
depends 'pleaserun'
|
require "twirloc/version"
require "twirloc/twitter_client"
require "twirloc/location_guesser"
require "twirloc/tweet_fetcher"
require "twirloc/tweet"
require "twirloc/midpoint_calculator"
require "twirloc/algorithms"
require "twirloc/google_location"
require "thor"
module Twirloc
class CLI < Thor
desc "total USERNAME", "get total number of tweets for USERNAME"
def total(username)
twitter = TwitterClient.new
tweet_count = twitter.user_tweet_count(username)
puts tweet_count
end
desc "geo USERNAME", "checks if profile is geo enabled for USERNAME"
def geo(username)
twitter = TwitterClient.new
enabled = twitter.user_geo_enabled?(username)
puts enabled ? "enabled" : "disabled"
end
desc "geocenter_user_tweets USERNAME", "calculates geographic centerpoint of any lat/lon coordinates from tweets by USERNAME"
def geocenter_user_tweets(username)
twitter = TwitterClient.new
location = twitter.user_tweets_geo_center(username)
puts location
end
desc "locate USERNAME", "takes best guess at users location"
def locate(username)
twitter = TwitterClient.new
location = twitter.guess_location(username)
puts location
end
end
end
|
module Mysears::MystoreHelper
# TODO | remove
# Article looks like:
# <Article
# id: 245,
# article_instance_id: 4,
# article_category_id: 57,
# title: "Saturday Family Fun!",
# content: "<p><img src=\"http://www.mysears.com/managed_images/...",
# permalink: "Saturday-Family-Fun--245",
# comments_enabled: true,
# page_title: "",
# meta_keywords: "",
# meta_description: "",
# user_id: 330155,
# published_at: "2010-08-09 10:08:38",
# is_sticky: false,
# created_at: "2010-08-09 10:08:38",
# updated_at: "2010-08-13 08:46:56",
# status: "published",
# teaser: "<p>Saturday Family Fun happening Aug. 14 see our si...",
# show_teaser_on_page_1: true,
# article_type: "article",
# contributor_id: nil,
# type: nil,
# start_time: nil,
# end_time: nil,
# time_details: nil,
# all_day: false,
# is_rsvpable: false,
# coupon_code: nil,
# coupon_expiration: nil
# >
def mystore_pagination_info(page_num, total_num_results, page_size)
"Displaying #{((page_num-1)*page_size)+1} - #{[page_num*page_size, total_num_results].min} of #{total_num_results} Results"
end
def mystore_pagination_links(search_value, search_radius, page_num, total_num_results, page_size)
html = ''
if page_num > 1
html += link_to('Prev', {:controller=>'mystore', :search_value=>search_value, :search_radius=>search_radius, :page_num=>page_num-1})
end
if page_num <= ((total_num_results-1)/page_size)
html += link_to('Next', {:controller => 'mystore', :search_value => @search_value, :search_radius => @search_radius, :page_num => @page_num+1})
end
html
end
def normalized_store_info(stores)
results = []
displayed_details = ['id', 'title', 'Address', 'City', 'State', 'Zip code', 'Telephone', 'Fax', 'Store Email', 'Hours', 'Twitter Username']
detail_keys = displayed_details.collect { | detail | detail.gsub(/\s/, '_').downcase }
stores.each do | store |
values = displayed_details.map { | detail | store[detail] || store.get_answer_value(detail) }
results.push arrays_to_hash detail_keys, values
end
results
end
def store_url
url_for :controller => 'product', :action => 'show', :id => @product.id
end
def discussions_page?
params[:controller] == 'posts' || params[:controller] == 'topics'
end
def format_contact_info(normalized_store)
markup = ''
['address', 'city', 'state', 'zip_code', 'telephone', 'fax', 'store_email'].each do | p |
piece = normalized_store[p]
unless piece.empty?
markup << 'phone: ' if p == 'telephone'
markup << p << ': ' if (p == 'fax')
markup << "email: <a href=\"mailto:#{piece}\">#{piece}</a>" if p == 'store_email'
markup << piece unless (p == 'store_email' || p == 'address')
markup << "<p class=\"address\">#{piece}" if p == 'address'
markup << '<br/>' unless (p == "city" || p == "state" || p == 'zip_code')
markup << ',' if p == "city"
markup << ' ' if (p == "city" || p == "state")
markup << "</p>" if p == 'zip_code'
end
end
markup
end
def is_event?(article)
article.kind_of?(Event)
end
def can_rsvp?(article)
article.kind_of?(Event) and article.is_rsvpable?
end
def dateline(article_or_event, date_format='%B %d, %Y')
dl = article_or_event.published_at? ? %{posted #{article_or_event.published_at.strftime(date_format)}} : "Not published"
%{<i class="dateline">#{dl}</i>}
end
def event_date_heading(evt)
# TODO | Add day of week only as event gets closer
format_compare = '%m %d %Y %k:%M'
format_compare_day = '%m %d %Y'
format_day = '%a, %b %e'
format_hour = '%l:%M%P'
format_full = %{#{format_day} #{format_hour}}
now = Time.new
if evt.all_day or evt.start_time.strftime(format_compare) == evt.end_time.strftime(format_compare)
date = evt.start_time.strftime format_day
time = evt.start_time.strftime format_hour
else
# Same day
if evt.start_time.strftime(format_compare_day) == evt.end_time.strftime(format_compare_day)
date = evt.start_time.strftime format_day
time = evt.start_time.strftime(format_hour) << ' - ' << evt.end_time.strftime(format_hour)
# Multi day
else
date = evt.start_time.strftime(format_day) << ' - ' << evt.end_time.strftime(format_day)
time = evt.start_time.strftime format_hour
end
end
impending = ''
if evt.start_time.strftime(format_compare_day) == now.strftime(format_compare_day)
impending = '<em class="when">Today</em>'
end
{:date => date, :time => time, :impending => impending}
end
end
|
require 'rubygems'
require 'rake/testtask'
require 'rake/rdoctask'
$LOAD_PATH.unshift File.expand_path("../lib", __FILE__)
require "typus/version"
desc 'Default: run unit tests.'
task :default => :test
desc 'Test the typus plugin.'
Rake::TestTask.new(:test) do |t|
t.libs << 'lib'
t.libs << 'test'
t.pattern = 'test/**/*_test.rb'
t.verbose = true
end
desc 'Build the gem.'
task :build do
system "gem build typus.gemspec"
end
desc 'Build and release the gem.'
task :release => :build do
version = Typus::VERSION
system "git tag v#{version}"
system "git push origin v#{version}"
system "gem push pkg/typus-#{version}.gem"
system "git clean -fd"
system "gem push typus-#{version}"
end
desc 'Generate specdoc-style documentation from tests'
task :specs do
puts 'Started'
timer, count = Time.now, 0
File.open('SPECDOC', 'w') do |file|
Dir.glob('test/**/*_test.rb').each do |test|
test =~ /.*\/([^\/].*)_test.rb$/
file.puts "#{$1.gsub('_', ' ').capitalize} should:" if $1
File.read(test).map { |line| /test_(.*)$/.match line }.compact.each do |spec|
file.puts "- #{spec[1].gsub('_', ' ')}"
sleep 0.001; print '.'; $stdout.flush; count += 1
end
file.puts
end
end
puts <<-MSG
\nFinished in #{Time.now - timer} seconds.
#{count} specifications documented.
MSG
end
|
class CreateImageTable < ActiveRecord::Migration
def change
create_table :images do |t|
t.string :filename
t.string :hash_id
t.string :extension
t.timestamps
end
add_foreign_key :users, :images
add_foreign_key :games, :images
end
end
|
Rails.application.routes.draw do
devise_for :users
resources :users, only: [:index, :show]
resources :articles
root 'articles#index'
end
|
FactoryBot.define do
factory :__activity do
title { Faker::Lorem.sentence }
partner_organisation_identifier { "GCRF-#{Faker::Alphanumeric.alpha(number: 5).upcase!}" }
roda_identifier { nil }
beis_identifier { nil }
description { Faker::Lorem.paragraph }
sector_category { "111" }
sector { "11110" }
source_fund_code { Fund.by_short_name("NF").id }
programme_status { 7 }
planned_start_date { Date.today }
planned_end_date { Date.tomorrow }
actual_start_date { Date.yesterday }
actual_end_date { Date.today }
geography { :recipient_region }
recipient_region { "489" }
recipient_country { nil }
intended_beneficiaries { ["CU", "DM", "DO"] }
benefitting_countries { nil }
gdi { "4" }
fstc_applies { true }
aid_type { "D01" }
level { :fund }
publish_to_iati { true }
gcrf_strategic_area { ["17A", "RF"] }
gcrf_challenge_area { 0 }
oda_eligibility_lead { Faker::Name.name }
uk_po_named_contact { Faker::Name.name }
fund_pillar { "0" }
ispf_themes { [1] }
ispf_oda_partner_countries { ["IN"] }
ispf_non_oda_partner_countries { ["IN"] }
form_state { "complete" }
before(:create) do |activity|
if activity.roda_identifier.blank? && activity.parent.present?
activity.roda_identifier = Activity::RodaIdentifierGenerator.new(
parent_activity: activity.parent,
extending_organisation: activity.extending_organisation,
is_non_oda: activity.is_oda == false
).generate
end
end
trait :with_report do
after(:create) do |activity|
fund = activity.associated_fund
create(:report, :active, fund: fund, organisation: activity.organisation)
end
end
trait :with_commitment do
after(:build) do |activity|
activity.commitment = build(:commitment)
end
end
factory :fund_activity do
level { :fund }
association :organisation, factory: :beis_organisation
association :extending_organisation, factory: :beis_organisation
trait :gcrf do
roda_identifier { "GCRF" }
title { "Global Challenges Research Fund (GCRF)" }
source_fund_code { Fund.by_short_name("GCRF").id }
initialize_with do
Activity.find_or_initialize_by(roda_identifier: "GCRF")
end
end
trait :newton do
roda_identifier { "NF" }
title { "Newton Fund" }
source_fund_code { Fund.by_short_name("NF").id }
initialize_with do
Activity.find_or_initialize_by(roda_identifier: "NF")
end
end
trait :ooda do
roda_identifier { "OODA" }
title { "Other ODA" }
source_fund_code { Fund.by_short_name("OODA").id }
initialize_with do
Activity.find_or_initialize_by(roda_identifier: "OODA")
end
end
trait :ispf do
roda_identifier { "ISPF" }
title { "International Science Partnerships Fund" }
source_fund_code { Fund.by_short_name("ISPF").id }
initialize_with do
Activity.find_or_initialize_by(roda_identifier: "ISPF")
end
end
end
factory :programme_activity do
parent factory: :fund_activity
level { :programme }
objectives { Faker::Lorem.paragraph }
country_partner_organisations { ["National Council for the State Funding Agencies (CONFAP)"] }
collaboration_type { "1" }
association :organisation, factory: :beis_organisation
association :extending_organisation, factory: :partner_organisation
trait :newton_funded do
source_fund_code { Fund.by_short_name("NF").id }
parent do
Activity.fund.find_by(source_fund_code: Fund.by_short_name("NF").id) || create(:fund_activity, :newton)
end
end
trait :gcrf_funded do
source_fund_code { Fund.by_short_name("GCRF").id }
parent do
Activity.fund.find_by(source_fund_code: Fund.by_short_name("GCRF").id) || create(:fund_activity, :gcrf)
end
end
trait :ooda_funded do
source_fund_code { Fund.by_short_name("OODA").id }
parent do
Activity.fund.find_by(source_fund_code: Fund.by_short_name("OODA").id) || create(:fund_activity, :ooda)
end
end
trait :ispf_funded do
source_fund_code { Fund.by_short_name("ISPF").id }
is_oda { true }
parent do
Activity.fund.find_by(source_fund_code: Fund.by_short_name("ISPF").id) || create(:fund_activity, :ispf)
end
end
after(:create) do |programme, _evaluator|
programme.implementing_organisations << programme.organisation
programme.reload
end
end
factory :project_activity do
parent factory: :programme_activity
level { :project }
objectives { Faker::Lorem.paragraph }
call_present { "true" }
call_open_date { Date.yesterday }
call_close_date { Date.tomorrow }
collaboration_type { "1" }
total_applications { "25" }
total_awards { "12" }
policy_marker_gender { "not_assessed" }
policy_marker_climate_change_adaptation { "not_assessed" }
policy_marker_climate_change_mitigation { "not_assessed" }
policy_marker_biodiversity { "not_assessed" }
policy_marker_desertification { "not_assessed" }
policy_marker_disability { "not_assessed" }
policy_marker_disaster_risk_reduction { "not_assessed" }
policy_marker_nutrition { "not_assessed" }
channel_of_delivery_code { "11000" }
association :organisation, factory: :partner_organisation
association :extending_organisation, factory: :partner_organisation
factory :project_activity_with_implementing_organisations do
transient do
implementing_organisations_count { 3 }
end
after(:create) do |project_activity, evaluator|
project_activity.implementing_organisations = create_list(
:implementing_organisation,
evaluator.implementing_organisations_count
)
project_activity.reload
end
end
trait :newton_funded do
source_fund_code { Fund.by_short_name("NF").id }
parent factory: [:programme_activity, :newton_funded]
end
trait :gcrf_funded do
source_fund_code { Fund.by_short_name("GCRF").id }
parent factory: [:programme_activity, :gcrf_funded]
end
trait :ispf_funded do
source_fund_code { Fund.by_short_name("ISPF").id }
is_oda { true }
parent do
create(:programme_activity, :ispf_funded, is_oda: is_oda)
end
end
end
factory :third_party_project_activity do
parent factory: :project_activity
level { :third_party_project }
objectives { Faker::Lorem.paragraph }
call_present { "true" }
call_open_date { Date.yesterday }
call_close_date { Date.tomorrow }
collaboration_type { "1" }
total_applications { "25" }
total_awards { "12" }
policy_marker_gender { "not_assessed" }
policy_marker_climate_change_adaptation { "not_assessed" }
policy_marker_climate_change_mitigation { "not_assessed" }
policy_marker_biodiversity { "not_assessed" }
policy_marker_desertification { "not_assessed" }
policy_marker_disability { "not_assessed" }
policy_marker_disaster_risk_reduction { "not_assessed" }
policy_marker_nutrition { "not_assessed" }
channel_of_delivery_code { "11000" }
association :organisation, factory: :partner_organisation
association :extending_organisation, factory: :partner_organisation
trait :newton_funded do
source_fund_code { Fund.by_short_name("NF").id }
parent factory: [:project_activity, :newton_funded]
end
trait :gcrf_funded do
source_fund_code { Fund.by_short_name("GCRF").id }
parent factory: [:project_activity, :gcrf_funded]
end
trait :ispf_funded do
source_fund_code { Fund.by_short_name("ISPF").id }
is_oda { true }
parent do
create(:project_activity, :ispf_funded, is_oda: is_oda)
end
end
after(:create) do |project, _evaluator|
project.implementing_organisations << create(:implementing_organisation)
project.reload
end
end
end
trait :at_identifier_step do
form_state { "identifier" }
partner_organisation_identifier { nil }
title { nil }
description { nil }
objectives { nil }
sector_category { nil }
sector { nil }
call_present { nil }
programme_status { nil }
country_partner_organisations { nil }
planned_start_date { nil }
planned_end_date { nil }
actual_start_date { nil }
actual_end_date { nil }
geography { nil }
recipient_region { nil }
recipient_country { nil }
collaboration_type { nil }
aid_type { nil }
policy_marker_gender { nil }
policy_marker_climate_change_adaptation { nil }
policy_marker_climate_change_mitigation { nil }
policy_marker_biodiversity { nil }
policy_marker_desertification { nil }
policy_marker_disability { nil }
policy_marker_disaster_risk_reduction { nil }
policy_marker_nutrition { nil }
oda_eligibility_lead { nil }
end
trait :at_purpose_step do
form_state { "purpose" }
title { nil }
description { nil }
objectives { nil }
sector { nil }
call_present { nil }
programme_status { nil }
country_partner_organisations { nil }
planned_start_date { nil }
planned_end_date { nil }
actual_start_date { nil }
actual_end_date { nil }
geography { nil }
recipient_region { nil }
recipient_country { nil }
intended_beneficiaries { nil }
gdi { nil }
collaboration_type { nil }
aid_type { nil }
policy_marker_gender { nil }
policy_marker_climate_change_adaptation { nil }
policy_marker_climate_change_mitigation { nil }
policy_marker_biodiversity { nil }
policy_marker_desertification { nil }
policy_marker_disability { nil }
policy_marker_disaster_risk_reduction { nil }
policy_marker_nutrition { nil }
oda_eligibility_lead { nil }
end
trait :at_collaboration_type_step do
form_state { "collaboration_type" }
collaboration_type { nil }
aid_type { nil }
policy_marker_gender { nil }
policy_marker_climate_change_adaptation { nil }
policy_marker_climate_change_mitigation { nil }
policy_marker_biodiversity { nil }
policy_marker_desertification { nil }
policy_marker_disability { nil }
policy_marker_disaster_risk_reduction { nil }
policy_marker_nutrition { nil }
oda_eligibility_lead { nil }
end
trait :at_sustainable_development_goals_step do
form_state { "sustainable_development_goals" }
sdgs_apply { false }
sdg_1 { nil }
sdg_2 { nil }
sdg_3 { nil }
end
trait :with_transparency_identifier do
after(:create) do |activity|
parent_identifier = activity.parent.present? ? "#{activity.parent.partner_organisation_identifier}-" : ""
activity.transparency_identifier = "#{parent_identifier}#{activity.partner_organisation_identifier}"
activity.save
end
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure(2) do |config|
# Every Vagrant development environment requires a box. You can search for
# boxes at https://atlas.hashicorp.com/search.
config.vm.box = "ubuntu/xenial64"
# Enable provisioning with a shell script. Additional provisioners such as
# Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the
# documentation for more information about their specific syntax and use.
config.vm.provision "shell", inline: <<-SHELL
echo -e "127.0.0.1 $(cat /etc/hostname)\n$(cat /etc/hosts)" | sudo tee /etc/hosts
sudo apt-get -y update
sudo apt-get -y upgrade
# sudo apt-get install virtualbox-guest-additions-iso
# sudo apt-get -y install openjdk-9-jdk-headless
SHELL
end
|
# Underline first letter of string
class Symbol
def underline_first
to_s.capitalize!
"\e[4m#{self[0]}\e[0m#{self[1..-1]}"
end
end
# Monkey-patch for want of better ideas. In the initial move, the colours and
# their positions are irrelevant; all codes with the same number of colours and
# repitions of those colours are equivalent (e.g. [0, 0, 1] ~ [2, 3, 3]). So
# first partition integers into arrays of integers with that sum. Then translate
# those into the lowest value codes. Then pick the most instructive.
class Integer
def partition
[[self]] + [self - 1, 1].part_iter
end
end
# Partition implementation
class Array
def part_iter
[dup] + if self[0] > self[1]
decrement_start
push1.part_iter + if self[-2] > self[-1]
increment_end.part_iter
else []
end
else []
end
end
private
def decrement_start
self[0] -= 1
end
def push1
self + [1]
end
def increment_end
self[0...-1] << self[-1] + 1
end
end
|
feature 'Deleting a comment' do
before(:each) do
sign_up
log_in
post_peep
comment
comment2
end
scenario 'User who made a can delete it' do
expect{ click_button('delete_comment_5') }.to change(Comment, :count).by(-1)
expect(page).not_to have_content('Test comment')
expect(page).to have_content('Commenting number 2')
end
scenario 'Other users can\'t delete others\' comments' do
log_out
sign_up(name: 'Clemence Guillaume',
username: 'clems',
email: 'clemence.guill@gmail.com',
password: 'clems',
password_confirmation: 'clems')
expect(page).not_to have_button('Delete this comment')
end
scenario 'Guest can\'t delete others\' comments' do
log_out
visit('/')
click_button('Continue as guest')
expect(page).not_to have_button('Delete this comment')
end
end
|
class Point < ActiveRecord::Base
belongs_to :user
belongs_to :show
validates_presence_of :user_id, :show_id, :points
end
|
#
# Cookbook:: aar
# Recipe:: default
#
# Copyright:: 2017, The Authors, All Rights Reserved.
include_recipe 'lamp::default'
passwords = data_bag_item('passwords', 'mysql')
# Flask and python
package [ 'libapache2-mod-wsgi', 'python-pip', 'python-mysqldb', 'git' ]
execute 'install-flask' do
command <<-EOF
pip install flask
EOF
end
# Get the AAR files
git '/tmp/Awesome-Appliance-Repair' do
action :sync
repository 'https://github.com/colincam/Awesome-Appliance-Repair.git'
# TODO Figure this thing out
notifies :run, 'bash[mv_ARR]', :immediately
end
bash 'mv_AAR' do
cwd '/tmp/Awesome-Appliance-Repair'
code <<-EOH
mv AAR /var/www/
EOH
action :nothing
not_if {File.exists?('/var/www/AAR')}
end
execute "chown-data-www" do
command "chown -R www-data:www-data /var/www/AAR"
user "root"
action :run
end
template '/var/www/AAR/AAR_config.py' do
source 'create_config.py.erb'
variables(
admin_pass: passwords['admin_password'],
secret_key: passwords['secret_key']
)
end
# Database config
# Create a path to SQL file in cache
create_tables_script_path = ::File.join(Chef::Config[:file_cache_path], 'make_AARdb.sql')
# Get the creation script
cookbook_file create_tables_script_path do
source 'make_AARdb.sql'
end
# Seed the database with table and test data
execute "initialize #{node['lamp']['database']['dbname']} database" do
command "mysql -h 127.0.0.1 -u #{node['lamp']['database']['admin_username']} -p#{passwords['admin_password']} -D #{node['lamp']['database']['dbname']} < #{create_tables_script_path}"
not_if "mysql -h 127.0.0.1 -u #{node['lamp']['database']['admin_username']} -p#{passwords['admin_password']} -D #{node['lamp']['database']['dbname']} -e 'describe customer;'"
end
|
class UsersController < ApplicationController
respond_to :html, :json
include UserInfoHelper
# before_action :get_current_user
def show
user = User.find(params["id"])
if user
user = inject_extra_user_props(user)
render json: user
else
redirect_to root_path
end
end
# def edit
# end
def login
current_user = User.find_by_email(params[:user][:email])
if current_user && current_user.password == params[:user][:password]
session[:user_id] = current_user.id
render json: current_user
else
render json: "Invalid Login"
end
end
def current_user
current_user = nil
if session[:user_id]
current_user = User.find(session[:user_id])
end
render json: session.to_json
end
def logout
session[:user_id] = nil
redirect_to root_path
end
# def new
# end
def create
user = User.new(user_params)
user.password = user_params[:password]
if user.save!
session[:user_id] = user.id
render json: user
else
render json: "Noooooo"
end
end
def destroy
end
def update
end
def user_params
params.require(:user).require(:user).permit(:first_name, :last_name, :email, :password)
end
# def get_current_user
# current_user = User.find
# end
end
|
class Contact < ApplicationRecord
# belongs_to :kind
# Faz com que a chave para Kind seja Opcional
belongs_to :kind, optional:true
has_many :phones
# Um Contato terá um Endereço
has_one :address
# Permite que o telefone possa ser cadastrado ao mesmo tempo que se cadastra um Contato
# Permite apagar um telefone a partir do Contato
accepts_nested_attributes_for :phones, allow_destroy: true
# Permite que o Endereço possa ser cadastrado ao mesmo tempo que se cadastra um Contato
# Address está no singular pois a regra é has_one
# Update only vai permitir que indepentemente se vai criar mais de um Address ou Dar um
# Patch sem o ID ele nao criará um registro novo, somente irá fazer o update do registro
# Pois está com a regra do has_one
accepts_nested_attributes_for :address, update_only: true
def to_br
{
name: self.name,
email: self.email,
birthdate: (I18n.l(self.birthdate) unless self.birthdate.blank?)
}
end
def birthdate_br
I18n.l(self.birthdate) unless self.birthdate.blank?
end
def updated_at_br
I18n.l(self.updated_at) unless self.updated_at.blank?
end
def hello
I18n.t('hello')
end
def i18n
I18n.default_locale
end
def author
"Jorge Teruya"
end
def kind_description
self.kind.description
end
# Adiciona o mesmo retorno para todos os json
# Super invoca a função original
#def as_json(options={})
# super(
# root: true,
#methods: :author
# Método para trazer um campo específico diretamente no json
# methods: [:author, :kind_description],
#include: :kind
# Include traz os dados aninhados
# include: { kind: {only: :description}}
# )
#end
end
|
name "apt"
maintainer "Till Klampaeckel"
maintainer_email "till@php.net"
license "Apache 2.0"
description "Configures apt and apt services"
version "0.10.0"
recipe "apt", "Runs apt-get update during compile phase and sets up preseed directories"
recipe "apt::cacher", "Set up an APT cache"
recipe "apt::proxy", "Set up an APT proxy"
recipe "apt::ppa", "Setup the tools needed to initialize PPAs"
recipe "apt::repair", "Install apt-repair-sources"
%w{ ubuntu debian }.each do |os|
supports os
end
|
# frozen_string_literal: true
require 'spec_helper'
require 'web_test/be_fast'
RSpec.describe WebTest::BeFast do
it { is_expected.not_to be_nil }
describe '#test' do
it 'handles a fast site' do
result = WebTest::BeFast.test url: 'http://nonstop.qa'
expect(result.success?).to be true
expect(result.score).to be >= 85
end
end
describe '#parse' do
it 'can parse the overall score' do
api_response = File.read(SAMPLE_PAGESPEED_JSON_RESPONSE)
data = WebTest::BeFast.parse json: api_response
expect(data[:score]).to eq 85
end
end
describe WebTest::BeFast::TestResult do
it 'requires :success' do
expect do
WebTest::BeFast::TestResult.new {}
end.to raise_error(ArgumentError, /success/i)
end
it 'requires :score' do
expect do
WebTest::BeFast::TestResult.new { |r| r.success = true }
end.to raise_error(ArgumentError, /score/i)
end
it 'requires :response' do
expect do
WebTest::BeFast::TestResult.new { |r|
r.success = true
r.score = 90
}
end.to raise_error(ArgumentError, /response/i)
end
end
end
|
class Customer < ActiveRecord::Base
validates :full_name, presence: true
belongs_to :province
end
|
module Downloadable
extend ActiveSupport::Concern
def download
return Rails.logger.info "File already downloaded: #{tmp_file}" if File.exist? tmp_file
source = open(external_address)
IO.copy_stream(source, tmp_file)
end
end
|
class NeighborsController < ApplicationController
before_action :set_neighbors
def neighbors
render json: @neighbors
end
private
def set_neighbors
@neighbors = NeighborList.instance
end
end
|
require 'memoist'
StubbedDestructiveMethod = Class.new(StandardError)
class Github
extend Memoist
attr_accessor :token, :client
def initialize(token = Env.github_api_token)
@token, @client = token, Octokit::Client.new(access_token: token)
end
def has_repo?(full_name)
client.repository?(full_name)
end
def ensure_repo!(full_name, organization, privacy = "true")
return true if has_repo?(full_name)
stub_outside_production("##{__callee__} issued with #{full_name} and #{options}") do
create_repo(full_name, organization, privacy)
end
end
def create_repo!(full_name, organization, team, privacy = "true")
team_object = team_by_field(organization, team)
options = {organization: organization, team_id: team_object.id, private: privacy}
stub_outside_production("##{__callee__} issued with #{full_name} and #{options}") do
client.create_repository(full_name, options)
end
end
def teams(organization)
client.organization_teams(organization)
end
memoize :teams
def team_by_field(organization, value, field = :name)
select_by_field.call(:teams, organization, field, value)
end
memoize :team_by_field
def hooks(full_name)
client.hooks(full_name)
end
memoize :hooks
def hooks_by_field(full_name, value, field = :name)
select_by_field.call(:hooks, full_name, field, value)
end
memoize :hooks_by_field
def select_by_field
->(method, arg, field, value) do
send(method, arg).select { |t| t.public_send(field).to_s =~ /#{value}/i }.first
end
end
def create_hook!(full_name, hook)
existing_hook = hooks_by_field(full_name, hook.name)
stub_outside_production("##{__callee__} issued for repo: #{full_name} with #{hook}, and existing_hook #{existing_hook}") do
if existing_hook
hook.payload.merge!(existing_hook){ |key, v1, v2| v1 } # Prioritize first hash
client.edit_hook(full_name, existing_hook.id, existing_hook.name, hook.payload)
else
client.create_hook(full_name, hook.name, hook.payload)
end
end
end
def stub_outside_production(msg, condition = Rails.env.production?)
if condition
yield
else
raise(StubbedDestructiveMethod, msg)
end
end
end
|
class CreateTownHealthRecords < ActiveRecord::Migration
def change
create_table :town_health_records do |t|
t.string :city_name
t.integer :population
t.integer :number_of_children
t.integer :number_of_seniors
t.integer :per_capita_income
t.integer :number_below_poverty
t.decimal :percent_below_poverty
t.decimal :percent_apc
t.decimal :percent_c_sections
t.integer :number_of_infant_deaths
t.decimal :infant_mr
t.decimal :percent_low_birth_weight
t.decimal :percent_multiple_births
t.decimal :percent_pf_pnc
t.decimal :percent_teen_births
t.timestamps
end
end
end
|
class AddConfirmationCodeToExpenses < ActiveRecord::Migration
def change
add_column :expenses, :confirmation_code, :string
end
end
|
class CreatePasFindings < ActiveRecord::Migration
def self.up
create_table 'pas_findings' do |t|
t.column :model_activity_dataset_id, :int
t.column :sequence, :integer
t.column :evidence, :string
t.column :text, :string
end
add_index "pas_findings", :model_activity_dataset_id
end
def self.down
remove_index "pas_findings", :model_activity_dataset_id
drop_table 'pas_findings'
end
end
|
require 'rails_helper'
feature 'user visits monologue new page' do
context 'as a user I want to vist the monologue new page' do
let!(:user) { FactoryGirl.create(:user) }
scenario 'so that I can view a form for uploading a monologue' do
visit root_path
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
click_button 'Sign In'
click_button 'Add A New Monologue'
expect(page).to have_css("form")
expect(page).to have_content("Upload Your Monologue!")
expect(page).to_not have_content("#{user.first_name}'s Profile")
end
end
end
|
class AppSample::AdminController < ModuleController
component_info 'AppSample', :description => 'App Sample support',
:access => :public
# Register a handler feature
register_permission_category :app_sample, "AppSample" ,"Permissions related to App Sample"
register_permissions :app_sample, [ [ :manage, 'Manage App Sample', 'Manage App Sample' ],
[ :config, 'Configure App Sample', 'Configure App Sample' ]
]
cms_admin_paths "options",
"App Sample Options" => { :action => 'index' },
"Options" => { :controller => '/options' },
"Modules" => { :controller => '/modules' }
permit 'app_sample_config'
content_model :things
def self.get_things_info
[
{ :name => 'Things', :url => { :controller => '/app_sample/manage_things' },
:permissino => 'app_sample_manage'
}
]
end
public
def options
cms_page_path ['Options','Modules'],"App Sample Options"
@options = self.class.module_options(params[:options])
if request.post? && @options.valid?
Configuration.set_config_model(@options)
flash[:notice] = "Updated App Sample module options".t
redirect_to :controller => '/modules'
return
end
end
def self.module_options(vals=nil)
Configuration.get_config_model(Options,vals)
end
class Options < HashModel
# Options attributes
# attributes :attribute_name => value
end
end
|
#!/usr/bin/env ruby
require 'rubygems'
require 'bundler/setup'
Bundler.require(:default)
require 'yaml'
settings = YAML.load_file('settings.yml')
thread_id = settings['thread_id']
access_token = settings['access_token']
DB = Sequel.connect('sqlite://messages.db')
messages = DB[:messages]
g = Koala::Facebook::API.new(access_token)
puts 'Fetching message count...'
fql = "SELECT message_count FROM thread WHERE thread_id=#{thread_id}"
message_count = FbGraph::Query.new(fql).fetch(access_token).first['message_count']
puts "Seeing #{message_count} messages..."
(1...message_count).each do |i|
next unless messages.where(:local_id => i).first.nil?
puts "Fetching message #{i}"
message = g.get_object("#{thread_id}_#{i}")
if message['message'].nil?
next
end
messages.insert({
:facebook_id => message['id'],
:local_id => i,
:from => message['from']['name'],
:message => message['message'],
:created_time => DateTime.parse(message['created_time'])
})
end |
with_tag(:div, :class => :address) do
address.hidden_field :id
address.text_area :street, :size => "30x3", :focus => true, :label_class => :street
address.select :kind, I18n.translate('contacts.address_types'), :no_label => true
address.buttons :delete
clear
address.text_field :locality
address.text_field :region
address.text_field :country, :autocomplete => true
address.text_field :postalcode, :size => 20
end |
require 'helper'
describe Esendex::Client do
subject { Esendex::Client }
describe '.get' do
let(:credentials) { dummy_credentials }
let(:path) { "some/url/path" }
let(:args) { { query: "what", thing: "yep" } }
let(:expected_code) { 418 }
let(:expected_body) { "Hi I'm a body" }
let(:uri) { mock }
let(:form_params) { mock }
let(:http) { mock }
let(:get_request) { mock }
before {
URI.expects(:encode_www_form).with(args).returns(form_params)
uri.expects(:query=).with(form_params)
subject.expects(:url).with(path).returns(uri)
subject
.expects(:execute)
.with(credentials, get_request)
.returns([expected_code, expected_body])
Net::HTTP::Get.expects(:new).with(uri).returns(get_request)
}
it 'returns the expected status code' do
code, _ = subject.get(credentials, path, args)
code.must_equal expected_code
end
it 'returns the expected body' do
_, body = subject.get(credentials, path, args)
body.must_equal expected_body
end
end
describe '.get' do
let(:credentials) { dummy_credentials }
let(:path) { "some/url/path" }
let(:expected_code) { 418 }
let(:expected_body) { "Hi I'm a body" }
let(:uri) { mock }
let(:http) { mock }
let(:get_request) { mock }
before {
subject.expects(:url).with(path).returns(uri)
subject
.expects(:execute)
.with(credentials, get_request)
.returns([expected_code, expected_body])
Net::HTTP::Delete.expects(:new).with(uri).returns(get_request)
}
it 'returns the expected status code' do
code, _ = subject.delete(credentials, path)
code.must_equal expected_code
end
it 'returns the expected body' do
_, body = subject.delete(credentials, path)
body.must_equal expected_body
end
end
describe '.post' do
let(:credentials) { dummy_credentials }
let(:path) { "some/url/path?query=yah" }
let(:expected_code) { 418 }
let(:expected_body) { "Hi I'm a body" }
let(:xml) { "</xml>" }
let(:serialisable_object) { stub(serialise: xml) }
let(:post_request) { mock }
before {
subject
.expects(:execute)
.with(credentials, post_request)
.returns([expected_code, expected_body])
Net::HTTP::Post
.expects(:new)
.with(subject::ROOT + path)
.returns(post_request)
post_request
.expects(:body=)
.with(xml)
post_request
.expects(:content_type=)
.with('application/xml')
}
it 'returns the expected status code' do
code, _ = subject.post(credentials, path, serialisable_object)
code.must_equal expected_code
end
it 'returns the expected body' do
_, body = subject.post(credentials, path, serialisable_object)
body.must_equal expected_body
end
end
describe '.put' do
let(:credentials) { dummy_credentials }
let(:path) { "some/url/path?query=yah" }
let(:expected_code) { 418 }
let(:expected_body) { "Hi I'm a body" }
let(:xml) { "</xml>" }
let(:serialisable_object) { stub(serialise: xml) }
let(:post_request) { mock }
before {
subject
.expects(:execute)
.with(credentials, post_request)
.returns([expected_code, expected_body])
Net::HTTP::Put
.expects(:new)
.with(subject::ROOT + path)
.returns(post_request)
post_request
.expects(:body=)
.with(xml)
post_request
.expects(:content_type=)
.with('application/xml')
}
it 'returns the expected status code' do
code, _ = subject.put(credentials, path, serialisable_object)
code.must_equal expected_code
end
it 'returns the expected body' do
_, body = subject.put(credentials, path, serialisable_object)
body.must_equal expected_body
end
end
describe '.execute' do
let(:username) { 'myusername' }
let(:password) { 'mypassword' }
let(:credentials) { Esendex::Credentials.new(username, password) }
let(:expected_code) { 418 }
let(:expected_body) { "Hi I'm a body" }
let(:http) { mock }
let(:request) { mock }
let(:response) { stub(body: expected_body, code: expected_code) }
before {
Net::HTTP
.expects(:start)
.with(subject::ROOT.host, subject::ROOT.port, use_ssl: true)
.yields(http)
.returns(expected_code, expected_body)
request
.expects(:[]=)
.with("User-Agent", subject::USER_AGENT)
request
.expects(:basic_auth)
.with(username, password)
http
.expects(:request)
.with(request)
.returns(response)
}
it 'returns the expected status code' do
code, _ = subject.send(:execute, credentials, request)
code.must_equal expected_code
end
it 'returns the expected body' do
_, body = subject.send(:execute, credentials, request)
body.must_equal expected_body
end
end
end
|
require 'spec_helper'
module Dustbag
describe Items do
include_context 'load xml from fixture'
it_behaves_like 'a collection node of', Item
describe '#request' do
it { expect(subject.request).to be_a_kind_of Request }
end
describe '#total_results' do
it { expect(subject.total_results).to eq 1630787 }
end
describe '#total_pages' do
it { expect(subject.total_pages).to eq 163079 }
end
describe '#more_search_results_url' do
it { expect(subject.more_search_results_url).to eq 'http://www.amazon.com/gp/redirect.html?linkCode=xm2&SubscriptionId=MyAccessKeyId&location=http%3A%2F%2Fwww.amazon.com%2Fgp%2Fsearch%3Fkeywords%3Dmoto%2Bg%26url%3Dsearch-alias%253Daws-amazon-aps&tag=affiliate-tag&creative=386001&camp=2025' }
end
end
end
|
ENV['RACK_ENV'] = 'test'
require 'rack/test'
require 'minitest/autorun'
require_relative '../todo'
require './lib/todo_helpers'
require './lib/task_store'
require './lib/task'
require 'sinatra'
enable :sessions
class TestToDoHelpers < Minitest::Test
include Rack::Test::Methods
def app
Sinatra::Application
end
def setup
sleep 0.2
@store = TaskStore.new
@my_own_store = TaskStore.new(1) # #1 will always be a test store
@users = UserStore.new('users.yml')
end
def test_compile_categories
# setup objects
# dummy data mimics user input
params = {"description" => "Test task 123", "categories" => "foo, bar"}
@task1 = Task.new(@store, params)
@task1.categories["deleted"] = true
@task1.categories["foobar"] = true
@store.save(@task1)
@task2 = Task.new(@store, params)
@task2.categories["completed"] = true
@task2.categories["foobar"] = true
@store.save(@task2)
@task3 = Task.new(@store, params)
@task3.categories[nil] = "foobar"
@store.save(@task3)
@task4 = Task.new(@store, params)
@task4.categories["deleted"] = true
@task4.categories["completed"] = true
@store.save(@task4)
@tasks = @store.all
# list of items that should be deleted; update if you add more "deleted"s
@testers_to_delete = [@task1, @task4]
@testers_to_delete_length = @testers_to_delete.length
# removes "deleted" and "completed" from categories
refute(compile_categories(@tasks).include?("deleted"))
refute(compile_categories(@tasks).include?("completed"))
# includes categories only once (no duplicates)
assert(1, compile_categories(@tasks).count {|x| x == "foo"})
# rejects the nil category
refute(compile_categories(@tasks).include? nil)
# ACTUALLY TESTS test_delete_forever_all
@store_length_before_deletion = @store.all.length
@store = delete_forever_all(@store, @testers_to_delete)
sleep 0.2
@store_length_after_deletion = @store.all.length
assert_equal(@testers_to_delete_length, @store_length_before_deletion -
@store_length_after_deletion)
# teardown objects
@store.delete_forever(@task1.id)
@store.delete_forever(@task2.id)
@store.delete_forever(@task3.id)
@store.delete_forever(@task4.id)
sleep 0.4
end
def test_validate_email
# email validates (or doesn't)--different addresses validate
assert(validate_email("yo.larrysanger@gmail.com")) # returns true if valid
assert(validate_email("president@whitehouse.gov"))
# refute(validate_email("foo..bar@gmail.com")) # fine, I won't validate that
refute(validate_email("president@@whitehouse.gov"))
refute(validate_email("foo#bar.com"))
refute(validate_email("foo@bar&com"))
refute(validate_email("bazqux"))
refute(validate_email("google.com"))
refute(validate_email("foo@"))
refute(validate_email("foo@bar"))
refute(validate_email("@bar.com"))
refute(validate_email("@bar"))
end
def test_email_not_duplicate
# create new account using foo@bar.com
test1 = User.new("foo@bar.com", "asdf1234", assign_user_id(@users))
@users.save(test1)
# a second instance of the address doesn't validate
refute(email_not_duplicate("foo@bar.com", @users))
# teardown this test user
@users.delete_forever(test1.id)
sleep 0.2
end
def test_validate_pwd
# validates OK password
assert(validate_pwd("asdf8asdf"))
# must be at least eight characters long
assert_equal(validate_pwd("asd5"),"Password must have at least 8 characters. ")
# must contain a number
assert_equal(validate_pwd("asdfasdf"),"Password must have at least one number. ")
# must contain a letter
assert_equal(validate_pwd("12341234"),"Password must have at least one letter. ")
end
def test_passwords_match
# if two input passwords match, return true; else, return false
assert(passwords_match("foobar98", "foobar98"))
refute(passwords_match("foobar98", "foobar99"))
end
def test_confirm_credentials
# create an account for testing
testuser = User.new("foo@bar.com", "asdf1234", assign_user_id(@users))
@users.save(testuser)
# given the user's email and password, test if the user can log in
assert(confirm_credentials("foo@bar.com", "asdf1234", @users))
# test that a zany, never-to-be-seen username and password don't log in
refute(confirm_credentials("jkkdoalk@asdkflkjsadl.wmx", "asdf1234", @users))
# teardown this test user
@users.delete_forever(testuser.id)
sleep 0.2
end
# NOT TESTING THIS BECAUSE I CAN'T (WON'T) PASS SESSION VARIABLES AND
# I REFUSE TO EDIT THE TARGET METHOD TO FIT THE TEST...SEEMS A BAD IDEA.
def test_check_and_maybe_load_taskstore
=begin
# if logging in, .path should equal /userdata/foo
session[:id] = 1 # should simulate logging in
logged_in_store = check_and_maybe_load_taskstore(@store)
assert_match(/\/userdata\//, logged_in_store.path) # a /tmp/ path has been called
# if logging out, .path should equal /tmp/foo
session.clear # should simulate logging out
logged_out_store = check_and_maybe_load_taskstore(@my_own_store)
assert_match(/\/tmp\//, logged_in_store.path) # a /tmp/ path has been called
=end
end
def teardown
end
=begin
* NEXT: Go through the list below and retire items that are done.
* Auto-create /tmp and /userdata as needed
* Post question on Stack Overflow about the seeming Process problem
First research "Errno::EACCES: Permission denied @ unlink_internal" some more.
* DONE: check_and_maybe_load_taskstore requirements:
* IF
task store exists
session[:id] doesn't exist
task store path = /tmp/
THEN return the task store submitted
* IF
task store exists
session[:id] doesn't exist
task store path = /userdata/
THEN let store = TaskStore.new
* IF
task store exists
session[:id] exists
task store path = /userdata/
THEN return the task store submitted
* If
task store exists
session[:id] exists
task store path = /tmp/
THEN let store = TaskStore.new(session[:id])
* If
task store doesn't exist
session[:id] doesn't exist
THEN let store = TaskStore.new
* If
task store doesn't exist
session[:id] exists
THEN let store = TaskStore.new(session[:id])
* NOTE: it IS possible for someone to arrive at this method without any
TaskStore having been loaded. On the other hand, you certainly don't want
to load it every time the method is called. Therefore, you need to check
if it's loaded first.
* At the beginning of every 'get' route, perform check that the right datafile
is loaded. To perform this check, determine whether the task store's path
includes '/userdata/' or else '/tmp/'. If /userdata/, and session[:id] exists,
do nothing (or load the right file if not done already); but if session[:id]
doesn't exist, then re-initialize 'store' (i.e., store = TaskStore.new). If
/tmp/, and session[:id] doesn't exist, do nothing (or, again, load the right
file if not done already); but if session[:id] does exist, then re-initialize
'store' like this: store = TaskStore.new(session[:id]). THEN RELOAD THE PAGE
so that the proper data shows up!
* In to_do_helpers.rb (to execute code WITH id!)
* write check_task_store, which will actually toggle the used store from
/tmp and /userdata and back.
* When the user logs in, this should create a new TaskStore object, loading data
from the associated user datafile, *and* this object should then (and
thereafter) be associated with store. Make the datafile live at userdata/<id>.
Make temporary data live at tmp/<temp_id>. (See below for details.)
* When a new TaskStore is initialized, store its storage path. How will it get
it? Well, from a passed parameter. Presumably, if session[:id] exists, then
TaskStore will be initialized something like this:
TaskStore.new(session[:id])
But if no param is passed, then .storage_path is populated according to a
TaskStore method that picks the next available ID in ./tmp.
* DONE: Edit calls to TaskStore.new (to remove file_name as necessary).
* DONE: Write determine_path.
* DONE: Write tests for determine_path.
* DONE: Get them to pass.
* Then test that everything still works.
* DONE: In task_store.rb
* DONE: edit param
* DONE: add attr_accessor for :path
* DONE: add method for assigning .path
* DONE: add method to delete path
* DONE: test code works without id passed
* FIXED: find out why /tmp/ number doesn't increase (stays on 1.yml)
* YES: find out whether you want the number to increase
* DONE: write tests for code WITH id
=end
end
|
class ApplicationController < ActionController::Base
before_action :basic if Rails.env.production?
protect_from_forgery with: :exception
include SessionsHelper
private
def require_user_logged_in
unless logged_in?
redirect_to login_url
end
end
def counts(user)
@count_plans = user.plans.count
@count_followings = user.followings.count
@count_followers = user.followers.count
end
def basic
authenticate_or_request_with_http_basic do |user, pass|
user == 'tabino' && pass == 'shiori'
end
end
end
|
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.admin?
can :manage, :admin
can :manage, :groupings
can :manage, :institutions
can :manage, :notices
can :manage, :states
can :manage, :users
else
can :access, :pages
end
end
end
|
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
Gem::Specification.new do |s|
s.name = 'zero_logger'
s.version = '0.0.1'
s.date = '2018-04-10'
s.summary = "Indent console output for cli"
s.description = "Using zero logger to add indent of the output of programs"
s.authors = ["Albert Yangchuanosaurus"]
s.email = '355592261@qq.com'
s.files = `git ls-files`.split("\n")
#s.require_paths << 'templates' # template resources
s.homepage =
'https://github.com/yangchuanosaurus/ZeroLogger'
s.license = 'MIT'
s.required_ruby_version = '>= 2.4.0'
end |
$:.push File.expand_path('../lib', __FILE__)
require 'filmbuff/version'
Gem::Specification.new do |s|
s.name = 'filmbuff'
s.version = FilmBuff::VERSION
s.authors = ['Kristoffer Sachse']
s.email = ['hello@kristoffer.is']
s.homepage = 'https://github.com/sachse/filmbuff'
s.summary = 'A Ruby wrapper for IMDb\'s JSON API'
s.description = 'Film Buff provides a Ruby wrapper for IMDb\'s JSON API, ' <<
'which is the fastest and easiest way to get information ' <<
'from IMDb.'
s.required_ruby_version = '>= 1.9'
s.add_dependency('faraday', '~> 0.8')
s.add_dependency('faraday_middleware', '~> 0.8')
s.add_dependency('faraday-http-cache', '~> 0.1')
s.add_development_dependency('minitest', '>= 1.4.0')
s.add_development_dependency('vcr', '>= 2.4')
s.add_development_dependency('yard', '>= 0.8.5.2')
s.add_development_dependency('kramdown')
s.add_development_dependency('simplecov')
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test}/*`.split("\n")
s.require_paths = ['lib']
end
|
# frozen_string_literal: true
Given("there is an extant species Lasius niger in a fossil genus") do
genus = create :genus, protonym: create(:protonym, :genus_group, :fossil)
create :species, name_string: "Lasius niger", genus: genus
end
Given("I open all database scripts one by one") do
script_names = DatabaseScript.all.map(&:to_param)
script_names.each do |script_name|
step %(I open the database script "#{script_name}")
end
end
When("I open the database script {string}") do |database_script_name|
visit "/database_scripts/#{database_script_name}"
step 'I should see "Show source"' # Anything to confirm the page was rendered.
end
|
module SportsDataApi
module Mlb
class Exception < ::Exception
end
DIR = File.join(File.dirname(__FILE__), 'mlb')
BASE_URL = 'http://api.sportsdatallc.org/mlb-%{access_level}%{version}'
DEFAULT_VERSION = 4
SPORT = :mlb
autoload :Team, File.join(DIR, 'team')
autoload :Teams, File.join(DIR, 'teams')
autoload :Player, File.join(DIR, 'player')
autoload :Players, File.join(DIR, 'players')
autoload :Game, File.join(DIR, 'game')
autoload :Games, File.join(DIR, 'games')
autoload :Season, File.join(DIR, 'season')
autoload :Broadcast, File.join(DIR, 'broadcast')
autoload :GameStat, File.join(DIR,'game_stat')
autoload :GameStats, File.join(DIR, 'game_stats')
autoload :Boxscore, File.join(DIR, 'boxscore')
autoload :Venue, File.join(DIR, 'venue')
autoload :Venues, File.join(DIR, 'venues')
autoload :TeamSeasonStats, File.join(DIR, 'team_season_stats')
autoload :PlayerSeasonStats, File.join(DIR, 'player_season_stats')
autoload :Standings, File.join(DIR, 'standings')
##
# Fetches all NBA teams
def self.teams(year=Date.today.year, version = DEFAULT_VERSION)
response = self.response_xml(version, "/teams/#{year}.xml")
return Teams.new(response.xpath('/teams'))
end
##
# Fetches MLB season schedule for a given year and season
def self.schedule(year=Date.today.year, version = DEFAULT_VERSION)
response = self.response_xml(version, "/schedule/#{year}.xml")
return Season.new(response.xpath("calendars"))
end
##
# Fetches MLB daily schedule for a given date
def self.daily(year, month, day, version = DEFAULT_VERSION)
response = self.response_xml(version, "/daily/schedule/#{year}/#{month}/#{day}.xml")
return Games.new(response.xpath("calendars"))
end
##
# Fetches MLB venues
def self.venues(version = DEFAULT_VERSION)
response = self.response_xml(version, "/venues/venues.xml")
return Venues.new(response.xpath("venues"))
end
##
# Fetch MLB game stats
def self.game_statistics(event_id, version = DEFAULT_VERSION )
response = self.response_xml(version, "/statistics/#{event_id}.xml")
return GameStats.new(response.xpath("/statistics"))
end
##
# Fetch MLB Game Boxscore
def self.game_boxscore(event_id, version = DEFAULT_VERSION )
response = self.response_xml(version, "/boxscore/#{event_id}.xml")
return Boxscore.new(response.xpath("/boxscore"))
end
##
# Fetches MLB team roster
def self.team_roster(year=Date.today.year, version = DEFAULT_VERSION)
response = self.response_xml(version, "/rosters-full/#{year}.xml")
return Players.new(response.xpath("rosters"))
end
##
# Fetches MLB team stats
def self.team_season_stats(year, version = DEFAULT_VERSION)
response = self.response_xml(version, "/seasontd/teams/#{year}.xml")
TeamSeasonStats.new(response.xpath('statistics'))
end
##
# Fetches MLB player season stats and returns for EVERY PLAYER ARE YOU SERIOUS
def self.player_season_stats(year, version = DEFAULT_VERSION)
response = self.response_xml(version, "/seasontd/players/#{year}.xml")
PlayerSeasonStats.new(response.xpath('statistics'))
end
##
# Fetches MLB divisional standings
def self.standings(year, version = DEFAULT_VERSION)
response = self.response_xml(version, "/rankings/#{year}.xml")
Standings.new(response.xpath('rankings').first)
end
private
def self.response_xml(version, url)
base_url = BASE_URL % { access_level: SportsDataApi.access_level(SPORT), version: version }
response = SportsDataApi.generic_request("#{base_url}#{url}", SPORT)
Nokogiri::XML(response.to_s).remove_namespaces!
end
end
end
|
class Beta03 < ActiveRecord::Migration
def self.up
create_table :compliments do |t|
t.column :review_id, :integer
t.column :user_id, :integer
t.column :from_user_id, :integer
t.column :created_at, :datetime
t.column :text, :text
end
add_index :compliments, :review_id
add_index :compliments, :user_id
add_index :compliments, :from_user_id
create_table :user_stats do |t|
t.column :user_id, :string
t.column :reviews_written, :integer
t.column :compliments, :integer
t.column :friends, :integer
t.column :fans, :integer
end
add_index :user_stats, :user_id
end
def self.down
drop_table :compliments
drop_table :user_stats
end
end
|
namespace :prep do
desc 'Expose reoccurring events, correct occurrences dates'
task :do => :environment do
Occurrence.correct_dates
#Occurrence.expose
Occurrence.correct_categories
Event.correct_images
end
task :expose => :environment do
#Occurrence.correct_category
Occurrence.expose
end
task :unexpose => :environment do
Occurrence.expose :revert => true
end
desc 'Fixes event data in order to show it simplier and faster. Should run once a day.'
task :correct_dates => :environment do
#Attribute.recount # Recount categories
# Expose week-day-only repeating events (like Teatro)
Occurrence.correct_dates
end
task :correct_categories => :environment do
Occurrence.correct_categories
end
task :remove_duplicates => :environment do
Occurrence.delete_duplicates
end
task :images => :environment do
Event.correct_images
end
end
|
require 'spec_helper'
describe RightBranch::Updater do
let(:gh) { double(:github) }
let(:repo) { 'doge/wow' }
let(:updater) { described_class.new(repository: repo) }
before { allow(updater).to receive(:github).and_return(gh) }
describe '#resubmit_pr' do
it 'creats new pull request againts branch' do
original_pr_number = 1
title, body, label, branch = %w(title body label branch)
pr = { title: 'title', body: 'body', head: { label: 'label' } }
allow(updater).to receive(:get_pr).with(original_pr_number).and_return(pr)
expect(gh).to receive(:create_pull_request).with \
repo, branch, label, title, body
updater.send(:resubmit_pr, original_pr_number, branch)
end
end
describe '#run!' do
it 'resubmits original pull request' do
original = '1'
branch = 'test'
allow(updater).to receive(:comment_on_issue)
allow(updater).to receive(:update_pr)
expect(updater).to receive(:resubmit_pr)
.with(original, branch).and_return double(number: '2')
updater.run!(original, branch)
end
it 'closes original pr' do
original = '1'
new_pr = double(:new_pr, number: '2')
allow(updater).to receive(:resubmit_pr).and_return new_pr
allow(updater).to receive(:comment_on_issue)
expect(updater).to receive(:update_pr).with \
original, state: 'closed'
updater.run!(original, 'testing')
end
it 'comment on original pr with new pr number' do
original = '1'
new_pr = double(:new_pr, number: '2')
allow(updater).to receive(:resubmit_pr).and_return new_pr
allow(updater).to receive(:update_pr)
allow(updater).to receive(:comment_on_issue).with \
original, 'Reopened against `testing` (#2)'
updater.run!(original, 'testing')
end
end
end
|
RSpec.describe Zenform::Param::RuleBase do
module Zenform
module Param
class DummyContentForRuleBase < RuleBase
FIELDS = %w{field value}
FIELDS.each { |f| attr_reader f }
end
end
end
let(:klass) { Zenform::Param::DummyContentForRuleBase }
let(:instance) { klass.new content, ticket_fields: ticket_fields, ticket_forms: ticket_forms }
let(:content) { base_content }
let(:base_content) { { "field" => field, "value" => value } }
let(:field) { "ticket_form_id" }
let(:value) { "ticket_form_user" }
let(:client) { double "ZendeskAPI::Client" }
let(:ticket_fields) { base_ticket_fields }
let(:base_ticket_fields) { { "ticket_field_os" => ticket_field_os, "ticket_field_user_id" => ticket_field_user_id } }
let(:ticket_field_os) { { "id" => 100, "name" => "os" } }
let(:ticket_field_user_id) { { "id" => 99, "name" => "user_id" } }
let(:ticket_forms) { base_ticket_forms }
let(:base_ticket_forms) { { "ticket_form_agent" => ticket_form_agent, "ticket_form_user" => ticket_form_user } }
let(:ticket_form_agent) { { "id" => 200, "name" => "For agent" } }
let(:ticket_form_user) { { "id" => 201, "name" => "For user" } }
describe "#value" do
subject { instance.value }
context "value is not array" do
it { is_expected.to eq "ticket_form_user" }
end
context "value is array" do
context "value size is 1" do
let(:value) { ["ticket_form_user"] }
it { is_expected.to eq "ticket_form_user" }
end
context "value size is over 1" do
let(:field) { "notification_user" }
let(:value) { [123, "message subject", "mssage body"] }
it { is_expected.to eq value }
end
end
end
describe "#validate!" do
subject { -> { instance.validate! } }
context "invalid" do
let(:value) { "ticket_form_dummy_slug" }
it { is_expected.to raise_error Zenform::ContentError }
end
context "valid" do
it { is_expected.not_to raise_error }
end
end
describe "#format" do
subject { instance.format }
context "value includes ticket_forms slug" do
let(:expected) { { "field" => field, "value" => ticket_forms[value]["id"] } }
it { is_expected.to eq expected }
end
context "value includes ticket_forms slug" do
let(:field) { "ticket_field_os" }
let(:value) { "iOS" }
let(:expected) do
{
"field" => Zenform::Param::RuleBase::FIELD_PARAM_FOR_TICKET_FIELD % { id: ticket_fields[field]["id"] },
"value" => value
}
end
it { is_expected.to eq expected }
end
end
end
|
# coding: utf-8
class DepartmentsController < ApplicationController
before_filter :auth_required
def index
end
def search
@items = Department.order(:name)
if !params[:q].blank?
@items = @items.where("(name LIKE :q)", {:q => "%#{params[:q]}%"})
end
render :layout => false
end
def new
@department = Department.new
render :layout => false
end
def create
@department= Department.new(department_params)
flash = {}
if @department.save
flash[:notice] = "Departamento creado satisfactoriamente."
# LOG
@department.activity_log.create(user_id: current_user.id,
message: "Creó el departamento \"#{@department.name}\" (ID: #{@department.id}).")
json = {}
json[:id] = @department.id
json[:title] = @department.name
json[:flash] = flash
render :json => json
else
flash[:error] = "No se pudo crear el departamento."
json = {}
json[:flash] = flash
json[:model_name] = self.class.name.sub("Controller", "").singularize
json[:errors] = {}
json[:errors] = @department.errors
render :json => json, :status => :unprocessable_entity
end
end
def show
@department = Department.find(params[:id])
render :layout => false
end
def update
@department = Department.find(params[:id])
@department.last_updated_by = current_user.id
flash = {}
if @department.update_attributes(department_params)
flash[:notice] = "El departamento esta actualizado satisfactoriamente."
json = {}
json[:id] = @department.id
json[:title] = @department.name
json[:flash] = flash
render :json => json
else
flash[:error] = "No se pudo actualizar el departamento."
json = {}
json[:flash] = flash
json[:model_name] = self.class.name.sub("Controller", "").singularize
json[:errors] = {}
json[:errors] = @department.errors
render :json => json, :status => :unprocessable_entity
end
end
protected
def department_params
params[:department].permit(:name, :code, :description, :user_id)
end
end
|
# frozen_string_literal: true
# rubocop:todo all
require 'spec_helper'
describe 'Bulk insert' do
include PrimarySocket
let(:fail_point_base_command) do
{ 'configureFailPoint' => "failCommand" }
end
let(:collection_name) { 'bulk_insert_spec' }
let(:collection) { authorized_client[collection_name] }
describe 'inserted_ids' do
before do
collection.delete_many
end
context 'success' do
it 'returns one insert_id as array' do
result = collection.insert_many([
{:_id => 9},
])
expect(result.inserted_ids).to eql([9])
end
end
context 'error on first insert' do
it 'is an empty array' do
collection.insert_one(:_id => 9)
begin
result = collection.insert_many([
{:_id => 9},
])
fail 'Should have raised'
rescue Mongo::Error::BulkWriteError => e
expect(e.result['inserted_ids']).to eql([])
end
end
end
context 'error on third insert' do
it 'is an array of the first two ids' do
collection.insert_one(:_id => 9)
begin
result = collection.insert_many([
{:_id => 7},
{:_id => 8},
{:_id => 9},
])
fail 'Should have raised'
rescue Mongo::Error::BulkWriteError => e
expect(e.result['inserted_ids']).to eql([7, 8])
end
end
end
context 'entire operation fails' do
min_server_fcv '4.0'
require_topology :single, :replica_set
it 'is an empty array' do
collection.client.use(:admin).command(fail_point_base_command.merge(
:mode => {:times => 1},
:data => {:failCommands => ['insert'], errorCode: 100}))
begin
result = collection.insert_many([
{:_id => 7},
{:_id => 8},
{:_id => 9},
])
fail 'Should have raised'
rescue Mongo::Error => e
result = e.send(:instance_variable_get, '@result')
expect(result).to be_a(Mongo::Operation::Insert::BulkResult)
expect(result.inserted_ids).to eql([])
end
end
end
end
end
|
module Billing::ChargesHelper
def charge_header_tag(charge)
class_name, title = if charge.paid?
["success", "TRANSACCIÓN EXITOSA"]
elsif charge.created? || charge.pending?
["info", "PENDIENTE POR CONFIRMAR"]
elsif charge.error?
["danger", "ERROR EN LA TRANSACCIÓN"]
elsif charge.rejected?
["danger", "TRANSACCIÓN RECHAZADA"]
end
content_tag 'div', "<strong>#{title}</strong>".html_safe, class: "alert alert-#{class_name}"
end
end
|
require 'game'
describe Game do
let(:game) { Game.new }
it "should score all gutter balls as 0" do
game.score("--" * 10).should == 0
end
it "should score single rolls in each frame" do
game.score("9-"*10).should == 90
end
context "spares" do
it "should score a spare without points in the next roll" do
game.score("5/" + "--"*9).should == 10
end
it "should score a spare with points in the next roll" do
game.score("5/5-" + "--"*8).should == 20
end
end
context "strikes" do
it "should score a strike without points in the next roll" do
game.score("X" + "--"*9).should == 10
end
it "should score a strike with points in the next roll" do
game.score("X" + "5-" + "--"*8).should == 20
end
it "should score three consequtive strikes" do
game.score("XXX" + "--"*7).should == 60
end
end
context "extended last frame" do
it "should score with a spare in the second roll" do
game.score("--"*9 + "3/5").should == 15
end
it "should score with a strike as the extended throw" do
game.score("--"*9 + "XXX").should == 30
end
end
it "should score the perfect game" do
game.score("X"*12).should == 300
end
end
describe Parse do
include Parse
it "should parse dashes into frames" do
parse("--").should have(1).frame
parse("----").should have(2).frame
end
it "should parse strikes into frames" do
parse("X").should have(1).frame
parse("XX").should have(2).frames
parse("X--").should have(2).frames
end
it "should parse an extended game into frames" do
parse("--"*9+"3/5").should have(10).frames
parse("--"*9+"XXX").should have(10).frames
end
end
def first_of_rolls(*chars)
new_rolls = chars.map {|char| Roll.new(char)}
new_rolls.each_cons(2) {|roll, next_roll| next_roll.previous = roll; roll.next = next_roll}
new_rolls.first
end
describe Roll do
it { Roll.new("-").score.should == 0 }
it { Roll.new("3").score.should == 3 }
it { Roll.new("X").score.should == 10 }
it { Roll.new("X").should be_a_strike }
it "should provide a score for a spare" do
current_roll = Roll.new("/")
current_roll.previous = Roll.new("3")
current_roll.score.should == 7
current_roll.should be_a_spare
end
it "should provide the next rolls" do
roll = first_of_rolls("3", "4", "5")
roll.and_the_next(1).should have(2).rolls
roll.and_the_next(2).should have(3).rolls
roll.and_the_next(1).map(&:score).inject(:+).should == 7
roll.and_the_next(2).map(&:score).inject(:+).should == 12
end
end
def new_frame(first_roll, second_roll)
r1 = Roll.new(first_roll)
r2 = Roll.new(second_roll)
r1.next = r2
Frame.new(r1)
end
describe Frame do
context "gutter frame" do
it { new_frame("-", "-").score.should == 0 }
end
context "frame with the second roll being a gutter ball" do
it { new_frame("5", "-").score.should == 5}
end
context "frame with pins standing" do
it { new_frame("1", "2").score.should == 3 }
end
end
describe StrikeOrSpareFrame do
context "spares" do
let(:frame) { StrikeOrSpareFrame.new(first_of_rolls("3", "/", "5")) }
it { frame.score.should == 15 }
end
context "strikes" do
let(:frame) { StrikeOrSpareFrame.new(first_of_rolls("X", "5", "3")) }
it { frame.score.should == 18 }
end
context "last frame" do
it { StrikeOrSpareFrame.new(first_of_rolls("3", "/", "3")).score.should == 13 }
end
end |
require 'spec_helper'
describe Game do
it { should have_db_column(:winner_id).of_type(:integer) }
it { should have_db_column(:loser_id).of_type(:integer) }
it { should belong_to :winner }
it { should belong_to :loser }
it { should have_many :user_games }
it { should have_many :users }
it { should have_many :moves }
it { should have_many :pieces }
it { should have_one :board }
context ".empty_space?" do
Board.create(coord:'31', is_occupied: false, game_id: 1)
Board.create(coord:'00', is_occupied: true, game_id: 1)
it "method returns true if the destination space is empty" do
expect(Game.empty_space?('31')).to eq true
end
it "method returns false if the destination space is not empty" do
expect(Game.empty_space?('00')).to eq false
end
end
context ".move_distance_calculation" do
it "should return positive one" do
expect(Game.move_distance_calculation('51', '40', 'B12')).to eq 1
end
it "should return positive two" do
expect(Game.move_distance_calculation('51', '33', 'B12')).to eq 2
end
it "should return negative one" do
expect(Game.move_distance_calculation('26', '37', 'R12')).to eq -1
end
it "should return negative two" do
expect(Game.move_distance_calculation('26', '44', 'R12')).to eq -2
end
it "should return false" do
expect(Game.move_distance_calculation('26', '53', 'R12')).to eq false
end
it "should return false" do
expect(Game.move_distance_calculation('53', '26', 'R12')).to eq false
end
end
context ".valid_row_dist? for top to bottom" do
it "should return true if destination row index equals the starting row index plus the move distance" do
expect(Game.valid_row_dist?('24', '35', -1)).to eq true
end
it "should return false if destination row index does not equal the starting row index plus the move distance" do
expect(Game.valid_row_dist?('24', '37', false)).to eq false
end
end
context ".valid_row_dist? for bottom to top" do
it "should return true if destination row index equals the starting row index plus the move distance" do
expect(Game.valid_row_dist?('53', '44', 1)).to eq true
end
it "should return false if destination row index does not equal the starting row index plus the move distance" do
expect(Game.valid_row_dist?('53', '40', false)).to eq false
end
end
context ".valid_col_dist? for top to bottom" do
it "should return true if destination column index equals the starting column index plus the move distance" do
expect(Game.valid_col_dist?('24', '35', -1)).to eq true
end
it "should return false if destination column index does not equal the starting column index plus the move distance" do
expect(Game.valid_col_dist?('24', '37', -1)).to eq false
end
end
context ".valid_col_dist for bottom to top" do
it "should return true if destination column index equals the starting column index plus the move distance" do
expect(Game.valid_col_dist?('53', '44', 1)).to eq true
end
it "should return false if destination column index does not equal the starting column index plus the move distance" do
expect(Game.valid_col_dist?('53', '40', 1)).to eq false
end
end
context ".valid_move? top to bottom" do
it "should return true if the move is valid top to bottom non-jump move" do
expect(Game.valid_move?('24', '35', 'R11')).to eq true
end
it "should return false if the move is move is invalid top to bottom non-jump move" do
expect(Game.valid_move?('24', '37', 'R11')).to eq false
end
it "method returns true if the move is valid jump move" do
expect(Game.valid_move?('24', '46', 'R11')).to eq true
end
it "method returns false if the move is invalid jump move" do
expect(Game.valid_move?('24', '57', 'R11')).to eq false
end
end
context ".valid_move? bottom to top" do
it "should return true if the move is valid non-jump move" do
expect(Game.valid_move?('53', '31', 'B11')).to eq true
end
it "should return false if the move is move is invalid non-jump move" do
expect(Game.valid_move?('53', '40', 'B11')).to eq false
end
it "should return true if the move is valid jump move" do
expect(Game.valid_move?('53', '31', 'B11')).to eq true
end
it "should return false if the move is invalid jump move" do
expect(Game.valid_move?('53', '22', 'B11')).to eq false
end
end
context ".player_move_direction" do
it "should return a positive integer if the player is Red" do
expect(Game.player_move_direction('R11')).to eq -1
end
it "should return a positive integer if the player is Black" do
expect(Game.player_move_direction('B11')).to eq 1
end
end
context ".find_square_between_origin_and_destination" do
it "should return the coord of the square between the start and end locations during a jump move" do
expect(Game.find_square_between_origin_and_destination('53', '31')).to eq '42'
end
it "should return the coord of the square between the start and end locations during a jump move" do
expect(Game.find_square_between_origin_and_destination('24', '46')).to eq '35'
end
it "should return the coord of the square between the start and end locations during a jump move" do
expect(Game.find_square_between_origin_and_destination('26', '44')).to eq '35'
end
end
context ".opponent_in_jump_midpoint?" do
Board.create(coord:'00', is_occupied: true, game_id: 1)
Board.create(coord:'02', is_occupied: true, game_id: 1)
Board.create(coord:'04', is_occupied: true, game_id: 1)
Board.create(coord:'06', is_occupied: true, game_id: 1)
Board.create(coord:'11', is_occupied: true, game_id: 1)
Board.create(coord:'13', is_occupied: true, game_id: 1)
Board.create(coord:'15', is_occupied: true, game_id: 1)
Board.create(coord:'17', is_occupied: true, game_id: 1)
Board.create(coord:'20', is_occupied: true, game_id: 1)
Board.create(coord:'22', is_occupied: false, game_id: 1)
Board.create(coord:'24', is_occupied: false, game_id: 1)
Board.create(coord:'26', is_occupied: true, game_id: 1)
Board.create(coord:'30', is_occupied: false, game_id: 1)
Board.create(coord:'31', is_occupied: false, game_id: 1)
Board.create(coord:'32', is_occupied: false, game_id: 1)
Board.create(coord:'33', is_occupied: true, game_id: 1)
Board.create(coord:'34', is_occupied: false, game_id: 1)
Board.create(coord:'35', is_occupied: true, game_id: 1)
Board.create(coord:'36', is_occupied: false, game_id: 1)
Board.create(coord:'37', is_occupied: false, game_id: 1)
Board.create(coord:'40', is_occupied: false, game_id: 1)
Board.create(coord:'41', is_occupied: false, game_id: 1)
Board.create(coord:'42', is_occupied: false, game_id: 1)
Board.create(coord:'43', is_occupied: false, game_id: 1)
Board.create(coord:'44', is_occupied: true, game_id: 1)
Board.create(coord:'45', is_occupied: false, game_id: 1)
Board.create(coord:'46', is_occupied: true, game_id: 1)
Board.create(coord:'47', is_occupied: false, game_id: 1)
Board.create(coord:'51', is_occupied: true, game_id: 1)
Board.create(coord:'53', is_occupied: true, game_id: 1)
Board.create(coord:'55', is_occupied: false, game_id: 1)
Board.create(coord:'57', is_occupied: false, game_id: 1)
Board.create(coord:'60', is_occupied: true, game_id: 1)
Board.create(coord:'62', is_occupied: true, game_id: 1)
Board.create(coord:'64', is_occupied: true, game_id: 1)
Board.create(coord:'66', is_occupied: true, game_id: 1)
Board.create(coord:'71', is_occupied: true, game_id: 1)
Board.create(coord:'73', is_occupied: true, game_id: 1)
Board.create(coord:'75', is_occupied: true, game_id: 1)
Board.create(coord:'77', is_occupied: true, game_id: 1)
# Top player (Red)
Piece.create(location: '00', is_king: false, game_id: 1, unique_piece_id: 'R1')
Piece.create(location: '02', is_king: false, game_id: 1, unique_piece_id: 'R2')
Piece.create(location: '04', is_king: false, game_id: 1, unique_piece_id: 'R3')
Piece.create(location: '06', is_king: false, game_id: 1, unique_piece_id: 'R4')
Piece.create(location: '11', is_king: false, game_id: 1, unique_piece_id: 'R5')
Piece.create(location: '13', is_king: false, game_id: 1, unique_piece_id: 'R6')
Piece.create(location: '15', is_king: false, game_id: 1, unique_piece_id: 'R7')
Piece.create(location: '17', is_king: false, game_id: 1, unique_piece_id: 'R8')
Piece.create(location: '20', is_king: false, game_id: 1, unique_piece_id: 'R9')
Piece.create(location: '33', is_king: false, game_id: 1, unique_piece_id: 'R10')
Piece.create(location: '35', is_king: false, game_id: 1, unique_piece_id: 'R11')
Piece.create(location: '26', is_king: false, game_id: 1, unique_piece_id: 'R12')
# Bottom player (Black)
Piece.create(location: '51', is_king: false, game_id: 1, unique_piece_id: 'B12')
Piece.create(location: '53', is_king: false, game_id: 1, unique_piece_id: 'B11')
Piece.create(location: '44', is_king: false, game_id: 1, unique_piece_id: 'B10')
Piece.create(location: '46', is_king: false, game_id: 1, unique_piece_id: 'B9')
Piece.create(location: '60', is_king: false, game_id: 1, unique_piece_id: 'B8')
Piece.create(location: '62', is_king: false, game_id: 1, unique_piece_id: 'B7')
Piece.create(location: '64', is_king: false, game_id: 1, unique_piece_id: 'B6')
Piece.create(location: '66', is_king: false, game_id: 1, unique_piece_id: 'B5')
Piece.create(location: '71', is_king: false, game_id: 1, unique_piece_id: 'B4')
Piece.create(location: '73', is_king: false, game_id: 1, unique_piece_id: 'B3')
Piece.create(location: '75', is_king: false, game_id: 1, unique_piece_id: 'B2')
Piece.create(location: '77', is_king: false, game_id: 1, unique_piece_id: 'B1')
it "should return true if the square being jumped is occupied by the opponent's piece" do
expect(Game.opponent_in_jump_midpoint?('35', '57', 'R11')).to eq true
end
it "should return true if the square being jumped is occupied by the opponent's piece" do
expect(Game.opponent_in_jump_midpoint?('44', '22', 'B10')).to eq true
end
it "should return false if the square is empty" do
expect(Game.opponent_in_jump_midpoint?('20', '42', 'R9')).to eq false
end
it "should return false if the square has the player's own piece" do
expect(Game.opponent_in_jump_midpoint?('60', '42', 'B8')).to eq false
end
end
end
|
require 'rails_helper'
RSpec.describe "StaticPages", type: :request do
describe "toppage" do
it "正常なレスポンスを返すこと" do
get root_path
expect(response).to be_success
expect(response).to have_http_status "200"
end
end
describe "aboutpage" do
it "正常なレスポンスを返すこと" do
get staticpages_about_path
expect(response).to be_success
expect(response).to have_http_status "200"
end
end
end
|
module UserBase
extend ActiveSupport::Concern
included do
## Mixin
# include Shared::Common
# include Redis::Objects
include ActiveModel::ForbiddenAttributesProtection
include ActiveModel::SecurePassword
extend Enumerize
# include Ransackable
# include Optionsable
# include Trashable
belongs_to :op, class_name: 'User', foreign_key: 'op_id'
## Validations
validates :username, uniqueness: { case_sensitive: false }, format: { with: /\A(?!_|-)([a-zA-Z0-9]|[\-_](?!_|-|$)){3,16}\z/, message: I18n.t('errors.messages.space_name') }, length: {:in => 3..16}, allow_blank: true
validates :username, exclusion: { in: %w(admin superuser guanliyuan administrator root andrew super) }
validates :email, presence: true, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/}
validates_uniqueness_of :email, case_sensitive: false#, conditions: -> { not_trashed }
validates :password, length: { minimum: 6 }, on: :create
validates_length_of :password, :minimum => 6, :if => :in_password_reset
validates :phone_number, length: { minimum: 11 }, if: :phone_number?
# validates :realname, presence: true, format: { with: /\p{Han}+/u }, length: { :minimum => 2 }
# validates :agreement, acceptance: true
# validate_harmonious_of :realname, :note
## Others
has_secure_password
enumerize :role, in: { user: 0, admin: 1 }, default: :user, predicates: true
enumerize :status, in: { pending: 0, activated: 1, banned: 2, trashed: 3 }, default: :pending
# choice_ransack :id, :username, :email, :role, :status, :created_at, :updated_at # ransack 排序
# add_options_field_methods(%w{email_bk username_bk})
attr_accessor :agreement, :login, :in_password_reset, :in_regist_info
alias_attribute :login, :username
alias_attribute :name, :email
## Redis
# value :tmp_email, expiration: 1.hour
## Callbacks
after_destroy :handle_on_after_destroy
end
module ClassMethods
def find_by_username_or_email(login)
if login.include?('@')
User.where(email: login.downcase ).first
else
User.where(username: login.downcase).first
end
end
def find_by_remember_token(token)
user = where(id: token.split('$').first).first
(user && user.remember_token == token) ? user : nil
end
def activate(id)
if id.is_a?(Array)
id.map { |one_id| activate(one_id) }
else
unscoped.find(id).activate!
end
end
def find_by_confirmation_token(token)
user_id, email, timestamp = verifier_for('confirmation').verify(token)
User.find_by(id: user_id, email: email) if timestamp > 1.hour.ago
rescue ActiveSupport::MessageVerifier::InvalidSignature
nil
end
def find_by_password_reset_token(token)
user_id, timestamp = verifier_for('password-reset').verify(token)
User.find_by(id: user_id) if timestamp > 1.hour.ago
rescue ActiveSupport::MessageVerifier::InvalidSignature
nil
end
end
def send_rename_mail(mail)
self.check_email(mail)
if self.errors.blank?
self.tmp_email = mail
UserMailer.rename_mail(self.id).deliver_later if Rails.env == 'production'
else
self.tmp_email.delete
end
end
def check_email(mail)
if /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/ =~ mail
self.errors.add :email, "email 已经存在" if User.exists?( email: mail)
else
self.errors.add :email, "email 不是一个合法的邮件地址"
end
end
def activated?
self.status.activated?
end
def remember_token
[id, Digest::SHA512.hexdigest(password_digest)].join('$')
end
def password_reset_token
self.class.verifier_for('password-reset').generate([id, Time.now])
end
def confirmation_token
self.class.verifier_for('confirmation').generate([id, email, Time.now])
end
def unlock_token
self.class.verifier_for('unlock').generate([id, email, Time.now])
end
# 激活帐号
def activate!
raise ReadOnlyRecord if readonly?
raise '不能重复激活' if self.activated?
raise '已封禁,不能激活' if self.status.banned?
self.confirmed_at = Time.now
self.status = :activated
self.save!
end
def remail!
raise ReadOnlyRecord if readonly?
raise '失败,请重新修改' if self.tmp_email.nil?
self.email = self.tmp_email.value
self.tmp_email.delete
self.confirmed_at = Time.now
self.save!
end
private
def handle_on_after_destroy
self.email_bk = self.email
self.username_bk = self.username
self.email = "trashed_#{self.id}@yeneibao.com"
self.username = "trashed_#{self.id}"
self.save
end
end
|
class ApiAbility
include CanCan::Ability
def initialize(client)
client ||= Client.new
can :manage, Order, client_id: client.id
can :manage, OrderItem, order: {client_id: client.id}
end
end
|
Rails.application.routes.draw do
# Root page
root 'home#index'
# Person
resources :person
# Pets
resources :pet
# User
get 'signup' => 'user#new'
resources :user
# Login
get 'login' => 'session#new'
delete 'logout' => 'session#destroy'
resources :session
end
|
namespace :check do
namespace :migrate do
task add_user_id_to_relationship: :environment do
# Read the last annotation id we need to process that was set at migration time.
last_id = Rails.cache.read('check:migrate:add_user_id_to_relationship:last_id')
raise "No last_id found in cache for check:migrate:add_user_id_to_relationship! Aborting." if last_id.nil?
# Get the user id from the paper trail and store it in the object itself.
rel = Version.where(item_type: 'Relationship').where('id < ?', last_id)
n = rel.count
i = 0
rel.find_each do |v|
i += 1
puts "[#{Time.now}] (#{i}/#{n}) Migrating relationship #{v.item_id}"
r = v.item
next if r.nil?
r.update_column(:user_id, v.whodunnit.to_i)
end
end
end
end
|
require 'active_support/concern'
module Decorator
extend ActiveSupport::Concern
# Better way.
module ClassMethods
attr_accessor :my_message
end
#module ClassMethods
# def my_message=(value)
# @my_message = value
# end
#
# def my_message
# @my_message
# end
#end
alias :old_to_s :to_s
def to_s
raise 'No message set' unless self.class.my_message
old_to_s + 'improved'
end
def inspect
old_to_s # This is not entirely correct because inspect does more than to_s, but did not get that far in the demo.
end
end
|
class Site2014Controller < ApplicationController
include HighVoltage::StaticPage
layout '2014/application'
def send_email
TransactionMailer.sponsor_mail(params).deliver
render nothing: true
end
end
|
#encoding: utf-8
require "spec_helper"
describe StatisticsHelper do
describe "calculate all or cetain tasks results summary" do
before(:each) do
@project = FactoryGirl.create(:project)
@task = @project.tasks.create(FactoryGirl.attributes_for(:task))
@task.reviewers.create(FactoryGirl.attributes_for(:reviewer))
@task.task_results.create(FactoryGirl.attributes_for(:task_result))
end
it "calculateAlltasksResultsSummary(tasks) returns an array of 3 arrays of integers
if results and reviewers are available" do
resultssummary = helper.calculateAllTasksResultsSummary([@task])
expect(resultssummary[0][0]).to be_kind_of(Float)
expect(resultssummary[1][0]).to be_kind_of(Float)
expect(resultssummary[2][0]).to be_kind_of(Integer)
end
it "calculateAlltasksResultsSummary(tasks) returns an array of 3 arrays of zeros
if there are no task_results or reviewers" do
task = @project.tasks.create(FactoryGirl.attributes_for(:task))
resultssummary = calculateAllTasksResultsSummary([task])
expect(resultssummary[0][0]).to eq 0
expect(resultssummary[1][0]).to eq 0
expect(resultssummary[2][0]).to eq 0
end
it "calculateResultsSummary(tasks) returns the average accumulated success and time of each task
if there are task results and reviewers" do
@task.reviewers.create(FactoryGirl.attributes_for(:reviewer))
@task.task_results.create(:success => false, :time => 6)
resultssummary = helper.calculateResultsSummary([@task])
expect(resultssummary[0][0].length).to eq(@task.reviewers.length + 1)
expect(resultssummary[0][0][1]).to eq(3)
expect(resultssummary[1][0].length).to eq(@task.reviewers.length + 1)
expect(resultssummary[1][0][1]).to eq(1)
end
it "calculateResultsSummary(tasks) returns a notice if there are no reviewers" do
task = @project.tasks.create(FactoryGirl.attributes_for(:task))
notice = helper.calculateResultsSummary([task])
expect(notice).to eq("لم يتم احد المهمة")
end
it "calculateResultsSummary(tasks) returns a notice if there are reviewers but no results" do
task = @project.tasks.create(FactoryGirl.attributes_for(:task))
task.reviewers.create(FactoryGirl.attributes_for(:reviewer))
notice = helper.calculateResultsSummary([task])
expect(notice).to eq("لا توجد نتائج")
end
end
describe "calculate statistics of reviewer information of certain task" do
before(:each) do
@project = FactoryGirl.create(:project)
@task = @project.tasks.create(FactoryGirl.attributes_for(:task))
end
it "getReviewerInfos(task) returns a notice if there are no reviewers" do
notice = helper.getReviewerInfos(@task)
expect(notice).to eq("لم يتم احد المهمة")
end
it "getReviewerInfos(task) returns a notice if there is no reviewer info for any reviewer" do
@task.reviewers.create(FactoryGirl.attributes_for(:reviewer))
arrayofnotices = helper.getReviewerInfos(@task)
expect(arrayofnotices[0]).to eq("لم يستكمل أحد المراجعين استمارة المعلومات الشخصية")
expect(arrayofnotices[1]).to eq("لم يستكمل أحد المراجعين استمارة المعلومات الشخصية")
expect(arrayofnotices[2]).to eq("لم يستكمل أحد المراجعين استمارة المعلومات الشخصية")
end
it "getReviewerInfos(task) returns a notice if a age attribute has
not been supplied by any reviewer" do
reviewer = @task.reviewers.create(FactoryGirl.attributes_for(:reviewer))
reviewer.create_reviewer_info(:gender => true, :country => "Egypt")
reviewersinfos = helper.getReviewerInfos(@task)
expect(reviewersinfos[0]).to eq("لم يجب أحد من المراجعين عن سنه")
end
it "getReviewerInfos(task) returns a notice if a country attribute has
not been supplied by any reviewer" do
reviewer = @task.reviewers.create(FactoryGirl.attributes_for(:reviewer))
reviewer.create_reviewer_info(:gender => true, :age => 19)
reviewersinfos = helper.getReviewerInfos(@task)
expect(reviewersinfos[1]).to eq("لم يجب أحد من المراجعين عن بلده")
end
it "getReviewerInfos(task) returns a notice if a gender attribute has
not been supplied by any reviewer" do
reviewer = @task.reviewers.create(FactoryGirl.attributes_for(:reviewer))
reviewer.create_reviewer_info(:age => 19, :country => "Egypt")
reviewersinfos = helper.getReviewerInfos(@task)
expect(reviewersinfos[2]).to eq("لم يجب أحد من المراجعين عن نوعه")
end
it "getReviewerInfos(task) returns an array of all attributes info if they are all supplied" do
reviewer1 = @task.reviewers.create(FactoryGirl.attributes_for(:reviewer))
reviewer1.create_reviewer_info(FactoryGirl.attributes_for(:reviewer_info))
reviewer2 = @task.reviewers.create(FactoryGirl.attributes_for(:reviewer))
reviewer2.create_reviewer_info(:age => 23, :gender => false, :country => "Egypt")
reviewer3 = @task.reviewers.create(FactoryGirl.attributes_for(:reviewer))
reviewer3.create_reviewer_info(:age => 49, :gender => false, :country => "Libya")
reviewer4 = @task.reviewers.create(FactoryGirl.attributes_for(:reviewer))
reviewer4.create_reviewer_info(:age => 84, :gender => true, :country => "Libya")
reviewersinfos = helper.getReviewerInfos(@task)
expect(reviewersinfos).to eq([[['السن أقل من 20', 'السن أقل من 40', 'السن أقل من 60', 'السن أكثر من 60'],
[1,1,1,1]], [["Egypt", "Libya"], [2, 2]], [['ذكر', 'أنثى'], [2,2]]])
end
end
it "getOccurrences(card, group) returns number of occurrences of card in group" do
project = FactoryGirl.create(:project)
cardsort = project.cardsorts.create(:title => "A", :description => "DES", :open => false)
group = cardsort.groups.create(:title => "A", :description=> "DES")
card = cardsort.cards.create(:title => "A", :description => "DES")
reviewer = FactoryGirl.create(:reviewer)
cardsortresult = CardsortResult.create(:cardsort_id => cardsort.id, :card_id => card.id,
:group_id => group.id, :reviewer_id => reviewer.id)
o = helper.getOccurrences(cardsortresult.card, cardsortresult.group, cardsort, nil)
expect(o).to eq(1)
expect(getGroupsAndCards([cardsortresult])).to eq([[group], [card]])
end
describe "methods that generate charts should return a chart" do
before(:each) do
project = FactoryGirl.create(:project)
@task = project.tasks.create(FactoryGirl.attributes_for(:task))
@reviewer = @task.reviewers.create(FactoryGirl.attributes_for(:reviewer))
end
it "drawLinechart(resultsSummary, tasks, title) should return a chart" do
@task.task_results.create(FactoryGirl.attributes_for(:task_result))
resultsSummary = calculateResultsSummary([@task])
timechart = helper.drawLinechart(resultsSummary[0], [@task], 'title')
successchart = helper.drawLinechart(resultsSummary[1], [@task], 'title')
expect(timechart).to be_kind_of(GoogleVisualr::Interactive::LineChart)
expect(successchart).to be_kind_of(GoogleVisualr::Interactive::LineChart)
end
it "drawBarchart(tasks) should return a chart" do
@task.task_results.create(FactoryGirl.attributes_for(:task_result))
chart = helper.drawBarchart([@task])
expect(chart).to be_kind_of(GoogleVisualr::Interactive::ColumnChart)
end
it "drawPiechart(tasks) should return a chart" do
@reviewer.create_reviewer_info(FactoryGirl.attributes_for(:reviewer_info))
reviewersinfos = getReviewerInfos(@task)
agechart = drawPiechart(reviewersinfos[0], 'test')
countrychart = drawPiechart(reviewersinfos[1], 'test')
genderchart = drawPiechart(reviewersinfos[2], 'test')
expect(agechart).to be_kind_of(GoogleVisualr::Interactive::PieChart)
expect(genderchart).to be_kind_of(GoogleVisualr::Interactive::PieChart)
expect(countrychart).to be_kind_of(GoogleVisualr::Interactive::PieChart)
end
end
it "getQuestionResults(question) returns a chart" do
question = Qquestion.create(:body => "TEST", :qtype => 3, :choices_attributes => [:body => "ChoiceA"])
chart = helper.getQuestionResults(question, 3)
expect(chart).to be_kind_of(GoogleVisualr::Interactive::PieChart)
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.