Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Create Connection's scope only once. | module Alf
class Connection
#
# Defines the internal, private contract seen by Alf's internals
# on connections.
#
module Internal
# The connection specification
attr_reader :conn_spec
# Creates an connection instance, wired to the specified folder.
#
# @param [String] folder path to the folder to use as dataset source.
def initialize(conn_spec, scope_helpers = [ Lang::Functional ])
@scope_helpers = scope_helpers
@conn_spec = conn_spec
end
# Returns an optimizer instance
def optimizer
Optimizer.new(self).
register(Optimizer::Restrict.new, Operator::Relational::Restrict)
end
# Returns a compiler instance
def compiler
Engine::Compiler.new(self)
end
# Returns a low-level Iterator for a given named variable
def iterator(name)
raise NotImplementedError, "Unable to serve `#{name}` in Connection.iterator"
end
# Returns the heading of a given named variable
def heading(name)
raise NotSupportedError, "Unable to infer heading for `#{name}`"
end
# Returns the keys of a given named variable
def keys(name)
raise NotSupportedError, "Unable to infer keys for `#{name}`"
end
# Returns an evaluation scope.
#
# @return [Scope] a scope instance on the global variables of the underlying database.
def scope
Lang::Lispy.new(self, @scope_helpers)
end
end # module Internal
end # class Connection
end # module Alf | module Alf
class Connection
#
# Defines the internal, private contract seen by Alf's internals
# on connections.
#
module Internal
# The connection specification
attr_reader :conn_spec
# The scope that defines the global database scope
attr_reader :scope
# Creates an connection instance, wired to the specified folder.
#
# @param [String] folder path to the folder to use as dataset source.
def initialize(conn_spec, scope_helpers = [ Lang::Functional ])
@conn_spec = conn_spec
@scope = Lang::Lispy.new(self, scope_helpers)
end
# Returns an optimizer instance
def optimizer
Optimizer.new(self).
register(Optimizer::Restrict.new, Operator::Relational::Restrict)
end
# Returns a compiler instance
def compiler
Engine::Compiler.new(self)
end
# Returns a low-level Iterator for a given named variable
def iterator(name)
raise NotImplementedError, "Unable to serve `#{name}` in Connection.iterator"
end
# Returns the heading of a given named variable
def heading(name)
raise NotSupportedError, "Unable to infer heading for `#{name}`"
end
# Returns the keys of a given named variable
def keys(name)
raise NotSupportedError, "Unable to infer keys for `#{name}`"
end
# Returns a native schema instance
def native_schema
raise NotSupportedError, "Unable to infer native schema on `#{self}`"
end
end # module Internal
end # class Connection
end # module Alf |
Set default rate expiration hour for amazon | require_dependency 'spree/calculator'
module Spree::Calculator::Shipping::Amazon
class Base < Spree::ShippingCalculator
def compute_package(package)
provider.estimate_cost(package, service)
end
def estimate_delivery_window(package, ship_date)
provider.estimate_delivery_window(package, service, ship_date)
end
def available?(package)
provider.can_fulfill?(package)
end
def fulfillment_provider
provider
end
def service
raise NotImplementedError, "Please implement 'service' in your calculator: #{self.class.name}"
end
protected
def self.description
raise NotImplementedError, "Please implement 'description' in your calculator: #{self.class.name}"
end
private
def provider
Spree::Fulfillment::Config.amazon_provider
end
end
end | require_dependency 'spree/calculator'
module Spree::Calculator::Shipping::Amazon
class Base < Spree::ShippingCalculator
def compute_package(package)
provider.estimate_cost(package, service)
end
def estimate_delivery_window(package, ship_date)
provider.estimate_delivery_window(package, service, ship_date)
end
def available?(package)
provider.can_fulfill?(package)
end
def fulfillment_provider
provider
end
def service
raise NotImplementedError, "Please implement 'service' in your calculator: #{self.class.name}"
end
def rate_daily_expiration_hour
if respond_to?(:preferred_rate_daily_expiration_hour) && preferred_rate_daily_expiration_hour
preferred_rate_daily_expiration_hour
else
11
end
end
protected
def self.description
raise NotImplementedError, "Please implement 'description' in your calculator: #{self.class.name}"
end
private
def provider
Spree::Fulfillment::Config.amazon_provider
end
end
end |
Fix typo in netconsole::install test with missing } | require 'spec_helper'
describe 'netconsole::install' do
context 'with defaults for all parameters' do
let (:facts){
{
:puppetversion => ENV['PUPPET_VERSION'],
:facterversion => ENV['FACTER_VERSION'],
:osfamily => 'redhat',
:operatingsystem => 'centos',
:operatingsystemrelease => '6.6',
:concat_basedir => '/dnf',
}
}
it { should contain_class('netconsole::install') }
it { should contain_package('netconsole')
} ) }
end
context 'with settings for all parameters' do
let (:facts){
{
:puppetversion => ENV['PUPPET_VERSION'],
:facterversion => ENV['FACTER_VERSION'],
:osfamily => 'redhat',
:operatingsystem => 'centos',
:operatingsystemrelease => '6.6',
:concat_basedir => '/dnf',
}
}
let(:params) { {
:package_list => 'foo',
} }
it { should contain_class('netconsole::install') }
it { should contain_package('foo')
end
end
| require 'spec_helper'
describe 'netconsole::install' do
context 'with defaults for all parameters' do
let (:facts){
{
:puppetversion => ENV['PUPPET_VERSION'],
:facterversion => ENV['FACTER_VERSION'],
:osfamily => 'redhat',
:operatingsystem => 'centos',
:operatingsystemrelease => '6.6',
:concat_basedir => '/dnf',
}
}
it { should contain_class('netconsole::install') }
it { should contain_package('netconsole')
} ) }
end
context 'with settings for all parameters' do
let (:facts){
{
:puppetversion => ENV['PUPPET_VERSION'],
:facterversion => ENV['FACTER_VERSION'],
:osfamily => 'redhat',
:operatingsystem => 'centos',
:operatingsystemrelease => '6.6',
:concat_basedir => '/dnf',
}
}
let(:params) { {
:package_list => 'foo',
} }
it { should contain_class('netconsole::install') }
it { should contain_package('foo') }
end
end
|
Remove timestamps and created_by methods | module Georgia
class ApplicationDecorator < Draper::Decorator
delegate_all
%w(created_at updated_at).each do |timestamp|
define_method("pretty_#{timestamp}") { model.send(timestamp).strftime('%F') }
end
def created_by_name
return 'unknown' unless model and model.created_by
"#{model.created_by.name} (#{pretty_created_at})"
end
def updated_by_name
return 'unknown' unless model and model.updated_by
"#{model.updated_by.name} (#{pretty_updated_at})"
end
end
end | module Georgia
class ApplicationDecorator < Draper::Decorator
delegate_all
end
end |
Remove hide_action as it is not supported in Rails 5 | module HighVoltage::StaticPage
extend ActiveSupport::Concern
included do
layout ->(_) { HighVoltage.layout }
rescue_from ActionView::MissingTemplate do |exception|
if exception.message =~ %r{Missing template #{page_finder.content_path}}
invalid_page
else
raise exception
end
end
rescue_from HighVoltage::InvalidPageIdError, with: :invalid_page
hide_action :current_page, :page_finder, :page_finder_factory
end
def show
render template: current_page
end
def current_page
page_finder.find
end
def page_finder
page_finder_factory.new(params[:id])
end
def page_finder_factory
HighVoltage::PageFinder
end
def invalid_page
raise ActionController::RoutingError, "No such page: #{params[:id]}"
end
end
| module HighVoltage::StaticPage
extend ActiveSupport::Concern
included do
layout ->(_) { HighVoltage.layout }
rescue_from ActionView::MissingTemplate do |exception|
if exception.message =~ %r{Missing template #{page_finder.content_path}}
invalid_page
else
raise exception
end
end
rescue_from HighVoltage::InvalidPageIdError, with: :invalid_page
end
def show
render template: current_page
end
def invalid_page
raise ActionController::RoutingError, "No such page: #{params[:id]}"
end
private
def current_page
page_finder.find
end
def page_finder
page_finder_factory.new(params[:id])
end
def page_finder_factory
HighVoltage::PageFinder
end
end
|
Update little cms to 1.19 | require 'formula'
class LittleCms <Formula
url 'http://www.littlecms.com/lcms-1.18a.tar.gz'
homepage 'http://www.littlecms.com/'
md5 'f4abfe1c57ea3f633c2e9d034e74e3e8'
def install
system "./configure", "--prefix=#{prefix}", "--disable-debug"
system "make install"
end
end
| require 'formula'
class LittleCms <Formula
url 'http://www.littlecms.com/lcms-1.19.tar.gz'
homepage 'http://www.littlecms.com/'
md5 '8af94611baf20d9646c7c2c285859818'
aka 'lcms'
def install
system "./configure", "--prefix=#{prefix}", "--disable-debug"
system "make install"
end
end
|
Add Gem.clear_paths to server minitest so pg gem is loaded correctly on first converge | #
# Copyright 2012, 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.
#
require File.expand_path('../support/helpers', __FILE__)
describe 'postgresql::server' do
include Helpers::Postgresql
it 'installs the postgresql server packages' do
node['postgresql']['server']['packages'].each do |pkg|
package(pkg).must_be_installed
end
end
it 'runs the postgresql service' do
service((node['postgresql']['server']['service_name'] || 'postgresql')).must_be_running
end
it 'can connect to postgresql' do
require 'pg'
conn = PG::Connection.new(
:host => 'localhost',
:port => '5432',
:password => node['postgresql']['password']['postgres'],
:user => "postgres"
)
assert_match(/localhost/, conn.host)
end
end
| #
# Copyright 2012, 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.
#
require File.expand_path('../support/helpers', __FILE__)
describe 'postgresql::server' do
include Helpers::Postgresql
it 'installs the postgresql server packages' do
node['postgresql']['server']['packages'].each do |pkg|
package(pkg).must_be_installed
end
end
it 'runs the postgresql service' do
service((node['postgresql']['server']['service_name'] || 'postgresql')).must_be_running
end
it 'can connect to postgresql' do
Gem.clear_paths
require 'pg'
conn = PG::Connection.new(
:host => 'localhost',
:port => '5432',
:password => node['postgresql']['password']['postgres'],
:user => "postgres"
)
assert_match(/localhost/, conn.host)
end
end
|
Set example description for HTTP routes. | module Lita
module RSpec
module Matchers
# Used to complete an HTTP routing test chain.
class HTTPRouteMatcher
def initialize(context, http_method, path, invert: false)
@context = context
@http_method = http_method
@path = path
@method = invert ? :not_to : :to
end
# Sets an expectation that an HTTP route will or will not be triggered,
# then makes an HTTP request against the app with the HTTP request
# method and path originally provided.
# @param route [Symbol] The name of the method that should or should not
# be triggered.
# @return [void]
def to(route)
m = @method
h = @http_method
p = @path
@context.instance_eval do
expect_any_instance_of(described_class).public_send(m, receive(route))
env = Rack::MockRequest.env_for(p, method: h)
robot.app.call(env)
end
end
end
end
end
end
| module Lita
module RSpec
module Matchers
# Used to complete an HTTP routing test chain.
class HTTPRouteMatcher
attr_accessor :context, :http_method, :inverted, :path
attr_reader :expected_route
alias_method :inverted?, :inverted
def initialize(context, http_method, path, invert: false)
self.context = context
self.http_method = http_method
self.path = path
self.inverted = invert
set_description
end
# Sets an expectation that an HTTP route will or will not be triggered,
# then makes an HTTP request against the app with the HTTP request
# method and path originally provided.
# @param route [Symbol] The name of the method that should or should not
# be triggered.
# @return [void]
def to(route)
self.expected_route = route
m = method
h = http_method
p = path
context.instance_eval do
expect_any_instance_of(described_class).public_send(m, receive(route))
env = Rack::MockRequest.env_for(p, method: h)
robot.app.call(env)
end
end
private
def description_prefix
if inverted?
"doesn't route"
else
"routes"
end
end
def expected_route=(route)
@expected_route = route
set_description
end
def method
if inverted?
:not_to
else
:to
end
end
def set_description
description = "#{description_prefix} #{http_method.upcase} #{path}"
description << " to :#{expected_route}" if expected_route
::RSpec.current_example.metadata[:description] = description
end
end
end
end
end
|
Update session to 7 day expiry | # Be sure to restart your server when you modify this file.
Rails.application.config.session_store ActionDispatch::Session::CacheStore, :expire_after => 1.day
| # Be sure to restart your server when you modify this file.
Rails.application.config.session_store ActionDispatch::Session::CacheStore, :expire_after => 7.day
|
Add a way to retrieve all transaction splits for a user | class TransactionSplit < ActiveRecord::Base
belongs_to :transaction_record
has_many :pie_piece_transaction_splits
has_many :pie_pieces, through: :pie_piece_transaction_splits
end
| class TransactionSplit < ActiveRecord::Base
belongs_to :transaction_record
has_many :pie_piece_transaction_splits
has_many :pie_pieces, through: :pie_piece_transaction_splits
scope :user, ->(id) {
joins(:transaction_record)
.where('transaction_records.user_id = ?', id)
}
end
|
Remove attempt to eager load InventoryUnitBuilder | module Spree
module Stock
class InventoryUnitBuilder
def initialize(order)
@order = order
end
def units
@order.line_items.flat_map do |line_item|
line_item.quantity.times.map do |i|
@order.inventory_units.includes(
variant: {
product: {
shipping_category: {
shipping_methods: [:calculator, { zones: :zone_members }]
}
}
}
).build(
pending: true,
variant: line_item.variant,
line_item: line_item,
order: @order
)
end
end
end
end
end
end
| module Spree
module Stock
class InventoryUnitBuilder
def initialize(order)
@order = order
end
def units
@order.line_items.flat_map do |line_item|
line_item.quantity.times.map do |i|
@order.inventory_units.build(
pending: true,
variant: line_item.variant,
line_item: line_item,
order: @order
)
end
end
end
end
end
end
|
Use the Directory number as outbound CallerID | require 'sinatra'
require 'twilio-ruby'
require './phonebook'
require './directory_services'
# A populated Phonebook, suitable for searching
# @return [Phonebook]
def phonebook
@phonebook ||= Phonebook.new.tap do |phonebook|
DirectoryService.getDirectory(ENV['YP_PHONEBOOK_URI']).each do |name, phone|
phonebook.add(name, phone)
end
end
end
get '/' do
'YellowPages'
end
post '/twilio/incoming' do
Twilio::TwiML::Response.new do |r|
r.Gather(action: '/twilio/search', finishOnKey: '#', numDigits: 3) do
r.Say('Enter the first three letters of a name.', voice: 'woman')
end
end.text
end
post '/twilio/search' do
matches = phonebook.dialpad_search(params['Digits'])
if matches.empty?
Twilio::TwiML::Response.new do |r|
r.Say 'No matches found.'
r.Hangup
end.text
else
name, number = matches.first
Twilio::TwiML::Response.new do |r|
r.Say "Connecting to #{name}"
r.Dial { r.Number number }
end.text
end
end
| require 'sinatra'
require 'twilio-ruby'
require './phonebook'
require './directory_services'
# A populated Phonebook, suitable for searching
# @return [Phonebook]
def phonebook
@phonebook ||= Phonebook.new.tap do |phonebook|
DirectoryService.getDirectory(ENV['YP_PHONEBOOK_URI']).each do |name, phone|
phonebook.add(name, phone)
end
end
end
get '/' do
'YellowPages'
end
post '/twilio/incoming' do
Twilio::TwiML::Response.new do |r|
r.Gather(action: '/twilio/search', finishOnKey: '#', numDigits: 3) do
r.Say('Enter the first three letters of a name.', voice: 'woman')
end
end.text
end
post '/twilio/search' do
matches = phonebook.dialpad_search(params['Digits'])
if matches.empty?
Twilio::TwiML::Response.new do |r|
r.Say 'No matches found.'
r.Hangup
end.text
else
name, number = matches.first
Twilio::TwiML::Response.new do |r|
r.Say "Connecting to #{name}"
r.Dial(callerId: params['To']) { r.Number number }
end.text
end
end
|
Update string to trigger changelog check | module Fastlane
module Helper
class ChangelogHelper
# class methods that you define here become available in your action
# as `Helper::ChangelogHelper.your_method`
#
def self.show_message
UI.message("Hello from the changelog plugin helper!")
end
def self.get_line_separator(file_path)
f = File.open(file_path)
enum = f.each_char
c = enum.next
loop do
case c[/\r|\n/]
when "\n" then break
when "\r"
c << "\n" if enum.peek == "\n"
break
end
c = enum.next
end
c[0][/\r|\n/] ? c : "\n"
end
end
end
end
| module Fastlane
module Helper
class ChangelogHelper
# class methods that you define here become available in your action
# as `Helper::ChangelogHelper.your_method`
#
def self.show_message
UI.message("Hello from the changelog plugin helper")
end
def self.get_line_separator(file_path)
f = File.open(file_path)
enum = f.each_char
c = enum.next
loop do
case c[/\r|\n/]
when "\n" then break
when "\r"
c << "\n" if enum.peek == "\n"
break
end
c = enum.next
end
c[0][/\r|\n/] ? c : "\n"
end
end
end
end
|
Add on method in handler | require 'ruboty/Fizzbuzz/actions/fizzbuzz'
module Ruboty
module Handler
class Fizzbuzz < Base
end
end
end
| require 'ruboty/Fizzbuzz/actions/fizzbuzz'
module Ruboty
module Handler
class Fizzbuzz < Base
on /fizzbuzz (?<number>.*?)\z/, name: 'fizzbuzz', description: 'output fizzbuzz result'
end
end
end
|
Use template path in users/index view spec | require 'spec_helper'
describe "/users" do
fixtures :users, :events
it "should not include admin column by default" do
assigns[:users] = [users(:aaron), users(:quentin)]
render '/users/index'
response.should_not have_selector(".admin", :content => "admin")
end
it "should include admin column when admin is logged in" do
login_as(:aaron)
assigns[:users] = [users(:aaron), users(:quentin)]
render '/users/index'
response.should have_selector(".admin", :content => "admin")
end
end
| require 'spec_helper'
describe "users/index.html.erb" do
fixtures :users, :events
it "should not include admin column by default" do
assigns[:users] = [users(:aaron), users(:quentin)]
render '/users/index'
response.should_not have_selector(".admin", :content => "admin")
end
it "should include admin column when admin is logged in" do
login_as(:aaron)
assigns[:users] = [users(:aaron), users(:quentin)]
render '/users/index'
response.should have_selector(".admin", :content => "admin")
end
end
|
Add a spec for explicit relationship joining | require 'spec_helper'
describe 'Relationship - One To One - Explicit Loading' do
before(:all) do
setup_db
insert_user 1, 'John', 18
insert_user 2, 'Jane', 21
insert_user 3, 'Piotr', 29
insert_address 1, 3, 'Street 1/2', 'Krakow', '12345'
insert_address 2, 2, 'Street 1/2', 'Chicago', '54321'
insert_address 3, 1, 'Street 2/4', 'Boston', '67890'
class Address
attr_reader :id, :street, :city, :zipcode
def initialize(attributes)
@id, @street, @city, @zipcode = attributes.values_at(
:id, :street, :city, :zipcode)
end
class Mapper < DataMapper::Mapper::VeritasMapper
map :id, :type => Integer, :key => true
map :user_id, :type => Integer
map :street, :type => String
map :city, :type => String
map :zipcode, :type => String
model Address
relation_name :addresses
repository :postgres
end
end
class User
attr_reader :id, :name, :age, :address
def initialize(attributes)
@id, @name, @age = attributes.values_at(:id, :name, :age)
@address = attributes[:address]
end
class Mapper < DataMapper::Mapper::VeritasMapper
map :id, :type => Integer, :key => true
map :name, :type => String, :to => :username
map :age, :type => Integer
model User
relation_name :users
repository :postgres
end
end
end
let(:user_mapper) do
DataMapper[User]
end
let(:address_mapper) do
DataMapper[Address]
end
it 'loads parent and then child' do
user = user_mapper.to_a.last
address = address_mapper.join(user_mapper.rename(:id => :user_id)).first
address.should be_instance_of(Address)
address.id.should eql(1)
address.city.should eql('Krakow')
end
end
| |
Add migration: Create track_identities table | # frozen_string_literal: true
class CreateTrackIdentities < ActiveRecord::Migration[5.1]
def change
create_table :track_identities, id: :uuid, default: "uuid_generate_v4()" do |t|
t.string :name, null: false
t.string :artist_name, null: false
t.index [:name]
t.index [:name, :artist_name], unique: true
end
add_column :tracks, :identity_id, :uuid
add_index :tracks, :identity_id
end
end
| |
Add wait for what we're actually waiting for | # encoding: utf-8
require_relative 'admin_page.rb'
class ItemTypes < AdminPage
def visit
@browser.goto intranet(:item_types)
self
end
def show_all
@browser.select_list(:name => "table_item_type_length").select_value("-1")
self
end
def create(code, desc)
@browser.execute_script("document.getElementById('newitemtype').click()")
Watir::Wait.until(BROWSER_WAIT_TIMEOUT) {
@browser.h3(:text => "Add item type").present?
}
form = @browser.form(:id => "itemtypeentry")
form.text_field(:id => "itemtype").set code
form.text_field(:id => "description").set desc
form.submit
self
end
def delete(code)
item_type_table.rows.each do |row|
if row.text.include?(code)
row.link(:href => /op=delete_confirm/).click
@browser.input(:value => "Delete this Item Type").click
break
end
end
end
def exists(code, desc)
text = item_type_table.text
text.should include(code)
text.should include(desc)
self
end
def item_type_table
table = @browser.table(:id => "table_item_type")
table.wait_until_present
table
end
end | # encoding: utf-8
require_relative 'admin_page.rb'
class ItemTypes < AdminPage
def visit
@browser.goto intranet(:item_types)
self
end
def show_all
@browser.select_list(:name => "table_item_type_length").select_value("-1")
self
end
def create(code, desc)
@browser.execute_script("document.getElementById('newitemtype').click()")
Watir::Wait.until {
@browser.form(:id => "itemtypeentry").text_field(:id => "itemtype").present?
}
form = @browser.form(:id => "itemtypeentry")
form.text_field(:id => "itemtype").set code
form.text_field(:id => "description").set desc
form.submit
self
end
def delete(code)
item_type_table.rows.each do |row|
if row.text.include?(code)
row.link(:href => /op=delete_confirm/).click
@browser.input(:value => "Delete this Item Type").click
break
end
end
end
def exists(code, desc)
text = item_type_table.text
text.should include(code)
text.should include(desc)
self
end
def item_type_table
table = @browser.table(:id => "table_item_type")
table.wait_until_present
table
end
end |
Fix data migrations for role labels. | class UpdateCoreRoleLabels < ActiveRecord::DataMigration
def up
Role.where(name: [:user, :manager]).update_all(label: 'Staff')
Role.find_or_create_by(name: :super_manager).update(label: 'Manager', privilege: false, role_parent_id: nil)
end
def down
Role.find_by(name: :super_manager).update(label: nil, privilege: true)
Role.where(name: [:user, :manager]).update_all(label: nil)
end
end | class UpdateCoreRoleLabels < ActiveRecord::DataMigration
def up
Role.where(name: [:user, :manager]).update_all(label: 'Staff')
Role.find_or_initialize_by(name: :super_manager).update(label: 'Manager', privilege: false, role_parent_id: nil)
end
def down
Role.find_by(name: :super_manager).update(label: nil, privilege: true)
Role.where(name: [:user, :manager]).update_all(label: nil)
end
end |
Make sure the user exists | class RevertDetailedGuidesToDraft < ActiveRecord::Migration
def up
user = User.find_by_name("Automatic Data Importer")
PaperTrail.enabled = false
data.each do |row|
guide = Document.at_slug(DetailedGuide, row[0])
next unless guide
latest_edition = guide.latest_edition
next unless latest_edition
all_editions_including_deleted = Edition.unscoped.where(document_id: guide)
other_editions = all_editions_including_deleted - [latest_edition]
other_editions.each do |old_edition|
EditionAuthor.where(edition_id: old_edition).update_all(edition_id: latest_edition)
old_edition.destroy
end
FactCheckRequest.where(edition_id: other_editions).update_all(edition_id: latest_edition)
Version.where(item_id: other_editions).update_all(item_id: latest_edition)
latest_edition.editorial_remarks.create!(author: user, body: "Reset to draft")
latest_edition.update_attributes(state: "draft")
end
end
def down
end
def data
CSV.read(
File.dirname(__FILE__) + '/20121008103408_revert_detailed_guides_to_draft.csv',
headers: false)
end
end
| class RevertDetailedGuidesToDraft < ActiveRecord::Migration
def up
user = User.find_by_name("Automatic Data Importer")
return unless user
PaperTrail.enabled = false
data.each do |row|
guide = Document.at_slug(DetailedGuide, row[0])
next unless guide
latest_edition = guide.latest_edition
next unless latest_edition
all_editions_including_deleted = Edition.unscoped.where(document_id: guide)
other_editions = all_editions_including_deleted - [latest_edition]
other_editions.each do |old_edition|
EditionAuthor.where(edition_id: old_edition).update_all(edition_id: latest_edition)
old_edition.destroy
end
FactCheckRequest.where(edition_id: other_editions).update_all(edition_id: latest_edition)
Version.where(item_id: other_editions).update_all(item_id: latest_edition)
latest_edition.editorial_remarks.create!(author: user, body: "Reset to draft")
latest_edition.update_attributes(state: "draft")
end
end
def down
end
def data
CSV.read(
File.dirname(__FILE__) + '/20121008103408_revert_detailed_guides_to_draft.csv',
headers: false)
end
end
|
Fix insane tests using relative paths | require 'rubygems'
require 'rspec'
require 'provision'
require 'provision/vm/virsh'
require 'provision/core/machine_spec'
describe Provision::VM::Virsh do
before do
end
it 'creates a virt machine xml file in libvirt' do
machine_spec = Provision::Core::MachineSpec.new(
:hostname=>"vmx1",
:disk_dir=>"build/",
:vnc_port=>9005,
:ram => "1G",
:interfaces => [{:type=>"bridge",:name=>"br0"}, {:type=>"network", :name=>"provnat0"}],
:images_dir => "build",
:libvirt_dir => "build"
)
virt_manager = Provision::VM::Virsh.new()
virt_manager.define_vm(machine_spec)
File.exist?("build/vmx1.xml").should eql(true)
IO.read("build/vmx1.xml").should match("vmx1")
IO.read("build/vmx1.xml").should match("1G")
IO.read("build/vmx1.xml").should match("build/vmx1.img")
end
end
| require 'rubygems'
require 'rspec'
require 'provision'
require 'provision/vm/virsh'
require 'provision/core/machine_spec'
require 'tmpdir'
describe Provision::VM::Virsh do
before do
end
it 'creates a virt machine xml file in libvirt' do
d = Dir.mktmpdir
machine_spec = Provision::Core::MachineSpec.new(
:hostname=>"vmx1",
:disk_dir=>"build/",
:vnc_port=>9005,
:ram => "1G",
:interfaces => [{:type=>"bridge",:name=>"br0"}, {:type=>"network", :name=>"provnat0"}],
:images_dir => "build",
:libvirt_dir => d
)
virt_manager = Provision::VM::Virsh.new()
virt_manager.define_vm(machine_spec)
File.exist?("#{d}/vmx1.xml").should eql(true)
IO.read("#{d}/vmx1.xml").should match("vmx1")
IO.read("#{d}/vmx1.xml").should match("1G")
IO.read("#{d}/vmx1.xml").should match("build/vmx1.img")
end
end
|
Remove private and reformat tiles | class Scrabble
attr_reader :word
def initialize(word)
@word = word.to_s.strip.downcase
end
def score
word.chars.sum { |letter| TILE_POINTS[letter] }
end
private
def self.score(word)
new(word).score
end
TILE_POINTS = {
'a' => 1,
'b' => 3,
'c' => 3,
'd' => 2,
'e' => 1,
'f' => 4,
'g' => 2,
'h' => 4,
'i' => 1,
'j' => 8,
'k' => 5,
'l' => 1,
'm' => 3,
'n' => 1,
'o' => 1,
'p' => 3,
'q' => 10,
'r' => 1,
's' => 1,
't' => 1,
'u' => 1,
'v' => 4,
'w' => 4,
'x' => 8,
'y' => 4,
'z' => 10
}
end
| class Scrabble
attr_reader :word
def initialize(word)
@word = word.to_s.strip.upcase
end
def score
word.chars.sum { |letter| TILE_POINTS[letter] }
end
def self.score(word)
new(word).score
end
TILE_POINTS = {
'A' => 1, 'G' => 2, 'M' => 3, 'S' => 1, 'Y' => 4,
'B' => 3, 'H' => 4, 'N' => 1, 'T' => 1, 'Z' => 10,
'C' => 3, 'I' => 1, 'O' => 1, 'U' => 1,
'D' => 2, 'J' => 8, 'P' => 3, 'V' => 4,
'E' => 1, 'K' => 5, 'Q' => 10, 'W' => 4,
'F' => 4, 'L' => 1, 'R' => 1, 'X' => 8,
}
end
|
Convert version test to a unit test instead of a spec | require_relative '../../../test_helper'
describe OmniAuth::OpenIDConnect::VERSION do
it "must be defined" do
OmniAuth::OpenIDConnect::VERSION.wont_be_nil
end
end
| require_relative '../../../test_helper'
class OmniAuth::OpenIDConnect::VersionTest < MiniTest::Test
def test_version_defined
refute_nil OmniAuth::OpenIDConnect::VERSION
end
end
|
Include fontawesome on the list of assets to be precompiled by the asset pipeline | module Spree
module Backend
class Engine < ::Rails::Engine
config.middleware.use "Spree::Backend::Middleware::SeoAssist"
initializer "spree.backend.environment", :before => :load_config_initializers do |app|
Spree::Backend::Config = Spree::BackendConfiguration.new
end
# filter sensitive information during logging
initializer "spree.params.filter" do |app|
app.config.filter_parameters += [:password, :password_confirmation, :number]
end
# sets the manifests / assets to be precompiled, even when initialize_on_precompile is false
initializer "spree.assets.precompile", :group => :all do |app|
app.config.assets.precompile += %w[
spree/backend/all*
spree/backend/orders/edit_form.js
spree/backend/address_states.js
jqPlot/excanvas.min.js
spree/backend/images/new.js
jquery.jstree/themes/apple/*
]
end
end
end
end
| module Spree
module Backend
class Engine < ::Rails::Engine
config.middleware.use "Spree::Backend::Middleware::SeoAssist"
initializer "spree.backend.environment", :before => :load_config_initializers do |app|
Spree::Backend::Config = Spree::BackendConfiguration.new
end
# filter sensitive information during logging
initializer "spree.params.filter" do |app|
app.config.filter_parameters += [:password, :password_confirmation, :number]
end
# sets the manifests / assets to be precompiled, even when initialize_on_precompile is false
initializer "spree.assets.precompile", :group => :all do |app|
app.config.assets.precompile += %w[
spree/backend/all*
spree/backend/orders/edit_form.js
spree/backend/address_states.js
jqPlot/excanvas.min.js
spree/backend/images/new.js
jquery.jstree/themes/apple/*
fontawesome-webfont*
]
end
end
end
end
|
Validate presence of category and data attribute | class Event < ActiveRecord::Base
belongs_to :user, polymorphic: true
belongs_to :exercise
belongs_to :file
end
| class Event < ActiveRecord::Base
belongs_to :user, polymorphic: true
belongs_to :exercise
belongs_to :file
validates :category, presence: true
validates :data, presence: true
end
|
Move secret token to an environment variable | # Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
Marblerun::Application.config.secret_token = '27685cb6fe0e341cadc051456952b33b19a4e17c15fb6275af56b4958c918707ab20d814d942dc6447d32cc03bf6d20e573a2228427534524368b5666a757780'
| # Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
Marblerun::Application.config.secret_token = ENV.fetch('SECRET_TOKEN')
|
Remove active_model dependency from controller | require "active_model"
class CoronavirusLandingPageController < ApplicationController
slimmer_template "gem_layout_full_width"
def show
@statistics = FetchCoronavirusStatisticsService.call
if @statistics
set_expiry content_item.max_age, public_cache: content_item.public_cache
else
logger.warn "Serving /coronavirus without statistics"
set_expiry 30.seconds
end
breadcrumbs = [{ title: t("shared.breadcrumbs_home"), url: "/", is_page_parent: true }]
title = {
text: presenter.page_header,
}
render "show",
locals: {
breadcrumbs: breadcrumbs,
title: title,
details: presenter,
special_announcement: special_announcement,
}
end
private
def set_slimmer_template
set_gem_layout_full_width
end
def content_item
@content_item ||= ContentItem.find!(request.path)
end
def presenter
@presenter ||= CoronavirusLandingPagePresenter.new(content_item.to_hash, params[:nation])
end
def special_announcement
@special_announcement ||= SpecialAnnouncementPresenter.new(content_item.to_hash)
end
end
| class CoronavirusLandingPageController < ApplicationController
slimmer_template "gem_layout_full_width"
def show
@statistics = FetchCoronavirusStatisticsService.call
if @statistics
set_expiry content_item.max_age, public_cache: content_item.public_cache
else
logger.warn "Serving /coronavirus without statistics"
set_expiry 30.seconds
end
breadcrumbs = [{ title: t("shared.breadcrumbs_home"), url: "/", is_page_parent: true }]
title = {
text: presenter.page_header,
}
render "show",
locals: {
breadcrumbs: breadcrumbs,
title: title,
details: presenter,
special_announcement: special_announcement,
}
end
private
def set_slimmer_template
set_gem_layout_full_width
end
def content_item
@content_item ||= ContentItem.find!(request.path)
end
def presenter
@presenter ||= CoronavirusLandingPagePresenter.new(content_item.to_hash, params[:nation])
end
def special_announcement
@special_announcement ||= SpecialAnnouncementPresenter.new(content_item.to_hash)
end
end
|
Stop requiring the library in gemspec | require File.expand_path('../lib/acts_as_versioned', __FILE__)
Gem::Specification.new do |gem|
gem.name = 'mongo_mapper_acts_as_versioned'
gem.version = MongoMapper::Acts::Versioned::VERSION
gem.platform = Gem::Platform::RUBY
gem.authors = ['Gigamo']
gem.email = ['gigamo@gmail.com']
gem.homepage = 'http://github.com/gigamo/mongo_mapper_acts_as_versioned'
gem.summary = "Basic MongoMapper port of technoweenie's acts_as_versioned"
gem.description = gem.summary
gem.rubyforge_project = 'mongo_mapper_acts_as_versioned'
gem.require_paths = ['lib']
gem.files =
Dir['{lib,spec}/**/*', 'LICENSE', 'README.md'] & `git ls-files -z`.split("\0")
gem.add_dependency 'activesupport'
gem.add_development_dependency 'rspec'
gem.required_rubygems_version = '>= 1.3.6'
end
| Gem::Specification.new do |gem|
gem.name = 'mongo_mapper_acts_as_versioned'
gem.version = '0.2.0'
gem.platform = Gem::Platform::RUBY
gem.authors = ['Gigamo']
gem.email = ['gigamo@gmail.com']
gem.homepage = 'http://github.com/gigamo/mongo_mapper_acts_as_versioned'
gem.summary = "Basic MongoMapper port of technoweenie's acts_as_versioned"
gem.description = gem.summary
gem.rubyforge_project = 'mongo_mapper_acts_as_versioned'
gem.require_paths = ['lib']
gem.files =
Dir['{lib,spec}/**/*', 'LICENSE', 'README.md'] & `git ls-files -z`.split("\0")
gem.add_dependency 'activesupport'
gem.add_development_dependency 'rspec'
gem.required_rubygems_version = '>= 1.3.6'
end
|
Use the proper Ruby classes in properties | # frozen_string_literal: true
#
# Cookbook:: rabbitmq
# Resource:: erlang_zypper_repository_on_suse_factory
#
# Copyright:: 2019, Pivotal Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
#
default_action :create
attribute :baseurl, String, required: true
property :gpgautoimportkeys, [true, false], default: true
attribute :gpgcheck, [true, false], default: false
attribute :gpgkey, String
attribute :repo_gpgcheck, [true, false], default: true
attribute :repositoryid, String
attribute :enabled, [true, false], default: true
attribute :priority, String
attribute :proxy, String
attribute :proxy_username, String
attribute :proxy_password, String
attribute :sslcacert, String
attribute :sslclientcert, String
attribute :sslclientkey, String
attribute :sslverify, [true, false]
attribute :timeout
| # frozen_string_literal: true
#
# Cookbook:: rabbitmq
# Resource:: erlang_zypper_repository_on_suse_factory
#
# Copyright:: 2019, Pivotal Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
#
default_action :create
attribute :baseurl, String, required: true
property :gpgautoimportkeys, [TrueClass, FalseClass], default: true
attribute :gpgcheck, [true, false], default: false
attribute :gpgkey, String
attribute :repo_gpgcheck, [true, false], default: true
attribute :repositoryid, String
attribute :enabled, [true, false], default: true
attribute :priority, String
attribute :proxy, String
attribute :proxy_username, String
attribute :proxy_password, String
attribute :sslcacert, String
attribute :sslclientcert, String
attribute :sslclientkey, String
attribute :sslverify, [true, false]
attribute :timeout
|
Make cleanup of /tmp/os-image-rspec* work | require 'rspec/core/formatters/console_codes'
RSpec.configure do |config|
if ENV['OS_IMAGE']
config.before(:all) do
@os_image_dir = Dir.mktmpdir('os-image-rspec')
Bosh::Core::Shell.new.run("sudo tar xf #{ENV['OS_IMAGE']} -C #{@os_image_dir}")
SpecInfra::Backend::Exec.instance.chroot_dir = @os_image_dir
end
config.after(:all) do
FileUtils.rm_rf(@os_image_dir)
end
else
warning = 'All OS_IMAGE tests are being skipped. ENV["OS_IMAGE"] must be set to test OS images'
puts RSpec::Core::Formatters::ConsoleCodes.wrap(warning, :yellow)
config.filter_run_excluding os_image: true
end
end
| require 'rspec/core/formatters/console_codes'
RSpec.configure do |config|
if ENV['OS_IMAGE']
config.before(:all) do
@os_image_dir = Dir.mktmpdir('os-image-rspec')
Bosh::Core::Shell.new.run("sudo tar xf #{ENV['OS_IMAGE']} -C #{@os_image_dir}")
SpecInfra::Backend::Exec.instance.chroot_dir = @os_image_dir
end
config.after(:all) do
Bosh::Core::Shell.new.run("sudo rm -rf #{@os_image_dir}")
end
else
warning = 'All OS_IMAGE tests are being skipped. ENV["OS_IMAGE"] must be set to test OS images'
puts RSpec::Core::Formatters::ConsoleCodes.wrap(warning, :yellow)
config.filter_run_excluding os_image: true
end
end
|
Use append_file rather than insert_into file for authentication_helpers hook | module Spree
class CustomUserGenerator < Rails::Generators::NamedBase
include Rails::Generators::ResourceHelpers
desc "Set up a Spree installation with a custom User class"
def self.source_paths
paths = self.superclass.source_paths
paths << File.expand_path('../templates', __FILE__)
paths.flatten
end
def generate
template 'migration.rb.tt', "db/migrate/#{Time.now.strftime("%Y%m%d%H%m%S")}_add_spree_fields_to_custom_user_table.rb"
template 'authentication_helpers.rb.tt', "lib/spree/authentication_helpers.rb"
insert_into_file 'config/initializers/spree.rb', :before => "# Configure Spree Preferences" do
%Q{require 'spree/authentication_helpers'\n}
end
end
def klass
class_name.constantize
end
def table_name
klass.table_name
end
end
end
| module Spree
class CustomUserGenerator < Rails::Generators::NamedBase
include Rails::Generators::ResourceHelpers
desc "Set up a Spree installation with a custom User class"
def self.source_paths
paths = self.superclass.source_paths
paths << File.expand_path('../templates', __FILE__)
paths.flatten
end
def generate
template 'migration.rb.tt', "db/migrate/#{Time.now.strftime("%Y%m%d%H%m%S")}_add_spree_fields_to_custom_user_table.rb"
template 'authentication_helpers.rb.tt', "lib/spree/authentication_helpers.rb"
append_file 'config/initializers/spree.rb' do
%Q{require 'spree/authentication_helpers'\n}
end
end
def klass
class_name.constantize
end
def table_name
klass.table_name
end
end
end
|
Refactor confusing 'more_opts' line in create_payment_method | module FakeBraintree
class Redirect
include Helpers
attr_reader :id
def initialize(params, merchant_id)
hash, query = *params[:tr_data].split("|", 2)
@transparent_data = Rack::Utils.parse_nested_query(query)
@merchant_id = merchant_id
@id = create_id(@merchant_id)
@params = params
@kind = @transparent_data['kind']
end
def url
uri.to_s
end
def confirm
if @kind == 'create_customer'
Customer.new(@params["customer"], {:merchant_id => @merchant_id}).create
elsif @kind == 'create_payment_method'
options = {:merchant_id => @merchant_id}
if more_opts = (@transparent_data['credit_card'] && @transparent_data['credit_card'].delete('options'))
options.merge!(more_opts)
end
options.symbolize_keys!
CreditCard.new(@params['credit_card'].merge(@transparent_data['credit_card']), options).create
end
end
private
def uri
URI.parse(@transparent_data["redirect_url"]).merge("?#{base_query}&hash=#{hash(base_query)}")
end
def base_query
"http_status=200&id=#{@id}&kind=#{@kind}"
end
def hash(string)
Braintree::Digest.hexdigest(Braintree::Configuration.private_key, string)
end
end
end
| module FakeBraintree
class Redirect
include Helpers
attr_reader :id
def initialize(params, merchant_id)
hash, query = *params[:tr_data].split("|", 2)
@transparent_data = Rack::Utils.parse_nested_query(query)
@merchant_id = merchant_id
@id = create_id(@merchant_id)
@params = params
@kind = @transparent_data['kind']
end
def url
uri.to_s
end
def confirm
if @kind == 'create_customer'
Customer.new(@params["customer"], {:merchant_id => @merchant_id}).create
elsif @kind == 'create_payment_method'
credit_card_options = {:merchant_id => @merchant_id}
credit_card_options.merge!(@transparent_data['credit_card'].fetch('options', {}))
credit_card_options.symbolize_keys!
CreditCard.new(@params['credit_card'].merge(@transparent_data['credit_card']), credit_card_options).create
end
end
private
def uri
URI.parse(@transparent_data["redirect_url"]).merge("?#{base_query}&hash=#{hash(base_query)}")
end
def base_query
"http_status=200&id=#{@id}&kind=#{@kind}"
end
def hash(string)
Braintree::Digest.hexdigest(Braintree::Configuration.private_key, string)
end
end
end
|
Revert "No need for Rails 3 hack" | require "active_record"
require "groupdate/order_hack"
require "groupdate/scopes"
require "groupdate/series"
ActiveRecord::Base.send(:extend, Groupdate::Scopes)
module ActiveRecord
module Associations
class CollectionProxy
if ActiveRecord::VERSION::MAJOR == 3
delegate *Groupdate::METHODS, to: :scoped
end
end
end
end
# hack for issue before Rails 5
# https://github.com/rails/rails/issues/7121
module ActiveRecord
module Calculations
private
if ActiveRecord::VERSION::MAJOR < 5
def column_alias_for_with_hack(*keys)
if keys.first.is_a?(Groupdate::OrderHack)
keys.first.field
else
column_alias_for_without_hack(*keys)
end
end
alias_method_chain :column_alias_for, :hack
end
end
end
| require "active_record"
require "groupdate/order_hack"
require "groupdate/scopes"
require "groupdate/series"
ActiveRecord::Base.send(:extend, Groupdate::Scopes)
module ActiveRecord
class Relation
if ActiveRecord::VERSION::MAJOR == 3 && ActiveRecord::VERSION::MINOR < 2
def method_missing_with_hack(method, *args, &block)
if Groupdate::METHODS.include?(method)
scoping { @klass.send(method, *args, &block) }
else
method_missing_without_hack(method, *args, &block)
end
end
alias_method_chain :method_missing, :hack
end
end
end
module ActiveRecord
module Associations
class CollectionProxy
if ActiveRecord::VERSION::MAJOR == 3
delegate *Groupdate::METHODS, to: :scoped
end
end
end
end
# hack for issue before Rails 5
# https://github.com/rails/rails/issues/7121
module ActiveRecord
module Calculations
private
if ActiveRecord::VERSION::MAJOR < 5
def column_alias_for_with_hack(*keys)
if keys.first.is_a?(Groupdate::OrderHack)
keys.first.field
else
column_alias_for_without_hack(*keys)
end
end
alias_method_chain :column_alias_for, :hack
end
end
end
|
Fix valid related content url helper method | class RelatedContentsController < ApplicationController
VALID_URL = /#{Setting['url']}\/.*\/.*/
skip_authorization_check
respond_to :html, :js
def create
if relationable_object && related_object
RelatedContent.create(parent_relationable: @relationable, child_relationable: @related, author: current_user)
flash[:success] = t('related_content.success')
else
flash[:error] = t('related_content.error', url: Setting['url'])
end
redirect_to @relationable
end
def score_positive
score(:positive)
end
def score_negative
score(:negative)
end
private
def score(action)
@related = RelatedContent.find_by(id: params[:id])
@related.send("score_#{action}", current_user)
render template: 'relationable/_refresh_score_actions'
end
def valid_url?
params[:url].match(VALID_URL)
end
def relationable_object
@relationable = params[:relationable_klass].singularize.camelize.constantize.find_by(id: params[:relationable_id])
end
def related_object
if valid_url?
url = params[:url]
related_klass = url.match(/\/(#{RelatedContent::RELATIONABLE_MODELS.join("|")})\//)[0].delete("/")
related_id = url.match(/\/[0-9]+/)[0].delete("/")
@related = related_klass.singularize.camelize.constantize.find_by(id: related_id)
end
rescue
nil
end
end
| class RelatedContentsController < ApplicationController
skip_authorization_check
respond_to :html, :js
def create
if relationable_object && related_object
RelatedContent.create(parent_relationable: @relationable, child_relationable: @related, author: current_user)
flash[:success] = t('related_content.success')
else
flash[:error] = t('related_content.error', url: Setting['url'])
end
redirect_to @relationable
end
def score_positive
score(:positive)
end
def score_negative
score(:negative)
end
private
def score(action)
@related = RelatedContent.find_by(id: params[:id])
@related.send("score_#{action}", current_user)
render template: 'relationable/_refresh_score_actions'
end
def valid_url?
params[:url].start_with?(Setting['url'])
end
def relationable_object
@relationable = params[:relationable_klass].singularize.camelize.constantize.find_by(id: params[:relationable_id])
end
def related_object
if valid_url?
url = params[:url]
related_klass = url.match(/\/(#{RelatedContent::RELATIONABLE_MODELS.join("|")})\//)[0].delete("/")
related_id = url.match(/\/[0-9]+/)[0].delete("/")
@related = related_klass.singularize.camelize.constantize.find_by(id: related_id)
end
rescue
nil
end
end
|
Create rake task to convert direct url references to paperclip attachments. | desc 'Convert url references to paperclip attachments'
task :urls_to_paperclip, [:model_name, :url_field, :attachment_field] => :environment do |_, args|
puts "Starting task"
model_name = args[:model_name]
url_field = args[:url_field]
attachment_field = args[:attachment_field]
attachment_file_name_field = "#{attachment_field}_file_name"
klass = model_name.classify.constantize
records = klass.where.not(url_field => nil)
file_missing_count = 0
unsaved_record_count = 0
saved_record_count = 0
puts "#{records.size} records found needing conversion"
records.each do |record|
url = record.send(url_field)
file_name = url.split('/').last
file = FileStore.get(url)
if file
record.assign_attributes(attachment_field => file, attachment_file_name_field => file_name)
if record.save
print '.'
saved_record_count += 1
else
print 'X'
unsaved_record_count += 1
end
else
print '-'
file_missing_count += 1
end
end
puts "\nGenerating thumbnails"
ENV['CLASS'] = "#{klass}"
Rake::Task["paperclip:refresh:thumbnails"].invoke
puts "\nDone"
puts "\n#{saved_record_count} records were saved\n"
puts "#{unsaved_record_count} records could not be saved\n"
puts "#{file_missing_count} records referenced files that could not be located\n"
end
| |
Make sure the content type is decorated. | module Concerns
module Backend
module ContentTypeController
extend ActiveSupport::Concern
included do
layout 'backend/lightbox'
before_action :find_model
helper_method :content_path
end
module ClassMethods
def model(value)
define_method(:model) { value }
end
def allowed_params(*args)
define_method(:allowed_params) do
params.require(model.name.tableize.singularize).permit(*args)
end
end
end
def find_model
@model = model.find params[:id]
end
# TODO refactor?
def content_path
column = @model.column
path = "edit_translation_backend_#{column.row.rowable.class.to_s.downcase}_path"
send(path, column.row.rowable, locale, anchor: "content-row-#{column.row.id}")
end
def update
if @model.update_attributes allowed_params
redirect_to content_path
else
render :edit
end
end
end
end
end
| module Concerns
module Backend
module ContentTypeController
extend ActiveSupport::Concern
included do
layout 'backend/lightbox'
before_action :find_model
helper_method :content_path
end
module ClassMethods
def model(value)
define_method(:model) { value }
end
def allowed_params(*args)
define_method(:allowed_params) do
params.require(model.name.tableize.singularize).permit(*args)
end
end
end
def find_model
@model = model.find(params[:id]).decorate
end
# TODO refactor?
def content_path
column = @model.column
path = "edit_translation_backend_#{column.row.rowable.class.to_s.downcase}_path"
send(path, column.row.rowable, locale, anchor: "content-row-#{column.row.id}")
end
def update
if @model.update_attributes allowed_params
redirect_to content_path
else
render :edit
end
end
end
end
end
|
Use a default batch_id in revalidate | require "alephant/broker/errors"
module Alephant
module Broker
module LoadStrategy
module Revalidate
class Fetcher
include Logger
attr_reader :component_meta
def initialize(component_meta)
@component_meta = component_meta
end
def fetch
Alephant::Broker::Cache::CachedObject.new(s3.get(s3_path))
rescue AWS::S3::Errors::NoSuchKey, InvalidCacheKey
logger.metric "S3InvalidCacheKey"
raise Alephant::Broker::Errors::ContentNotFound
end
private
def s3_path
lookup.read(
component_meta.id,
component_meta.options,
component_meta.batch_id
).tap do |obj|
raise InvalidCacheKey if obj.location.nil?
end.location
end
def s3
@s3 ||= Alephant::Storage.new(
Broker.config[:s3_bucket_id],
Broker.config[:s3_object_path]
)
end
def lookup
@lookup ||= Alephant::Lookup.create(
Broker.config[:lookup_table_name],
Broker.config
)
end
end
end
end
end
end
| require "alephant/broker/errors"
module Alephant
module Broker
module LoadStrategy
module Revalidate
class Fetcher
include Logger
attr_reader :component_meta
def initialize(component_meta)
@component_meta = component_meta
end
def fetch
Alephant::Broker::Cache::CachedObject.new(s3.get(s3_path))
rescue AWS::S3::Errors::NoSuchKey, InvalidCacheKey
logger.metric "S3InvalidCacheKey"
raise Alephant::Broker::Errors::ContentNotFound
end
private
def s3_path
lookup.read(
component_meta.id,
component_meta.options,
component_meta.batch_id || 1
).tap do |obj|
raise InvalidCacheKey if obj.location.nil?
end.location
end
def s3
@s3 ||= Alephant::Storage.new(
Broker.config[:s3_bucket_id],
Broker.config[:s3_object_path]
)
end
def lookup
@lookup ||= Alephant::Lookup.create(
Broker.config[:lookup_table_name],
Broker.config
)
end
end
end
end
end
end
|
Remove static attribute in store credit reason factory | # frozen_string_literal: true
FactoryBot.define do
factory :store_credit_reason, class: 'Spree::StoreCreditReason' do
name "Input error"
end
end
| # frozen_string_literal: true
FactoryBot.define do
factory :store_credit_reason, class: 'Spree::StoreCreditReason' do
name { "Input error" }
end
end
|
Include snapshot list unit test | require File.expand_path("../../../../../base", __FILE__)
require Vagrant.source_root.join("plugins/commands/snapshot/command/list")
describe VagrantPlugins::CommandSnapshot::Command::List do
include_context "unit"
let(:iso_env) do
# We have to create a Vagrantfile so there is a root path
env = isolated_environment
env.vagrantfile("")
env.create_vagrant_env
end
let(:guest) { double("guest") }
let(:host) { double("host") }
let(:machine) { iso_env.machine(iso_env.machine_names[0], :dummy) }
let(:argv) { [] }
subject { described_class.new(argv, iso_env) }
before do
allow(machine.provider).to receive(:capability?).with(:snapshot_list).
and_return(true)
allow(machine.provider).to receive(:capability).with(:snapshot_list).
and_return([])
allow(subject).to receive(:with_target_vms) { |&block| block.call machine }
end
describe "execute" do
context "with an unsupported provider" do
let(:argv) { ["foo"] }
before do
allow(machine.provider).to receive(:capability?).with(:snapshot_list).
and_return(false)
end
it "raises an exception" do
machine.id = "foo"
expect { subject.execute }.
to raise_error(Vagrant::Errors::SnapshotNotSupported)
end
end
context "with a vm given" do
let(:argv) { ["foo"] }
it "prints a message if the vm does not exist" do
machine.id = nil
expect(iso_env.ui).to receive(:info).with { |message, _|
expect(message).to include("VM not created")
}
expect(machine).to_not receive(:action)
expect(subject.execute).to eq(0)
end
it "prints a message if no snapshots have been taken" do
machine.id = "foo"
expect(iso_env.ui).to receive(:output)
.with(/No snapshots have been taken yet!/, anything)
expect(subject.execute).to eq(0)
end
it "prints a list of snapshots" do
machine.id = "foo"
allow(machine.provider).to receive(:capability).with(:snapshot_list).
and_return(["foo", "bar", "baz"])
expect(iso_env.ui).to receive(:output).with(/foo/, anything)
expect(iso_env.ui).to receive(:output).with(/bar/, anything)
expect(iso_env.ui).to receive(:output).with(/baz/, anything)
expect(subject.execute).to eq(0)
end
end
end
end
| |
Use rails root instead of ../../../../ | require 'rails/generators'
require 'rails/generators/migration'
class RailsSettingsGenerator < Rails::Generators::Base
include Rails::Generators::Migration
def self.source_root
File.join(File.dirname(__FILE__), 'templates')
end
def self.next_migration_number(dirname) #:nodoc:
if ActiveRecord::Base.timestamped_migrations
Time.now.utc.strftime("%Y%m%d%H%M%S")
else
"%.3d" % (current_migration_number(dirname) + 1)
end
end
# Every method that is declared below will be automatically executed when the generator is run
def create_migration_file
f = File.open File.join(File.dirname(__FILE__), 'templates', 'schema.rb')
schema = f.read; f.close
schema.gsub!(/ActiveRecord::Schema.*\n/, '')
schema.gsub!(/^end\n*$/, '')
f = File.open File.join(File.dirname(__FILE__), 'templates', 'migration.rb')
migration = f.read; f.close
migration.gsub!(/SCHEMA_AUTO_INSERTED_HERE/, schema)
tmp = File.open "tmp/~migration_ready.rb", "w"
tmp.write migration
tmp.close
migration_template '../../../tmp/~migration_ready.rb',
'db/migrate/create_rails_settings_tables.rb'
remove_file 'tmp/~migration_ready.rb'
end
end | require 'rails/generators'
require 'rails/generators/migration'
class RailsSettingsGenerator < Rails::Generators::Base
include Rails::Generators::Migration
def self.source_root
File.join(File.dirname(__FILE__), 'templates')
end
def self.next_migration_number(dirname) #:nodoc:
if ActiveRecord::Base.timestamped_migrations
Time.now.utc.strftime("%Y%m%d%H%M%S")
else
"%.3d" % (current_migration_number(dirname) + 1)
end
end
# Every method that is declared below will be automatically executed when the generator is run
def create_migration_file
f = File.open File.join(File.dirname(__FILE__), 'templates', 'schema.rb')
schema = f.read; f.close
schema.gsub!(/ActiveRecord::Schema.*\n/, '')
schema.gsub!(/^end\n*$/, '')
f = File.open File.join(File.dirname(__FILE__), 'templates', 'migration.rb')
migration = f.read; f.close
migration.gsub!(/SCHEMA_AUTO_INSERTED_HERE/, schema)
tmp = File.open "tmp/~migration_ready.rb", "w"
tmp.write migration
tmp.close
migration_template "#{Rails.root}/tmp/~migration_ready.rb",
'db/migrate/create_rails_settings_tables.rb'
remove_file 'tmp/~migration_ready.rb'
end
end |
Use described_class in the specs. | require 'spec_helper'
try_spec do
require './spec/fixtures/api_user'
describe DataMapper::TypesFixtures::APIUser do
supported_by :all do
subject { DataMapper::TypesFixtures::APIUser.new(:name => 'alice') }
let(:original_api_key) { subject.api_key }
it "should have a default value" do
original_api_key.should_not be_nil
end
it "should preserve the default value" do
subject.api_key.should == original_api_key
end
it "should generate unique API Keys for each resource" do
other_resource = DataMapper::TypesFixtures::APIUser.new(:name => 'eve')
other_resource.api_key.should_not == original_api_key
end
end
end
end
| require 'spec_helper'
try_spec do
require './spec/fixtures/api_user'
describe DataMapper::TypesFixtures::APIUser do
supported_by :all do
subject { described_class.new(:name => 'alice') }
let(:original_api_key) { subject.api_key }
it "should have a default value" do
original_api_key.should_not be_nil
end
it "should preserve the default value" do
subject.api_key.should == original_api_key
end
it "should generate unique API Keys for each resource" do
other_resource = described_class.new(:name => 'eve')
other_resource.api_key.should_not == original_api_key
end
end
end
end
|
Set a default from email address. | Rails.application.configure do
config.cache_classes = true # Code is not reloaded between requests.
config.eager_load = true # Eager load code on boot.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
config.assets.js_compressor = :uglifier
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
config.assets.digest = true
config.log_level = :debug
# Production email settings: send via Sendgrid, generate URLs with our hostname
config.action_mailer.default_url_options = { host: 'www.local-welcome.org' }
ActionMailer::Base.smtp_settings = {
address: 'smtp.sendgrid.net',
port: '587',
authentication: :plain,
user_name: ENV['SENDGRID_USERNAME'],
password: ENV['SENDGRID_PASSWORD'],
domain: 'heroku.com',
enable_starttls_auto: true
}
config.i18n.fallbacks = true
config.active_support.deprecation = :notify # Send deprecation notices to registered listeners.
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
config.active_record.dump_schema_after_migration = false
end
| Rails.application.configure do
config.cache_classes = true # Code is not reloaded between requests.
config.eager_load = true # Eager load code on boot.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
config.assets.js_compressor = :uglifier
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
config.assets.digest = true
config.log_level = :debug
# Production email settings: send via Sendgrid, generate URLs with our hostname
config.action_mailer.default_url_options = { host: 'www.local-welcome.org' }
config.action_mailer.default_options = { from: "noreply@local-welcome.org" }
config.action_mailer.smtp_settings = {
address: 'smtp.sendgrid.net',
port: '587',
authentication: :plain,
user_name: ENV['SENDGRID_USERNAME'],
password: ENV['SENDGRID_PASSWORD'],
domain: 'heroku.com',
enable_starttls_auto: true
}
config.i18n.fallbacks = true
config.active_support.deprecation = :notify # Send deprecation notices to registered listeners.
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
config.active_record.dump_schema_after_migration = false
end
|
Add the default database connection. | require 'rubygems'
require 'sinatra/base'
require 'lib/interview'
require 'slim'
class TheSetup < Sinatra::Base
configure do
Slim::Engine.set_default_options(:pretty => true)
end
get '/' do
@interviews = Interview.find_recent()
slim :index
end
get '/interviews/?' do
end
get '/about/?' do
end
get '/community/?' do
end
end
| require 'rubygems'
require 'sinatra/base'
require 'lib/interview'
require 'slim'
class TheSetup < Sinatra::Base
configure do
Mongoon::Document.database = Mongo::Connection.new.db("usesthis")
Slim::Engine.set_default_options(:pretty => true)
end
get '/' do
@interviews = Interview.find_recent()
slim :index
end
get '/interviews/?' do
end
get '/about/?' do
end
get '/community/?' do
end
end |
Add config/amqp.yml to .gitignore in generator. | require 'rails/generators'
module Hare
class InstallGenerator < Rails::Generators::Base
source_root File.expand_path('../templates', __FILE__)
def create_executable_file
filepath = Rails.root + "bin/hare"
template "hare", filepath
chmod filepath, 0755
end
def create_amqp_config_file
filepath = Rails.root + "config"
template "amqp.yml.sample", filepath + "amqp.yml.sample"
end
end
end
| require 'rails/generators'
module Hare
class InstallGenerator < Rails::Generators::Base
source_root File.expand_path('../templates', __FILE__)
def create_executable_file
filepath = Rails.root + "bin/hare"
template "hare", filepath
chmod filepath, 0755
end
def create_amqp_config_file
filepath = Rails.root + "config"
template "amqp.yml.sample", filepath + "amqp.yml.sample"
append_file Rails.root + '.gitignore', 'config/amqp.yml'
end
end
end
|
Set condition for nested infection_organisms to be rejected if fields are blank. | class PeritonitisEpisode < ActiveRecord::Base
belongs_to :patient
belongs_to :episode_type
belongs_to :fluid_description
has_many :medications, as: :treatable
has_many :medication_routes, through: :medications
has_many :patients, through: :medications, as: :treatable
has_many :infection_organisms, as: :infectable
has_many :organism_codes, -> { uniq }, through: :infection_organisms, as: :infectable
accepts_nested_attributes_for :medications, allow_destroy: true,
reject_if: proc { |attrs| attrs[:dose].blank? && attrs[:notes].blank? && attrs[:frequency].blank? }
accepts_nested_attributes_for :infection_organisms
# validate :number_of_medication_routes
# def number_of_medication_routes
# unless medication_routes.any? && medication_routes.size == 5
# errors.add(:medication_routes, "Must have 5")
# end
# end
end
| class PeritonitisEpisode < ActiveRecord::Base
belongs_to :patient
belongs_to :episode_type
belongs_to :fluid_description
has_many :medications, as: :treatable
has_many :medication_routes, through: :medications
has_many :patients, through: :medications, as: :treatable
has_many :infection_organisms, as: :infectable
has_many :organism_codes, -> { uniq }, through: :infection_organisms, as: :infectable
accepts_nested_attributes_for :medications, allow_destroy: true,
reject_if: proc { |attrs| attrs[:dose].blank? && attrs[:notes].blank? && attrs[:frequency].blank? }
accepts_nested_attributes_for :infection_organisms, allow_destroy: true,
reject_if: proc { |attrs| attrs[:sensitvity].blank? && attrs[:organism_code_id].blank? }
# validate :number_of_medication_routes
# def number_of_medication_routes
# unless medication_routes.any? && medication_routes.size == 5
# errors.add(:medication_routes, "Must have 5")
# end
# end
end
|
Update running average calculator specs to new format | require 'spec_helper'
describe ProgressBar::Calculators::RunningAverage do
describe '.calculate' do
it 'calculates properly' do
expect(ProgressBar::Calculators::RunningAverage.calculate(4.5, 12, 0.1)).to be_within(0.001).of 11.25
expect(ProgressBar::Calculators::RunningAverage.calculate(8.2, 51, 0.7)).to be_within(0.001).of 21.04
expect(ProgressBar::Calculators::RunningAverage.calculate(41.8, 100, 0.59)).to be_within(0.001).of 65.662
end
end
end
| require 'rspectacular'
require 'ruby-progressbar/calculators/running_average'
class ProgressBar
module Calculators
describe RunningAverage do
it 'can properly calculate a running average' do
first_average = RunningAverage.calculate(4.5, 12, 0.1)
expect(first_average).to be_within(0.001).of 11.25
second_average = RunningAverage.calculate(8.2, 51, 0.7)
expect(second_average).to be_within(0.001).of 21.04
third_average = RunningAverage.calculate(41.8, 100, 0.59)
expect(third_average).to be_within(0.001).of 65.662
end
end
end
end
|
Use TaskRouterClient in test for realism | require 'spec_helper'
class Twilio::REST::TaskRouter::StatisticsTestHarnessStatistics
def initialize(*args)
end
end
class StatisticsTestHarness
include Twilio::REST::TaskRouter::Statistics
def initialize(path, client)
@path = path
@client = client
end
end
describe Twilio::REST::TaskRouter::Statistics do
it "creates a new statistics object based on the class" do
client = double("Client")
allow(client).to receive(:get)
harness = StatisticsTestHarness.new("/test/harness", client)
expect(harness.statistics).to(
be_an_instance_of(Twilio::REST::TaskRouter::StatisticsTestHarnessStatistics)
)
end
it "passes parameters to the HTTP request for statistics" do
client = Twilio::REST::Client.new 'someSid', 'someAuthToken'
allow(Net::HTTP::Get).to receive(:new)
.with("/test/harness/Statistics.json?Minutes=15", Twilio::REST::BaseClient::HTTP_HEADERS)
.and_call_original
harness = StatisticsTestHarness.new("/test/harness", client)
expect(harness.statistics(minutes: 15)).to(
be_an_instance_of(Twilio::REST::TaskRouter::StatisticsTestHarnessStatistics)
)
end
end
| require 'spec_helper'
class Twilio::REST::TaskRouter::StatisticsTestHarnessStatistics
def initialize(*args)
end
end
class StatisticsTestHarness
include Twilio::REST::TaskRouter::Statistics
def initialize(path, client)
@path = path
@client = client
end
end
describe Twilio::REST::TaskRouter::Statistics do
it "creates a new statistics object based on the class" do
client = double("Client")
allow(client).to receive(:get)
harness = StatisticsTestHarness.new("/test/harness", client)
expect(harness.statistics).to(
be_an_instance_of(Twilio::REST::TaskRouter::StatisticsTestHarnessStatistics)
)
end
it "passes parameters to the HTTP request for statistics" do
client = Twilio::REST::TaskRouterClient.new 'someSid', 'someAuthToken', 'someWorkspaceSid'
allow(Net::HTTP::Get).to receive(:new)
.with("/test/harness/Statistics?Minutes=15", Twilio::REST::BaseClient::HTTP_HEADERS)
.and_call_original
harness = StatisticsTestHarness.new("/test/harness", client)
expect(harness.statistics(minutes: 15)).to(
be_an_instance_of(Twilio::REST::TaskRouter::StatisticsTestHarnessStatistics)
)
end
end
|
Add color specification code (Bash, curl related) | require 'sinatra'
require 'sinatra/base'
require_relative 'license_list'
require 'active_support'
require 'active_support/core_ext'
class LicenseDownload < Sinatra::Base
private
def valid_license_name?(license_name)
LICENSE_LIST.keys.include?(license_name)
end
def read_specified_file(license_name)
File.read("license_files/#{LICENSE_LIST[license_name]}")
end
def license_name
params[:splat].to_a
.first
.delete('/')
.to_sym
end
def error_message
message = "Please specify a type of license name.\n"
message << "\n"
message << "Supported list:\n"
message << LICENSE_LIST.map { |key, _value| key }.join(', ')
message << "\n"
end
get '*' do
return error_message unless valid_license_name?(license_name)
read_specified_file(license_name)
end
end
| require 'sinatra'
require 'sinatra/base'
require_relative 'license_list'
require 'active_support'
require 'active_support/core_ext'
class LicenseDownload < Sinatra::Base
private
def valid_license_name?(license_name)
LICENSE_LIST.keys.include?(license_name)
end
def read_specified_file(license_name)
File.read("license_files/#{LICENSE_LIST[license_name]}")
end
def license_name
params[:splat].to_a
.first
.delete('/')
.to_sym
end
def error_message
message = ''
message << "\e[1m" # To Bold
message << "\e[93m" # To LightYellow
message << "Please specify a type of license name.\n"
message << "\n"
message << "\e[94m" # To LightBlue
message << "Supported list:\n"
message << "\e[0m" # Reset all style
message << LICENSE_LIST.map { |key, _value| key }.join(', ')
message << "\n"
end
get '*' do
return error_message unless valid_license_name?(license_name)
read_specified_file(license_name)
end
end
|
Check if puppet is running before raise error | #!/usr/bin/env ruby
require 'yaml'
puppet_last_run_summary = "/var/lib/puppet/state/last_run_summary.yaml"
if File.exist?(puppet_last_run_summary) then
puppet_report = YAML.load_file(puppet_last_run_summary)
else
raise "#{puppet_last_run_summary} does not exist!"
end
report_age = Time.new.to_i - puppet_report['time']['last_run'].to_i
if report_age > 3600 then
raise 'Puppet agent did not update report for over an hour'
end
if puppet_report['events'] and puppet_report['events']['failure'].to_i > 0 then
raise 'Puppet catalog apply finished with errors'
end
| #!/usr/bin/env ruby
require 'pathname'
require 'yaml'
agent_catalog_run = Pathname.new('/var/lib/puppet/state/agent_catalog_run.lock')
puppet_last_run_summary = Pathname.new('/var/lib/puppet/state/last_run_summary.yaml')
if agent_catalog_run.exist? then
if Time.new - agent_catalog_run.mtime > 3600
raise 'Puppet process is blocked for over an hour'
end
exit 0
end
if puppet_last_run_summary.exist? then
puppet_report = YAML.load_file(puppet_last_run_summary)
else
raise "#{puppet_last_run_summary.to_s} does not exist!"
end
report_age = Time.new.to_i - puppet_report['time']['last_run'].to_i
if report_age > 3600 then
raise 'Puppet agent did not update report for over an hour'
end
if puppet_report['events'] and puppet_report['events']['failure'].to_i > 0 then
raise 'Puppet catalog apply finished with errors'
end
|
Add scenario for getting all received messages | require 'helper'
describe 'getting all of my received messages' do
let(:username) { String.generate }
let(:password) { String.generate }
subject { Esendex.new(username, password) }
let(:count) { 34 }
let(:messages) { MessageHeaders.generate(count) }
let(:response_body) { messages.to_xml }
before {
stub_request(:get, "https://#{username}:#{password}@api.esendex.com/v1.0/inbox/messages?")
.with(query: {"count" => 25, "startIndex" => 0},
headers: {"User-Agent" => Esendex::Client::USER_AGENT})
.to_return(status: 200, body: response_body)
stub_request(:get, "https://#{username}:#{password}@api.esendex.com/v1.0/inbox/messages?")
.with(query: {"count" => 25, "startIndex" => 25},
headers: {"User-Agent" => Esendex::Client::USER_AGENT})
.to_return(status: 200, body: MessageHeaders.generate(0).to_xml)
}
it 'returns an Enumerable that iterates over my sent messages' do
returned_messages = subject.messages.received.entries
returned_messages.size.must_equal count
returned_messages.zip(messages) do |returned, expected|
returned.id.must_equal expected.id
returned.status.must_equal expected.status
returned.last_status_at.must_equal expected.laststatusat
returned.submitted_at.must_equal expected.submittedat
returned.type.must_equal expected.type
returned.to.phonenumber.must_equal expected.to
returned.from.phonenumber.must_equal expected.from
returned.summary.must_equal expected.summary
returned.body.uri.must_equal expected.body
returned.direction.must_equal expected.direction
returned.parts.must_equal expected.parts
returned.username.must_equal expected.username
end
end
end
| |
Add a spec of beginless range for Ruby 2.7 | # frozen_string_literal: true
RSpec.describe RuboCop::AST::RangeNode do
let(:range_node) { parse_source(source).ast }
describe '.new' do
context 'with an inclusive range' do
let(:source) do
'1..2'
end
it { expect(range_node.is_a?(described_class)).to be(true) }
it { expect(range_node.range_type?).to be(true) }
end
context 'with an exclusive range' do
let(:source) do
'1...2'
end
it { expect(range_node.is_a?(described_class)).to be(true) }
it { expect(range_node.range_type?).to be(true) }
end
context 'with an infinite range' do
let(:ruby_version) { 2.6 }
let(:source) do
'1..'
end
it { expect(range_node.is_a?(described_class)).to be(true) }
it { expect(range_node.range_type?).to be(true) }
end
end
end
| # frozen_string_literal: true
RSpec.describe RuboCop::AST::RangeNode do
let(:range_node) { parse_source(source).ast }
describe '.new' do
context 'with an inclusive range' do
let(:source) do
'1..2'
end
it { expect(range_node.is_a?(described_class)).to be(true) }
it { expect(range_node.range_type?).to be(true) }
end
context 'with an exclusive range' do
let(:source) do
'1...2'
end
it { expect(range_node.is_a?(described_class)).to be(true) }
it { expect(range_node.range_type?).to be(true) }
end
context 'with an infinite range' do
let(:ruby_version) { 2.6 }
let(:source) do
'1..'
end
it { expect(range_node.is_a?(described_class)).to be(true) }
it { expect(range_node.range_type?).to be(true) }
end
context 'with a beiginless range' do
let(:ruby_version) { 2.7 }
let(:source) do
'..42'
end
it { expect(range_node.is_a?(described_class)).to be(true) }
it { expect(range_node.range_type?).to be(true) }
end
end
end
|
Use [] as default for .tld list | require 'logger'
module VagrantDNS
class Config < Vagrant::Config::Base
class << self
attr_accessor :listen, :logger, :ipv4only, :auto_run
def listen
@listen ||= [[:udp, "127.0.0.1", 5300]]
end
def ipv4only
@ipv4only || @ipv4only.nil?
end
def auto_run
return true if @auto_run.nil?
@auto_run
end
end
attr_accessor :records, :tlds, :ipv4only, :patterns
def pattern=(pattern)
self.patterns = pattern
end
def tld=(tld)
@tlds = Array(tld)
end
# explicit hash, to get symbols in hash keys
def to_hash
{
:patterns => (patterns ? Array(patterns) : patterns),
:records => records,
:tlds => tlds,
:ipv4only => ipv4only
}
end
end
end
| require 'logger'
module VagrantDNS
class Config < Vagrant::Config::Base
class << self
attr_accessor :listen, :logger, :ipv4only, :auto_run
def listen
@listen ||= [[:udp, "127.0.0.1", 5300]]
end
def ipv4only
@ipv4only || @ipv4only.nil?
end
def auto_run
return true if @auto_run.nil?
@auto_run
end
end
attr_accessor :records, :tlds, :ipv4only, :patterns
def pattern=(pattern)
self.patterns = pattern
end
def tld=(tld)
@tlds = Array(tld)
end
def tlds
@tlds ||= []
end
# explicit hash, to get symbols in hash keys
def to_hash
{
:patterns => (patterns ? Array(patterns) : patterns),
:records => records,
:tlds => tlds,
:ipv4only => ipv4only
}
end
end
end
|
Make it clear this is an IO, not a String | ##
# Raised when Mechanize encounters an error while reading the response body
# from the server. Contains the response headers and the response body up to
# the error along with the initial error.
class Mechanize::ResponseReadError < Mechanize::Error
attr_reader :body
attr_reader :error
attr_reader :response
##
# Creates a new ResponseReadError with the +error+ raised, the +response+
# and the +body+ read so far.
def initialize error, response, body
@error = error
@response = response
@body = body
end
def message # :nodoc:
"#{@error.message} (#{self.class})"
end
end
| ##
# Raised when Mechanize encounters an error while reading the response body
# from the server. Contains the response headers and the response body up to
# the error along with the initial error.
class Mechanize::ResponseReadError < Mechanize::Error
attr_reader :body_io
attr_reader :error
attr_reader :response
##
# Creates a new ResponseReadError with the +error+ raised, the +response+
# and the +body_io+ for content read so far.
def initialize error, response, body_io
@error = error
@response = response
@body_io = body_io
end
def message # :nodoc:
"#{@error.message} (#{self.class})"
end
end
|
Set the title on creation page to when validation fails | class RegistrationsController < Devise::RegistrationsController
before_filter :check_product_name, :only => 'new'
helper_method :individual?
def new
if %w{partner sponsor}.include? @product_name
@contact_request = ContactRequest.new
@product_name == "sponsor" ? @title = "Sponsor us" : @title = "Partner with us"
render 'contact_requests/new'
else
@title = "Sign up"
super
end
end
def create
if params[:contact_request]
@contact_request = ContactRequest.new(params[:contact_request])
@product_name = @contact_request.product_name
respond_to do |format|
if @contact_request.save
format.html { render "contact_requests/create" }
format.json { render json: @contact_request, status: :created, location: @contact_request }
else
format.html { render "contact_requests/new" }
format.json { render json: @contact_request.errors, status: :unprocessable_entity }
end
end
else
super
end
end
protected
def check_product_name
@product_name = params[:level].to_s
redirect_to 'http://www.theodi.org/join-us' unless %w{supporter partner sponsor individual}.include?(@product_name)
end
def individual?
@member.individual? || Member.is_individual_level?(@product_name)
end
end
| class RegistrationsController < Devise::RegistrationsController
before_filter :check_product_name, :only => 'new'
before_filter :set_title, :only => %w[new create]
helper_method :individual?
def new
if %w{partner sponsor}.include? @product_name
@contact_request = ContactRequest.new
render 'contact_requests/new'
else
super
end
end
def create
if params[:contact_request]
@contact_request = ContactRequest.new(params[:contact_request])
@product_name = @contact_request.product_name
respond_to do |format|
if @contact_request.save
format.html { render "contact_requests/create" }
format.json { render json: @contact_request, status: :created, location: @contact_request }
else
format.html { render "contact_requests/new" }
format.json { render json: @contact_request.errors, status: :unprocessable_entity }
end
end
else
super
end
end
protected
def check_product_name
@product_name = params[:level].to_s
redirect_to 'http://www.theodi.org/join-us' unless %w{supporter partner sponsor individual}.include?(@product_name)
end
def set_title
@title = case @product_name
when 'sponsor'
'Sponsor us'
when 'partner'
'Partner with us'
else
"Sign up"
end
end
def individual?
@member.individual? || Member.is_individual_level?(@product_name)
end
end
|
Add images to assets precompile | require 'rails'
module CountryFlags
class Railtie < ::Rails::Railtie
initializer 'country_flags.view_helpers' do
ActionView::Base.send :include, Helper
end
end
end | require 'rails'
module CountryFlags
class Railtie < ::Rails::Railtie
initializer 'country_flags.view_helpers' do
ActionView::Base.send :include, Helper
Rails.application.config.assets.precompile += %w(country_flags/png/* country_flags/gif/*)
end
end
end |
Test log in from an invalid domain | require 'rails_helper'
feature "Authentication" do
before do
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:gplus] = OmniAuth::AuthHash.new({
provider: 'gplus',
info: {
email: 'test.user@digital.justice.gov.uk'
}
})
end
scenario "Logging in and out" do
visit '/'
expect(page).to have_text("Please log in to continue")
click_link "log in"
expect(page).to have_text("Logged in as test.user@digital.justice.gov.uk")
click_link "Log out"
expect(page).to have_text("Please log in to continue")
end
end
| require 'rails_helper'
feature "Authentication" do
before do
OmniAuth.config.test_mode = true
end
scenario "Logging in and out" do
OmniAuth.config.mock_auth[:gplus] = valid_user
visit '/'
expect(page).to have_text("Please log in to continue")
click_link "log in"
expect(page).to have_text("Logged in as test.user@digital.justice.gov.uk")
click_link "Log out"
expect(page).to have_text("Please log in to continue")
end
scenario 'Log in failure' do
OmniAuth.config.mock_auth[:gplus] = invalid_user
visit '/'
expect(page).to have_text("Please log in to continue")
click_link "log in"
expect(page).to have_text(/sign in with a MOJ DS or GDS account/)
end
end
def invalid_user
OmniAuth::AuthHash.new({
provider: 'gplus',
info: {
email: 'test.user@example.com'
}
})
end
def valid_user
OmniAuth::AuthHash.new({
provider: 'gplus',
info: {
email: 'test.user@digital.justice.gov.uk'
}
})
end
|
Update Guard dependency to ~> 2.0 | # encoding: utf-8
$:.push File.expand_path('../lib', __FILE__)
require 'guard/minitest/version'
Gem::Specification.new do |s|
s.name = 'guard-minitest'
s.version = Guard::MinitestVersion::VERSION
s.platform = Gem::Platform::RUBY
s.license = 'MIT'
s.authors = ['Yann Lugrin', 'RΓ©my Coutable']
s.email = ['remy@rymai.me']
s.homepage = 'http://rubygems.org/gems/guard-minitest'
s.summary = 'Guard plugin for the Minitest framework'
s.description = 'Guard::Minitest automatically run your tests with Minitest framework (much like autotest)'
s.required_ruby_version = '>= 1.9.2'
s.add_runtime_dependency 'guard', '>= 2.0.0.pre.3'
s.add_runtime_dependency 'minitest', '>= 2.1'
s.add_development_dependency 'bundler'
s.files = Dir.glob('{lib}/**/*') + %w[CHANGELOG.md LICENSE README.md]
s.require_path = 'lib'
end
| # encoding: utf-8
$:.push File.expand_path('../lib', __FILE__)
require 'guard/minitest/version'
Gem::Specification.new do |s|
s.name = 'guard-minitest'
s.version = Guard::MinitestVersion::VERSION
s.platform = Gem::Platform::RUBY
s.license = 'MIT'
s.authors = ['Yann Lugrin', 'RΓ©my Coutable']
s.email = ['remy@rymai.me']
s.homepage = 'https://rubygems.org/gems/guard-minitest'
s.summary = 'Guard plugin for the Minitest framework'
s.description = 'Guard::Minitest automatically run your tests with Minitest framework (much like autotest)'
s.required_ruby_version = '>= 1.9.2'
s.add_runtime_dependency 'guard', '~> 2.0'
s.add_runtime_dependency 'minitest', '>= 2.1'
s.add_development_dependency 'bundler'
s.files = Dir.glob('{lib}/**/*') + %w[CHANGELOG.md LICENSE README.md]
s.require_path = 'lib'
end
|
Add dependency on capistrano 2.15.5 and minor version bump | # -*- encoding: utf-8 -*-
$:.push File.expand_path('../lib', __FILE__)
Gem::Specification.new do |s|
s.name = 'capistrano-ec2tag'
s.version = '0.1.1'
s.authors = ['Douglas Jarquin']
s.email = ['douglasjarquin@me.com']
s.homepage = 'https://github.com/douglasjarquin/capistrano-ec2tag'
s.summary = 'A Capistrano plugin aimed at easing the pain of deploying to Amazon EC2 instances.'
s.description = 'capistrano-ec2tag is a Capistrano plugin designed to simplify the task of deploying to infrastructure hosted on Amazon EC2. It was completely inspired by the capistrano-ec2group plugin, to which all credit is due.'
s.rubyforge_project = 'capistrano-ec2tag'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ['lib']
s.add_dependency 'capistrano', '>=2.14.2'
s.add_dependency 'aws-sdk', '>=1.8.5'
end
| # -*- encoding: utf-8 -*-
$:.push File.expand_path('../lib', __FILE__)
Gem::Specification.new do |s|
s.name = 'capistrano-ec2tag'
s.version = '0.1.2'
s.authors = ['Douglas Jarquin']
s.email = ['douglasjarquin@me.com']
s.homepage = 'https://github.com/douglasjarquin/capistrano-ec2tag'
s.summary = 'A Capistrano plugin aimed at easing the pain of deploying to Amazon EC2 instances.'
s.description = 'capistrano-ec2tag is a Capistrano plugin designed to simplify the task of deploying to infrastructure hosted on Amazon EC2. It was completely inspired by the capistrano-ec2group plugin, to which all credit is due.'
s.rubyforge_project = 'capistrano-ec2tag'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ['lib']
s.add_dependency 'capistrano', '>=2.15.5'
s.add_dependency 'aws-sdk', '>=1.8.5'
end
|
Update test for neo4j output | # frozen_string_literal: true
def furbies
@furbies ||= rand(200..299)
end
describe 'neo4j installation' do
describe command('which neo4j') do
its(:stdout) { should match 'bin/neo4j' }
end
describe 'neo4j commands' do
before :all do
sh('service neo4j start')
tcpwait('127.0.0.1', 1337, 30)
sh("neo4j-shell -v -c 'create (n:thing {furbies: #{furbies}});'")
end
describe command("neo4j-shell -v -c 'cd 0 && ls'") do
its(:stdout) { should include('furbies =', furbies.to_s) }
its(:stderr) { should be_empty }
end
end
end
| # frozen_string_literal: true
def furbies
@furbies ||= rand(200..299)
end
describe 'neo4j installation' do
describe command('which neo4j') do
its(:stdout) { should match 'bin/neo4j' }
end
describe 'neo4j commands' do
before :all do
sh('service neo4j start')
tcpwait('127.0.0.1', 1337, 30)
sh("neo4j-shell -v -c 'create (n:thing {furbies: #{furbies}});'")
end
describe command("neo4j-shell -v -c 'cd 0 && ls'") do
its(:stdout) { should include('furbies =', furbies.to_s) }
its(:stderr) { should match 'Picked up _JAVA_OPTIONS: -Xmx2048m -Xms512m\n' }
end
end
end
|
Add mailer sending after subscribing | #
# == NewsletterUsersController
#
class NewsletterUsersController < ApplicationController
before_action :set_newsletter_user, only: [:unsubscribe]
after_action :send_welcome_newsletter, only: [:create]
def create
@newsletter_user = NewsletterUser.new(newsletter_user_params)
respond_to do |format|
if @newsletter_user.save
format.html { redirect_to :back }
format.js { render :show, status: :created }
else
format.html { redirect_to :back }
format.js { render 'errors', status: :unprocessable_entity }
end
end
end
def unsubscribe
if @newsletter_user.token == params[:token]
@newsletter_user.destroy
flash[:success] = I18n.t('newsletter.unsubscribe.success')
else
flash[:error] = I18n.t('newsletter.unsubscribe.fail')
end
# TODO: redirect to fr or en depending of the language
redirect_to :root
end
private
def newsletter_user_params
params.require(:newsletter_user).permit(:email, :lang)
end
def set_newsletter_user
@newsletter_user = NewsletterUser.find(params[:newsletter_user_id])
rescue ActiveRecord::RecordNotFound
flash[:error] = I18n.t('newsletter.unsubscribe.invalid')
redirect_to :root
end
def send_welcome_newsletter
# Sends email to user when user is created.
SendEmailJob.set(wait: 10.seconds).perform_later(@newsletter_user)
end
end
| #
# == NewsletterUsersController
#
class NewsletterUsersController < ApplicationController
before_action :set_newsletter_user, only: [:unsubscribe]
after_action :send_welcome_newsletter, only: [:create]
def create
@newsletter_user = NewsletterUser.new(newsletter_user_params)
respond_to do |format|
if @newsletter_user.save
format.html { redirect_to :back }
format.js { render :show, status: :created }
else
format.html { redirect_to :back }
format.js { render 'errors', status: :unprocessable_entity }
end
end
end
def unsubscribe
if @newsletter_user.token == params[:token]
@newsletter_user.destroy
flash[:success] = I18n.t('newsletter.unsubscribe.success')
else
flash[:error] = I18n.t('newsletter.unsubscribe.fail')
end
# TODO: redirect to fr or en depending of the language
redirect_to :root
end
private
def newsletter_user_params
params.require(:newsletter_user).permit(:email, :lang)
end
def set_newsletter_user
@newsletter_user = NewsletterUser.find(params[:newsletter_user_id])
rescue ActiveRecord::RecordNotFound
flash[:error] = I18n.t('newsletter.unsubscribe.invalid')
redirect_to :root
end
# Sends email to user when user is created.
def send_welcome_newsletter
WelcomeNewsletterJob.set(wait: 10.seconds).perform_later(@newsletter_user)
end
end
|
Tidy up artefacts whose formats have changed | class SynchroniseArtefactKindsWithLatestEditionFormats < Mongoid::Migration
def self.up
# We don't want to run any update callbacks, just change the column
Artefact.skip_callback(:update, :after, :update_editions)
Artefact.each do |artefact|
latest_edition = artefact.latest_edition
next if latest_edition.nil?
next if latest_edition.kind_for_artefact == artefact.kind
puts "Changing #{artefact.slug} (#{artefact.content_id}) from #{artefact.kind} to #{latest_edition.kind_for_artefact}"
artefact.update_attribute(:kind, latest_edition.kind_for_artefact)
end
# restore the update callback for future migrations
Artefact.set_callback(:update, :after, :update_editions)
end
def self.down
end
end
| |
Change pg_search from pg_search_scope to multisearchable against | class Program < ActiveRecord::Base
include PgSearch
belongs_to :school
pg_search_scope :program_search, :against => [:program_name, :interest_area]
end
| class Program < ActiveRecord::Base
include PgSearch
belongs_to :school
multisearchable :against => [:program_name, :interest_area]
end
|
Fix integrations tests for Docker Machine | require 'spec_helper'
describe file('/usr/local/bin/docker-machine') do
it { should be_file }
it { should be_mode 755 }
it { should be_owned_by 'root' }
end
describe command('docker-machine --version') do
its(:stdout) { should match /0.10.2/m }
its(:exit_status) { should eq 0 }
end
| require 'spec_helper'
describe file('/usr/local/bin/docker-machine') do
it { should be_file }
it { should be_mode 755 }
it { should be_owned_by 'root' }
end
describe command('docker-machine --version') do
its(:stdout) { should match /0.10.0/m }
its(:exit_status) { should eq 0 }
end
|
Add client logic to import worker. | class DailyImportWorker
include Sidekiq::Worker
sidekiq_options queue: 'daily_import'
def perform
User.create(email: "me@example.com")
end
end
| class DailyImportWorker
include Sidekiq::Worker
sidekiq_options queue: 'daily_import'
def perform
client = ClinicalTrials::Client.new
client.create_studies
end
end
|
Change Datamatrix height on ZPL2 | module Languages
class Zpl2
class BarcodeFactory
def self.create_barcode(font, code_type, opts = {})
if Barcode1D::BarcodeClasses.keys.include? code_type
Barcode1D.new font,code_type,opts
elsif Barcode2D::BarcodeClasses.keys.include? code_type
Barcode2D.new font,code_type,opts
else
raise ArgumentException.new("Unknown barcode: #{code_type}")
end
end
end
class Barcode1D
BarcodeClasses = {
code_128: "BC"
}
def initialize(font, code_type, opts = {})
@font = font
@code = BarcodeClasses[code_type]
@human_readable = "Y"
end
def render(text)
"^#{@code}#{@font.rotation},#{@font.height*2},#{@human_readable},N,N^FD#{text}^FS"
end
end
class Barcode2D
BarcodeClasses = {
data_matrix: ["X",1,16,16]
}
def initialize(font, code_type, opts = {})
@font = font
@code, @symbol_height, @columns_encode, @rows_encode = BarcodeClasses[code_type]
end
def render(text)
"^B#{@code}#{@font.rotation},#{@symbol_height},200,#{@columns_encode},#{@rows_encode}^FD#{text}^FS"
end
end
end
end
| module Languages
class Zpl2
class BarcodeFactory
def self.create_barcode(font, code_type, opts = {})
if Barcode1D::BarcodeClasses.keys.include? code_type
Barcode1D.new font,code_type,opts
elsif Barcode2D::BarcodeClasses.keys.include? code_type
Barcode2D.new font,code_type,opts
else
raise ArgumentException.new("Unknown barcode: #{code_type}")
end
end
end
class Barcode1D
BarcodeClasses = {
code_128: "BC"
}
def initialize(font, code_type, opts = {})
@font = font
@code = BarcodeClasses[code_type]
@human_readable = "Y"
end
def render(text)
"^#{@code}#{@font.rotation},#{@font.height*2},#{@human_readable},N,N^FD#{text}^FS"
end
end
class Barcode2D
BarcodeClasses = {
data_matrix: ["X",4,16,16]
}
def initialize(font, code_type, opts = {})
@font = font
@code, @symbol_height, @columns_encode, @rows_encode = BarcodeClasses[code_type]
end
def render(text)
"^B#{@code}#{@font.rotation},#{@symbol_height},200,#{@columns_encode},#{@rows_encode}^FD#{text}^FS"
end
end
end
end
|
Add OS / .NET detection to the installer. Tested working |
#
# Cookbook Name:: ms_dotnet35
# Recipe:: default
#
# Copyright 2012, Webtrends Inc.
#
# All rights reserved
#
#Install .NET 3.5 Feature if we don't find part of the package arleady installed
windows_feature "NetFx3" do
action :install
end |
#
# Cookbook Name:: ms_dotnet35
# Recipe:: default
#
# Copyright 2012, Webtrends Inc.
#
# All rights reserved
#
#Install .NET 3.5 Feature if we don't find part of the package arleady installed
case node['platform']
when "windows"
if (win_version.windows_server_2008? || win_version.windows_server_2008_r2? || win_version.windows_7? || win_version.windows_vista?)
if !File.exists?("C:/Windows/Microsoft.NET/Framework/v3.5")
windows_feature "NetFx3" do
action :install
end
end
elsif (win_version.windows_server_2003_r2? || win_version.windows_server_2003? || win_version.windows_xp?)
Chef::Log.warn('The .NET 3.5 Chef recipe currently only supports Windows Vista, 7, 2008, and 2008 R2.')
end
else
Chef::Log.warn('Microsoft .NET 3.5 can only be installed on the Windows platform.')
end
windows_feature "NetFx3" do
action :install
end
|
Add step to verify original Grouping | module KnowsTheDomain
def itunes
@itunes ||= Itunes.new
end
end
World(KnowsTheDomain)
# Scenario Outline: Get artist group and genre information
Given(/^track (\d+)$/) do |track_id|
itunes = Itunes.new
$track = itunes.album( track_id )
end
Then(/^artist "([^"]*)", album "([^"]*)", grouping "([^"]*)", genre "([^"]*)"$/) do |artist, album, grouping, genre|
expect($track["Artist"]).to eql(artist)
expect($track["Album"]).to eql(album)
expect($track["Grouping"]).to eql(grouping)
expect($track["Genre"]).to eql(genre)
end
# Scenario: Change group and genre information without saving to disk
Given(/^track with id (\d+)$/) do |track_id|
$track_id = track_id
$track = itunes.album( track_id )
end
When(/^I change the grouping to "([^"]*)"$/) do |new_grouping|
itunes.update_album( $track_id, "Grouping", new_grouping)
end
Then(/^all the album track groupings are "([^"]*)"$/) do |grouping|
expect(itunes.same?( $track_id, grouping)).to be_truthy
end
| module KnowsTheDomain
def itunes
@itunes ||= Itunes.new
end
end
World(KnowsTheDomain)
# Scenario Outline: Get artist group and genre information
Given(/^track (\d+)$/) do |track_id|
itunes = Itunes.new
$track = itunes.album( track_id )
end
Then(/^artist "([^"]*)", album "([^"]*)", grouping "([^"]*)", genre "([^"]*)"$/) do |artist, album, grouping, genre|
expect($track["Artist"]).to eql(artist)
expect($track["Album"]).to eql(album)
expect($track["Grouping"]).to eql(grouping)
expect($track["Genre"]).to eql(genre)
end
# Scenario: Change group and genre information without saving to disk
Given(/^track with id (\d+)$/) do |track_id|
$track_id = track_id
$track = itunes.album( track_id )
end
Given(/^an original grouping "([^"]*)"$/) do |old_grouping|
expect($track["Grouping"]).to eql(old_grouping)
end
When(/^I change the grouping to "([^"]*)"$/) do |new_grouping|
itunes.update_album( $track_id, "Grouping", new_grouping)
end
Then(/^all the album track groupings are "([^"]*)"$/) do |grouping|
expect(itunes.same?( $track_id, grouping)).to be_truthy
end
|
Add xhr handling for responses | class ResponsesController < ApplicationController
def new
if current_user != nil
@parent = parent_object
@parent_name = @parent.class.name.downcase.pluralize
@response = Response.new
else
redirect_to login_path
end
end
def create
@parent = parent_object
@response = @parent.responses.build(responder_id: current_user.id, content: params[:response][:content])
if @response.save
redirect_to parent_url(@parent)
else
flash.now[:alert] = "Comment must have content."
render :new
end
end
private
def parent_object
case
when params[:question_id] then Question.find(params[:question_id])
when params[:answer_id] then Answer.find(params[:answer_id])
end
end
def parent_url(parent)
case
when params[:question_id] then question_path(parent)
when params[:answer_id] then question_path(parent.question_id)
end
end
end
| class ResponsesController < ApplicationController
def new
if current_user != nil
@parent = parent_object
@parent_name = @parent.class.name.downcase.pluralize
@response = Response.new
if request.xhr?
render 'responses/_response_form.html.erb', locals: {parent: @parent, response: @response}, layout: false
else
render 'responses/new.html.erb'
end
else
redirect_to login_path
end
end
def create
@parent = parent_object
@response = @parent.responses.build(responder_id: current_user.id, content: params[:response][:content])
if @response.save
if request.xhr?
render 'responses/_response.html.erb', locals: {response: @response}, layout: false
else
redirect_to parent_url(@parent)
end
else
flash.now[:alert] = "Comment must have content."
render :new
end
end
private
def parent_object
case
when params[:question_id] then Question.find(params[:question_id])
when params[:answer_id] then Answer.find(params[:answer_id])
end
end
def parent_url(parent)
case
when params[:question_id] then question_path(parent)
when params[:answer_id] then question_path(parent.question_id)
end
end
end
|
Remove IBM from flavors tests | for provider, config in compute_providers
next if [:glesys, :voxel].include?(provider)
Shindo.tests("Fog::Compute[:#{provider}] | flavors", [provider]) do
flavors_tests(Fog::Compute[provider], (config[:flavors_attributes] || {}), config[:mocked])
end
end
| for provider, config in compute_providers
next if [:glesys, :voxel, :ibm].include?(provider)
Shindo.tests("Fog::Compute[:#{provider}] | flavors", [provider]) do
flavors_tests(Fog::Compute[provider], (config[:flavors_attributes] || {}), config[:mocked])
end
end
|
Make paper trail use a user's name instead of id | class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :authenticate_user!
private_class_method def self.active_tab(tab, *options)
before_action(*options) { @active_tab = tab }
end
private_class_method def self.require_permission(permission_options, *options)
before_action(*options) { PermissionError.check(current_user, permission_options) }
end
end
| class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :authenticate_user!
before_filter :set_paper_trail_whodunnit
def user_for_paper_trail
user_signed_in? ? current_user.name : 'Unknown'
end
private_class_method def self.active_tab(tab, *options)
before_action(*options) { @active_tab = tab }
end
private_class_method def self.require_permission(permission_options, *options)
before_action(*options) { PermissionError.check(current_user, permission_options) }
end
end
|
Move chef dependency to development, to avoid unintended chef gem update | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'chef/provider/service/daemontools/version'
Gem::Specification.new do |spec|
spec.name = "chef-provider-service-daemontools"
spec.version = Chef::Provider::Service::Daemontools::VERSION
spec.authors = ["HIROSE Masaaki"]
spec.email = ["hirose31@gmail.com"]
spec.summary = %q{Chef's provider to manage service under daemontools.}
spec.description = %q{Chef's provider to manage service under daemontools.}
spec.homepage = "https://github.com/hirose31/chef-provider-service-daemontools"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "chef"
spec.add_development_dependency "bundler", "~> 1.6"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'chef/provider/service/daemontools/version'
Gem::Specification.new do |spec|
spec.name = "chef-provider-service-daemontools"
spec.version = Chef::Provider::Service::Daemontools::VERSION
spec.authors = ["HIROSE Masaaki"]
spec.email = ["hirose31@gmail.com"]
spec.summary = %q{Chef's provider to manage service under daemontools.}
spec.description = %q{Chef's provider to manage service under daemontools.}
spec.homepage = "https://github.com/hirose31/chef-provider-service-daemontools"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.6"
spec.add_development_dependency "chef"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
end
|
Revert jquery change as was in kelkoo-services branch | $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "mixingpanel/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "mixingpanel"
s.version = Mixingpanel::VERSION
s.authors = ["Guillermo Guerrero"]
s.email = ["g.guerrero.bus@gmail.com"]
s.homepage = "https://github.com/gguerrero/mixingpanel"
s.summary = "High level utilities for using Mixpanel from your Rails project"
s.description = "High level utilities for using Mixpanel from your Rails project"
s.files = `git ls-files`.split("\n")
s.add_dependency "rails", ">= 3.2.14"
s.add_development_dependency 'rake'
s.add_development_dependency "jquery-rails"
s.add_development_dependency 'coffee-script'
s.add_development_dependency 'jasmine'
end
| $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "mixingpanel/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "mixingpanel"
s.version = Mixingpanel::VERSION
s.authors = ["Guillermo Guerrero"]
s.email = ["g.guerrero.bus@gmail.com"]
s.homepage = "https://github.com/gguerrero/mixingpanel"
s.summary = "High level utilities for using Mixpanel from your Rails project"
s.description = "High level utilities for using Mixpanel from your Rails project"
s.files = `git ls-files`.split("\n")
s.add_dependency "rails", ">= 3.2.14"
s.add_dependency "jquery-rails", '~> 2.1.4'
s.add_development_dependency 'rake'
s.add_development_dependency 'coffee-script'
s.add_development_dependency 'jasmine'
end
|
Improve concern syntax and definition | # frozen_string_literal: true
# Finds a unique permalink for a new or updated record.
# It considers soft-deleted records which are ignored by Spree.
# Spree's work:
# https://github.com/spree/spree/blob/09b55f7/core/lib/spree/core/permalinks.rb
#
# This may become obsolete with Spree 2.3.
# https://github.com/spree/spree/commits/master/core/lib/spree/core/permalinks.rb
module PermalinkGenerator
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def find_available_value(existing, requested)
return requested unless existing.include?(requested)
used_indices = existing.map do |p|
p.slice!(/^#{requested}/)
p.match(/^\d+$/).to_s.to_i
end
options = (1..used_indices.length + 1).to_a - used_indices
requested + options.first.to_s
end
end
def create_unique_permalink(requested)
existing = others.where("permalink LIKE ?", "#{requested}%").pluck(:permalink)
self.class.find_available_value(existing, requested)
end
def others
if id.nil?
scope_with_deleted
else
scope_with_deleted.where('id != ?', id)
end
end
def scope_with_deleted
if self.class.respond_to?(:with_deleted)
self.class.with_deleted
else
self.class.where(nil)
end
end
end
| # frozen_string_literal: true
# Finds a unique permalink for a new or updated record.
# It considers soft-deleted records which are ignored by Spree.
# Spree's work:
# https://github.com/spree/spree/blob/09b55f7/core/lib/spree/core/permalinks.rb
#
# This may become obsolete with Spree 2.3.
# https://github.com/spree/spree/commits/master/core/lib/spree/core/permalinks.rb
module PermalinkGenerator
extend ActiveSupport::Concern
class_methods do
def find_available_value(existing, requested)
return requested unless existing.include?(requested)
used_indices = existing.map do |p|
p.slice!(/^#{requested}/)
p.match(/^\d+$/).to_s.to_i
end
options = (1..used_indices.length + 1).to_a - used_indices
requested + options.first.to_s
end
end
private
def create_unique_permalink(requested)
existing = others.where("permalink LIKE ?", "#{requested}%").pluck(:permalink)
self.class.find_available_value(existing, requested)
end
def others
if id.nil?
scope_with_deleted
else
scope_with_deleted.where('id != ?', id)
end
end
def scope_with_deleted
if self.class.respond_to?(:with_deleted)
self.class.with_deleted
else
self.class.where(nil)
end
end
end
|
Correct issue with adding auth token in tests | module TestHelpers
#
# Authentication test helper
#
module AuthHelper
#
# Gets an auth token for the provided user
#
def auth_token(user = User.first)
user.extend_authentication_token(true)
user.auth_token
end
#
# Adds an authentication token to the hash data or string URL
# This prevents us from having to keep adding the :auth_token
# key to any GET/POST/PUT etc. data that is needed
#
def add_auth_token(data, user = User.first)
# Passed in an id instead of a user model? Find the user model from User.find
user = User.find(user) if user.is_a? Integer
if data.is_a? Hash
data[:auth_token] = auth_token user
elsif data.is_a? String
# If we have a question mark, we need to add a query paramater using &
# otherwise use ?
data << (data.include?('?') ? '&' : '?') << "auth_token=#{auth_token}"
end
data
end
#
# Alias for above for nicer usage (e.g., get with_auth_token "http://")
#
def with_auth_token(data, user = User.first)
add_auth_token data, user
end
module_function :auth_token
module_function :add_auth_token
module_function :with_auth_token
end
end
| module TestHelpers
#
# Authentication test helper
#
module AuthHelper
#
# Gets an auth token for the provided user
#
def auth_token(user = User.first)
user.extend_authentication_token(true)
user.auth_token
end
#
# Adds an authentication token to the hash data or string URL
# This prevents us from having to keep adding the :auth_token
# key to any GET/POST/PUT etc. data that is needed
#
def add_auth_token(data, user = User.first)
# Passed in an id instead of a user model? Find the user model from User.find
user = User.find(user) if user.is_a? Integer
if data.is_a? Hash
data[:auth_token] = auth_token user
elsif data.is_a? String
# If we have a question mark, we need to add a query paramater using &
# otherwise use ?
data << (data.include?('?') ? '&' : '?') << "auth_token=#{auth_token user}"
end
data
end
#
# Alias for above for nicer usage (e.g., get with_auth_token "http://")
#
def with_auth_token(data, user = User.first)
add_auth_token data, user
end
module_function :auth_token
module_function :add_auth_token
module_function :with_auth_token
end
end
|
Set podspec version to 1.0.1 | Pod::Spec.new do |s|
s.name = "AppInfoTracker"
s.version = "1.0.0"
s.summary = "App information tracker for your iOS, OS X, and tvOS app"
s.description = <<-DESC
* Install versions history.
* Tell you is First launch for certain version or build or today.
* Tell you numbers of startups for app.
DESC
s.homepage = "https://github.com/qiusuo8/AppInfoTracker"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Zhao Zhihui" => "zhihui.zhao.jl@gmail.com" }
s.social_media_url = "https://github.com/qiusuo8"
s.ios.deployment_target = "8.0"
s.tvos.deployment_target = "9.0"
s.osx.deployment_target = "10.10"
s.watchos.deployment_target = "2.0"
s.source = { :git => "https://github.com/qiusuo8/AppInfoTracker.git", :tag => s.version }
s.source_files = ["Sources/*.swift", "Sources/AppInfoTracker.h", "Sources/AppInfoTracker.swift"]
s.public_header_files = ["Sources/AppInfoTracker.h"]
s.requires_arc = true
s.framework = "Foundation"
s.pod_target_xcconfig = { 'SWIFT_VERSION' => '3.0' }
end
| Pod::Spec.new do |s|
s.name = "AppInfoTracker"
s.version = "1.0.1"
s.summary = "App information tracker for your iOS, OS X, and tvOS app"
s.description = <<-DESC
AppInfoTracker
* Install versions history.
* Tell you is First launch for certain version or build or today.
* Tell you numbers of startups for app.
DESC
s.homepage = "https://github.com/qiusuo8/AppInfoTracker"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Zhao Zhihui" => "zhihui.zhao.jl@gmail.com" }
s.social_media_url = "https://github.com/qiusuo8"
s.ios.deployment_target = "8.0"
s.tvos.deployment_target = "9.0"
s.osx.deployment_target = "10.10"
s.watchos.deployment_target = "2.0"
s.source = { :git => "https://github.com/qiusuo8/AppInfoTracker.git", :tag => s.version }
s.source_files = ["Sources/*.swift", "Sources/AppInfoTracker.h", "Sources/AppInfoTracker.swift"]
s.public_header_files = ["Sources/AppInfoTracker.h"]
s.requires_arc = true
s.framework = "Foundation"
s.pod_target_xcconfig = { 'SWIFT_VERSION' => '3.0' }
end
|
Test the existing behaviour of ResultSet. | require "test_helper"
require "document"
require "elasticsearch/result_set"
class ResultSetTest < ShouldaUnitTestCase
FIELDS = %w(link title description format)
def mappings
{
"edition" => {
"properties" => Hash[FIELDS.map { |f| [f, { "type" => "foo" }] }]
}
}
end
context "empty result set" do
setup do
@response = {
"hits" => {
"total" => 0,
"hits" => []
}
}
end
should "report zero results" do
assert_equal 0, ResultSet.new(mappings, @response).total
end
should "have an empty result set" do
assert_equal 0, ResultSet.new(mappings, @response).results.size
end
end
context "single result" do
setup do
@response = {
"hits" => {
"total" => 1,
"hits" => [
{
"_score" => 12,
"_source" => { "foo" => "bar" }
}
]
}
}
end
should "report one result" do
assert_equal 1, ResultSet.new(mappings, @response).total
end
should "pass the fields to Document.from_hash" do
expected_hash = has_entry("foo", "bar")
Document.expects(:from_hash).with(expected_hash, mappings).returns(:doc)
assert_equal [:doc], ResultSet.new(mappings, @response).results
end
should "pass the result score to Document.from_hash" do
expected_hash = has_entry("es_score", 12)
Document.expects(:from_hash).with(expected_hash, mappings).returns(:doc)
assert_equal [:doc], ResultSet.new(mappings, @response).results
end
end
end
| |
Remove line in spec helper that caused a LoadError for rspec 2.9.0 | require "spork"
require "factory_girl"
require "test/unit"
if RUBY_PLATFORM =~ /darwin/
require "spork/ext/ruby-debug"
end
ENV["RAILS_ENV"] ||= "test"
abort("RAILS_ENV != test") unless ENV["RAILS_ENV"] == "test"
Spork.prefork do
require File.expand_path("../../config/environment", __FILE__)
require "rspec/rails"
require "rspec/autorun"
require "capybara/rails"
require "database_cleaner"
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
RSpec.configure do |config|
config.mock_with :rspec
config.use_transactional_fixtures = false
config.before(:suite) { DatabaseCleaner.strategy = :truncation }
config.before(:each) { DatabaseCleaner.start }
config.after(:each) { DatabaseCleaner.clean }
config.infer_base_class_for_anonymous_controllers = false
config.mock_with :rspec
config.include Factory::Syntax::Methods
config.order = "random"
end
end
Spork.each_run do
ActiveSupport::Dependencies.clear
ActiveRecord::Base.instantiate_observers
load "#{Rails.root}/config/routes.rb"
Dir["#{Rails.root}/app/**/*.rb"].each { |f| load f }
FactoryGirl.factories.clear
FactoryGirl.sequences.clear
FactoryGirl.traits.clear
load "#{::Rails.root}/spec/factories.rb"
end
| require "spork"
require "factory_girl"
require "test/unit"
if RUBY_PLATFORM =~ /darwin/
require "spork/ext/ruby-debug"
end
ENV["RAILS_ENV"] ||= "test"
abort("RAILS_ENV != test") unless ENV["RAILS_ENV"] == "test"
Spork.prefork do
require File.expand_path("../../config/environment", __FILE__)
require "rspec/rails"
require "rspec/autorun"
require "capybara/rails"
require "database_cleaner"
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
RSpec.configure do |config|
config.mock_with :rspec
config.use_transactional_fixtures = false
config.before(:suite) { DatabaseCleaner.strategy = :truncation }
config.before(:each) { DatabaseCleaner.start }
config.after(:each) { DatabaseCleaner.clean }
config.infer_base_class_for_anonymous_controllers = false
config.mock_with :rspec
config.include Factory::Syntax::Methods
config.order = "random"
end
end
Spork.each_run do
ActiveRecord::Base.instantiate_observers
load "#{Rails.root}/config/routes.rb"
Dir["#{Rails.root}/app/**/*.rb"].each { |f| load f }
FactoryGirl.factories.clear
FactoryGirl.sequences.clear
FactoryGirl.traits.clear
load "#{::Rails.root}/spec/factories.rb"
end
|
Add t() to translate bug check | require 'checks/base_check'
require 'processors/lib/find_call'
#Check for vulnerability in translate() helper that allows cross-site scripting
#http://groups.google.com/group/rubyonrails-security/browse_thread/thread/2b61d70fb73c7cc5
class CheckTranslateBug < BaseCheck
Checks.add self
def run_check
if (version_between?('2.3.0', '2.3.99') and OPTIONS[:escape_html]) or
version_between?('3.0.0', '3.0.10') or
version_between?('3.1.0', '3.1.1')
if uses_translate?
confidence = CONFIDENCE[:high]
else
confidence = CONFIDENCE[:med]
end
version = tracker.config[:rails_version]
if version =~ /^3\.1/
message = "Versions before 3.1.2 have a vulnerability in the translate helper."
elsif version =~ /^3\.0/
message = "Versions before 3.0.11 have a vulnerability in translate helper."
else
message = "Rails 2.3.x using the rails_xss plugin have a vulnerability in translate helper."
end
warn :warning_type => "Cross Site Scripting",
:message => message,
:confidence => confidence,
:file => gemfile_or_environment
end
end
def uses_translate?
not tracker.find_call([], :translate).empty?
end
end
| require 'checks/base_check'
require 'processors/lib/find_call'
#Check for vulnerability in translate() helper that allows cross-site scripting
#http://groups.google.com/group/rubyonrails-security/browse_thread/thread/2b61d70fb73c7cc5
class CheckTranslateBug < BaseCheck
Checks.add self
def run_check
if (version_between?('2.3.0', '2.3.99') and OPTIONS[:escape_html]) or
version_between?('3.0.0', '3.0.10') or
version_between?('3.1.0', '3.1.1')
if uses_translate?
confidence = CONFIDENCE[:high]
else
confidence = CONFIDENCE[:med]
end
version = tracker.config[:rails_version]
if version =~ /^3\.1/
message = "Versions before 3.1.2 have a vulnerability in the translate helper."
elsif version =~ /^3\.0/
message = "Versions before 3.0.11 have a vulnerability in translate helper."
else
message = "Rails 2.3.x using the rails_xss plugin have a vulnerability in translate helper."
end
warn :warning_type => "Cross Site Scripting",
:message => message,
:confidence => confidence,
:file => gemfile_or_environment
end
end
def uses_translate?
not tracker.find_call([], [:t, :translate]).empty?
end
end
|
Change to fix logo output. | # encoding: utf-8
RSpec.describe 'rtty' do
it "prints available commands and global options" do
output = <<-OUT
\e[31m βββββ
βββ³ββ³β³ββ»βββ
β£ββ«ββ«ββ³β³β³ββ«
β βββ«ββ«βββ
β
β βββ»ββββ β
βββββββ»ββ»ββ
\e[0m
Commands:
rtty help [COMMAND] # Describe available commands or one specific command
rtty new PROJECT_NAME [OPTIONS] # Create a new command line app skeleton.
rtty version # tty version
Options:
[--no-color] # Disable colorization in output.
-r, [--dry-run], [--no-dry-run] # Run but do not make any changes.
[--debug], [--no-debug] # Run with debug logging.
OUT
command = "bundle exe rtty"
out = `#{command}`
expect(out).to eq(output)
end
end
| # encoding: utf-8
RSpec.describe 'rtty' do
it "prints available commands and global options" do
logo = <<-EOS
βββββ
βββ³ββ³β³ββ»βββ
β£ββ«ββ«ββ³β³β³ββ«
β βββ«ββ«βββ
β
β βββ»ββββ β
βββββββ»ββ»ββ
EOS
output = <<-OUT
\e[31m#{logo}\e[0m
Commands:
rtty help [COMMAND] # Describe available commands or one specific command
rtty new PROJECT_NAME [OPTIONS] # Create a new command line app skeleton.
rtty version # tty version
Options:
[--no-color] # Disable colorization in output.
-r, [--dry-run], [--no-dry-run] # Run but do not make any changes.
[--debug], [--no-debug] # Run with debug logging.
OUT
command = "bundle exe rtty"
out = `#{command}`
expect(out).to eq(output)
end
end
|
Fix this to use the puppetpath correctly. | require 'beaker-rspec'
UNSUPPORTED_PLATFORMS = [ 'windows', 'Solaris' ]
unless ENV['RS_PROVISION'] == 'no'
hosts.each do |host|
# Install Puppet
if host.is_pe?
install_pe
else
install_package host, 'rubygems'
on host, 'gem install puppet --no-ri --no-rdoc'
on host, "mkdir -p #{host['distmoduledir']}"
end
end
end
RSpec.configure do |c|
# Project root
proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..'))
# Readable test descriptions
c.formatter = :documentation
# Configure all nodes in nodeset
c.before :suite do
# Install module and dependencies
puppet_module_install(:source => proj_root, :module_name => 'ntp')
hosts.each do |host|
shell("/bin/touch #{default['distmoduledir']}/hiera.yaml")
shell('puppet module install puppetlabs-stdlib', :acceptable_exit_codes => [0,1])
end
end
end
| require 'beaker-rspec'
UNSUPPORTED_PLATFORMS = [ 'windows', 'Solaris' ]
unless ENV['RS_PROVISION'] == 'no'
hosts.each do |host|
# Install Puppet
if host.is_pe?
install_pe
else
install_package host, 'rubygems'
on host, 'gem install puppet --no-ri --no-rdoc'
on host, "mkdir -p #{host['distmoduledir']}"
end
end
end
RSpec.configure do |c|
# Project root
proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..'))
# Readable test descriptions
c.formatter = :documentation
# Configure all nodes in nodeset
c.before :suite do
# Install module and dependencies
puppet_module_install(:source => proj_root, :module_name => 'ntp')
hosts.each do |host|
shell("/bin/touch #{default['puppetpath']}/hiera.yaml")
shell('puppet module install puppetlabs-stdlib', :acceptable_exit_codes => [0,1])
end
end
end
|
Fix Rails 6 deprecation warning | require 'rubygems'
require 'bundler/setup'
require 'combustion'
Combustion.path = 'spec/rails/stub_app'
Combustion.initialize! :action_controller,
:action_view
require 'rspec/rails'
require 'capybara/rspec'
require 'capybara/rails'
require 'spec_helper'
require 'rails/support/mock_person'
# Ensure that the rails plugin is installed
require 'arbre/rails'
module AdditionalHelpers
def protect_against_forgery?
true
end
def form_authenticity_token(form_options: {})
"AUTH_TOKEN"
end
end
def mock_action_view(assigns = {})
controller = ActionView::TestCase::TestController.new
ActionView::Base.send :include, ActionView::Helpers
ActionView::Base.send :include, AdditionalHelpers
ActionView::Base.new(ActionController::Base.view_paths, assigns, controller)
end
RSpec.configure do |config|
config.include Capybara::RSpecMatchers
end
| require 'rubygems'
require 'bundler/setup'
require 'combustion'
Combustion.path = 'spec/rails/stub_app'
Combustion.initialize! :action_controller,
:action_view
require 'rspec/rails'
require 'capybara/rspec'
require 'capybara/rails'
require 'spec_helper'
require 'rails/support/mock_person'
# Ensure that the rails plugin is installed
require 'arbre/rails'
module AdditionalHelpers
def protect_against_forgery?
true
end
def form_authenticity_token(form_options: {})
"AUTH_TOKEN"
end
end
def mock_action_view(assigns = {})
controller = ActionView::TestCase::TestController.new
ActionView::Base.send :include, ActionView::Helpers
ActionView::Base.send :include, AdditionalHelpers
context = ActionView::LookupContext.new(ActionController::Base.view_paths)
ActionView::Base.new(context, assigns, controller)
end
RSpec.configure do |config|
config.include Capybara::RSpecMatchers
end
|
Build size by number of keys | class HashMap
attr_reader :weight
attr_reader :size
def initialize
@data = Array.new(10)
@size = 0
@weight = 0.8
end
def empty?
@size == 0
end
def underlying_size
@data.length
end
end
| class HashMap
attr_reader :weight
def initialize
@keys = []
@data = Array.new(10)
@weight = 0.8
end
def empty?
size == 0
end
def size
@keys.length
end
def underlying_size
@data.length
end
end
|
Add started_at and finished_at to Backupset, and use for statistics. | module Frakup
class Backupset
include DataMapper::Resource
property :id,
Serial
property :created_at,
DateTime
property :updated_at,
DateTime
has n, :backupelements
has n, :fileobjects, :through => :backupelements
def self.backup(source, target)
time_start = Time.now
$log.info "Backup started"
$log.info " - source: #{source}"
$log.info " - target: #{target}"
backupset = Backupset.create
$log.info " Created Backupset ##{backupset.id}"
Pathname.glob(File.join(source, "**", "*")).each do |f|
Backupelement.store(backupset, f)
end
time_stop = Time.now
$log.info " Backup finished"
$log.info " - duration: #{Time.at(time_stop - time_start).gmtime.strftime('%R:%S')}"
$log.info " - backupelements: #{backupset.backupelements.count}"
$log.info " - fileobjects: #{backupset.fileobjects.count}"
$log.info " - size: #{Frakup::Helper.human_size(backupset.fileobjects.sum(:size))}"
end
end
end
| module Frakup
class Backupset
include DataMapper::Resource
property :id,
Serial
property :created_at,
DateTime
property :updated_at,
DateTime
has n, :backupelements
has n, :fileobjects, :through => :backupelements
property :started_at,
DateTime
property :finished_at,
DateTime
def self.backup(source, target)
$log.info "Backup started"
$log.info " - source: #{source}"
$log.info " - target: #{target}"
backupset = Backupset.create(
:started_at => Time.now
)
$log.info " Created Backupset ##{backupset.id}"
Pathname.glob(File.join(source, "**", "*")).each do |f|
Backupelement.store(backupset, f)
end
backupset.finished_at = Time.now
backupset.save
$log.info " Backup finished"
$log.info " - duration: #{Time.at(backupset.finished_at - backupset.started_at).gmtime.strftime('%R:%S')}"
$log.info " - backupelements: #{backupset.backupelements.count}"
$log.info " - fileobjects: #{backupset.fileobjects.count}"
$log.info " - size: #{Frakup::Helper.human_size(backupset.fileobjects.sum(:size))}"
end
end
end
|
Comment out the feature test as it wasn't completed | require 'spec_helper'
feature "Build an addition" do
scenario "User wants to build an addition" do
visit "/permits/new"
check "permit[addition]"
click_button "Submit"
expect(page).to have_text("Enter your address")
end
end | require 'spec_helper'
feature "Build an addition" do
scenario "User wants to build an addition" do
# visit "/permits/new"
# check "permit[addition]"
# click_button "Submit"
# expect(page).to have_text("Enter your address")
end
end |
Raise a proper exception for 422 | module Quaderno
module Exceptions
class InvalidSubdomainOrToken < Exception
end
class InvalidID < Exception
end
class RateLimitExceeded < Exception
end
class HasAssociatedDocuments < Exception
end
class RequiredFieldsEmpty < Exception
end
def self.included(receiver)
receiver.send :extend, ClassMethods
end
module ClassMethods
def check_exception_for(party_response, params = {})
if params[:rate_limit].nil? == false
raise(Quaderno::Exceptions::RateLimitExceeded, 'Rate limit exceeded') if party_response.response.class == Net::HTTPForbidden
end
if params[:subdomain_or_token].nil? == false
raise(Quaderno::Exceptions::InvalidSubdomainOrToken, 'Invalid subdomain or token') if party_response.response.class == Net::HTTPUnauthorized
end
if params[:id].nil? == false
raise(Quaderno::Exceptions::InvalidID, "Invalid #{ api_model } instance identifier") if (party_response.response.class == Net::HTTPInternalServerError) || (party_response.response.class == Net::HTTPNotFound)
end
if params[:required_fields].nil? == false
raise(Quaderno::Exceptions::RequiredFieldsEmpty, "#{ JSON::parse party_response.body }") if party_response.response.class == Net::HTTPClientError
end
if params[:has_documents].nil? == false
raise(Quaderno::Exceptions::HasAssociatedDocuments, "#{ JSON::parse party_response.body }") if party_response.response.class == Net::HTTPClientError
end
end
end
end
end | module Quaderno
module Exceptions
class InvalidSubdomainOrToken < Exception
end
class InvalidID < Exception
end
class RateLimitExceeded < Exception
end
class HasAssociatedDocuments < Exception
end
class RequiredFieldsEmpty < Exception
end
def self.included(receiver)
receiver.send :extend, ClassMethods
end
module ClassMethods
def check_exception_for(party_response, params = {})
if params[:rate_limit].nil? == false
raise(Quaderno::Exceptions::RateLimitExceeded, 'Rate limit exceeded') if party_response.response.class == Net::HTTPForbidden
end
if params[:subdomain_or_token].nil? == false
raise(Quaderno::Exceptions::InvalidSubdomainOrToken, 'Invalid subdomain or token') if party_response.response.class == Net::HTTPUnauthorized
end
if params[:id].nil? == false
raise(Quaderno::Exceptions::InvalidID, "Invalid #{ api_model } instance identifier") if (party_response.response.class == Net::HTTPInternalServerError) || (party_response.response.class == Net::HTTPNotFound)
end
debugger
if params[:required_fields].nil? == false
raise(Quaderno::Exceptions::RequiredFieldsEmpty, "#{ JSON::parse party_response.body }") if party_response.response.class == Net::HTTPUnprocessableEntity
end
if params[:has_documents].nil? == false
raise(Quaderno::Exceptions::HasAssociatedDocuments, "#{ JSON::parse party_response.body }") if party_response.response.class == Net::HTTPClientError
end
end
end
end
end |
Update Thunderbird Beta to 32.0b1 | class ThunderbirdBeta < Cask
version '31.0b3'
sha256 '82cf13b42f72a660920cfd025220d2ce9ddfb56327b01721b4b02e065752061d'
url 'https://download-installer.cdn.mozilla.net/pub/thunderbird/releases/31.0b3/mac/en-US/Thunderbird%2031.0b3.dmg'
homepage 'https://www.mozilla.org/en-US/thunderbird/all-beta.html'
link 'Thunderbird.app'
end
| class ThunderbirdBeta < Cask
version '32.0b1'
sha256 '0f66e9cb452293e248d92c9a156c0b81c50e81ba1107922ab6f8b555934e83d3'
url 'https://download-installer.cdn.mozilla.net/pub/thunderbird/releases/32.0b1/mac/en-US/Thunderbird%2032.0b1.dmg'
homepage 'https://www.mozilla.org/en-US/thunderbird/all-beta.html'
link 'Thunderbird.app'
end
|
Add test for travis variant with single ruby version | describe 'travis.yml' do
it "matches versions and excludes" do
travis = YAML.safe_load(File.open(ManageIQ::UI::Classic::Engine.root.join('.travis.yml')))
versions = travis['rvm']
if versions.length > 1
excludes = travis.dig('matrix', 'exclude').map { |ex| ex['rvm'] }.sort.uniq
expect(excludes.length).to eq(versions.length - 1)
expect(versions[0..-2]).to eq(excludes)
end
end
end
| describe 'travis.yml' do
let(:travis) { YAML.safe_load(File.open(ManageIQ::UI::Classic::Engine.root.join('.travis.yml'))) }
let(:versions) { travis['rvm'] }
it "matches versions and excludes for multiple ruby versions" do
if versions.length > 1
excludes = travis.dig('matrix', 'exclude').map { |ex| ex['rvm'] }.sort.uniq
expect(excludes.length).to eq(versions.length - 1)
expect(versions[0..-2]).to eq(excludes)
end
end
it "does not exclude any testsuite for single ruby version" do
if versions.length == 1
excludes = travis.dig('matrix', 'exclude')
expect(excludes).to be(nil)
end
end
end
|
Add new time travel example | describe 'Time travel with ActiveSupport::Testing::TimeHelpers' do
context 'travel_back' do
before { travel_to Time.new(2004, 11, 24, 01, 04, 44) }
after { travel_back }
it do
expect(Time.current.year).to eq 2004
expect(Time.now.year).to eq 2004
# ensure knapsack_pro adds raw method
# to detect real time
expect(Time.raw_now.year).to be >= 2017
end
end
context 'travel_to block' do
let!(:yesterday) { 1.day.ago }
it do
travel_to(1.day.ago) do
expect(Time.current.day).to eq yesterday.day
expect(Time.raw_now.year).to be >= 2017
end
end
end
end
| describe 'Time travel with ActiveSupport::Testing::TimeHelpers' do
context 'travel_back' do
before { travel_to Time.new(2004, 11, 24, 01, 04, 44) }
after { travel_back }
it do
expect(Time.current.year).to eq 2004
expect(Time.now.year).to eq 2004
# ensure knapsack_pro adds raw method
# to detect real time
expect(Time.raw_now.year).to be >= 2017
end
end
context 'travel_to block' do
let!(:yesterday) { 1.day.ago }
it do
travel_to(1.day.ago) do
expect(Time.current.day).to eq yesterday.day
expect(Time.raw_now.year).to be >= 2017
end
end
end
context 'travel_to block 2014' do
let!(:time_2014) { Time.new(2004, 11, 24, 01, 04, 44) }
it do
travel_to(time_2014) do
expect(Time.current.year).to eq 2004
expect(Time.raw_now.year).to be >= 2017
end
end
end
end
|
Use pkg_info for check_is_installed and get_version | class Specinfra::Command::Smartos::Base::Package < Specinfra::Command::Solaris::Base::Package
class << self
def check_is_installed(package, version=nil)
cmd = "/opt/local/bin/pkgin list 2> /dev/null | grep -qw ^#{escape(package)}"
if version
cmd = "#{cmd}-#{escape(version)}"
end
cmd
end
def get_version(package, opts=nil)
"pkgin list | cut -f 1 -d ' ' | grep -E '^#{escape(package)}-([^-])+$' | grep -Eo '(\\.|\\w)+$'"
end
end
end
| class Specinfra::Command::Smartos::Base::Package < Specinfra::Command::Solaris::Base::Package
class << self
def check_is_installed(package, version=nil)
cmd = "pkg_info -qE #{escape(package)}"
if version
cmd = "#{cmd}-#{escape(version)}"
end
cmd
end
def get_version(package, opts=nil)
"pkg_info -E #{escape(package)} | awk -F '-' '{print $NF}'"
end
end
end
|
Fix typo in the XSRF token header | class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :authenticate
after_filter :set_csrf_cookie_for_ng
helper_method :current_user, :signed_in?
private
def authenticate
unless signed_in?
redirect_to sign_in_path
end
end
def signed_in?
current_user.present?
end
def current_user
@current_user ||= User.where(remember_token: session[:remember_token]).first
end
def set_csrf_cookie_for_ng
cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery?
end
def verified_request?
super || form_authenticity_token == request.headers['X_XSRF_TOKEN']
end
end
| class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :authenticate
after_filter :set_csrf_cookie_for_ng
helper_method :current_user, :signed_in?
private
def authenticate
unless signed_in?
redirect_to sign_in_path
end
end
def signed_in?
current_user.present?
end
def current_user
@current_user ||= User.where(remember_token: session[:remember_token]).first
end
def set_csrf_cookie_for_ng
if protect_against_forgery?
cookies['XSRF-TOKEN'] = form_authenticity_token
end
end
protected
def verified_request?
super || form_authenticity_token == request.headers['X-XSRF-TOKEN']
end
end
|
Add a spec for BasicObject subclasses that include Kernel (from JRUBY-4871) | require File::join( File::dirname(__FILE__), %w{ .. .. spec_helper } )
ruby_version_is "1.9" do
require File::join( File::dirname(__FILE__), %w{ shared behavior } )
MyBO = Class::new BasicObject
describe "BasicObject's subclasses behave" do
extend BasicObjectBehavior
it "privately" do
MyBO.private_instance_methods.sort.should == private_features.sort
end
it "protectedly" do
MyBO.protected_instance_methods.sort.should == protected_features.sort
end
it "publically" do
MyBO.instance_methods.sort.should == public_features.sort
end
end
end
| require File::join( File::dirname(__FILE__), %w{ .. .. spec_helper } )
ruby_version_is "1.9" do
require File::join( File::dirname(__FILE__), %w{ shared behavior } )
MyBO = Class::new BasicObject
describe "BasicObject's subclasses" do
extend BasicObjectBehavior
it "contain only private methods from BasicObject" do
MyBO.private_instance_methods.sort.should == private_features.sort
end
it "contain only protected methods from BasicObject" do
MyBO.protected_instance_methods.sort.should == protected_features.sort
end
it "contain only public methods from BasicObject" do
MyBO.instance_methods.sort.should == public_features.sort
end
it "can mix in Kernel and Kernel's methods work properly" do
cls = Class.new BasicObject
cls.send :include, Kernel
obj = cls.new
# obviously not testing every method, but a sampling should suffice
obj.instance_variables.should == []
obj.instance_variable_set(:@foo, 'foo').should == 'foo'
obj.instance_variable_get(:@foo).should == 'foo'
lambda {obj.send :hash}.should_not raise_error
end
end
end
|
Add VERSION_INFO for easier machine parsing. | module RestClient
VERSION = '2.0.0.alpha' unless defined?(self::VERSION)
def self.version
VERSION
end
end
| module RestClient
VERSION_INFO = [2, 0, 0, 'alpha'] unless defined?(self::VERSION_INFO)
VERSION = VERSION_INFO.map(&:to_s).join('.') unless defined?(self::VERSION)
def self.version
VERSION
end
end
|
Fix content controller icon (use new font-awesome icon name) | Releaf.setup do |conf|
# Default settings are commented out
### setup menu items and therefore available controllers
conf.menu = [
{
:controller => 'releaf/content',
:helper => 'releaf_nodes',
:icon => 'file-text-alt',
},
{
:name => "inventory",
:items => %w[admin/books admin/authors],
:icon => 'briefcase',
},
{
:name => "permissions",
:items => %w[releaf/admins releaf/roles],
:icon => 'user',
},
{
:controller => 'releaf/translations',
:helper => 'releaf_translation_groups',
:icon => 'group',
},
]
conf.available_locales = ["en", "lv"]
# conf.layout = 'releaf/admin'
# conf.devise_for 'releaf/admin'
end
| Releaf.setup do |conf|
# Default settings are commented out
### setup menu items and therefore available controllers
conf.menu = [
{
:controller => 'releaf/content',
:helper => 'releaf_nodes',
:icon => 'file-text-o',
},
{
:name => "inventory",
:items => %w[admin/books admin/authors],
:icon => 'briefcase',
},
{
:name => "permissions",
:items => %w[releaf/admins releaf/roles],
:icon => 'user',
},
{
:controller => 'releaf/translations',
:helper => 'releaf_translation_groups',
:icon => 'group',
},
]
conf.available_locales = ["en", "lv"]
# conf.layout = 'releaf/admin'
# conf.devise_for 'releaf/admin'
end
|
Add application GitUp to Cask | cask :v1 => 'gitup' do
version :latest
sha256 :no_check
# amazonaws.com is the official download host per the vendor homepage
url 'https://s3-us-west-2.amazonaws.com/gitup-builds/stable/GitUp.zip'
name 'GitUp'
homepage 'http://gitup.co'
license :gratis
app 'GitUp.app'
end
| |
Add a minimal spec for the 'undef' keyword | require File.dirname(__FILE__) + '/../spec_helper'
| require File.dirname(__FILE__) + '/../spec_helper'
class UndefSpecClass
def meth=(other);nil;end
end
describe "The undef keyword" do
it "should undefine 'meth='" do
obj = UndefSpecClass.new
(obj.meth = 5).should == 5
class UndefSpecClass
undef meth=
end
should_raise(NoMethodError) { obj.meth = 5 }
end
end
|
Fix migration without DOWNTIME clause specified | class MigrateUsersNotificationLevel < ActiveRecord::Migration
# Migrates only users who changed their default notification level :participating
# creating a new record on notification settings table
DOWNTIME = false
def up
execute(%Q{
INSERT INTO notification_settings
(user_id, level, created_at, updated_at)
(SELECT id, notification_level, created_at, updated_at FROM users WHERE notification_level != 1)
})
end
# Migrates from notification settings back to user notification_level
# If no value is found the default level of 1 will be used
def down
execute(%Q{
UPDATE users u SET
notification_level = COALESCE((SELECT level FROM notification_settings WHERE user_id = u.id AND source_type IS NULL), 1)
})
end
end
| class MigrateUsersNotificationLevel < ActiveRecord::Migration
DOWNTIME = false
# Migrates only users who changed their default notification level :participating
# creating a new record on notification settings table
DOWNTIME = false
def up
execute(%Q{
INSERT INTO notification_settings
(user_id, level, created_at, updated_at)
(SELECT id, notification_level, created_at, updated_at FROM users WHERE notification_level != 1)
})
end
# Migrates from notification settings back to user notification_level
# If no value is found the default level of 1 will be used
def down
execute(%Q{
UPDATE users u SET
notification_level = COALESCE((SELECT level FROM notification_settings WHERE user_id = u.id AND source_type IS NULL), 1)
})
end
end
|
Add a method to resolve the message that was reacted to | # frozen_string_literal: true
require 'discordrb/events/generic'
require 'discordrb/data'
module Discordrb::Events
# Generic superclass for events about adding and removing reactions
class ReactionEvent
# @return [Emoji] the emoji that was reacted with.
attr_reader :emoji
def initialize(data, bot)
@bot = bot
@emoji = Discordrb::Emoji.new(data['emoji'], bot, nil)
@user_id = data['user_id'].to_i
@message_id = data['message_id'].to_i
@channel_id = data['channel_id'].to_i
end
# @return [User] the user that reacted to this message.
def user
# Cache the user so we don't do requests all the time
@user ||= @bot.user(@user_id)
end
end
end
| # frozen_string_literal: true
require 'discordrb/events/generic'
require 'discordrb/data'
module Discordrb::Events
# Generic superclass for events about adding and removing reactions
class ReactionEvent
# @return [Emoji] the emoji that was reacted with.
attr_reader :emoji
def initialize(data, bot)
@bot = bot
@emoji = Discordrb::Emoji.new(data['emoji'], bot, nil)
@user_id = data['user_id'].to_i
@message_id = data['message_id'].to_i
@channel_id = data['channel_id'].to_i
end
# @return [User] the user that reacted to this message.
def user
# Cache the user so we don't do requests all the time
@user ||= @bot.user(@user_id)
end
# @return [Message] the message that was reacted to.
def message
@message ||= channel.load_message(@message_id)
end
end
end
|
Add forgotten Property.drop_table on migration file | class AddTranslationsToMainModels < ActiveRecord::Migration
def up
params = { :name => :string, :description => :text, :meta_description => :string,
:meta_keywords => :string }
Spree::Product.create_translation_table!(params, { :migrate_data => true })
params = { :name => :string, :description => :string }
Spree::Promotion.create_translation_table!(params, { :migrate_data => true })
params = { :name => :string, :presentation => :string }
Spree::OptionType.create_translation_table!(params, { :migrate_data => true })
Spree::Property.create_translation_table!(params, { :migrate_data => true })
Spree::Taxonomy.create_translation_table!({ :name => :string }, { :migrate_data => true })
params = { :name => :string, :description => :text, :meta_title => :string,
:meta_description => :string, :meta_keywords => :string,
:permalink => :string }
Spree::Taxon.create_translation_table!(params, { :migrate_data => true })
end
def down
Spree::Product.drop_translation_table! :migrate_data => true
Spree::Promotion.drop_translation_table! :migrate_data => true
Spree::OptionType.drop_translation_table! :migrate_data => true
Spree::Taxonomy.drop_translation_table! :migrate_data => true
Spree::Taxon.drop_translation_table! :migrate_data => true
end
end
| class AddTranslationsToMainModels < ActiveRecord::Migration
def up
params = { :name => :string, :description => :text, :meta_description => :string,
:meta_keywords => :string }
Spree::Product.create_translation_table!(params, { :migrate_data => true })
params = { :name => :string, :description => :string }
Spree::Promotion.create_translation_table!(params, { :migrate_data => true })
params = { :name => :string, :presentation => :string }
Spree::OptionType.create_translation_table!(params, { :migrate_data => true })
Spree::Property.create_translation_table!(params, { :migrate_data => true })
Spree::Taxonomy.create_translation_table!({ :name => :string }, { :migrate_data => true })
params = { :name => :string, :description => :text, :meta_title => :string,
:meta_description => :string, :meta_keywords => :string,
:permalink => :string }
Spree::Taxon.create_translation_table!(params, { :migrate_data => true })
end
def down
Spree::Product.drop_translation_table! :migrate_data => true
Spree::Promotion.drop_translation_table! :migrate_data => true
Spree::Property.drop_translation_table! :migrate_data => true
Spree::OptionType.drop_translation_table! :migrate_data => true
Spree::Taxonomy.drop_translation_table! :migrate_data => true
Spree::Taxon.drop_translation_table! :migrate_data => true
end
end
|
Add cask for Aquamacs version of emacs. | class Aquamacs < Cask
url 'http://downloads.sourceforge.net/project/aquamacs/Releases/Aquamacs-Emacs-2.4.dmg'
homepage 'http://aquamacs.org/'
version '2.4'
end
| |
Use a different config for Unicorn in development | worker_processes 4
timeout 30
preload_app true
| if ENV['RACK_ENV'] == 'development'
worker_processes 1
else
worker_processes 4
timeout 30
end
preload_app true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.