repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
Flatiron-group/tenant_verification
|
app/controllers/landlords_controller.rb
|
<gh_stars>0
class LandlordsController < ApplicationController
def show
id = params[:id]
landlord = Landlord.find(id)
render json: landlord
end
def create
# param keys may subject to change depending on the body of the post request
new_landlord = Landlord.new(first_name: params[:first_name], last_name: params[:last_name], email: params[:email], password: params[:password])
if new_landlord.valid?
Landlord.create(first_name: params[:first_name], last_name: params[:last_name], email: params[:email], password: params[:password])
# message can be altered for better UI experience in the future
render json: {message: "Landlord successfully created"}
else
# message can be altered for better UI experience in the future
render json: {message: "There was an error."}
end
end
def update
id = params[:id]
if Landlord.update(id, first_name: params[:first_name], last_name: params[:last_name], email: params[:email], password: params[:password]).valid?
Landlord.update(id, first_name: params[:first_name], last_name: params[:last_name], email: params[:email], password: params[:password])
updated_landlord = Landlord.find(id)
# message can be altered for better UI experience in the future
render json: {landlord: updated_landlord, message: "Landlord successfully updated"}
else
# message can be altered for better UI experience in the future
render json: {message: "Update failed"}
end
end
def destroy
id = params[:id]
Landlord.destroy(id)
render json: {message: "Successfully deleted"}
end
end
|
Flatiron-group/tenant_verification
|
test/controllers/land_lords_controller_test.rb
|
require 'test_helper'
class LandLordsControllerTest < ActionDispatch::IntegrationTest
test "should get show" do
get land_lords_show_url
assert_response :success
end
test "should get create" do
get land_lords_create_url
assert_response :success
end
test "should get update" do
get land_lords_update_url
assert_response :success
end
test "should get delete" do
get land_lords_delete_url
assert_response :success
end
end
|
Flatiron-group/tenant_verification
|
config/routes.rb
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
post "/login", to: "sessions#create"
delete "/logout", to: "sessions#destroy"
get "/get_current_user", to: "sessions#get_current_user"
resources :landlords do
resources :addresses
end
resources :landlords do
resources :tenants
end
resources :tenants do
resources :reviews
end
end
|
Flatiron-group/tenant_verification
|
app/controllers/tenants_controller.rb
|
<reponame>Flatiron-group/tenant_verification
class TenantsController < ApplicationController
def index
if !params[:landlord_id]
tenants = Tenant.all
render json: tenants
else
tenants = Landlord.find(params[:landlord_id]).tenants
render json: tenants
end
end
def show
if !params[:landlord_id]
id = params[:id]
tenant = Tenant.find(id)
render json: tenant
else
id = params[:id]
landlord_id = params[:landlord_id]
tenant = Landlord.find(landlord_id).tenants.find(id)
render json: tenant
end
end
def create
# param keys may subject to change depending on the body of the post request
if !params[:landlord_id]
new_tenant = Tenant.new(first_name: params[:first_name], last_name: params[:last_name])
if new_tenant.valid?
Tenant.create(first_name: params[:first_name], last_name: params[:last_name])
# message can be altered for better UI experience in the future
render json: {message: "Tenant successfully created"}
else
# message can be altered for better UI experience in the future
render json: {message: "There was an error."}
end
else
new_tenant = Tenant.new(first_name: params[:first_name], last_name: params[:last_name])
if new_tenant.valid?
Tenant.create(first_name: params[:first_name], last_name: params[:last_name])
# all inputs for creating the Review are default values. Only the landlord_id and tenant_id are actual correct values. MUST BE UPDATED!!! Needed the default values to pass Review validations
Review.create(start_date: Date.new(2000, 1, 1), end_date: Date.new(2000, 1, 1), landlord_id: params[:landlord_id], tenant_id: Tenant.last.id, address: "TBD", comment: "TBD")
# message can be altered for better UI experience in the future
render json: {message: "Tenant successfully created"}
else
# message can be altered for better UI experience in the future
render json: {message: "There was an error."}
end
end
end
def update
# this method does not need to be changed for the nested routes because for the nested route, the :id in params[:id] refers to the tenant id because its the last model in the nested route. Will need to change IF it is triple nested
id = params[:id]
if Tenant.update(id, first_name: params[:first_name], last_name: params[:last_name]).valid?
Tenant.update(id, first_name: params[:first_name], last_name: params[:last_name])
updated_tenant = Tenant.find(id)
# message can be altered for better UI experience in the future
render json: {tenant: updated_tenant, message: "Tenant successfully updated"}
else
# message can be altered for better UI experience in the future
render json: {message: "Update failed"}
end
end
def destroy
# this method does not need to be changed for the nested routes because for the nested route, the :id in params[:id] refers to the tenant id because its the last model in the nested route. Will need to change IF it is triple nested
id = params[:id]
Tenant.destroy(id)
render json: {message: "Successfully deleted"}
end
end
|
raspimeteo/dutch_top40
|
lib/dutch_top40/cli.rb
|
class DutchTop40::CLI
def call
logo
puts "One moment, acquiring data.",""
list_songs
menu
end
def list_songs
@songs = DutchTop40::Songs.list
print_songs
puts
end
def print_songs
puts "Dutch Top40 - week #{Time.now.strftime("%U")}", ""
@songs.each.with_index(1) do |song, index|
puts "#{index}. #{song.title}"
end
end
def menu
input = nil
while input != 'exit'
puts "Which song do you want more info on? Type list to see list again, type exit to quit.",""
input = gets.strip.downcase
case input.to_i
when 1..@songs.size
puts "------------------------------------------------------------------------------------"
puts "Current rank #{input}."
puts "------------------------------------------------------------------------------------"
puts "#{@songs[input.to_i-1].title} - performing artist(s): #{@songs[input.to_i-1].name}"
puts "weeks in Top40: #{@songs[input.to_i-1].listed} - last weeks rank: #{@songs[input.to_i-1].last_weeks_rank}"
puts "------------------------------------------------------------------------------------"
else
puts "Invalid input!" unless input == 'exit' || input == 'list'
if input == 'list'
print_songs
end
if input == 'exit'
goodbye
end
end
end
end
def goodbye
logo
puts "See you next time..."
end
def logo
puts "
````````````````````` ```````````````````` ````````````````````
`:``````````````````.+. -.``````````````````-/` :```````````````````+.
:` `---:::::::---` /Ny`: `.-/+::+/:` hm/:`.///////-///:-` -Nd`
-. ```oyyyyyyo``` .NN-/ ./oyyyo`+yyys/ +Mh.-`syyyyyy/.yyyyys. `dM:
`: -yyyyyys` hM+:`.+yyyyys.:yyyyyy- -Nm.: +yyyyyys`oyyyyyy/ sMs
: `syyyyyy- oMy.--syyyyyy:.yyyyyyy:`mM::`-yyyyyyy./yyyyyys./Md`
:` oyyyyyy+ :Mm./-yyyyyyy+`syyyyyys`yMo-.`syyyyyy/-yyyyyyo..NN.
.- /yyyyyys` `mM-:`syyyyyys`+yyyyyys./Md`: oyyyyyys.syyss+- dM/
/ .yyyyyyy. yMo.- syyyyyy.:yyyyyyo`.NN./ :yyyyyys-....` oMy
:` `syyyyyy: +Mh`: -syyyy:.yyyyy+- `dM/-..yyyyyyy- :Mm`
.- /yssssso -NN./ `/oso-+o+/-` sMs`: +ssssss: `mM-
: `mM:-. :Mm`/ hM+
.-hdddddddddddddddddmMs -/dddddddmmmmdmmmmmmNN.`-ymmmmmmmmmmmmmmmmmmMh
-------------------- .-------------------. .---................`
.-..................-: :....-----........../
: `::::::` sm+:` .:/+-++:. -mh
:` `:syyyyyo :Mm-- `:syyy:-yyyy: `mM:
.. -/syyyyys` `mN:: -syyyy+`syyyys yMo
`: -:./yyyyyy- hM+:` /yyyyys`+yyyyyo /Md
: .:. .yyyyyy+ +Mh-. /yyyyyy--yyyyyy: .NN.
-. .:- `syyyyys` -Nm-: `yyyyyy/`syyyyy/ `dM/
`: `/:....+yyyyyy:` `mM:: -yyyyyo`oyyyys: sMs
: `...../yyyyyy/.` yMo-` `syyyy.:yyys+. :Md`
:` `osssss+ /Mh.- .+os/.oo+:. .mN-
.- `````` .NN.: ````` hM+
::yyyyyyyyyyyyyyyyyymM/.:syyyyyyyyyyyyyyyyyhMy
.+++++++///////////// `+++++++++++++++/////`
"
end
end
|
raspimeteo/dutch_top40
|
lib/dutch_top40/songs.rb
|
<reponame>raspimeteo/dutch_top40
class DutchTop40::Songs
attr_accessor :title, :name, :listed, :last_weeks_rank
@@songs = []
def initialize(title, name, listed, last_weeks_rank)
@title = title
@name = name
@listed = listed
@last_weeks_rank = last_weeks_rank
@@songs << self
end
def self.list
DutchTop40::Scraper.scrape_songs
@@songs
end
end
|
raspimeteo/dutch_top40
|
lib/dutch_top40.rb
|
require_relative "./dutch_top40/version"
require 'nokogiri'
require 'open-uri'
require 'pry'
require_relative './dutch_top40/cli'
require_relative './dutch_top40/songs'
require_relative './dutch_top40/scraper'
|
raspimeteo/dutch_top40
|
lib/dutch_top40/scraper.rb
|
class DutchTop40::Scraper
attr_accessor :title, :name, :listed, :last_weeks_rank
def self.scrape_songs
doc = Nokogiri::HTML(open("http://top40.nl"))
doc.search('.listScroller .list-right').each do |song|
# binding.pry
title = song.css('.songtitle').text.strip
name = song.css('.artist').text
details = song.css('.details').text
listed = details.split(' | ')[1].gsub(/Aantal weken: /,'').strip
if details.split(' | ')[0].gsub(/Vorige week: #/,'').strip == '-'
last_weeks_rank = 'new entry'
else
last_weeks_rank = details.split(' | ')[0].gsub(/Vorige week: #/,'').strip
end
DutchTop40::Songs.new(title, name, listed, last_weeks_rank)
end
end
end
|
johnbintz/sisyphus-rails
|
lib/sisyphus-rails/form_helper.rb
|
<gh_stars>1-10
module ActionView
module Helpers
module FormHelper
def form_for_with_sisyphus(record, options = {}, &proc)
case record
when String, Symbol
object_name = record
else
object = record.is_a?(Array) ? record.last : record
object_name = options[:as] || ActiveModel::Naming.param_key(object)
end
# There is an order of precedence debugger
Sisyphus::process = true
Sisyphus::process = Sisyphus::config["SISYPHUS_ENABLED"] if Sisyphus::config.include?("SISYPHUS_ENABLED")
if Sisyphus::config["EXCLUDE_MODELS"].present?
Sisyphus::process = false if Sisyphus::config["EXCLUDE_MODELS"].include?(model_name_from_record_or_class(object_name))
end
Sisyphus::process = options[:with_sisyphus] if options.include?(:with_sisyphus)
#strip all the sisyphus options from the options hash before moving on
form_for_without_sisyphus(record, options.reject{|k,v| k =~ /sisyphus(.*)/}, &proc)
end
alias_method_chain :form_for, :sisyphus
end
end
end
|
johnbintz/sisyphus-rails
|
lib/sisyphus-rails/engine.rb
|
<gh_stars>1-10
module Sisyphus
class Engine < ::Rails::Engine
initializer "sisyphus-rails.load_config_data" do |app|
Sisyphus.setup do |config|
config.app_root = app.root
#Load the configuration from the environment or a yaml file
Sisyphus.config = Hash.new
#load the config file if we have it
if FileTest.exist?("#{::Rails.root}/config/sisyphus.yml")
config = YAML.load_file("#{::Rails.root}/config/sisyphus.yml")
config = config[::Rails.env]
Sisyphus.config["SISYPHUS_ENABLED"] = config['sisyphus_enabled'] if config.include?('sisyphus_enabled')
Sisyphus.config["EXCLUDE_MODELS"] = config['exclude_models'].split(',') if config.include?('exclude_models')
Sisyphus.config["INCLUDE_MODELS"] = config['include_models'].split(',') if config.include?('include_models')
end
#if we have ENV flags prefer them
Sisyphus.config["SISYPHUS_ENABLED"] = ENV["SISYPHUS_ENABLED"] if ENV.include?("SISYPHUS_ENABLED")
Sisyphus.config["EXCLUDE_MODELS"] = ENV["EXCLUDE_MODELS"].split(',') if ENV.include?("EXCLUDE_MODELS")
Sisyphus.config["INCLUDE_MODELS"] = ENV["INCLUDE_MODELS"].split(',') if ENV.include?("INCLUDE_MODELS")
end
app.config.assets.precompile << 'ckeditor/plugins/onchange/plugin.js'
end
end
end
|
johnbintz/sisyphus-rails
|
lib/sisyphus-rails/form_tag_helper.rb
|
module ActionView
module Helpers
module FormTagHelper
def form_tag_with_sisyphus(url_for_options = {}, options = {}, &block)
buf = ActiveSupport::SafeBuffer.new
if options.has_key?(:id) && Sisyphus::process
buf.safe_concat("<script type=\"text/javascript\">$(document).ready(function() {$('##{options[:id]}').sisyphus({excludeFields: $('input[name=utf8], input[name=_method], input[name=authenticity_token]')});});</script>")
end
buf << form_tag_without_sisyphus(url_for_options, options, &block)
end
alias_method_chain :form_tag, :sisyphus
end
end
end
|
johnbintz/sisyphus-rails
|
lib/sisyphus-rails.rb
|
<filename>lib/sisyphus-rails.rb
require "sisyphus-rails/version"
require "sisyphus-rails/engine"
require "sisyphus-rails/form_helper"
require "sisyphus-rails/form_tag_helper"
module Sisyphus
mattr_accessor :process
mattr_accessor :app_root
mattr_accessor :config
def self.setup
yield self
end
end
|
johnbintz/sisyphus-rails
|
lib/generators/sisyphus/configuration/configuration_generator.rb
|
<gh_stars>1-10
module Sisyphus
module Generators
class ConfigurationGenerator < ::Rails::Generators::Base
source_root File.expand_path('../templates', __FILE__)
desc "Creates blank config file for extended configuration."
def create_yaml
template "sisyphus.yml", "config/sisyphus.yml"
end
end
end
end
|
johnbintz/sisyphus-rails
|
sisyphus-rails.gemspec
|
<gh_stars>1-10
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'sisyphus-rails/version'
Gem::Specification.new do |gem|
gem.name = "sisyphus-rails"
gem.version = Sisyphus::Rails::VERSION
gem.authors = ["<NAME>"]
gem.email = ["<EMAIL>"]
gem.description = %q{Include gmail like auto-save on your forms}
gem.summary = %q{Using Sisyphus.js and jStorage.js the gem overrides the default rails form builder to add an auto-save feature to your forms.}
gem.homepage = "https://www.github.com/dnoonan/sisyphus-rails"
gem.files = `git ls-files`.split($/)
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ["lib"]
gem.requirements << 'requires jQuery 1.4+ to be included before Sisyphus'
gem.requirements << 'requires jQuery 1.8+ to be included if you require jStorage'
gem.add_dependency "rails", ">= 3.1.0"
end
|
salsify/avrolution
|
spec/avrolution/compatibility_break_spec.rb
|
# frozen_string_literal: true
describe Avrolution::CompatibilityBreak do
let(:name) { 'com.example.test' }
let(:fingerprint) do
Avro::Schema.parse({ name: name, type: :record }.to_json).sha256_resolution_fingerprint.to_s(16)
end
before do
Avro.disable_schema_name_validation = true if Avro.respond_to?(:disable_schema_name_validation=)
end
after do
Avro.disable_schema_name_validation = false if Avro.respond_to?(:disable_schema_name_validation=)
end
context "validation" do
let(:with_compatibility) { 'NONE' }
let(:after_compatibility) { nil }
subject { described_class.new(name, fingerprint, with_compatibility, after_compatibility) }
context "when name is blank" do
let(:name) { '' }
it { is_expected.to be_invalid }
end
context "when fingerprint is blank" do
let(:fingerprint) { nil }
it { is_expected.to be_invalid }
end
context "when with_compatibility does not have a valid value" do
let(:with_compatibility) { 'FOO' }
it { is_expected.to be_invalid }
end
context "when after_compatibility does not have a valid value" do
let(:after_compatibility) { 'BAR' }
it { is_expected.to be_invalid }
end
end
describe "#validate!" do
let(:with_compatibility) { 'NONE' }
let(:after_compatibility) { nil }
let(:compatibility_break) do
described_class.new(name, fingerprint, with_compatibility, after_compatibility)
end
context "when the compatibility break is valid" do
it "returns nil" do
expect(compatibility_break.validate!).to be_nil
end
end
context "when the compatibility break is invalid" do
subject(:compatibility_break) do
described_class.new(nil, '', 'FOO', 'BAR')
end
it "raises an error with the validation messages" do
expect do
compatibility_break.validate!
end.to raise_error(described_class::ValidationError,
"Name can't be blank, Fingerprint can't be blank, "\
'With compatibility is not included in the list, '\
'After compatibility is not included in the list')
end
end
end
describe "#key" do
subject { described_class.new(name, fingerprint) }
its(:key) { is_expected.to eq([name, fingerprint]) }
end
describe "#line" do
let(:with_compatibility) { 'FORWARD' }
subject { described_class.new(name, fingerprint, with_compatibility) }
its(:line) { is_expected.to eq("#{name} #{fingerprint} #{with_compatibility}") }
context "when after_compatibility is set" do
let(:with_compatibility) { 'NONE' }
let(:after_compatibility) { 'BACKWARD' }
subject { described_class.new(name, fingerprint, with_compatibility, after_compatibility) }
its(:line) { is_expected.to eq("#{name} #{fingerprint} #{with_compatibility} #{after_compatibility}") }
end
end
describe "#register_options" do
let(:with_compatibility) { 'FULL' }
subject { described_class.new(name, fingerprint, with_compatibility) }
its(:register_options) { is_expected.to eq(with_compatibility: with_compatibility) }
context "when after_compatibility is set" do
let(:with_compatibility) { 'NONE' }
let(:after_compatibility) { 'BACKWARD' }
subject { described_class.new(name, fingerprint, with_compatibility, after_compatibility) }
its(:register_options) do
is_expected.to eq(with_compatibility: with_compatibility, after_compatibility: after_compatibility)
end
end
end
end
|
salsify/avrolution
|
lib/avrolution/version.rb
|
# frozen_string_literal: true
module Avrolution
VERSION = '0.7.2'
end
|
salsify/avrolution
|
spec/avrolution/configuration_spec.rb
|
# frozen_string_literal: true
describe Avrolution, "configuration" do
describe "#compatibility_schema_registry_url" do
let(:configured_value) { 'http://static.example.com' }
subject(:url) do
described_class.compatibility_schema_registry_url
end
before do
Avrolution.compatibility_schema_registry_url = configured_value
end
it "returns the configured value" do
expect(url).to eq(configured_value)
end
context "when the configured value is a Proc" do
let(:dynamic_value) { 'http://dynamic.example.com' }
let(:configured_value) do
-> { dynamic_value }
end
it "returns the result of the proc" do
expect(url).to eq(dynamic_value)
end
end
context "when a value is not configured" do
let(:configured_value) { nil }
it "raises an error" do
expect { url }.to raise_error('compatibility_schema_registry_url must be set')
end
end
context "when the environment variable is set" do
let(:env_value) { 'http://environment.example.com' }
let(:env_var_name) { 'COMPATIBILITY_SCHEMA_REGISTRY_URL' }
before do
allow(ENV).to receive(:[]).with(env_var_name).and_return(env_value)
end
it "returns the environment value" do
expect(url).to eq(env_value)
end
end
end
describe "#deployment_schema_registry_url" do
let(:configured_value) { 'http://static.example.com' }
subject(:url) do
described_class.deployment_schema_registry_url
end
before do
Avrolution.deployment_schema_registry_url = configured_value
end
it "returns the configured value" do
expect(url).to eq(configured_value)
end
context "when the configured value is a Proc" do
let(:dynamic_value) { 'http://dynamic.example.com' }
let(:configured_value) do
-> { dynamic_value }
end
it "returns the result of the proc" do
expect(url).to eq(dynamic_value)
end
end
context "when a value is not configured" do
let(:configured_value) { nil }
it "raises an error" do
expect { url }.to raise_error('deployment_schema_registry_url must be set')
end
end
context "when the environment variable is set" do
let(:env_value) { 'http://environment.example.com' }
let(:env_var_name) { 'DEPLOYMENT_SCHEMA_REGISTRY_URL' }
before do
allow(ENV).to receive(:[]).with(env_var_name).and_return(env_value)
end
it "returns the environment value" do
expect(url).to eq(env_value)
end
end
end
end
|
salsify/avrolution
|
lib/avrolution/compatibility_breaks_file.rb
|
<filename>lib/avrolution/compatibility_breaks_file.rb
# frozen_string_literal: true
module Avrolution
module CompatibilityBreaksFile
NONE = 'NONE'
class DuplicateEntryError < StandardError
def initialize(key)
super("duplicate entry for key #{key}")
end
end
def self.path
Avrolution.compatibility_breaks_file
end
def self.add(name:,
fingerprint:,
with_compatibility: NONE,
after_compatibility: nil,
logger: Avrolution.logger)
compatibility_break = Avrolution::CompatibilityBreak.new(
name, fingerprint, with_compatibility, after_compatibility
)
compatibility_break.validate!
compatibility_breaks = load
raise DuplicateEntryError.new([name, fingerprint]) if compatibility_breaks.key?(compatibility_break.key)
line = compatibility_break.line
File.write(path, "#{line}\n", mode: 'a')
logger.info("Added #{line.inspect} to #{path}")
end
def self.load
return {} unless File.exist?(path)
File.read(path).each_line.each_with_object({}) do |line, compatibility_breaks|
next if line.blank? || /^#/ =~ line.strip
compatibility_break = Avrolution::CompatibilityBreak.new(*line.strip.split(' '))
compatibility_break.validate!
raise DuplicateEntryError.new(compatibility_break.key) if compatibility_breaks.key?(compatibility_break.key)
compatibility_breaks[compatibility_break.key] = compatibility_break
end
end
end
end
|
salsify/avrolution
|
spec/support/contexts/rake_setup.rb
|
# frozen_string_literal: true
require 'rake'
shared_context "rake setup" do
let(:rake) { Rake::Application.new }
let(:task) { rake[task_name] }
before do
Rake.application = rake
Rake.application.rake_require(task_path, $LOAD_PATH, [])
Rake::Task.define_task(:environment)
end
end
|
salsify/avrolution
|
spec/avrolution/compatibility_breaks_file_spec.rb
|
<filename>spec/avrolution/compatibility_breaks_file_spec.rb
# frozen_string_literal: true
describe Avrolution::CompatibilityBreaksFile, :fakefs do
let(:logger) { instance_double(Logger, info: nil) }
before do
FileUtils.mkdir_p(File.dirname(described_class.path))
end
describe ".path" do
it "returns the path to the compatibility breaks file" do
expect(described_class.path).to eq(Avrolution.compatibility_breaks_file)
end
end
describe ".add" do
let(:name) { 'com.salsify.foo' }
let(:fingerprint) { 'ABC123' }
let(:with_compatibility) { 'FORWARD' }
let(:after_compatibility) { 'FULL' }
context "validation" do
it "raises an error when name is blank" do
expect do
described_class.add(name: '', fingerprint: fingerprint)
end.to raise_error(Avrolution::CompatibilityBreak::ValidationError, "Name can't be blank")
end
it "raises an error when fingerprint is blank" do
expect do
described_class.add(name: name, fingerprint: '')
end.to raise_error(Avrolution::CompatibilityBreak::ValidationError, "Fingerprint can't be blank")
end
it "raises an error when with compatibility is invalid" do
expect do
described_class.add(name: name, fingerprint: fingerprint, with_compatibility: 'FOO')
end.to raise_error(
Avrolution::CompatibilityBreak::ValidationError,
'With compatibility is not included in the list'
)
end
it "raises an error when after compatibility is invalid" do
expect do
described_class.add(name: name, fingerprint: fingerprint, after_compatibility: 'FOO')
end.to raise_error(
Avrolution::CompatibilityBreak::ValidationError,
'After compatibility is not included in the list'
)
end
end
it "adds a line to the compatibility breaks file" do
described_class.add(name: name, fingerprint: fingerprint, with_compatibility: with_compatibility, logger: logger)
expect(File.read(described_class.path)).to eq("#{name} #{fingerprint} #{with_compatibility}\n")
end
context "when with_compatibility is not specified" do
it "defaults with_compatibility to NONE" do
described_class.add(name: name, fingerprint: fingerprint, logger: logger)
expect(File.read(described_class.path)).to eq("#{name} #{fingerprint} NONE\n")
end
end
context "when after compatibility is included" do
it "adds a line to the compatibility breaks file" do
described_class.add(name: name,
fingerprint: fingerprint,
with_compatibility: with_compatibility,
after_compatibility: after_compatibility,
logger: logger)
expect(File.read(described_class.path)).to eq(
"#{name} #{fingerprint} #{with_compatibility} #{after_compatibility}\n"
)
end
end
context "when the line to be added duplicates an existing entry" do
let(:file_contents) do <<~TEXT
com.salsify.foo ABC123 BACKWARD
TEXT
end
before do
File.write(described_class.path, file_contents)
end
it "raises an error" do
expect do
described_class.add(name: name, fingerprint: fingerprint, logger: logger)
end.to raise_error(described_class::DuplicateEntryError)
end
end
end
describe ".load" do
subject(:compatibility_breaks) { described_class.load }
context "when the file does not exist" do
it "returns an empty hash", :aggregate_failures do
expect(compatibility_breaks).to be_a(Hash)
expect(compatibility_breaks).to be_empty
end
end
context "when the file exists" do
let(:key) { ['com.salsify.foo', 'ABC123'] }
let(:file_contents) do <<~TEXT
# ignore me
com.salsify.foo ABC123 BACKWARD
com.salsify.bar XYZ456 NONE FULL
TEXT
end
before do
File.write(described_class.path, file_contents)
end
it "loads the entries" do
expect(compatibility_breaks).to have_key(key)
end
context "when the file contains invalid entries" do
let(:file_contents) do <<~TEXT
ONE TWO THREE FOUR
TEXT
end
it "raises an error" do
expect do
compatibility_breaks
end.to raise_error(Avrolution::CompatibilityBreak::ValidationError)
end
end
context "when the file contains duplicate entries" do
let(:file_contents) do <<~TEXT
com.salsify.foo ABC123 BACKWARD
com.salsify.foo ABC123 FORWARD
TEXT
end
it "raises an error" do
expect do
compatibility_breaks
end.to raise_error(described_class::DuplicateEntryError, "duplicate entry for key #{key}")
end
end
end
end
end
|
salsify/avrolution
|
lib/avrolution/rake/add_compatibility_break_task.rb
|
<filename>lib/avrolution/rake/add_compatibility_break_task.rb
# frozen_string_literal: true
require 'avrolution/rake/base_task'
module Avrolution
module Rake
class AddCompatibilityBreakTask < BaseTask
def initialize(**)
super
@name ||= :add_compatibility_break
@task_desc ||= 'Add an Avro schema compatibility break. Parameters: name, fingerprint, ' \
'with_compatibility, after_compatibility'
end
private
def perform
compatibility_break_args = ENV.to_h.slice(
'name', 'fingerprint', 'with_compatibility', 'after_compatibility'
).symbolize_keys
missing_args = [:name, :fingerprint].select do |arg|
compatibility_break_args[arg].blank?
end
if missing_args.any?
puts missing_args.map { |arg| "#{arg} can't be blank" }.join(', ')
puts 'Usage: rake avro:add_compatibility_break name=<name> fingerprint=<fingerprint> ' \
'[with_compatibility=<default:NONE>] [after_compatibility=<compatibility>]'
exit(1)
end
Avrolution::CompatibilityBreaksFile.add(**compatibility_break_args)
end
end
end
end
|
salsify/avrolution
|
lib/generators/avrolution/install_generator.rb
|
<reponame>salsify/avrolution
# frozen_string_literal: true
require 'rails/generators/base'
module Avrolution
class InstallGenerator < Rails::Generators::Base
source_paths << File.join(__dir__, 'templates')
def create_compatibility_breaks_file
copy_file('avro_compatibility_breaks.txt')
end
end
end
|
salsify/avrolution
|
spec/avrolution/tasks_spec.rb
|
# frozen_string_literal: true
describe "rake tasks" do
include_context "rake setup"
let(:task_path) { 'avrolution/rake/rails_avrolution' }
describe "register_schemas" do
let(:task_name) { 'avro:register_schemas' }
let(:schema_files) { ['app.avsc'] }
let(:register_schemas) { Avrolution::RegisterSchemas.new(schema_files) }
before do
@original_schemas = ENV['schemas']
ENV['schemas'] = schema_files.join(',')
allow(Avrolution::RegisterSchemas).to receive(:new).and_return(register_schemas)
allow(register_schemas).to receive(:call).and_call_original
end
after do
ENV['schemas'] = @original_schemas
end
it "dispatches to a RegisterSchemas instance" do
task.invoke
expect(register_schemas).to have_received(:call)
end
end
describe "check_compatibility" do
let(:task_name) { 'avro:check_compatibility' }
let(:compatibility_check) { Avrolution::CompatibilityCheck.new }
before do
allow(Avrolution::CompatibilityCheck).to receive(:new).and_return(compatibility_check)
allow(compatibility_check).to receive(:call).and_call_original
end
it "dispatches to a CompatibilityCheck instance" do
task.invoke
expect(compatibility_check).to have_received(:call)
end
end
describe "add_compatibility_break" do
let(:task_name) { 'avro:add_compatibility_break' }
before do
allow(Avrolution::CompatibilityBreaksFile).to receive(:add)
@original_name = ENV['name']
ENV['name'] = 'test-name'
@original_fingerprint = ENV['fingerprint']
ENV['fingerprint'] = 'test-fingerprint'
end
after do
ENV['name'] = @original_name
ENV['fingerprint'] = @original_fingerprint
end
it "adds a compatibility break entry" do
task.invoke
expect(Avrolution::CompatibilityBreaksFile).to have_received(:add)
end
end
end
|
salsify/avrolution
|
lib/avrolution/compatibility_check.rb
|
# frozen_string_literal: true
require 'avro-resolution_canonical_form'
require 'private_attr'
require 'diffy'
require 'avro_schema_registry-client'
module Avrolution
class CompatibilityCheck
extend PrivateAttr
attr_reader :incompatible_schemas
NONE = 'NONE'
FULL = 'FULL'
BOTH = 'BOTH'
BACKWARD = 'BACKWARD'
FORWARD = 'FORWARD'
private_attr_reader :schema_registry, :compatibility_breaks,
:logger
def initialize(logger: Avrolution.logger)
@incompatible_schemas = []
@schema_registry = build_schema_registry
@compatibility_breaks = Avrolution::CompatibilityBreaksFile.load
@logger = logger
end
def call
check_schemas(Avrolution.root)
self
end
def success?
incompatible_schemas.empty?
end
private
def check_schemas(path)
vendor_bundle_path = File.join(path, 'vendor/bundle/')
Dir[File.join(path, '**/*.avsc')].reject do |file|
file.start_with?(vendor_bundle_path)
end.each do |schema_file|
check_schema_compatibility(schema_file)
end
end
def check_schema_compatibility(file)
json = File.read(file)
schema = Avro::Schema.parse(json)
return unless schema.type_sym == :record
fullname = schema.fullname
fingerprint = schema.sha256_resolution_fingerprint.to_s(16)
logger.info("Checking compatibility: #{fullname}")
return if schema_registered?(fullname, schema)
compatible = schema_registry.compatible?(fullname, schema, 'latest')
if compatible.nil?
# compatible is nil if the subject is not registered
logger.info("... New schema: #{fullname}")
elsif !compatible && !compatibility_fallback(schema, fullname, fingerprint)
incompatible_schemas << file
report_incompatibility(json, schema, fullname, fingerprint)
end
end
def schema_registered?(fullname, schema)
schema_registry.lookup_subject_schema(fullname, schema)
rescue Excon::Errors::NotFound
nil
end
# For a schema that is incompatible with the latest registered schema,
# check if there is a compatibility break defined and check compatibility
# using the level defined by the break.
def compatibility_fallback(schema, fullname, fingerprint)
compatibility_break = compatibility_breaks[[fullname, fingerprint]]
if compatibility_break
logger.info("... Checking compatibility with level set to #{compatibility_break.with_compatibility}")
schema_registry.compatible?(
fullname, schema, 'latest', with_compatibility: compatibility_break.with_compatibility
)
else
false
end
end
def report_incompatibility(json, schema, fullname, fingerprint)
last_json = schema_registry.subject_version(fullname)['schema']
last_schema = Avro::Schema.parse(last_json)
backward = schema.read?(last_schema)
forward = last_schema.read?(schema)
compatibility_with_last = if backward && forward
FULL
elsif backward
BACKWARD
elsif forward
FORWARD
else
NONE
end
logger.info("... Compatibility with last version: #{compatibility_with_last}")
logger.info(Diffy::Diff.new(last_json, json, context: 3).to_s) unless compatibility_with_last == FULL
compatibility = schema_registry.subject_config(fullname)['compatibility'] ||
schema_registry.global_config['compatibility']
compatibility = FULL if compatibility == BOTH
logger.info("... Current compatibility level: #{compatibility}")
logger.info(
"\n To allow a compatibility break, run:\n" \
" rake avro:add_compatibility_break name=#{fullname} fingerprint=#{fingerprint} " \
"with_compatibility=#{compatibility_with_last} [after_compatibility=<LEVEL>]\n"
)
end
def build_schema_registry
AvroSchemaRegistry::Client.new(Avrolution.compatibility_schema_registry_url,
logger: Avrolution.logger)
end
end
end
|
salsify/avrolution
|
spec/spec_helper.rb
|
# frozen_string_literal: true
$LOAD_PATH.unshift File.expand_path('../lib', __dir__)
require 'simplecov'
SimpleCov.start
require 'avrolution'
# pp must be required prior to fakefs/spec_helpers
require 'pp'
require 'fakefs/spec_helpers'
require 'rspec/its'
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].sort.each { |f| require f }
# FakeFS does not play well with locales lazy-loaded by I18n, so generate
# an error to pre-cache them.
# rubocop:disable Style/RescueModifier
Avrolution::CompatibilityBreak
.new('', '', 'FOO', 'BAR')
.validate! rescue nil
# rubocop:enable Style/RescueModifier
RSpec.configure do |config|
config.before do
Avrolution.root = '/schema_root'
Avrolution.compatibility_schema_registry_url = 'https://compatibility.example.com'
Avrolution.deployment_schema_registry_url = 'https://deployment.example.com'
end
config.include FakeFS::SpecHelpers, fakefs: true
end
|
salsify/avrolution
|
lib/avrolution/rake/rails_avrolution.rake
|
# frozen_string_literal: true
require 'avrolution/rake/check_compatibility_task'
require 'avrolution/rake/add_compatibility_break_task'
require 'avrolution/rake/register_schemas_task'
Avrolution::Rake::AddCompatibilityBreakTask.define(dependencies: [:environment])
Avrolution::Rake::CheckCompatibilityTask.define(dependencies: [:environment])
Avrolution::Rake::RegisterSchemasTask.define(dependencies: [:environment])
|
salsify/avrolution
|
lib/avrolution/rake/base_task.rb
|
# frozen_string_literal: true
require 'rake/tasklib'
module Avrolution
module Rake
class BaseTask < ::Rake::TaskLib
attr_accessor :name, :task_namespace, :task_desc, :dependencies
def self.define(**options, &block)
new(**options, &block).define
end
def initialize(name: nil, dependencies: [])
super()
@name = name
@task_namespace = :avro
@dependencies = dependencies
yield self if block_given?
end
def define
namespace task_namespace do
desc task_desc
task(name.to_sym => dependencies) do
perform
end
end
end
private
def perform
raise NotImplementedError
end
end
end
end
|
salsify/avrolution
|
lib/avrolution/configuration.rb
|
<filename>lib/avrolution/configuration.rb
# frozen_string_literal: true
module Avrolution
COMPATIBILITY = 'compatibility'
DEPLOYMENT = 'deployment'
class << self
# Root directory to search for schemas, and default location for
# compatibility breaks file
attr_writer :root
# Path to the compatibility breaks file. Defaults to
# #{Avrolution.root}/avro_compatibility_breaks.txt
attr_writer :compatibility_breaks_file
# The URL (including any Basic Auth) for the schema registry to use for
# compatibility checks
attr_writer :compatibility_schema_registry_url
# The URL (including any Basic Auth) for the schema registry to use for
# deployment
attr_writer :deployment_schema_registry_url
attr_accessor :logger
def fetch_url(label)
env_name = "#{label.upcase}_SCHEMA_REGISTRY_URL"
ivar_name = "@#{env_name.downcase}"
env_value = ENV[env_name]
result = if env_value
env_value
elsif instance_variable_get(ivar_name)
ivar_value = instance_variable_get(ivar_name)
ivar_value = instance_variable_set(ivar_name, ivar_value.call) if ivar_value.is_a?(Proc)
ivar_value
end
raise "#{env_name.downcase} must be set" if result.blank?
result
end
end
self.logger = Avrolution::PassthruLogger.new($stdout)
def self.root
@root || raise('root must be set')
end
def self.compatibility_breaks_file
@compatibility_breaks_file ||= "#{root}/avro_compatibility_breaks.txt"
end
def self.compatibility_schema_registry_url
fetch_url(COMPATIBILITY)
end
def self.deployment_schema_registry_url
fetch_url(DEPLOYMENT)
end
def self.configure
yield self
end
end
|
salsify/avrolution
|
lib/avrolution/rake/check_compatibility_task.rb
|
# frozen_string_literal: true
require 'avrolution/rake/base_task'
module Avrolution
module Rake
class CheckCompatibilityTask < BaseTask
def initialize(**)
super
@name ||= :check_compatibility
@task_desc ||= 'Check that all Avro schemas are compatible with latest registered in production'
end
private
def perform
check = Avrolution::CompatibilityCheck.new.call
if check.success?
puts 'All schemas are compatible!'
else
puts "\nIncompatible schemas found: #{check.incompatible_schemas.join(', ')}"
exit(1)
end
end
end
end
end
|
salsify/avrolution
|
spec/avrolution/register_schemas_spec.rb
|
<reponame>salsify/avrolution
# frozen_string_literal: true
describe Avrolution::RegisterSchemas, :fakefs do
let(:schema_registry) { instance_double(AvroSchemaRegistry::Client) }
let(:logger) { instance_double(Logger, info: nil) }
let(:app_schema_path) { File.join(Avrolution.root, 'avro/schema') }
let(:schema_files) { [] }
let(:register_schemas) { described_class.new(schema_files) }
before do
allow(ENV).to receive(:[]).and_call_original
allow(ENV).to receive(:[]).with('COMPATIBILITY_REGISTRY_URL').and_return('registry_url')
allow(AvroSchemaRegistry::Client).to receive(:new).and_return(schema_registry)
FileUtils.mkdir_p(app_schema_path)
end
describe "#call" do
let(:app_schema_file) { File.join(app_schema_path, 'app.avsc') }
let(:schema_files) { [app_schema_file] }
let(:fingerprint) do
Avro::Schema.parse(File.read(app_schema_file)).sha256_resolution_fingerprint.to_s(16)
end
let(:fullname) { 'com.salsify.app' }
let(:json) do
{
type: :record,
name: fullname,
fields: [{ type: :string, name: :s, default: '' }]
}.to_json
end
before do
allow(schema_registry).to receive(:register_without_lookup)
File.write(app_schema_file, json)
end
it "registers the specified schema file" do
register_schemas.call
expect(schema_registry).to have_received(:register_without_lookup)
.with(fullname, json)
end
context "when the new schema is incompatible" do
before do
allow(schema_registry).to receive(:register_without_lookup).and_raise(Excon::Error::Conflict.new(409))
end
it "raises an error" do
expect do
register_schemas.call
end.to raise_error(described_class::IncompatibleSchemaError, "incompatible schema #{fullname}")
end
end
context "when a compatibility break is defined for a schema file" do
let(:compatibility_breaks_file) { Avrolution::CompatibilityBreaksFile.path }
let(:with_compatibility) { 'NONE' }
let(:after_compatibility) { 'FULL' }
before do
FileUtils.mkdir_p(File.dirname(compatibility_breaks_file))
File.write(
compatibility_breaks_file,
"#{fullname} #{fingerprint} #{with_compatibility} #{after_compatibility}\n"
)
end
it "registers the specified schema file" do
register_schemas.call
expect(schema_registry).to have_received(:register_without_lookup)
.with(fullname, json, with_compatibility: with_compatibility, after_compatibility: after_compatibility)
end
end
context "when a schema file does not exist" do
let(:schema_files) { File.join(app_schema_path, '/does/not/exist.avsc') }
it "does not raise an error" do
expect do
register_schemas.call
end.not_to raise_error
end
end
end
end
|
salsify/avrolution
|
lib/avrolution/railtie.rb
|
# frozen_string_literal: true
module Avrolution
class Railtie < Rails::Railtie
initializer 'avrolution.configure' do
Avrolution.configure do |config|
config.root = Rails.root
end
end
rake_tasks do
load File.expand_path('rake/rails_avrolution.rake', __dir__)
end
end
end
|
salsify/avrolution
|
lib/avrolution.rb
|
<gh_stars>0
# frozen_string_literal: true
require 'avrolution/version'
require 'logger'
module Avrolution
class PassthruLogger < Logger
def initialize(*)
super
@formatter = ->(_severity, _time, _progname, msg) { "#{msg}\n" }
end
end
end
require 'active_support/core_ext/object/try'
require 'avrolution/configuration'
require 'avrolution/compatibility_break'
require 'avrolution/compatibility_breaks_file'
require 'avrolution/compatibility_check'
require 'avrolution/register_schemas'
require 'avrolution/railtie' if defined?(Rails)
|
salsify/avrolution
|
lib/avrolution/register_schemas.rb
|
<filename>lib/avrolution/register_schemas.rb<gh_stars>0
# frozen_string_literal: true
require 'avro_schema_registry-client'
require 'private_attr'
require 'procto'
module Avrolution
class RegisterSchemas
extend PrivateAttr
include Procto.call
attr_reader :schema_files
private_attr_reader :compatibility_breaks, :schema_registry
class IncompatibleSchemaError < StandardError
def initialize(name)
super("incompatible schema #{name}")
end
end
def initialize(schema_files)
@schema_files = Array(schema_files)
@compatibility_breaks = Avrolution::CompatibilityBreaksFile.load
@schema_registry = build_schema_registry
end
def call
schemas.each do |(json, schema)|
register_schema(schema, json)
end
end
private
def register_schema(schema, json)
fullname = schema.fullname
fingerprint = schema.sha256_resolution_fingerprint.to_s(16)
compatibility_break = compatibility_breaks[[fullname, fingerprint]]
begin
if compatibility_break
schema_registry.register_without_lookup(
fullname,
json,
**compatibility_break.register_options
)
else
schema_registry.register_without_lookup(fullname, json)
end
rescue Excon::Error::Conflict
raise IncompatibleSchemaError.new(fullname)
end
end
def schemas
@schemas ||= schema_files.map do |schema_file|
if File.exist?(schema_file)
json = File.read(schema_file)
[json, Avro::Schema.parse(json)]
end
end.compact
end
def build_schema_registry
AvroSchemaRegistry::Client.new(Avrolution.deployment_schema_registry_url,
logger: Avrolution.logger)
end
end
end
|
salsify/avrolution
|
spec/avrolution/compatibility_check_spec.rb
|
# frozen_string_literal: true
describe Avrolution::CompatibilityCheck, :fakefs do
let(:schema_registry) { instance_double(AvroSchemaRegistry::Client) }
let(:app_schema_path) { File.join(Avrolution.root, 'avro/schema') }
let(:logger) { instance_double(Logger, info: nil) }
let(:not_found_error) { Excon::Errors::NotFound.new('Not Found') }
before do
allow(ENV).to receive(:[]).and_call_original
allow(ENV).to receive(:[]).with('COMPATIBILITY_REGISTRY_URL').and_return('registry_url')
allow(AvroSchemaRegistry::Client).to receive(:new).and_return(schema_registry)
FileUtils.mkdir_p(app_schema_path)
# Diffy uses the tmp directory
FileUtils.mkdir('/tmp')
end
subject(:check) { described_class.new(logger: logger) }
describe "#call" do
let(:app_schema_file) { File.join(app_schema_path, 'app.avsc') }
let(:fingerprint) do
Avro::Schema.parse(File.read(app_schema_file)).sha256_resolution_fingerprint.to_s(16)
end
let(:new_json) do
{
type: :record,
name: 'com.salsify.app',
fields: [{ type: :string, name: :s, default: '' }]
}.to_json
end
before do
File.write(app_schema_file, new_json)
end
context "when there are schema files under vendor/bundle" do
let(:app_schema_path) { File.join(Avrolution.root, 'vendor/bundle') }
let(:new_json) { 'this is invalid json' }
it "ignores schema files under vendor/bundle" do
expect(check.call).to be_success
end
end
context "when all schemas are compatible" do
before do
allow(schema_registry).to receive(:compatible?).and_return(true)
allow(schema_registry).to receive(:lookup_subject_schema).and_raise(not_found_error)
end
it "returns success" do
expect(check.call).to be_success
expect(schema_registry).to have_received(:compatible?)
.with('com.salsify.app', Avro::Schema, 'latest')
end
end
context "when all schemas are already registered" do
let(:id) { rand(1..100) }
before do
allow(schema_registry).to receive(:lookup_subject_schema).and_return(id)
end
it "returns success" do
expect(check.call).to be_success
expect(schema_registry).to have_received(:lookup_subject_schema)
.with('com.salsify.app', Avro::Schema)
end
end
shared_examples_for "an incompatible schema" do
let(:old_json) do
# no field default
{
type: :record,
name: 'com.salsify.app',
fields: [{ type: :int, name: :i }]
}.to_json
end
let(:actual_compatibility) { 'BACKWARD' }
let(:config_compatibility) { 'BOTH' }
let(:reported_config_compatibility) { 'FULL' }
before do
allow(schema_registry).to receive(:lookup_subject_schema).and_raise(not_found_error)
allow(schema_registry).to receive(:subject_version).and_return('schema' => old_json)
allow(schema_registry).to receive(:subject_config).and_return('compatibility' => config_compatibility)
end
it "returns failure", :aggregate_failures do
expect(check.call).not_to be_success
expect(check.incompatible_schemas).to eq([app_schema_file])
expect(logger).to have_received(:info).with(/Compatibility with last version: #{actual_compatibility}/)
expect(logger).to have_received(:info).with(/Current compatibility level: #{reported_config_compatibility}/)
expect(logger).to have_received(:info).with(
/rake avro:add_compatibility_break name=com\.salsify\.app fingerprint=#{fingerprint} with_compatibility=#{actual_compatibility}/ # rubocop:disable Layout/LineLength
)
end
end
context "when there is an incompatible schema" do
before do
allow(schema_registry).to receive(:compatible?).and_return(false)
end
it_behaves_like "an incompatible schema"
it_behaves_like "an incompatible schema" do
let(:actual_compatibility) { 'FORWARD' }
let(:old_json) do
# has field default
{
type: :record,
name: 'com.salsify.app',
fields: [{ type: :int, name: :i, default: 0 }]
}.to_json
end
let(:new_json) do
# no field default
{
type: :record,
name: 'com.salsify.app',
fields: [{ type: :string, name: :s }]
}.to_json
end
end
it_behaves_like "an incompatible schema" do
let(:config_compatibility) { 'FULL_TRANSITIVE' }
let(:actual_compatibility) { 'FULL' }
let(:old_json) do
# has field default
{
type: :record,
name: 'com.salsify.app',
fields: [{ type: :int, name: :i, default: 0 }]
}.to_json
end
let(:new_json) do
# has field default
{
type: :record,
name: 'com.salsify.app',
fields: [{ type: :string, name: :s, default: '' }]
}.to_json
end
end
end
context "when there is an incompatible schema with a compatibility break defined" do
let(:compatibility_breaks_file) { Avrolution::CompatibilityBreaksFile.path }
let(:with_compatibility) { 'NONE' }
before do
allow(schema_registry).to receive(:lookup_subject_schema).and_return(not_found_error)
allow(schema_registry).to receive(:compatible?).with('com.salsify.app', Avro::Schema, 'latest')
.and_return(false)
FileUtils.mkdir_p(File.dirname(compatibility_breaks_file))
File.write(compatibility_breaks_file, "com.salsify.app #{fingerprint} #{with_compatibility}\n")
end
context "when the schema is compatible using the defined compatibility break" do
before do
allow(schema_registry).to receive(:compatible?)
.with('com.salsify.app', Avro::Schema, 'latest', with_compatibility: with_compatibility).and_return(true)
end
it "returns success" do
expect(check.call).to be_success
end
end
context "when the schema is still incompatible using the compatibility break" do
let(:with_compatibility) { 'FORWARD' }
before do
allow(schema_registry).to receive(:compatible?)
.with('com.salsify.app', Avro::Schema, 'latest', with_compatibility: with_compatibility).and_return(false)
end
it_behaves_like "an incompatible schema"
end
end
end
end
|
salsify/avrolution
|
lib/avrolution/rake/register_schemas_task.rb
|
# frozen_string_literal: true
require 'avrolution/rake/base_task'
module Avrolution
module Rake
class RegisterSchemasTask < BaseTask
def initialize(**)
super
@name ||= :register_schemas
@task_desc ||= 'Register the specified Avro JSON schemas'
end
private
def perform
raise 'schemas must be specified' if ENV['schemas'].blank?
schemas = ENV['schemas'].split(',')
Avrolution::RegisterSchemas.call(schemas)
end
end
end
end
|
salsify/avrolution
|
lib/avrolution/compatibility_break.rb
|
<reponame>salsify/avrolution
# frozen_string_literal: true
require 'active_model'
module Avrolution
class CompatibilityBreak
include ActiveModel::Validations
ValidationError = Class.new(StandardError)
VALID_COMPATIBILITY_VALUES = [
'BACKWARD',
'BACKWARD_TRANSITIVE',
'FORWARD',
'FORWARD_TRANSITIVE',
'FULL',
'FULL_TRANSITIVE',
'NONE'
].freeze
NONE = 'NONE'
attr_reader :name, :fingerprint, :with_compatibility, :after_compatibility
validates_presence_of :name, :fingerprint
validates_inclusion_of :with_compatibility, in: VALID_COMPATIBILITY_VALUES, allow_nil: true
validates_inclusion_of :after_compatibility, in: VALID_COMPATIBILITY_VALUES, allow_nil: true
def initialize(name, fingerprint, with_compatibility = NONE, after_compatibility = nil, *extra)
@name = name
@fingerprint = fingerprint
@with_compatibility = with_compatibility.upcase
@after_compatibility = after_compatibility.try(:upcase)
@extra = extra
end
def key
[name, fingerprint]
end
def validate!
raise ValidationError.new(errors.full_messages.join(', ')) unless valid?
end
def line
[name, fingerprint, with_compatibility, after_compatibility].compact.join(' ')
end
def register_options
{ with_compatibility: with_compatibility }.tap do |options|
options[:after_compatibility] = after_compatibility if after_compatibility.present?
end
end
end
end
|
LorTos/BottomDrawerView
|
BottomDrawerView.podspec
|
<filename>BottomDrawerView.podspec
#
# Be sure to run `pod spec lint BottomDrawerView.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see https://guides.cocoapods.org/syntax/podspec.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |spec|
spec.name = "BottomDrawerView"
spec.version = "0.4.5"
spec.summary = "A versatile draggable bottom drawer. CocoaPods library written in swift."
spec.description = <<-DESC
A dismissable bottom draggable view, use it for partial messages or options. A draggable UIViewController that sits on top of another UIViewController, giving it more functionality and options.
DESC
spec.homepage = "https://github.com/LorTos/BottomDrawerView"
spec.license = { :type => "MIT", :file => "LICENSE" }
spec.author = "LorTos"
spec.platform = :ios, "11.0"
spec.swift_versions = ["4.2", "5.0", "5.1", "5.2"]
spec.source = { :git => "https://github.com/LorTos/BottomDrawerView.git", :tag => "#{spec.version}" }
spec.source_files = "Sources/BottomDrawerView/*.swift"
end
|
salonlofts/spring-commands-specjour
|
lib/spring-commands-specjour.rb
|
<filename>lib/spring-commands-specjour.rb
if defined?(Spring.register_command)
require "spring/commands/specjour"
end
|
salonlofts/spring-commands-specjour
|
lib/spring/commands/specjour.rb
|
module Spring
module Commands
class Specjour
def env(*)
'test'
end
def exec_name
'specjour'
end
end
Spring.register_command 'specjour', Specjour.new
end
end
|
cbenattrue/INDEX
|
SY_20190727.rb
|
#
# DB Script Tool
# Ruby - 2019-07-27 11:00:03
#
# MODEL CLASSES FOR SY DATABASE
#!/usr/bin/ruby
# SY.rb -------------------------------------
#
# Ruby - Model Class - SY.SY
# 2019-07-27 10:57:35
#
class SY
#attr_accessor :SY
#
# Constructor
#
# Example:
# mySY = SY.new( val1, val2,.. )
#
def initialize(m_SY)
self.SY = m_SY
end
#
# Getters and Setters
#
def SY # getter
@SY
end
def SY=(m_SY) # setter
@SY = m_SY
end
#
# Methods
#
def to_s
super + ""
#"SY: #{@SY}"
end
end
|
suvajitgupta/Tasks
|
proxy-patch.rb
|
<filename>proxy-patch.rb
require 'net/http'
require 'net/https'
RootCA = '/etc/ssl/certs'
module SC
module Rack
# Rack application proxies requests as needed for the given project.
class Proxy
def initialize(project)
@project = project
@proxies = project.buildfile.proxies
end
def call(env)
url = env['PATH_INFO']
@proxies.each do |proxy, value|
if url.match(/^#{Regexp.escape(proxy.to_s)}/)
return handle_proxy(value, proxy.to_s, env)
end
end
return [404, {}, "not found"]
end
def handle_proxy(proxy, proxy_url, env)
origin_host = env['SERVER_NAME'] # capture the origin host for cookies
http_method = env['REQUEST_METHOD'].to_s.downcase
url = env['PATH_INFO']
params = env['QUERY_STRING']
# collect headers...
headers = {}
env.each do |key, value|
next unless key =~ /^HTTP_/
next if key =~/^HTTP_ACCEPT_ENCODING/ # we can't proxy gzip'd or zip'd stuff
key = key.gsub(/^HTTP_/,'').downcase.sub(/^\w/){|l| l.upcase}.gsub(/_(\w)/){|l| "-#{$1.upcase}"} # remove HTTP_, dasherize and titleize
headers[key] = value
end
# Rack documentation says CONTENT_TYPE and CONTENT_LENGTH aren't prefixed by HTTP_
headers['Content-Type'] = env['CONTENT_TYPE'] if env['CONTENT_TYPE']
headers['Content-Length'] = env['CONTENT_LENGTH'] if env['CONTENT_LENGTH']
http_host, http_port = proxy[:to].split(':')
http_port = '443' if http_port.nil? and proxy[:https]
http_port = '80' if http_port.nil?
# added 4/23/09 per <NAME>, corrects problem
# when making requests to virtual hosts
headers['Host'] = "#{http_host}:#{http_port}"
if proxy[:url]
url = url.sub(/^#{Regexp.escape proxy_url}/, proxy[:url])
end
http_path = [url]
http_path << params if params && params.size>0
http_path = http_path.join('?')
response = nil
no_body_method = %w(delete get copy head move options trace)
# headers.each do |key, value|
# SC.logger << " #{key}: #{value}\n"
# end
if proxy[:username] and proxy[:password]
SC.logger << "Using basic HTTP authentication\n"
headers['Authorization'] = 'Basic ' + ["#{proxy[:username]}:#{proxy[:password]}"].pack('m').strip
end
if proxy[:https]
# custom
headers['COOKIE'] = $cookies[http_host] if $cookies
SC.logger << "The Cookie is: #{headers['COOKIE']} for #{http_host}\n"
headers.delete("HOST")
SC.logger << "Sending HTTPS request\n"
http = ::Net::HTTP.new(http_host, http_port)
http.use_ssl = true
if File.directory? RootCA
http.ca_path = RootCA
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.verify_depth = 5
else
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
http.start do |http|
if no_body_method.include?(http_method)
response = http.send(http_method, http_path, headers)
else
http_body = env['rack.input'].gets || ''
response = http.send(http_method, http_path, http_body, headers)
end
end
SC.logger << "~ PROXY: #{http_method.upcase} #{response.code} #{url} -> https://#{http_host}:#{http_port}#{http_path}\n"
else
::Net::HTTP.start(http_host, http_port) do |http|
if no_body_method.include?(http_method)
response = http.send(http_method, http_path, headers)
else
http_body = env['rack.input'].gets || ''
response = http.send(http_method, http_path, http_body, headers)
end
end
SC.logger << "~ PROXY: #{http_method.upcase} #{response.code} #{url} -> http://#{http_host}:#{http_port}#{http_path}\n"
end
body = response.body
body = "[]" if body == nil
# display and construct specific response headers
response_headers = {}
ignore_headers = ['transfer-encoding', 'keep-alive', 'connection']
$cookies = {} unless $cookies
response.each do |key, value|
next if ignore_headers.include?(key.downcase)
# If this is a cookie, strip out the domain. This technically may
# break certain scenarios where services try to set cross-domain
# cookies, but those services should not be doing that anyway...
if key.downcase == 'set-cookie'
value.gsub!(/domain=[^\;]+\;? ?/,'')
value.gsub!(/expires=[^\;]+\;? ?/,'')
value.gsub!(/path=[^\;]+\;? ?/,'')
value.gsub!(/secure; HttpOnly, /,'')
$cookies[http_host] = value #get the cookie for other sessions
end
# Location headers should rewrite the hostname if it is included.
value.gsub!(/^https?:\/\/#{http_host}(:[0-9]+)?\//, "http://#{http_host}/") if key.downcase == 'location'
SC.logger << " #{key}: #{value}\n"
response_headers[key] = value
end
return [response.code, ::Rack::Utils::HeaderHash.new(response_headers), [body]]
end
end
end
end
|
suvajitgupta/Tasks
|
spec/login.rb
|
<gh_stars>1-10
# Tasks/Lebowski login tests
# Author: <NAME>, <NAME>
describe "Login using bad user name should fail" do
it "will confirm that an error message is displayed on a failed login attempt" do
App['login_panel'].should be_pane_attached
App['login_panel.login_error_message_label'].should have_value ''
App['login_panel.login_name_field',TextFieldView].type "InvalidLoginName"
App['login_panel.password_field'].type "InvalidPassword"
App['login_panel.signin_button'].click
end
it "will clear the login and password fields, error message disappears" do
puts "... login error = #{App['login_panel.login_error_message_label'].value}"
App.wait_until(60) do |it|
match = it['login_panel.login_error_message_label'].value =~ /Login failed/i
not match.nil?
end
App['login_panel.login_name_field'].clear
App['login_panel.password_field'].clear
end
end
describe "Add a new user" do
it "will confirm that there is a Guest Signup button" do
App['login_panel.guest_signup_button'].should have_title /Guest Sign Up/i
end
it "will open the Guest Signup panel" do
App['login_panel.guest_signup_button'].click
App['signup_panel'].wait_until {|it| it.is_pane_attached}
App['signup_panel.signup_prompt'].should have_value /Guest Sign Up/i
App['signup_panel.signup_button'].should_not be_enabled
App['signup_panel.signup_button'].should have_title /Sign Up/i
App['signup_panel.cancel_button'].should have_title /Cancel/i
end
it "will populate the user information in the Guest Signup panel and Cancel" do
App['signup_panel.full_name_label'].should have_value /Full Name:/i
App['signup_panel.full_name_field'].type "#{NEWUSERFULLNAME}"
App['signup_panel.login_name_label'].should have_value /Login Name:/i
App['signup_panel.login_name_field'].type NEWUSERLOGINNAME
App['signup_panel.cancel_button'].click
App['signup_panel'].wait_until {|it| !it.is_pane_attached}
App['signup_panel'].should_not be_visible_in_window
App['login_panel'].should be_visible_in_window
end
it "will login as guest user: #{NEWUSERLOGINNAME}" do
App['login_panel.login_name_field'].type NEWUSERLOGINNAME
App['login_panel.signin_button'].click
end
it "will confirm that the main pane is visible in window and the login panel is not" do
App['login_panel'].wait_until {|it| !it.is_pane_attached}
App['login_panel'].should_not be_pane_attached
App['main_pane'].should be_pane_attached
end
it "will confirm the current user logged in has a role of 'Guest'" do
App['core_tasks'].wait_until { |it| it.object?('currentUser') }
current_user = App['core_tasks.currentUser']
current_user.should have_role that_matches(/Guest/i)
end
end
describe "Log the user out of the application" do
it "will click on Logout from the Actions menu" do
App['actions_button'].click
App.wait_until { |it| it.responding_panes.one?(MenuPane) }
pane = App.responding_panes.find_first(MenuPane)
puts "... pane class = #{pane.class}, sc_class = #{pane.sc_class}"
puts "... pane menu items count = #{pane.menu_items.count}"
pane.menu_items.click /^L/i
App.wait_until {|it| it.key_pane.kind_of?(AlertPane) }
pane = App.key_pane AlertPane
pane.should have_message /Confirmation/i
pane.should have_description /Are you sure you want to log out from the application\?/i
pane.click_button 'Yes'
end
end
|
suvajitgupta/Tasks
|
spec/main.rb
|
# Tasks/Lebowski login tests
# Author: <NAME>, <NAME>
App = MainApplication.new \
:app_root_path => "/tasks",
:app_name => "Tasks",
:app_server_port => 4400,
:browser => :safari
App.start do |app|
app['isLoaded'] == true
# app.driver.run_script "window.ononbeforeunload = null"
end
App.move_to 1, 1 # Have a slight offset for Firefox so that the window will actually be moved
App.resize_to 1024, 768
require 'config'
require 'login'
|
suvajitgupta/Tasks
|
spec/config.rb
|
# Tasks/Lebowski login tests
# Author: <NAME>, <NAME>
App.define_path 'mainPane', 'mainPage.mainPane', MainPane
USER_NAME = "SA"
PASSWORD = ""
USER_ROLE = "Manager"
NEWUSERLOGINNAME = "guest"
NEWUSERFULLNAME = "Guest User"
App.define_framework 'core_tasks', 'CoreTasks'
App.define_path 'login_panel', 'loginPage.panel', PanelPane
App.define_paths_for 'login_panel' do |path|
path.define_path 'login_name_field', 'contentView.loginNameField', TextFieldView
path.define_path 'password_field', 'contentView.passwordField', TextFieldView
path.define_path 'signin_button', 'contentView.signinButton', ButtonView
path.define_path 'login_error_message_label', 'contentView.loginErrorMessageLabel', LabelView
path.define_path 'guest_signup_button', 'contentView.guestSignupButton', ButtonView
end
App.define_path 'signup_panel', 'signupPane', PanelPane
App.define_paths_for 'signup_panel' do |path|
path.define_path 'signup_prompt', 'contentView.signupPrompt', LabelView
path.define_path 'signup_button', 'contentView.signupButton', ButtonView
path.define_path 'cancel_button', 'contentView.cancelButton', ButtonView
path.define_path 'full_name_label', 'contentView.userInformation.fullNameLabel', LabelView
path.define_path 'full_name_field', 'contentView.userInformation.fullNameField', TextFieldView
path.define_path 'login_name_label', 'contentView.userInformation.loginNameLabel', LabelView
path.define_path 'login_name_field', 'contentView.userInformation.loginNameField', TextFieldView
path.define_path 'role_label', 'contentView.userInformation.roleLabel', LabelView
path.define_path 'role_field', 'contentView.userInformation.roleField', 'SC.SelectButtonView' # was SelectFieldView
path.define_path 'email_label', 'contentView.userInformation.emailLabel', LabelView
path.define_path 'email_field', 'contentView.userInformation.emailField', TextFieldView
path.define_path 'password_label', 'contentView.userInformation.passwordLabel', LabelView
path.define_path 'password_field', 'contentView.userInformation.passwordField', TextFieldView
end
App.define_path 'main_pane', 'mainPage.mainPane', MainPane
App.define_path 'actions_button', 'main_pane.masterDetailView.detailView.topToolbar.actionsButton', ButtonView
|
Tonkpils/celluloid-eventsource
|
spec/celluloid/eventsource/response_parser_spec.rb
|
require 'spec_helper'
RSpec.describe Celluloid::EventSource::ResponseParser do
let(:success_headers) {<<-eos
HTTP/1.1 200 OK
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 131
X_CASE_HEADER: foo
X_Mixed-Case: bar
x-lowcase-header: hello
eos
}
let(:error_headers) {<<-eos
HTTP/1.1 400 OK
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 131
eos
}
let(:response_string) { "#{success_headers}\n\n{'hello' : 'world'}\n"}
let(:parser) { subject }
def streamed(string)
stream = StringIO.new(string)
stream.each do |line|
yield line
end
end
it 'parses a complete http response' do
streamed(response_string) do |line|
parser << line
end
expect(parser.status).to eq(200)
expect(parser.headers?).to be_truthy
expect(parser.headers['Content-Type']).to eq('text/html; charset=UTF-8')
expect(parser.headers['Content-Length']).to eq("131")
end
it 'waits until the entire request is found' do
streamed(success_headers) do |line|
parser << line
end
expect(parser.status).to eq(200)
expect(parser.headers?).to be_falsey
expect(parser.headers).to be_nil
end
it 'makes response headers canonicalized' do
streamed(response_string) { |line| parser << line }
expected_headers = {
'X-Mixed-Case' => 'bar', 'Content-Type' => 'text/html; charset=UTF-8', 'Content-Length' => "131",
'X-Case-Header' => 'foo', 'X-Lowcase-Header' => "hello"
}
expect(parser.headers).to include(expected_headers)
end
end
|
Tonkpils/celluloid-eventsource
|
lib/celluloid/eventsource/version.rb
|
<reponame>Tonkpils/celluloid-eventsource
module Celluloid
class EventSource
VERSION = "0.3.0"
end
end
|
Tonkpils/celluloid-eventsource
|
lib/celluloid/eventsource/response_parser.rb
|
require 'http/parser'
module Celluloid
class EventSource
class ResponseParser
extend Forwardable
attr_reader :headers
delegate [:status_code, :<<] => :@parser
def initialize
@parser = Http::Parser.new(self)
@headers = nil
@chunk = ""
end
def headers?
!!@headers
end
def status
@parser.status_code
end
def on_headers_complete(headers)
@headers = canonical_headers(headers)
end
def on_body(chunk)
@chunk << chunk
end
def chunk
chunk = @chunk
unless chunk.empty?
@chunk = ""
end
chunk.to_s
end
private
def canonical_headers(headers)
headers.each_with_object({}) do |(key, value), canonicalized_headers|
name = canonicalize_header(key)
canonicalized_headers[name] = value
end
end
def canonicalize_header(name)
name.gsub('_', '-').split("-").map(&:capitalize).join("-")
end
end
end
end
|
Tonkpils/celluloid-eventsource
|
lib/celluloid/eventsource.rb
|
<gh_stars>1-10
require "celluloid/eventsource/version"
require 'celluloid/io'
require 'celluloid/eventsource/response_parser'
require 'uri'
module Celluloid
class EventSource
include Celluloid::IO
attr_reader :url, :with_credentials
attr_reader :ready_state
CONNECTING = 0
OPEN = 1
CLOSED = 2
execute_block_on_receiver :initialize
def initialize(uri, options = {})
self.url = uri
options = options.dup
@ready_state = CONNECTING
@with_credentials = options.delete(:with_credentials) { false }
@headers = default_request_headers.merge(options.fetch(:headers, {}))
@event_type_buffer = ""
@last_event_id_buffer = ""
@data_buffer = ""
@last_event_id = String.new
@reconnect_timeout = 10
@on = { open: ->{}, message: ->(_) {}, error: ->(_) {} }
@parser = ResponseParser.new
@chunked = false
yield self if block_given?
async.listen
end
def url=(uri)
@url = URI(uri)
end
def connected?
ready_state == OPEN
end
def closed?
ready_state == CLOSED
end
def listen
establish_connection
chunked? ? process_chunked_stream : process_stream
rescue IOError
# Closing the socket during read causes this exception and kills the actor
# We really don't wan to do anything if the socket is closed.
end
def close
@socket.close if @socket
@ready_state = CLOSED
end
def on(event_name, &action)
@on[event_name.to_sym] = action
end
def on_open(&action)
@on[:open] = action
end
def on_message(&action)
@on[:message] = action
end
def on_error(&action)
@on[:error] = action
end
private
MessageEvent = Struct.new(:type, :data, :last_event_id)
def ssl?
url.scheme == 'https'
end
def establish_connection
@socket = Celluloid::IO::TCPSocket.new(@url.host, @url.port)
if ssl?
@socket = Celluloid::IO::SSLSocket.new(@socket)
@socket.connect
end
@socket.write(request_string)
until @parser.headers?
@parser << @socket.readline
end
if @parser.status_code != 200
until @socket.eof?
@parser << @socket.readline
end
close
@on[:error].call({status_code: @parser.status_code, body: @parser.chunk})
return
end
handle_headers(@parser.headers)
end
def default_request_headers
{
'Accept' => 'text/event-stream',
'Cache-Control' => 'no-cache',
'Host' => url.host
}
end
def clear_buffers!
@data_buffer = ""
@event_type_buffer = ""
end
def dispatch_event(event)
unless closed?
@on[event.type] && @on[event.type].call(event)
end
end
def chunked?
@chunked
end
def process_chunked_stream
until closed? || @socket.eof?
handle_chunked_stream
end
end
def process_stream
until closed? || @socket.eof?
line = @socket.readline
line.strip.empty? ? process_event : parse_line(line)
end
end
def handle_chunked_stream
chunk_header = @socket.readline
bytes_to_read = chunk_header.to_i(16)
bytes_read = 0
while bytes_read < bytes_to_read do
line = @socket.readline
bytes_read += line.size
line.strip.empty? ? process_event : parse_line(line)
end
if !line.nil? && line.strip.empty?
process_event
end
end
def parse_line(line)
case line
when /^:.*$/
when /^(\w+): ?(.*)$/
process_field($1, $2)
else
if chunked? && !@data_buffer.empty?
@data_buffer.rstrip!
process_field("data", line.rstrip)
end
end
end
def process_event
@last_event_id = @last_event_id_buffer
return if @data_buffer.empty?
@data_buffer.chomp!("\n") if @data_buffer.end_with?("\n")
event = MessageEvent.new(:message, @data_buffer, @last_event_id)
event.type = @event_type_buffer.to_sym unless @event_type_buffer.empty?
dispatch_event(event)
ensure
clear_buffers!
end
def process_field(field_name, field_value)
case field_name
when "event"
@event_type_buffer = field_value
when "data"
@data_buffer << field_value.concat("\n")
when "id"
@last_event_id_buffer = field_value
when "retry"
if /^(?<num>\d+)$/ =~ field_value
@reconnect_timeout = num.to_i
end
end
end
def handle_headers(headers)
if headers['Content-Type'].include?("text/event-stream")
@chunked = !headers["Transfer-Encoding"].nil? && headers["Transfer-Encoding"].include?("chunked")
@ready_state = OPEN
@on[:open].call
else
close
@on[:error].call({status_code: @parser.status_code, body: "Invalid Content-Type #{headers['Content-Type']}. Expected text/event-stream"})
end
end
def request_string
headers = @headers.map { |k, v| "#{k}: #{v}" }
["GET #{url.request_uri} HTTP/1.1", headers].flatten.join("\r\n").concat("\r\n\r\n")
end
end
end
|
Tonkpils/celluloid-eventsource
|
spec/support/dummy_server.rb
|
require 'webrick'
require 'atomic'
require 'json'
require 'support/black_hole'
class DummyServer < WEBrick::HTTPServer
CHUNK_SIZE = 100
CONFIG = {
:BindAddress => '127.0.0.1',
:Port => 5000,
:AccessLog => BlackHole,
:Logger => BlackHole,
:DoNotListen => true,
:OutputBufferSize => CHUNK_SIZE
}.freeze
def initialize(options = {})
super(CONFIG)
mount('/', SSETestServlet)
mount('/error', ErrorServlet)
end
def endpoint
"#{scheme}://#{addr}:#{port}"
end
def addr
config[:BindAddress]
end
def port
config[:Port]
end
def scheme
'http'
end
# Simple server that broadcasts Time.now
class SSETestServlet < WEBrick::HTTPServlet::AbstractServlet
def initialize(*args)
@event_id = Atomic.new(0)
super
end
def do_GET(req, res)
event = String(Array(req.path.match(/\/?(\w+)/i)).pop).to_sym
res.content_type = 'text/event-stream; charset=utf-8'
res['Cache-Control'] = 'no-cache'
r,w = IO.pipe
res.body = r
res.chunked = true
t = Thread.new do
begin
w << "retry: 1000\n"
case event
when :continuous_chunks
data = "data: %s\ndata: %s\ndata: %s\n\n" % ["o" * CHUNK_SIZE, "m" * CHUNK_SIZE, "g" * CHUNK_SIZE]
w << data
when :multiple_chunks
data = {test: "long_chunk", another_chunk: "a" * CHUNK_SIZE, chunks: "f" * CHUNK_SIZE}.to_json
w << "data: #{data}\n\n"
when :continuous
w << "data: YHOO\ndata: +2\ndata: 10\n\n"
when :chunk
data = "f" * (CHUNK_SIZE + 25)
w << "data: %s\n\n" % data
when :ping
w << ": ignore this line\n"
w << "event: \ndata: pong\n\n" # easy way to know a 'ping' has been sent
else
42.times do
w << "id: %s\nevent: %s\ndata: %s\n\n" % [ @event_id.update { |v| v + 1 },
event,
Time.now ]
end
w << "event: %s\ndata: %s\n\n" % %w(end end)
end
rescue => ex
puts $!.inspect, $@ unless ex.is_a?(Errno::EPIPE)
ensure
w.close
end
end
end
end
class ErrorServlet < WEBrick::HTTPServlet::AbstractServlet
def do_GET(req, res)
res.content_type = 'application/json; charset=utf-8'
res.status = 400
res.keep_alive = false # true by default
res.body = '{"msg": "blop"}'
end
end
end
|
anotheren/SwiftyHash
|
SwiftyHash.podspec
|
Pod::Spec.new do |s|
s.name = "SwiftyHash"
s.version = "1.0"
s.summary = "A Swifty wrapper for CommonCrypto"
s.homepage = "https://github.com/anotheren/SwiftyHash"
s.license = { :type => "MIT" }
s.author = { "liudong" => "<EMAIL>" }
s.requires_arc = true
s.ios.deployment_target = "8.0"
s.source = { :git => "https://github.com/anotheren/SwiftyHash.git",
:tag => s.version }
s.source_files = "Source/*.swift"
end
|
rails753developer/find_mass_assignment
|
lib/tasks/find_mass_assignment_tasks.rake
|
<reponame>rails753developer/find_mass_assignment<filename>lib/tasks/find_mass_assignment_tasks.rake
desc "Find potential mass assignment vulnerabilities"
task :find_mass_assignment do
require File.join(File.dirname(__FILE__), "../find_mass_assignment.rb")
MassAssignment.find
end
|
rails753developer/find_mass_assignment
|
lib/unsafe_build_and_create.rb
|
class ActiveRecord::Base
# Build and create records unsafely, bypassing attr_accessible.
# These methods are especially useful in tests and in the console.
# Inspired in part by http://pastie.textmate.org/104042
class << self
# Make a new record unsafely.
# This replaces new/build. For example,
# User.unsafe_new(:admin => true)
# works even if 'admin' isn't attr_accessible.
def unsafe_new(attrs = {})
record = new
record.unsafe_attributes = attrs
record
end
# Allow an unsafe build.
# For example,
# @blog.posts.unsafe_build(:published => true)
# works even if 'published' isn't attr_accessible.
alias_method :unsafe_build, :unsafe_new
# Create a record unsafely.
# For example,
# User.unsafe_create(:admin => true)
# works even if 'admin' isn't attr_accessible.
def unsafe_create(attrs)
record = unsafe_build(attrs)
record.save
record
end
# Same as unsafe_create, but raises an exception on error
# The analogy to create/create! is exact.
def unsafe_create!(attrs)
record = unsafe_build(attrs)
record.save!
record
end
end
# Update attributes unsafely.
# For example,
# @user.unsafe_update_attributes(:admin => true)
# works even if 'admin' isn't attr_accessible.
def unsafe_update_attributes(attrs)
self.unsafe_attributes = attrs
save
end
# Same as unsafe_update_attributes, but raises an exception on error
def unsafe_update_attributes!(attrs)
self.unsafe_attributes = attrs
save!
end
# Set attributes unsafely, bypassing attr_accessible.
def unsafe_attributes=(attrs)
raise attr_accessible_error unless attr_accessible_defined?
attrs.each do |k, v|
send("#{k}=", v)
end
end
private
def attr_accessible_defined?
!self.class.accessible_attributes.nil?
end
def attr_accessible_error
"#{self.class.name} is not protected by attr_accessible"
end
end
|
rails753developer/find_mass_assignment
|
init.rb
|
require File.join(File.dirname(__FILE__), "lib", "unsafe_build_and_create")
|
wvk/railsdav
|
lib/railsdav/renderer.rb
|
# encoding: utf-8
require 'builder'
if Rails.version > '4.0'
require 'active_support'
require 'active_support/core_ext/hash/conversions'
end
module Railsdav
class Renderer
autoload :ResourceDescriptor, 'railsdav/renderer/resource_descriptor'
autoload :ResponseCollector, 'railsdav/renderer/response_collector'
autoload :ResponseTypeSelector, 'railsdav/renderer/response_type_selector'
# Return the webdav metadata for a given URL/path
#
# If the given route is recognized, a controller and action can be identified.
# To get the properties for that URI, we lookup the metadata
# specified in the target controller (see #enable_webdav_for)
#
def self.webdav_metadata_for_url(routing_data)
controller = "#{routing_data[:controller]}_controller".camelize.constantize
controller ? controller.webdav_metadata_for_action(routing_data[:action]) : nil
end
attr_accessor :depth
# Create a new Renderer instance that will render an XML multistatus response.
#
# Arguments:
# controller: the current controller instance
#
def initialize(controller)
@controller = controller
@request = controller.request
# @depth = (@request.headers['Depth'].to_i > 0) ? 1 : 0 # depth "infinite" is not yet supported
@depth = (@request.headers['Depth'].to_i)
Rails.logger.debug "Depth:#{@request.headers['Depth']}"
end
# Render the requested response_type.
#
# Arguments:
# response_type: currently either :propstat or :response.
# options:
# - for response: :href, :status, :error (see #response)
# - for propstat: :size, :format, :created_at, :updated_at, :resource_layout, ... (see #propstat)
def respond_with(response_type, options = {})
self.send response_type, options
end
protected
def request_format
if @controller.params[:format].blank?
if @controller.webdav_metadata_for_current_action[:collection]
return :collection
else
return @controller.request_format
end
else
return @controller.params[:format]
end
end
def render
@dav = Builder::XmlMarkup.new :indent => 2
@dav.instruct!
@dav.tag!("D:multistatus", "xmlns:D" => 'DAV:') do
yield @dav
end
@dav.target!
end
# Render a WebDAV multistatus response with a single "response" element.
# This is primarily intended vor responding to single resource errors.
#
# Arguments:
# options:
# - href: the requested resource URL, usually request.url
# - status: the response status, something like :unprocessable_entity or 204.
# - error: an Error description, if any.
#
def response(options = {})
elements = options.slice(:error)
render do
response_for options[:href] do |dav|
elements.each do |name, value|
status_for options[:status]
dav.__send__ name, value
end
end
end
end
def status_for(status)
code = Rack::Utils.status_code(status || :ok)
status = "HTTP/1.1 #{code} #{Rack::Utils::HTTP_STATUS_CODES[code]}"
@dav.tag! "D:status", status
end
# Allows you to `render :webdav => :not_found` and get a 404
# status properly embedded inside multi-status
def not_found(options = {})
render do |dav|
status_for 404
end
end
# Render a WebDAV multistatus response with a "response" element per resource
# TODO: explain the magic implemented here
# Arguments:
# TODO: describe valid arguments
#
def propstat(options = {})
response_collector = ResponseCollector.new(@controller, self.request_format)
# retrieve properties for this resource and all subresources if this is a collection
if options[:respond_to_block]
options[:respond_to_block].call(response_collector)
end
render do |dav|
propstat_for response_collector.resource
propstat_for response_collector.subresources if @depth >= 0
end
end
private
def propstat_for(*resources)
params = @controller.params.dup
if params[:propfind]
# OK
elsif @controller.request.body.size > 0 # rails version without automatic XML body params parsing, so do it by hand here:
@controller.request.body.rewind
params.merge! Hash.from_xml(@controller.request.body.read)
end
params[:propfind] ||= {:prop => []}
if params[:propfind].respond_to? :to_unsafe_h
propfind_params = params[:propfind].to_unsafe_h
else
propfind_params = params[:propfind]
end
if propfind_params.has_key? 'allprop'
requested_properties = nil # fill it later, see below.
else
requested_properties = propfind_params[:prop]
end
resources.flatten.each do |resource|
hash = resource.props
case hash[:updated_at]
when Time, DateTime
updated_at = hash[:updated_at]
when String
updated_at = Time.parse(hash[:updated_at])
else
updated_at = Time.now
end
# note: all of these are assumed to be from the DAV:
# namespace!
response_hash = {
:quota_used_bytes => 0,
:quota_available_bytes => 10.gigabytes,
:creationdate => updated_at.iso8601,
:getlastmodified => updated_at.rfc2822,
:getcontentlength => hash[:size],
:getcontenttype => hash[:format].to_s
}
if resource.collection?
response_hash[:resourcetype] = proc { @dav.tag! "D:collection" } # must be block to render <collection></collection> instead of "collection"
response_hash[:getcontenttype] = nil
end
requested_properties ||= response_hash.keys
# as a workaround for another bug in Flycode's WebDAV module,
# which expects (because of how it does element name matching)
# that the properties are always returned with a specified
# namespace prefix. Now, the original Railsdav makes a
# slightly careless assumption of its own; it just directly
# matches element names in its fixed list, counting on (and
# there are none so far) collisions between property names
# from various name spaces. As such, it just assumes that if
# the property name is discrimated by a namespace, the client
# has only done so by putting a non-prefixed `xmlns` attribute
# on the propfind properties (ie., it did not try to use a
# prefix itself). Railsdav really should track and match
# properties by both name *and* namespace, in order to be
# properly compliant.
# So, back to the Flycode WebDAV bug: we work around this here
# by collecting all of the requested properties, gathering the
# namespaces from them, and defining them *all* as prefixes.
# all of our built-in properties are in the DAV namespace
# anyway:
gathered_namespaces = {}
@namespace_counter ||= 1
namespaced_requested_properties = {}
Rails.logger.debug requested_properties.inspect
requested_properties.each do |prop_name, opts|
if prop_name.to_s.include?(':')
# see first paragraph of long comment above
Rails.logger.warn 'DAV propfind prop request contains a namespace prefix; we do NOT handle these properly yet!'
end
if opts and opts['xmlns']
gathered_namespaces["xmlns:lp#{@namespace_counter}"] = opts['xmlns']
opts.delete 'xmlns'
namespaced_requested_properties["lp#{@namespace_counter}:#{prop_name}"] = opts
@namespace_counter +=1
else
# just copy it through; however, we'll assume it's in the
# DAV namespace (which we hardcoded to the `D` prefix).
namespaced_requested_properties["D:#{prop_name}"] = opts
end
end
response_for(resource.url) do |dav|
dav.tag! 'D:propstat', gathered_namespaces do
status_for hash[:status]
dav.tag! 'D:prop' do
namespaced_requested_properties.each do |both_prop_name, opts|
prop_space_and_name_pair = both_prop_name.split(':')
prop_name = prop_space_and_name_pair[1] || prop_space_and_name_pair[0]
if prop_val = response_hash[prop_name.to_sym]
if prop_val.respond_to? :call
if opts
dav.tag! both_prop_name, opts.to_h, &prop_val
else
dav.tag! both_prop_name, &prop_val
end
else
dav.tag! both_prop_name, prop_val, opts.to_h
end
elsif opts
dav.tag! both_prop_name, opts
else
dav.tag! both_prop_name
end
end # requested_properties.each
end # dav.prop
end # dav.propstat
end # dav.response_for
end # resource_layout.keys.each
end # def propstat_for
def response_for(href)
@dav.tag! 'D:response' do
@dav.tag! 'D:href', href
yield @dav
end
end
end # class Railsdav
end # module Railsdav
|
wvk/railsdav
|
lib/railsdav/renderer/response_type_selector.rb
|
<filename>lib/railsdav/renderer/response_type_selector.rb
# encoding: utf-8
module Railsdav
class Renderer
class ResponseTypeSelector
attr_reader :subresources, :resource_options
def initialize(controller, request_format)
@controller, @request_format = controller, request_format
@subresources = []
# TODO: somehow allow passing more options to current resource
@resource_options = {:format => @request_format.to_sym}
end
def format(name, options)
if Mime::Type.lookup_by_extension(name.to_s)
if @request_format.to_sym == name
# TODO: somehow get the attributes (size, updated-at, ...) from the actual Mime responder block here
@resource_options.merge! options
end
else
raise UnknownMimeTypeExtension, "#{name} is not a valid MIME type file extension."
end
end
# loop over all urls marked as subresources in webdav responder block
# and add them with all their acceptable mime types
def subresource(*subresources)
return unless @request_format == :collection
options = subresources.extract_options!
subresources.each do |resource_url|
relative_resource_url = resource_url.sub %r(^#{ActionController::Base.relative_url_root}), '' # HACK
route = Rails.application.routes.recognize_path(relative_resource_url)
if meta = Renderer.webdav_metadata_for_url(route)
# show the resource as a collection unless disabled
if meta[:collection]
@subresources << Renderer::ResourceDescriptor.new(resource_url, options.merge(:format => :collection))
elsif meta[:accept].blank?
# show the resource without .:format suffix, but not as a collection
@subresources << Renderer::ResourceDescriptor.new(resource_url, options)
end
# show the resource with all the specified format suffixes
if meta[:accept]
[meta[:accept]].flatten.each do |type_name|
mime_type = Mime::Type.lookup_by_extension(type_name)
subresource_url = @controller.url_for(route.merge(:format => type_name))
@subresources << Renderer::ResourceDescriptor.new(subresource_url, options.merge(:format => mime_type))
end
end
else
raise MissingWebDAVMetadata, "no WebDAV metadata found for #{resource_url}, please specify it using #enable_webdav_for"
end
end
@resource_options[:size] = @subresources.size
end
end
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
spec/converters/roman_to_arabic_converter_spec.rb
|
require 'spec_helper'
RSpec.describe Merchant::RomanToArabicConverter do
examples = {
'I' => 1,
'II' => 2,
'III' => 3,
'IV' => 4,
'V' => 5,
'VI' => 6,
'IX' => 9,
'XXVII' => 27,
'XLVIII' => 48,
'LIX' => 59,
'XCIII' => 93,
'CXXIII' => 123,
'CXLI' => 141,
'CLXIII' => 163,
'CDII' => 402,
'DLXXV' => 575,
'CMXI' => 911,
'MXXIV' => 1024,
'MMM' => 3000,
'MMMCMXCIX' => 3999
}
examples.each do |roman, arabic|
it "converts #{roman} to #{arabic}" do
expect(subject.convert(roman)).to eq(arabic)
end
end
it 'raises an error converting invalid roman numerals' do
expect { subject.convert('MMMM') }.to raise_error(
'Can not convert roman numeral MMMM to arabic'
)
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
lib/merchant/nodes/commodity_conversion.rb
|
<gh_stars>0
module Merchant
class CommodityConversion
attr_reader :from_commodity, :to_commodity, :galactic
def initialize(from_commodity, to_commodity, galactic)
@from_commodity = from_commodity
@to_commodity = to_commodity
@galactic = galactic
end
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
lib/merchant.rb
|
require 'merchant/converters/roman_to_arabic_converter'
require 'merchant/models/commodity'
require 'merchant/parser'
require 'merchant/version'
%w[nodes services].each do |dir|
Dir["#{File.dirname(__FILE__)}/merchant/#{dir}/*.rb"].each do |file|
require file
end
end
require 'merchant/galactic_trade'
require 'merchant/cli'
|
ChrisWilding/merchants-guide-to-the-galaxy
|
spec/services/galatic_to_roman_service_spec.rb
|
require 'spec_helper'
RSpec.describe Merchant::GalacticToRomanService do
context 'handles?' do
it 'returns true for TranslationDefinition nodes' do
node = Merchant::TranslationDefinition.new('glob', 'I')
expect(subject.handles?(node)).to be_truthy
end
it 'returns false for other nodes' do
node = Merchant::UnknownDefinitionOrQuery.new
expect(subject.handles?(node)).to be_falsey
end
end
it 'process returns nil' do
node = Merchant::TranslationDefinition.new('glob', 'I')
expect(subject.process(node)).to be_nil
end
context 'when it has processed the nodes' do
before do
nodes = [
Merchant::TranslationDefinition.new('glob', 'I'),
Merchant::TranslationDefinition.new('prok', 'V'),
Merchant::TranslationDefinition.new('pish', 'X'),
Merchant::TranslationDefinition.new('tegj', 'L')
]
nodes.each { |node| subject.process(node) }
end
it 'transalates a galactic numeral' do
expect(subject.translate_numeral('pish')).to eq('X')
end
it 'transalates a string of galactic numerals' do
str = 'pish tegj prok glob'
expect(subject.translate_numerals(str)).to eq('XLVI')
end
end
it 'raises an error when it can not translate a galactic numeral' do
expect { subject.translate_numeral('BANG') }.to raise_error(
'Can not translate invalid numeral BANG'
)
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
spec/models/commodity_spec.rb
|
require 'spec_helper'
RSpec.describe Merchant::Commodity do
let(:name) { 'Sausages' }
subject { described_class.new(450, name, 4950) }
it 'has a name' do
expect(subject.name).to eq(name)
end
it 'returns the unit price in credits' do
expect(subject.credits).to eq(11)
end
context 'when the unit price is a decimal' do
subject { described_class.new(4, name, 782) }
it 'returns the price as a decimal' do
expect(subject.credits).to eq(BigDecimal.new('195.5'))
end
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
spec/services/galatic_to_arabic_service_spec.rb
|
<reponame>ChrisWilding/merchants-guide-to-the-galaxy
require 'spec_helper'
RSpec.describe Merchant::GalacticToArabicService do
subject do
galactic_to_roman_service = Merchant::GalacticToRomanService.new
nodes = [
Merchant::TranslationDefinition.new('glob', 'I'),
Merchant::TranslationDefinition.new('prok', 'V'),
Merchant::TranslationDefinition.new('pish', 'X'),
Merchant::TranslationDefinition.new('tegj', 'L')
]
nodes.each { |node| galactic_to_roman_service.process(node) }
described_class.new(galactic_to_roman_service)
end
context 'handles?' do
it 'returns true for TranslationQuery nodes' do
node = Merchant::TranslationQuery.new('glob')
expect(subject.handles?(node)).to be_truthy
end
it 'returns false for other nodes' do
node = Merchant::UnknownDefinitionOrQuery.new
expect(subject.handles?(node)).to be_falsey
end
end
it 'converts galactic numerals to arabic' do
expect(subject.convert('tegj pish prok glob')).to eq(66)
end
[
[
Merchant::TranslationQuery.new('pish tegj glob glob'),
'pish tegj glob glob is 42'
],
[
Merchant::TranslationQuery.new('glob glob'),
'glob glob is 2'
]
].each do |node, expected|
it 'process returns the galactic numeral value in arabic numerals' do
expect(subject.process(node)).to eq(expected)
end
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
lib/merchant/services/price_query_service.rb
|
module Merchant
class PriceQueryService
def initialize(galactic_to_arabic_service, price_definition_service)
@galactic_to_arabic_service = galactic_to_arabic_service
@price_definition_service = price_definition_service
end
def handles?(node)
node.is_a?(PriceQuery)
end
def process(node)
arabic = @galactic_to_arabic_service.convert(node.galactic)
price = @price_definition_service.price_of(node.commodity)
"#{node.galactic} #{node.commodity} is #{Integer(arabic * price)} Credits"
end
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
lib/merchant/nodes/translation_definition.rb
|
<gh_stars>0
module Merchant
class TranslationDefinition
attr_reader :galactic, :roman
def initialize(galactic, roman)
@galactic = galactic
@roman = roman
end
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
lib/merchant/services/galactic_to_roman_service.rb
|
<reponame>ChrisWilding/merchants-guide-to-the-galaxy
module Merchant
class GalacticToRomanService
def initialize
@lookup = {}
end
def handles?(node)
node.is_a?(TranslationDefinition)
end
def process(node)
@lookup[node.galactic] = node.roman
nil
end
def translate_numeral(str)
roman = @lookup[str]
raise "Can not translate invalid numeral #{str}" unless roman
roman
end
def translate_numerals(str)
str.split.collect do |numeral|
translate_numeral(numeral)
end.join
end
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
spec/nodes/translation_definition_spec.rb
|
require 'spec_helper'
RSpec.describe Merchant::TranslationDefinition do
subject do
described_class.new('prok', 'V')
end
it 'has a galactic property' do
expect(subject.galactic).to eq('prok')
end
it 'has a roman property' do
expect(subject.roman).to eq('V')
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
lib/merchant/nodes/translation_query.rb
|
<filename>lib/merchant/nodes/translation_query.rb
module Merchant
class TranslationQuery
attr_reader :galactic
def initialize(galactic)
@galactic = galactic
end
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
lib/merchant/nodes/price_definition.rb
|
<filename>lib/merchant/nodes/price_definition.rb
module Merchant
class PriceDefinition
attr_reader :commodity, :credits, :galactic
def initialize(galactic, commodity, credits)
@galactic = galactic
@commodity = commodity
@credits = credits
end
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
lib/merchant/nodes/unknown_defintion_or_query.rb
|
<filename>lib/merchant/nodes/unknown_defintion_or_query.rb
module Merchant
class UnknownDefinitionOrQuery
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
lib/merchant/parser.rb
|
require 'strscan'
module Merchant
class Parser
COMMODITY_CONVERSION = /how many .* is .* \?/
NEWLINE = /\n/
NEWLINE_OR_EOS = /#{NEWLINE}|$/
PRICE_DEFINITION = /^.* is \d+ Credits$/
PRICE_QUERY = /^how many Credits is .* \?$/
ROMAN = /I|V|X|L|C|D|M/
IS = / is /
TRANSLATION_DEFINITION = /^\w+ is #{ROMAN}$/
TRANSLATION_QUERY = /^how much is .* \?$/
MAPPING = {
parse_price_definition: PRICE_DEFINITION,
parse_price_query: PRICE_QUERY,
parse_translation_definition: TRANSLATION_DEFINITION,
parse_translation_query: TRANSLATION_QUERY,
parse_commodity_conversion: COMMODITY_CONVERSION
}.freeze
attr_reader :ast
def initialize(input)
@scanner = StringScanner.new(input)
@ast = []
end
def parse
default = -> { :parse_unknown_definition_or_query }
until scanner.eos?
method, = MAPPING.find(default) do |_, regexp|
scanner.match?(regexp)
end
send(method)
end
ast
end
private
attr_reader :scanner
def parse_translation_definition
galactic = scanner.scan_until(IS).chomp(IS.source)
roman = scanner.scan(ROMAN).strip
ast << TranslationDefinition.new(galactic, roman)
scanner.skip_until(NEWLINE_OR_EOS)
end
def parse_price_definition
*galactic, commodity = scanner.scan_until(IS).chomp(IS.source).split
credits = scanner.scan(/\d+/)
ast << PriceDefinition.new(galactic.join(' '), commodity, credits)
scanner.skip_until(NEWLINE_OR_EOS)
end
def parse_translation_query
scanner.skip(/how much is /)
galactic = scanner.scan_until(/\?/).chomp('?').strip
ast << TranslationQuery.new(galactic)
scanner.skip_until(NEWLINE_OR_EOS)
end
def parse_price_query
scanner.skip(/how many Credits is /)
*galactic, commodity = scanner.scan_until(/\?/).chomp('?').split
ast << PriceQuery.new(galactic.join(' '), commodity)
scanner.skip(NEWLINE_OR_EOS)
end
def parse_unknown_definition_or_query
scanner.skip_until(NEWLINE_OR_EOS)
ast << UnknownDefinitionOrQuery.new
end
def parse_commodity_conversion
scanner.skip(/how many /)
from_commodity = scanner.scan_until(IS).chomp(IS.source)
*galactic, to_commodity = scanner.scan_until(/\?/).chomp('?').split
ast << CommodityConversion.new(
from_commodity, to_commodity, galactic.join(' ')
)
scanner.skip(NEWLINE_OR_EOS)
end
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
lib/merchant/services/galactic_to_arabic_service.rb
|
<gh_stars>0
module Merchant
class GalacticToArabicService
def initialize(galactic_to_roman_service)
@roman_to_arabic_converter = RomanToArabicConverter.new
@galactic_to_roman_service = galactic_to_roman_service
end
def convert(galactic)
roman = @galactic_to_roman_service.translate_numerals(galactic)
@roman_to_arabic_converter.convert(roman)
end
def handles?(node)
node.is_a?(TranslationQuery)
end
def process(node)
galactic = node.galactic
arabic = convert(galactic)
"#{galactic} is #{arabic}"
end
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
lib/merchant/cli.rb
|
module Merchant
class CLI
def run
if ARGV.length == 1
input = File.read(ARGV[0])
galactic_trade = GalacticTrade.new
puts galactic_trade.conduct(input)
else
puts 'Usage: merchant ./path/to/input.txt'
end
end
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
spec/galatic_trade_spec.rb
|
<reponame>ChrisWilding/merchants-guide-to-the-galaxy
require 'spec_helper'
RSpec.describe Merchant::GalacticTrade do
input = 'glob is I
prok is V
pish is X
tegj is L
glob glob Silver is 34 Credits
glob prok Gold is 57800 Credits
pish pish Iron is 3910 Credits
how much is pish tegj glob glob ?
how many Credits is glob prok Silver ?
how many Credits is glob prok Gold ?
how many Credits is glob prok Iron ?
how much wood could a woodchuck chuck if a woodchuck could chuck wood ?'
expected = 'pish tegj glob glob is 42
glob prok Silver is 68 Credits
glob prok Gold is 57800 Credits
glob prok Iron is 782 Credits
I have no idea what you are talking about'
it 'conducts galactic trade' do
result = subject.conduct(input)
expect(result).to eq(expected)
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
spec/nodes/unknown_defintion_or_translation_spec.rb
|
<gh_stars>0
require 'spec_helper'
RSpec.describe Merchant::UnknownDefinitionOrQuery do
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
spec/nodes/price_query_spec.rb
|
require 'spec_helper'
RSpec.describe Merchant::PriceQuery do
subject do
described_class.new('glob glob', 'Silver')
end
it 'has a commodity property' do
expect(subject.commodity).to eq('Silver')
end
it 'has a galactic property' do
expect(subject.galactic).to eq('glob glob')
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
lib/merchant/models/commodity.rb
|
<reponame>ChrisWilding/merchants-guide-to-the-galaxy<filename>lib/merchant/models/commodity.rb<gh_stars>0
require 'bigdecimal'
module Merchant
class Commodity
attr_reader :credits, :name
def initialize(number, name, credits)
@credits = BigDecimal.new(credits) / BigDecimal.new(number)
@name = name
end
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
lib/merchant/services/unknown_definition_or_query_service.rb
|
module Merchant
class UnknownDefinitionOrQueryService
def handles?(node)
node.is_a?(UnknownDefinitionOrQuery)
end
def process(_)
'I have no idea what you are talking about'
end
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
spec/cli_spec.rb
|
require 'spec_helper'
RSpec.describe Merchant::CLI do
expected = 'pish tegj glob glob is 42
atre mpor hnga is 1600
glob prok Silver is 68 Credits
glob prok Gold is 57800 Credits
glob prok Iron is 782 Credits
I have no idea what you are talking about'
it 'loads the file and conducts the galactic trade' do
ARGV.replace(["#{File.dirname(__FILE__)}/../fixtures/input.txt"])
expect(STDOUT).to receive(:puts).with(expected)
subject.run
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
spec/services/price_definition_service_spec.rb
|
require 'spec_helper'
RSpec.describe Merchant::PriceDefinitionService do
subject do
galactic_to_roman_service = Merchant::GalacticToRomanService.new
galactic_to_roman_service.process(
Merchant::TranslationDefinition.new('glob', 'I')
)
galactic_to_arabic_service = Merchant::GalacticToArabicService.new(
galactic_to_roman_service
)
described_class.new(galactic_to_arabic_service)
end
context 'handles?' do
it 'returns true for PriceDefinition nodes' do
node = Merchant::PriceDefinition.new('glob', 'Silver', '38')
expect(subject.handles?(node)).to be_truthy
end
it 'returns false for other nodes' do
node = Merchant::UnknownDefinitionOrQuery.new
expect(subject.handles?(node)).to be_falsey
end
end
context 'process' do
let!(:result) do
node = Merchant::PriceDefinition.new('glob glob', 'Silver', '34')
subject.process(node)
end
it 'calculates the unit price in credits for a commodity' do
expect(subject.price_of('Silver')).to eq(17)
end
it 'returns nil' do
expect(result).to be_nil
end
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
spec/nodes/commodity_conversion_spec.rb
|
RSpec.describe Merchant::CommodityConversion do
subject do
described_class.new('Silver', 'Gold', 'glob')
end
it 'has a from commodity property' do
expect(subject.from_commodity).to eq('Silver')
end
it 'has a to commodity property' do
expect(subject.to_commodity).to eq('Gold')
end
it 'has a galactic property' do
expect(subject.galactic).to eq('glob')
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
lib/merchant/services/price_definition_service.rb
|
module Merchant
class PriceDefinitionService
def initialize(galactic_to_arabic_service)
@galactic_to_arabic_service = galactic_to_arabic_service
@lookup = {}
end
def handles?(node)
node.is_a?(PriceDefinition)
end
def process(node)
arabic = @galactic_to_arabic_service.convert(node.galactic)
commodity = Merchant::Commodity.new(arabic, node.commodity, node.credits)
@lookup[commodity.name] = commodity.credits
nil
end
def price_of(name)
credits = @lookup[name]
raise "No price of #{name}" unless credits
credits
end
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
lib/merchant/converters/roman_to_arabic_converter.rb
|
module Merchant
class RomanToArabicConverter
MAPPING = {
'M' => 1000,
'CM' => 900,
'D' => 500,
'CD' => 400,
'C' => 100,
'XC' => 90,
'L' => 50,
'XL' => 40,
'X' => 10,
'IX' => 9,
'V' => 5,
'IV' => 4,
'I' => 1
}.freeze
def initialize
pairs = 1.upto(3999).collect do |i|
roman = i_to_roman(i)
[roman, i]
end
@lookup = Hash[pairs]
end
def convert(roman)
arabic = @lookup[roman]
raise "Can not convert roman numeral #{roman} to arabic" unless arabic
arabic
end
private
def i_to_roman(i)
MAPPING.inject('') do |out, (roman, arabic)|
while i >= arabic
out << roman
i -= arabic
end
out
end
end
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
spec/services/price_query_service_spec.rb
|
require 'spec_helper'
RSpec.describe Merchant::PriceQueryService do
subject do
galactic_to_roman_service = Merchant::GalacticToRomanService.new
galactic_to_roman_service.process(
Merchant::TranslationDefinition.new('glob', 'I')
)
galactic_to_roman_service.process(
Merchant::TranslationDefinition.new('prok', 'V')
)
galactic_to_arabic_service = Merchant::GalacticToArabicService.new(
galactic_to_roman_service
)
price_definition_service = Merchant::PriceDefinitionService.new(
galactic_to_arabic_service
)
price_definition_service.process(
Merchant::PriceDefinition.new('glob glob', 'Silver', '34')
)
described_class.new(galactic_to_arabic_service, price_definition_service)
end
context 'handles?' do
it 'returns true for PriceQuery nodes' do
node = Merchant::PriceQuery.new('glob glob', 'Silver')
expect(subject.handles?(node)).to be_truthy
end
it 'returns false for other nodes' do
node = Merchant::UnknownDefinitionOrQuery.new
expect(subject.handles?(node)).to be_falsey
end
end
it 'process calculates the unit price in credits for a commodity' do
node = Merchant::PriceQuery.new('glob prok', 'Silver')
expect(subject.process(node)).to eq('glob prok Silver is 68 Credits')
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
spec/nodes/translation_query_spec.rb
|
<gh_stars>0
require 'spec_helper'
RSpec.describe Merchant::TranslationQuery do
let(:galactic) { 'prok' }
subject do
described_class.new(galactic)
end
it 'has a galactic property' do
expect(subject.galactic).to eq(galactic)
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
spec/services/unknown_definition_or_query_service.rb
|
<gh_stars>0
require 'spec_helper'
RSpec.describe Merchant::UnknownDefinitionOrQueryService do
context 'handles?' do
it 'returns true for UnknownDefinitionOrQuery nodes' do
node = Merchant::UnknownDefinitionOrQuery.new
expect(subject.handles?(node)).to be_truthy
end
it 'returns false for other nodes' do
node = Merchant::PriceQuery.new('glob glob', 'Silver')
expect(subject.handles?(node)).to be_falsey
end
end
it 'returns a message' do
node = Merchant::UnknownDefintionOrQuery.new
message = 'I have no idea what you are talking about'
expect(subject.process(node)).to eq(message)
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
lib/merchant/nodes/price_query.rb
|
<filename>lib/merchant/nodes/price_query.rb
module Merchant
class PriceQuery
attr_reader :commodity, :galactic
def initialize(galactic, commodity)
@galactic = galactic
@commodity = commodity
end
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
lib/merchant/galactic_trade.rb
|
<gh_stars>0
module Merchant
class GalacticTrade
def initialize
@galactic_to_roman_service = GalacticToRomanService.new
@galactic_to_arabic_service = GalacticToArabicService.new(
@galactic_to_roman_service
)
@price_definition_service = PriceDefinitionService.new(
@galactic_to_arabic_service
)
@price_query_service = PriceQueryService.new(
@galactic_to_arabic_service, @price_definition_service
)
end
def conduct(input)
ast = Parser.new(input).parse
ast.each_with_object([]) do |node, out|
service = services.find { |s| s.handles?(node) }
result = service.process(node)
out << result if result
end.join("\n")
end
private
def services
@services ||= [
@galactic_to_roman_service,
@galactic_to_arabic_service,
@price_definition_service,
@price_query_service,
UnknownDefinitionOrQueryService.new
]
end
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
spec/merchant_spec.rb
|
<gh_stars>0
require 'spec_helper'
RSpec.describe Merchant do
it 'has a version number' do
expect(Merchant::VERSION).not_to be nil
end
end
|
ChrisWilding/merchants-guide-to-the-galaxy
|
spec/parser_spec.rb
|
require 'spec_helper'
RSpec.describe Merchant::Parser do
it 'parses a translation definition' do
parser = described_class.new('prok is V')
translation_definition = parser.parse.first
expect(translation_definition.galactic).to eq('prok')
expect(translation_definition.roman).to eq('V')
end
it 'parses a price definition' do
parser = described_class.new('glob glob Silver is 34 Credits')
price_definition = parser.parse.first
expect(price_definition.galactic).to eq('glob glob')
expect(price_definition.commodity).to eq('Silver')
expect(price_definition.credits).to eq('34')
end
it 'parses a translation query' do
parser = described_class.new('how much is pish tegj glob glob ?')
translation_query = parser.parse.first
expect(translation_query.galactic).to eq('pish tegj glob glob')
end
it 'parses a price query' do
parser = described_class.new('how many Credits is glob prok Silver ?')
price_query = parser.parse.first
expect(price_query.galactic).to eq('glob prok')
expect(price_query.commodity).to eq('Silver')
end
it 'parses an unknown definition or query' do
parser = described_class.new(
'how much wood could a woodchuck chuck if a woodchuck could chuck wood ?'
)
unknown_definition_or_query = parser.parse.first
expect(unknown_definition_or_query).to be_a(
Merchant::UnknownDefinitionOrQuery
)
end
it 'parsers a commodity conversion' do
parser = described_class.new('how many Silver is glob Gold ?')
commodity_conversion = parser.parse.first
expect(commodity_conversion.from_commodity).to eq('Silver')
expect(commodity_conversion.to_commodity).to eq('Gold')
expect(commodity_conversion.galactic).to eq('glob')
end
it 'parses multiple items' do
parser = described_class.new("tegj is L\nglob glob Silver is 34 Credits")
translation_definition, price_definition = parser.parse
expect(translation_definition.galactic).to eq('tegj')
expect(translation_definition.roman).to eq('L')
expect(price_definition.galactic).to eq('glob glob')
expect(price_definition.commodity).to eq('Silver')
expect(price_definition.credits).to eq('34')
end
end
|
rajat2502/WikiEduDashboard
|
config/schedule.rb
|
<filename>config/schedule.rb
# Use this file to easily define all of your cron jobs.
#
# It's helpful, but not entirely necessary to understand cron before proceeding.
# http://en.wikipedia.org/wiki/Cron
# Example:
#
# set :output, '/path/to/my/cron_log.log'
#
# every 2.hours do
# command '/usr/bin/some_great_command'
# runner 'MyModel.some_method'
# rake 'some:great:rake:task'
# end
#
# every 4.days do
# runner 'AnotherModel.prune_old_records'
# end
# Learn more: http://github.com/javan/whenever
set :output, 'log/cron.log'
# Course updates will pull in revisions and articles for courses that are ongoing
# or still within the update window. They are sorted into queues depending on how
# long they run, with short courses having their own queue and very long ones their
# own as well.
every 5.minutes do
rake 'batch:schedule_course_updates'
end
# Constant updates are independent of the main course stats, pulling in revision
# metadata, generating alerts, and doing other data and network-intensive tasks,
# for all current courses.
every 4.minutes do
rake 'batch:update_constantly'
end
# This pulls in additional data and performs other tasks that do not need to be
# done many times per day.
every 1.day, at: '4:30 am' do
rake 'batch:update_daily'
end
every [:monday, :tuesday, :wednesday, :thursday], at: '10:15 am' do
rake 'batch:survey_update'
end
every [:monday, :tuesday, :wednesday, :thursday], at: '10:30 am' do
rake 'experiments:spring_2018_cmu_experiment'
end
every [:monday, :tuesday, :wednesday, :thursday, :friday], at: ['6:00 am', '1:00 pm'] do
rake 'batch:ticket_notifications'
end
|
rajat2502/WikiEduDashboard
|
spec/features/multiwiki_assignment_spec.rb
|
<filename>spec/features/multiwiki_assignment_spec.rb<gh_stars>1-10
# frozen_string_literal: true
require 'rails_helper'
describe 'multiwiki assignments', type: :feature, js: true do
let(:admin) { create(:admin) }
let(:course) { create(:course, submitted: true) }
let(:user) { create(:user) }
before do
page.current_window.resize_to(1920, 1080)
allow(Features).to receive(:disable_wiki_output?).and_return(true)
login_as(admin)
course.campaigns << Campaign.last
create(:courses_user, course_id: course.id, user_id: user.id,
role: CoursesUsers::Roles::STUDENT_ROLE)
end
it 'creates a valid assignment from a wiki URL' do
VCR.use_cassette 'multiwiki_assignment' do
visit "/courses/#{course.slug}/students/articles"
first('.student-selection .student').click
button = first('.assign-button')
expect(button).to have_content 'Assign an article'
button.click
within('#users') do
first('input').set('https://ta.wiktionary.org/wiki/%E0%AE%86%E0%AE%99%E0%AF%8D%E0%AE%95%E0%AE%BF%E0%AE%B2%E0%AE%AE%E0%AF%8D')
end
click_button 'Assign'
click_button 'OK'
visit "/courses/#{course.slug}/students/articles"
first('.student-selection .student').click
within('#users') do
expect(page).to have_content 'ஆங்கிலம்'
link = first('.assignment-links a')
expect(link[:href]).to include('ta.wiktionary')
end
end
end
it 'creates a valid assignment from an article and an alternative project and language' do
VCR.use_cassette 'multiwiki_assignment' do
visit "/courses/#{course.slug}/students/articles"
first('.student-selection .student').click
button = first('.assign-button')
expect(button).to have_content 'Assign an article'
button.click
within('#users') do
find('input', visible: true).set('No le des prisa, dolor')
click_link 'Change'
find('div.wiki-select').click
within('.wiki-select') do
find('input').send_keys('es.wikisource', :enter)
end
end
click_button 'Assign'
click_button 'OK'
visit "/courses/#{course.slug}/students/articles"
first('.student-selection .student').click
within('#users') do
expect(page).to have_content 'No le des prisa'
link = first('.assignment-links a')
expect(link[:href]).to include('es.wikisource')
end
end
end
it 'will create a valid assignment for multilingual wikisource projects' do
VCR.use_cassette 'multiwiki_assignment' do
visit "/courses/#{course.slug}/students/articles"
first('.student-selection .student').click
button = first('.assign-button')
expect(button).to have_content 'Assign an article'
button.click
within('#users') do
first('input').set('https://wikisource.org/wiki/Heyder_Cansa')
end
click_button 'Assign'
click_button 'OK'
visit "/courses/#{course.slug}/students/articles"
first('.student-selection .student').click
within('#users') do
expect(page).to have_content '<NAME>'
link = first('.assignment-links a')
expect(link[:href]).to include('wikisource')
end
end
end
it 'will create a valid assignment for multilingual wikimedia incubator projects' do
VCR.use_cassette 'multiwiki_assignment' do
visit "/courses/#{course.slug}/students/articles"
first('.student-selection .student').click
button = first('.assign-button')
expect(button).to have_content 'Assign an article'
button.click
within('#users') do
first('input').set('https://incubator.wikimedia.org/wiki/Wp/kiu/Heyder_Cansa')
end
click_button 'Assign'
click_button 'OK'
visit "/courses/#{course.slug}/students/articles"
first('.student-selection .student').click
within('#users') do
expect(page).to have_content 'Wp/kiu/Hey'
link = first('.assignment-links a')
expect(link[:href]).to include('incubator.wikimedia')
end
end
end
end
|
rajat2502/WikiEduDashboard
|
app/workers/term_recap_email_worker.rb
|
<gh_stars>1-10
# frozen_string_literal: true
class TermRecapEmailWorker
include Sidekiq::Worker
sidekiq_options unique: :until_executed
def self.send_email(course:, campaign:)
perform_async(course.id, campaign.id)
end
def perform(course_id, campaign_id)
course = Course.find(course_id)
campaign = Campaign.find(campaign_id)
TermRecapMailer.send_recap(course, campaign)
course.flags[:recap_sent_at] = Time.now.utc
course.save
end
end
|
rajat2502/WikiEduDashboard
|
spec/presenters/special_users_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require_relative '../../app/presenters/special_users'
describe SpecialUsers do
let(:user) { create(:user) }
describe 'Wikipedia Expert roles' do
let(:role) { 'wikipedia_experts' }
it 'can be added and removed' do
expect(described_class.wikipedia_experts.count).to eq(0)
described_class.set_user(role, user.username)
expect(described_class.wikipedia_experts.count).to eq(1)
described_class.remove_user(role, username: user.username)
expect(described_class.wikipedia_experts.count).to eq(0)
end
end
end
|
rajat2502/WikiEduDashboard
|
setup/populate_dashboard.rb
|
# frozen_string_literal: true
require_dependency "#{Rails.root}/lib/importers/user_importer"
require_dependency "#{Rails.root}/app/services/update_course_stats"
# Set up some example data in the dashboard
def populate_dashboard
puts "setting up example courses..."
artfeminism_2018 = Campaign.find_by_slug('artfeminsism_2018') || Campaign.create(slug: 'artfeminism_2018',
title: 'Art+Feminism 2018',
default_course_type: 'Editathon',
default_passcode: '<PASSWORD>',
register_accounts: true)
it_wiki = Wiki.get_or_create(language: 'it', project: 'wikipedia')
florence_editathon = Course.find_by_slug('Uffizi/WDG_-_AF_2018_Florence') || Course.create(type: 'Editathon',
slug: 'Uffizi/WDG_-_AF_2018_Florence',
title: 'WDG - AF 2018 Florence',
school: 'Uffizi',
term: '',
passcode: '',
start: '2018-02-21'.to_date,
end: '2018-03-14'.to_date,
home_wiki: it_wiki,
needs_update: true)
florence_editathon.campaigns << artfeminism_2018 if florence_editathon.campaigns.none?
florence_facilitator = UserImporter.new_from_username('Solelu', it_wiki)
CoursesUsers.find_or_create_by(user: florence_facilitator, course: florence_editathon, role: 1)
florence_editors = %w[
Krys.ro
Apmsilva
Krislane_de_Andrade
Nikeknacksandsnacks
Racheleb76
Kaspo
Nea.Lapini
Chiara.toti
MissDaae
Ciucia60
Lizwicks
Katy1q77
Matt.the.iconoclast
Alejandeath
Sherilovemusic
]
florence_editors.each do |username|
user = UserImporter.new_from_username(username, it_wiki)
CoursesUsers.find_or_create_by(user: user, course: florence_editathon, role: 0)
end
en_wiki = Wiki.get_or_create(language: 'en', project: 'wikipedia')
selfie = Article.find_or_create_by(title: 'Selfie', mw_page_id: 1, wiki: en_wiki)
Assignment.find_or_create_by(course: florence_editathon, article: selfie, article_title: 'Selfie', role: 0)
brisbane_editathon = Course.find_by_slug('QCA/Brisbane_QCA_ArtandFeminism_2018') || Course.create!(type: 'Editathon',
slug: 'QCA/Brisbane_QCA_ArtandFeminism_2018',
title: 'Brisbane QCA ArtandFeminism 2018',
school: 'QCA',
term: '',
passcode: '',
start: '2018-01-21'.to_date,
end: '2018-03-14'.to_date,
home_wiki: en_wiki,
needs_update: true)
brisbane_editathon.campaigns << artfeminism_2018 if brisbane_editathon.campaigns.none?
brisbane_facilitator = UserImporter.new_from_username('LouiseRMayhew', en_wiki)
CoursesUsers.find_or_create_by(user: brisbane_facilitator, course: brisbane_editathon, role: 1)
brisbane_editors = %w[
LouiseRMayhew
Susan777
Yizazy
Kay_S_Lawrence
Agoddard2
Ejsnails
KirstyKrasidakis
Taana_R
Charlottetheturtle
Jessmariexox
FriDaInformation
]
brisbane_editors.each do |username|
user = UserImporter.new_from_username(username, en_wiki)
CoursesUsers.find_or_create_by(user: user, course: brisbane_editathon, role: 0)
end
ragesoss_example_course = Course.find_by_slug('test/Ragesoss_(test)') || Course.create!(type: 'ClassroomProgramCourse',
slug: 'test/Ragesoss_(test)',
title: 'Ragesoss',
school: 'test',
term: 'test',
passcode: 'abcdefgh',
start: '2017-07-04'.to_date,
end: '2020-12-31'.to_date,
home_wiki: en_wiki)
ragesoss_example_course.campaigns << Campaign.first if ragesoss_example_course.campaigns.none?
ragesoss = UserImporter.new_from_username('Ragesoss', en_wiki)
CoursesUsers.find_or_create_by(user: ragesoss, course: ragesoss_example_course, role: 0)
[florence_editathon, brisbane_editathon, ragesoss_example_course].each do |course|
puts "getting data for #{course.slug}..."
UpdateCourseStats.new(course)
end
end
|
rajat2502/WikiEduDashboard
|
spec/features/students_page_spec.rb
|
<reponame>rajat2502/WikiEduDashboard<filename>spec/features/students_page_spec.rb<gh_stars>1-10
# frozen_string_literal: true
require 'rails_helper'
require "#{Rails.root}/lib/wiki_edits"
# Wait one second after loading a path
# Allows React to properly load the page
# Remove this after implementing server-side rendering
def js_visit(path)
visit path
sleep 1
end
describe 'Students Page', type: :feature, js: true do
before do
include type: :feature
include Devise::TestHelpers
page.current_window.resize_to(1920, 1080)
allow_any_instance_of(WikiEdits).to receive(:oauth_credentials_valid?).and_return(true)
@course = create(:course,
id: 10001,
title: 'This.course',
slug: 'This_university.foo/This.course_(term_2015)',
start: 3.months.ago,
end: 3.months.from_now,
school: 'This university.foo',
term: 'term 2015',
description: 'This is a great course')
campaign = create(:campaign)
@course.campaigns << campaign
@user = create(:user, username: 'Mr_Tester',
real_name: '<NAME>',
trained: true)
create(:courses_user,
id: 1,
course_id: @course.id,
user_id: @user.id,
real_name: @user.real_name)
article = create(:article,
id: 1,
title: 'Article_Title',
namespace: 0,
language: 'es',
rating: 'fa')
create(:articles_course,
article_id: article.id,
course_id: @course.id)
create(:revision,
id: 1,
user_id: @user.id,
article_id: article.id,
date: Time.zone.today,
characters: 2,
views: 10,
new_article: false)
end
it 'displays a list of students' do
js_visit "/courses/#{@course.slug}/students/overview"
sleep 1 # Try to avoid issue where this test fails with 0 rows found.
expect(page).to have_content @user.username
end
it 'opens a list of individual student revisions' do
js_visit "/courses/#{@course.slug}/students/overview"
sleep 1 # Try to avoid issue where this test fails with 0 rows found.
expect(page).not_to have_content 'Article Title'
page.first('tr.students').click
sleep 1
within 'table.users' do
expect(page).to have_content 'User Contributions'
expect(page).to have_content 'Article Title'
end
end
describe 'display of user name' do
let(:user) { create(:user) }
context 'logged out' do
it 'does not display real name' do
js_visit "/courses/#{@course.slug}/students/overview"
sleep 1 # Try to avoid issue where this test fails with 0 rows found.
within 'table.users' do
expect(page).not_to have_content @user.real_name
end
end
end
context 'logged in' do
before do
login_as user
js_visit "/courses/#{@course.slug}/students/overview"
sleep 1 # Try to avoid issue where this test fails with 0 rows found.
end
after do
logout user
end
context 'non-admin' do
it 'does not display real name' do
within 'table.users' do
expect(page).not_to have_content @user.real_name
end
end
end
context 'admin' do
let(:user) { create(:admin) }
it 'displays real name' do
within 'table.users' do
expect(page).to have_content @user.real_name
end
end
end
context 'instructor' do
let(:user) { create(:user, permissions: 1) }
let!(:courses_user) do
create(:courses_user, course_id: @course.id, user_id: user.id, role: 1)
end
it 'displays real name' do
within 'table.users' do
expect(page).to have_content @user.real_name
end
end
end
end
end
end
|
rajat2502/WikiEduDashboard
|
app/controllers/alerts_controller.rb
|
# frozen_string_literal: true
class AlertsController < ApplicationController
before_action :require_signed_in, only: [:create]
before_action :require_admin_permissions, only: [:resolve]
before_action :set_alert, only: [:resolve]
# Creates only NeedHelpAlert. Doesn't require admin permission.
# Other type of alerts are created via the update cycle, not directly by users.
def create
ensure_alerts_are_enabled { return }
@alert = NeedHelpAlert.new(alert_params)
@alert.user = current_user
# :target_user_id will be nil for the 'dashboard help' option
set_default_target_user unless alert_params[:target_user_id]
if @alert.save
generate_ticket
render json: {}, status: :ok
else
render json: { errors: @alert.errors, message: 'unable to create alert' },
status: :internal_server_error
end
end
# Resolves alert if it is resolvable? Requires admin permission.
# Normally, same alerts won't be created for the second time.
# Resolving alert, allows it to be created for the second time if conditions are met.
def resolve
ensure_alert_is_resolvable { return }
@alert.update resolved: true
render json: { alert: @alert }
end
private
def generate_ticket
TicketDispenser::Dispenser.call(
content: @alert.message,
details: {
sender_email: @alert.user.email,
subject: 'Need Help Alert'
},
project_id: @alert.course_id,
owner_id: @alert.target_user_id,
sender_id: @alert.user_id
)
end
def ensure_alerts_are_enabled
return if Features.enable_get_help_button?
render json: {}, status: :bad_request
yield
end
def ensure_alert_is_resolvable
return if @alert.resolvable?
render json: {}, status: :unprocessable_entity
yield
end
def alert_params
params.permit(:target_user_id, :message, :course_id)
end
def set_default_target_user
@alert.target_user_id = SpecialUsers.technical_help_staff&.id
end
def set_alert
@alert = Alert.find(params[:id])
end
end
|
rajat2502/WikiEduDashboard
|
lib/tasks/courses_wikis.rake
|
# frozen_string_literal: true
namespace :courses_wikis do
desc 'Creates CoursesWikis association for existing courses through revisions'
task migrate: :environment do
Rails.logger.debug 'Creating CoursesWikis associations'
default_wiki_id = if Features.wiki_ed?
[]
else
[Wiki.get_or_create(language: nil, project: 'wikidata').id]
end
Course.all.each do |course|
# The Course#wiki_ids method is removed
# and hence its contents is used here.
wiki_ids = [course.home_wiki_id] + [default_wiki_id] + course.assignments.pluck(:wiki_id)
course.update(wikis: Wiki.find(wiki_ids))
end
end
end
|
rajat2502/WikiEduDashboard
|
app/models/wiki_content/category.rb
|
<reponame>rajat2502/WikiEduDashboard
# frozen_string_literal: true
# == Schema Information
#
# Table name: categories
#
# id :bigint(8) not null, primary key
# wiki_id :integer
# article_titles :text(16777215)
# name :string(255)
# depth :integer default(0)
# created_at :datetime not null
# updated_at :datetime not null
# source :string(255) default("category")
#
require_dependency "#{Rails.root}/lib/importers/category_importer"
require_dependency "#{Rails.root}/lib/importers/transclusion_importer"
require_dependency "#{Rails.root}/lib/article_utils"
require_dependency "#{Rails.root}/lib/petscan_api.rb"
class Category < ApplicationRecord
belongs_to :wiki
has_many :categories_courses, class_name: 'CategoriesCourses', dependent: :destroy
has_many :courses, through: :categories_courses
serialize :article_titles, Array
def self.refresh_categories_for(courses)
CategoriesCourses.where(course: courses).find_each do |category_course|
category_course.category.refresh_titles
end
end
def refresh_titles
self.article_titles = title_list_from_wiki.map do |title|
ArticleUtils.format_article_title(title)
end
save
end
def article_ids
Article.where(namespace: 0, wiki_id: wiki_id, title: article_titles).pluck(:id)
end
def name_with_prefix
"#{source.capitalize}:#{name}"
end
private
def title_list_from_wiki
case source
when 'category'
CategoryImporter.new(wiki).page_titles_for_category(name_with_prefix, depth)
when 'psid'
PetScanApi.new.page_titles_for_psid(name)
when 'template'
TransclusionImporter.new(self).transcluded_titles
end
end
end
|
rajat2502/WikiEduDashboard
|
app/views/revision_analytics/recent_uploads.json.jbuilder
|
<gh_stars>100-1000
# frozen_string_literal: true
json.uploads @uploads do |upload|
json.call(upload, :id, :uploaded_at, :usage_count, :url, :thumburl)
json.file_name pretty_filename(upload)
json.uploader upload.user.username
end
|
rajat2502/WikiEduDashboard
|
lib/alerts/dyk_nomination_monitor.rb
|
<reponame>rajat2502/WikiEduDashboard
# frozen_string_literal: true
require_dependency "#{Rails.root}/lib/importers/category_importer"
# This class identifies articles that have been nominated
# for the Did You Know process on English Wikipedia
class DYKNominationMonitor
def self.create_alerts_for_course_articles
new.create_alerts_from_page_titles
end
def initialize
@wiki = Wiki.find_by(language: 'en', project: 'wikipedia')
find_pending_dyk_nominations
extract_page_titles_from_nominations
normalize_titles
end
def create_alerts_from_page_titles
course_articles = ArticlesCourses.joins(:article)
.where(articles: { title: @page_titles, wiki_id: @wiki.id })
course_articles.each do |articles_course|
create_alert(articles_course)
end
end
private
DYK_CATEGORY = 'Category:Pending DYK nominations'
DYK_CATEGORY_DEPTH = 0
def find_pending_dyk_nominations
@dyk_titles = CategoryImporter.new(@wiki)
.page_titles_for_category(DYK_CATEGORY, DYK_CATEGORY_DEPTH)
end
def extract_page_titles_from_nominations
@dyk_article_titles = @dyk_titles.map do |dyk_title|
dyk_title[%r{Template:Did you know nominations/(.*)}, 1]
end
end
def normalize_titles
@page_titles = @dyk_article_titles.map do |title|
next if title.blank?
title.tr(' ', '_')
end
@page_titles.compact!
@page_titles.uniq!
end
def create_alert(articles_course)
return if alert_already_exists?(articles_course)
first_revision = articles_course
.course.revisions.where(article_id: articles_course.article_id).first
alert = Alert.create!(type: 'DYKNominationAlert',
article_id: articles_course.article_id,
user_id: first_revision&.user_id,
course_id: articles_course.course_id,
revision_id: first_revision&.id)
alert.email_instructors_and_wikipedia_experts
end
def alert_already_exists?(articles_course)
Alert.exists?(article_id: articles_course.article_id,
course_id: articles_course.course_id,
type: 'DYKNominationAlert',
resolved: false)
end
end
|
rajat2502/WikiEduDashboard
|
app/models/training_library.rb
|
<filename>app/models/training_library.rb<gh_stars>1-10
# frozen_string_literal: true
# == Schema Information
#
# Table name: training_libraries
#
# id :bigint(8) not null, primary key
# name :string(255)
# wiki_page :string(255)
# introduction :text(65535)
# categories :text(16777215)
# translations :text(16777215)
# exclude_from_index :boolean default: false
# slug :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
require_dependency "#{Rails.root}/lib/training/training_base"
#= Class representing an individual training module
class TrainingLibrary < ApplicationRecord
serialize :categories, Array
serialize :translations, Hash
validates_uniqueness_of :slug, case_sensitive: false
validates_presence_of [:id, :name, :slug, :introduction, :categories]
def self.path_to_yaml
"#{base_path}/libraries/*.yml"
end
def self.wiki_base_page
ENV['training_libraries_wiki_page']
end
def self.trim_id_from_filename
false
end
def self.load
TrainingBase.load(content_class: self)
end
def self.base_path
TrainingBase.base_path
end
def self.save_if_valid(training_library, slug)
valid = training_library.valid?
if training_library.errors[:slug].any? && slug
raise TrainingBase::DuplicateSlugError,
"Duplicate TrainingLibrary slug detected: #{slug}"
end
training_library.save if valid
training_library
end
def self.inflate(content, slug, wiki_page = nil)
training_library = TrainingLibrary.find_or_initialize_by(id: content['id'])
training_library.slug = slug
training_library.name = content['name'] || content[:name]
training_library.introduction = content['introduction'] || content[:introduction]
training_library.translations = content['translations']
training_library.wiki_page = wiki_page
training_library.categories = content['categories']
training_library.exclude_from_index = content['exclude_from_index']
TrainingLibrary.save_if_valid(training_library, slug)
rescue StandardError, TypeError => e # rubocop:disable Lint/ShadowedException
puts "There's a problem with file '#{slug}'" if Rails.env.development?
raise e
end
####################
# Instance methods #
####################
def translated_name
translated(:name) || name
end
def translated_introduction
translated(:introduction) || introduction
end
def translated(key)
translations.dig(I18n.locale.to_s, key)
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.