text stringlengths 10 2.61M |
|---|
class AddUserIdToVisuals < ActiveRecord::Migration
def change
add_column :visuals, :user_id, :integer
add_index :visuals, :user_id
end
end
|
class User < ActiveRecord::Base
def name_and_age
"#{name} and #{age}"
end
end
|
# Puma can serve each request in a thread from an internal thread pool.
# The `threads` method setting takes two numbers: a minimum and maximum.
# Any libraries that use thread pools should be configured to match
# the maximum value specified for Puma. Default is set to 5 threads for minimum
# and maximum; this matches the default thread size of Active Record.
#
workers 1
threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
threads threads_count, threads_count
# Specifies the `port` that Puma will listen on to receive requests; default is 3000.
#
port ENV.fetch("PORT") { 3005 }
# Specifies the `environment` that Puma will run in.
#
environment ENV.fetch("RAILS_ENV") { "development" }
# Specifies the number of `workers` to boot in clustered mode.
# Workers are forked webserver processes. If using threads and workers together
# the concurrency of the application would be max `threads` * `workers`.
# Workers do not work on JRuby or Windows (both of which do not support
# processes).
#
# workers ENV.fetch("WEB_CONCURRENCY") { 2 }
# Use the `preload_app!` method when specifying a `workers` number.
# This directive tells Puma to first boot the application and load code
# before forking the application. This takes advantage of Copy On Write
# process behavior so workers use less memory.
#
# preload_app!
# Allow puma to be restarted by `rails restart` command.
plugin :tmp_restart
on_worker_boot do
# t = Thread.new do
# puts "[Wakeup]Started counter"
# next_poke_time = (Time.now.utc.localtime("+08:00") + 30.minutes)
# while true
# begin
# sleep(1)
# if Time.now.utc.localtime("+08:00").strftime("%k:%M:%S") == next_poke_time.strftime("%k:%M:%S")
# res = RestClient.get 'http://localhost:3005'
# next_poke_time = (Time.now.utc.localtime("+08:00") + 30.minutes)
# puts res.code==200? "Wake success, next poke starting at #{next_poke_time.strftime("%k:%M:%S")}" : "Wake failed"
# end
# rescue SystemExit, Interrupt
# puts "關閉中"
# t.join
# end
# end
# end
end |
# frozen_string_literal: true
# == Schema Information
#
# Table name: articles
#
# id :integer not null, primary key
# title :string(255)
# views :integer default(0)
# created_at :datetime
# updated_at :datetime
# character_sum :integer default(0)
# revision_count :integer default(0)
# views_updated_at :date
# namespace :integer
# rating :string(255)
# rating_updated_at :datetime
# deleted :boolean default(FALSE)
# language :string(10)
# average_views :float(24)
# average_views_updated_at :date
# wiki_id :integer
# mw_page_id :integer
#
require 'rails_helper'
require "#{Rails.root}/lib/importers/article_importer"
require "#{Rails.root}/lib/importers/view_importer"
describe Article do
describe '#update' do
it 'should do a null update for an article' do
VCR.use_cassette 'article/update' do
# Add an article
article = build(:article,
id: 1,
title: 'Selfie',
namespace: 0,
views_updated_at: '2014-12-31'.to_date)
# Run update with no revisions
article.update
expect(article.views).to eq(0)
# Add a revision and update again.
build(:revision,
article_id: 1,
views: 10).save
article.update
expect(article.views).to eq(10)
end
end
end
describe 'cache methods' do
it 'should update article cache data' do
# Add an article
article = build(:article,
id: 1,
title: 'Selfie',
namespace: 0,
views_updated_at: '2014-12-31'.to_date)
# Add a revision so that update_views has something to run on.
build(:revision,
article_id: 1).save
article.update_cache
expect(article.revision_count).to be_kind_of(Integer)
expect(article.character_sum).to be_kind_of(Integer)
end
end
describe '.update_all_caches' do
it 'should update caches for articles' do
# Try it with no articles.
Article.update_all_caches
# Add an article.
build(:article,
id: 1,
title: 'Selfie',
namespace: 0).save
# Update again with this article.
Article.update_all_caches
end
end
describe 'deleted articles' do
it 'should not contribute to cached course values' do
course = create(:course, end: '2016-12-31'.to_date)
course.users << create(:user, id: 1)
CoursesUsers.update_all(role: CoursesUsers::Roles::STUDENT_ROLE)
(1..2).each do |i|
article = create(:article,
id: i,
title: "Basket Weaving #{i}",
namespace: 0,
deleted: i > 1)
create(:revision,
id: i,
article_id: i,
characters: 1000,
views: 1000,
user_id: 1,
date: '2015-03-01'.to_date)
course.articles << article
end
course.courses_users.each(&:update_cache)
course.articles_courses.each(&:update_cache)
course.update_cache
expect(course.article_count).to eq(1)
expect(course.view_sum).to eq(1000)
expect(course.character_sum).to eq(1000)
end
end
end
|
class Artist
attr_accessor :name, :songs
@@all = []
def initialize(name)
@name = name
@songs = []
@@all << self #This is a better way to save each new Artist as it's created
end
def self.all
@@all
end
def songs
@songs
end
def add_song(name)
self.songs << name
end
def save
# self.class.all << self #See initialize above
end
def self.find_or_create_by_name(the_artists_name)
@@all.each do |artist_object|
if artist_object.name == the_artists_name
return artist_object
end
end
self.new(the_artists_name)
end
def print_songs
self.songs.each {|song| puts song.name}
end
end
|
# Global configuration and build options for Swift.
module Lightspeed
# Top-level API for configuring Swift build settings.
#
# Example:
#
# Lightspeed.configure do |c|
# c.sdk = :macosx
# end
#
def self.configure
yield Configuration.instance
end
# Access the shared configuration.
def self.configuration
Configuration.instance
end
# Encapsulates a set of Swift build settings.
class Configuration
### Configurable attributes
# SDK to compile against.
attr_accessor :sdk
# Build locations
attr_accessor :build_dir,
:build_intermediates_dir,
:build_products_dir,
:executables_dir
### Initialization
def self.instance
@@instance ||= new
end
def initialize
@sdk = :macosx
@build_dir = 'Build'
end
### SDK paths
def self.sdk
instance.sdk
end
## Source file location
def base_dir
@base_dir || Dir.pwd
end
def with_base_dir(base_dir, &block)
@base_dir = base_dir
yield
@base_dir = nil
end
### Build locations
def executables_dir
@executables_dir ||= "bin"
end
def build_products_dir
@build_products_dir ||= File.join(build_dir, "Products")
end
def build_intermediates_dir
@build_intermediates_dir ||= File.join(build_dir, "Intermediates")
end
def target_build_dir(target)
File.join(build_intermediates_dir, target.ext(".build"))
end
end
end
|
class Group < AbstractPage
has_many :memberships
has_many :users, through: :memberships
# validates :users, :presence => true
validates :name, :presence => true, :uniqueness => {:case_sensitive => false}
extend FriendlyId
friendly_id :name, use: [:slugged, :finders, :history]
has_paper_trail
def should_generate_new_friendly_id?
name_changed?
end
end
|
require 'service_helper'
describe JmPlayer::Data::Player do
let(:attributes){ {name: 'foo', nick: 'bar', uuid: SecureRandom.uuid } }
let(:listener){ double(:listener) }
let(:player){ described_class.new(attributes) }
let(:events){ JmPlayer::Data::Player::EVENTS }
specify{ subject.should respond_to(:insert) }
before do
described_class.count.should eq 0
subject.subscribe(listener)
end
context 'when the attributes are valids' do
subject{ described_class.new(attributes) }
it 'can insert data' do
listener.should_receive( events[:insert][:ok] )
subject.insert_foo
described_class.count.should eq 1
end
end
context 'when the attributes are invalid' do
subject{ described_class.new() }
it 'can insert data' do
listener.should_receive( events[:insert][:ko] )
subject.insert_foo
described_class.count.should eq 0
end
end
end
|
Then /^I should see the file group id for the file group with location '([^']*)' in the file group collection table$/ do |location|
id = FileGroup.find_by(external_file_location: location).id
within_table('file_groups') do
step "I should see '#{id}'"
end
end
And /^I should not see '([^']*)' in the related file groups section$/ do |string|
within('#related-file-groups') do
step "I should not see '#{string}'"
end
end
And /^The file group with location '([^']*)' for the collection titled '([^']*)' should have producer titled '([^']*)'$/ do |location, collection_title, producer_title|
find_file_group(collection_title, location).producer.title.should == producer_title
end
Given /^The file group with location '([^']*)' for the collection titled '([^']*)' has producer titled '([^']*)'$/ do |location, collection_title, producer_title|
file_group = find_file_group(collection_title, location)
file_group.producer = Producer.find_by(title: producer_title)
file_group.save
end
And(/^the file group titled '([^']*)' has a target file group titled '([^']*)'$/) do |source_title, target_title|
source_file_group = FileGroup.find_by(title: source_title)
target_file_group = FileGroup.find_by(title: target_title)
source_file_group.target_file_groups << target_file_group
end
And(/^the file group titled '([^']*)' should have relation note '([^']*)' for the target file group '([^']*)'$/) do |source_title, note, target_title|
source_file_group = FileGroup.find_by(title: source_title)
target_file_group = FileGroup.find_by(title: target_title)
source_file_group.target_relation_note(target_file_group).should == note
end
And(/^the file group titled '([^']*)' has relation note '([^']*)' for the target file group '([^']*)'$/) do |source_title, note, target_title|
source_file_group = FileGroup.find_by(title: source_title)
target_file_group = FileGroup.find_by(title: target_title)
join = RelatedFileGroupJoin.find_or_create_by(source_file_group_id: source_file_group.id, target_file_group_id: target_file_group.id)
join.note = note
join.save!
end
And(/^the cfs root for the file group titled '([^']*)' should be nil$/) do |title|
FileGroup.find_by(title: title).cfs_root.should be_nil
end
Then(/^a user is unauthorized to start a file group for the collection titled '([^']*)'$/) do |title|
rack_login('a user')
get new_file_group_path(collection_id: Collection.find_by(title: title).id)
expect(last_response.redirect?).to be_truthy
expect(last_response.location).to match(/#{unauthorized_path}$/)
end
Then(/^a user is unauthorized to create a file group for the collection titled '([^']*)'$/) do |title|
rack_login('a user')
post file_groups_path(file_group: {collection_id: Collection.find_by(title: title).id,
storage_level: 'bit-level store'})
expect(last_response.redirect?).to be_truthy
expect(last_response.location).to match(/#{unauthorized_path}$/)
end
private
def find_file_group(collection_title, location)
collection = Collection.find_by(title: collection_title)
collection.file_groups.where(external_file_location: location).first
end |
module Pod
class Command
class Bin < Command
class Add < Bin
self.summary = '再不删除二进制的情况下为组件添加源码调试能力,多个组件名称用逗号分隔'
def initialize(argv)
@nameArgv = argv.shift_argument
UI.puts "add输入参数:#{@nameArgv}".red
super
end
def run
addSource
end
def addSource()
nameArray = @nameArgv.split
if nameArray.length == 0
UI.puts "请输入要下载组件源码名称".red
return
end
nameArray.each_index {|index|
item = nameArray[index]
UI.puts "#{item}".red
downSource(item)
}
UI.puts "下载完成...".red
end
def downSource(name)
command = 'dwarfdump /Users/suzhiqiu/Library/Developer/Xcode/DerivedData/LibSource-gvmdthzquecjhpdskogxxrkgtmhc/Build/Products/Debug-iphonesimulator/libLibSource.a | grep \'DW_AT_comp_dir\''
UI.puts "#{command}".red
# if output.empty
# UI.puts "没找到二进制编译路径信息".red
# end
serverPath = 'https://github.com/suzhiqiu/UCARRobot'
localPath = '~/Downloads/q'
UI.puts "开始下载#{name}".red
command = `git clone #{serverPath} #{localPath}`
output = `#{command}`.lines.to_a
UI.puts "#{output}".red
end
end
end
end
end
|
require 'word_chains'
describe "word_chains" do
before(:each) do
dict = { 3 => ["cat",
"cot",
"cog",
"dog",
"the"]}
@chain = WordChain.new(dict)
end
it "should load the dictionary right" do
@chain.dict.should == { 3 => ["cat",
"cot",
"cog",
"dog",
"the"]}
end
it "should return true for cat and cot" do
@chain.one_letter_difference?("cat", "cot").should be_true
end
it "should be false for cat and dog" do
@chain.one_letter_difference?("cat", "dog").should be_false
end
it "should be false for cat and tag" do
@chain.one_letter_difference?("cat", "tag").should be_false
end
it "should return true for words of the same length" do
@chain.same_length?("one", "the").should be_true
end
it "should return false for words with a different length" do
@chain.same_length?("blah", "foo").should be_false
end
it "should return ['cot'] for 'cat'" do
@chain.all_one_off_words("cat").should == ["cot"]
end
it "should return [] for 'the'" do
@chain.all_one_off_words("the").should == []
end
it "should return ['cot'] for 'cat'" do
@chain.unvisited_one_off_words("cat").should == ["cot"]
end
it "should search" do
@chain.search("cat", "dog", ["cat"]).should == ["cat", "cot", "cog", "dog"]
end
end
|
class AddInviteeToMember < ActiveRecord::Migration[6.0]
def change
add_column :members, :is_invited, :boolean
end
end
|
require 'rails/generators'
class Natural::InstallGenerator < Rails::Generators::Base
source_root File.expand_path('../templates', __FILE__)
def copy_application_policy
template 'application_policy.rb', 'app/policies/application_policy.rb'
helper_path = Rails.root.join('spec', 'rails_helper.rb')
if File.exists?(helper_path)
template('pundit.rb', 'spec/support/pundit.rb')
helper_content = File.read(helper_path)
support_file_loader = "Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }"
unless helper_content.include?(support_file_loader)
helper_content.gsub!("require 'rspec/rails'",
"require 'rspec/rails'\n#{support_file_loader}")
File.open(helper_path, 'w') { |f| f.puts helper_content }
end
end
end
end
|
Pod::Spec.new do |s|
s.name = "MMKV"
s.version = "1.2.7"
s.summary = "MMKV is a cross-platform key-value storage framework developed by WeChat."
s.description = <<-DESC
The MMKV, for Objective-C.
MMKV is an efficient, complete, easy-to-use mobile key-value storage framework used in the WeChat application.
It can be a replacement for NSUserDefaults & SQLite.
DESC
s.homepage = "https://github.com/Tencent/MMKV"
s.license = { :type => "BSD 3-Clause", :file => "LICENSE.TXT"}
s.author = { "guoling" => "guoling@tencent.com" }
s.ios.deployment_target = "9.0"
s.osx.deployment_target = "10.9"
s.source = { :git => "https://github.com/Tencent/MMKV.git", :tag => "v#{s.version}" }
s.vendored_frameworks = 'Output/MMKV-Release-iphoneuniversal/MMKV.framework'
s.libraries = "z", "c++"
s.framework = "CoreFoundation"
end
|
class SongsController < ApplicationController
def index
if params[:artist_id]
@artist = Artist.find_by(id: params[:artist_id])
if @artist.nil?
redirect_to artists_path, alert: "Artist not found"
else
@songs = @artist.songs
end
else
@songs = Song.all
end
end
def show
if params[:artist_id]
@artist = Artist.find_by(id: params[:artist_id])
@song = @artist.songs.find_by(id: params[:id])
if @song.nil?
redirect_to artist_songs_path(@artist), alert: "Song not found"
end
else
@song = Song.find(params[:id])
end
end
def new
#we need to see if :artist_id is set and if artist_id is valid artist
if params[:artist_id] && !Artist.exists?(params[:artist_id])
#artist_id exists but is not valid
redirect_to artists_path, alert: "Artist not found."
else
#this would set artist_id to nil if not exists but still works in this instance
@song = Song.new(artist_id: params[:artist_id])
end
end
def create
@song = Song.new(song_params)
if @song.save
redirect_to @song
else
render :new
end
end
def edit
if params[:artist_id]
@nested = true
#find and validate the artist
artist = Artist.find_by(id: params[:artist_id])
if artist.nil?
#no artist is found
redirect_to artists_path, alert: "Artist not found."
else
#we limit scope to only songs by artist_id
@song = artist.songs.find_by(id: params[:id])
#redirect to artists/:artist_id/songs and alert if no song is found
redirect_to artist_songs_path(artist), alert: "Song not found." if @song.nil?
end
else
#no artist_id so we are /songs/:id/edit
@song = Song.find(params[:id])
end
end
def update
@song = Song.find(params[:id])
@song.update(song_params)
if @song.save
redirect_to @song
else
render :edit
end
end
def destroy
@song = Song.find(params[:id])
@song.destroy
flash[:notice] = "Song deleted."
redirect_to songs_path
end
private
def song_params
params.require(:song).permit(:title, :artist_name, :artist_id)
end
end
|
Rails.application.routes.draw do
devise_for :users, controllers: {
registrations: 'users/registrations',
sessions: 'users/sessions'
}
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :messages
# root to: 'notifications#index'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
# Websockets resemble this URL
get "notifications/index", to: "notifications#index"
root to: "chat_rooms#index"
resources :chat_rooms, only: [:new, :create, :show, :index, :destroy]
mount ActionCable.server => '/cable'
# get "dashboard", to: "skills#dashboard"
get "dashboard", to: "skills#dashboard"
resources :users, only: [] do
resources :chat_rooms, only: [:new, :create, :destroy]
resources :profile, only: [:index]
end
resource :profile do
resources :skills, only: [:edit, :update, :destroy]
# get "dashboard", to: "profile#dashboard"
end
resources :skills
resources :home, only: [:index]
end |
require 'rss'
require 'net/http'
require 'uri'
require 'json'
API_KEY = Rails.application.secrets.youtube_api_key.freeze
API_DOMAIN = 'www.googleapis.com'.freeze
API_PATH = '/youtube/v3/search'.freeze
API_URI = 'https://' + API_DOMAIN + API_PATH + '?part=snippet&maxResults=1&q='
API_URI.freeze
API_SSL_PORT = 443
module Tasks
# batch
class UpdateDailyRanking
def self.execute
update_aggregate_dates
# fetch rss results
Itune.pluck(:itunes_url, :itune_id) .each do |value|
begin
rss = RSS::Parser.parse(value[0], true)
rescue => e
logger.fatal e.backtrace.join("\n")
end
update_daily_ranking(rss, value[1])
end
end
def self.update_aggregate_dates
day = AggregateDate.new
today = Date.today
day.this_date = today
day.save
end
def self.update_daily_ranking(rss, itune_id)
ranking = 0
rss.items.each do |item|
titile_artist = String(item.title) \
.gsub(/<('.*?'|'.*?'|[^''])*?>/, '').encode('UTF-8')
artist = titile_artist.gsub(/^.*-\s/, '')
title = titile_artist.gsub(/\s-.*$/, '')
update_youtubes(artist, title)
rank = DailyRanking.new
rank.rank = ranking += 1
rank.aggregate_date_id = AggregateDate.maximum('aggregate_date_id')
rank.itune_id = itune_id
begin
result = Youtube.where(artist: artist, title: title) \
.pluck(:youtube_id)
rank.youtube_id = result[0]
rescue NoMethodError
rank.youtube_id = nil
end
rank.save
end
end
def self.update_youtubes(artist, title)
if Youtube.find_by(artist: artist, title: title).nil?
music = Youtube.new
music.artist = artist
music.title = title
music.youtube_url = get_youtube_uri(artist, title)
music.save
end
end
def self.get_youtube_uri(artist, title)
https = Net::HTTP.new(API_DOMAIN, API_SSL_PORT)
https.use_ssl = true
https.verify_mode = OpenSSL::SSL::VERIFY_PEER
uri = API_URI + artist.gsub(' ', '%20') + '%20' + title.gsub(' ', '%20') \
+ '&key=' + API_KEY
result = JSON.parse(https.request_get(uri).body)
begin
return result['items'][0]['id']['videoId']
rescue NoMethodError
return nil
end
end
end
end
|
class RemoveColumnsFromBookedItem < ActiveRecord::Migration
def change
remove_column :booked_items, :date_entered
remove_column :booked_items, :time_entered
remove_column :booked_items, :unit_type
end
end
|
class Application < ActiveRecord::Base
attr_accessible :name, :entity, :redirect_uri, :entity_attributes
has_many :connection_contexts
has_many :identity_contexts
has_many :entity_contexts
belongs_to :entity
accepts_nested_attributes_for :entity
belongs_to :user
validates :name, :presence => true, :uniqueness => true
validates_associated :entity, :if => :not_credport
validates :redirect_uri, :presence => true, :redirect_uri => true
def not_credport
name != 'credport'
end
# Doorkeeper related stuff
has_one :doorkeeper_application, :class_name => "Doorkeeper::Application"
after_create :create_doorkeeper_application_callback
def create_doorkeeper_application_callback
self.create_doorkeeper_application!(:name => self.name, :redirect_uri => self.redirect_uri)
end
after_save :save_redirect_uri
def save_redirect_uri
self.doorkeeper_application.update_attribute :redirect_uri, self.redirect_uri
end
end
|
require "spec_helper"
module Netvisor
describe Configuration do
describe "#host" do
it "default value is nil" do
Configuration.new.host = 'http://foo.bar'
end
end
describe "#host=" do
it "can set value" do
config = Configuration.new
config.host = 'http://foo.bar'
expect(config.host).to eq('http://foo.bar')
end
end
end
end
|
require_dependency "survey_builder/application_controller"
module SurveyBuilder
class SurveyResponsesController < ApplicationController
before_action :set_survey_form!
before_action :set_survey_response, only: [:show, :edit, :update, :destroy]
helper :all
# GET /survey_responses
def index
@survey_responses = @survey_form.survey_responses
end
# GET /survey_responses/1
def show
end
# GET /survey_responses/new
def new
@questions = @survey_form.questions
@survey_response = @survey_form.survey_responses.build(survey_form: @survey_form)
@answers = []
@questions.each do |question|
Rails.logger.info "\n\n\n\n\nThere are some questions \n"
answer = @survey_response.answers.build(question: question)
@answers.push(answer)
end
Rails.logger.info "\n\n\n\n\n\nSurvey Response answers count : #{@survey_response.answers.size} \n\n\n\n\n\n"
end
# GET /survey_responses/1/edit
def edit
end
# POST /survey_responses
def create
puts survey_response_params
@survey_response = @survey_form.survey_responses.build(survey_response_params)
if @survey_response.save
redirect_to survey_form_survey_response_path(@survey_form, @survey_response), notice: 'Survey response was successfully created.'
else
render :new
end
end
# PATCH/PUT /survey_responses/1
def update
if @survey_response.update(survey_response_params)
redirect_to survey_form_survey_response_path(@survey_form, @survey_response), notice: 'Survey response was successfully updated.'
else
render :edit
end
end
# DELETE /survey_responses/1
def destroy
@survey_response.destroy
redirect_to survey_form_survey_responses_path(@survey_form), notice: 'Survey response was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_survey_form!
@survey_form = SurveyForm.find(params[:survey_form_id])
end
def set_survey_response
@survey_response = SurveyResponse.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def survey_response_params
params[:survey_response][:user_id] = current_user.id
params[:survey_response][:survey_form_id] = @survey_form.id
parse_user_response
puts " params Here - #{params}"
params.require(:survey_response).permit(:survey_form_id, :user_id, :time_to_answer, answers_attributes: [:question_id, :survey_response_id, :answer_data])
end
def parse_user_response
answers = params[:answer]
formatted_answers = []
answers.each do | qid, ans |
question = Question.find_by_id(qid)
if question
formatted_answers.push({:question_id => qid,
:answer_data => question.format_answer(ans).to_json,
:survey_response_id => params[:survey_response_id]
})
end
end
params[:survey_response][:answers_attributes] = formatted_answers
end
end
end
|
#
# Cookbook Name:: cookbook_qubell_mssql
# Recipe::file_query
#
# Copyright 2014, Qubell
#
# All rights reserved - Do Not Redistribute
#
sql_f = node[:cookbook_qubell_mssql][:sql_url]
sql_f.each_index do |i|
sql_file = Chef::Config[:file_cache_path] + "/query#{i}.sql"
remote_file sql_file do
source sql_f[i]
mode "0644"
action :create
end
sql_server_database "run #{sql_file}" do
connection node[:cookbook_qubell_mssql][:schema]
sql { ::File.open(sql_file).read }
database_name node[:cookbook_qubell_mssql][:schema][:dbname]
action :query
end
end
|
class ChangeEstateRegnumIntegerSizing < ActiveRecord::Migration
def change
change_column :estates, :regnum, :integer, limit: 8
end
end
|
class AllowAuthorIdNull < ActiveRecord::Migration[5.2]
def change
change_column_null(:channels, :author_id, true)
end
end
|
class SongsController < ApplicationController
def show
@song = Song.find_by id: params[:id]
end
def new
end
def create
@song = Song.new song_params
if @song.save
redirect_to @song
else
render json: {result: false, song: @song.errors}, status: :unprocessable_entity
end
end
private
def song_params
params.permit(:name, :picture)
end
end
|
require 'test_helper'
feature 'Access home page online' do
scenario 'the site is up and running' do
# Given that the site is deployed and running
# When I visit the index page online
visit 'http://www.sotoseattle.com'
# Then I can see the welcome page
page.must_have_content 'bits and pieces'
page.must_have_content 'Javier Soto'
end
end
|
require "spec_helper"
describe ContractUpdated do
describe "notify" do
let(:consultant){ create(:consultant) }
let(:mail) { ContractUpdated.notify(consultant) }
it "renders the headers" do
mail.subject.should eq("Recently Updated Contract on GCES")
mail.to.should eq([consultant.email])
end
it "renders the body" do
mail.body.encoded.should match("recently made updates to our contract")
end
end
end
|
# frozen_string_literal: true
require "rails_helper"
RSpec.describe ActivityPresenter do
RSpec.shared_examples "a code translator" do |field, args, field_type|
let(:field) { field }
let(:args) { args.reverse_merge(source: "iati") }
let(:field_type) { field_type }
let(:activity) { build(:project_activity) }
def cast_code_to_field(code)
return code if field_type.nil?
return code.to_i if field_type == "Integer"
return [code] if field_type == "Array"
end
it "has translations for all of the codes" do
Codelist.new(**args).each do |code|
code = cast_code_to_field(code["code"])
activity.write_attribute(field, code)
expect(described_class.new(activity).send(field)).to_not match(/translation missing/)
end
end
end
describe "#title_hint" do
context "when the activity is a programme" do
it "includes all notes about the title field" do
activity = build(:programme_activity)
expect(ActivityPresenter.new(activity).title_hint).to eq("A short title that explains the purpose of the programme (level B). There is no character limit to this field. However, when this data is published to Statistics in International Development the title will be truncated at 150 characters.")
end
context "and non-ODA" do
it "includes character limit notes about the title field, but not SID information" do
activity = build(:programme_activity, :ispf_funded, is_oda: false)
expect(ActivityPresenter.new(activity).title_hint).to eq("A short title that explains the purpose of the programme (level B). There is no character limit to this field.")
end
end
end
context "when the activity is a project" do
it "includes all notes about the title field" do
activity = build(:project_activity)
expect(ActivityPresenter.new(activity).title_hint).to eq("A short title that explains the purpose of the project (level C). There is no character limit to this field. However, when this data is published to Statistics in International Development the title will be truncated at 150 characters.")
end
context "and non-ODA" do
it "includes character limit notes about the title field, but not SID information" do
activity = build(:project_activity, :ispf_funded, is_oda: false)
expect(ActivityPresenter.new(activity).title_hint).to eq("A short title that explains the purpose of the project (level C). There is no character limit to this field.")
end
end
end
context "when the activity is a third-party project" do
it "includes all notes about the title field" do
activity = build(:third_party_project_activity)
expect(ActivityPresenter.new(activity).title_hint).to eq("A short title that explains the purpose of the third-party project (level D). There is no character limit to this field. However, when this data is published to Statistics in International Development the title will be truncated at 150 characters.")
end
context "and non-ODA" do
it "includes character limit notes about the title field, but not SID information" do
activity = build(:third_party_project_activity, :ispf_funded, is_oda: false)
expect(ActivityPresenter.new(activity).title_hint).to eq("A short title that explains the purpose of the third-party project (level D). There is no character limit to this field.")
end
end
end
end
describe "#description_hint" do
context "when the activity is a programme" do
it "includes all notes about the description field" do
activity = build(:programme_activity)
expect(ActivityPresenter.new(activity).description_hint).to eq("There is no character limit to this field. However, when this data is published to Statistics in International Development the description will be truncated at 4000 characters.")
end
context "and non-ODA" do
it "includes character limit notes about the description field, but not SID information" do
activity = build(:programme_activity, :ispf_funded, is_oda: false)
expect(ActivityPresenter.new(activity).description_hint).to eq("There is no character limit to this field.")
end
end
end
context "when the activity is a project" do
it "includes all notes about the description field" do
activity = build(:project_activity)
expect(ActivityPresenter.new(activity).description_hint).to eq("There is no character limit to this field. However, when this data is published to Statistics in International Development the description will be truncated at 4000 characters.")
end
context "and non-ODA" do
it "includes character limit notes about the description field, but not SID information" do
activity = build(:project_activity, :ispf_funded, is_oda: false)
expect(ActivityPresenter.new(activity).description_hint).to eq("There is no character limit to this field.")
end
end
end
context "when the activity is a third-party project" do
it "includes all notes about the description field" do
activity = build(:third_party_project_activity)
expect(ActivityPresenter.new(activity).description_hint).to eq("There is no character limit to this field. However, when this data is published to Statistics in International Development the description will be truncated at 4000 characters.")
end
context "and non-ODA" do
it "includes character limit notes about the description field, but not SID information" do
activity = build(:third_party_project_activity, :ispf_funded, is_oda: false)
expect(ActivityPresenter.new(activity).description_hint).to eq("There is no character limit to this field.")
end
end
end
end
describe "#aid_type" do
it_behaves_like "a code translator", "aid_type", {type: "aid_type"}
context "when the aid_type exists" do
it "returns the locale value for the code" do
activity = build(:project_activity, aid_type: "a01")
result = described_class.new(activity).aid_type
expect(result).to eql("General budget support")
end
it "returns the locale value when the code is upper case" do
activity = build(:project_activity, aid_type: "A01")
result = described_class.new(activity).aid_type
expect(result).to eql("General budget support")
end
end
context "when the activity does not have an aid_type set" do
it "returns nil" do
activity = build(:project_activity, :at_identifier_step)
result = described_class.new(activity)
expect(result.aid_type).to be_nil
end
end
end
describe "#aid_type_with_code" do
context "when the aid_type exists" do
it "returns the code and the locale value separated by a colon" do
activity = build(:project_activity, aid_type: "A01")
result = described_class.new(activity).aid_type_with_code
expect(result).to eql("A01: General budget support")
end
end
context "when the activity does not have an aid_type set" do
it "returns nil" do
activity = build(:project_activity, :at_identifier_step)
result = described_class.new(activity)
expect(result.aid_type_with_code).to be_nil
end
end
end
describe "#covid19_related" do
it_behaves_like "a code translator", "covid19_related", {type: "covid19_related_research", source: "beis"}
let(:covid19_related) { 3 }
let(:activity) { build(:project_activity, covid19_related: covid19_related) }
subject { described_class.new(activity).covid19_related }
context "when the super value is nil" do
let(:covid19_related) { nil }
it "returns nil" do
expect(subject).to be_nil
end
end
it "returns the locale value for the code" do
expect(subject).to eql("New activity that will somewhat focus on COVID-19")
end
end
describe "#sector" do
it_behaves_like "a code translator", "sector", {type: "sector"}
context "when the sector exists" do
it "returns the locale value for the code" do
activity = build(:project_activity, sector: "11110")
result = described_class.new(activity).sector
expect(result).to eql("Education policy and administrative management")
end
end
context "when the activity does not have a sector set" do
it "returns nil" do
activity = build(:project_activity, sector: nil)
result = described_class.new(activity)
expect(result.sector).to be_nil
end
end
end
describe "#sector_with_code" do
context "when the sector exists" do
it "returns the code followed by the locale value separated by a colon" do
activity = build(:project_activity, sector: "11110")
result = described_class.new(activity).sector_with_code
expect(result).to eql("11110: Education policy and administrative management")
end
end
context "when the activity does not have a sector set" do
it "returns nil" do
activity = build(:project_activity, sector: nil)
result = described_class.new(activity)
expect(result.sector_with_code).to be_nil
end
end
end
describe "#call_present" do
context "when there is a call" do
it "returns the locale value for this option" do
activity = build(:project_activity, call_present: "true")
result = described_class.new(activity)
expect(result.call_present).to eq("Yes")
end
end
context "when there is not a call" do
it "returns the locale value for this option" do
activity = build(:project_activity, call_present: "false")
result = described_class.new(activity)
expect(result.call_present).to eq("No")
end
end
end
describe "#call_open_date" do
context "when the call open date exists" do
it "returns a human readable date" do
activity = build(:project_activity, call_open_date: "2020-02-20")
result = described_class.new(activity).call_open_date
expect(result).to eq("20 Feb 2020")
end
end
context "when the planned start date does not exist" do
it "returns nil" do
activity = build(:project_activity, call_open_date: nil)
result = described_class.new(activity)
expect(result.call_open_date).to be_nil
end
end
end
describe "#call_close_date" do
context "when the call close date exists" do
it "returns a human readable date" do
activity = build(:project_activity, call_close_date: "2020-06-23")
result = described_class.new(activity).call_close_date
expect(result).to eq("23 Jun 2020")
end
end
context "when the planned close date does not exist" do
it "returns nil" do
activity = build(:project_activity, call_close_date: nil)
result = described_class.new(activity)
expect(result.call_close_date).to be_nil
end
end
end
describe "#programme_status" do
it_behaves_like "a code translator", "programme_status", {type: "programme_status", source: "beis"}
context "when the programme status exists" do
it "returns the locale value for the code" do
activity = build(:project_activity, programme_status: "spend_in_progress")
result = described_class.new(activity).programme_status
expect(result).to eql("Spend in progress")
end
end
context "when the activity does not have a programme status set" do
it "returns nil" do
activity = build(:project_activity, programme_status: nil)
result = described_class.new(activity)
expect(result.programme_status).to be_nil
end
end
end
describe "#planned_start_date" do
context "when the planned start date exists" do
it "returns a human readable date" do
activity = build(:project_activity, planned_start_date: "2020-02-25")
result = described_class.new(activity).planned_start_date
expect(result).to eql("25 Feb 2020")
end
end
context "when the planned start date does not exist" do
it "returns nil" do
activity = build(:project_activity, planned_start_date: nil)
result = described_class.new(activity)
expect(result.planned_start_date).to be_nil
end
end
end
describe "#planned_end_date" do
context "when the planned end date exists" do
it "returns a human readable date" do
activity = build(:project_activity, planned_end_date: "2021-04-03")
result = described_class.new(activity).planned_end_date
expect(result).to eql("3 Apr 2021")
end
end
context "when the planned end date does not exist" do
it "returns nil" do
activity = build(:project_activity, planned_end_date: nil)
result = described_class.new(activity)
expect(result.planned_end_date).to be_nil
end
end
end
describe "#actual_start_date" do
context "when the actual start date exists" do
it "returns a human readable date" do
activity = build(:project_activity, actual_start_date: "2020-11-06")
result = described_class.new(activity).actual_start_date
expect(result).to eql("6 Nov 2020")
end
end
context "when the actual start date does not exist" do
it "returns nil" do
activity = build(:project_activity, actual_start_date: nil)
result = described_class.new(activity)
expect(result.actual_start_date).to be_nil
end
end
end
describe "#actual_end_date" do
context "when the actual end date exists" do
it "returns a human readable date" do
activity = build(:project_activity, actual_end_date: "2029-05-27")
result = described_class.new(activity).actual_end_date
expect(result).to eql("27 May 2029")
end
end
context "when the actual end date does not exist" do
it "returns nil" do
activity = build(:project_activity, actual_end_date: nil)
result = described_class.new(activity)
expect(result.actual_end_date).to be_nil
end
end
end
describe "#benefitting_countries" do
it_behaves_like "a code translator", "benefitting_countries", {type: "benefitting_countries", source: "beis"}, "Array"
context "when there are benefitting countries" do
it "returns the locale value for the codes of the countries joined in sentence form" do
activity = build(:project_activity, benefitting_countries: ["AR", "EC", "BR"])
result = described_class.new(activity).benefitting_countries
expect(result).to eql("Argentina, Ecuador, and Brazil")
end
it "handles unexpected country codes" do
activity = build(:project_activity, benefitting_countries: ["UK"])
result = described_class.new(activity).benefitting_countries
expect(result).to eql t("page_content.activity.unknown_country", code: "UK")
end
end
end
describe "#benefitting_region" do
subject { described_class.new(activity).benefitting_region }
let(:activity) { build(:project_activity) }
before { expect(activity).to receive(:benefitting_region).at_least(:once).and_return(region) }
context "when there is a benefitting region" do
let(:region) { BenefittingRegion.new(name: "Some region") }
it { is_expected.to eq(region.name) }
end
context "when there is no benefitting region" do
let(:region) { nil }
it { is_expected.to be_nil }
end
end
describe "#recipient_region" do
it_behaves_like "a code translator", "recipient_region", {type: "recipient_region"}
context "when the aid_type recipient_region" do
it "returns the locale value for the code" do
activity = build(:project_activity, recipient_region: "489")
result = described_class.new(activity).recipient_region
expect(result).to eql("South America, regional")
end
end
context "when the activity does not have a recipient_region set" do
it "returns nil" do
activity = build(:project_activity, recipient_region: nil)
result = described_class.new(activity)
expect(result.recipient_region).to be_nil
end
end
end
describe "#recipient_country" do
it_behaves_like "a code translator", "recipient_country", {type: "benefitting_countries", source: "beis"}
context "when there is a recipient_country" do
it "returns the name from the code" do
activity = build(:project_activity, recipient_country: "CL")
result = described_class.new(activity).recipient_country
expect(result).to eq "Chile"
end
it "handles unexpected country codes" do
activity = build(:project_activity, benefitting_countries: ["UK"])
result = described_class.new(activity).benefitting_countries
expect(result).to eql t("page_content.activity.unknown_country", code: "UK")
end
end
context "when the activity does not have a recipient_country set" do
it "returns nil" do
activity = build(:project_activity, recipient_country: nil)
result = described_class.new(activity)
expect(result.recipient_country).to be_nil
end
end
end
describe "#intended_beneficiaries" do
it_behaves_like "a code translator", "intended_beneficiaries", {type: "recipient_country"}, "Array"
context "when there are other benefitting countries" do
it "returns the locale value for the codes of the countries" do
activity = build(:project_activity, intended_beneficiaries: ["AR", "EC", "BR"])
result = described_class.new(activity).intended_beneficiaries
expect(result).to eql("Argentina, Ecuador, and Brazil")
end
it "handles unexpected country codes" do
activity = build(:project_activity, benefitting_countries: ["UK"])
result = described_class.new(activity).benefitting_countries
expect(result).to eql t("page_content.activity.unknown_country", code: "UK")
end
end
end
describe "#gdi" do
it_behaves_like "a code translator", "gdi", {type: "gdi"}
context "when gdi exists" do
it "returns the locale value for the code" do
activity = build(:project_activity, gdi: "3")
result = described_class.new(activity).gdi
expect(result).to eql("Yes - China and India")
end
end
context "when the activity does not have a gdi set" do
it "returns nil" do
activity = build(:project_activity, gdi: nil)
result = described_class.new(activity)
expect(result.gdi).to be_nil
end
end
end
describe "#collaboration_type" do
it_behaves_like "a code translator", "collaboration_type", {type: "collaboration_type"}
context "when collaboration_type exists" do
it "returns the locale value for the code" do
activity = build(:project_activity, collaboration_type: "1")
result = described_class.new(activity).collaboration_type
expect(result).to eql("Bilateral")
end
end
context "when the activity does not have a collaboration_type set" do
it "returns nil" do
activity = build(:project_activity, collaboration_type: nil)
result = described_class.new(activity)
expect(result.collaboration_type).to be_nil
end
end
end
describe "#flow" do
it "returns the locale value for the default ODA code" do
activity = build(:project_activity)
result = described_class.new(activity).flow
expect(result).to eql("ODA")
end
end
describe "#flow_with_code" do
it "returns the default flow string & code number" do
fund = create(:project_activity)
expect(described_class.new(fund).flow_with_code).to eql("10: ODA")
end
end
describe "#policy_marker_gender" do
it_behaves_like "a code translator", "policy_marker_gender", {type: "policy_significance", source: "beis"}, "Integer"
context "when gender exists" do
it "returns the locale value for the code" do
activity = build(:project_activity, policy_marker_gender: "not_targeted")
result = described_class.new(activity).policy_marker_gender
expect(result).to eql("Not targeted")
end
end
context "when the value is the BEIS custom value" do
it "returns the locale value for the custom code" do
activity = build(:project_activity, policy_marker_gender: "not_assessed")
result = described_class.new(activity).policy_marker_gender
expect(result).to eql("Not assessed")
end
end
context "when the activity does not have a gender set" do
it "returns nil" do
activity = build(:project_activity, policy_marker_gender: nil)
result = described_class.new(activity)
expect(result.policy_marker_gender).to be_nil
end
end
end
describe "#sustainable_development_goals_apply" do
let(:activity) { build(:project_activity, sdgs_apply: sdgs_apply) }
subject { described_class.new(activity).sustainable_development_goals_apply }
context "when sdgs_apply is true" do
let(:sdgs_apply) { true }
it { is_expected.to eq("Yes") }
end
context "when sdgs_apply is false" do
let(:sdgs_apply) { false }
it { is_expected.to eq("No") }
end
end
describe "#sustainable_development_goals" do
it "returns 'Not applicable' when the user selects that SDGs do not apply (sdgs_apply is false)" do
activity = build(:project_activity, sdgs_apply: false)
result = described_class.new(activity).sustainable_development_goals
expect(result).to eq("Not applicable")
end
it "leaves the field blank when the SDG form step has not been filled yet" do
activity = build(:project_activity, sdgs_apply: false, form_state: nil)
result = described_class.new(activity).sustainable_development_goals
expect(result).to be_nil
end
it "when there is a single SDG, return its name" do
activity = build(:project_activity, sdgs_apply: true, sdg_1: 5)
result = described_class.new(activity)
items = Nokogiri::HTML(result.sustainable_development_goals).css("ol > li")
expect(items[0].text).to eql "Gender Equality"
end
it "when there are multiple SDGs, return their names, separated by a slash" do
activity = build(:project_activity, sdgs_apply: true, sdg_1: 5, sdg_2: 1)
result = described_class.new(activity)
items = Nokogiri::HTML(result.sustainable_development_goals).css("ol > li")
expect(items[0].text).to eql "Gender Equality"
expect(items[1].text).to eql "No Poverty"
end
it "when there are no SDGs return nil" do
activity = build(:project_activity, sdgs_apply: true, sdg_1: nil, sdg_2: nil, sdg_3: nil)
result = described_class.new(activity)
expect(result.sustainable_development_goals).to be_nil
end
end
describe "#gcrf_strategic_area" do
it "returns the code list description values for the stored integers" do
activity = build(:project_activity, gcrf_strategic_area: %w[17A RF])
result = described_class.new(activity)
expect(result.gcrf_strategic_area).to eql "UKRI Collective Fund (2017 allocation) and Academies Collective Fund: Resilient Futures"
end
end
describe "#ispf_themes" do
it "returns the code list description value for the stored integer" do
activity = build(:programme_activity, :ispf_funded, ispf_themes: [1, 2])
result = described_class.new(activity)
expect(result.ispf_themes).to eql "Resilient Planet and Transformative Technologies"
end
end
describe "#ispf_oda_partner_countries" do
it_behaves_like "a code translator", "ispf_oda_partner_countries", {type: "ispf_oda_partner_countries", source: "beis"}, "Array"
context "when there are partner countries" do
it "returns the locale value for the codes of the countries joined in sentence form" do
activity = build(:programme_activity, ispf_oda_partner_countries: ["BR", "IN", "LDC"], is_oda: true)
result = ActivityPresenter.new(activity).ispf_oda_partner_countries
expect(result).to eq("Brazil, India (ODA), and Least developed countries")
end
it "handles unexpected country codes" do
activity = build(:programme_activity, ispf_oda_partner_countries: ["ZZ"])
result = ActivityPresenter.new(activity).ispf_oda_partner_countries
expect(result).to eq t("page_content.activity.unknown_country", code: "ZZ")
end
end
end
describe "#ispf_non_oda_partner_countries" do
it_behaves_like "a code translator", "ispf_non_oda_partner_countries", {type: "ispf_non_oda_partner_countries", source: "beis"}, "Array"
context "when there are partner countries" do
it "returns the locale value for the codes of the countries joined in sentence form" do
activity = build(:programme_activity, ispf_non_oda_partner_countries: ["CA", "IN"], is_oda: false)
result = ActivityPresenter.new(activity).ispf_non_oda_partner_countries
expect(result).to eq("Canada and India (non-ODA)")
end
it "handles unexpected country codes" do
activity = build(:programme_activity, ispf_non_oda_partner_countries: ["ZZ"])
result = ActivityPresenter.new(activity).ispf_non_oda_partner_countries
expect(result).to eq t("page_content.activity.unknown_country", code: "ZZ")
end
end
end
describe "#tags" do
it "returns the code list descriptions of the tags as a newline-separated list" do
activity = build(:programme_activity, :ispf_funded, tags: [1, 2])
result = described_class.new(activity)
expect(result.tags).to eql "Ayrton Fund<br>ICF Funded"
end
end
describe "#gcrf_challenge_area" do
it_behaves_like "a code translator", "gcrf_challenge_area", {type: "gcrf_challenge_area", source: "beis"}, "Integer"
it "returns the locale value for the stored integer" do
activity = build(:project_activity, gcrf_challenge_area: 2)
result = described_class.new(activity)
expect(result.gcrf_challenge_area).to eql "Sustainable health and well being"
end
end
describe "#oda_eligibility" do
it_behaves_like "a code translator", "oda_eligibility", {type: "oda_eligibility", source: "beis"}, "Integer"
context "when the activity is ODA eligible" do
it "returns the locale value for this option" do
activity = build(:project_activity, oda_eligibility: 1)
result = described_class.new(activity)
expect(result.oda_eligibility).to eq("Eligible")
end
end
context "when the activity is no longer ODA eligible" do
it "returns the locale value for this option" do
activity = build(:project_activity, oda_eligibility: 2)
result = described_class.new(activity)
expect(result.oda_eligibility).to eq("No longer eligible")
end
end
context "when the activity was never ODA eligible" do
it "returns the locale value for this option" do
activity = build(:project_activity, oda_eligibility: 0)
result = described_class.new(activity)
expect(result.oda_eligibility).to eq("No - was never eligible")
end
end
end
describe "#call_to_action" do
it "returns 'edit' if the desired attribute is present" do
activity = build(:project_activity, title: "My title")
expect(described_class.new(activity).call_to_action(:title)).to eql("edit")
end
it "returns 'edit' if the desired attribute is 'false'" do
activity = build(:project_activity, fstc_applies: false)
expect(described_class.new(activity).call_to_action(:title)).to eql("edit")
end
it "returns 'add' if the desired attribute is not present" do
activity = build(:project_activity, title: nil)
expect(described_class.new(activity).call_to_action(:title)).to eql("add")
end
end
describe "#display_title" do
context "when the title is nil" do
it "returns a default display_title" do
activity = create(:project_activity, :at_purpose_step, title: nil)
expect(described_class.new(activity).display_title).to eql("Untitled (#{activity.id})")
end
end
context "when the title is present" do
it "returns the title" do
activity = build(:project_activity)
expect(described_class.new(activity).display_title).to eql(activity.title)
end
end
end
describe "#parent_title" do
context "when the activity has a parent" do
it "returns the title of the parent" do
fund = create(:fund_activity, title: "A parent title")
programme = create(:programme_activity, parent: fund)
expect(described_class.new(programme).parent_title).to eql("A parent title")
end
end
context "when the activity does NOT have a parent" do
it "returns nil" do
fund = create(:fund_activity, title: "No parent")
expect(described_class.new(fund).parent_title).to eql(nil)
end
end
end
describe "#level" do
context "when the activity is a fund" do
it "returns the custom_capitalisation version of the string" do
fund = create(:fund_activity)
expect(described_class.new(fund).level).to eql("Fund (level A)")
end
end
context "when the activity is a programme" do
it "returns the custom_capitalisation version of the string" do
programme = create(:programme_activity)
expect(described_class.new(programme).level).to eql("Programme (level B)")
end
end
context "when the activity is a project" do
it "returns the custom_capitalisation version of the string" do
project = create(:project_activity)
expect(described_class.new(project).level).to eql("Project (level C)")
end
end
context "when the activity is a third_party_project" do
it "returns the custom_capitalisation version of the string" do
third_party_project = create(:third_party_project_activity)
expect(described_class.new(third_party_project).level).to eql("Third-party project (level D)")
end
end
end
describe "#tied_status_with_code" do
it "returns the code number & tied status string" do
fund = create(:project_activity)
expect(described_class.new(fund).tied_status_with_code).to eql("5: Untied")
end
end
describe "#finance_with_code" do
it "returns the code number & finance string" do
fund = create(:project_activity)
expect(described_class.new(fund).finance_with_code).to eql("110: Standard grant")
end
end
describe "#link_to_roda" do
it "returns the full URL to the activity in RODA" do
project = create(:project_activity)
expect(described_class.new(project).link_to_roda).to eq "http://test.local/organisations/#{project.organisation.id}/activities/#{project.id}/details"
end
end
describe "#actual_total_for_report_financial_quarter" do
it "returns the actual total scoped to report as a formatted number" do
project = create(:project_activity, :with_report)
report = Report.for_activity(project).first
current_quarter = FinancialQuarter.for_date(Date.today)
_actual_in_report_scope = create(:actual, parent_activity: project, report: report, value: 100.20, **current_quarter)
_actual_outside_report_scope = create(:actual, parent_activity: project, report: report, value: 300, **current_quarter.pred)
expect(described_class.new(project).actual_total_for_report_financial_quarter(report: report))
.to eq "100.20"
end
end
describe "#forecasted_total_for_report_financial_quarter" do
it "returns the forecast total per report as a formatted number" do
project = create(:project_activity)
reporting_cycle = ReportingCycle.new(project, 3, 2020)
forecast = ForecastHistory.new(project, financial_quarter: 4, financial_year: 2020)
reporting_cycle.tick
forecast.set_value(200.20)
reporting_cycle.tick
report = Report.for_activity(project).in_historical_order.first
expect(described_class.new(project).forecasted_total_for_report_financial_quarter(report: report))
.to eq "200.20"
end
end
describe "#variance_for_report_financial_quarter" do
it "returns the variance per report as a formatted number" do
project = create(:project_activity)
reporting_cycle = ReportingCycle.new(project, 3, 2019)
forecast = ForecastHistory.new(project, financial_quarter: 4, financial_year: 2019)
reporting_cycle.tick
forecast.set_value(1500)
reporting_cycle.tick
report = Report.for_activity(project).in_historical_order.first
_actual = create(:actual, parent_activity: project, report: report, value: 200, **report.own_financial_quarter)
expect(described_class.new(project).variance_for_report_financial_quarter(report: report))
.to eq "-1300.00"
end
end
describe "#channel_of_delivery_code" do
it "returns the IATI code and IATI name of item" do
activity = build(:project_activity, channel_of_delivery_code: "20000")
result = described_class.new(activity)
expect(result.channel_of_delivery_code).to eq("20000: Non-Governmental Organisation (NGO) and Civil Society")
end
end
describe "#total_spend" do
it "returns the value to two decimal places with a currency symbol" do
activity = build(:programme_activity)
create(:actual, parent_activity: activity, value: 20)
expect(described_class.new(activity).total_spend).to eq("£20.00")
end
end
describe "#total_budget" do
it "returns the value to two decimal places with a currency symbol" do
activity = build(:programme_activity)
create(:budget, parent_activity: activity, value: 50)
expect(described_class.new(activity).total_budget).to eq("£50.00")
end
end
describe "#total_forecasted" do
it "returns the value to two decimal places with a currency symbol" do
activity = build(:programme_activity)
ReportingCycle.new(activity, 3, 2019).tick
ForecastHistory.new(activity, financial_quarter: 4, financial_year: 2019).set_value(50)
expect(described_class.new(activity).total_forecasted).to eq("£50.00")
end
end
describe "#commitment" do
context "when the activity has a commitment" do
let(:activity) { build(:programme_activity, commitment: build(:commitment)) }
it "returns a CommitmentPresenter" do
expect(described_class.new(activity).commitment).to be_a(CommitmentPresenter)
end
end
context "when the activity has no commitment" do
let(:activity) { build(:programme_activity, commitment: nil) }
it "returns nil" do
expect(described_class.new(activity).commitment).to be_nil
end
end
end
end
|
require 'mirrors/iseq/references_visitor'
module Mirrors
# Represents a file on disk, normally corresponding to an entry in
# +$LOADED_FEATURES+ or the definition point of a class or method.
class FileMirror < Mirror
# Trivial object to represent a file path. Only really useful for
# {Mirrors.reflect} to unambiguously determine the mirror type.
File = Struct.new(:path)
# @return [String] path to the file on disk (uniquely identifying)
def name
@reflectee.path
end
# @return [String] path to the file on disk
def path
@reflectee.path
end
# @return [RubyVM::InstructionSequence] Result of compiling the file to
# YARV bytecode.
def native_code
@native_code ||= RubyVM::InstructionSequence.compile_file(path)
rescue Errno::ENOENT, Errno::EPERM
nil
end
# @return [String,nil] Disassembly of the YARV bytecode for this file, if
# available.
def bytecode
@bytecode ||= native_code ? native_code.disasm : nil
end
# @return [Array<Marker>,nil] list of all methods invoked in this file,
# including method bodies.
def references
@references ||= begin
visitor = Mirrors::ISeq::ReferencesVisitor.new
visitor.call(native_code)
visitor.markers
end
end
# @return [String,nil] The source code of this method, if available.
def source
::File.read(path)
rescue Errno::ENOENT, Errno::EPERM
nil
end
end
end
|
describe SNMPTableViewer::Formatter::Table do
describe '#output' do
it 'With headings' do
headings = ['heading1', 'heading2', 'heading3']
data = [
['row1col1', 'row1col2', 'a,b'],
['row2col1', 'row2col2', 'b,c']
]
formatter = described_class.new(data: data, headings: headings)
expect(formatter.output).to eq [
'+----------+----------+----------+',
'| heading1 | heading2 | heading3 |',
'+----------+----------+----------+',
'| row1col1 | row1col2 | a,b |',
'| row2col1 | row2col2 | b,c |',
'+----------+----------+----------+',
].join("\n")
end
it 'Without headings' do
data = [
['row1col1', 'row1col2', 'a,b'],
['row2col1', 'row2col2', 'b,c']
]
formatter = described_class.new(data: data)
expect(formatter.output).to eq [
'+----------+----------+-----+',
'| row1col1 | row1col2 | a,b |',
'| row2col1 | row2col2 | b,c |',
'+----------+----------+-----+',
].join("\n")
end
context 'Transposes output' do
it 'With headings' do
headings = ['heading1', 'heading2', 'heading3']
data = [
['row1col1', 'row1col2', 'a,b'],
['row2col1', 'row2col2', 'b,c']
]
formatter = described_class.new(data: data, headings: headings)
expect(formatter.output(transpose: true)).to eq [
'+----------+----------+----------+',
'| heading1 | row1col1 | row2col1 |',
'| heading2 | row1col2 | row2col2 |',
'| heading3 | a,b | b,c |',
'+----------+----------+----------+',
].join("\n")
end
it 'Without headings' do
data = [
['row1col1', 'row1col2', 'a,b'],
['row2col1', 'row2col2', 'b,c']
]
formatter = described_class.new(data: data)
expect(formatter.output(transpose: true)).to eq [
'+----------+----------+',
'| row1col1 | row2col1 |',
'| row1col2 | row2col2 |',
'| a,b | b,c |',
'+----------+----------+',
].join("\n")
end
end # context transposes output
end # describe #output
end
|
class UserIndustriesController < ApplicationController
def new
skip_authorization # <-------- UPDATE CORRECTLY!
@user = current_user
@user_industry = UserIndustry.new
end
def create
skip_authorization # <-------- UPDATE CORRECTLY!
@user_industry = UserIndustry.new(user_industry_params)
@user = current_user
@user_industry.user = @user
if @user_industry.save
redirect_to new_after_sign_up_advice_preference_path(current_user)
else
render :new
end
end
private
def user_industry_params
params.require(:user_industry).permit(:work_experience, :industry_id)
end
end
|
class RecordGroup < ActiveRecord::Base
attr_accessible :date_from, :date_to, :note, :user_id
belongs_to :user
has_many :temperatures
end
|
module EditorConfigGenerator
# Object representation of an EditorConfig file
# rubocop:disable Style/AccessorMethodName
class EditorConfig
attr_reader :root, :indent_style, :indent_size,
:end_of_line, :charset, :trim_trailing_whitespace,
:insert_final_newline, :file_type
def initialize(options = {})
@root = nil
@file_type = :*
@indent_style = nil
@end_of_line = nil
@charset = nil
@trim_trailing_whitespace = nil
@insert_final_newline = nil
OptionTransformer.transform_options(options)
set_options(options)
end
def set_options(options)
set_root_option(options)
set_indent_style_option(options)
set_indent_size_option(options)
set_end_of_line_option(options)
set_charset_option(options)
set_trailing_space_option(options)
set_final_newline_option(options)
set_file_type_option(options)
end
def set_file_type_option(options)
return if options[:file_type].nil?
@file_type = options[:file_type]
end
def set_final_newline_option(options)
return if options[:insert_final_newline].nil?
@insert_final_newline = options[:insert_final_newline]
end
def set_trailing_space_option(options)
return if options[:trim_trailing_whitespace].nil?
@trim_trailing_whitespace = options[:trim_trailing_whitespace]
end
def set_charset_option(options)
return if options[:charset].nil?
@charset = options[:charset]
end
def set_end_of_line_option(options)
return if options[:end_of_line].nil?
@end_of_line = options[:end_of_line]
end
def set_indent_size_option(options)
return if options[:indent_size].nil?
@indent_size = options[:indent_size]
end
def set_indent_style_option(options)
return if options[:indent_style].nil?
@indent_style = options[:indent_style]
end
def set_root_option(options)
return if options[:root].nil?
@root = options[:root]
end
def to_s
config_string = ''
append_root_to_s(config_string)
append_file_type_to_s(config_string)
append_indent_style_to_s(config_string)
append_indent_size_to_s(config_string)
append_end_of_line_to_s(config_string)
append_charset_to_s(config_string)
append_whitespace_to_s(config_string)
append_final_newline_to_s(config_string)
config_string
end
def append_final_newline_to_s(config_string)
return if @insert_final_newline.nil?
config_string << "insert_final_newline = #{@insert_final_newline}\n"
end
def append_whitespace_to_s(config_string)
return if @trim_trailing_whitespace.nil?
config_string << 'trim_trailing_whitespace ' \
"= #{@trim_trailing_whitespace}\n"
end
def append_charset_to_s(config_string)
return if @charset.nil?
config_string << "charset = #{@charset}\n"
end
def append_end_of_line_to_s(config_string)
return if @end_of_line.nil?
config_string << "end_of_line = #{@end_of_line}\n"
end
def append_indent_size_to_s(config_string)
return if @indent_size.nil?
config_string << "indent_size = #{@indent_size}\n"
end
def append_indent_style_to_s(config_string)
return if @indent_style.nil?
config_string << "indent_style = #{@indent_style}\n"
end
def append_file_type_to_s(config_string)
config_string << "[#{@file_type}]\n"
end
def append_root_to_s(config_string)
return if @root.nil?
config_string << "root = #{@root}\n"
end
def to_s_without_root
lines = to_s.lines
lines.delete_at 0
lines.join
end
def to_s_without_line(line_identifier)
lines = to_s.lines
index = lines.index(line_identifier)
lines.delete_at index
lines.join
end
def minimum?
# The minimum editor config file is one with only root and file_type set
@indent_style.nil? &&
@indent_size.nil? &&
@end_of_line.nil? &&
@charset.nil? &&
@trim_trailing_whitespace.nil? &&
@insert_final_newline.nil?
end
def defaults?
minimum? &&
@file_type == :* &&
@root.nil?
end
end
end
|
require 'spec_helper'
describe DashboardController do
describe 'GET #index' do
let(:limit) { 5 }
let(:response) { double('response', header: { 'Total-Count' => '10' }) }
let(:resource_response) { double('resource_response', response: response) }
let(:resources) do
{
'Application' => { list: resource_response, count: 10, manage_path: apps_path, more_count: 5 },
'Source' => { list: resource_response, count: 10, manage_path: template_repos_path, more_count: 5 },
'Image' => { list: resource_response, count: 10, manage_path: images_path, more_count: 5 }
}
end
it 'calls all_with_response on APP' do
expect(App).to receive(:all_with_response).with(params: { limit: limit }).and_return(resource_response)
get :index
end
it 'calls all_with_response on TemplateRepo' do
expect(TemplateRepo).to receive(:all_with_response).with(params: { limit: limit }).and_return(resource_response)
get :index
end
it 'calls all_with_response on LocalImage' do
expect(LocalImage).to receive(:all_with_response).with(params: { limit: limit }).and_return(resource_response)
get :index
end
it 'assigns values to the resources instance variable' do
[App, TemplateRepo, LocalImage].each do |resource|
resource.stub(:all_with_response).and_return(resource_response)
end
get :index
expect(assigns(:resources)).to eq resources
end
it 'the map of resources contains expected keys' do
get :index
expect(assigns(:resources).keys).to match_array %w(Application Source Image)
end
end
end
|
class User < ApplicationRecord
extend Enumerize
has_secure_password
enumerize :role, in: [:user, :admin]
validates :email, presence: true, uniqueness: true
validates :role, presence: true
has_many :tasks, dependent: :destroy
def fetch_tasks
role.admin? ? Task.all : tasks
end
end
|
# frozen_string_literal: true
class HoldChange < ActiveRecord::Base
# attr_accessible :status, :comment, :hold_id, :admin_user_id
validates_presence_of :hold_id, :status
belongs_to :hold
belongs_to :admin_user
after_save :do_after_save
def do_after_save
update_hold
if hold.teacher_set.present?
send_change_status_email
else
send_teacher_set_deleted_email
end
end
def send_change_status_email
# deliver email if status has been changed to error, pending, closed, or cancelled
HoldMailer.status_change(hold, status, comment).deliver if ['error', 'pending', 'closed', 'cancelled'].include? status
end
def send_teacher_set_deleted_email
HoldMailer.teacher_set_deleted_notification(hold, status, comment).deliver if ['closed', 'cancelled'].include? status
end
def update_hold
# puts "updating hold status: ", hold.status, status
hold.status = status
hold.save
end
end
|
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
GENDERS = ['man', 'woman']
has_many :received_reviews, class_name: 'Review', foreign_key: 'destinator_id'
has_many :sent_reviews, class_name: 'Review', foreign_key: 'creator_id'
has_many :received_messages, class_name: 'Message', foreign_key: 'destinator_id'
has_many :sent_messages, class_name: 'Message', foreign_key: 'creator_id'
has_many :jobs
has_many :received_requests, class_name: 'Request', foreign_key: 'destinator_id'
has_many :sent_requests, class_name: 'Request', foreign_key: 'creator_id'
has_attachment :picture
validates :sexe, inclusion: { in: GENDERS, allow_nil: true }
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable, omniauth_providers: [:facebook]
FACEBOOK_GENDER = {
'male' => 'man',
'female' => 'woman'
}
def requests
Request.where('creator_id = ? OR destinator_id = ?', id, id)
end
def reviews
Review.where('creator_id = ? OR destinator_id = ?', id, id)
end
def self.find_for_facebook_oauth(auth)
user_params = auth.slice(:provider, :uid)
user_params.merge! auth.info.slice(:email, :first_name, :last_name)
user_params[:facebook_picture_url] = auth.info.image
user_params[:token] = auth.credentials.token
user_params[:token_expiry] = Time.at(auth.credentials.expires_at)
user_params = user_params.to_h
user_params[:sexe] = FACEBOOK_GENDER[auth.extra.raw_info.gender]
user = User.where(provider: auth.provider, uid: auth.uid).first
user ||= User.where(email: auth.info.email).first # User did a regular sign up in the past.
if user
user.update(user_params)
else
user = User.new(user_params)
user.picture_url = auth.info.image.to_s
user.password = Devise.friendly_token[0,20] # Fake password for validation
user.save!
end
return user
end
end
|
require 'spec_helper'
RSpec.describe Sentry::Event do
let(:configuration) do
Sentry::Configuration.new.tap do |config|
config.dsn = Sentry::TestHelper::DUMMY_DSN
end
end
describe "#initialize" do
it "initializes a Event when all required keys are provided" do
expect(described_class.new(configuration: configuration)).to be_a(described_class)
end
it "initializes a Event with correct default values" do
configuration.server_name = "foo.local"
configuration.environment = "test"
configuration.release = "721e41770371db95eee98ca2707686226b993eda"
event = described_class.new(configuration: configuration)
expect(event.timestamp).to be_a(String)
expect(event.user).to eq({})
expect(event.extra).to eq({})
expect(event.contexts).to eq({})
expect(event.tags).to eq({})
expect(event.fingerprint).to eq([])
expect(event.platform).to eq(:ruby)
expect(event.server_name).to eq("foo.local")
expect(event.environment).to eq("test")
expect(event.release).to eq("721e41770371db95eee98ca2707686226b993eda")
expect(event.sdk).to eq("name" => "sentry.ruby", "version" => Sentry::VERSION)
expect(event.dynamic_sampling_context).to eq(nil)
end
end
describe "#inspect" do
let(:client) do
Sentry::Client.new(configuration)
end
subject do
e = begin
1/0
rescue => e
e
end
client.event_from_exception(e)
end
it "still contains relevant info" do
expect(subject.inspect).to match(/@event_id="#{subject.event_id}"/)
end
it "ignores @configuration" do
expect(subject.inspect).not_to match(/@configuration/)
end
it "ignores @modules" do
expect(subject.inspect).not_to match(/@modules/)
end
it "ignores @backtrace" do
expect(subject.inspect).not_to match(/@backtrace/)
end
end
context 'rack context specified', rack: true do
require 'stringio'
before do
perform_basic_setup
Sentry.get_current_scope.set_rack_env(
'REQUEST_METHOD' => 'POST',
'QUERY_STRING' => 'biz=baz',
'HTTP_HOST' => 'localhost',
'SERVER_NAME' => 'localhost',
'SERVER_PORT' => '80',
'HTTP_X_FORWARDED_FOR' => '1.1.1.1, 2.2.2.2',
'HTTP_X_REQUEST_ID' => 'abcd-1234-abcd-1234',
'REMOTE_ADDR' => '192.168.1.1',
'PATH_INFO' => '/lol',
'rack.url_scheme' => 'http',
'rack.input' => StringIO.new('foo=bar')
)
end
let(:event) do
Sentry::Event.new(configuration: Sentry.configuration)
end
let(:scope) { Sentry.get_current_scope }
context "without config.send_default_pii = true" do
it "filters out pii data" do
scope.apply_to_event(event)
expect(event.to_hash[:request]).to eq(
env: { 'SERVER_NAME' => 'localhost', 'SERVER_PORT' => '80' },
headers: { 'Host' => 'localhost', 'X-Request-Id' => 'abcd-1234-abcd-1234' },
method: 'POST',
url: 'http://localhost/lol',
)
expect(event.to_hash[:tags][:request_id]).to eq("abcd-1234-abcd-1234")
expect(event.to_hash[:user][:ip_address]).to eq(nil)
end
it "removes ip address headers" do
scope.apply_to_event(event)
# doesn't affect scope's rack_env
expect(scope.rack_env).to include("REMOTE_ADDR")
expect(event.request.headers.keys).not_to include("REMOTE_ADDR")
expect(event.request.headers.keys).not_to include("Client-Ip")
expect(event.request.headers.keys).not_to include("X-Real-Ip")
expect(event.request.headers.keys).not_to include("X-Forwarded-For")
end
end
context "with config.send_default_pii = true" do
before do
Sentry.configuration.send_default_pii = true
end
it "adds correct data" do
Sentry.get_current_scope.apply_to_event(event)
expect(event.to_hash[:request]).to eq(
data: { 'foo' => 'bar' },
env: { 'SERVER_NAME' => 'localhost', 'SERVER_PORT' => '80', "REMOTE_ADDR" => "192.168.1.1" },
headers: { 'Host' => 'localhost', "X-Forwarded-For" => "1.1.1.1, 2.2.2.2", "X-Request-Id" => "abcd-1234-abcd-1234" },
method: 'POST',
query_string: 'biz=baz',
url: 'http://localhost/lol',
cookies: {}
)
expect(event.to_hash[:tags][:request_id]).to eq("abcd-1234-abcd-1234")
expect(event.to_hash[:user][:ip_address]).to eq("2.2.2.2")
end
context "with config.trusted_proxies = [\"2.2.2.2\"]" do
before do
Sentry.configuration.trusted_proxies = ["2.2.2.2"]
end
it "calculates the correct ip address" do
Sentry.get_current_scope.apply_to_event(event)
expect(event.to_hash[:request]).to eq(
:data=>{"foo"=>"bar"},
env: { 'SERVER_NAME' => 'localhost', 'SERVER_PORT' => '80', "REMOTE_ADDR" => "192.168.1.1" },
headers: { 'Host' => 'localhost', "X-Forwarded-For" => "1.1.1.1, 2.2.2.2", "X-Request-Id" => "abcd-1234-abcd-1234" },
method: 'POST',
query_string: 'biz=baz',
url: 'http://localhost/lol',
cookies: {}
)
expect(event.to_hash[:tags][:request_id]).to eq("abcd-1234-abcd-1234")
expect(event.to_hash[:user][:ip_address]).to eq("1.1.1.1")
end
end
end
end
describe '#to_json_compatible' do
subject do
Sentry::Event.new(configuration: configuration).tap do |event|
event.extra = {
'my_custom_variable' => 'value',
'date' => Time.utc(0),
'anonymous_module' => Class.new
}
end
end
it "should coerce non-JSON-compatible types" do
json = subject.to_json_compatible
expect(json["extra"]['my_custom_variable']).to eq('value')
expect(json["extra"]['date']).to be_a(String)
expect(json["extra"]['anonymous_module']).not_to be_a(Class)
end
end
describe ".get_log_message" do
let(:client) do
Sentry::Client.new(configuration)
end
let(:hub) do
Sentry::Hub.new(client, Sentry::Scope.new)
end
context "with adnormal event" do
subject do
Sentry::Event.new(configuration: configuration)
end
it "returns placeholder message" do
expect(described_class.get_log_message(subject.to_hash)).to eq('<no message value>')
expect(described_class.get_log_message(subject.to_json_compatible)).to eq('<no message value>')
end
end
context "with transaction event" do
let(:transaction) do
Sentry::Transaction.new(name: "test transaction", op: "sql.active_record", hub: hub, sampled: true)
end
subject do
client.event_from_transaction(transaction)
end
it "returns the transaction's name" do
expect(described_class.get_log_message(subject.to_hash)).to eq("test transaction")
expect(described_class.get_log_message(subject.to_json_compatible)).to eq("test transaction")
end
end
context "with exception event" do
subject do
client.event_from_exception(Exception.new("error!"))
end
it "returns the exception's message" do
expect(described_class.get_log_message(subject.to_hash)).to include("Exception: error!")
expect(described_class.get_log_message(subject.to_json_compatible)).to match("Exception: error!")
end
end
context "with message event" do
subject do
client.event_from_message("test")
end
it "returns the event's message" do
expect(described_class.get_log_message(subject.to_hash)).to eq("test")
expect(described_class.get_log_message(subject.to_json_compatible)).to eq("test")
end
end
end
end
|
require 'bcrypt'
class User < ActiveRecord::Base
validates :email, :password_digest, :session_token, presence: true
validates :email, uniqueness: true
after_initialize :ensure_session_token
has_many :subs,
foreign_key: :moderator_id,
inverse_of: :moderator
has_many :posts,
foreign_key: :author_id,
inverse_of: :author
has_many :comments,
foreign_key: :author_id
def self.generate_session_token
SecureRandom::urlsafe_base64(16)
end
def self.find_by_credentials(credentials = {})
user = User.find_by_email(credentials[:email])
return nil if user.nil?
user.is_password?(credentials[:password]) ? user : nil
end
def password=(password)
return unless password.present?
self.password_digest = BCrypt::Password.create(password)
end
def is_password?(password)
BCrypt::Password.new(self.password_digest).is_password?(password)
end
def reset_session_token!
self.session_token = self.class.generate_session_token
self.save!
self.session_token
end
def ensure_session_token
self.session_token ||= self.class.generate_session_token
end
end
|
require 'yaml'
require 'pathname'
require 'erb'
module Minarai
module Loaders
class Base
def initialize(path)
@path = path
end
def load
case
when !existed_file?
raise "Does not exist file: #{pathname}"
when yml_file?
load_yaml_file
when erb_file?
load_erb_file
else
raise 'inalid extname error'
end
end
private
def binding_for_erb
TOPLEVEL_BINDING
end
def loaded_class
raise NotImplementedError
end
def load_yaml_file
loaded_class.new(load_file_from_yaml)
end
def load_erb_file
self.class.new(parsed_erb_file.path).load
end
def parsed_erb
ERB.new(pathname.read).result(binding_for_erb)
end
def parsed_erb_file
@parsed_erb_file ||= Tempfile.open(['', '.yml']) do |tmp|
tmp.puts parsed_erb
tmp
end
end
def existed_file?
pathname.exist?
end
def yml_file?
%w(.yml yaml).include?(pathname.extname)
end
def erb_file?
pathname.extname == '.erb'
end
def load_file_from_yaml
YAML.load_file(pathname)
end
def pathname
@pathname ||= Pathname.new(@path)
end
end
end
end
|
require 'cases/sqlserver_helper'
require 'models/event'
class FinderTestSqlserver < ActiveRecord::TestCase
end
class FinderTest < ActiveRecord::TestCase
COERCED_TESTS = [:test_string_sanitation]
include SqlserverCoercedTest
def test_coerced_string_sanitation
assert_not_equal "'something ' 1=1'", ActiveRecord::Base.sanitize("something ' 1=1")
if quote_values_as_utf8?
assert_equal "N'something; select table'", ActiveRecord::Base.sanitize("something; select table")
else
assert_equal "'something; select table'", ActiveRecord::Base.sanitize("something; select table")
end
end
end
|
class LocalVarsInScope
def initialize(binding)
@source_binding = binding
end
def include?(var_name)
begin
return @source_binding.local_variable_defined?(var_name)
rescue NameError # some method name are not valid local variable names so local_variable_defined? will raise a NameError
false
end
end
end |
# coding: utf-8
# frozen_string_literal: true
# This file is part of IPsec packetgen plugin.
# See https://github.com/sdaubert/packetgen-plugin-ipsec for more informations
# Copyright (c) 2018 Sylvain Daubert <sylvain.daubert@laposte.net>
# This program is published under MIT license.
module PacketGen::Plugin
class IKE
# TrafficSelector substructure, as defined in RFC 7296, §3.13.1:
# 1 2 3
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | TS Type |IP Protocol ID*| Selector Length |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | Start Port* | End Port* |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | |
# ~ Starting Address* ~
# | |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | |
# ~ Ending Address* ~
# | |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# @author Sylvain Daubert
class TrafficSelector < PacketGen::Types::Fields
# IPv4 traffic selector type
TS_IPV4_ADDR_RANGE = 7
# IPv6 traffic selector type
TS_IPV6_ADDR_RANGE = 8
# @!attribute [r] type
# 8-bit TS type
# @return [Integer]
define_field :type, PacketGen::Types::Int8, default: 7
# @!attribute [r] protocol
# 8-bit protocol ID
# @return [Integer]
define_field :protocol, PacketGen::Types::Int8, default: 0
# @!attribute length
# 16-bit Selector Length
# @return [Integer]
define_field :length, PacketGen::Types::Int16
# @!attribute start_port
# 16-bit Start port
# @return [Integer]
define_field :start_port, PacketGen::Types::Int16, default: 0
# @!attribute end_port
# 16-bit End port
# @return [Integer]
define_field :end_port, PacketGen::Types::Int16, default: 65_535
# @!attribute start_addr
# starting address
# @return [IP::Addr, IPv6::Addr]
define_field :start_addr, PacketGen::Header::IP::Addr
# @!attribute end_addr
# starting address
# @return [IP::Addr, IPv6::Addr]
define_field :end_addr, PacketGen::Header::IP::Addr
# @param [Hash] options
# @options[Integer] :type
# @options[Integer] :protocol
# @options[Integer] :length
# @option [String] :start_addr
# @option [String] :end_addr
# @option [Range] :ports port range
def initialize(options={}) # rubocop:disable Metrics/AbcSize
super
select_addr options
self[:start_addr].from_human(options[:start_addr]) if options[:start_addr]
self[:end_addr].from_human(options[:end_addr]) if options[:end_addr]
self.type = options[:type] if options[:type]
self.protocol = options[:protocol] if options[:protocol]
self[:length].value = sz unless options[:length]
return unless options[:ports]
self.start_port = options[:ports].begin
self.end_port = options[:ports].end
end
# Populate object from a string
# @param [String] str
# @return [self]
def read(str)
super
select_addr_from_type type
super
end
undef type=, protocol=
# Set type
# @param [Integer,String] value
# @return [Integer]
def type=(value)
type = case value
when Integer
value
else
c = self.class.constants.grep(/TS_#{value.upcase}/).first
c ? self.class.const_get(c) : nil
end
raise ArgumentError, "unknown type #{value.inspect}" unless type
select_addr_from_type type
self[:type].value = type
end
# Set protocol
# @param [Integer,String] value
# @return [Integer]
def protocol=(value)
protocol = case value
when Integer
value
else
PacketGen::Proto.getprotobyname(value)
end
raise ArgumentError, "unknown protocol #{value.inspect}" unless protocol
self[:protocol].value = protocol
end
# Get a human readable string
# @return [String]
def to_human
h = start_addr << '-' << end_addr
unless human_protocol.empty?
h << "/#{human_protocol}"
h << "[#{start_port}-#{end_port}]" if (start_port..end_port) != (0..65_535)
end
h
end
# Get human readable protocol name. If protocol ID is 0, an empty string
# is returned.
# @return [String]
def human_protocol
if protocol.zero?
''
else
PacketGen::Proto.getprotobynumber(protocol) || protocol.to_s
end
end
# Get human readable TS type
# @return [String]
def human_type
case type
when TS_IPV4_ADDR_RANGE
'IPv4'
when TS_IPV6_ADDR_RANGE
'IPv6'
else
"type #{type}"
end
end
private
def select_addr_from_type(type)
case type
when TS_IPV4_ADDR_RANGE, 'IPV4', 'IPv4', 'ipv4', nil
self[:start_addr] = PacketGen::Header::IP::Addr.new unless self[:start_addr].is_a?(PacketGen::Header::IP::Addr)
self[:end_addr] = PacketGen::Header::IP::Addr.new unless self[:end_addr].is_a?(PacketGen::Header::IP::Addr)
when TS_IPV6_ADDR_RANGE, 'IPV6', 'IPv6', 'ipv6'
self[:start_addr] = PacketGen::Header::IPv6::Addr.new unless self[:start_addr].is_a?(PacketGen::Header::IPv6::Addr)
self[:end_addr] = PacketGen::Header::IPv6::Addr.new unless self[:end_addr].is_a?(PacketGen::Header::IPv6::Addr)
else
raise ArgumentError, "unknown type #{type}"
end
end
def select_addr(options)
if options[:type]
select_addr_from_type options[:type]
elsif options[:start_addr]
ipv4 = IPAddr.new(options[:start_addr]).ipv4?
self.type = ipv4 ? TS_IPV4_ADDR_RANGE : TS_IPV6_ADDR_RANGE
elsif options[:end_addr]
ipv4 = IPAddr.new(options[:end_addr]).ipv4?
self.type = ipv4 ? TS_IPV4_ADDR_RANGE : TS_IPV6_ADDR_RANGE
end
end
end
# Set of {TrafficSelector}, used by {TSi} and {TSr}.
# @author Sylvain Daubert
class TrafficSelectors < PacketGen::Types::Array
set_of TrafficSelector
end
# This class handles Traffic Selector - Initiator payloads, denoted TSi.
#
# A TSi payload consists of the IKE generic payload Plugin (see {Payload})
# and some specific fields:
# 1 2 3
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | Next Payload |C| RESERVED | Payload Length |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | Number of TSs | RESERVED |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | |
# ~ <Traffic Selectors> ~
# | |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# These specific fields are:
# * {#num_ts},
# * {#rsv1},
# * {#rsv2},
# * and {#traffic_selectors}.
#
# == Create a TSi payload
# # Create a IKE packet with a TSi payload
# pkt = PacketGen.gen('IP').add('UDP').add('IKE').add('IKE::TSi')
# # add a traffic selector to this payload
# pkt.ike_tsi.traffic_selectors << { protocol: 'tcp', ports: 1..1024, start_addr: '20.0.0.1', end_addr: '21.255.255.254' }
# # add another traffic selector (IPv6, all protocols)
# pkt.ike_tsi.traffic_selectors << { start_addr: '2001::1', end_addr: '200a:ffff:ffff:ffff:ffff:ffff:ffff:ffff' }
# @author Sylvain Daubert
class TSi < Payload
# Payload type number
PAYLOAD_TYPE = 44
remove_field :content
# @!attribute num_ts
# 8-bit Number of TSs
# @return [Integer]
define_field_before :body, :num_ts, PacketGen::Types::Int8
# @!attribute rsv
# 24-bit RESERVED field
# @return [Integer]
define_field_before :body, :rsv, PacketGen::Types::Int24
# @!attribute traffic_selectors
# Set of {TrafficSelector}
# @return {TrafficSelectors}
define_field_before :body, :traffic_selectors, TrafficSelectors,
builder: ->(h, t) { t.new(counter: h[:num_ts]) }
alias selectors traffic_selectors
# Compute length and set {#length} field
# @return [Integer] new length
def calc_length
selectors.each(&:calc_length)
super
end
end
class TSr < TSi
# Payload type number
PAYLOAD_TYPE = 45
end
end
PacketGen::Header.add_class IKE::TSi
PacketGen::Header.add_class IKE::TSr
end
|
require 'spec_helper'
describe TKOaly::Auth do
describe "generic case" do
before(:each) do
@username = 'foobar'
@auth_query_mock = mock(TKOaly::Auth::Query)
TKOaly::Auth::Query.should_receive(:new).and_return(@auth_query_mock)
@auth_response_mock = mock(TKOaly::Auth::Response)
TKOaly::Auth::Response.should_receive(:new).and_return(@auth_response_mock)
@auth_query_mock.stub!(:fetch).and_return(@auth_response_mock)
end
it "should tell when foobar belongs to RandomRole" do
@role = 'RandomRole'
@auth_response_mock.should_receive(:belongs?).and_return(true)
TKOaly::Auth.generic_question(@username, @role).should be_true
end
it "should tell when foobar doesn't belong to StaticRole" do
@role = 'StaticRole'
@auth_response_mock.should_receive(:belongs?).and_return(false)
TKOaly::Auth.generic_question(@username, @role).should be_false
end
end
describe "tarkisto admin" do
before(:each) do
@tarkisto_admin_group = 'ExamOfficer'
end
it "should tell if user can administrate tarkisto" do
valid_admin_user = 'saada'
TKOaly::Auth.should_receive(:generic_question).with(valid_admin_user, @tarkisto_admin_group).and_return(true)
TKOaly::Auth.tarkisto_admin?(valid_admin_user).should be_true
end
it "should tell if user can not administrate tarkisto" do
invalid_admin_user = 'l33th4x0r'
TKOaly::Auth.should_receive(:generic_question).with(invalid_admin_user, @tarkisto_admin_group).and_return(false)
TKOaly::Auth.tarkisto_admin?(invalid_admin_user).should be_false
end
end
end
|
class LookcharController < ApplicationController
before_action :authenticate_user!
def input; end
def output
@nick = params[:nick]
@result = if !@nick || @nick.empty?
@result = nil
else
show_char(@nick)
end
respond_to do |format|
format.js { render 'output.js.erb' }
end
end
private
def show_char(nick)
Char.where('nick LIKE ?', nick)
end
end
|
require 'spec_helper'
describe RakutenWebService::Travel::SearchResult do
let(:resource_class) do
Class.new(RakutenWebService::Resource) do
endpoint 'https://api.example.com/SearchDummyResource'
end
end
let(:search_result) do
RakutenWebService::Travel::SearchResult.new({}, resource_class)
end
describe '#next_page?' do
let(:response) do
double().tap do |d|
allow(d).to receive('[]').with('pagingInfo').and_return(pagingInfo)
end
end
before do
allow(search_result).to receive(:response).and_return(response)
end
context 'when current page does not reach at the last page' do
let(:pagingInfo) do
{ 'page' => 1, 'pageCount' => 10 }
end
it 'should have next page' do
expect(search_result).to be_next_page
end
end
context 'when current page reaches at the last page' do
let(:pagingInfo) do
{ 'page' => 5, 'pageCount' => 5 }
end
it 'should not have next page' do
expect(search_result).to_not be_next_page
end
end
end
describe '#next_page' do
let(:response) do
double().tap do |d|
allow(d).to receive('[]').with('pagingInfo').and_return(pagingInfo)
end
end
before do
allow(search_result).to receive(:response).and_return(response)
end
let(:pagingInfo) do
{ 'page' => 2, 'pageCount' => 3 }
end
it 'shold call search to fetch next page results.' do
expect(search_result).to receive(:search).with({'page' => 3})
search_result.next_page
end
end
describe '#search' do
it 'should return trave\'s search result' do
expect(search_result.search({})).to be_a(RakutenWebService::Travel::SearchResult)
end
end
end
|
require 'spec_helper'
describe DoceboRuby::Resource do
describe '.api=' do
before do
DoceboRuby::Resource.api = 'test'
end
it 'sets the api' do
expect(DoceboRuby::Resource.api).to eq 'test'
end
end
end
|
require 'rails_helper'
feature "creating a new message" do
before(:each) do
visit "/login"
fill_in "user[username]", with: "lukeskywalker"
click_button "Create User"
end
scenario "message was created succesfully" do
fill_in "message[message]", with: "This is a super long message yeah yeah yeah"
click_button "Post Message"
expect(page).to have_current_path("/messages")
expect(page).to have_content("This is a super long message yeah yeah yeah")
end
scenario "message was empty" do
click_button "Post Message"
expect(page).to have_current_path("/messages")
expect(page).to have_content("Message can't be blank")
end
scenario "message to be at least 10 characters" do
fill_in "message[message]", with: "short"
click_button "Post Message"
expect(page).to have_current_path("/messages")
expect(page).to have_content("Message is too short (minimum is 10 characters)")
end
end |
class DuosController < ApplicationController
before_action :set_duo, only: [:show, :edit, :update, :destroy]
#Create Dogs all
@dogs = Dog.all
# GET /duos
# GET /duos.json
def index
@duos = Duo.all
end
# GET /duos/1
# GET /duos/1.json
def show
end
# GET /duos/new
def new
@duo = Duo.new
end
# GET /duos/1/edit
def edit
end
# POST /duos
# POST /duos.json
def create
@duo = Duo.new(duo_params)
respond_to do |format|
if @duo.save
format.html { redirect_to @duo, notice: 'Duo was successfully created.' }
format.json { render :show, status: :created, location: @duo }
else
format.html { render :new }
format.json { render json: @duo.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /duos/1
# PATCH/PUT /duos/1.json
def update
respond_to do |format|
if @duo.update(duo_params)
format.html { redirect_to @duo, notice: 'Duo was successfully updated.' }
format.json { render :show, status: :ok, location: @duo }
else
format.html { render :edit }
format.json { render json: @duo.errors, status: :unprocessable_entity }
end
end
end
# DELETE /duos/1
# DELETE /duos/1.json
def destroy
@duo.destroy
respond_to do |format|
format.html { redirect_to duos_url, notice: 'Duo was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_duo
@duo = Duo.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def duo_params
params.require(:duo).permit(:handler_id, :dog_id)
end
end
|
require 'sinatra'
require_relative 'lib/bot'
require_relative 'lib/admin'
class Server < Sinatra::Base
set :show_exceptions, false
set :raise_errors, false
helpers Bot
helpers Admin
post '/' do
begin
Bot.bot.handle_item(params)
rescue StandardError => e
[500, {}, { error: e.message }.to_json]
end
end
get '/status' do
Admin.status_msg
end
end
|
class CreateCategories < ActiveRecord::Migration
def self.up
create_table :categories, :force => true do |t|
# Needed by acts_as_category
t.integer :parent_id
t.integer :ancestors_count, :default => 0
t.integer :descendants_count, :default => 0
t.integer :children_count, :default => 0
t.boolean :hidden
# Optional
t.string :name, :description
t.integer :position, :pictures_count
end
end
def self.down
drop_table :categories
end
end
|
module Moonr
class ArrayLiteral < ASTElem
def jseval(context, strict = false)
arr = JSArray.new
@arg.inject(arr) do |arr, literal|
pad = literal.elisions
len = arr.get(:length)
init_result = literal.elem.nil? ? nil : literal.elem.jseval(context)
if init_result.nil?
arr.put "length", pad+len, false
else
init_value = init_result.get_value
arr.def_own_property (len+pad).to_s, PropDescriptor.new(:value => init_value,
:writable => true,
:enumerable => true,
:configurable => true), false
end
arr
end
end
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 rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
# Tutors
Tutor.create!([
{
first_name: "Sergiu",
last_name: "Rosca",
email: "rmagnum2002@gmail.com",
password: "pass2013",
activated: true, activated_at: Time.now, confirmation_token: nil,
confirmed_at: Time.now,
confirmation_sent_at: Time.now, address: "Patriarchou Grigoriou E, Spata-Artemida 190 16, Greece",
latitude: 37.96531225105652,
longitude: 23.99847473906243,
gmaps: true, postal_code: "190 16",
country: "Greece", locality: "Artemida",
administrative_area_level_2: "Attica",
administrative_area_level_1: "Attica", location_type: "",
phone: "1234567810",
avatar: File.open(File.join(Rails.root, 'avatars','sergiu.jpg')),
distance: 10,
type: 'Tutor'
},
{
first_name: "Nicholas",
last_name: "Cage",
email: "ncage@gmail.com",
password: "pass2013",
activated: true, activated_at: Time.now, confirmation_token: nil,
confirmed_at: Time.now,
confirmation_sent_at: Time.now, address: "Agiou Trifonos, Lamia 351 00, Greece",
latitude: 38.8850718,
longitude: 22.450129800000013,
gmaps: true, postal_code: "351 00",
country: "Greece", locality: "Lamia",
administrative_area_level_2: "Sterea Ellada",
administrative_area_level_1: "Thessalia Sterea Ellada", location_type: "",
phone: "1234567811",
avatar: File.open(File.join(Rails.root, 'avatars','cage.jpg')),
distance: 10,
type: 'Tutor'
},
{
first_name: "John",
last_name: "Travolta",
email: "jtravolta@gmail.com",
password: "pass2013",
activated: true, activated_at: Time.now, confirmation_token: nil,
confirmed_at: Time.now,
confirmation_sent_at: Time.now, address: "Trivonianou 9-15, Athens 116 36, Greece",
latitude: 37.96482019420022,
longitude: 23.734103337109445,
gmaps: true, postal_code: "116 36",
country: "Greece", locality: "Athens",
administrative_area_level_2: "Attica",
administrative_area_level_1: "Attica", location_type: "",
phone: "1234567812",
avatar: File.open(File.join(Rails.root, 'avatars','travolta.jpg')),
distance: 15,
type: 'Tutor'
},
{
first_name: "Brad",
last_name: "Pitt",
email: "bpitt@gmail.com",
password: "pass2013",
activated: true, activated_at: Time.now, confirmation_token: nil,
confirmed_at: Time.now,
confirmation_sent_at: Time.now, address: "Agiou Trifonos, Lamia 351 00, Greece",
latitude: 38.8850718,
longitude: 22.450129800000013,
gmaps: true, postal_code: "351 00",
country: "Greece", locality: "Lamia",
administrative_area_level_2: "Sterea Ellada",
administrative_area_level_1: "Thessalia Sterea Ellada", location_type: "",
phone: "1234567813",
avatar: File.open(File.join(Rails.root, 'avatars','pitt.jpg')),
distance: 5,
type: 'Tutor'
},
{
first_name: "Robert",
last_name: "De Niro",
email: "rdeniro@gmail.com",
password: "pass2013",
activated: true, activated_at: Time.now, confirmation_token: nil,
confirmed_at: Time.now,
confirmation_sent_at: Time.now, address: "Millerou 43, Athens 104 36, Greece",
latitude: 37.9838675,
longitude: 23.71843260000003,
gmaps: true, postal_code: "104 36",
country: "Greece", locality: "Athens",
administrative_area_level_2: "",
administrative_area_level_1: "Attica", location_type: "",
phone: "1234567814",
avatar: File.open(File.join(Rails.root, 'avatars','deniro.jpg')),
distance: 15,
type: 'Tutor'
},
{
first_name: "Leonardo",
last_name: "Di Caprio",
email: "ldicaprio@gmail.com",
password: "pass2013",
activated: true, activated_at: Time.now, confirmation_token: nil,
confirmed_at: Time.now,
confirmation_sent_at: Time.now, address: "Ethniki Odos Volou Neochoriou, Volos 373 00, Greece",
latitude: 39.33687147787983,
longitude: 23.043391518750013,
gmaps: true, postal_code: "373 00",
country: "Greece", locality: "Kato Lechonia",
administrative_area_level_2: "Thessalia",
administrative_area_level_1: "Thessalia Sterea Ellada", location_type: "",
phone: "1234567815",
avatar: File.open(File.join(Rails.root, 'avatars','dicaprio.jpg')),
distance: 10,
type: 'Tutor'
},
{
first_name: "Matt",
last_name: "Damon",
email: "mdamon@gmail.com",
password: "pass2013",
activated: true, activated_at: Time.now, confirmation_token: nil,
confirmed_at: Time.now,
confirmation_sent_at: Time.now, address: "Kapetan Gkoni 17, Pavlos Melas 564 30, Greece",
latitude: 40.66649728093227,
longitude: 22.933528237500013,
gmaps: true, postal_code: "564 30",
country: "Greece", locality: "Stavroupoli",
administrative_area_level_2: "Kentriki Makedonia",
administrative_area_level_1: "Makedonia Thraki", location_type: "",
phone: "1234567816",
avatar: File.open(File.join(Rails.root, 'avatars','damon.jpg')),
distance: 15,
type: 'Tutor'
},
{
first_name: "Keira",
last_name: "Knightley",
email: "kknightley@gmail.com",
password: "pass2013",
activated: true, activated_at: Time.now, confirmation_token: nil,
confirmed_at: Time.now,
confirmation_sent_at: Time.now, address: "Thessaloniki, Pylaia 555 35, Greece",
latitude: 40.59562661731052,
longitude: 22.980220132031263,
gmaps: true, postal_code: "555 35",
country: "Greece", locality: "Pylaia",
administrative_area_level_2: "Kentriki Makedonia",
administrative_area_level_1: "Makedonia Thraki", location_type: "",
phone: "1234567817",
avatar: File.open(File.join(Rails.root, 'avatars','keira.jpg')),
distance: 15,
type: 'Tutor'
},
{
first_name: "Michelle",
last_name: "Pfeiffer",
email: "mpfeiffer@gmail.com",
password: "pass2013",
activated: true, activated_at: Time.now, confirmation_token: nil,
confirmed_at: Time.now,
confirmation_sent_at: Time.now, address: "Omirou 16-22, Kalamata 241 00, Greece",
latitude: 37.029608,
longitude: 22.113270599999964,
gmaps: true, postal_code: "241 00",
country: "Greece", locality: "Kalamata",
administrative_area_level_2: "Peloponnese",
administrative_area_level_1: "Peloponnisos Dytiki Ellada ke Ionio", location_type: "",
phone: "1234567818",
avatar: File.open(File.join(Rails.root, 'avatars','pfeiffer.jpg')),
distance: 10,
type: 'Tutor'
},
{
first_name: "Al",
last_name: "Pacino",
email: "apacino@gmail.com",
password: "pass2013",
activated: true, activated_at: Time.now, confirmation_token: nil,
confirmed_at: Time.now,
confirmation_sent_at: Time.now, address: "Vironos 11-13, Kalamata 241 00, Greece",
latitude: 37.04019712224404,
longitude: 22.116665092065432,
gmaps: true, postal_code: "241 00",
country: "Greece", locality: "Kalamata",
administrative_area_level_2: "Peloponnese",
administrative_area_level_1: "Peloponnisos Dytiki Ellada ke Ionio", location_type: "",
phone: "1234567819",
avatar: File.open(File.join(Rails.root, 'avatars','pacino.jpg')),
distance: 5,
type: 'Tutor'
},
{
first_name: "Barbra",
last_name: "Streisand",
email: "bstreisand@gmail.com",
password: "pass2013",
activated: true, activated_at: Time.now, confirmation_token: nil,
confirmed_at: Time.now,
confirmation_sent_at: Time.now, address: "Athinon 134-138, Kalamata 241 00, Greece",
latitude: 37.04149882349846,
longitude: 22.098383155419924,
gmaps: true, postal_code: "241 00",
country: "Greece", locality: "Kalamata",
administrative_area_level_2: "Peloponnese",
administrative_area_level_1: "Peloponnisos Dytiki Ellada ke Ionio", location_type: "",
phone: "1234567820",
avatar: File.open(File.join(Rails.root, 'avatars','streisand.jpg')),
distance: 15,
type: 'Tutor'
},
{
first_name: "Monica",
last_name: "Bellucci",
email: "mbellucci@gmail.com",
password: "pass2013",
activated: true, activated_at: Time.now, confirmation_token: nil,
confirmed_at: Time.now,
confirmation_sent_at: Time.now, address: "Georgiou Ventiri 13-17, Kalamata 241 00, Greece",
latitude: 37.024412218767715,
longitude: 22.13320895726929,
gmaps: true, postal_code: "241 00",
country: "Greece", locality: "Kalamata",
administrative_area_level_2: "Peloponnese",
administrative_area_level_1: "Peloponnisos Dytiki Ellada ke Ionio", location_type: "",
phone: "1234567821",
avatar: File.open(File.join(Rails.root, 'avatars','bellucci.jpg')),
distance: 10,
type: 'Tutor'
},
{
first_name: "Sophie",
last_name: "Marceau",
email: "smarceau@gmail.com",
password: "pass2013",
activated: true, activated_at: Time.now, confirmation_token: nil,
confirmed_at: Time.now,
confirmation_sent_at: Time.now, address: "Dioskouron 22-32, Sparti 231 00, Greece",
latitude: 37.0765554,
longitude: 22.430808800000023,
gmaps: true, postal_code: "231 00",
country: "Greece", locality: "Sparti",
administrative_area_level_2: "Peloponnese",
administrative_area_level_1: "Peloponnisos Dytiki Ellada ke Ionio", location_type: "",
phone: "1234567822",
avatar: File.open(File.join(Rails.root, 'avatars','marceau.jpg')),
distance: 5,
type: 'Tutor'
},
{
first_name: "Catherine",
last_name: "Zeta-Jones",
email: "czeta-jones@gmail.com",
password: "pass2013",
activated: true, activated_at: Time.now, confirmation_token: nil,
confirmed_at: Time.now,
confirmation_sent_at: Time.now, address: "Plateon, Sparti 231 00, Greece",
latitude: 37.06957028586847,
longitude: 22.43909146143801,
gmaps: true, postal_code: "231 00",
country: "Greece", locality: "Sparti",
administrative_area_level_2: "Peloponnese",
administrative_area_level_1: "Peloponnisos Dytiki Ellada ke Ionio", location_type: "",
phone: "1234567823",
avatar: File.open(File.join(Rails.root, 'avatars','zeta-jones.jpg')),
distance: 10,
type: 'Tutor'
},
{
first_name: "Ray",
last_name: "Liotta",
email: "rliotta@gmail.com",
password: "pass2013",
activated: true, activated_at: Time.now, confirmation_token: nil,
confirmed_at: Time.now,
confirmation_sent_at: Time.now, address: "Agisilaou 11, Sparti 231 00, Greece",
latitude: 37.0692708,
longitude: 22.42945880000002,
gmaps: true, postal_code: "231 00",
country: "Greece", locality: "Sparti",
administrative_area_level_2: "Peloponnese",
administrative_area_level_1: "Peloponnisos Dytiki Ellada ke Ionio", location_type: "",
phone: "1234567824",
avatar: File.open(File.join(Rails.root, 'avatars','liotta.jpg')),
distance: 15,
type: 'Tutor'
},
{
first_name: "George",
last_name: "Clooney",
email: "gclooney@gmail.com",
password: "pass2013",
activated: true, activated_at: Time.now, confirmation_token: nil,
confirmed_at: Time.now,
confirmation_sent_at: Time.now, address: "Ananiou 1-5, Sparti 231 00, Greece",
latitude: 37.0738569,
longitude: 22.42492919999995,
gmaps: true, postal_code: "231 00",
country: "Greece", locality: "Sparti",
administrative_area_level_2: "Peloponnese",
administrative_area_level_1: "Peloponnisos Dytiki Ellada ke Ionio", location_type: "",
phone: "1234567825",
avatar: File.open(File.join(Rails.root, 'avatars','clooney.jpg')),
distance: 10,
type: 'Tutor'
}
])
|
class AddWorkerIdToOtherStudy < ActiveRecord::Migration
def change
unless column_exists? :worker_center_of_studies, :worker_id
add_column :worker_center_of_studies, :worker_id, :integer
end
end
end
|
class UserProgress < ActiveRecord::Base
belongs_to :step
belongs_to :student
belongs_to :lesson
after_create {
self.unique_hash = SecureRandom.base64(16)
until self.save
self.unique_hash = SecureRandom.base64(16)
end
}
def to_param
unique_hash
end
end |
module AttrAbility
class Attributes
attr_reader :attributes
def initialize
@attributes = Hash.new([])
end
def add(attributes)
normalized = attributes.is_a?(AttrAbility::Attributes) ? attributes.attributes : normalize(attributes)
normalized.each do |attribute, values|
if @attributes[attribute] != true
if values == true
@attributes[attribute] = true
else
@attributes[attribute] = (@attributes[attribute] + values).uniq
end
end
end
end
def allow?(attribute, value)
@attributes[attribute.to_s] == true || @attributes[attribute.to_s].include?(value.to_s)
end
private
def normalize(attributes)
Hash[
attributes.map do |attribute_or_hash|
if attribute_or_hash.is_a?(Hash)
attribute_or_hash.map do |attribute, values|
[attribute.to_s, Array(values).map(&:to_s)]
end
else
[[attribute_or_hash.to_s, true]]
end
end.flatten(1)
]
end
end
end |
require 'integration_test_helper'
class PersonTest < ActionDispatch::IntegrationTest
test "can see the welcome page" do
get "/"
assert_select "h1", "Pessoas de Interesse"
end
test "can create a person" do
get "/persones/new"
assert_response :success
post "/persones",
params: { person: {name: "Pedro",birthdate: "1978-10-20",email: 'pedro@gmail.com',twitter: 'pedro',
phone_number: '15-998764530',profession: "Engenheiro",career_id: careeres(:career1).id,
pais_id: paises(:brasil).id} }
assert_response :redirect
follow_redirect!
assert_response :success
assert_select "td", "Pedro"
end
test "can edit a person" do
get "/persones/edit/1"
assert_response :success
post "/persones",
params: { person: {name: "Pedro",birthdate: "1978-10-20",email: 'pedro@gmail.com',twitter: 'pedro',
phone_number: '15-998764530',profession: "Engenheiro",career_id: careeres(:career1).id,
pais_id: paises(:brasil).id} }
assert_response :redirect
follow_redirect!
assert_response :success
assert_select "td", "Pedro"
end
end
|
# frozen-string-literal: true
require "test_helper"
class EncryptedParametersTest < MiniTest::Unit::TestCase
def test_missing_encrypted_params
controller = MockController.new({})
assert_equal({}, controller.encrypted_params)
end
def test_invalid_encrypted_params
controller = MockController.new("_encrypted" => { "key" => "value" })
assert_raises ActiveSupport::MessageVerifier::InvalidSignature do
controller.encrypted_params
end
end
def test_properly_encrypted_params
value = EncryptedFormFields.encrypt_and_sign("value")
controller = MockController.new("_encrypted" => { "key" => value })
assert_equal({ "key" => "value" }, controller.encrypted_params)
controller = MockController.new("_encrypted" => { "key" => [value] })
assert_equal({ "key" => ["value"] }, controller.encrypted_params)
controller = MockController.new("_encrypted" => { "key" => { "nested" => value } })
assert_equal({ "key" => { "nested" => "value" } }, controller.encrypted_params)
end
end
|
class UsersController < ApplicationController
before_filter :require_self_or_admin, :except=>[:ldap_search]
before_filter :scrape_params
PER_PAGE = 20
PAGE = 1
##
# GET /users/1
# GET /users/1.json
def show
@user = User.includes(:user_default_emails).find(params[:id])
#prepare_contacts
respond_to do |format|
format.html # index.html.erb
format.json {render :json => @user }
end
end
##
# Search LDAP server for user information
# Custom route
# POST /ldap_search
# POST /ldap_search.json
def ldap_search
scanner = LdapQuery::Scanner.search params[:q]
@ude = scanner.as_ude_attributes
@ude[:errors] = scanner.errors
respond_to do |format|
format.json {render :json => @ude }
end
end
##
# Update user information
# PUT /users/1
# PUT /users/1.json
def update
@user = User.find(params[:id])
if params[:user].has_key?(:is_admin) && current_user.is_admin
@user.is_admin = params[:user][:is_admin]
end
@user.assign_attributes(params[:user])
did_save = @user.save
if @user.fix_ude_approval_order_gaps?
flash[:alert] = 'There were gaps in the approval order that have been automatically corrected'
end
respond_to do |format|
if did_save
prepare_contacts
flash[:notice] = 'Changes have been saved'
format.html { render :action=>:show }
format.json { head :ok }
else
prepare_contacts
format.html { render :action=>:show }
format.json { render :json => @user.errors, :status => :unprocessable_entity }
end
end
end
protected
# create upto the maximum number of contacts allowed
def prepare_contacts
return unless defined? @user
@user.user_default_emails.sort_by{|a| a.role_id.to_i}
end
# Remove empty ude's if they are missing email and id
def scrape_params
return unless params[:user] && params[:user][:user_default_emails_attributes]
params[:user][:user_default_emails_attributes].each { |idx,attrs|
elem = params[:user][:user_default_emails_attributes]
elem.delete(idx) unless attrs[:email].to_s.size > 0 || attrs[:id].to_s.size > 0
}
end
protected
def require_self_or_admin
if not ( current_user.is_admin or current_user.id == params[:id].to_i)
flash[:alert] = "Access Denied"
redirect_to current_user
return
end
end
end
|
require 'spec_helper'
describe Artwork do
it "has a valid factory" do
FactoryGirl.create(:artwork, :with_home_image).should be_valid
end
it "is invalid without a title" do
@artwork = FactoryGirl.create(:artwork, :with_home_image)
@artwork.title = nil
@artwork.should_not be_valid
end
it "is invalid without a series" do
Artwork.create(
:title => Faker::Name.name,
:series_id => nil,
:image => File.new(Rails.root + 'spec/support/images/rails.png')
).should_not be_valid
end
it "is invalid without an image" do
@artwork = FactoryGirl.create(:artwork)
@artwork.image.destroy
@artwork.should_not be_valid
end
it "is invalid without a thumbnail" do
@artwork = FactoryGirl.create(:artwork)
@artwork.thumbnail.destroy
@artwork.should_not be_valid
end
it "should not have more than one home image" do
artwork1 = FactoryGirl.create(:artwork, :with_home_image)
artwork2 = FactoryGirl.create(:artwork).should be_valid
artwork3 = FactoryGirl.create(:artwork, :with_home_image).should_not be_valid
end
end
|
#
# Cookbook Name:: build
# Recipe:: provision_clean_aws
#
# Copyright (c) 2015 The Authors, All Rights Reserved.
delivery_secrets = get_project_secrets
cluster_name = "#{node['delivery']['change']['stage']}_#{node['delivery']['change']['pipeline']}"
path = node['delivery']['workspace']['repo']
cache = node['delivery']['workspace']['cache']
ssh_private_key_path = File.join(cache, '.ssh', "chef-delivery-cluster")
ssh_public_key_path = File.join(cache, '.ssh', "chef-delivery-cluster.pub")
directory File.join(cache, '.ssh')
directory File.join(cache, '.aws')
directory File.join(path, 'environments')
file ssh_private_key_path do
content delivery_secrets['private_key']
owner node['delivery_builder']['build_user']
group node['delivery_builder']['build_user']
mode '0600'
end
file ssh_public_key_path do
content delivery_secrets['public_key']
owner node['delivery_builder']['build_user']
group node['delivery_builder']['build_user']
mode '0644'
end
template "Create Environment Template" do
path File.join(path, "environments/#{cluster_name}.json")
source 'environment.json.erb'
variables(
:delivery_license => "#{cache}/delivery.license",
:delivery_version => "latest",
:cluster_name => cluster_name
)
end
template File.join(cache, '.aws/config') do
source 'aws-config.erb'
variables(
:aws_access_key_id => delivery_secrets['access_key_id'],
:aws_secret_access_key => delivery_secrets['secret_access_key'],
:region => delivery_secrets['region']
)
end
s3_file File.join(cache, 'delivery.license') do
remote_path "licenses/delivery-internal.license"
bucket "delivery-packages"
aws_access_key_id delivery_secrets['access_key_id']
aws_secret_access_key delivery_secrets['secret_access_key']
action :create
end
# Assemble your gem dependencies
execute "chef exec bundle install" do
cwd path
end
# Assemble your cookbook dependencies
execute "chef exec bundle exec berks vendor cookbooks" do
cwd path
end
# Destroy the old Delivery Cluster
#
# We are using a temporal cache directory to save the state of our cluster.
# HERE: we are moving the data back to the repository path before we trigger
# the destroy task
#
# TODO: We need to figure a better way to do this
execute "Destroy the old Delivery Cluster" do
cwd path
command <<-EOF
mv /var/opt/delivery/workspace/delivery-cluster-aws-cache/clients clients
mv /var/opt/delivery/workspace/delivery-cluster-aws-cache/nodes nodes
mv /var/opt/delivery/workspace/delivery-cluster-aws-cache/trusted_certs .chef/.
mv /var/opt/delivery/workspace/delivery-cluster-aws-cache/delivery-cluster-data-* .chef/.
chef exec bundle exec chef-client -z -o delivery-cluster::destroy_all -E #{cluster_name} > #{cache}/delivery-cluster-destroy-all.log
EOF
environment ({
'AWS_CONFIG_FILE' => "#{cache}/.aws/config"
})
only_if do ::File.exists?('var/opt/delivery/workspace/delivery-cluster-aws-cache/nodes') end
end
# Create a new Delivery Cluster
#
# We are using a temporal cache directory to save the state of our cluster
# HERE: we are copying the data after we create the Delivery Cluster
#
# TODO: We need to figure a better way to do this
execute "Create a new Delivery Cluster" do
cwd path
command <<-EOF
chef exec bundle exec chef-client -z -o delivery-cluster::setup -E #{cluster_name} -l auto > #{cache}/delivery-cluster-setup.log
cp -r clients nodes .chef/delivery-cluster-data-* .chef/trusted_certs /var/opt/delivery/workspace/delivery-cluster-aws-cache/
EOF
environment ({
'AWS_CONFIG_FILE' => "#{cache}/.aws/config"
})
end
# Print the Delivery Credentials
ruby_block 'print-delivery-credentials' do
block do
puts File.read(File.join(path, ".chef/delivery-cluster-data-#{cluster_name}/#{cluster_name}.creds"))
end
end
ruby_block "Get Services" do
block do
list_services = Mixlib::ShellOut.new("rake info:list_core_services",
:cwd => node['delivery']['workspace']['repo'])
list_services.run_command
if list_services.stdout
node.run_state['delivery'] ||= {}
node.run_state['delivery']['stage'] ||= {}
node.run_state['delivery']['stage']['data'] ||= {}
node.run_state['delivery']['stage']['data']['cluster_details'] ||= {}
previous_line = nil
list_services.stdout.each_line do |line|
if previous_line =~ /^delivery-server\S+:$/
ipaddress = line.match(/^ ipaddress: (\S+)$/)[1]
node.run_state['delivery']['stage']['data']['cluster_details']['delivery'] ||= {}
node.run_state['delivery']['stage']['data']['cluster_details']['delivery']['url'] = ipaddress
elsif previous_line =~ /^build-node\S+:/
ipaddress = line.match(/^ ipaddress: (\S+)$/)[1]
node.run_state['delivery']['stage']['data']['cluster_details']['build_nodes'] ||= []
node.run_state['delivery']['stage']['data']['cluster_details']['build_nodes'] << ipaddress
elsif line =~ /^chef_server_url.*$/
ipaddress = URI(line.match(/^chef_server_url\s+'(\S+)'$/)[1]).host
node.run_state['delivery']['stage']['data']['cluster_details']['chef_server'] ||= {}
node.run_state['delivery']['stage']['data']['cluster_details']['chef_server']['url'] = ipaddress
end
previous_line = line
end
## Note: There is a temporal issue here where a new artifact could be promoted
## between provsioning and this call. We also need to unwind the addition of '-1'
## tot he version number we do in this helper function. Ahrg!!! Artifactory.
delivery_version = ::DeliverySugarExtras::Helpers.get_delivery_versions(node)[0]
node.run_state['delivery']['stage']['data']['cluster_details']['delivery']['version'] = delivery_version[0,delivery_version.index('-', -2)]
end
end
end
delivery_stage_db
|
require 'rails_helper'
RSpec.describe Match, type: :model do
describe 'relationships' do
it { should have_many(:match_answers) }
it { should have_many(:match_questions) }
it { should have_many(:questions).through(:match_questions) }
it { should have_many(:teams) }
end
describe '#add_question' do
let!(:match) { create(:match) }
let!(:question) { create(:question) }
it 'adds a question and applies a corresponding point value for that question' do
match.add_question(question: question, point_value: 30)
expect(match.questions).to include question
expect(match.match_questions.first.point_value).to eq 30
end
it 'without a point value specified, it will have a point value of 0' do
match.add_question(question: question)
expect(match.questions).to include question
expect(match.match_questions.first.point_value).to eq 0
end
end
describe '#set_point_value_for and #point_value_for' do
it 'works' do
match = create(:match)
question = build(:question)
match.add_question(question)
match.set_point_value_for(question: question, point_value: 5)
expect(match.point_value_for(question: question)).to eq 5
end
end
describe '#total_point_value_for_team' do
it 'works' do
match = create(:match)
question1 = create(:question, :with_answers)
question2 = create(:question, :with_answers)
question3 = create(:question, :with_answers)
match.add_question(question: question1, point_value: 5)
match.add_question(question: question2, point_value: 20)
match.add_question(question: question3, point_value: 30)
team1 = create(:team, match: match)
team2 = create(:team, match: match)
match.match_answers.create(
team: team1,
match_question: match.match_question_for(question: question1),
is_correct: true
)
match.match_answers.create!(
team: team1,
match_question: match.match_question_for(question: question2),
is_correct: true
)
match.match_answers.create!(
team: team1,
match_question: match.match_question_for(question: question3),
is_correct: false
)
expect(match.total_point_value_for(team: team1)).to eq 25
expect(match.total_point_value_for(team: team2)).to eq 0
end
end
end
|
module Faceter
module Nodes
# The node describes wrapping hash values into nested tuple
#
# @api private
#
class Wrap < AbstractMapper::AST::Node
attribute :key
attribute :selector
# Transformer function, defined by the node
#
# @return [Transproc::Function]
#
def transproc
Functions[:wrap, key, selector]
end
end # class Wrap
end # module Nodes
end # module Faceter
|
When /^I order (\d+) "([^"]*)"/ do |qty, item|
@items ||= []
@items << [qty, item]
end
Then /^I should see a packing slip:/ do |slip|
input =
@items.map do |pair|
'%s;%s' % pair
end.join("\n")
create_file("input.txt", input)
run "ruby ../../runner.rb"
regexp = Regexp.escape(slip)
combined_output.chomp.should match(/#{regexp}/m)
end
When /^I order a copy of "([^"]*)"$/ do |book|
@items ||= []
@items << [1, book]
end
Then /^the packing slip should be sent to the royalty department$/ do
combined_output.should =~ /A copy of the packing slip was sent to the royalty department/
end
When /^I purchase a membership$/ do
@items ||= []
@items << [1, "Membership"]
end
Then /^my membership should be activated$/ do
combined_output.should =~ /Your membership has been activated/
end
When /^I upgrade my membership$/ do
@items ||= []
@items << [1, "Upgrade Member"]
end
Then /^my membership should be upgraded$/ do
combined_output.should =~ /Your membership has been upgraded/
end
Then /^the sales agent should receive a commission payment$/ do
combined_output.should =~ /The sales agent has received a commission payment/
end
|
class AddingRestOfHandles < ActiveRecord::Migration[5.1]
def change
add_column :trainees, :spoj_handle, :string
add_column :trainees, :timus_handle, :string
add_column :trainees, :uri_handle, :string
add_column :trainees, :codechef_handle, :string
end
end
|
require 'spec_helper'
describe SessionsController do
describe 'GET new' do
it 'redirects to the home page for authenticated users' do
set_current_user
get :new
expect(response).to redirect_to home_path
end
end
describe 'POST create' do
context 'with valid credentials' do
let(:bob) { Fabricate(:user, password: 'password') }
before { post :create, email: bob.email, password: bob.password }
it 'sets the user to the session' do
expect(session[:user_id]).to eq(bob.id)
end
it 'redirects to the home page' do
expect(response).to redirect_to home_path
end
end
context 'without valid credentials' do
before { post :create }
it 'does not put the signed in user in the session' do
expect(session[:user_id]).to be_nil
end
it_behaves_like "require_sign_in" do
let(:action) { nil }
end
it 'sets the flash message' do
expect(flash[:danger]).to be_present
end
end
end
describe 'GET destroy' do
before do
set_current_user
get :destroy
end
it 'clears the session for the user' do
expect(session[:user_id]).to be_nil
end
it 'sets the flash message' do
expect(flash['success']).not_to be_blank
end
it 'redirects to the front page' do
expect(response).to redirect_to root_path
end
end
end
|
class NetworksController < ApplicationController
before_action :logged_in_user
before_action :admin_user
def index
@networks = Network.order(name: :asc)
end
def new
@network = Network.new
end
def create
@network = Network.new(network_params)
if @network.save
flash[:success] = "Network added."
redirect_to networks_url
else
render 'new'
end
end
def edit
@network = Network.find_by_id(params[:id])
end
def update
@network = Network.find_by_id(params[:id])
if @network.update_attributes(network_params)
flash[:success] = "Network updated."
redirect_to networks_url
else
render 'edit'
end
end
def destroy
Network.find_by_id(params[:id]).destroy
flash[:success] = "Network deleted"
redirect_to networks_url
end
private
def network_params
params.require(:network).permit(:name, :cidr)
end
# Confirms a logged-in user.
def logged_in_user
unless logged_in?
store_location
redirect_to root_url
end
end
# Confirms an admin user.
def admin_user
redirect_to(root_url) unless current_user.admin?
end
end
|
class PlayersDecorator < SimpleDelegator
def all_data
joins(:position).joins(:team).pluck_to_hash(
:id,
:first_name,
:last_name,
:code,
:news,
:chance_of_playing_this_round,
:chance_of_playing_next_round,
:in_dreamteam,
:status,
:form,
:minutes,
:goals_scored,
:assists,
:clean_sheets,
:goals_conceded,
:own_goals,
:penalties_saved,
:penalties_missed,
:yellow_cards,
:red_cards,
:saves,
:bonus,
:influence,
:creativity,
:threat,
:ict_index,
:position_id,
:team_id,
:open_play_crosses,
:big_chances_created,
:clearances_blocks_interceptions,
:recoveries,
:key_passes,
:tackles,
:winning_goals,
:dribbles,
:fouls,
:errors_leading_to_goal,
:offside,
:target_missed,
:points_per_game,
:event_points,
:total_points,
:singular_name_short,
:short_name,
:name
)
end
end
|
class Usuario < ApplicationRecord
belongs_to :genero
validates :nome, :idade, :genero_id, :cpf, presence:true
validates :cpf, uniqueness:true
s
validates_length_of :cpf, is: 14
validates_numericality_of :idade, minimum: 18, maximum: 115
end
|
class Service
generator_for :name, :start => 'Service 000001'
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
# User.create(email: "testing@gmail.com", username: 'TestUser', password: 'password')
# Universe.create(name: "Alorramola", description: 'Has magical properties', user_id: 1)
# Universe.create(name: "Techdevia", description: 'Sci-fi Universe', user_id: 1)
# Character.create(name: "Jane Hutton", user_id: 1)
# Character.create(name: "Hiro Smith", user_id: 1)
# Character.create(name: "Marie Alex", user_id: 1)
# Character.create(name: "Roxanne Mecure", user_id: 1)
# Character.create(name: "Debra", user_id: 1)
# Character.create(name: "Fiona", user_id: 1)
# Character.create(name: "Christy", user_id: 1)
# Character.create(name: "Luanne", user_id: 1)
# Character.create(name: "Lulu", user_id: 1)
# Character.create(name: "Samantha", user_id: 1)
# Character.create(name: "Gillian", user_id: 1)
# Character.create(name: "Minerva", user_id: 1)
# Character.create(name: "Drake", user_id: 1)
# Character.create(name: "Richard", user_id: 1)
# Character.create(name: "Alvin", user_id: 1)
# Character.create(name: "Sarah", user_id: 1)
# Character.create(name: "Savannah", user_id: 1)
# Character.create(name: "Sabrina", user_id: 1)
# Relationship.create(character_id: 1, character2: 2, affiliation: "Cousin", user_id: 1)
# Relationship.create(character_id: 1, character2: 4, affiliation: "Friend", user_id: 1)
# Relationship.create(character_id: 2, character2: 3, affiliation: "Friend", user_id: 1)
# Relationship.create(character_id: 2, character2: 5, affiliation: "Couple", user_id: 1)
# Relationship.create(character_id: 3, character2: 4, affiliation: "Friend", user_id: 1)
# Relationship.create(character_id: 3, character2: 5, affiliation: "Friend", user_id: 1)
# Relationship.create(character_id: 4, character2: 6, affiliation: "Friend", user_id: 1)
# Relationship.create(character_id: 4, character2: 7, affiliation: "Friend", user_id: 1)
# Relationship.create(character_id: 4, character2: 8, affiliation: "Friend", user_id: 1)
# Relationship.create(character_id: 4, character2: 9, affiliation: "Friend", user_id: 1)
# Relationship.create(character_id: 6, character2: 7, affiliation: "Friend", user_id: 1)
# Relationship.create(character_id: 6, character2: 8, affiliation: "Friend", user_id: 1)
# Relationship.create(character_id: 6, character2: 9, affiliation: "Friend", user_id: 1)
# Relationship.create(character_id: 7, character2: 8, affiliation: "Friend", user_id: 1)
# Relationship.create(character_id: 7, character2: 9, affiliation: "Friend", user_id: 1)
# Relationship.create(character_id: 8, character2: 9, affiliation: "Friend", user_id: 1)
# Relationship.create(character_id: 10, character2: 11, affiliation: "Couple", user_id: 1)
# Relationship.create(character_id: 10, character2: 16, affiliation: "Mother", user_id: 1)
# Relationship.create(character_id: 10, character2: 17, affiliation: "Mother", user_id: 1)
# Relationship.create(character_id: 10, character2: 18, affiliation: "Mother", user_id: 1)
# Relationship.create(character_id: 11, character2: 16, affiliation: "Father", user_id: 1)
# Relationship.create(character_id: 11, character2: 17, affiliation: "Father", user_id: 1)
# Relationship.create(character_id: 11, character2: 18, affiliation: "Father", user_id: 1)
# Relationship.create(character_id: 10, character2: 13, affiliation: "Friend", user_id: 1)
# Relationship.create(character_id: 11, character2: 13, affiliation: "Friend", user_id: 1)
# Relationship.create(character_id: 13, character2: 14, affiliation: "Business Partner", user_id: 1)
# Relationship.create(character_id: 10, character2: 12, affiliation: "Friends", user_id: 1)
# Relationship.create(character_id: 2, character2: 12, affiliation: "Senior", user_id: 1)
# Relationship.create(character_id: 3, character2: 12, affiliation: "Senior", user_id: 1)
# Relationship.create(character_id: 5, character2: 12, affiliation: "Senior", user_id: 1)
# Relationship.create(character_id: 14, character2: 16, affiliation: "Couple", user_id: 1)
# Relationship.create(character_id: 15, character2: 17, affiliation: "Couple", user_id: 1)
# CharactersStory.create(character_id: 1, story_id: 1, importance: 1, notes: "Not important")
# CharactersStory.create(character_id: 1, story_id: 2, importance: 1, notes: "Not important")
# CharactersStory.create(character_id: 2, story_id: 2, importance: 5, notes: "Very important")
# CharactersStory.create(character_id: 3, story_id: 1, importance: 2, notes: "A little important")
# CharactersStory.create(character_id: 3, story_id: 2, importance: 5, notes: "Very important")
# CharactersStory.create(character_id: 4, story_id: 1, importance: 5, notes: "Very little important")
# CharactersStory.create(character_id: 4, story_id: 2, importance: 2, notes: "A little important")
# CharactersStory.create(character_id: 5, story_id: 2, importance: 5, notes: "Very important")
# Story.create(name: "The Lorems", universe_id: 1, genre_id: 3, summary: "Funny Romance story about a group of kids",user_id: 1)
# Story.create(name: "Bananas", universe_id: 1, genre_id: 4, summary: "A mind-controlling virus called Banana is spreading across the world",user_id: 1)
# Story.create(name: "General Assembly", universe_id: 1, genre_id: 1, summary: "An alternative world where Coders conquered the world and everyone is enlisted to code",user_id: 1)
# Quality.create(quality: 'Hair', value: 'Black', character_id: 1)
# Quality.create(quality: 'Hair', value: 'Brown', character_id: 2)
# Quality.create(quality: 'Hair', value: 'Black', character_id: 3)
# Quality.create(quality: 'Height', value: 'Tall', character_id: 1)
Genre.create(name: "Sci-fi")
Genre.create(name: "Comedy")
Genre.create(name: "Romance")
Genre.create(name: "Fantasy")
# Genre.create(name: "Horror") |
class CreateSmallGoals < ActiveRecord::Migration
def change
create_table :small_goals do |t|
t.string :title
t.date :due
t.integer :public_range
t.boolean :favorite
t.timestamps null: false
end
end
end
|
# frozen_string_literal: true
module MiniSql
module Oracle
class PreparedConnection < Connection
attr_reader :unprepared
def initialize(unprepared_connection)
@unprepared = unprepared_connection
@raw_connection = unprepared_connection.raw_connection
@param_encoder = unprepared_connection.param_encoder
@prepared_cache = PreparedCache.new(@raw_connection)
@param_binder = PreparedBinds.new
end
def build(_)
raise 'Builder can not be called on prepared connections, instead of `::MINI_SQL.prepared.build(sql).query` use `::MINI_SQL.build(sql).prepared.query`'
end
def prepared(condition = true)
condition ? self : @unprepared
end
def deserializer_cache
@unprepared.deserializer_cache
end
private def run(sql, params)
if params && params.length > 0
sql = param_encoder.encode(sql, *params)
end
cursor = raw_connection.parse(sql)
res = cursor.exec
if block_given?
yield cursor
else
res
end
ensure
cursor.close if cursor
end
end
end
end |
# app/hyperstack/components/footer.rb
class Footer < HyperComponent
include Hyperstack::Router::Helpers
render do
return if Todo.count == 0
FOOTER(class: :footer) do
SPAN(class: 'todo-count') { "#{pluralize(Todo.active.count, 'item')} left" }
UL(class: :filters) do
link_item(:all)
link_item(:active)
link_item(:completed)
end
if Todo.completed.count > 0
BUTTON(class: 'clear-completed') { 'Clear completed' }
.on(:click) { Todo.completed.each(&:destroy) }
end
end
end
def link_item(path)
LI { NavLink("/#{path}", active_class: :selected) { path.camelize } }
end
end
|
class Audio < ActiveRecord::Base
belongs_to :user
belongs_to :album, :counter_cache => true
has_many :article_audios
has_many :articles, :through => :article_audios
define_index do
indexes :name, :sortable => true
indexes data_file_name
end
has_attached_file :data,
:url => "/assets/audios/:id/:style/:basename.:extension",
:path => ":rails_root/public/assets/audios/:id/:style/:basename.:extension"
end
|
class ProductNamesProductTag < ActiveRecord::Base
belongs_to :product_name
belongs_to :product_tag
end |
module Types
class RentalType < Types::BaseObject
name 'Rental'
field :id, !types.ID
field :rental_type, !types.String
field :accomodates, !types.Int
field :posta_code, types.String
field :owner, Tupes::UserType do
resolve -> (obj, args, ctx) { obj.user }
end
field :bookings, !types[Types::BookingType]
end
end
|
require 'rails_helper'
describe 'when user visits index page' do
it 'shows list of all trip names' do
trip = Trip.create(name: 'Pigeon')
visit trips_path
expect(page).to have_content(trip.name)
end
it 'can click single trip to see show page' do
trip1 = Trip.create(name: 'Pigeon')
trip2 = Trip.create(name: 'Hawk')
visit trips_path
click_link "#{trip1.name}"
expect(current_path).to eq(trip_path(trip1))
expect(page).to have_content(trip1.name)
expect(page).to_not have_content(trip2.name)
end
end
|
require './test/helper'
class UriProxyTest < Test::Unit::TestCase
context "a new instance" do
setup do
@open_return = StringIO.new("xxx")
@open_return.stubs(:content_type).returns("image/png")
Paperclip::UriAdapter.any_instance.stubs(:download_content).returns(@open_return)
@uri = URI.parse("http://thoughtbot.com/images/thoughtbot-logo.png")
@subject = Paperclip.io_adapters.for(@uri)
end
should "return a file name" do
assert_equal "thoughtbot-logo.png", @subject.original_filename
end
should 'close open handle after reading' do
assert_equal true, @open_return.closed?
end
should "return a content type" do
assert_equal "image/png", @subject.content_type
end
should "return the size of the data" do
assert_equal @open_return.size, @subject.size
end
should "generate an MD5 hash of the contents" do
assert_equal Digest::MD5.hexdigest("xxx"), @subject.fingerprint
end
should "generate correct fingerprint after read" do
fingerprint = Digest::MD5.hexdigest(@subject.read)
assert_equal fingerprint, @subject.fingerprint
end
should "generate same fingerprint" do
assert_equal @subject.fingerprint, @subject.fingerprint
end
should "return the data contained in the StringIO" do
assert_equal "xxx", @subject.read
end
should 'accept a content_type' do
@subject.content_type = 'image/png'
assert_equal 'image/png', @subject.content_type
end
should 'accept an orgiginal_filename' do
@subject.original_filename = 'image.png'
assert_equal 'image.png', @subject.original_filename
end
end
context "a directory index url" do
setup do
Paperclip::UriAdapter.any_instance.stubs(:download_content).returns(StringIO.new("xxx"))
@uri = URI.parse("http://thoughtbot.com")
@subject = Paperclip.io_adapters.for(@uri)
end
should "return a file name" do
assert_equal "index.html", @subject.original_filename
end
should "return a content type" do
assert_equal "text/html", @subject.content_type
end
end
context "a url with query params" do
setup do
Paperclip::UriAdapter.any_instance.stubs(:download_content).returns(StringIO.new("xxx"))
@uri = URI.parse("https://github.com/thoughtbot/paperclip?file=test")
@subject = Paperclip.io_adapters.for(@uri)
end
should "return a file name" do
assert_equal "paperclip", @subject.original_filename
end
end
end
|
# require 'rest-client'
require 'json'
require 'pry'
class CommandLineInterface
def welcome
puts "Welcome to the Pokemon API browser."
end
def get_pokemon_name_from_user
puts "Please enter a pokemon name"
gets.chomp.downcase
end
def give_stats_to_user(response)
api = ApiCommunicator.new
puts api.poke_info(response)
end
end
|
json.array!(@admin_computers) do |admin_computer|
json.extract! admin_computer, :id
json.url admin_computer_url(admin_computer, format: :json)
end
|
module PagesHelper
def calc_completeness
completeness = 0
if current_user.about_contents_complete?
completeness += 16.6
end
if current_user.business_details_complete?
completeness += 16.6
end
if current_user.integrations_complete?
completeness += 16.6
end
if current_user.services_contents_complete?
completeness += 16.6
end
if current_user.extra_pages_complete?
completeness += 16.6
end
if current_user.uploads_complete?
completeness += 16.6
end
return completeness
end
def is_complete?
calc_completeness().round == 100
end
def nearly_done_message
case calc_completeness().round
when 17
'One down! Only five to go. 😁'
when 33
'Look at you go - thats two complete! Keep it going. Only four more to go! 🤠'
when 50
'Halfway! 🎉 Nice work. It\'s the easy one\'s left, I swear. '
when 66
'Two thirds done now - you\'re at the final push! 💪'
when 83
'Second last one. You\'ve got this! 🤗'
when 100
'YOU DID IT! 👏👏 All done! Time to celebrate! Go grab a beer or something - you\'ve earned it!'
end
end
end
|
class GameTeams
attr_reader :game_id,
:team_id,
:hoa,
:result,
:settled_in,
:head_coach,
:goals,
:shots,
:tackles,
:pim,
:powerPlayOpportunities,
:powerPlayGoals,
:faceOffWinPercentage,
:giveaways,
:takeaways
def initialize(line)
@game_id = line.split(",")[0]
@team_id = line.split(",")[1]
@hoa = line.split(",")[2]
@result = line.split(",")[3]
@settled_in = line.split(",")[4]
@head_coach = line.split(",")[5]
@goals = line.split(",")[6].to_i
@shots = line.split(",")[7].to_i
@tackles = line.split(",")[8].to_i
@pim = line.split(",")[9].to_i
@powerPlayOpportunities = line.split(",")[10].to_i
@powerPlayGoals = line.split(",")[11].to_i
@faceOffWinPercentage = line.split(",")[12].to_f
@giveaways = line.split(",")[13].to_i
@takeaways = line.split(",")[14].to_i
end
end
|
#encoding: utf-8
require 'rest-client'
require 'nokogiri'
class LotteryApp
def initialize customer
@customer = customer
end
def get_lottery lottery
order_id = lottery.random_unique_id
user_id = lottery.phone
last_lottery = Lottery.last
inside_comm_key = last_lottery.comm_key if last_lottery
inside_comm_key ||= get_comm_key
connect_to_yipai user_id, order_id, inside_comm_key
begin
lottery_hash = @data[0]
lottery.update_attributes(game_type: lottery_hash['gameType'].to_i,
issue: lottery_hash['issue'].to_i,
seq_no: lottery_hash['seqNo'].to_i,
flowid: lottery_hash['flowid'],
amount: lottery_hash['amount'].to_i,
vote_type: lottery_hash['voteType'].to_i,
vote_nums: lottery_hash['voteNums'],
multi: lottery_hash['multi'].to_i,
comm_key: inside_comm_key)
return lottery
rescue Exception => e
lottery.destroy
p e.message
end
end
def update_mobile lottery, mobile
user_id = @customer.id.to_s
body = user_id + CHANNEL_CODE + mobile
comm_sign = encrypt body, inside_comm_key
url = BASE_URL + "updateMobile?id=#{CHANNEL_CODE}&userID=#{user_id}&mobile=#{mobile}&sign=#{comm_sign}"
Rails.logger.info url
resp = RestClient.get url
xml = Nokogiri::XML(resp)
message = JSON.parse xml.at_css('return').children[0].text
Rails.logger.info message
@error_code = message['errorCode']
@times ||= 0
@times += 1
update_mobile(lottery, mobile) if @error_code == '9007' && @times < 3
@datas = message['datas']
end
# 获取某一期的中奖记录列表
def get_award_info lottery
issue = lottery.issue
last_lottery = Lottery.last
inside_comm_key = last_lottery.comm_key if last_lottery
inside_comm_key = get_comm_key if inside_comm_key.blank? || @error_code == '9007'
body = issue.to_s + CHANNEL_CODE
comm_sign = encrypt body, inside_comm_key
url = BASE_URL + "getAwardInfo?id=#{CHANNEL_CODE}&issue=#{issue}&sign=#{comm_sign}"
Rails.logger.info url
resp = RestClient.get url
xml = Nokogiri::XML(resp)
@message = JSON.parse xml.at_css('return').children[0].text
Rails.logger.info @message
@error_code = @message['errorCode']
@times ||= 0
@times += 1
get_award_info(lottery) if @error_code == '9007' && @times < 3
@datas = @message['datas']
end
# 获取用户的彩票列表
# -1, 所有彩票
# 0, 待开奖
# 1, 未中奖
# 2, 已中奖
def get_lottery_records type, page = 1
page_size = 10
last_lottery = Lottery.last
inside_comm_key = last_lottery.comm_key if last_lottery
inside_comm_key = get_comm_key if inside_comm_key.blank? || @error_code == '9007'
phone = @customer.phone
phone ||= @customer.lotteries.first.phone
body = phone + CHANNEL_CODE + type.to_s + page.to_s + page_size.to_s
comm_sign = encrypt body, inside_comm_key
url = BASE_URL + "getLotteryListByUserID?id=#{CHANNEL_CODE}&userID=#{phone}&type=#{type}&page=#{page}&pageSize=#{page_size}&sign=#{comm_sign}"
Rails.logger.info url
resp = RestClient.get url
xml = Nokogiri::XML(resp)
@message = JSON.parse xml.at_css('return').children[0].text
Rails.logger.info @message
@error_code = @message['errorCode']
@times ||= 0
@times += 1
get_lottery_records(type) if @error_code == '9007' && @times < 3
@datas = @message['datas']
end
def get_account_info
end
private
def trans_key key
url = BASE_URL + "transSignKey?id=#{CHANNEL_CODE}&key=#{key}"
p url
resp = RestClient.get url
@xml = Nokogiri::XML(resp)
message = @xml.at_css('return').children[0].text
transed_key = JSON.parse(message)['key']
end
def get_secure_key sign
url = BASE_URL + "getSecuretKeyByID?id=#{CHANNEL_CODE}&sign=#{sign}"
p url
resp = RestClient.get url
@xml = Nokogiri::XML(resp)
message = @xml.at_css('return').children[0].text
transed_key = JSON.parse(message)['key']
end
def get_comm_key
trans_init_key = trans_key INIT_SECRET
sign = encrypt CHANNEL_CODE, trans_init_key
securet_key = get_secure_key sign
inside_key = decrypt securet_key, trans_init_key
trans_inside_key = trans_key inside_key
return trans_inside_key
end
def encrypt content, key
cipher = OpenSSL::Cipher::AES.new(128, :ECB)
cipher.encrypt
cipher.key = [key].pack 'H*'
encrypted = cipher.update(content) + cipher.final
return encrypted.unpack('H*')[0].upcase
end
def decrypt(encrypted, key)
decipher = OpenSSL::Cipher::AES.new(128, :ECB)
decipher.decrypt
decipher.padding = 1
decipher.key = [key].pack 'H*'
plain = decipher.update([encrypted].pack('H*')) + decipher.final
return plain
end
def connect_to_yipai user_id, order_id, inside_comm_key
amount = 20
num = 1
body = user_id.to_s + CHANNEL_CODE + order_id.to_s + amount.to_s + num.to_s;
comm_sign = encrypt body, inside_comm_key
url = BASE_URL + "getLottery?id=#{CHANNEL_CODE}&userID=#{user_id}&amount=#{amount}&num=#{num}&orderID=#{order_id}&sign=#{comm_sign}"
Rails.logger.info url
resp = RestClient.get url
xml = Nokogiri::XML(resp)
message = JSON.parse xml.at_css('return').children[0].text
Rails.logger.info message
@data = message['datas']
@error_code = message['errorCode']
@times ||= 0
@times += 1
connect_to_yipai(user_id, order_id, get_comm_key) if @error_code == '9007' && @times < 3
end
end |
# encoding: UTF-8
#
# Cookbook Name:: pacemaker
# library:: clihelper
#
# Copyright 2016, Target Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'shellwords'
#
# CLI Helper methods
#
module Clihelper
#
# Format an array of items for the commandline. Escape special shell chars
# and put equal sign between key and value
#
# @param [Array] parameters
# a hash of parameters
#
# @return [String]
# the formated string
#
def format_array(array_list)
array_str = ''
array_list.each do |value|
array_str << "#{value.shellescape} "
end
array_str.strip
end
#
# Format a hash of parameters for the commandline. Escape special shell chars
# and put equal sign between key and value
#
# @param [Hash] parameters
# a hash of parameters
#
# @return [String]
# the formated string
#
def format_param_hash(param_hash)
param_str = ''
param_hash.each do |key, value|
param_str << "#{key.shellescape}=#{value.shellescape} "
end
param_str.strip
end
#
# Format a hash of ops for the commandline. Escape special shell chars
# and put equal sign between key and value
#
# @param [Hash] parameters
# a hash of parameters
#
# @return [String]
# the formated string
#
def format_ops_hash(op_hash)
ops_str = ''
op_hash.each do |key, value|
ops_str << "op #{key} #{format_param_hash(value)} "
end
ops_str.strip
end
#
# Create an optional clause string for a command if the hash is not empty.
# Escape special shell chars and put equal sign between key and value
#
# @param [String] clause name
# name of the commands optional clause
#
# @param [Hash] parameters
# a hash of parameters
#
# @return [String]
# the formated string
#
def format_clause_hash(clause_name, clause_hash)
clause_str = ''
unless clause_hash == {}
clause_str = "#{clause_name} #{format_param_hash(clause_hash)} "
end
clause_str.strip
end
end
|
# encoding: UTF-8
require 'logger'
#ログ出力
log = Logger.new('./output/log.txt')
log.debug('debug_') #デバッグ
log.info('info_') #インフォメーション
log.warn('warn_') #注意
log.error('error') #エラー
log.fatal('fatal') #致命的
log.unknown('unknown') #謎
log.level=Logger::INFO #ログレベルの設定
log.level=Logger::FATAL
|
class PostsController < ApplicationController
def index
find_category_by_slug
find_posts_by_category_and_paginate
end
def show
@post = Post.find_by(slug: params[:id])
end
private
def find_category_by_slug
@category = Category.find_by(slug: params[:category_id])
end
def find_posts_by_category_and_paginate
@posts = Post.where(category: @category).paginate(page: params[:page], per_page: 10)
end
end |
module Rack
class MogileFS
class Endpoint
# Adds ability to pass in a custom mapper to map PATH_INFO to a
# MogileFS key. By default it is assumed that the path is the same as
# the key. For example your keys will look like this:
#
# "/assets/images/myimage.gif"
#
# Create a custom mapper like this:
#
# Rack::MogileFS::Endpoint.new(
# :mapper => lambda { |path| "/namespace/" + path }
# )
module Mapper
def key_for_path(path)
@options[:mapper].respond_to?(:call) ?
@options[:mapper].call(path) : super
end
end
end
end
end
|
#!/Users/spamram/.rvm/rubies/ruby-1.9.2-p180/bin/ruby
# Goal:
# Find the sum of all the multiples of 3 or 5 below 1000.
sum = 0
1.upto(999) {|n| sum += n if (n % 3 == 0 || n % 5 == 0)}
puts sum |
Foliate.config.tap do |config|
config.default_per_page = 10
config.page_param = :page
end
|
class ApplicationController < ActionController::Base
private
def not_authenticated
redirect_to login_path
end
end
|
module Users
module EmailConfirmationService
include BaseService
def send_email(user, flash)
user.generate_confirmation_token
UserMailer.confirmation(user).deliver
flash[:notice] = "Sent confirmation email to #{user.email}. " \
'Please check your spam folder if the email has not reached your inbox.'
end
end
end
|
module Reports
class DrugStockCalculation
include Memery
def initialize(state:, protocol_drugs:, drug_category:, current_drug_stocks:, previous_drug_stocks: DrugStock.none, patient_count: nil)
@protocol_drugs = protocol_drugs
@drug_category = drug_category
@current_drug_stocks = current_drug_stocks
@previous_drug_stocks = previous_drug_stocks
@patient_count = patient_count
@coefficients = patient_days_coefficients(state)
end
def protocol_drugs_by_category
@protocol_drugs_by_category ||= @protocol_drugs.group_by(&:drug_category)
end
def patient_days
return nil if stocks_on_hand.empty?
{stocks_on_hand: stocks_on_hand,
patient_count: @patient_count,
load_coefficient: @coefficients[:load_coefficient],
new_patient_coefficient: new_patient_coefficient,
estimated_patients: estimated_patients,
patient_days: patient_days_calculation}
rescue => e
# drug is not in formula, or other configuration error
error_info = {
coefficients: @coefficients,
drug_category: @drug_category,
in_stock_by_rxnorm_code: in_stock_by_rxnorm_code,
patient_count: @patient_count,
protocol: @protocol,
exception: e
}
trace("patient_days", "Reports::DrugStockCalculation#patient_days", error_info)
{patient_days: "error"}
end
def consumption
protocol_drugs = protocol_drugs_by_category[@drug_category]
drug_consumption = protocol_drugs.each_with_object({}) { |protocol_drug, consumption|
opening_balance = previous_month_in_stock_by_rxnorm_code&.dig(protocol_drug.rxnorm_code)
received = received_by_rxnorm_code&.dig(protocol_drug.rxnorm_code)
redistributed = redistributed_by_rxnorm_code&.dig(protocol_drug.rxnorm_code)
closing_balance = in_stock_by_rxnorm_code&.dig(protocol_drug.rxnorm_code)
consumption[protocol_drug] = consumption_calculation(opening_balance, received, redistributed, closing_balance)
}
drug_consumption[:base_doses] = base_doses(drug_consumption)
drug_consumption
rescue => e
# drug is not in formula, or other configuration error
error_info = {
coefficients: @coefficients,
drug_category: @drug_category,
in_stock_by_rxnorm_code: in_stock_by_rxnorm_code,
previous_month_in_stock_by_rxnorm_code: previous_month_in_stock_by_rxnorm_code,
patient_count: @patient_count,
protocol: @protocol,
exception: e
}
trace("consumption", "Reports::DrugStockCalculation#consumption", error_info)
{consumption: "error"}
end
def stocks_on_hand
@stocks_on_hand ||= protocol_drugs_by_category[@drug_category].map do |protocol_drug|
rxnorm_code = protocol_drug.rxnorm_code
in_stock = in_stock_by_rxnorm_code&.dig(rxnorm_code)
next if in_stock.nil?
coefficient = drug_coefficient(rxnorm_code)
{protocol_drug: protocol_drug,
in_stock: in_stock,
coefficient: coefficient,
stock_on_hand: coefficient * in_stock}
end&.compact
end
def drug_coefficient(rxnorm_code)
@coefficients.dig(:drug_categories, @drug_category, rxnorm_code)
end
def drug_name_and_dosage(drug)
"#{drug.name} #{drug.dosage}"
end
def patient_days_calculation
(stocks_on_hand.map { |stock| stock[:stock_on_hand] }.reduce(:+) / estimated_patients).floor
end
def consumption_calculation(opening_balance, received, redistributed, closing_balance)
return {consumed: nil} if [opening_balance, received, closing_balance].all?(&:nil?)
{
opening_balance: opening_balance,
received: received,
redistributed: redistributed,
closing_balance: closing_balance,
consumed: opening_balance + (received || 0) - (redistributed || 0) - closing_balance
}
rescue => e
error_info = {
protocol: @protocol,
opening_balance: opening_balance,
received: received,
redistributed: redistributed,
closing_balance: closing_balance,
exception: e
}
trace("consumption_calculation", "Reports::DrugStockCalculation#consumption_calculation", error_info)
{consumed: "error"}
end
def base_doses(drug_consumption)
base_doses = {}
base_doses[:drugs] = drug_consumption.map { |drug, consumption|
{name: drug_name_and_dosage(drug),
consumed: consumption[:consumed],
coefficient: drug_coefficient(drug.rxnorm_code)}
}
base_doses[:total] = base_doses_calculation(base_doses[:drugs])
base_doses
end
def base_doses_calculation(doses)
doses
.reject { |dose| dose[:consumed].nil? || dose[:consumed] == "error" }
.map { |dose| dose[:consumed] * dose[:coefficient] }
.reduce(:+)
end
def estimated_patients
@estimated_patients ||= @patient_count * @coefficients[:load_coefficient] * new_patient_coefficient
end
def new_patient_coefficient
@new_patient_coefficient ||= @coefficients.dig(:drug_categories, @drug_category, :new_patient_coefficient)
end
def patient_days_coefficients(state)
drug_stock_config = Rails.application.config.drug_stock_config
env = ENV.fetch("SIMPLE_SERVER_ENV")
# This is a hack for convenience in envs with generated data
# Once we make formula coefficients a first class model, we can get rid of this
if env != "production" && drug_stock_config[state].nil?
drug_stock_config.values.first
else
drug_stock_config[state]
end
end
def drug_attribute_sum_by_rxnorm_code(drug_stocks, attribute)
drug_stocks
.select { |drug_stock| drug_stock[attribute].present? }
.group_by { |drug_stock| drug_stock.protocol_drug.rxnorm_code }
.map { |rxnorm_code, drug_stocks| [rxnorm_code, drug_stocks.pluck(attribute).sum] }
.to_h
end
memoize def in_stock_by_rxnorm_code
drug_attribute_sum_by_rxnorm_code(@current_drug_stocks, :in_stock)
end
memoize def received_by_rxnorm_code
drug_attribute_sum_by_rxnorm_code(@current_drug_stocks, :received)
end
memoize def redistributed_by_rxnorm_code
drug_attribute_sum_by_rxnorm_code(@current_drug_stocks, :redistributed)
end
memoize def previous_month_in_stock_by_rxnorm_code
drug_attribute_sum_by_rxnorm_code(@previous_drug_stocks, :in_stock)
end
def trace(name, resource, error_info)
Datadog::Tracing.trace(name, resource: resource) do |span|
error_info.each { |tag, value| span.set_tag(tag.to_s, value.to_s) }
end
end
end
end
|
require 'test_helper'
class ProjectGeneratorTest < Test::Unit::TestCase
include Sprout::TestHelper
context "A new Project generator" do
setup do
@temp = File.join(fixtures, 'generators', 'tmp')
FileUtils.mkdir_p @temp
@generator = Robotlegs::ProjectGenerator.new
@generator.path = @temp
@generator.logger = StringIO.new
end
teardown do
remove_file @temp
end
should "generate a new Project" do
@generator.input = "Fwee"
@generator.execute
input_dir = File.join(@temp, "Fwee")
assert_directory input_dir
rakefile = File.join(input_dir, "rakefile.rb")
assert_file rakefile
assert_file rakefile do |content|
assert_match /src\/Fwee.mxml/, content
end
gemfile = File.join(input_dir, "Gemfile")
assert_file gemfile
src_dir = File.join(input_dir, "src")
assert_directory src_dir
context_file = File.join(src_dir, "FweeContext.as")
assert_file context_file
main_file = File.join(src_dir, "Fwee.mxml")
assert_file main_file do |content|
assert_match /FweeCompleteHandler/, content
assert_match /xmlns:context="*"/, content
end
lib_dir = File.join(input_dir, "lib")
assert_directory lib_dir
bin_dir = File.join(input_dir, "bin")
assert_directory bin_dir
model_dir = File.join(src_dir, "model")
assert_directory model_dir
view_dir = File.join(src_dir, "view")
assert_directory view_dir
controller_dir = File.join(src_dir, "controller")
assert_directory controller_dir
service_dir = File.join(src_dir, "service")
assert_directory service_dir
notifications_dir = File.join(src_dir, "events")
assert_directory notifications_dir
#Second level directories
proxy_dir = File.join(model_dir, "proxy")
assert_directory proxy_dir
vo_dir = File.join(model_dir, "vo")
assert_directory vo_dir
mediators_dir = File.join(view_dir, "mediators")
assert_directory mediators_dir
components_dir = File.join(view_dir, "components")
assert_directory components_dir
skins_dir = File.join(view_dir, "skins")
assert_directory skins_dir
commands_dir = File.join(controller_dir, "commands")
assert_directory commands_dir
dto_dir = File.join(service_dir, "dto")
assert_directory dto_dir
end
should "respect shallow" do
@generator.input = "Fwi"
@generator.shallow = true
@generator.execute
input_dir = File.join(@temp, "Fwi")
assert_directory input_dir
vo_dir = File.join(input_dir, "src", "model", "vo")
assert !File.exists?(vo_dir)
dto_dir = File.join(input_dir, "src", "service", "dto")
assert !File.exists?(dto_dir)
end
should "add package directories" do
@generator.input = "Fwo"
@generator.package = "com/developsigner"
@generator.execute
input_dir = File.join(@temp, "Fwo")
assert_directory input_dir
src_dir = File.join(input_dir, "src")
assert_directory src_dir
package_dir = File.join(src_dir, "com", "developsigner")
assert_directory package_dir
context_file = File.join(package_dir, "FwoContext.as")
assert_file context_file
main_file = File.join(src_dir, "Fwo.mxml")
assert_file main_file do |content|
assert_match /FwoCompleteHandler/, content
assert_match /com.developsigner.*/, content
end
end
should "respect notifications override" do
@generator.input = "Fwum"
@generator.notifications = "signals"
@generator.execute
src_dir = File.join(@temp, "Fwum", "src")
assert_directory src_dir
notifications_dir = File.join(src_dir, "signals")
assert_directory notifications_dir
end
end
end
|
class Admin::AppsController < Admin::BaseController
load_and_authorize_resource
skip_load_resource :only => [:create]
add_breadcrumb :controller, action: :index
before_action :set_admin_app, only: [:show, :edit, :update, :destroy]
# GET /admin/apps
# GET /admin/apps.json
def index
add_breadcrumb :index, :index
@admin_apps = initialize_grid(App, per_page: 20)
end
# GET /admin/apps/1
# GET /admin/apps/1.json
def show
add_breadcrumb :show, :show
end
# GET /admin/apps/new
def new
add_breadcrumb :new, :new
@admin_app = App.new
end
# GET /admin/apps/1/edit
def edit
add_breadcrumb :edit, :edit
end
# POST /admin/apps
# POST /admin/apps.json
def create
@admin_app = App.new(admin_app_params)
respond_to do |format|
if @admin_app.save
format.html { redirect_to [:admin, @admin_app], notice: 'App was successfully created.' }
format.json { render :show, status: :created, location: [:admin, @admin_app] }
else
format.html { render :new }
format.json { render json: [:admin, @admin_app].errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /admin/apps/1
# PATCH/PUT /admin/apps/1.json
def update
respond_to do |format|
if @admin_app.update(admin_app_params)
format.html { redirect_to [:admin, @admin_app], notice: 'App was successfully updated.' }
format.json { render :show, status: :ok, location: @admin_app }
else
format.html { render :edit }
format.json { render json: @admin_app.errors, status: :unprocessable_entity }
end
end
end
# DELETE /admin/apps/1
# DELETE /admin/apps/1.json
def destroy
@admin_app.destroy
respond_to do |format|
format.html { redirect_to admin_apps_url, notice: 'App was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_admin_app
@admin_app = App.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def admin_app_params
params.require(:app).permit(:name, :access_key, :secret_key, :permission_level, :enable)
end
end
|
require 'spec_helper_acceptance'
require 'pry'
describe 'Solaris DNS provider' do
fmri = "svc:/network/dns/client"
# a sample manifest to apply
pp = <<-EOP
dns { 'current':
nameserver => ['1.2.3.4', '2.3.4.5'],
domain => 'foo.com',
search => ['foo.com', 'bar.com'],
sortlist => ['1.2.3.4/5', '2.3.4.5/6'],
options => ['debug', 'retry:3'],
}
EOP
# disable service so configuration doesn't get overridden by server
shell("svcadm disable dns/client", :acceptable_exit_codes => 0)
it 'should apply a manifest with no errors' do
apply_manifest(pp, :catch_failures => true)
end
it 'should apply the manifest again with no updates triggered' do
expect(apply_manifest(pp, :catch_failures => true).exit_code).to be_zero
end
it 'should correctly apply the nameserver value' do
shell("svcprop -p config/nameserver #{fmri} | egrep -s '^1.2.3.4 2.3.4.5$'", :acceptable_exit_codes => 0)
end
it 'should correctly apply the domain value' do
shell("svcprop -p config/domain #{fmri} | egrep -s '^foo.com$'", :acceptable_exit_codes => 0)
end
it 'should correctly apply the search value' do
shell("svcprop -p config/search #{fmri} | egrep -s '^foo.com bar.com$'", :acceptable_exit_codes => 0)
end
it 'should correctly apply the sortlist value' do
shell("svcprop -p config/sortlist #{fmri} | egrep -s '^1.2.3.4/5 2.3.4.5/6$'", :acceptable_exit_codes => 0)
end
it 'should correctly apply the options value' do
shell("svcprop -p config/options #{fmri} | egrep -s '^debug retry:3$'", :acceptable_exit_codes => 0)
end
end
|
#!/usr/bin/env ruby
require 'optparse'
options = { action: :run }
daemonize_help = "run daemonized in the background (default: false)"
logfile_help = "the log filename"
op = OptionParser.new
op.banner = "Docker autodeployment tool."
op.separator ""
op.separator "Usage: server [options]"
op.separator ""
op.separator ""
op.separator "Process options:"
op.on("-d", "--daemonize", daemonize_help) { options[:daemonize] = true }
op.on("-l", "--log LOGFILE", logfile_help) { |value| options[:logfile] = value }
op.separator ""
op.separator "Ruby options:"
op.separator ""
op.separator "Common options:"
op.on("-h", "--help") { options[:action] = :help }
op.on("-v", "--version") { options[:action] = :version }
op.on("-s", "--stop") { options[:action] = :stop }
op.on("-i", "--status") { options[:action] = :status }
op.separator ""
op.parse!(ARGV)
require_relative '../lib/environment' unless options[:action] == :help
case options[:action]
when :help then puts op.to_s
when :version then puts '1.0.0'
when :stop then Movinga::Utils::Autodeploy.stop('autodeploy.pid')
when :status then Movinga::Utils::Autodeploy.pid_status('autodeploy.pid')
else
Movinga::Utils::Autodeploy.start(options.merge!(pidfile: 'autodeploy.pid'))
end
|
#!/usr/bin/env ruby
require "json"
class DeployCssLint
def initialize
@config_dir = File.expand_path('~/.oroshi/config/csslint/')
@csslintjson = File.join(@config_dir, "csslintrc.json")
@csslintrc = File.expand_path("~/.csslintrc")
end
# Read a JSON file an return a ruby object
def read_json(file)
return JSON.parse(File.read(file))
end
# generate the final ~/.csslintrc file by concatenating the base with the
# custom tags
def generate
base = []
json = read_json(@csslintjson)
json.each do |key, list|
base << "--#{key}=#{list.join(',')}"
end
output = base.join(" ")
File.write(@csslintrc, output);
end
def run
generate
end
end
DeployCssLint.new().run()
|
class OakPark
include DataMapper::Resource
property :hole_number, Integer, key: true
property :hole_par, Integer
property :hole_si, Integer
property :hole_distance, Integer
end
|
require 'date'
require 'pry'
class KeyGen
attr_reader :key
def key_map(key)
a_key = key.to_s[0..1].to_i
b_key = key.to_s[1..2].to_i
c_key = key.to_s[2..3].to_i
d_key = key.to_s[3..-1].to_i
raw_keys = [a_key, b_key, c_key, d_key]
end
def offsets_map(date)
squared_date = ((date ** 2).to_s)[-4..-1]
a_offset = squared_date[0].to_i
b_offset = squared_date[1].to_i
c_offset = squared_date[2].to_i
d_offset = squared_date[3].to_i
raw_offsets = [a_offset, b_offset, c_offset, d_offset]
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.