Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add comment to puts statement | answer = 1 + rand(1000)
puts answer
puts "Guess what number I'm thinking of. It's between 1 and 1000"
guess = gets.to_i
while guess != answer
puts "Wrong! Guess again!"
guess = gets.to_i
end
puts "You got it!" | answer = 1 + rand(1000)
puts answer # This statement is temporary while I test the game.
puts "Guess what number I'm thinking of. It's between 1 and 1000"
guess = gets.to_i
while guess != answer
puts "Wrong! Guess again!"
guess = gets.to_i
end
puts "You got it!" |
Use SQL to update records in migration | class LoadIssueIdToSearcherRecord < ActiveRecord::Migration
def change
reversible do |d|
d.up do
sql = "UPDATE searcher_records SET issue_id = original_id WHERE original_type = 'Issue'"
execute(sql)
# Following query on PostgreSQL causes error, so I decided to update searcher_records using AR
# sql = "UPDATE searcher_records AS s SET issue_id = j.journalized_id FROM journals AS j WHERE original_id = j.id AND original_type = 'Journal'"
# execute(sql)
n_records = Journal.count(:id)
n_pages = n_records / 1000
(0..n_pages).each do |offset|
Journal.limit(1000).offset(offset * 1000).each do |record|
FullTextSearch::SearcherRecord
.where(original_id: record.id, original_type: "Journal")
.update_all(issue_id: record.journalized_id)
end
end
end
d.down do
# Do nothing
end
end
end
end
| class LoadIssueIdToSearcherRecord < ActiveRecord::Migration
def change
reversible do |d|
d.up do
sql = "UPDATE searcher_records SET issue_id = original_id WHERE original_type = 'Issue'"
execute(sql)
sql = case
when Redmine::Database.postgresql?
"UPDATE searcher_records AS s SET issue_id = j.journalized_id FROM journals AS j WHERE original_id = j.id AND original_type = 'Journal'"
when Redmine::Database.mysql?
"update searcher_records as s join journals as j on s.original_id = j.id set s.issue_id = j.journalized_id where s.original_type = 'Journal'"
end
execute(sql)
end
d.down do
# Do nothing
end
end
end
end
|
Restructure to allow matches_all to be called from a subclass | module Discordrb::Events
class Negated
attr_reader :object
def initialize(object); @object = object; end
end
def matches_all(attributes, to_check, &block)
# "Zeroth" case: attributes is nil
return true unless attributes
# First case: there's a single negated attribute
if attributes.is_a? Negated
# The contained object might also be an array, so recursively call matches_all (and negate the result)
return !matches_all(attributes.object, to_check, &block)
end
# Second case: there's a single, not-negated attribute
unless attributes.is_a? Array
return yield(attributes, to_check)
end
# Third case: it's an array of attributes
attributes.reduce(false) do |result, element|
result || yield(element, to_check)
end
end
class EventHandler
def initialize(attributes, block)
@attributes = attributes
@block = block
end
def matches?(event)
raise "Attempted to call matches?() from a generic EventHandler"
end
def match(event)
@block.call(event) if matches? event
end
end
# Event handler that matches all events
class TrueEventHandler < EventHandler
def matches?(event)
true
end
end
end
def not!(object)
Discordrb::Events::Negated.new(object)
end
| module Discordrb::Events
class Negated
attr_reader :object
def initialize(object); @object = object; end
end
def self.matches_all(attributes, to_check, &block)
# "Zeroth" case: attributes is nil
return true unless attributes
# First case: there's a single negated attribute
if attributes.is_a? Negated
# The contained object might also be an array, so recursively call matches_all (and negate the result)
return !matches_all(attributes.object, to_check, &block)
end
# Second case: there's a single, not-negated attribute
unless attributes.is_a? Array
return yield(attributes, to_check)
end
# Third case: it's an array of attributes
attributes.reduce(false) do |result, element|
result || yield(element, to_check)
end
end
class EventHandler
def initialize(attributes, block)
@attributes = attributes
@block = block
end
def matches?(event)
raise "Attempted to call matches?() from a generic EventHandler"
end
def match(event)
@block.call(event) if matches? event
end
def matches_all(attributes, to_check, &block)
Discordrb::Events.matches_all(attributes, to_check, &block)
end
end
# Event handler that matches all events
class TrueEventHandler < EventHandler
def matches?(event)
true
end
end
end
def not!(object)
Discordrb::Events::Negated.new(object)
end
|
Clean localstorage before each test | RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.disable_monkey_patching!
# This setting enables warnings. It's recommended, but in some cases may
# be too noisy due to issues in dependencies.
config.warnings = true
if config.files_to_run.one?
config.default_formatter = 'doc'
end
config.order = :random
Kernel.srand config.seed
end
require 'capybara/rspec'
require 'capybara/poltergeist'
require 'phantomjs'
ADDRESS = ENV.fetch('PLAYGROUND_UI_ADDRESS', '127.0.0.1')
PORT = ENV.fetch('PLAYGROUND_UI_PORT', '5000')
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(app, phantomjs: Phantomjs.path)
end
Capybara.javascript_driver = :poltergeist
Capybara.app_host = "http://#{ADDRESS}:#{PORT}"
Capybara.run_server = false
| RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.disable_monkey_patching!
# This setting enables warnings. It's recommended, but in some cases may
# be too noisy due to issues in dependencies.
config.warnings = true
if config.files_to_run.one?
config.default_formatter = 'doc'
end
config.order = :random
Kernel.srand config.seed
end
require 'capybara/rspec'
require 'capybara/poltergeist'
require 'phantomjs'
ADDRESS = ENV.fetch('PLAYGROUND_UI_ADDRESS', '127.0.0.1')
PORT = ENV.fetch('PLAYGROUND_UI_PORT', '5000')
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(app, phantomjs: Phantomjs.path)
end
Capybara.javascript_driver = :poltergeist
Capybara.app_host = "http://#{ADDRESS}:#{PORT}"
Capybara.run_server = false
RSpec.configure do |config|
config.before do
visit '/'
page.execute_script 'localStorage.clear();'
end
end
|
Add sampler for CPU usage | module Custodian
module Samplers
class CPU < Custodian::Samplers::Sampler
describe "CPU usage"
def sample
cpu = `top -l 1`.match /CPU usage: ([0-9]+\.[0-9]+%) user, ([0-9]+\.[0-9]+%) sys, ([0-9]+\.[0-9]+%) idle/
{
"User" => cpu[1],
"System" => cpu[2],
"Idle" => cpu[3]
}
end
end
end
end
| |
Remove reference to dependency service | require 'fulmar/version'
require 'fulmar/service/bootstrap_service'
require 'fulmar/service/helper_service'
require 'fulmar/domain/service/initialization_service'
require 'fulmar/domain/service/application_service'
require 'fulmar/domain/service/configuration_service'
require 'fulmar/domain/service/template_rendering_service'
require 'fulmar/domain/service/file_sync_service'
require 'fulmar/domain/service/dependency_service'
require 'fulmar/infrastructure/service/copy_service'
require 'fulmar/infrastructure/service/ssh_config_service'
require 'fileutils'
bootstrap = Fulmar::Service::BootstrapService.new
bootstrap.fly
| require 'fulmar/version'
require 'fulmar/service/bootstrap_service'
require 'fulmar/service/helper_service'
require 'fulmar/domain/service/initialization_service'
require 'fulmar/domain/service/application_service'
require 'fulmar/domain/service/configuration_service'
require 'fulmar/domain/service/template_rendering_service'
require 'fulmar/domain/service/file_sync_service'
require 'fulmar/infrastructure/service/copy_service'
require 'fulmar/infrastructure/service/ssh_config_service'
require 'fileutils'
bootstrap = Fulmar::Service::BootstrapService.new
bootstrap.fly
|
Add description for xdebug formula | require File.expand_path("../../Abstract/abstract-php-extension", __FILE__)
class Php53Xdebug < AbstractPhp53Extension
init
homepage "http://xdebug.org"
url "http://xdebug.org/files/xdebug-2.2.7.tgz"
sha256 "4fce7fc794ccbb1dd0b961191cd0323516e216502fe7209b03711fc621642245"
head "https://github.com/xdebug/xdebug.git"
def extension_type
"zend_extension"
end
def install
Dir.chdir "xdebug-#{version}" unless build.head?
ENV.universal_binary if build.universal?
safe_phpize
system "./configure", "--prefix=#{prefix}",
phpconfig,
"--disable-debug",
"--disable-dependency-tracking",
"--enable-xdebug"
system "make"
prefix.install "modules/xdebug.so"
write_config_file if build.with? "config-file"
end
end
| require File.expand_path("../../Abstract/abstract-php-extension", __FILE__)
class Php53Xdebug < AbstractPhp53Extension
init
desc "PHP extension which provides debugging and profiling capabilities."
homepage "http://xdebug.org"
url "http://xdebug.org/files/xdebug-2.2.7.tgz"
sha256 "4fce7fc794ccbb1dd0b961191cd0323516e216502fe7209b03711fc621642245"
head "https://github.com/xdebug/xdebug.git"
def extension_type
"zend_extension"
end
def install
Dir.chdir "xdebug-#{version}" unless build.head?
ENV.universal_binary if build.universal?
safe_phpize
system "./configure", "--prefix=#{prefix}",
phpconfig,
"--disable-debug",
"--disable-dependency-tracking",
"--enable-xdebug"
system "make"
prefix.install "modules/xdebug.so"
write_config_file if build.with? "config-file"
end
end
|
Add in category_id to attributes | module Square
module Connect
class Item < Node
attr_accessor(
:merchant,
:creator,
:created_at,
:description,
:name,
:visibility,
:category_id,
:category,
:variations
)
def attributes
{description: description,
name: name,
visibility: visibility,
variations: variations.collect(&:attributes)}
end
def initialize(*args)
super do |attributes|
self.merchant = if attributes[:merchant_id]
Merchant.new attributes[:merchant_id], access_token
else
Merchant.me access_token
end
self.created_at = if attributes[:created_at]
Time.parse attributes[:created_at]
end
self.description = attributes[:description]
self.name = attributes[:name]
self.visibility = attributes[:visibility]
self.category = Hash(attributes[:category]) if attributes[:category]
self.category_id = self.category[:id] if attributes[:category]
self.category_id = attributes[:category_id] if attributes[:category_id]
self.variations = Array(attributes[:variations]).collect do |variation_attributes|
ItemVariation.new variation_attributes
end
self.endpoint = endpoint_for merchant.identifier, :items, identifier
end
end
end
end
end | module Square
module Connect
class Item < Node
attr_accessor(
:merchant,
:creator,
:created_at,
:description,
:name,
:visibility,
:category_id,
:category,
:variations
)
def attributes
{description: description,
name: name,
visibility: visibility,
category_id: category_id,
variations: variations.collect(&:attributes)}
end
def initialize(*args)
super do |attributes|
self.merchant = if attributes[:merchant_id]
Merchant.new attributes[:merchant_id], access_token
else
Merchant.me access_token
end
self.created_at = if attributes[:created_at]
Time.parse attributes[:created_at]
end
self.description = attributes[:description]
self.name = attributes[:name]
self.visibility = attributes[:visibility]
self.category = Hash(attributes[:category]) if attributes[:category]
self.category_id = self.category[:id] if attributes[:category]
self.category_id = attributes[:category_id] if attributes[:category_id]
self.variations = Array(attributes[:variations]).collect do |variation_attributes|
ItemVariation.new variation_attributes
end
self.endpoint = endpoint_for merchant.identifier, :items, identifier
end
end
end
end
end |
Add test for knife-opc org creation | # Copyright: Copyright (c) 2016 Chef Software, Inc.
# License: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'pedant/rspec/knife_util'
require 'pedant/rspec/user_util'
describe 'knife', :knife do
context 'opc' do
context 'org' do
context 'create' do
include Pedant::RSpec::KnifeUtil
include Pedant::RSpec::UserUtil
let(:org_name) { "org-#{rand(1<<32)}" }
let(:superuser_rb) { '/etc/opscode/pivotal.rb'}
let(:requestor) { superuser }
let(:admin_requestor) { superuser }
after(:each) { knife "opc org delete #{org_name} -c #{superuser_rb} --yes" }
context 'without associations' do
let(:command) { "knife opc org create #{org_name} #{org_name} -c #{superuser_rb} --disable-editing" }
it 'should succeed' do
should have_outcome :status => 0, :stdout => /-----BEGIN (RSA )?PRIVATE KEY-----/
end
end
context 'with associations' do
let(:username) { "user-#{rand(1<<32)}" }
let(:command) { "knife opc org create #{org_name} #{org_name} --association #{username} -c #{superuser_rb} --disable-editing" }
before(:each) { knife "opc user create #{username} #{username} #{username} #{username}@foo.bar 'badger badger' -c #{superuser_rb} --disable-editing" }
after(:each) { knife "opc user remove #{username} -c #{superuser_rb} --disable-editing" }
it 'should succeed' do
should have_outcome :status => 0, :stdout => /-----BEGIN (RSA )?PRIVATE KEY-----/
end
end
end
end
end
end
| |
Switch cookie serializer to json | # Be sure to restart your server when you modify this file.
# Specify a serializer for the signed and encrypted cookie jars.
# Valid options are :json, :marshal, and :hybrid.
Rails.application.config.action_dispatch.cookies_serializer = :marshal
| # Be sure to restart your server when you modify this file.
# Specify a serializer for the signed and encrypted cookie jars.
# Valid options are :json, :marshal, and :hybrid.
Rails.application.config.action_dispatch.cookies_serializer = :hybrid
|
Increase Delayed::Worker.max_attempts to 2 in case a job gets killed during a deploy | Delayed::Worker.sleep_delay = 10
Delayed::Worker.max_attempts = 1
Delayed::Worker.max_run_time = 20.minutes
| Delayed::Worker.sleep_delay = 10
Delayed::Worker.max_attempts = 2
Delayed::Worker.max_run_time = 20.minutes
|
Make nil handling more explicit. | module ActiveRecord
module DatabaseValidations
module StringTruncator
extend ActiveSupport::Concern
module ClassMethods
def truncate_string(field)
column = self.columns_hash[field.to_s]
case column.type
when :string
lambda do
return if self.changes[field].nil?
limit = StringTruncator.mysql_textual_column_limit(column)
value = self[field].to_s
if value.length > limit
self[field] = value.slice(0, limit)
end
end
when :text
lambda do
return if self.changes[field].nil?
limit = StringTruncator.mysql_textual_column_limit(column)
value = self[field].to_s
value.encode!('utf-8') if value.encoding != Encoding::UTF_8
if value.bytesize > limit
self[field] = value.mb_chars.limit(limit).to_s
end
end
end
end
end
def self.mysql_textual_column_limit(column)
@mysql_textual_column_limits ||= {}
@mysql_textual_column_limits[column] ||= begin
raise ArgumentError, "Only UTF-8 textual columns are supported." unless column.text? && column.collation =~ /\Autf8_/
column.limit
end
end
end
end
end
| module ActiveRecord
module DatabaseValidations
module StringTruncator
extend ActiveSupport::Concern
module ClassMethods
def truncate_string(field)
column = self.columns_hash[field.to_s]
case column.type
when :string
lambda do
return unless self.attribute_changed?(field)
return if self[field].nil?
limit = StringTruncator.mysql_textual_column_limit(column)
value = self[field].to_s
if value.length > limit
self[field] = value.slice(0, limit)
end
end
when :text
lambda do
return unless self.attribute_changed?(field)
return if self[field].nil?
limit = StringTruncator.mysql_textual_column_limit(column)
value = self[field].to_s
value.encode!('utf-8') if value.encoding != Encoding::UTF_8
if value.bytesize > limit
self[field] = value.mb_chars.limit(limit).to_s
end
end
end
end
end
def self.mysql_textual_column_limit(column)
@mysql_textual_column_limits ||= {}
@mysql_textual_column_limits[column] ||= begin
raise ArgumentError, "Only UTF-8 textual columns are supported." unless column.text? && column.collation =~ /\Autf8_/
column.limit
end
end
end
end
end
|
Move out of JSONAPI module | module JSONAPI
class ActiveRecordOperationsProcessor < OperationsProcessor
private
def transaction
if @transactional
ActiveRecord::Base.transaction do
yield
end
else
yield
end
end
def rollback
raise ActiveRecord::Rollback if @transactional
end
def process_operation(operation)
operation.apply(@context)
rescue ActiveRecord::DeleteRestrictionError => e
record_locked_error = JSONAPI::Exceptions::RecordLocked.new(e.message)
return JSONAPI::ErrorsOperationResult.new(record_locked_error.errors[0].code, record_locked_error.errors)
rescue ActiveRecord::RecordNotFound
record_not_found = JSONAPI::Exceptions::RecordNotFound.new(operation.associated_key)
return JSONAPI::ErrorsOperationResult.new(record_not_found.errors[0].code, record_not_found.errors)
end
end
end | class ActiveRecordOperationsProcessor < JSONAPI::OperationsProcessor
private
def transaction
if @transactional
ActiveRecord::Base.transaction do
yield
end
else
yield
end
end
def rollback
raise ActiveRecord::Rollback if @transactional
end
def process_operation(operation)
operation.apply(@context)
rescue ActiveRecord::DeleteRestrictionError => e
record_locked_error = JSONAPI::Exceptions::RecordLocked.new(e.message)
return JSONAPI::ErrorsOperationResult.new(record_locked_error.errors[0].code, record_locked_error.errors)
rescue ActiveRecord::RecordNotFound
record_not_found = JSONAPI::Exceptions::RecordNotFound.new(operation.associated_key)
return JSONAPI::ErrorsOperationResult.new(record_not_found.errors[0].code, record_not_found.errors)
end
end
|
ADD dishwasher and trash wunderbar ID | # 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).
User.create({
name: 'Tobi',
})
User.create({
name: 'Christoph',
})
User.create({
name: 'Clemens',
})
User.create({
name: 'Roby',
})
Device.create({
name: 'Dishwasher',
reference: 'dw',
strategy: 'onetime',
})
| # 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).
User.create({
name: 'Tobi',
})
User.create({
name: 'Christoph',
})
User.create({
name: 'Clemens',
})
User.create({
name: 'Roby',
})
Device.create({
name: 'Dishwasher',
reference: '89287aad-db10-4303-ad01-5547c67eca96',
strategy: 'countdown',
})
Device.create({
name: 'Trash',
reference: '103156b3-1a78-42c2-a4af-1512721ded3d',
strategy: 'countdown',
})
|
Migrate test database before running specs | require 'simplecov'
SimpleCov.start do
add_filter '/spec'
end
RSpec.configure do |config|
config.filter_run :focus
config.run_all_when_everything_filtered = true
config.default_formatter = 'doc' unless config.files_to_run.one?
config.order = :random
Kernel.srand config.seed
config.expect_with :rspec do |expectations|
expectations.syntax = :expect
end
config.mock_with :rspec do |mocks|
mocks.syntax = :expect
mocks.verify_partial_doubles = true
end
config.alias_it_should_behave_like_to :has_behavior, 'has behavior:'
# config.profile_examples = 10
end
| require 'simplecov'
SimpleCov.start do
add_filter '/spec'
end
RSpec.configure do |config|
config.before(:suite) do
load Rails.root.join('db/schema.rb')
end
config.filter_run :focus
config.run_all_when_everything_filtered = true
config.default_formatter = 'doc' unless config.files_to_run.one?
config.order = :random
Kernel.srand config.seed
config.expect_with :rspec do |expectations|
expectations.syntax = :expect
end
config.mock_with :rspec do |mocks|
mocks.syntax = :expect
mocks.verify_partial_doubles = true
end
config.alias_it_should_behave_like_to :has_behavior, 'has behavior:'
# config.profile_examples = 10
end
|
Fix Github url in gemspec | require 'date'
Gem::Specification.new do |s|
s.name = %q{spork-rails}
s.version = "3.2.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Tim Harper"]
s.date = Date.today.to_s
s.description = %q{Plugin for Spork to support Rails.}
s.email = ["timcharper+spork@gmail.com"]
s.executables = []
s.extra_rdoc_files = [
"MIT-LICENSE",
"README.rdoc"
]
s.files = ["Gemfile", "README.rdoc", "MIT-LICENSE"] + Dir["lib/**/*"] + Dir["features/**/*"] + Dir["spec/**/*"]
s.homepage = %q{http://github.com/timcharper/spork-rails}
s.rdoc_options = ["--main", "README.rdoc"]
s.require_paths = ["lib"]
s.rubyforge_project = %q{spork}
s.rubygems_version = %q{1.3.5}
s.summary = %q{spork}
s.test_files = Dir["features/**/*"] + Dir["spec/**/*"]
s.add_dependency "spork", ">= 1.0rc0"
s.add_dependency "rails", ">= 3.0.0", "< 3.3.0"
end
| require 'date'
Gem::Specification.new do |s|
s.name = %q{spork-rails}
s.version = "3.2.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Tim Harper"]
s.date = Date.today.to_s
s.description = %q{Plugin for Spork to support Rails.}
s.email = ["timcharper+spork@gmail.com"]
s.executables = []
s.extra_rdoc_files = [
"MIT-LICENSE",
"README.rdoc"
]
s.files = ["Gemfile", "README.rdoc", "MIT-LICENSE"] + Dir["lib/**/*"] + Dir["features/**/*"] + Dir["spec/**/*"]
s.homepage = %q{http://github.com/sporkrb/spork-rails}
s.rdoc_options = ["--main", "README.rdoc"]
s.require_paths = ["lib"]
s.rubyforge_project = %q{spork}
s.rubygems_version = %q{1.3.5}
s.summary = %q{spork}
s.test_files = Dir["features/**/*"] + Dir["spec/**/*"]
s.add_dependency "spork", ">= 1.0rc0"
s.add_dependency "rails", ">= 3.0.0", "< 3.3.0"
end
|
Move (no decision taken) to tooltip | class CreateSrgHistories < ActiveRecord::Migration
def up
create_table :srg_histories do |t|
t.string :name
t.string :tooltip
t.timestamps
end
add_column :eu_decisions, :srg_history_id, :integer
add_foreign_key :eu_decisions, :srg_histories, name: 'eu_decisions_srg_history_id_fk'
execute(<<-SQL
INSERT INTO srg_histories(name, tooltip, created_at, updated_at)
VALUES ('In consultation', NULL, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP), ('Discussed at SRG (no decision taken)', NULL, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
SQL
)
end
def down
remove_foreign_key :eu_decisions, name: 'eu_decisions_srg_history_id_fk'
remove_column :eu_decisions, :srg_history_id
drop_table :srg_histories
end
end
| class CreateSrgHistories < ActiveRecord::Migration
def up
create_table :srg_histories do |t|
t.string :name
t.string :tooltip
t.timestamps
end
add_column :eu_decisions, :srg_history_id, :integer
add_foreign_key :eu_decisions, :srg_histories, name: 'eu_decisions_srg_history_id_fk'
execute(<<-SQL
INSERT INTO srg_histories(name, tooltip, created_at, updated_at)
VALUES ('In consultation', NULL, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP), ('Discussed at SRG', 'no decision taken', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
SQL
)
end
def down
remove_foreign_key :eu_decisions, name: 'eu_decisions_srg_history_id_fk'
remove_column :eu_decisions, :srg_history_id
drop_table :srg_histories
end
end
|
Fix bug in API handling of request body | require 'exceptions'
require 'v1/defaults'
require 'v1/envelopes'
require 'query_gremlin'
module API
module V1
# Gremlin endpoint
class Gremlin < Grape::API
helpers SharedHelpers
desc 'Executes a Gremlin query'
before do
authenticate!
end
post '/gremlin' do
response = QueryGremlin.call(env['rack.request.form_vars'])
status response.status
response.result
end
end
end
end
| require 'exceptions'
require 'v1/defaults'
require 'v1/envelopes'
require 'query_gremlin'
module API
module V1
# Gremlin endpoint
class Gremlin < Grape::API
helpers SharedHelpers
desc 'Executes a Gremlin query'
before do
authenticate!
end
post '/gremlin' do
payload = request.body.read
request.body.rewind
response = QueryGremlin.call(payload)
status response.status
response.result
end
end
end
end
|
Update for new FB app | Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, '101448083266993', 'e6fd636f8f479f62f9e62ce76d9bd8f9', {:scope => 'publish_stream,email', :client_options => {:ssl => {:ca_path => '/etc/ssl/certs'}}}
end
if Rails.env.development?
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
end
| Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, '216097298441765', 'cb27474f079a8ae3a07e592c7d8fb2e1', {:scope => 'publish_stream,email', :client_options => {:ssl => {:ca_path => '/etc/ssl/certs'}}}
end
if Rails.env.development?
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
end
|
Rearrange module definition for better code indexing | module Tint
class << self
attr_accessor :attribute_capitalization
def configuration
if block_given?
yield(Tint)
end
end
alias :config :configuration
end
@attribute_capitalization = :camel_case
end
require "tint/version"
require "tint/decorator"
| require "tint/version"
require "tint/decorator"
module Tint
class Decorator
end
class << self
attr_accessor :attribute_capitalization
def configuration
if block_given?
yield(Tint)
end
end
alias :config :configuration
end
@attribute_capitalization = :camel_case
end
|
Add migration to optimize user_details | class OptimizeUserDetails < ActiveRecord::Migration
def up
execute <<-SQL
DROP VIEW "1".user_details;
CREATE VIEW "1".user_details AS
SELECT u.id,
u.name,
u.address_city,
u.deactivated_at,
thumbnail_image(u.*) AS profile_img_thumbnail,
u.facebook_link,
u.full_text_index,
u.twitter AS twitter_username,
CASE
WHEN is_owner_or_admin(u.id) OR has_published_projects(u.*) THEN u.email
ELSE NULL::text
END AS email,
COALESCE(ut.total_contributed_projects, 0::bigint) AS total_contributed_projects,
COALESCE(ut.total_published_projects, 0::bigint) AS total_published_projects,
( SELECT json_agg(DISTINCT ul.link) AS json_agg
FROM user_links ul
WHERE ul.user_id = u.id) AS links
FROM users u
LEFT JOIN "1".user_totals ut ON ut.user_id = u.id;
CREATE INDEX users_full_text_index_ix ON users USING gin (full_text_index);
GRANT SELECT ON "1".user_details TO admin;
SQL
end
def down
execute <<-SQL
DROP VIEW "1".user_details;
CREATE VIEW "1".user_details AS
SELECT u.id,
u.name,
u.address_city,
u.deactivated_at,
thumbnail_image(u.*) AS profile_img_thumbnail,
u.facebook_link,
CASE
WHEN is_owner_or_admin(u.id) THEN u.full_text_index
ELSE NULL
END AS full_text_index,
u.twitter AS twitter_username,
CASE
WHEN is_owner_or_admin(u.id) OR has_published_projects(u.*) THEN u.email
ELSE NULL::text
END AS email,
COALESCE(ut.total_contributed_projects, 0::bigint) AS total_contributed_projects,
COALESCE(ut.total_published_projects, 0::bigint) AS total_published_projects,
( SELECT json_agg(DISTINCT ul.link) AS json_agg
FROM user_links ul
WHERE ul.user_id = u.id) AS links
FROM users u
LEFT JOIN "1".user_totals ut ON ut.user_id = u.id;
GRANT SELECT ON "1".user_details TO public;
SQL
end
end
| |
Fix to support https & http. | module Rbgct
require 'rbgct/chart_factory'
require 'rbgct/charts/chart'
require 'rbgct/charts/line_chart'
require 'rbgct/charts/pie_chart'
require 'rbgct/charts/bar_chart'
class NotImplementedError < StandardError; end
def self.include_javascript(packages=['corechart','table'])
<<-EOL
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
var rbgct = {
"graphs" : {},
"loadedPackages" : [],
"packages" : ['#{packages.join("\',\'")}'],
"drawGraphs" : (function(){
for(var i in rbgct.graphs){
rbgct.graphs[i]();
}
}),
"loadPackages" : (function(){
for(var i in rbgct.packages){
if( rbgct.loadedPackages.indexOf(rbgct.packages[i]) == -1 ){
google.load('visualization', '1', {packages: [rbgct.packages[i]]});
rbgct.loadedPackages.push(rbgct.packages[i]);
}
}
google.setOnLoadCallback(rbgct.drawGraphs)
})
};
rbgct.loadPackages();
</script>
EOL
end
def self.render(data, opts={})
raise ArgumentError.new('Dataset must respond to :each') unless data.respond_to?(:each)
chart = ChartFactory[opts[:type]].new(data,opts)
chart.render
end
end | module Rbgct
require 'rbgct/chart_factory'
require 'rbgct/charts/chart'
require 'rbgct/charts/line_chart'
require 'rbgct/charts/pie_chart'
require 'rbgct/charts/bar_chart'
class NotImplementedError < StandardError; end
def self.include_javascript(packages=['corechart','table'])
<<-EOL
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type="text/javascript">
var rbgct = {
"graphs" : {},
"loadedPackages" : [],
"packages" : ['#{packages.join("\',\'")}'],
"drawGraphs" : (function(){
for(var i in rbgct.graphs){
rbgct.graphs[i]();
}
}),
"loadPackages" : (function(){
for(var i in rbgct.packages){
if( rbgct.loadedPackages.indexOf(rbgct.packages[i]) == -1 ){
google.load('visualization', '1', {packages: [rbgct.packages[i]]});
rbgct.loadedPackages.push(rbgct.packages[i]);
}
}
google.setOnLoadCallback(rbgct.drawGraphs)
})
};
rbgct.loadPackages();
</script>
EOL
end
def self.render(data, opts={})
raise ArgumentError.new('Dataset must respond to :each') unless data.respond_to?(:each)
chart = ChartFactory[opts[:type]].new(data,opts)
chart.render
end
end |
Fix up remove user test case | require File.join(File.dirname(__FILE__), "../../toolbox/webrobot/lib/webrobot_core")
describe "Local Admin - Remove User", :local => true do
it "should remove the specified user" do
@selenium.login('admin', 'password', 'helpButton-btnIconEl')
expect { @selenium.title.should eql("ADTRAN Neo") }.to_not raise_error
sleep 3
@suite.click(:xpath, '//*[@id="removeUser_wiz"]')
@suite.click_text_from_combobox(:id, 'removeUserWiz_comboBox-inputEl', "Automated User")
sleep 5
@suite.click(:xpath, '//*[@id="removeUserWizard_next_btn"]')
@suite.click(:xpath, '//*[@id="removeUserWizard_save_btn"]')
sleep 5
@suite.click(:xpath, '//*[@id="removeUser_wiz"]')
@suite.click_text_from_combobox(:id, 'removeUserWiz_comboBox-inputEl', "Reassign Test")
sleep 5
@suite.click(:xpath, '//*[@id="removeUserWizard_next_btn"]')
@suite.click(:xpath, '//*[@id="removeUserWizard_save_btn"]')
sleep 5
end
end
| require File.join(File.dirname(__FILE__), "../../toolbox/webrobot/lib/webrobot_core")
describe "Local Admin - Remove User", :local => true do
it "should remove the specified user" do
@selenium.login('admin', 'password', 'helpButton-btnIconEl')
expect { @selenium.title.should eql("ADTRAN Neo") }.to_not raise_error
sleep 3
@selenium.click(:xpath, '//*[@id="removeUser_wiz"]')
@selenium.click_text_from_combobox(:id, 'removeUserWiz_comboBox-inputEl', "Automated User")
sleep 5
@selenium.click(:xpath, '//*[@id="removeUserWizard_next_btn"]')
@selenium.click(:xpath, '//*[@id="removeUserWizard_save_btn"]')
sleep 5
@selenium.click(:xpath, '//*[@id="removeUser_wiz"]')
@selenium.click_text_from_combobox(:id, 'removeUserWiz_comboBox-inputEl', "Reassign Test")
sleep 5
@selenium.click(:xpath, '//*[@id="removeUserWizard_next_btn"]')
@selenium.click(:xpath, '//*[@id="removeUserWizard_save_btn"]')
sleep 5
end
end
|
Fix date can be array | require 'fileutils'
require 'yaml'
require 'archivist/client'
module Archdown
# The Librarian takes a book and puts it in the library
class Librarian
attr_reader :library, :book
def initialize(library, book)
@library = library
@book = book
@failure = nil
end
def metadata
{
'title' => @book.title,
'author' => @book.creator,
'year' => @book.date.year,
'source' => "http://archive.org/details/#{@book.identifier}",
'status' => "OCR ONLY",
'archive_org_id' => @book.identifier,
}.tap do |meta|
meta['failure'] = @failure if @failure
end
end
def book_dir
@library.path_for_identifier(@book.identifier)
end
def book_filepath
File.join(book_dir, @book.identifier + '.md')
end
def make_book_dir
FileUtils.mkdir_p(book_dir)
end
def store_book(&block)
make_book_dir
begin
text = @book.download
rescue Archivist::Model::Document::UnsupportedFormat => e
@failure = e.to_s
rescue StandardError => e
@failure = e.to_s
end
yield metadata, self if block_given?
content = metadata.to_yaml
content += "---\n"
content += text if text
File.open(book_filepath, "w") do |file|
file.write content
end
end
end
end | require 'fileutils'
require 'yaml'
require 'archivist/client'
module Archdown
# The Librarian takes a book and puts it in the library
class Librarian
attr_reader :library, :book
def initialize(library, book)
@library = library
@book = book
@failure = nil
end
def metadata
year = @book.date.kind_of?(Array) ? @book.date.first : @book.date
{
'title' => @book.title,
'author' => @book.creator,
'year' => year,
'source' => "http://archive.org/details/#{@book.identifier}",
'status' => "OCR ONLY",
'archive_org_id' => @book.identifier,
}.tap do |meta|
meta['failure'] = @failure if @failure
end
end
def book_dir
@library.path_for_identifier(@book.identifier)
end
def book_filepath
File.join(book_dir, @book.identifier + '.md')
end
def make_book_dir
FileUtils.mkdir_p(book_dir)
end
def store_book(&block)
make_book_dir
begin
text = @book.download
rescue Archivist::Model::Document::UnsupportedFormat => e
@failure = e.to_s
rescue StandardError => e
@failure = e.to_s
end
yield metadata, self if block_given?
content = metadata.to_yaml
content += "---\n"
content += text if text
File.open(book_filepath, "w") do |file|
file.write content
end
end
end
end |
Add stal as a dependency | Gem::Specification.new do |s|
s.name = "ohm"
s.version = "2.1.0"
s.summary = %{Object-hash mapping library for Redis.}
s.description = %Q{Ohm is a library that allows to store an object in Redis, a persistent key-value database. It has very good performance.}
s.authors = ["Michel Martens", "Damian Janowski", "Cyril David"]
s.email = ["michel@soveran.com", "djanowski@dimaion.com", "me@cyrildavid.com"]
s.homepage = "http://soveran.github.io/ohm/"
s.license = "MIT"
s.files = `git ls-files`.split("\n")
s.rubyforge_project = "ohm"
s.add_dependency "redic"
s.add_dependency "nido"
s.add_dependency "msgpack"
s.add_development_dependency "cutest"
end
| Gem::Specification.new do |s|
s.name = "ohm"
s.version = "2.1.0"
s.summary = %{Object-hash mapping library for Redis.}
s.description = %Q{Ohm is a library that allows to store an object in Redis, a persistent key-value database. It has very good performance.}
s.authors = ["Michel Martens", "Damian Janowski", "Cyril David"]
s.email = ["michel@soveran.com", "djanowski@dimaion.com", "me@cyrildavid.com"]
s.homepage = "http://soveran.github.io/ohm/"
s.license = "MIT"
s.files = `git ls-files`.split("\n")
s.rubyforge_project = "ohm"
s.add_dependency "redic"
s.add_dependency "nido"
s.add_dependency "stal"
s.add_dependency "msgpack"
s.add_development_dependency "cutest"
end
|
Update Schema::DSL to work with the new constructor | require 'rom/sql/schema/inferrer'
require 'rom/sql/schema/associations_dsl'
module ROM
module SQL
class Schema < ROM::Schema
class DSL < ROM::Schema::DSL
attr_reader :associations_dsl
def associations(&block)
@associations_dsl = AssociationsDSL.new(name, &block)
end
def call
SQL::Schema.new(name, attributes, opts)
end
def opts
opts = { inferrer: inferrer }
if associations_dsl
{ **opts, associations: associations_dsl.call }
else
opts
end
end
end
end
end
end
| require 'rom/sql/schema/inferrer'
require 'rom/sql/schema/associations_dsl'
module ROM
module SQL
class Schema < ROM::Schema
class DSL < ROM::Schema::DSL
attr_reader :associations_dsl
def associations(&block)
@associations_dsl = AssociationsDSL.new(name, &block)
end
def call
SQL::Schema.new(name, opts.merge(attributes: attributes))
end
def opts
opts = { inferrer: inferrer }
if associations_dsl
{ **opts, associations: associations_dsl.call }
else
opts
end
end
end
end
end
end
|
Update test User class to have the correct superclass | unless ENV['TRAVIS']
require 'simplecov'
require 'simplecov-rcov'
SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter
SimpleCov.start
else
require 'coveralls'
Coveralls.wear!
end
ENV["RAILS_ENV"] ||= "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'authlogic'
require 'authlogic/test_case'
class User
def nyuidn
user_attributes[:nyuidn]
end
def error; end
def uid
username
end
end
class ActiveSupport::TestCase
fixtures :all
def set_dummy_pds_user(user_session)
user_session.instance_variable_set("@pds_user".to_sym, users(:real_user))
end
end
# VCR is used to 'record' HTTP interactions with
# third party services used in tests, and play em
# back. Useful for efficiency, also useful for
# testing code against API's that not everyone
# has access to -- the responses can be cached
# and re-used.
require 'vcr'
require 'webmock'
# To allow us to do real HTTP requests in a VCR.turned_off, we
# have to tell webmock to let us.
WebMock.allow_net_connect!
VCR.configure do |c|
c.cassette_library_dir = 'test/vcr_cassettes'
# webmock needed for HTTPClient testing
c.hook_into :webmock
end
| unless ENV['TRAVIS']
require 'simplecov'
require 'simplecov-rcov'
SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter
SimpleCov.start
else
require 'coveralls'
Coveralls.wear!
end
ENV["RAILS_ENV"] ||= "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'authlogic'
require 'authlogic/test_case'
class User < ActiveRecord::Base
def nyuidn
user_attributes[:nyuidn]
end
def error; end
def uid
username
end
end
class ActiveSupport::TestCase
fixtures :all
def set_dummy_pds_user(user_session)
user_session.instance_variable_set("@pds_user".to_sym, users(:real_user))
end
end
# VCR is used to 'record' HTTP interactions with
# third party services used in tests, and play em
# back. Useful for efficiency, also useful for
# testing code against API's that not everyone
# has access to -- the responses can be cached
# and re-used.
require 'vcr'
require 'webmock'
# To allow us to do real HTTP requests in a VCR.turned_off, we
# have to tell webmock to let us.
WebMock.allow_net_connect!
VCR.configure do |c|
c.cassette_library_dir = 'test/vcr_cassettes'
# webmock needed for HTTPClient testing
c.hook_into :webmock
end
|
Fix line wrap to be consistent with other gems | # encoding: utf-8
# Be sure to restart your server when you modify this file.
TestApp::Application.config.session_store(
:cookie_store, :key => '_test_app_session')
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rails generate session_migration")
# TestApp::Application.config.session_store :active_record_store
| # encoding: utf-8
# Be sure to restart your server when you modify this file.
TestApp::Application.config.session_store \
:cookie_store, :key => '_test_app_session'
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rails generate session_migration")
# TestApp::Application.config.session_store :active_record_store
|
Fix style complains by rubocop | # encoding: UTF-8
require 'spec_helper'
describe Morpher::Evaluator::Transformer::Map do
let(:object) { described_class.new(operand) }
context '#intransitive' do
let(:operand) { Morpher.evaluator(s(:attribute, :length)) }
include_examples 'transforming evaluator'
include_examples 'intransitive evaluator'
include_examples 'no invalid input'
let(:valid_input) { [ 'foo' ] }
let(:expected_output) { [ 3 ] }
end
context '#transitive' do
let(:operand) { Morpher.evaluator(s(:guard, s(:primitive, String))) }
include_examples 'transforming evaluator'
include_examples 'transitive evaluator'
include_examples 'no invalid input'
let(:valid_input) { [ 'foo' ] }
let(:invalid_input) { [ nil ] }
let(:expected_output) { [ 'foo' ] }
end
end
| # encoding: UTF-8
require 'spec_helper'
describe Morpher::Evaluator::Transformer::Map do
let(:object) { described_class.new(operand) }
context '#intransitive' do
let(:operand) { Morpher.evaluator(s(:attribute, :length)) }
include_examples 'transforming evaluator'
include_examples 'intransitive evaluator'
include_examples 'no invalid input'
let(:valid_input) { ['foo'] }
let(:expected_output) { [3] }
end
context '#transitive' do
let(:operand) { Morpher.evaluator(s(:guard, s(:primitive, String))) }
include_examples 'transforming evaluator'
include_examples 'transitive evaluator'
include_examples 'no invalid input'
let(:valid_input) { ['foo'] }
let(:invalid_input) { [nil] }
let(:expected_output) { ['foo'] }
end
end
|
Add mongo port in raw because build fail on travis | require 'mongo'
include Mongo
class Revuelog
attr_reader :time, :nick, :message
def initialize(time, nick, message)
@time = time
@nick = nick
@message = message
end
def to_hash
{"time" => @time, "nick" => @nick, "message" => @message}
end
end
class Revuedb
Host = ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'
Port = ENV['MONGO_RUBY_DRIVER_PORT'] || MongoClient::DEFAULT_PORT
Collname = ENV['MONGO_RUBY_DRIVER_COLL'] || 'revue-coll-spec'
def initialize(host=Host, port=Port, collname=Collname)
@coll = MongoClient.new(host,port).db('revue-db').collection(collname)
end
def find(key, value)
@coll.find({key => value}, :fields => [key]).to_a
end
def distinct(key)
@coll.distinct(key).to_a
end
def dbinsert(revuehash)
@coll.insert(revuehash)
end
def dbclean
@coll.drop
end
end
| require 'mongo'
include Mongo
class Revuelog
attr_reader :time, :nick, :message
def initialize(time, nick, message)
@time = time
@nick = nick
@message = message
end
def to_hash
{"time" => @time, "nick" => @nick, "message" => @message}
end
end
class Revuedb
Host = ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'
Port = ENV['MONGO_RUBY_DRIVER_PORT'] || '27017'
Collname = ENV['MONGO_RUBY_DRIVER_COLL'] || 'revue-coll-spec'
def initialize(host=Host, port=Port, collname=Collname)
@coll = MongoClient.new(host,port).db('revue-db').collection(collname)
end
def find(key, value)
@coll.find({key => value}, :fields => [key]).to_a
end
def distinct(key)
@coll.distinct(key).to_a
end
def dbinsert(revuehash)
@coll.insert(revuehash)
end
def dbclean
@coll.drop
end
end
|
Fix improper indenting as per Rubocop check | module Entity
class Doc < Base
expose :id
expose :title
expose :body
expose :keywords
expose :title_tag
expose :meta_description
expose :category_id
expose :user_id
expose :active
expose :rank
expose :version
expose :front_page
expose :created_at
expose :updated_at
expose :topics_count
expose :allow_comments
end
end
| module Entity
class Doc < Base
expose :id
expose :title
expose :body
expose :keywords
expose :title_tag
expose :meta_description
expose :category_id
expose :user_id
expose :active
expose :rank
expose :version
expose :front_page
expose :created_at
expose :updated_at
expose :topics_count
expose :allow_comments
end
end
|
Whitelist providers to avoid session data being tampered with | require './lib/actions/oauth_signup_action'
#
# Handle signup or signin
# from various oauth providers
#
# Heavily overlaps with Authentications controller
#
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
create
end
def failure
flash[:alert] = "Authentication failed."
redirect_to request.env['omniauth.origin'] || "/"
end
private
def create
auth = request.env['omniauth.auth']
action = Growstuff::OauthSignupAction.new
@authentication = nil
if auth
member = action.find_or_create_from_authorization(auth)
@authentication = action.establish_authentication(auth, member)
unless action.member_created?
sign_in_and_redirect member, event: :authentication #this will throw if @user is not activated
set_flash_message(:notice, :success, kind: auth['provider']) if is_navigational_format?
else
session["devise.#{auth['provider']}_data"] = request.env["omniauth.auth"]
sign_in member
redirect_to finish_signup_url(member)
end
else
redirect_to request.env['omniauth.origin'] || edit_member_registration_path
end
end
def after_sign_in_path_for(resource)
if resource.tos_agreement
super resource
else
finish_signup_path(resource)
end
end
end | require './lib/actions/oauth_signup_action'
#
# Handle signup or signin
# from various oauth providers
#
# Heavily overlaps with Authentications controller
#
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
create
end
def failure
flash[:alert] = "Authentication failed."
redirect_to request.env['omniauth.origin'] || "/"
end
private
def create
auth = request.env['omniauth.auth']
action = Growstuff::OauthSignupAction.new
@authentication = nil
if auth
member = action.find_or_create_from_authorization(auth)
@authentication = action.establish_authentication(auth, member)
unless action.member_created?
sign_in_and_redirect member, event: :authentication #this will throw if @user is not activated
set_flash_message(:notice, :success, kind: auth['provider']) if is_navigational_format?
else
raise "Invalid provider" unless ['facebook', 'twitter', 'flickr'].index(auth['provider'].to_s)
session["devise.#{auth['provider']}_data"] = request.env["omniauth.auth"]
sign_in member
redirect_to finish_signup_url(member)
end
else
redirect_to request.env['omniauth.origin'] || edit_member_registration_path
end
end
def after_sign_in_path_for(resource)
if resource.tos_agreement
super resource
else
finish_signup_path(resource)
end
end
end |
Include build task of chrome extension in top-level build task | PROJECT_ID = 'work2d-162714'.freeze
DOMAIN = 'code2d.net'.freeze
REGION = 'us-east-1'.freeze
TERRAFORM_VARS = "-var domain=#{DOMAIN} -var region=#{REGION}".freeze
task :test do
%w[app functions].each do |dir|
cd dir do
sh 'rake test'
end
end
end
task :build do
cd 'app' do
sh 'rake build'
end
cd 'functions' do
sh 'rake build'
end
end
task deploy: :build do
sh 'terraform init'
sh 'terraform get'
sh "terraform apply #{TERRAFORM_VARS}"
sh 'firebase deploy'
sh "gsutil cors set storage_cors.json gs://#{PROJECT_ID}.appspot.com"
name_servers = `terraform output name_servers`
.split(/[,\s]+/)
.map { |s| 'Name=' + s }
.join ' '
sh %W[
aws route53domains update-domain-nameservers
--domain #{DOMAIN}
--nameservers #{name_servers}
].join ' '
end
task :withdraw do
sh "terraform destroy #{TERRAFORM_VARS}"
end
task :clean do
cd 'app' do
sh 'rake clean'
end
cd 'functions' do
sh 'rake clean'
end
end
| PROJECT_ID = 'work2d-162714'.freeze
DOMAIN = 'code2d.net'.freeze
REGION = 'us-east-1'.freeze
TERRAFORM_VARS = "-var domain=#{DOMAIN} -var region=#{REGION}".freeze
task :test do
%w[app functions].each do |dir|
cd dir do
sh 'rake test'
end
end
end
task :build do
%w[app functions chrome-extension].each do |dir|
cd dir do
sh 'rake build'
end
end
end
task deploy: :build do
sh 'terraform init'
sh 'terraform get'
sh "terraform apply #{TERRAFORM_VARS}"
sh 'firebase deploy'
sh "gsutil cors set storage_cors.json gs://#{PROJECT_ID}.appspot.com"
name_servers = `terraform output name_servers`
.split(/[,\s]+/)
.map { |s| 'Name=' + s }
.join ' '
sh %W[
aws route53domains update-domain-nameservers
--domain #{DOMAIN}
--nameservers #{name_servers}
].join ' '
end
task :withdraw do
sh "terraform destroy #{TERRAFORM_VARS}"
end
task :clean do
cd 'app' do
sh 'rake clean'
end
cd 'functions' do
sh 'rake clean'
end
end
|
Clarify player ranking order in endpoint description | module API
module V1
module Entities
class Ranking < Grape::Entity
expose :player, using: Entities::Player
expose :rating
end
end
class Rankings < Grape::API
resource :rankings do
desc "Returns an ordered list of player rankings"
get do
rankings = Player.all.map { |player|
{
player: player,
rating: player.rating
}
}.sort_by { |ranking| ranking[:rating] }.reverse
present rankings, with: Entities::Ranking
end
end
end
end
end
| module API
module V1
module Entities
class Ranking < Grape::Entity
expose :player, using: Entities::Player
expose :rating
end
end
class Rankings < Grape::API
resource :rankings do
desc "Returns an list of player rankings in descending rating order"
get do
rankings = Player.all.map { |player|
{
player: player,
rating: player.rating
}
}.sort_by { |ranking| ranking[:rating] }.reverse
present rankings, with: Entities::Ranking
end
end
end
end
end
|
Remove aws-sdk from the gemspec file | require_relative 'lib/redshift_connector/version'
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'redshift-connector'
s.version = RedshiftConnector::VERSION
s.summary = 'Redshift bulk data connector'
s.description = 'redshift-connector is a bulk data connector for Rails (ActiveRecord).'
s.license = 'MIT'
s.author = ['Minero Aoki']
s.email = 'aamine@loveruby.net'
s.homepage = 'https://github.com/bricolages/redshift-connector'
s.files = Dir.glob(['README.md', 'lib/**/*.rb', 'test/**/*'])
s.require_path = 'lib'
s.required_ruby_version = '>= 2.1.0'
s.add_dependency 'redshift-connector-data_file', '>= 7.0.0'
s.add_dependency 'activerecord'
s.add_dependency 'activerecord-redshift'
s.add_dependency 'pg', '~> 0.18.0'
s.add_dependency 'activerecord-import'
s.add_dependency 'aws-sdk', '~> 2.0'
s.add_development_dependency 'test-unit'
s.add_development_dependency 'pry'
s.add_development_dependency 'rake'
end
| require_relative 'lib/redshift_connector/version'
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'redshift-connector'
s.version = RedshiftConnector::VERSION
s.summary = 'Redshift bulk data connector'
s.description = 'redshift-connector is a bulk data connector for Rails (ActiveRecord).'
s.license = 'MIT'
s.author = ['Minero Aoki']
s.email = 'aamine@loveruby.net'
s.homepage = 'https://github.com/bricolages/redshift-connector'
s.files = Dir.glob(['README.md', 'lib/**/*.rb', 'test/**/*'])
s.require_path = 'lib'
s.required_ruby_version = '>= 2.1.0'
s.add_dependency 'redshift-connector-data_file', '>= 7.0.0'
s.add_dependency 'activerecord'
s.add_dependency 'activerecord-redshift'
s.add_dependency 'pg', '~> 0.18.0'
s.add_dependency 'activerecord-import'
s.add_development_dependency 'test-unit'
s.add_development_dependency 'pry'
s.add_development_dependency 'rake'
end
|
Upgrade Plex Home Theater to v1.2.1.314 and add 64bits version | class PlexHomeTheater < Cask
version '1.0.9.180'
sha256 'f7c51b212febafbca77e0af193819c7d7035a38600d65550db1362edadee31b7'
url 'http://downloads.plexapp.com/plex-home-theater/1.0.9.180-bde1e61d/PlexHomeTheater-1.0.9.180-bde1e61d-macosx-i386.zip'
homepage 'https://plex.tv'
link 'Plex Home Theater.app'
end
| class PlexHomeTheater < Cask
version '1.2.1.314'
if MacOS.prefer_64_bit?
sha256 '0e243ca7112cccd11f75bf799ff21a69413dc1eca6652f934ed456ac54fab5ae'
url 'http://downloads.plexapp.com/plex-home-theater/1.2.1.314-7cb0133e/PlexHomeTheater-1.2.1.314-7cb0133e-macosx-x86_64.zip'
else
sha256 '87954578b4aa1ec93876115967b0da61d6fa47f3f1125743a55f688366d56860'
url 'http://downloads.plexapp.com/plex-home-theater/1.2.1.314-7cb0133e/PlexHomeTheater-1.2.1.314-7cb0133e-macosx-i386.zip'
end
homepage 'https://plex.tv'
link 'Plex Home Theater.app'
end
|
Allow marshalled legacy objects to work | # This file and class exist solely to allow legacy marshalled tokens in URLs
# (sent in emails) to be loaded. These contain marshalled Deferred::Visitor
# objects, and Marshal.load raises an exception if the class does not exist.
#
# Do not add any new code here. Do not use this class anywhere.
# When this file is no longer needed, remove it.
#
module Deferred
class Visitor < ::Visitor
end
end
| |
Fix mailer settings using new format | class PantographMailer < ActionMailer::Base
default from: Settings.admin.email
def tweet_failed(message)
@message = message
mail(
to: Settings.monitoring.email,
subject: message,
host: Settings.host
)
end
end
| class PantographMailer < ActionMailer::Base
default from: Constant.admin.email
def tweet_failed(message)
@message = message
mail(
to: Setting['advanced.monitoring_email'],
subject: message,
host: Constant.host
)
end
end
|
Add current group subdomain shared context. | shared_context "with subdomain", use: :subdomain do
def set_subdomain(subdomain)
@original_default_host = Capybara.default_host
Capybara.default_host = "http://#{subdomain}.example.com"
end
def unset_subdomain
Capybara.default_host = @original_default_host
end
end
| shared_context "with subdomain", use: :subdomain do
def set_subdomain(subdomain)
@original_default_host = Capybara.default_host
Capybara.default_host = "http://#{subdomain}.example.com"
end
def unset_subdomain
Capybara.default_host = @original_default_host
end
end
shared_context "with current group subdomain", use: :current_subdomain do
include_context "with subdomain"
before { set_subdomain(current_group.short_name) }
after { unset_subdomain }
end
|
Refactor to make the code simpler. | require_relative 'mayusculas'
module Identificamex
module Nombre
# Clase base para normalizar las cadenas de nombres y apellidos. La clase
# se encarga de convertir a mayúsculas las cadenas y recorre los nombres para
# descartar los nombres ignorados.
#
# Los nombres ignorados deben ser provistos por las clases que hereden.
class NormalizadorCadena
include Mayusculas
def initialize(nombre)
@nombre = mayusculas(nombre)
end
def normalizar
nombre_aceptado || primer_nombre
end
private
def nombre_aceptado
nombres.find{|nombre| no_ignorado?(nombre) } if nombres.count > 1
end
def no_ignorado?(nombre)
!nombres_ignorados.member?(nombre)
end
def primer_nombre
nombres.first
end
def nombres_ignorados
raise NotImplementedError
end
def nombres
@nombres ||= @nombre.split
end
end
end
end
| require_relative 'mayusculas'
module Identificamex
module Nombre
# Clase base para normalizar las cadenas de nombres y apellidos. La clase
# se encarga de convertir a mayúsculas las cadenas y recorre los nombres para
# descartar los nombres ignorados.
#
# Los nombres ignorados deben ser provistos por las clases que hereden.
class NormalizadorCadena
include Mayusculas
def initialize(nombre)
@nombre = mayusculas(nombre)
end
def normalizar
nombre_aceptado || primer_nombre
end
private
def nombre_aceptado
(nombres - nombres_ignorados).first
end
def primer_nombre
nombres.first
end
def nombres_ignorados
raise NotImplementedError
end
def nombres
@nombres ||= @nombre.split
end
end
end
end
|
Add automation engine service model for SwiftManager | module MiqAeMethodService
class MiqAeServiceManageIQ_Providers_StorageManager_SwiftManager < MiqAeServiceManageIQ_Providers_StorageManager
expose :parent_manager, :association => true
expose :cloud_object_store_containers, :association => true
expose :cloud_object_store_objects, :association => true
end
end
| |
Fix GP test crash by changing table names | module Rake
module TableTask
module TableCreation
OLDTABLE = "old"
NEWTABLE = "new"
def create_timed_tables(old_table, *new_tables)
return if (Table.exist?(old_table) &&
new_tables.all? { |new_table|
Table.exist?(new_table) && Table.mtime(new_table) > Table.mtime(old_table)
})
now = Time.now
create_table(old_table)
sleep(1.0)
new_tables.each do |new_table|
create_table(new_table)
end
end
def create_table(name)
Table.new name, nil, '(var1 integer, var2 integer)' unless Table.exist?(name)
Table.mtime(name)
end
def drop_table(name)
Table.drop(name) rescue nil
end
end
end
end
| module Rake
module TableTask
module TableCreation
OLDTABLE = "old_table"
NEWTABLE = "new_table"
def create_timed_tables(old_table, *new_tables)
return if (Table.exist?(old_table) &&
new_tables.all? { |new_table|
Table.exist?(new_table) && Table.mtime(new_table) > Table.mtime(old_table)
})
now = Time.now
create_table(old_table)
sleep(1.0)
new_tables.each do |new_table|
create_table(new_table)
end
end
def create_table(name)
Table.new name, nil, '(var1 integer, var2 integer)' unless Table.exist?(name)
Table.mtime(name)
end
def drop_table(name)
Table.drop(name) rescue nil
end
end
end
end
|
Kill mutation in Relation.build (:heart: mutant) | # encoding: utf-8
require 'spec_helper'
describe Relation, '.build' do
subject { described_class.build(relation, mapper) }
fake(:relation) { Axiom::Relation }
fake(:mapped_relation) { Axiom::Relation }
fake(:mapper) { Mapper }
before do
stub(mapper).call(relation) { mapped_relation }
stub(mapped_relation).optimize { mapped_relation }
end
its(:relation) { should be(mapped_relation) }
its(:mapper) { should be(mapper) }
end
| # encoding: utf-8
require 'spec_helper'
describe Relation, '.build' do
subject { described_class.build(relation, mapper) }
fake(:relation) { Axiom::Relation }
fake(:mapped) { Axiom::Relation }
fake(:optimized) { Axiom::Relation }
fake(:mapper) { Mapper }
before do
stub(mapper).call(relation) { mapped }
stub(mapped).optimize { optimized }
end
its(:relation) { should be(optimized) }
its(:mapper) { should be(mapper) }
end
|
Fix spec for uncommunicative-method-name smell. | require 'spec_helper'
require 'reek/smells/uncommunicative_method_name'
require 'reek/smells/smell_detector_shared'
require 'reek/core/code_parser'
require 'reek/core/sniffer'
include Reek
include Reek::Smells
describe UncommunicativeMethodName do
before :each do
@source_name = 'wallamalloo'
@detector = UncommunicativeMethodName.new(@source_name)
end
it_should_behave_like 'SmellDetector'
['help', '+', '-', '/', '*'].each do |method_name|
it "accepts the method name '#{method_name}'" do
"def #{method_name}(fred) basics(17) end".should_not smell_of(UncommunicativeMethodName)
end
end
['x', 'x2', 'method2'].each do |method_name|
context 'with a bad name' do
before :each do
src = 'def x() end'
ctx = CodeContext.new(nil, src.to_reek_source.syntax_tree)
@smells = @detector.examine_context(ctx)
@warning = @smells[0]
end
it_should_behave_like 'common fields set correctly'
it 'reports the correct values' do
@smells[0].smell[UncommunicativeMethodName::METHOD_NAME_KEY].should == 'x'
@smells[0].lines.should == [1]
@smells[0].context.should == 'x'
end
end
end
end
| require 'spec_helper'
require 'reek/smells/uncommunicative_method_name'
require 'reek/smells/smell_detector_shared'
require 'reek/core/code_parser'
require 'reek/core/sniffer'
include Reek
include Reek::Smells
describe UncommunicativeMethodName do
before :each do
@source_name = 'wallamalloo'
@detector = UncommunicativeMethodName.new(@source_name)
end
it_should_behave_like 'SmellDetector'
['help', '+', '-', '/', '*'].each do |method_name|
it "accepts the method name '#{method_name}'" do
"def #{method_name}(fred) basics(17) end".should_not smell_of(UncommunicativeMethodName)
end
end
['x', 'x2', 'method2'].each do |method_name|
context 'with a bad name' do
before do
src = "def #{method_name}; end"
ctx = CodeContext.new(nil, src.to_reek_source.syntax_tree)
smells = @detector.examine_context(ctx)
@warning = smells[0]
end
it_should_behave_like 'common fields set correctly'
it 'reports the correct values' do
@warning.smell[UncommunicativeMethodName::METHOD_NAME_KEY].should == method_name
@warning.lines.should == [1]
@warning.context.should == method_name
end
end
end
end
|
Add the `<app_root>/test` dir to the `$LOAD_PATH` as a string: | require "rails/command"
require "rails/test_unit/minitest_plugin"
module Rails
module Command
class TestCommand < Base # :nodoc:
no_commands do
def help
perform # Hand over help printing to minitest.
end
end
def perform(*)
$LOAD_PATH << Rails::Command.root.join("test")
Minitest.run_via = :rails
require "active_support/testing/autorun"
end
end
end
end
| require "rails/command"
require "rails/test_unit/minitest_plugin"
module Rails
module Command
class TestCommand < Base # :nodoc:
no_commands do
def help
perform # Hand over help printing to minitest.
end
end
def perform(*)
$LOAD_PATH << Rails::Command.root.join("test").to_s
Minitest.run_via = :rails
require "active_support/testing/autorun"
end
end
end
end
|
Put extra payload in the args instead | require 'travis/addons/handlers/base'
require 'travis/addons/handlers/task'
require 'travis/addons/handlers/github_status'
module Travis
module Addons
module Handlers
class GithubCheckStatus < GithubStatus
include Handlers::Task
EVENTS = /build:(created|started|finished|canceled|restarted)/
def handle?
if gh_apps_enabled?
installation = Installation.where(owner: repository.owner, removed_by_id: nil).first
if installation
payload.merge!({installation: installation.id})
true
elsif tokens.any?
Addons.logger.error "Falling back to user tokens"
payload.merge!({tokens: tokens})
true
else
false
end
else
Addons.logger.error "No GitHub OAuth tokens found for #{object.repository.slug}" unless tokens.any?
tokens.any?
end
end
def handle
run_task(:github_check_status, payload, {})
end
def gh_apps_enabled?
!! repository.managed_by_installation_at
end
class Instrument < Addons::Instrument
def notify_completed
publish
end
end
Instrument.attach_to(self)
end
end
end
end
| require 'travis/addons/handlers/base'
require 'travis/addons/handlers/task'
require 'travis/addons/handlers/github_status'
module Travis
module Addons
module Handlers
class GithubCheckStatus < GithubStatus
include Handlers::Task
EVENTS = /build:(created|started|finished|canceled|restarted)/
def handle?
if gh_apps_enabled?
installation = Installation.where(owner: repository.owner, removed_by_id: nil).first
if installation
@args = {installation: installation.id}
true
elsif tokens.any?
Addons.logger.error "Falling back to user tokens"
@args = {tokens: tokens}
true
else
false
end
else
Addons.logger.error "No GitHub OAuth tokens found for #{object.repository.slug}" unless tokens.any?
tokens.any?
end
end
def handle
run_task(:github_check_status, payload, @args)
end
def gh_apps_enabled?
!! repository.managed_by_installation_at
end
class Instrument < Addons::Instrument
def notify_completed
publish
end
end
Instrument.attach_to(self)
end
end
end
end
|
Add test for `edit` command | # frozen_string_literal: true
require "./test/helper"
clean_describe "edit" do
subject do
stdout, stderr, status = Open3.capture3(
"EDITOR=cat bundle exec bin/friends --colorless --filename #{filename} edit"
)
{
stdout: stdout,
stderr: stderr,
status: status.exitstatus
}
end
let(:content) { CONTENT }
it 'opens the file in the "editor"' do
# Because of the way that the edit command uses `Kernel.exec` to replace itself,
# our `Open3.capture3` call doesn't return STDOUT from before the `Kernel.exec`
# call, meaning we can't test output of the status message we print out, and
# our test here can check that STDOUT is equivalent to the `Kernel.exec` command's
# output, even though visually that's not what happens.
stdout_only content
end
end
| |
Add method show to schools controller for each school | class SchoolsController < ApplicationController
def search
@location = Location.find_by(loc_code: params["loc_code"])
if @location.loc_code == "nyc"
@results = School.in_nyc_location.search_nyc_schools(params["search"])
render 'search1.js.erb'
else
@results = School.in_ros_location.search_ros_schools(params["search"])
render 'search2.js.erb'
end
end
# def random40
# @json = Array.new
# 20.times do
# offset = rand(School.count)
# rand_record = School.offset(offset).first
# @json << {
# school: rand_record.school,
# total_enrollment: rand_record.total_enrollment,
# amount_owed: rand_record.amount_owed
# }
# end
# respond_to do |format|
# format.html
# format.json { render json: @json }
# end
# end
end
| class SchoolsController < ApplicationController
def search
@location = Location.find_by(loc_code: params["loc_code"])
if @location.loc_code == "nyc"
@results = School.in_nyc_location.search_nyc_schools(params["search"])
render 'search1.js.erb'
else
@results = School.in_ros_location.search_ros_schools(params["search"])
render 'search2.js.erb'
end
end
def show
@school = School.find(params["school_id"])
end
# def random40
# @json = Array.new
# 20.times do
# offset = rand(School.count)
# rand_record = School.offset(offset).first
# @json << {
# school: rand_record.school,
# total_enrollment: rand_record.total_enrollment,
# amount_owed: rand_record.amount_owed
# }
# end
# respond_to do |format|
# format.html
# format.json { render json: @json }
# end
# end
end
|
Fix one more schema discrepancy | class Types::TicketTypeType < Types::BaseObject
field :id, Integer, null: false
field :name, String, null: true
field :publicly_available, Boolean, null: false
field :counts_towards_convention_maximum, Boolean, null: false
field :allows_event_signups, Boolean, null: false
field :maximum_event_provided_tickets, Integer, null: false do
argument :event_id, Integer, required: false
end
def maximum_event_provided_tickets(**args)
if args[:event_id]
object.maximum_event_provided_tickets_for_event_id(args[:event_id])
else
object.maximum_event_provided_tickets
end
end
field :description, String, null: true
field :pricing_schedule, Types::ScheduledMoneyValueType, null: true
field :convention, Types::ConventionType, null: false
def convention
RecordLoader.for(Convention).load(object.convention_id)
end
end
| class Types::TicketTypeType < Types::BaseObject
field :id, Integer, null: false
field :name, String, null: true
field :publicly_available, Boolean, null: false
field :counts_towards_convention_maximum, Boolean, null: false
field :allows_event_signups, Boolean, null: false
field :maximum_event_provided_tickets, Integer, null: false do
argument :event_id, Integer, required: false, camelize: false
end
def maximum_event_provided_tickets(**args)
if args[:event_id]
object.maximum_event_provided_tickets_for_event_id(args[:event_id])
else
object.maximum_event_provided_tickets
end
end
field :description, String, null: true
field :pricing_schedule, Types::ScheduledMoneyValueType, null: true
field :convention, Types::ConventionType, null: false
def convention
RecordLoader.for(Convention).load(object.convention_id)
end
end
|
Add watchOS target to podspec | Pod::Spec.new do |spec|
spec.name = 'Argo'
spec.version = '2.0.0'
spec.summary = 'Functional JSON parsing library for Swift.'
spec.homepage = 'https://github.com/thoughtbot/Argo'
spec.license = { :type => 'MIT', :file => 'LICENSE' }
spec.author = {
'Gordon Fontenot' => 'gordon@thoughtbot.com',
'Tony DiPasquale' => 'tony@thoughtbot.com',
'thoughtbot' => nil,
}
spec.social_media_url = 'http://twitter.com/thoughtbot'
spec.source = { :git => 'https://github.com/thoughtbot/Argo.git', :tag => "v#{spec.version}", :submodules => true }
spec.source_files = 'Argo/**/*.{h,swift}', 'Carthage/Checkouts/Runes/Source/Runes.swift'
spec.requires_arc = true
spec.ios.deployment_target = '8.0'
spec.osx.deployment_target = '10.9'
end
| Pod::Spec.new do |spec|
spec.name = 'Argo'
spec.version = '2.0.0'
spec.summary = 'Functional JSON parsing library for Swift.'
spec.homepage = 'https://github.com/thoughtbot/Argo'
spec.license = { :type => 'MIT', :file => 'LICENSE' }
spec.author = {
'Gordon Fontenot' => 'gordon@thoughtbot.com',
'Tony DiPasquale' => 'tony@thoughtbot.com',
'thoughtbot' => nil,
}
spec.social_media_url = 'http://twitter.com/thoughtbot'
spec.source = { :git => 'https://github.com/thoughtbot/Argo.git', :tag => "v#{spec.version}", :submodules => true }
spec.source_files = 'Argo/**/*.{h,swift}', 'Carthage/Checkouts/Runes/Source/Runes.swift'
spec.requires_arc = true
spec.ios.deployment_target = '8.0'
spec.osx.deployment_target = '10.9'
spec.watchos.deployment_target = '2.0'
end
|
Remove set_lang params and auto translating after setting | module ChineseT2s
module Middleware
class TranslationT2s
def initialize(app)
@app = app
end
def call(env)
set_lang = env['QUERY_STRING'][/\bset_lang=(\w+)/, 1]
unless set_lang.nil?
env['rack.session'].delete('chinese_t2s_lang') if set_lang == 'tw'
env['rack.session']['chinese_t2s_lang'] = 'cn' if set_lang == 'cn'
end
status, headers, bodies = @app.call(env)
if status == 200 && bodies.present?
params = env['rack.request.query_hash'] || {}
if (env['rack.session']['chinese_t2s_lang'] || params['lang']) == 'cn'
case bodies
when ActionDispatch::Response # Rails
body = ChineseT2s::translate(bodies.body)
bodies.body = body
when Rack::BodyProxy # Grape
if defined?(::Rails) && (::Rails::VERSION::MAJOR <= 3) || (::Rails::VERSION::MAJOR == 4 && ::RAILS::VERSION::MINOR == 0)
body = bodies.body.first
body.gsub!(/((\\u[0-9a-z]{4})+)/){ $1[2..-1].split('\\u').map{|s| s.to_i(16)}.pack('U*') }
body = ChineseT2s::translate(body)
bodies.body = [body]
headers['Content-Length'] = body.bytesize.to_s
end
when Sprockets::ProcessedAsset
end
end
end
[status, headers, bodies]
end
end
end
end
| module ChineseT2s
module Middleware
class TranslationT2s
def initialize(app)
@app = app
end
def call(env)
status, headers, bodies = @app.call(env)
if status == 200 && bodies.present?
params = env['rack.request.query_hash'] || {}
if (env['rack.session']['chinese_t2s_lang'] || params['lang']) == 'cn'
case bodies
when ActionDispatch::Response # Rails
body = ChineseT2s::translate(bodies.body)
bodies.body = body
when Rack::BodyProxy # Grape
if defined?(::Rails) && (::Rails::VERSION::MAJOR <= 3) || (::Rails::VERSION::MAJOR == 4 && ::RAILS::VERSION::MINOR == 0)
body = bodies.body.first
body.gsub!(/((\\u[0-9a-z]{4})+)/){ $1[2..-1].split('\\u').map{|s| s.to_i(16)}.pack('U*') }
body = ChineseT2s::translate(body)
bodies.body = [body]
headers['Content-Length'] = body.bytesize.to_s
end
when Sprockets::ProcessedAsset
end
end
end
[status, headers, bodies]
end
end
end
end
|
Update primary key for dl_keyed_join | # frozen_string_literal: true
class DestroyAsyncParent < ActiveRecord::Base
self.primary_key = "parent_id"
has_one :dl_keyed_has_one, dependent: :destroy_async,
foreign_key: :destroy_async_parent_id, primary_key: :parent_id
has_many :dl_keyed_has_many, dependent: :destroy_async,
foreign_key: :many_key, primary_key: :parent_id
has_many :dl_keyed_join, dependent: :destroy_async,
foreign_key: :destroy_async_parent_id, primary_key: :joins_key
has_many :dl_keyed_has_many_through,
through: :dl_keyed_join, dependent: :destroy_async,
foreign_key: :dl_has_many_through_key_id, primary_key: :through_key
end
| # frozen_string_literal: true
class DestroyAsyncParent < ActiveRecord::Base
self.primary_key = "parent_id"
has_one :dl_keyed_has_one, dependent: :destroy_async,
foreign_key: :destroy_async_parent_id, primary_key: :parent_id
has_many :dl_keyed_has_many, dependent: :destroy_async,
foreign_key: :many_key, primary_key: :parent_id
has_many :dl_keyed_join, dependent: :destroy_async,
foreign_key: :destroy_async_parent_id, primary_key: :parent_id
has_many :dl_keyed_has_many_through,
through: :dl_keyed_join, dependent: :destroy_async,
foreign_key: :dl_has_many_through_key_id, primary_key: :through_key
end
|
Fix hidden budget investments restore feature | class Admin::HiddenCommentsController < Admin::BaseController
has_filters %w{without_confirmed_hide all with_confirmed_hide}
before_action :load_comment, only: [:confirm_hide, :restore]
def index
@comments = Comment.not_valuations.only_hidden.with_visible_author
.send(@current_filter).order(hidden_at: :desc).page(params[:page])
end
def confirm_hide
@comment.confirm_hide
redirect_to request.query_parameters.merge(action: :index)
end
def restore
@comment.restore
@comment.ignore_flag
Activity.log(current_user, :restore, @comment)
redirect_to request.query_parameters.merge(action: :index)
end
private
def load_comment
@comment = Comment.not_valuations.with_hidden.find(params[:id])
end
end
| class Admin::HiddenCommentsController < Admin::BaseController
has_filters %w{without_confirmed_hide all with_confirmed_hide}
before_action :load_comment, only: [:confirm_hide, :restore]
def index
@comments = Comment.not_valuations.only_hidden.with_visible_author
.send(@current_filter).order(hidden_at: :desc).page(params[:page])
end
def confirm_hide
@comment.confirm_hide
redirect_to request.query_parameters.merge(action: :index)
end
def restore
@comment.restore(recursive: true)
@comment.ignore_flag
Activity.log(current_user, :restore, @comment)
redirect_to request.query_parameters.merge(action: :index)
end
private
def load_comment
@comment = Comment.not_valuations.with_hidden.find(params[:id])
end
end
|
Clean up InstallBuckets action a bit | require_relative '../bucket'
module VagrantPlugins
module Cachier
class Action
class InstallBuckets
def initialize(app, env)
@app = app
end
def call(env)
@app.call(env)
@env = env
configure_cache_buckets
end
def configure_cache_buckets
return unless @env[:machine].config.cache.enabled?
if @env[:machine].config.cache.auto_detect
Bucket.auto_detect(@env)
end
return unless @env[:machine].config.cache.buckets.any?
@env[:ui].info 'Configuring cache buckets...'
cache_config = @env[:machine].config.cache
cache_config.buckets.each do |bucket_name, configs|
# cachier_debug "Installing #{bucket_name} with configs #{configs.inspect}"
Bucket.install(bucket_name, @env, configs)
end
data_file = @env[:machine].data_dir.join('cache_dirs')
data_file.open('w') { |f| f.print @env[:cache_dirs].uniq.join("\n") }
end
end
end
end
end
| require_relative '../bucket'
module VagrantPlugins
module Cachier
class Action
class InstallBuckets
def initialize(app, env)
@app = app
end
def call(env)
@app.call(env)
configure_cache_buckets(env)
end
def configure_cache_buckets
return unless env[:machine].config.cache.enabled?
if env[:machine].config.cache.auto_detect
Bucket.auto_detect(env)
end
return unless env[:machine].config.cache.buckets.any?
env[:ui].info 'Configuring cache buckets...'
cache_config = env[:machine].config.cache
cache_config.buckets.each do |bucket_name, configs|
# cachier_debug "Installing #{bucket_name} with configs #{configs.inspect}"
Bucket.install(bucket_name, env, configs)
end
data_file = env[:machine].data_dir.join('cache_dirs')
data_file.open('w') { |f| f.print env[:cache_dirs].uniq.join("\n") }
end
end
end
end
end
|
Work around ruby 1.8 mimetype conflict | $:.push File.expand_path("../lib", __FILE__)
require "gyoku/version"
Gem::Specification.new do |s|
s.name = "gyoku"
s.version = Gyoku::VERSION
s.platform = Gem::Platform::RUBY
s.authors = "Daniel Harrington"
s.email = "me@rubiii.com"
s.homepage = "https://github.com/savonrb/#{s.name}"
s.summary = "Translates Ruby Hashes to XML"
s.description = "Gyoku translates Ruby Hashes to XML"
s.rubyforge_project = "gyoku"
s.license = "MIT"
s.add_dependency "builder", ">= 2.1.2"
s.add_development_dependency "rake"
s.add_development_dependency "rspec"
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"]
end
| $:.push File.expand_path("../lib", __FILE__)
require "gyoku/version"
Gem::Specification.new do |s|
s.name = "gyoku"
s.version = Gyoku::VERSION
s.platform = Gem::Platform::RUBY
s.authors = "Daniel Harrington"
s.email = "me@rubiii.com"
s.homepage = "https://github.com/savonrb/#{s.name}"
s.summary = "Translates Ruby Hashes to XML"
s.description = "Gyoku translates Ruby Hashes to XML"
s.rubyforge_project = "gyoku"
s.license = "MIT"
s.add_dependency "builder", ">= 2.1.2"
if RUBY_VERSION < "1.9"
s.add_dependency "mime-types", "< 2.0.0"
end
s.add_development_dependency "rake"
s.add_development_dependency "rspec"
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"]
end
|
Add conekta payments to spree payment methods | module SpreeConekta
class Engine < ::Rails::Engine
require 'spree'
engine_name 'spree_gateway'
config.autoload_paths += %W(#{config.root}/lib)
# use rspec for tests
config.generators do |g|
g.test_framework :rspec
end
if Rails.version >= '3.1'
initializer :assets do |config|
Rails.application.config.assets.precompile += %w( spree_conekta.js )
end
end
def self.activate
Dir.glob(File.join(File.dirname(__FILE__), "../../app/**/*_decorator*.rb")) do |c|
Rails.env.production? ? require(c) : load(c)
end
end
initializer "spree.gateway.payment_methods", :after => "spree.register.payment_methods" do |app|
app.config.spree.payment_methods << Spree::BillingIntegration::Conekta
end
config.to_prepare &method(:activate).to_proc
end
end
| module SpreeConekta
class Engine < ::Rails::Engine
require 'spree'
engine_name 'spree_gateway'
config.autoload_paths += %W(#{config.root}/lib)
# use rspec for tests
config.generators do |g|
g.test_framework :rspec
end
if Rails.version >= '3.1'
initializer :assets do |config|
Rails.application.config.assets.precompile += %w( spree_conekta.js )
end
end
def self.activate
Dir.glob(File.join(File.dirname(__FILE__), "../../app/**/*_decorator*.rb")) do |c|
Rails.env.production? ? require(c) : load(c)
end
end
initializer "spree.gateway.payment_methods", :after => "spree.register.payment_methods" do |app|
app.config.spree.payment_methods << Spree::BillingIntegration::Conekta
app.config.spree.payment_methods << Spree::BillingIntegration::Conekta::Card
app.config.spree.payment_methods << Spree::BillingIntegration::Conekta::Cash
app.config.spree.payment_methods << Spree::BillingIntegration::Conekta::Bank
end
config.to_prepare &method(:activate).to_proc
end
end
|
Validate access tokens against the WOO API | module WooApi
module AppApi
class Base
def self.build_request(path, configuration = {})
local_configuration = configuration.dup
if local_configuration[:token_auth]
local_configuration[:token] = current_access_token
local_configuration.delete(:token_auth)
end
HTTPI::Request.new(url: "#{WooApi::AppApi::BASE_URL}#{path}", body: local_configuration)
end
private
def self.current_access_token
if WooAppApiToken.any? && WooAppApiToken.last.expires_at > Time.current
WooAppApiToken.last.access_token
else
WooApi::AppApi::User.login
current_access_token
end
end
def self.parse_response_items(response)
JSON(response.body)['items']
end
end
end
end
| module WooApi
module AppApi
class Base
def self.build_request(path, configuration = {})
local_configuration = configuration.dup
if local_configuration[:token_auth]
local_configuration[:token] = current_access_token
local_configuration.delete(:token_auth)
end
HTTPI::Request.new(url: "#{WooApi::AppApi::BASE_URL}#{path}", body: local_configuration)
end
private
def self.current_access_token
last_token = WooAppApiToken.last.access_token
if WooAppApiToken.any? && WooAppApiToken.last.expires_at > Time.current && access_token_valid?(last_token)
last_token
else
WooApi::AppApi::User.login
current_access_token
end
end
def self.access_token_valid?(access_token)
response = HTTPI.post(HTTPI::Request.new(url: "#{WooApi::AppApi::BASE_URL}/session/activity", body: {token: access_token, pageSize: 1}))
response.code == 200
end
def self.parse_response_items(response)
JSON(response.body)['items']
end
end
end
end
|
Revert "Go to gpx_offline mode" | name "web"
description "Role applied to all web/api servers"
default_attributes(
:accounts => {
:users => {
:rails => {
:status => :role,
:members => [ :tomh, :grant ]
}
}
},
:nfs => {
"/store/rails" => { :host => "ironbelly", :path => "/store/rails" }
},
:passenger => {
:pool_idle_time => 0
},
:web => {
:status => "gpx_offline",
:database_host => "db",
:readonly_database_host => "katla"
}
)
run_list(
"recipe[nfs]"
)
| name "web"
description "Role applied to all web/api servers"
default_attributes(
:accounts => {
:users => {
:rails => {
:status => :role,
:members => [ :tomh, :grant ]
}
}
},
:nfs => {
"/store/rails" => { :host => "ironbelly", :path => "/store/rails" }
},
:passenger => {
:pool_idle_time => 0
},
:web => {
:status => "online",
:database_host => "db",
:readonly_database_host => "katla"
}
)
run_list(
"recipe[nfs]"
)
|
Rename misleading method 'dirs' to 'all' | module Trackler
# Problems is the collection of problems that we have metadata for.
class Problems
include Enumerable
SLUG_PATTERN = Regexp.new(".*\/exercises\/([^\/]*)\/")
attr_reader :root
def initialize(root)
@root = root
end
def each
valid.each do |problem|
yield problem
end
end
def [](slug)
by_slug[slug]
end
# rubocop:disable Style/OpMethod
def -(slugs)
(by_slug.keys - slugs).sort
end
private
def valid
@valid ||= dirs.select(&:active?)
end
def dirs
@exercise_ids ||= Dir["%s/common/exercises/*/" % root].sort.map { |f|
Problem.new(f[SLUG_PATTERN, 1], root)
}
end
def by_slug
@by_slug ||= problem_map
end
def problem_map
hash = Hash.new { |_, k| Problem.new(k, root) }
valid.each do |problem|
hash[problem.slug] = problem
end
hash
end
end
end
| module Trackler
# Problems is the collection of problems that we have metadata for.
class Problems
include Enumerable
SLUG_PATTERN = Regexp.new(".*\/exercises\/([^\/]*)\/")
attr_reader :root
def initialize(root)
@root = root
end
def each
valid.each do |problem|
yield problem
end
end
def [](slug)
by_slug[slug]
end
# rubocop:disable Style/OpMethod
def -(slugs)
(by_slug.keys - slugs).sort
end
private
def valid
@valid ||= all.select(&:active?)
end
def all
@exercise_ids ||= Dir["%s/common/exercises/*/" % root].sort.map { |f|
Problem.new(f[SLUG_PATTERN, 1], root)
}
end
def by_slug
@by_slug ||= problem_map
end
def problem_map
hash = Hash.new { |_, k| Problem.new(k, root) }
valid.each do |problem|
hash[problem.slug] = problem
end
hash
end
end
end
|
Make the shorthand expansion more strict to allow non-Github repos | require 'fileutils'
Puppet::Type.type(:repository).provide(:git) do
desc "Git repository clones"
# FIX: needs to infer path
CRED_HELPER_PATH = "#{Facter[:boxen_home].value}/bin/boxen-git-credential"
CRED_HELPER = "-c credential.helper=#{CRED_HELPER_PATH}"
GIT_BIN = "#{Facter[:boxen_home].value}/homebrew/bin/git"
commands :git => GIT_BIN
def self.default_protocol
'https'
end
def exists?
File.directory?(@resource[:path]) &&
File.directory?("#{@resource[:path]}/.git")
end
def create
source = expand_source(@resource[:source])
path = @resource[:path]
if File.exist? CRED_HELPER_PATH
args = [
GIT_BIN,
"clone",
CRED_HELPER,
[@resource[:extra]].flatten.join(' ').strip,
source,
path
]
else
args = [
GIT_BIN,
"clone",
[@resource[:extra]].flatten.join(' ').strip,
source,
path
]
end
execute args.flatten.join(' '), :uid => Facter[:luser].value
end
def destroy
path = @resource[:path]
FileUtils.rm_rf path
end
def expand_source(source)
if source =~ /\A\S+\/\S+\z/
"#{@resource[:protocol]}://github.com/#{source}"
else
source
end
end
end
| require 'fileutils'
Puppet::Type.type(:repository).provide(:git) do
desc "Git repository clones"
# FIX: needs to infer path
CRED_HELPER_PATH = "#{Facter[:boxen_home].value}/bin/boxen-git-credential"
CRED_HELPER = "-c credential.helper=#{CRED_HELPER_PATH}"
GIT_BIN = "#{Facter[:boxen_home].value}/homebrew/bin/git"
commands :git => GIT_BIN
def self.default_protocol
'https'
end
def exists?
File.directory?(@resource[:path]) &&
File.directory?("#{@resource[:path]}/.git")
end
def create
source = expand_source(@resource[:source])
path = @resource[:path]
if File.exist? CRED_HELPER_PATH
args = [
GIT_BIN,
"clone",
CRED_HELPER,
[@resource[:extra]].flatten.join(' ').strip,
source,
path
]
else
args = [
GIT_BIN,
"clone",
[@resource[:extra]].flatten.join(' ').strip,
source,
path
]
end
execute args.flatten.join(' '), :uid => Facter[:luser].value
end
def destroy
path = @resource[:path]
FileUtils.rm_rf path
end
def expand_source(source)
if source =~ /\A[^\/\s]+\/[^\/\s]+\z/
@resource[:protocol]}://github.com/#{source}"
else
source
end
end
end
|
Add a test for the empty search results page | # frozen_string_literal: true
require 'test_helper'
require 'support/sphinx'
require 'support/web_mocking'
class Search < ActionDispatch::IntegrationTest
include WebMocking
include SphinxHelpers
before do
ThinkingSphinx::Test.start
create(:ad, woeid_code: 766_273, title: 'muebles oro', status: 1)
create(:ad, woeid_code: 766_273, title: 'tele', type: 2)
create(:ad, woeid_code: 753_692, title: 'muebles plata', status: 1)
index
mocking_yahoo_woeid_info(766_273) do
visit ads_woeid_path(766_273, type: 'give')
end
end
after { ThinkingSphinx::Test.stop }
it 'searchs ads in current location by title' do
fill_in 'q', with: 'muebles'
click_button 'buscar'
page.assert_selector '.ad_excerpt_list', count: 1, text: 'muebles oro'
end
end
| # frozen_string_literal: true
require 'test_helper'
require 'support/sphinx'
require 'support/web_mocking'
class Search < ActionDispatch::IntegrationTest
include WebMocking
include SphinxHelpers
before do
ThinkingSphinx::Test.start
create(:ad, woeid_code: 766_273, title: 'muebles oro', status: 1)
create(:ad, woeid_code: 766_273, title: 'tele', type: 2)
create(:ad, woeid_code: 753_692, title: 'muebles plata', status: 1)
index
mocking_yahoo_woeid_info(766_273) do
visit ads_woeid_path(766_273, type: 'give')
end
end
after { ThinkingSphinx::Test.stop }
it 'searchs ads in current location by title' do
fill_in 'q', with: 'muebles'
click_button 'buscar'
page.assert_selector '.ad_excerpt_list', count: 1, text: 'muebles oro'
end
it 'shows a no results message when nothing found in current location' do
fill_in 'q', with: 'espejo'
click_button 'buscar'
page.assert_selector '.ad_excerpt_list', count: 0
assert_content 'No hay anuncios que coincidan con la búsqueda espejo en ' \
'la ubicación Madrid, Madrid, España'
end
end
|
Add "vanity" attributes to the User resource | module ChefAPI
class Resource::User < Resource::Base
collection_path '/users'
schema do
attribute :username, type: String, primary: true, required: true
attribute :admin, type: Boolean, default: false
attribute :public_key, type: String
end
class << self
#
# @see Base.each
#
def each(prefix = {}, &block)
collection(prefix).each do |info|
name = URI.escape(info['user']['username'])
response = connection.get("/users/#{name}")
result = from_json(response, prefix)
block.call(result) if block
end
end
#
# Authenticate a user with the given +username+ and +password+.
#
# @note Requires Enterprise Chef
#
# @example Authenticate a user
# User.authenticate(username: 'user', password: 'pass')
# #=> { "status" => "linked", "user" => { ... } }
#
# @param [Hash] options
# the list of options to authenticate with
#
# @option options [String] username
# the username to authenticate with
# @option options [String] password
# the plain-text password to authenticate with
#
# @return [Hash]
# the parsed JSON response from the server
#
def authenticate(options = {})
connection.post('/authenticate_user', options)
end
end
end
end
| module ChefAPI
class Resource::User < Resource::Base
collection_path '/users'
schema do
attribute :username, type: String, primary: true, required: true
attribute :admin, type: Boolean, default: false
attribute :public_key, type: String
# "Vanity" attributes
attribute :first_name, type: String
attribute :middle_name, type: String
attribute :last_name, type: String
attribute :display_name, type: String
attribute :email, type: String
attribute :city, type: String
attribute :country, type: String
attribute :twitter_account, type: String
end
class << self
#
# @see Base.each
#
def each(prefix = {}, &block)
collection(prefix).each do |info|
name = URI.escape(info['user']['username'])
response = connection.get("/users/#{name}")
result = from_json(response, prefix)
block.call(result) if block
end
end
#
# Authenticate a user with the given +username+ and +password+.
#
# @note Requires Enterprise Chef
#
# @example Authenticate a user
# User.authenticate(username: 'user', password: 'pass')
# #=> { "status" => "linked", "user" => { ... } }
#
# @param [Hash] options
# the list of options to authenticate with
#
# @option options [String] username
# the username to authenticate with
# @option options [String] password
# the plain-text password to authenticate with
#
# @return [Hash]
# the parsed JSON response from the server
#
def authenticate(options = {})
connection.post('/authenticate_user', options)
end
end
end
end
|
Add an refactor factory test. | describe Metacrunch::Mab2::AlephMabXmlDocumentFactory do
it "should parse Aleph MAB XML files" do
xml = File.read(File.join(RSpec.root, "assets", "aleph_mab_xml", "file1.xml"))
factory = Metacrunch::Mab2::AlephMabXmlDocumentFactory.new(xml)
document = factory.to_document
#binding.pry
expect(document.all_data_fields.count).to be(27)
expect(document.all_control_fields.count).to be(6)
expect(document.data_fields("070").count).to be(2)
expect(document.data_fields("100").first.all_sub_fields.count).to be(3)
expect(document.data_fields("100").first.sub_fields("p").first.value).not_to be_nil
end
end
| describe Metacrunch::Mab2::AlephMabXmlDocumentFactory do
context "with default test xml file" do
let(:factory) { Metacrunch::Mab2::AlephMabXmlDocumentFactory.new(default_test_xml) }
describe ".to_document" do
subject { factory.to_document }
it "should return a Mab2::Document" do
expect(subject).to be_instance_of(Metacrunch::Mab2::Document)
end
it "should find 27 data fields" do
expect(subject.all_data_fields.count).to be(27)
end
it "should find 6 control fields" do
expect(subject.all_control_fields.count).to be(6)
end
it "should find 2 data fields with tag 070" do
expect(subject.data_fields("070").count).to be(2)
end
it "should find 1 data field with tag 100" do
expect(subject.data_fields("100").first).not_to be_nil
end
it "should find 3 sub fields of data field with tag 100" do
expect(subject.data_fields("100").first.all_sub_fields.count).to be(3)
end
it "sub field p of data field 100 is not nil" do
expect(subject.data_fields("100").first.sub_fields("p").first.value).not_to be_nil
end
it "decodes html entities" do
expect(subject.values(data_field: "331", sub_field: "a").first).to eq("<<Das>> Linux für Studenten")
end
end
end
private
def default_test_xml
File.read(File.join(RSpec.root, "assets", "aleph_mab_xml", "file1.xml"))
end
end
|
Fix not updated spec after renaming test entities. | require "spec_helper"
require "mongoid_embed_finder/relation_discovery"
describe MongoidEmbedFinder::RelationDiscovery do
describe "#relations" do
subject { described_class.new(Child, :parent).relations }
its(:child_class) { should eq Child }
its(:parent_class) { should eq Parent }
its('children.key') { should eq "children" }
its('children.class_name') { should eq "Child" }
its('parent.setter') { should eq "parent=" }
end
end | require "spec_helper"
require "mongoid_embed_finder/relation_discovery"
describe MongoidEmbedFinder::RelationDiscovery do
describe "#relations" do
subject { described_class.new(Door, :car).relations }
its(:child_class) { should eq Door }
its(:parent_class) { should eq Car }
its('children.key') { should eq "doors" }
its('children.class_name') { should eq "Door" }
its('parent.setter') { should eq "car=" }
end
end |
Add some notes regarding type size | module GirFFI
module FFIExt
module Pointer
def to_ptr
self
end
def to_value
self
end
def to_object
# TODO: Move implementation here.
ArgHelper.object_pointer_to_object self
end
def put_bool offset, value
int = value ? 1 : 0
put_int32 offset, int
end
def get_bool offset
int = get_int32 offset
return (int != 0)
end
end
end
end
FFI::Pointer.send :include, GirFFI::FFIExt::Pointer
| module GirFFI
module FFIExt
module Pointer
def to_ptr
self
end
def to_value
self
end
def to_object
# TODO: Move implementation here.
ArgHelper.object_pointer_to_object self
end
# XXX: int32 is size 4, bool is size 1. Why u no crash?
def put_bool offset, value
int = value ? 1 : 0
put_int32 offset, int
end
# XXX: int32 is size 4, bool is size 1. Why u no crash?
def get_bool offset
int = get_int32 offset
return (int != 0)
end
end
end
end
FFI::Pointer.send :include, GirFFI::FFIExt::Pointer
|
Add tests for "attributes" attribute | require 'spec_helper'
describe "Adding attribute called 'attributes'" do
context "when mass assignment is disabled" do
before do
module Examples
class User
include Virtus.model(mass_assignment: false)
attribute :attributes
end
end
end
it "allows model to use `attributes` attribute" do
user = Examples::User.new
expect(user.attributes).to eq(nil)
user.attributes = "attributes string"
expect(user.attributes).to eq("attributes string")
end
it "doesn't accept `attributes` key in initializer" do
user = Examples::User.new(attributes: 'attributes string')
expect(user.attributes).to eq(nil)
end
end
end
| |
Use status on supported platforms. | #
# Cookbook Name:: openssh
# Recipe:: default
#
# Copyright 2008-2009, Opscode, 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.
#
packages = case node[:platform]
when "centos","redhat","fedora"
%w{openssh-clients openssh}
else
%w{openssh-client openssh-server}
end
packages.each do |pkg|
package pkg
end
service "ssh" do
case node[:platform]
when "centos","redhat","fedora"
service_name "sshd"
else
service_name "ssh"
end
supports :restart => true
action [ :enable, :start ]
end
| #
# Cookbook Name:: openssh
# Recipe:: default
#
# Copyright 2008-2009, Opscode, 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.
#
packages = case node[:platform]
when "centos","redhat","fedora"
%w{openssh-clients openssh}
else
%w{openssh-client openssh-server}
end
packages.each do |pkg|
package pkg
end
service "ssh" do
case node[:platform]
when "centos","redhat","fedora"
service_name "sshd"
else
service_name "ssh"
end
supports value_for_platform(
"debian" => { "default" => [ :restart, :reload ] },
"ubuntu" => { "default" => [ :restart, :reload ] },
"centos" => { "default" => [ :restart, :reload, :status ] },
"redhat" => { "default" => [ :restart, :reload, :status ] },
"fedora" => { "default" => [ :restart, :reload, :status ] },
"default" => { "default" => [:restart, :reload ] }
)
action [ :enable, :start ]
end
|
Add smoke test to touch all the elements for real. | require 'spec_helper.rb'
class ExampleObserver
include ImapMonitor::EmailEvent::Observer
def initialize(account = {})
@tracker = ImapMonitor::Email::Tracker.new(ImapMonitor::Connector.new(account))
@tracker.register(self)
end
def go
tracker.async.start
puts "Tracker started..."
end
def tracker
@tracker
end
def custom
@custom ||= []
end
def property_changed(clazz, property, email)
puts 'Property Change Received'
@custom << "#{property}, #{email.subject}"
end
end
describe 'Imap monitor smoken test' do
let(:details) {{ host: 'imap.gmail.com', port: 993, username: 'email', password: 'password', use_ssl: true }}
let(:observer) { ExampleObserver.new(details) }
it 'receives one call to the observer with the email' do
observer.go
while(observer.custom.size == 0)
end
observer.tracker.stop
expect(observer.tracker.connector.connection.disconnected?).to eq false
expect(observer.custom.size).to eq 1
expect(observer.custom.first).to include 'NewMail'
end
end
| |
Add feature spec for store autocomplete | require 'spec_helper'
RSpec.describe "Store promotion rule", js: true do
stub_authorization!
let!(:store) { create(:store, name: "Real fake doors") }
let!(:promotion) { create(:promotion) }
it "Can add a store rule to a promotion" do
visit spree.edit_admin_promotion_path(promotion)
select2 "Store", from: "Add rule of type"
within("#rules_container") { click_button "Add" }
select2_search store.name, from: "Choose Stores"
within("#rules_container") { click_button "Update" }
expect(page).to have_content('successfully updated')
end
end
| |
Update spec expectations to avoid flake specs | require "rails_helper"
describe "Email campaigns", :admin do
let!(:campaign1) { create(:campaign) }
let!(:campaign2) { create(:campaign) }
scenario "Track email templates" do
3.times { visit root_path(track_id: campaign1.track_id) }
5.times { visit root_path(track_id: campaign2.track_id) }
visit admin_stats_path
click_link campaign1.name
expect(page).to have_content "#{campaign1.name} (3)"
click_link "Go back"
click_link campaign2.name
expect(page).to have_content "#{campaign2.name} (5)"
end
scenario "Do not track erroneous track_ids" do
visit root_path(track_id: campaign1.track_id)
visit root_path(track_id: Campaign.last.id + 1)
visit admin_stats_path
click_link campaign1.name
expect(page).to have_content "#{campaign1.name} (1)"
click_link "Go back"
expect(page).not_to have_content campaign2.name.to_s
end
end
| require "rails_helper"
describe "Email campaigns", :admin do
let!(:campaign1) { create(:campaign) }
let!(:campaign2) { create(:campaign) }
scenario "Track email templates" do
3.times { visit root_path(track_id: campaign1.track_id) }
5.times { visit root_path(track_id: campaign2.track_id) }
visit admin_stats_path
click_link campaign1.name
expect(page).to have_content "#{campaign1.name} (3)"
click_link "Go back"
click_link campaign2.name
expect(page).to have_content "#{campaign2.name} (5)"
end
scenario "Do not track erroneous track_ids" do
visit root_path(track_id: campaign1.track_id)
visit root_path(track_id: Campaign.last.id + 1)
visit admin_stats_path
expect(page).to have_content campaign1.name
expect(page).not_to have_content campaign2.name
click_link campaign1.name
expect(page).to have_content "#{campaign1.name} (1)"
end
end
|
Add XQuartz 2.7.5_rc4. Brew is whining when you start a doctor with 2.7.4. | class XQuartz < Cask
url 'http://xquartz.macosforge.org/downloads/SL/XQuartz-2.7.4.dmg'
homepage 'http://xquartz.macosforge.org/'
version '2.7.4'
sha1 '98b2ca8580046d5b91250c5a244c8182437dc9d7'
install 'XQuartz.pkg'
end
| class XQuartz < Cask
url 'http://xquartz.macosforge.org/downloads/SL/XQuartz-2.7.5_rc4.dmg'
homepage 'http://xquartz.macosforge.org/'
version '2.7.5_rc4'
sha1 '273b5b208546779d3e35842d84efd2ba7927b253'
install 'XQuartz.pkg'
end
|
Define default proof status number. | class AddNumberToProofAttempt < ActiveRecord::Migration
def change
add_column :proof_attempts, :number, :integer, null: false
end
end
| class AddNumberToProofAttempt < ActiveRecord::Migration
def change
add_column :proof_attempts, :number, :integer, null: false, default: 0
end
end
|
Fix specification of dependencies in podspec | Pod::Spec.new do |s|
s.name = "Atlas"
s.version = '1.0.0'
s.summary = "Atlas is a library of communications user interface components integrated with LayerKit."
s.homepage = 'https://atlas.layer.com/'
s.social_media_url = 'http://twitter.com/layer'
s.documentation_url = 'http://atlas.layer.com/docs'
s.license = 'Apache2'
s.author = { 'Kevin Coleman' => 'kevin@layer.com',
'Blake Watters' => 'blake@layer.com',
'Klemen Verdnik' => 'klemen@layer.com',
'Ben Blakely' => 'ben@layer.com' }
s.source = { git: "https://github.com/layerhq/Atlas-iOS.git", tag: "v#{s.version}" }
s.platform = :ios, '7.0'
s.requires_arc = true
s.source_files = 'Code/**/*.{h,m}'
s.ios.resource_bundle = { 'AtlasResource' => 'Resources/*' }
s.header_mappings_dir = 'Code'
s.ios.frameworks = 'UIKit, CoreLocation, MobileCoreServices'
s.ios.deployment_target = '7.0'
s.dependency 'LayerKit'
end
| Pod::Spec.new do |s|
s.name = "Atlas"
s.version = '1.0.0'
s.summary = "Atlas is a library of communications user interface components integrated with LayerKit."
s.homepage = 'https://atlas.layer.com/'
s.social_media_url = 'http://twitter.com/layer'
s.documentation_url = 'http://atlas.layer.com/docs'
s.license = 'Apache2'
s.author = { 'Kevin Coleman' => 'kevin@layer.com',
'Blake Watters' => 'blake@layer.com',
'Klemen Verdnik' => 'klemen@layer.com',
'Ben Blakely' => 'ben@layer.com' }
s.source = { git: "https://github.com/layerhq/Atlas-iOS.git", tag: "v#{s.version}" }
s.platform = :ios, '7.0'
s.requires_arc = true
s.source_files = 'Code/**/*.{h,m}'
s.ios.resource_bundle = { 'AtlasResource' => 'Resources/*' }
s.header_mappings_dir = 'Code'
s.ios.frameworks = %w{UIKit CoreLocation MobileCoreServices}
s.ios.deployment_target = '7.0'
s.dependency 'LayerKit'
end
|
Add rake task to download and replace database with heroku snapshot | # desc "Explaining what the task does"
# task :forest do
# # Task goes here
# end
| desc "Download and replace this database with a current capture from heroku."
namespace :forest do
task 'db:capture' => :environment do
db = Rails.application.config.database_configuration[Rails.env]
user = db['username']
database = db['database']
puts "This command captures a snapshot of the Heroku database, downloads it, drops the local database and recreates if from the Heroku snapshot."
puts "Please run:"
puts "heroku pg:backups:capture; heroku pg:backups:download; bin/rails db:drop; bin/rails db:create; pg_restore --verbose --clean --no-acl --no-owner -h localhost#{if user then " -U #{user}" end} -d #{database} latest.dump; rm latest.dump"
end
end
|
Use low priority for emails sent at promo launch | require "#{Rails.root}/app/helpers/promos_helper"
namespace :promo do
# Generates the promo tokens and sends emails
task :launch_promo => :environment do
include PromosHelper
begin
unless promo_running?
puts "Promo is not running, check the active_promo_id config var."
end
publishers = Publisher.where(promo_token_2018q1: nil).where(promo_enabled_2018q1: false).where.not(email: nil)
publishers.find_each do |publisher|
token = PublisherPromoTokenGenerator.new(publisher: publisher).perform
next unless token
PromoMailer.activate_promo_2018q1(publisher).deliver_later
end
rescue PublisherPromoTokenGenerator::InvalidPromoIdError => error
require "raven"
Raven.capture_exception(error)
puts "Did not launch promo because of invalid promo id. Check the active_promo_id config var."
end
end
end | require "#{Rails.root}/app/helpers/promos_helper"
namespace :promo do
# Generates the promo tokens and sends emails
task :launch_promo => :environment do
include PromosHelper
begin
unless promo_running?
puts "Promo is not running, check the active_promo_id config var."
end
publishers = Publisher.where(promo_token_2018q1: nil).where(promo_enabled_2018q1: false).where.not(email: nil)
publishers.find_each do |publisher|
token = PublisherPromoTokenGenerator.new(publisher: publisher).perform
next unless token
PromoMailer.activate_promo_2018q1(publisher).deliver_later(queue: :low)
end
rescue PublisherPromoTokenGenerator::InvalidPromoIdError => error
require "raven"
Raven.capture_exception(error)
puts "Did not launch promo because of invalid promo id. Check the active_promo_id config var."
end
end
end |
Set appropriate assets pack for the keyword filter page | # frozen_string_literal: true
class FiltersController < ApplicationController
include Authorization
layout 'admin'
before_action :set_filters, only: :index
before_action :set_filter, only: [:edit, :update, :destroy]
def index
@filters = current_account.custom_filters
end
def new
@filter = current_account.custom_filters.build
end
def create
@filter = current_account.custom_filters.build(resource_params)
if @filter.save
redirect_to filters_path
else
render action: :new
end
end
def edit; end
def update
if @filter.update(resource_params)
redirect_to filters_path
else
render action: :edit
end
end
def destroy
@filter.destroy
redirect_to filters_path
end
private
def set_filters
@filters = current_account.custom_filters
end
def set_filter
@filter = current_account.custom_filters.find(params[:id])
end
def resource_params
params.require(:custom_filter).permit(:phrase, :expires_in, :irreversible, context: [])
end
end
| # frozen_string_literal: true
class FiltersController < ApplicationController
include Authorization
layout 'admin'
before_action :set_filters, only: :index
before_action :set_filter, only: [:edit, :update, :destroy]
before_action :set_pack
def index
@filters = current_account.custom_filters
end
def new
@filter = current_account.custom_filters.build
end
def create
@filter = current_account.custom_filters.build(resource_params)
if @filter.save
redirect_to filters_path
else
render action: :new
end
end
def edit; end
def update
if @filter.update(resource_params)
redirect_to filters_path
else
render action: :edit
end
end
def destroy
@filter.destroy
redirect_to filters_path
end
private
def set_pack
use_pack 'settings'
end
def set_filters
@filters = current_account.custom_filters
end
def set_filter
@filter = current_account.custom_filters.find(params[:id])
end
def resource_params
params.require(:custom_filter).permit(:phrase, :expires_in, :irreversible, context: [])
end
end
|
Set required Ruby version to 2.2.2 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'vcloud/tools/version'
Gem::Specification.new do |s|
s.name = 'vcloud-tools'
s.version = Vcloud::Tools::VERSION
s.authors = ['Government Digital Service']
s.summary = %q{Tools for VMware vCloud}
s.homepage = 'https://github.com/gds-operations/vcloud-tools'
s.license = 'MIT'
s.files = `git ls-files`.split($/)
s.executables = s.files.grep(%r{^bin/}) {|f| File.basename(f)}
s.test_files = s.files.grep(%r{^(test|spec|features)/})
s.require_paths = ['lib']
s.required_ruby_version = '>= 1.9.3'
s.add_runtime_dependency 'vcloud-core'
s.add_runtime_dependency 'vcloud-edge_gateway'
s.add_runtime_dependency 'vcloud-launcher'
s.add_runtime_dependency 'vcloud-net_launcher'
s.add_runtime_dependency 'vcloud-walker'
s.add_development_dependency 'gem_publisher', '1.2.0'
s.add_development_dependency 'rake'
s.add_development_dependency 'vcloud-tools-tester'
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'vcloud/tools/version'
Gem::Specification.new do |s|
s.name = 'vcloud-tools'
s.version = Vcloud::Tools::VERSION
s.authors = ['Government Digital Service']
s.summary = %q{Tools for VMware vCloud}
s.homepage = 'https://github.com/gds-operations/vcloud-tools'
s.license = 'MIT'
s.files = `git ls-files`.split($/)
s.executables = s.files.grep(%r{^bin/}) {|f| File.basename(f)}
s.test_files = s.files.grep(%r{^(test|spec|features)/})
s.require_paths = ['lib']
s.required_ruby_version = '>= 2.2.2'
s.add_runtime_dependency 'vcloud-core'
s.add_runtime_dependency 'vcloud-edge_gateway'
s.add_runtime_dependency 'vcloud-launcher'
s.add_runtime_dependency 'vcloud-net_launcher'
s.add_runtime_dependency 'vcloud-walker'
s.add_development_dependency 'gem_publisher', '1.2.0'
s.add_development_dependency 'rake'
s.add_development_dependency 'vcloud-tools-tester'
end
|
Raise an error if OrganisationMember creation fails. | class OrganisationMembersController < ApplicationController
before_filter :get_or_create_user, :only => [:create]
before_filter :get_user, :only => [:destroy]
def create
unless @user.new_record? || @user.organisations.include?(current_organisation)
current_organisation.organisation_members.create(
:user => @user,
:sponsor => @current_user
)
redirect_to current_organisation
else
@organisation = current_organisation
render :template => 'organisations/show'
end
end
def destroy
@user.organisation_members.
find_by_organisation_id(current_organisation.id).destroy
redirect_to organisation_url
end
protected
def get_or_create_user
@user = User.find(:first, :conditions => params[:user])
@user ||= User.create(params[:user])
end
def get_user
@user = current_organisation.users.find(params[:id])
end
end
| class OrganisationMembersController < ApplicationController
before_filter :get_or_create_user, :only => [:create]
before_filter :get_user, :only => [:destroy]
def create
unless @user.new_record? || @user.organisations.include?(current_organisation)
current_organisation.organisation_members.create!(
:user => @user,
:sponsor => @current_user
)
redirect_to current_organisation
else
@organisation = current_organisation
render :template => 'organisations/show'
end
end
def destroy
@user.organisation_members.
find_by_organisation_id(current_organisation.id).destroy
redirect_to organisation_url
end
protected
def get_or_create_user
@user = User.find(:first, :conditions => params[:user])
@user ||= User.create(params[:user])
end
def get_user
@user = current_organisation.users.find(params[:id])
end
end
|
Allow an admin to delete an HD Session | # frozen_string_literal: true
module Renalware
module HD
class ClosedSessionPolicy < BasePolicy
def destroy?
edit?
end
def edit?
return false unless record.persisted?
user_is_super_admin? || !record.immutable?
end
end
end
end
| # frozen_string_literal: true
module Renalware
module HD
class ClosedSessionPolicy < BasePolicy
def destroy?
edit?
end
def edit?
return false unless record.persisted?
user_is_admin? || user_is_super_admin? || !record.immutable?
end
end
end
end
|
Fix requirements in pod spec | Pod::Spec.new do |s|
s.name = 'RunIt'
s.module_name = 'RunIt'
s.version = '0.1.0'
s.homepage = 'https://github.com/Wisors/RunIt'
s.summary = 'A simple component helps you have only one Singleton.'
s.author = { 'Nikishin Alexander' => 'wisorus@gmail.com' }
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.platforms = { :ios => '7.0' }
s.ios.deployment_target = '7.0'
s.source_files = 'Sources/*.swift'
s.source = { :git => 'https://github.com/Wisors/RunIt.git', :tag => s.version }
end | Pod::Spec.new do |s|
s.name = 'RunIt'
s.module_name = 'RunIt'
s.version = '0.1.0'
s.homepage = 'https://github.com/Wisors/RunIt'
s.summary = 'A simple component helps you have only one Singleton.'
s.author = { 'Nikishin Alexander' => 'wisorus@gmail.com' }
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.platforms = { :ios => '8.0' }
s.ios.deployment_target = '8.0'
s.source_files = 'Sources/*.swift'
s.source = { :git => 'https://github.com/Wisors/RunIt.git', :tag => s.version }
end |
Use certs in all environments | module StarterKit
class AuthConfig < Settingslogic
source "#{Rails.root}/config/auth.yml"
namespace Rails.env
load!
end
end
OmniAuth.config.logger = Rails.logger
OmniAuth.config.path_prefix = '/o'
StarterKit::Application.config.middleware.use OmniAuth::Builder do
StarterKit::AuthConfig.providers.each do |k, v|
opts = (v.try(:[], 'oauth') || {}).symbolize_keys
if Rails.env.development?
opts.merge!({client_options: {ssl: {ca_file: Rails.root.join('lib/assets/certs/cacert.pem').to_s}}})
end
provider k, v['key'], v['secret'], opts
end
end
| module StarterKit
class AuthConfig < Settingslogic
source "#{Rails.root}/config/auth.yml"
namespace Rails.env
load!
end
end
OmniAuth.config.logger = Rails.logger
OmniAuth.config.path_prefix = '/o'
StarterKit::Application.config.middleware.use OmniAuth::Builder do
StarterKit::AuthConfig.providers.each do |k, v|
opts = (v.try(:[], 'oauth') || {}).symbolize_keys
opts.merge!({client_options: {ssl: {ca_file: Rails.root.join('lib/assets/certs/cacert.pem').to_s}}})
provider k, v['key'], v['secret'], opts
end
end
|
Append a "_" to memoized instance variables | module ActiveSupport
module Memoizable
def self.included(base) #:nodoc:
base.extend(ClassMethods)
end
module ClassMethods
def memoize(symbol)
original_method = "_unmemoized_#{symbol}"
raise "Already memoized #{symbol}" if instance_methods.map(&:to_s).include?(original_method)
alias_method original_method, symbol
class_eval <<-EOS, __FILE__, __LINE__
def #{symbol}
if defined? @#{symbol}
@#{symbol}
else
@#{symbol} = #{original_method}
end
end
EOS
end
end
def freeze
methods.each do |method|
if m = method.to_s.match(/\A_unmemoized_(.*)/)
send(m[1]).freeze
end
end
super
end
end
end
| module ActiveSupport
module Memoizable
def self.included(base) #:nodoc:
base.extend(ClassMethods)
end
module ClassMethods
def memoize(symbol)
original_method = "_unmemoized_#{symbol}"
memoized_ivar = "@_memoized_#{symbol}"
raise "Already memoized #{symbol}" if instance_methods.map(&:to_s).include?(original_method)
alias_method original_method, symbol
class_eval <<-EOS, __FILE__, __LINE__
def #{symbol}
if defined? #{memoized_ivar}
#{memoized_ivar}
else
#{memoized_ivar} = #{original_method}
end
end
EOS
end
end
def freeze
methods.each do |method|
if m = method.to_s.match(/\A_unmemoized_(.*)/)
send(m[1]).freeze
end
end
super
end
end
end
|
Update gemspec for new version | Gem::Specification.new do |s|
s.name = 'random_point_generator'
s.version = '0.0.1'
s.date = '2014-12-08'
s.licenses =['MIT']
s.summary = 'Generates random map points, within an optional bounding box.'
s.authors = ['Kyle Tolle']
s.email = 'kyle@nullsix.com'
s.files = ['lib/random_point_generator.rb', 'spec/random_point_generator_spec.rb']
s.homepage = 'https://github.com/kyletolle/random_point_generator'
s.add_development_dependency 'rspec', '~> 3.0', '>= 3.0.0'
end
| Gem::Specification.new do |s|
s.name = 'random_point_generator'
s.summary = 'Generates random map points, within an optional bounding box.'
s.homepage = 'https://github.com/kyletolle/random_point_generator'
s.version = '0.0.2'
s.date = '2014-12-08'
s.licenses = ['MIT']
s.authors = ['Kyle Tolle']
s.email = ['kyle@nullsix.com']
s.files = ['lib/random_point_generator.rb', 'spec/random_point_generator_spec.rb']
s.add_development_dependency 'rspec', '~> 3.0', '>= 3.0.0'
end
|
Update annuity rates for December | class GuaranteedIncomeCalculator
TAX_FREE_POT_PORTION = 0.25
TAXABLE_POT_PORTION = 0.75
def initialize(pot:, age:)
self.pot = pot
self.age = age
end
attr_accessor :pot, :age
def estimate
{ income: income_rounded, tax_free_lump_sum: tax_free_lump_sum }
end
private
def tax_free_lump_sum
pot * TAX_FREE_POT_PORTION
end
def income
taxable_amount * annuity_rate
end
def income_rounded
income.round(-2)
end
def taxable_amount
pot * TAXABLE_POT_PORTION
end
# https://pensionwise-guidance.atlassian.net/wiki/pages/viewpage.action?pageId=34237
def annuity_rate
case age
when 55...60 then 0.04337
when 60...65 then 0.04808
when 65...70 then 0.05444
when 70...75 then 0.06179
else 0.07172
end
end
end
| class GuaranteedIncomeCalculator
TAX_FREE_POT_PORTION = 0.25
TAXABLE_POT_PORTION = 0.75
def initialize(pot:, age:)
self.pot = pot
self.age = age
end
attr_accessor :pot, :age
def estimate
{ income: income_rounded, tax_free_lump_sum: tax_free_lump_sum }
end
private
def tax_free_lump_sum
pot * TAX_FREE_POT_PORTION
end
def income
taxable_amount * annuity_rate
end
def income_rounded
income.round(-2)
end
def taxable_amount
pot * TAXABLE_POT_PORTION
end
# https://pensionwise-guidance.atlassian.net/wiki/pages/viewpage.action?pageId=34237
def annuity_rate
case age
when 55...60 then 0.04389
when 60...65 then 0.04850
when 65...70 then 0.05492
when 70...75 then 0.06199
else 0.07293
end
end
end
|
Rename and refactor, took @m50 suggestion | module SyntaxHelper
def specific_page_vue
" #{controller_name} #{action_name} "
end
def vue_include_tag
javascript_include_tag "https://cdn.jsdelivr.net/npm/vue/dist/vue.js" if Rails.env.development?
end
def rails_version
content_tag :p, Rails.version
end
def vue_on_rails_version
content_tag :p, Vueonrails::VERSION
end
def vue_component(identifier, variable=nil)
concat("<div id=\"#{identifier}\" refs=\"#{identifier}\">".html_safe)
concat("</div>".html_safe)
if(variable != nil)
variable.each {|key, value|
concat("<div id=\"vueonrails-#{key}\" data-#{key}=\'#{value}\'>".html_safe)
concat("</div>".html_safe)
}; nil
end
end
#server side rendering via hypernova
def render_vue(id, name)
render_react_component(id, name: name)
end
end
| module SyntaxHelper
def specific_page_vue
" #{controller_name} #{action_name} "
end
def vue_include_tag
javascript_include_tag "https://cdn.jsdelivr.net/npm/vue/dist/vue.js" if Rails.env.development?
end
def rails_version
content_tag :p, Rails.version
end
def vue_on_rails_version
content_tag :p, Vueonrails::VERSION
end
def vue_component(identifier, variable=nil)
concat("<div id=\"#{identifier}\" refs=\"#{identifier}\">".html_safe)
concat("</div>".html_safe)
if(variable != nil)
variable.each {|key, value|
concat("<div id=\"vueonrails-#{key}\" data-#{key}=\'#{value}\'>".html_safe)
concat("</div>".html_safe)
}; nil
end
end
#server side rendering via hypernova
def render_vue_component(id, data = {})
render_react_component(id, data)
end
end
|
Add .pre for next release | # This file is maintained by a herd of rabid monkeys with Rakes.
module EY
class CloudClient
VERSION = '1.0.13'
end
end
# Please be aware that the monkeys like tho throw poo sometimes.
| # This file is maintained by a herd of rabid monkeys with Rakes.
module EY
class CloudClient
VERSION = '1.0.14.pre'
end
end
# Please be aware that the monkeys like tho throw poo sometimes.
|
Fix email setup bug using wrong session variable | class Administration::EmailSetupsController < ApplicationController
before_filter :only_admins
def show
if OneBody.email_configured?
@domain = OneBody.smtp_config['address']
else
redirect_to new_administration_email_setup_path
end
end
def new
end
def create
secret_api_key = params[:secret_api_key]
if secret_api_key.present?
session[:mailgun_key] = secret_api_key
redirect_to action: :edit
else
redirect_to action: :new
end
end
def edit
if session[:mailgun]
@domains = EmailSetup.new(session[:mailgun_key]).domains
else
redirect_to action: :new
end
end
def update
if params[:domain].present?
setup = EmailSetup.new(session[:mailgun_key])
setup.domain = params[:domain]
if setup.save!
redirect_to action: :show, notice: t('administration.email_setups.edit.success')
else
redirect_to action: :edit, notice: t('administration.email_setups.edit.failure')
end
else
redirect_to action: :edit
end
end
private
def only_admins
return if @logged_in.super_admin?
render text: t('only_admins'), layout: true, status: 401
return false
end
end
| class Administration::EmailSetupsController < ApplicationController
before_filter :only_admins
def show
if OneBody.email_configured?
@domain = OneBody.smtp_config['address']
else
redirect_to new_administration_email_setup_path
end
end
def new
end
def create
secret_api_key = params[:secret_api_key]
if secret_api_key.present?
session[:mailgun_key] = secret_api_key
redirect_to action: :edit
else
redirect_to action: :new
end
end
def edit
if session[:mailgun_key]
@domains = EmailSetup.new(session[:mailgun_key]).domains
else
redirect_to action: :new
end
end
def update
if params[:domain].present?
setup = EmailSetup.new(session[:mailgun_key])
setup.domain = params[:domain]
if setup.save!
redirect_to action: :show, notice: t('administration.email_setups.edit.success')
else
redirect_to action: :edit, notice: t('administration.email_setups.edit.failure')
end
else
redirect_to action: :edit
end
end
private
def only_admins
return if @logged_in.super_admin?
render text: t('only_admins'), layout: true, status: 401
return false
end
end
|
Use class-based caching for queries in EnterpriseInjectionData | module OpenFoodNetwork
class EnterpriseInjectionData
def active_distributor_ids
@active_distributor_ids ||=
Enterprise.distributors_with_active_order_cycles.ready_for_checkout.pluck(:id)
end
def earliest_closing_times
@earliest_closing_times ||= OrderCycle.earliest_closing_times
end
def shipping_method_services
@shipping_method_services ||= Spree::ShippingMethod.services
end
def supplied_taxons
@supplied_taxons ||= Spree::Taxon.supplied_taxons
end
def all_distributed_taxons
@all_distributed_taxons ||= Spree::Taxon.distributed_taxons(:all)
end
def current_distributed_taxons
@current_distributed_taxons ||= Spree::Taxon.distributed_taxons(:current)
end
end
end
| module OpenFoodNetwork
class EnterpriseInjectionData
def active_distributor_ids
@active_distributor_ids ||=
Enterprise.distributors_with_active_order_cycles.ready_for_checkout.pluck(:id)
end
def earliest_closing_times
@earliest_closing_times ||= OrderCycle.earliest_closing_times
end
def shipping_method_services
@shipping_method_services ||= begin
CacheService.cached_data_by_class("shipping_method_services", Spree::ShippingMethod) do
# This result relies on a simple join with DistributorShippingMethod.
# Updated DistributorShippingMethod records touch their associated Spree::ShippingMethod.
Spree::ShippingMethod.services
end
end
end
def supplied_taxons
@supplied_taxons ||= begin
CacheService.cached_data_by_class("supplied_taxons", Spree::Taxon) do
# This result relies on a join with associated supplied products, through the
# class Classification which maps the relationship. Classification records touch
# their associated Spree::Taxon when updated. A Spree::Product's primary_taxon
# is also touched when changed.
Spree::Taxon.supplied_taxons
end
end
end
def all_distributed_taxons
@all_distributed_taxons ||= Spree::Taxon.distributed_taxons(:all)
end
def current_distributed_taxons
@current_distributed_taxons ||= Spree::Taxon.distributed_taxons(:current)
end
end
end
|
Fix Tee Time join bug and delete tee time if leave makes it empty | class UserTeeTimesController < ApplicationController
def create
@user_tee_time = UserTee_time.new
authorize @user_tee_time
@tee_time = TeeTime.find_by_id(params[:user_tee_time][:tee_time_id])
@user = User.find_by_id(params[:user_tee_time][:user_id])
if @tee_time.add_user(@user)
flash[:confirmation] = "Success! You're in"
else
flash[:warning] = "Unable to join"
end
redirect_to tee_time_path(@tee_time)
end
def destroy
tee_time = TeeTime.find_by_id(params[:user_tee_time][:tee_time_id])
@user_tee_time = UserTeeTime.find_by(tee_time_id: params[:user_tee_time][:tee_time_id], user_id: params[:user_tee_time][:user_id])
authorize @user_tee_time
@user_tee_time.destroy
flash[:confirmation] = "Successfully left Tee Time"
redirect_to tee_time_path(tee_time)
end
private
def user_tee_time_params
params.require(:user_tee_time).permit(:tee_time_id, :user_id)
end
end
| class UserTeeTimesController < ApplicationController
def create
@user_tee_time = UserTeeTime.new
authorize @user_tee_time
@tee_time = TeeTime.find_by_id(params[:user_tee_time][:tee_time_id])
@user = User.find_by_id(params[:user_tee_time][:user_id])
if @tee_time.add_user(@user)
flash[:confirmation] = "Success! You're in"
else
flash[:warning] = "Unable to join"
end
redirect_to tee_time_path(@tee_time)
end
def destroy
tee_time = TeeTime.find_by_id(params[:user_tee_time][:tee_time_id])
@user_tee_time = UserTeeTime.find_by(tee_time_id: params[:user_tee_time][:tee_time_id], user_id: params[:user_tee_time][:user_id])
authorize @user_tee_time
@user_tee_time.destroy
if tee_time.users.empty?
flash[:confirmation] = "Successfully left and deleted Tee Time"
tee_time.destroy
redirect_to user_path(current_user)
else
flash[:confirmation] = "Successfully left Tee Time"
redirect_to tee_time_path(tee_time)
end
end
private
def user_tee_time_params
params.require(:user_tee_time).permit(:tee_time_id, :user_id)
end
end
|
Add CocoaPods podspec for 0.1 release. | Pod::Spec.new do |s|
s.name = 'SVProgressHUD'
s.version = '0.1'
s.platform = :ios
s.license = 'MIT'
s.summary = 'A clean and lightweight progress HUD for your iOS app.'
s.homepage = 'http://samvermette.com/199'
s.author = { 'Sam Vermette' => 'samvermette@gmail.com' }
s.source = { :git => 'https://github.com/samvermette/SVProgressHUD.git', :tag => '0.1' }
s.description = 'SVProgressHUD is a clean, lightweight and unobtrusive progress HUD for iOS. ' \
'It’s a simplified and prettified alternative to the popular MBProgressHUD. ' \
'Its fade in/out animations are highly inspired on Lauren Britcher’s HUD in ' \
'Tweetie for iOS. The success and error icons are from Glyphish.'
s.source_files = 'SVProgressHUD/*.{h,m}'
s.clean_paths = 'Demo'
s.framework = 'QuartzCore'
s.resources = 'SVProgressHUD/SVProgressHUD.bundle'
end
| |
Use standard image tag when no value | module TypeStation
class ContentPresenter < BasePresenter
presents :content
def tag(default, options = {})
css_class = options.delete(:class) if options.include?(:class)
cl_image_tag((value.present? ? value['identifier'] : default), options.merge({class: ['ts-editable-image-tag', css_class], data: options}))
end
def link(default, html_options = nil, &block)
css_class = html_options.delete(:class) if html_options.include?(:class)
content_tag(:a, nil, html_options.merge({class: ['ts-editable-link-tag', css_class], href: (value.present? ? cloudinary_url(value['identifier']) : default)}), &block)
end
def value
content
end
end
end
| module TypeStation
class ContentPresenter < BasePresenter
presents :content
def tag(default, options = {})
css_class = options.delete(:class) if options.include?(:class)
if value.present?
cl_image_tag(value['identifier'], options.merge({class: ['ts-editable-image-tag', css_class], data: options}))
else
image_tag(default, options.merge({class: ['ts-editable-image-tag', css_class], data: options}))
end
end
def link(default, html_options = nil, &block)
css_class = html_options.delete(:class) if html_options.include?(:class)
content_tag(:a, nil, html_options.merge({class: ['ts-editable-link-tag', css_class], href: (value.present? ? cloudinary_url(value['identifier']) : default)}), &block)
end
def value
content
end
end
end
|
Correct last migration not to remove the body | class MigrateNotesToEditorsOnEdition < ActiveRecord::Migration
def up
Edition.where('notes_to_editors !=""').each do |edition|
edition.update_attribute :body, "\n##Notes to editors\n\n#{edition.notes_to_editors}"
end
remove_column :editions, :notes_to_editors
end
def down
add_column :editions, :notes_to_editors
end
end
| class MigrateNotesToEditorsOnEdition < ActiveRecord::Migration
def up
Edition.where('notes_to_editors !=""').each do |edition|
edition.update_attribute :body, "#{body}\n\n##Notes to editors\n\n#{edition.notes_to_editors}"
end
remove_column :editions, :notes_to_editors
end
def down
add_column :editions, :notes_to_editors, :text
end
end
|
Use forward slash for paths | describe "sets $VERBOSE to true", :shared => true do
it "sets $VERBOSE to true" do
ruby_exe("fixtures/verbose.rb", :options => @method, :dir => "#{File.dirname(__FILE__)}\\..").chomp.match(/true$/).should_not == nil
end
end
| describe "sets $VERBOSE to true", :shared => true do
it "sets $VERBOSE to true" do
ruby_exe("fixtures/verbose.rb", :options => @method, :dir => "#{File.dirname(__FILE__)}/..").chomp.match(/true$/).should_not == nil
end
end
|
Upgrade VMware Horizon Client to 3.5.2-3151577 to make sure it works properly under El Capitan | cask :v1 => 'vmware-horizon-client' do
version '3.4.0-2769709'
sha256 'df0ed13716d4dbd5dae7dc77f2f29668907860b205f50132b6a1533364d3dd97'
url "https://download3.vmware.com/software/view/viewclients/CART15Q2/VMware-Horizon-Client-#{version}.dmg"
name 'VMware Horizon Client'
homepage 'https://www.vmware.com/'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
app 'VMware Horizon Client.app'
end
| cask :v1 => 'vmware-horizon-client' do
version '3.5.2-3151577'
sha256 '52254a1203706ed8a7700b888f9d88b0754ff053698d21313d4f7683fcfff48c'
url "https://download3.vmware.com/software/view/viewclients/CART15Q4_3/VMware-Horizon-Client-#{version}.dmg"
name 'VMware Horizon Client'
homepage 'https://www.vmware.com/'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
app 'VMware Horizon Client.app'
end
|
Create rake task that copies view files into the generator/template directory for use when updating gem views | # desc "Explaining what the task does"
# task :stylin do
# # Task goes here
# end
| namespace :stylin do
namespace :development do
desc "Copy templates from view directories into template directory"
task :copy_templates_for_generator do
view_path = File.expand_path("../../../app/views", __FILE__)
template_path = File.expand_path("../../generators/templates/views", __FILE__)
FileUtils.rm_r(template_path)
FileUtils.cp_r(view_path, template_path)
end
end
end
|
Configure fuci base with team city server | require 'fuci/team_city/version'
require 'fuci/configurable'
module Fuci
module TeamCity
include Fuci::Configurable
class << self
attr_accessor :host, :username, :password, :default_branch
end
end
end
| require 'fuci/team_city/version'
require 'fuci/configurable'
module Fuci
configure do |fu|
fu.server = Fuci::TeamCity::Server
end
module TeamCity
include Fuci::Configurable
class << self
attr_accessor :host, :username, :password, :default_branch
end
end
end
|
Use data URI as default placeholder | # -*- coding: utf-8 -*-
module Lazyload
module Rails
# Stores runtime configuration information.
#
# Example settings
# Lazyload::Rails.configure do |c|
# c.placeholder = "/public/img/grey.gif"
# end
class Configuration
# The placeholder image to put into the img src attribute
# (default: 1×1 pixel grey gif at
# "http://www.appelsiini.net/projects/lazyload/img/grey.gif").
def placeholder
@placeholder
end
def placeholder=(new_placeholder)
@placeholder = new_placeholder
end
# Set default settings
def initialize
@placeholder = "http://www.appelsiini.net/projects/lazyload/img/grey.gif"
end
end
end
end
| # -*- coding: utf-8 -*-
module Lazyload
module Rails
# Stores runtime configuration information.
#
# Example settings
# Lazyload::Rails.configure do |c|
# c.placeholder = "/public/img/grey.gif"
# end
class Configuration
# The placeholder image to put into the img src attribute
# (default: 1×1 pixel grey gif at
# "http://www.appelsiini.net/projects/lazyload/img/grey.gif").
def placeholder
@placeholder
end
def placeholder=(new_placeholder)
@placeholder = new_placeholder
end
# Set default settings
def initialize
@placeholder = "data:image/gif;base64,R0lGODdhAQABAPAAAMPDwwAAACwAAAAAAQABAAACAkQBADs="
end
end
end
end
|
Access MIME types by correct keys | require 'rails/railtie'
module Transit
module Rails
class Railtie < ::Rails::Railtie
config.before_initialize do
require 'transit/rails/renderer'
require 'action_controller/metal/renderers'
Mime::Type.register "application/transit+json", :transit
Mime::Type.register_alias "application/transit+json", :transit_verbose
Mime::Type.register "application/transit+msgpack", :transit_msgpack
end
config.after_initialize do
ActionController.add_renderer :transit do |obj, options|
Transit::Rails::Renderer.new(obj, options).render
end
end
initializer "transit.configure_rails_initialization" do |app|
require 'transit/rails/reader'
parameter_parsers = { Mime[:TRANSIT] => Transit::Rails::Reader.make_reader(:json),
Mime[:TRANSIT_MSGPACK] => Transit::Rails::Reader.make_reader(:msgpack) }
if ActionDispatch::Request.respond_to?(:parameter_parsers=)
ActionDispatch::Request.parameter_parsers = (ActionDispatch::Request.parameter_parsers || {}).merge(parameter_parsers)
else
app.middleware.swap("ActionDispatch::ParamsParser",
"ActionDispatch::ParamsParser", parameter_parsers)
end
end
end
end
end
| require 'rails/railtie'
module Transit
module Rails
class Railtie < ::Rails::Railtie
config.before_initialize do
require 'transit/rails/renderer'
require 'action_controller/metal/renderers'
Mime::Type.register "application/transit+json", :transit
Mime::Type.register_alias "application/transit+json", :transit_verbose
Mime::Type.register "application/transit+msgpack", :transit_msgpack
end
config.after_initialize do
ActionController.add_renderer :transit do |obj, options|
Transit::Rails::Renderer.new(obj, options).render
end
end
initializer "transit.configure_rails_initialization" do |app|
require 'transit/rails/reader'
parameter_parsers = { Mime[:transit] => Transit::Rails::Reader.make_reader(:json),
Mime[:transit_msgpack] => Transit::Rails::Reader.make_reader(:msgpack) }
if ActionDispatch::Request.respond_to?(:parameter_parsers=)
ActionDispatch::Request.parameter_parsers = (ActionDispatch::Request.parameter_parsers || {}).merge(parameter_parsers)
else
app.middleware.swap("ActionDispatch::ParamsParser",
"ActionDispatch::ParamsParser", parameter_parsers)
end
end
end
end
end
|
Fix feature spec for visiting asciicast page | require 'spec_helper'
feature "Asciicast lists" do
let!(:asciicast) { load_asciicast(1) }
scenario 'Visiting all' do
visit browse_path
expect(page).to have_content(/All Asciicasts/i)
expect_browse_links
expect(page).to have_link("##{asciicast.id}")
expect(page).to have_selector('.supplimental .play-button')
end
scenario 'Visiting popular' do
visit popular_path
expect(page).to have_content(/Popular Asciicasts/i)
expect_browse_links
expect(page).to have_link("##{asciicast.id}")
expect(page).to have_selector('.supplimental .play-button')
end
end
| require 'spec_helper'
feature "Asciicast lists" do
let!(:asciicast) { load_asciicast(1) }
scenario 'Visiting all' do
visit browse_path
expect(page).to have_content(/All Asciicasts/i)
expect_browse_links
expect(page).to have_link("##{asciicast.id}")
expect(page).to have_selector('.supplimental .play-button')
end
scenario 'Visiting popular' do
visit asciicast_path(asciicast)
visit popular_path
expect(page).to have_content(/Popular Asciicasts/i)
expect_browse_links
expect(page).to have_link("##{asciicast.id}")
expect(page).to have_selector('.supplimental .play-button')
end
end
|
Load current_network in an ApplicationController before_filter | class ApplicationController < ActionController::Base
include HoptoadNotifier::Catcher
filter_parameter_logging :password, :password_confirmation, :credit_card_number
helper :all # include all helpers, all the time
include AuthenticatedSystem
include SslRequirement
# cache_sweeper :home_sweeper, :except => [:index, :show]
before_filter :can_create?, :only => [:new, :create]
before_filter :can_edit?, :only => [:edit, :update, :destroy]
map_resource :profile, :singleton => true, :class => "User", :find => :current_user
protect_from_forgery
def current_network
subdomain = current_subdomain.downcase if current_subdomain
@current_network ||= Network.find_by_name(subdomain)
end
protected
def login_cookies
create_current_login_cookie
update_balance_cookie
end
def create_current_login_cookie
cookies[:current_user_full_name] = current_user.full_name
end
def can_create?
true
end
def can_edit?
true
end
def update_balance_cookie
cookies[:balance_text] = render_to_string(:partial => 'shared/balance')
end
end
| class ApplicationController < ActionController::Base
include HoptoadNotifier::Catcher
filter_parameter_logging :password, :password_confirmation, :credit_card_number
helper :all # include all helpers, all the time
include AuthenticatedSystem
include SslRequirement
# cache_sweeper :home_sweeper, :except => [:index, :show]
before_filter :can_create?, :only => [:new, :create]
before_filter :can_edit?, :only => [:edit, :update, :destroy]
before_filter :current_network
map_resource :profile, :singleton => true, :class => "User", :find => :current_user
protect_from_forgery
def current_network
subdomain = current_subdomain.downcase if current_subdomain
@current_network ||= Network.find_by_name(subdomain)
end
protected
def login_cookies
create_current_login_cookie
update_balance_cookie
end
def create_current_login_cookie
cookies[:current_user_full_name] = current_user.full_name
end
def can_create?
true
end
def can_edit?
true
end
def update_balance_cookie
cookies[:balance_text] = render_to_string(:partial => 'shared/balance')
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.