Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix monsters search not outputting anything | module FelyneBot
module Commands
module Wiki
extend Discordrb::Commands::CommandContainer
command(
:wiki,
description: "Searches the Wiki",
useage: "wiki <search>"
) do |event, list, *search|
search = search.join(' ')
if list == 'mats'
event << "<http://monsterhunteronline.in/materials/?search=#{search}>"
else
if list == 'skill'
event << "<http://monsterhunteronline.in/skills/?search=#{search}>"
else
if list == 'armor'
event << "<http://monsterhunteronline.in/armor/?search=#{search}>"
else
wiki = IO.readlines("bot/wiki")[0]
wiki = wiki.split(",")
links = ""
wiki.grep(/#{list}/).each { |x| links << "<http://monsterhunteronline.in/#{x}> \n" }
if links.length > 2000
event << "Output has too many characters. Please be more specific in your search."
else
if links.length < 1
event << "I wasn't able to dig up any results. Please try something else!"
else
event << links
end
end
end
end
end
puts "#{event.timestamp}: #{event.user.name}: CMD: wiki"
nil
end
end
end
end | module FelyneBot
module Commands
module Wiki
extend Discordrb::Commands::CommandContainer
command(
:wiki,
description: "Searches the Wiki",
useage: "wiki <search>"
) do |event, list, *search|
search = search.join(' ')
if list == 'mats'
event << "<http://monsterhunteronline.in/materials/?search=#{search}>"
else
if list == 'skill'
event << "<http://monsterhunteronline.in/skills/?search=#{search}>"
else
if list == 'armor'
event << "<http://monsterhunteronline.in/armor/?search=#{search}>"
else
if list == 'monsters'
event << "<http://monsterhunteronline.in/monsters>"
else
wiki = IO.readlines("bot/wiki")[0]
wiki = wiki.split(",")
links = ""
wiki.grep(/#{list}/).each { |x| links << "<http://monsterhunteronline.in/#{x}> \n" }
if links.length > 2000
event << "Output has too many characters. Please be more specific in your search."
else
if links.length < 1
event << "I wasn't able to dig up any results. Please try something else!"
else
event << links
end
end
end
end
end
end
puts "#{event.timestamp}: #{event.user.name}: CMD: wiki"
nil
end
end
end
end |
Add warning when you have no database config | file "config/database.yml.template" do |task|
abort "I don't know what to tell you, dude. There's no #{task.name}. So maybe you should make one of those, and see where that gets you."
end
file "config/database.yml" => "config/database.yml.template" do |task|
puts "Dude! I found #{task.prerequisites.first}, so I'll make a copy of it for you."
cp task.prerequisites.first, task.name
abort "Make sure it's cromulent to your setup, then rerun the last command."
end
task :environment => "config/database.yml"
| |
Fix parsing Pipfile when version isn't defined | # frozen_string_literal: true
require 'json'
require 'license_finder/package_utils/pypi'
module LicenseFinder
class Pipenv < PackageManager
def initialize(options = {})
super
@lockfile = Pathname('Pipfile.lock')
end
def current_packages
@current_packages ||=
begin
packages = {}
each_dependency(groups: allowed_groups) do |name, data, group|
version = canonicalize(data['version'])
package = packages.fetch(key_for(name, version)) do |key|
packages[key] = build_package_for(name, version)
end
package.groups << group
end
packages.values
end
end
def possible_package_paths
project_path ? [project_path.join(@lockfile)] : [@lockfile]
end
private
def each_dependency(groups: [])
dependencies = JSON.parse(IO.read(detected_package_path))
groups.each do |group|
dependencies[group].each do |name, data|
yield name, data, group
end
end
end
def canonicalize(version)
version.sub(/^==/, '')
end
def build_package_for(name, version)
PipPackage.new(name, version, PyPI.definition(name, version))
end
def key_for(name, version)
"#{name}-#{version}"
end
def allowed_groups
%w[default develop] - ignored_groups.to_a
end
def ignored_groups
@ignored_groups || []
end
end
end
| # frozen_string_literal: true
require 'json'
require 'license_finder/package_utils/pypi'
module LicenseFinder
class Pipenv < PackageManager
def initialize(options = {})
super
@lockfile = Pathname('Pipfile.lock')
end
def current_packages
@current_packages ||=
begin
packages = {}
each_dependency(groups: allowed_groups) do |name, data, group|
version = canonicalize(data['version'] || 'unknown')
package = packages.fetch(key_for(name, version)) do |key|
packages[key] = build_package_for(name, version)
end
package.groups << group
end
packages.values
end
end
def possible_package_paths
project_path ? [project_path.join(@lockfile)] : [@lockfile]
end
private
def each_dependency(groups: [])
dependencies = JSON.parse(IO.read(detected_package_path))
groups.each do |group|
dependencies[group].each do |name, data|
yield name, data, group
end
end
end
def canonicalize(version)
version.sub(/^==/, '')
end
def build_package_for(name, version)
PipPackage.new(name, version, PyPI.definition(name, version))
end
def key_for(name, version)
"#{name}-#{version}"
end
def allowed_groups
%w[default develop] - ignored_groups.to_a
end
def ignored_groups
@ignored_groups || []
end
end
end
|
Send the patches to the mailing list. | class Vcs
# See http://rubyforge.org/projects/vcs
# and http://vcs.rubyforge.org
protocol_version '0.1'
def local_commit! ( *args )
common_commit!("k2.0 <%= rev %>: <%= title %>", *args) do |subject|
mail!(:to => %w[kernelteam@gostai.com],
:subject => subject)
end
end
default_commit :local_commit
end # class Vcs
| class Vcs
# See http://rubyforge.org/projects/vcs
# and http://vcs.rubyforge.org
protocol_version '0.1'
def local_commit! ( *args )
common_commit!("k2.0 <%= rev %>: <%= title %>", *args) do |subject|
mail!(:to => %w[kernel-patches@lists.gostai.com],
:subject => subject)
end
end
default_commit :local_commit
end # class Vcs
|
Use version 2 of appliance console | # Add gems here, in Gemfile syntax, which are dependencies of the appliance itself rather than a part of the ManageIQ application
gem "manageiq-appliance_console", "~>1.2", ">=1.2.4", :require => false
gem "manageiq-postgres_ha_admin", "~>1.0.0", :require => false
| # Add gems here, in Gemfile syntax, which are dependencies of the appliance itself rather than a part of the ManageIQ application
gem "manageiq-appliance_console", "~>2.0", :require => false
gem "manageiq-postgres_ha_admin", "~>1.0.0", :require => false
|
Fix glob match for cached bp in write pivnet metadata | #!/usr/bin/env ruby
root_dir = Dir.pwd
require_relative 'buildpack-pivnet-metadata-writer'
require_relative "#{root_dir}/buildpacks-ci/lib/git-client"
buildpack = ENV.fetch('BUILDPACK')
metadata_dir = File.join(root_dir, 'pivnet-buildpack-metadata', 'pivnet-metadata')
buildpack_dir = File.join(root_dir, 'buildpack')
recent_changes_filename = File.join(root_dir, 'buildpack-artifacts', 'RECENT_CHANGES')
buildpack_files = ''
Dir.chdir('pivotal-buildpacks-cached') do
buildpack_files = Dir["#{buildpack}_buildpack-cached-*-v*.zip"]
end
if buildpack_files.count != 1
puts "Expected 1 cached buildpack file, found #{buildpack_files.count}:"
puts buildpack_files
exit 1
else
cached_buildpack_filename = buildpack_files.first
writer = BuildpackPivnetMetadataWriter.new(buildpack, metadata_dir, buildpack_dir, cached_buildpack_filename, recent_changes_filename)
writer.run!
Dir.chdir(metadata_dir) do
GitClient.add_file("#{buildpack}.yml")
GitClient.safe_commit("Create Pivnet release metadata for #{buildpack.capitalize} buildpack v#{writer.get_version}")
end
system("rsync -a pivnet-buildpack-metadata/ pivnet-buildpack-metadata-artifacts")
end
| #!/usr/bin/env ruby
root_dir = Dir.pwd
require_relative 'buildpack-pivnet-metadata-writer'
require_relative "#{root_dir}/buildpacks-ci/lib/git-client"
buildpack = ENV.fetch('BUILDPACK')
metadata_dir = File.join(root_dir, 'pivnet-buildpack-metadata', 'pivnet-metadata')
buildpack_dir = File.join(root_dir, 'buildpack')
recent_changes_filename = File.join(root_dir, 'buildpack-artifacts', 'RECENT_CHANGES')
buildpack_files = ''
Dir.chdir('pivotal-buildpacks-cached') do
buildpack_files = Dir["#{buildpack}_buildpack-cached*-v*.zip"]
end
if buildpack_files.count != 1
puts "Expected 1 cached buildpack file, found #{buildpack_files.count}:"
puts buildpack_files
exit 1
else
cached_buildpack_filename = buildpack_files.first
writer = BuildpackPivnetMetadataWriter.new(buildpack, metadata_dir, buildpack_dir, cached_buildpack_filename, recent_changes_filename)
writer.run!
Dir.chdir(metadata_dir) do
GitClient.add_file("#{buildpack}.yml")
GitClient.safe_commit("Create Pivnet release metadata for #{buildpack.capitalize} buildpack v#{writer.get_version}")
end
system("rsync -a pivnet-buildpack-metadata/ pivnet-buildpack-metadata-artifacts")
end
|
Send patches to the right ML. | class Vcs
# See http://rubyforge.org/projects/vcs
# and http://vcs.rubyforge.org
protocol_version '0.1'
def local_commit! ( *args )
common_commit!("k1 <%= rev %>: <%= title %>", *args) do |subject|
mail!(:to => %w[kernel1@gostai.com],
:subject => subject)
end
end
default_commit :local_commit
end # class Vcs
| class Vcs
# See http://rubyforge.org/projects/vcs
# and http://vcs.rubyforge.org
protocol_version '0.1'
def local_commit! ( *args )
common_commit!("k1 <%= rev %>: <%= title %>", *args) do |subject|
mail!(:to => %w[kernel-patches@lists.gostai.com],
:subject => subject)
end
end
default_commit :local_commit
end # class Vcs
|
Fix redirect to nil on comment creation | class Site::CommentsController < ApplicationController
def index
@site_comments = SiteComment.order('created_at desc').page params[:page]
end
def new
@site_comment = current_user ? current_user.site_comments.new : SiteComment.new
end
def create
@site_comment = SiteComment.new permitted_params
@site_comment.user = current_user if current_user
if @site_comment.save
set_flash_message(:success)
redirect_to request.referer
else
render 'new', status: :conflict
end
end
def destroy
@site_comment = SiteComment.find params[:id]
if @site_comment.destroy
set_flash_message(:success)
else
set_flash_message(:failure)
end
end
protected
def permitted_params
params.require(:site_comment).permit :name, :email, :body, :context_url, :context_data
end
end
| class Site::CommentsController < ApplicationController
def index
@site_comments = SiteComment.order('created_at desc').page params[:page]
end
def new
@site_comment = current_user ? current_user.site_comments.new : SiteComment.new
end
def create
@site_comment = SiteComment.new permitted_params
@site_comment.user = current_user if current_user
if @site_comment.save
set_flash_message(:success)
redirect_to request.referer || root_path
else
render 'new', status: :conflict
end
end
def destroy
@site_comment = SiteComment.find params[:id]
if @site_comment.destroy
set_flash_message(:success)
else
set_flash_message(:failure)
end
end
protected
def permitted_params
params.require(:site_comment).permit :name, :email, :body, :context_url, :context_data
end
end
|
Add cache for crazy speed boost | require "parslet"
require "expgen/version"
require "expgen/parser"
require "expgen/transform"
require "expgen/randomizer"
module Expgen
def self.gen(exp)
Randomizer.randomize(Transform.new.apply((Parser.new.parse(exp.source))))
end
end
| require "parslet"
require "expgen/version"
require "expgen/parser"
require "expgen/transform"
require "expgen/randomizer"
module Expgen
def self.cache
@cache ||= {}
end
def self.clear_cache
@cache = nil
end
def self.gen(exp)
cache[exp.source] ||= Transform.new.apply((Parser.new.parse(exp.source)))
Randomizer.randomize(cache[exp.source])
end
end
|
Update Podspec to version 0.0.2 | Pod::Spec.new do |s|
s.name = "CCKit"
s.version = "0.0.1"
s.summary = "Cliq Consulting reusable components for iOS."
s.description = <<-DESC
Helpers, MACROS and MVC iOS components provided by Cliq Consulting.
* Lifecycle management for network based models
* Twitter Login Manager
DESC
s.homepage = "http://cliqconsulting.com"
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.authors = { "Glenn Marcus" => "glenn@cliqconsulting.com", "Leonardo Lobato" => "leo@cliqconsulting.com" }
s.social_media_url = "http://twitter.com/cliqconsulting"
s.platform = :ios, '6.0'
s.source = { :git => "git@cliqconsulting.unfuddle.com:cliqconsulting/cckit.git", :tag => s.version.to_s }
s.source_files = 'CCKit/**/*.{h,m}'
s.exclude_files = 'CCKit/CCTwitterLoginManager.{h,m}', 'CCKit/OAuthCore/*', 'CCKit/TWiOSReverseAuth/*'
s.requires_arc = true
s.ios.xcconfig = { 'HEADER_SEARCH_PATHS' => '$(PODS_ROOT)/../../CCKit/**' }
end
| Pod::Spec.new do |s|
s.name = "CCKit"
s.version = "0.0.2"
s.summary = "Cliq Consulting reusable components for iOS."
s.description = <<-DESC
Helpers, MACROS and MVC iOS components provided by Cliq Consulting.
* Lifecycle management for network based models
* Common views, view controllers, collection layouts, collection cells and helpers
DESC
s.homepage = "http://cliqconsulting.com"
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.authors = { "Glenn Marcus" => "glenn@cliqconsulting.com", "Leonardo Lobato" => "leo@cliqconsulting.com" }
s.social_media_url = "http://twitter.com/cliqconsulting"
s.platform = :ios, '7.0'
s.source = { :git => "git@cliqconsulting.unfuddle.com:cliqconsulting/cckit.git", :tag => s.version.to_s }
s.source_files = 'CCKit/**/*.{h,m}'
s.exclude_files = 'CCKit/CCTwitterLoginManager.{h,m}', 'CCKit/OAuthCore/*', 'CCKit/TWiOSReverseAuth/*'
s.requires_arc = true
s.ios.xcconfig = { 'HEADER_SEARCH_PATHS' => '$(PODS_ROOT)/../../CCKit/**' }
end
|
Add ApplicationRecordLite that is for holding is and class of AR | module ManagerRefresh
class ApplicationRecordLite
attr_reader :base_class_name, :id
# ApplicationRecord is very bloaty in memory, so this class server for storing base_class and primary key
# of the ApplicationRecord, which is just enough for filling up relationships
def initialize(base_class_name, id)
@base_class_name = base_class_name
@id = id
end
end
end
| |
Fix another old style AR query. | class Checkin::GroupsController < ApplicationController
def index
@groups = {}
date = params[:date] ? Date.parse(params[:date]) : Date.today
CheckinTime.for_date(date, params[:campus]).each do |time|
@groups[time.time_to_s] = time.groups.order('group_times.ordering')
.select('group_times.print_nametag, group_times.section, groups.*')
.map { |g| [g.id, g.name, g.print_nametag?, g.link_code, g.section] }
.group_by { |g| g[4].to_s }
end
respond_to do |format|
format.json do
render :text => {
'groups' => @groups,
'updated_at' => GroupTime.last(:order => 'updated_at').updated_at
}.to_json
end
end
end
end
| class Checkin::GroupsController < ApplicationController
def index
@groups = {}
date = params[:date] ? Date.parse(params[:date]) : Date.today
CheckinTime.for_date(date, params[:campus]).each do |time|
@groups[time.time_to_s] = time.groups.order('group_times.ordering')
.select('group_times.print_nametag, group_times.section, groups.*')
.map { |g| [g.id, g.name, g.print_nametag?, g.link_code, g.section] }
.group_by { |g| g[4].to_s }
end
respond_to do |format|
format.json do
render :text => {
'groups' => @groups,
'updated_at' => GroupTime.order('updated_at').last.updated_at
}.to_json
end
end
end
end
|
Configure block should work correctly now. | require "has_face/configuration"
require "has_face/version"
require "has_face/validator"
module HasFace
# Add load paths straight to I18n, so engines and application can overwrite it.
require 'i18n'
I18n.load_path << File.expand_path('../has_face/locales/en.yml', __FILE__)
class << self
configs = [ :api_key, :api_secret, :enable_validation, :detect_url]
configs.each do |config|
delegate config, "#{config}=", :to => HasFace::Configuration
end
end
end
| require "has_face/configuration"
require "has_face/version"
require "has_face/validator"
module HasFace
# Add load paths straight to I18n, so engines and application can overwrite it.
require 'i18n'
I18n.load_path << File.expand_path('../has_face/locales/en.yml', __FILE__)
class << self
configs = [ :api_key, :api_secret, :enable_validation, :detect_url]
configs.each do |config|
delegate config, "#{config}=", :to => HasFace::Configuration
end
def configure
yield self
end
end
end
|
Load together all properties that are lazy-designated but not yet loaded. | require 'forwardable'
module DataMapper
module Validations
##
#
# @author Guy van den Berg
# @since 0.9
class ContextualValidators
extend Forwardable
#
# Delegators
#
def_delegators :@contexts, :empty?, :each
include Enumerable
attr_reader :contexts
def initialize
@contexts = {}
end
#
# API
#
# Return an array of validators for a named context
#
# @param [String]
# Context name for which return validators
# @return [Array<DataMapper::Validations::GenericValidator>]
# An array of validators
def context(name)
contexts[name] ||= []
end
# Clear all named context validators off of the resource
#
def clear!
contexts.clear
end
# Execute all validators in the named context against the target
#
# @param [Symbol]
# named_context the context we are validating against
# @param [Object]
# target the resource that we are validating
# @return [Boolean]
# true if all are valid, otherwise false
def execute(named_context, target)
target.errors.clear!
context(named_context).map do |validator|
validator.execute?(target) ? validator.call(target) : true
end.all?
end
end # module ContextualValidators
end # module Validations
end # module DataMapper
| require 'forwardable'
module DataMapper
module Validations
##
#
# @author Guy van den Berg
# @since 0.9
class ContextualValidators
extend Forwardable
#
# Delegators
#
def_delegators :@contexts, :empty?, :each
include Enumerable
attr_reader :contexts
def initialize
@contexts = {}
end
#
# API
#
# Return an array of validators for a named context
#
# @param [String]
# Context name for which return validators
# @return [Array<DataMapper::Validations::GenericValidator>]
# An array of validators
def context(name)
contexts[name] ||= []
end
# Clear all named context validators off of the resource
#
def clear!
contexts.clear
end
# Execute all validators in the named context against the target. Load
# together any properties that are designated lazy but are not yet loaded.
#
# @param [Symbol]
# named_context the context we are validating against
# @param [Object]
# target the resource that we are validating
# @return [Boolean]
# true if all are valid, otherwise false
def execute(named_context, target)
target.errors.clear!
validators = context(named_context).select { |validator| validator.execute?(target) }
# Load all lazy, not-yet-loaded, needs-to-be-validated properties.
need_to_load = validators.map{ |v| target.class.properties[v.field_name] }.select { |p| p.lazy? && !p.loaded?(target) }
target.__send__(:eager_load, need_to_load)
validators.map { |validator| validator.call(target) }.all?
end
end # module ContextualValidators
end # module Validations
end # module DataMapper
|
Update uBar to version 3.0.3 | cask :v1 => 'ubar' do
version '2.5.0'
sha256 '0b5388a7bd599d48836e08b9138acc0c802aa86e65d6128f66e03a734eb2a823'
url "http://www.brawersoftware.com/downloads/ubar/ubar#{version.delete('.')}.zip"
appcast "http://brawersoftware.com/appcasts/feeds/ubar/ubar#{version.to_i}.xml",
:sha256 => 'bc407a2ec6071e585a0a3843b49f7df32a7a38a77dafd79cc63e8ae197f21d13'
name 'uBar'
homepage 'http://brawersoftware.com/products/ubar'
license :commercial
app 'uBar.app'
depends_on :macos => '>= :mavericks'
end
| cask :v1 => 'ubar' do
version '3.0.3'
sha256 '6e3d650aa0560e7f71c4e4b68f1fd175c1c76a9611fc7f2def7d0fe53ba383fc'
url "http://www.brawersoftware.com/downloads/ubar/ubar#{version.delete('.')}.zip"
appcast "http://brawersoftware.com/appcasts/feeds/ubar/ubar#{version.to_i}.xml",
:sha256 => 'bc407a2ec6071e585a0a3843b49f7df32a7a38a77dafd79cc63e8ae197f21d13'
name 'uBar'
homepage 'http://brawersoftware.com/products/ubar'
license :commercial
app 'uBar.app'
depends_on :macos => '>= :mavericks'
end
|
Fix homepage to use SSL in f.lux Cask | cask :v1 => 'flux' do
version :latest
sha256 :no_check
url 'https://justgetflux.com/mac/Flux.zip'
appcast 'https://justgetflux.com/mac/macflux.xml'
name 'f.lux'
homepage 'http://justgetflux.com'
license :gratis
app 'Flux.app'
postflight do
suppress_move_to_applications
end
zap :delete => '~/Library/Preferences/org.herf.Flux.plist'
end
| cask :v1 => 'flux' do
version :latest
sha256 :no_check
url 'https://justgetflux.com/mac/Flux.zip'
appcast 'https://justgetflux.com/mac/macflux.xml'
name 'f.lux'
homepage 'https://justgetflux.com/'
license :gratis
app 'Flux.app'
postflight do
suppress_move_to_applications
end
zap :delete => '~/Library/Preferences/org.herf.Flux.plist'
end
|
Add .gemspec to gem so that the ':path' option in Gemfile works | version_file = File.expand_path('lib/union_station_hooks_core/version_data.rb', File.dirname(__FILE__))
version_data = eval(File.read(version_file))
Gem::Specification.new do |s|
s.name = "union_station_hooks_core"
s.version = version_data[:string]
s.authors = ["Hongli Lai"]
s.description = "Union Station Ruby hooks core code."
s.summary = "Union Station Ruby hooks core code"
s.email = "info@phusion.nl"
s.license = "MIT"
s.files = Dir[
"README.md",
"LICENSE.md",
"lib/**/*"
]
s.homepage = "https://github.com/phusion/union_station_hooks_core"
s.require_paths = ["lib"]
# DO NOT ADD ANY FURTHER DEPENDENCIES! See hacking/Vendoring.md,
# section "No dependencies", for more information.
end
| version_file = File.expand_path('lib/union_station_hooks_core/version_data.rb', File.dirname(__FILE__))
version_data = eval(File.read(version_file))
Gem::Specification.new do |s|
s.name = "union_station_hooks_core"
s.version = version_data[:string]
s.authors = ["Hongli Lai"]
s.description = "Union Station Ruby hooks core code."
s.summary = "Union Station Ruby hooks core code"
s.email = "info@phusion.nl"
s.license = "MIT"
s.files = Dir[
"README.md",
"LICENSE.md",
"*.gemspec",
"lib/**/*"
]
s.homepage = "https://github.com/phusion/union_station_hooks_core"
s.require_paths = ["lib"]
# DO NOT ADD ANY FURTHER DEPENDENCIES! See hacking/Vendoring.md,
# section "No dependencies", for more information.
end
|
Refactor the ReplacementIdUpdates class for readability | class AssetManager::AttachmentUpdater::ReplacementIdUpdates
def self.call(attachment_data)
return [] unless attachment_data.replaced?
replacement = attachment_data.replaced_by
Enumerator.new do |enum|
enum.yield AssetManager::AttachmentUpdater::Update.new(
attachment_data, attachment_data.file, replacement_legacy_url_path: replacement.file.asset_manager_path
)
if attachment_data.pdf?
if replacement.pdf?
enum.yield AssetManager::AttachmentUpdater::Update.new(
attachment_data, attachment_data.file.thumbnail, replacement_legacy_url_path: replacement.file.thumbnail.asset_manager_path
)
else
enum.yield AssetManager::AttachmentUpdater::Update.new(
attachment_data, attachment_data.file.thumbnail, replacement_legacy_url_path: replacement.file.asset_manager_path
)
end
end
end
end
end
| class AssetManager::AttachmentUpdater::ReplacementIdUpdates
def self.call(attachment_data)
return [] unless attachment_data.replaced?
replacement = attachment_data.replaced_by
Enumerator.new do |enum|
enum.yield(
AssetManager::AttachmentUpdater::Update.new(
attachment_data,
attachment_data.file,
replacement_legacy_url_path: replacement.file.asset_manager_path,
),
)
if attachment_data.pdf?
replacement_legacy_url_path = if replacement.pdf?
replacement.file.thumbnail.asset_manager_path
else
replacement.file.asset_manager_path
end
enum.yield(
AssetManager::AttachmentUpdater::Update.new(
attachment_data,
attachment_data.file.thumbnail,
replacement_legacy_url_path: replacement_legacy_url_path,
),
)
end
end
end
end
|
Bump gem version to 0.0.3 | Gem::Specification.new do |s|
s.name = 'academic_benchmarks'
s.version = '0.0.2'
s.date = '2015-12-07'
s.summary = "A ruby api for accessing the Academic Benchmarks API"
s.description = "A ruby api for accessing the Academic Benchmarks API. " \
"A valid subscription with accompanying credentials " \
"will be required to access the API"
s.authors = ["Benjamin Porter"]
s.email = 'bporter@instructure.com'
s.files = ['lib/academic_benchmarks.rb'] + Dir['lib/academic_benchmarks/**/*']
s.homepage = 'https://github.com/instructure/academic_benchmarks'
s.license = 'AGPL-3.0'
s.add_runtime_dependency 'httparty', '~> 0.13'
s.add_runtime_dependency "activesupport", ">= 3.2.22", "<= 4.2"
s.add_development_dependency "byebug", '~> 4.0'
s.add_development_dependency "rspec", "~> 3.1"
s.add_development_dependency "awesome_print", "~> 1.6"
end
| Gem::Specification.new do |s|
s.name = 'academic_benchmarks'
s.version = '0.0.3'
s.date = '2015-12-18'
s.summary = "A ruby api for accessing the Academic Benchmarks API"
s.description = "A ruby api for accessing the Academic Benchmarks API. " \
"A valid subscription with accompanying credentials " \
"will be required to access the API"
s.authors = ["Benjamin Porter"]
s.email = 'bporter@instructure.com'
s.files = ['lib/academic_benchmarks.rb'] + Dir['lib/academic_benchmarks/**/*']
s.homepage = 'https://github.com/instructure/academic_benchmarks'
s.license = 'AGPL-3.0'
s.add_runtime_dependency 'httparty', '~> 0.13'
s.add_runtime_dependency "activesupport", ">= 3.2.22", "<= 4.2"
s.add_development_dependency "byebug", '~> 4.0'
s.add_development_dependency "rspec", "~> 3.1"
s.add_development_dependency "awesome_print", "~> 1.6"
end
|
Add a method to copy the boostrap.css file into the Rails application | require "frontend_generators/version"
module FrontendGenerators
class Bootstrap
def run
end
def bootstrap_css
File.join(root, "assets", "bootstrap", "bootstrap.css")
end
def root
File.expand_path("../", File.dirname(__FILE__))
end
end
end
| require "frontend_generators/version"
module FrontendGenerators
class Bootstrap
def run
FileUtils.cp(bootstrap_css, css_destination)
end
def css_destination
File.join(Rails.root, "vendor", "stylesheets", "bootstrap.css")
end
def bootstrap_css
File.join(root, "assets", "bootstrap", "bootstrap.css")
end
def root
File.expand_path("../", File.dirname(__FILE__))
end
end
end
|
Remove sass-rails as a dependency | require "brewery/engine"
require "brewery/auth_core"
require "jquery-rails"
require "sass-rails"
require "coffee-rails"
require "bootstrap-sass"
require "authlogic"
require "cancan"
require "will_paginate"
require "crummy"
require "email_validator"
require "simple_form"
module Brewery
end
| require "brewery/engine"
require "brewery/auth_core"
require "jquery-rails"
require "coffee-rails"
require "bootstrap-sass"
require "authlogic"
require "cancan"
require "will_paginate"
require "crummy"
require "email_validator"
require "simple_form"
module Brewery
end
|
Use alias_method instead of alias_method_chain | require "active_support/core_ext/module/aliasing.rb"
require "active_support/core_ext/hash/reverse_merge.rb"
class Money
def format_with_settings(*rules)
rules = normalize_formatting_rules(rules)
# Apply global defaults for money only for non-nil values
defaults = {
no_cents_if_whole: MoneyRails::Configuration.no_cents_if_whole,
symbol: MoneyRails::Configuration.symbol,
sign_before_symbol: MoneyRails::Configuration.sign_before_symbol
}.reject { |_k, v| v.nil? }
rules.reverse_merge!(defaults)
unless MoneyRails::Configuration.default_format.nil?
rules.reverse_merge!(MoneyRails::Configuration.default_format)
end
format_without_settings(rules)
end
alias_method_chain :format, :settings
end
| require "active_support/core_ext/module/aliasing.rb"
require "active_support/core_ext/hash/reverse_merge.rb"
class Money
alias_method :orig_format, :format
def format(*rules)
rules = normalize_formatting_rules(rules)
# Apply global defaults for money only for non-nil values
defaults = {
no_cents_if_whole: MoneyRails::Configuration.no_cents_if_whole,
symbol: MoneyRails::Configuration.symbol,
sign_before_symbol: MoneyRails::Configuration.sign_before_symbol
}.reject { |_k, v| v.nil? }
rules.reverse_merge!(defaults)
unless MoneyRails::Configuration.default_format.nil?
rules.reverse_merge!(MoneyRails::Configuration.default_format)
end
orig_format(rules)
end
end
|
Add a little more debug/loc info on thread failures | # Copyright (c) 2014, Stuart Glenn, OMRF
# Distributed under a BSD 3-Clause
# Full license available in LICENSE.txt distributed with this software
require "shellwords"
require "optical/version"
require "optical/configuration"
require "optical/library"
require "optical/sample"
require "optical/chip_analysis"
require "optical/filters"
require "optical/chip_bam_visual"
require "optical/bam"
require "optical/peak_caller"
require "optical/checkpointable"
require "optical/final_report"
require "optical/igv_session"
module Optical
def self.threader(enum,on_error)
workers = []
enum.each do |item|
workers << Thread.new do
yield item
end
end
exits = []
workers.each do |w|
begin
exits << w.value()
rescue => err
exits << false
on_error.call("Exception in a worker thread: #{err} (#{err.backtrace.first}")
end
end
if exits.any?{|e| !e}
on_error.call("A thread failed")
return false
end
return true
end
end
| # Copyright (c) 2014, Stuart Glenn, OMRF
# Distributed under a BSD 3-Clause
# Full license available in LICENSE.txt distributed with this software
require "shellwords"
require "optical/version"
require "optical/configuration"
require "optical/library"
require "optical/sample"
require "optical/chip_analysis"
require "optical/filters"
require "optical/chip_bam_visual"
require "optical/bam"
require "optical/peak_caller"
require "optical/checkpointable"
require "optical/final_report"
require "optical/igv_session"
module Optical
def self.threader(enum,on_error)
workers = []
enum.each do |item|
workers << Thread.new do
yield item
end
end
exits = []
workers.each do |w|
begin
exits << w.value()
rescue => err
exits << false
on_error.call("Exception in a worker thread: #{err} (#{err.backtrace.first}")
end
end
if exits.any?{|e| !e}
on_error.call("A thread failed near: #{caller_locations(2,1)[0].to_s}")
return false
end
return true
end
end
|
Return 'absent' instead of nil | # Make virtualenv version available as a fact
# Works with virualenv loaded and without, pip installed and package installed
require 'puppet'
pkg = Puppet::Type.type(:package).new(:name => "virtualenv")
Facter.add("virtualenv_version") do
has_weight 100
setcode do
begin
Facter::Util::Resolution.exec('virtualenv --version')
rescue
false
end
end
end
Facter.add("virtualenv_version") do
has_weight 50
setcode do
begin
unless [:absent,'purged'].include?(pkg.retrieve[pkg.property(:ensure)])
/^.*(\d+\.\d+\.\d+).*$/.match(pkg.retrieve[pkg.property(:ensure)])[1]
end
rescue
false
end
end
end
| # Make virtualenv version available as a fact
# Works with virualenv loaded and without, pip installed and package installed
require 'puppet'
pkg = Puppet::Type.type(:package).new(:name => "virtualenv")
Facter.add("virtualenv_version") do
has_weight 100
setcode do
begin
Facter::Util::Resolution.exec('virtualenv --version') || "absent"
rescue
false
end
end
end
Facter.add("virtualenv_version") do
has_weight 50
setcode do
begin
unless [:absent,'purged'].include?(pkg.retrieve[pkg.property(:ensure)])
/^.*(\d+\.\d+\.\d+).*$/.match(pkg.retrieve[pkg.property(:ensure)])[1]
end
rescue
false
end
end
end
|
Remove log_trace from Result inspection | # encoding: utf-8
module CartoDB
module Importer2
class Result
ATTRIBUTES = %w{ name schema extension tables success error_code log_trace support_tables original_name }.freeze
attr_reader *ATTRIBUTES.map(&:to_sym)
attr_writer :name
def initialize(attributes)
@support_tables = []
ATTRIBUTES.each do |attribute|
instance_variable_set :"@#{attribute}",
attributes.fetch(attribute.to_sym, nil)
end
@original_name = name
end
def success?
success == true
end
def qualified_table_name
%Q("#{schema}"."#{table_name}")
end
def table_name
tables.first
end
def update_support_tables(new_list)
@support_tables = new_list
end
end
end
end
| # encoding: utf-8
module CartoDB
module Importer2
class Result
ATTRIBUTES = %w{ name schema extension tables success error_code log_trace support_tables original_name }.freeze
attr_reader *ATTRIBUTES.map(&:to_sym)
attr_writer :name
def initialize(attributes)
@support_tables = []
ATTRIBUTES.each do |attribute|
instance_variable_set :"@#{attribute}",
attributes.fetch(attribute.to_sym, nil)
end
@original_name = name
end
def success?
success == true
end
def qualified_table_name
%Q("#{schema}"."#{table_name}")
end
def table_name
tables.first
end
def update_support_tables(new_list)
@support_tables = new_list
end
def to_s
"<Result #{name}>"
end
def inspect
attrs = (ATTRIBUTES - ['log_trace']).map { |attr| "@#{attr}=#{instance_variable_get "@#{attr}"}" }.join(', ')
"<#{self.class} #{attrs}>"
end
end
end
end
|
Use a string to avoid expansion | require 'spec_helper'
describe Raptor::VERSION do
it 'holds the version number of the library' do
splits = Raptor::VERSION.to_s.split( '.' )
splits.should be_any
splits.each { |number| number.should match /\d+/ }
end
end
| require 'spec_helper'
describe "Raptor::VERSION" do
it 'holds the version number of the library' do
splits = Raptor::VERSION.to_s.split( '.' )
splits.should be_any
splits.each { |number| number.should match /\d+/ }
end
end
|
Add rescue to return nil | module Nessus
class Client
# @author Erran Carey <me@errancarey.com>
module Policy
# GET /policy/list
def policy_list
response = get '/policy/list'
response['reply']['contents']['policies']['policy']
end
# @!group Policy Auxiliary Methods
# @return [Array<Array<String>>] an object containing a list of policies
# and their policy IDs
def policies
policy_list.map do |policy|
[policy['policyname'], policy['policyid']]
end
end
# @return [String] looks up policy ID by policy name
def policy_id_by_name(name)
policy_list.find{|policy| policy['policyname'].eql? name}['policyid']
end
# @return [String] looks up policy name by policy ID
def policy_name_by_id(id)
policy_list.find{|policy| policy['policyid'].eql? id}['policyname']
end
#@!endgroup
end
end
end
| module Nessus
class Client
# @author Erran Carey <me@errancarey.com>
module Policy
# GET /policy/list
def policy_list
response = get '/policy/list'
response['reply']['contents']['policies']['policy']
end
# @!group Policy Auxiliary Methods
# @return [Array<Array<String>>] an object containing a list of policies
# and their policy IDs
def policies
policy_list.map do |policy|
[policy['policyname'], policy['policyid']]
end
end
# @return [String] looks up policy ID by policy name
def policy_id_by_name(name)
policy_list.find{|policy| policy['policyname'].eql? name}['policyid']
rescue
nil
end
# @return [String] looks up policy name by policy ID
def policy_name_by_id(id)
policy_list.find{|policy| policy['policyid'].eql? id}['policyname']
rescue
nil
end
#@!endgroup
end
end
end
|
Check as early as possible if we should handle JWT | require "rack/indicium/version"
module Rack
class Indicium
class Sentry
def initialize(app)
@app = app
if defined?(Raven)
@sentry_client = Raven
else
warn "%s: Raven not definied, can't send JWT headers to Sentry." % self.class.to_s
end
end
def call(env)
check_for_jwt(env)
@app.call(env)
end
def check_for_jwt(env)
return unless enabled?
context = {
"jwt.header" => env["jwt.header"],
"jwt.payload" => env["jwt.payload"],
}
client.extra_context(context)
end
def client
@sentry_client
end
def enabled?
!!@sentry_client
end
end
end
end
| require "rack/indicium/version"
module Rack
class Indicium
class Sentry
def initialize(app)
@app = app
if defined?(Raven)
@sentry_client = Raven
else
warn "%s: Raven not definied, can't send JWT headers to Sentry." % self.class.to_s
end
end
def call(env)
check_for_jwt(env) if enabled?
@app.call(env)
end
def check_for_jwt(env)
context = {
"jwt.header" => env["jwt.header"],
"jwt.payload" => env["jwt.payload"],
}
client.extra_context(context)
end
def client
@sentry_client
end
def enabled?
!!@sentry_client
end
end
end
end
|
Fix warning in Rails 4: adopt Rails 5 behaviour | parent_class = ActiveRecord::Migration
parent_class = parent_class[5.0] if Rails::VERSION::MAJOR >= 5
class CreateActiveAdminComments < parent_class
def self.up
create_table :active_admin_comments do |t|
t.string :namespace
t.text :body
t.string :resource_id, null: false
t.string :resource_type, null: false
t.references :author, polymorphic: true
t.timestamps
end
add_index :active_admin_comments, [:namespace]
unless Rails::VERSION::MAJOR >= 5
add_index :active_admin_comments, [:author_type, :author_id]
end
add_index :active_admin_comments, [:resource_type, :resource_id]
end
def self.down
drop_table :active_admin_comments
end
end
| parent_class = ActiveRecord::Migration
parent_class = parent_class[5.0] if Rails::VERSION::MAJOR >= 5
class CreateActiveAdminComments < parent_class
def self.up
create_table :active_admin_comments do |t|
t.string :namespace
t.text :body
t.string :resource_id, null: false
t.string :resource_type, null: false
t.references :author, polymorphic: true
if Rails::VERSION::MAJOR >= 5
t.timestamps
else
t.timestamps null: false
end
end
add_index :active_admin_comments, [:namespace]
unless Rails::VERSION::MAJOR >= 5
add_index :active_admin_comments, [:author_type, :author_id]
end
add_index :active_admin_comments, [:resource_type, :resource_id]
end
def self.down
drop_table :active_admin_comments
end
end
|
Add the correct oozie prefix to the VIP URL | # Cookbook Name : bcpc-hadoop
# Recipe Name : oozie_client
# Description : To setup oozie-client
include_recipe 'bcpc-hadoop::oozie_config'
::Chef::Recipe.send(:include, Bcpc_Hadoop::Helper)
::Chef::Resource::Bash.send(:include, Bcpc_Hadoop::Helper)
package hwx_pkg_str('oozie-client', node[:bcpc][:hadoop][:distribution][:release]) do
action :install
end
hdp_select('oozie-client', node[:bcpc][:hadoop][:distribution][:active_release])
oozie_url = "http://#{node[:bcpc][:management][:vip]}:" +
node[:bcpc][:hadoop][:oozie_port].to_s
file '/etc/profile.d/oozie-url.sh' do
mode 0555
user 'root'
group 'root'
content <<-EOM
# This file was created by Chef.
# Local changes will be reverted.
export OOZIE_URL=#{oozie_url}
EOM
end
| # Cookbook Name : bcpc-hadoop
# Recipe Name : oozie_client
# Description : To setup oozie-client
include_recipe 'bcpc-hadoop::oozie_config'
::Chef::Recipe.send(:include, Bcpc_Hadoop::Helper)
::Chef::Resource::Bash.send(:include, Bcpc_Hadoop::Helper)
package hwx_pkg_str('oozie-client', node[:bcpc][:hadoop][:distribution][:release]) do
action :install
end
hdp_select('oozie-client', node[:bcpc][:hadoop][:distribution][:active_release])
oozie_url = "http://#{node[:bcpc][:management][:vip]}:" +
node[:bcpc][:hadoop][:oozie_port].to_s + '/oozie'
file '/etc/profile.d/oozie-url.sh' do
mode 0555
user 'root'
group 'root'
content <<-EOM
# This file was created by Chef.
# Local changes will be reverted.
export OOZIE_URL=#{oozie_url}
EOM
end
|
Remove version pin from Rubocop because Ruby 2.2 is not supported anymore | # frozen_string_literal: true
lib = File.expand_path('lib', __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'version'
Gem::Specification.new do |spec|
spec.authors = ['Martin Spickermann']
spec.email = ['spickermann@gmail.com']
spec.homepage = 'https://github.com/spickermann/has_configuration'
spec.license = 'MIT'
spec.name = 'has_configuration'
spec.version = HasConfiguration::VERSION::STRING
spec.summary = 'Simple configuration handling'
spec.description = <<-DESCRIPTION
Loads configuration setting from a yml file and adds a configuation method
to class and instances
DESCRIPTION
spec.files = Dir['CHANGELOG', 'MIT-LICENSE', 'README', 'lib/**/*', 'spec/**/*']
spec.require_path = ['lib']
spec.required_ruby_version = '>= 2.3.0'
spec.add_dependency('activesupport', '>= 4.2.2')
spec.add_development_dependency('coveralls')
spec.add_development_dependency('rake')
spec.add_development_dependency('rspec')
spec.add_development_dependency('rubocop', '< 0.75')
spec.add_development_dependency('rubocop-rspec')
end
| # frozen_string_literal: true
lib = File.expand_path('lib', __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'version'
Gem::Specification.new do |spec|
spec.authors = ['Martin Spickermann']
spec.email = ['spickermann@gmail.com']
spec.homepage = 'https://github.com/spickermann/has_configuration'
spec.license = 'MIT'
spec.name = 'has_configuration'
spec.version = HasConfiguration::VERSION::STRING
spec.summary = 'Simple configuration handling'
spec.description = <<-DESCRIPTION
Loads configuration setting from a yml file and adds a configuation method
to class and instances
DESCRIPTION
spec.files = Dir['CHANGELOG', 'MIT-LICENSE', 'README', 'lib/**/*', 'spec/**/*']
spec.require_path = ['lib']
spec.required_ruby_version = '>= 2.3.0'
spec.add_dependency('activesupport', '>= 4.2.2')
spec.add_development_dependency('coveralls')
spec.add_development_dependency('rake')
spec.add_development_dependency('rspec')
spec.add_development_dependency('rubocop')
spec.add_development_dependency('rubocop-rspec')
end
|
Migrate vendor, activities, and schedules | # encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20140130193522) do
create_table "activities", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "schedules", force: true do |t|
t.date "date"
t.time "time_start"
t.time "time_end"
t.integer "quantity"
t.integer "amount_sold"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "vendors", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
end
| |
Fix one test to use new rule syntax. | $:.unshift(File.dirname(File.dirname(__FILE__)))
require 'clipp_test'
class TestRegression < CLIPPTestCase
def test_trivial
clipp(input: "echo:foo")
end
def test_body_before_header
clipp(input: "htp:body_before_header.t")
end
def test_empty_header
clipp(input: "raw:empty_header.req,empty_header.resp")
end
def test_http09
clipp(input: "raw:http09.req,http09.resp")
end
def test_manyblank
clipp(input: "raw:manyblank.req,manyblank.resp")
end
def test_basic_rule
clipp(
input: "echo:\"GET /foo\"",
default_site_config: <<-EOS
Rule REQUEST_METHOD "@rx GET" id:1 phase:REQUEST_HEADER block event
EOS
)
assert_log_match /action "block" executed/
end
def test_negative_content_length
request = <<-EOS
GET / HTTP/1.1
Content-Length: -1
EOS
request.gsub!(/^\s+/,"")
clipp(
input_hashes: [simple_hash(request)],
input: "pb:- @parse @fillbody"
)
end
end
| $:.unshift(File.dirname(File.dirname(__FILE__)))
require 'clipp_test'
class TestRegression < CLIPPTestCase
def test_trivial
clipp(input: "echo:foo")
end
def test_body_before_header
clipp(input: "htp:body_before_header.t")
end
def test_empty_header
clipp(input: "raw:empty_header.req,empty_header.resp")
end
def test_http09
clipp(input: "raw:http09.req,http09.resp")
end
def test_manyblank
clipp(input: "raw:manyblank.req,manyblank.resp")
end
def test_basic_rule
clipp(
input: "echo:\"GET /foo\"",
default_site_config: <<-EOS
Rule REQUEST_METHOD @rx GET id:1 phase:REQUEST_HEADER block event
EOS
)
assert_log_match /action "block" executed/
end
def test_negative_content_length
request = <<-EOS
GET / HTTP/1.1
Content-Length: -1
EOS
request.gsub!(/^\s+/,"")
clipp(
input_hashes: [simple_hash(request)],
input: "pb:- @parse @fillbody"
)
end
end
|
Exclude tests from code coverage report | unless ENV['CI']
begin
require 'simplecov'
SimpleCov.start
rescue LoadError
end
end
require 'test/unit'
require 'stringio'
if ENV['LEFTRIGHT']
begin
require 'leftright'
rescue LoadError
puts "Run `gem install leftright` to install leftright."
end
end
require File.expand_path('../../lib/faraday', __FILE__)
begin
require 'ruby-debug'
rescue LoadError
# ignore
else
Debugger.start
end
module Faraday
class TestCase < Test::Unit::TestCase
LIVE_SERVER = case ENV['LIVE']
when /^http/ then ENV['LIVE']
when nil then nil
else 'http://127.0.0.1:4567'
end
def test_default
assert true
end unless defined? ::MiniTest
def capture_warnings
old, $stderr = $stderr, StringIO.new
begin
yield
$stderr.string
ensure
$stderr = old
end
end
end
end
require 'webmock/test_unit'
WebMock.disable_net_connect!(:allow => Faraday::TestCase::LIVE_SERVER)
| unless ENV['CI']
begin
require 'simplecov'
SimpleCov.start do
add_filter 'test'
end
rescue LoadError
end
end
require 'test/unit'
require 'stringio'
if ENV['LEFTRIGHT']
begin
require 'leftright'
rescue LoadError
puts "Run `gem install leftright` to install leftright."
end
end
require File.expand_path('../../lib/faraday', __FILE__)
begin
require 'ruby-debug'
rescue LoadError
# ignore
else
Debugger.start
end
module Faraday
class TestCase < Test::Unit::TestCase
LIVE_SERVER = case ENV['LIVE']
when /^http/ then ENV['LIVE']
when nil then nil
else 'http://127.0.0.1:4567'
end
def test_default
assert true
end unless defined? ::MiniTest
def capture_warnings
old, $stderr = $stderr, StringIO.new
begin
yield
$stderr.string
ensure
$stderr = old
end
end
end
end
require 'webmock/test_unit'
WebMock.disable_net_connect!(:allow => Faraday::TestCase::LIVE_SERVER)
|
Move helpre_method to beginning of file | # encoding: UTF-8
class ApplicationController < ActionController::Base
protect_from_forgery
private
def current_user
session[:auth_token] = cookies[:auth_token] if cookies[:auth_token]
@current_user ||= User.find_by_auth_token(session[:auth_token]) if session[:auth_token]
end
helper_method :current_user
def authentication_check
redirect_to signin_path unless current_user
end
def ominiauth_user_gate
if current_user && current_user.email.blank? && current_user.asked_for_email.nil?
current_user.update_attribute(:asked_for_email, true)
redirect_to email_users_path
else
return true
end
end
def choose_layout
current_user ? "application" : "public"
end
end
| # encoding: UTF-8
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :current_user
private
def current_user
session[:auth_token] = cookies[:auth_token] if cookies[:auth_token]
@current_user ||= User.find_by_auth_token(session[:auth_token]) if session[:auth_token]
end
def authentication_check
redirect_to signin_path unless current_user
end
def ominiauth_user_gate
if current_user && current_user.email.blank? && current_user.asked_for_email.nil?
current_user.update_attribute(:asked_for_email, true)
redirect_to email_users_path
else
return true
end
end
def choose_layout
current_user ? "application" : "public"
end
end
|
Use Rails' configured asset prefix in tests | class EmberTestsController < ActionController::Base
def index
render text: test_html_with_corrected_asset_urls, layout: false
end
private
def test_html_with_corrected_asset_urls
test_html.gsub(%r{assets/}i, "assets/#{app_name}/")
end
def test_html
tests_index_path.read
end
def tests_index_path
app.tests_path.join("index.html")
end
def app
EmberCLI.get_app(app_name)
end
def app_name
params.fetch(:app_name)
end
end
| class EmberTestsController < ActionController::Base
def index
render text: test_html_with_corrected_asset_urls, layout: false
end
private
def test_html_with_corrected_asset_urls
test_html.gsub(%r{assets/}i, "#{asset_prefix}/#{app_name}/")
end
def test_html
tests_index_path.read
end
def tests_index_path
app.tests_path.join("index.html")
end
def app
EmberCLI.get_app(app_name)
end
def app_name
params.fetch(:app_name)
end
def asset_prefix
Rails.configuration.assets.prefix
end
end
|
Use 'shell_expand_guest_path' guest capability to expand "~/" in shared folder mounts | module VagrantPlugins
module Parallels
module GuestLinuxCap
class MountParallelsSharedFolder
def self.mount_parallels_shared_folder(machine, name, guestpath, options)
machine.communicate.tap do |comm|
# clear prior symlink
if comm.test("test -L \"#{guestpath}\"", :sudo => true)
comm.sudo("rm \"#{guestpath}\"")
end
# clear prior directory if exists
if comm.test("test -d \"#{guestpath}\"", :sudo => true)
comm.sudo("rm -Rf \"#{guestpath}\"")
end
# create intermediate directories if needed
intermediate_dir = File.dirname(guestpath)
if !comm.test("test -d \"#{intermediate_dir}\"", :sudo => true)
comm.sudo("mkdir -p \"#{intermediate_dir}\"")
end
# finally make the symlink
comm.sudo("ln -s \"/media/psf/#{name}\" \"#{guestpath}\"")
end
end
end
end
end
end
| module VagrantPlugins
module Parallels
module GuestLinuxCap
class MountParallelsSharedFolder
def self.mount_parallels_shared_folder(machine, name, guestpath, options)
# Expand the guest path so we can handle things like "~/vagrant"
expanded_guest_path = machine.guest.capability(
:shell_expand_guest_path, guestpath)
machine.communicate.tap do |comm|
# clear prior symlink
if comm.test("test -L \"#{expanded_guest_path}\"", :sudo => true)
comm.sudo("rm \"#{expanded_guest_path}\"")
end
# clear prior directory if exists
if comm.test("test -d \"#{expanded_guest_path}\"", :sudo => true)
comm.sudo("rm -Rf \"#{expanded_guest_path}\"")
end
# create intermediate directories if needed
intermediate_dir = File.dirname(expanded_guest_path)
if !comm.test("test -d \"#{intermediate_dir}\"", :sudo => true)
comm.sudo("mkdir -p \"#{intermediate_dir}\"")
end
# finally make the symlink
comm.sudo("ln -s \"/media/psf/#{name}\" \"#{expanded_guest_path}\"")
end
end
end
end
end
end
|
Remove doubled at sign for S3 doc block | Puppet::Type.newtype(:s3) do
@@doc = %q{Get files from S3
Example:
s3 {'/path/on/my/filesystem':
ensure => present,
source => '/bucket/subdir/s3_object',
region => 'us-east-1', # better for speed if you set it in s3
access_key_id => 'ITSASECRET',
secret_access_key => 'ITSASECRETTOO',
}
}
ensurable
newparam(:path, :namevar => true) do
desc "Path to the file on the local filesystem"
validate do |v|
path = Pathname.new(v)
unless path.absolute?
raise ArgumentError, "Path not absolute: #{path}"
end
end
end
newparam(:source) do
desc "The aws s3 bucket path"
end
newparam(:access_key_id) do
desc "AWS secret access key id"
end
newparam(:secret_access_key) do
desc "AWS secret access key"
end
newparam(:region) do
desc "AWS region of S3"
end
end
| Puppet::Type.newtype(:s3) do
@doc = %q{Get files from S3
Example:
s3 {'/path/on/my/filesystem':
ensure => present,
source => '/bucket/subdir/s3_object',
region => 'us-east-1', # better for speed if you set it in s3
access_key_id => 'ITSASECRET',
secret_access_key => 'ITSASECRETTOO',
}
}
ensurable
newparam(:path, :namevar => true) do
desc "Path to the file on the local filesystem"
validate do |v|
path = Pathname.new(v)
unless path.absolute?
raise ArgumentError, "Path not absolute: #{path}"
end
end
end
newparam(:source) do
desc "The aws s3 bucket path"
end
newparam(:access_key_id) do
desc "AWS secret access key id"
end
newparam(:secret_access_key) do
desc "AWS secret access key"
end
newparam(:region) do
desc "AWS region of S3"
end
end
|
Add xml_doc accessor on base Model to expose access to the raw XML, because sometimes that's handy to see :) |
module Spreedly
class Model
include Fields
field :token
field :created_at, :updated_at, type: :date_time
def initialize(xml_doc)
initialize_fields(xml_doc)
end
end
end
|
module Spreedly
class Model
include Fields
field :token
field :created_at, :updated_at, type: :date_time
attr_reader :xml_doc
def initialize(xml_doc)
@xml_doc = xml_doc
initialize_fields(xml_doc)
end
end
end
|
Remove not needed database.yml from serializer | class ProjectSerializer < ActiveModel::Serializer
attributes :repository_name, :repository_owner, :github_access_token,
:build_commands
has_many :files
def github_access_token
object.user.github_access_token
end
def files
object.project_files
end
def build_commands
<<-TEXT
bundle install
mkdir -p config
echo '#{database_yml}' > config/database.yml
RAILS_ENV=test rake db:create
RAILS_ENV=test rake db:reset
TEXT
end
private
def database_yml
"test: \n"\
" adapter: postgresql\n"\
" database: testributor_test\n"\
" username: postgres\n"\
" password: \n"\
" host: db"
end
end
| class ProjectSerializer < ActiveModel::Serializer
attributes :repository_name, :repository_owner, :github_access_token,
:build_commands
has_many :files
def github_access_token
object.user.github_access_token
end
def files
object.project_files
end
def build_commands
<<-TEXT
bundle install
RAILS_ENV=test rake db:create
RAILS_ENV=test rake db:reset
TEXT
end
end
|
Remove now-unneeded 'd' prefix from sent message | require_relative 'rbhelium'
require 'base64'
token = Base64.decode64("C8Slmiwm6dreZrUhy5YPiA==")
conn = Helium::Connection.new do |mac, packet|
puts "Got data #{mac}, #{packet}"
end
puts "subscribing..."
status = conn.subscribe(0x0000112233440001, token)
puts "status: #{status}"
status = conn.send(0x0000112233440001, token, "dhello, from ruby land")
puts "status: #{status}"
sleep 15
| require_relative 'rbhelium'
require 'base64'
token = Base64.decode64("C8Slmiwm6dreZrUhy5YPiA==")
conn = Helium::Connection.new do |mac, packet|
puts "Got data #{mac}, #{packet}"
end
puts "subscribing..."
status = conn.subscribe(0x0000112233440001, token)
puts "status: #{status}"
status = conn.send(0x0000112233440001, token, "hello, from ruby land")
puts "status: #{status}"
sleep 15
|
Build system: factor out Info.plist manipulation | # encoding: UTF-8
require 'CFPropertyList'
class InfoPList
attr_accessor :data
attr_reader :file
def initialize(bundle_path)
@file = File.join(bundle_path, 'Contents', 'Info.plist')
@plist = CFPropertyList::List.new(file: @file)
@data = CFPropertyList.native_types(@plist.value)
end
def write!
@plist.value = CFPropertyList.guess(@data, convert_unknown_to_string: true)
@plist.save(@file, CFPropertyList::List::FORMAT_BINARY)
end
end
| |
Check only method calls with one argument | module Scanny
module Checks
# Checks for methods executing external commands that pass the command
# through shell expansion. This can cause unwanted code execution if the
# command includes unescaped input.
class ShellExpandingMethodsCheck < Check
def pattern
[
pattern_shell_expanding,
pattern_shell_execute,
pattern_popen,
pattern_execute_string
].join("|")
end
def check(node)
if Machete.matches?(node, pattern_shell_expanding)
# The command goes through shell expansion only if it is passed as one
# argument.
message = "The \"#{node.name}\" method passes the executed command through shell expansion."
else
message = "Execute system commands can lead the system to run dangerous code"
end
issue :high, message, :cwe => [88, 78]
end
# system("rm -rf /")
def pattern_shell_expanding
<<-EOT
SendWithArguments<
receiver = Self | ConstantAccess<name = :Kernel>,
name = :` | :exec | :system,
arguments = ActualArguments<array = [any]>
>
EOT
end
# Kernel.spawn("ls -lA")
def pattern_shell_execute
"SendWithArguments<name = :system | :spawn | :exec>"
end
# IO.popen
# IO.popen3
def pattern_popen
"SendWithArguments<name ^= :popen>"
end
# `system_command`
def pattern_execute_string
"ExecuteString"
end
end
end
end
| module Scanny
module Checks
# Checks for methods executing external commands that pass the command
# through shell expansion. This can cause unwanted code execution if the
# command includes unescaped input.
class ShellExpandingMethodsCheck < Check
def pattern
[
pattern_shell_expanding,
pattern_popen,
pattern_execute_string
].join("|")
end
def check(node)
# The command goes through shell expansion only if it is passed as one
# argument.
issue :high, warning_message(node), :cwe => [88, 78]
end
def warning_message(node = nil)
name = node.respond_to?(:name) ? node.name : "`"
"The \"#{name}\" method passes the executed command through shell expansion."
end
# system("rm -rf /")
def pattern_shell_expanding
<<-EOT
SendWithArguments<
receiver = Self | ConstantAccess<name = :Kernel>,
name = :` | :exec | :system | :spawn,
arguments = ActualArguments<array = [any]>
>
EOT
end
# IO.popen
# IO.popen3
def pattern_popen
<<-EOT
SendWithArguments<
name ^= :popen,
arguments = ActualArguments<array = [any]>
>
EOT
end
# `system_command`
def pattern_execute_string
"ExecuteString"
end
end
end
end
|
Send jobs to all the widgets | SCHEDULER.every '1h', :first_in => Time.now + 10 do
q2_progress = Progress.new("sFETRDq0")
send_event('2014-q2-current-month', items: q2_progress.current_month)
send_event('2014-q2-rest-of-quarter', items: q2_progress.rest_of_quarter)
send_event('2014-q2-discuss', items: q2_progress.to_discuss)
send_event('2014-q2-done', items: q2_progress.done)
end
| SCHEDULER.every '1h', :first_in => Time.now + 10 do
boards = {
"2013-q1" => "cEwY2JHh",
"2013-q2" => "m5Gxybf6",
"2013-q3" => "wkIzhRE3",
"2013-q4" => "5IZH6yGG",
"2014-q1" => "8P2Hgzlh",
"2014-q2" => "sFETRDq0"
}
boards.each do |k,v|
progress = Progress.new(v)
send_event("#{k}-current-month", items: progress.current_month)
send_event("#{k}-rest-of-quarter", items: progress.rest_of_quarter)
send_event("#{k}-discuss", items: progress.to_discuss)
send_event("#{k}-done", items: progress.done)
end
end
|
Add check for OS in PlaylistManager.playlist | module Nehm
module PlaylistManager
def self.playlist
@temp_playlist || default_user_playlist || music_master_library
end
def self.set_playlist
loop do
playlist = HighLine.new.ask('Enter name of default iTunes playlist to which you want add tracks (press Enter to set it to default iTunes Music library)')
# If entered nothing, unset iTunes playlist
if playlist == ''
Cfg[:playlist] = nil
puts Paint['Default iTunes playlist unset', :green]
break
end
if AppleScript.list_of_playlists.include? playlist
Cfg[:playlist] = playlist
puts Paint["Default iTunes playlist set up to #{playlist}", :green]
break
else
puts Paint['Invalid playlist name. Please enter correct name', :red]
end
end
end
def self.temp_playlist=(playlist)
if AppleScript.list_of_playlists.include? playlist
@temp_playlist = Playlist.new(playlist)
else
puts Paint['Invalid playlist name. Please enter correct name', :red]
exit
end
end
module_function
def default_user_playlist
Playlist.new(Cfg[:playlist]) unless Cfg[:playlist].nil?
end
def music_master_library
Playlist.new(AppleScript.music_master_library)
end
end
end
| module Nehm
module PlaylistManager
def self.playlist
@temp_playlist || default_user_playlist || music_master_library unless OS.linux?
end
def self.set_playlist
loop do
playlist = HighLine.new.ask('Enter name of default iTunes playlist to which you want add tracks (press Enter to set it to default iTunes Music library)')
# If entered nothing, unset iTunes playlist
if playlist == ''
Cfg[:playlist] = nil
puts Paint['Default iTunes playlist unset', :green]
break
end
if AppleScript.list_of_playlists.include? playlist
Cfg[:playlist] = playlist
puts Paint["Default iTunes playlist set up to #{playlist}", :green]
break
else
puts Paint['Invalid playlist name. Please enter correct name', :red]
end
end
end
def self.temp_playlist=(playlist)
if AppleScript.list_of_playlists.include? playlist
@temp_playlist = Playlist.new(playlist)
else
puts Paint['Invalid playlist name. Please enter correct name', :red]
exit
end
end
module_function
def default_user_playlist
Playlist.new(Cfg[:playlist]) unless Cfg[:playlist].nil?
end
def music_master_library
Playlist.new(AppleScript.music_master_library)
end
end
end
|
Raise if 'users' environment variable does not be specified. | require 'redmine/version'
require 'redmine_audit/advisory'
require 'redmine_audit/database'
desc <<-END_DESC
Check redmine vulnerabilities.
Available options:
* users => comma separated list of user/group ids who should be notified
Example:
rake redmine:bundle_audit users="1,23, 56" RAILS_ENV="production"
END_DESC
namespace :redmine do
# Avoid to define same task twice.
# TODO: stop load twice this .rake file.
if !Rake::Task.task_defined?(:audit)
task audit: :environment do
# TODO: More better if requires mailer automatically.
require_dependency 'mailer'
require_relative '../../app/models/mailer.rb'
redmine_ver = Redmine::VERSION
advisories = RedmineAudit::Database.new.advisories(redmine_ver.to_s)
if advisories.length > 0
users = (ENV['users'] || '').split(',').each(&:strip!)
Mailer.with_synched_deliveries do
Mailer.unfixed_advisories_found(redmine_ver, advisories, users).deliver
end
end
end
end
end
| require 'redmine/version'
require 'redmine_audit/advisory'
require 'redmine_audit/database'
desc <<-END_DESC
Check redmine vulnerabilities.
Available options:
* users => comma separated list of user/group ids who should be notified
Example:
rake redmine:bundle_audit users="1,23, 56" RAILS_ENV="production"
END_DESC
namespace :redmine do
# Avoid to define same task twice.
# TODO: stop load twice this .rake file.
if !Rake::Task.task_defined?(:audit)
task audit: :environment do
users = (ENV['users'] || '').split(',').each(&:strip!)
if users.empty?
raise 'need to specify environment variable: users'
end
# TODO: More better if requires mailer automatically.
require_dependency 'mailer'
require_relative '../../app/models/mailer.rb'
redmine_ver = Redmine::VERSION
advisories = RedmineAudit::Database.new.advisories(redmine_ver.to_s)
if advisories.length > 0
Mailer.with_synched_deliveries do
Mailer.unfixed_advisories_found(redmine_ver, advisories, users).deliver
end
end
end
end
end
|
Add purchase type seed data | dian = User.create(name: "Dian", email: "dian@example.com", password: "abc123")
julianna = User.create(name: "Julianna", email: "juls@example.com", password: "123456")
jenny = User.create(name: "Jenny", email: "jellylee@example.com", password: "iamjenny")
ExpenseType.create(name: "Housing")
ExpenseType.create(name: "Transportation")
ExpenseType.create(name: "Food")
ExpenseType.create(name: "Phone")
ExpenseType.create(name: "Misc. 1")
ExpenseType.create(name: "Misc. 2")
ExpenseType.create(name: "Misc. 3") | dian = User.create(name: "Dian", email: "dian@example.com", password: "abc123")
julianna = User.create(name: "Julianna", email: "juls@example.com", password: "123456")
jenny = User.create(name: "Jenny", email: "jellylee@example.com", password: "iamjenny")
ExpenseType.create(name: "Housing")
ExpenseType.create(name: "Transportation")
ExpenseType.create(name: "Food")
ExpenseType.create(name: "Phone")
ExpenseType.create(name: "Misc. 1")
ExpenseType.create(name: "Misc. 2")
ExpenseType.create(name: "Misc. 3")
PurchaseType.create(name:"small")
PurchaseType.create(name:"medium")
PurchaseType.create(name:"large") |
Add configuration option to suppress notifications | module Citygram
module Services
module Channels
class Base < Struct.new(:subscription, :event)
def self.call(subscription, event)
new(subscription, event).call
end
def call
raise 'abstract - must subclass'
end
end
end
end
end
| module Citygram
module Services
module Channels
class Base < Struct.new(:subscription, :event)
def self.call(subscription, event)
instance = new(subscription, event)
if ENV['SUPPRESS_NOTIFICATIONS']
instance.suppress
else
instance.call
end
end
def call
raise 'abstract - must subclass'
end
def suppress
Citygram::App.logger.info 'SUPPRESSED: class=%s subscription_id=%s event_id=%s' % [
self.class.name,
subscription.id,
event.id
]
end
end
end
end
end
|
Fix indentation in generated YAML | # frozen_string_literal: true
require 'yaml'
module RuboCop
module RSpec
# Builds a YAML config file from two config hashes
class ConfigFormatter
EXTENSION_ROOT_DEPARTMENT = %r{^(RSpec/)}.freeze
STYLE_GUIDE_BASE_URL = 'https://www.rubydoc.info/gems/rubocop-rspec/RuboCop/Cop/RSpec/'
def initialize(config, descriptions)
@config = config
@descriptions = descriptions
end
def dump
YAML.dump(unified_config).gsub(EXTENSION_ROOT_DEPARTMENT, "\n\\1")
end
private
def unified_config
cops.each_with_object(config.dup) do |cop, unified|
unified[cop] = config.fetch(cop)
.merge(descriptions.fetch(cop))
.merge('StyleGuide' => STYLE_GUIDE_BASE_URL + cop.sub('RSpec/', ''))
end
end
def cops
(descriptions.keys | config.keys).grep(EXTENSION_ROOT_DEPARTMENT)
end
attr_reader :config, :descriptions
end
end
end
| # frozen_string_literal: true
require 'yaml'
module RuboCop
module RSpec
# Builds a YAML config file from two config hashes
class ConfigFormatter
EXTENSION_ROOT_DEPARTMENT = %r{^(RSpec/)}.freeze
STYLE_GUIDE_BASE_URL = 'https://www.rubydoc.info/gems/rubocop-rspec/RuboCop/Cop/RSpec/'
def initialize(config, descriptions)
@config = config
@descriptions = descriptions
end
def dump
YAML.dump(unified_config)
.gsub(EXTENSION_ROOT_DEPARTMENT, "\n\\1")
.gsub(/^(\s+)- /, '\1 - ')
end
private
def unified_config
cops.each_with_object(config.dup) do |cop, unified|
unified[cop] = config.fetch(cop)
.merge(descriptions.fetch(cop))
.merge('StyleGuide' => STYLE_GUIDE_BASE_URL + cop.sub('RSpec/', ''))
end
end
def cops
(descriptions.keys | config.keys).grep(EXTENSION_ROOT_DEPARTMENT)
end
attr_reader :config, :descriptions
end
end
end
|
Include new-line between message and actual input/output | class Hotspots
module Repository #:nodoc: all
module Driver
class Git
def initialize(options)
@log = options[:logger]
@colour = options[:colour]
end
def pretty_log(options)
execute_with_log Command::Git::Log.new(:since_days => options[:since_days], :message_filter => options[:message_filter])
end
def show_one_line_names(options)
execute_with_log Command::Git::Show.new(:commit_hash => options[:commit_hash])
end
private
def execute_with_log(command)
command.run.tap do |output|
@log.message("[input] #{command}", :level => :info, :colour => :green)
@log.message("[output] #{output}", :level => :info, :colour => :red)
end
end
end
end
end
end
| class Hotspots
module Repository #:nodoc: all
module Driver
class Git
def initialize(options)
@log = options[:logger]
@colour = options[:colour]
end
def pretty_log(options)
execute_with_log Command::Git::Log.new(:since_days => options[:since_days], :message_filter => options[:message_filter])
end
def show_one_line_names(options)
execute_with_log Command::Git::Show.new(:commit_hash => options[:commit_hash])
end
private
def execute_with_log(command)
command.run.tap do |output|
@log.message("[input]\n#{command}", :level => :info, :colour => :green)
@log.message("[output]\n#{output}", :level => :info, :colour => :red)
end
end
end
end
end
end
|
Add task to delete ChatChannelsUsers and ChatMessages without a channel_id. | # Due to a bug ChatChannelsUsers and ChatMessages without a channel_id were created.
# This tasks deletes them.
namespace :cg do
namespace :chat do
desc "Deletes ChatChannelsUsers and ChatMessages without a channel_id"
task(:clean_invalid => :environment) do
ChatChannelsUser.all(:conditions => "channel_id IS NULL").each do |c_user|
c_user.destroy
end
ChatMessage.all(:conditions => "channel_id IS NULL").each do |m|
m.destroy
end
end
end
end
| |
Add code climate to spec | require_relative '../lib/ClassBrowser'
describe "Test that the ObjectSpace hierarchy can be displayed" do
it "main runs" do
expect { main }.to output(/BasicObject/).to_stdout
end
end
| require "codeclimate-test-reporter"
CodeClimate::TestReporter.start
require_relative '../lib/ClassBrowser'
describe "Test that the ObjectSpace hierarchy can be displayed" do
it "main runs" do
expect { main }.to output(/BasicObject/).to_stdout
end
end
|
Update rake and rspec versions | # -*- encoding: utf-8 -*-
$:.push File.expand_path('../lib', __FILE__)
require 'pronto/poper/version'
Gem::Specification.new do |s|
s.name = 'pronto-poper'
s.version = Pronto::PoperVersion::VERSION
s.platform = Gem::Platform::RUBY
s.author = 'Mindaugas Mozūras'
s.email = 'mindaugas.mozuras@gmail.com'
s.homepage = 'http://github.org/mmozuras/pronto-poper'
s.summary = 'Pronto runner for Poper, git commit message analyzer'
s.required_rubygems_version = '>= 1.3.6'
s.license = 'MIT'
s.files = Dir.glob('{lib}/**/*') + %w[LICENSE README.md]
s.test_files = `git ls-files -- {spec}/*`.split("\n")
s.require_paths = ['lib']
s.add_dependency 'pronto', '~> 0.2.0'
s.add_dependency 'poper', '~> 0.0.1'
s.add_development_dependency 'rake', '~> 10.1.0'
s.add_development_dependency 'rspec', '~> 2.14.0'
end
| # -*- encoding: utf-8 -*-
$:.push File.expand_path('../lib', __FILE__)
require 'pronto/poper/version'
Gem::Specification.new do |s|
s.name = 'pronto-poper'
s.version = Pronto::PoperVersion::VERSION
s.platform = Gem::Platform::RUBY
s.author = 'Mindaugas Mozūras'
s.email = 'mindaugas.mozuras@gmail.com'
s.homepage = 'http://github.org/mmozuras/pronto-poper'
s.summary = 'Pronto runner for Poper, git commit message analyzer'
s.required_rubygems_version = '>= 1.3.6'
s.license = 'MIT'
s.files = Dir.glob('{lib}/**/*') + %w[LICENSE README.md]
s.test_files = `git ls-files -- {spec}/*`.split("\n")
s.require_paths = ['lib']
s.add_dependency 'pronto', '~> 0.2.0'
s.add_dependency 'poper', '~> 0.0.1'
s.add_development_dependency 'rake', '~> 10.3.0'
s.add_development_dependency 'rspec', '~> 3.0'
end
|
Create a single group in our migration. | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
Group.create(number: "48", street: "Wall Street", city: "New York", zip_code: "10005")
| # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
# Create a single group
Group.find_or_create_by({primary_number: "48",
street_name: "Wall",
street_suffix: "St",
city_name: "New York",
state_abbreviation: "NY",
zipcode: "10005"})
|
Update dry-configurable dependency to match dry-validation | # encoding: utf-8
$LOAD_PATH.unshift File.expand_path('../lib', __FILE__)
require 'mjml/version'
Gem::Specification.new do |s|
s.name = 'mjml-ruby'
s.version = MJML::VERSION
s.authors = ['Mykola Basov']
s.email = ['kolybasov@gmail.com']
s.homepage = 'https://github.com/kolybasov/mjml-ruby'
s.summary = 'MJML parser and template engine for Ruby'
s.license = 'MIT'
s.post_install_message = 'Don\'t forget to run $ npm install -g mjml@^3.0'
s.files = `git ls-files app lib`.split("\n")
s.test_files = s.files.grep(%r{^(test|spec|features)/})
s.platform = Gem::Platform::RUBY
s.require_paths = ['lib']
s.add_runtime_dependency 'dry-configurable', '~> 0.3', '~> 0.4'
s.add_development_dependency 'rake'
s.add_development_dependency 'minitest', '~> 5.9', '>= 5.0'
s.add_development_dependency 'tilt', '~> 2.0', '>= 2.0'
s.add_development_dependency 'sprockets', '~> 3.7', '>= 3.0'
s.add_development_dependency 'byebug', '~> 9.0', '>= 9.0'
end
| # encoding: utf-8
$LOAD_PATH.unshift File.expand_path('../lib', __FILE__)
require 'mjml/version'
Gem::Specification.new do |s|
s.name = 'mjml-ruby'
s.version = MJML::VERSION
s.authors = ['Mykola Basov']
s.email = ['kolybasov@gmail.com']
s.homepage = 'https://github.com/kolybasov/mjml-ruby'
s.summary = 'MJML parser and template engine for Ruby'
s.license = 'MIT'
s.post_install_message = 'Don\'t forget to run $ npm install -g mjml@^3.0'
s.files = `git ls-files app lib`.split("\n")
s.test_files = s.files.grep(%r{^(test|spec|features)/})
s.platform = Gem::Platform::RUBY
s.require_paths = ['lib']
s.add_runtime_dependency 'dry-configurable', '~> 0.1', '>= 0.1.3'
s.add_development_dependency 'rake'
s.add_development_dependency 'minitest', '~> 5.9', '>= 5.0'
s.add_development_dependency 'tilt', '~> 2.0', '>= 2.0'
s.add_development_dependency 'sprockets', '~> 3.7', '>= 3.0'
s.add_development_dependency 'byebug', '~> 9.0', '>= 9.0'
end
|
Use correct form of "or" operator. | # Django deployment
set :python, "python"
set :django_project_subdirectory, "project"
set :django_use_south, false
depend :remote, :command, "#{python}"
def django_manage(cmd, options={})
puts options
path = options.delete(:path) or "#{latest_release}"
run "cd #{path}/#{django_project_subdirectory}; #{python} manage.py #{cmd}"
end
namespace :django do
desc "Run custom Django management command in latest release."
task :manage do
set_from_env_or_ask :command, "Enter management command"
django_manage "#{command}"
end
end
namespace :deploy do
desc "Run manage.py syncdb in latest release."
task :migrate, :roles => :db, :only => { :primary => true } do
# FIXME: path, see default railsy deploy:migrate
django_manage "syncdb --noinput"
django_manage "migrate" if fetch(:django_use_south, false)
end
end
# depend :remote, :python_module, "module_name"
# runs #{python} and tries to import module_name.
class Capistrano::Deploy::RemoteDependency
def python_module(module_name, options={})
@message ||= "Cannot import `#{module_name}'"
python = configuration.fetch(:python, "python")
try("#{python} -c 'import #{module_name}'", options)
self
end
end
| # Django deployment
set :python, "python"
set :django_project_subdirectory, "project"
set :django_use_south, false
depend :remote, :command, "#{python}"
def django_manage(cmd, options={})
path = options.delete(:path) || "#{latest_release}"
run "cd #{path}/#{django_project_subdirectory}; #{python} manage.py #{cmd}"
end
namespace :django do
desc "Run custom Django management command in latest release."
task :manage do
set_from_env_or_ask :command, "Enter management command"
django_manage "#{command}"
end
end
namespace :deploy do
desc "Run manage.py syncdb in latest release."
task :migrate, :roles => :db, :only => { :primary => true } do
# FIXME: path, see default railsy deploy:migrate
django_manage "syncdb --noinput"
django_manage "migrate" if fetch(:django_use_south, false)
end
end
# depend :remote, :python_module, "module_name"
# runs #{python} and tries to import module_name.
class Capistrano::Deploy::RemoteDependency
def python_module(module_name, options={})
@message ||= "Cannot import `#{module_name}'"
python = configuration.fetch(:python, "python")
try("#{python} -c 'import #{module_name}'", options)
self
end
end
|
Add definition for sequel gem | #
# Copyright 2012-2014 Chef Software, 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.
#
name "sequel-gem"
default_version "4.13.0"
dependency "ruby"
dependency "rubygems"
build do
env = with_standard_compiler_flags(with_embedded_path)
gem "install sequel" \
" --version '#{version}'" \
" --bindir '#{install_dir}/embedded/bin'" \
" --no-ri --no-rdoc", env: env
end
| |
Implement GithubGistFormula in a more natural way | # Base classes for specialized types of formulae.
# See chcase for an example
class ScriptFileFormula < Formula
def install
bin.install Dir['*']
end
end
# See browser for an example
class GithubGistFormula < ScriptFileFormula
def initialize(*)
url = self.class.stable.url
self.class.stable.version(File.basename(File.dirname(url))[0,6])
super
end
end
# This formula serves as the base class for several very similar
# formulae for Amazon Web Services related tools.
class AmazonWebServicesFormula < Formula
# Use this method to peform a standard install for Java-based tools,
# keeping the .jars out of HOMEBREW_PREFIX/lib
def standard_install
rm Dir['bin/*.cmd'] # Remove Windows versions
libexec.install Dir['*']
bin.install_symlink Dir["#{libexec}/bin/*"] - ["#{libexec}/bin/service"]
end
# Use this method to generate standard caveats.
def standard_instructions home_name, home_value=libexec
<<-EOS.undent
Before you can use these tools you must export some variables to your $SHELL.
To export the needed variables, add them to your dotfiles.
* On Bash, add them to `~/.bash_profile`.
* On Zsh, add them to `~/.zprofile` instead.
export JAVA_HOME="$(/usr/libexec/java_home)"
export AWS_ACCESS_KEY="<Your AWS Access ID>"
export AWS_SECRET_KEY="<Your AWS Secret Key>"
export #{home_name}="#{home_value}"
EOS
end
end
| # Base classes for specialized types of formulae.
# See chcase for an example
class ScriptFileFormula < Formula
def install
bin.install Dir['*']
end
end
# See browser for an example
class GithubGistFormula < ScriptFileFormula
def self.url(val)
super
version File.basename(File.dirname(val))[0, 6]
end
end
# This formula serves as the base class for several very similar
# formulae for Amazon Web Services related tools.
class AmazonWebServicesFormula < Formula
# Use this method to peform a standard install for Java-based tools,
# keeping the .jars out of HOMEBREW_PREFIX/lib
def standard_install
rm Dir['bin/*.cmd'] # Remove Windows versions
libexec.install Dir['*']
bin.install_symlink Dir["#{libexec}/bin/*"] - ["#{libexec}/bin/service"]
end
# Use this method to generate standard caveats.
def standard_instructions home_name, home_value=libexec
<<-EOS.undent
Before you can use these tools you must export some variables to your $SHELL.
To export the needed variables, add them to your dotfiles.
* On Bash, add them to `~/.bash_profile`.
* On Zsh, add them to `~/.zprofile` instead.
export JAVA_HOME="$(/usr/libexec/java_home)"
export AWS_ACCESS_KEY="<Your AWS Access ID>"
export AWS_SECRET_KEY="<Your AWS Secret Key>"
export #{home_name}="#{home_value}"
EOS
end
end
|
Add check for vulnerability in nested attributes | require 'checks/base_check'
require 'processors/lib/find_call'
class CheckNestedAttributes < BaseCheck
Checks.add self
def run_check
version = tracker.config[:rails_version]
if (version == "2.3.9" or version == "3.0.0") and uses_nested_attributes?
message = "Vulnerability in nested attributes (CVE-2010-3933). Upgrade to Rails version "
if version == "2.3.9"
message << "2.3.10"
else
message << "3.0.1"
end
warn :warning_type => "Nested Attributes",
:message => message,
:confidence => CONFIDENCE[:high]
end
end
def uses_nested_attributes?
tracker.models.each do |name, model|
return true if model[:options][:accepts_nested_attributes_for]
end
false
end
end
| |
Fix configuration for travis and coveralls | # This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require 'spec_helper'
require File.expand_path('../../config/environment', __FILE__)
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
end
| |
Update api prefix from v1 to v2 | # frozen_string_literal: true
module GirlScout
DEFAULT_API_PREFIX = 'https://api.helpscout.net/v1'
class Config
class << self
attr_accessor :api_key
attr_writer :api_prefix
def api_prefix
@api_prefix ||= DEFAULT_API_PREFIX
end
def reset!
@api_key = nil
@api_prefix = DEFAULT_API_PREFIX
end
end
end
end
| # frozen_string_literal: true
module GirlScout
DEFAULT_API_PREFIX = 'https://api.helpscout.net/v2'
class Config
class << self
attr_accessor :client_id, :client_secret
attr_writer :api_prefix
def api_prefix
@api_prefix ||= DEFAULT_API_PREFIX
end
def reset!
@client_id = nil
@client_secret = nil
@api_prefix = DEFAULT_API_PREFIX
end
end
end
end
|
Remove unused variable from Transmit class. | require 'net/http'
require 'uri'
class Transmit
attr_accessor :uri, :port, :api_token, :data
def initialize(url, api_token, data)
@api_token = api_token
@data = data
@uri = URI(url)
@port = uri.port
end
def http
@_http ||= Net::HTTP.new(uri.host, uri.port)
end
def post_entry
@_response ||= http.post(uri.path, data, headers)
end
def post_success?
post_entry.class == Net::HTTPCreated ? true : false
end
def headers
{
"Content-Type" => "application/json",
"Authorization" => "Token token=#{api_token}"
}
end
end
| require 'net/http'
require 'uri'
class Transmit
attr_accessor :api_token, :data, :uri
def initialize(url, api_token, data)
@api_token = api_token
@data = data
@uri = URI(url)
end
def http
@_http ||= Net::HTTP.new(uri.host, uri.port)
end
def post_entry
@_response ||= http.post(uri.path, data, headers)
end
def post_success?
post_entry.class == Net::HTTPCreated ? true : false
end
def headers
{
"Content-Type" => "application/json",
"Authorization" => "Token token=#{api_token}"
}
end
end
|
Remove incorrect prepend to `ActiveRecord::ColumnDumper` | # frozen_string_literal: true
module ActiveRecord #:nodoc:
module ConnectionAdapters #:nodoc:
module OracleEnhanced #:nodoc:
module ColumnDumper #:nodoc:
def prepare_column_options(column)
spec = super
if supports_virtual_columns? && column.virtual?
spec[:as] = column.virtual_column_data_default
spec = { type: schema_type(column).inspect }.merge!(spec) unless column.type == :decimal
end
spec
end
private
def default_primary_key?(column)
schema_type(column) == :integer
end
end
end
end
module ColumnDumper #:nodoc:
prepend ConnectionAdapters::OracleEnhanced::ColumnDumper
end
end
| # frozen_string_literal: true
module ActiveRecord #:nodoc:
module ConnectionAdapters #:nodoc:
module OracleEnhanced #:nodoc:
module ColumnDumper #:nodoc:
def prepare_column_options(column)
spec = super
if supports_virtual_columns? && column.virtual?
spec[:as] = column.virtual_column_data_default
spec = { type: schema_type(column).inspect }.merge!(spec) unless column.type == :decimal
end
spec
end
private
def default_primary_key?(column)
schema_type(column) == :integer
end
end
end
end
end
|
Handle load path in case FSSM isn't on the load path when required. | module FSSM
FileNotFoundError = Class.new(StandardError)
CallbackError = Class.new(StandardError)
class << self
def monitor(*args, &block)
monitor = FSSM::Monitor.new
context = args.empty? ? monitor : monitor.path(*args)
context.instance_eval(&block) if block_given?
monitor.run
end
end
end
require 'pathname'
require 'fssm/ext'
require 'fssm/support'
require 'fssm/path'
require 'fssm/state'
require 'fssm/monitor'
require "fssm/backends/#{FSSM::Support.backend.downcase}"
FSSM::Backends::Default = FSSM::Backends.const_get(FSSM::Support.backend)
| module FSSM
FileNotFoundError = Class.new(StandardError)
CallbackError = Class.new(StandardError)
class << self
def monitor(*args, &block)
monitor = FSSM::Monitor.new
context = args.empty? ? monitor : monitor.path(*args)
context.instance_eval(&block) if block_given?
monitor.run
end
end
end
$:.unshift(File.dirname(__FILE__))
require 'pathname'
require 'fssm/ext'
require 'fssm/support'
require 'fssm/path'
require 'fssm/state'
require 'fssm/monitor'
require "fssm/backends/#{FSSM::Support.backend.downcase}"
FSSM::Backends::Default = FSSM::Backends.const_get(FSSM::Support.backend)
$:.shift
|
Clean up our test helper | require 'rubygems'
require 'bundler/setup'
$:.unshift(File.dirname(__FILE__) + '/../lib')
$:.unshift(File.dirname(__FILE__))
require 'test/unit'
require 'pp'
require 'etl'
require 'shoulda'
require 'flexmock/test_unit'
database_yml = File.dirname(__FILE__) + '/config/database.yml'
ETL::Engine.init(:config => database_yml)
ETL::Engine.logger = Logger.new(STDOUT)
# ETL::Engine.logger.level = Logger::DEBUG
ETL::Engine.logger.level = Logger::FATAL
db = YAML::load(IO.read(database_yml))['operational_database']['adapter']
# allow both mysql2 and mysql adapters
db = db.gsub('mysql2', 'mysql')
raise "Unsupported test db '#{db}'" unless ['mysql', 'postgresql'].include?(db)
require "connection/#{db}/connection"
ActiveRecord::Base.establish_connection :operational_database
ETL::Execution::Job.delete_all
require 'mocks/mock_source'
require 'mocks/mock_destination'
# shortcut to launch a ctl file
def process(file)
Engine.process(File.join(File.dirname(__FILE__), file))
end
puts "ActiveRecord::VERSION = #{ActiveRecord::VERSION::STRING}"
| $:.unshift(File.dirname(__FILE__) + '/../lib')
$:.unshift(File.dirname(__FILE__))
require 'test/unit'
require 'pp'
require 'etl'
require 'shoulda'
require 'flexmock/test_unit'
raise "Missing required DB environment variable" unless ENV['DB']
database_yml = File.dirname(__FILE__) + '/config/database.yml'
ETL::Engine.init(:config => database_yml)
ETL::Engine.logger = Logger.new(STDOUT)
# ETL::Engine.logger.level = Logger::DEBUG
ETL::Engine.logger.level = Logger::FATAL
ActiveRecord::Base.establish_connection :operational_database
ETL::Execution::Job.delete_all
require 'mocks/mock_source'
require 'mocks/mock_destination'
# shortcut to launch a ctl file
def process(file)
Engine.process(File.join(File.dirname(__FILE__), file))
end
puts "ActiveRecord::VERSION = #{ActiveRecord::VERSION::STRING}"
|
Use pessimistic operator for depends | name 'kitchen-in-travis'
maintainer 'Xabier de Zuazo'
maintainer_email 'xabier@zuazo.org'
license 'Apache 2.0'
description <<-EOH
Cookbook example to run test-kitchen inside Travis CI using kitchen-docker in
User Mode Linux.
EOH
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.1.0'
depends 'nginx'
| name 'kitchen-in-travis'
maintainer 'Xabier de Zuazo'
maintainer_email 'xabier@zuazo.org'
license 'Apache 2.0'
description <<-EOH
Cookbook example to run test-kitchen inside Travis CI using kitchen-docker in
User Mode Linux.
EOH
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.1.0'
depends 'nginx', '~> 2.7'
|
Add rake as a dev dep | spec = Gem::Specification.new do |s|
s.name = "brochure"
s.version = "0.5.3"
s.platform = Gem::Platform::RUBY
s.authors = ["Sam Stephenson", "Josh Peek"]
s.email = ["sstephenson@gmail.com", "josh@joshpeek.com"]
s.homepage = "http://github.com/sstephenson/brochure"
s.summary = "Rack + ERB static sites"
s.description = "A Rack application for serving static sites with ERB templates."
s.files = Dir["lib/**/*.rb", "README.md", "LICENSE"]
s.require_path = "lib"
s.add_dependency "hike", "~> 1.0"
s.add_dependency "rack", "~> 1.0"
s.add_dependency "tilt", "~> 1.1"
s.add_development_dependency "rack-test"
s.add_development_dependency "haml"
end
| spec = Gem::Specification.new do |s|
s.name = "brochure"
s.version = "0.5.3"
s.platform = Gem::Platform::RUBY
s.authors = ["Sam Stephenson", "Josh Peek"]
s.email = ["sstephenson@gmail.com", "josh@joshpeek.com"]
s.homepage = "http://github.com/sstephenson/brochure"
s.summary = "Rack + ERB static sites"
s.description = "A Rack application for serving static sites with ERB templates."
s.files = Dir["lib/**/*.rb", "README.md", "LICENSE"]
s.require_path = "lib"
s.add_dependency "hike", "~> 1.0"
s.add_dependency "rack", "~> 1.0"
s.add_dependency "tilt", "~> 1.1"
s.add_development_dependency "rake"
s.add_development_dependency "rack-test"
s.add_development_dependency "haml"
end
|
Fix the name of variable. | #!/usr/bin/siren
# coding: utf-8
#
# 交線 発生サンプル
#
tor = Prim::torus [], Vec::zdir, 30, 10, Math::PI * 2
pln = Build::infplane [], [0.5, 0.3, 0.8].to_v.normal
int_line = tor.section(pln)
faces = []
int_line.explore(ShapeType::EDGE) do |e|
w = Build::wire [e]
faces << (Build::face w, true)
end
comp = Build::compound faces
BRepIO::save comp, "int.brep"
BRepIO::save tor, "torus.brep"
| #!/usr/bin/siren
# coding: utf-8
#
# 交線 発生サンプル
#
tor = Prim.torus [0, 0, 0], Vec.zdir, 30, 10, Math::PI * 2
pln = Build.infplane [0, 0, 0], [0.5, 0.3, 0.8].to_v.normal
int_curve = tor.section(pln)
faces = []
int_curve.edges do |e|
w = Build.wire [e]
faces << (Build.face w, true)
end
comp = Build.compound faces
BRepIO.save comp, "int.brep"
BRepIO.save tor, "torus.brep"
|
Add missing dev dependency on Rake | # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "sr71/version"
Gem::Specification.new do |s|
s.name = "sr71"
s.version = Sr71::VERSION
s.authors = ["Michael Pilat"]
s.email = ["mike@mikepilat.com"]
s.homepage = "http://mikepilat.com/"
s.summary = %q{A remote service monitor}
s.description = %q{A remote service monitor}
s.rubyforge_project = "sr71"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.add_dependency "eventmachine", "~> 1.0.0"
s.add_dependency "em-http-request", "~> 1.0"
s.add_development_dependency "rspec", "~> 2.11.0"
end
| # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "sr71/version"
Gem::Specification.new do |s|
s.name = "sr71"
s.version = Sr71::VERSION
s.authors = ["Michael Pilat"]
s.email = ["mike@mikepilat.com"]
s.homepage = "http://mikepilat.com/"
s.summary = %q{A remote service monitor}
s.description = %q{A remote service monitor}
s.rubyforge_project = "sr71"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.add_dependency "eventmachine", "~> 1.0.0"
s.add_dependency "em-http-request", "~> 1.0"
s.add_development_dependency "rspec", "~> 2.11.0"
s.add_development_dependency "rake", "~> 10.3"
end
|
Create options responses for other endpoints | AnnotatorStore::Engine.routes.draw do
# Root path
root 'pages#index', defaults: { format: :json }
# Search
match 'search', to: 'pages#search', via: [:get], defaults: { format: :json }, constraints: { format: :json }
# Annotations Endpoint
resources :annotations, only: [:create, :show, :update, :destroy], defaults: { format: :json }, constraints: { format: :json } do
match '/', to: 'annotations#options', via: [:options], on: :collection
end
end
| AnnotatorStore::Engine.routes.draw do
# Root path
root 'pages#index', defaults: { format: :json }
# Search
match 'search', to: 'pages#search', via: [:get], defaults: { format: :json }, constraints: { format: :json }
match 'search', to: 'annotations#options', via: [:options], defaults: { format: :json }, constraints: { format: :json }
# Annotations Endpoint
resources :annotations, only: [:create, :show, :update, :destroy], defaults: { format: :json }, constraints: { format: :json } do
match '/', to: 'annotations#options', via: [:options], on: :collection
match '/', to: 'annotations#options', via: [:options], on: :member
end
end
|
Fix a problem where Viking wasn't always loaded when the initializer was running | Merb::BootLoader.after_app_loads do
config_path = Merb.root / 'config' / 'spam_protection.yml'
# Initialize Viking with all the information it needs to use the
# spam protection service of choice
if File.exists?(config_path)
unless (config = YAML.load_file(config_path))[:api].blank?
Viking.default_engine = config[:api]
Viking.connect_options = config[:connect_options]
end
end
end | # Sometimes Viking isn't loaded at this point, so we make sure it is here
unless Object.const_defined?("Viking")
require Merb.root / 'lib' / 'viking' / 'viking'
end
Merb::BootLoader.after_app_loads do
config_path = Merb.root / 'config' / 'spam_protection.yml'
# Initialize Viking with all the information it needs to use the
# spam protection service of choice
if File.exists?(config_path)
unless (config = YAML.load_file(config_path))[:api].blank?
Viking.default_engine = config[:api]
Viking.connect_options = config[:connect_options]
end
end
end |
Reorder helper method at bottom | RSpec::Matchers.define :have_table_row do |row|
match_for_should do |node|
@row = row
false_on_timeout_error do
wait_until { rows_under(node).include? row }
end
end
match_for_should_not do |node|
@row = row
false_on_timeout_error do
# Without this sleep, we trigger capybara's wait when looking up the table, for the full
# period of default_wait_time.
sleep 0.1
wait_until { !rows_under(node).include? row }
end
end
def rows_under(node)
node.all('tr').map { |tr| tr.all('th, td').map(&:text) }
end
def false_on_timeout_error
yield
rescue TimeoutError
false
else
true
end
failure_message_for_should do |text|
"expected to find table row #{@row}"
end
failure_message_for_should_not do |text|
"expected not to find table row #{@row}"
end
end
| RSpec::Matchers.define :have_table_row do |row|
match_for_should do |node|
@row = row
false_on_timeout_error do
wait_until { rows_under(node).include? row }
end
end
match_for_should_not do |node|
@row = row
false_on_timeout_error do
# Without this sleep, we trigger capybara's wait when looking up the table, for the full
# period of default_wait_time.
sleep 0.1
wait_until { !rows_under(node).include? row }
end
end
failure_message_for_should do |text|
"expected to find table row #{@row}"
end
failure_message_for_should_not do |text|
"expected not to find table row #{@row}"
end
def rows_under(node)
node.all('tr').map { |tr| tr.all('th, td').map(&:text) }
end
def false_on_timeout_error
yield
rescue TimeoutError
false
else
true
end
end
|
Disable confirmation column in the CSV. We'll re-add once we get the proper data and if it clears security | class Promo::EmailBreakdownsJob
include Sidekiq::Worker
sidekiq_options queue: :default, retry: true
def perform(publisher_id)
referral_codes = PromoRegistration.where(publisher_id: publisher_id).pluck(:referral_code)
csv = CSV.parse(Promo::RegistrationStatsReportGenerator.new(
referral_codes: referral_codes,
start_date: 1.days.ago.to_date,
end_date: 1.days.ago.to_date,
reporting_interval: PromoRegistration::DAILY,
is_geo: true,
include_ratios: false
).perform)
new_csv = []
csv.each do |row|
row.delete_at(2) # delete Day column
new_csv << row.join(",")
end
publisher = Publisher.find_by(id: publisher_id)
PublisherMailer.promo_breakdowns(publisher, new_csv.join("\n")).deliver_now
end
end
| class Promo::EmailBreakdownsJob
include Sidekiq::Worker
sidekiq_options queue: :default, retry: true
def perform(publisher_id)
referral_codes = PromoRegistration.where(publisher_id: publisher_id).pluck(:referral_code)
csv = CSV.parse(Promo::RegistrationStatsReportGenerator.new(
referral_codes: referral_codes,
start_date: 1.days.ago.to_date,
end_date: 1.days.ago.to_date,
reporting_interval: PromoRegistration::DAILY,
is_geo: true,
include_ratios: false
).perform)
new_csv = []
csv.each do |row|
row.delete_at(5) # delete the 30-day-confirmation column
row.delete_at(2) # delete Day column
new_csv << row.join(",")
end
publisher = Publisher.find_by(id: publisher_id)
PublisherMailer.promo_breakdowns(publisher, new_csv.join("\n")).deliver_now
end
end
|
Add action to show user profile page | class StudentsController < ApplicationController
before_filter :authenticate_user!
def index
@students = Student.order("name")
end
end
| class StudentsController < ApplicationController
before_filter :authenticate_user!
#TODO: Add before filter to ensure user's partner has a relationship
def index
@students = Student.order("name")
end
def show
@student = Student.find(params[:id])
end
end
|
Remove unused district serializer params | class DistrictSerializer < ActiveModel::Serializer
attributes :name, :region, :vpc_id, :public_elb_security_group, :private_elb_security_group,
:instance_security_group, :ecs_service_role, :ecs_instance_profile,
:private_hosted_zone_id, :s3_bucket_name, :container_instances,
:stack_status, :nat_type, :cluster_size, :cluster_instance_type,
:cluster_backend, :cidr_block, :stack_name, :bastion_ip,
:aws_access_key_id, :aws_role
has_many :heritages
has_many :plugins
end
| class DistrictSerializer < ActiveModel::Serializer
attributes :name, :region, :s3_bucket_name, :container_instances,
:stack_status, :nat_type, :cluster_size, :cluster_instance_type,
:cluster_backend, :cidr_block, :stack_name, :bastion_ip,
:aws_access_key_id, :aws_role
has_many :heritages
has_many :plugins
end
|
Update user finding (by username) in teams members (team of users) controller | class Teams::MembersController < Teams::ApplicationController
skip_before_filter :authorize_manage_user_team!, only: [:index]
def index
@members = user_team.members
end
def new
@users = User.potential_team_members(user_team)
@users = UserDecorator.decorate @users
end
def create
unless params[:user_ids].blank?
user_ids = params[:user_ids]
access = params[:default_project_access]
is_admin = params[:group_admin]
user_team.add_members(user_ids, access, is_admin)
end
redirect_to team_members_path(user_team), notice: 'Members was successfully added into Team of users.'
end
def edit
team_member
end
def update
options = {default_projects_access: params[:default_project_access], group_admin: params[:group_admin]}
if user_team.update_membership(team_member, options)
redirect_to team_members_path(user_team), notice: "Membership for #{team_member.name} was successfully updated in Team of users."
else
render :edit
end
end
def destroy
user_team.remove_member(team_member)
redirect_to team_path(user_team), notice: "Member #{team_member.name} was successfully removed from Team of users."
end
protected
def team_member
@member ||= user_team.members.find(params[:id])
end
end
| class Teams::MembersController < Teams::ApplicationController
skip_before_filter :authorize_manage_user_team!, only: [:index]
def index
@members = user_team.members
end
def new
@users = User.potential_team_members(user_team)
@users = UserDecorator.decorate @users
end
def create
unless params[:user_ids].blank?
user_ids = params[:user_ids]
access = params[:default_project_access]
is_admin = params[:group_admin]
user_team.add_members(user_ids, access, is_admin)
end
redirect_to team_members_path(user_team), notice: 'Members was successfully added into Team of users.'
end
def edit
team_member
end
def update
options = {default_projects_access: params[:default_project_access], group_admin: params[:group_admin]}
if user_team.update_membership(team_member, options)
redirect_to team_members_path(user_team), notice: "Membership for #{team_member.name} was successfully updated in Team of users."
else
render :edit
end
end
def destroy
user_team.remove_member(team_member)
redirect_to team_path(user_team), notice: "Member #{team_member.name} was successfully removed from Team of users."
end
protected
def team_member
@member ||= user_team.members.find_by_username(params[:id])
end
end
|
Change update method to avoid ActiveRecord::ReadOnly when updating variant | Spree::Api::VariantsController.class_eval do
def update
authorize! :update, Spree::Variant
@variant = Spree::Variant.find(params[:id])
if @variant.update_attributes(params[:variant])
respond_with(@variant, :status => 200, :default_template => :show)
else
invalid_resource!(@product)
end
end
end | |
Mark validation errors as HTML-safe | module FormHelper
def messages_on_error(object)
return '' if object.errors.count.zero?
content_tag(:div, :class => "errors") do
content_tag(:h2, pluralize(object.errors.count, "erreur") + ' : ') +
content_tag(:ul) do
object.errors.values.flatten.map do |err|
content_tag(:li, err)
end.join
end
end
end
end
| module FormHelper
def messages_on_error(object)
return '' if object.errors.count.zero?
content_tag(:div, :class => "errors") do
content_tag(:h2, pluralize(object.errors.count, "erreur") + ' : ') +
content_tag(:ul) do
object.errors.values.flatten.map do |err|
content_tag(:li, err)
end.join.html_safe
end
end
end
end
|
Use correct path to app settings. | class AppSettings < Settingslogic
source Rails.root.join("config/app_settings.yml")
end | class AppSettings < Settingslogic
# This points at /var/vcap/packages, not /var/vcap/jobs which is where
# BOSH renders the config templates.
#source Rails.root.join("config/app_settings.yml")
source '/var/vcap/jobs/cf-mysql-broker/config/app_settings.yml'
end |
Append git to repo url | Pod::Spec.new do |s|
s.name = 'XINGAPIClientTester'
s.version = '0.0.1'
s.license = 'MIT'
s.ios.deployment_target = '6.0'
s.osx.deployment_target = '10.7'
s.summary = 'The client tester for the XINGAPIClient'
s.author = {
'XING iOS Team' => 'iphonedev@xing.com'
}
s.source = {
:git => 'https://github.com/xing/XINGAPIClientTester',
:tag => '0.0.1'
}
s.source_files = '*.{h,m}'
s.requires_arc = true
s.homepage = 'https://www.xing.com'
s.dependency 'OHHTTPStubs', '~> 3.0.2'
s.dependency 'Expecta', '~> 0.2.1'
s.dependency 'XINGAPI', '~> 0.0.4'
end
| Pod::Spec.new do |s|
s.name = 'XINGAPIClientTester'
s.version = '0.0.1'
s.license = 'MIT'
s.ios.deployment_target = '6.0'
s.osx.deployment_target = '10.7'
s.summary = 'The client tester for the XINGAPIClient'
s.author = {
'XING iOS Team' => 'iphonedev@xing.com'
}
s.source = {
:git => 'https://github.com/xing/XINGAPIClientTesteri.git',
:tag => '0.0.1'
}
s.source_files = '*.{h,m}'
s.requires_arc = true
s.homepage = 'https://www.xing.com'
s.dependency 'OHHTTPStubs', '~> 3.0.2'
s.dependency 'Expecta', '~> 0.2.1'
s.dependency 'XINGAPI', '~> 0.0.4'
end
|
Add base64_binary native type to XSD builder | module Spectifly
module Xsd
class Types
Native = [
'boolean',
'string',
'date',
'date_time',
'integer',
'non_negative_integer',
'positive_integer',
'decimal'
]
Extended = Spectifly::Types::Extended
class << self
def build_extended(xml = nil)
xml ||= ::Builder::XmlMarkup.new(:indent => 2)
xml.instruct! :xml, :version => '1.0', :encoding => 'UTF-8'
xml.xs :schema, 'xmlns:xs' => "http://www.w3.org/2001/XMLSchema", 'elementFormDefault' => "qualified" do
Extended.each_pair do |name, attributes|
field = Spectifly::Xsd::Field.new(name.dup, attributes.dup)
field.type_block(true).call(xml)
end
end
end
end
end
end
end | module Spectifly
module Xsd
class Types
Native = [
'boolean',
'string',
'date',
'date_time',
'integer',
'non_negative_integer',
'positive_integer',
'decimal',
'base64_binary'
]
Extended = Spectifly::Types::Extended
class << self
def build_extended(xml = nil)
xml ||= ::Builder::XmlMarkup.new(:indent => 2)
xml.instruct! :xml, :version => '1.0', :encoding => 'UTF-8'
xml.xs :schema, 'xmlns:xs' => "http://www.w3.org/2001/XMLSchema", 'elementFormDefault' => "qualified" do
Extended.each_pair do |name, attributes|
field = Spectifly::Xsd::Field.new(name.dup, attributes.dup)
field.type_block(true).call(xml)
end
end
end
end
end
end
end |
Move parsing into its own class | module QueryStringSearch
class SearchOption
attr_reader :attribute, :desired_value, :operator
def initialize(raw_query)
parsed_query = /(?<attribute>\w+)(?<operator>\W+)(?<value>.+)/.match(raw_query)
if parsed_query
self.attribute = parsed_query[:attribute]
self.desired_value = parsed_query[:value]
self.operator = parsed_query[:operator]
end
end
def attribute
@attribute ? @attribute.to_sym : nil
end
private
attr_writer :attribute, :desired_value, :operator
end
end
| module QueryStringSearch
class SearchOption
attr_reader :attribute, :desired_value, :operator
def initialize(raw_query)
parsed_query = KeyValue.parse(raw_query)
self.attribute = parsed_query.attribute
self.desired_value = parsed_query.desired_value
self.operator = parsed_query.operator
end
def attribute
@attribute ? @attribute.to_sym : nil
end
private
attr_writer :attribute, :desired_value, :operator
end
class KeyValue
attr_accessor :attribute, :desired_value, :operator
def self.parse(raw_query)
new(/(?<attribute>\w+)(?<operator>\W+)(?<desired_value>.+)/.match(raw_query))
end
def initialize(match_data)
match_data = match_data ? match_data : {}
self.attribute = match_data[:attribute]
self.desired_value = match_data[:desired_value]
self.operator = match_data[:operator]
end
end
end
|
Split logo size in width and height obj | class Api::PartnerSerializer < ActiveModel::Serializer
attributes :id, :name, :url, :logo, :logo_dimensions, :contact_name, :contact_email
end
| class Api::PartnerSerializer < ActiveModel::Serializer
attributes :id, :name, :url, :logo, :logo_size, :contact_name, :contact_email
def logo_size
dimensions = object.logo_dimensions.split('x')
{ width: dimensions[0].to_i, height: dimensions[1].to_i}
end
end
|
Make the scenario with the non-integer number fail | Given(/^the calculator has clean memory$/) do
@result = 0
@numbersList = []
end
Given(/^I have entered (\d+) into the calculator$/) do |arg1|
@numbersList << arg1.to_i
end
When(/^I press add$/) do
@numbersList.each do |number|
@result = @result + number
end
end
Then(/^the result should be (\d+) on the screen$/) do |arg1|
expect(@result).to eql(arg1.to_i)
end
| Given(/^the calculator has clean memory$/) do
@result = 0
@numbersList = []
end
Given(/^I have entered (\d+) into the calculator$/) do |arg1|
@numbersList << arg1.to_i
end
Given(/^I have entered (\d+)\.(\d+) into the calculator$/) do |arg1, arg2|
expect("this is a hacky way of making the scenario with a non-integer number").to eql("fail")
end
When(/^I press add$/) do
@numbersList.each do |number|
@result = @result + number
end
end
Then(/^the result should be (\d+) on the screen$/) do |arg1|
expect(@result).to eql(arg1.to_i)
end
Then(/^the result should be (\d+)\.(\d+) on the screen$/) do |arg1, arg2|
expect("this is a hacky way of making the scenario with a non-integer number").to eql("fail")
end
|
Remove obsolete block (we're always getting a new redis now) | require_relative "../../test/support/taxonomy_helper"
module AdminTaxonomyHelper
include TaxonomyHelper
def select_taxon(label)
check label
end
def select_taxon_and_save(label, save_btn_label)
select_taxon(label)
click_button save_btn_label
end
def stub_taxonomy_data
redis_cache_has_taxons [root_taxon, draft_taxon1, draft_taxon2]
end
def stub_patch_links
Services.publishing_api.stubs(patch_links: { status: 200 })
end
def check_links_patched_in_publishing_api
expect(Services.publishing_api).to respond_to(:patch_links)
end
end
World(AdminTaxonomyHelper)
Around do |_, block|
redis = Redis.new
Redis.new = nil
block.call
ensure
Redis.new = redis
end
| require_relative "../../test/support/taxonomy_helper"
module AdminTaxonomyHelper
include TaxonomyHelper
def select_taxon(label)
check label
end
def select_taxon_and_save(label, save_btn_label)
select_taxon(label)
click_button save_btn_label
end
def stub_taxonomy_data
redis_cache_has_taxons [root_taxon, draft_taxon1, draft_taxon2]
end
def stub_patch_links
Services.publishing_api.stubs(patch_links: { status: 200 })
end
def check_links_patched_in_publishing_api
expect(Services.publishing_api).to respond_to(:patch_links)
end
end
World(AdminTaxonomyHelper)
|
Fix typo in religion "other names" field strong param | class ReligionsController < ContentController
private
def content_params
params.require(:religion).permit(content_param_list)
end
def content_param_list
%i(
name description other_name universe_id
origin_story
teachings prophecies places_of_worship worship_services obligations paradise
initiation rituals holidays
notes private_notes privacy
) + [
custom_attribute_values: [:name, :value],
religious_figureships_attributes: [:id, :notable_figure_id, :_destroy],
deityships_attributes: [:id, :deity_id, :_destroy],
religious_locationships_attributes: [:id, :practicing_location_id, :_destroy],
artifactships_attributes: [:id, :artifact_id, :_destroy],
religious_raceships_attributes: [:id, :race_id, :_destroy]
]
end
end
| class ReligionsController < ContentController
private
def content_params
params.require(:religion).permit(content_param_list)
end
def content_param_list
%i(
name description other_names universe_id
origin_story
teachings prophecies places_of_worship worship_services obligations paradise
initiation rituals holidays
notes private_notes privacy
) + [
custom_attribute_values: [:name, :value],
religious_figureships_attributes: [:id, :notable_figure_id, :_destroy],
deityships_attributes: [:id, :deity_id, :_destroy],
religious_locationships_attributes: [:id, :practicing_location_id, :_destroy],
artifactships_attributes: [:id, :artifact_id, :_destroy],
religious_raceships_attributes: [:id, :race_id, :_destroy]
]
end
end
|
Change how default admin name is handled | module SocialNetworking
# A set of data representing a Social Profile belonging to a Participant.
class Profile < ActiveRecord::Base
ACTION_TYPES = %w( created completed )
Actions = Struct.new(*ACTION_TYPES.map(&:to_sym)).new(*ACTION_TYPES)
belongs_to :participant
has_many :profile_answers,
class_name: "SocialNetworking::ProfileAnswer",
foreign_key: :social_networking_profile_id,
dependent: :destroy
has_many :comments, as: "item"
has_many :likes, as: "item"
validates :participant, presence: true
delegate :latest_action_at, :active_membership_end_date,
to: :participant
def to_serialized
{}
end
def description
"Welcome, #{user_name}!"
end
def shared_description
"Profile Created: #{participant.display_name}"
end
def user_name
if participant.is_admin
"ThinkFeelDo"
else
participant.display_name
end
end
end
end
| module SocialNetworking
# A set of data representing a Social Profile belonging to a Participant.
class Profile < ActiveRecord::Base
ACTION_TYPES = %w( created completed )
Actions = Struct.new(*ACTION_TYPES.map(&:to_sym)).new(*ACTION_TYPES)
belongs_to :participant
has_many :profile_answers,
class_name: "SocialNetworking::ProfileAnswer",
foreign_key: :social_networking_profile_id,
dependent: :destroy
has_many :comments, as: "item"
has_many :likes, as: "item"
validates :participant, presence: true
delegate :latest_action_at, :active_membership_end_date,
to: :participant
def to_serialized
{}
end
def description
"Welcome, #{user_name}!"
end
def shared_description
"Profile Created: #{participant.display_name}"
end
def user_name
participant.display_name
end
end
end
|
Implement Rip.logo as ASCII art | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
if File.exists?(ENV['BUNDLE_GEMFILE'])
require 'bundler'
Bundler.setup
end
$LOAD_PATH.unshift(File.expand_path(__dir__ + '/../lib'))
require 'pathname'
module Rip
def self.project_path
Pathname(@path || '.').expand_path
end
def self.project_path=(path)
@path = path
end
def self.root
Pathname File.expand_path('..', __FILE__)
end
end
require 'rip/cli'
require 'rip/core'
require 'rip/exceptions'
require 'rip/nodes'
require 'rip/utilities'
require 'rip/compiler'
require 'rip/loaders'
require 'rip/version'
| ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
if File.exists?(ENV['BUNDLE_GEMFILE'])
require 'bundler'
Bundler.setup
end
$LOAD_PATH.unshift(File.expand_path(__dir__ + '/../lib'))
require 'pathname'
module Rip
def self.logo
<<-'RIP'
_ _ _
/\ \ /\ \ /\ \
/ \ \ \ \ \ / \ \
/ /\ \ \ /\ \_\ / /\ \ \
/ / /\ \_\ / /\/_/ / / /\ \_\
/ / /_/ / / / / / / / /_/ / /
/ / /__\/ / / / / / / /__\/ /
/ / /_____/ / / / / / /_____/
/ / /\ \ \ ___/ / /__ / / /
/ / / \ \ \/\__\/_/___\/ / /
\/_/ \_\/\/_________/\/_/
RIP
end
def self.project_path
Pathname(@path || '.').expand_path
end
def self.project_path=(path)
@path = path
end
def self.root
Pathname File.expand_path('..', __FILE__)
end
end
require 'rip/cli'
require 'rip/core'
require 'rip/exceptions'
require 'rip/nodes'
require 'rip/utilities'
require 'rip/compiler'
require 'rip/loaders'
require 'rip/version'
|
Fix load path problem caused from rake | require "altria/command"
require "altria/configuration"
require "altria/responder"
require "altria/version"
require "altria/workspace"
module Altria
class << self
def configuration
@configuration ||= Altria::Configuration.new
end
end
end
| $LOAD_PATH.unshift File.expand_path("..", __FILE__)
require "altria/command"
require "altria/configuration"
require "altria/responder"
require "altria/version"
require "altria/workspace"
module Altria
class << self
def configuration
@configuration ||= Altria::Configuration.new
end
end
end
|
Create cask for BassJump.prefpane v2.5.1 | class Bassjump < Cask
if MacOS.version == :mavericks
url 'http://ffe82a399885f9f28605-66638985576304cbe11c530b9b932f18.r24.cf2.rackcdn.com/BassJumpInstaller_2.5.1.dmg.zip'
version '2.5.1'
sha256 '14408480cded51f6334753639e973ebbf2fc40f34ff64e1c35d2f32507d88afd'
nested_container 'BassJumpInstaller_2.5.1.dmg'
install 'BassJumpInstaller.pkg'
else
url 'http://ffe82a399885f9f28605-66638985576304cbe11c530b9b932f18.r24.cf2.rackcdn.com/BassJumpSoundSystem-2.0.3-249-ML.mpkg.zip'
version '2.0.3'
sha256 '8e4dffa6bb3b532b994f379d19d70903f59fc019916f10cba9d01b8075d69a7f'
install 'BassJump Sound System-2.0.3-249-ML.mpkg'
end
homepage 'http://www.twelvesouth.com/product/bassjump-2-for-macbook'
caveats do
reboot
end
uninstall :pkgutil => [
'com.twelvesouth.bassjump.installer.halplugin',
'com.twelvesouth.bassjump.installer.overridekext',
'com.twelvesouth.bassjump.installer.prefpane',
],
:kext => 'com.twelvesouth.driver.BassJumpOverrideDriver'
end
| |
Add connect_response_valid? Method to Version7 | module Tomcat
module Manager
module Api
class Version7
###########################
# URL Response Methods
###########################
def connect_path
"/manager/text/list"
end
end
end
end
end
| module Tomcat
module Manager
module Api
class Version7
###########################
# URL Response Methods
###########################
def connect_path
"/manager/text/list"
end
###########################
# Processing Methods
###########################
def connect_response_valid?(response_code)
response_code == "200"
end
end
end
end
end
|
Fix RSpec dev dependency in gemspec | require File.expand_path('../lib/vimrunner/version', __FILE__)
Gem::Specification.new do |s|
s.name = 'vimrunner'
s.version = Vimrunner::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ['Andrew Radev', 'Paul Mucur']
s.email = ['andrey.radev@gmail.com']
s.homepage = 'http://github.com/AndrewRadev/vimrunner'
s.summary = 'Lets you control a Vim instance through Ruby'
s.description = <<-D
Using Vim's client/server functionality, this library exposes a way to
spawn a Vim instance and control it programatically. Apart from being a fun
party trick, this can be used to integration test Vim script.
D
s.add_development_dependency 'rake'
s.add_development_dependency 'rdoc'
s.add_development_dependency 'simplecov'
s.add_development_dependency 'rspec', '>= 2.13.0'
s.required_rubygems_version = '>= 1.3.6'
s.rubyforge_project = 'vimrunner'
s.files = Dir['lib/**/*.rb', 'vim/*', 'bin/*', 'LICENSE', '*.md']
s.require_path = 'lib'
s.executables = ['vimrunner']
end
| require File.expand_path('../lib/vimrunner/version', __FILE__)
Gem::Specification.new do |s|
s.name = 'vimrunner'
s.version = Vimrunner::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ['Andrew Radev', 'Paul Mucur']
s.email = ['andrey.radev@gmail.com']
s.homepage = 'http://github.com/AndrewRadev/vimrunner'
s.summary = 'Lets you control a Vim instance through Ruby'
s.description = <<-D
Using Vim's client/server functionality, this library exposes a way to
spawn a Vim instance and control it programatically. Apart from being a fun
party trick, this can be used to integration test Vim script.
D
s.add_development_dependency 'rake'
s.add_development_dependency 'rdoc'
s.add_development_dependency 'simplecov'
s.add_development_dependency 'rspec', '~> 2.13.0'
s.required_rubygems_version = '>= 1.3.6'
s.rubyforge_project = 'vimrunner'
s.files = Dir['lib/**/*.rb', 'vim/*', 'bin/*', 'LICENSE', '*.md']
s.require_path = 'lib'
s.executables = ['vimrunner']
end
|
Fix uri parsing for local paths | require 'thor'
require 'daun'
require 'rugged'
require 'git_clone_url'
module Daun
# All daun cli subcommands are made available by this class.
class CLI < Thor
desc 'init remote_url destination', 'Initialize a daun directory'
def init(remote_url, destination)
Daun::RuggedDaun.new(destination).init(remote_url)
end
desc 'checkout', 'Checks out git working tree as per daun configuration'
option :directory, default: '.'
option :ssh_private_key, default: File.join(ENV['HOME'], '.ssh', 'id_rsa')
option :ssh_public_key, default: File.join(ENV['HOME'], '.ssh', 'id_rsa.pub')
def checkout
rugged_daun = Daun::RuggedDaun.new(options[:directory])
repository = rugged_daun.repository
origin = repository.remotes['origin']
origin_uri = GitCloneUrl.parse(origin.url)
credentials = nil
if [nil, 'ssh'].include? origin_uri.scheme
credentials = Rugged::Credentials::SshKey.new(
:username => origin_uri.user,
:privatekey => options[:ssh_private_key],
:publickey => options[:ssh_public_key],
)
end
rugged_daun.checkout credentials
end
end
end
| require 'thor'
require 'daun'
require 'rugged'
require 'uri'
require 'git_clone_url'
module Daun
# All daun cli subcommands are made available by this class.
class CLI < Thor
desc 'init remote_url destination', 'Initialize a daun directory'
def init(remote_url, destination)
Daun::RuggedDaun.new(destination).init(remote_url)
end
desc 'checkout', 'Checks out git working tree as per daun configuration'
option :directory, default: '.'
option :ssh_private_key, default: File.join(ENV['HOME'], '.ssh', 'id_rsa')
option :ssh_public_key, default: File.join(ENV['HOME'], '.ssh', 'id_rsa.pub')
def checkout
rugged_daun = Daun::RuggedDaun.new(options[:directory])
repository = rugged_daun.repository
origin = repository.remotes['origin']
begin
origin_uri = GitCloneUrl.parse(origin.url)
rescue URI::InvalidComponentError
origin_uri = URI.parse(origin.url)
end
is_ssh_scheme = case origin_uri.scheme
when nil, 'ssh' then true
else false
end
credentials = case (is_ssh_scheme and !origin_uri.user.nil?)
when true then
Rugged::Credentials::SshKey.new(
:username => origin_uri.user,
:privatekey => options[:ssh_private_key],
:publickey => options[:ssh_public_key],
)
else nil
end
rugged_daun.checkout credentials
end
end
end
|
Define Config outside of metaclass | require 'logger'
require 'syslog/logger'
module Proxy
ROOT = File.expand_path(File.dirname(__FILE__))
require "#{ROOT}/core_extensions/pathname"
require "#{ROOT}/proxy/cache"
require "#{ROOT}/proxy/nginx_config"
class << self
Config = Struct.new(:env)
def config
@config ||= Config.new
end
def configure
yield config
end
def production?
config.env == "production"
end
def logger
return @logger if defined?(@logger)
if production?
@logger = Syslog::Logger.new("proxy")
@logger.level = Logger::INFO
else
@logger = Logger.new(STDOUT)
@logger.progname = "proxy"
@logger.level = Logger::DEBUG
end
@logger
end
end
end
| require 'logger'
require 'syslog/logger'
module Proxy
ROOT = File.expand_path(File.dirname(__FILE__))
require "#{ROOT}/core_extensions/pathname"
require "#{ROOT}/proxy/cache"
require "#{ROOT}/proxy/nginx_config"
Config = Struct.new(:env)
class << self
def config
@config ||= Config.new
end
def configure
yield config
end
def production?
config.env == "production"
end
def logger
return @logger if defined?(@logger)
if production?
@logger = Syslog::Logger.new("proxy")
@logger.level = Logger::INFO
else
@logger = Logger.new(STDOUT)
@logger.progname = "proxy"
@logger.level = Logger::DEBUG
end
@logger
end
end
end
|
Fix rubocop issues for NFV support | module OpenstackHandle
class NFVDelegate < DelegateClass(Fog::NFV::OpenStack)
include OpenstackHandle::HandledList
include Vmdb::Logging
SERVICE_NAME = "NFV"
attr_reader :name
def initialize(dobj, os_handle, name)
super(dobj)
@os_handle = os_handle
@name = name
end
end
end
| module OpenstackHandle
class NFVDelegate < DelegateClass(Fog::NFV::OpenStack)
include OpenstackHandle::HandledList
include Vmdb::Logging
SERVICE_NAME = "NFV".freeze
attr_reader :name
def initialize(dobj, os_handle, name)
super(dobj)
@os_handle = os_handle
@name = name
end
end
end
|
Add ability to override Firefox::Bridge's @launcher | module Selenium
module WebDriver
module Firefox
# @api private
class Bridge < Remote::Bridge
def initialize(opts = {})
@launcher = Launcher.new(
Binary.new,
opts.delete(:port) || DEFAULT_PORT,
opts.delete(:profile)
)
http_client = opts.delete(:http_client)
unless opts.empty?
raise ArgumentError, "unknown option#{'s' if opts.size != 1}: #{opts.inspect}"
end
@launcher.launch
remote_opts = {
:url => @launcher.url,
:desired_capabilities => :firefox
}
remote_opts.merge!(:http_client => http_client) if http_client
super(remote_opts)
end
def browser
:firefox
end
def driver_extensions
[DriverExtensions::TakesScreenshot]
end
def quit
super
@launcher.quit
nil
end
end # Bridge
end # Firefox
end # WebDriver
end # Selenium
| module Selenium
module WebDriver
module Firefox
# @api private
class Bridge < Remote::Bridge
def initialize(opts = {})
@launcher = create_launcher(opts)
http_client = opts.delete(:http_client)
unless opts.empty?
raise ArgumentError, "unknown option#{'s' if opts.size != 1}: #{opts.inspect}"
end
@launcher.launch
remote_opts = {
:url => @launcher.url,
:desired_capabilities => :firefox
}
remote_opts.merge!(:http_client => http_client) if http_client
super(remote_opts)
end
def browser
:firefox
end
def driver_extensions
[DriverExtensions::TakesScreenshot]
end
def quit
super
@launcher.quit
nil
end
private
def create_launcher(opts)
Launcher.new(
Binary.new,
opts.delete(:port) || DEFAULT_PORT,
opts.delete(:profile)
)
end
end # Bridge
end # Firefox
end # WebDriver
end # Selenium
|
Add unit and request tasks to regular specs | require_relative "application_generator"
desc "Run the full suite using 1 core"
task test: [:setup, :spec, :cucumber]
desc 'Creates a test rails app for the specs to run against'
task :setup, [:rails_env, :template] do |_t, opts|
ActiveAdmin::ApplicationGenerator.new(opts).generate
end
desc "Run the specs"
task :spec do
system("rspec")
end
desc "Run the cucumber scenarios"
task cucumber: [:"cucumber:regular", :"cucumber:reloading"]
namespace :cucumber do
desc "Run the standard cucumber scenarios"
task :regular do
system("cucumber")
end
desc "Run the cucumber scenarios that test reloading"
task :reloading do
system("cucumber --profile class-reloading")
end
end
| require_relative "application_generator"
desc "Run the full suite using 1 core"
task test: [:setup, :spec, :cucumber]
desc 'Creates a test rails app for the specs to run against'
task :setup, [:rails_env, :template] do |_t, opts|
ActiveAdmin::ApplicationGenerator.new(opts).generate
end
desc "Run the specs"
task :spec do
system("rspec")
end
namespace :spec do
%i(unit request).each do |type|
desc "Run #{type} specs"
task type do
system("rspec spec/#{type}")
end
end
end
desc "Run the cucumber scenarios"
task cucumber: [:"cucumber:regular", :"cucumber:reloading"]
namespace :cucumber do
desc "Run the standard cucumber scenarios"
task :regular do
system("cucumber")
end
desc "Run the cucumber scenarios that test reloading"
task :reloading do
system("cucumber --profile class-reloading")
end
end
|
Add a test for the shared example test helper | require_relative '../spec_helper'
require 'govuk_message_queue_consumer/test_helpers'
describe "The usage of the shared example" do
class WellDevelopedMessageQueueConsumer
def process(_message)
end
end
describe WellDevelopedMessageQueueConsumer do
it_behaves_like "a message queue processor"
end
end
| |
Disable Shrine instrumentation unless log_level is set to debug | require 'shrine'
require 'shrine/storage/s3'
# require "shrine/storage/file_system"
s3_options = Rails.application.credentials.s3
if s3_options
Shrine.storages = {
cache: Shrine::Storage::S3.new(prefix: 'cache', public: true, **s3_options),
store: Shrine::Storage::S3.new(prefix: 'media', public: true, **s3_options),
}
end
Shrine.plugin :activerecord # Load Active Record integration
Shrine.plugin :cached_attachment_data # For retaining cached file on form redisplays
Shrine.plugin :determine_mime_type
Shrine.plugin :infer_extension
Shrine.plugin :instrumentation
Shrine.plugin :pretty_location
Shrine.plugin :remote_url, max_size: 40*1024*1024 # ~40mb
Shrine.plugin :refresh_metadata
Shrine.plugin :restore_cached_data # Refresh metadata for cached files
Shrine.plugin :type_predicates
Shrine.plugin :uppy_s3_multipart # Enable S3 multipart upload for Uppy https://github.com/janko/uppy-s3_multipart
Shrine.plugin :url_options, store: { host: Rails.application.credentials.asset_host } if Rails.application.credentials.asset_host.present?
| require 'shrine'
require 'shrine/storage/s3'
# require "shrine/storage/file_system"
s3_options = Rails.application.credentials.s3
if s3_options
Shrine.storages = {
cache: Shrine::Storage::S3.new(prefix: 'cache', public: true, **s3_options),
store: Shrine::Storage::S3.new(prefix: 'media', public: true, **s3_options),
}
end
Shrine.plugin :activerecord # Load Active Record integration
Shrine.plugin :cached_attachment_data # For retaining cached file on form redisplays
Shrine.plugin :determine_mime_type
Shrine.plugin :infer_extension
Shrine.plugin :instrumentation if (Rails.env.development? || Rails.application.config.log_level == :debug)
Shrine.plugin :pretty_location
Shrine.plugin :remote_url, max_size: 40*1024*1024 # ~40mb
Shrine.plugin :refresh_metadata
Shrine.plugin :restore_cached_data # Refresh metadata for cached files
Shrine.plugin :type_predicates
Shrine.plugin :uppy_s3_multipart # Enable S3 multipart upload for Uppy https://github.com/janko/uppy-s3_multipart
Shrine.plugin :url_options, store: { host: Rails.application.credentials.asset_host } if Rails.application.credentials.asset_host.present?
|
Fix operator_roles test after changes in 2304e863 | require 'spec_helper'
describe 'swift::proxy::keystone' do
let :fragment_file do
'/var/lib/puppet/concat/_etc_swift_proxy-server.conf/fragments/79_swift_keystone'
end
let :pre_condition do
'
include concat::setup
concat { "/etc/swift/proxy-server.conf": }
'
end
it { should contain_file(fragment_file).with_content(/[filter:keystone]/) }
it { should contain_file(fragment_file).with_content(/paste.filter_factory = keystone.middleware.swift_auth:filter_factory/) }
describe 'with defaults' do
it { should contain_file(fragment_file).with_content(/operator_roles = admin SwiftOperator/) }
it { should contain_file(fragment_file).with_content(/is_admin = true/) }
it { should contain_file(fragment_file).with_content(/cache = swift.cache/) }
it { should contain_keystone__client__authtoken('/etc/swift/proxy-server.conf') }
end
describe 'with parameter overrides' do
let :params do
{
:operator_roles => 'foo',
:is_admin => 'false',
:cache => 'somecache'
}
it { should contain_file(fragment_file).with_content(/operator_roles = foo/) }
it { should contain_file(fragment_file).with_content(/is_admin = false/) }
it { should contain_file(fragment_file).with_content(/cache = somecache/) }
end
end
end
| require 'spec_helper'
describe 'swift::proxy::keystone' do
let :fragment_file do
'/var/lib/puppet/concat/_etc_swift_proxy-server.conf/fragments/79_swift_keystone'
end
let :pre_condition do
'
include concat::setup
concat { "/etc/swift/proxy-server.conf": }
'
end
it { should contain_file(fragment_file).with_content(/[filter:keystone]/) }
it { should contain_file(fragment_file).with_content(/paste.filter_factory = keystone.middleware.swift_auth:filter_factory/) }
describe 'with defaults' do
it { should contain_file(fragment_file).with_content(/operator_roles = admin, SwiftOperator/) }
it { should contain_file(fragment_file).with_content(/is_admin = true/) }
it { should contain_file(fragment_file).with_content(/cache = swift.cache/) }
it { should contain_keystone__client__authtoken('/etc/swift/proxy-server.conf') }
end
describe 'with parameter overrides' do
let :params do
{
:operator_roles => 'foo',
:is_admin => 'false',
:cache => 'somecache'
}
it { should contain_file(fragment_file).with_content(/operator_roles = foo/) }
it { should contain_file(fragment_file).with_content(/is_admin = false/) }
it { should contain_file(fragment_file).with_content(/cache = somecache/) }
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.