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
|
---|---|---|---|---|---|
62315e80c77c66ac503671523ff0dcf9f81678da | 9,454 | require 'excon'
require 'digest'
require_relative 'changelog'
require_relative '../analytics/app_identifier_guesser'
require_relative '../helper'
require_relative '../ui/ui'
module FastlaneCore
# Verifies, the user runs the latest version of this gem
class UpdateChecker
def self.start_looking_for_update(gem_name)
return if Helper.test?
return if FastlaneCore::Env.truthy?("FASTLANE_SKIP_UPDATE_CHECK")
@start_time = Time.now
Thread.new do
begin
send_launch_analytic_events_for(gem_name)
rescue
# we don't want to show a stack trace if something goes wrong
end
end
Thread.new do
begin
server_results[gem_name] = fetch_latest(gem_name)
rescue
# we don't want to show a stack trace if something goes wrong
end
end
end
def self.server_results
@results ||= {}
end
class << self
attr_reader :start_time
end
def self.update_available?(gem_name, current_version)
latest = server_results[gem_name]
return (latest and Gem::Version.new(latest) > Gem::Version.new(current_version))
end
def self.show_update_status(gem_name, current_version)
Thread.new do
begin
send_completion_events_for(gem_name)
rescue
# we don't want to show a stack trace if something goes wrong
end
end
if update_available?(gem_name, current_version)
show_update_message(gem_name, current_version)
end
end
# Show a message to the user to update to a new version of fastlane (or a sub-gem)
# Use this method, as this will detect the current Ruby environment and show an
# appropriate message to the user
def self.show_update_message(gem_name, current_version)
available = server_results[gem_name]
puts("")
puts('#######################################################################')
if available
puts("# #{gem_name} #{available} is available. You are on #{current_version}.")
else
puts("# An update for #{gem_name} is available. You are on #{current_version}.")
end
puts("# You should use the latest version.")
puts("# Please update using `#{self.update_command(gem_name: gem_name)}`.")
puts("# To see what's new, open https://github.com/fastlane/#{gem_name}/releases.") if FastlaneCore::Env.truthy?("FASTLANE_HIDE_CHANGELOG")
if !Helper.bundler? && !Helper.contained_fastlane? && Random.rand(5) == 1
# We want to show this message from time to time, if the user doesn't use bundler, nor bundled fastlane
puts('#######################################################################')
puts("# Run `sudo gem cleanup` from time to time to speed up fastlane")
end
puts('#######################################################################')
Changelog.show_changes(gem_name, current_version, update_gem_command: UpdateChecker.update_command(gem_name: gem_name)) unless FastlaneCore::Env.truthy?("FASTLANE_HIDE_CHANGELOG")
ensure_rubygems_source
end
# The command that the user should use to update their mac
def self.update_command(gem_name: "fastlane")
if Helper.bundler?
"bundle update #{gem_name.downcase}"
elsif Helper.contained_fastlane? || Helper.homebrew?
"fastlane update_fastlane"
elsif Helper.mac_app?
"the Fabric app. Launch the app and navigate to the fastlane tab to get the most recent version."
else
"sudo gem install #{gem_name.downcase}"
end
end
# Check if RubyGems is set as a gem source
# on some machines that might not be the case
# and then users can't find the update when
# running the specified command
def self.ensure_rubygems_source
return if Helper.contained_fastlane?
return if `gem sources`.include?("https://rubygems.org")
puts("")
UI.error("RubyGems is not listed as your Gem source")
UI.error("You can run `gem sources` to see all your sources")
UI.error("Please run the following command to fix this:")
UI.command("gem sources --add https://rubygems.org")
end
def self.fetch_latest(gem_name)
JSON.parse(Excon.get(generate_fetch_url(gem_name)).body)["version"]
end
def self.generate_fetch_url(gem_name)
"https://rubygems.org/api/v1/gems/#{gem_name}.json"
end
def self.send_launch_analytic_events_for(gem_name)
return if FastlaneCore::Env.truthy?("FASTLANE_OPT_OUT_USAGE")
ci = Helper.ci?.to_s
app_id_guesser = FastlaneCore::AppIdentifierGuesser.new(args: ARGV, gem_name: gem_name)
project_hash = app_id_guesser.p_hash
p_hash = project_hash if project_hash
platform = @platform if @platform # this has to be called after `p_hash`
send_launch_analytic_events(p_hash, gem_name, platform, ci)
end
def self.send_launch_analytic_events(p_hash, tool, platform, ci)
timestamp_seconds = Time.now.to_i
analytics = []
analytics << event_for_p_hash(p_hash, tool, platform, timestamp_seconds) if p_hash
analytics << event_for_launch(tool, ci, timestamp_seconds)
send_events(analytics)
end
def self.event_for_p_hash(p_hash, tool, platform, timestamp_seconds)
{
event_source: {
oauth_app_name: oauth_app_name,
product: 'fastlane'
},
actor: {
name: 'project',
detail: p_hash
},
action: {
name: 'update_checked'
},
primary_target: {
name: 'tool',
detail: tool || 'unknown'
},
secondary_target: {
name: 'platform',
detail: secondary_target_string(platform || 'unknown')
},
millis_since_epoch: timestamp_seconds * 1000,
version: 1
}
end
def self.event_for_launch(tool, ci, timestamp_seconds)
{
event_source: {
oauth_app_name: oauth_app_name,
product: 'fastlane'
},
actor: {
name: 'tool',
detail: tool || 'unknown'
},
action: {
name: 'launched'
},
primary_target: {
name: 'ci',
detail: ci
},
secondary_target: {
name: 'launch',
detail: secondary_target_string('')
},
millis_since_epoch: timestamp_seconds * 1000,
version: 1
}
end
def self.send_completion_events_for(gem_name)
return if FastlaneCore::Env.truthy?("FASTLANE_OPT_OUT_USAGE")
ci = Helper.ci?.to_s
install_method = if Helper.rubygems?
'gem'
elsif Helper.bundler?
'bundler'
elsif Helper.mac_app?
'mac_app'
elsif Helper.contained_fastlane?
'standalone'
elsif Helper.homebrew?
'homebrew'
else
'unknown'
end
duration = (Time.now - start_time).to_i
timestamp_seconds = Time.now.to_i
send_completion_events(gem_name, ci, install_method, duration, timestamp_seconds)
end
def self.send_events(analytics)
analytic_event_body = { analytics: analytics }.to_json
url = ENV["FASTLANE_METRICS_URL"] || "https://fastlane-metrics.fabric.io/public"
Excon.post(url,
body: analytic_event_body,
headers: { "Content-Type" => 'application/json' })
end
def self.event_for_completion(tool, ci, duration, timestamp_seconds)
{
event_source: {
oauth_app_name: oauth_app_name,
product: 'fastlane'
},
actor: {
name: 'tool',
detail: tool || 'unknown'
},
action: {
name: 'completed_with_duration'
},
primary_target: {
name: 'duration',
detail: duration.to_s
},
secondary_target: {
name: 'ci',
detail: secondary_target_string(ci)
},
millis_since_epoch: timestamp_seconds * 1000,
version: 1
}
end
def self.event_for_install_method(tool, ci, install_method, timestamp_seconds)
{
event_source: {
oauth_app_name: oauth_app_name,
product: 'fastlane'
},
actor: {
name: 'tool',
detail: tool || 'unknown'
},
action: {
name: 'completed_with_install_method'
},
primary_target: {
name: 'install_method',
detail: install_method
},
secondary_target: {
name: 'ci',
detail: secondary_target_string(ci)
},
millis_since_epoch: timestamp_seconds * 1000,
version: 1
}
end
def self.secondary_target_string(string)
return string
end
def self.oauth_app_name
return 'fastlane-refresher'
end
def self.send_completion_events(tool, ci, install_method, duration, timestamp_seconds)
analytics = []
analytics << event_for_completion(tool, ci, duration, timestamp_seconds)
analytics << event_for_install_method(tool, ci, install_method, timestamp_seconds)
send_events(analytics)
end
end
end
| 31.618729 | 185 | 0.598477 |
0369179f1eec9173b57a9daa317d46559d760902 | 689 |
Pod::Spec.new do |s|
s.name = "ISaMaterialLogIn"
s.version = "0.1.0"
s.summary = "A Login/SignUp ViewController with Material Design animations and error handling!"
s.homepage = "https://github.com/FraDeliro/ISaMaterialLogIn"
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { "FraDeliro" => "[email protected]" }
s.source = { :git => 'https://github.com/FraDeliro/ISaMaterialLogIn.git', :tag => s.version.to_s }
s.social_media_url = "https://twitter.com/FDeliro"
s.ios.deployment_target = "9.0"
s.source_files = "ISaMaterialLogIn/Classes/**/*"
s.dependency 'Material', '~> 2.0'
end
| 43.0625 | 110 | 0.606676 |
5d143e18cca108a3ec2115e28356a1507d959ea1 | 13,265 | require 'spec_helper'
describe Assessments::Permission do
describe '#initialize' do
let(:assessment) {
create(:assessment)
}
it {
expect(Assessments::Permission.new(assessment).assessment).to eq assessment
}
end
describe '#available_permissions' do
it {
expect(Assessments::Permission.available_permissions).to eq [:facilitator, :participant]
}
end
describe '#request_access' do
let(:assessment) {
create(:assessment, :with_participants)
}
let(:user) {
create(:user, :with_district)
}
before(:each) do
Assessments::Permission.request_access(
user: user,
roles: 'facilitator',
assessment_id: assessment.id)
end
it {
expect(AccessRequest.find_by(tool: assessment, user: user)).not_to be_nil
}
end
describe '#requested' do
let(:access_request) {
create(:access_request)
}
let(:access_permission) {
Assessments::Permission.new(assessment)
}
let(:assessment) {
access_request.tool
}
it {
expect(access_permission.requested.first).to eq access_request
}
end
describe '#get_access_request' do
let(:access_request) {
create(:access_request)
}
let(:assessment) {
access_request.tool
}
let(:access_permission) {
Assessments::Permission.new(assessment)
}
context 'when the user is a member of the request' do
let(:user) {
access_request.user
}
it {
expect(access_permission.get_access_request(user)).to eq access_request
}
end
context 'when the user is not a member of the request' do
let(:user) {
create(:user, :with_district)
}
it {
expect(access_permission.get_access_request(user)).to be_nil
}
end
end
describe '#possible_roles_permissions' do
let(:assessment_permission) {
Assessments::Permission.new(assessment)
}
let(:assessment) {
create(:assessment, :with_participants)
}
let(:user) {
create(:user, :with_district)
}
context 'when the user is a participant' do
let!(:participant) {
create(:participant, user: user, assessment: assessment)
}
it {
expect(assessment_permission.possible_roles_permissions(user)).to eq [:facilitator]
}
end
context 'when the user is a facilitator' do
before(:each) do
assessment.facilitators << user
end
it {
expect(assessment_permission.possible_roles_permissions(user)).to eq [:participant]
}
end
end
describe '#get_level' do
let(:assessment) {
create(:assessment, :with_participants)
}
let(:assessment_permission) {
Assessments::Permission.new(assessment)
}
context 'when the user is a facilitator' do
let(:user) {
assessment.facilitators.sample
}
it {
expect(assessment_permission.get_level(user)).to eq :facilitator
}
end
context 'when the user is a participant' do
let(:user) {
assessment.participants.sample.user
}
it {
expect(assessment_permission.get_level(user)).to eq :participant
}
end
context 'when the user is a network partner' do
let(:user) {
u = create(:user, :with_network_partner_role)
assessment.network_partners << u
u
}
it {
expect(assessment_permission.get_level(user)).to eq :network_partner
}
end
end
describe '#add_level' do
let(:assessment) {
create(:assessment, :with_participants)
}
let(:assessment_permission) {
Assessments::Permission.new(assessment)
}
let(:user) {
create(:user)
}
context 'when adding a facilitator' do
before(:each) do
expect(AccessGrantedNotificationWorker).to receive(:perform_async).with(assessment.id, user.id, :facilitator)
assessment_permission.add_level(user, :facilitator)
end
it {
expect(assessment.facilitators.include?(user)).to be true
}
end
context 'when adding a network partner' do
before(:each) do
expect(AccessGrantedNotificationWorker).to receive(:perform_async).with(assessment.id, user.id, :network_partner)
assessment_permission.add_level(user, :network_partner)
end
it {
expect(assessment.network_partners.include?(user)).to be true
}
end
context 'when adding a viewer' do
before(:each) do
expect(AccessGrantedNotificationWorker).to receive(:perform_async).with(assessment.id, user.id, :viewer)
assessment_permission.add_level(user, :viewer)
end
it {
expect(assessment.viewers.include?(user)).to be true
}
end
context 'when adding any other level' do
before(:each) do
expect(AccessGrantedNotificationWorker).not_to receive(:perform_async).with(assessment.id, user.id, :admin)
end
it {
expect(assessment_permission.add_level(user, :admin)).to be false
}
end
end
describe '#update_level' do
let(:assessment) {
create(:assessment, :with_participants)
}
let(:assessment_permission) {
Assessments::Permission.new(assessment)
}
context 'when the user is the owner of the assessment' do
let(:user) {
assessment.user
}
context 'when attempting to update to network partner' do
let(:level) {
:network_partner
}
before(:each) do
assessment_permission.update_level(user, level)
end
it {
expect(assessment.network_partner?(user)).to be false
}
end
context 'when attempting to update to viewer' do
let(:level) {
:viewer
}
before(:each) do
assessment_permission.update_level(user, level)
end
it {
expect(assessment.viewer?(user)).to be false
}
end
context 'when attempting to update to participant' do
let(:level) {
:participant
}
before(:each) do
assessment_permission.update_level(user, level)
end
it {
expect(assessment.participant?(user)).to be false
}
end
end
context 'when the user is a facilitator of the assessment' do
let(:user) {
assessment.facilitators.sample
}
context 'when attempting to update to network partner' do
let(:level) {
:network_partner
}
before(:each) do
assessment_permission.update_level(user, level)
end
it {
expect(assessment.network_partner?(user)).to be true
}
end
context 'when attempting to update to viewer' do
let(:level) {
:viewer
}
before(:each) do
assessment_permission.update_level(user, level)
end
it {
expect(assessment.viewer?(user)).to be true
}
end
context 'when attempting to update to participant' do
let(:level) {
:participant
}
before(:each) do
assessment_permission.update_level(user, level)
end
it {
expect(assessment.participant?(user)).to be false
}
end
end
context 'when the user is a participant of the assessment' do
let(:user) {
assessment.participants.sample.user
}
context 'when attempting to update to network partner' do
let(:level) {
:network_partner
}
before(:each) do
assessment_permission.update_level(user, level)
end
it {
expect(assessment.network_partner?(user)).to be true
}
end
context 'when attempting to update to viewer' do
let(:level) {
:viewer
}
before(:each) do
assessment_permission.update_level(user, level)
end
it {
expect(assessment.viewer?(user)).to be true
}
end
context 'when attempting to update to facilitator' do
let(:level) {
:facilitator
}
before(:each) do
assessment_permission.update_level(user, level)
end
it {
expect(assessment.facilitator?(user)).to be true
}
end
end
context 'when the user is a network partner of the assessment' do
let(:user) {
u = create(:user, :with_network_partner_role)
assessment.network_partners << u
u
}
context 'when attempting to update to participant' do
let(:level) {
:participant
}
before(:each) do
assessment_permission.update_level(user, level)
end
it {
expect(assessment.participant?(user)).to be false
}
end
context 'when attempting to update to viewer' do
let(:level) {
:viewer
}
before(:each) do
assessment_permission.update_level(user, level)
end
it {
expect(assessment.viewer?(user)).to be true
}
end
context 'when attempting to update to facilitator' do
let(:level) {
:facilitator
}
before(:each) do
assessment_permission.update_level(user, level)
end
it {
expect(assessment.facilitator?(user)).to be true
}
end
end
context 'when the user is a viewer of the assessment' do
let(:user) {
u = create(:user, :with_district)
assessment.viewers << u
u
}
context 'when attempting to update to network partner' do
let(:level) {
:network_partner
}
before(:each) do
assessment_permission.update_level(user, level)
end
it {
expect(assessment.network_partner?(user)).to be true
}
end
context 'when attempting to update to viewer' do
let(:level) {
:viewer
}
before(:each) do
assessment_permission.update_level(user, level)
end
it {
expect(assessment.viewer?(user)).to be true
}
end
context 'when attempting to update to facilitator' do
let(:level) {
:facilitator
}
before(:each) do
assessment_permission.update_level(user, level)
end
it {
expect(assessment.facilitator?(user)).to be true
}
end
end
context 'when updating to the same role' do
let(:user) {
assessment.facilitators.sample
}
let(:level) {
:facilitator
}
it {
expect(assessment_permission).not_to receive(:revoke_level).with(user)
expect(assessment_permission).not_to receive(:add_level).with(user, level)
assessment_permission.update_level(user, level)
}
end
end
describe '#deny' do
let(:assessment_permission) {
Assessments::Permission.new(assessment)
}
let(:assessment) {
access_request.tool
}
let(:user) {
access_request.user
}
let(:access_request) {
create(:access_request)
}
before(:each) do
assessment_permission.deny(user)
end
it {
expect(AccessRequest.find_by(tool: assessment, user: user)).to be_nil
}
end
describe '#accept_permission_requested' do
let(:assessment_permission) {
Assessments::Permission.new(assessment)
}
let(:assessment) {
access_request.tool
}
let(:access_request) {
create(:access_request)
}
let(:user) {
access_request.user
}
it {
expect(AccessGrantedNotificationWorker).to receive(:perform_async)
assessment_permission.accept_permission_requested(user)
expect(assessment.facilitator?(user)).to be true
}
it {
expect(assessment_permission.requested).to include(access_request)
}
end
describe '#accept_permission_requested' do
context 'when the access request is for a participant' do
let(:access_request) {
create(:access_request, :with_participant_role)
}
let(:assessment) {
access_request.tool
}
let(:user) {
access_request.user
}
let(:assessment_permission) {
Assessments::Permission.new(assessment)
}
it {
expect(AccessGrantedNotificationWorker).not_to receive(:perform_async)
assessment_permission.accept_permission_requested(user)
}
end
context 'when the access request is not for a participant' do
let(:access_request) {
create(:access_request)
}
let(:assessment) {
access_request.tool
}
let(:user) {
access_request.user
}
let(:assessment_permission) {
Assessments::Permission.new(assessment)
}
it {
expect(AccessGrantedNotificationWorker).to receive(:perform_async)
assessment_permission.accept_permission_requested(user)
}
end
end
end
| 22.071547 | 121 | 0.596758 |
62e99bf794be0bf2a4739b9927901110cffb8024 | 909 | # This file was generated automatically by dotnet-releaser - DO NOT EDIT
class Allseer < Formula
desc "Package Description"
homepage "https://github.com/jorelius/AllSeer"
version "1.0.0"
license "MIT"
on_macos do
if Hardware::CPU.intel? && Hardware::CPU.is_64_bit?
url "https://github.com/jorelius/AllSeer/releases/download/v1.0.0/allseer.1.0.0.osx-x64.tar.gz"
sha256 "72dd13cc78ae38813d3c99f4b5002e729cf8e3344dcfcd6c7cfc7ffbeaebe0de"
def install
cp_r '.', bin
bin.install "allseer"
end
end
end
on_linux do
if Hardware::CPU.intel? && Hardware::CPU.is_64_bit?
url "https://github.com/jorelius/AllSeer/releases/download/v1.0.0/allseer.1.0.0.linux-x64.tar.gz"
sha256 "d7aeb604e543fe810fa2de437d2ac53a4d4b1c31a2b3ece61a3c9c545146015a"
def install
cp_r '.', bin
bin.install "allseer"
end
end
end
end
| 30.3 | 103 | 0.691969 |
26d82d4ea153d3e3b6dbc280064fd32910007dff | 58,233 | module ActiveRecord
# Raised by <tt>save!</tt> and <tt>create!</tt> when the record is invalid. Use the
# +record+ method to retrieve the record which did not validate.
# begin
# complex_operation_that_calls_save!_internally
# rescue ActiveRecord::RecordInvalid => invalid
# puts invalid.record.errors
# end
class RecordInvalid < ActiveRecordError
attr_reader :record
def initialize(record)
@record = record
errors = @record.errors.full_messages.join(I18n.t('support.array.words_connector', :default => ', '))
super(I18n.t('activerecord.errors.messages.record_invalid', :errors => errors))
end
end
class Error
attr_accessor :base, :attribute, :type, :message, :options
def initialize(base, attribute, type = nil, options = {})
self.base = base
self.attribute = attribute
self.type = type || :invalid
self.options = options
self.message = options.delete(:message) || self.type
end
def message
# When type is a string, it means that we do not have to do a lookup, because
# the user already sent the "final" message.
type.is_a?(String) ? type : generate_message(default_options)
end
def full_message
attribute.to_s == 'base' ? message : generate_full_message(default_options)
end
alias :to_s :message
def value
@base.respond_to?(attribute) ? @base.send(attribute) : nil
end
protected
# Translates an error message in it's default scope (<tt>activerecord.errrors.messages</tt>).
# Error messages are first looked up in <tt>models.MODEL.attributes.ATTRIBUTE.MESSAGE</tt>, if it's not there,
# it's looked up in <tt>models.MODEL.MESSAGE</tt> and if that is not there it returns the translation of the
# default message (e.g. <tt>activerecord.errors.messages.MESSAGE</tt>). The translated model name,
# translated attribute name and the value are available for interpolation.
#
# When using inheritence in your models, it will check all the inherited models too, but only if the model itself
# hasn't been found. Say you have <tt>class Admin < User; end</tt> and you wanted the translation for the <tt>:blank</tt>
# error +message+ for the <tt>title</tt> +attribute+, it looks for these translations:
#
# <ol>
# <li><tt>activerecord.errors.models.admin.attributes.title.blank</tt></li>
# <li><tt>activerecord.errors.models.admin.blank</tt></li>
# <li><tt>activerecord.errors.models.user.attributes.title.blank</tt></li>
# <li><tt>activerecord.errors.models.user.blank</tt></li>
# <li><tt>activerecord.errors.messages.blank</tt></li>
# <li>any default you provided through the +options+ hash (in the activerecord.errors scope)</li>
# </ol>
def generate_message(options = {})
keys = @base.class.self_and_descendants_from_active_record.map do |klass|
if (klass_name = klass.name)
[ :"models.#{klass_name.underscore}.attributes.#{attribute}.#{@message}",
:"models.#{klass_name.underscore}.#{@message}" ]
else
[]
end
end.flatten
keys << options.delete(:default)
keys << :"messages.#{@message}"
keys << @message if @message.is_a?(String)
keys << @type unless @type == @message
keys.compact!
options.merge!(:default => keys)
I18n.translate(keys.shift, options)
end
# Wraps an error message into a full_message format.
#
# The default full_message format for any locale is <tt>"%{attribute} %{message}"</tt>.
# One can specify locale specific default full_message format by storing it as a
# translation for the key <tt>:"activerecord.errors.full_messages.format"</tt>.
#
# Additionally one can specify a validation specific error message format by
# storing a translation for <tt>:"activerecord.errors.full_messages.[message_key]"</tt>.
# E.g. the full_message format for any validation that uses :blank as a message
# key (such as validates_presence_of) can be stored to <tt>:"activerecord.errors.full_messages.blank".</tt>
#
# Because the message key used by a validation can be overwritten on the
# <tt>validates_*</tt> class macro level one can customize the full_message format for
# any particular validation:
#
# # app/models/article.rb
# class Article < ActiveRecord::Base
# validates_presence_of :title, :message => :"title.blank"
# end
#
# # config/locales/en.yml
# en:
# activerecord:
# errors:
# full_messages:
# title:
# blank: This title is screwed!
def generate_full_message(options = {})
keys = [
:"full_messages.#{@message}",
:'full_messages.format',
'%{attribute} %{message}'
]
options.merge!(:default => keys, :message => self.message)
I18n.translate(keys.shift, options)
end
# Return user options with default options.
#
def default_options
options.reverse_merge :scope => [:activerecord, :errors],
:model => @base.class.human_name,
:attribute => @base.class.human_attribute_name(attribute.to_s),
:value => value
end
end
# Active Record validation is reported to and from this object, which is used by Base#save to
# determine whether the object is in a valid state to be saved. See usage example in Validations.
class Errors
include Enumerable
class << self
def default_error_messages
ActiveSupport::Deprecation.warn("ActiveRecord::Errors.default_error_messages has been deprecated. Please use I18n.translate('activerecord.errors.messages').")
I18n.translate 'activerecord.errors.messages'
end
end
def initialize(base) # :nodoc:
@base = base
clear
end
# Adds an error to the base object instead of any particular attribute. This is used
# to report errors that don't tie to any specific attribute, but rather to the object
# as a whole. These error messages don't get prepended with any field name when iterating
# with +each_full+, so they should be complete sentences.
def add_to_base(msg)
add(:base, msg)
end
# Adds an error message (+messsage+) to the +attribute+, which will be returned on a call to <tt>on(attribute)</tt>
# for the same attribute and ensure that this error object returns false when asked if <tt>empty?</tt>. More than one
# error can be added to the same +attribute+ in which case an array will be returned on a call to <tt>on(attribute)</tt>.
# If no +messsage+ is supplied, :invalid is assumed.
# If +message+ is a Symbol, it will be translated, using the appropriate scope (see translate_error).
#
def add(attribute, message = nil, options = {})
options[:message] = options.delete(:default) if options[:default].is_a?(Symbol)
error, message = message, nil if message.is_a?(Error)
@errors[attribute.to_s] ||= []
@errors[attribute.to_s] << (error || Error.new(@base, attribute, message, options))
end
# Will add an error message to each of the attributes in +attributes+ that is empty.
def add_on_empty(attributes, custom_message = nil)
for attr in [attributes].flatten
value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
is_empty = value.respond_to?(:empty?) ? value.empty? : false
add(attr, :empty, :default => custom_message) unless !value.nil? && !is_empty
end
end
# Will add an error message to each of the attributes in +attributes+ that is blank (using Object#blank?).
def add_on_blank(attributes, custom_message = nil)
for attr in [attributes].flatten
value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s]
add(attr, :blank, :default => custom_message) if value.blank?
end
end
# Returns true if the specified +attribute+ has errors associated with it.
#
# class Company < ActiveRecord::Base
# validates_presence_of :name, :address, :email
# validates_length_of :name, :in => 5..30
# end
#
# company = Company.create(:address => '123 First St.')
# company.errors.invalid?(:name) # => true
# company.errors.invalid?(:address) # => false
def invalid?(attribute)
!@errors[attribute.to_s].nil?
end
# Returns +nil+, if no errors are associated with the specified +attribute+.
# Returns the error message, if one error is associated with the specified +attribute+.
# Returns an array of error messages, if more than one error is associated with the specified +attribute+.
#
# class Company < ActiveRecord::Base
# validates_presence_of :name, :address, :email
# validates_length_of :name, :in => 5..30
# end
#
# company = Company.create(:address => '123 First St.')
# company.errors.on(:name) # => ["is too short (minimum is 5 characters)", "can't be blank"]
# company.errors.on(:email) # => "can't be blank"
# company.errors.on(:address) # => nil
def on(attribute)
attribute = attribute.to_s
return nil unless @errors.has_key?(attribute)
errors = @errors[attribute].map(&:to_s)
errors.size == 1 ? errors.first : errors
end
alias :[] :on
# Returns errors assigned to the base object through +add_to_base+ according to the normal rules of <tt>on(attribute)</tt>.
def on_base
on(:base)
end
# Yields each attribute and associated message per error added.
#
# class Company < ActiveRecord::Base
# validates_presence_of :name, :address, :email
# validates_length_of :name, :in => 5..30
# end
#
# company = Company.create(:address => '123 First St.')
# company.errors.each{|attr,msg| puts "#{attr} - #{msg}" }
# # => name - is too short (minimum is 5 characters)
# # name - can't be blank
# # address - can't be blank
def each
@errors.each_key { |attr| @errors[attr].each { |error| yield attr, error.message } }
end
# Yields each attribute and associated error per error added.
#
# class Company < ActiveRecord::Base
# validates_presence_of :name, :address, :email
# validates_length_of :name, :in => 5..30
# end
#
# company = Company.create(:address => '123 First St.')
# company.errors.each_error{|attr,err| puts "#{attr} - #{err.type}" }
# # => name - :too_short
# # name - :blank
# # address - :blank
def each_error
@errors.each_key { |attr| @errors[attr].each { |error| yield attr, error } }
end
# Yields each full error message added. So <tt>Person.errors.add("first_name", "can't be empty")</tt> will be returned
# through iteration as "First name can't be empty".
#
# class Company < ActiveRecord::Base
# validates_presence_of :name, :address, :email
# validates_length_of :name, :in => 5..30
# end
#
# company = Company.create(:address => '123 First St.')
# company.errors.each_full{|msg| puts msg }
# # => Name is too short (minimum is 5 characters)
# # Name can't be blank
# # Address can't be blank
def each_full
full_messages.each { |msg| yield msg }
end
# Returns all the full error messages in an array.
#
# class Company < ActiveRecord::Base
# validates_presence_of :name, :address, :email
# validates_length_of :name, :in => 5..30
# end
#
# company = Company.create(:address => '123 First St.')
# company.errors.full_messages # =>
# ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Address can't be blank"]
def full_messages(options = {})
@errors.values.inject([]) do |full_messages, errors|
full_messages + errors.map { |error| error.full_message }
end
end
# Returns true if no errors have been added.
def empty?
@errors.empty?
end
# Removes all errors that have been added.
def clear
@errors = ActiveSupport::OrderedHash.new
end
# Returns the total number of errors added. Two errors added to the same attribute will be counted as such.
def size
@errors.values.inject(0) { |error_count, attribute| error_count + attribute.size }
end
alias_method :count, :size
alias_method :length, :size
# Returns an XML representation of this error object.
#
# class Company < ActiveRecord::Base
# validates_presence_of :name, :address, :email
# validates_length_of :name, :in => 5..30
# end
#
# company = Company.create(:address => '123 First St.')
# company.errors.to_xml
# # => <?xml version="1.0" encoding="UTF-8"?>
# # <errors>
# # <error>Name is too short (minimum is 5 characters)</error>
# # <error>Name can't be blank</error>
# # <error>Address can't be blank</error>
# # </errors>
def to_xml(options={})
options[:root] ||= "errors"
options[:indent] ||= 2
options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
options[:builder].instruct! unless options.delete(:skip_instruct)
options[:builder].errors do |e|
full_messages.each { |msg| e.error(msg) }
end
end
def generate_message(attribute, message = :invalid, options = {})
Error.new(@base, attribute, message, options).to_s
end
end
# Please do have a look at ActiveRecord::Validations::ClassMethods for a higher level of validations.
#
# Active Records implement validation by overwriting Base#validate (or the variations, +validate_on_create+ and
# +validate_on_update+). Each of these methods can inspect the state of the object, which usually means ensuring
# that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).
#
# Example:
#
# class Person < ActiveRecord::Base
# protected
# def validate
# errors.add_on_empty %w( first_name last_name )
# errors.add("phone_number", "has invalid format") unless phone_number =~ /[0-9]*/
# end
#
# def validate_on_create # is only run the first time a new object is saved
# unless valid_discount?(membership_discount)
# errors.add("membership_discount", "has expired")
# end
# end
#
# def validate_on_update
# errors.add_to_base("No changes have occurred") if unchanged_attributes?
# end
# end
#
# person = Person.new("first_name" => "David", "phone_number" => "what?")
# person.save # => false (and doesn't do the save)
# person.errors.empty? # => false
# person.errors.count # => 2
# person.errors.on "last_name" # => "can't be empty"
# person.errors.on "phone_number" # => "has invalid format"
# person.errors.each_full { |msg| puts msg }
# # => "Last name can't be empty\n" +
# # "Phone number has invalid format"
#
# person.attributes = { "last_name" => "Heinemeier", "phone_number" => "555-555" }
# person.save # => true (and person is now saved in the database)
#
# An Errors object is automatically created for every Active Record.
module Validations
VALIDATIONS = %w( validate validate_on_create validate_on_update )
def self.included(base) # :nodoc:
base.extend ClassMethods
base.class_eval do
alias_method_chain :save, :validation
alias_method_chain :save!, :validation
end
base.send :include, ActiveSupport::Callbacks
base.define_callbacks *VALIDATIONS
end
# Active Record classes can implement validations in several ways. The highest level, easiest to read,
# and recommended approach is to use the declarative <tt>validates_..._of</tt> class methods (and
# +validates_associated+) documented below. These are sufficient for most model validations.
#
# Slightly lower level is +validates_each+. It provides some of the same options as the purely declarative
# validation methods, but like all the lower-level approaches it requires manually adding to the errors collection
# when the record is invalid.
#
# At a yet lower level, a model can use the class methods +validate+, +validate_on_create+ and +validate_on_update+
# to add validation methods or blocks. These are ActiveSupport::Callbacks and follow the same rules of inheritance
# and chaining.
#
# The lowest level style is to define the instance methods +validate+, +validate_on_create+ and +validate_on_update+
# as documented in ActiveRecord::Validations.
#
# == +validate+, +validate_on_create+ and +validate_on_update+ Class Methods
#
# Calls to these methods add a validation method or block to the class. Again, this approach is recommended
# only when the higher-level methods documented below (<tt>validates_..._of</tt> and +validates_associated+) are
# insufficient to handle the required validation.
#
# This can be done with a symbol pointing to a method:
#
# class Comment < ActiveRecord::Base
# validate :must_be_friends
#
# def must_be_friends
# errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
# end
# end
#
# Or with a block which is passed the current record to be validated:
#
# class Comment < ActiveRecord::Base
# validate do |comment|
# comment.must_be_friends
# end
#
# def must_be_friends
# errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
# end
# end
#
# This usage applies to +validate_on_create+ and +validate_on_update+ as well.
module ClassMethods
DEFAULT_VALIDATION_OPTIONS = {
:on => :save,
:allow_nil => false,
:allow_blank => false,
:message => nil
}.freeze
ALL_RANGE_OPTIONS = [ :is, :within, :in, :minimum, :maximum ].freeze
ALL_NUMERICALITY_CHECKS = { :greater_than => '>', :greater_than_or_equal_to => '>=',
:equal_to => '==', :less_than => '<', :less_than_or_equal_to => '<=',
:odd => 'odd?', :even => 'even?' }.freeze
# Validates each attribute against a block.
#
# class Person < ActiveRecord::Base
# validates_each :first_name, :last_name do |record, attr, value|
# record.errors.add attr, 'starts with z.' if value[0] == ?z
# end
# end
#
# Options:
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
# * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_each(*attrs)
options = attrs.extract_options!.symbolize_keys
attrs = attrs.flatten
# Declare the validation.
send(validation_method(options[:on] || :save), options) do |record|
attrs.each do |attr|
value = record.send(attr)
next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
yield record, attr, value
end
end
end
# Encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example:
#
# Model:
# class Person < ActiveRecord::Base
# validates_confirmation_of :user_name, :password
# validates_confirmation_of :email_address, :message => "should match confirmation"
# end
#
# View:
# <%= password_field "person", "password" %>
# <%= password_field "person", "password_confirmation" %>
#
# The added +password_confirmation+ attribute is virtual; it exists only as an in-memory attribute for validating the password.
# To achieve this, the validation adds accessors to the model for the confirmation attribute. NOTE: This check is performed
# only if +password_confirmation+ is not +nil+, and by default only on save. To require confirmation, make sure to add a presence
# check for the confirmation attribute:
#
# validates_presence_of :password_confirmation, :if => :password_changed?
#
# Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "doesn't match confirmation").
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_confirmation_of(*attr_names)
configuration = { :on => :save }
configuration.update(attr_names.extract_options!)
attr_accessor(*(attr_names.map { |n| "#{n}_confirmation" }))
validates_each(attr_names, configuration) do |record, attr_name, value|
unless record.send("#{attr_name}_confirmation").nil? or value == record.send("#{attr_name}_confirmation")
record.errors.add(attr_name, :confirmation, :default => configuration[:message])
end
end
end
# Encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example:
#
# class Person < ActiveRecord::Base
# validates_acceptance_of :terms_of_service
# validates_acceptance_of :eula, :message => "must be abided"
# end
#
# If the database column does not exist, the +terms_of_service+ attribute is entirely virtual. This check is
# performed only if +terms_of_service+ is not +nil+ and by default on save.
#
# Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "must be accepted").
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is true).
# * <tt>:accept</tt> - Specifies value that is considered accepted. The default value is a string "1", which
# makes it easy to relate to an HTML checkbox. This should be set to +true+ if you are validating a database
# column, since the attribute is typecast from "1" to +true+ before validation.
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_acceptance_of(*attr_names)
configuration = { :on => :save, :allow_nil => true, :accept => "1" }
configuration.update(attr_names.extract_options!)
db_cols = begin
column_names
rescue Exception # To ignore both statement and connection errors
[]
end
names = attr_names.reject { |name| db_cols.include?(name.to_s) }
attr_accessor(*names)
validates_each(attr_names,configuration) do |record, attr_name, value|
unless value == configuration[:accept]
record.errors.add(attr_name, :accepted, :default => configuration[:message])
end
end
end
# Validates that the specified attributes are not blank (as defined by Object#blank?). Happens by default on save. Example:
#
# class Person < ActiveRecord::Base
# validates_presence_of :first_name
# end
#
# The first_name attribute must be in the object and it cannot be blank.
#
# If you want to validate the presence of a boolean field (where the real values are true and false),
# you will want to use <tt>validates_inclusion_of :field_name, :in => [true, false]</tt>.
#
# This is due to the way Object#blank? handles boolean values: <tt>false.blank? # => true</tt>.
#
# Configuration options:
# * <tt>message</tt> - A custom error message (default is: "can't be blank").
# * <tt>on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>,
# <tt>:update</tt>).
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).
# The method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).
# The method, proc or string should return or evaluate to a true or false value.
#
def validates_presence_of(*attr_names)
configuration = { :on => :save }
configuration.update(attr_names.extract_options!)
# can't use validates_each here, because it cannot cope with nonexistent attributes,
# while errors.add_on_empty can
send(validation_method(configuration[:on]), configuration) do |record|
record.errors.add_on_blank(attr_names, configuration[:message])
end
end
# Validates that the specified attribute matches the length restrictions supplied. Only one option can be used at a time:
#
# class Person < ActiveRecord::Base
# validates_length_of :first_name, :maximum => 30
# validates_length_of :last_name, :maximum => 30, :message => "less than %{count} if you don't mind"
# validates_length_of :fax, :in => 7..32, :allow_nil => true
# validates_length_of :phone, :in => 7..32, :allow_blank => true
# validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name"
# validates_length_of :zip_code, :minimum => 5, :too_short => "please enter at least %{count} characters"
# validates_length_of :smurf_leader, :is => 4, :message => "papa is spelled with %{count} characters... don't play me"
# validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least %{count} words"), :tokenizer => lambda {|str| str.scan(/\w+/) }
# end
#
# Configuration options:
# * <tt>:minimum</tt> - The minimum size of the attribute.
# * <tt>:maximum</tt> - The maximum size of the attribute.
# * <tt>:is</tt> - The exact size of the attribute.
# * <tt>:within</tt> - A range specifying the minimum and maximum size of the attribute.
# * <tt>:in</tt> - A synonym(or alias) for <tt>:within</tt>.
# * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
# * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
# * <tt>:too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is %{count} characters)").
# * <tt>:too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is %{count} characters)").
# * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt> method and the attribute is the wrong size (default is: "is the wrong length (should be %{count} characters)").
# * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>, <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>:tokenizer</tt> - Specifies how to split up the attribute string. (e.g. <tt>:tokenizer => lambda {|str| str.scan(/\w+/)}</tt> to
# count words as in above example.)
# Defaults to <tt>lambda{ |value| value.split(//) }</tt> which counts individual characters.
def validates_length_of(*attrs)
# Merge given options with defaults.
options = {
:tokenizer => lambda {|value| value.split(//)}
}.merge(DEFAULT_VALIDATION_OPTIONS)
options.update(attrs.extract_options!.symbolize_keys)
# Ensure that one and only one range option is specified.
range_options = ALL_RANGE_OPTIONS & options.keys
case range_options.size
when 0
raise ArgumentError, 'Range unspecified. Specify the :within, :maximum, :minimum, or :is option.'
when 1
# Valid number of options; do nothing.
else
raise ArgumentError, 'Too many range options specified. Choose only one.'
end
# Get range option and value.
option = range_options.first
option_value = options[range_options.first]
key = {:is => :wrong_length, :minimum => :too_short, :maximum => :too_long}[option]
custom_message = options[:message] || options[key]
case option
when :within, :in
raise ArgumentError, ":#{option} must be a Range" unless option_value.is_a?(Range)
validates_each(attrs, options) do |record, attr, value|
value = options[:tokenizer].call(value) if value.kind_of?(String)
if value.nil? or value.size < option_value.begin
record.errors.add(attr, :too_short, :default => custom_message || options[:too_short], :count => option_value.begin)
elsif value.size > option_value.end
record.errors.add(attr, :too_long, :default => custom_message || options[:too_long], :count => option_value.end)
end
end
when :is, :minimum, :maximum
raise ArgumentError, ":#{option} must be a nonnegative Integer" unless option_value.is_a?(Integer) and option_value >= 0
# Declare different validations per option.
validity_checks = { :is => "==", :minimum => ">=", :maximum => "<=" }
validates_each(attrs, options) do |record, attr, value|
value = options[:tokenizer].call(value) if value.kind_of?(String)
unless !value.nil? and value.size.method(validity_checks[option])[option_value]
record.errors.add(attr, key, :default => custom_message, :count => option_value)
end
end
end
end
alias_method :validates_size_of, :validates_length_of
# Validates whether the value of the specified attributes are unique across the system. Useful for making sure that only one user
# can be named "davidhh".
#
# class Person < ActiveRecord::Base
# validates_uniqueness_of :user_name, :scope => :account_id
# end
#
# It can also validate whether the value of the specified attributes are unique based on multiple scope parameters. For example,
# making sure that a teacher can only be on the schedule once per semester for a particular class.
#
# class TeacherSchedule < ActiveRecord::Base
# validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
# end
#
# When the record is created, a check is performed to make sure that no record exists in the database with the given value for the specified
# attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.
#
# Configuration options:
# * <tt>:message</tt> - Specifies a custom error message (default is: "has already been taken").
# * <tt>:scope</tt> - One or more columns by which to limit the scope of the uniqueness constraint.
# * <tt>:case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (+true+ by default).
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
#
# === Concurrency and integrity
#
# Using this validation method in conjunction with ActiveRecord::Base#save
# does not guarantee the absence of duplicate record insertions, because
# uniqueness checks on the application level are inherently prone to race
# conditions. For example, suppose that two users try to post a Comment at
# the same time, and a Comment's title must be unique. At the database-level,
# the actions performed by these users could be interleaved in the following manner:
#
# User 1 | User 2
# ------------------------------------+--------------------------------------
# # User 1 checks whether there's |
# # already a comment with the title |
# # 'My Post'. This is not the case. |
# SELECT * FROM comments |
# WHERE title = 'My Post' |
# |
# | # User 2 does the same thing and also
# | # infers that his title is unique.
# | SELECT * FROM comments
# | WHERE title = 'My Post'
# |
# # User 1 inserts his comment. |
# INSERT INTO comments |
# (title, content) VALUES |
# ('My Post', 'hi!') |
# |
# | # User 2 does the same thing.
# | INSERT INTO comments
# | (title, content) VALUES
# | ('My Post', 'hello!')
# |
# | # ^^^^^^
# | # Boom! We now have a duplicate
# | # title!
#
# This could even happen if you use transactions with the 'serializable'
# isolation level. There are several ways to get around this problem:
# - By locking the database table before validating, and unlocking it after
# saving. However, table locking is very expensive, and thus not
# recommended.
# - By locking a lock file before validating, and unlocking it after saving.
# This does not work if you've scaled your Rails application across
# multiple web servers (because they cannot share lock files, or cannot
# do that efficiently), and thus not recommended.
# - Creating a unique index on the field, by using
# ActiveRecord::ConnectionAdapters::SchemaStatements#add_index. In the
# rare case that a race condition occurs, the database will guarantee
# the field's uniqueness.
#
# When the database catches such a duplicate insertion,
# ActiveRecord::Base#save will raise an ActiveRecord::StatementInvalid
# exception. You can either choose to let this error propagate (which
# will result in the default Rails exception page being shown), or you
# can catch it and restart the transaction (e.g. by telling the user
# that the title already exists, and asking him to re-enter the title).
# This technique is also known as optimistic concurrency control:
# http://en.wikipedia.org/wiki/Optimistic_concurrency_control
#
# Active Record currently provides no way to distinguish unique
# index constraint errors from other types of database errors, so you
# will have to parse the (database-specific) exception message to detect
# such a case.
def validates_uniqueness_of(*attr_names)
configuration = { :case_sensitive => true }
configuration.update(attr_names.extract_options!)
validates_each(attr_names,configuration) do |record, attr_name, value|
# The check for an existing value should be run from a class that
# isn't abstract. This means working down from the current class
# (self), to the first non-abstract class. Since classes don't know
# their subclasses, we have to build the hierarchy between self and
# the record's class.
class_hierarchy = [record.class]
while class_hierarchy.first != self
class_hierarchy.insert(0, class_hierarchy.first.superclass)
end
# Now we can work our way down the tree to the first non-abstract
# class (which has a database table to query from).
finder_class = class_hierarchy.detect { |klass| !klass.abstract_class? }
column = finder_class.columns_hash[attr_name.to_s]
if value.nil?
comparison_operator = "IS ?"
elsif column.text?
comparison_operator = "#{connection.case_sensitive_equality_operator} ?"
value = column.limit ? value.to_s.mb_chars[0, column.limit] : value.to_s
else
comparison_operator = "= ?"
end
sql_attribute = "#{record.class.quoted_table_name}.#{connection.quote_column_name(attr_name)}"
if value.nil? || (configuration[:case_sensitive] || !column.text?)
condition_sql = "#{sql_attribute} #{comparison_operator}"
condition_params = [value]
else
condition_sql = "LOWER(#{sql_attribute}) #{comparison_operator.sub('?', 'LOWER(?)')}"
condition_params = [value.to_s]
end
if scope = configuration[:scope]
Array(scope).map do |scope_item|
scope_value = record.send(scope_item)
condition_sql << " AND " << attribute_condition("#{record.class.quoted_table_name}.#{connection.quote_column_name(scope_item)}", scope_value)
condition_params << scope_value
end
end
unless record.new_record?
condition_sql << " AND #{record.class.quoted_table_name}.#{record.class.primary_key} <> ?"
condition_params << record.send(:id)
end
finder_class.with_exclusive_scope do
if finder_class.exists?([condition_sql, *condition_params])
record.errors.add(attr_name, :taken, :default => configuration[:message], :value => value)
end
end
end
end
# Validates whether the value of the specified attribute is of the correct form by matching it against the regular expression
# provided.
#
# class Person < ActiveRecord::Base
# validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
# end
#
# Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the string, <tt>^</tt> and <tt>$</tt> match the start/end of a line.
#
# A regular expression must be provided or else an exception will be raised.
#
# Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "is invalid").
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
# * <tt>:with</tt> - The regular expression used to validate the format with (note: must be supplied!).
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_format_of(*attr_names)
configuration = { :on => :save, :with => nil }
configuration.update(attr_names.extract_options!)
raise(ArgumentError, "A regular expression must be supplied as the :with option of the configuration hash") unless configuration[:with].is_a?(Regexp)
validates_each(attr_names, configuration) do |record, attr_name, value|
unless value.to_s =~ configuration[:with]
record.errors.add(attr_name, :invalid, :default => configuration[:message], :value => value)
end
end
end
# Validates whether the value of the specified attribute is available in a particular enumerable object.
#
# class Person < ActiveRecord::Base
# validates_inclusion_of :gender, :in => %w( m f )
# validates_inclusion_of :age, :in => 0..99
# validates_inclusion_of :format, :in => %w( jpg gif png ), :message => "extension %{value} is not included in the list"
# end
#
# Configuration options:
# * <tt>:in</tt> - An enumerable object of available items.
# * <tt>:message</tt> - Specifies a custom error message (default is: "is not included in the list").
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_inclusion_of(*attr_names)
configuration = { :on => :save }
configuration.update(attr_names.extract_options!)
enum = configuration[:in] || configuration[:within]
raise(ArgumentError, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum.respond_to?(:include?)
validates_each(attr_names, configuration) do |record, attr_name, value|
unless enum.include?(value)
record.errors.add(attr_name, :inclusion, :default => configuration[:message], :value => value)
end
end
end
# Validates that the value of the specified attribute is not in a particular enumerable object.
#
# class Person < ActiveRecord::Base
# validates_exclusion_of :username, :in => %w( admin superuser ), :message => "You don't belong here"
# validates_exclusion_of :age, :in => 30..60, :message => "This site is only for under 30 and over 60"
# validates_exclusion_of :format, :in => %w( mov avi ), :message => "extension %{value} is not allowed"
# end
#
# Configuration options:
# * <tt>:in</tt> - An enumerable object of items that the value shouldn't be part of.
# * <tt>:message</tt> - Specifies a custom error message (default is: "is reserved").
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_exclusion_of(*attr_names)
configuration = { :on => :save }
configuration.update(attr_names.extract_options!)
enum = configuration[:in] || configuration[:within]
raise(ArgumentError, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum.respond_to?(:include?)
validates_each(attr_names, configuration) do |record, attr_name, value|
if enum.include?(value)
record.errors.add(attr_name, :exclusion, :default => configuration[:message], :value => value)
end
end
end
# Validates whether the associated object or objects are all valid themselves. Works with any kind of association.
#
# class Book < ActiveRecord::Base
# has_many :pages
# belongs_to :library
#
# validates_associated :pages, :library
# end
#
# Warning: If, after the above definition, you then wrote:
#
# class Page < ActiveRecord::Base
# belongs_to :book
#
# validates_associated :book
# end
#
# this would specify a circular dependency and cause infinite recursion.
#
# NOTE: This validation will not fail if the association hasn't been assigned. If you want to ensure that the association
# is both present and guaranteed to be valid, you also need to use +validates_presence_of+.
#
# Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "is invalid")
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_associated(*attr_names)
configuration = { :on => :save }
configuration.update(attr_names.extract_options!)
validates_each(attr_names, configuration) do |record, attr_name, value|
unless (value.is_a?(Array) ? value : [value]).collect { |r| r.nil? || r.valid? }.all?
record.errors.add(attr_name, :invalid, :default => configuration[:message], :value => value)
end
end
end
# Validates whether the value of the specified attribute is numeric by trying to convert it to
# a float with Kernel.Float (if <tt>only_integer</tt> is false) or applying it to the regular expression
# <tt>/\A[\+\-]?\d+\Z/</tt> (if <tt>only_integer</tt> is set to true).
#
# class Person < ActiveRecord::Base
# validates_numericality_of :value, :on => :create
# end
#
# Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "is not a number").
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
# * <tt>:only_integer</tt> - Specifies whether the value has to be an integer, e.g. an integral value (default is +false+).
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is +false+). Notice that for fixnum and float columns empty strings are converted to +nil+.
# * <tt>:greater_than</tt> - Specifies the value must be greater than the supplied value.
# * <tt>:greater_than_or_equal_to</tt> - Specifies the value must be greater than or equal the supplied value.
# * <tt>:equal_to</tt> - Specifies the value must be equal to the supplied value.
# * <tt>:less_than</tt> - Specifies the value must be less than the supplied value.
# * <tt>:less_than_or_equal_to</tt> - Specifies the value must be less than or equal the supplied value.
# * <tt>:odd</tt> - Specifies the value must be an odd number.
# * <tt>:even</tt> - Specifies the value must be an even number.
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_numericality_of(*attr_names)
configuration = { :on => :save, :only_integer => false, :allow_nil => false }
configuration.update(attr_names.extract_options!)
numericality_options = ALL_NUMERICALITY_CHECKS.keys & configuration.keys
(numericality_options - [ :odd, :even ]).each do |option|
raise ArgumentError, ":#{option} must be a number" unless configuration[option].is_a?(Numeric)
end
validates_each(attr_names,configuration) do |record, attr_name, value|
raw_value = record.send("#{attr_name}_before_type_cast") || value
next if configuration[:allow_nil] and raw_value.nil?
if configuration[:only_integer]
unless raw_value.to_s =~ /\A[+-]?\d+\Z/
record.errors.add(attr_name, :not_a_number, :value => raw_value, :default => configuration[:message])
next
end
raw_value = raw_value.to_i
else
begin
raise ArgumentError if raw_value.to_s =~ /\A\s*0x/ # new rubies allow this, but we don't want it for compatibility
raw_value = Kernel.Float(raw_value)
rescue ArgumentError, TypeError
record.errors.add(attr_name, :not_a_number, :value => raw_value, :default => configuration[:message])
next
end
end
numericality_options.each do |option|
case option
when :odd, :even
unless raw_value.to_i.method(ALL_NUMERICALITY_CHECKS[option])[]
record.errors.add(attr_name, option, :value => raw_value, :default => configuration[:message])
end
else
record.errors.add(attr_name, option, :default => configuration[:message], :value => raw_value, :count => configuration[option]) unless raw_value.method(ALL_NUMERICALITY_CHECKS[option])[configuration[option]]
end
end
end
end
# Creates an object just like Base.create but calls save! instead of save
# so an exception is raised if the record is invalid.
def create!(attributes = nil, &block)
if attributes.is_a?(Array)
attributes.collect { |attr| create!(attr, &block) }
else
object = new(attributes)
yield(object) if block_given?
object.save!
object
end
end
private
def validation_method(on)
case on
when :save then :validate
when :create then :validate_on_create
when :update then :validate_on_update
end
end
end
# The validation process on save can be skipped by passing false. The regular Base#save method is
# replaced with this when the validations module is mixed in, which it is by default.
def save_with_validation(perform_validation = true)
if perform_validation && valid? || !perform_validation
save_without_validation
else
false
end
end
# Attempts to save the record just like Base#save but will raise a RecordInvalid exception instead of returning false
# if the record is not valid.
def save_with_validation!
if valid?
save_without_validation!
else
raise RecordInvalid.new(self)
end
end
# Runs +validate+ and +validate_on_create+ or +validate_on_update+ and returns true if no errors were added otherwise false.
def valid?
errors.clear
run_callbacks(:validate)
validate
if new_record?
run_callbacks(:validate_on_create)
validate_on_create
else
run_callbacks(:validate_on_update)
validate_on_update
end
errors.empty?
end
# Performs the opposite of <tt>valid?</tt>. Returns true if errors were added, false otherwise.
def invalid?
!valid?
end
# Returns the Errors object that holds all information about attribute error messages.
def errors
@errors ||= Errors.new(self)
end
protected
# Overwrite this method for validation checks on all saves and use <tt>Errors.add(field, msg)</tt> for invalid attributes.
def validate
end
# Overwrite this method for validation checks used only on creation.
def validate_on_create
end
# Overwrite this method for validation checks used only on updates.
def validate_on_update
end
end
end
| 50.549479 | 223 | 0.624783 |
21dd451ffb108f6f3247247cb34f4a0a3ebf6c30 | 1,383 | module AutomateApi
module Resource
class Endpoint < Hashie::Dash
property :path
property :collect
property :method, default: :get
property :klass, default: nil
property :alias, default: nil
end
class EndpointNotSupported < StandardError
def initialize(endpoint, klass)
super "Undefined api endpoint '#{endpoint}' for #{klass}.endpoints"
end
end
class EndpointCollection < Hashie::Mash
disable_warnings
end
module EndpointAddon
def self.included(base)
base.extend ClassMethods
end
def supports?(name)
self.class.supports?(name)
end
def supports!(name)
raise EndpointNotSupported.new(name, self.class) unless supports?(name)
end
module ClassMethods
def supports?(name)
!endpoint(name).nil?
end
def endpoint(name)
endpoints[name] || endpoint_alias(name)
end
def endpoint_alias(name)
ep = endpoints.select { |k,ep| ep.alias == name }.first
ep.last unless ep.nil?
end
def endpoints(args = nil)
@endpoints ||= EndpointCollection.new
args.each_pair do |name, config|
@endpoints[name] = Endpoint.new(config)
end unless args.nil?
@endpoints
end
end
end
end
end
| 22.672131 | 79 | 0.597252 |
eddba5e80ee60aad54a1758c71476f78dc165541 | 2,788 | # encoding: UTF-8
control 'V-219256' do
title "The Ubuntu operating system must generate audit records for
successful/unsuccessful uses of the fchmodat system call."
desc "Without generating audit records that are specific to the security and
mission needs of the organization, it would be difficult to establish,
correlate, and investigate the events relating to an incident or identify those
responsible for one.
Audit records can be generated from various components within the
information system (e.g., module or policy filter).
"
desc 'rationale', ''
desc 'check', "
Verify the Ubuntu operating system generates an audit record when
successful/unsuccessful attempts to use the \"fchmodat\" system call.
Check the configured audit rules with the following commands:
# sudo auditctl -l | grep fchmodat
-a always,exit -F arch=b32 -S fchmodat -F auid>=1000 -F auid!=-1 -k
perm_chng
-a always,exit -F arch=b64 -S fchmodat -F auid>=1000 -F auid!=-1 -k
perm_chng
If the command does not return lines that match the example or the lines
are commented out, this is a finding.
Note:
For 32-bit architectures, only the 32-bit specific output lines from the
commands are required.
The '-k' allows for specifying an arbitrary identifier and the string after
it does not need to match the example output above.
"
desc 'fix', "
Configure the audit system to generate an audit event for any
successful/unsuccessful use of the \"fchmodat\" system call.
Add or update the following rules in the \"/etc/audit/rules.d/stig.rules\"
file:
-a always,exit -F arch=b32 -S fchmodat -F auid>=1000 -F auid!=4294967295 -k
perm_chng
-a always,exit -F arch=b64 -S fchmodat -F auid>=1000 -F auid!=4294967295 -k
perm_chng
Notes: For 32-bit architectures, only the 32-bit specific entries are
required.
The \"root\" account must be used to view/edit any files in the
/etc/audit/rules.d/ directory.
In order to reload the rules file, issue the following command:
# sudo augenrules --load
"
impact 0.5
tag severity: 'medium'
tag gtitle: 'SRG-OS-000064-GPOS-00033'
tag satisfies: ['SRG-OS-000064-GPOS-00033', 'SRG-OS-000462-GPOS-00206']
tag gid: 'V-219256'
tag rid: 'SV-219256r508662_rule'
tag stig_id: 'UBTU-18-010333'
tag fix_id: 'F-20980r305097_fix'
tag cci: ['SV-109841', 'V-100737', 'CCI-000172']
tag nist: ['AU-12 c']
if os.arch == 'x86_64'
describe auditd.syscall('fchmodat').where { arch == 'b64' } do
its('action.uniq') { should eq ['always'] }
its('list.uniq') { should eq ['exit'] }
end
end
describe auditd.syscall('fchmodat').where { arch == 'b32' } do
its('action.uniq') { should eq ['always'] }
its('list.uniq') { should eq ['exit'] }
end
end
| 34 | 79 | 0.704089 |
39eb4e8952fb65cc5e39ee4202364fef08b524fc | 823 | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/enumerize/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Sergey Nartimov"]
gem.email = "[email protected]"
gem.description = %q{Enumerated attributes with I18n and ActiveRecord/Mongoid support}
gem.summary = %q{Enumerated attributes with I18n and ActiveRecord/Mongoid support}
gem.homepage = "https://github.com/twinslash/enumerize"
gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
gem.files = `git ls-files`.split("\n")
gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
gem.name = "enumerize"
gem.require_paths = ["lib"]
gem.version = Enumerize::VERSION
gem.add_dependency('activesupport', '>= 3.1.3')
end
| 41.15 | 90 | 0.646416 |
d5c86658e07185c831f0fe44caf68130efe169cc | 5,540 | # typed: false
# frozen_string_literal: true
require "formula"
require "missing_formula"
require "descriptions"
require "cli/parser"
require "search"
module Homebrew
extend T::Sig
module_function
extend Search
PACKAGE_MANAGERS = {
macports: ->(query) { "https://www.macports.org/ports.php?by=name&substr=#{query}" },
fink: ->(query) { "https://pdb.finkproject.org/pdb/browse.php?summary=#{query}" },
opensuse: ->(query) { "https://software.opensuse.org/search?q=#{query}" },
fedora: ->(query) { "https://apps.fedoraproject.org/packages/s/#{query}" },
debian: lambda { |query|
"https://packages.debian.org/search?keywords=#{query}&searchon=names&suite=all§ion=all"
},
ubuntu: lambda { |query|
"https://packages.ubuntu.com/search?keywords=#{query}&searchon=names&suite=all§ion=all"
},
}.freeze
sig { returns(CLI::Parser) }
def search_args
Homebrew::CLI::Parser.new do
description <<~EOS
Perform a substring search of cask tokens and formula names for <text>. If <text>
is flanked by slashes, it is interpreted as a regular expression.
The search for <text> is extended online to `homebrew/core` and `homebrew/cask`.
If no <text> is provided, list all locally available formulae (including tapped ones).
No online search is performed.
EOS
switch "--formula", "--formulae",
description: "Without <text>, list all locally available formulae (no online search is performed). " \
"With <text>, search online and locally for formulae."
switch "--cask", "--casks",
description: "Without <text>, list all locally available casks (including tapped ones, no online " \
"search is performed). With <text>, search online and locally for casks."
switch "--desc",
description: "Search for formulae with a description matching <text> and casks with "\
"a name matching <text>."
switch "--pull-request",
description: "Search for GitHub pull requests containing <text>."
switch "--open",
depends_on: "--pull-request",
description: "Search for only open GitHub pull requests."
switch "--closed",
depends_on: "--pull-request",
description: "Search for only closed GitHub pull requests."
package_manager_switches = PACKAGE_MANAGERS.keys.map { |name| "--#{name}" }
package_manager_switches.each do |s|
switch s,
description: "Search for <text> in the given package manager's list."
end
conflicts "--desc", "--pull-request"
conflicts "--open", "--closed"
conflicts(*package_manager_switches)
# TODO: (2.9) add `min: 1` when the `odeprecated`/`odisabled` for `brew search` with no arguments is removed
named_args :text_or_regex
end
end
def search
args = search_args.parse
if package_manager = PACKAGE_MANAGERS.find { |name,| args[:"#{name}?"] }
_, url = package_manager
exec_browser url.call(URI.encode_www_form_component(args.named.join(" ")))
return
end
if args.no_named?
if args.cask?
raise UsageError, "specifying both --formula and --cask requires <text>" if args.formula?
puts Formatter.columns(Cask::Cask.to_a.map(&:full_name).sort)
else
odeprecated "`brew search` with no arguments to output formulae", "`brew formulae`"
puts Formatter.columns(Formula.full_names.sort)
end
return
end
query = args.named.join(" ")
string_or_regex = query_regexp(query)
if args.desc?
search_descriptions(string_or_regex)
elsif args.pull_request?
only = if args.open? && !args.closed?
"open"
elsif args.closed? && !args.open?
"closed"
end
GitHub.print_pull_requests_matching(query, only)
else
remote_results = search_taps(query, silent: true)
local_formulae = search_formulae(string_or_regex)
remote_formulae = remote_results[:formulae]
all_formulae = local_formulae + remote_formulae
local_casks = search_casks(string_or_regex)
remote_casks = remote_results[:casks]
all_casks = local_casks + remote_casks
print_formulae = args.formula?
print_casks = args.cask?
print_formulae = print_casks = true if !print_formulae && !print_casks
ohai "Formulae", Formatter.columns(all_formulae) if print_formulae && all_formulae.any?
if print_casks && all_casks.any?
puts if args.formula? && all_formulae.any?
ohai "Casks", Formatter.columns(all_casks)
end
count = all_formulae.count + all_casks.count
if $stdout.tty? && (reason = MissingFormula.reason(query, silent: true)) && local_casks.exclude?(query)
if count.positive?
puts
puts "If you meant #{query.inspect} specifically:"
end
puts reason
end
odie "No formulae or casks found for #{query.inspect}." if count.zero?
end
return unless $stdout.tty?
return if args.no_named?
metacharacters = %w[\\ | ( ) [ ] { } ^ $ * + ?].freeze
return unless metacharacters.any? do |char|
args.named.any? do |arg|
arg.include?(char) && !arg.start_with?("/")
end
end
opoo <<~EOS
Did you mean to perform a regular expression search?
Surround your query with /slashes/ to search locally by regex.
EOS
end
end
| 35.063291 | 115 | 0.638087 |
e8cc7305d5bef80b2c51264c136d729c554aca2a | 3,197 | require "test_helper"
class DowntimeTest < ActiveSupport::TestCase
context "validations" do
should "validate presence of message" do
downtime = FactoryBot.build(:downtime, message: nil)
assert_not downtime.valid?
assert_includes downtime.errors[:message], "can't be blank"
end
should "validate presence of start time" do
downtime = FactoryBot.build(:downtime, start_time: nil)
assert_not downtime.valid?
assert_includes downtime.errors[:start_time], "can't be blank"
end
should "validate presence of end time" do
downtime = FactoryBot.build(:downtime, end_time: nil)
assert_not downtime.valid?
assert_includes downtime.errors[:end_time], "can't be blank"
end
should "validate presence of artefact" do
downtime = FactoryBot.build(:downtime, artefact: nil)
assert_not downtime.valid?
assert_includes downtime.errors[:artefact], "can't be blank"
end
should "validate end time is in future" do
downtime = FactoryBot.build(:downtime, end_time: Time.zone.yesterday)
assert_not downtime.valid?
assert_includes downtime.errors[:end_time], "must be in the future"
end
should "validate end time is in future only on create" do
downtime = FactoryBot.create(:downtime)
downtime.assign_attributes(start_time: Time.zone.today - 3, end_time: Time.zone.yesterday)
assert downtime.valid?
end
should "validate start time is earlier than end time" do
downtime = FactoryBot.build(:downtime, start_time: Time.zone.today + 2, end_time: Time.zone.today + 1)
assert_not downtime.valid?
assert_includes downtime.errors[:start_time], "must be earlier than end time"
end
end
context "for an artefact" do
should "be returned if found" do
downtime = FactoryBot.create(:downtime)
assert_equal downtime, Downtime.for(downtime.artefact)
end
should "be nil if not found" do
assert_nil Downtime.for(FactoryBot.build(:artefact))
end
end
context "publicising downtime" do
should "start at display_start_time" do
now = Time.zone.parse("2015-01-01")
Timecop.freeze(now) do
downtime = FactoryBot.build(:downtime)
downtime.start_time = Time.zone.parse("2015-01-02 03:00")
assert downtime.publicise?
downtime.start_time = Time.zone.parse("2015-01-01 21:00")
assert downtime.publicise?
downtime.start_time = Time.zone.parse("2015-01-03 00:00")
assert_not downtime.publicise?
end
end
should "stop after scheduled end time" do
Timecop.freeze(Time.zone.now + 10) do
downtime = FactoryBot.build(:downtime)
downtime.end_time = Time.zone.now - 1.minute
assert_not downtime.publicise?
end
end
end
context "#display_start_time" do
should "return the datetime of midnight the day before it's scheduled" do
downtime = FactoryBot.build(:downtime)
downtime.start_time = Time.zone.parse("2015-01-02 03:00")
expected_start_time = Time.zone.parse("2015-01-01 00:00")
assert_equal expected_start_time, downtime.display_start_time
end
end
end
| 31.343137 | 108 | 0.69096 |
018a934cf95728ad81cc6892e7ca0fd34219bfd0 | 1,148 | # Licensed to Elasticsearch B.V under one or more agreements.
# Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information
module Elasticsearch
module XPack
module API
module SQL
module Actions
# TODO: Description
#
# @option arguments [Hash] :body Use the `query` element to start a query. Use the `cursor` element to continue a query. (*Required*)
# @option arguments [String] :format a short version of the Accept header, e.g. json, yaml
#
# @see Execute SQL
#
def query(arguments={})
raise ArgumentError, "Required argument 'body' missing" unless arguments[:body]
valid_params = [
:format ]
method = Elasticsearch::API::HTTP_POST
path = "_sql"
params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params
body = arguments[:body]
perform_request(method, path, params, body).body
end
end
end
end
end
end
| 33.764706 | 143 | 0.610627 |
1d6e2cbbe0d86865192b37bb7e7044a9cf61a65e | 176 | require "thor"
module Hackerrank
module Thor
module Crawlers
end
module Generators
end
module Parsers
end
module Presenters
end
end
end
| 9.777778 | 21 | 0.647727 |
e9b59069628ceed80ec2372423ef236fa38775d2 | 484 | # frozen_string_literal: true
require "rails_helper"
module Renalware
module Letters
describe Letterhead, type: :model do
it :aggregate_failures do
is_expected.to validate_presence_of(:name)
is_expected.to validate_presence_of(:unit_info)
is_expected.to validate_presence_of(:trust_name)
is_expected.to validate_presence_of(:trust_caption)
is_expected.to respond_to(:include_pathology_in_letter_body?)
end
end
end
end
| 26.888889 | 69 | 0.739669 |
210fe66f637cee899b989930d4ee433845221aad | 11,008 | require 'msf/core'
require 'msf/base'
require 'msf/ui'
require 'msf/ui/console/framework_event_manager'
require 'msf/ui/console/command_dispatcher'
require 'msf/ui/console/table'
require 'find'
module Msf
module Ui
module Console
###
#
# This class implements a user interface driver on a console interface.
#
###
class Driver < Msf::Ui::Driver
ConfigCore = "framework/core"
ConfigGroup = "framework/ui/console"
DefaultPrompt = "%undmsf%clr"
DefaultPromptChar = "%clr>"
#
# The console driver processes various framework notified events.
#
include FrameworkEventManager
#
# The console driver is a command shell.
#
include Rex::Ui::Text::DispatcherShell
#
# Initializes a console driver instance with the supplied prompt string and
# prompt character. The optional hash can take extra values that will
# serve to initialize the console driver.
#
# The optional hash values can include:
#
# AllowCommandPassthru
#
# Whether or not unknown commands should be passed through and executed by
# the local system.
#
# RealReadline
#
# Whether or to use the system Readline or the RBReadline (default)
#
# HistFile
#
# Name of a file to store command history
#
def initialize(prompt = DefaultPrompt, prompt_char = DefaultPromptChar, opts = {})
# Choose a readline library before calling the parent
rl = false
rl_err = nil
begin
if(opts['RealReadline'])
require 'readline'
rl = true
end
rescue ::LoadError
rl_err = $!
end
# Default to the RbReadline wrapper
require 'readline_compatible' if(not rl)
histfile = opts['HistFile'] || Msf::Config.history_file
# Call the parent
super(prompt, prompt_char, histfile)
# Temporarily disable output
self.disable_output = true
# Load pre-configuration
load_preconfig
# Initialize attributes
self.framework = opts['Framework'] || Msf::Simple::Framework.create
# Initialize the user interface to use a different input and output
# handle if one is supplied
if (opts['LocalInput'] or opts['LocalOutput'])
init_ui( opts['LocalInput'], opts['LocalOutput'])
else
init_ui(Rex::Ui::Text::Input::Stdio.new, Rex::Ui::Text::Output::Stdio.new)
end
init_tab_complete
# Add the core command dispatcher as the root of the dispatcher
# stack
enstack_dispatcher(CommandDispatcher::Core)
# Report readline error if there was one..
if not rl_err.nil?
print_error("***")
print_error("* WARNING: Unable to load readline: #{rl_err}")
print_error("* Falling back to RbReadLine")
print_error("***")
end
# Add the database dispatcher if it is usable
if(framework.db.usable)
require 'msf/ui/console/command_dispatcher/db'
enstack_dispatcher(CommandDispatcher::Db)
else
print_error("***")
print_error("* WARNING: No database support: #{framework.db.error.class} #{framework.db.error}")
print_error("***")
end
begin
require 'openssl'
rescue ::LoadError
print_error("***")
print_error("* WARNING: No OpenSSL support. This is required by meterpreter payloads and many exploits")
print_error("* Please install the ruby-openssl package (apt-get install libopenssl-ruby on Debian/Ubuntu")
print_error("***")
end
# Register event handlers
register_event_handlers
# Load console-specific configuration
load_config(opts['Config'])
# Re-enable output
self.disable_output = false
# Load additional modules as necessary
self.framework.modules.add_module_path(opts['ModulePath'], false) if opts['ModulePath']
# Whether or not command passthru should be allowed
self.command_passthru = (opts['AllowCommandPassthru'] == false) ? false : true
# Disables "dangerous" functionality of the console
@defanged = opts['Defanged'] == true
# If we're defanged, then command passthru should be disabled
if @defanged
self.command_passthru = false
end
# Process things before we actually display the prompt and get rocking
on_startup
# Process the resource script
if opts['Resource'] and opts['Resource'].kind_of? Array
opts['Resource'].each { |r|
load_resource(r)
}
else
# If the opt is nil here, we load ~/.msf3/msfconsole.rc
load_resource(opts['Resource'])
end
end
#
# Loads configuration that needs to be analyzed before the framework
# instance is created.
#
def load_preconfig
begin
conf = Msf::Config.load
rescue
wlog("Failed to load configuration: #{$!}")
return
end
if (conf.group?(ConfigCore))
conf[ConfigCore].each_pair { |k, v|
on_variable_set(true, k, v)
}
end
end
#
# Loads configuration for the console.
#
def load_config(path=nil)
begin
conf = Msf::Config.load(path)
rescue
wlog("Failed to load configuration: #{$!}")
return
end
# If we have configuration, process it
if (conf.group?(ConfigGroup))
conf[ConfigGroup].each_pair { |k, v|
case k.downcase
when "activemodule"
run_single("use #{v}")
end
}
end
end
#
# Saves configuration for the console.
#
def save_config
# Build out the console config group
group = {}
if (active_module)
group['ActiveModule'] = active_module.fullname
end
# Save it
begin
Msf::Config.save(ConfigGroup => group)
rescue ::Exception
print_error("Failed to save console config: #{$!}")
end
end
#
# Processes the resource script file for the console.
#
def load_resource(path=nil)
path ||= File.join(Msf::Config.config_directory, 'msfconsole.rc')
return if not ::File.readable?(path)
lines = ::File.readlines(path)
while lines.length > 0
line = lines.shift
break if not line
line.strip!
next if line.length == 0
next if line =~ /^#/
if line =~ /^<ruby>/
buff = ''
while lines.length > 0
line = lines.shift
break if not line
break if line =~ /^<\/ruby>/
buff << line
end
if ! buff.empty?
print_status("resource (#{path})> Ruby Code (#{buff.length} bytes)")
begin
eval(buff, binding)
rescue ::Interrupt
raise $!
rescue ::Exception => e
print_error("resource (#{path})> Ruby Error: #{e.class} #{e} #{e.backtrace}")
end
end
else
print_line("resource (#{path})> #{line}")
run_single(line)
end
end
end
#
# Creates the resource script file for the console.
#
def save_resource(data, path=nil)
path ||= File.join(Msf::Config.config_directory, 'msfconsole.rc')
begin
rcfd = File.open(path, 'w')
rcfd.write(data)
rcfd.close
rescue ::Exception
end
end
#
# Called before things actually get rolling such that banners can be
# displayed, scripts can be processed, and other fun can be had.
#
def on_startup
# Check for modules that failed to load
if (framework.modules.failed.length > 0)
print_error("WARNING! The following modules could not be loaded!")
framework.modules.failed.each_pair do |file, err|
print_error("\t#{file}: #{err}")
end
end
framework.events.on_ui_start(Msf::Framework::Revision)
# Build the banner message
run_single("banner")
self.on_command_proc = Proc.new { |command| framework.events.on_ui_command(command) }
end
#
# Called when a variable is set to a specific value. This allows the
# console to do extra processing, such as enabling logging or doing
# some other kind of task. If this routine returns false it will indicate
# that the variable is not being set to a valid value.
#
def on_variable_set(glob, var, val)
case var.downcase
when "payload"
if (framework and framework.modules.valid?(val) == false)
return false
elsif (active_module)
active_module.datastore.clear_non_user_defined
elsif (framework)
framework.datastore.clear_non_user_defined
end
when "sessionlogging"
handle_session_logging(val) if (glob)
when "consolelogging"
handle_console_logging(val) if (glob)
when "loglevel"
handle_loglevel(val) if (glob)
end
end
#
# Called when a variable is unset. If this routine returns false it is an
# indication that the variable should not be allowed to be unset.
#
def on_variable_unset(glob, var)
case var.downcase
when "sessionlogging"
handle_session_logging('0') if (glob)
when "consolelogging"
handle_console_logging('0') if (glob)
when "loglevel"
handle_loglevel(nil) if (glob)
end
end
#
# The framework instance associated with this driver.
#
attr_reader :framework
#
# Whether or not commands can be passed through.
#
attr_reader :command_passthru
#
# The active module associated with the driver.
#
attr_accessor :active_module
#
# The active session associated with the driver.
#
attr_accessor :active_session
#
# If defanged is true, dangerous functionality, such as exploitation, irb,
# and command shell passthru is disabled. In this case, an exception is
# raised.
#
def defanged?
if @defanged
raise DefangedException
end
end
def stop
framework.events.on_ui_stop()
super
end
protected
attr_writer :framework # :nodoc:
attr_writer :command_passthru # :nodoc:
#
# If an unknown command was passed, try to see if it's a valid local
# executable. This is only allowed if command passthru has been permitted
#
def unknown_command(method, line)
[method, method+".exe"].each do |cmd|
if (command_passthru == true and Rex::FileUtils.find_full_path(cmd))
print_status("exec: #{line}")
print_line('')
self.busy = true
begin
io = ::IO.popen(line, "r")
io.each_line do |data|
print(data)
end
io.close
rescue ::Errno::EACCES, ::Errno::ENOENT
print_error("Permission denied exec: #{line}")
end
self.busy = false
return
end
end
super
end
##
#
# Handlers for various global configuration values
#
##
#
# SessionLogging.
#
def handle_session_logging(val)
if (val =~ /^(y|t|1)/i)
Msf::Logging.enable_session_logging(true)
print_line("Session logging will be enabled for future sessions.")
else
Msf::Logging.enable_session_logging(false)
print_line("Session logging will be disabled for future sessions.")
end
end
#
# ConsoleLogging.
#
def handle_console_logging(val)
if (val =~ /^(y|t|1)/i)
Msf::Logging.enable_log_source('console')
print_line("Console logging is now enabled.")
set_log_source('console')
rlog("\n[*] Console logging started: #{Time.now}\n\n", 'console')
else
rlog("\n[*] Console logging stopped: #{Time.now}\n\n", 'console')
unset_log_source
Msf::Logging.disable_log_source('console')
print_line("Console logging is now disabled.")
end
end
#
# This method handles adjusting the global log level threshold.
#
def handle_loglevel(val)
set_log_level(Rex::LogSource, val)
set_log_level(Msf::LogSource, val)
end
end
#
# This exception is used to indicate that functionality is disabled due to
# defanged being true
#
class DefangedException < ::Exception
def to_s
"This functionality is currently disabled (defanged mode)"
end
end
end
end
end
| 23.322034 | 109 | 0.696039 |
d5804d9e1c0d1a3e0ff0863b5c35e0e037f466ab | 584 | require 'dotenv'
Dotenv.load
NEXMO_API_KEY = ENV['NEXMO_API_KEY']
NEXMO_API_SECRET = ENV['NEXMO_API_SECRET']
VERIFY_REQUEST_ID = ENV['VERIFY_REQUEST_ID']
VERIFY_CODE = ENV['VERIFY_CODE']
require 'nexmo'
client = Nexmo::Client.new(
api_key: NEXMO_API_KEY,
api_secret: NEXMO_API_SECRET
)
response = client.verify.check(
request_id: VERIFY_REQUEST_ID,
code: VERIFY_CODE
)
# when the check is successful
if response.status == '0'
# the cost of this verification
puts response.price
# the currency ofthe cost
puts response.currency
else
puts response.error_text
end
| 19.466667 | 44 | 0.763699 |
e2901cdbb4d2abbbbc521a0aaf3ad441a164f060 | 324 | begin
puts 10/0
rescue => e
puts "\nYou broke the internets!"
puts e.class
end
#You broke the internets!
#ZeroDivisionError
#===============
class Person
def initialize(name)
raise ArgumentError, "\nNo name present, sucka!\n" if name.empty?
end
end
Joe = Person.new('') #notice the Argument error message
| 15.428571 | 69 | 0.67284 |
28c491f42e8e3eff9e93ecae109a78b10d1ca09f | 1,022 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(*Rails.groups)
require "mirror_theme"
module Dummy
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
| 37.851852 | 99 | 0.731898 |
b99d84d59c8ec40a3d25a716dc0e35f9fdd7dfd2 | 3,759 | # frozen_string_literal: true
require "test_helper"
#
# Some common specs for breakpoints
#
module BreakpointSpecs
def test_shows_breakpoint_enabled
assert_match @regexp, @output.string
end
def test_shows_breakpoint_hit
assert_match @regexp, @output.string
match = @output.string.match(@regexp)
assert_match(/^ Breakpoint #{match[:id]}\. First hit/, @output.string)
end
def test_shows_breakpoint_line
assert_match(/\=> \s*#{@line}:/, @output.string)
end
end
#
# Tests for breakpoint commands
#
class BreakpointsTest < Minitest::Test
def setup
super
@input = InputTester.new "break --delete-all"
@output = StringIO.new
end
def teardown
super
clean_remove_const(:Break1Example)
clean_remove_const(:Break2Example)
end
def width
Byebug.breakpoints.last.id.to_s.length
end
end
#
# Tests setting a breakpoint by line number
#
class SettingBreakpointsTestByLineNumber < BreakpointsTest
def setup
super
@input.add("break 8")
redirect_pry_io(@input, @output) { load test_file("break1") }
@line = 8
@regexp = / Breakpoint (?<id>\d+): #{test_file('break1')} @ 8 \(Enabled\)/
end
include BreakpointSpecs
end
#
# Tests setting a breakpoint in a method
#
class SettingBreakpointsTestByMethodId < BreakpointsTest
def setup
super
@input.add("break Break1Example#a")
redirect_pry_io(@input, @output) { load test_file("break1") }
@line = RUBY_VERSION >= "2.5.0" ? 8 : 7
@regexp = / Breakpoint (?<id>\d+): Break1Example#a \(Enabled\)/
end
include BreakpointSpecs
end
#
# Tests setting a breakpoint in a bang method
#
class SettingBreakpointsTestByMethodIdForBangMethods < BreakpointsTest
def setup
super
@input.add("break Break1Example#c!")
redirect_pry_io(@input, @output) { load test_file("break1") }
@line = RUBY_VERSION >= "2.5.0" ? 18 : 17
@regexp = / Breakpoint (?<id>\d+): Break1Example#c! \(Enabled\)/
end
include BreakpointSpecs
end
#
# Tests setting a breakpoint in a (non fully qualified) method
#
class SettingBreakpointsTestByMethodIdWithinContext < BreakpointsTest
def setup
super
@input.add("break #b")
redirect_pry_io(@input, @output) { load test_file("break2") }
@line = 9
@regexp = / Breakpoint (?<id>\d+): Break2Example#b \(Enabled\)/
end
include BreakpointSpecs
end
#
# Tests listing breakpoints
#
class ListingBreakpoints < BreakpointsTest
def setup
super
@input.add("break #b", "break")
redirect_pry_io(@input, @output) { load test_file("break2") }
end
def test_shows_all_breakpoints
assert_match(/Yes \s*Break2Example#b/, @output.string)
end
def test_properly_displays_breakpoint_list
assert_match(/ {#{width - 1}}# Enabled At/, @output.string)
assert_match(/ \d{#{width}} Yes Break2Example#b/, @output.string)
end
end
#
# Tests disabling breakpoints
#
class DisablingBreakpoints < BreakpointsTest
def setup
super
@input.add("break #b", "break --disable-all")
redirect_pry_io(@input, @output) { load test_file("break2") }
end
def test_shows_breakpoints_as_disabled
assert_match(/ {#{width - 1}}# Enabled At/, @output.string)
assert_match(/ \d{#{width}} No Break2Example#b/, @output.string)
end
end
#
# Tests that the break Ruby keyword does not conflict with the break command
#
class BreakInsideMultilineInput < BreakpointsTest
def setup
super
@input.add("2.times do |i|", "break 18 if i > 0", "end")
redirect_pry_io(@input, @output) { load test_file("break1") }
end
def test_it_is_ignored
assert_equal 0, Pry::Byebug::Breakpoints.size
end
def test_lets_input_be_properly_evaluated
assert_match(/=> 18/, @output.string)
end
end
| 22.111765 | 79 | 0.693269 |
f8a502719d464c23390d2e36b3cc0584c26e0369 | 1,371 | # coding: utf-8
Gem::Specification.new do |spec|
spec.name = "alembic-jekyll-theme"
spec.version = "3.0.4"
spec.authors = ["David Darnes"]
spec.email = ["[email protected]"]
spec.summary = %q{A Jekyll boilerplate theme designed to be a starting point for any Jekyll website.}
spec.description = "A Jekyll boilerplate theme designed to be a starting point for any Jekyll website. Rather than starting from scratch, this boilerplate is designed to get the ball rolling immediately."
spec.homepage = "https://alembic.darn.es"
spec.license = "MIT"
spec.metadata["plugin_type"] = "theme"
spec.files = `git ls-files -z`.split("\x0").select { |f| f.match(%r{^(assets|_layouts|_includes|_sass|LICENSE|README|sw|manifest)}i) }
spec.add_runtime_dependency "jekyll", "~> 3.6"
spec.add_runtime_dependency "jekyll-sitemap", "~> 0.13"
spec.add_runtime_dependency "jekyll-mentions", "~> 1.2"
spec.add_runtime_dependency "jekyll-paginate", "~> 1.1"
spec.add_runtime_dependency "jekyll-seo-tag", "~> 2.3"
spec.add_runtime_dependency "jekyll-redirect-from", "~> 0.12"
spec.add_runtime_dependency "jekyll-default-layout", "~> 0.1"
spec.add_runtime_dependency "jekyll-feed", "~> 0.9"
spec.add_runtime_dependency "jemoji", "~> 0.9"
spec.add_development_dependency "bundler", "~> 1.14"
end
| 45.7 | 208 | 0.687819 |
39fb0183554e49be32a8046597d427be9b6a53b5 | 363 | # frozen_string_literal: true
require_relative 'rails-route-checker/app_interface'
require_relative 'rails-route-checker/config_file'
require_relative 'rails-route-checker/loaded_app'
require_relative 'rails-route-checker/runner'
require_relative 'rails-route-checker/parsers/loader'
require_relative 'rails-route-checker/version'
module RailsRouteChecker; end
| 33 | 53 | 0.85124 |
1d6300f0541074143bf79da08d91b0b65028fc57 | 646 | # -*- coding: UTF-8 -*-
# Persian module
module Persian
# Persian Text class
# Digest Persian texts
class Text
# Replace english characters with it's key persian value on standard persian keyboard
# For now just support QWERTY keyboard
def self.english_to_persian_char(text)
EN_FA_KEYBOARD_CHAR.each { |k, v| text.gsub!(k, v) }
text
end
# Replace standard persian keyboard characters with it's key persian value on english keyboard
# For now just support QWERTY keyboard
def self.persian_to_english_char(text)
EN_FA_KEYBOARD_CHAR.each { |v, k| text.gsub!(k, v) }
text
end
end
end
| 28.086957 | 98 | 0.695046 |
280675348092b66f11bd7e0fe7356ac4e57ca7a4 | 377 | # frozen_string_literal: true
title 'maven archives profile'
control 'maven archive' do
impact 1.0
title 'should be installed'
describe file('/etc/default/maven.sh') do
it { should exist }
end
describe file('/usr/local/lib/apache-maven-3.8.3/bin/mvn') do
it { should exist }
end
describe file('/usr/local/bin/mvn') do
it { should exist }
end
end
| 19.842105 | 63 | 0.679045 |
b9b41ab24d95ddd101f6528e159cffe29ea3bcee | 118 | @trips.each do |trip|
json.set! trip.id do
json.partial! 'api/trips/trip-summary', trip: trip
end
end
| 19.666667 | 58 | 0.627119 |
bffb1059cd10e4e7826d29f36cc6c2155ae41ed0 | 671 |
def generate_flags
config = ''
if Gem::Version.new(node['prometheus']['version']) < Gem::Version.new('2.0.0-alpha.0')
# Generate cli opts for prometheus 1.x
node['prometheus']['flags'].each do |flag_key, flag_value|
config += "-#{flag_key}=#{flag_value} " if flag_value != ''
end
else
# Generate cli opts for prometheus 2.x & hopefully beyond if there are no changes
node['prometheus']['v2_cli_opts'].each do |opt_key, opt_value|
config += "--#{opt_key}=#{opt_value} " if opt_value != ''
end
node['prometheus']['v2_cli_flags'].each do |opt_flag|
config += "--#{opt_flag} " if opt_flag != ''
end
end
config
end
| 33.55 | 88 | 0.630402 |
7aa3d3bcbf7ac4fbb0b95ec549652a7b5c0dbc94 | 322 | require 'spec_helper'
module GitTransactor
describe EAD do
let(:ead_file_path) { 'spec/fixtures/ead/wag_108.xml' }
let(:ead) { GitTransactor::EAD.new(ead_file_path) }
describe '.eadid' do
it 'should return the correct eadid' do
expect(ead.eadid).to be == 'wag_108'
end
end
end
end
| 23 | 59 | 0.658385 |
6a8967b5d96933168a0f6502268f52ab7a7c6919 | 182 | RSpec.describe ArchiveMigration do
it "has a version number" do
expect(ArchiveMigration::VERSION).not_to be nil
end
it "testing" do
ArchiveMigration.recover
end
end
| 18.2 | 51 | 0.741758 |
bb3d1befed6bd4c4a5eff50e8f03522fa239b0ca | 1,366 | class Iojs < Formula
homepage "https://iojs.org/"
url "https://iojs.org/dist/v1.6.4/iojs-v1.6.4.tar.xz"
sha256 "bcbf57c1af6260980bed53f52d1d505eb09b8fa6f938ec70b415f363a96fdcdf"
bottle do
sha256 "7ba0151933b0e2a91296f5b0c9ae865a65d4b7ee729523427505c9095ef95449" => :yosemite
sha256 "d1e66bb417275d8a2b96c184508017b62fda6b726275d466efc70870b992ca21" => :mavericks
sha256 "b9fd2b1f888dfab437dfbd44dcc2ad8dc73b9d47e28ae79ba2f9c244949d3eab" => :mountain_lion
end
keg_only "iojs conflicts with node (which is currently more established)"
option "with-debug", "Build with debugger hooks"
option "with-icu4c", "Build with Intl (icu4c) support"
depends_on "pkg-config" => :build
depends_on "icu4c" => :optional
depends_on :python => :build
def install
args = %W[--prefix=#{prefix} --without-npm]
args << "--debug" if build.with? "debug"
args << "--with-intl=system-icu" if build.with? "icu4c"
system "./configure", *args
system "make", "install"
end
def caveats; <<-EOS.undent
iojs was installed without npm.
iojs currently requires a patched npm (i.e. not the npm installed by node).
EOS
end
test do
path = testpath/"test.js"
path.write "console.log('hello');"
output = `#{bin}/iojs #{path}`.strip
assert_equal "hello", output
assert_equal 0, $?.exitstatus
end
end
| 29.695652 | 95 | 0.707906 |
f7883d61ff0a8aa1b036e6eda99618a7e1525e6f | 1,173 | module Spree
module Admin
class ImagesController < ResourceController
before_action :load_product
before_action :load_edit_data, except: :index
create.before :set_viewable
update.before :set_viewable
private
def location_after_destroy
spree.admin_product_images_url(@product)
end
def location_after_save
spree.admin_product_images_url(@product)
end
def load_edit_data
@variants = @product.variants.map do |variant|
[variant.sku_and_options_text, variant.id]
end
@variants.insert(0, [Spree.t(:all), @product.master_id])
end
def set_viewable
@image.viewable_type = 'Spree::Variant'
@image.viewable_id = params[:image][:viewable_id]
end
def load_product
@product = scope.friendly.find(params[:product_id])
end
def scope
current_store.products
end
def collection_url
spree.admin_product_images_url
end
def model_class
Spree::Image
end
def collection
@collection ||= load_product.variant_images
end
end
end
end
| 21.722222 | 64 | 0.640239 |
1ad2f007089dc14f018c44cb938a21a2a18d9e08 | 2,000 | require 'thread'
module Celluloid
# Maintain a thread pool FOR SPEED!!
class InternalPool
attr_accessor :busy_size, :idle_size, :max_idle
def initialize
@pool = []
@mutex = Mutex.new
@busy_size = @idle_size = 0
reset
end
def reset
# TODO: should really adjust this based on usage
@max_idle = 16
end
# Get a thread from the pool, running the given block
def get(&block)
@mutex.synchronize do
begin
if @pool.empty?
thread = create
else
thread = @pool.shift
@idle_size -= 1
end
end until thread.status # handle crashed threads
@busy_size += 1
thread[:celluloid_queue] << block
thread
end
end
# Return a thread to the pool
def put(thread)
@mutex.synchronize do
if @pool.size >= @max_idle
thread[:celluloid_queue] << nil
else
clean_thread_locals(thread)
@pool << thread
@idle_size += 1
@busy_size -= 1
end
end
end
# Create a new thread with an associated queue of procs to run
def create
queue = Queue.new
thread = Thread.new do
while proc = queue.pop
begin
proc.call
rescue => ex
Logger.crash("thread crashed", ex)
end
put thread
end
end
thread[:celluloid_queue] = queue
thread
end
# Clean the thread locals of an incoming thread
def clean_thread_locals(thread)
thread.keys.each do |key|
next if key == :celluloid_queue
# Ruby seems to lack an API for deleting thread locals. WTF, Ruby?
thread[key] = nil
end
end
def shutdown
@mutex.synchronize do
@max_idle = 0
@pool.each do |thread|
thread[:celluloid_queue] << nil
end
end
end
end
self.internal_pool = InternalPool.new
end | 21.505376 | 74 | 0.557 |
21d015ba958849e0e567315e564817cfcb669f26 | 2,696 | #
# 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'
require 'fluent/configurable'
require 'fluent/system_config'
module Fluent
module Plugin
class Base
include Configurable
include SystemConfig::Mixin
State = Struct.new(:configure, :start, :stop, :before_shutdown, :shutdown, :after_shutdown, :close, :terminate)
def initialize
super
@_state = State.new(false, false, false, false, false, false, false, false)
end
def has_router?
false
end
def configure(conf)
super
@_state ||= State.new(false, false, false, false, false, false, false, false)
@_state.configure = true
self
end
def start
@_state.start = true
self
end
def stop
@_state.stop = true
self
end
def before_shutdown
@_state.before_shutdown = true
self
end
def shutdown
@_state.shutdown = true
self
end
def after_shutdown
@_state.after_shutdown = true
self
end
def close
@_state.close = true
self
end
def terminate
@_state.terminate = true
self
end
def configured?
@_state.configure
end
def started?
@_state.start
end
def stopped?
@_state.stop
end
def before_shutdown?
@_state.before_shutdown
end
def shutdown?
@_state.shutdown
end
def after_shutdown?
@_state.after_shutdown
end
def closed?
@_state.close
end
def terminated?
@_state.terminate
end
def inspect
# Plugin instances are sometimes too big to dump because it may have too many thins (buffer,storage, ...)
# Original commit comment says that:
# To emulate normal inspect behavior `ruby -e'o=Object.new;p o;p (o.__id__<<1).to_s(16)'`.
# https://github.com/ruby/ruby/blob/trunk/gc.c#L788
"#<%s:%014x>" % [self.class.name, '0x%014x' % (__id__ << 1)]
end
end
end
end
| 22.098361 | 117 | 0.598294 |
870f3142c8a2a5137480247aa592e7259406721b | 695 | Pod::Spec.new do |spec|
spec.name = "XColor"
spec.version = "0.3"
spec.summary = "XColor is a color handling extension for UIColor written in Swift."
spec.homepage = "https://github.com/jaumevn/XColor"
spec.license = { :type => "MIT", :file => "LICENSE" }
spec.source = { :git => "https://github.com/jaumevn/XColor.git", :tag => "#{spec.version}" }
spec.author = { "Jaume Vinas Navas" => "[email protected]" }
spec.ios.deployment_target = '8.0'
spec.watchos.deployment_target = '2.0'
spec.tvos.deployment_target = '9.0'
spec.macos.deployment_target = '10.9'
spec.swift_version = '5.0'
spec.source_files = 'Source/*.swift'
end
| 36.578947 | 100 | 0.627338 |
d51be525855f452ae14979466b13d9835c0ed51b | 2,662 | require 'active_support/core_ext/hash'
module RareMap
# RareMap::Options defines all available options of RareMap.
# @author Wei-Ming Wu
# @!attribute [r] opts
# @return [Hash] the details of options
class Options
# A default group name
DEFAULT_GROUP = 'default'
attr_reader :opts
# Creates a Options.
#
# @param raw_opts [Hash] the details of options
# @return [Options] a Options object
def initialize(raw_opts = {})
raw_opts ||= {}
raw_opts = raw_opts.with_indifferent_access
@opts = { group: DEFAULT_GROUP,
primary_key: {},
foreign_key: { suffix: nil, alias: {} } }.with_indifferent_access
if raw_opts.kind_of? Hash
if raw_opts[:group]
@opts[:group] = raw_opts[:group]
end
if raw_opts[:primary_key].kind_of? Hash
@opts[:primary_key] = raw_opts[:primary_key].select { |k, v| k.kind_of? String and v.kind_of? String }
end
if raw_opts[:foreign_key].kind_of? Hash and raw_opts[:foreign_key][:suffix].kind_of? String
@opts[:foreign_key][:suffix] = raw_opts[:foreign_key][:suffix]
end
if raw_opts[:foreign_key].kind_of? Hash and raw_opts[:foreign_key][:alias].kind_of? Hash
@opts[:foreign_key][:alias] = raw_opts[:foreign_key][:alias].select { |k, v| k.kind_of? String and v.kind_of? String }
end
if raw_opts[:group].kind_of? String
@opts[:group] = raw_opts[:group]
end
end
end
# Checks if this Options belongs to a group.
#
# @return [true, false] true if this Options contains a group, false otherwise
def group?
@opts[:group] != DEFAULT_GROUP
end
# Returns the name of this Options' group
#
# @return [String] the name of this Options' group
def group
@opts[:group] || DEFAULT_GROUP
end
# Returns the primary key of a table specified by this Options
#
# @return [String, nil] the primary key of a table specified by this Options
def find_primary_key_by_table(table_name)
@opts[:primary_key].values_at(table_name).first
end
# Returns the table of a foreign key specified by this Options
#
# @return [String, nil] the table of a foreign key specified by this Options
def find_table_by_foreign_key(column_name)
@opts[:foreign_key][:alias].values_at(column_name).first
end
# Returns the suffix of a foreign key should have
#
# @return [String, nil] the suffix of a foreign key should have
def fk_suffix
@opts[:foreign_key][:suffix]
end
end
end | 34.128205 | 129 | 0.634861 |
21bf89e43f806c3f354e9a016497e5cb218552bf | 753 | cask 'font-monoid-xtrasmall-dollar-0-1-l-nocalt' do
version :latest
sha256 :no_check
# github.com/larsenwork/monoid was verified as official when first introduced to the cask
url 'https://github.com/larsenwork/monoid/blob/release/Monoid-XtraSmall-Dollar-0-1-l-NoCalt.zip?raw=true'
name 'Monoid-XtraSmall-Dollar-0-1-l-NoCalt'
homepage 'http://larsenwork.com/monoid/'
font 'Monoid-Bold-XtraSmall-Dollar-0-1-l-NoCalt.ttf'
font 'Monoid-Italic-XtraSmall-Dollar-0-1-l-NoCalt.ttf'
font 'Monoid-Regular-XtraSmall-Dollar-0-1-l-NoCalt.ttf'
font 'Monoid-Retina-XtraSmall-Dollar-0-1-l-NoCalt.ttf'
caveats <<~EOS
#{token} is dual licensed with MIT and OFL licenses.
https://github.com/larsenwork/monoid/tree/master#license
EOS
end
| 37.65 | 107 | 0.749004 |
e95eb531c9b3627cc9dc2b9b20c9f4d8b398c774 | 1,815 | #-- copyright
# OpenProject Backlogs Plugin
#
# Copyright (C)2013-2014 the OpenProject Foundation (OPF)
# Copyright (C)2011 Stephan Eckardt, Tim Felgentreff, Marnen Laibow-Koser, Sandro Munda
# Copyright (C)2010-2011 friflaj
# Copyright (C)2010 Maxime Guilbot, Andrew Vit, Joakim Kolsjö, ibussieres, Daniel Passos, Jason Vasquez, jpic, Emiliano Heyns
# Copyright (C)2009-2010 Mark Maglana
# Copyright (C)2009 Joe Heck, Nate Lowrie
#
# 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 Backlogs is a derivative work based on ChiliProject Backlogs.
# The copyright follows:
# Copyright (C) 2010-2011 - Emiliano Heyns, Mark Maglana, friflaj
# Copyright (C) 2011 - Jens Ulferts, Gregor Schmidt - Finn GmbH - Berlin, Germany
#
# 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 doc/COPYRIGHT.rdoc for more details.
#++
require_dependency 'work_package'
module OpenProject::Bcf::Patches::WorkPackagePatch
def self.included(base)
base.class_eval do
has_one :bcf_issue, class_name: 'Bcf::Issue', foreign_key: 'work_package_id'
end
end
end
| 40.333333 | 125 | 0.761983 |
f8c4fc9b67a133991474b3377107229b47283951 | 1,096 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'basher/version'
Gem::Specification.new do |spec|
spec.name = "basher-basher"
spec.version = Basher::VERSION
spec.authors = ["shuriu"]
spec.email = ["[email protected]"]
spec.summary = %q{Small CLI text game that tests your typing speed.}
spec.homepage = "https://github.com/shuriu/basher"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "bin"
spec.executables = ["basher"]
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.11"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "minitest", "~> 5.0"
spec.add_development_dependency "pry"
spec.add_development_dependency "binding_of_caller"
spec.add_development_dependency "pry-byebug"
spec.add_dependency "curtis", "~> 0.1.3"
spec.add_dependency "artii", "~> 2.1.1"
end
| 36.533333 | 104 | 0.662409 |
035345e3410fe915bc565d679bc27486fd45bf92 | 1,308 | class AddOauth2Tables < ActiveRecord::Migration
def self.up
create_table 'oauth_clients', :force => true do |t|
t.string 'name'
t.string 'oauth_identifier', :null => false
t.string 'oauth_secret', :null => false
t.string 'oauth_redirect_uri'
end
create_table 'oauth_authorization_codes', :force => true do |t|
t.integer 'authorization_id', :null => false
t.string 'code', :null => false
t.datetime 'expires_at'
t.datetime 'created_at'
t.datetime 'updated_at'
t.string 'redirect_uri'
end
create_table 'oauth_authorizations', :force => true do |t|
t.integer 'client_id', :null => false
t.integer 'resource_owner_id'
t.string 'resource_owner_type'
t.string 'scope'
t.datetime 'expires_at'
end
create_table 'oauth_access_tokens', :force => true do |t|
t.integer 'authorization_id', :null => false
t.string 'access_token', :null => false
t.string 'refresh_token'
t.datetime 'expires_at'
t.datetime 'created_at'
t.datetime 'updated_at'
end
end
def self.down
drop_table 'oauth_access_tokens'
drop_table 'oauth_authorizations'
drop_table 'oauth_authorization_codes'
drop_table 'oauth_clients'
end
end
| 29.727273 | 67 | 0.644495 |
7a3d40e905f3d29999f6f421b7508ee04d986683 | 2,871 | require "test_helper"
class StructUpdateNonExistentAttributeTest < Minitest::Test
class Chassis < FormObj::Struct
attribute :brakes
end
class Team < FormObj::Struct
attribute :name
attribute :cars, array: true do
attribute :code, primary_key: true
attribute :driver
attribute :chassis, class: 'StructUpdateNonExistentAttributeTest::Chassis'
end
end
def setup
@team = Team.new(
name: 'McLaren',
cars: [{
code: '275 F1',
driver: 'Villoresi',
chassis: {
brakes: :disc,
}
}],
)
end
def test_that_error_is_raised_when_try_to_update_non_existent_attribute
assert_raises(FormObj::UnknownAttributeError) { @team.update_attributes(a: 1) }
assert_raises(FormObj::UnknownAttributeError) { @team.update_attributes(cars: [{a: 1}]) }
assert_raises(FormObj::UnknownAttributeError) { @team.update_attributes(cars: [{chassis: {a: 1}}]) }
end
def test_that_error_is_raised_when_try_to_update_non_existent_attribute_with_parameter_raise_if_not_found_equal_to_true
assert_raises(FormObj::UnknownAttributeError) { @team.update_attributes({a: 1}, raise_if_not_found: true) }
assert_raises(FormObj::UnknownAttributeError) { @team.update_attributes({cars: [{a: 1}]}, raise_if_not_found: true) }
assert_raises(FormObj::UnknownAttributeError) { @team.update_attributes({cars: [{chassis: {a: 1}}]}, raise_if_not_found: true) }
end
def test_that_non_existent_attribute_is_ignored_when_try_to_update_it_with_parameter_raise_if_not_found_equal_to_false
assert_same(@team, @team.update_attributes({
name: 'Ferrari',
a: 1,
cars: [{
code: '275 F1',
b: 2,
chassis: {
brakes: :drum,
c: 3
}
}],
}, raise_if_not_found: false))
assert_equal('Ferrari', @team.name)
assert_equal(1, @team.cars.size)
assert_equal('275 F1', @team.cars[0].code)
assert_equal('Villoresi', @team.cars[0].driver)
assert_equal(:drum, @team.cars[0].chassis.brakes)
assert_raises(NoMethodError) { @team.a }
assert_raises(NoMethodError) { @team.cars[0].b }
assert_raises(NoMethodError) { @team.cars[0].chassis.c }
end
end
| 39.875 | 132 | 0.53396 |
61ae68d95ee234174515a594c0490a6ea7cc3062 | 331 | class CreateTaxonConfirmations < ActiveRecord::Migration[5.1]
def change
create_table :taxon_confirmations do |t|
t.integer :taxid
t.integer :sample_id
t.integer :user_id
t.string :strength # "watched" or "confirmed"
t.index [:sample_id, :strength, :taxid]
t.timestamps
end
end
end
| 23.642857 | 61 | 0.667674 |
79d7a920e5d877c8371540bda9c56587d39b8402 | 4,950 | #-- encoding: UTF-8
#-- 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 'journal_formatter'
require 'redmine/acts/journalized/format_hooks'
require 'open_project/journal_formatter/diff'
require 'open_project/journal_formatter/attachment'
require 'open_project/journal_formatter/custom_field'
# The ActiveRecord model representing journals.
class LegacyJournal < ActiveRecord::Base
include Comparable
include JournalFormatter
include JournalDeprecated
include FormatHooks
# Make sure each journaled model instance only has unique version ids
validates_uniqueness_of :version, scope: [:journaled_id, :type]
# Define a default class_name to prevent `uninitialized constant Journal::Journaled`
# subclasses will be given an actual class name when they are created by aaj
#
# e.g. IssueJournal will get class_name: 'Issue'
belongs_to :journaled, class_name: 'Journal'
belongs_to :user
register_journal_formatter :diff, OpenProject::JournalFormatter::Diff
register_journal_formatter :attachment, OpenProject::JournalFormatter::Attachment
register_journal_formatter :custom_field, OpenProject::JournalFormatter::CustomField
# "touch" the journaled object on creation
after_create :touch_journaled_after_creation
# Scopes to all journals excluding the initial journal - useful for change
# logs like the history on issue#show
scope :changing, -> {
where(['version > 1'])
}
# let all child classes have Journal as it's model name
# used to not having to create another route for every subclass of Journal
def self.inherited(child)
child.instance_eval do
def model_name
Journal.model_name
end
end
super
end
def touch_journaled_after_creation
journaled.touch
end
# In conjunction with the included Comparable module, allows comparison of journal records
# based on their corresponding version numbers, creation timestamps and IDs.
def <=>(other)
[version, created_at, id].map(&:to_i) <=> [other.version, other.created_at, other.id].map(&:to_i)
end
# Returns whether the version has a version number of 1. Useful when deciding whether to ignore
# the version during reversion, as initial versions have no serialized changes attached. Helps
# maintain backwards compatibility.
def initial?
version < 2
end
# The anchor number for html output
def anchor
version - 1
end
# Possible shortcut to the associated project
def project
if journaled.respond_to?(:project)
journaled.project
elsif journaled.is_a? Project
journaled
end
end
def editable_by?(user)
journaled.journal_editable_by?(user)
end
def details
attributes['changed_data'] || {}
end
# TODO Evaluate whether this can be removed without disturbing any migrations
alias_method :changed_data, :details
def new_value_for(prop)
details[prop.to_s].last if details.keys.include? prop.to_s
end
def old_value_for(prop)
details[prop.to_s].first if details.keys.include? prop.to_s
end
# Returns a string of css classes
def css_classes
s = 'journal'
s << ' has-notes' unless notes.blank?
s << ' has-details' unless details.empty?
s
end
# This is here to allow people to disregard the difference between working with a
# Journal and the object it is attached to.
# The lookup is as follows:
## => Call super if the method corresponds to one of our attributes (will end up in AR::Base)
## => Try the journaled object with the same method and arguments
## => On error, call super
def method_missing(method, *args, &block)
return super if respond_to?(method) || attributes[method.to_s]
journaled.send(method, *args, &block)
rescue NoMethodError => e
e.name == method ? super : raise(e)
end
end
| 33.445946 | 101 | 0.745859 |
bf8cfe5b44f5eca27b399185015c130ea629bb98 | 144 | # Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_youtubeAudio_session'
| 36 | 82 | 0.8125 |
6aeeb2bd0cac5a3ddf6b306f343b7a61670c131d | 15,453 | # frozen_string_literal: true
module Engine
module Game
module G18Dixie
module Companies
AUCTIONABLE_PRIVATE_DESCRIPTION = 'Auctionable'
AUCTIONABLE_PRIVATE_DESC_DETAIL = 'This private cannot be purchased, it may instead be put up for auction as a SR action'
POOL_PRIVATE_DESCRIPTION = 'Buyable Private'
POOL_PRIVATE_DESC_DETAIL = 'This private may be purchased for its face value as a SR action'
POOL_PRIVATE_ABILITY = Ability::Description.new(
type: 'description',
description: POOL_PRIVATE_DESCRIPTION,
desc_detail: POOL_PRIVATE_DESC_DETAIL
)
COMPANIES = [
# Available SR1
{
name: 'P1: Atlanta, Valdosta & Western Rwy.',
sym: 'P1',
value: 20,
revenue: 5,
desc: 'Owner may allow a Corporation controlled by the owner to lay a tile in a river hex at no cost. '\
'This can be an extra tile lay if desired. Taking this action closes the Private Company.',
abilities: [
{ type: 'description', description: AUCTIONABLE_PRIVATE_DESCRIPTION, desc_detail: AUCTIONABLE_PRIVATE_DESC_DETAIL },
],
color: nil,
},
{
name: 'P2: Atlanta, St. Andrews Bay Railway Co.',
sym: 'P2',
value: 30,
revenue: 10,
desc: 'Owner may place a +$10 token on any city or town within 4 hexes of Dothan (L14). Place the other token on '\
'the assigned Corporation\'s charter during its operating turn. The token adds +$10 to the value of the city '\
'for all trains that Corporation runs to the tokened city or town. This income bonus *never expires* and can '\
'never be given or sold to another railroad. It can be inherited by the SCL or ICG if assigned to the '\
'predecessor Corporations. Assigning the token to a Corporation closes the Private Company',
abilities: [
{ type: 'description', description: AUCTIONABLE_PRIVATE_DESCRIPTION, desc_detail: AUCTIONABLE_PRIVATE_DESC_DETAIL },
],
color: nil,
},
{
name: 'P3: Atlanta & West Point Railroad',
sym: 'P3',
value: 50,
revenue: 15,
desc: 'This Private Company reserves a token slot in Atlanta. A placeholder token is placed as soon as the Private '\
'Company is purchased. This token blocks routes. During a Corporation\'s operating turn, the owner of this '\
'Private Company may place an extra free token in Atlanta replacing the placeholder token with an extra '\
'Corporation\s token that they control. This extra token may be transferred to the SCL or ICG if it belonged '\
'to a predecessor company. Exchanging the token closes the Private Company. If the placeholder token is not '\
'prior to the start of phase 6 when the Minor Companies close, it is removed from Atlanta and any Corporation '\
'may place a token there, using normal token placement rules',
abilities: [
{ type: 'description', description: AUCTIONABLE_PRIVATE_DESCRIPTION, desc_detail: AUCTIONABLE_PRIVATE_DESC_DETAIL },
],
color: nil,
},
{
name: 'P4: Derrick, Carver & Thomas, RR Accountants',
sym: 'P4',
value: 50,
revenue: 10,
desc: 'At any time during a company\'s operating turn, or just prior to a stock round, the owner may take the '\
'priority deal from the current holder (including themself) and an extra immediate payment of $10 from the '\
'bank. Taking this action closes the Private Company.',
abilities: [
{ type: 'description', description: AUCTIONABLE_PRIVATE_DESCRIPTION, desc_detail: AUCTIONABLE_PRIVATE_DESC_DETAIL },
],
color: nil,
},
{
name: 'P5: Alabama Great Southern Railroad',
sym: 'P5',
value: 80,
revenue: 10,
desc: 'The owner may use this Private Company to allow a Corporation they are president of to purchase a train from '\
'the depot for 50% of the listed prive *at any time* during that operating companys turn. This is an '\
'exception to rule [4.7] regarding when trains can be bought. If this option is used prior to the purchase '\
'of the first 6+1 train, it counts as the only allowed train purchase from the depot by that company. '\
'Using this special ability closes the Private Company',
abilities: [
{ type: 'description', description: AUCTIONABLE_PRIVATE_DESCRIPTION, desc_detail: AUCTIONABLE_PRIVATE_DESC_DETAIL },
],
color: nil,
},
{
name: 'P6: South Carolina Canal and Rail Road Company',
sym: 'P6',
value: 140,
revenue: 0,
desc: 'The purchaser of this Private Company immediately receives teh 20% president\'s certificate of the Southern '\
'Railway. The owner then immediately sets the par value for the Southern Railway, places 3 regular shares '\
'of the Southern Railway into the Open Market (thus it is floated and will operate with no further '\
'share purchases), and discards this Private Company. As long as this Private Company is in the game and '\
'unbought, the Southern Railway\'s president\'s share is reserved.',
abilities: [{ type: 'shares', shares: 'SR_0' },
{
type: 'description',
description: AUCTIONABLE_PRIVATE_DESCRIPTION,
desc_detail: AUCTIONABLE_PRIVATE_DESC_DETAIL,
}],
color: nil,
},
# Available SR2
{
name: 'P7: New Athens Yards',
sym: 'P7',
value: 100,
revenue: 15,
desc: 'The owner of this Private Company may assign one or two spare parts tokens to any existing trains owned by '\
'a Corporation of which they are the president. This must be done during the Corporation\'s operating turn. '\
'The spare parts tokens give the trains delayed obsolecense as described in section [4.6]. If assigning two '\
'tokens, both tokens must be assigned at the same time and to the same non-permanent train. Assigning either '\
'or both tokens closes the Private Company. THese tokens cannot be reassigned to another train but the trains '\
'can transfer to the SCL or ICG if previously assigned to a train owned by a predecessor. Once assigned '\
'to a train, that train cannot be sold to any other Corporation.',
abilities: [
{ type: 'description', description: AUCTIONABLE_PRIVATE_DESCRIPTION, desc_detail: AUCTIONABLE_PRIVATE_DESC_DETAIL },
],
color: nil,
},
{
name: 'P8: "Pan American" Pullman Service',
sym: 'P8',
value: 50,
revenue: 15,
desc: 'Comes with an assignable +$20/+$30 Pan American token which can be placed on any train belonging to a '\
'Corporation at any time. Placing the token closes the Private Company and adds to the income of a run. '\
'The +$30 side is used if assigned to a train owned by the IC, Frisco, ACL or WRA. The +$20 side is '\
'used if assigned to a train owned by all other companies. Once placed on a train, this token can never be '\
'transferred, nor can that train be sold to any other Corporation, although it could be inherited by the '\
'SCL (if placed on a 5 Train). If neither token has been placed when phase 6 begins, this ability is lost. '\
'The token is removed as soon as the train it was assigned to is scrapped.',
abilities: [
{ type: 'description', description: AUCTIONABLE_PRIVATE_DESCRIPTION, desc_detail: AUCTIONABLE_PRIVATE_DESC_DETAIL },
],
color: nil,
},
{
name: 'P9: Dixie Flyer Pullman Service',
sym: 'P9',
value: 110,
revenue: 5,
desc: 'This Private Company comes with a 1D+1 Train. When the Private Companies close at the start of Phase 6, the '\
'owner may assign the 1D+1 train to a Corporation that they are president of at no cost. It may not be '\
'assigned to a Corporation at any other time. If the owner chooses not to assign the train to a Corporation, '\
'it is removed from the game. If the 1D+1 Train causes the owning company to exceed its train limit, its '\
'President must choose a train to be discarded. If the 1D+1 is discarded, it is removed from the game '\
'instead of being placed in the Open Market',
abilities: [
{ type: 'description', description: AUCTIONABLE_PRIVATE_DESCRIPTION, desc_detail: AUCTIONABLE_PRIVATE_DESC_DETAIL },
],
color: nil,
},
{
name: 'P10: Western Railway of Alabama',
sym: 'P10',
value: 150,
revenue: 0,
desc: 'The purchaser of this Private Company immediately receives teh 20% president\'s certificate of the WRA '\
'. The owner then immediately sets the par value for the WRA, places 3 regular shares of the '\
'WRA into the Open Market (thus it is floated and will operate with no further share purchases), '\
'and discards this Private Company. As long as this Private Company is in the game and unbought, the WRA'\
'\'s president\'s share is reserved.',
abilities: [
{ type: 'shares', shares: 'WRA_0' },
],
color: nil,
},
{
sym: ' 1',
value: 90,
revenue: 0,
name: 'M1: Georgia & Florida Railroad',
color: 'black',
desc: 'Closes at the end of OR2.1. '\
'Is exchanged for a preferred share of SR, which gets the minor\'s token and treasury',
text_color: 'white',
},
{
sym: ' 2',
value: 120,
revenue: 0,
name: 'M2: Tennessee Central Railway',
color: 'black',
desc: 'Closes at the end of OR2.1. '\
'Is exchanged for a preferred share of L&N or SR, which gets the minor\'s token and treasury',
text_color: 'white',
},
{
sym: ' 3',
value: 90,
revenue: 0,
name: 'M3: Missisippi Central Railroad',
color: 'black',
desc: 'Closes at the end of OR2.1. '\
'Is exchanged for a preferred share of Frisco, which gets the minor\'s token and treasury',
text_color: 'white',
},
{
sym: ' 4',
value: 80,
revenue: 0,
name: 'M4: Alabama & Tenessee River Railroad',
color: 'black',
desc: 'Closes at the end of OR2.1. '\
'Is exchanged for a preferred share of WRA, which gets the minor\'s token and treasury',
text_color: 'white',
},
{
sym: ' 5',
value: 100,
revenue: 0,
name: 'M5: Tallahassee Railroad',
color: 'black',
desc: 'Closes at the end of OR2.2. '\
'Is exchanged for a preferred share of SAL, which gets the minor\'s token and treasury',
text_color: 'white',
},
{
sym: ' 6',
value: 100,
revenue: 0,
name: 'M6: Atlanta, Birmingham & Coast Railroad',
color: 'black',
desc: 'Closes at the end of OR2.2. '\
'Is exchanged for a preferred share of ACL, which gets the minor\'s token and treasury',
text_color: 'white',
},
{
sym: ' 7',
value: 100,
revenue: 0,
name: 'M7: Western & Atlantic Railroad',
color: 'black',
desc: 'Closes at the end of OR2.2. '\
'Is exchanged for a preferred share of L&B, which gets the minor\'s token and treasury',
text_color: 'white',
},
{
sym: ' 8',
value: 100,
revenue: 0,
name: 'M8: Georgia Railroad',
color: 'black',
desc: 'Closes at the end of OR2.2. '\
'Is exchanged for a preferred share of CoG, which gets the minor\'s token and treasury',
text_color: 'white',
},
{
sym: ' 9',
value: 120,
revenue: 0,
name: 'M9: Nashville, Chattanooga & St. Louis Railway',
color: 'black',
desc: 'Closes at the end of OR3.1. '\
'Is exchanged for a preferred share of L&N, which gets the minor\'s token and treasury. '\
'Has a choice of starting location',
text_color: 'white',
},
{
sym: '10',
value: 120,
revenue: 0,
name: 'M10: Gulf, Mobile & Ohio Railroad',
color: 'black',
desc: 'Closes at the end of OR3.1. '\
'Is exchanged for a preferred share of IC, which gets the minor\'s token and treasury',
text_color: 'white',
},
{
sym: '11',
value: 120,
revenue: 0,
name: 'M11: Mobile & Ohio Railroad',
color: 'black',
desc: 'Closes at the end of OR3.1. '\
'Is exchanged for a preferred share of IC, which gets the minor\'s token and treasury',
text_color: 'white',
},
{
sym: '12',
value: 120,
revenue: 0,
name: 'M12: Memphis & Charleston RR',
color: 'black',
desc: 'Closes at the end of OR3.1. '\
'Is exchanged for a preferred share of Cog, Frisco, or WRA, '\
'which gets the minor\'s token and treasury. '\
'Has a choice of starting location',
text_color: 'white',
},
{
sym: '13',
value: 140,
revenue: 0,
name: 'M13: New Orleans and Texas RR',
color: 'black',
desc: 'Closes at the end of OR3.1. '\
'Is exchanged for any any remaining preferred share, '\
'the corresponding corporation gets the minor\'s token and treasury',
text_color: 'white',
},
].freeze
end
end
end
end
| 44.151429 | 130 | 0.545331 |
265af2ec1e30ca467460a8f6757d04273f2bd615 | 1,152 | require('rspec')
require('anagram')
require('pry')
describe('#anagram') do
it("checks if two words are anagrams") do
obj = Anagram.new("words", "sword")
expect(obj.anagram_checker).to(eq("These words are anagrams."))
end
it("checks if two words with different cases are anagrams") do
obj = Anagram.new("Words", "Sword")
expect(obj.anagram_checker).to(eq("These words are anagrams."))
end
it("checks if two words both contain vowels") do
obj = Anagram.new("Wrds", "Swrd")
expect(obj.anagram_checker).to(eq("You need to input actual words!"))
end
it("checks if the two words are antigrams") do
obj = Anagram.new("Banana", "Shoe")
expect(obj.anagram_checker).to(eq("These words have no letter matches and are antigrams."))
end
it("checks if two sentences are anagrams or antigrams") do
obj = Anagram.new("The Morse Code", "Here come dots!")
expect(obj.anagram_checker).to(eq("These sentences are anagrams."))
end
it("checks if words contain three letters in row") do
obj = Anagram.new("helllo", "ollleh")
expect(obj.anagram_checker).to(eq("You need to input actual words!"))
end
end | 38.4 | 95 | 0.689236 |
791e758acd0a9c0faf8629b56746b11ddbd2c4d3 | 360 | # frozen_string_literal: true
module Officevibe
Error = Class.new(StandardError)
InvalidAuthToken = Class.new(Officevibe::Error)
class ClientMiddleware < Faraday::Response::Middleware
def on_complete(env)
case env[:status]
when 302
raise Officevibe::InvalidAuthToken, JSON.parse(env.body)["message"]
end
end
end
end
| 22.5 | 75 | 0.708333 |
33c01b20c6f2bf27c27c0c1de1a90c90e8f87fcb | 3,498 | class ZooKeeper
# this is the default watcher provided by the zookeeper connection
# and is used to monitor all watch events on any paths
# watchers are implemented by adding the :watch => true flag to
# any #children or #get or #exists calls
# you never really need to initialize this yourself
class EventHandler
import org.apache.zookeeper.Watcher if defined?(JRUBY_VERSION)
# @private
# :nodoc:
attr_accessor :zk
# @private
# :nodoc:
def initialize(zookeeper_client)
@zk = zookeeper_client
@callbacks = Hash.new { |h,k| h[k] = [] }
end
# register a path with the handler
# your block will be called with all events on that path.
# aliased as #subscribe
# @param [String] path the path you want to listen to
# @param [Block] block the block to execute when a watch event happpens
# @yield [connection, event] We will call your block with the connection the
# watch event occured on and the event object
# @return [ZooKeeper::EventHandlerSubscription] the subscription object
# you can use to to unsubscribe from an event
# @see ZooKeeper::WatcherEvent
# @see ZooKeeper::EventHandlerSubscription
def register(path, &block)
EventHandlerSubscription.new(self, path, block).tap do |subscription|
@callbacks[path] << subscription
end
end
alias :subscribe :register
# registers a "state of the connection" handler
# @param [String] state the state you want to register for
# @param [Block] block the block to execute on state changes
# @yield [connection, event] yields your block with
def register_state_handler(state, &block)
register("state_#{state}", &block)
end
# @deprecated use #unsubscribe on the subscription object
# @see ZooKeeper::EventHandlerSubscription#unsubscribe
def unregister_state_handler(*args)
if args.first.is_a?(EventHandlerSubscription)
unregister(args.first)
else
unregister("state_#{args.first}", args[1])
end
end
# @deprecated use #unsubscribe on the subscription object
# @see ZooKeeper::EventHandlerSubscription#unsubscribe
def unregister(*args)
if args.first.is_a?(EventHandlerSubscription)
subscription = args.first
elsif args.first.is_a?(String) and args[1].is_a?(EventHandlerSubscription)
subscription = args[1]
else
path, index = args[0..1]
@callbacks[path][index] = nil
return
end
ary = @callbacks[subscription.path]
if index = ary.index(subscription)
ary[index] = nil
end
end
alias :unsubscribe :unregister
if defined?(JRUBY_VERSION)
# @private
# :nodoc:
def process(event)
handle_process(ZooKeeper::WatcherEvent.new(event.type.getIntValue, event.state.getIntValue, event.path))
end
else
# @private
# :nodoc:
def process(event)
handle_process(event)
end
end
protected
def handle_process(event)
if event.path and !event.path.empty? and @callbacks[event.path]
@callbacks[event.path].each do |callback|
callback.call(event, @zk) if callback.respond_to?(:call)
end
elsif (!event.path || event.path.empty?) and @callbacks["state_#{event.state}"]
@callbacks["state_#{event.state}"].each do |callback|
callback.call(event, @zk) if callback.respond_to?(:call)
end
end
end
end
end
| 33.314286 | 112 | 0.664666 |
e2e912258e7cb540121b2e052b0499908c5b186a | 51 | module SugoiWebpageCapture
VERSION = "0.0.3"
end
| 12.75 | 26 | 0.745098 |
e2ff607434821c7f530631107c43607e9f981d46 | 427 | before do
@errors = Array.new
end
get '/login' do
erb :"/login/index"
end
post '/login' do
user = User.find_by(username: params[:user][:username])
if user && user.authenticate(params[:user][:password])
session[:user_id] = user.id
redirect "/questions"
else
@errors << "Invalid Username or Password, BRO!"
erb :"/login/index"
end
end
get '/logout' do
session[:user_id] = nil
redirect '/'
end
| 17.08 | 57 | 0.64637 |
037b7d4f5b8e13429ccf199143a3f9cfb29ff173 | 177 | class AddFieldsToUsers < ActiveRecord::Migration[4.2]
def change
add_column :users, :research_interests, :text
add_column :users, :organisation_id, :integer
end
end
| 25.285714 | 53 | 0.751412 |
33cd151062238a840242d5594eb15b80510053fd | 944 | cask 'lightproxy' do
version '1.1.27'
sha256 'a37df94cbd771e2547924dc31002c7e139dfd1d757aaedb94573cf03b1cda1b4'
# github.com/alibaba/lightproxy/ was verified as official when first introduced to the cask
url "https://github.com/alibaba/lightproxy/releases/download/v#{version}/LightProxy-#{version}.dmg"
appcast 'https://github.com/alibaba/lightproxy/releases.atom'
name 'LightProxy'
homepage 'https://alibaba.github.io/lightproxy/'
app 'LightProxy.app'
uninstall_postflight do
stdout, * = system_command '/usr/bin/security',
args: ['find-certificate', '-a', '-c', 'LigthProxy', '-Z'],
sudo: true
hashes = stdout.lines.grep(%r{^SHA-256 hash:}) { |l| l.split(':').second.strip }
hashes.each do |h|
system_command '/usr/bin/security',
args: ['delete-certificate', '-Z', h],
sudo: true
end
end
end
| 37.76 | 101 | 0.630297 |
1c838f5bbab594027aedc8513092e02a7801a022 | 557 | module Fog
module Aliyun
class Storage
class Real
# Initiate a multipart upload
#
# @param bucket_name [String] Name of bucket to create
# @param object_name [String] Name of object to create
# @param options [Hash]
#
# @see https://help.aliyun.com/document_detail/31992.html
#
def initiate_multipart_upload(bucket_name, object_name, options = {})
@oss_protocol.initiate_multipart_upload(bucket_name, object_name, options)
end
end
end
end
end
| 27.85 | 84 | 0.626571 |
1129a8f2df47d8122221f130348d417d4153ea6e | 179 | # frozen_string_literal: true
require 'set'
module Ped
DOMAINS = File.readlines(File.join(File.dirname(__FILE__), 'domains.txt'))
.map(&:strip)
.to_set
.freeze
end
| 17.9 | 76 | 0.692737 |
4a968f7bd3d0324706b342bcd54e3723862c4424 | 563 | # # encoding: utf-8
if os[:family] == 'redhat'
describe file('/etc/sysconfig/atop') do
it { should be_file }
its('content') { should match "LOGPATH" }
its('content') { should match "INTERVAL" }
end
elsif os[:family] == 'debian'
describe file('/etc/default/atop') do
it { should be_file }
its('content') { should match "LOGPATH" }
its('content') { should match "INTERVAL" }
end
end
describe package('atop') do
it { should be_installed }
end
describe service('atop') do
it { should be_enabled }
it { should be_running }
end
| 22.52 | 46 | 0.642984 |
7a0577512ed2b8e2e7a877764baefe4a095141a9 | 324 | require 'wgif/cli'
require 'wgif/converter'
require 'wgif/download_bar'
require 'wgif/downloader'
require 'wgif/exceptions'
require 'wgif/gif_maker'
require 'wgif/installer'
require 'wgif/info_displayer'
require 'wgif/uploader'
require 'wgif/validator'
require 'wgif/version'
require 'wgif/video'
require 'wgif/video_cache'
| 23.142857 | 29 | 0.799383 |
6ab34b2b15b31ed686dd35984418d1f7e37db18d | 4,119 | require 'spec_helper'
describe Article::Page, dbscope: :example do
let(:node) { create :article_node_page }
describe ".new_size_input" do
let!(:form) { create(:cms_form, cur_site: cms_site, state: 'public', sub_type: 'static') }
let!(:file1) do
SS::File.create_empty!(
cur_user: cms_user, site_id: cms_site.id, model: "article/page", filename: "logo.png", content_type: 'image/png'
) do |file|
::FileUtils.cp("#{Rails.root}/spec/fixtures/ss/logo.png", file.path)
end
end
let!(:file2) do
SS::File.create_empty!(
cur_user: cms_user, site_id: cms_site.id, model: "article/page", filename: "logo.png", content_type: 'image/png'
) do |file|
::FileUtils.cp("#{Rails.root}/spec/fixtures/ss/logo.png", file.path)
end
end
let!(:column1) { create(:cms_column_free, cur_form: form, order: 1) }
let!(:column2) { create(:cms_column_file_upload, cur_form: form, order: 1, file_type: 'image', html_tag: "a+img") }
let!(:html_size) { html.bytesize }
let!(:file_size1) { File.size(file1.path) }
let!(:file_size2) { File.size(file2.path) }
context "with html only" do
let!(:html) { "<h1>SHIRASAGI</h1>" }
let!(:item) { create :article_page, cur_node: node, html: html }
it do
expect(item.size).to eq html_size
end
end
context "with block html only" do
let!(:html) { item.try(:render_html).presence || item.try(:html) }
let!(:item) do
create(
:article_page, cur_node: node, form: form,
column_values: [
column1.value_type.new(column: column1, value: "<p>#{unique_id}</p><script>#{unique_id}</script>")
]
)
end
it do
expect(item.size).to eq html_size
end
end
context "with thumbnail only" do
let!(:item) { create :article_page, cur_node: node, thumb: file1 }
it do
expect(item.size).to eq file_size1
end
end
context "with file only" do
let!(:item) { create :article_page, cur_node: node, file_ids: [file1.id] }
it do
expect(item.size).to eq file_size1
end
end
context "with block file only" do
let!(:item) do
create(
:article_page, cur_node: node, form: form,
column_values: [
column2.value_type.new(
column: column2, html_tag: column2.html_tag, file: file1,
file_label: "<p>#{unique_id}</p><script>#{unique_id}</script>",
text: Array.new(2) { "<p>#{unique_id}</p><script>#{unique_id}</script>" }.join("\n"),
image_html_type: "thumb", link_url: "http://#{unique_id}.example.jp/"
)
]
)
end
let!(:value) { item.try(:render_html).presence || item.try(:html) }
it do
expect(item.size).to eq value.bytesize + file_size1
end
end
context "with html and thumbnail and file" do
let!(:html) { "<h1>SHIRASAGI</h1>" }
let!(:item) { create :article_page, cur_node: node, html: html, thumb: file1, file_ids: [file2.id] }
it do
expect(item.size).to eq html_size + file_size1 + file_size2
end
end
context "with block html and thumbnail and file" do
let!(:item) do
create(
:article_page, cur_node: node, form: form, thumb: file1,
column_values: [
column2.value_type.new(
column: column2, html_tag: column2.html_tag, file: file2,
file_label: "<p>#{unique_id}</p><script>#{unique_id}</script>",
text: Array.new(2) { "<p>#{unique_id}</p><script>#{unique_id}</script>" }.join("\n"),
image_html_type: "thumb", link_url: "http://#{unique_id}.example.jp/"
)
]
)
end
let!(:value) { item.try(:render_html).presence || item.try(:html) }
it do
expect(item.size).to eq value.bytesize + file_size1 + file_size2
end
end
end
end
| 34.613445 | 121 | 0.563972 |
acc721ce2fbe6b301ba5c70c81dcaa42238e5066 | 1,373 | class UsersController < ApplicationController
def edit
@user = User.find_by_id UserParams.build(params).fetch(:id)
end
# we should allow logged in users to update their pending_organisation_id
# and only superadmins should be allowed to update organisation_id
# makes me think of a attributes permissions matrix
def update
usr = User.find_by_id UserParams.build(params).fetch(:id)
UserOrganisationClaimer.new(self, usr, usr).call(UserParams.build(params).fetch(:pending_organisation_id))
end
def update_message_for_admin_status
org = Organisation.find(UserParams.build(params).fetch(:pending_organisation_id))
flash[:notice] = "You have requested admin status for #{org.name}"
send_email_to_superadmin_about_request_for_admin_of org # could be moved to an hook on the user model?
redirect_to organisation_path(UserParams.build(params).fetch(:pending_organisation_id))
end
def send_email_to_superadmin_about_request_for_admin_of org
superadmin_emails = User.superadmins.pluck(:email)
AdminMailer.new_user_waiting_for_approval(org.name, superadmin_emails).deliver_now
end
class UserParams
def self.build params
params.permit(
:id,
:email,
:password,
:password_confirmation,
:remember_me,
:pending_organisation_id
)
end
end
end
| 35.205128 | 110 | 0.744355 |
e8af712bcd896c26cb35e7cdc43088bfb6d4cf3b | 2,740 | require File.expand_path("../../Requirements/php-meta-requirement", __FILE__)
class PhpCodeSniffer < Formula
desc "Check coding standards in PHP, JavaScript and CSS"
homepage "https://pear.php.net/package/PHP_CodeSniffer"
url "http://download.pear.php.net/package/PHP_CodeSniffer-3.1.1.tgz"
sha256 "b69af3322937cdb866332b653da591eedf947e025b2b363e60991cf49db43f8c"
bottle do
cellar :any_skip_relocation
sha256 "e42e61fe8a96c2f8ac2c31aeb7426f589e93da54e6165c58c892e532b80ee88d" => :high_sierra
sha256 "e42e61fe8a96c2f8ac2c31aeb7426f589e93da54e6165c58c892e532b80ee88d" => :sierra
sha256 "e42e61fe8a96c2f8ac2c31aeb7426f589e93da54e6165c58c892e532b80ee88d" => :el_capitan
end
depends_on PhpMetaRequirement
def phpcs_standards
etc+name+"Standards"
end
def phpcs_script_name
"phpcs"
end
def phpcbf_script_name
"phpcbf"
end
def install
prefix.install Dir["PHP_CodeSniffer-#{version}/*"]
if File.symlink? libexec+phpcs_script_name
File.delete libexec+phpcs_script_name
end
libexec.install_symlink prefix+"bin"+phpcs_script_name
if File.symlink? libexec+phpcbf_script_name
File.delete libexec+phpcbf_script_name
end
libexec.install_symlink prefix+"bin"+phpcbf_script_name
# Remove Windows batch files
File.delete bin+"phpcbf.bat"
File.delete bin+"phpcs.bat"
# Make sure the config file is preserved on upgrades. We do that
# be substituting @data_dir@ with #{etc} and making sure the
# folder #{etc}/PHP_CodeSniffer exists.
if File.exist?(prefix+"CodeSniffer.conf")
(etc+"PHP_CodeSniffer").mkpath
inreplace "#{prefix}/CodeSniffer.conf", /@data_dir@/, etc
end
# Create a place for other formulas to link their standards.
phpcs_standards.mkpath
# Configure installed_paths, but don't overwrite it if already set
# (preserve config).
`#{bin+phpcs_script_name} --config-show | grep -q installed_paths`
unless $CHILD_STATUS.to_i.zero?
system bin+phpcs_script_name, "--config-set", "installed_paths", phpcs_standards
end
end
def caveats; <<-EOS.undent
Verify your installation by running:
#{phpcs_script_name} --version
You can read more about phpcs by running:
brew home #{name}
Sniffs must be upgraded to be compatible with version 3.0
https://github.com/squizlabs/PHP_CodeSniffer/wiki/Version-3.0-Upgrade-Guide
EOS
end
test do
(testpath/"test.php").write <<-EOS.undent
<?php
echo "foo"."bar"
EOS
system bin+phpcs_script_name, "--standard=Zend", "test.php"
system "#{bin}/#{phpcs_script_name} --standard=PEAR --report=emacs test.php | grep -q 'error - Missing file doc comment'"
end
end
| 30.10989 | 125 | 0.725912 |
e249a9f578770af88f53b90aae1fa56d0c2c88c7 | 1,815 | #
# Be sure to run `pod lib lint FFSpecialKit.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'FFSpecialKit'
s.version = '0.2.0'
s.summary = 'A short description of FFSpecialKit.'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
TODO: Add long description of the pod here.
DESC
s.homepage = 'https://github.com/lingdf/FFSpecialKit'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'lingdf' => '[email protected]' }
s.source = { :git => 'https://github.com/lingdf/FFSpecialKit.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '8.0'
s.source_files = 'FFSpecialKit/Classes/**/*'
# s.resource_bundles = {
# 'FFSpecialKit' => ['FFSpecialKit/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
s.dependency 'Masonry'
s.dependency 'YYWebImage'
s.dependency 'ReactiveCocoa', '~>4.0.4-alpha-4'
s.dependency 'FFCategoryKit'
s.dependency 'FFMainViewKit'
s.dependency 'FFAPIs'
s.dependency 'FFConfigsKit'
s.dependency 'FFReformerKeysKit'
end
| 36.3 | 103 | 0.654545 |
7917a15440990bbe98f5c8b93e4ec32984c9e3a3 | 574 | require 'simplecov'
require './spec/support/simplecov_quality_formatter'
module SimpleCovHelper
def start_simple_cov(name)
SimpleCov.start do
add_filter '/spec/'
add_filter '/lib/generators'
command_name name
formatters = [SimpleCov::Formatter::QualityFormatter]
if ENV['TRAVIS']
require 'codeclimate-test-reporter'
if CodeClimate::TestReporter.run?
formatters << CodeClimate::TestReporter::Formatter
end
end
formatter SimpleCov::Formatter::MultiFormatter[*formatters]
end
end
end
| 22.96 | 65 | 0.688153 |
ab5a2d3785156b11b773352a4ba476325f4a3ed6 | 633 | # typed: false
RSpec.shared_examples 'rails sub-gem auto_instrument?' do
context 'auto_instrument?' do
subject(:auto_instrument?) { integration.auto_instrument? }
context 'outside of a rails application' do
before do
allow(Datadog::Tracing::Contrib::Rails::Utils).to receive(:railtie_supported?).and_return(false)
end
it { is_expected.to be(true) }
end
context 'when within a rails application' do
before do
allow(Datadog::Tracing::Contrib::Rails::Utils).to receive(:railtie_supported?).and_return(true)
end
it { is_expected.to be(false) }
end
end
end
| 26.375 | 104 | 0.680885 |
388edcecf9274062b27df334293fe50953f0412f | 1,025 | cask 'datagrip' do
version '2019.3.3,193.6494.42'
sha256 '8cac9f932f19f8bd5a3d1446bd193f985224157a19acd551917525913beed24f'
url "https://download.jetbrains.com/datagrip/datagrip-#{version.before_comma}.dmg"
appcast 'https://data.services.jetbrains.com/products/releases?code=DG&latest=true&type=release'
name 'DataGrip'
homepage 'https://www.jetbrains.com/datagrip/'
auto_updates true
app 'DataGrip.app'
uninstall_postflight do
ENV['PATH'].split(File::PATH_SEPARATOR).map { |path| File.join(path, 'datagrip') }.each { |path| File.delete(path) if File.exist?(path) && File.readlines(path).grep(%r{# see com.intellij.idea.SocketLock for the server side of this interface}).any? }
end
zap trash: [
"~/Library/Application Support/DataGrip#{version.major_minor}",
"~/Library/Caches/DataGrip#{version.major_minor}",
"~/Library/Logs/DataGrip#{version.major_minor}",
"~/Library/Preferences/DataGrip#{version.major_minor}",
]
end
| 41 | 253 | 0.696585 |
012ee8c7f2316277eeaa6f2e7e19dbdd52463c0d | 1,591 | require 'spec_helper'
describe Instrumentality::Executor do
before do
allow(Instrumentality::Logger).to receive(:log)
end
describe '.execute' do
context 'when command exits with status different than zero' do
let(:command) { 'exit 1' }
it 'should raise an error' do
expect do
Instrumentality::Executor.execute(command)
end.to raise_error(Instrumentality::Executor::ExecutorError)
end
end
context 'when command exits with status zero' do
let(:command) { 'echo "Hi!"' }
it 'should not raise an error' do
expect do
Instrumentality::Executor.execute(command)
end.not_to raise_error
end
end
end
describe '.execute_async' do
let(:command) { 'sleep 5' }
it 'should spawn process' do
expect(Process).to receive(:spawn).exactly(1) do |cmd|
expect(cmd).to eql(command)
end
Instrumentality::Executor.execute_async(command)
end
end
describe '.timeout' do
context "when process doesn't exist" do
let(:process) { 'most_certainly_does_not_exist_dot_exe' }
let(:timeout) { 1 }
it 'should raise an error' do
expect do
Instrumentality::Executor.timeout(process, timeout)
end.to raise_error(Instrumentality::Executor::ExecutorError)
end
end
context 'when process exist' do
let(:process) { 'Finder' }
let(:timeout) { 1 }
it 'should return a pid' do
expect(Instrumentality::Executor.timeout(process, timeout)).not_to eql('')
end
end
end
end
| 25.253968 | 82 | 0.639849 |
ed5ea2fb1c2cfea4a81f22f335175564019bd1e9 | 1,256 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'jekyll/widgets/version'
Gem::Specification.new do |spec|
spec.name = 'jekyll-widgets'
spec.version = Jekyll::Widgets::VERSION
spec.authors = ['Adam Bouqdib']
spec.email = ['[email protected]']
spec.summary = "A set of useful widgets for jekyll sites."
spec.homepage = 'https://github.com/abemedia/jekyll-widgets'
spec.license = 'MIT'
# Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
# delete this section to allow pushing this gem to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = 'https://rubygems.org'
else
raise 'RubyGems 2.0 or newer is required to protect against public gem pushes.'
end
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.add_dependency 'jekyll', '~> 3.3'
spec.add_development_dependency 'bundler', '~> 1.10'
spec.add_development_dependency 'rubocop', '~> 0.37'
end
| 39.25 | 104 | 0.66242 |
28e4021bb2a73b02e89bff8c7b016610d97322af | 1,853 | # Class that holds definitions for all of the pages in RedSky
# These can be used to determine if the browser is currently displaying that page
#
# Field types :
# Use :text_field instead of :input if it's a text-field
# Use :button instead of :input if it's a button
# Otherwise, use the actual HTML element type
require_relative 'page_objects'
class RSPages
@@browser = nil
@@pages = [] # an array of Page objects
@@page_names = []
def self.make_pages(browser)
@@browser = browser
# Google Search
page = Page.new("googleSearch", "search_term_field")
page.add_field("search_term", :text_field, :name, "q")
page.add_field("search_button", :button, :name, "btnK")
self.add_page(page)
# Google Search Results
page = Page.new("googleSearchResults", "result_stats_field")
page.add_field("result_stats", :div, :id, "resultStats")
self.add_page(page)
end
##################################################################################################
def self.add_page(page)
page.browser = @@browser # set the browser object for each page
# TODO have only one browser object (here in RSPages), and have each page know how to find it, instead of taking
# their own copy of the object
@@pages << page
@@page_names << page.name
end
# Outputs info on the pages currently stored
def self.info
s = ""
s += "#{@@pages.size} pages defined. Names :"
@@page_names.each {|f| s += "\n#{f}" }
s
end
# Will convert name to a string
def self.page_known?(name)
@@page_names.include?(name.to_s)
end
# Retrieves the specific page; raises if it cannot be found
# Will convert name to a string
def self.find(name)
raise "Could not locate page '#{name}'" unless self.page_known?(name)
@@pages[@@page_names.index(name.to_s)]
end
end
| 26.855072 | 116 | 0.637885 |
e8255a4e95624acc3eb0d296e7c24d11b6689aee | 4,152 | module DBI
#
# TypeUtil is a series of utility methods for type management.
#
class TypeUtil
@@conversions = { }
#
# Register a conversion for a DBD. This applies to bound parameters for
# outgoing statements; please look at DBI::Type for result sets.
#
# Conversions are given a driver_name, which is then used to look up
# the conversion to perform on the object. Please see #convert for more
# information. Driver names are typically provided by the DBD, but may
# be overridden at any stage temporarily by assigning to the
# +driver_name+ attribute for the various handles.
#
# A conversion block is normally a +case+ statement that identifies
# various native ruby types and converts them to string, but ultimately
# the result type is dependent on low-level driver. The resulting
# object will be fed to the query as the bound value.
#
# The result of the block is two arguments, the first being the result
# object, and the second being a +cascade+ flag, which if true
# instructs #convert to run the result through the +default+ conversion
# as well and use its result. This is advantageous when you just need
# to convert everything to string, and allow +default+ to properly escape
# it.
#
def self.register_conversion(driver_name, &block)
raise "Must provide a block" unless block_given?
@@conversions[driver_name] = block
end
#
# Convert object for +driver_name+. See #register_conversion for a
# complete explanation of how type conversion is performed.
#
# If the conversion is instructed to cascade, it will go to the special
# "default" conversion, which is a pre-defined common case (and
# mutable) ruleset for native types. Note that it will use the result
# from the first conversion, not what was originally passed. Be sure to
# leave the object untouched if that is your intent. E.g., if your DBD
# converts an Integer to String and tells it to cascade, the "default"
# conversion will get a String and quote it, not an Integer (which has
# different rules).
#
def self.convert(driver_name, obj)
if @@conversions[driver_name]
newobj, cascade = @@conversions[driver_name].call(obj)
if cascade
return @@conversions["default"].call(newobj)
end
return newobj
end
return @@conversions["default"].call(obj)
end
#
# Convenience method to match many SQL named types to DBI::Type classes. If
# none can be matched, returns DBI::Type::Varchar.
#
def self.type_name_to_module(type_name)
case type_name
when /^int(?:\d+|eger)?$/i
DBI::Type::Integer
when /^varchar$/i, /^character varying$/i
DBI::Type::Varchar
when /^(?:float|real)$/i
DBI::Type::Float
when /^bool(?:ean)?$/i, /^tinyint$/i
DBI::Type::Boolean
when /^time(?:stamp(?:tz)?)?$/i
DBI::Type::Timestamp
when /^(?:decimal|numeric)$/i
DBI::Type::Decimal
else
DBI::Type::Varchar
end
end
end
end
DBI::TypeUtil.register_conversion("default") do |obj|
case obj
when DBI::Binary # these need to be handled specially by the driver
obj
when ::NilClass
nil
when ::TrueClass
"'1'"
when ::FalseClass
"'0'"
when ::Time, ::Date, ::DateTime
"'#{::DateTime.parse(obj.to_s).strftime("%Y-%m-%dT%H:%M:%S")}'"
when ::String, ::Symbol
obj = obj.to_s
obj = obj.gsub(/\\/) { "\\\\" }
obj = obj.gsub(/'/) { "''" }
"'#{obj}'"
when ::BigDecimal
obj.to_s("F")
when ::Numeric
obj.to_s
else
"'#{obj.to_s}'"
end
end
| 37.745455 | 83 | 0.575626 |
f748ac9ae192093b2e4788cd393782750f1b8357 | 430 | # frozen_string_literal: true
module Neo4j
module Driver
module Exceptions
# Failed to authenticate the driver to the server due to bad credentials provided.
# When this error happens, the error could be recovered by closing the current driver and restart a new driver with
# the correct credentials.
# @since 1.1
class AuthenticationException < SecurityException
end
end
end
end
| 26.875 | 121 | 0.718605 |
62b60b32eff291fc3a8a9469fc88f8be59e7eeee | 23 | module AdiesHelper
end
| 7.666667 | 18 | 0.869565 |
e2aa2be25190292a70edd180e7477670cbc2fd9b | 846 | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/netsuite/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ['Ryan Moran', 'Michael Bianco']
gem.email = ['[email protected]', '[email protected]']
gem.description = %q{NetSuite SuiteTalk API Wrapper}
gem.summary = %q{NetSuite SuiteTalk API (SOAP) Wrapper}
gem.homepage = 'https://github.com/NetSweet/netsuite'
gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
gem.files = `git ls-files`.split("\n")
gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
gem.name = 'netsuite'
gem.require_paths = ['lib']
gem.version = Netsuite::VERSION
gem.add_dependency 'savon', '~> 2.3.0'
gem.add_development_dependency 'rspec', '~> 3.1.0'
end
| 38.454545 | 85 | 0.626478 |
1c39ed12465adac525e7e539289537e8c9dd41f6 | 202 | class AddPercentDefaultInExpenses < ActiveRecord::Migration[5.2]
def up
change_column_default :expenses, :percent, 0
end
def down
change_column_default :expenses, :percent, nil
end
end
| 20.2 | 64 | 0.752475 |
e9cc1cb10e68c97925cab0ad7aa35b826fac6e96 | 387 | # frozen_string_literal: true
module Flippant
class Registry
def initialize
clear
end
def register(group, fun = nil, &block)
table[group.to_s] = fun || block
end
def registered
table
end
def registered?(group)
table.key?(group.to_s)
end
def clear
@table = {}
end
private
attr_reader :table
end
end
| 12.9 | 42 | 0.591731 |
ac0195c4367cad546f8e4aae650d20f270b82ba6 | 18,400 | # frozen-string-literal: true
module Sequel
class Database
# ---------------------
# :section: 7 - Miscellaneous methods
# These methods don't fit neatly into another category.
# ---------------------
# Hash of extension name symbols to callable objects to load the extension
# into the Database object (usually by extending it with a module defined
# in the extension).
EXTENSIONS = {}
# The general default size for string columns for all Sequel::Database
# instances.
DEFAULT_STRING_COLUMN_SIZE = 255
# Empty exception regexp to class map, used by default if Sequel doesn't
# have specific support for the database in use.
DEFAULT_DATABASE_ERROR_REGEXPS = {}.freeze
# Mapping of schema type symbols to class or arrays of classes for that
# symbol.
SCHEMA_TYPE_CLASSES = {:string=>String, :integer=>Integer, :date=>Date, :datetime=>[Time, DateTime].freeze,
:time=>Sequel::SQLTime, :boolean=>[TrueClass, FalseClass].freeze, :float=>Float, :decimal=>BigDecimal,
:blob=>Sequel::SQL::Blob}.freeze
# Nested hook Proc; each new hook Proc just wraps the previous one.
@initialize_hook = Proc.new {|db| }
# Register a hook that will be run when a new Database is instantiated. It is
# called with the new database handle.
def self.after_initialize(&block)
raise Error, "must provide block to after_initialize" unless block
Sequel.synchronize do
previous = @initialize_hook
@initialize_hook = Proc.new do |db|
previous.call(db)
block.call(db)
end
end
end
# Apply an extension to all Database objects created in the future.
def self.extension(*extensions)
after_initialize{|db| db.extension(*extensions)}
end
# Register an extension callback for Database objects. ext should be the
# extension name symbol, and mod should either be a Module that the
# database is extended with, or a callable object called with the database
# object. If mod is not provided, a block can be provided and is treated
# as the mod object.
def self.register_extension(ext, mod=nil, &block)
if mod
raise(Error, "cannot provide both mod and block to Database.register_extension") if block
if mod.is_a?(Module)
block = proc{|db| db.extend(mod)}
else
block = mod
end
end
Sequel.synchronize{EXTENSIONS[ext] = block}
end
# Run the after_initialize hook for the given +instance+.
def self.run_after_initialize(instance)
@initialize_hook.call(instance)
end
# Converts a uri to an options hash. These options are then passed
# to a newly created database object.
def self.uri_to_options(uri)
{
:user => uri.user,
:password => uri.password,
:port => uri.port,
:host => uri.hostname,
:database => (m = /\/(.*)/.match(uri.path)) && (m[1])
}
end
private_class_method :uri_to_options
# The options hash for this database
attr_reader :opts
# Set the timezone to use for this database, overridding <tt>Sequel.database_timezone</tt>.
attr_writer :timezone
# The specific default size of string columns for this Sequel::Database, usually 255 by default.
attr_accessor :default_string_column_size
# Constructs a new instance of a database connection with the specified
# options hash.
#
# Accepts the following options:
# :cache_schema :: Whether schema should be cached for this Database instance
# :default_string_column_size :: The default size of string columns, 255 by default.
# :keep_reference :: Whether to keep a reference to this instance in Sequel::DATABASES, true by default.
# :logger :: A specific logger to use.
# :loggers :: An array of loggers to use.
# :log_connection_info :: Whether connection information should be logged when logging queries.
# :log_warn_duration :: The number of elapsed seconds after which queries should be logged at warn level.
# :name :: A name to use for the Database object.
# :preconnect :: Whether to automatically connect to the maximum number of servers. Can use a valid
# of 'concurrently' to preconnect in separate threads.
# :quote_identifiers :: Whether to quote identifiers.
# :servers :: A hash specifying a server/shard specific options, keyed by shard symbol .
# :single_threaded :: Whether to use a single-threaded connection pool.
# :sql_log_level :: Method to use to log SQL to a logger, :info by default.
#
# All options given are also passed to the connection pool.
def initialize(opts = OPTS)
@opts ||= opts
@opts = connection_pool_default_options.merge(@opts)
@loggers = Array(@opts[:logger]) + Array(@opts[:loggers])
@opts[:servers] = {} if @opts[:servers].is_a?(String)
@sharded = !!@opts[:servers]
@opts[:adapter_class] = self.class
@opts[:single_threaded] = @single_threaded = typecast_value_boolean(@opts.fetch(:single_threaded, Sequel.single_threaded))
@default_string_column_size = @opts[:default_string_column_size] || DEFAULT_STRING_COLUMN_SIZE
@schemas = {}
@prepared_statements = {}
@transactions = {}
@symbol_literal_cache = {}
@timezone = nil
@dataset_class = dataset_class_default
@cache_schema = typecast_value_boolean(@opts.fetch(:cache_schema, true))
@dataset_modules = []
@loaded_extensions = []
@schema_type_classes = SCHEMA_TYPE_CLASSES.dup
self.sql_log_level = @opts[:sql_log_level] ? @opts[:sql_log_level].to_sym : :info
self.log_warn_duration = @opts[:log_warn_duration]
self.log_connection_info = typecast_value_boolean(@opts[:log_connection_info])
@pool = ConnectionPool.get_pool(self, @opts)
reset_default_dataset
adapter_initialize
unless typecast_value_boolean(@opts[:keep_reference]) == false
Sequel.synchronize{::Sequel::DATABASES.push(self)}
end
Sequel::Database.run_after_initialize(self)
if typecast_value_boolean(@opts[:preconnect]) && @pool.respond_to?(:preconnect, true)
concurrent = typecast_value_string(@opts[:preconnect]) == "concurrently"
@pool.send(:preconnect, concurrent)
end
case exts = @opts[:extensions]
when String
extension(*exts.split(',').map(&:to_sym))
when Array
extension(*exts)
when Symbol
extension(exts)
when nil
# nothing
else
raise Error, "unsupported Database :extensions option: #{@opts[:extensions].inspect}"
end
end
# Freeze internal data structures for the Database instance.
def freeze
valid_connection_sql
metadata_dataset
@opts.freeze
@loggers.freeze
@pool.freeze
@dataset_class.freeze
@dataset_modules.freeze
@schema_type_classes.freeze
@loaded_extensions.freeze
metadata_dataset
super
end
# Disallow dup/clone for Database instances
undef_method :dup, :clone, :initialize_copy
if RUBY_VERSION >= '1.9.3'
undef_method :initialize_clone, :initialize_dup
end
# Cast the given type to a literal type
#
# DB.cast_type_literal(Float) # double precision
# DB.cast_type_literal(:foo) # foo
def cast_type_literal(type)
type_literal(:type=>type)
end
# Load an extension into the receiver. In addition to requiring the extension file, this
# also modifies the database to work with the extension (usually extending it with a
# module defined in the extension file). If no related extension file exists or the
# extension does not have specific support for Database objects, an Error will be raised.
# Returns self.
def extension(*exts)
Sequel.extension(*exts)
exts.each do |ext|
if pr = Sequel.synchronize{EXTENSIONS[ext]}
unless Sequel.synchronize{@loaded_extensions.include?(ext)}
Sequel.synchronize{@loaded_extensions << ext}
pr.call(self)
end
else
raise(Error, "Extension #{ext} does not have specific support handling individual databases (try: Sequel.extension #{ext.inspect})")
end
end
self
end
# Convert the given timestamp from the application's timezone,
# to the databases's timezone or the default database timezone if
# the database does not have a timezone.
def from_application_timestamp(v)
Sequel.convert_output_timestamp(v, timezone)
end
# Returns a string representation of the database object including the
# class name and connection URI and options used when connecting (if any).
def inspect
a = []
a << uri.inspect if uri
if (oo = opts[:orig_opts]) && !oo.empty?
a << oo.inspect
end
"#<#{self.class}: #{a.join(' ')}>"
end
# Proxy the literal call to the dataset.
#
# DB.literal(1) # 1
# DB.literal(:a) # a
# DB.literal('a') # 'a'
def literal(v)
schema_utility_dataset.literal(v)
end
# Return the literalized version of the symbol if cached, or
# nil if it is not cached.
def literal_symbol(sym)
Sequel.synchronize{@symbol_literal_cache[sym]}
end
# Set the cached value of the literal symbol.
def literal_symbol_set(sym, lit)
Sequel.synchronize{@symbol_literal_cache[sym] = lit}
end
# Synchronize access to the prepared statements cache.
def prepared_statement(name)
Sequel.synchronize{prepared_statements[name]}
end
# Proxy the quote_identifier method to the dataset,
# useful for quoting unqualified identifiers for use
# outside of datasets.
def quote_identifier(v)
schema_utility_dataset.quote_identifier(v)
end
# Return ruby class or array of classes for the given type symbol.
def schema_type_class(type)
@schema_type_classes[type]
end
# Default serial primary key options, used by the table creation code.
def serial_primary_key_options
{:primary_key => true, :type => Integer, :auto_increment => true}
end
# Cache the prepared statement object at the given name.
def set_prepared_statement(name, ps)
Sequel.synchronize{prepared_statements[name] = ps}
end
# Whether this database instance uses multiple servers, either for sharding
# or for master/slave.
def sharded?
@sharded
end
# The timezone to use for this database, defaulting to <tt>Sequel.database_timezone</tt>.
def timezone
@timezone || Sequel.database_timezone
end
# Convert the given timestamp to the application's timezone,
# from the databases's timezone or the default database timezone if
# the database does not have a timezone.
def to_application_timestamp(v)
Sequel.convert_timestamp(v, timezone)
end
# Typecast the value to the given column_type. Calls
# typecast_value_#{column_type} if the method exists,
# otherwise returns the value.
# This method should raise Sequel::InvalidValue if assigned value
# is invalid.
def typecast_value(column_type, value)
return nil if value.nil?
meth = "typecast_value_#{column_type}"
begin
# Allow calling private methods as per-type typecasting methods are private
respond_to?(meth, true) ? send(meth, value) : value
rescue ArgumentError, TypeError => e
raise Sequel.convert_exception_class(e, InvalidValue)
end
end
# Returns the URI use to connect to the database. If a URI
# was not used when connecting, returns nil.
def uri
opts[:uri]
end
# Explicit alias of uri for easier subclassing.
def url
uri
end
private
# Per adapter initialization method, empty by default.
def adapter_initialize
end
# Returns true when the object is considered blank.
# The only objects that are blank are nil, false,
# strings with all whitespace, and ones that respond
# true to empty?
def blank_object?(obj)
return obj.blank? if obj.respond_to?(:blank?)
case obj
when NilClass, FalseClass
true
when Numeric, TrueClass
false
when String
obj.strip.empty?
else
obj.respond_to?(:empty?) ? obj.empty? : false
end
end
# An enumerable yielding pairs of regexps and exception classes, used
# to match against underlying driver exception messages in
# order to raise a more specific Sequel::DatabaseError subclass.
def database_error_regexps
DEFAULT_DATABASE_ERROR_REGEXPS
end
# Return the Sequel::DatabaseError subclass to wrap the given
# exception in.
def database_error_class(exception, opts)
database_specific_error_class(exception, opts) || DatabaseError
end
# Return the SQLState for the given exception, if one can be determined
def database_exception_sqlstate(exception, opts)
nil
end
# Return a specific Sequel::DatabaseError exception class if
# one is appropriate for the underlying exception,
# or nil if there is no specific exception class.
def database_specific_error_class(exception, opts)
return DatabaseDisconnectError if disconnect_error?(exception, opts)
if sqlstate = database_exception_sqlstate(exception, opts)
if klass = database_specific_error_class_from_sqlstate(sqlstate)
return klass
end
else
database_error_regexps.each do |regexp, klss|
return klss if exception.message =~ regexp
end
end
nil
end
NOT_NULL_CONSTRAINT_SQLSTATES = %w'23502'.freeze.each(&:freeze)
FOREIGN_KEY_CONSTRAINT_SQLSTATES = %w'23503 23506 23504'.freeze.each(&:freeze)
UNIQUE_CONSTRAINT_SQLSTATES = %w'23505'.freeze.each(&:freeze)
CHECK_CONSTRAINT_SQLSTATES = %w'23513 23514'.freeze.each(&:freeze)
SERIALIZATION_CONSTRAINT_SQLSTATES = %w'40001'.freeze.each(&:freeze)
# Given the SQLState, return the appropriate DatabaseError subclass.
def database_specific_error_class_from_sqlstate(sqlstate)
case sqlstate
when *NOT_NULL_CONSTRAINT_SQLSTATES
NotNullConstraintViolation
when *FOREIGN_KEY_CONSTRAINT_SQLSTATES
ForeignKeyConstraintViolation
when *UNIQUE_CONSTRAINT_SQLSTATES
UniqueConstraintViolation
when *CHECK_CONSTRAINT_SQLSTATES
CheckConstraintViolation
when *SERIALIZATION_CONSTRAINT_SQLSTATES
SerializationFailure
end
end
# Return true if exception represents a disconnect error, false otherwise.
def disconnect_error?(exception, opts)
opts[:disconnect]
end
# Convert the given exception to an appropriate Sequel::DatabaseError
# subclass, keeping message and backtrace.
def raise_error(exception, opts=OPTS)
if !opts[:classes] || Array(opts[:classes]).any?{|c| exception.is_a?(c)}
raise Sequel.convert_exception_class(exception, database_error_class(exception, opts))
else
raise exception
end
end
# Typecast the value to an SQL::Blob
def typecast_value_blob(value)
value.is_a?(Sequel::SQL::Blob) ? value : Sequel::SQL::Blob.new(value)
end
# Typecast the value to true, false, or nil
def typecast_value_boolean(value)
case value
when false, 0, "0", /\Af(alse)?\z/i, /\Ano?\z/i
false
else
blank_object?(value) ? nil : true
end
end
# Typecast the value to a Date
def typecast_value_date(value)
case value
when DateTime, Time
Date.new(value.year, value.month, value.day)
when Date
value
when String
Sequel.string_to_date(value)
when Hash
Date.new(*[:year, :month, :day].map{|x| (value[x] || value[x.to_s]).to_i})
else
raise InvalidValue, "invalid value for Date: #{value.inspect}"
end
end
# Typecast the value to a DateTime or Time depending on Sequel.datetime_class
def typecast_value_datetime(value)
Sequel.typecast_to_application_timestamp(value)
end
if RUBY_VERSION >= '2.4'
# Typecast a string to a BigDecimal
def _typecast_value_string_to_decimal(value)
BigDecimal(value)
end
else
# :nocov:
def _typecast_value_string_to_decimal(value)
d = BigDecimal(value)
if d.zero?
# BigDecimal parsing is loose by default, returning a 0 value for
# invalid input. If a zero value is received, use Float to check
# for validity.
begin
Float(value)
rescue ArgumentError
raise InvalidValue, "invalid value for BigDecimal: #{value.inspect}"
end
end
d
end
# :nocov:
end
# Typecast the value to a BigDecimal
def typecast_value_decimal(value)
case value
when BigDecimal
value
when Numeric
BigDecimal(value.to_s)
when String
_typecast_value_string_to_decimal(value)
else
raise InvalidValue, "invalid value for BigDecimal: #{value.inspect}"
end
end
# Typecast the value to a Float
def typecast_value_float(value)
Float(value)
end
# Typecast the value to an Integer
def typecast_value_integer(value)
(value.is_a?(String) && value =~ /\A0+(\d)/) ? Integer(value, 10) : Integer(value)
end
# Typecast the value to a String
def typecast_value_string(value)
case value
when Hash, Array
raise Sequel::InvalidValue, "invalid value for String: #{value.inspect}"
else
value.to_s
end
end
# Typecast the value to a Time
def typecast_value_time(value)
case value
when Time
if value.is_a?(SQLTime)
value
else
SQLTime.create(value.hour, value.min, value.sec, value.nsec/1000.0)
end
when String
Sequel.string_to_time(value)
when Hash
SQLTime.create(*[:hour, :minute, :second].map{|x| (value[x] || value[x.to_s]).to_i})
else
raise Sequel::InvalidValue, "invalid value for Time: #{value.inspect}"
end
end
end
end
| 34.200743 | 142 | 0.667391 |
f7be51df4bea900aa1ffa5643a248090c937c8d5 | 839 | class Recipe < ApplicationRecord
belongs_to :category
belongs_to :user
accepts_nested_attributes_for :category, reject_if: :all_blank
has_many :comments, dependent: :destroy
has_many :users, through: :comments
has_many :ingredients, dependent: :destroy
accepts_nested_attributes_for :ingredients, reject_if: :all_blank, allow_destroy: true
has_many :directions, dependent: :destroy
accepts_nested_attributes_for :directions, reject_if: :all_blank, allow_destroy: true
validates :title, :description, presence: true
scope :alphabetize, -> { order(:title, :asc) }
def self.search(params)
where("LOWER(title) LIKE :term OR LOWER(description) LIKE :term", term: "%#{params}%")
end
def category_name
self.category ? self.category.name : "category not available"
end
end
| 26.21875 | 92 | 0.727056 |
28ff35c71a42d341085b91e2bca2c5927e15952e | 119 | class LifeRecord < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :lifeRecords
end | 17 | 37 | 0.798319 |
bf1344674904ab696edcc1a5511faea1be4a5f90 | 546 | # frozen_string_literal: true
require 'logging_library/custom_formatter'
require 'logging_library/logger_factory'
require 'logging_library/logger'
require 'logging_library/mixins/loggable'
require 'logging_library/version'
module LoggingLibrary
Loggable = Mixins::Loggable
LOG_LEVELS = Mixlib::Log::LEVELS.keys.freeze
class << self
def output_device
@output_device ||= $stderr
end
attr_writer :output_device
end
end
# Avoid buffering output when running under e.g. Foreman.
$stdout.sync = true
$stderr.sync = true
| 21 | 57 | 0.767399 |
5de05610894dbba991719b0c96d033e5e553c39d | 2,051 | ###################################################################################################
# This script send packets in all VLANs [1-4094] with all possible priorities [0-7].
###################################################################################################
require 'rubygems'
require 'racket'
require 'l2tester'
# Uncomment to enable debugs.
#L2tester::Logger.config_log_level(L2tester::Logger::L2T_LOG_DEBUG)
if ARGV.size < 1
puts <<-EOS
This script send packets in all VLANs [1-4094] with all possible priorities [0-7].
Usage: ruby send_all_vlans.rb <iface> [interval]
Arguments
iface : Interface that will output frames. Ex: eth0
interval : Interval in ms between each frame. Default: 1 ms.
EOS
else
# Get interval if user supplied!
interval_ms = ARGV.size > 1 ? ARGV[1].to_f : 1.0
begin
action_vlan = L2tester::Action.new
action_vlan.type = L2tester::Action::ACTION_INCREMENT
action_vlan.mask = 0x0FFF000000000000
action_vlan.byte = 14
action_vlan.range_first = 1
action_vlan.range_last = 4094
action_prio = L2tester::Action.new
action_prio.type = L2tester::Action::ACTION_INCREMENT
action_prio.mask = 0xE000000000000000
action_prio.byte = 14
action_prio.range_first = 0
action_prio.range_last = 7
action_vlan.chain_action(action_prio, L2tester::Action::ACTION_CHAIN_WHEN_FINISHED)
packet = Racket::Racket.new
packet.l2 = Racket::L2::Ethernet.new
packet.l2.src_mac = "10:00:01:02:03:04"
packet.l2.dst_mac = 'FF:FF:FF:FF:FF:FF'
packet.l2.ethertype = 0x8100
packet.l3 = Racket::L2::VLAN.new("\0"*100)
packet.l3.priority = 0
packet.l3.cfi = 0
packet.l3.id = 0
packet.l3.type = 0x5010
sender = L2tester::Sender.new(ARGV[0], packet.pack)
sender.manual_bandwidth(1, (interval_ms*1000000).to_i);
sender.set_action(action_vlan)
started = Time.now
sender.run(4094*8)
puts "Time elapsed #{Time.now - started} s"
rescue Exception => e
puts e
end
end | 32.046875 | 99 | 0.627011 |
7a40f46db0dd1ca1dfb849c06243539edba81574 | 576 | #
# Output ecr repository
#
require 'kumogata/template/helper'
_output "#{args[:name]} ecr repository",
ref_value: "#{args[:name]} ecr repository",
export: _export_string(args, "ecr repository")
_output "#{args[:name]} ecr repository uri",
value: _join([ _account_id,
".dkr.ecr.",
_region,
".amazonaws.com/",
_ref(_resource_name("#{args[:name]} ecr repository")),
], ""),
export: _export_string(args, "ecr repository uri")
| 33.882353 | 78 | 0.519097 |
4aa3a6232152f478609e4f7b13fa8d00cb4ef207 | 287 | cask 'kubernetes-cli-1.19.11' do
version '1.19.11'
sha256 'c3b968b7e454376dc249e5968e433673ce14b3f31f2ea298b87fc67a1f8e7ccf'
url "https://dl.k8s.io/v#{version}/kubernetes-client-darwin-amd64.tar.gz"
name 'Kubernetes Client'
homepage 'https://kubernetes.io/'
end
| 31.888889 | 77 | 0.728223 |
037defc7849f61bd8bb3604a4a1c5086754adc2c | 3,923 | # frozen_string_literal: true
require 'singleton'
class LitmusHelper
include Singleton
include PuppetLitmus
end
def iptables_flush_all_tables
['filter', 'nat', 'mangle', 'raw'].each do |t|
expect(LitmusHelper.instance.run_shell("iptables -t #{t} -F").stderr).to eq('')
end
end
def ip6tables_flush_all_tables
['filter', 'mangle'].each do |t|
expect(LitmusHelper.instance.run_shell("ip6tables -t #{t} -F").stderr).to eq('')
end
end
def install_iptables
LitmusHelper.instance.run_shell('iptables -V')
rescue
if os[:family] == 'redhat'
if fetch_os_name == 'oraclelinux' && os[:release].to_i == 7
LitmusHelper.instance.run_shell('yum install iptables -y')
else
LitmusHelper.instance.run_shell('yum install iptables-services -y')
end
else
LitmusHelper.instance.run_shell('apt-get install iptables -y')
end
end
def iptables_version
install_iptables
x = LitmusHelper.instance.run_shell('iptables -V')
x.stdout.split(' ')[1][1..-1]
end
def pre_setup
LitmusHelper.instance.run_shell('mkdir -p /lib/modules/`uname -r`')
LitmusHelper.instance.run_shell('depmod -a')
end
def update_profile_file
LitmusHelper.instance.run_shell("sed -i '/mesg n/c\\test -t 0 && mesg n || true' ~/.profile")
LitmusHelper.instance.run_shell("sed -i '/mesg n || true/c\\test -t 0 && mesg n || true' ~/.profile")
end
def fetch_os_name
@facter_os_name ||= LitmusHelper.instance.run_shell('facter os.name').stdout.delete("\n").downcase
end
RSpec.configure do |c|
# This flag is disabling test 'condition' from firewall_attributes_exceptions
# because this test is failing on docker containers, but it's compatible with vmpooler machines
# To enable tests on abs/vmpooler machines just set to `true` this flag
c.filter_run_excluding condition_parameter_test: false
c.before :suite do
# Depmod is not availible by default on our AlmaLinux 8 docker image
if ['almalinux-8'].include?("#{fetch_os_name}-#{os[:release].to_i}")
LitmusHelper.instance.run_shell('yum install kmod -y')
end
if ['centos-6', 'centos-7', 'oraclelinux-6', 'scientific-6', 'scientific-7'].include?("#{fetch_os_name}-#{os[:release].to_i}")
LitmusHelper.instance.run_shell('yum update -y')
LitmusHelper.instance.run_shell('depmod -a')
['filter', 'nat', 'mangle', 'raw'].each do |t|
LitmusHelper.instance.run_shell("modprobe iptable_#{t}")
LitmusHelper.instance.run_shell("modprobe ip6table_#{t}")
end
LitmusHelper.instance.run_shell('touch /etc/sysconfig/iptables')
LitmusHelper.instance.run_shell('touch /etc/sysconfig/ip6tables')
end
if os[:family] == 'debian'
LitmusHelper.instance.run_shell('apt-get update -y')
LitmusHelper.instance.run_shell('apt-get install kmod') if os[:release].to_i == 10
end
if fetch_os_name == 'centos' && os[:release].to_i == 8
pp = <<-PUPPETCODE
package { 'iptables-services':
ensure => 'latest',
}
package { 'policycoreutils':
ensure => 'latest',
}
PUPPETCODE
LitmusHelper.instance.apply_manifest(pp)
end
if os[:family] == 'debian' && os[:release].to_i == 10
pp = <<-PUPPETCODE
package { 'net-tools':
ensure => 'latest',
}
PUPPETCODE
LitmusHelper.instance.apply_manifest(pp)
LitmusHelper.instance.run_shell('update-alternatives --set iptables /usr/sbin/iptables-legacy', expect_failures: true)
LitmusHelper.instance.run_shell('update-alternatives --set ip6tables /usr/sbin/ip6tables-legacy', expect_failures: true)
end
pp = <<-PUPPETCODE
package { 'conntrack-tools':
ensure => 'latest',
}
package { 'xtables-addons-common':
ensure => 'latest',
}
package { 'iptables':
ensure => 'latest',
}
PUPPETCODE
LitmusHelper.instance.apply_manifest(pp)
end
end
| 34.113043 | 130 | 0.672699 |
e82b9ee79cd474fbb5311a5914b6a5523818808a | 1,119 | # -*- encoding: utf-8 -*-
Gem::Specification.new do |spec|
spec.add_dependency 'activesupport', ['>= 3.0', '< 4.2']
spec.authors = ["Brandon Keepers", "Brian Ryckbost", "Chris Gaffney", "David Genord II", "Erik Michaels-Ober", "Matt Griffin", "Steve Richert", "Tobias Lütke"]
spec.description = "Delayed_job (or DJ) encapsulates the common pattern of asynchronously executing longer tasks in the background. It is a direct extraction from Shopify where the job table is responsible for a multitude of core tasks."
spec.email = ['[email protected]']
spec.files = %w(CHANGELOG.md CONTRIBUTING.md LICENSE.md README.md Rakefile delayed_job.gemspec)
spec.files += Dir.glob('{contrib,lib,recipes,spec}/**/*')
spec.homepage = 'http://github.com/collectiveidea/delayed_job'
spec.licenses = ['MIT']
spec.name = 'delayed_job'
spec.require_paths = ['lib']
spec.summary = 'Database-backed asynchronous priority queue system -- Extracted from Shopify'
spec.test_files = Dir.glob('spec/**/*')
spec.version = '4.0.0'
end
| 62.166667 | 242 | 0.66756 |
283e59e378c65c059397fe4a3e07b69871e8d114 | 347 | class LearnBlogCLI::Posts
attr_accessor :name, :url, :author, :description
@@all = []
def initialize(name=nil, url=nil, author=nil, description=nil)
@name = name
@url = url
@author = author
@description = description
@@all << self
end
def self.all
@@all
end
def self.clear
@@all.clear
end
end
| 14.458333 | 65 | 0.608069 |
389c5d49b9d008a6c8b7a58cac727c11fdbf6140 | 2,841 | # Copyright (C) 2014-2020 MongoDB 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.
module Mongo
# Allows objects to easily log operations.
#
# @since 2.0.0
module Loggable
# The standard MongoDB log prefix.
#
# @since 2.0.0
PREFIX = 'MONGODB'.freeze
# Convenience method to log debug messages with the standard prefix.
#
# @example Log a debug message.
# log_debug('Message')
#
# @param [ String ] message The message to log.
#
# @since 2.0.0
def log_debug(message)
logger.debug(format_message(message)) if logger.debug?
end
# Convenience method to log error messages with the standard prefix.
#
# @example Log a error message.
# log_error('Message')
#
# @param [ String ] message The message to log.
#
# @since 2.0.0
def log_error(message)
logger.error(format_message(message)) if logger.error?
end
# Convenience method to log fatal messages with the standard prefix.
#
# @example Log a fatal message.
# log_fatal('Message')
#
# @param [ String ] message The message to log.
#
# @since 2.0.0
def log_fatal(message)
logger.fatal(format_message(message)) if logger.fatal?
end
# Convenience method to log info messages with the standard prefix.
#
# @example Log a info message.
# log_info('Message')
#
# @param [ String ] message The message to log.
#
# @since 2.0.0
def log_info(message)
logger.info(format_message(message)) if logger.info?
end
# Convenience method to log warn messages with the standard prefix.
#
# @example Log a warn message.
# log_warn('Message')
#
# @param [ String ] message The message to log.
#
# @since 2.0.0
def log_warn(message)
logger.warn(format_message(message)) if logger.warn?
end
# Get the logger instance.
#
# @example Get the logger instance.
# loggable.logger
#
# @return [ Logger ] The logger.
#
# @since 2.1.0
def logger
((options && options[:logger]) || Logger.logger)
end
private
def format_message(message)
format("%s | %s".freeze, _mongo_log_prefix, message)
end
def _mongo_log_prefix
(options && options[:log_prefix]) || PREFIX
end
end
end
| 25.827273 | 74 | 0.645195 |
33b662cfb9d5c7d88a48582a89566b7624c77d74 | 1,020 | require 'discordrb'
require_relative '../helpers/general'
module Bot::Commands
module General
extend Discordrb::Commands::CommandContainer
command :hello do |event|
event.respond "Hello, #{event.user.name}"
end
command :kuji do |event|
# Get command user's voice channel
voice_channel = nil
event.server.channels.each do |channel|
if channel.type == 2
channel.users.each do |user|
if user.id == event.user.id
voice_channel = channel
end
end
end
end
if !voice_channel
event.bot.send_message(event.channel.id, "You are not in any voice channel")
return
end
# Get voice channel members
member = []
voice_channel.users.each do |user|
member.push(user) if !user.bot_account
end
# Select one at random
selected = Helpers::General.shuffle(member)[0].name
event.bot.send_message(event.channel.id, selected)
end
end
end
| 26.153846 | 84 | 0.616667 |
28805ef3363bf61f145410a8e8a9aa2d0c28d066 | 1,502 | class TwoFactor::Sms < ::TwoFactor
attr_accessor :send_code_phase
attr_accessor :country, :phone_number
validates_presence_of :phone_number, if: :send_code_phase
validate :valid_phone_number_for_country
def verify?
if !expired? && otp_secret == otp
touch(:last_verify_at)
refresh!
true
else
if otp.blank?
errors.add :otp, :blank
else
errors.add :otp, :invalid
end
false
end
end
def sms_message
I18n.t('sms.verification_code', code: otp_secret)
end
def send_otp
refresh! if expired?
update_phone_number_to_member if send_code_phase
AMQPQueue.enqueue(:sms_notification, phone: member.phone_number, message: sms_message)
end
private
def valid_phone_number_for_country
return if not send_code_phase
if Phonelib.invalid_for_country?(phone_number, country)
errors.add :phone_number, :invalid
end
end
def country_code
ISO3166::Country[country].try :country_code
end
def update_phone_number_to_member
phone = Phonelib.parse([country_code, phone_number].join)
member.update phone_number: phone.sanitized.to_s
end
def gen_code
self.otp_secret = '%06d' % SecureRandom.random_number(1000000)
self.refreshed_at = Time.now
end
def send_notification
return if not self.activated_changed?
if self.activated
MemberMailer.sms_auth_activated(member.id)
else
MemberMailer.sms_auth_deactivated(member.id)
end
end
end
| 22.41791 | 90 | 0.717044 |
0394c9a4650fd090746d60ce9a93a13a3213a3c2 | 2,041 | #
# Be sure to run `pod lib lint MDHomeProject.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'MDHomeProject'
def self.smart_version
tag = `git describe --abbrev=0 --tags 2>/dev/null`.strip
if $?.success? then tag else "0.0.1" end
end
s.version = smart_version
s.summary = 'A short description of MDHomeProject.'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
TODO: Add long description of the pod here.
DESC
s.homepage = 'https://github.com/Leon0206/MDHomeProject'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Leon0206' => '[email protected]' }
s.source = { :git => 'https://github.com/Leon0206/MDHomeProject.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '9.0'
s.source_files = 'MDHomeProject/Classes/**/*'
s.resource_bundles = {
'MDHomeProject' => ['MDHomeProject/Assets/*.*']
}
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
s.dependency 'MDPageMaster'
s.dependency 'SSZipArchive'
s.dependency 'MDCommonKit'
s.dependency 'MDEasyCache'
s.dependency 'MDStatePageKit'
s.dependency 'ReactiveObjC'
s.dependency 'SDWebImage'
s.dependency 'Masonry'
s.dependency 'Aspects'
s.dependency 'AFNetworking'
s.dependency 'SSZipArchive'
end
| 34.59322 | 106 | 0.659971 |
629a1a2b65b36809d84723f6d1e90e6d739b4dad | 518 | $:.push File.expand_path("../lib", __FILE__)
Gem::Specification.new do |s|
s.name = "enumerable-detect-value"
s.version = '0.1.0'
s.authors = [ "Daniel Doubrovkine" ]
s.email = "[email protected]"
s.platform = Gem::Platform::RUBY
s.required_rubygems_version = '>= 1.3.6'
s.files = Dir['**/*']
s.require_paths = [ "lib" ]
s.homepage = "http://github.com/dblock/enumerable-detect-value"
s.licenses = [ "MIT" ]
s.summary = "Unlike Enumerable#detect, #detect_value returns the evaluated value."
end
| 32.375 | 84 | 0.664093 |
6186e68313bf08040f1a3b25a5232463807e22c2 | 2,547 | # frozen_string_literal: true
module Stupidedi
module Versions
module FunctionalGroups
module FortyTen
module SegmentDefs
s = Schema
e = ElementDefs
r = ElementReqs
CAS = s::SegmentDef.build(:CAS, "Claims Adjustment",
"To supply adjustment reason codes and amounts as needed for an entire claim or for a particular service within the claim being paid",
e::E1033.simple_use(r::Mandatory, s::RepeatCount.bounded(1)),
e::E1034.simple_use(r::Mandatory, s::RepeatCount.bounded(1)),
e::E782 .simple_use(r::Mandatory, s::RepeatCount.bounded(1)),
e::E380 .simple_use(r::Optional, s::RepeatCount.bounded(1)),
e::E1034.simple_use(r::Relational, s::RepeatCount.bounded(1)),
e::E782 .simple_use(r::Relational, s::RepeatCount.bounded(1)),
e::E380 .simple_use(r::Relational, s::RepeatCount.bounded(1)),
e::E1034.simple_use(r::Relational, s::RepeatCount.bounded(1)),
e::E782 .simple_use(r::Relational, s::RepeatCount.bounded(1)),
e::E380 .simple_use(r::Relational, s::RepeatCount.bounded(1)),
e::E1034.simple_use(r::Relational, s::RepeatCount.bounded(1)),
e::E782 .simple_use(r::Relational, s::RepeatCount.bounded(1)),
e::E380 .simple_use(r::Relational, s::RepeatCount.bounded(1)),
e::E1034.simple_use(r::Relational, s::RepeatCount.bounded(1)),
e::E782 .simple_use(r::Relational, s::RepeatCount.bounded(1)),
e::E380 .simple_use(r::Relational, s::RepeatCount.bounded(1)),
e::E1034.simple_use(r::Relational, s::RepeatCount.bounded(1)),
e::E782 .simple_use(r::Relational, s::RepeatCount.bounded(1)),
e::E380 .simple_use(r::Relational, s::RepeatCount.bounded(1)),
SyntaxNotes::L.build( 5, 6, 7),
SyntaxNotes::C.build( 6, 5),
SyntaxNotes::C.build( 7, 5),
SyntaxNotes::L.build( 8, 9, 10),
SyntaxNotes::C.build( 9, 8),
SyntaxNotes::C.build(10, 8),
SyntaxNotes::L.build(11, 12, 13),
SyntaxNotes::C.build(12, 11),
SyntaxNotes::C.build(13, 11),
SyntaxNotes::L.build(14, 15, 16),
SyntaxNotes::C.build(15, 14),
SyntaxNotes::C.build(16, 14),
SyntaxNotes::L.build(17, 18, 19),
SyntaxNotes::C.build(18, 17),
SyntaxNotes::C.build(19, 17))
end
end
end
end
end
| 43.913793 | 146 | 0.584609 |
8723f41783c7183d29b772ab36eee023bf37a5fc | 132 | module Geotab
class DeviceStatusInfo
include Geotab::Concerns::Findable
include Geotab::Concerns::Initializable
end
end
| 18.857143 | 43 | 0.772727 |
033ba97ff4f07217d809c7a3f4d859a5c2a07f58 | 160 | class AddMorefieldsToUser < ActiveRecord::Migration
def change
add_column :users, :box_bg_color, :string
add_column :users, :theme, :string
end
end
| 22.857143 | 51 | 0.74375 |
877a883bed85fffcba4ea09959068e0172cbed3f | 324 | # => 1.0.0 Initial Release
# => 1.1.0 Added delete_object and delete_bucket methods
# => 1.1.1 Fixed typo in gemspec and added additional documentation
# => 1.2.0 Added additional Fog::Storage::AWS parameter handling
# => 1.3.0 Added multi-threaded multipart upload
module Ubiquity
class S3
VERSION = '1.3.0'
end
end | 32.4 | 67 | 0.722222 |
4aea09618d0c332ec2cf69466b08dd48ed168480 | 167 | # frozen_string_literal: true
FactoryBot.define do
factory :plan_limits do
plan
trait :default_plan do
plan factory: :default_plan
end
end
end
| 13.916667 | 33 | 0.706587 |
1a02454784e0578e62edd9a25416305c9a3eae63 | 933 | module RbtcArbitrage
module Client
attr_accessor :options
attr_writer :balance
def initialize config={}
@options = config
@options = {}
set_key config, :volume, 0.01
set_key config, :cutoff, 2
set_key config, :logger, Logger.new(STDOUT)
set_key config, :verbose, true
set_key config, :live, false
self
end
def validate_keys *args
args.each do |key|
key = key.to_s.upcase
if ENV[key].blank?
raise ArgumentError, "Exiting because missing required ENV variable $#{key}."
end
end
end
def buy
trade :buy
end
def sell
trade :sell
end
def address
ENV["#{exchange.to_s.upcase}_ADDRESS"]
end
def logger
@options[:logger]
end
private
def set_key config, key, default
@options[key] = config.has_key?(key) ? config[key] : default
end
end
end | 19.4375 | 87 | 0.595927 |
289f1de8ba4672372c9d7e76c2dbbe291763f86a | 9,335 | module Hue
class Bulb
attr_accessor :id, :stash, :options
def initialize(light_num, options = {})
self.id = light_num
self.options = options
end
def status
JSON.parse Net::HTTP.get(Bridge.uri('lights', id))
end
def states
status['state']
end
def [](item)
states[item.to_s]
end
def update(settings = {})
puts @options.merge(settings).inspect
Bridge.update Bridge.uri('lights', id, 'state'), @options.merge(settings)
end
def name
status['name']
end
def name=(_name)
Bridge.update uri('lights', light_id), name: _name
end
def on?
self[:on]
end
def off?
!on?
end
def on
update on: true
on?
end
def off
update on: false
off?
end
def brightness
self[:bri]
end
def brightness=(bri)
update bri: bri
brightness
end
def hue
self[:hue]
end
def hue=(_hue)
_hue = (_hue * (65536.0 / 360)).to_i
update hue: _hue
hue
end
def sat
self[:sat]
end
def sat=(_sat)
update sat: _sat
sat
end
def transition_time
# transition time in seconds
(options[:transitiontime] || 1).to_f / 10
end
def transition_time=(time)
# transition time in seconds
self.options[:transitiontime] = (time * 10).to_i
end
def colortemp
self[:ct]
end
alias :ct :colortemp
def colortemp=(_ct)
update ct: [[_ct, 154].max, 500].min
colortemp
end
alias :ct= :colortemp=
def colormode
self[:colormode]
end
def blinking?
!!(self['alert'] =~ /l?select/)
end
def blink(start = true)
update(alert: (start ? 'lselect' : 'none'))
end
def solid
update alert: 'none'
end
def flash
update alert: 'select'
update alert: 'none'
end
def settings
state = states
options.merge case state['colormode']
when 'ct'
{'ct' => state['ct']}
when 'xy'
{'xy' => state['xy']}
when 'hs'
{'hue' => state['hue'], 'sat' => state['sat']}
end.merge('on' => state['on'], 'bri' => state['bri'])
end
def rgb
send %(#{colormode}_to_rgb)
end
def red
rgb[:red]
end
def green
rgb[:green]
end
def blue
rgb[:blue]
end
def red=(_red)
self.rgb = [_red, green, blue]
end
def green=(_green)
self.rgb = [red, _green, blue]
end
def blue=(_blue)
self.rgb = [red, green, _blue]
end
def kelvin
# convert colortemp setting to Kelvin
1000000 / self['ct']
end
def kelvin=(_temp)
self.colortemp = 1000000 / [_temp, 1].max
end
def ct_to_rgb
# using method described at
# http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/
temp = kelvin / 100
red = temp <= 66 ? 255 : 329.698727446 * ((temp - 60) ** -0.1332047592)
green = if temp <= 66
99.4708025861 * Math.log(temp) - 161.1195681661
else
288.1221695283 * ((temp - 60) ** -0.0755148492)
end
blue = if temp >= 66
255
elsif temp <= 19
0
else
138.5177312231 * Math.log(temp - 10) - 305.0447927307
end
{ red: [[red, 0].max, 255].min.to_i,
green: [[green, 0].max, 255].min.to_i,
blue: [[blue, 0].max, 255].min.to_i
}
end
def xyz
vals = states['xy']
vals + [1 - vals.first - vals.last]
end
def xy_to_rgb
values = (RGB_MATRIX * Matrix[xyz].transpose).to_a.flatten.map{|x| [[x * 255, 0].max, 255].min.to_i}
{ red: values[0],
green: values[1],
blue: values[2]
}
end
def hue_in_degrees
self['hue'].to_f / (65536.0 / 360)
end
def hue_as_decimal
hue_in_degrees / 360
end
def sat_as_decimal
self['sat'] / 255.0
end
def brightness_as_decimal
brightness / 255.0
end
def hs_to_rgb
h, s, v = hue_as_decimal, sat_as_decimal, brightness_as_decimal
if s == 0 #monochromatic
red = green = blue = v
else
v = 1.0 # We are setting the value to 1. Don't count brightness here
i = (h * 6).floor
f = h * 6 - i
p = v * (1 - s)
q = v * (1 - f * s)
t = v * (1 - (1 - f) * s)
case i % 6
when 0
red, green, blue = v, t, p
when 1
red, green, blue = q, v, p
when 2
red, green, blue = p, v, t
when 3
red, green, blue = p, q, v
when 4
red, green, blue = t, p, v
when 5
red, green, blue = v, p, q
end
end
{ red: [[red * 255, 0].max, 255].min.to_i,
green: [[green * 255, 0].max, 255].min.to_i,
blue: [[blue * 255, 0].max, 255].min.to_i
}
end
def rgb=(colors)
red, green, blue = colors[0] / 255.0, colors[1] / 255.0, colors[2] / 255.0
max = [red, green, blue].max
min = [red, green, blue].min
h, s, l = 0, 0, ((max + min) / 2 * 255)
d = max - min
s = max == 0 ? 0 : (d / max * 255)
h = case max
when min
0 # monochromatic
when red
(green - blue) / d + (green < blue ? 6 : 0)
when green
(blue - red) / d + 2
when blue
(red - green) / d + 4
end * 60 # / 6 * 360
h = (h * (65536.0 / 360)).to_i
update hue: h, sat: s.to_i#, bri: l.to_i
[h, s, 1.0]
end
def stash!
self.stash ||= settings
end
def restore!
if stash
update stash
unstash!
end
end
def unstash!
self.stash = nil
end
def candle(repeat = 15)
# 0-65536 for hue, 182 per deg. Ideal 30-60 deg (5460-10920)
stash!
on if off?
repeat.times do
hue = ((rand * 3460) + 5460).to_i
sat = rand(64) + 170
bri = rand(32) + 16
delay = (rand * 0.35) + (@delay ||= 0)
update(hue: hue, sat: sat, bri: bri, transitiontime: (delay * 10).to_i)
sleep delay
end
restore!
end
# Experimental Sunrise/Sunset action
# this will transition from off and warm light to on and daytime light
# in a curve that mimics the actual sunrise.
def perform_sunrise(total_time_in_minutes = 18)
# total_time / 18 steps == time_per_step
# the multiplier should be 600 * time per step
minutes_per_step = total_time_in_minutes / 18.0
multiplier = (minutes_per_step * 60 * 10).to_i
perform_sun_transition total_time_in_minutes, sunrise_steps(multiplier)
end
def perform_sunrise(total_time_in_minutes = 18)
multiplier = sunrise_multiplier total_time_in_minutes
steps = sunrise_steps(multiplier)
if on?
puts "ON! #{steps[0][:bri]} :: #{brightness} :: #{brightness > steps[0][:bri]}"
while brightness >= steps[0][:bri]
steps.shift
end
end
steps.each_with_index do |step, i|
update step.merge(on: true)
sleep(step[:transitiontime] / 10.0)
end
end
def perform_sunset(total_time_in_minutes = 18)
multiplier = sunrise_multiplier total_time_in_minutes
steps = sunset_steps(multiplier)
if on?
puts "ON! #{steps[0][:bri]} :: #{brightness} :: #{brightness > steps[0][:bri]}"
while brightness <= steps[0][:bri]
steps.shift
end
end
steps.each_with_index do |step, i|
update step.merge(on: true)
sleep(step[:transitiontime] / 10.0)
end
off
end
SUN_STEPS = [ 1.5, 2, 3, 1, 4, 2.5 ]
SUN_TIMES = [ 3, 3, 3, 1, 2, 1]
def sunrise_multiplier(total_time_in_minutes)
# total_time / 18 steps == time_per_step
# the multiplier should be 600 * time per step
minutes_per_step = total_time_in_minutes / 18.0
(minutes_per_step * 60 * 10).to_i
end
def sunrise_brightness
sun_bri_unit = 10
SUN_STEPS.inject([0]){|all, i| all << ((i * sun_bri_unit) + all[-1]).to_i } << 255
end
def sunrise_temps
sun_temp_unit = 16
SUN_STEPS.inject([500]){|all, i| all << (all[-1] - (i * sun_temp_unit)).to_i} << 200
end
def sunrise_times
[0, SUN_TIMES, 5].flatten
end
def sunset_times
[0, 5, SUN_TIMES.reverse].flatten
end
def sunrise_steps(multiplier = 600)
bri_steps = sunrise_brightness
tmp_steps = sunrise_temps
steps = []
sunrise_times.each_with_index do |t, i|
steps << {bri: bri_steps[i], ct: tmp_steps[i], transitiontime: (t * multiplier)}
end
steps
end
def sunset_steps(multiplier = 600)
bri_steps = sunrise_brightness.reverse
tmp_steps = sunrise_temps.reverse
steps = []
sunset_times.each_with_index do |t, i|
steps << {bri: bri_steps[i], ct: tmp_steps[i], transitiontime: (t * multiplier)}
end
steps
end
end
end # Hue
| 22.120853 | 106 | 0.527799 |
877e20bba85a67df6ec29d2eca56c71a92be9b3c | 197 | # Read about factories at https://github.com/thoughtbot/factory_bot
FactoryBot.define do
factory :identifier_global_lsid, class: 'Identifier::Global::Lsid', traits: [:housekeeping] do
end
end
| 28.142857 | 96 | 0.77665 |
e935debdca09ef366d3c12a7aff10d095054f340 | 393 | class AccountActivationsController < ApplicationController
def edit
user = User.find_by(email: params[:email])
if user && !user.activated? && user.authenticated?(:activation, params[:id])
user.activate
log_in user
flash[:success] = "アカウントが有効化されました"
redirect_to user
else
flash[:danger] = "リンクが無効になっています"
redirect_to root_url
end
end
end | 26.2 | 80 | 0.6743 |
216e1513d804acc92f88dd864ba2df29fac5f054 | 156 | json.array!(@messages) do |message|
json.extract! message, :id, :postfix_queue_id, :postfix_message_id
json.url message_url(message, format: :json)
end
| 31.2 | 68 | 0.75641 |
1a39f20002bfa4a27012af38cf684f3f52b75025 | 411 | require 'spec_helper'
# Specs in this file have access to a helper object that includes
# the OrdersHelper. For example:
#
# describe OrdersHelper do
# describe "string concat" do
# it "concats two strings with spaces" do
# expect(helper.concat_strings("this","that")).to eq("this that")
# end
# end
# end
describe OrdersHelper do
pending "add some examples to (or delete) #{__FILE__}"
end
| 25.6875 | 71 | 0.705596 |
03635e75107db678fb0e6c56bc860fd2ed9a141b | 2,165 | class JsonrpcGlib < Formula
desc "GNOME library to communicate with JSON-RPC based peers"
homepage "https://gitlab.gnome.org/GNOME/jsonrpc-glib"
url "https://download.gnome.org/sources/jsonrpc-glib/3.30/jsonrpc-glib-3.30.0.tar.xz"
sha256 "841780eb93f0ad3e79a6bda61e803210bdddf21648afac9403d0bfd4e814fb7c"
bottle do
sha256 "08055f3b024c2ef7edfeb02c4a96596b74c24262c0744795aa6988b00bd07e51" => :mojave
sha256 "8fa9192a292b11295854bb1e542e70eefee5cdc92f409c4f9fb583ae8ac95b84" => :high_sierra
sha256 "b05435b22585488d3592c2cb2c06214855fda1760ac390fabf524398e0ed8ed8" => :sierra
sha256 "fdb2d0e079eaf266fd929122c4b24f9e130fba6f98e20290163a42276ed2f4ea" => :el_capitan
end
depends_on "gobject-introspection" => :build
depends_on "meson-internal" => :build
depends_on "ninja" => :build
depends_on "pkg-config" => :build
depends_on "python" => :build
depends_on "glib"
depends_on "json-glib"
def install
ENV.refurbish_args
mkdir "build" do
system "meson", "--prefix=#{prefix}", "-Dwith_vapi=false", ".."
system "ninja"
system "ninja", "install"
end
end
test do
(testpath/"test.c").write <<~EOS
#include <jsonrpc-glib.h>
int main(int argc, char *argv[]) {
JsonrpcInputStream *stream = jsonrpc_input_stream_new(NULL);
return 0;
}
EOS
gettext = Formula["gettext"]
glib = Formula["glib"]
json_glib = Formula["json-glib"]
pcre = Formula["pcre"]
flags = (ENV.cflags || "").split + (ENV.cppflags || "").split + (ENV.ldflags || "").split
flags += %W[
-I#{gettext.opt_include}
-I#{glib.opt_include}/glib-2.0
-I#{glib.opt_lib}/glib-2.0/include
-I#{include}/jsonrpc-glib-1.0
-I#{json_glib.opt_include}/json-glib-1.0
-I#{pcre.opt_include}
-D_REENTRANT
-L#{gettext.opt_lib}
-L#{glib.opt_lib}
-L#{json_glib.opt_lib}
-L#{lib}
-lgio-2.0
-lglib-2.0
-lgobject-2.0
-lintl
-ljson-glib-1.0
-ljsonrpc-glib-1.0
-Wl,-framework
-Wl,CoreFoundation
]
system ENV.cc, "test.c", "-o", "test", *flags
system "./test"
end
end
| 30.492958 | 93 | 0.657275 |
bbdeb5e7b6ec13cfbffcd7be31cbb87237967231 | 14,291 |
require 'test_helper'
class NodeControllerTest < ActionController::TestCase
# def should_get_index(usermsg)
# get :index
# assert_response :success
# assert_template 'welcome/index'
# assert_equal 'layouts/welcome', @response.layout, "Wrong layout"
# assert_select 'div#user_bar_frontpage ul li#user-bar-greeting' do |e|
# assert_match usermsg, e.to_s
# end
# assert_match usermsg,@response.body
# end
def setup
login_as(make_admin_user)
end
def test_index
assert_nothing_raised do
get :index
assert_response :redirect
assert_redirected_to :controller => "node", :action => "list"
end
end
def test_list
@node = Node.make(:virtual)
get :list
assert_response :success
end
def test_new
get :new
assert_response :success
end
def test_edit
@node = Node.make(:virtual)
get :edit, :id => @node.node_id
assert_response :success
end
def test_update
@node = Node.make(:virtual)
newhostname = 'test1'
post :update, :id=> @node.node_id, :node => {:hostname => newhostname }
assert_response :redirect
assert_redirected_to :controller => "node", :action => "show", :id => @node.node_id
end
def test_update_partial
end
def test_show
@node = Node.make(:virtual)
get :show, :id => @node.node_id
assert_response :success
assert_tag :tag => 'h1', :child => /#{@node.hostname}/
end
def test_create
@node = prepare_proper_node :virtual
assert_not_nil Network.datacenter_mgmt_network(@node[:datacenter_id])
assert_difference 'Node.count' do
post :create, :node => @node
end
assert_nil flash[:warning]
assert_redirect :controller => 'node', :action => "show"
assert_match /Node was successfully created/, flash[:notice]
return Node.find_by_hostname_and_datacenter_id(@node[:hostname], @node[:datacenter_id])
end
def test_loc
dc = Datacenter.find(:first)
n = Node.make(:virtual, :datacenter_id => dc.id)
get :loc, :id => dc.name
assert_response :success
assert_match /#{n.hostname}/, @response.body
assert_template 'node/list'
end
def test_cls
n = Node.make(:virtual)
get :cls, :id => "virtual"
assert_response :success
assert_match /#{n.hostname}/, @response.body
assert_template 'node/list'
end
def test_host_ip
net = Network.make
i = net.next_ip()
n = Node.make(:virtual, :mgmt_ip_address => i )
get :host, :id => i.to_s
assert_response :success
assert_match /#{n.hostname}/, @response.body
assert_template 'node/list'
end
def test_host_hostname
n1 = Node.make(:virtual, :hostname => "someserver01")
n2 = Node.make(:virtual, :hostname => "someserver02")
get :host, :id => "someserver"
assert_response :success
assert_match /#{n1.hostname}/, @response.body
assert_match /#{n2.hostname}/, @response.body
assert_template 'node/list'
end
def test_add_nic_virtual
@node = create_node_by_controller :virtual
@nic = Nic.plan
assert_difference('Nic.count') do
post :add_nic, :id => @node.node_id, :nic => @nic
assert_response :success
end
assert_template :partial => '_nics'
end
def test_add_nic_physical
@node = create_node_by_controller :physical
@nic = Nic.plan(:mac_address => 'cc:70:ed:d3:a6:f9', :port_name => 'eth42', :network_type => 'lan')
assert_difference('Nic.count') do
post :add_nic, :id => @node.node_id, :nic => @nic
assert_response :success
end
assert_template :partial => '_nics'
assert_not_nil @node.nics.detect { |nic| nic.port_name == 'eth42' }
end
def test_remove_nic_physical
@node = create_node_by_controller :physical
@nic = Nic.make
@node.nics << @nic
assert_difference('@node.nics.count', -1) do
post :remove_nic, :id => @node.node_id, :nic => @nic.nic_id
assert_response :success
end
assert_template :partial => '_nics'
end
# FIXME: Uncomment when we've established WHAT we want to do to nics that
# are on virtual nodes. Right now, the controller flashes a message that
# says the nic isn't attached to the node. Even if it is?
#def test_remove_nic_virtual
#@node = create_node_by_controller :virtual
#@nic = Nic.make
#@node.nics << @nic
#assert_difference('@node.nics.count', -1) do
#post :remove_nic, :id => @node.node_id, :nic => @nic.nic_id
#assert_response :success
#end
#!assert_template :partial => '_nics'
#end
def test_plug_serial_console
@node = create_node_by_controller :physical
@scs = SerialConsole.make
assert_nothing_raised do
post :plug_serial_console, :id => @node.node_id, :serial_console => @scs
assert_match /Error plugging in port/, @response.body
assert_template :partial => '_serial_consoles'
end
@scs = SerialConsole.plan
assert_nothing_raised do
assert_difference('SerialConsole.count', 1) do
post :plug_serial_console, :id => @node.node_id, :serial_console => @scs
assert_template :partial => '_serial_consoles'
end
end
end
def test_unplug_serial_console
# Failure cases - Checked first to save a SerialConsole.make
@scs = SerialConsole.make
assert_nothing_raised do
post :unplug_serial_console, :id => @scs.node_id.to_i + 1, :serial_consoles_id => @scs.id
assert_template :partial => '_serial_consoles'
assert_match /Error unplugging wrong node/, @response.body
end
# Clean run
assert_nothing_raised do
post :unplug_serial_console, :id => @scs.node_id, :serial_consoles_id => @scs.id
assert_template :partial => '_serial_consoles'
end
assert_raise ActiveRecord::RecordNotFound do
# NOTE: This may be better done by doing a find with the appropriate
# conditions for node_id. If we choose to just dissasociate down the
# road then it's still valid.
SerialConsole.find(@scs.id)
end
end
def test_plug_pdu
@node = Node.make(:physical)
@pdu = Pdu.make
assert_nothing_raised do
post :plug_pdu, :id => @node.node_id, :pdu => @pdu
assert_match /Error plugging in port/, @response.body
assert_template :partial => '_pdus'
end
@node = Node.make(:physical)
@pdu = Pdu.plan
assert_nothing_raised do
assert_difference('Pdu.count', 1) do
post :plug_pdu, :id => @node.node_id, :pdu => @pdu
assert_template :partial => '_pdus'
end
end
end
def test_unplug_pdu
# Failure cases
@pdu = Pdu.make
assert_nothing_raised do
post :unplug_pdu, :id => @pdu.node.node_id.to_i + 1, :pdus_id => @pdu.id
assert_template :partial => '_pdus'
assert_match /Error unplugging wrong node/, @response.body
end
# Clean run
assert_nothing_raised do
post :unplug_pdu, :id => @pdu.node_id, :pdus_id => @pdu.id
assert_template :partial => '_pdus'
end
assert_raise ActiveRecord::RecordNotFound do
Pdu.find(@pdu.id)
end
end
def test_add_switch_port
@node = create_node_by_controller :physical
@nsp = NetworkSwitchPort.make
assert_nothing_raised do
post :add_switch_port, :id => @node.node_id, :switch_port => @nsp
assert_match /Error plugging in port/, @response.body
assert_template :partial => '_switch_ports'
end
@switch = Node.make(:switch)
@nsp = NetworkSwitchPort.plan(:switch_id => @switch.id)
@node = Node.make(:physical, :datacenter_id => @switch.datacenter_id)
assert_nothing_raised do
assert_difference('NetworkSwitchPort.count', 1) do
post :add_switch_port, :id => @node.node_id, :switch_port => @nsp
assert_template :partial => '_switch_ports'
end
end
end
def test_remove_switch_port
@sw = NetworkSwitchPort.make
assert_nothing_raised do
post :remove_switch_port, :id => @sw.node_id, :port => @sw.id
assert_template :partial => '_switch_ports'
end
assert_raise ActiveRecord::RecordNotFound do
NetworkSwitchPort.find(@sw.id)
end
end
def test_add_disk
@node = create_node_by_controller :virtual
@disk = Disk.plan :iscsi, :disk_type => 'sandisk'
assert_difference('Disk.count') do
post :add_disk, :id => @node.node_id, :disk => @disk
assert_response :success
end
assert_template :partial => '_disks'
assert_not_nil @node.node_disks.detect{|nd| nd.block_name == "sdb"}
end
def test_remove_disk
@node = create_node_by_controller :virtual
@disk = Disk.make :file
@node.disks << @disk
assert_difference('@node.disks.count', -1) do
post :remove_disk, :id => @node.node_id, :disk => @disk.id
assert_response :success
end
assert_template :partial => '_disks'
end
def test_destroy
@node = Node.make(:virtual)
assert_nothing_raised do
Node.find(@node.node_id)
end
assert_nothing_raised do
post :destroy, :id => @node.node_id
assert_equal Hash.new, flash
assert_response :redirect
assert_redirected_to :controller => "node", :action => "list"
end
assert_raise ActiveRecord::RecordNotFound do
Node.find(@node.node_id)
end
end
def test_add_disk_increment_block_name_basic
add_disk_increment_block_name DiskType.file, DiskType.file, "sda2", "sda3"
add_disk_increment_block_name DiskType.file, DiskType.file, "sda2", "sda3", true
end
def test_add_disk_increment_block_name_iscsi
add_disk_increment_block_name DiskType.iscsi, DiskType.iscsi, "sda", "sdb"
add_disk_increment_block_name DiskType.iscsi, DiskType.iscsi, "sda", "sdb", true
end
def test_add_disk_increment_block_name_iscsi_sda1_to_sdb
add_disk_increment_block_name DiskType.iscsi, DiskType.iscsi, "sda1", "sdb"
add_disk_increment_block_name DiskType.iscsi, DiskType.iscsi, "sda1", "sdb", true
end
def test_add_disk_increment_block_name_xen_from_iscsi
add_disk_increment_block_name DiskType.iscsi, DiskType.file, "sda2", "sdb"
add_disk_increment_block_name DiskType.iscsi, DiskType.file, "sda2", "sdb", true
end
def test_add_disk_increment_block_name_iscsi_from_xen
add_disk_increment_block_name DiskType.file, DiskType.iscsi, "sda1", "sdb"
add_disk_increment_block_name DiskType.file, DiskType.iscsi, "sda1", "sdb", true
end
def test_add_disk_increment_block_name_digit_overflow
add_disk_increment_block_name DiskType.file, DiskType.file, "sda15", "sdb"
add_disk_increment_block_name DiskType.file, DiskType.file, "sda15", "sdb", true
end
def test_add_disk_already_at_largest
@disk = Disk.make :file
@node = Node.make :virtual
NodeDisk.make :node => @node, :disk => @disk, :block_name => "sddx15"
@disk = Disk.plan :file, :disk_type => 'xendisk'
post :add_disk, :id => @node.node_id, :disk => @disk
#FIXME: will always pass even if bad, should compare {} or Hash.new
#flash is (apparently) never nil, but an empty hash
assert_not_nil flash
end
def test_add_node_to_cluster
@node = Node.make(:virtual)
@cluster = Cluster.make
assert_nothing_raised do
post :add_node_to_cluster, :cluster => @cluster, :id => @node.node_id
assert_template :partial => '_clusters'
assert @cluster.reload.nodes.include? @node
end
assert_nothing_raised do
#We need to trigger a failure...
@node = Node.make(:virtual)
(@cluster.nodes << @node) and @cluster.save!
post :add_node_to_cluster, :cluster => @cluster, :id => @node.node_id
assert_template :partial => '_clusters'
# FIXME: This doesn't show, like it is supposed to. BUG.
assert_match /Error node already in cluster/, @response.body, 'FIXME: kris expects this to fail'
end
end
def test_map_to_xen_host
#FIXME: If node is :physical we fail silentley across the board
@node = Node.make :virtual
@xm = XenMapping.plan
assert_nothing_raised do
post :map_to_xen_host, :id => @node.node_id, :xen_mapping => @xm
assert_template :partial => '_xen'
puts @response.body
assert_instance_of XenMapping,
XenMapping.find(:first, :conditions => {
:guest_id => @node.node_id,
:host_id => @xm[:host_id] })
end
end
def test_add_xen_guest
@node = Node.make :virtual
@xm = XenMapping.make
assert_nothing_raised do
post :map_to_xen_host, :id => @node.node_id, :xen_mapping => @xm
assert_template :partial => '_xen'
end
end
def test_remove_from_xen_host
@xm = XenMapping.make
assert_nothing_raised do
post :remove_from_xen_host, :id => @xm.guest_id
assert_response :success
assert_template :partial => '_xen'
end
assert_raise ActiveRecord::RecordNotFound do
XenMapping.find @xm.id
end
end
def test_remove_xen_guest
@xm = XenMapping.make
assert_nothing_raised do
post :remove_xen_guest, :id => @xm.host_id, :guest_id => @xm.guest_id
assert_response :success
assert_template :partial => '_xen'
end
assert_raise ActiveRecord::RecordNotFound do
XenMapping.find @xm.id
end
end
#def test_modify_nodes
#end
#def test_modify_disks
#end
#def test_sanitize_search
#end
#def test_set_xen_info
#end
#def test_create_xen_mapping
#end
private
def add_disk_increment_block_name(existing_type, adding_type, existing_block, assert_block, physical=false)
if existing_type == DiskType.file
@disk = Disk.make :file
else
@disk = Disk.make :iscsi
end
@node = physical ? Node.make(:physical) : Node.make(:virtual)
NodeDisk.make :node => @node, :disk => @disk, :block_name => existing_block.to_s
if adding_type == DiskType.file
@disk = Disk.plan :file, :disk_type => 'xendisk'
else
@disk = Disk.plan :iscsi, :disk_type => 'sandisk'
end
post :add_disk, :id => @node.node_id, :disk => @disk
assert_response :success
assert_nil flash[:error]
assert @node.disks.detect{|d| d.block_name(@node) == assert_block}
assert_template :partial => '_disks'
end
def random_element(arr)
arr.sort_by{ rand }.first
end
public
end
| 31.477974 | 109 | 0.67637 |
010e58a6c21655d541301c1369906795a098776f | 3,230 | # frozen_string_literal: true
module Funding
class BursaryForm < TraineeForm
FIELDS = %i[
funding_type
applying_for_bursary
bursary_tier
applying_for_scholarship
applying_for_grant
].freeze
NON_TRAINEE_FIELDS = %i[
funding_type
].freeze
NONE_TYPE = "none"
FUNDING_TYPES = (Trainee.bursary_tiers.keys + FUNDING_TYPE_ENUMS.values + [NONE_TYPE]).freeze
attr_accessor(*FIELDS)
validates :funding_type, inclusion: { in: FUNDING_TYPES }
delegate :can_apply_for_scholarship?, :can_apply_for_tiered_bursary?,
:can_apply_for_grant?, :grant_amount,
:scholarship_amount, to: :funding_manager
def initialize(trainee, params: {}, user: nil, store: FormStore)
params = add_fields_from_params(params)
super(trainee, params: params, user: user, store: store)
end
def view_partial
if can_apply_for_grant?
"grant_form"
elsif can_apply_for_tiered_bursary?
"tiered_bursary_form"
else
"non_tiered_bursary_form"
end
end
private
def compute_fields
opts = trainee.attributes.symbolize_keys.slice(*FIELDS)
opts = add_funding_type_from_db(opts)
opts.merge!(new_attributes)
opts
end
def funding_manager
@funding_manager ||= FundingManager.new(trainee)
end
def add_funding_type_from_db(opts)
opts[:funding_type] =
if trainee.bursary_tier.present?
trainee.bursary_tier
elsif trainee.applying_for_bursary?
FUNDING_TYPE_ENUMS[:bursary]
elsif trainee.applying_for_scholarship?
FUNDING_TYPE_ENUMS[:scholarship]
elsif trainee.applying_for_grant?
FUNDING_TYPE_ENUMS[:grant]
elsif (trainee.applying_for_bursary == false) ||
(trainee.applying_for_scholarship == false) ||
(trainee.applying_for_grant == false)
NONE_TYPE
end
opts
end
def add_fields_from_params(opts)
case opts[:funding_type]
when *Trainee.bursary_tiers.keys
opts[:bursary_tier] = opts[:funding_type]
opts[:applying_for_bursary] = true
opts[:applying_for_scholarship] = false
opts[:applying_for_grant] = false
when FUNDING_TYPE_ENUMS[:bursary]
opts[:bursary_tier] = nil
opts[:applying_for_bursary] = true
opts[:applying_for_scholarship] = false
opts[:applying_for_grant] = false
when FUNDING_TYPE_ENUMS[:scholarship]
opts[:bursary_tier] = nil
opts[:applying_for_bursary] = false
opts[:applying_for_scholarship] = true
opts[:applying_for_grant] = false
when FUNDING_TYPE_ENUMS[:grant]
opts[:bursary_tier] = nil
opts[:applying_for_bursary] = false
opts[:applying_for_scholarship] = false
opts[:applying_for_grant] = true
when NONE_TYPE
opts[:bursary_tier] = nil
opts[:applying_for_bursary] = false
opts[:applying_for_scholarship] = false
opts[:applying_for_grant] = false
end
opts
end
def form_store_key
:bursary
end
def fields_to_ignore_before_save
NON_TRAINEE_FIELDS
end
end
end
| 28.333333 | 97 | 0.663777 |
611b27f154a85e4d9f8af1c48c6aa85457112992 | 488 | namespace 'mk' do
desc 'Create a new migration at migrations/YYYYMMDDHHMMSS_name.rb'
task :migration, :name do |_, args|
make_class_template "migrations/#{Time.now.utc.strftime('%Y%m%d%H%M%S')}_#{args[:name]}.rb", "class #{args[:name].camelize} < ActiveRecord::Migration"
end
desc 'Create a new model at models/name.rb'
task :model, :name do |_, args|
make_class_template "models/#{args[:name]}.rb", "class Kit::#{args[:name].camelize} < ActiveRecord::Base"
end
end
| 37.538462 | 154 | 0.688525 |
f82c8ddef2ab7b73f9e8112eecd26dc6f6ca1a30 | 1,526 | require 'carrierwave'
require 'remotipart'
require 'bootsy/engine'
require 'bootsy/container'
require 'bootsy/form_helper'
require 'bootsy/form_builder'
require 'bootsy/core_ext'
autoload :BootsyInput, 'bootsy/simple_form/bootsy_input'
# Public: Top Bootsy module
module Bootsy
## CONFIGURATION OPTIONS
# Default editor options
mattr_accessor :editor_options
@@editor_options = {
font_styles: true,
emphasis: true,
lists: true,
html: false,
link: true,
image: true,
color: true
}
# Image versions available
mattr_accessor :image_versions_available
@@image_versions_available = [:small, :medium, :large, :original]
# Whether user can destroy uploaded files
mattr_accessor :allow_destroy
@@allow_destroy = true
# Settings for small images
mattr_accessor :small_image
@@small_image = { width: 160, height: 160 }
# Settings for medium images
mattr_accessor :medium_image
@@medium_image = { width: 360, height: 360 }
# Settings for large images
mattr_accessor :large_image
@@large_image = { width: 760, height: 760 }
# Settings for the original version of images
mattr_accessor :original_image
@@original_image = {}
# Storage mode
mattr_accessor :storage
@@storage = :file
# Store directory (inside 'public')
mattr_accessor :store_dir
@@store_dir = 'uploads'
# Default way to setup Bootsy. Run rails generate bootsy:install
# to create a fresh initializer with all configuration values.
def self.setup
yield self
end
end
| 23.476923 | 67 | 0.728047 |
fff3b28b9411d9a7bf93a3accfd3a9a553b15a9c | 1,273 | gem 'dm-core', '~>0.9.10'
require 'dm-core'
module DataMapper
module Resource
class << self
alias_method :_dm_shorthand_included, :included
def included(target)
_dm_shorthand_included(target)
parentname, basename = target.name.split /::(?=\w+$)/
if basename
parent = parentname.split(/::/).inject(Kernel) { |mod, str| mod.const_get(str) }
else
basename = parentname
parent = Kernel
end
eval(<<-EOS, binding, __FILE__, __LINE__)
class << parent
def #{basename}(repository_name)
class_cache[repository_name] ||= begin
klass = Class.new(#{target.name})
klass.instance_eval do
(class << self; self; end).send(:define_method, :_repository_name) do
repository_name
end
private
def default_repository_name
@repository_name ||= _repository_name
end
end
klass
end
end
private
def class_cache
@class_cache ||= {}
end
end
EOS
end
end
end
end
| 24.018868 | 90 | 0.495679 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.