hexsha
stringlengths 40
40
| size
int64 2
1.01M
| content
stringlengths 2
1.01M
| avg_line_length
float64 1.5
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
1
|
---|---|---|---|---|---|
919f906d9ac1c8ffff017c6e32815bc300bd8404 | 170 | # frozen_string_literal: true
lib = File.expand_path('../../lib', __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'nonnative'
require 'konfig'
| 21.25 | 55 | 0.741176 |
bf1e3e70d8902d98889e4316de558181b0efa415 | 716 | # Allows Writing of 100.to_money for +Numeric+ types
# 100.to_money => #<Money @pence=10000>
# 100.37.to_money => #<Money @pence=10037>
class Numeric
def to_money
Money.new(self * 100)
end
end
# Allows Writing of '100'.to_money for +String+ types
# Excess characters will be discarded
# '100'.to_money => #<Money @pence=10000>
# '100.37'.to_money => #<Money @pence=10037>
class String
def to_money
# Get the currency
matches = scan /([A-Z]{2,3})/
currency = matches[0] ? matches[0][0] : Money.default_currency
# Get the pence amount
matches = scan /(\-?\d+(\.(\d+))?)/
pence = matches[0] ? (matches[0][0].to_f * 100) : 0
Money.new(pence, currency)
end
end
| 26.518519 | 66 | 0.625698 |
d531fc03296777397385f52891718b93f577fd41 | 1,726 | #Markdown
set :markdown_engine, :redcarpet
#Livereload
activate :livereload
###
# Compass
###
# Susy grids in Compass
# First: gem install compass-susy-plugin
# require 'susy'
# Change Compass configuration
# compass_config do |config|
# config.output_style = :compact
# end
###
# Page options, layouts, aliases and proxies
###
# Per-page layout changes:
#
# With no layout
# page "/path/to/file.html", :layout => false
#
# With alternative layout
# page "/path/to/file.html", :layout => :otherlayout
#
# A path which all have the same layout
# with_layout :admin do
# page "/admin/*"
# end
# Proxy (fake) files
# page "/this-page-has-no-template.html", :proxy => "/template-file.html" do
# @which_fake_page = "Rendering a fake page with a variable"
# end
###
# Helpers
###
# Automatic image dimensions on image_tag helper
# activate :automatic_image_sizes
# Methods defined in the helpers block are available in templates
# helpers do
# def some_helper
# "Helping"
# end
# end
set :css_dir, 'stylesheets'
set :js_dir, 'javascripts'
set :images_dir, 'images'
# Build-specific configuration
configure :build do
# For example, change the Compass output style for deployment
activate :minify_css
# Minify Javascript on build
activate :minify_javascript
# Create favicon/touch icon set from source/favicon_base.png
activate :favicon_maker
activate :sprockets
# Enable cache buster
# activate :cache_buster
# Use relative URLs
# activate :relative_assets
# Compress PNGs after build
# First: gem install middleman-smusher
# require "middleman-smusher"
# activate :smusher
# Or use a different image path
# set :http_path, "/Content/images/"
end | 19.613636 | 76 | 0.709733 |
2615286be4d30679b5172d78a4e7169a9d6d588e | 2,967 | require "active_support/core_ext/integer/time"
Rails.application.configure do
# Configure 'rails notes' to inspect Cucumber files
config.annotations.register_directories('features')
config.annotations.register_extensions('feature') { |tag| /#\s*(#{tag}):?\s*(.*)$/ }
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded any time
# it changes. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = true
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.action_controller.enable_fragment_cache_logging = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise exceptions for disallowed deprecations.
config.active_support.disallowed_deprecation = :raise
# Tell Active Support which deprecation messages to disallow.
config.active_support.disallowed_deprecation_warnings = []
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations.
# config.i18n.raise_on_missing_translations = true
# Annotate rendered view with file names.
# config.action_view.annotate_rendered_view_with_filenames = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
# Uncomment if you wish to allow Action Cable access from any origin.
# config.action_cable.disable_request_forgery_protection = true
end
| 36.62963 | 87 | 0.766768 |
185f38267efb9196b9f347ae9c517e63ed55517b | 780 | module Auth::Concerns::Work::InformConcern
extend ActiveSupport::Concern
included do
## what does this do really ?
field :who_and_when_to_inform, type: Hash
field :inform_on_actions, type: Array, default: []
after_update do |document|
document.inform if document.inform_on_actions.include? "after_update"
end
before_destroy do |document|
document.inform if document.inform_on_actions.include? "before_destroy"
end
def inform
self.who_and_when_to_inform.keys.each do |person_id|
information = Auth::Work::Information.new
information.resource_id = person_id
information.send_at = self.who_and_when_to_inform[person_id]
## other options can be added.
## like payload and format.
information.inform
end
end
end
end | 25.16129 | 74 | 0.74359 |
f8150f703060eff07a9477203d2657d6e1f20a9b | 869 | module Spree
class Calculator::FlatPercentTaxonTotal < Calculator
preference :flat_percent, :decimal, :default => 0
preference :taxon, :string, :default => ''
# attr_accessible :preferred_flat_percent, :preferred_taxon
def self.description
I18n.t(:flat_percent_taxon)
end
def compute(object)
return unless object.present? and object.line_items.present?
match_taxons = preferred_taxon.split(',')
item_total = 0.0
object.line_items.each do |line_item|
matched = false
match_taxons.each do |tx|
matched = true if line_item.product.taxons.where(:name => tx).present?
end
item_total += line_item.amount if matched
end
value = item_total * BigDecimal(self.preferred_flat_percent.to_s) / 100.0
(value * 100).round.to_f / 100
end
end
end
| 28.966667 | 80 | 0.659379 |
bb854f9cc506b1573a212b1292d2eee591b85bc6 | 2,702 | require 'test_helper'
class PasswordResetsTest < ActionDispatch::IntegrationTest
def setup
ActionMailer::Base.deliveries.clear
@user = users(:danny)
end
test "password resets" do
get new_password_reset_path
assert_template 'password_resets/new'
# Invalid email
post password_resets_path, params: { password_reset: { email: "" } }
assert_not flash.empty?
assert_template 'password_resets/new'
# Valid email
post password_resets_path,
params: { password_reset: { email: @user.email } }
assert_not_equal @user.reset_digest, @user.reload.reset_digest
assert_equal 1, ActionMailer::Base.deliveries.size
assert_not flash.empty?
assert_redirected_to root_url
# Password reset form
user = assigns(:user)
# Wrong email
get edit_password_reset_path(user.reset_token, email: "")
assert_redirected_to root_url
# Inactive user
user.toggle!(:activated)
get edit_password_reset_path(user.reset_token, email: user.email)
assert_redirected_to root_url
user.toggle!(:activated)
# Correct email, wrong token
get edit_password_reset_path('wrong token', email: user.email)
assert_redirected_to root_url
# Correct email and token
get edit_password_reset_path(user.reset_token, email: user.email)
assert_template 'password_resets/edit'
assert_select "input[name=email][type=hidden][value=?]", user.email
# Invalid password & confirmation
patch password_reset_path(user.reset_token),
params: { email: user.email,
user: { password: "foobaz",
password_confirmation: "barquux" } }
assert_select 'div#error_explanation'
# Empty password
patch password_reset_path(user.reset_token),
params: { email: user.email,
user: { password: "",
password_confirmation: "" } }
assert_select 'div#error_explanation'
# Valid password & confirmation
patch password_reset_path(user.reset_token),
params: { email: user.email,
user: { password: "foobaz",
password_confirmation: "foobaz" } }
assert is_logged_in?
assert_not flash.empty?
assert_redirected_to user
assert_nil user.reload.reset_digest
end
test "expired token" do
get new_password_reset_path
post password_resets_path,
params: { password_reset: { email: @user.email } }
@user = assigns(:user)
@user.update_attribute(:reset_sent_at, 3.hours.ago)
patch password_reset_path(@user.reset_token),
params: { email: @user.email,
user: { password: "foobar",
password_confirmation: "foobar" } }
assert_response :redirect
follow_redirect!
assert_match /expired/i, response.body
end
end
| 34.202532 | 71 | 0.707994 |
f7b4b8dba92809df15a3214ffc3164fbed618dea | 7,557 | # Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
require 'date'
# rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength
module OCI
# Details for creating a database home.
#
# **Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.
#
# This class has direct subclasses. If you are using this class as input to a service operations then you should favor using a subclass over the base class
class Database::Models::CreateDbHomeBase
SOURCE_ENUM = [
SOURCE_NONE = 'NONE'.freeze,
SOURCE_DB_BACKUP = 'DB_BACKUP'.freeze,
SOURCE_VM_CLUSTER_NEW = 'VM_CLUSTER_NEW'.freeze,
SOURCE_VM_CLUSTER_BACKUP = 'VM_CLUSTER_BACKUP'.freeze
].freeze
# The user-provided name of the database home.
# @return [String]
attr_accessor :display_name
# The source of database: NONE for creating a new database. DB_BACKUP for creating a new database by restoring from a database backup.
#
# @return [String]
attr_reader :source
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
# rubocop:disable Style/SymbolLiteral
'display_name': :'displayName',
'source': :'source'
# rubocop:enable Style/SymbolLiteral
}
end
# Attribute type mapping.
def self.swagger_types
{
# rubocop:disable Style/SymbolLiteral
'display_name': :'String',
'source': :'String'
# rubocop:enable Style/SymbolLiteral
}
end
# rubocop:disable Metrics/CyclomaticComplexity, Layout/EmptyLines, Metrics/PerceivedComplexity, Metrics/AbcSize
# Given the hash representation of a subtype of this class,
# use the info in the hash to return the class of the subtype.
def self.get_subtype(object_hash)
type = object_hash[:'source'] # rubocop:disable Style/SymbolLiteral
return 'OCI::Database::Models::CreateDbHomeWithDbSystemIdFromBackupDetails' if type == 'DB_BACKUP'
return 'OCI::Database::Models::CreateDbHomeWithVmClusterIdFromBackupDetails' if type == 'VM_CLUSTER_BACKUP'
return 'OCI::Database::Models::CreateDbHomeWithDbSystemIdDetails' if type == 'NONE'
return 'OCI::Database::Models::CreateDbHomeWithVmClusterIdDetails' if type == 'VM_CLUSTER_NEW'
# TODO: Log a warning when the subtype is not found.
'OCI::Database::Models::CreateDbHomeBase'
end
# rubocop:enable Metrics/CyclomaticComplexity, Layout/EmptyLines, Metrics/PerceivedComplexity, Metrics/AbcSize
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
# @option attributes [String] :display_name The value to assign to the {#display_name} property
# @option attributes [String] :source The value to assign to the {#source} property
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
self.display_name = attributes[:'displayName'] if attributes[:'displayName']
raise 'You cannot provide both :displayName and :display_name' if attributes.key?(:'displayName') && attributes.key?(:'display_name')
self.display_name = attributes[:'display_name'] if attributes[:'display_name']
self.source = attributes[:'source'] if attributes[:'source']
self.source = "NONE" if source.nil? && !attributes.key?(:'source') # rubocop:disable Style/StringLiterals
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Custom attribute writer method checking allowed values (enum).
# @param [Object] source Object to be assigned
def source=(source)
raise "Invalid value for 'source': this must be one of the values in SOURCE_ENUM." if source && !SOURCE_ENUM.include?(source)
@source = source
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# Checks equality by comparing each attribute.
# @param [Object] other the other object to be compared
def ==(other)
return true if equal?(other)
self.class == other.class &&
display_name == other.display_name &&
source == other.source
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# @see the `==` method
# @param [Object] other the other object to be compared
def eql?(other)
self == other
end
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[display_name, source].hash
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
public_method("#{key}=").call(
attributes[self.class.attribute_map[key]]
.map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) }
)
end
elsif !attributes[self.class.attribute_map[key]].nil?
public_method("#{key}=").call(
OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]])
)
end
# or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = public_method(attr).call
next if value.nil? && !instance_variable_defined?("@#{attr}")
hash[param] = _to_hash(value)
end
hash
end
private
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
# rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
| 37.226601 | 157 | 0.684531 |
26f9a31b8e30aacd2c8280edba4f77b62ef6a5a8 | 2,263 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Compute::Mgmt::V2017_12_01
module Models
#
# Describes a virtual machines scale set IP Configuration's PublicIPAddress
# configuration
#
class VirtualMachineScaleSetPublicIPAddressConfiguration
include MsRestAzure
# @return [String] The publicIP address configuration name.
attr_accessor :name
# @return [Integer] The idle timeout of the public IP address.
attr_accessor :idle_timeout_in_minutes
# @return [VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettings]
# The dns settings to be applied on the publicIP addresses .
attr_accessor :dns_settings
#
# Mapper for VirtualMachineScaleSetPublicIPAddressConfiguration class as
# Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'VirtualMachineScaleSetPublicIPAddressConfiguration',
type: {
name: 'Composite',
class_name: 'VirtualMachineScaleSetPublicIPAddressConfiguration',
model_properties: {
name: {
client_side_validation: true,
required: true,
serialized_name: 'name',
type: {
name: 'String'
}
},
idle_timeout_in_minutes: {
client_side_validation: true,
required: false,
serialized_name: 'properties.idleTimeoutInMinutes',
type: {
name: 'Number'
}
},
dns_settings: {
client_side_validation: true,
required: false,
serialized_name: 'properties.dnsSettings',
type: {
name: 'Composite',
class_name: 'VirtualMachineScaleSetPublicIPAddressConfigurationDnsSettings'
}
}
}
}
}
end
end
end
end
| 31 | 93 | 0.582413 |
d5f1c21facce4e3a4d82f477d5103454cdb56641 | 998 | # Rails: ne zaboraviti u config/environments/production.rb postaviti config.assets.compile=true
module JRubyCipango
module Factory
['org.jruby.rack.DefaultRackApplicationFactory',
'org.jruby.rack.SharedRackApplicationFactory',
'org.jruby.rack.RackServletContextListener',
'org.jruby.rack.rails.RailsServletContextListener',
'org.jruby.Ruby'
].each {|c| java_import c }
class JRCRackFactory < DefaultRackApplicationFactory
field_accessor :rackContext
def newRuntime
runtime = Ruby.get_global_runtime
$servlet_context=rackContext
require 'rack/handler/servlet'
return runtime
end
end
class JRCRackListener < RackServletContextListener
field_reader :factory
def newApplicationFactory(context)
if factory
return factory
else
return (
SharedRackApplicationFactory.new(JRCRackFactory.new)
)
end
end
end
end
end
| 27.722222 | 95 | 0.680361 |
e877acbfe53d94cf3291e7bce3ab48e2eb3d514a | 2,664 | RSpec.describe BBK::App::Handler do
subject { described_class.new }
let(:default) { proc {|*args| args } }
let(:match_rule) { [:meta, { headers: { type: 'test' } }] }
it 'with default block' do
subj = described_class.new(&default)
expect(subj.instance_variable_get('@default').call(1, 2, 3)).to eq [1, 2, 3]
end
it 'with default lambda' do
subj = described_class.new
default_lambda = subj.instance_variable_get('@default')
expect(default_lambda).not_to be_nil
expect(default_lambda).to respond_to(:call)
end
context 'register' do
let(:processor) do
Class.new(BBK::App::Processors::Base) do
def self.rule
[:meta, { key: :value }]
end
end
end
let(:block_rule) { [:meta, {}] }
let(:block) { proc {} }
it 'register processor' do
handlers = subject.instance_variable_get('@handlers')
expect do
subject.register processor
end.to change { handlers.size }.from(0).to(1)
key, value = handlers.first
expect(key).to be_a BBK::App::Matchers::Base
expect(value).to be_a BBK::App::Factory
expect(value.klass).to eq processor
end
it 'double register processor' do
handlers = subject.instance_variable_get('@handlers')
expect do
subject.register processor
subject.register processor
end.to change { handlers.size }.from(0).to(1)
key, value = handlers.first
expect(key).to be_a BBK::App::Matchers::Base
expect(value).to be_a BBK::App::Factory
expect(value.klass).to eq processor
end
it 'register block' do
handlers = subject.instance_variable_get('@handlers')
expect do
subject.register(*block_rule, &block)
end.to change { handlers.size }.from(0).to(1)
key, value = handlers.first
expect(key).to be_a BBK::App::Matchers::Headers
expect(value).to be_a Proc
end
it 'invalid rule' do
expect do
subject.register 42
end.to raise_error(RuntimeError, /type and rule or method/)
end
it 'invalid callable' do
expect do
subject.register(*block_rule, 42)
end.to raise_error(RuntimeError, /callable object or class missing/)
end
end
it 'default setter' do
v = proc {}
expect do
subject.default(&v)
end.to change { subject.instance_variable_get('@default') }
end
it 'match rule' do
subject.register(*match_rule, default)
result = subject.match match_rule.last, {}, {}
expect(result).to be_a Array
expect(result.first).to eq match_rule.last.deep_stringify_keys
expect(result.last).to eq default
end
end
| 27.463918 | 80 | 0.641517 |
11323c932775fa533f1f02edb91fd4daf82eb904 | 4,776 | # encoding: utf-8
require 'spec_helper'
require 'set'
describe Bugsnag::Helpers do
describe "trim_if_needed" do
it "preserves bool types" do
value = Bugsnag::Helpers.trim_if_needed([1, 3, true, "NO", "2", false])
expect(value[2]).to be_a(TrueClass)
expect(value[5]).to be_a(FalseClass)
end
it "preserves Numeric types" do
value = Bugsnag::Helpers.trim_if_needed([1, 3.445, true, "NO", "2", false])
expect(value[0]).to be_a(Numeric)
expect(value[1]).to be_a(Numeric)
end
it "preserves String types" do
value = Bugsnag::Helpers.trim_if_needed([1, 3, true, "NO", "2", false])
expect(value[3]).to be_a(String)
expect(value[4]).to be_a(String)
end
context "payload length is less than allowed" do
it "does not change strings" do
value = SecureRandom.hex(4096)
expect(Bugsnag::Helpers.trim_if_needed(value)).to eq value
end
it "does not change arrays" do
value = 1000.times.map {|i| "#{i} - #{i + 1}" }
expect(Bugsnag::Helpers.trim_if_needed(value)).to eq value
end
it "does not change hashes" do
value = Hash[*1000.times.map{|i| ["#{i}", i]}.flatten]
expect(Bugsnag::Helpers.trim_if_needed(value)).to eq value
end
end
context "payload length is greater than allowed" do
it "trims metadata strings" do
payload = {
:events => [{
:metaData => 50000.times.map {|i| "should truncate" }.join(""),
:preserved => "Foo"
}]
}
expect(::JSON.dump(payload).length).to be > Bugsnag::Helpers::MAX_PAYLOAD_LENGTH
trimmed = Bugsnag::Helpers.trim_if_needed(payload)
expect(::JSON.dump(trimmed).length).to be <= Bugsnag::Helpers::MAX_PAYLOAD_LENGTH
expect(trimmed[:events][0][:metaData].length).to be <= Bugsnag::Helpers::MAX_STRING_LENGTH
expect(trimmed[:events][0][:preserved]).to eq("Foo")
end
it "truncates metadata arrays" do
payload = {
:events => [{
:metaData => 50000.times.map {|i| "should truncate" },
:preserved => "Foo"
}]
}
expect(::JSON.dump(payload).length).to be > Bugsnag::Helpers::MAX_PAYLOAD_LENGTH
trimmed = Bugsnag::Helpers.trim_if_needed(payload)
expect(::JSON.dump(trimmed).length).to be <= Bugsnag::Helpers::MAX_PAYLOAD_LENGTH
expect(trimmed[:events][0][:metaData].length).to be <= Bugsnag::Helpers::MAX_ARRAY_LENGTH
expect(trimmed[:events][0][:preserved]).to eq("Foo")
end
it "trims stacktrace code" do
payload = {
:events => [{
:exceptions => [{
:stacktrace => [
{
:lineNumber => 1,
:file => '/trace1',
:code => 50.times.map {|i| SecureRandom.hex(3072) }
},
{
:lineNumber => 2,
:file => '/trace2',
:code => 50.times.map {|i| SecureRandom.hex(3072) }
}
]
}]
}]
}
expect(::JSON.dump(payload).length).to be > Bugsnag::Helpers::MAX_PAYLOAD_LENGTH
trimmed = Bugsnag::Helpers.trim_if_needed(payload)
expect(::JSON.dump(trimmed).length).to be <= Bugsnag::Helpers::MAX_PAYLOAD_LENGTH
trace = trimmed[:events][0][:exceptions][0][:stacktrace]
expect(trace.length).to eq(2)
expect(trace[0][:lineNumber]).to eq(1)
expect(trace[0][:file]).to eq('/trace1')
expect(trace[0][:code]).to be_nil
expect(trace[1][:lineNumber]).to eq(2)
expect(trace[1][:file]).to eq('/trace2')
expect(trace[1][:code]).to be_nil
end
it "trims stacktrace entries" do
payload = {
:events => [{
:exceptions => [{
:stacktrace => 18000.times.map do |index|
{
:lineNumber => index,
:file => "/path/to/item_#{index}.rb",
:code => { "#{index}" => "puts 'code'" }
}
end
}]
}]
}
expect(::JSON.dump(payload).length).to be > Bugsnag::Helpers::MAX_PAYLOAD_LENGTH
trimmed = Bugsnag::Helpers.trim_if_needed(payload)
expect(::JSON.dump(trimmed).length).to be <= Bugsnag::Helpers::MAX_PAYLOAD_LENGTH
trace = trimmed[:events][0][:exceptions][0][:stacktrace]
expect(trace.length).to eq(30)
30.times.map do |index|
expect(trace[index][:lineNumber]).to eq(index)
expect(trace[index][:file]).to eq("/path/to/item_#{index}.rb")
expect(trace[index][:code]).to be_nil
end
end
end
end
end
| 36.181818 | 98 | 0.551298 |
3951fc54a15e287c89347fa73d28e418f53b85aa | 358 | cask 'retro-virtual-machine' do
version '1.0.1'
sha256 '2144c713889780fcc1b4f9e994f4466514f9434974c942406f966145adaf899d'
url "http://www.retrovirtualmachine.org/release/Retro%20Virtual%20Machine%20v#{version}.dmg"
name 'Retro Virtual Machine'
homepage 'http://www.retrovirtualmachine.org'
license :gratis
app 'Retro Virtual Machine.app'
end
| 29.833333 | 94 | 0.784916 |
385bee812d2506075dccacefb0733f5fe9649c21 | 757 | cask 'xee' do
version '3.5.3,45:1504018134'
sha256 '756719157ae7d9cd3a0153ca80b48b71a239691d3ff8aa0061fd529a825d7926'
# devmate.com/cx.c3.Xee3 was verified as official when first introduced to the cask
url "https://dl.devmate.com/cx.c3.Xee3/#{version.after_comma.before_colon}/#{version.after_colon}/Xee-#{version.after_comma.before_colon}.zip"
appcast 'https://updates.devmate.com/cx.c3.Xee3.xml'
name 'Xee³'
homepage 'https://theunarchiver.com/xee'
auto_updates true
app 'Xee³.app'
zap trash: [
'~/Library/Application Support/Xee³',
'~/Library/Caches/cx.c3.Xee3',
'~/Library/Cookies/cx.c3.Xee3.binarycookies',
'~/Library/Preferences/cx.c3.Xee3.plist',
]
end
| 34.409091 | 144 | 0.677675 |
1dff24b674aa2c36d6ec5a068d270701339e902e | 116 | class Schedule < ApplicationRecord
validates :category, presence: true
validates :post_time, presence: true
end
| 23.2 | 38 | 0.793103 |
d580e4f571fee8ecfeca892ce4cfa86c02ac0643 | 2,574 | require 'fluent/output'
require_relative 'barito_timber'
require_relative 'barito_client_trail'
require_relative 'barito_transport'
module Fluent
class BaritoBatchK8sOutput < BufferedOutput
PLUGIN_NAME = 'barito_batch_k8s'
Fluent::Plugin.register_output(PLUGIN_NAME, self)
config_param :application_secret, :string, :default => nil
config_param :application_group_secret, :string, :default => nil
config_param :application_name, :string, :default => nil
config_param :produce_url, :string, :default => ''
config_param :cluster_name, :string, :default => ''
# Overide from BufferedOutput
def start
super
end
# Overide from BufferedOutput
def format(tag, time, record)
[tag, time, record].to_msgpack
end
# Overide from BufferedOutput
def write(chunk)
data = {
'items' => []
}
transport = Fluent::Plugin::BaritoTransport.new(@produce_url, log)
chunk.msgpack_each do |tag, time, record|
# Kubernetes annotations
k8s_metadata = record['kubernetes']
record = clean_attribute(record)
trail = Fluent::Plugin::ClientTrail.new(true)
timber = Fluent::Plugin::TimberFactory::create_timber(tag, time, record, trail)
new_timber = merge_log_attribute(timber)
# Add kubernetes information
new_timber['k8s_metadata'] = {
'pod_name' => k8s_metadata['pod_name'],
'namespace_name' => k8s_metadata['namespace_name'],
'container_name' => k8s_metadata['container_name'],
'host' => k8s_metadata['host'],
'cluster_name' => @cluster_name
}
data['items'] << new_timber
end
if @application_secret.nil? or @application_secret.empty?
return if @application_group_secret.nil? or @application_name.nil?
header = {
content_type: :json,
'X-App-Group-Secret' => @application_group_secret,
'X-App-Name' => @application_name
}
else
header = {content_type: :json, 'X-App-Secret' => @application_secret}
end
transport.send(data, header)
end
def clean_attribute(record)
# Delete kubernetes & docker field
record.delete('kubernetes')
record.delete('docker')
record
end
def merge_log_attribute(record)
message_log = nil
begin
message_log = JSON.parse(record['log'])
rescue
end
if !message_log.nil?
return record.merge(message_log)
end
record
end
end
end
| 27.382979 | 87 | 0.638306 |
1a64d14dc8a889eef08201ab3589757dbba54994 | 232 | module Contacts
class Homepage < ActiveRecord::Base
belongs_to :contact, dependent: :destroy
validates :homepagetype, length: { in: 1..30 }, presence: true
validates :url, presence: true, uniqueness: true
end
end
| 21.090909 | 66 | 0.706897 |
08b9082d2df624d07d78e478221f5f8353928794 | 2,318 | # frozen_string_literal: true
require "forwardable"
module Wordword
class Command
extend Forwardable
def_delegators :command, :run
# Execute this command
#
# @api public
def execute(*)
raise(
NotImplementedError,
"#{self.class}##{__method__} must be implemented",
)
end
# The external commands runner
#
# @see http://www.rubydoc.info/gems/tty-command
#
# @api public
def command(**options)
require "tty-command"
TTY::Command.new(options)
end
# The cursor movement
#
# @see http://www.rubydoc.info/gems/tty-cursor
#
# @api public
def cursor
require "tty-cursor"
TTY::Cursor
end
# Open a file or text in the user's preferred editor
#
# @see http://www.rubydoc.info/gems/tty-editor
#
# @api public
def editor
require "tty-editor"
TTY::Editor
end
# File manipulation utility methods
#
# @see http://www.rubydoc.info/gems/tty-file
#
# @api public
def generator
require "tty-file"
TTY::File
end
# Terminal output paging
#
# @see http://www.rubydoc.info/gems/tty-pager
#
# @api public
def pager(**options)
require "tty-pager"
TTY::Pager.new(options)
end
# Terminal platform and OS properties
#
# @see http://www.rubydoc.info/gems/tty-pager
#
# @api public
def platform
require "tty-platform"
TTY::Platform.new
end
# The interactive prompt
#
# @see http://www.rubydoc.info/gems/tty-prompt
#
# @api public
def prompt(**options)
require "tty-prompt"
TTY::Prompt.new(options)
end
# Get terminal screen properties
#
# @see http://www.rubydoc.info/gems/tty-screen
#
# @api public
def screen
require "tty-screen"
TTY::Screen
end
# The unix which utility
#
# @see http://www.rubydoc.info/gems/tty-which
#
# @api public
def which(*args)
require "tty-which"
TTY::Which.which(*args)
end
# Check if executable exists
#
# @see http://www.rubydoc.info/gems/tty-which
#
# @api public
def exec_exist?(*args)
require "tty-which"
TTY::Which.exist?(*args)
end
end
end
| 18.693548 | 58 | 0.581104 |
1c38f903d56f2652653de20dd0961c2f063e7eea | 139 | require_relative '../../../spec_helper'
describe "Process::GID.re_exchangeable?" do
it "needs to be reviewed for spec completeness"
end
| 23.166667 | 49 | 0.741007 |
18a12f53231b854a3140252bb241fc26077dd31b | 210 | require 'rails_helper'
field_name = field_name_from __FILE__
type = type_from __FILE__
describe field_name do
it_behaves_like \
"#{type} partial", field_name,
value: IPAddr.new('192.168.2.0/24')
end
| 21 | 39 | 0.742857 |
1dd761a1bb3d6dc27197132e6cf1a4bc0c6a9a51 | 309 | require 'mina'
require 'rake'
class RakeScope
include Rake::DSL if Rake.const_defined?(:DSL)
include Mina::Helpers
end
def rake(&blk)
if block_given?
@scope ||= RakeScope.new
@scope.instance_eval &blk
end
@scope
end
def root(*a)
File.join File.expand_path('../../', __FILE__), *a
end
| 14.714286 | 52 | 0.673139 |
4a177067a695a05bd944afb5cd3601a035de6999 | 3,753 | require 'test_helper'
class CustomTypeCaster
def self.cast(*)
:mock
end
end
JsonOrgApiClient::Schema.register custom: CustomTypeCaster
class SchemaResource < TestResource
property :a, type: :string, default: 'foo'
property :b, type: :boolean, default: false
property :c
property :d, type: :integer
end
class SchemaResource2 < TestResource
property :a, type: :float
end
class SchemaResource3 < TestResource
property :a, type: :custom
end
class MultipleSchema < TestResource
properties :name, :short_name, :long_name, type: :string
end
class SchemableTest < MiniTest::Test
def test_default_attributes
resource = SchemaResource.new
assert resource.attributes.has_key?(:a), ':a should be in attributes'
assert resource.attributes.has_key?(:b), ':b should be in attributes'
refute resource.attributes.has_key?(:c), ':c should not be in attributes'
refute resource.attributes.has_key?(:d), ':d should not be in attributes'
end
def test_defines_fields
resource = SchemaResource.new
%w(a b c d).each do |method_name|
assert resource.respond_to?(method_name), "should respond_to?(:#{method_name})"
assert resource.respond_to?("#{method_name}="), "should respond_to?(:#{method_name}=)"
end
assert_equal 4, SchemaResource.schema.size
end
def test_defines_defaults
resource = SchemaResource.new
assert_equal 'foo', resource.a
assert_equal 'foo', resource['a']
assert_equal false, resource.b
assert_equal false, resource['b']
assert_nil resource.c
assert_nil resource.d
end
def test_find_property_definition
property = SchemaResource.schema[:a]
assert property
assert_equal :a, property.name
assert_equal :string, property.type
assert_equal 'foo', property.default
end
def test_casts_data
resource = SchemaResource.new
resource.b = "false"
assert_equal false, resource.b, "should cast boolean strings"
resource.d = "1"
assert_equal 1, resource.d
end
# sanity to make sure we're not doing anything crazy with inheritance
def test_schemas_do_not_collide
assert_equal 4, SchemaResource.schema.size
assert_equal 1, SchemaResource2.schema.size
end
def test_can_define_multiple_properties
assert_equal 3, MultipleSchema.schema.size
MultipleSchema.schema.each_property do |property|
assert_equal :string, property.type
assert_nil property.default
end
end
def test_casts_values_when_instantiating
resource = SchemaResource.new({
a: 123,
b: 'false',
c: :blah,
d: "12345"
})
assert_equal "123", resource.a
assert_equal false, resource.b
assert_equal :blah, resource.c
assert_equal 12345, resource.d
end
def test_casts_values_when_bulk_assigning_attributes
resource = SchemaResource.new
resource.attributes = {
a: 123,
b: 'false',
c: :blah,
d: "12345"
}
assert_equal "123", resource.a
assert_equal false, resource.b
assert_equal :blah, resource.c
assert_equal 12345, resource.d
end
def test_boolean_casts_to_true
["1", 1, "true", true].each do |v|
resource = SchemaResource.new
resource.b = v
assert_equal true, resource.b
end
end
def test_boolean_casts_to_false
["0", 0, "false", false].each do |v|
resource = SchemaResource.new
resource.b = v
assert_equal false, resource.b
end
end
def test_boolean_defaults_to_default
resource = SchemaResource.new
resource.b = :bogus
assert_equal false, resource.b
end
def test_custom_types
resource = SchemaResource3.new(a: 'anything')
assert_equal :mock, resource.a
assert_equal :mock, resource['a']
end
end
| 24.529412 | 92 | 0.705036 |
6184ad7bb32687210d9a0bfcdc7afa1825e1841a | 121 | require 'test_helper'
class UniUserTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| 15.125 | 43 | 0.702479 |
39f0ed22dec5917d482296f775c29676a126f7fb | 572 | require File.expand_path('../helper', __FILE__)
class HipChatTest < Service::TestCase
def setup
@stubs = Faraday::Adapter::Test::Stubs.new
end
def test_push
@stubs.post "/v1/webhooks/github" do |env|
assert_match /(^|\&)payload=%7B%22a%22%3A1%7D($|\&)/, env[:body]
assert_match "auth_token=a", env[:body]
assert_match "room_id=r", env[:body]
[200, {}, '']
end
svc = service(
{'auth_token' => 'a', 'room' => 'r'}, 'a' => 1)
svc.receive_push
end
def service(*args)
super Service::HipChat, *args
end
end
| 22 | 70 | 0.596154 |
1a96a86359fe364da74c00238c7bb8aa059defc2 | 3,877 | # Creates dot type plots
class Rubyplot::Dot < Rubyplot::Artist
def draw
@geometry.has_left_labels = true
super
return unless @geometry.has_data
# Setup spacing.
spacing_factor = 1.0
@items_width = @graph_height / @geometry.column_count.to_f
@item_width = @items_width * spacing_factor / @geometry.norm_data.size
@d = @d.stroke_opacity 0.0
padding = (@items_width * (1 - spacing_factor)) / 2
@geometry.norm_data.each_with_index do |data_row, row_index|
data_row[DATA_VALUES_INDEX].each_with_index do |data_point, point_index|
x_pos = @graph_left + (data_point * @graph_width)
y_pos = @graph_top + (@items_width * point_index) + padding + (@items_width.to_f / 2.0).round
if row_index == 0
@d = @d.stroke(@marker_color)
@d = @d.fill(@marker_color)
@d = @d.stroke_width 1.0
@d = @d.stroke_opacity 0.1
@d = @d.fill_opacity 0.1
@d = @d.line(@graph_left, y_pos, @graph_left + @graph_width, y_pos)
@d = @d.fill_opacity 1
end
@d = @d.fill @plot_colors[row_index]
@d = @d.circle(x_pos, y_pos, x_pos + (@item_width.to_f / 3.0).round, y_pos)
draw_label(y_pos, point_index)
end
end
@d.draw(@base_image)
end
# Instead of base class version, draws vertical background lines and label
def draw_line_markers
@d = @d.stroke_antialias false
# Draw horizontal line markers and annotate with numbers
@d = @d.stroke(@marker_color)
@d = @d.stroke_width 1
if @y_axis_increment
increment = @y_axis_increment
number_of_lines = (@spread / @y_axis_increment).to_i
else
# Try to use a number of horizontal lines that will come out even.
#
# TODO Do the same for larger numbers...100, 75, 50, 25
if @geometry.marker_count.nil?
(3..7).each do |lines|
if @spread % lines == 0.0
@geometry.marker_count = lines
break
end
end
@geometry.marker_count ||= 5
end
# TODO: Round maximum marker value to a round number like 100, 0.1, 0.5, etc.
@geometry.increment = @spread > 0 && @geometry.marker_count > 0 ? significant(@spread / @geometry.marker_count) : 1
number_of_lines = @geometry.marker_count
increment = @geometry.increment
end
(0..number_of_lines).each do |index|
marker_label = @geometry.minimum_value + index * increment
x = @graph_left + (marker_label - @geometry.minimum_value) * @graph_width / @spread
@d = @d.line(x, @graph_bottom, x, @graph_bottom + 0.5 * LABEL_MARGIN)
unless @geometry.hide_line_numbers
@d.fill = @font_color
@d.font = @font if @font
@d.stroke = 'transparent'
@d.pointsize = scale_fontsize(@marker_font_size)
@d.gravity = CenterGravity
# TODO: Center text over line
@d = @d.scale_annotation(@base_image,
0, 0, # Width of box to draw text in
x, @graph_bottom + (LABEL_MARGIN * 2.0), # Coordinates of text
label(marker_label, increment), @scale)
end # unless
@d = @d.stroke_antialias true
end
end
# Draw on the Y axis instead of the X
def draw_label(y_offset, index)
if !@labels[index].nil? && @geometry.labels_seen[index].nil?
@d.fill = @font_color
@d.font = @font if @font
@d.stroke = 'transparent'
@d.font_weight = NormalWeight
@d.pointsize = scale_fontsize(@marker_font_size)
@d.gravity = EastGravity
@d = @d.scale_annotation(@base_image,
1, 1,
-@graph_left + LABEL_MARGIN * 2.0, y_offset,
@labels[index], @scale)
@geometry.labels_seen[index] = 1
end
end
end
| 36.575472 | 121 | 0.600464 |
bfd4ce41e91935a69999f82f3c466e83176e11b2 | 2,457 | namespace :cartodb do
# This rake retrieves all sync tables that should get synchronized, and puts the synchronization tasks at Resque
# NOTE: This version does not mark the tables as "enqueued", should be done if planning to run multiple instances
desc 'Runs the sync tables process'
task :sync_tables, [:force_all_arg] => [:environment] do |task, args|
puts '> Sync tables started' if ENV['VERBOSE']
require_relative '../../services/synchronizer/lib/synchronizer/collection'
collection = CartoDB::Synchronizer::Collection.new
# This fetches and enqueues
collection.fetch_and_enqueue(args[:force_all_arg].present? ? args[:force_all_arg] : false)
puts '> Sync tables finished' if ENV['VERBOSE']
end
desc 'Adds visualization_id to every Synchronization'
task :populate_synchronization_visualization_ids => [:environment] do |task, args|
require_relative '../../services/synchronizer/lib/synchronizer/collection'
collection = CartoDB::Synchronizer::Collection.new
collection.fetch_all.each { |record|
begin
synchronization = CartoDB::Synchronization::Member.new(id: record[:id]).fetch
rescue KeyError
synchronization = nil
end
if synchronization
begin
table = UserTable.where({
name: synchronization.name,
user_id: synchronization.user_id
}).first
if table.nil?
puts "\nSync id '#{record[:id]}' related table not found"
else
table = table.service
end
rescue StandardError => exception
table = nil
puts "\nSync id '#{record[:id]}' errored: #{exception.inspect}"
end
unless table.nil?
if synchronization.visualization_id.nil?
begin
synchronization.visualization_id = table.table_visualization.id
rescue StandardError => exception
puts "\nSync id '#{record[:id]}' errored, canonical visualization not found"
end
begin
synchronization.store
printf '.'
rescue StandardError => exception
puts "\nSync id '#{record[:id]}' errored: #{exception.inspect}"
end
else
printf 'S'
end
end
else
puts "\nSync id '#{record[:id]}' errored: missing synchronization entry"
end
}
puts "\nFINISHED"
end
end
| 35.608696 | 115 | 0.627595 |
2670e7c255167c8f114a58d3f5ab886266c76efa | 45 | class PublicProfile < ActiveRecord::Base
end | 15 | 40 | 0.822222 |
e9a8362fcc7191c2f90223ac9ec3bb97945c6747 | 1,036 | module Elasticsearch
module XPack
module API
module MachineLearning
module Actions
# TODO: Description
#
# @option arguments [String] :datafeed_id The ID of the datafeed to delete (*Required*)
# @option arguments [Boolean] :force True if the datafeed should be forcefully deleted
#
# @see http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-delete-datafeed.html
#
def delete_datafeed(arguments={})
raise ArgumentError, "Required argument 'datafeed_id' missing" unless arguments[:datafeed_id]
valid_params = [
:force ]
method = Elasticsearch::API::HTTP_DELETE
path = "_xpack/ml/datafeeds/#{arguments[:datafeed_id]}"
params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params
body = nil
perform_request(method, path, params, body).body
end
end
end
end
end
end
| 34.533333 | 105 | 0.612934 |
61a62976a2b1cf91c5605490329d9aac29d91d77 | 2,475 | require './util/debug'
# Uniforms:
# Data (variables) that are not vertex specific for a model.
#
# Uniforms
# have a variable name inside the shader code (gpu)
# have a location id in cpu space
#
# Looking up the location id from the variable name is expensive.
# So this class caches the location id after the first lookup.
#
class Uniforms_Location_Cache
def initialize
@uniform_locations = {}
end
# to do cache on program_id too
def uniform_location(program_id, name)
uniform_sym = name.to_sym
locations = @uniform_locations
locations[uniform_sym] ||= Gl.getUniformLocation(program_id, name.to_s)
end
alias_method :[], :uniform_location
end
class Gpu
def set_uniform_matrix(program_id, uniform_name, data)
location = @uniformsLocationCache.uniform_location(program_id, uniform_name)
d = data.to_a.flatten.pack("f*")
Gl.uniformMatrix4fv(location, 1, Gl::GL_FALSE, d)
check_for_gl_error(uniform_name: uniform_name, gl_program_id: program_id)
end
def set_uniform_vector(program_id, uniform_name, data, element_count=4)
location = @uniformsLocationCache.uniform_location(program_id, uniform_name)
data_array = data.to_a.first(element_count)
d = data_array.pack("f*")
Gl.uniform3f(location, *data_array) if element_count == 3
Gl.uniform4fv(location, 1, d) if element_count == 4
check_for_gl_error(uniform_name: uniform_name, gl_program_id: program_id)
end
# Set uniforms in bulk from data structure of form
#
# uniform_variables_hash = {
# var_name: = {container: {:vector, :matrix}, data: actual_data},
# model: = {container: :matrix, data: _matrix},
# color: = {container: :vector, data: _color},
# }
#
def set_uniforms_in_bulk(program_id, uniform_variables_hash)
uniform_variables_hash.each_pair do |parameter, config_and_data|
elements = config_and_data.fetch(:elements, 4)
#container = config_and_data[:container]
data = config_and_data[:data]
location = @uniformsLocationCache.uniform_location(program_id, parameter)
#set_uniform_matrix(program_id, parameter, data ) if container == :matrix
set_uniform_vector(program_id, parameter, data, elements ) if data.is_a? Geo3d::Vector
set_uniform_matrix(program_id, parameter, data ) if data.is_a? Geo3d::Matrix
Gl.uniform1f(location, data) if data.is_a? Float
Gl.uniform1i(location, data) if data.is_a? Integer
end
end
end
| 30.182927 | 92 | 0.724444 |
e871b9c6f14a4f3f3f0e768e7b8414960e4ec2dd | 623 | module PragmaticSegmenter
module Languages
class English
class Process < PragmaticSegmenter::Process
end
class Cleaner < PragmaticSegmenter::Cleaner
def clean
super
clean_quotations(@clean_text)
end
private
def clean_quotations(txt)
txt.gsub(/`/, "'")
end
def abbreviations
[]
end
end
class AbbreviationReplacer < PragmaticSegmenter::AbbreviationReplacer
private
def abbreviations
PragmaticSegmenter::Abbreviation.new
end
end
end
end
end
| 18.323529 | 76 | 0.585875 |
bfd0df1e53d96183f720b525aa2fa817864352d7 | 601 | require 'active_support/all'
require 'decent_exposure'
require 'decent_decoration'
require 'action_controller'
require 'action_dispatch'
require 'active_model'
module Rails
class App
def env_config; {} end
def routes
@routes ||= ActionDispatch::Routing::RouteSet.new.tap do |routes|
routes.draw do
resources :conferences, only: %i(show)
resources :attendees, only: %i(show)
end
end
end
end
def self.application
@app ||= App.new
end
end
require 'fixtures/models'
require 'fixtures/decorators'
require 'fixtures/controllers'
| 18.78125 | 71 | 0.687188 |
798bcd5c4a7c5667706802fcc3652b8908422b98 | 941 | class Hysteresis < ArduinoPlugin
# jdbarnhart
# 20080728
#
#
# purpose
#
# add hysteresis to analog readings, typically sensors or potentiometers
#
# use
# two steps
#
# one
# declare :device => :sensor
# example:
# input_pin 1, :as => :sensor_one, :device => :sensor
#
# two
# instead of:
# my_lcd.print analogRead sensor_two
# use add_hyst
# my_lcd.print sensor_one.with_hyst 4
#
# # note, 4 is the amount of hysteresis
#
#
void with_hysteresis(int pin, int amt)
{
with_hyst(pin, amt);
}
int with_hyst(int pin, int amt)
{
int read;
unsigned int i;
read = analogRead(pin);
for (i = 0; i < (int) (sizeof(hyst) / sizeof(hyst[0])); i++) {
if (pin == hyst[i].pin) {
if (((read - hyst[i].state) > amt ) || ((hyst[i].state - read) > amt )) {
hyst[i].state = read;
return hyst[i].state;
}
else
return hyst[i].state;
}
}
}
end | 18.096154 | 79 | 0.573858 |
61bf200a8a1242a581381e929ac7ce3d7a91c157 | 2,138 | # Copyright (c) 2010-2011, Diaspora Inc. This file is
# licensed under the Affero General Public License version 3 or later. See
# the COPYRIGHT file.
ENV["RAILS_ENV"] ||= 'test'
require File.join(File.dirname(__FILE__), '..', 'config', 'environment') unless defined?(Rails)
require 'helper_methods'
require 'rspec/rails'
require 'webmock/rspec'
require 'factory_girl'
include WebMock::API
WebMock::Config.instance.allow_localhost = false
include HelperMethods
# Force fixture rebuild
FileUtils.rm_f(File.join(Rails.root, 'tmp', 'fixture_builder.yml'))
# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
fixture_builder_file = "#{File.dirname(__FILE__)}/support/fixture_builder.rb"
support_files = Dir["#{File.dirname(__FILE__)}/support/**/*.rb"] - [fixture_builder_file]
support_files.each {|f| require f }
require fixture_builder_file
RSpec.configure do |config|
config.include Devise::TestHelpers, :type => :controller
config.mock_with :rspec
config.use_transactional_fixtures = true
config.before(:each) do
I18n.locale = :en
stub_request(:post, "https://pubsubhubbub.appspot.com/")
$process_queue = false
end
config.before(:each, :type => :controller) do
self.class.render_views
end
config.after(:all) do
`rm -rf #{Rails.root}/tmp/uploads/*`
end
end
Dir["#{File.dirname(__FILE__)}/shared_behaviors/**/*.rb"].each do |f|
require f
end
disable_typhoeus
ProcessedImage.enable_processing = false
def set_up_friends
[local_luke, local_leia, remote_raphael]
end
def alice
@alice ||= User.where(:username => 'alice').first
end
def bob
@bob ||= User.where(:username => 'bob').first
end
def eve
@eve ||= User.where(:username => 'eve').first
end
def local_luke
@local_luke ||= User.where(:username => 'luke').first
end
def local_leia
@local_leia ||= User.where(:username => 'leia').first
end
def remote_raphael
@remote_raphael ||= Person.where(:diaspora_handle => '[email protected]').first
end
def photo_fixture_name
@photo_fixture_name = File.join(File.dirname(__FILE__), 'fixtures', 'button.png')
end
| 24.860465 | 95 | 0.727315 |
088b1abcc4f0a41e3e18751b9cbf74e38dc84adb | 133 | class AddDescriptionToGalleries < ActiveRecord::Migration[5.1]
def change
add_column :galleries, :description, :text
end
end
| 22.166667 | 62 | 0.766917 |
01dfcb066421450db32f08da754827d481bea280 | 528 | # WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
require_relative '../../aws-sdk-core/spec/shared_spec_helper'
$:.unshift(File.expand_path('../../lib', __FILE__))
$:.unshift(File.expand_path('../../../aws-sdk-core/lib', __FILE__))
$:.unshift(File.expand_path('../../../aws-sigv4/lib', __FILE__))
require 'rspec'
require 'webmock/rspec'
require 'aws-sdk-mediaconnect'
| 31.058824 | 74 | 0.723485 |
5dfbdf4278b20466c2101723cc9971f9a3631de0 | 74 | # frozen_string_literal: true
module Extensions::FormForWithResource; end
| 24.666667 | 43 | 0.851351 |
9100960940d6eb54f5292130820ad22a9704068d | 142 | class AddDurationToIntervals < ActiveRecord::Migration[5.1]
def change
add_column :intervals, :duration, :integer, default: 0
end
end
| 23.666667 | 59 | 0.753521 |
08129012a201f5964d895dda55ad043cd033b998 | 1,984 | require "puppet/parameter/boolean"
# Autogenic core type
Puppet::Type.newtype(:azure_resource_group) do
@doc = "Resource group information."
ensurable
validate do
required_properties = [
:location,
:parameters,
]
required_properties.each do |property|
# We check for both places so as to cover the puppet resource path as well
if self[:ensure] == :present && self[property].nil? && self.provider.send(property) == :absent
raise Puppet::Error, "In azure_resource_group you must provide a value for #{property}"
end
end
end
newproperty(:id) do
desc "The ID of the resource group."
validate do |value|
true
end
end
newproperty(:location) do
desc "The location of the resource group. It cannot be changed after the resource group has been created. It must be one of the supported Azure locations."
validate do |value|
true
end
end
newproperty(:managed_by) do
desc "The ID of the resource that manages this resource group."
validate do |value|
true
end
end
newparam(:name) do
isnamevar
desc "The name of the resource group."
validate do |value|
true
end
end
newproperty(:properties) do
desc "The resource group properties."
validate do |value|
true
end
end
newproperty(:tags) do
desc "The tags attached to the resource group."
validate do |value|
true
end
end
newproperty(:type) do
desc "The type of the resource group."
validate do |value|
true
end
end
newparam(:api_version) do
desc "The API version to use for this operation."
validate do |value|
true
end
end
newparam(:parameters) do
desc "Parameters supplied to the create or update a resource group."
validate do |value|
true
end
end
newparam(:subscription_id) do
desc "The ID of the target subscription."
validate do |value|
true
end
end
end
| 23.619048 | 159 | 0.660282 |
085467a8258f5e8c01c19f4d69c00eed99ae183c | 77 | require 'test_helper'
class MyHeywatchHelperTest < ActionView::TestCase
end
| 15.4 | 49 | 0.831169 |
38d45a336f8f18b5b4e7cc08b9b7edb9b9827067 | 455 | #
# Cookbook Name:: jbpm
# Recipe:: default
#
# The attribute evaluates to either
# oracle_wrapper or oracle-xe_wrapper
#
# Set by jbpm recipe in rdk_provision
if ::File.exists?("/etc/oratab")
include_recipe "#{node[:jbpm][:oracle_cookbook]}::env_vars"
else
include_recipe "#{node[:jbpm][:oracle_cookbook]}"
end
include_recipe "jboss-eap_wrapper"
include_recipe "jbpm::install"
include_recipe "jbpm::oracle_config"
include_recipe "jbpm::configure"
| 22.75 | 61 | 0.753846 |
e8c2b6c879bdfb01c7b49ceaa911c4604735a1a4 | 668 | require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module SimpleQrCodeRails
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.2
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
end
end
| 33.4 | 82 | 0.767964 |
18aa41146f194912481889cdf905a5f94e21f050 | 2,078 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::AlertsManagement::Mgmt::V2019_03_01
module Models
#
# Properties of the operation
#
class OperationDisplay
include MsRestAzure
# @return [String] Provider name
attr_accessor :provider
# @return [String] Resource name
attr_accessor :resource
# @return [String] Operation name
attr_accessor :operation
# @return [String] Description of the operation
attr_accessor :description
#
# Mapper for OperationDisplay class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'operation_display',
type: {
name: 'Composite',
class_name: 'OperationDisplay',
model_properties: {
provider: {
client_side_validation: true,
required: false,
serialized_name: 'provider',
type: {
name: 'String'
}
},
resource: {
client_side_validation: true,
required: false,
serialized_name: 'resource',
type: {
name: 'String'
}
},
operation: {
client_side_validation: true,
required: false,
serialized_name: 'operation',
type: {
name: 'String'
}
},
description: {
client_side_validation: true,
required: false,
serialized_name: 'description',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 25.975 | 70 | 0.492782 |
2113ba9f3640d098702f75a9a2d5585c5672cae6 | 2,175 | #-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2017 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
require 'spec_helper'
describe 'my routes', type: :routing do
it '/my/add_block POST routes to my#add_block' do
expect(post('/my/add_block')).to route_to('my#add_block')
end
it '/my/page_layout GET routes to my#page_layout' do
expect(get('/my/page_layout')).to route_to('my#page_layout')
end
it '/my/remove_block POST routes to my#remove_block' do
expect(post('/my/remove_block')).to route_to('my#remove_block')
end
it '/my/account GET routes to my#account' do
expect(get('/my/account')).to route_to('my#account')
end
it '/my/account PATCH routes to my#account' do
expect(patch('/my/account')).to route_to('my#account')
end
it '/my/generate_rss_key POST routes to my#generate_rss_key' do
expect(post('/my/generate_rss_key')).to route_to('my#generate_rss_key')
end
it '/my/generate_api_key POST routes to my#generate_api_key' do
expect(post('/my/generate_api_key')).to route_to('my#generate_api_key')
end
end
| 36.25 | 91 | 0.738851 |
acd84ad210f477bd26455f523d83d71dc54b96ec | 408 | require 'test_helper'
class LikesControllerTest < ActionController::TestCase
test "should get like" do
get :like
assert_response :success
end
test "should get unlike" do
get :unlike
assert_response :success
end
test "should get create" do
get :create
assert_response :success
end
test "should get destroy" do
get :destroy
assert_response :success
end
end
| 16.32 | 54 | 0.703431 |
26e1b31a568cc89684028e95251c5b11100302ce | 300 | module Hamming
class << self
def compute(first, second)
raise ArgumentError if first.length != second.length
first.chars.zip(second.chars).reduce(0) do |diff, pair|
pair.first == pair.last ? diff : diff + 1
end
end
end
end
module BookKeeping
VERSION = 3
end
| 18.75 | 61 | 0.643333 |
e2d29de26deb67c6b69e173c3c505cee8076dc57 | 59,388 | require 'rails_helper'
feature 'Submission review overlay', js: true do
include UserSpecHelper
include MarkdownEditorHelper
include NotificationHelper
include SubmissionsHelper
include DevelopersNotificationsHelper
include ConfigHelper
let(:school) { create :school, :current }
let(:course) { create :course, school: school }
let(:level) { create :level, :one, course: course }
let(:target_group) { create :target_group, level: level }
let(:target) { create :target, :for_founders, target_group: target_group }
let(:target_2) { create :target, :for_founders, target_group: target_group }
let(:auto_verify_target) do
create :target, :for_founders, target_group: target_group
end
let(:grade_labels_for_1) do
[
{ 'grade' => 1, 'label' => 'Bad' },
{ 'grade' => 2, 'label' => 'Good' },
{ 'grade' => 3, 'label' => 'Great' },
{ 'grade' => 4, 'label' => 'Wow' }
]
end
let(:evaluation_criterion_1) do
create :evaluation_criterion,
course: course,
max_grade: 4,
pass_grade: 2,
grade_labels: grade_labels_for_1
end
let(:evaluation_criterion_2) { create :evaluation_criterion, course: course }
let(:team) { create :startup, level: level }
let(:coach) { create :faculty, school: school }
let(:team_coach_user) { create :user, name: 'John Doe' }
let(:team_coach) { create :faculty, school: school, user: team_coach_user }
let(:school_admin) { create :school_admin }
before do
create :faculty_course_enrollment, faculty: coach, course: course
create :faculty_course_enrollment, faculty: team_coach, course: course
create :faculty_startup_enrollment,
:with_course_enrollment,
faculty: team_coach,
startup: team
# Set evaluation criteria on the target so that its submissions can be reviewed.
target.evaluation_criteria << [
evaluation_criterion_1,
evaluation_criterion_2
]
target_2.evaluation_criteria << [
evaluation_criterion_1,
evaluation_criterion_2
]
end
context 'with a pending submission' do
let(:student) { team.founders.first }
let!(:submission_pending) do
create(
:timeline_event,
:with_owners,
owners: [student],
latest: true,
target: target
)
end
let!(:submission_pending_2) do
create(
:timeline_event,
:with_owners,
owners: [student],
latest: true,
target: target_2,
reviewer_assigned_at: 1.day.ago,
reviewer: team_coach
)
end
let!(:submission_file_attachment) do
create(:timeline_event_file, timeline_event: submission_pending)
end
let!(:submission_audio_attachment) do
create(
:timeline_event_file,
timeline_event: submission_pending,
file_path: 'files/audio_file_sample.mp3'
)
end
scenario 'coach visits submission review page' do
sign_in_user coach.user,
referrer: review_timeline_event_path(submission_pending)
within("div[aria-label='submissions-overlay-header']") do
expect(page).to have_content('Level 1')
expect(page).to have_content("Submitted by #{student.name}")
expect(page).to have_link(
student.name,
href: "/students/#{student.id}/report"
)
expect(page).to have_link(target.title, href: "/targets/#{target.id}")
expect(page).to have_content(target.title)
expect(page).to have_text 'Assigned Coaches'
# Hovering over the avatar should reveal the name of the assigned coach.
page.find('svg', text: 'JD').hover
expect(page).to have_text('John Doe')
end
click_button 'Start Review'
dismiss_notification
expect(page).to have_content('Add Your Feedback')
expect(page).to have_content('Grade Card')
expect(page).to have_content(evaluation_criterion_1.name)
expect(page).to have_content(evaluation_criterion_2.name)
expect(page).to have_button('Save grades', disabled: true)
click_button 'Remove assignment'
dismiss_notification
expect(page).to have_button('Start Review')
end
scenario 'coach visits an assigned submission' do
sign_in_user team_coach.user,
referrer: review_timeline_event_path(submission_pending_2)
expect(page).to have_text(team_coach.name)
expect(page).not_to have_text('Start Review')
expect(page).to have_button('Remove assignment')
end
scenario 'coach takes over an assigned submission' do
sign_in_user coach.user,
referrer: review_timeline_event_path(submission_pending_2)
expect(page).to have_text(team_coach.name)
expect(page).not_to have_text('Start Review')
click_button 'Yes, Assign Me'
dismiss_notification
expect(page).to have_text(coach.name)
expect(page).to have_button('Remove assignment')
end
scenario 'coach evaluates a pending submission and gives a feedback' do
notification_service = prepare_developers_notification
sign_in_user coach.user, referrer: review_course_path(course)
expect(page).to have_content(target.title)
expect(page).to have_content(target_2.title)
find("a[data-submission-id='#{submission_pending.id}']").click
click_button 'Start Review'
dismiss_notification
expect(submission_pending.reload.reviewer).to eq(coach)
expect(submission_pending.reviewer_assigned_at).not_to eq(nil)
expect(page).to have_content('Grade Card')
feedback = Faker::Markdown.sandwich(sentences: 6)
add_markdown(feedback)
within(
"div[aria-label='evaluation-criterion-#{evaluation_criterion_1.id}']"
) do
expect(page).to have_selector(
'.course-review-editor__grade-pill',
count: 4
)
find("button[title='Bad']").click
end
# status should be reviewing as the target is not graded completely
within("div[aria-label='submission-status']") do
expect(page).to have_text('Reviewing')
end
within(
"div[aria-label='evaluation-criterion-#{evaluation_criterion_2.id}']"
) do
expect(page).to have_selector(
'.course-review-editor__grade-pill',
count: 3
)
find("button[title='Bad']").click
end
# the status should be Rejected
within("div[aria-label='submission-status']") do
expect(page).to have_text('Rejected')
end
within(
"div[aria-label='evaluation-criterion-#{evaluation_criterion_2.id}']"
) { find("button[title='Good']").click }
# the status should be Rejected
within("div[aria-label='submission-status']") do
expect(page).to have_text('Rejected')
end
click_button 'Save grades & send feedback'
expect(page).to have_text('The submission has been marked as reviewed')
dismiss_notification
expect(page).to have_button('Undo Grading')
submission = submission_pending.reload
expect(submission.reviewer).to eq(nil)
expect(submission.reviewer_assigned_at).to eq(nil)
expect(submission.evaluator_id).to eq(coach.id)
expect(submission.passed_at).to eq(nil)
expect(submission.evaluated_at).not_to eq(nil)
expect(submission.startup_feedback.count).to eq(1)
expect(submission.startup_feedback.last.feedback).to eq(feedback)
expect(submission.timeline_event_grades.pluck(:grade)).to contain_exactly(
1,
2
)
# the submission must be removed from the pending list
find("button[aria-label='submissions-overlay-close']").click
click_link 'Pending'
expect(page).to have_text(submission_pending_2.target.title)
expect(page).to_not have_text(submission.target.title)
expect_published(
notification_service,
course,
:submission_graded,
coach.user,
submission
)
end
scenario 'coach generates feedback from review checklist' do
sign_in_user coach.user,
referrer: review_timeline_event_path(submission_pending)
# Checklist item 1
checklist_title_1 = Faker::Lorem.sentence
c1_result_0_title = Faker::Lorem.sentence
c1_result_0_feedback = Faker::Markdown.sandwich(sentences: 3)
c1_result_1_title = Faker::Lorem.sentence
c1_result_1_feedback = Faker::Markdown.sandwich(sentences: 3)
# Checklist item 2
checklist_title_2 = Faker::Lorem.sentence
c2_result_0_title = Faker::Lorem.sentence
c2_result_0_feedback = Faker::Markdown.sandwich(sentences: 3)
c2_result_1_title = Faker::Lorem.sentence
c2_result_1_feedback = Faker::Markdown.sandwich(sentences: 3)
expect(target.review_checklist).to eq([])
click_button 'Start Review'
dismiss_notification
click_button 'Create Review Checklist'
within("div[data-checklist-item='0']") do
fill_in 'checklist_0_title', with: checklist_title_1
fill_in 'result_00_title', with: c1_result_0_title
fill_in 'result_00_feedback', with: c1_result_0_feedback
fill_in 'result_01_title', with: c1_result_1_title
fill_in 'result_01_feedback', with: c1_result_1_feedback
end
click_button 'Add Checklist Item'
within("div[data-checklist-item='1']") do
fill_in 'checklist_1_title', with: checklist_title_2
fill_in 'result_10_title', with: c2_result_0_title
fill_in 'result_10_feedback', with: c2_result_0_feedback
click_button 'Add Result'
fill_in 'result_11_title', with: c2_result_1_title
fill_in 'result_11_feedback', with: c2_result_1_feedback
end
click_button 'Save Checklist'
expect(page).to have_content('Edit Checklist')
expect(target.reload.review_checklist).not_to eq([])
# Reload Page
visit review_timeline_event_path(submission_pending)
click_button 'Show Review Checklist'
within("div[data-checklist-item='0']") do
expect(page).to have_content(checklist_title_1)
within("div[data-result-item='0']") do
expect(page).to have_content(c1_result_0_title)
find('label', text: c1_result_0_title).click
end
within("div[data-result-item='1']") do
expect(page).to have_content(c1_result_1_title)
find('label', text: c1_result_1_title).click
end
end
within("div[data-checklist-item='1']") do
expect(page).to have_content(checklist_title_2)
within("div[data-result-item='0']") do
expect(page).to have_content(c2_result_0_title)
find('label', text: c2_result_0_title).click
end
within("div[data-result-item='1']") do
expect(page).to have_content(c2_result_1_title)
find('label', text: c2_result_1_title).click
end
end
click_button 'Generate Feedback'
expect(page).not_to have_button('Generate Feedback')
expect(page).to have_text('Feedback generated from review checklist')
within("div[aria-label='feedback']") do
expect(page).to have_content(c1_result_0_feedback)
expect(page).to have_content(c1_result_1_feedback)
expect(page).to have_content(c2_result_0_feedback)
end
click_button 'Show Review Checklist'
click_button 'Edit Checklist'
within("div[data-checklist-item='1']") do
within("div[data-result-item='0']") do
find("button[title='Remove checklist result']").click
end
end
within("div[data-checklist-item='1']") do
find("button[title='Remove checklist item']").click
end
within("div[data-checklist-item='0']") do
find("button[title='Remove checklist item']").click
end
click_button 'Save Checklist'
click_button 'Create Review Checklist'
expect(target.reload.review_checklist).to eq([])
end
scenario 'coach changes the order of review checklist' do
sign_in_user coach.user,
referrer: review_timeline_event_path(submission_pending)
# Checklist item 1
checklist_title_1 = 'Checklist item one'
c1_result_0_title = Faker::Lorem.sentence
c1_result_0_feedback = Faker::Markdown.sandwich(sentences: 3)
c1_result_1_title = Faker::Lorem.sentence
c1_result_1_feedback = Faker::Markdown.sandwich(sentences: 3)
# Checklist item 2
checklist_title_2 = 'Checklist item two'
c2_result_0_title = Faker::Lorem.sentence
c2_result_0_feedback = Faker::Markdown.sandwich(sentences: 3)
c2_result_1_title = Faker::Lorem.sentence
c2_result_1_feedback = Faker::Markdown.sandwich(sentences: 3)
# Checklist item 3
checklist_title_3 = 'Checklist item three'
c3_result_0_title = Faker::Lorem.sentence
c3_result_0_feedback = Faker::Markdown.sandwich(sentences: 3)
c3_result_1_title = Faker::Lorem.sentence
c3_result_1_feedback = Faker::Markdown.sandwich(sentences: 3)
expect(target.review_checklist).to eq([])
click_button 'Start Review'
dismiss_notification
click_button 'Create Review Checklist'
within("div[data-checklist-item='0']") do
fill_in 'checklist_0_title', with: checklist_title_1
fill_in 'result_00_title', with: c1_result_0_title
fill_in 'result_00_feedback', with: c1_result_0_feedback
fill_in 'result_01_title', with: c1_result_1_title
fill_in 'result_01_feedback', with: c1_result_1_feedback
end
click_button 'Add Checklist Item'
within("div[data-checklist-item='1']") do
fill_in 'checklist_1_title', with: checklist_title_2
fill_in 'result_10_title', with: c2_result_0_title
fill_in 'result_10_feedback', with: c2_result_0_feedback
click_button 'Add Result'
fill_in 'result_11_title', with: c2_result_1_title
fill_in 'result_11_feedback', with: c2_result_1_feedback
end
click_button 'Add Checklist Item'
within("div[data-checklist-item='2']") do
fill_in 'checklist_2_title', with: checklist_title_3
fill_in 'result_20_title', with: c3_result_0_title
fill_in 'result_20_feedback', with: c3_result_0_feedback
click_button 'Add Result'
fill_in 'result_21_title', with: c3_result_1_title
fill_in 'result_21_feedback', with: c3_result_1_feedback
end
click_button 'Save Checklist'
expect(page).to have_content('Edit Checklist')
expect(target.reload.review_checklist).not_to eq([])
# Reload Page
visit review_timeline_event_path(submission_pending)
click_button 'Show Review Checklist'
click_button 'Edit Checklist'
# The first checklist item should only have the "move down" button.
within("div[data-checklist-item='0']") do
expect(page).to_not have_button('Move Up checklist item')
find("button[title='Move Down checklist item']")
end
# Checklist item in the middle should have both buttons.
within("div[data-checklist-item='1']") do
find("button[title='Move Up checklist item']")
find("button[title='Move Down checklist item']")
end
#The last checklist item should only have the "move up" button.
within("div[data-checklist-item='2']") do
expect(page).to_not have_button('Move Down checklist item')
find("button[title='Move Up checklist item']")
end
# The second checklist item, moved up
within("div[data-checklist-item='1']") do
find("button[title='Move Up checklist item']").click
end
# The first checklist item, should have the content as checklist_item_2 and should loose the "move up button"
within("div[data-checklist-item='0']") do
expect(page).to_not have_button('Move Up checklist item')
find("button[title='Move Down checklist item']")
expect(
find('input', id: 'checklist_0_title').value
).to eq checklist_title_2
within("div[data-result-item='0']") do
expect(
find('input', id: 'result_00_title').value
).to eq c2_result_0_title
end
within("div[data-result-item='1']") do
expect(
find('input', id: 'result_01_title').value
).to eq c2_result_1_title
end
end
# The second checklist item, moved down
within("div[data-checklist-item='1']") do
find("button[title='Move Down checklist item']").click
end
# The middle checklist item, should have the content as checklist_item_3 and should have the "move up & down button"
within("div[data-checklist-item='1']") do
find("button[title='Move Up checklist item']")
find("button[title='Move Down checklist item']")
expect(
find('input', id: 'checklist_1_title').value
).to eq checklist_title_3
within("div[data-result-item='0']") do
expect(
find('input', id: 'result_10_title').value
).to eq c3_result_0_title
end
within("div[data-result-item='1']") do
expect(
find('input', id: 'result_11_title').value
).to eq c3_result_1_title
end
end
# Results iniside checklist item move up & move down
within("div[data-checklist-item='1']") do
within("div[data-result-item='0']") do
expect(page).to_not have_button('Move Up checklist result')
find("button[title='Move Down checklist result']").click
expect(
find('input', id: 'result_10_title').value
).to eq c3_result_1_title
end
within("div[data-result-item='1']") do
expect(page).to_not have_button('Move Down checklist result')
find("button[title='Move Up checklist result']").click
expect(
find('input', id: 'result_11_title').value
).to eq c3_result_1_title
end
end
click_button 'Save Checklist'
expect(page).to have_content('Edit Checklist')
expect(target.reload.review_checklist).not_to eq([])
# Reload Page
visit review_timeline_event_path(submission_pending)
click_button 'Show Review Checklist'
within("div[data-checklist-item='0']") do
expect(page).to have_content(checklist_title_2)
within("div[data-result-item='0']") do
expect(page).to have_content(c2_result_0_title)
find('label', text: c2_result_0_title).click
end
within("div[data-result-item='1']") do
expect(page).to have_content(c2_result_1_title)
find('label', text: c2_result_1_title).click
end
end
within("div[data-checklist-item='1']") do
expect(page).to have_content(checklist_title_3)
within("div[data-result-item='0']") do
expect(page).to have_content(c3_result_0_title)
find('label', text: c3_result_0_title).click
end
within("div[data-result-item='1']") do
expect(page).to have_content(c3_result_1_title)
find('label', text: c3_result_1_title).click
end
end
within("div[data-checklist-item='2']") do
expect(page).to have_content(checklist_title_1)
within("div[data-result-item='0']") do
expect(page).to have_content(c1_result_0_title)
find('label', text: c1_result_0_title).click
end
within("div[data-result-item='1']") do
expect(page).to have_content(c1_result_1_title)
find('label', text: c1_result_1_title).click
end
end
end
scenario 'coach evaluates a pending submission and mark a checklist as incorrect' do
question_1 = Faker::Lorem.sentence
question_2 = Faker::Lorem.sentence
question_3 = Faker::Lorem.sentence
question_4 = Faker::Lorem.sentence
question_5 = Faker::Lorem.sentence
question_6 = Faker::Lorem.sentence
answer_1 = Faker::Lorem.sentence
answer_2 = 'https://example.org/invalidLink'
answer_3 = Faker::Lorem.sentence
answer_4 = Faker::Lorem.sentence
answer_5 = [submission_file_attachment.id.to_s]
answer_6 = submission_audio_attachment.id.to_s
submission_checklist_long_text = {
'kind' => Target::CHECKLIST_KIND_LONG_TEXT,
'title' => question_1,
'result' => answer_1,
'status' => TimelineEvent::CHECKLIST_STATUS_NO_ANSWER
}
submission_checklist_link = {
'kind' => Target::CHECKLIST_KIND_LINK,
'title' => question_2,
'result' => answer_2,
'status' => TimelineEvent::CHECKLIST_STATUS_NO_ANSWER
}
submission_checklist_choice = {
'kind' => Target::CHECKLIST_KIND_MULTI_CHOICE,
'title' => question_3,
'result' => answer_3,
'status' => TimelineEvent::CHECKLIST_STATUS_NO_ANSWER
}
submission_checklist_short_text = {
'kind' => Target::CHECKLIST_KIND_SHORT_TEXT,
'title' => question_4,
'result' => answer_4,
'status' => TimelineEvent::CHECKLIST_STATUS_NO_ANSWER
}
submission_checklist_files = {
'kind' => Target::CHECKLIST_KIND_FILES,
'title' => question_5,
'result' => answer_5,
'status' => TimelineEvent::CHECKLIST_STATUS_NO_ANSWER
}
submission_checklist_audio = {
'kind' => Target::CHECKLIST_KIND_AUDIO,
'title' => question_6,
'result' => answer_6,
'status' => TimelineEvent::CHECKLIST_STATUS_NO_ANSWER
}
submission_checklist = [
submission_checklist_long_text,
submission_checklist_link,
submission_checklist_choice,
submission_checklist_short_text,
submission_checklist_files,
submission_checklist_audio
]
submission_pending.update!(checklist: submission_checklist)
sign_in_user coach.user,
referrer: review_timeline_event_path(submission_pending)
click_button 'Start Review'
dismiss_notification
within(
"div[aria-label='#{submission_pending.checklist.first['title']}']"
) do
expect(page).to have_content(question_1)
expect(page).to have_content(answer_1)
end
within(
"div[aria-label='#{submission_pending.checklist.second['title']}']"
) do
expect(page).to have_content(question_2)
expect(page).to have_content(answer_2)
click_button 'Mark as incorrect'
expect(page).to have_content('Mark as correct')
end
within(
"div[aria-label='#{submission_pending.checklist.third['title']}']"
) do
expect(page).to have_content(question_3)
expect(page).to have_content(answer_3)
click_button 'Mark as incorrect'
expect(page).to have_content('Mark as correct')
end
within("div[aria-label='#{submission_pending.checklist[5]['title']}']") do
expect(page).to have_content(question_6)
click_button 'Mark as incorrect'
expect(page).to have_content('Mark as correct')
end
expect(page).to have_content('Grade Card')
within(
"div[aria-label='evaluation-criterion-#{evaluation_criterion_1.id}']"
) { find("button[title='Good']").click }
# status should be reviewing as the target is not graded completely
within("div[aria-label='submission-status']") do
expect(page).to have_text('Reviewing')
end
within(
"div[aria-label='evaluation-criterion-#{evaluation_criterion_2.id}']"
) { find("button[title='Good']").click }
# the status should be Rejected
within("div[aria-label='submission-status']") do
expect(page).to have_text('Completed')
end
click_button 'Save grades'
expect(page).to have_text('The submission has been marked as reviewed')
dismiss_notification
within(
"div[aria-label='#{submission_pending.checklist.second['title']}']"
) { expect(page).to have_content('Incorrect') }
new_checklist = [
submission_checklist_long_text,
{
'kind' => Target::CHECKLIST_KIND_LINK,
'title' => question_2,
'result' => answer_2,
'status' => TimelineEvent::CHECKLIST_STATUS_FAILED
},
{
'kind' => Target::CHECKLIST_KIND_MULTI_CHOICE,
'title' => question_3,
'result' => answer_3,
'status' => TimelineEvent::CHECKLIST_STATUS_FAILED
},
submission_checklist_short_text,
submission_checklist_files,
{
'kind' => Target::CHECKLIST_KIND_AUDIO,
'title' => question_6,
'result' => answer_6,
'status' => TimelineEvent::CHECKLIST_STATUS_FAILED
}
]
expect(submission_pending.reload.checklist).to eq(new_checklist)
# Reload page
visit review_timeline_event_path(submission_pending)
within(
"div[aria-label='#{submission_pending.checklist.first['title']}']"
) do
find('p', text: question_1).click
expect(page).to have_content(answer_1)
end
within(
"div[aria-label='#{submission_pending.checklist.second['title']}']"
) do
expect(page).to have_content(question_2)
expect(page).to have_content(answer_2)
expect(page).to have_content('Incorrect')
end
within(
"div[aria-label='#{submission_pending.checklist.third['title']}']"
) do
expect(page).to have_content(question_3)
expect(page).to have_content(answer_3)
expect(page).to have_content('Incorrect')
end
within(
"div[aria-label='#{submission_pending.checklist.last['title']}']"
) do
find('p', text: question_6).click
expect(page).to have_content('Incorrect')
end
accept_confirm { click_button('Undo Grading') }
click_button 'Start Review'
dismiss_notification
expect(page).to have_text('Add Your Feedback')
expect(submission_pending.reload.checklist).to eq(submission_checklist)
end
scenario 'coach evaluates a pending submission without giving a feedback' do
sign_in_user coach.user,
referrer: review_timeline_event_path(submission_pending)
click_button 'Start Review'
dismiss_notification
expect(page).to have_content('Grade Card')
within(
"div[aria-label='evaluation-criterion-#{evaluation_criterion_1.id}']"
) { find("button[title='Good']").click }
# status should be reviewing as the target is not graded completely
within("div[aria-label='submission-status']") do
expect(page).to have_text('Reviewing')
end
within(
"div[aria-label='evaluation-criterion-#{evaluation_criterion_2.id}']"
) { find("button[title='Good']").click }
# the status should be completed
within("div[aria-label='submission-status']") do
expect(page).to have_text('Completed')
end
click_button 'Save grades'
expect(page).to have_text('The submission has been marked as reviewed')
dismiss_notification
expect(page).to have_button('Undo Grading')
submission = submission_pending.reload
expect(submission.evaluator_id).to eq(coach.id)
expect(submission.passed_at).not_to eq(nil)
expect(submission.evaluated_at).not_to eq(nil)
expect(submission.startup_feedback.count).to eq(0)
expect(submission.timeline_event_grades.pluck(:grade)).to eq([2, 2])
end
scenario 'student tries to access the submission review page' do
sign_in_user team.founders.first.user,
referrer: review_timeline_event_path(submission_pending)
expect(page).to have_text("The page you were looking for doesn't exist!")
end
scenario 'school admin tries to access the submission review page' do
sign_in_user school_admin.user,
referrer: review_timeline_event_path(submission_pending)
expect(page).to have_text("The page you were looking for doesn't exist!")
end
scenario 'coach is warned when a student has dropped out' do
team.update!(dropped_out_at: 1.day.ago)
sign_in_user coach.user,
referrer: review_timeline_event_path(submission_pending)
expect(page).to have_text(
'This submission is from a student whose access to the course has ended, or has dropped out.'
)
end
scenario "coach is warned when a student's access to course has ended" do
team.update!(access_ends_at: 1.day.ago)
sign_in_user coach.user,
referrer: review_timeline_event_path(submission_pending)
expect(page).to have_text(
'This submission is from a student whose access to the course has ended, or has dropped out.'
)
end
context 'when submission is from students who are now in different teams' do
let(:another_team) do
create :startup, level: level, dropped_out_at: 1.day.ago
end
before { submission_pending.founders << another_team.founders.first }
scenario 'coach is warned when one student in the submission is inactive' do
sign_in_user coach.user,
referrer: review_timeline_event_path(submission_pending)
expect(page).to have_text(
'This submission is linked to one or more students whose access to the course has ended, or have dropped out.'
)
end
end
scenario 'coach leaves a note about a student' do
note = Faker::Lorem.sentence
sign_in_user team_coach.user,
referrer: review_timeline_event_path(submission_pending)
click_button 'Start Review'
dismiss_notification
click_button 'Write a Note'
add_markdown note, id: "note-for-submission-#{submission_pending.id}"
within(
"div[aria-label='evaluation-criterion-#{evaluation_criterion_1.id}']"
) { find("button[title='Good']").click }
within(
"div[aria-label='evaluation-criterion-#{evaluation_criterion_2.id}']"
) { find("button[title='Good']").click }
click_button 'Save grades'
expect(page).to have_text('The submission has been marked as reviewed')
dismiss_notification
new_notes = CoachNote.where(note: note)
expect(new_notes.count).to eq(1)
expect(new_notes.first.student_id).to eq(student.id)
end
scenario 'coach leaves a note for a team submission' do
another_student = team.founders.where.not(id: student).first
submission_pending.founders << another_student
note = Faker::Lorem.sentence
sign_in_user team_coach.user,
referrer: review_timeline_event_path(submission_pending)
click_button 'Start Review'
dismiss_notification
click_button 'Write a Note'
add_markdown note, id: "note-for-submission-#{submission_pending.id}"
within(
"div[aria-label='evaluation-criterion-#{evaluation_criterion_1.id}']"
) { find("button[title='Good']").click }
within(
"div[aria-label='evaluation-criterion-#{evaluation_criterion_2.id}']"
) { find("button[title='Good']").click }
click_button 'Save grades'
expect(page).to have_text('The submission has been marked as reviewed')
dismiss_notification
new_notes = CoachNote.where(note: note)
expect(new_notes.count).to eq(2)
expect(new_notes.pluck(:student_id)).to contain_exactly(
student.id,
another_student.id
)
end
scenario 'coach opens the overlay for a submission after its status has changed in the DB' do
# Opening the overlay should reload data on index if it's different.
sign_in_user coach.user, referrer: review_course_path(course)
click_link 'Pending'
expect(page).to have_text(target.title)
expect(page).to have_text(target_2.title)
# Review the submission from the backend.
submission_pending.update(
passed_at: Time.zone.now,
evaluated_at: Time.zone.now,
evaluator: coach
)
grade_submission(
submission_pending,
SubmissionsHelper::GRADE_PASS,
target
)
# Open the overlay.
find("a[data-submission-id='#{submission_pending.id}']").click
# It should show Completed.
within("div[aria-label='submission-status']") do
expect(page).to have_text('Completed')
end
find("button[aria-label='submissions-overlay-close']").click
# Closing the overlay should show that the item has been removed from the pending list.
expect(page).not_to have_text(target.title)
expect(page).to have_text(target_2.title) # The second submission should still be there.
# The submission should be visible in the Pending list.
click_link 'Reviewed'
# The submission should show up in the Reviewed list.
expect(page).to have_text(target.title)
# Undo the grading of the submission from the backend.
submission_pending.timeline_event_grades.destroy_all
submission_pending.update(
passed_at: nil,
evaluated_at: nil,
evaluator: nil
)
find("a[data-submission-id='#{submission_pending.id}']").click
# The overlay should show pending review status.
expect(page).to have_text('Start Review')
find("button[aria-label='submissions-overlay-close']").click
# Closing the overlay should show that the item has been removed from the reviewed list.
expect(page).not_to have_text(target.title)
end
end
context 'when the course has inactive students' do
let(:inactive_team) do
create :startup, level: level, access_ends_at: 1.day.ago
end
let!(:pending_submission_from_inactive_team) do
create(
:timeline_event,
:with_owners,
latest: true,
owners: inactive_team.founders,
target: target
)
end
let!(:reviewed_submission_from_inactive_team) do
create(
:timeline_event,
:with_owners,
latest: true,
owners: inactive_team.founders,
target: target,
evaluator_id: coach.id,
evaluated_at: 1.day.ago,
passed_at: 1.day.ago
)
end
before do
create(
:timeline_event_grade,
timeline_event: reviewed_submission_from_inactive_team,
evaluation_criterion: evaluation_criterion_1,
grade: 4
)
end
scenario 'coach visits pending submission page' do
sign_in_user coach.user,
referrer:
review_timeline_event_path(
pending_submission_from_inactive_team
)
expect(page).to have_button('Create Review Checklist', disabled: true)
expect(page).to have_button('Write a Note', disabled: true)
expect(page).to have_button('Save grades', disabled: true)
end
scenario 'coach visits reviewed submission page' do
sign_in_user coach.user,
referrer:
review_timeline_event_path(
reviewed_submission_from_inactive_team
)
expect(page).to have_button('Undo Grading', disabled: true)
expect(page).to have_button('Add feedback', disabled: true)
end
end
context 'with a reviewed submission' do
let!(:submission_reviewed) do
create(
:timeline_event,
:with_owners,
latest: true,
owners: team.founders,
target: target,
evaluator_id: coach.id,
evaluated_at: 1.day.ago,
passed_at: 1.day.ago
)
end
let!(:timeline_event_grade) do
create(
:timeline_event_grade,
timeline_event: submission_reviewed,
evaluation_criterion: evaluation_criterion_1,
grade: 4
)
end
scenario 'coach visits submission review page' do
sign_in_user coach.user,
referrer: review_timeline_event_path(submission_reviewed)
within("div[aria-label='submissions-overlay-header']") do
expect(page).to have_content('Level 1')
expect(page).to have_content('Submitted by')
# Each name should be linked to the report page.
team.founders.each do |student|
expect(page).to have_link(
student.name,
href: "/students/#{student.id}/report"
)
end
expect(page).to have_link(target.title, href: "/targets/#{target.id}")
end
expect(page).to have_content('Submission 1')
expect(page).to have_content('Completed')
within("div[aria-label='submission-status']") do
expect(page).to have_text('Completed')
expect(page).to have_text('Evaluated By')
expect(page).to have_text(coach.name)
end
expect(page).to have_button('Undo Grading')
within(
"div[aria-label='evaluation-criterion-#{evaluation_criterion_1.id}']"
) do
expect(page).to have_text(evaluation_criterion_1.name)
expect(page).to have_text(
"#{timeline_event_grade.grade}/#{evaluation_criterion_1.max_grade}"
)
end
expect(page).to have_button('Add feedback')
end
scenario 'coach add his feedback' do
sign_in_user coach.user,
referrer: review_timeline_event_path(submission_reviewed)
within("div[aria-label='submission-status']") do
expect(page).to have_text('Completed')
expect(page).to have_text('Evaluated By')
expect(page).to have_text(coach.name)
end
expect(page).to have_button('Undo Grading')
expect(page).to have_button('Add feedback')
click_button 'Add feedback'
expect(page).not_to have_button('Add feedback')
expect(page).to have_button('Share Feedback', disabled: true)
feedback = Faker::Markdown.sandwich(sentences: 6)
add_markdown(feedback)
click_button 'Share Feedback'
expect(page).to have_text('Your feedback will be e-mailed to the student')
dismiss_notification
expect(page).to have_button('Add another feedback')
within("div[data-title='feedback-section']") do
expect(page).to have_text(coach.name)
end
submission = submission_reviewed.reload
expect(submission.startup_feedback.count).to eq(1)
expect(submission.startup_feedback.last.feedback).to eq(feedback)
end
scenario 'coach can undo grading' do
sign_in_user coach.user,
referrer: review_timeline_event_path(submission_reviewed)
within("div[aria-label='submission-status']") do
expect(page).to have_text('Completed')
expect(page).to have_text('Evaluated By')
expect(page).to have_text(coach.name)
end
accept_confirm { click_button 'Undo Grading' }
expect(page).to have_text('Start Review')
submission = submission_reviewed.reload
expect(submission.evaluator_id).to eq(nil)
expect(submission.passed_at).to eq(nil)
expect(submission.evaluated_at).to eq(nil)
expect(submission.timeline_event_grades).to eq([])
end
scenario 'coach uses the next button' do
sign_in_user coach.user,
referrer: review_timeline_event_path(submission_reviewed)
click_button 'Next'
expect(page).to have_text('There are no other similar submissions.')
dismiss_notification
end
context 'with two reviewed submissions' do
let!(:submission_reviewed_old) do
create(
:timeline_event,
:with_owners,
owners: team.founders,
target: target,
created_at: 3.days.ago
)
end
scenario 'coach re-grades an old submission' do
sign_in_user coach.user,
referrer:
review_timeline_event_path(submission_reviewed_old)
click_button 'Start Review'
dismiss_notification
within(
"div[aria-label='evaluation-criterion-#{evaluation_criterion_1.id}']"
) { find("button[title='Good']").click }
within(
"div[aria-label='evaluation-criterion-#{evaluation_criterion_2.id}']"
) { find("button[title='Bad']").click }
click_button 'Save grades'
expect(page).to have_text('The submission has been marked as reviewed')
click_link 'Submission #1'
expect(page).to have_text('Submission 1')
expect(page).to have_text('2/4')
expect(page).to have_text('1/3')
click_link 'Submission #2'
expect(page).to have_text('Submission 2')
expect(page).to have_text('4/4')
end
scenario 'coach uses the next button' do
sign_in_user coach.user,
referrer: review_timeline_event_path(submission_reviewed)
click_button 'Next'
expect(page).to have_current_path(
"#{review_timeline_event_path(submission_reviewed_old)}?sortCriterion=SubmittedAt&sortDirection=Descending"
)
end
end
end
context 'when evaluation criteria changed for a target with graded submissions' do
let(:target_1) { create :target, :for_founders, target_group: target_group }
let!(:submission_reviewed) do
create(
:timeline_event,
:with_owners,
latest: true,
owners: [team.founders.first],
target: target_1,
evaluator_id: coach.id,
evaluated_at: 1.day.ago,
passed_at: 1.day.ago
)
end
let!(:timeline_event_grade_1) do
create(
:timeline_event_grade,
timeline_event: submission_reviewed,
evaluation_criterion: evaluation_criterion_1
)
end
let!(:timeline_event_grade_2) do
create(
:timeline_event_grade,
timeline_event: submission_reviewed,
evaluation_criterion: evaluation_criterion_2
)
end
let!(:submission_pending) do
create(
:timeline_event,
:with_owners,
latest: true,
owners: [team.founders.first],
target: target_1
)
end
before { target_1.evaluation_criteria << [evaluation_criterion_1] }
scenario 'coach visits a submission and grades pending submission' do
sign_in_user coach.user,
referrer: review_timeline_event_path(submission_reviewed)
# Evaluation criteria at the point of grading are shown for reviewed submissions
within(
"div[aria-label='evaluation-criterion-#{evaluation_criterion_1.id}']"
) do
expect(page).to have_text(evaluation_criterion_1.name)
expect(page).to have_text(
"#{timeline_event_grade_1.grade}/#{evaluation_criterion_1.max_grade}"
)
end
within(
"div[aria-label='evaluation-criterion-#{evaluation_criterion_2.id}']"
) do
expect(page).to have_text(evaluation_criterion_2.name)
expect(page).to have_text(
"#{timeline_event_grade_2.grade}/#{evaluation_criterion_2.max_grade}"
)
end
click_link 'Submission #2'
click_button 'Start Review'
dismiss_notification
# New list of evaluation criteria are shown for pending submissions
expect(page).to have_text(evaluation_criterion_1.name)
expect(page).not_to have_text(evaluation_criterion_2.name)
# grades the pending submission
within(
"div[aria-label='evaluation-criterion-#{evaluation_criterion_1.id}']"
) { find("button[title='Good']").click }
click_button 'Save grades'
expect(page).to have_text('The submission has been marked as reviewed')
dismiss_notification
end
end
context 'with a reviewed submission that has feedback' do
let!(:submission_reviewed) do
create(
:timeline_event,
:with_owners,
latest: true,
owners: [team.founders.first],
target: target,
evaluator_id: coach.id,
evaluated_at: 1.day.ago,
passed_at: 1.day.ago
)
end
let!(:feedback) do
create(
:startup_feedback,
faculty_id: coach.id,
timeline_event: submission_reviewed
)
end
let!(:timeline_event_grade) do
create(
:timeline_event_grade,
timeline_event: submission_reviewed,
evaluation_criterion: evaluation_criterion_1
)
end
scenario 'team coach add his feedback' do
sign_in_user team_coach.user,
referrer: review_timeline_event_path(submission_reviewed)
within("div[aria-label='submission-status']") do
expect(page).to have_text('Completed')
expect(page).to have_text('Evaluated By')
expect(page).to have_text(coach.name)
end
expect(page).to have_button('Undo Grading')
within("div[data-title='feedback-section']") do
expect(page).to have_text(coach.name)
end
expect(page).to have_button('Add another feedback')
click_button 'Add another feedback'
expect(page).not_to have_button('Add feedback')
expect(page).to have_button('Share Feedback', disabled: true)
feedback = Faker::Markdown.sandwich(sentences: 6)
add_markdown(feedback)
click_button 'Share Feedback'
expect(page).to have_text('Your feedback will be e-mailed to the student')
dismiss_notification
expect(page).to have_button('Add another feedback')
submission = submission_reviewed.reload
expect(submission.startup_feedback.count).to eq(2)
expect(submission.startup_feedback.last.feedback).to eq(feedback)
end
scenario 'team coach undo grading' do
sign_in_user team_coach.user,
referrer: review_timeline_event_path(submission_reviewed)
within("div[aria-label='submission-status']") do
expect(page).to have_text('Completed')
expect(page).to have_text('Evaluated By')
expect(page).to have_text(coach.name)
end
accept_confirm { click_button 'Undo Grading' }
expect(page).to have_text('Start Review')
submission = submission_reviewed.reload
expect(submission.evaluator_id).to eq(nil)
expect(submission.passed_at).to eq(nil)
expect(submission.evaluated_at).to eq(nil)
expect(submission.timeline_event_grades).to eq([])
end
scenario 'coach clears grading for a submission with feedback' do
sign_in_user team_coach.user,
referrer: review_timeline_event_path(submission_reviewed)
accept_confirm { click_button 'Undo Grading' }
expect(submission_reviewed.startup_feedback.count).to eq(1)
click_button 'Start Review'
dismiss_notification
within("div[data-title='feedback-section']") do
expect(page).to have_text(coach.name)
expect(page).to have_content(
submission_reviewed.startup_feedback.first.feedback
)
end
end
end
context 'with an auto verified submission' do
let(:auto_verified_submission) do
create(
:timeline_event,
:with_owners,
latest: true,
owners: [team.founders.first],
target: auto_verify_target,
passed_at: 1.day.ago
)
end
scenario 'coach visits submission review page' do
sign_in_user team_coach.user,
referrer:
review_timeline_event_path(auto_verified_submission)
expect(page).to have_text("The page you were looking for doesn't exist!")
end
end
context 'when there are some submissions that have a mixed list of owners' do
let(:target) { create :target, :for_team, target_group: target_group }
let(:team_1) { create :startup, level: level }
let(:team_2) { create :startup, level: level }
let!(:submission_reviewed_1) do
create(
:timeline_event,
:with_owners,
latest: true,
owners: [team_2.founders.first] + team_1.founders,
target: target,
evaluator_id: coach.id,
evaluated_at: 1.day.ago,
passed_at: 1.day.ago
)
end
let!(:submission_reviewed_2) do
create(
:timeline_event,
:with_owners,
latest: true,
owners: team_1.founders + team_2.founders,
target: target,
evaluator_id: coach.id,
evaluated_at: 1.day.ago,
passed_at: 1.day.ago
)
end
let!(:submission_reviewed_3) do
create(
:timeline_event,
:with_owners,
latest: true,
owners: team_1.founders + team_2.founders,
target: target,
evaluator_id: coach.id,
evaluated_at: 1.day.ago,
passed_at: 1.day.ago
)
end
let!(:submission_reviewed_4) do
create(
:timeline_event,
:with_owners,
latest: true,
owners: team_1.founders,
target: target,
evaluator_id: coach.id,
evaluated_at: 1.day.ago,
passed_at: 1.day.ago
)
end
let!(:timeline_event_grade_1) do
create(
:timeline_event_grade,
timeline_event: submission_reviewed_1,
evaluation_criterion: evaluation_criterion_1
)
end
let!(:timeline_event_grade_2) do
create(
:timeline_event_grade,
timeline_event: submission_reviewed_2,
evaluation_criterion: evaluation_criterion_1
)
end
let!(:timeline_event_grade_3) do
create(
:timeline_event_grade,
timeline_event: submission_reviewed_3,
evaluation_criterion: evaluation_criterion_1
)
end
let!(:timeline_event_grade_4) do
create(
:timeline_event_grade,
timeline_event: submission_reviewed_4,
evaluation_criterion: evaluation_criterion_1
)
end
scenario "coach viewing a submission's review page is only shown other submissions with identical owners" do
sign_in_user team_coach.user,
referrer: review_timeline_event_path(submission_reviewed_1)
# submission 1
expect(page).to have_text(submission_reviewed_1.checklist.first['title'])
expect(page).to have_text(team_1.founders.last.name)
expect(page).to have_text(team_2.founders.first.name)
expect(page).to_not have_text(team_1.name)
expect(page).to_not have_text(team_2.name)
expect(page).not_to have_text(
submission_reviewed_2.checklist.first['title']
)
expect(page).not_to have_text(
submission_reviewed_3.checklist.first['title']
)
# submission 2 and 3
visit review_timeline_event_path(submission_reviewed_3)
expect(page).to have_text(team_1.founders.last.name)
expect(page).to have_text(team_2.founders.first.name)
expect(page).to have_link(
href: "/submissions/#{submission_reviewed_3.id}/review"
)
expect(page).to have_link(
href: "/submissions/#{submission_reviewed_2.id}/review"
)
expect(page).not_to have_link(
href: "/submissions/#{submission_reviewed_1.id}/review"
)
end
end
context 'when there are team targets and individual target submissions to review' do
let(:individual_target) do
create :target, :for_founders, target_group: target_group
end
let(:team_target) { create :target, :for_team, target_group: target_group }
let(:team_1) { create :startup, level: level }
let(:team_2) { create :startup, level: level }
let(:student) { team_1.founders.first }
let!(:submission_individual_target) do
create(
:timeline_event,
:with_owners,
latest: true,
owners: [student],
target: individual_target
)
end
let!(:submission_team_target) do
create(
:timeline_event,
:with_owners,
latest: true,
owners: team_2.founders,
target: team_target
)
end
let!(:submission_team_target_2) do
create(
:timeline_event,
:with_owners,
latest: true,
owners: [student, team_2.founders.first],
target: team_target
)
end
before do
# Set evaluation criteria on the target so that its submissions can be reviewed.
individual_target.evaluation_criteria << [evaluation_criterion_1]
team_target.evaluation_criteria << [evaluation_criterion_1]
end
scenario 'coaches are shown team name along with list of students if target is submitted by a team' do
sign_in_user team_coach.user,
referrer: review_timeline_event_path(submission_team_target)
expect(page).to have_title("Submission 1 | L1 | #{team_2.name}")
expect(page).to have_text(team_2.founders.first.name)
expect(page).to have_text(team_2.founders.last.name)
expect(page).to have_text(team_2.name)
end
scenario 'coaches are shown just the name of the student if target is not a team target' do
sign_in_user team_coach.user,
referrer:
review_timeline_event_path(submission_individual_target)
expect(page).to have_title("Submission 1 | L1 | #{student.name}")
expect(page).to have_text(student.name)
expect(page).to_not have_text(team_1.name)
end
scenario 'coaches are shown just the name of the students if current teams of students associated with submission are different' do
sign_in_user team_coach.user,
referrer:
review_timeline_event_path(submission_team_target_2)
expect(page).to have_title(
"Submission 1 | L1 | #{student.name}, #{team_2.founders.first.name}"
)
expect(page).to have_text(student.name)
expect(page).to have_text(team_2.founders.first.name)
expect(page).to_not have_text(team_1.name)
expect(page).to_not have_text(team_2.name)
end
scenario 'coaches are not shown report on automation tests in the absence of a submission report' do
sign_in_user team_coach.user,
referrer: review_timeline_event_path(submission_team_target)
expect(page).to have_title("Submission 1 | L1 | #{team_2.name}")
expect(page).to_not have_text('Automated tests are queued')
end
end
context 'student has undone submissions for a target' do
let!(:submission_reviewed) do
create(
:timeline_event,
:with_owners,
latest: false,
owners: [team.founders.first],
target: target,
evaluator_id: coach.id,
evaluated_at: 2.days.ago,
passed_at: 2.days.ago
)
end
let!(:timeline_event_grade_1) do
create(
:timeline_event_grade,
timeline_event: submission_reviewed,
evaluation_criterion: evaluation_criterion_1
)
end
let!(:timeline_event_grade_2) do
create(
:timeline_event_grade,
timeline_event: submission_reviewed,
evaluation_criterion: evaluation_criterion_2
)
end
let!(:submission_archived) do
create(
:timeline_event,
:with_owners,
latest: false,
owners: [team.founders.first],
target: target,
archived_at: 1.day.ago
)
end
let!(:submission_pending) do
create(
:timeline_event,
:with_owners,
latest: true,
owners: [team.founders.first],
target: target
)
end
scenario 'coach attempts to access the review page for an archived submission' do
sign_in_user team_coach.user,
referrer: review_timeline_event_path(submission_archived)
expect(page).to have_text("The page you were looking for doesn't exist")
end
scenario 'coach visits pending submission and finds archived submission in history' do
sign_in_user team_coach.user,
referrer: review_timeline_event_path(submission_pending)
expect(page).to have_selector('.submission-info__tab', count: 3)
expect(page).not_to have_link(
href: "/submissions/#{submission_archived.id}/review"
)
within("a[title='Submission #1']") do
expect(page).to have_text('Submission #1')
expect(page).to have_text('Completed')
end
within("div[title='Submission #2']") do
expect(page).to have_text('Submission #2')
expect(page).to have_text('Deleted')
end
within("a[title='Submission #3']") do
expect(page).to have_text('Submission #3')
expect(page).to have_text('Pending Review')
end
end
end
context 'when a submission report exists for a submission' do
let(:student) { team.founders.first }
let!(:submission_with_report) do
create(
:timeline_event,
:with_owners,
owners: [student],
latest: true,
target: target
)
end
let!(:submission_report) do
create :submission_report, :queued, submission: submission_with_report
end
around do |example|
with_secret(submission_report_poll_time: 2) { example.run }
end
scenario 'indicates the status of the automated test in submission review page' do
sign_in_user team_coach.user,
referrer: review_timeline_event_path(submission_with_report)
expect(page).to have_text('Automated tests are queued')
expect(page).to_not have_button('Show Test Report')
submission_report.update!(
status: 'in_progress',
started_at: 2.minutes.ago
)
refresh
expect(page).to have_text('Automated tests are in progress')
expect(page).to have_text('Started 2 minutes ago')
submission_report.update!(
status: 'completed',
conclusion: 'success',
started_at: 2.minutes.ago,
completed_at: Time.zone.now,
test_report: 'Foo'
)
refresh
expect(page).to have_text('All automated tests succeeded')
expect(page).to_not have_text('Foo')
click_button 'Show Test Report'
expect(page).to have_text('Foo')
submission_report.update!(
status: 'completed',
conclusion: 'failure',
started_at: 2.minutes.ago,
completed_at: Time.zone.now,
test_report: 'Bar'
)
refresh
expect(page).to have_text('Some automated tests failed')
click_button 'Show Test Report'
expect(page).to have_text('Bar')
end
scenario 'status of the report is checked every 30 seconds without page reload if current status is not completed' do
sign_in_user team_coach.user,
referrer: review_timeline_event_path(submission_with_report)
expect(page).to have_text('Automated tests are queued')
submission_report.update!(
status: 'completed',
conclusion: 'success',
test_report: 'A new report description',
started_at: 2.minutes.ago,
completed_at: Time.zone.now
)
sleep 2
expect(page).to have_text('All automated tests succeeded')
click_button 'Show Test Report'
expect(page).to have_text('A new report description')
end
end
end
| 33.159129 | 135 | 0.65195 |
ed88f855ac6e590cfbdc5568f020c8d25b8a5433 | 16,789 | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin/input'
require 'fluent/plugin/parser'
require 'fluent/event'
require 'http/parser'
require 'webrick/httputils'
require 'uri'
require 'socket'
require 'json'
module Fluent::Plugin
class InHttpParser < Parser
Fluent::Plugin.register_parser('in_http', self)
def parse(text)
# this plugin is dummy implementation not to raise error
yield nil, nil
end
end
class HttpInput < Input
Fluent::Plugin.register_input('http', self)
helpers :parser, :compat_parameters, :event_loop, :server
EMPTY_GIF_IMAGE = "GIF89a\u0001\u0000\u0001\u0000\x80\xFF\u0000\xFF\xFF\xFF\u0000\u0000\u0000,\u0000\u0000\u0000\u0000\u0001\u0000\u0001\u0000\u0000\u0002\u0002D\u0001\u0000;".force_encoding("UTF-8")
desc 'The port to listen to.'
config_param :port, :integer, default: 9880
desc 'The bind address to listen to.'
config_param :bind, :string, default: '0.0.0.0'
desc 'The size limit of the POSTed element. Default is 32MB.'
config_param :body_size_limit, :size, default: 32*1024*1024 # TODO default
desc 'The timeout limit for keeping the connection alive.'
config_param :keepalive_timeout, :time, default: 10 # TODO default
config_param :backlog, :integer, default: nil
desc 'Add HTTP_ prefix headers to the record.'
config_param :add_http_headers, :bool, default: false
desc 'Add REMOTE_ADDR header to the record.'
config_param :add_remote_addr, :bool, default: false
config_param :blocking_timeout, :time, default: 0.5
desc 'Set a white list of domains that can do CORS (Cross-Origin Resource Sharing)'
config_param :cors_allow_origins, :array, default: nil
desc 'Respond with empty gif image of 1x1 pixel.'
config_param :respond_with_empty_img, :bool, default: false
desc 'Respond status code with 204.'
config_param :use_204_response, :bool, default: false
config_section :parse do
config_set_default :@type, 'in_http'
end
EVENT_RECORD_PARAMETER = '_event_record'
def configure(conf)
compat_parameters_convert(conf, :parser)
super
m = if @parser_configs.first['@type'] == 'in_http'
@parser_msgpack = parser_create(usage: 'parser_in_http_msgpack', type: 'msgpack')
@parser_msgpack.estimate_current_event = false
@parser_json = parser_create(usage: 'parser_in_http_json', type: 'json')
@parser_json.estimate_current_event = false
@format_name = 'default'
@parser_time_key = if parser_config = conf.elements('parse').first
parser_config['time_key'] || 'time'
else
'time'
end
method(:parse_params_default)
else
@parser = parser_create
@format_name = @parser_configs.first['@type']
@parser_time_key = @parser.time_key
method(:parse_params_with_parser)
end
self.singleton_class.module_eval do
define_method(:parse_params, m)
end
end
class KeepaliveManager < Coolio::TimerWatcher
def initialize(timeout)
super(1, true)
@cons = {}
@timeout = timeout.to_i
end
def add(sock)
@cons[sock] = sock
end
def delete(sock)
@cons.delete(sock)
end
def on_timer
@cons.each_pair {|sock,val|
if sock.step_idle > @timeout
sock.close
end
}
end
end
def multi_workers_ready?
true
end
def start
@_event_loop_run_timeout = @blocking_timeout
super
log.debug "listening http", bind: @bind, port: @port
@km = KeepaliveManager.new(@keepalive_timeout)
event_loop_attach(@km)
server_create_connection(:in_http, @port, bind: @bind, backlog: @backlog, &method(:on_server_connect))
@float_time_parser = Fluent::NumericTimeParser.new(:float)
end
def close
server_wait_until_stop
super
end
def on_request(path_info, params)
begin
path = path_info[1..-1] # remove /
tag = path.split('/').join('.')
record_time, record = parse_params(params)
# Skip nil record
if record.nil?
log.debug { "incoming event is invalid: path=#{path_info} params=#{params.to_json}" }
if @respond_with_empty_img
return ["200 OK", {'Content-Type'=>'image/gif; charset=utf-8'}, EMPTY_GIF_IMAGE]
else
if @use_204_response
return ["204 No Content", {}]
else
return ["200 OK", {'Content-Type'=>'text/plain'}, ""]
end
end
end
unless record.is_a?(Array)
if @add_http_headers
params.each_pair { |k,v|
if k.start_with?("HTTP_")
record[k] = v
end
}
end
if @add_remote_addr
record['REMOTE_ADDR'] = params['REMOTE_ADDR']
end
end
time = if param_time = params['time']
param_time = param_time.to_f
param_time.zero? ? Fluent::EventTime.now : @float_time_parser.parse(param_time)
else
record_time.nil? ? Fluent::EventTime.now : record_time
end
rescue
return ["400 Bad Request", {'Content-Type'=>'text/plain'}, "400 Bad Request\n#{$!}\n"]
end
# TODO server error
begin
# Support batched requests
if record.is_a?(Array)
mes = Fluent::MultiEventStream.new
record.each do |single_record|
if @add_http_headers
params.each_pair { |k,v|
if k.start_with?("HTTP_")
single_record[k] = v
end
}
end
if @add_remote_addr
single_record['REMOTE_ADDR'] = params['REMOTE_ADDR']
end
if defined? @parser
single_time = @parser.parse_time(single_record)
single_time, single_record = @parser.convert_values(single_time, single_record)
else
single_time = if t = single_record.delete(@parser_time_key)
Fluent::EventTime.from_time(Time.at(t))
else
time
end
end
mes.add(single_time, single_record)
end
router.emit_stream(tag, mes)
else
router.emit(tag, time, record)
end
rescue
return ["500 Internal Server Error", {'Content-Type'=>'text/plain'}, "500 Internal Server Error\n#{$!}\n"]
end
if @respond_with_empty_img
return ["200 OK", {'Content-Type'=>'image/gif; charset=utf-8'}, EMPTY_GIF_IMAGE]
else
if @use_204_response
return ["204 No Content", {}]
else
return ["200 OK", {'Content-Type'=>'text/plain'}, ""]
end
end
end
private
def on_server_connect(conn)
handler = Handler.new(conn, @km, method(:on_request), @body_size_limit, @format_name, log, @cors_allow_origins)
conn.on(:data) do |data|
handler.on_read(data)
end
conn.on(:write_complete) do |_|
handler.on_write_complete
end
conn.on(:close) do |_|
handler.on_close
end
end
def parse_params_default(params)
if msgpack = params['msgpack']
@parser_msgpack.parse(msgpack) do |_time, record|
return nil, record
end
elsif js = params['json']
@parser_json.parse(js) do |_time, record|
return nil, record
end
else
raise "'json' or 'msgpack' parameter is required"
end
end
def parse_params_with_parser(params)
if content = params[EVENT_RECORD_PARAMETER]
@parser.parse(content) { |time, record|
raise "Received event is not #{@format_name}: #{content}" if record.nil?
return time, record
}
else
raise "'#{EVENT_RECORD_PARAMETER}' parameter is required"
end
end
class Handler
attr_reader :content_type
def initialize(io, km, callback, body_size_limit, format_name, log, cors_allow_origins)
@io = io
@km = km
@callback = callback
@body_size_limit = body_size_limit
@next_close = false
@format_name = format_name
@log = log
@cors_allow_origins = cors_allow_origins
@idle = 0
@km.add(self)
@remote_port, @remote_addr = io.remote_port, io.remote_addr
@parser = Http::Parser.new(self)
end
def step_idle
@idle += 1
end
def on_close
@km.delete(self)
end
def on_read(data)
@idle = 0
@parser << data
rescue
@log.warn "unexpected error", error: $!.to_s
@log.warn_backtrace
@io.close
end
def on_message_begin
@body = ''
end
def on_headers_complete(headers)
expect = nil
size = nil
if @parser.http_version == [1, 1]
@keep_alive = true
else
@keep_alive = false
end
@env = {}
@content_type = ""
@content_encoding = ""
headers.each_pair {|k,v|
@env["HTTP_#{k.gsub('-','_').upcase}"] = v
case k
when /\AExpect\z/i
expect = v
when /\AContent-Length\Z/i
size = v.to_i
when /\AContent-Type\Z/i
@content_type = v
when /\AContent-Encoding\Z/i
@content_encoding = v
when /\AConnection\Z/i
if v =~ /close/i
@keep_alive = false
elsif v =~ /Keep-alive/i
@keep_alive = true
end
when /\AOrigin\Z/i
@origin = v
when /\AX-Forwarded-For\Z/i
# For multiple X-Forwarded-For headers. Use first header value.
v = v.first if v.is_a?(Array)
@remote_addr = v.split(",").first
when /\AAccess-Control-Request-Method\Z/i
@access_control_request_method = v
when /\AAccess-Control-Request-Headers\Z/i
@access_control_request_headers = v
end
}
if expect
if expect == '100-continue'
if !size || size < @body_size_limit
send_response_nobody("100 Continue", {})
else
send_response_and_close("413 Request Entity Too Large", {}, "Too large")
end
else
send_response_and_close("417 Expectation Failed", {}, "")
end
end
end
def on_body(chunk)
if @body.bytesize + chunk.bytesize > @body_size_limit
unless closing?
send_response_and_close("413 Request Entity Too Large", {}, "Too large")
end
return
end
@body << chunk
end
# Web browsers can send an OPTIONS request before performing POST
# to check if cross-origin requests are supported.
def handle_options_request
# Is CORS enabled in the first place?
if @cors_allow_origins.nil?
return send_response_and_close("403 Forbidden", {}, "")
end
# in_http does not support HTTP methods except POST
if @access_control_request_method != 'POST'
return send_response_and_close("403 Forbidden", {}, "")
end
header = {
"Access-Control-Allow-Methods" => "POST",
"Access-Control-Allow-Headers" => @access_control_request_headers || "",
}
# Check the origin and send back a CORS response
if @cors_allow_origins.include?('*')
header["Access-Control-Allow-Origin"] = "*"
send_response_and_close("200 OK", header, "")
elsif include_cors_allow_origin
header["Access-Control-Allow-Origin"] = @origin
send_response_and_close("200 OK", header, "")
else
send_response_and_close("403 Forbidden", {}, "")
end
end
def on_message_complete
return if closing?
if @parser.http_method == 'OPTIONS'
return handle_options_request()
end
# CORS check
# ==========
# For every incoming request, we check if we have some CORS
# restrictions and white listed origins through @cors_allow_origins.
unless @cors_allow_origins.nil?
unless @cors_allow_origins.include?('*') or include_cors_allow_origin
send_response_and_close("403 Forbidden", {'Connection' => 'close'}, "")
return
end
end
# Content Encoding
# =================
# Decode payload according to the "Content-Encoding" header.
# For now, we only support 'gzip' and 'deflate'.
begin
if @content_encoding == 'gzip'
@body = Zlib::GzipReader.new(StringIO.new(@body)).read
elsif @content_encoding == 'deflate'
@body = Zlib::Inflate.inflate(@body)
end
rescue
@log.warn 'fails to decode payload', error: $!.to_s
send_response_and_close("400 Bad Request", {}, "")
return
end
@env['REMOTE_ADDR'] = @remote_addr if @remote_addr
uri = URI.parse(@parser.request_url)
params = WEBrick::HTTPUtils.parse_query(uri.query)
if @format_name != 'default'
params[EVENT_RECORD_PARAMETER] = @body
elsif @content_type =~ /^application\/x-www-form-urlencoded/
params.update WEBrick::HTTPUtils.parse_query(@body)
elsif @content_type =~ /^multipart\/form-data; boundary=(.+)/
boundary = WEBrick::HTTPUtils.dequote($1)
params.update WEBrick::HTTPUtils.parse_form_data(@body, boundary)
elsif @content_type =~ /^application\/json/
params['json'] = @body
elsif @content_type =~ /^application\/msgpack/
params['msgpack'] = @body
end
path_info = uri.path
params.merge!(@env)
@env.clear
code, header, body = *@callback.call(path_info, params)
body = body.to_s
unless @cors_allow_origins.nil?
if @cors_allow_origins.include?('*')
header['Access-Control-Allow-Origin'] = '*'
elsif include_cors_allow_origin
header['Access-Control-Allow-Origin'] = @origin
end
end
if @keep_alive
header['Connection'] = 'Keep-Alive'
send_response(code, header, body)
else
send_response_and_close(code, header, body)
end
end
def close
@io.close
end
def on_write_complete
@io.close if @next_close
end
def send_response_and_close(code, header, body)
send_response(code, header, body)
@next_close = true
end
def closing?
@next_close
end
def send_response(code, header, body)
header['Content-Length'] ||= body.bytesize
header['Content-Type'] ||= 'text/plain'
data = %[HTTP/1.1 #{code}\r\n]
header.each_pair {|k,v|
data << "#{k}: #{v}\r\n"
}
data << "\r\n"
@io.write(data)
@io.write(body)
end
def send_response_nobody(code, header)
data = %[HTTP/1.1 #{code}\r\n]
header.each_pair {|k,v|
data << "#{k}: #{v}\r\n"
}
data << "\r\n"
@io.write(data)
end
def include_cors_allow_origin
if @origin.nil?
return false
end
if @cors_allow_origins.include?(@origin)
return true
end
filtered_cors_allow_origins = @cors_allow_origins.select {|origin| origin != ""}
r = filtered_cors_allow_origins.find do |origin|
(start_str, end_str) = origin.split("*", 2)
@origin.start_with?(start_str) && @origin.end_with?(end_str)
end
!r.nil?
end
end
end
end
| 30.69287 | 203 | 0.575019 |
5da6f7e93eb8aadeeee6d305ac8a940ed27a1dd1 | 896 | # Player representation.
require_relative './entity.rb'
class Shark < Entity
def initialize(game)
@game = game
super()
@name = :shark
@width = 100
@height = 20
@y = rand(game.height() * 0.66) + (game.height() * 0.33) - @height
@x = -width + (rand(2) * (game.width + @width))
if @x > 0 then @direction = -1 else @direction = 1 end
@speed = (rand(10) + 10) / 20.0
end
def update
@x += (@speed * @direction)
# if off screen.
if @x < -(@width + 10) then @health = -1 end
if @x > @game.width + @width + 10 then @health = -1 end
end
def draw
@game.draw_quad(self.x + 0, self.y + 0, 0xFFFFFFFF,
self.x + self.width, self.y + 0, 0xFFFFFFFF,
self.x + self.width, self.y + self.height, 0xFFFF0000,
self.x + 0, self.y + self.height, 0xFFFF0000,
10)
end
end | 21.853659 | 75 | 0.53125 |
919bf0ddfbf7952e00668b0e149d59c8e230244c | 233 | class CreateRepositories < ActiveRecord::Migration
def change
create_table :repositories, id: :uuid do |t|
t.string :name
t.string :deb_host
t.string :homepage
t.timestamps null: false
end
end
end
| 21.181818 | 50 | 0.669528 |
6ab2a6fb4a7d20ac83f968357c753e7a79b3ae77 | 942 | RSpec.describe BankOcr::Parser do
ZEROS = File.read 'spec/fixtures/zeros.txt'
ONES = File.read 'spec/fixtures/ones.txt'
ONE_THROUGH_NINE = File.read 'spec/fixtures/one_through_nine.txt'
THREE_CODES = File.read 'spec/fixtures/three_codes.txt'
describe '#parse' do
it 'takes a row of zeros' do
result = subject.parse ZEROS
expect(result).to eq [[0, 0, 0, 0, 0, 0, 0, 0, 0]]
end
it 'takes a row of ones' do
result = subject.parse ONES
expect(result).to eq [[1, 1, 1, 1, 1, 1, 1, 1, 1]]
end
it 'takes a row of one through nine' do
result = subject.parse ONE_THROUGH_NINE
expect(result).to eq [[1, 2, 3, 4, 5, 6, 7, 8, 9]]
end
it 'takes more than one row' do
result = subject.parse THREE_CODES
expect(result).to eq [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 2, 3, 4, 5, 6, 7, 8, 9]
]
end
end
end
| 28.545455 | 67 | 0.575372 |
262346c8d582658e869ea3f22450ab7763707c07 | 316 | class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.text :content
t.integer :commentable_id
t.string :commentable_type
t.timestamps null: false
end
add_index :comments, :commentable_type
add_index :comments, :commentable_id
end
end
| 21.066667 | 46 | 0.702532 |
ff575acdb187ada4292d5de0d8a1ec7f7c2bd9e1 | 526 | cask "royal-tsx" do
version "4.3.3.1000"
sha256 "9e8c3b6f5f211b06bbc6e49e9e396a98bdc7cdb0c4973b5b29da1ae786cc8b3d"
# https://royaltsx-v4.royalapplications.com/ was verified as official when first introduced to the cask
url "https://royaltsx-v4.royalapplications.com/updates/royaltsx_#{version}.dmg"
appcast "https://royaltsx-v#{version.major}.royalapplications.com/updates_stable.php"
name "Royal TSX"
homepage "https://www.royalapplications.com/ts/mac/features"
auto_updates :yes
app "Royal TSX.app"
end
| 35.066667 | 105 | 0.777567 |
f805ef9ad43d32e98b6bd83576dd31842f52244c | 873 | module Collective::Collectors
class PGBouncer < Collective::Collector
requires :pg
collect do
group 'pgbouncer' do |group|
instrument group, 'stats'
instrument group, 'pools'
end
end
private
def instrument(group, thing)
group.group thing do |group|
instrument_tuples group, show(thing)
end
end
def show(thing)
conn.exec "show #{thing};"
end
def instrument_tuples(group, tuples)
tuples.each do |tuple|
source = tuple.key?('database') ? tuple['database'] : ''
tuple.each do |k,v|
group.instrument(k, v, source: source) if instrumentable?(v)
end
end
end
def conn
@conn ||= PG.connect(connection_options)
end
def connection_options
(options[:connection] || {}).merge(dbname: 'pgbouncer')
end
end
end
| 20.785714 | 70 | 0.601375 |
6abc4a1d97ddddb23600f831505f0f229b127f48 | 1,364 | require 'r10k'
require 'log4r'
require 'log4r/configurator'
module R10K::Logging
include Log4r
LOG_LEVELS = %w{DEBUG2 DEBUG1 DEBUG INFO NOTICE WARN ERROR FATAL}
def logger_name
self.class.to_s
end
def logger
unless @logger
@logger = Log4r::Logger.new(self.logger_name)
@logger.add R10K::Logging.outputter
end
@logger
end
class << self
include Log4r
def levels
@levels ||= LOG_LEVELS.each.inject({}) do |levels, k|
levels[k] = Log4r.const_get(k)
levels
end
end
def parse_level(val)
begin
Integer(val)
rescue
levels[val.upcase]
end
end
def included(klass)
unless @log4r_loaded
Configurator.custom_levels(*LOG_LEVELS)
Logger.global.level = Log4r::ALL
@log4r_loaded = true
end
end
def level
@level || Log4r::WARN # Default level is WARN
end
def level=(val)
level = parse_level val
raise "Invalid log level: #{val}" unless level
outputter.level = level
@level = level
end
def formatter
@formatter ||= Log4r::PatternFormatter.new(:pattern => '[%C - %l] %m')
end
def outputter
@outputter ||= Log4r::StderrOutputter.new('console',
:level => self.level,
:formatter => formatter
)
end
end
end
| 18.684932 | 76 | 0.599707 |
26cade9575d3c7d44f10ed45c8a5cfa6c2b847a5 | 1,050 | class Mpg123 < Formula
desc "MP3 player for Linux and UNIX"
homepage "https://www.mpg123.de/"
url "https://downloads.sourceforge.net/project/mpg123/mpg123/1.26.2/mpg123-1.26.2.tar.bz2"
sha256 "00f7bf7ea64fcec2c9d07751d6ad8849343ee09c282ea3b0d5dd486e886e2ff3"
bottle do
sha256 "29e4e2b5e306f94d2ce0e900f8413b4751f5df28488a476558527119b09bf015" => :catalina
sha256 "9e80680b18a8b2e000d32aee02c5b5b03e95d617119d1a922a1ac48da4df66f6" => :mojave
sha256 "6a9d7414515325f52473be05e484faa1c314ffb65582588d9c312400d3e9d6bd" => :high_sierra
end
def install
# Work around Xcode 11 clang bug
ENV.append_to_cflags "-fno-stack-check" if DevelopmentTools.clang_build_version >= 1010
args = %W[
--disable-debug
--disable-dependency-tracking
--prefix=#{prefix}
--with-default-audio=coreaudio
--with-module-suffix=.so
--with-cpu=x86-64
]
system "./configure", *args
system "make", "install"
end
test do
system bin/"mpg123", "--test", test_fixtures("test.mp3")
end
end
| 31.818182 | 93 | 0.726667 |
0153c2490d4db8c85d57038216a24c6274c2d8f1 | 833 | # (C) Copyright 2017 Hewlett Packard Enterprise Development LP
#
# Licensed under the Apache License, Version 2.0 (the "License");
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
require_relative '../c7000/volume'
module OneviewSDK
module API1200
module Synergy
# Volume resource implementation for API1200 Synergy
class Volume < OneviewSDK::API1200::C7000::Volume
end
end
end
end
| 36.217391 | 85 | 0.758703 |
871febe3fc8377c3c53a75dc3ddf1a67949eafd5 | 2,249 | module VCAP::CloudController
class AppVersion < Sequel::Model
many_to_one :app
many_to_one :droplet
export_attributes :app_guid, :version_guid, :version_count, :description, :instances, :memory
import_attributes :app_guid, :version_guid, :version_count, :description, :instances, :memory
def validate
validates_presence :app
validates_presence :droplet
validates_presence :version_count
validates_presence :version_guid
end
def rollback(code_only)
app.droplet_hash = droplet.droplet_hash
if !code_only
app.instances = instances
app.memory = memory
end
app.version_description = "rolled back to v#{version_count}"
app.version_updated = true
app.set_new_version # a rollback creates a new version, similar to Heroku
app.save
end
def self.latest_version(app)
versions = where( :app => app ).map(:version_count)
if versions.is_a? Array
max = versions.map { |x| x.to_i }.max
return max || 0
end
return 0
end
def self.build_description(app)
pushed_new_code = app.column_changed?(:droplet_hash)
changed_instances = app.column_changed?(:instances)
changed_memory = app.column_changed?(:memory)
messages = []
if pushed_new_code
messages << "pushed new code"
end
if changed_instances
messages << "changed instances to #{app.instances}"
end
if changed_memory
messages << "changed memory to #{app.memory}MB"
end
messages.join ", "
end
def self.make_new_version(app)
description_field = app.version_description || build_description(app)
current_droplet = app.current_droplet
current_droplet.updated_at = Time.now
current_droplet.save
new_version_count = latest_version(app) + 1
version = new( :app => app, :droplet => current_droplet, :version_count => new_version_count, :version_guid => app.version, :instances => app.instances, :memory => app.memory, :description => description_field )
version.save
version
end
def self.user_visibility_filter(user)
{:app => App.user_visible(user)}
end
end
end
| 28.468354 | 217 | 0.66474 |
389eab263aac24bbd11906cd217f045f93016b0d | 1,800 | module Cryptoexchange::Exchanges
module Xcoex
module Services
class Market < Cryptoexchange::Services::Market
class << self
def supports_individual_ticker_query?
false
end
end
def fetch
output = super(ticker_url)
adapt_all(output)
end
def ticker_url
"#{Cryptoexchange::Exchanges::Xcoex::Market::API_URL}/ticker"
end
def adapt_all(output)
output.map do |output|
next if output["DailyTradedTotalVolume"] == 0
base, target = Xcoex::Market.separate_symbol(output["Symbol"])
market_pair = Cryptoexchange::Models::MarketPair.new(
base: base,
target: target,
market: Xcoex::Market::NAME
)
adapt(market_pair, output)
end.compact
end
def adapt(market_pair, output)
ticker = Cryptoexchange::Models::Ticker.new
ticker.base = market_pair.base
ticker.target = market_pair.target
ticker.market = Xcoex::Market::NAME
if output["LastBuyTimestamp"].to_i > output["LastSellTimestamp"].to_i
ticker.last = NumericHelper.to_d(output["LastBuyPrice"])
else
ticker.last = NumericHelper.to_d(output["LastSellPrice"])
end
ticker.volume = NumericHelper.to_d(output["DailyTradedTotalVolume"])
ticker.ask = NumericHelper.to_d(output["BestAsk"])
ticker.bid = NumericHelper.to_d(output["BestBid"])
ticker.timestamp = nil
ticker.payload = output
ticker
end
end
end
end
end
| 31.578947 | 81 | 0.546111 |
394b6862e93a692a009698932f3b07e01c9507e6 | 279 | require 'rails_helper'
RSpec.describe "StockLevelAdjustments", type: :request do
describe "GET /stock_level_adjustments" do
it "works! (now write some real specs)" do
get stock_level_adjustments_path
expect(response).to have_http_status(200)
end
end
end
| 25.363636 | 57 | 0.741935 |
215a2ec9bde326a0999757df1fa5f2686750eb2c | 86 | Rails.application.routes.draw do
resources :instruments
resources :orchestras
end
| 17.2 | 32 | 0.813953 |
edc184ab5149d88bc56c31492013d96c10caab00 | 99,788 | require 'rails_helper'
require 'aasm/rspec'
require "#{BenefitSponsors::Engine.root}/spec/shared_contexts/benefit_market.rb"
require "#{BenefitSponsors::Engine.root}/spec/shared_contexts/benefit_application.rb"
RSpec.describe HbxEnrollment, type: :model, dbclean: :after_each do
describe HbxEnrollment, dbclean: :around_each do
include_context "setup benefit market with market catalogs and product packages"
include_context "setup initial benefit application"
context "an employer defines a plan year with multiple benefit groups, adds employees to roster and assigns benefit groups" do
before do
white_collar_benefit_group = build(:benefit_sponsors_benefit_packages_benefit_package, health_sponsored_benefit: true, product_package: product_package, benefit_application: initial_application)
initial_application.benefit_packages << white_collar_benefit_group
initial_application.save!
end
let(:blue_collar_employee_count) {7}
let(:white_collar_employee_count) {5}
let(:fte_count) {blue_collar_employee_count + white_collar_employee_count}
let(:employer_profile) {benefit_sponsorship.profile}
let(:organization) {employer_profile.organization}
let(:plan_year) {initial_application}
let(:blue_collar_benefit_group) {plan_year.benefit_groups[0]}
let!(:blue_collar_census_employees) { FactoryGirl.create_list(:census_employee, blue_collar_employee_count, employer_profile: employer_profile, benefit_sponsorship: benefit_sponsorship, benefit_group: current_benefit_package)}
let!(:white_collar_census_employees) {FactoryGirl.create_list(:census_employee, white_collar_employee_count, employer_profile: employer_profile, benefit_sponsorship: benefit_sponsorship, benefit_group: current_benefit_package) }
it "should have a valid plan year in enrolling state" do
expect(plan_year.aasm_state).to eq :active
end
it "should have a roster with all blue and white collar employees" do
expect(employer_profile.census_employees.size).to eq fte_count
end
context "and employees create employee roles and families" do
let(:blue_collar_employee_roles) do
bc_employees = blue_collar_census_employees.collect do |census_employee|
person = Person.create!(
first_name: census_employee.first_name,
last_name: census_employee.last_name,
ssn: census_employee.ssn,
dob: census_employee.dob,
gender: "male"
)
employee_role = person.employee_roles.build(
employer_profile: census_employee.employer_profile,
census_employee: census_employee,
hired_on: census_employee.hired_on
)
census_employee.employee_role = employee_role
census_employee.save!
employee_role
end
bc_employees
end
let(:white_collar_employee_roles) do
wc_employees = white_collar_census_employees.collect do |census_employee|
person = Person.create!(
first_name: census_employee.first_name,
last_name: census_employee.last_name,
ssn: census_employee.ssn,
# ssn: (census_employee.ssn.to_i + 20).to_s,
dob: census_employee.dob,
gender: "male"
)
employee_role = person.employee_roles.build(
employer_profile: census_employee.employer_profile,
census_employee: census_employee,
hired_on: census_employee.hired_on
)
census_employee.employee_role = employee_role
census_employee.save!
employee_role
end
wc_employees
end
let(:blue_collar_families) do
blue_collar_employee_roles.reduce([]) {|list, employee_role| family = Family.find_or_build_from_employee_role(employee_role); list << family}
end
let(:white_collar_families) do
white_collar_employee_roles.reduce([]) {|list, employee_role| family = Family.find_or_build_from_employee_role(employee_role); list << family}
end
it "should include the requisite blue collar employee roles and families" do
expect(blue_collar_employee_roles.size).to eq blue_collar_employee_count
expect(blue_collar_families.size).to eq blue_collar_employee_count
end
it "should include the requisite white collar employee roles and families" do
expect(white_collar_employee_roles.size).to eq white_collar_employee_count
expect(white_collar_families.size).to eq white_collar_employee_count
end
end
end
end
describe HbxEnrollment, dbclean: :after_each do
include_context "BradyWorkAfterAll"
before :all do
create_brady_census_families
end
context "is created from an employer_profile, benefit_group, and coverage_household" do
# attr_reader :enrollment, :household, :coverage_household
# before :all do
# @household = mikes_family.households.first
# @coverage_household = household.coverage_households.first
# @enrollment = household.create_hbx_enrollment_from(
# employee_role: mikes_employee_role,
# coverage_household: coverage_household,
# benefit_group: nil,
# benefit_group_assignment: @mikes_census_employee.active_benefit_group_assignment,
# benefit_package: @mikes_benefit_group,
# sponsored_benefit: @mikes_benefit_group.sponsored_benefits.first
# )
# end
# it "should assign the benefit group assignment" do
# expect(enrollment.benefit_group_assignment_id).not_to be_nil
# end
# it "should be employer sponsored" do
# expect(enrollment.kind).to eq "employer_sponsored"
# end
# it "should set the employer_profile" do
# expect(enrollment.employer_profile._id).to eq mikes_employer._id
# end
# it "should be active" do
# expect(enrollment.is_active?).to be_truthy
# end
# it "should be effective when the plan_year starts by default" do
# expect(enrollment.effective_on).to eq mikes_plan_year.start_on
# end
# it "should be valid" do
# expect(enrollment.valid?).to be_truthy
# end
# it "should default to enrolling everyone" do
# expect(enrollment.applicant_ids).to match_array(coverage_household.applicant_ids)
# end
# it "should not return a total premium" do
# expect {enrollment.total_premium}.not_to raise_error
# end
# it "should not return an employee cost" do
# expect {enrollment.total_employee_cost}.not_to raise_error
# end
# it "should not return an employer contribution" do
# expect {enrollment.total_employer_contribution}.not_to raise_error
# end
# context "and the employee enrolls" do
# before :all do
# enrollment.plan = enrollment.benefit_group.reference_plan
# enrollment.save
# end
# it "should return a total premium" do
# Caches::PlanDetails.load_record_cache!
# expect(enrollment.total_premium).to be
# end
# it "should return an employee cost" do
# Caches::PlanDetails.load_record_cache!
# expect(enrollment.total_employee_cost).to be
# end
# it "should return an employer contribution" do
# Caches::PlanDetails.load_record_cache!
# expect(enrollment.total_employer_contribution).to be
# end
# end
# context "update_current" do
# before :all do
# @enrollment2 = household.create_hbx_enrollment_from(
# employee_role: mikes_employee_role,
# coverage_household: coverage_household,
# benefit_group: mikes_benefit_group,
# benefit_group_assignment: @mikes_benefit_group_assignments
# )
# @enrollment2.save
# @enrollment2.update_current(is_active: false)
# end
# it "enrollment and enrollment2 should have same household" do
# expect(@enrollment2.household).to eq enrollment.household
# end
# it "enrollment2 should be not active" do
# expect(@enrollment2.is_active).to be_falsey
# end
# it "enrollment should be active" do
# expect(enrollment.is_active).to be_truthy
# end
# end
# context "inactive_related_hbxs" do
# before :all do
# @enrollment3 = household.create_hbx_enrollment_from(
# employee_role: mikes_employee_role,
# coverage_household: coverage_household,
# benefit_group: mikes_benefit_group,
# benefit_group_assignment: @mikes_benefit_group_assignments
# )
# @enrollment3.save
# @enrollment3.inactive_related_hbxs
# end
# it "should have an assigned hbx_id" do
# expect(@enrollment3.hbx_id).not_to eq nil
# end
# it "enrollment and enrollment3 should have same household" do
# expect(@enrollment3.household).to eq enrollment.household
# end
# it "enrollment should be not active" do
# expect(enrollment.is_active).to be_falsey
# end
# it "enrollment3 should be active" do
# expect(@enrollment3.is_active).to be_truthy
# end
# it "should only one active when they have same employer" do
# hbxs = @enrollment3.household.hbx_enrollments.select do |hbx|
# hbx.employee_role.employer_profile_id == @enrollment3.employee_role.employer_profile_id and hbx.is_active?
# end
# expect(hbxs.count).to eq 1
# end
# end
# context "waive_coverage_by_benefit_group_assignment" do
# before :each do
# @enrollment4 = household.create_hbx_enrollment_from(
# employee_role: mikes_employee_role,
# coverage_household: coverage_household,
# benefit_group: mikes_benefit_group,
# benefit_group_assignment: @mikes_benefit_group_assignments
# )
# allow(@enrollment4).to receive(:notify_on_save).and_return true
# @enrollment4.save
# @enrollment5 = household.create_hbx_enrollment_from(
# employee_role: mikes_employee_role,
# coverage_household: coverage_household,
# benefit_group: mikes_benefit_group,
# benefit_group_assignment: @mikes_benefit_group_assignments
# )
# allow(@enrollment5).to receive(:notify_on_save).and_return true
# @enrollment5.save
# @enrollment4.waive_coverage_by_benefit_group_assignment("start a new job")
# @enrollment5.reload
# end
# it "enrollment4 should be inactive" do
# expect(@enrollment4.aasm_state).to eq "inactive"
# end
# it "enrollment4 should get waiver_reason" do
# expect(@enrollment4.waiver_reason).to eq "start a new job"
# end
# it "enrollment5 should not be waived" do
# expect(@enrollment5.aasm_state).to eq "shopping"
# end
# it "enrollment5 should not have waiver_reason" do
# expect(@enrollment5.waiver_reason).to eq nil
# end
# end
# context "should shedule termination previous auto renewing enrollment" do
# before :each do
# @enrollment6 = household.create_hbx_enrollment_from(
# employee_role: mikes_employee_role,
# coverage_household: coverage_household,
# benefit_group: mikes_benefit_group,
# benefit_group_assignment: @mikes_benefit_group_assignments
# )
# @enrollment6.effective_on=TimeKeeper.date_of_record + 1.days
# @enrollment6.aasm_state = "auto_renewing"
# allow(@enrollment6).to receive(:notify_on_save).and_return true
# @enrollment6.save
# @enrollment7 = household.create_hbx_enrollment_from(
# employee_role: mikes_employee_role,
# coverage_household: coverage_household,
# benefit_group: mikes_benefit_group,
# benefit_group_assignment: @mikes_benefit_group_assignments
# )
# allow(@enrollment7).to receive(:notify_on_save).and_return true
# @enrollment7.save
# @enrollment7.cancel_previous(TimeKeeper.date_of_record.year)
# end
# it "doesn't move enrollment for shop market" do
# expect(@enrollment6.aasm_state).to eq "auto_renewing"
# end
# it "should not cancel current shopping enrollment" do
# expect(@enrollment7.aasm_state).to eq "shopping"
# end
# end
# context "decorated_elected_plans" do
# let(:benefit_package) {BenefitPackage.new}
# let(:consumer_role) {FactoryGirl.create(:consumer_role)}
# let(:person) {double(primary_family: family)}
# let(:family) {double}
# let(:enrollment) {
# enrollment = household.new_hbx_enrollment_from(
# consumer_role: consumer_role,
# coverage_household: coverage_household,
# benefit_package: benefit_package,
# qle: true
# )
# enrollment.save
# enrollment
# }
# let(:hbx_profile) {double}
# let(:benefit_sponsorship) {double(earliest_effective_date: TimeKeeper.date_of_record - 2.months, renewal_benefit_coverage_period: renewal_bcp, current_benefit_coverage_period: bcp)}
# let(:renewal_bcp) {double(earliest_effective_date: TimeKeeper.date_of_record - 2.months)}
# let(:bcp) {double(earliest_effective_date: TimeKeeper.date_of_record - 2.months)}
# let(:plan) {FactoryGirl.create(:plan)}
# let(:plan2) {FactoryGirl.create(:plan)}
# context "when in open enrollment" do
# before :each do
# allow(HbxProfile).to receive(:current_hbx).and_return hbx_profile
# allow(hbx_profile).to receive(:benefit_sponsorship).and_return benefit_sponsorship
# allow(benefit_sponsorship).to receive(:current_benefit_period).and_return(bcp)
# allow(consumer_role).to receive(:person).and_return(person)
# allow(coverage_household).to receive(:household).and_return household
# allow(household).to receive(:family).and_return family
# allow(family).to receive(:is_under_special_enrollment_period?).and_return false
# allow(family).to receive(:is_under_ivl_open_enrollment?).and_return true
# allow(enrollment).to receive(:enrollment_kind).and_return "open_enrollment"
# end
# it "should return decoratored plans when not in the open enrollment" do
# allow(renewal_bcp).to receive(:open_enrollment_contains?).and_return false
# allow(benefit_sponsorship).to receive(:current_benefit_period).and_return(bcp)
# allow(bcp).to receive(:elected_plans_by_enrollment_members).and_return [plan]
# expect(enrollment.decorated_elected_plans('health').first.class).to eq UnassistedPlanCostDecorator
# expect(enrollment.decorated_elected_plans('health').count).to eq 1
# expect(enrollment.decorated_elected_plans('health').first.id).to eq plan.id
# end
# it "should return decoratored plans when in the open enrollment" do
# allow(benefit_sponsorship).to receive(:current_benefit_period).and_return(renewal_bcp)
# allow(renewal_bcp).to receive(:open_enrollment_contains?).and_return true
# allow(renewal_bcp).to receive(:elected_plans_by_enrollment_members).and_return [plan2]
# expect(enrollment.decorated_elected_plans('health').first.class).to eq UnassistedPlanCostDecorator
# expect(enrollment.decorated_elected_plans('health').count).to eq 1
# expect(enrollment.decorated_elected_plans('health').first.id).to eq plan2.id
# end
# end
# context "when in special enrollment" do
# let(:sep) {SpecialEnrollmentPeriod.new(effective_on: TimeKeeper.date_of_record)}
# before :each do
# allow(HbxProfile).to receive(:current_hbx).and_return hbx_profile
# allow(hbx_profile).to receive(:benefit_sponsorship).and_return benefit_sponsorship
# allow(benefit_sponsorship).to receive(:current_benefit_period).and_return(bcp)
# allow(consumer_role).to receive(:person).and_return(person)
# allow(coverage_household).to receive(:household).and_return household
# allow(household).to receive(:family).and_return family
# allow(family).to receive(:current_sep).and_return sep
# allow(family).to receive(:current_special_enrollment_periods).and_return [sep]
# allow(family).to receive(:is_under_special_enrollment_period?).and_return true
# allow(enrollment).to receive(:enrollment_kind).and_return "special_enrollment"
# end
# it "should return decoratored plans when not in the open enrollment" do
# enrollment.update_attributes(effective_on: sep.effective_on - 1.month)
# allow(renewal_bcp).to receive(:open_enrollment_contains?).and_return false
# allow(benefit_sponsorship).to receive(:benefit_coverage_period_by_effective_date).with(enrollment.effective_on).and_return(bcp)
# allow(bcp).to receive(:elected_plans_by_enrollment_members).and_return [plan]
# expect(enrollment.decorated_elected_plans('health').first.class).to eq UnassistedPlanCostDecorator
# expect(enrollment.decorated_elected_plans('health').count).to eq 1
# expect(enrollment.decorated_elected_plans('health').first.id).to eq plan.id
# expect(enrollment.created_at).not_to be_nil
# end
# end
# end
context "status_step" do
let(:hbx_enrollment) {HbxEnrollment.new}
it "return 1 when coverage_selected" do
hbx_enrollment.aasm_state = "coverage_selected"
expect(hbx_enrollment.status_step).to eq 1
end
it "return 2 when transmitted_to_carrier" do
hbx_enrollment.aasm_state = "transmitted_to_carrier"
expect(hbx_enrollment.status_step).to eq 2
end
it "return 3 when enrolled_contingent" do
hbx_enrollment.aasm_state = "enrolled_contingent"
expect(hbx_enrollment.status_step).to eq 3
end
it "return 4 when coverage_enrolled" do
hbx_enrollment.aasm_state = "coverage_enrolled"
expect(hbx_enrollment.status_step).to eq 4
end
it "return 5 when coverage_canceled" do
hbx_enrollment.aasm_state = "coverage_canceled"
expect(hbx_enrollment.status_step).to eq 5
end
it "return 5 when coverage_terminated" do
hbx_enrollment.aasm_state = "coverage_terminated"
expect(hbx_enrollment.status_step).to eq 5
end
end
context "enrollment_kind" do
let(:hbx_enrollment) {HbxEnrollment.new}
it "should fail validation when blank" do
hbx_enrollment.enrollment_kind = ""
expect(hbx_enrollment.valid?).to eq false
expect(hbx_enrollment.errors[:enrollment_kind].any?).to eq true
end
it "should fail validation when not in ENROLLMENT_KINDS" do
hbx_enrollment.enrollment_kind = "test"
expect(hbx_enrollment.valid?).to eq false
expect(hbx_enrollment.errors[:enrollment_kind].any?).to eq true
end
it "is_open_enrollment?" do
hbx_enrollment.enrollment_kind = "open_enrollment"
expect(hbx_enrollment.is_open_enrollment?).to eq true
expect(hbx_enrollment.is_special_enrollment?).to eq false
end
it "is_special_enrollment?" do
hbx_enrollment.enrollment_kind = "special_enrollment"
expect(hbx_enrollment.is_open_enrollment?).to eq false
expect(hbx_enrollment.is_special_enrollment?).to eq true
end
end
end
context "#propogate_waiver", dbclean: :after_each do
let(:family) {FactoryGirl.create(:family, :with_primary_family_member)}
let(:census_employee) {FactoryGirl.create(:census_employee)}
let(:benefit_group_assignment) {FactoryGirl.create(:benefit_group_assignment, benefit_group: package, census_employee: census_employee)}
let(:application) {double(:start_on => TimeKeeper.date_of_record.beginning_of_month, :end_on => (TimeKeeper.date_of_record.beginning_of_month + 1.year) - 1.day, :aasm_state => :active)}
let(:package) {double("BenefitPackage", :is_a? => BenefitSponsors::BenefitPackages::BenefitPackage, :_id => "id", :plan_year => application, :benefit_application => application)}
let(:ivl_enrollment) {FactoryGirl.create(:hbx_enrollment, :individual_unassisted, household: family.active_household)}
let(:existing_shop_enrollment) {FactoryGirl.create(:hbx_enrollment, :shop, household: family.active_household)}
let(:enrollment_for_waiver) {FactoryGirl.create(:hbx_enrollment, household: family.active_household, predecessor_enrollment_id: existing_shop_enrollment.id, benefit_group_assignment_id: benefit_group_assignment.id)}
before do
allow(census_employee).to receive(:benefit_group_assignments).and_return [benefit_group_assignment]
end
it "should return false if it is an ivl enrollment" do
expect(ivl_enrollment.propogate_waiver).to eq false
end
it "should return true for shop enrollment" do
expect(enrollment_for_waiver.propogate_waiver).to eq true
end
it "should waive the benefit group assignment if enrollment belongs to health & shop" do
enrollment_for_waiver.propogate_waiver
benefit_group_assignment.reload
expect(benefit_group_assignment.aasm_state).to eq "coverage_waived"
end
it "should not waive the benefit group assignment if enrollment belongs to dental" do
enrollment_for_waiver.update_attribute(:coverage_kind, "dental")
enrollment_for_waiver.propogate_waiver
expect(benefit_group_assignment.aasm_state).not_to eq "coverage_waived"
end
it "should cancel the shop enrollment" do
enrollment_for_waiver.propogate_waiver
existing_shop_enrollment.reload
expect(existing_shop_enrollment.aasm_state).to eq "coverage_canceled"
end
end
end
describe HbxProfile, "class methods", type: :model do
# before :all do
# create_brady_census_families
# end
context "#find" do
it "should return nil with invalid id" do
expect(HbxEnrollment.find("text")).to eq nil
end
end
context "new_from" do
include_context "BradyWorkAfterAll"
attr_reader :household, :coverage_household
before :all do
create_brady_coverage_households
@household = mikes_family.households.first
@coverage_household = household.coverage_households.first
end
let(:benefit_package) {BenefitPackage.new}
let(:consumer_role) {FactoryGirl.create(:consumer_role)}
let(:person) {double(primary_family: family)}
let(:family) {double(current_sep: double(effective_on: TimeKeeper.date_of_record))}
let(:hbx_profile) {double}
let(:benefit_sponsorship) {double(earliest_effective_date: TimeKeeper.date_of_record - 2.months, renewal_benefit_coverage_period: renewal_bcp, current_benefit_coverage_period: bcp)}
let(:bcp) {double(earliest_effective_date: TimeKeeper.date_of_record - 2.months)}
let(:renewal_bcp) {double(earliest_effective_date: TimeKeeper.date_of_record - 2.months)}
before :each do
allow(HbxProfile).to receive(:current_hbx).and_return hbx_profile
allow(hbx_profile).to receive(:benefit_sponsorship).and_return benefit_sponsorship
allow(benefit_sponsorship).to receive(:current_benefit_period).and_return(bcp)
allow(consumer_role).to receive(:person).and_return(person)
allow(household).to receive(:family).and_return family
allow(family).to receive(:is_under_ivl_open_enrollment?).and_return true
end
shared_examples_for "new enrollment from" do |qle, sep, enrollment_period, error|
context "#{enrollment_period} period" do
let(:enrollment) {HbxEnrollment.new_from(consumer_role: consumer_role, coverage_household: coverage_household, benefit_package: benefit_package, qle: qle)}
before do
allow(family).to receive(:is_under_special_enrollment_period?).and_return sep
allow(family).to receive(:is_under_ivl_open_enrollment?).and_return enrollment_period == "open_enrollment"
end
unless error
it "assigns #{enrollment_period} as enrollment_kind when qle is #{qle}" do
expect(enrollment.enrollment_kind).to eq enrollment_period
end
it "should have submitted at as current date and time" do
enrollment.save
expect(enrollment.submitted_at).not_to be_nil
end
it "creates hbx_enrollment members " do
expect(enrollment.hbx_enrollment_members).not_to be_empty
end
it "creates members with coverage_start_on as enrollment effective_on" do
expect(enrollment.hbx_enrollment_members.first.coverage_start_on).to eq enrollment.effective_on
end
else
it "raises an error" do
expect {HbxEnrollment.new_from(consumer_role: consumer_role, coverage_household: coverage_household, benefit_package: benefit_package, qle: false)}.to raise_error(RuntimeError)
end
end
end
end
it_behaves_like "new enrollment from", false, true, "open_enrollment", false
it_behaves_like "new enrollment from", true, true, "special_enrollment", false
it_behaves_like "new enrollment from", false, false, "not_open_enrollment", "raise_an_error"
end
context "is reporting a qle before the employer plan start_date and having a expired plan year" do
include_context "setup benefit market with market catalogs and product packages"
include_context "setup renewal application"
let(:predecessor_state) { :expired }
let(:renewal_state) { :active }
let(:renewal_effective_date) { TimeKeeper.date_of_record.prev_month.beginning_of_month }
let(:coverage_household) {double}
let(:coverage_household_members) {double}
let(:household) {FactoryGirl.create(:household, family: family)}
let(:qle_kind) {FactoryGirl.create(:qualifying_life_event_kind, :effective_on_event_date)}
let(:census_employee) { create(:census_employee, benefit_sponsorship: benefit_sponsorship, employer_profile: benefit_sponsorship.profile) }
let(:employee_role) { FactoryGirl.create(:employee_role, person: person, census_employee: census_employee, employer_profile: benefit_sponsorship.profile) }
let(:person) {FactoryGirl.create(:person)}
let(:family) {FactoryGirl.create(:family, :with_primary_family_member, person: person)}
let(:sep) {
sep = family.special_enrollment_periods.new
sep.effective_on_kind = 'date_of_event'
sep.qualifying_life_event_kind= qle_kind
sep.qle_on= TimeKeeper.date_of_record - 7.days
sep.start_on = sep.qle_on
sep.end_on = sep.qle_on + 30.days
sep.save
sep
}
before do
renewal_application
allow(coverage_household).to receive(:household).and_return family.active_household
allow(coverage_household).to receive(:coverage_household_members).and_return []
allow(sep).to receive(:is_active?).and_return true
allow(family).to receive(:is_under_special_enrollment_period?).and_return true
expired_py = benefit_sponsorship.benefit_applications.where(aasm_state: 'expired').first
census_employee.benefit_group_assignments << BenefitGroupAssignment.new(benefit_group: expired_py.benefit_packages[0], start_on: expired_py.start_on)
census_employee.update_attributes(:employee_role_id => employee_role.id, hired_on: TimeKeeper.date_of_record - 2.months)
census_employee.update_attribute(:ssn, census_employee.employee_role.person.ssn)
end
it "should return a sep with an effective date that equals to sep date" do
enrollment = HbxEnrollment.new_from(employee_role: employee_role, coverage_household: coverage_household, benefit_group: nil, benefit_package: nil, benefit_group_assignment: nil, qle: true)
expect(enrollment.effective_on).to eq sep.qle_on
end
end
context "coverage_year" do
include_context "setup benefit market with market catalogs and product packages"
include_context "setup initial benefit application"
let(:date) {TimeKeeper.date_of_record}
let(:current_effective_date) { TimeKeeper.date_of_record.beginning_of_month }
let(:sponsored_benefit_package) { initial_application.benefit_packages[0] }
let(:plan) {Plan.new(active_year: date.year)}
let(:hbx_enrollment) {HbxEnrollment.new(sponsored_benefit_package_id: sponsored_benefit_package.id, effective_on: current_effective_date, kind: "employer_sponsored", plan: plan)}
it "should return plan year start on year when shop" do
expect(hbx_enrollment.coverage_year).to eq current_effective_date.year
end
it "should return plan year when ivl" do
allow(hbx_enrollment).to receive(:kind).and_return("")
expect(hbx_enrollment.coverage_year).to eq hbx_enrollment.plan.active_year
end
it "should return correct year when ivl" do
allow(hbx_enrollment).to receive(:kind).and_return("")
allow(hbx_enrollment).to receive(:plan).and_return(nil)
expect(hbx_enrollment.coverage_year).to eq hbx_enrollment.effective_on.year
end
end
# TODO - reimplement this spec
context "calculate_effective_on_from" do
let(:date) {TimeKeeper.date_of_record}
let(:family) {double(current_sep: double(effective_on: date), is_under_special_enrollment_period?: true)}
let(:hbx_profile) {double}
let(:benefit_sponsorship) {double}
let(:bcp) {double}
let(:benefit_group) {double()}
let(:employee_role) {double(hired_on: date)}
context "shop" do
it "special_enrollment" do
expect(HbxEnrollment.calculate_effective_on_from(market_kind: 'shop', qle: true, family: family, employee_role: nil, benefit_group: benefit_group, benefit_sponsorship: nil)).to eq date
end
it "open_enrollment" do
effective_on = date - 10.days
allow(benefit_group).to receive(:effective_on_for).and_return(effective_on)
allow(family).to receive(:is_under_special_enrollment_period?).and_return(false)
expect(HbxEnrollment.calculate_effective_on_from(market_kind: 'shop', qle: false, family: family, employee_role: employee_role, benefit_group: benefit_group, benefit_sponsorship: nil)).to eq effective_on
end
end
context "individual" do
before :each do
allow(HbxProfile).to receive(:current_hbx).and_return hbx_profile
allow(hbx_profile).to receive(:benefit_sponsorship).and_return benefit_sponsorship
allow(benefit_sponsorship).to receive(:current_benefit_period).and_return(bcp)
end
it "special_enrollment" do
expect(HbxEnrollment.calculate_effective_on_from(market_kind: 'individual', qle: true, family: family, employee_role: nil, benefit_group: nil, benefit_sponsorship: nil)).to eq date
end
it "open_enrollment" do
effective_on = date - 10.days
allow(bcp).to receive(:earliest_effective_date).and_return effective_on
allow(family).to receive(:is_under_special_enrollment_period?).and_return(false)
expect(HbxEnrollment.calculate_effective_on_from(market_kind: 'individual', qle: false, family: family, employee_role: nil, benefit_group: nil, benefit_sponsorship: benefit_sponsorship)).to eq effective_on
end
end
end
if ExchangeTestingConfigurationHelper.individual_market_is_enabled?
context "ivl user switching plan from one carrier to other carrier previous hbx_enrollment aasm_sate should be cancel/terminate in DB." do
let(:person1) {FactoryGirl.create(:person, :with_consumer_role)}
let(:family1) {FactoryGirl.create(:family, :with_primary_family_member, :person => person1)}
let(:household) {FactoryGirl.create(:household, family: family1)}
let(:date) {TimeKeeper.date_of_record}
let!(:carrier_profile1) {FactoryGirl.build(:carrier_profile)}
let!(:carrier_profile2) {FactoryGirl.create(:carrier_profile, organization: organization)}
let!(:organization) {FactoryGirl.create(:organization, legal_name: "CareFirst", dba: "care")}
let(:plan1) {Plan.new(active_year: date.year, market: "individual", carrier_profile: carrier_profile1)}
let(:plan2) {Plan.new(active_year: date.year, market: "individual", carrier_profile: carrier_profile2)}
let(:hbx_enrollment1) {HbxEnrollment.new(kind: "individual", plan: plan1, household: family1.latest_household, enrollment_kind: "open_enrollment", aasm_state: 'coverage_selected', consumer_role: person1.consumer_role, enrollment_signature: true)}
let(:hbx_enrollment2) {HbxEnrollment.new(kind: "individual", plan: plan2, household: family1.latest_household, enrollment_kind: "open_enrollment", aasm_state: 'shopping', consumer_role: person1.consumer_role, enrollment_signature: true, effective_on: date)}
before do
TimeKeeper.set_date_of_record_unprotected!(Date.today + 20.days) if TimeKeeper.date_of_record.month == 1 || TimeKeeper.date_of_record.month == 12
end
after do
TimeKeeper.set_date_of_record_unprotected!(Date.today) if TimeKeeper.date_of_record.month == 1 || TimeKeeper.date_of_record.month == 12
end
it "should cancel hbx enrollemnt plan1 from carrier1 when choosing plan2 from carrier2" do
hbx_enrollment1.effective_on = date + 1.day
hbx_enrollment2.effective_on = date
# This gets processed on 31st Dec
if hbx_enrollment1.effective_on.year != hbx_enrollment2.effective_on.year
hbx_enrollment1.effective_on = date + 2.day
hbx_enrollment2.effective_on = date + 1.day
end
hbx_enrollment2.select_coverage!
hbx_enrollment1_from_db = HbxEnrollment.by_hbx_id(hbx_enrollment1.hbx_id).first
expect(hbx_enrollment1_from_db.coverage_canceled?).to be_truthy
expect(hbx_enrollment2.coverage_selected?).to be_truthy
end
it "should not cancel hbx enrollemnt of previous plan year enrollment" do
hbx_enrollment1.effective_on = date + 1.year
hbx_enrollment2.effective_on = date
hbx_enrollment2.select_coverage!
expect(hbx_enrollment1.coverage_canceled?).to be_falsy
expect(hbx_enrollment2.coverage_selected?).to be_truthy
end
it "should terminate hbx enrollemnt plan1 from carrier1 when choosing hbx enrollemnt plan2 from carrier2" do
hbx_enrollment1.effective_on = date - 10.days
hbx_enrollment2.select_coverage!
hbx_enrollment1_from_db = HbxEnrollment.by_hbx_id(hbx_enrollment1.hbx_id).first
expect(hbx_enrollment1_from_db.coverage_terminated?).to be_truthy
expect(hbx_enrollment2.coverage_selected?).to be_truthy
expect(hbx_enrollment1_from_db.terminated_on).to eq hbx_enrollment2.effective_on - 1.day
end
it "terminates previous enrollments if both effective on in the future" do
hbx_enrollment1.effective_on = date + 10.days
hbx_enrollment2.effective_on = date + 20.days
hbx_enrollment2.select_coverage!
expect(hbx_enrollment1.coverage_terminated?).to be_truthy
expect(hbx_enrollment2.coverage_selected?).to be_truthy
expect(hbx_enrollment1.terminated_on).to eq hbx_enrollment2.effective_on - 1.day
end
end
end
context "can_terminate_coverage?" do
let(:hbx_enrollment) {HbxEnrollment.new(
kind: 'employer_sponsored',
aasm_state: 'coverage_selected',
effective_on: TimeKeeper.date_of_record - 10.days
)}
it "should return false when may not terminate_coverage" do
hbx_enrollment.aasm_state = 'inactive'
expect(hbx_enrollment.can_terminate_coverage?).to eq false
end
context "when may_terminate_coverage is true" do
before :each do
hbx_enrollment.aasm_state = 'coverage_selected'
end
it "should return true" do
hbx_enrollment.effective_on = TimeKeeper.date_of_record - 10.days
expect(hbx_enrollment.can_terminate_coverage?).to eq true
end
it "should return false" do
hbx_enrollment.effective_on = TimeKeeper.date_of_record + 10.days
expect(hbx_enrollment.can_terminate_coverage?).to eq false
end
end
end
context "cancel_coverage!", dbclean: :after_each do
let(:family) {FactoryGirl.create(:family, :with_primary_family_member)}
let(:hbx_enrollment) {FactoryGirl.create(:hbx_enrollment, household: family.active_household, aasm_state: "inactive")}
it "should cancel the enrollment" do
hbx_enrollment.cancel_coverage!
expect(hbx_enrollment.aasm_state).to eq "coverage_canceled"
end
it "should not populate the terminated on" do
hbx_enrollment.cancel_coverage!
expect(hbx_enrollment.terminated_on).to eq nil
end
end
context "cancel_for_non_payment!", dbclean: :after_each do
let(:family) {FactoryGirl.create(:family, :with_primary_family_member)}
let(:hbx_enrollment) {FactoryGirl.create(:hbx_enrollment, household: family.active_household, aasm_state: "inactive")}
it "should cancel the enrollment" do
hbx_enrollment.cancel_for_non_payment!
expect(hbx_enrollment.aasm_state).to eq "coverage_canceled"
end
it "should not populate the terminated on" do
hbx_enrollment.cancel_for_non_payment!
expect(hbx_enrollment.terminated_on).to eq nil
end
end
context "terminate_for_non_payment!", dbclean: :after_each do
let(:family) {FactoryGirl.create(:family, :with_primary_family_member)}
let(:hbx_enrollment) {FactoryGirl.create(:hbx_enrollment, household: family.active_household, aasm_state: "coverage_selected")}
it "should terminate enrollment" do
hbx_enrollment.terminate_for_non_payment!
expect(hbx_enrollment.aasm_state).to eq "coverage_terminated"
end
it "should populate terminate on" do
hbx_enrollment.terminate_for_non_payment!
expect(hbx_enrollment.terminated_on).to eq hbx_enrollment.terminated_on
end
end
end
describe HbxEnrollment, dbclean: :after_each do
include_context "setup benefit market with market catalogs and product packages"
include_context "setup initial benefit application"
context ".can_select_coverage?" do
let(:current_effective_date) { TimeKeeper.date_of_record.beginning_of_month }
let(:effective_on) { current_effective_date }
let(:hired_on) { TimeKeeper.date_of_record - 3.months }
let(:employee_created_at) { hired_on }
let(:employee_updated_at) { employee_created_at }
let(:person) {FactoryGirl.create(:person, first_name: 'John', last_name: 'Smith', dob: '1966-10-10'.to_date, ssn: '123456789')}
let(:shop_family) {FactoryGirl.create(:family, :with_primary_family_member)}
let(:aasm_state) { :active }
let(:census_employee) { create(:census_employee, :with_active_assignment, benefit_sponsorship: benefit_sponsorship, employer_profile: benefit_sponsorship.profile, benefit_group: current_benefit_package, hired_on: hired_on, created_at: employee_created_at, updated_at: employee_updated_at) }
let(:employee_role) { FactoryGirl.create(:employee_role, benefit_sponsors_employer_profile_id: abc_profile.id, hired_on: census_employee.hired_on, census_employee_id: census_employee.id) }
let(:enrollment_kind) { "open_enrollment" }
let(:special_enrollment_period_id) { nil }
let(:shop_enrollment) { FactoryGirl.create(:hbx_enrollment,
household: shop_family.latest_household,
coverage_kind: "health",
effective_on: effective_on,
enrollment_kind: enrollment_kind,
kind: "employer_sponsored",
submitted_at: effective_on - 10.days,
benefit_sponsorship_id: benefit_sponsorship.id,
sponsored_benefit_package_id: current_benefit_package.id,
sponsored_benefit_id: current_benefit_package.sponsored_benefits[0].id,
employee_role_id: employee_role.id,
benefit_group_assignment_id: census_employee.active_benefit_group_assignment.id,
special_enrollment_period_id: special_enrollment_period_id
)
}
context 'under open enrollment' do
let(:current_effective_date) { (TimeKeeper.date_of_record + 2.months).beginning_of_month }
let(:aasm_state) { :enrollment_open }
let(:hired_on) { TimeKeeper.date_of_record.prev_year }
let(:open_enrollment_period) { TimeKeeper.date_of_record..(effective_period.min - 10.days) }
it "should allow" do
expect(shop_enrollment.can_select_coverage?).to be_truthy
end
end
context 'outside open enrollment' do
let(:hired_on) { TimeKeeper.date_of_record.prev_year }
it "should not allow" do
expect(shop_enrollment.can_select_coverage?).to be_falsey
end
end
context 'when its a new hire' do
let(:effective_on) { hired_on.next_month.beginning_of_month }
let(:hired_on) { TimeKeeper.date_of_record }
it "should allow" do
expect(shop_enrollment.can_select_coverage?).to be_truthy
end
end
context 'when not a new hire' do
it "should not allow" do
expect(shop_enrollment.can_select_coverage?).to be_falsey
end
# TODO: code commented out in hbx_enrollment model. code needs to be enabled before adding this spec back.
# it "should get a error msg" do
# shop_enrollment.can_select_coverage?
# expect(shop_enrollment.errors.any?).to be_truthy
# expect(shop_enrollment.errors.full_messages.to_s).to match /You can not keep an existing plan which belongs to previous plan year/
# end
end
context 'when roster create present' do
let(:employee_created_at) { TimeKeeper.date_of_record }
it "should allow" do
expect(shop_enrollment.can_select_coverage?).to be_truthy
end
end
context 'when roster update present' do
let(:employee_updated_at) { TimeKeeper.date_of_record }
it "should not allow" do
expect(shop_enrollment.can_select_coverage?).to be_falsey
end
# TODO: code commented out in hbx_enrollment model. code needs to be enabled before adding this spec back.
# it "should get a error msg" do
# shop_enrollment.can_select_coverage?
# expect(shop_enrollment.errors.any?).to be_truthy
# expect(shop_enrollment.errors.full_messages.to_s).to match /You can not keep an existing plan which belongs to previous plan year/
# end
end
context 'with QLE' do
let(:effective_on) { qle_date.next_month.beginning_of_month }
let(:qualifying_life_event_kind) {FactoryGirl.create(:qualifying_life_event_kind)}
let(:user) {instance_double("User", :primary_family => test_family, :person => person)}
let(:qle) {FactoryGirl.create(:qualifying_life_event_kind)}
let(:test_family) {FactoryGirl.build(:family, :with_primary_family_member)}
let(:person) {shop_family.primary_family_member.person}
let(:special_enrollment_period) {
special_enrollment = shop_family.special_enrollment_periods.build({
qle_on: qle_date,
effective_on_kind: "first_of_month",
})
special_enrollment.qualifying_life_event_kind = qualifying_life_event_kind
special_enrollment.save
special_enrollment
}
let(:enrollment_kind) { "special_enrollment" }
let(:special_enrollment_period_id) { special_enrollment_period.id }
before do
allow(shop_enrollment).to receive(:plan_year_check).with(employee_role).and_return false
end
context 'under special enrollment period' do
let(:qle_date) { TimeKeeper.date_of_record }
it "should allow" do
expect(shop_enrollment.can_select_coverage?).to be_truthy
end
end
context 'outside special enrollment period' do
let(:qle_date) { TimeKeeper.date_of_record - 2.months }
it "should not allow" do
expect(shop_enrollment.can_select_coverage?).to be_falsey
end
end
end
end
end
context "Benefits are terminated" do
let(:effective_on_date) {TimeKeeper.date_of_record.beginning_of_month}
let!(:hbx_profile) {FactoryGirl.create(:hbx_profile)}
context "Individual benefit" do
let(:ivl_family) {FactoryGirl.create(:family, :with_primary_family_member)}
let(:ivl_enrollment) {FactoryGirl.create(:hbx_enrollment,
household: ivl_family.latest_household,
coverage_kind: "health",
effective_on: effective_on_date,
enrollment_kind: "open_enrollment",
kind: "individual",
submitted_at: effective_on_date - 10.days
)
}
let(:ivl_termination_date) {TimeKeeper.date_of_record}
it "should be open enrollment" do
expect(ivl_enrollment.is_open_enrollment?).to be_truthy
end
context "and coverage is terminated" do
before do
ivl_enrollment.terminate_benefit(TimeKeeper.date_of_record)
end
it "should have terminated date" do
expect(ivl_enrollment.terminated_on).to eq ivl_termination_date
end
it "should be in terminated state" do
expect(ivl_enrollment.aasm_state).to eq "coverage_terminated"
end
end
end
end
describe HbxEnrollment, "given a set of broker accounts", dbclean: :after_each do
let(:submitted_at) {Time.mktime(2008, 12, 13, 12, 34, 00)}
subject {HbxEnrollment.new(:submitted_at => submitted_at)}
let(:broker_agency_account_1) {double(:start_on => start_on_1, :end_on => end_on_1)}
let(:broker_agency_account_2) {double(:start_on => start_on_2, :end_on => end_on_2)}
describe "with both accounts active before the purchase, and the second one unterminated" do
let(:start_on_1) {submitted_at - 12.days}
let(:start_on_2) {submitted_at - 5.days}
let(:end_on_1) {nil}
let(:end_on_2) {nil}
it "should be able to select the applicable broker" do
expect(subject.select_applicable_broker_account([broker_agency_account_1, broker_agency_account_2])).to eq broker_agency_account_2
end
end
describe "with both accounts active before the purchase, and the later one terminated" do
let(:start_on_1) {submitted_at - 12.days}
let(:start_on_2) {submitted_at - 5.days}
let(:end_on_1) {nil}
let(:end_on_2) {submitted_at - 2.days}
it "should have no applicable broker" do
expect(subject.select_applicable_broker_account([broker_agency_account_1, broker_agency_account_2])).to eq nil
end
end
describe "with one account active before the purchase, and the other active after" do
let(:start_on_1) {submitted_at - 12.days}
let(:start_on_2) {submitted_at + 5.days}
let(:end_on_1) {nil}
let(:end_on_2) {nil}
it "should be able to select the applicable broker" do
expect(subject.select_applicable_broker_account([broker_agency_account_1, broker_agency_account_2])).to eq broker_agency_account_1
end
end
describe "with one account active before the purchase and terminated before the purchase, and the other active after" do
let(:start_on_1) {submitted_at - 12.days}
let(:start_on_2) {submitted_at + 5.days}
let(:end_on_1) {submitted_at - 3.days}
let(:end_on_2) {nil}
it "should have no applicable broker" do
expect(subject.select_applicable_broker_account([broker_agency_account_1, broker_agency_account_2])).to eq nil
end
end
end
describe HbxEnrollment, "given an enrollment kind of 'special_enrollment'", dbclean: :after_each do
subject {HbxEnrollment.new({:enrollment_kind => "special_enrollment"})}
it "should NOT be a shop new hire" do
expect(subject.new_hire_enrollment_for_shop?).to eq false
end
describe "and given a special enrollment period, with a reason of 'birth'" do
let(:qle_on) {Date.today}
before :each do
allow(subject).to receive(:special_enrollment_period).and_return(SpecialEnrollmentPeriod.new(
:qualifying_life_event_kind => QualifyingLifeEventKind.new(:reason => "birth"),
:qle_on => qle_on
))
end
it "should have the eligibility event date of the qle_on" do
expect(subject.eligibility_event_date).to eq qle_on
end
it "should have eligibility_event_kind of 'birth'" do
expect(subject.eligibility_event_kind).to eq "birth"
end
end
end
describe HbxEnrollment, "given an enrollment kind of 'open_enrollment'", dbclean: :after_each do
subject {HbxEnrollment.new({:enrollment_kind => "open_enrollment"})}
it "should not have an eligibility event date" do
expect(subject.eligibility_event_has_date?).to eq false
end
describe "in the IVL market" do
before :each do
subject.kind = "unassisted_qhp"
end
it "should not have an eligibility event date" do
expect(subject.eligibility_event_has_date?).to eq false
end
it "should NOT be a shop new hire" do
expect(subject.new_hire_enrollment_for_shop?).to eq false
end
it "should have eligibility_event_kind of 'open_enrollment'" do
expect(subject.eligibility_event_kind).to eq "open_enrollment"
end
end
describe "in the SHOP market, purchased outside of open enrollment" do
include_context "setup benefit market with market catalogs and product packages"
include_context "setup initial benefit application"
let(:current_effective_date) { TimeKeeper.date_of_record.beginning_of_month }
let(:reference_date) { current_effective_date }
# let(:open_enrollment_start) {reference_date - 15.days}
# let(:open_enrollment_end) {reference_date - 5.days}
let(:purchase_time) {Time.now - 20.days}
let(:hired_on) {reference_date - 21.days}
before :each do
subject.kind = "employer_sponsored"
subject.submitted_at = purchase_time
subject.benefit_group_assignment = BenefitGroupAssignment.new({
:census_employee => CensusEmployee.new({
:hired_on => hired_on
})
})
allow(subject).to receive(:sponsored_benefit_package).and_return(current_benefit_package)
end
it "should have an eligibility event date" do
expect(subject.eligibility_event_has_date?).to eq true
end
it "should be a shop new hire" do
expect(subject.new_hire_enrollment_for_shop?).to eq true
end
it "should have eligibility_event_kind of 'new_hire'" do
expect(subject.eligibility_event_kind).to eq "new_hire"
end
it "should have the eligibility event date of hired_on" do
expect(subject.eligibility_event_date).to eq hired_on
end
end
describe "in the SHOP market, purchased during open enrollment" do
include_context "setup benefit market with market catalogs and product packages"
include_context "setup initial benefit application"
let(:current_effective_date) { TimeKeeper.date_of_record.beginning_of_month.prev_month }
let(:reference_date) { current_effective_date }
let(:purchase_time) { initial_application.open_enrollment_end_on.prev_day }
let(:hired_on) {(reference_date - 21.days).to_date}
before :each do
subject.kind = "employer_sponsored"
subject.submitted_at = purchase_time
subject.benefit_group_assignment = BenefitGroupAssignment.new({
:census_employee => CensusEmployee.new({
:hired_on => hired_on,
:created_at => hired_on
})
})
allow(subject).to receive(:sponsored_benefit_package).and_return(current_benefit_package)
end
describe "when coverage start is the same as the plan year" do
before(:each) do
subject.effective_on = reference_date
subject.submitted_at = purchase_time
end
it "should NOT have an eligibility event date" do
expect(subject.eligibility_event_has_date?).to eq false
end
it "should NOT be a shop new hire" do
expect(subject.new_hire_enrollment_for_shop?).to eq false
end
it "should have eligibility_event_kind of 'open_enrollment'" do
expect(subject.eligibility_event_kind).to eq "open_enrollment"
end
end
describe "when coverage start is the different from the plan year" do
before(:each) do
subject.effective_on = reference_date + 12.days
end
it "should have an eligibility event date" do
expect(subject.eligibility_event_has_date?).to eq true
end
it "should be a shop new hire" do
expect(subject.new_hire_enrollment_for_shop?).to eq true
end
it "should have eligibility_event_kind of 'new_hire'" do
expect(subject.eligibility_event_kind).to eq "new_hire"
end
it "should have the eligibility event date of hired_on" do
expect(subject.eligibility_event_date).to eq hired_on
end
end
end
end
describe HbxEnrollment, 'dental shop calculation related', type: :model, dbclean: :after_each do
context ".find_enrollments_by_benefit_group_assignment" do
let(:enrollment) { FactoryGirl.create(:hbx_enrollment,
household: family.active_household,
benefit_group_assignment_id: benefit_group_assignment.id,
aasm_state: "coverage_selected",
coverage_kind: "health",
kind: "employer_sponsored"
)}
let(:family) { FactoryGirl.create(:family, :with_primary_family_member)}
let(:benefit_group_assignment) { FactoryGirl.build(:benefit_group_assignment)}
let(:subject) { HbxEnrollment.find_enrollments_by_benefit_group_assignment(benefit_group_assignment) }
it "should return the enrollment with the benefit group assignment" do
enrollment
expect(subject).to include enrollment
end
it "should be empty if no active coverage" do
enrollment.update_attributes(aasm_state: "shopping")
expect(subject).to be_empty
end
it "should be empty when no active enrollment with given benefit_group_assignment id" do
enrollment.update_attributes(aasm_state: "coverage_selected", benefit_group_assignment_id: "")
expect(subject).to be_empty
end
it "should return the dental enrollment" do
enrollment.update_attributes(coverage_kind: 'dental', aasm_state: 'coverage_selected')
expect(subject).to include enrollment
end
end
end
context "A cancelled external enrollment", :dbclean => :after_each do
let(:family) {FactoryGirl.create(:family, :with_primary_family_member)}
let(:enrollment) do
FactoryGirl.create(:hbx_enrollment,
household: family.active_household,
kind: "employer_sponsored",
submitted_at: TimeKeeper.datetime_of_record - 3.day,
created_at: TimeKeeper.datetime_of_record - 3.day
)
end
before do
enrollment.aasm_state = "coverage_canceled"
enrollment.terminated_on = enrollment.effective_on
enrollment.external_enrollment = true
enrollment.hbx_enrollment_members.each do |em|
em.coverage_end_on = em.coverage_start_on
end
enrollment.save!
end
it "should not be visible to the family" do
expect(family.enrollments_for_display.to_a).to eq([])
end
it "should not be visible to the family" do
enrollment.aasm_state = "coverage_terminated"
enrollment.external_enrollment = true
enrollment.save!
expect(family.enrollments_for_display.to_a).to eq([])
end
it "should not be visible to the family" do
enrollment.aasm_state = "coverage_selected"
enrollment.external_enrollment = true
enrollment.save!
expect(family.enrollments_for_display.to_a).to eq([])
end
it "should not be visible to the family" do
enrollment.aasm_state = "coverage_canceled"
enrollment.external_enrollment = false
enrollment.save!
expect(family.enrollments_for_display.to_a).to eq([])
end
it "should not be visible to the family" do
enrollment.aasm_state = "coverage_canceled"
enrollment.external_enrollment = true
enrollment.save!
expect(family.enrollments_for_display.to_a).to eq([])
end
it "should not be visible to the family" do
enrollment.aasm_state = "coverage_selected"
enrollment.external_enrollment = false
enrollment.save!
expect(family.enrollments_for_display.to_a).not_to eq([])
end
it "should not be visible to the family" do
enrollment.aasm_state = "coverage_terminated"
enrollment.external_enrollment = false
enrollment.save!
expect(family.enrollments_for_display.to_a).not_to eq([])
end
end
context "for cobra", :dbclean => :after_each do
let(:enrollment) {HbxEnrollment.new(kind: 'employer_sponsored')}
let(:cobra_enrollment) {HbxEnrollment.new(kind: 'employer_sponsored_cobra')}
context "is_cobra_status?" do
it "should return false" do
expect(enrollment.is_cobra_status?).to be_falsey
end
it "should return true" do
enrollment.kind = 'employer_sponsored_cobra'
expect(enrollment.is_cobra_status?).to be_truthy
end
end
context "cobra_future_active?" do
it "should return false when not cobra" do
expect(enrollment.cobra_future_active?).to be_falsey
end
context "when cobra" do
it "should return false" do
allow(cobra_enrollment).to receive(:future_active?).and_return false
expect(cobra_enrollment.cobra_future_active?).to be_falsey
end
it "should return true" do
allow(cobra_enrollment).to receive(:future_active?).and_return true
expect(cobra_enrollment.cobra_future_active?).to be_truthy
end
end
end
context "future_enrollment_termination_date" do
let(:employee_role) {FactoryGirl.create(:employee_role)}
let(:census_employee) {FactoryGirl.create(:census_employee)}
let(:coverage_termination_date) {TimeKeeper.date_of_record + 1.months}
it "should return blank if not coverage_termination_pending" do
expect(enrollment.future_enrollment_termination_date).to eq ""
end
it "should return coverage_termination_date by census_employee" do
census_employee.coverage_terminated_on = coverage_termination_date
employee_role.census_employee = census_employee
enrollment.employee_role = employee_role
enrollment.aasm_state = "coverage_termination_pending"
expect(enrollment.future_enrollment_termination_date).to eq coverage_termination_date
end
end
it "can_select_coverage?" do
enrollment.kind = 'employer_sponsored_cobra'
expect(enrollment.can_select_coverage?).to be_truthy
end
context "benefit_package_name" do
let(:benefit_group) {FactoryGirl.create(:benefit_group)}
let(:benefit_package) {BenefitPackage.new(title: 'benefit package title')}
it "for shop" do
enrollment.kind = 'employer_sponsored'
enrollment.benefit_group = benefit_group
expect(enrollment.benefit_package_name).to eq benefit_group.title
end
end
end
describe HbxEnrollment, 'Updating Existing Coverage', type: :model, dbclean: :after_each do
include_context "setup benefit market with market catalogs and product packages"
let(:effective_on) { current_effective_date }
let(:hired_on) { TimeKeeper.date_of_record - 3.months }
let(:person) {FactoryGirl.create(:person)}
let(:shop_family) {FactoryGirl.create(:family, :with_primary_family_member, person: person)}
let(:aasm_state) { :active }
let(:census_employee) { create(:census_employee, :with_active_assignment, benefit_sponsorship: benefit_sponsorship, employer_profile: benefit_sponsorship.profile, benefit_group: current_benefit_package, hired_on: hired_on, employee_role_id: employee_role.id) }
let(:employee_role) { FactoryGirl.create(:employee_role, benefit_sponsors_employer_profile_id: abc_profile.id, hired_on: hired_on, person: person) }
let(:enrollment_kind) { "open_enrollment" }
let(:special_enrollment_period_id) { nil }
let!(:enrollment) { FactoryGirl.create(:hbx_enrollment,
household: shop_family.latest_household,
coverage_kind: "health",
effective_on: effective_on,
enrollment_kind: enrollment_kind,
kind: "employer_sponsored",
submitted_at: effective_on - 20.days,
benefit_sponsorship_id: benefit_sponsorship.id,
sponsored_benefit_package_id: current_benefit_package.id,
sponsored_benefit_id: current_benefit_package.sponsored_benefits[0].id,
employee_role_id: employee_role.id,
benefit_group_assignment_id: census_employee.active_benefit_group_assignment.id,
special_enrollment_period_id: special_enrollment_period_id,
product_id: current_benefit_package.sponsored_benefits[0].reference_product.id
)
}
before do
employee_role.update(census_employee_id: census_employee.id)
end
context 'When family has active coverage and makes changes for their coverage', dbclean: :after_each do
include_context "setup initial benefit application"
let(:special_enrollment_period) {
FactoryGirl.create(:special_enrollment_period, family: shop_family)
}
let(:new_enrollment_eff_on) { TimeKeeper.date_of_record.next_month.beginning_of_month }
let(:new_enrollment) { FactoryGirl.create(:hbx_enrollment,
household: shop_family.latest_household,
coverage_kind: "health",
effective_on: new_enrollment_eff_on,
enrollment_kind: enrollment_kind,
kind: "employer_sponsored",
submitted_at: TimeKeeper.date_of_record,
benefit_sponsorship_id: benefit_sponsorship.id,
sponsored_benefit_package_id: current_benefit_package.id,
sponsored_benefit_id: current_benefit_package.sponsored_benefits[0].id,
employee_role_id: employee_role.id,
benefit_group_assignment_id: census_employee.active_benefit_group_assignment.id,
special_enrollment_period_id: special_enrollment_period.id,
predecessor_enrollment_id: enrollment.id,
aasm_state: 'shopping'
)
}
let(:terminated_date) { new_enrollment_eff_on - 1.day }
it 'should terminate existing coverage' do
expect(enrollment.coverage_selected?).to be_truthy
expect(enrollment.terminated_on).to be_nil
new_enrollment.select_coverage!
enrollment.reload
if terminated_date <= TimeKeeper.date_of_record
expect(enrollment.coverage_terminated?).to be_truthy
else
expect(enrollment.coverage_termination_pending?).to be_truthy
end
expect(enrollment.terminated_on).to eq(terminated_date)
end
end
context 'When family passively renewed', dbclean: :after_each do
include_context "setup renewal application"
let(:predecessor_application_catalog) { true }
let(:current_effective_date) { (TimeKeeper.date_of_record + 2.months).beginning_of_month - 1.year }
let(:renewal_state) { :enrollment_open }
let(:open_enrollment_period) { TimeKeeper.date_of_record..(effective_period.min - 10.days) }
let(:current_benefit_package) { renewal_application.predecessor.benefit_packages[0] }
let(:generate_passive_renewal) {
census_employee.update!(created_at: 2.months.ago)
census_employee.assign_to_benefit_package(benefit_package, renewal_effective_date)
benefit_package.renew_member_benefit(census_employee)
}
let(:enrollment_effective_on) { renewal_effective_date }
let(:special_enrollment_period_id) { nil }
let(:passive_renewal) { shop_family.reload.enrollments.where(:aasm_state => 'auto_renewing').first }
context 'When Actively Renewed', dbclean: :after_each do
let(:new_enrollment_product_id) { passive_renewal.product_id }
let(:new_enrollment) { FactoryGirl.create(:hbx_enrollment,
household: shop_family.latest_household,
coverage_kind: "health",
effective_on: enrollment_effective_on,
enrollment_kind: enrollment_kind,
kind: "employer_sponsored",
submitted_at: TimeKeeper.date_of_record,
benefit_sponsorship_id: benefit_sponsorship.id,
sponsored_benefit_package_id: benefit_package.id,
sponsored_benefit_id: benefit_package.sponsored_benefits[0].id,
employee_role_id: employee_role.id,
benefit_group_assignment_id: census_employee.renewal_benefit_group_assignment.id,
predecessor_enrollment_id: passive_renewal.id,
product_id: new_enrollment_product_id,
special_enrollment_period_id: special_enrollment_period_id,
aasm_state: 'shopping'
)
}
before do
allow(benefit_package).to receive(:is_renewal_benefit_available?).and_return(true)
generate_passive_renewal
end
context 'with same effective date as passive renewal' do
it 'should cancel their passive renewal' do
expect(passive_renewal).not_to be_nil
new_enrollment.select_coverage!
passive_renewal.reload
new_enrollment.reload
expect(passive_renewal.coverage_canceled?).to be_truthy
expect(new_enrollment.coverage_selected?).to be_truthy
end
end
context 'with effective date later to the passive renewal' do
let(:enrollment_effective_on) { renewal_effective_date.next_month }
it 'should terminate the passive renewal' do
expect(passive_renewal).not_to be_nil
new_enrollment.select_coverage!
passive_renewal.reload
new_enrollment.reload
expect(new_enrollment.coverage_selected?).to be_truthy
expect(passive_renewal.coverage_termination_pending?).to be_truthy
expect(passive_renewal.terminated_on).to eq(new_enrollment.effective_on - 1.day)
end
end
end
context '.update_renewal_coverage', dbclean: :after_each do
before do
allow(benefit_package).to receive(:is_renewal_benefit_available?).and_return(true)
generate_passive_renewal
end
context 'when EE enters SEP and picks new plan' do
let(:enrollment_effective_on) { renewal_effective_date - 3.months }
let(:new_enrollment) { FactoryGirl.create(:hbx_enrollment,
household: shop_family.latest_household,
coverage_kind: "health",
effective_on: enrollment_effective_on,
enrollment_kind: enrollment_kind,
kind: "employer_sponsored",
submitted_at: TimeKeeper.date_of_record,
benefit_sponsorship_id: benefit_sponsorship.id,
sponsored_benefit_package_id: current_benefit_package.id,
sponsored_benefit_id: current_benefit_package.sponsored_benefits[0].id,
employee_role_id: employee_role.id,
benefit_group_assignment_id: census_employee.active_benefit_group_assignment.id,
predecessor_enrollment_id: enrollment.id,
product_id: new_enrollment_product.id,
special_enrollment_period_id: special_enrollment_period_id,
aasm_state: 'shopping'
)
}
let(:new_enrollment_product) {
product_package = current_benefit_package.sponsored_benefits[0].product_package
product_package.products.detect{|product| product != enrollment.product }
}
let(:special_enrollment_period_id) { FactoryGirl.create(:special_enrollment_period, family: shop_family).id }
it 'should cancel passive renewal and create new passive' do
expect(passive_renewal).not_to be_nil
new_enrollment.select_coverage!
passive_renewal.reload
new_enrollment.reload
enrollment.reload
expect(enrollment.coverage_terminated?).to be_truthy
expect(passive_renewal.coverage_canceled?).to be_truthy
expect(new_enrollment.coverage_selected?).to be_truthy
new_passive = shop_family.reload.active_household.hbx_enrollments.where(:aasm_state => :auto_renewing, :effective_on => renewal_effective_date).first
expect(new_passive.product).to eq new_enrollment_product.renewal_product
end
context 'when employee actively renewed coverage' do
it 'should not cancel active renewal and should not generate passive' do
passive_renewal.update(aasm_state: 'coverage_selected')
new_enrollment.select_coverage!
passive_renewal.reload
enrollment.reload
expect(enrollment.coverage_terminated?).to be_truthy
expect(new_enrollment.coverage_selected?).to be_truthy
expect(passive_renewal.coverage_canceled?).to be_falsey
new_passive = shop_family.reload.enrollments.by_coverage_kind('health').where(:aasm_state => 'auto_renewing').first
expect(new_passive.blank?).to be_truthy
end
end
end
context 'when EE terminates current coverage' do
let(:new_enrollment) { FactoryGirl.create(:hbx_enrollment,
household: shop_family.latest_household,
coverage_kind: "health",
effective_on: enrollment_effective_on,
enrollment_kind: enrollment_kind,
kind: "employer_sponsored",
submitted_at: TimeKeeper.date_of_record,
benefit_sponsorship_id: benefit_sponsorship.id,
sponsored_benefit_package_id: current_benefit_package.id,
sponsored_benefit_id: current_benefit_package.sponsored_benefits[0].id,
employee_role_id: employee_role.id,
benefit_group_assignment_id: census_employee.active_benefit_group_assignment.id,
predecessor_enrollment_id: enrollment.id,
product_id: enrollment.product_id,
aasm_state: 'shopping'
)
}
it 'should cancel passive renewal and generate a waiver' do
pending("verify if update_renewal_coverage needs to be executed when EE current active coverage is terminated.")
expect(passive_renewal).not_to be_nil
new_enrollment.waive_coverage!
passive_renewal.reload
enrollment.reload
new_enrollment.reload
expect(enrollment.coverage_terminated?).to be_truthy
expect(new_enrollment.inactive?).to be_truthy
expect(passive_renewal.coverage_canceled?).to be_truthy
passive_waiver = shop_family.reload.enrollments.where(:aasm_state => 'renewing_waived').first
expect(passive_waiver.present?).to be_truthy
end
end
end
end
context "market_name" do
include_context "setup initial benefit application"
it "for shop" do
enrollment.kind = 'employer_sponsored'
expect(enrollment.market_name).to eq 'Employer Sponsored'
end
it "for individual" do
enrollment.kind = 'individual'
expect(enrollment.market_name).to eq 'Individual'
end
end
end
describe HbxEnrollment, 'Voiding enrollments', type: :model, dbclean: :after_each do
let!(:hbx_profile) {FactoryGirl.create(:hbx_profile)}
let(:family) {FactoryGirl.build(:individual_market_family)}
let(:hbx_enrollment) {FactoryGirl.build(:hbx_enrollment, :individual_unassisted, household: family.active_household, effective_on: TimeKeeper.date_of_record)}
context "Enrollment is in active state" do
it "enrollment is in coverage_selected state" do
expect(hbx_enrollment.coverage_selected?).to be_truthy
end
context "and the enrollment is invalidated" do
it "enrollment should transition to void state" do
hbx_enrollment.invalidate_enrollment!
expect(HbxEnrollment.find(hbx_enrollment.id).void?).to be_truthy
end
end
end
context "Enrollment is in terminated state" do
before do
hbx_enrollment.terminate_benefit(TimeKeeper.date_of_record - 2.months)
hbx_enrollment.save!
end
# Although slower, it's essential to read the record from DB, as the in-memory version may differ
it "enrollment is in terminated state" do
expect(HbxEnrollment.find(hbx_enrollment.id).coverage_terminated?).to be_truthy
end
context "and the enrollment is invalidated" do
before do
hbx_enrollment.invalidate_enrollment
hbx_enrollment.save!
end
it "enrollment should transition to void state" do
expect(HbxEnrollment.find(hbx_enrollment.id).void?).to be_truthy
end
it "terminated_on value should be null" do
expect(HbxEnrollment.find(hbx_enrollment.id).terminated_on).to be_nil
end
it "terminate_reason value should be null" do
expect(HbxEnrollment.find(hbx_enrollment.id).terminate_reason).to be_nil
end
end
end
end
describe HbxEnrollment, 'Renewal Purchase', type: :model, dbclean: :after_each do
let(:family) {FactoryGirl.build(:individual_market_family)}
let(:hbx_enrollment) {FactoryGirl.build(:hbx_enrollment, :individual_unassisted, household: family.active_household, kind: 'individual')}
context "open enrollment" do
before do
hbx_enrollment.update(enrollment_kind: 'open_enrollment')
end
it "should return true when auto_renewing" do
FactoryGirl.build(:hbx_enrollment, :individual_unassisted, household: family.active_household, aasm_state: 'auto_renewing')
expect(hbx_enrollment.is_active_renewal_purchase?).to be_truthy
end
it "should return true when renewing_coverage_selected" do
FactoryGirl.build(:hbx_enrollment, :individual_unassisted, household: family.active_household, aasm_state: 'renewing_coverage_selected')
expect(hbx_enrollment.is_active_renewal_purchase?).to be_truthy
end
it "should return false when coverage_selected" do
FactoryGirl.build(:hbx_enrollment, :individual_unassisted, household: family.active_household, aasm_state: 'coverage_selected')
expect(hbx_enrollment.is_active_renewal_purchase?).to be_falsey
end
end
it "should return false when it is not open_enrollment" do
hbx_enrollment.update(enrollment_kind: 'special_enrollment')
expect(hbx_enrollment.is_active_renewal_purchase?).to be_falsey
end
it "should return false when it is individual" do
hbx_enrollment.update(kind: 'employer_sponsored')
expect(hbx_enrollment.is_active_renewal_purchase?).to be_falsey
end
end
describe HbxEnrollment, 'state machine', dbclean: :after_each do
let(:family) {FactoryGirl.build(:individual_market_family)}
subject {FactoryGirl.build(:hbx_enrollment, :individual_unassisted, household: family.active_household)}
events = [:move_to_enrolled, :move_to_contingent, :move_to_pending]
shared_examples_for "state machine transitions" do |current_state, new_state, event|
it "transition #{current_state} to #{new_state} on #{event} event" do
expect(subject).to transition_from(current_state).to(new_state).on_event(event)
end
end
context "move_to_enrolled event" do
it_behaves_like "state machine transitions", :unverified, :coverage_selected, :move_to_enrolled
it_behaves_like "state machine transitions", :enrolled_contingent, :coverage_selected, :move_to_enrolled
end
context "move_to_contingent event" do
it_behaves_like "state machine transitions", :shopping, :enrolled_contingent, :move_to_contingent!
it_behaves_like "state machine transitions", :coverage_selected, :enrolled_contingent, :move_to_contingent!
it_behaves_like "state machine transitions", :unverified, :enrolled_contingent, :move_to_contingent!
it_behaves_like "state machine transitions", :coverage_enrolled, :enrolled_contingent, :move_to_contingent!
it_behaves_like "state machine transitions", :auto_renewing, :enrolled_contingent, :move_to_contingent!
end
context "move_to_pending event" do
it_behaves_like "state machine transitions", :shopping, :unverified, :move_to_pending!
it_behaves_like "state machine transitions", :coverage_selected, :unverified, :move_to_pending!
it_behaves_like "state machine transitions", :enrolled_contingent, :unverified, :move_to_pending!
it_behaves_like "state machine transitions", :coverage_enrolled, :unverified, :move_to_pending!
it_behaves_like "state machine transitions", :auto_renewing, :unverified, :move_to_pending!
end
end
describe HbxEnrollment, 'validate_for_cobra_eligiblity', dbclean: :after_each do
context 'When employee is designated as cobra' do
let(:effective_on) {TimeKeeper.date_of_record.beginning_of_month}
let(:cobra_begin_date) {TimeKeeper.date_of_record.next_month.beginning_of_month}
let(:hbx_enrollment) {HbxEnrollment.new(kind: 'employer_sponsored', effective_on: effective_on)}
let(:employee_role) {double(is_cobra_status?: true, census_employee: census_employee)}
let(:census_employee) {double(cobra_begin_date: cobra_begin_date, have_valid_date_for_cobra?: true, coverage_terminated_on: cobra_begin_date - 1.day)}
before do
allow(hbx_enrollment).to receive(:employee_role).and_return(employee_role)
end
context 'When Enrollment Effectve date is prior to cobra begin date' do
it 'should reset enrollment effective date to cobra begin date' do
hbx_enrollment.validate_for_cobra_eligiblity(employee_role)
expect(hbx_enrollment.kind).to eq 'employer_sponsored_cobra'
expect(hbx_enrollment.effective_on).to eq cobra_begin_date
end
end
context 'When Enrollment Effectve date is after cobra begin date' do
let(:cobra_begin_date) {TimeKeeper.date_of_record.prev_month.beginning_of_month}
it 'should not update enrollment effective date' do
hbx_enrollment.validate_for_cobra_eligiblity(employee_role)
expect(hbx_enrollment.kind).to eq 'employer_sponsored_cobra'
expect(hbx_enrollment.effective_on).to eq effective_on
end
end
context 'When employee not elgibile for cobra' do
let(:census_employee) {double(cobra_begin_date: cobra_begin_date, have_valid_date_for_cobra?: false, coverage_terminated_on: cobra_begin_date - 1.day)}
it 'should raise error' do
expect {hbx_enrollment.validate_for_cobra_eligiblity(employee_role)}.to raise_error("You may not enroll for cobra after #{Settings.aca.shop_market.cobra_enrollment_period.months} months later of coverage terminated.")
end
end
end
end
describe HbxEnrollment, '.build_plan_premium', type: :model, dbclean: :after_each do
include_context "setup benefit market with market catalogs and product packages"
include_context "setup initial benefit application"
let!(:employer_profile) {benefit_sponsorship.profile}
let(:benefit_group) {employer_profile.published_plan_year.benefit_groups.first}
let!(:census_employees) {
FactoryGirl.create :census_employee, :owner, employer_profile: employer_profile, benefit_sponsorship: benefit_sponsorship
employee = FactoryGirl.create :census_employee, employer_profile: employer_profile, benefit_sponsorship: benefit_sponsorship
employee.add_benefit_group_assignment benefit_group, benefit_group.start_on
}
let!(:plan) {
FactoryGirl.create(:plan, :with_premium_tables, market: 'shop', metal_level: 'gold', active_year: benefit_group.start_on.year, hios_id: "11111111122302-01", csr_variant_id: "01")
}
let(:ce) {employer_profile.census_employees.non_business_owner.first}
let!(:family) {
person = FactoryGirl.create(:person, last_name: ce.last_name, first_name: ce.first_name)
employee_role = FactoryGirl.create(:employee_role, person: person, census_employee: ce, benefit_sponsors_employer_profile_id: employer_profile.id)
ce.update_attributes({employee_role: employee_role})
Family.find_or_build_from_employee_role(employee_role)
}
let(:person) {family.primary_applicant.person}
context 'Employer Sponsored Coverage' do
let!(:enrollment) {
FactoryGirl.create(:hbx_enrollment,
household: family.active_household,
coverage_kind: "health",
effective_on: benefit_group.start_on,
enrollment_kind: "open_enrollment",
kind: "employer_sponsored",
sponsored_benefit_package_id: benefit_group.id,
employee_role_id: person.active_employee_roles.first.id,
benefit_group_assignment_id: ce.active_benefit_group_assignment.id,
plan_id: plan.id
)
}
context 'for congression employer' do
before do
allow(enrollment).to receive_message_chain("benefit_group.is_congress") {true}
end
it "should build premiums" do
plan = enrollment.build_plan_premium(qhp_plan: enrollment.plan)
expect(plan).to be_kind_of(PlanCostDecoratorCongress)
end
end
context 'for non congression employer' do
before do
allow(enrollment).to receive_message_chain("benefit_group.is_congress") {false}
allow(enrollment).to receive(:composite_rated?).and_return(false)
allow(enrollment).to receive_message_chain("benefit_group.reference_plan") { plan }
end
it "should build premiums" do
plan = enrollment.build_plan_premium(qhp_plan: enrollment.plan)
expect(plan).to be_kind_of(PlanCostDecorator)
end
end
end
context 'Individual Coverage' do
let!(:enrollment) {
FactoryGirl.create(:hbx_enrollment,
household: family.active_household,
coverage_kind: "health",
effective_on: TimeKeeper.date_of_record.beginning_of_month,
enrollment_kind: "open_enrollment",
kind: "individual",
plan_id: plan.id
)
}
it "should build premiums" do
plan = enrollment.build_plan_premium(qhp_plan: plan)
expect(plan).to be_kind_of(UnassistedPlanCostDecorator)
end
end
end
describe HbxEnrollment, dbclean: :after_each do
include_context "BradyWorkAfterAll"
before :all do
create_brady_census_families
end
context "Cancel / Terminate Previous Enrollments for Shop" do
let(:family) { FactoryGirl.create(:family, :with_primary_family_member)}
let(:existing_shop_enrollment) {FactoryGirl.create(:hbx_enrollment, :shop, household: family.active_household, effective_on: TimeKeeper.date_of_record)}
let(:new_enrollment) {FactoryGirl.create(:hbx_enrollment, :shop, household: family.active_household, predecessor_enrollment_id: existing_shop_enrollment.id, effective_on: TimeKeeper.date_of_record)}
it "should cancel the previous enrollment if the effective_on date of the previous and the current are the same." do
new_enrollment.update_existing_shop_coverage
existing_shop_enrollment.reload
expect(existing_shop_enrollment.aasm_state).to eq "coverage_canceled"
end
end
context "Cancel / Terminate Previous Enrollments for IVL" do
attr_reader :enrollment, :household, :coverage_household
let(:consumer_role) {FactoryGirl.create(:consumer_role)}
let(:hbx_profile) {FactoryGirl.create(:hbx_profile)}
let(:benefit_package) {hbx_profile.benefit_sponsorship.benefit_coverage_periods.first.benefit_packages.first}
let(:benefit_coverage_period) {hbx_profile.benefit_sponsorship.benefit_coverage_periods.first}
let(:family) {FactoryGirl.build(:family)}
before :each do
@household = mikes_family.households.first
@coverage_household = household.coverage_households.first
allow(benefit_coverage_period).to receive(:earliest_effective_date).and_return TimeKeeper.date_of_record
allow(coverage_household).to receive(:household).and_return household
allow(household).to receive(:family).and_return family
allow(family).to receive(:is_under_ivl_open_enrollment?).and_return true
@enrollment1 = household.create_hbx_enrollment_from(consumer_role: consumer_role, coverage_household: coverage_household, benefit_package: benefit_package)
@enrollment1.update_current(aasm_state: "coverage_selected", enrollment_signature: "somerandomthing!", effective_on: TimeKeeper.date_of_record.beginning_of_month)
@enrollment2 = household.create_hbx_enrollment_from(consumer_role: consumer_role, coverage_household: coverage_household, benefit_package: benefit_package)
@enrollment2.update_current(enrollment_signature: "somerandomthing!", effective_on: TimeKeeper.date_of_record.beginning_of_month)
end
it "should cancel the previous enrollment if the effective_on date of the previous and the current are the same." do
@enrollment2.cancel_previous(TimeKeeper.date_of_record.year)
expect(@enrollment1.aasm_state).to eq "coverage_canceled"
end
end
end
end
describe HbxEnrollment, type: :model, :dbclean => :after_each do
let!(:rating_area) { create_default(:benefit_markets_locations_rating_area) }
include_context "setup benefit market with market catalogs and product packages" do
let(:product_kinds) { [:health, :dental] }
end
include_context "setup initial benefit application" do
let(:dental_sponsored_benefit) { true }
end
describe ".renew_benefit" do
describe "given an renewing employer just entered open enrollment" do
describe "with employees who have made the following plan selections previous year:
- employee A has purchased:
- One health enrollment (Enrollment 1)
- One dental enrollment (Enrollment 2)
- employee B has purchased:
- One health enrollment (Enrollment 3)
- One dental waiver (Enrollment 4)
- employee C has purchased:
- One health waiver (Enrollment 5)
- One dental enrollment (Enrollment 6)
- employee D has purchased:
- One health waiver (Enrollment 7)
- One dental waiver (Enrollment 8)
- employee E has none
" do
let(:census_employees) {
create_list(:census_employee, 5, :with_active_assignment, benefit_sponsorship: benefit_sponsorship, employer_profile: benefit_sponsorship.profile, benefit_group: current_benefit_package)
}
let(:employee_A) {
ce = census_employees[0]
create_person(ce, abc_profile)
}
let!(:enrollment_1) {
create_enrollment(family: employee_A.person.primary_family, benefit_group_assignment: employee_A.census_employee.active_benefit_group_assignment, employee_role: employee_A,
submitted_at: current_effective_date - 10.days)
}
let!(:enrollment_2) {
create_enrollment(family: employee_A.person.primary_family, benefit_group_assignment: employee_A.census_employee.active_benefit_group_assignment, employee_role: employee_A,
submitted_at: current_effective_date - 10.days, coverage_kind: 'dental')
}
let(:employee_B) {
ce = census_employees[1]
create_person(ce, abc_profile)
}
let!(:enrollment_3) {
create_enrollment(family: employee_B.person.primary_family, benefit_group_assignment: employee_B.census_employee.active_benefit_group_assignment, employee_role: employee_B,
submitted_at: current_effective_date - 10.days)
}
let!(:enrollment_4) {
create_enrollment(family: employee_B.person.primary_family, benefit_group_assignment: employee_B.census_employee.active_benefit_group_assignment, employee_role: employee_B,
submitted_at: current_effective_date - 10.days, coverage_kind: 'dental', status: 'inactive')
}
let(:employee_C) {
ce = census_employees[2]
create_person(ce, abc_profile)
}
let!(:enrollment_5) {
create_enrollment(family: employee_C.person.primary_family, benefit_group_assignment: employee_C.census_employee.active_benefit_group_assignment, employee_role: employee_C,
submitted_at: current_effective_date - 10.days, status: 'inactive')
}
let!(:enrollment_6) {
create_enrollment(family: employee_C.person.primary_family, benefit_group_assignment: employee_C.census_employee.active_benefit_group_assignment, employee_role: employee_C,
submitted_at: current_effective_date - 10.days, coverage_kind: 'dental')
}
let(:employee_D) {
ce = census_employees[3]
create_person(ce, abc_profile)
}
let!(:enrollment_7) {
create_enrollment(family: employee_D.person.primary_family, benefit_group_assignment: employee_D.census_employee.active_benefit_group_assignment, employee_role: employee_D,
submitted_at: current_effective_date - 10.days, status: 'inactive')
}
let!(:enrollment_8) {
create_enrollment(family: employee_D.person.primary_family, benefit_group_assignment: employee_D.census_employee.active_benefit_group_assignment, employee_role: employee_D,
submitted_at: current_effective_date - 10.days, coverage_kind: 'dental', status: 'inactive')
}
let!(:employee_E) {
ce = census_employees[3]
create_person(ce, abc_profile)
}
let(:renewal_application) {
renewal_effective_date = current_effective_date.next_year
service_areas = initial_application.benefit_sponsorship.service_areas_on(renewal_effective_date)
benefit_sponsor_catalog = benefit_sponsorship.benefit_sponsor_catalog_for(service_areas, renewal_effective_date)
r_application = initial_application.renew(benefit_sponsor_catalog)
r_application.save
r_application
}
let(:renewal_benefit_package) {
renewal_application.benefit_packages[0]
}
before do
allow(::BenefitMarkets::Products::ProductRateCache).to receive(:lookup_rate).and_return(100.0)
renewal_benefit_package.sponsored_benefits.each do |sponsored_benefit|
allow(sponsored_benefit).to receive(:products).and_return(sponsored_benefit.product_package.products)
end
renewal_application
end
context 'renewing employee A' do
before do
renewal_benefit_package.renew_member_benefit(census_employees[0])
family.reload
end
let(:family) { employee_A.person.primary_family }
let(:health_renewals) { family.active_household.hbx_enrollments.renewing.by_health }
let(:dental_renewals) { family.active_household.hbx_enrollments.renewing.by_dental }
it 'does renew both health and dental enrollment' do
expect(health_renewals.size).to eq 1
expect(health_renewals[0].product).to eq enrollment_1.product.renewal_product
expect(dental_renewals.size).to eq 1
expect(dental_renewals[0].product).to eq enrollment_2.product.renewal_product
end
end
context 'renewing employee B' do
before do
renewal_benefit_package.renew_member_benefit(census_employees[1])
family.reload
end
let(:family) { employee_B.person.primary_family }
let(:health_renewals) { family.active_household.hbx_enrollments.renewing.by_health }
let(:dental_renewals) { family.active_household.hbx_enrollments.by_dental.select{|en| en.renewing_waived?} }
it 'does renew health coverage and waive dental coverage' do
expect(health_renewals.size).to eq 1
expect(health_renewals[0].product).to eq enrollment_3.product.renewal_product
expect(dental_renewals.size).to eq 1
end
end
context 'renewing employee C' do
before do
renewal_benefit_package.renew_member_benefit(census_employees[2])
family.reload
end
let(:family) { employee_C.person.primary_family }
let(:health_renewals) { family.active_household.hbx_enrollments.by_health.select{|en| en.renewing_waived?} }
let(:dental_renewals) { family.active_household.hbx_enrollments.renewing.by_dental }
it 'does renew health coverage and waive dental coverage' do
expect(health_renewals.size).to eq 1
expect(dental_renewals.size).to eq 1
expect(dental_renewals[0].product).to eq enrollment_6.product.renewal_product
end
end
context 'renewing employee D' do
before do
renewal_benefit_package.renew_member_benefit(census_employees[3])
family.reload
end
let(:family) { employee_D.person.primary_family }
let(:passive_renewals) { family.active_household.hbx_enrollments.renewing }
let(:health_waivers) { family.active_household.hbx_enrollments.by_health.select{|en| en.renewing_waived?} }
let(:dental_waivers) { family.active_household.hbx_enrollments.by_dental.select{|en| en.renewing_waived?} }
it 'does renew health coverage and waive dental coverage' do
expect(passive_renewals).to be_empty
expect(health_waivers.size).to eq 1
expect(dental_waivers.size).to eq 1
end
end
context 'renewing employee E' do
before do
renewal_benefit_package.renew_member_benefit(census_employees[4])
family.reload
end
let(:family) { employee_E.person.primary_family }
let(:passive_renewals) { family.active_household.hbx_enrollments.renewing }
let(:passive_waivers) { family.active_household.hbx_enrollments.select{|en| en.renewing_waived?} }
it 'does renew health coverage and waive dental coverage' do
expect(passive_renewals).to be_empty
expect(passive_waivers).to be_empty
end
end
def create_person(ce, employer_profile)
person = FactoryGirl.create(:person, last_name: ce.last_name, first_name: ce.first_name)
employee_role = FactoryGirl.create(:employee_role, person: person, census_employee: ce, employer_profile: employer_profile)
ce.update_attributes!({employee_role_id: employee_role.id})
Family.find_or_build_from_employee_role(employee_role)
employee_role
end
def create_enrollment(family: nil, benefit_group_assignment: nil, employee_role: nil, status: 'coverage_selected', submitted_at: nil, enrollment_kind: 'open_enrollment', effective_date: nil, coverage_kind: 'health')
benefit_package = benefit_group_assignment.benefit_package
sponsored_benefit = benefit_package.sponsored_benefit_for(coverage_kind.to_sym)
FactoryGirl.create(:hbx_enrollment,:with_enrollment_members,
enrollment_members: [family.primary_applicant],
household: family.active_household,
coverage_kind: coverage_kind,
effective_on: benefit_package.start_on,
enrollment_kind: enrollment_kind,
kind: "employer_sponsored",
submitted_at: submitted_at,
employee_role_id: employee_role.id,
benefit_sponsorship: benefit_package.benefit_sponsorship,
sponsored_benefit_package: benefit_package,
sponsored_benefit: sponsored_benefit,
benefit_group_assignment_id: benefit_group_assignment.id,
product: sponsored_benefit.reference_product,
aasm_state: status
)
end
end
end
end
end
| 44.808262 | 296 | 0.6889 |
f8f1a04ecc2fe85720635441ca3dd8f577aa2e4a | 13,088 | class InitSchema < ActiveRecord::Migration[5.1]
def up
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
enable_extension "uuid-ossp"
enable_extension "fuzzystrmatch"
enable_extension "pg_trgm"
create_table "aid_stations", id: :serial, force: :cascade do |t|
t.integer "event_id"
t.integer "split_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "open_time"
t.datetime "close_time"
t.integer "status"
t.string "captain_name"
t.string "comms_crew_names"
t.string "comms_frequencies"
t.string "current_issues"
t.index ["event_id"], name: "index_aid_stations_on_event_id"
t.index ["split_id"], name: "index_aid_stations_on_split_id"
end
create_table "courses", id: :serial, force: :cascade do |t|
t.string "name", limit: 64, null: false
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "created_by"
t.integer "updated_by"
t.datetime "next_start_time"
t.string "slug", null: false
t.index ["slug"], name: "index_courses_on_slug", unique: true
end
create_table "efforts", id: :serial, force: :cascade do |t|
t.integer "event_id", null: false
t.integer "person_id"
t.string "wave"
t.integer "bib_number"
t.string "city", limit: 64
t.string "state_code", limit: 64
t.integer "age"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "created_by"
t.integer "updated_by"
t.string "first_name"
t.string "last_name"
t.integer "gender"
t.string "country_code", limit: 2
t.date "birthdate"
t.integer "data_status"
t.integer "start_offset", default: 0, null: false
t.integer "dropped_split_id"
t.string "beacon_url"
t.string "report_url"
t.integer "dropped_lap"
t.string "phone", limit: 15
t.string "email"
t.string "slug", null: false
t.boolean "checked_in", default: false
t.string "photo_file_name"
t.string "photo_content_type"
t.integer "photo_file_size"
t.datetime "photo_updated_at"
t.index ["event_id"], name: "index_efforts_on_event_id"
t.index ["person_id"], name: "index_efforts_on_person_id"
t.index ["slug"], name: "index_efforts_on_slug", unique: true
end
create_table "event_groups", id: :serial, force: :cascade do |t|
t.string "name"
t.integer "organization_id"
t.boolean "available_live", default: false
t.boolean "auto_live_times", default: false
t.boolean "concealed", default: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "created_by"
t.integer "updated_by"
t.string "slug"
t.index ["organization_id"], name: "index_event_groups_on_organization_id"
t.index ["slug"], name: "index_event_groups_on_slug", unique: true
end
create_table "events", id: :serial, force: :cascade do |t|
t.integer "course_id", null: false
t.integer "organization_id"
t.string "name", limit: 64, null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "created_by"
t.integer "updated_by"
t.datetime "start_time"
t.boolean "concealed", default: false
t.boolean "available_live", default: false
t.string "beacon_url"
t.integer "laps_required"
t.uuid "staging_id", default: -> { "uuid_generate_v4()" }
t.string "slug", null: false
t.boolean "auto_live_times", default: false
t.string "home_time_zone", null: false
t.integer "event_group_id"
t.string "short_name"
t.index ["course_id"], name: "index_events_on_course_id"
t.index ["event_group_id"], name: "index_events_on_event_group_id"
t.index ["organization_id"], name: "index_events_on_organization_id"
t.index ["slug"], name: "index_events_on_slug", unique: true
t.index ["staging_id"], name: "index_events_on_staging_id", unique: true
end
create_table "live_times", id: :serial, force: :cascade do |t|
t.integer "event_id", null: false
t.integer "split_id", null: false
t.string "wave"
t.string "bib_number", null: false
t.datetime "absolute_time"
t.boolean "with_pacer"
t.boolean "stopped_here"
t.string "remarks"
t.string "batch"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "created_by"
t.integer "updated_by"
t.integer "split_time_id"
t.integer "bitkey", null: false
t.string "source", null: false
t.integer "pulled_by"
t.datetime "pulled_at"
t.string "entered_time"
t.index ["event_id"], name: "index_live_times_on_event_id"
t.index ["split_id"], name: "index_live_times_on_split_id"
t.index ["split_time_id"], name: "index_live_times_on_split_time_id"
end
create_table "locations", id: :serial, force: :cascade do |t|
t.string "name", limit: 64, null: false
t.text "description"
t.float "elevation"
t.decimal "latitude", precision: 9, scale: 6
t.decimal "longitude", precision: 9, scale: 6
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "created_by"
t.integer "updated_by"
end
create_table "organizations", id: :serial, force: :cascade do |t|
t.string "name", limit: 64, null: false
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "created_by"
t.integer "updated_by"
t.boolean "concealed", default: false
t.string "slug", null: false
t.index ["slug"], name: "index_organizations_on_slug", unique: true
end
create_table "partners", id: :serial, force: :cascade do |t|
t.integer "event_id", null: false
t.string "banner_link"
t.integer "weight", default: 1, null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "banner_file_name"
t.string "banner_content_type"
t.integer "banner_file_size"
t.datetime "banner_updated_at"
t.string "name", null: false
t.index ["event_id"], name: "index_partners_on_event_id"
end
create_table "people", id: :serial, force: :cascade do |t|
t.string "first_name", limit: 32, null: false
t.string "last_name", limit: 64, null: false
t.integer "gender", null: false
t.date "birthdate"
t.string "city"
t.string "state_code"
t.string "email"
t.string "phone"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "created_by"
t.integer "updated_by"
t.string "country_code", limit: 2
t.integer "user_id"
t.boolean "concealed", default: false
t.string "slug", null: false
t.string "topic_resource_key"
t.string "photo_file_name"
t.string "photo_content_type"
t.integer "photo_file_size"
t.datetime "photo_updated_at"
t.index ["slug"], name: "index_people_on_slug", unique: true
t.index ["topic_resource_key"], name: "index_people_on_topic_resource_key", unique: true
t.index ["user_id"], name: "index_people_on_user_id"
end
create_table "split_times", id: :serial, force: :cascade do |t|
t.integer "effort_id", null: false
t.integer "split_id", null: false
t.float "time_from_start", null: false
t.integer "data_status"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "created_by"
t.integer "updated_by"
t.integer "sub_split_bitkey"
t.boolean "pacer"
t.string "remarks"
t.integer "lap"
t.boolean "stopped_here", default: false
t.index ["effort_id", "lap", "split_id", "sub_split_bitkey"], name: "index_split_times_on_effort_id_and_time_point", unique: true
t.index ["effort_id"], name: "index_split_times_on_effort_id"
t.index ["split_id"], name: "index_split_times_on_split_id"
t.index ["sub_split_bitkey"], name: "index_split_times_on_sub_split_bitkey"
end
create_table "splits", id: :serial, force: :cascade do |t|
t.integer "course_id", null: false
t.integer "location_id"
t.integer "distance_from_start", null: false
t.float "vert_gain_from_start"
t.float "vert_loss_from_start"
t.integer "kind", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "created_by"
t.integer "updated_by"
t.string "description"
t.string "base_name"
t.integer "sub_split_bitmap", default: 1
t.decimal "latitude", precision: 9, scale: 6
t.decimal "longitude", precision: 9, scale: 6
t.float "elevation"
t.string "slug", null: false
t.index ["course_id"], name: "index_splits_on_course_id"
t.index ["location_id"], name: "index_splits_on_location_id"
t.index ["slug"], name: "index_splits_on_slug", unique: true
end
create_table "stewardships", id: :serial, force: :cascade do |t|
t.integer "user_id", null: false
t.integer "organization_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "level", default: 0
t.index ["organization_id"], name: "index_stewardships_on_organization_id"
t.index ["user_id", "organization_id"], name: "index_stewardships_on_user_id_and_organization_id", unique: true
t.index ["user_id"], name: "index_stewardships_on_user_id"
end
create_table "subscriptions", id: :serial, force: :cascade do |t|
t.integer "user_id", null: false
t.integer "person_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "protocol", default: 0, null: false
t.string "resource_key"
t.index ["person_id"], name: "index_subscriptions_on_person_id"
t.index ["resource_key"], name: "index_subscriptions_on_resource_key", unique: true
t.index ["user_id", "person_id", "protocol"], name: "index_subscriptions_on_user_id_and_person_id_and_protocol", unique: true
t.index ["user_id"], name: "index_subscriptions_on_user_id"
end
create_table "users", id: :serial, force: :cascade do |t|
t.string "first_name", limit: 32, null: false
t.string "last_name", limit: 64, null: false
t.integer "role"
t.string "provider"
t.string "uid"
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "unconfirmed_email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "pref_distance_unit", default: 0, null: false
t.integer "pref_elevation_unit", default: 0, null: false
t.string "slug", null: false
t.string "phone"
t.string "http_endpoint"
t.string "https_endpoint"
t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
t.index ["slug"], name: "index_users_on_slug", unique: true
end
add_foreign_key "aid_stations", "events"
add_foreign_key "aid_stations", "splits"
add_foreign_key "efforts", "events"
add_foreign_key "efforts", "people"
add_foreign_key "event_groups", "organizations"
add_foreign_key "events", "courses"
add_foreign_key "events", "event_groups"
add_foreign_key "events", "organizations"
add_foreign_key "live_times", "events"
add_foreign_key "live_times", "split_times"
add_foreign_key "live_times", "splits"
add_foreign_key "partners", "events"
add_foreign_key "people", "users"
add_foreign_key "split_times", "efforts"
add_foreign_key "split_times", "splits"
add_foreign_key "splits", "courses"
add_foreign_key "splits", "locations"
add_foreign_key "stewardships", "organizations"
add_foreign_key "stewardships", "users"
add_foreign_key "subscriptions", "people"
add_foreign_key "subscriptions", "users"
end
def down
raise ActiveRecord::IrreversibleMigration, "The initial migration is not revertable"
end
end
| 41.417722 | 135 | 0.66412 |
bffffd24e7f53382d79b11d593d9d1dab5cab94e | 225 | require "vagrant"
module VagrantPlugins
module Terraform
module Errors
class VagrantTerraformError < Vagrant::Errors::VagrantError
error_namespace("vagrant_terraform.errors")
end
end
end
end
| 17.307692 | 65 | 0.72 |
4ae7f1dddab543e8cdc35a581434845b9f6e4693 | 207 | require "rake/testtask"
desc "Test"
Rake::TestTask.new(:test) do |t|
# t.libs << "tests"
# t.libs << "lib"
t.warning = false
t.test_files = FileList[File.expand_path("./**/tests/**/*.test.rb")]
end
| 20.7 | 70 | 0.618357 |
e963e90f538d901a8834c2e51fe2bf56c8b01012 | 5,565 | require 'fabricio/models/organization'
require 'fabricio/services/organization_service'
require 'fabricio/services/app_service'
require 'fabricio/services/build_service'
require 'fabricio/services/version_service'
require 'fabricio/authorization/authorization_client'
require 'fabricio/authorization/session'
require 'fabricio/authorization/memory_session_storage'
require 'fabricio/authorization/memory_param_storage'
require 'fabricio/networking/network_client'
module Fabricio
# The main object of the gem. It's used to initiate all data requests.
class Client
# Default values for initialization parameters
# clientId and clientSecret are taken from Android application.
DEFAULT_CLIENT_ID = '2c18f8a77609ee6bbac9e53f3768fedc45fb96be0dbcb41defa706dc57d9c931'
DEFAULT_CLIENT_SECRET = '092ed1cdde336647b13d44178932cba10911577faf0eda894896188a7d900cc9'
DEFAULT_USERNAME = nil
DEFAULT_PASSWORD = nil
# In-memory session storage is used by default
DEFAULT_SESSION_STORAGE = Fabricio::Authorization::MemorySessionStorage.new
DEFAULT_PARAM_STORAGE = Fabricio::Authorization::MemoryParamStorage.new
attr_accessor :client_id, :client_secret, :username, :password, :session_storage, :param_storage;
# Default initialize options
def default_options
{
:client_id => DEFAULT_CLIENT_ID,
:client_secret => DEFAULT_CLIENT_SECRET,
:username => DEFAULT_USERNAME,
:password => DEFAULT_PASSWORD,
:session_storage => DEFAULT_SESSION_STORAGE,
:param_storage => DEFAULT_PARAM_STORAGE,
:params => {}
}
end
# Initializes a new Client object. You can use a block to fill all the options:
# client = Fabricio::Client.new do |config|
# config.username = '[email protected]'
# config.password = 'pa$$word'
# end
#
# After initializing you can query this client to get data:
# client.app.all
# client.app.active_now('app_id')
#
# @param options [Hash] Hash containing customizable options
# @option options [String] :client_id Client identifier. You can take it from the 'Organization' section in Fabric.io settings.
# @option options [String] :client_secret Client secret key. You can take it from the 'Organization' section in Fabric.io settings.
# @option options [String] :username Your Fabric.io username
# @option options [String] :password Your Fabric.io password
# @option options [Fabricio::Authorization::AbstractSessionStorage] :session_storage Your custom AbstractSessionStorage subclass that provides its own logic of storing session data.
# @option options [Fabricio::Authorization::AbstractParamStorage] :param_storage Your custom AbstractParamStorage subclass that provides its own logic of storing params.
# @option options [Hash] Default params
# @return [Fabricio::Client]
def initialize(options = default_options)
options.each { |key, value| instance_variable_set("@#{key}", value) }
yield(self) if block_given?
@auth_client = Fabricio::Authorization::AuthorizationClient.new
raise StandardError.new("Session is empty: #{auth_data}") if obtain_session.nil?
network_client = Fabricio::Networking::NetworkClient.new(@auth_client, @session_storage)
@organization_service ||= Fabricio::Service::OrganizationService.new(param_storage, network_client)
@app_service ||= Fabricio::Service::AppService.new(param_storage, network_client)
@build_service ||= Fabricio::Service::BuildService.new(param_storage, network_client)
@version_service ||= Fabricio::Service::VersionService.new(param_storage, network_client)
param_storage.store(options[:params]) unless options[:params].empty?
fill_default_params
end
# We use `method_missing` approach instead of explicit methods.
# Generally, look at the initialized services and use the first part of their names as a method.
# app_service -> client.app
#
# # @raise [NoMethodError] Error raised when unsupported method is called.
def method_missing(*args)
service = instance_variable_get("@#{args.first}_service")
return service if service
raise NoMethodError.new("There's no method called #{args.first} here -- please try again.", args.first)
end
private
# Obtains current session. If there is no cached session, it sends a request to OAuth API to get access and refresh tokens.
#
# @return [Fabricio::Authorization::Session]
def obtain_session
session = @session_storage.obtain_session
if session.nil?
session = @auth_client.auth(@username,
@password,
@client_id,
@client_secret)
@session_storage.store_session(session)
end
session
end
# Obtain organizations and apps and save as default if is only one
def fill_default_params
fill_organization
fill_app
end
# Obtain organizations and save as default if is only one
def fill_organization
if @param_storage.organization_id == nil
organizations = @organization_service.all
@param_storage.store_organization_id(organizations[0].id) if organizations.count == 1
end
end
# Obtain apps and save as default if is only one
def fill_app
if @param_storage.app_id == nil
apps = @app_service.all
@param_storage.store_app_id(apps[0].id) if apps.count == 1
end
end
end
end
| 43.139535 | 185 | 0.716262 |
085b21d34510296032f1b7c18343f853a0df68c3 | 37 | class Refine
VERSION = "0.3.4"
end
| 9.25 | 19 | 0.648649 |
1c69d48c48c7cdacef32c7dda7b9ce4558b07a3b | 10,686 | # frozen_string_literal: true
module Hyrax
class FileSetPresenter
include TitlePresenter
include CitableLinkPresenter
include EmbedCodePresenter
include OpenUrlPresenter
include ModelProxy
include PresentsAttributes
include CharacterizationBehavior
include WithEvents
include FeaturedRepresentatives::FileSetPresenter
include TombstonePresenter
include Rails.application.routes.url_helpers
include ActionView::Helpers::TagHelper
attr_accessor :solr_document, :current_ability, :request, :monograph_presenter, :file_set
# @param [SolrDocument] solr_document
# @param [Ability] current_ability
# @param [ActionDispatch::Request] request the http request context
def initialize(solr_document, current_ability, request = nil)
@solr_document = solr_document
@current_ability = current_ability
@request = request
end
# CurationConcern methods
delegate :stringify_keys, :human_readable_type, :collection?, :image?, :video?, :eps?,
:audio?, :pdf?, :office_document?, :representative_id, :to_s, to: :solr_document
# Methods used by blacklight helpers
delegate :has?, :first, :fetch, to: :solr_document
# Metadata Methods
delegate :resource_type, :caption, :alt_text, :description, :copyright_holder,
:content_type, :creator, :creator_full_name, :contributor, :date_created,
:keywords, :publisher, :language, :date_uploaded,
:rights_statement, :license, :embargo_release_date, :lease_expiration_date, :depositor, :tags,
:title_or_label, :section_title,
:allow_download, :allow_hi_res, :copyright_status, :rights_granted,
:exclusive_to_platform, :identifier, :permissions_expiration_date,
:allow_display_after_expiration, :allow_download_after_expiration, :credit_line,
:holding_contact, :external_resource_url, :primary_creator_role,
:display_date, :sort_date, :transcript, :translation, :file_format,
:label, :redirect_to, :has_model, :date_modified, :visibility,
:closed_captions, :visual_descriptions,
to: :solr_document
def monograph_id
Array(solr_document['monograph_id_ssim']).first
end
def parent
@parent_presenter ||= fetch_parent_presenter
end
def subjects
parent.subject
end
def previous_id?
parent.previous_file_sets_id? id
end
def previous_id
parent.previous_file_sets_id id
end
def next_id?
parent.next_file_sets_id? id
end
def next_id
parent.next_file_sets_id id
end
def link_name
current_ability.can?(:read, id) ? Array(solr_document['label_tesim']).first : 'File'
end
def multimedia?
# currently just need this for COUNTER reports
audio? || video? || image? || eps?
end
def external_resource?
external_resource_url.present?
end
def tombstone?
Sighrax.from_presenter(self).tombstone?
end
def allow_high_res_display?
if tombstone?
allow_display_after_expiration&.downcase == 'high-res'
else
allow_hi_res&.downcase == 'yes'
end
end
# Technical Metadata
def width
solr_document['width_is']
end
def height
solr_document['height_is']
end
def interactive_map?
/^interactive map$/i.match?(resource_type.first)
end
def mime_type
solr_document['mime_type_ssi']
end
def file_size
solr_document['file_size_lts']
end
def last_modified
solr_document['date_modified_dtsi']
end
def original_checksum
solr_document['original_checksum_ssim']
end
def browser_cache_breaker
# using the Solr doc's timestamp even though it'll change on any metadata update.
# More file-specific fields on the Solr doc can't be trusted to be ordered in a useful way on "reversioning".
# An alternative could be to pull the timestamp from the Hydra Derivatives thumbnail itself, for files that...
# actually get one, of course.
# Since we already have the FileSet solr doc, using the solr timestamp seems fine.
# In CommonWorkPresenter#cache_buster_id we use the thumbnail method since we don't have the representative solr doc.
return Time.parse(solr_document['timestamp']).to_i.to_s if solr_document['timestamp'].present?
""
end
def sample_rate
solr_document['sample_rate_ssim']
end
def duration
solr_document['duration_ssim']
end
def original_name
solr_document['original_name_tesim']
end
def file_set
@file_set ||= ::FileSet.find(id)
end
def file
# Get the original file from Fedora
file = file_set&.original_file
raise "FileSet #{id} original file is nil." if file.nil?
file
end
def extracted_text_file
file_set&.extracted_text
end
def extracted_text?
# TODO: remove this line when we have some extracted text in place that's worth offering for download...
# and/or a disclaimer as outlined in https://github.com/mlibrary/heliotrope/issues/1429
return false if Rails.env.eql?('production')
extracted_text_file&.size&.positive?
end
def thumbnail_path
solr_document['thumbnail_path_ss']
end
def using_default_thumbnail?
thumbnail_path.start_with?('/assets/')
end
def gylphicon
tag.span class: glyphicon_type + " file-set-glyphicon", "aria-label": alt_text&.first || ""
end
def glyphicon_type
return 'glyphicon glyphicon-file' if resource_type.blank?
glyphicon_by_resource_type
end
def glyphicon_by_resource_type
case resource_type.first.downcase
when 'text'
'glyphicon glyphicon-file'
when 'image'
'glyphicon glyphicon-picture'
when 'video'
'glyphicon glyphicon-film'
when 'audio'
'glyphicon glyphicon-volume-up'
when 'map', 'interactive map'
'glyphicon glyphicon-map-marker'
else
'glyphicon glyphicon-file'
end
end
def use_riiif_for_icon?
# sidestep hydra-derivatives and use riiif for FileSet icons
eps?
end
def use_glyphicon?
# If the thumbnail_path in Solr points to the assets directory, it is using a Hyrax default.
# aside: Much of the thumbnail behavior can be examined by reading this page and its links to Hyrax code:
# https://github.com/samvera/hyrax/wiki/How-Thumbnails-Get-rendered
# Anyway, this default (set with a call to ActionController::Base.helpers.image_path) can't be styled per...
# publisher so instead we'll use resource-type-specific glyphicons in "publisher branding" colors
mime_type.blank? || external_resource? || using_default_thumbnail?
end
def center_caption?
# when using the default thumbnail view (or glyphicon) both this and the download button are centered.
# The caption lies between these. It looks very weird if it's left-aligned, especially if it's short.
!image? && !video? && !audio? && !external_resource?
end
def download_button_label
extension = File.extname(label).delete('.').upcase if label.present?
download_label = extension == 'PDF' ? 'View' : 'Download'
size = ActiveSupport::NumberHelper.number_to_human_size(file_size) if file_size.present?
download_label += ' ' + extension if extension.present?
download_label += ' (' + size + ')' if size.present?
download_label
end
def extracted_text_download_button_label
'Download TXT (' + ActiveSupport::NumberHelper.number_to_human_size(extracted_text_file.size) + ')'
end
def extracted_text_download_filename
File.basename(label, '.*') + '.txt'
end
def heliotrope_media_partial(directory = 'media_display') # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
# we've diverged from the media_display_partial stuff in Hyrax, so check our asset-page partials here
partial = 'hyrax/file_sets/' + directory + '/'
partial + if external_resource?
'external_resource'
# this needs to come before `elsif image?` as these are also images
# less than 430 or so px wide means a "responsive" iframe with a 5:3 ratio will not fit a Leaflet...
# map with enough height for a single 256x256px tile. But actually it might make more sense to have...
# < 540 here as that's the width of the Leaflet map on the FileSet show page
elsif animated_gif? || (image? && width.present? && width < 450)
'static_image'
elsif image?
'leaflet_image'
elsif video?
'video'
elsif audio?
'audio'
elsif epub?
'epub'
elsif eps?
'image_service'
elsif interactive_map?
'interactive_map'
else
'default'
end
end
# Hyrax 2.x update, needed for the monograph show page
# Which we're probably getting rid of anyway, but... well whatever
def user_can_perform_any_action?
current_ability.can?(:edit, id) || current_ability.can?(:destroy, id) || current_ability.can?(:download, id)
end
# Score file_sets things, see HELIO-2912 and the FileSetIndexer
def score_version
solr_document['score_version_tesim']
end
# Returns true if the MIME type is image, or if MIME type is not available,
# if the file extension is a known image type.
def probable_image?
return true if mime_type&.start_with?('image/')
return false if label.nil?
%w[.bmp .gif .jp2 .jpeg .jpg .png .tif .tiff].member?(File.extname(label).downcase)
end
def animated_gif?
solr_document['animated_gif_bsi'] == true
end
private
def fetch_parent_presenter
@parent_document ||= ActiveFedora::SolrService.query("{!field f=member_ids_ssim}#{id}", rows: 1).first
return nil if @parent_document.blank?
case @parent_document["has_model_ssim"].first
when "Monograph"
Hyrax::MonographPresenter.new(::SolrDocument.new(@parent_document), current_ability)
when "Score"
Hyrax::ScorePresenter.new(::SolrDocument.new(@parent_document), current_ability)
else
WorkShowPresenter.new(::SolrDocument.new(@parent_document), current_ability)
end
end
end
end
| 33.709779 | 137 | 0.667509 |
e853b52c5376ace80812fb0dddd7cbd61529cd76 | 3,690 | RSpec.describe Sisense::API::Client do
SUPPORTED_HTTP_VERBS = %i[get post put patch delete].freeze
context 'constants' do
describe 'VERB_MAP' do
it('is defined') { expect(described_class.const_defined?('VERB_MAP')).to eq true }
it { expect(described_class::VERB_MAP.keys).to match_array(SUPPORTED_HTTP_VERBS) }
end
end
describe '#initialize' do
it 'defines http client instance' do
expect(subject.http).to be_a Net::HTTP
end
end
shared_examples 'a request made over http' do
let(:stubbed_request) { stub_request(method_used, "http://test-sisense.chronogolf.ca#{endpoint}") }
before do
stubbed_request
request
end
it { expect(stubbed_request).to have_been_requested }
end
context 'requests' do
let(:endpoint) { '/test-endpoint' }
SUPPORTED_HTTP_VERBS.each do |method|
describe "using `#{method.upcase}` method" do
it_behaves_like 'a request made over http' do
let(:method_used) { method }
let(:request) { subject.send(method_used, endpoint) }
end
end
end
end
describe '#parsed_response' do
context 'when response is single object' do
around { |test| VCR.use_cassette('user_retrieve') { test.run } }
let(:response) { subject.get('/api/v1/users/5b3293ad1ed43bccb04e2029') }
let(:object_class) { Sisense::User }
let(:parsed_response) { subject.parsed_response(response, object_class: object_class) }
it { expect(parsed_response).to be_a(object_class) }
end
context 'when response is collection' do
around { |test| VCR.use_cassette('users_list') { test.run } }
let(:response_collection) { subject.get('/api/v1/users') }
let(:object_class) { Sisense::User }
let(:parsed_response) { subject.parsed_response(response_collection, object_class: object_class) }
it { expect(parsed_response).to be_a(Array) }
it 'converts all response items as the expect object' do
expect(parsed_response.all? { |item| item.is_a?(object_class) }).to eq true
end
end
end
describe 'errors' do
context 'when get 404' do
around { |test| VCR.use_cassette('user_retrieve_404') { test.run } }
it 'raises' do
expect { subject.get('/api/v1/users/5b3293ad1ed43bccb04e2029') }.to raise_error Sisense::API::NotFoundError
end
end
context 'when get 422' do
around { |test| VCR.use_cassette('user_retrieve_422') { test.run } }
it 'raises' do
expect { subject.get('/api/v1/users/5b3293ad1ed43bccb04e2029') }.to raise_error Sisense::API::UnprocessableEntityError
end
end
context 'when get other error' do
around { |test| VCR.use_cassette('user_retrieve_500') { test.run } }
it 'raises' do
expect { subject.get('/api/v1/users/5b3293ad1ed43bccb04e2029') }.to raise_error Sisense::API::Error
end
end
context 'with error details in body in legacy format' do
around { |test| VCR.use_cassette('user_retrieve_500_v0_9') { test.run } }
it 'collects body errors' do
subject.get('/api/v1/users/5b3293ad1ed43bccb04e2029')
rescue Sisense::API::Error => e
expect(e).to have_attributes(code: 'X123', status: 'error', message: 'any server error')
end
end
context 'with error details in body' do
around { |test| VCR.use_cassette('user_retrieve_500') { test.run } }
it 'collects body errors' do
subject.get('/api/v1/users/5b3293ad1ed43bccb04e2029')
rescue Sisense::API::Error => e
expect(e).to have_attributes(code: 'X123', status: 'error', message: 'any server error')
end
end
end
end
| 32.654867 | 126 | 0.664228 |
ed1f3bd21fb776a0225d3a6d31293d44b3298278 | 283 | require 'pushbullet_api/api_handler'
require 'pushbullet_api/version'
require 'pushbullet_api/user'
require 'pushbullet_api/chat'
require 'pushbullet_api/device'
require 'pushbullet_api/push'
require 'pushbullet_api/subscription'
module PushbulletApi
# Your code goes here...
end
| 23.583333 | 37 | 0.823322 |
f8c048563cfb8472f0009bf36018aa66eda83bba | 3,621 | class Ruster::Node
include Ruster::Util
attr :addr
attr :id
attr :flags
attr :master_id
attr :ping_epoch
attr :pong_epoch
attr :config_epoch
attr :state
attr :slots
attr :migrating
attr :importing
attr :friends
def initialize(addr)
@addr = addr
end
def client
@client ||= Redic.new("redis://#{addr}")
end
def call(*args)
res = client.call(*args)
raise res if res.is_a?(RuntimeError)
res
end
def enabled?
parse_info(call("INFO", "cluster"))[:cluster_enabled] == "1"
end
def read_info_line!(info_line)
parts = info_line.split
@id = parts.shift
addr = parts.shift
@flags = parts.shift.split(",")
@addr = addr unless @flags.include?("myself")
@master_id = parts.shift
@ping_epoch = parts.shift.to_i
@pong_epoch = parts.shift.to_i
@config_epoch = parts.shift.to_i
@state = parts.shift
@slots = []
@migrating = {}
@importing = {}
parts.each do |slots|
case slots
when /^(\d+)-(\d+)$/ then @slots << ($1.to_i..$2.to_i)
when /^\d+$/ then @slots << (slots.to_i..slots.to_i)
when /^\[(\d+)-([<>])-([a-z0-9]+)\]$/
case $2
when ">" then @migrating[$1.to_i] = $3
when "<" then @importing[$1.to_i] = $3
end
end
end
end
def all_slots
slots.map(&:to_a).flatten
end
def to_s
"#{addr} [#{id}]"
end
def self.from_info_line(info_line)
_, addr, _ = info_line.split
new(addr).tap { |node| node.read_info_line!(info_line) }
end
def load!
@friends = []
call("CLUSTER", "NODES").split("\n").each do |line|
if line.include?("myself")
read_info_line!(line)
else
@friends << self.class.from_info_line(line)
end
end
end
def meet(ip, port)
call("CLUSTER", "MEET", ip, port)
end
def forget(node)
raise ArgumentError, "Node #{node} is not empty" unless node.slots.empty? and node.migrating.empty? and node.importing.empty?
call("CLUSTER", "FORGET", node.id)
end
def replicate(node)
call("CLUSTER", "REPLICATE", node.id)
end
def slaves
call("CLUSTER", "SLAVES", id).map do |line|
self.class.from_info_line(line)
end
end
def add_slots(*slots)
call("CLUSTER", "ADDSLOTS", *slots)
end
def del_slots(*slots)
call("CLUSTER", "DELSLOTS", *slots)
end
def flush_slots!
call("CLUSTER", "FLUSHSLOTS")
end
def cluster_info
parse_info(call("CLUSTER", "INFO"))
end
def ip
addr.split(":").first
end
def port
addr.split(":").last
end
# In Redis Cluster only DB 0 is enabled
DB0 = 0
def move_slot!(slot, target, options={})
options[:num_keys] ||= 10
options[:timeout] ||= call("CONFIG", "GET", "cluster-node-timeout")
# Tell the target node to import the slot
target.call("CLUSTER", "SETSLOT", slot, "IMPORTING", id)
# Tell the current node to export the slot
call("CLUSTER", "SETSLOT", slot, "MIGRATING", target.id)
# Export keys
done = false
until done
keys = call("CLUSTER", "GETKEYSINSLOT", slot, options[:num_keys])
done = keys.empty?
keys.each do |key|
call("MIGRATE", target.ip, target.port, key, DB0, options[:timeout])
end
# Tell cluster the location of the new slot
call("CLUSTER", "SETSLOT", slot, "NODE", target.id)
friends.each do |node|
node.call("CLUSTER", "SETSLOT", slot, "NODE", target.id)
end
end
end
def empty?
call("DBSIZE") == 0
end
def only_node?
parse_info(call("CLUSTER", "INFO"))[:cluster_known_nodes] == "1"
end
end
| 20.930636 | 129 | 0.599282 |
e84b9073040adb04fdc2e3732a5098d6797502ab | 1,295 | # frozen_string_literal: true
# An abstract class for rest resources
# Rest resources should not be initialized directly. They should be created by methods
# on Varanus
class Varanus::RestResource
# :nodoc:
def initialize varanus
@varanus = varanus
end
private
def check_result result
body = result.body
return unless body.is_a?(Hash)
return if body['code'].nil?
klass = Varanus::Error
if body['code'] == 0 && body['description'] =~ /process/
klass = Varanus::Error::StillProcessing
end
raise klass.new(body['code'], body['description'])
end
def get path, *args
result = @varanus.connection.get(path, *args)
check_result result
result.body
end
# Performs multiple GETs with varying positions to ensure all results are returned.
def get_with_size_and_position path, opts = {}
size = opts[:size] || 200
position = opts[:position] || 0
results = []
loop do
params = { size: size, position: position }.merge(opts)
new_results = get(path, params)
results += new_results
break if new_results.length < size
position += size
end
results
end
def post path, *args
result = @varanus.connection.post(path, *args)
check_result result
result.body
end
end
| 22.719298 | 87 | 0.666409 |
d525990506252d3b9068391729c84904d725d19d | 499 | # frozen_string_literal: true
module TestSites
# Wrapper for files in ./data.
class DataFile
def self.path(data_dir_relative_path)
DataFile.new(data_dir_relative_path).to_s
end
def initialize(filename)
@data_file = File.join(data_dir, filename)
end
def file
@data_file
end
def to_s
file.to_s
end
def data_dir
File.expand_path(
File.join(
__dir__,
'../../data'
)
)
end
end
end
| 15.59375 | 48 | 0.591182 |
e8b5049b08c5bd4aa837d2e8439823538da25a28 | 2,660 | require 'validators/qrda_cat3_validator'
class C2Task < Task
# C2 = Import and Calculate
# - Ability to Import Cat 1
# - Calculate every CQM
# - (implied) ability to export cat 3 (in order to be able to prove it)
#
# Also, if the parent product test includes a C3 Task,
# do that validation here
def validators
@validators = if product_test.c2_test
[::Validators::QrdaCat3Validator.new(product_test.expected_results,
false,
product_test.c3_test,
true,
product_test.bundle),
::Validators::ExpectedResultsValidator.new(product_test.expected_results)]
else
# A C2 task is created whenever C3 is selected. If C2 isn't also selected, this task doesn't perform any validations
[]
end
@validators
end
def execute(file, user)
te = test_executions.new(expected_results: expected_results, artifact: Artifact.new(file: file), user_id: user)
te.save!
TestExecutionJob.perform_later(te, self)
te.sibling_execution_id = product_test.tasks.c3_cat3_task.execute(file, user, te.id).id if product_test.c3_cat3_task?
te.save
te
end
def good_results
# Set the Submission Program to MIPS_INDIV if there is a C3 test and the test is for an ep measure.
cat3_submission_program = if product_test&.product&.c3_test
product_test&.measures&.first&.reporting_program_type == 'ep' ? 'MIPS_INDIV' : false
else
false
end
options = { provider: product_test.patients.first.providers.first, submission_program: cat3_submission_program,
start_time: start_date, end_time: end_date }
Qrda3R21.new(product_test.expected_results, product_test.measures, options).render
end
def last_updated_with_sibling
sibling = product_test.tasks.c3_cat3_task
return updated_at unless sibling
[updated_at, sibling.updated_at].max
end
# returns combined status including c3_cat3 task
def status_with_sibling
sibling = product_test.tasks.c3_cat3_task
return status unless sibling
return status if status == sibling.status
return 'errored' if errored? || sibling.errored?
return 'incomplete' if incomplete? || sibling.incomplete?
return 'pending' if pending? || sibling.pending?
'failing'
end
end
| 40.30303 | 137 | 0.615789 |
5de9dadcf9bb78ed96192427f0bb64b06e857818 | 6,464 | require "csv"
require "net/http"
require "aws-sdk-s3"
require "geocoder"
desc "Import postcode geolocation data"
task :import_postcode_cleanup do
db = ActiveRecord::Base.connection
db.drop_table :postcode_geolocation_tmp, if_exists: true
db.drop_table :postcode_geolocation_legacy, if_exists: true
puts "[#{Time.now}] Dropped postcode_geolocation_tmp / postcode_geolocation_legacy tables"
db.drop_table :postcode_outcode_geolocations_tmp, if_exists: true
db.drop_table :postcode_outcode_geolocations_legacy, if_exists: true
puts "[#{Time.now}] Dropped postcode_outcode_geolocations_tmp / postcode_outcode_geolocations_legacy tables"
end
task :import_postcode do
check_task_requirements
file_name = ENV["file_name"]
zipped = file_name.end_with?("zip")
file_io = retrieve_file_on_s3(file_name)
if zipped
Zip::InputStream.open(file_io) do |csv_io|
while (entry = csv_io.get_next_entry)
next unless entry.size.positive?
puts "[#{Time.now}] #{entry.name} was unzipped with a size of #{entry.size} bytes"
postcode_csv = CSV.new(csv_io, headers: true)
process_postcode_csv(postcode_csv)
end
end
else
puts "[#{Time.now}] Reading postcodes CSV file: #{ENV['file_name']}"
postcode_csv = CSV.new(file_io, headers: true)
process_postcode_csv(postcode_csv)
end
end
def check_task_requirements
if ENV["bucket_name"].nil? && ENV["instance_name"].nil?
abort("Please set the bucket_name or instance_name environment variable")
end
if ENV["file_name"].nil?
abort("Please set the file_name environment variable")
end
end
def retrieve_file_on_s3(file_name)
storage_config_reader = Gateway::StorageConfigurationReader.new(
bucket_name: ENV["bucket_name"],
instance_name: ENV["instance_name"],
)
storage_gateway = Gateway::StorageGateway.new(storage_config: storage_config_reader.get_configuration)
puts "[#{Time.now}] Retrieving from S3 file: #{file_name}"
storage_gateway.get_file_io(file_name)
end
def process_postcode_csv(postcode_csv, buffer_size = 10_000)
create_postcode_table
postcode_geolocation_buffer = []
outcodes = {}
row_number = 1
while (row = postcode_csv.shift)
postcode = row["pcd"]
lat = row["lat"]
long = row["long"]
region = get_region_codes[row["eer"].to_sym]
# Only considers England, NI and Wales
next if region.nil?
postcode = postcode.insert(-4, " ") if postcode[-4] != " "
new_outcode = postcode.split(" ")[0]
db = ActiveRecord::Base.connection
postcode_geolocation_buffer << [db.quote(postcode), lat, long, db.quote(region)].join(", ")
add_outcode(outcodes, new_outcode, lat, long, region)
if row_number % buffer_size == 0
insert_postcode_batch(postcode_geolocation_buffer)
postcode_geolocation_buffer.clear
end
row_number += 1
end
# Insert and clear remaining postcode buffer
unless postcode_geolocation_buffer.empty?
insert_postcode_batch(postcode_geolocation_buffer)
postcode_geolocation_buffer.clear
end
puts "[#{Time.now}] Inserted #{row_number} postcodes"
create_outcode_table
unless outcodes.empty?
insert_outcodes(outcodes)
puts "[#{Time.now}] Inserted #{outcodes.length} outcodes"
end
switch_postcode_table
switch_outcode_table
puts "[#{Time.now}] Postcode import completed"
end
def create_postcode_table
db = ActiveRecord::Base.connection
unless db.table_exists?(:postcode_geolocation_tmp)
db.create_table :postcode_geolocation_tmp, primary_key: :postcode, id: :string, force: :cascade do |t|
t.decimal :latitude
t.decimal :longitude
t.string :region
end
puts "[#{Time.now}] Created empty postcode_geolocation_tmp table"
end
end
def create_outcode_table
db = ActiveRecord::Base.connection
unless db.table_exists?(:postcode_outcode_geolocations_tmp)
db.create_table :postcode_outcode_geolocations_tmp, primary_key: :outcode, id: :string, force: :cascade do |t|
t.decimal :latitude
t.decimal :longitude
t.string :region
end
puts "[#{Time.now}] Created empty postcode_outcode_geolocations_tmp table"
end
end
def insert_postcode_batch(postcode_buffer)
db = ActiveRecord::Base.connection
batch = postcode_buffer.join("), (")
db.exec_query("INSERT INTO postcode_geolocation_tmp (postcode, latitude, longitude, region) VALUES(" + batch + ")")
end
def add_outcode(outcodes, new_outcode, lat, long, region)
unless outcodes.key?(new_outcode)
outcodes[new_outcode] = {
latitude: [],
longitude: [],
region: [],
}
end
outcodes[new_outcode][:latitude].push(lat.to_f)
outcodes[new_outcode][:longitude].push(long.to_f)
outcodes[new_outcode][:region].push(region)
end
def switch_postcode_table
db = ActiveRecord::Base.connection
db.rename_table :postcode_geolocation, :postcode_geolocation_legacy
puts "[#{Time.now}] Renamed table postcode_geolocation to postcode_geolocation_legacy"
db.rename_table :postcode_geolocation_tmp, :postcode_geolocation
puts "[#{Time.now}] Renamed table postcode_geolocation_tmp to postcode_geolocation"
end
def switch_outcode_table
db = ActiveRecord::Base.connection
db.rename_table :postcode_outcode_geolocations, :postcode_outcode_geolocations_legacy
puts "[#{Time.now}] Renamed table postcode_outcode_geolocations to postcode_outcode_geolocations_legacy"
db.rename_table :postcode_outcode_geolocations_tmp, :postcode_outcode_geolocations
puts "[#{Time.now}] Renamed table postcode_outcode_geolocations_tmp to postcode_outcode_geolocations"
end
def insert_outcodes(outcodes)
db = ActiveRecord::Base.connection
batch = outcodes.map do |outcode, data|
[
db.quote(outcode),
(data[:latitude].reduce(:+) / data[:latitude].size.to_f),
(data[:longitude].reduce(:+) / data[:longitude].size.to_f),
db.quote(data[:region].max_by { |i| data[:region].count(i) }),
].join(", ")
end
db.exec_query("INSERT INTO postcode_outcode_geolocations_tmp (outcode, latitude, longitude, region) VALUES(" + batch.join("), (") + ")")
end
def get_region_codes
{
E15000001: "North East",
E15000002: "North West",
E15000003: "Yorkshire and The Humber",
E15000004: "East Midlands",
E15000005: "West Midlands",
E15000006: "Eastern",
E15000007: "London",
E15000008: "South East",
E15000009: "South West",
N07000001: "Northern Ireland",
W08000001: "Wales",
}
end
| 30.635071 | 138 | 0.733756 |
1d35176ed4496ebb0ad34e3150aee3999d839b2f | 817 | # encoding: UTF-8
# frozen_string_literal: true
module API
module V2
module Management
module Entities
class Market < ::API::V2::Entities::Market
expose(
:position,
documentation: {
type: Integer,
desc: 'Market position.'
}
)
expose(
:created_at,
format_with: :iso8601,
documentation: {
type: String,
desc: 'Market created time in iso8601 format.'
}
)
expose(
:updated_at,
format_with: :iso8601,
documentation: {
type: String,
desc: 'Market updated time in iso8601 format.'
}
)
end
end
end
end
end
| 20.948718 | 60 | 0.4541 |
1a03c5be11abe53d040d9f43f754bf21484bac49 | 887 | module RediSearch
class ReindexBatchesJob < ActiveJob::Base
queue_as { RediSearch.queue_name }
def perform(klass, start, finish, batch_size)
klass = klass.constantize
start = start.to_i
finish = finish.to_i
batch_size = batch_size.to_i
batches_relation = nil
if ActiveRecord::VERSION::STRING >= "5.0"
batches_relation = klass.redisearch_import.find_in_batches(batch_size: batch_size, start: start, finish: finish)
else
batches_relation = klass.redisearch_import.where(klass.arel_table[:id].lteq(finish.to_i)).find_in_batches(batch_size: batch_size, start: start)
end
batches_relation.each do |records|
klass.redisearch_index.client.multi do
records.each do |record|
record.reindex(mode: :inline, replace: true)
end
end
end
end
end
end
| 28.612903 | 151 | 0.668546 |
61d742342063e34e9d7f03597592c9355786ce9a | 2,241 | require 'spec_helper'
describe Coursewareable::ResponsesController do
let(:assignment) { Fabricate('coursewareable/assignment') }
let(:classroom) { assignment.classroom }
let(:lecture) { assignment.lecture }
let(:user) { Fabricate(:confirmed_user) }
describe 'GET new' do
context 'being logged in as a user' do
before do
@controller.send(:auto_login, user)
@request.host = "#{classroom.slug}.#{@request.host}"
get(:new, :lecture_id => lecture.slug,
:assignment_id => assignment.slug, :use_route => :coursewareable)
end
it { should redirect_to(login_path) }
end
end
describe 'POST create' do
context 'being logged in as a user' do
before do
@controller.send(:auto_login, user)
@request.host = "#{classroom.slug}.#{@request.host}"
post(:create, :lecture_id => lecture.slug,
:assignment_id => assignment.slug, :use_route => :coursewareable,
:response => { :content => Faker::HTMLIpsum.body })
end
it { should redirect_to(login_path) }
end
end
describe 'GET show' do
let(:resp) do
Fabricate('coursewareable/response', :classroom => classroom,
:assignment => assignment)
end
context 'being logged in as a user' do
before do
@controller.send(:auto_login, user)
@request.host = "#{classroom.slug}.#{@request.host}"
get(:show, :lecture_id => lecture.slug,
:assignment_id => assignment.slug,
:id => resp.id,
:use_route => :coursewareable)
end
it { should redirect_to(login_path) }
end
end
describe 'DELETE destroy' do
let(:resp) do
Fabricate('coursewareable/response', :classroom => classroom,
:assignment => assignment)
end
context 'being logged in as a user' do
before do
@controller.send(:auto_login, user)
@request.host = "#{classroom.slug}.#{@request.host}"
delete(:destroy, :lecture_id => lecture.slug,
:assignment_id => assignment.slug,
:id => resp.id,
:use_route => :coursewareable)
end
it { should redirect_to(login_path) }
end
end
end
| 28.730769 | 77 | 0.605533 |
1d7f94805a6816010798eb77a2d33f0f1d3fb1d5 | 77 | # frozen_string_literal: true
module CatarseScripts
VERSION = '0.1.0'
end
| 12.833333 | 29 | 0.753247 |
386bf183a1033510382fcdc9c2662eee3c66c23a | 38 | module RAMF
VERSION = "0.0.1.a1"
end | 12.666667 | 22 | 0.657895 |
b998f90429913cfb4c8b830249ceb8107fa9f80e | 3,544 | require "test_helper"
require "fileutils"
require "tempfile"
class Bundleup::CLITest < Minitest::Test
include OutputHelpers
def test_it_works_with_a_sample_project # rubocop:disable Minitest/MultipleAssertions
stdout = within_copy_of_sample_project do
capturing_plain_output(stdin: "n\n") do
with_clean_bundler_env do
Bundleup::CLI.new([]).run
end
end
end
assert_includes(stdout, "Please wait a moment while I upgrade your Gemfile.lock...")
assert_includes(stdout, "The following gems will be updated:")
assert_match(/^mail\s+2\.7\.0\s+→ [\d.]+\s*$/, stdout)
assert_match(/^mocha\s+1\.11\.1\s+→ [\d.]+\s*$/, stdout)
assert_includes(stdout, "Note that the following gems are being held back:")
assert_match(/^rake\s+12\.3\.3\s+→ [\d.]+\s+:\s+pinned at ~> 12\.0\s+# Not ready for 13 yet\s*$/, stdout)
assert_match(/^rubocop\s+0\.89\.0\s+→ [\d.]+\s+:\s+pinned at = 0\.89\.0\s*$/, stdout)
assert_includes(stdout, "Do you want to apply these changes [Yn]?")
assert_includes(stdout, "Your original Gemfile.lock has been restored.")
end
def test_it_passes_args_to_bundle_update
stdout = capturing_plain_output(stdin: "n\n") do
Dir.chdir(File.expand_path("../fixtures/project", __dir__)) do
with_clean_bundler_env do
Bundleup::CLI.new(["--group=development"]).run
end
end
end
assert_includes(stdout, "running: bundle update --group=development")
end
def test_it_displays_usage
stdout = capturing_plain_output do
Bundleup::CLI.new(["-h"]).run
end
assert_includes(stdout, "Usage: bundleup [GEMS...] [OPTIONS]")
end
def test_it_raises_if_gemfile_not_present_in_working_dir
Dir.chdir(__dir__) do
error = assert_raises(Bundleup::CLI::Error) { Bundleup::CLI.new([]).run }
assert_equal("Gemfile and Gemfile.lock must both be present.", error.message)
end
end
def test_update_gemfile_flag # rubocop:disable Minitest/MultipleAssertions
stdout, updated_gemfile = within_copy_of_sample_project do
out = capturing_plain_output(stdin: "y\n") do
with_clean_bundler_env do
Bundleup::CLI.new(["--update-gemfile"]).run
end
end
[out, File.read("Gemfile")]
end
assert_match(/^mail\s+2\.7\.0\s+→ [\d.]+\s*$/, stdout)
assert_match(/^mocha\s+1\.11\.1\s+→ [\d.]+\s*$/, stdout)
assert_match(/^rubocop\s+0\.89\.0\s+→ [\d.]+\s*$/, stdout)
assert_match(/^rake\s+12\.3\.3\s+→ [\d.]+\s+:\s+pinned at ~> 12\.0\s+# Not ready for 13 yet\s*$/, stdout)
assert_includes(stdout, "Do you want to apply these changes [Yn]?")
assert_includes(stdout, "✔ Done!")
assert_includes(updated_gemfile, <<~GEMFILE)
gem "mail"
gem "mocha"
gem "rake", "~> 12.0" # Not ready for 13 yet
GEMFILE
assert_match(/^gem "rubocop", "[.\d]+"$/, updated_gemfile)
refute_match(/^gem "rubocop", "0.89.0"$/, updated_gemfile)
end
private
def with_clean_bundler_env(&block)
if defined?(Bundler)
if Bundler.respond_to?(:with_unbundled_env)
Bundler.with_unbundled_env(&block)
else
Bundler.with_clean_env(&block)
end
else
yield
end
end
def within_copy_of_sample_project(&block)
sample_dir = File.expand_path("../fixtures/project", __dir__)
sample_files = %w[Gemfile Gemfile.lock].map { |file| File.join(sample_dir, file) }
Dir.mktmpdir do |path|
FileUtils.cp(sample_files, path)
Dir.chdir(path, &block)
end
end
end
| 34.407767 | 109 | 0.657167 |
ffc36dbf6e91c4c6c4438ba987c02a986fdc9141 | 5,811 | # encoding: utf-8
#
=begin
-----------------
Benchmark: PostgreSQL 9.x Security Technical Implementation Guide
Status: Accepted
This Security Technical Implementation Guide is published as a tool to improve
the security of Department of Defense (DoD) information systems. The
requirements are derived from the National Institute of Standards and
Technology (NIST) 800-53 and related documents. Comments or proposed revisions
to this document should be sent via email to the following address:
[email protected].
Release Date: 2017-01-20
Version: 1
Publisher: DISA
Source: STIG.DOD.MIL
uri: http://iase.disa.mil
-----------------
=end
PG_LOG_DIR = attribute(
'pg_log_dir',
description: 'define path for the postgreql log directory',
default: '/var/lib/pgsql/9.5/data/pg_log')
PG_OWNER = attribute(
'pg_owner',
description: "The system user of the postgres process",
default: 'postgres'
)
only_if do
command('psql').exist?
end
control "V-72847" do
title "The audit information produced by PostgreSQL must be protected from
unauthorized modification."
desc "If audit data were to become compromised, then competent forensic
analysis and discovery of the true source of potentially malicious system
activity is impossible to achieve. To ensure the veracity of audit data
the information system and/or the application must protect audit information
from unauthorized modification. This requirement can be achieved through
multiple methods that will depend upon system architecture and design. Some
commonly employed methods include ensuring log files enjoy the proper file
system permissions and limiting log data locations. Applications providing
a user interface to audit data will leverage user permissions and roles
identifying the user accessing the data and the corresponding rights that
the user enjoys in order to make access decisions regarding the modification
of audit data. Audit information includes all information (e.g., audit
records, audit settings, and audit reports) needed to successfully audit
information system activity. Modification of database audit data could mask
the theft of, or the unauthorized modification of, sensitive data stored in
the database."
impact 0.5
tag "severity": "medium"
tag "gtitle": "SRG-APP-000119-DB-000060"
tag "gid": "V-72847"
tag "rid": "SV-87499r1_rule"
tag "stig_id": "PGS9-00-000400"
tag "cci": "CCI-000163"
tag "nist": ["AU-9", "Rev_4"]
tag "check": "Review locations of audit logs, both internal to the database
and database audit logs located at the operating system level. Verify there
are appropriate controls and permissions to protect the audit information from
unauthorized modification.
Note: The following instructions use the PGDATA environment variable. See
supplementary content APPENDIX-F for instructions on configuring PGDATA.
#### stderr Logging If the PostgreSQL server is configured to use stderr for
logging, the logs will be owned by the database owner (usually postgres user)
with a default permissions level of 0600. The permissions can be configured in
postgresql.conf.
To check the permissions for log files in postgresql.conf, as the database
owner (shown here as \"postgres\"), run the following command:
$ sudo su - postgres
$ grep \"log_file_mode\" ${PGDATA?}/postgresql.conf
If the permissions are not 0600, this is a finding.
Next, navigate to where the logs are stored. This can be found by running the
following command against postgresql.conf as the database owner (shown here as
\"postgres\"):
$ sudo su - postgres
$ grep \"log_directory\" ${PGDATA?}/postgresql.conf
With the log directory identified, as the database owner (shown here as
\"postgres\"),
list the permissions of the logs:
$ sudo su - postgres
$ ls -la ${PGDATA?}/pg_log
If logs are not owned by the database owner (shown here as \"postgres\") and
are not the same permissions as configured in postgresql.conf, this is a
finding.
#### syslog Logging
If the PostgreSQL server is configured to use syslog for logging, consult
the organizations syslog setting for permissions and ownership of logs."
tag "fix": "To ensure that logging is enabled, review supplementary content
APPENDIX-C for instructions on enabling logging. Note: The following
instructions use the PGDATA environment variable. See supplementary content
APPENDIX-F for instructions on configuring PGDATA.
#### stderr Logging
With stderr logging enabled, as the database owner (shown here as
\"postgres\"), set the following parameter in postgresql.conf:
$ vi ${PGDATA?}/postgresql.conf
log_file_mode = 0600
To change the owner and permissions of the log files, run the following:
$ chown postgres:postgres ${PGDATA?}/<log directory name>
$ chmod 0700 ${PGDATA?}/<log directory name>
$ chmod 600 ${PGDATA?}/<log directory name>/*.log
#### syslog Logging
If PostgreSQL is configured to use syslog for logging, the log files must be
configured to be owned by root with 0600 permissions.
$ chown root:root <log directory name>/<log_filename>
$ chmod 0700 <log directory name>
$ chmod 0600 <log directory name>/*.log"
# @todo also need to test that error logging is enabled (where?) or test if log
# outputs to stderr? the pg_log directory should be 0700.
# @todo we need to decide how we are going to test for error logging and what the
# default setup will be per the CM
describe directory(PG_LOG_DIR) do
it { should be_directory }
it { should be_owned_by PG_OWNER }
it { should be_grouped_into PG_OWNER }
its('mode') { should cmp '0700' }
end
describe command("find #{PG_LOG_DIR} -type f -perm 600 ! -perm 600 | wc -l") do
its('stdout.strip') { should eq '0' }
end
end
| 38.483444 | 81 | 0.749785 |
ab8158670543505c97baf13dbdd0066d2f446516 | 603 | module UserDecorator
def select_document
[
['Cedula de Ciudadania', 'Cedula de Ciudadania'],
['Tarjeta de Identidad', 'Tarjeta de Identidad'],
['Cédula de Extranjeria', 'Cedula de Extranjeria'],
['Pasaporte', 'Pasaporte'],
['Menor Sin Identificación', 'Menor Sin Identificación'],
['Adulto Sin Identificación', 'Adulto Sin Identificación'],
['Carnet Diplomático', 'Carnet Diplomático'],
['Certificado de Nacido Vivo (Menores de 2 Meses)', 'Certificado de Nacido Vivo (Menores de 2 Meses)'],
['Registro Civil', 'Registro Civil']
]
end
end | 35.470588 | 109 | 0.658375 |
e2c7a017302e3bd75feb20c59e21e05ff2740ad2 | 60 | # encoding: utf-8
module MarchHare
VERSION = "3.0.0"
end
| 10 | 19 | 0.666667 |
ab6926533fd92dd8d0bc2c9d18541d6c20d17ef3 | 152 | worker_processes 2
preload_app true
# listen "127.0.0.1:8080"
listen "/tmp/unicorn.sock"
stderr_path "/tmp/unicorn.log"
stdout_path "/tmp/unicorn.log"
| 19 | 30 | 0.763158 |
87aa655f35f48ddf964206fb318abb8a663e51f9 | 1,147 | Pod::Spec.new do |s|
s.name = 'Helpshift'
s.version = '3.1.1'
s.summary = 'Customer service helpdesk for mobile applications.'
s.license = { :type => 'Commercial', :text => 'See http://www.helpshift.com/terms/' }
s.homepage = 'http://www.helpshift.com/'
s.author = { 'Helpshift' => '[email protected]' }
s.source = { :http => 'https://s3.amazonaws.com/cdn.helpshift.com/library/ios/v3.1/helpshift-ios-3.1.1.zip' }
s.platform = :ios, '5.0'
s.source_files = 'helpshift-ios-3.1.1/Helpshift.h'
s.resources = 'helpshift-ios-3.1.1/HSResources/*.png', 'helpshift-ios-3.1.1/HSThemes/*.plist', 'helpshift-ios-3.1.1/HSResources/*.lproj'
s.preserve_paths = 'helpshift-ios-3.1.1/libHelpshift.a'
s.frameworks = 'CoreGraphics', 'QuartzCore', 'CoreText', 'SystemConfiguration', 'CoreTelephony', 'Foundation', 'UIKit'
s.libraries = 'sqlite3.0', 'z', 'Helpshift'
s.xcconfig = { 'LIBRARY_SEARCH_PATHS' => '"$(PODS_ROOT)/Helpshift/helpshift-ios-3.1.1"'}
s.requires_arc = false
end
| 63.722222 | 148 | 0.58762 |
4a49242d965bb91e5e8715fd9f9f66d9a737cd59 | 1,312 | require_relative '../spec_helper'
require 'stringio'
describe Raygun do
let(:failsafe_logger) { FakeLogger.new }
describe '#track_exception' do
context 'send in background' do
before do
Raygun.setup do |c|
c.send_in_background = true
c.api_url = 'http://example.api'
c.api_key = 'foo'
c.debug = true
c.failsafe_logger = failsafe_logger
end
end
context 'request times out' do
before do
stub_request(:post, 'http://example.api/entries').to_timeout
end
it 'logs the failure to the failsafe logger' do
error = StandardError.new
Raygun.track_exception(error)
# Occasionally doesn't write to the failsafe logger, add small timeout to add some safety
sleep 0.1
failsafe_logger.get.must_match /Problem reporting exception to Raygun/
end
end
end
end
describe '#reset_configuration' do
it 'clears any customized configuration options' do
Raygun.setup do |c|
c.api_url = 'http://test.api'
end
Raygun.configuration.api_url.must_equal 'http://test.api'
Raygun.reset_configuration
Raygun.configuration.api_url.must_equal Raygun.default_configuration.api_url
end
end
end
| 25.72549 | 99 | 0.641006 |
e2ba81eb0d22f52a1fef362e28b24b67a0a4efcd | 1,193 | require_relative '../../../spec_helper'
ruby_version_is ''...'3.0' do
require 'rexml/document'
describe "REXML::Element#delete_attribute" do
before :each do
@e = REXML::Element.new("Person")
@attr = REXML::Attribute.new("name", "Sean")
@e.add_attribute(@attr)
end
it "deletes an attribute from the element" do
@e.delete_attribute("name")
@e.attributes["name"].should be_nil
end
# Bug was filled with a patch in Ruby's tracker #20298
quarantine! do
it "receives an Attribute" do
@e.add_attribute(@attr)
@e.delete_attribute(@attr)
@e.attributes["name"].should be_nil
end
end
# Docs say that it returns the removed attribute but then examples
# show it returns the element with the attribute removed.
# Also fixed in #20298
it "returns the element with the attribute removed" do
elem = @e.delete_attribute("name")
elem.attributes.should be_empty
elem.to_s.should eql("<Person/>")
end
it "returns nil if the attribute does not exist" do
@e.delete_attribute("name")
at = @e.delete_attribute("name")
at.should be_nil
end
end
end
| 27.744186 | 70 | 0.644593 |
330170e34275cde6b7836356318ebb1a8af91d07 | 2,106 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Web::Mgmt::V2018_02_01
module Models
#
# Virtual IP mapping.
#
class VirtualIPMapping
include MsRestAzure
# @return [String] Virtual IP address.
attr_accessor :virtual_ip
# @return [Integer] Internal HTTP port.
attr_accessor :internal_http_port
# @return [Integer] Internal HTTPS port.
attr_accessor :internal_https_port
# @return [Boolean] Is virtual IP mapping in use.
attr_accessor :in_use
#
# Mapper for VirtualIPMapping class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'VirtualIPMapping',
type: {
name: 'Composite',
class_name: 'VirtualIPMapping',
model_properties: {
virtual_ip: {
client_side_validation: true,
required: false,
serialized_name: 'virtualIP',
type: {
name: 'String'
}
},
internal_http_port: {
client_side_validation: true,
required: false,
serialized_name: 'internalHttpPort',
type: {
name: 'Number'
}
},
internal_https_port: {
client_side_validation: true,
required: false,
serialized_name: 'internalHttpsPort',
type: {
name: 'Number'
}
},
in_use: {
client_side_validation: true,
required: false,
serialized_name: 'inUse',
type: {
name: 'Boolean'
}
}
}
}
}
end
end
end
end
| 26.658228 | 70 | 0.498101 |
e2b2de51901a497fee5cd8b2f228d0b168e68ae4 | 129 | class ChangeTypeColumnName < ActiveRecord::Migration[5.0]
def change
rename_column :surveys, :type, :survey_type
end
end
| 21.5 | 57 | 0.75969 |
0340c3b0d73027100b8b6ab8b7e2302c272bafbe | 1,219 | class PonyStable < Formula
desc "Dependency manager for the Pony language"
homepage "https://github.com/ponylang/pony-stable"
url "https://github.com/ponylang/pony-stable/archive/0.2.2.tar.gz"
sha256 "8fca5f0f600e695d648200a7492c5d8cea82581f4e4e138f0bb621911d9e4c13"
license "BSD-2-Clause"
head "https://github.com/ponylang/pony-stable.git"
bottle do
cellar :any_skip_relocation
sha256 "1375ab1923d90e07e05071bad1effb66aef547bd6d9fd98a40afbdb65596471e" => :catalina
sha256 "1375ab1923d90e07e05071bad1effb66aef547bd6d9fd98a40afbdb65596471e" => :mojave
sha256 "caf0c823ba581ab0e669d0372c06d1cb74262f05334814a5f49370659aa030d1" => :high_sierra
end
# "Stable is no longer being developed. It's been replaced by Corral
# (https://github.com/ponylang/corral)."
deprecate! date: "2020-05-12", because: :repo_archived
depends_on "ponyc"
def install
system "make", "prefix=#{prefix}", "install"
end
test do
(testpath/"test/main.pony").write <<~EOS
actor Main
new create(env: Env) =>
env.out.print("Hello World!")
EOS
system "#{bin}/stable", "env", "ponyc", "test"
assert_equal "Hello World!", shell_output("./test1").chomp
end
end
| 33.861111 | 93 | 0.726825 |
bb08f8734fb2e5740078442f93670223d738ff8c | 3,758 | require 'spec_helper'
require 'beaker/host'
class ClassPEClientToolsMixedWithPatterns
include Beaker::DSL::InstallUtils::PEClientTools
include Beaker::DSL::Patterns
end
describe ClassPEClientToolsMixedWithPatterns do
describe "#install_pe_client_tools_on" do
let(:hosts) do
make_hosts({:platform => platform })
end
opts = {
:puppet_collection => 'PC1',
:pe_client_tools_sha => '12345',
:pe_client_tools_version => '1.0.0-g12345'
}
before do
allow(subject). to receive(:scp_to)
end
context 'on el-6' do
let(:platform) { Beaker::Platform.new('el-6-x86_64') }
it 'installs' do
hosts.each do |host|
allow(subject). to receive(:fetch_http_file).with("http://builds.delivery.puppetlabs.net/pe-client-tools/#{opts[:pe_client_tools_sha]}/artifacts/el/6/PC1/x86_64", "pe-client-tools-#{opts[:pe_client_tools_version]}-1.el6.x86_64.rpm", "tmp/repo_configs")
allow(host). to receive(:external_copy_base)
expect(host).to receive(:install_package).with("pe-client-tools")
subject.install_pe_client_tools_on(host, opts)
end
end
end
context 'on ubuntu' do
let(:platform) { Beaker::Platform.new('ubuntu-1604-x86_64') }
it 'installs' do
hosts.each do |host|
allow(subject). to receive(:fetch_http_file).with("http://builds.delivery.puppetlabs.net/pe-client-tools/#{opts[:pe_client_tools_sha]}/artifacts/deb/xenial/PC1", "pe-client-tools_#{opts[:pe_client_tools_version]}-1xenial_x86_64.deb", "tmp/repo_configs")
allow(host). to receive(:external_copy_base)
expect(subject).to receive(:on).with(host, "dpkg -i pe-client-tools_#{opts[:pe_client_tools_version]}-1xenial_x86_64.deb")
subject.install_pe_client_tools_on(host, opts)
end
end
end
context 'on windows' do
let(:platform) { Beaker::Platform.new('windows-2012r2-x86_64') }
it 'installs' do
hosts.each do |host|
allow(subject). to receive(:fetch_http_file).with("http://builds.delivery.puppetlabs.net/pe-client-tools/#{opts[:pe_client_tools_sha]}/artifacts/deb/xenial/PC1", "pe-client-tools_#{opts[:pe_client_tools_version]}-1xenial_x86_64.deb", "tmp/repo_configs")
allow(host). to receive(:external_copy_base)
expect(subject).to receive(:generic_install_msi_on).with( host,
"http://builds.delivery.puppetlabs.net/pe-client-tools/#{opts[:pe_client_tools_sha]}/artifacts/windows/pe-client-tools-#{opts[:pe_client_tools_version]}-xx86_64.msi",
{},
{ :debug => true }
)
subject.install_pe_client_tools_on(host, opts)
end
end
end
context 'on OS X' do
let(:platform) { Beaker::Platform.new('osx-1111-x86_64') }
it 'installs' do
hosts.each do |host|
allow(subject). to receive(:fetch_http_file).with("http://builds.delivery.puppetlabs.net/pe-client-tools/#{opts[:pe_client_tools_sha]}/artifacts/apple/1111/PC1/x86_64", "pe-client-tools-#{opts[:pe_client_tools_version]}-1.osx1111.dmg", "tmp/repo_configs")
allow(host). to receive(:external_copy_base)
expect(host).to receive(:generic_install_dmg).with("pe-client-tools-#{opts[:pe_client_tools_version]}-1.osx1111.dmg", "pe-client-tools-#{opts[:pe_client_tools_version]}", "pe-client-tools-#{opts[:pe_client_tools_version]}-1-installer.pkg")
subject.install_pe_client_tools_on(host, opts)
end
end
end
end
end
| 49.447368 | 265 | 0.637307 |
f863766c1a3aba19ef587251de4579b79d2eaa4f | 3,856 | require_relative '../../spec_helper'
require_relative 'fixtures/classes'
describe "Class.new with a block given" do
it "yields the new class as self in the block" do
self_in_block = nil
klass = Class.new do
self_in_block = self
end
self_in_block.should equal klass
end
it "uses the given block as the class' body" do
klass = Class.new do
def self.message
"text"
end
def hello
"hello again"
end
end
klass.message.should == "text"
klass.new.hello.should == "hello again"
end
it "creates a subclass of the given superclass" do
sc = Class.new do
def self.body
@body
end
@body = self
def message; "text"; end
end
klass = Class.new(sc) do
def self.body
@body
end
@body = self
def message2; "hello"; end
end
klass.body.should == klass
sc.body.should == sc
klass.superclass.should == sc
klass.new.message.should == "text"
klass.new.message2.should == "hello"
end
it "runs the inherited hook after yielding the block" do
ScratchPad.record []
klass = Class.new(CoreClassSpecs::Inherited::D) do
ScratchPad << self
end
ScratchPad.recorded.should == [CoreClassSpecs::Inherited::D, klass]
end
end
describe "Class.new" do
it "creates a new anonymous class" do
klass = Class.new
klass.is_a?(Class).should == true
klass_instance = klass.new
klass_instance.is_a?(klass).should == true
end
it "raises a TypeError if passed a metaclass" do
obj = mock("Class.new metaclass")
meta = obj.singleton_class
-> { Class.new meta }.should raise_error(TypeError)
end
it "creates a class without a name" do
Class.new.name.should be_nil
end
it "creates a class that can be given a name by assigning it to a constant" do
::MyClass = Class.new
::MyClass.name.should == "MyClass"
a = Class.new
MyClass::NestedClass = a
MyClass::NestedClass.name.should == "MyClass::NestedClass"
end
it "sets the new class' superclass to the given class" do
top = Class.new
Class.new(top).superclass.should == top
end
it "sets the new class' superclass to Object when no class given" do
Class.new.superclass.should == Object
end
it "raises a TypeError when given a non-Class" do
error_msg = /superclass must be a Class/
-> { Class.new("") }.should raise_error(TypeError, error_msg)
-> { Class.new(1) }.should raise_error(TypeError, error_msg)
-> { Class.new(:symbol) }.should raise_error(TypeError, error_msg)
-> { Class.new(mock('o')) }.should raise_error(TypeError, error_msg)
-> { Class.new(Module.new) }.should raise_error(TypeError, error_msg)
-> { Class.new(BasicObject.new) }.should raise_error(TypeError, error_msg)
end
end
describe "Class#new" do
it "returns a new instance of self" do
klass = Class.new
klass.new.is_a?(klass).should == true
end
it "invokes #initialize on the new instance with the given args" do
klass = Class.new do
def initialize(*args)
@initialized = true
@args = args
end
def args
@args
end
def initialized?
@initialized || false
end
end
klass.new.should.initialized?
klass.new(1, 2, 3).args.should == [1, 2, 3]
end
it "uses the internal allocator and does not call #allocate" do
klass = Class.new do
def self.allocate
raise "allocate should not be called"
end
end
instance = klass.new
instance.should be_kind_of klass
instance.class.should equal klass
end
it "passes the block to #initialize" do
klass = Class.new do
def initialize
yield
end
end
klass.new { break 42 }.should == 42
end
end
| 24.717949 | 80 | 0.634336 |
1d2f84ac149a23de3f88291d16d8af77ed382bd4 | 1,596 | require 'rails_helper'
RSpec.describe NfgUi::Bootstrap::Utilities::Collapsible do
# Button is collapsible
let(:button) { FactoryBot.create(:bootstrap_button, **options, as: button_wrapper_el) }
let(:button_wrapper_el) { :button }
let(:options) { { collapse: collapse } }
let(:collapse) { tested_collapse }
let(:tested_collapse) { nil }
pending 'Specs needed for Collapsible utility'
describe '#collapse' do
subject { button.collapse }
context 'when collapse is present' do
let(:tested_collapse) { '#tested_collapse' }
it { is_expected.to eq tested_collapse }
end
context 'when :collapse is nil in the options' do
let(:tested_collapse) { nil }
it { is_expected.to be_nil }
end
context 'when :collapse is not present in the options' do
let(:options) { {} }
it { is_expected.to be_nil }
end
end
describe '#collapsed' do
subject { button.collapsed }
let(:test_id) { 'test_id' }
context 'when :collapsed is present within options' do
let(:test_collapsed) { false }
let(:options) { { id: test_id, collapsed: test_collapsed } }
it { is_expected.to eq test_collapsed }
end
context 'when :collapsed is not present within options' do
let(:options) { { id: test_id } }
it { is_expected.to be_nil }
end
end
describe '#collapsible' do
subject { button.collapsible }
end
describe '#non_html_attribute_options' do
subject { button.send(:non_html_attribute_options) }
it { is_expected.to include :collapse, :collapsed, :collapsible }
end
end
| 28.5 | 89 | 0.670426 |
79986cb72f547372a1cfd7374d0beca00b914a4b | 385 | # $RoughId: extconf.rb,v 1.4 2001/08/14 19:54:51 knu Exp $
# $Id: extconf.rb 25189 2009-10-02 12:04:37Z akr $
require "mkmf"
$defs << "-DHAVE_CONFIG_H"
$INCFLAGS << " -I$(srcdir)/.."
$objs = [
"sha2.#{$OBJEXT}",
"sha2init.#{$OBJEXT}",
]
have_header("sys/cdefs.h")
$preload = %w[digest]
if have_type("uint64_t", "defs.h", $defs.join(' '))
create_makefile("digest/sha2")
end
| 18.333333 | 58 | 0.620779 |
ed585d8ab61b4518e7e06e618c03519d70efe5d7 | 1,881 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::DataMigration::Mgmt::V2018_03_31_preview
module Models
#
# Output for the task that migrates on-prem SQL Server databases to Azure
# SQL Database
#
class MigrateSqlServerSqlDbTaskOutput
include MsRestAzure
@@discriminatorMap = Hash.new
@@discriminatorMap["ErrorOutput"] = "MigrateSqlServerSqlDbTaskOutputError"
@@discriminatorMap["TableLevelOutput"] = "MigrateSqlServerSqlDbTaskOutputTableLevel"
@@discriminatorMap["DatabaseLevelOutput"] = "MigrateSqlServerSqlDbTaskOutputDatabaseLevel"
@@discriminatorMap["MigrationLevelOutput"] = "MigrateSqlServerSqlDbTaskOutputMigrationLevel"
def initialize
@resultType = "MigrateSqlServerSqlDbTaskOutput"
end
attr_accessor :resultType
# @return [String] Result identifier
attr_accessor :id
#
# Mapper for MigrateSqlServerSqlDbTaskOutput class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'MigrateSqlServerSqlDbTaskOutput',
type: {
name: 'Composite',
polymorphic_discriminator: 'resultType',
uber_parent: 'MigrateSqlServerSqlDbTaskOutput',
class_name: 'MigrateSqlServerSqlDbTaskOutput',
model_properties: {
id: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'id',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 30.33871 | 98 | 0.629452 |
084d347e600c77eca917430d1f3f0676449930f1 | 7,241 | =begin
#BillForward REST API
#No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for BillForward::ProductRatePlanMigrationAmendment
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'ProductRatePlanMigrationAmendment' do
before do
# run before each test
@instance = BillForward::ProductRatePlanMigrationAmendment.new
end
after do
# run after each test
end
describe 'test an instance of ProductRatePlanMigrationAmendment' do
it 'should create an instact of ProductRatePlanMigrationAmendment' do
expect(@instance).to be_instance_of(BillForward::ProductRatePlanMigrationAmendment)
end
end
describe 'test attribute "created"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "changed_by"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "updated"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "type"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
#validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["InvoiceOutstandingChargesAmendment", "IssueInvoiceAmendment", "PricingComponentValueAmendment", "InvoiceRecalculationAmendment", "CancellationAmendment", "InvoiceNextExecutionAttemptAmendment", "FixedTermExpiryAmendment", "EndTrialAmendment", "ProductRatePlanMigrationAmendment", "AmendmentDiscardAmendment", "UpdateComponentValueAmendment", "ServiceEndAmendment", "ResumeSubscriptionAmendment", "CreateSubscriptionChargeAmendment", "TimerAmendment"])
#validator.allowable_values.each do |value|
# expect { @instance.type = value }.not_to raise_error
#end
end
end
describe 'test attribute "id"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "organization_id"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "subscription_id"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "amendment_type"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
#validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["InvoiceNextExecutionAttempt", "Cancellation", "PricingComponentValue", "AmendmentDiscard", "Compound", "FixedTermExpiry", "InvoiceRecalculation", "EndTrial", "InvoiceOutstandingCharges", "IssueInvoice", "ProductRatePlanMigration", "UpdateComponentValue", "ServiceEnd", "ResumeSubscription", "CreateSubscriptionCharge", "Timer"])
#validator.allowable_values.each do |value|
# expect { @instance.amendment_type = value }.not_to raise_error
#end
end
end
describe 'test attribute "actioning_time"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "actioned_time"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "state"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
#validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["Pending", "Succeeded", "Failed", "Discarded"])
#validator.allowable_values.each do |value|
# expect { @instance.state = value }.not_to raise_error
#end
end
end
describe 'test attribute "deleted"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "product_rate_plan_id"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "invoicing_type"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
#validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["Immediate", "Aggregated"])
#validator.allowable_values.each do |value|
# expect { @instance.invoicing_type = value }.not_to raise_error
#end
end
end
describe 'test attribute "mappings"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "previous_subscription_id"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "next_subscription_id"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "next_subscription_name"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "next_subscription_description"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "pricing_behaviour"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
#validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["None", "Full", "Difference", "DifferenceProRated", "ProRated"])
#validator.allowable_values.each do |value|
# expect { @instance.pricing_behaviour = value }.not_to raise_error
#end
end
end
end
| 38.515957 | 530 | 0.728905 |
f788f0d92b0ffb8cff39f4fd27274905a76dea63 | 371 | require 'spec_helper'
describe YARD::Cov::Config, '#output=' do
subject { config.output = output }
let(:config) { described_class.new }
let(:path) { 'tmp/*.rb' }
before { config.output = path }
context 'output' do
subject { config.output }
it { should be_a(YARD::Cov::ReportOutput) }
its(:to_s) { should eql('tmp/*.rb') }
end
end
| 19.526316 | 47 | 0.606469 |
383c3538baefeb6715d35d46e6ce43a45fe45d12 | 3,224 | class BillingAddressInfo
attr_accessor :address1, :address2, :city, :company, :country, :email, :fax, :first_name, :last_name, :phone, :state, :zip
# :internal => :external
def self.attribute_map
{
:address1 => :address1, :address2 => :address2, :city => :city, :company => :company, :country => :country, :email => :email, :fax => :fax, :first_name => :firstName, :last_name => :lastName, :phone => :phone, :state => :state, :zip => :zip
}
end
def initialize(attributes = {})
# Morph attribute keys into undescored rubyish style
if attributes.to_s != ""
if BillingAddressInfo.attribute_map["address1".to_sym] != nil
name = "address1".to_sym
value = attributes["address1"]
send("#{name}=", value) if self.respond_to?(name)
end
if BillingAddressInfo.attribute_map["address2".to_sym] != nil
name = "address2".to_sym
value = attributes["address2"]
send("#{name}=", value) if self.respond_to?(name)
end
if BillingAddressInfo.attribute_map["city".to_sym] != nil
name = "city".to_sym
value = attributes["city"]
send("#{name}=", value) if self.respond_to?(name)
end
if BillingAddressInfo.attribute_map["company".to_sym] != nil
name = "company".to_sym
value = attributes["company"]
send("#{name}=", value) if self.respond_to?(name)
end
if BillingAddressInfo.attribute_map["country".to_sym] != nil
name = "country".to_sym
value = attributes["country"]
send("#{name}=", value) if self.respond_to?(name)
end
if BillingAddressInfo.attribute_map["email".to_sym] != nil
name = "email".to_sym
value = attributes["email"]
send("#{name}=", value) if self.respond_to?(name)
end
if BillingAddressInfo.attribute_map["fax".to_sym] != nil
name = "fax".to_sym
value = attributes["fax"]
send("#{name}=", value) if self.respond_to?(name)
end
if BillingAddressInfo.attribute_map["first_name".to_sym] != nil
name = "first_name".to_sym
value = attributes["firstName"]
send("#{name}=", value) if self.respond_to?(name)
end
if BillingAddressInfo.attribute_map["last_name".to_sym] != nil
name = "last_name".to_sym
value = attributes["lastName"]
send("#{name}=", value) if self.respond_to?(name)
end
if BillingAddressInfo.attribute_map["phone".to_sym] != nil
name = "phone".to_sym
value = attributes["phone"]
send("#{name}=", value) if self.respond_to?(name)
end
if BillingAddressInfo.attribute_map["state".to_sym] != nil
name = "state".to_sym
value = attributes["state"]
send("#{name}=", value) if self.respond_to?(name)
end
if BillingAddressInfo.attribute_map["zip".to_sym] != nil
name = "zip".to_sym
value = attributes["zip"]
send("#{name}=", value) if self.respond_to?(name)
end
end
end
def to_body
body = {}
BillingAddressInfo.attribute_map.each_pair do |key,value|
body[value] = self.send(key) unless self.send(key).nil?
end
body
end
end
| 36.636364 | 246 | 0.60701 |
bf1f0a15b2c576ac2b8150095afd9b7edc49b87d | 8,049 | #
# Copyright 2011 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# == Schema Information
# Schema version: 20110207110131
#
# Table name: users
#
# id :integer not null, primary key
# username :string(255) not null
# email :string(255) not null
# crypted_password :string(255) not null
# password_salt :string(255) not null
# persistence_token :string(255) not null
# single_access_token :string(255) not null
# perishable_token :string(255) not null
# first_name :string(255)
# last_name :string(255)
# quota_id :integer
# login_count :integer default(0), not null
# failed_login_count :integer default(0), not null
# last_request_at :datetime
# current_login_at :datetime
# last_login_at :datetime
# current_login_ip :string(255)
# last_login_ip :string(255)
# created_at :datetime
# updated_at :datetime
#
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
require 'password'
require 'ldap'
class User < ActiveRecord::Base
class << self
include CommonFilterMethods
end
before_destroy :ensure_not_running_any_instances
has_many :permissions, :through => :entity
has_many :derived_permissions, :through => :entity
has_many :owned_instances, :class_name => "Instance", :foreign_key => "owner_id"
has_many :deployments, :foreign_key => "owner_id"
has_many :view_states
has_and_belongs_to_many :user_groups, :join_table => "members_user_groups",
:foreign_key => "member_id"
has_one :entity, :as => :entity_target, :class_name => "Alberich::Entity",
:dependent => :destroy
has_many :session_entities, :class_name => "Alberich::SessionEntity",
:dependent => :destroy
belongs_to :quota, :autosave => true, :dependent => :destroy
has_many :base_images, :class_name => "Tim::BaseImage"
attr_accessor :password
# this attr is used when validating non-local (ldap) users
# - these users have blank password, so validation should accept nil password
# for them
attr_accessor :ignore_password
accepts_nested_attributes_for :quota
before_validation :strip_whitespace
before_save :encrypt_password
validates :email, :presence => true,
:format => { :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i },
:if => Proc.new { |u| u.local_user? }
validates :username, :presence => true,
:length => { :within => 1..100 },
:uniqueness => true
validates :first_name, :length => { :maximum => 255 }
validates :last_name, :length => { :maximum => 255 }
validates :password, :presence => true,
:length => { :within => 4..255 },
:confirmation => true,
:if => Proc.new { |u| u.check_password? }
validates :quota, :presence => true
validate :validate_ldap_changes,
:if => Proc.new { |user| !user.new_record? && SETTINGS_CONFIG[:auth][:strategy] == "ldap" }
def name
"#{first_name} #{last_name}".strip
end
def self.authenticate(username, password, ipaddress)
username = username.strip unless username.nil?
return unless u = User.find_by_username(username)
# FIXME: this is because of tests - encrypted password is submitted,
# don't know how to get unencrypted version (from factorygirl)
if password.length == 192 and password == u.crypted_password
update_login_attributes(u, ipaddress)
elsif Password.check(password, u.crypted_password)
update_login_attributes(u, ipaddress)
else
u.failed_login_count += 1
u.save!
u = nil
end
u.save! unless u.nil?
return u
end
def self.authenticate_using_ldap(username, password, ipaddress)
if Ldap.valid_ldap_authentication?(username, password)
u = User.find_by_username(username) || create_ldap_user!(username)
update_login_attributes(u, ipaddress)
else
u = User.find_by_username(username)
if u.present?
u.failed_login_count += 1
u.save!
end
u = nil
end
u.save! unless u.nil?
return u
end
def self.authenticate_using_krb(username, ipaddress)
u = User.find_by_username(username) || create_krb_user!(username)
update_login_attributes(u, ipaddress)
u.save!
u
end
def self.update_login_attributes(u, ipaddress)
u.login_count += 1
u.last_login_ip = ipaddress
u.last_login_at = DateTime.now
end
def check_password?
# don't check password if it's a new no-local user (ldap)
# or if a user is updated
new_record? ? !ignore_password : !(password.blank? && password_confirmation.blank?)
end
def send_password_reset
generate_token(:password_reset_token)
self.password_reset_sent_at = Time.zone.now
save!
UserMailer.delay.password_reset(self.id)
end
def local_user?
new_record? ? !ignore_password : (!crypted_password.blank?)
end
PRESET_FILTERS_OPTIONS = []
def all_groups
group_list = []
group_list += self.user_groups if UserGroup.local_groups_active?
if UserGroup.ldap_groups_active?
ldap_group_names = Ldap.ldap_groups(self.username)
ldap_group_names.each do |group_name|
ldap_group = UserGroup.find_by_name_and_membership_source(
group_name, UserGroup::MEMBERSHIP_SOURCE_LDAP)
if ldap_group
# update group on each login so we can later check/purge groups
# that haven't been updated lately (i.e. no recent logins by users
# that belong to them)
ldap_group.touch
else
ldap_group = UserGroup.create!(:name => group_name,
:membership_source =>
UserGroup::MEMBERSHIP_SOURCE_LDAP)
end
group_list << ldap_group
end
end
group_list
end
def to_s
"#{self.first_name} #{self.last_name} (#{self.username})"
end
private
def self.apply_search_filter(search)
if search
where("lower(first_name) LIKE :search OR lower(last_name) LIKE :search OR lower(username) LIKE :search OR lower(email) LIKE :search", :search => "%#{search.downcase}%")
else
scoped
end
end
def validate_ldap_changes
if self.first_name_changed? || self.last_name_changed? || self.email_changed? ||
self.username_changed? || self.crypted_password_changed? then
errors.add(:base, _('Cannot edit LDAP user'))
end
end
def generate_token(column)
begin
self[column] = SecureRandom.urlsafe_base64
end while User.exists?(column => self[column])
end
def encrypt_password
self.crypted_password = Password::update(password) unless password.blank?
end
def self.create_ldap_user!(username)
User.create!(:username => username, :quota => Quota.new_for_user, :ignore_password => true)
end
def self.create_krb_user!(username)
User.create!(:username => username, :quota => Quota.new_for_user, :ignore_password => true)
end
def ensure_not_running_any_instances
raise _('%s has running instances') % username if deployments.any?{ |deployment| deployment.any_instance_running? }
end
def strip_whitespace
self.username = self.username.strip unless self.username.nil?
end
end
| 33.5375 | 174 | 0.662567 |
5d97d7122cf5e8f5654184a201185621dd1d96b7 | 124 | class AddContainerToPeople < ActiveRecord::Migration
def change
add_column :people, :container_id, :integer
end
end
| 20.666667 | 52 | 0.774194 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.