Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add working fax test code
require 'phaxio' require 'pry' Phaxio.config do |config| config.api_key = ENV['PHAXIO_API_KEY'] config.api_secret = ENV['PHAXIO_API_SECRET'] end file1 = File.new('/tmp/application_2bedc7f5a4bcfa8dbb32afac6fccd499-6-signed.png') file2 = File.new('/tmp/application_2bedc7f5a4bcfa8dbb32afac6fccd499-7.png') result = Phaxio.send_fax(to: ENV['FAX_DESTINATION_NUMBER'], filename: [file1, file2]) binding.pry
Allow indifferent access for content item hash
module PublishingApiHelper # state_history returns a hash like {"3"=>"draft", "2"=>"published", "1"=>"superseded"} # so we need to get the highest value for a key. def latest_edition_number(content_id, publication_state: "") latest_content_item = content_item(content_id) if publication_state.present? version = latest_content_item[:state_history].select { |_, hash| hash[publication_state] } return version.keys.first.to_i end latest_content_item[:state_history].keys.max.to_i end def content_item(content_id) Services.publishing_api.get_content(content_id) end end
module PublishingApiHelper # state_history returns a hash like {"3"=>"draft", "2"=>"published", "1"=>"superseded"} # so we need to get the highest value for a key. def latest_edition_number(content_id, publication_state: "") latest_content_item = content_item(content_id).with_indifferent_access if publication_state.present? version = latest_content_item[:state_history].select { |_, hash| hash[publication_state] } return version.keys.first.to_i end latest_content_item[:state_history].keys.max.to_i end def content_item(content_id) Services.publishing_api.get_content(content_id) end end
Use gif as podspec screenshot.
Pod::Spec.new do |s| s.name = "ASCFlatUIColor" s.version = "0.1.0" s.summary = "A collection of all Flat UI Colors." s.homepage = "https://github.com/schneiderandre/ASCFlatUIColor" s.screenshots = [ "https://dl.dropboxusercontent.com/u/19150300/Github/ASCFlatUIColor/iphone_white_1.png", "https://dl.dropboxusercontent.com/u/19150300/Github/ASCFlatUIColor/iphone_white_2.png" ] s.license = 'MIT' s.author = { "André Schneider" => "hello@andreschneider.me" } s.source = { :git => "https://github.com/schneiderandre/ASCFlatUIColor.git", :tag => s.version.to_s } s.social_media_url = 'https://twitter.com/aschndr' s.platform = :ios, '5.0' s.requires_arc = true s.source_files = 'Classes/*.{h,m}' end
Pod::Spec.new do |s| s.name = "ASCFlatUIColor" s.version = "0.1.0" s.summary = "A collection of all Flat UI Colors." s.homepage = "https://github.com/schneiderandre/ASCFlatUIColor" s.screenshot = "https://dl.dropboxusercontent.com/u/19150300/Github/ASCFlatUIColor/ASCFlatUIColor.gif" s.license = 'MIT' s.author = { "André Schneider" => "hello@andreschneider.me" } s.source = { :git => "https://github.com/schneiderandre/ASCFlatUIColor.git", :tag => s.version.to_s } s.social_media_url = 'https://twitter.com/aschndr' s.platform = :ios, '5.0' s.requires_arc = true s.source_files = 'Classes/*.{h,m}' end
Switch AppCleaner to no checksum
class Appcleaner < Cask url 'http://www.freemacsoft.net/downloads/AppCleaner_2.2.1.zip' homepage 'http://www.freemacsoft.net/appcleaner/' version '2.2.1' sha1 'd52dfbed9903799d21753be7fdd229c7277fba2a' link 'AppCleaner.app' end
class Appcleaner < Cask url 'http://www.freemacsoft.net/downloads/AppCleaner_2.2.1.zip' homepage 'http://www.freemacsoft.net/appcleaner/' version '2.2.1' no_checksum link 'AppCleaner.app' end
Update Data Science Studio to 2.2.2 and add gratis license
cask 'data-science-studio' do version '2.0.0' sha256 '97a2e10d14a26d337ba71170ddc5e4ad6e2b3eafe36adcd02048c7da2d402774' url "https://downloads.dataiku.com/public/studio/Data%20Science%20Studio%20#{version}.dmg" name 'Dataiku Data Science Studio' homepage 'https://www.dataiku.com' license :unknown # TODO: change license and remove this comment; ':unknown' is a machine-generated placeholder app 'DataScienceStudio.app' end
cask 'data-science-studio' do version '2.2.2' sha256 '4644cf19ba15acfadedfed1f005d9ac9a8970a829e4fdb0c8b7f7246f69ddaef' url "https://downloads.dataiku.com/public/studio/#{version}/Data%20Science%20Studio%20#{version}.dmg" name 'Dataiku Data Science Studio' homepage 'https://www.dataiku.com' license :gratis app 'DataScienceStudio.app' end
Use ruby 1.9 hash syntax
# Migration responsible for creating a table with activities class CreateActivities < ActiveRecord::Migration # Create table def self.up create_table :activities do |t| t.belongs_to :trackable, :polymorphic => true t.belongs_to :owner, :polymorphic => true t.string :key t.text :parameters t.belongs_to :recipient, :polymorphic => true t.timestamps end add_index :activities, [:trackable_id, :trackable_type] add_index :activities, [:owner_id, :owner_type] add_index :activities, [:recipient_id, :recipient_type] end # Drop table def self.down drop_table :activities end end
# Migration responsible for creating a table with activities class CreateActivities < ActiveRecord::Migration # Create table def self.up create_table :activities do |t| t.belongs_to :trackable, polymorphic: true t.belongs_to :owner, polymorphic: true t.string :key t.text :parameters t.belongs_to :recipient, polymorphic: true t.timestamps end add_index :activities, [:trackable_id, :trackable_type] add_index :activities, [:owner_id, :owner_type] add_index :activities, [:recipient_id, :recipient_type] end # Drop table def self.down drop_table :activities end end
Fix posts/index.html is not found
require './config/app.rb' module Rack class ScsBlog < Static def call(env) status, headers, response = @file_server.call(env) if status == 404 if env["PATH_INFO"] == "/" env["PATH_INFO"] = "index.html" else env["PATH_INFO"] = "#{env["PATH_INFO"]}.html" end status, headers, response = @file_server.call(env) if status == 404 env["PATH_INFO"] = App::ERROR_404_PATH end end super end end end use Rack::ScsBlog, :urls => [""], :root => "build", :index => 'index.html' run lambda { |env| [ 200, { 'Content-Type' => 'text/html', 'Cache-Control' => 'public, max-age=86400' }, File.open('build/index.html', File::RDONLY) ] }
require './config/app.rb' module Rack class ScsBlog < Static def call(env) status, headers, response = @file_server.call(env) if status == 404 ori_path = env["PATH_INFO"] if ori_path == "/" env["PATH_INFO"] = "index.html" else env["PATH_INFO"] = "#{ori_path}.html" status, headers, response = @file_server.call(env) if status == 404 env["PATH_INFO"] = "#{ori_path}/index.html" status, headers, response = @file_server.call(env) env["PATH_INFO"] = App::ERROR_404_PATH if status == 404 end end end super end end end use Rack::ScsBlog, :urls => [""], :root => "build", :index => 'index.html' run lambda { |env| [ 200, { 'Content-Type' => 'text/html', 'Cache-Control' => 'public, max-age=86400' }, File.open('build/index.html', File::RDONLY) ] }
Add Reviewer so Invenio can fetch and review Pull Requests
module Invenio class Reviewer attr_reader :client, :pull_requests def self.run reviewer = new reviewer.fetch reviewer.review end def initialize(client = GitHub::Client.new) @client = client @pull_requests = [] end def fetch end def review end end end
Add version to user agent
require 'faraday_middleware' module MtGox module Connection private def connection options = { :ssl => {:verify => false}, :url => 'https://mtgox.com', :headers => {:user_agent => "MtGoxGem"} } Faraday.new(options) do |connection| connection.use Faraday::Request::UrlEncoded connection.use Faraday::Response::RaiseError connection.use Faraday::Response::Rashify connection.use Faraday::Response::ParseJson connection.adapter(Faraday.default_adapter) end end end end
require 'faraday_middleware' require 'mtgox/version' module MtGox module Connection private def connection options = { :headers => { :user_agent => "mtgox gem #{MtGox::VERSION}", }, :ssl => {:verify => false}, :url => 'https://mtgox.com', } Faraday.new(options) do |connection| connection.use Faraday::Request::UrlEncoded connection.use Faraday::Response::RaiseError connection.use Faraday::Response::Rashify connection.use Faraday::Response::ParseJson connection.adapter(Faraday.default_adapter) end end end end
Clean up utf8 as we go.
# encoding: UTF-8 module Buildbox class Result require 'securerandom' attr_reader :uuid, :command attr_accessor :finished, :exit_status def initialize(command) @uuid = SecureRandom.uuid @output = "" @finished = false @command = command end def finished? finished end def success? exit_status == 0 end def append(chunk) @output += chunk end def output Buildbox::UTF8.clean(@output).chomp end def as_json { :uuid => @uuid, :command => @command, :output => output, :exit_status => @exit_status } end end end
# encoding: UTF-8 module Buildbox class Result require 'securerandom' attr_reader :uuid, :command attr_accessor :finished, :exit_status def initialize(command) @uuid = SecureRandom.uuid @output = "" @finished = false @command = command end def finished? finished end def success? exit_status == 0 end def append(chunk) @output += Buildbox::UTF8.clean(chunk) end def output @output.chomp end def as_json { :uuid => @uuid, :command => @command, :output => output, :exit_status => @exit_status } end end end
Fix issue with 414 error when posting to create a document
module Doccy class Documents def self.create(auth_token, template_id, document_params) options = { query: { auth_token: auth_token, document: document_params} } response = HTTParty.post("#{Doccy::Config.url}/templates/#{template_id}/documents.json", options) end def self.get(auth_token, template_id, document_id) options = { query: { auth_token: auth_token} } response = HTTParty.get("#{Doccy::Config.url}/templates/#{template_id}/documents/#{document_id}.json", options) end def self.download(auth_token, template_id, document_id, original=nil) if original options = { query: { auth_token: auth_token, original: true} } else options = { query: { auth_token: auth_token} } end response = HTTParty.get("#{Doccy::Config.url}/templates/#{template_id}/documents/#{document_id}/download.json", options) end end end
module Doccy class Documents def self.create(auth_token, template_id, document_params) # options = { query: { auth_token: auth_token, document: document_params} } options = { body: { auth_token: auth_token, document: document_params} } response = HTTParty.post("#{Doccy::Config.url}/templates/#{template_id}/documents.json", options) end def self.get(auth_token, template_id, document_id) options = { query: { auth_token: auth_token} } response = HTTParty.get("#{Doccy::Config.url}/templates/#{template_id}/documents/#{document_id}.json", options) end def self.download(auth_token, template_id, document_id, original=nil) if original options = { query: { auth_token: auth_token, original: true} } else options = { query: { auth_token: auth_token} } end response = HTTParty.get("#{Doccy::Config.url}/templates/#{template_id}/documents/#{document_id}/download.json", options) end end end
Add seed file which populates questions with comments
require 'faker' 20.times do Question.create!( title: Faker::Lorem.sentence, content: Faker::Lorem.paragraph, asker_id: rand(100), best_answer_id: rand(100)) end
require 'faker' 20.times do question = Question.create!( title: Faker::Lorem.sentence, content: Faker::Lorem.paragraph, asker_id: rand(100), best_answer_id: rand(100)) 5.times do question.comments << Comment.create!(content: Faker::Lorem.sentence) end end
Add Gravatar module for User model. Prefills data on registration
module Gravatar # Provides methods for social data added through Gravatar's Verified Services extend ActiveSupport::Concern included do %w(facebook flickr twitter linkedin).map do |network_name| # Defines predicate methods when module is loaded # Example: # User.first.linkedin? # => true # define_method "#{network_name}?" do account_names.include?(network_name) end # Defines dynamic getter methods when module is loaded # Example: # User.first.twitter # => "JonahBinario" # define_method network_name do social_info.send(network_name) if send("#{network_name}?") end end after_validation :prefill_social_data, if: :new_record? end def prefill_social_data self.facebook_username = self.facebook if self.facebook? self.flickr_username = self.flickr if self.flickr? self.twitter_username = self.twitter if self.twitter? self.linkedin_username = self.linkedin if self.linkedin? self.bio = self.about_me unless self.about_me.nil? end def gravatar_user_hash Digest::MD5::hexdigest(self.email.downcase) end # Returns an OpenStruct object with methods for each account found # This enables the methods defined in the included callback. # Can also be used like this: # User.first.available_info # => #<OpenStruct facebook="jose.a.padilla", linkedin="joseapadilla", twitter="jpadilla_"> # # User.first.available_info.twitter # => "jpadilla_" # def social_info user_social_info = {} account_data.map do |account| user_social_info[account['shortname']] = account['username'] end OpenStruct.new(user_social_info) end def about_me info.fetch('aboutMe', nil) end private def user_json JSON.parse(open("http://en.gravatar.com/#{gravatar_user_hash}.json").read) end def info user_json['entry'][0] end def account_data info['accounts'] end def account_names account_data.map { |a| a.fetch('shortname', nil) } end end
Sort role payment type options alphabetically
class RolePaymentType include ActiveRecordLikeInterface attr_accessor :id, :name Unpaied = create!(id: 1, name: "Unpaid") ParliamentarySecretary = create!(id: 2, name: "Paid as a Parliamentary Secretary") Whip = create!(id: 3, name: "Paid as a whip") Consultant = create!(id: 4, name: "Paid as a consultant") end
class RolePaymentType include ActiveRecordLikeInterface attr_accessor :id, :name Consultant = create!(id: 4, name: "Paid as a consultant") ParliamentarySecretary = create!(id: 2, name: "Paid as a Parliamentary Secretary") Whip = create!(id: 3, name: "Paid as a whip") Unpaied = create!(id: 1, name: "Unpaid") end
Add null:false constraint to item image attachment
class CreateItems < ActiveRecord::Migration[5.0] def change create_table :items do |t| t.integer :user_id, null: false t.integer :section_id, null: false t.attachment :image t.timestamps(null: false) end end end
class CreateItems < ActiveRecord::Migration[5.0] def change create_table :items do |t| t.integer :user_id, null: false t.integer :section_id, null: false t.attachment :image, null: false t.timestamps(null: false) end end end
Send Sidekiq errors to Sentry
if Supermarket::Config.sentry_url.present? && !Rails.env.test? require 'raven' Raven.configure do |config| config.dsn = Supermarket::Config.sentry_url end end
if Supermarket::Config.sentry_url.present? && !Rails.env.test? require 'raven' require 'raven/sidekiq' Raven.configure do |config| config.dsn = Supermarket::Config.sentry_url end end
Update gem spec to pull in version form the source
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require 'semantic_logger/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |spec| spec.name = 'semantic_logger' spec.version = SemanticLogger::VERSION spec.platform = Gem::Platform::RUBY spec.authors = ['Reid Morrison'] spec.email = ['reidmo@gmail.com'] spec.homepage = 'https://github.com/reidmorrison/semantic_logger' spec.summary = "Scalable, next generation logging for Ruby" spec.description = "Semantic Logger takes logging in Ruby to the next level by adding several new capabilities to the commonly used Logging API" spec.files = Dir["lib/**/*", "LICENSE.txt", "Rakefile", "README.md"] spec.test_files = Dir["test/**/*"] spec.license = "Apache License V2.0" spec.has_rdoc = true spec.add_dependency 'sync_attr', '>= 1.0' spec.add_dependency 'thread_safe', '>= 0.1.0' end
lib = File.expand_path('../lib/', __FILE__) $:.unshift lib unless $:.include?(lib) # Maintain your gem's version: require 'semantic_logger/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |spec| spec.name = 'semantic_logger' spec.version = SemanticLogger::VERSION spec.platform = Gem::Platform::RUBY spec.authors = ['Reid Morrison'] spec.email = ['reidmo@gmail.com'] spec.homepage = 'https://github.com/reidmorrison/semantic_logger' spec.summary = "Scalable, next generation logging for Ruby" spec.description = "Semantic Logger takes logging in Ruby to the next level by adding several new capabilities to the commonly used Logging API" spec.files = Dir["lib/**/*", "LICENSE.txt", "Rakefile", "README.md"] spec.test_files = Dir["test/**/*"] spec.license = "Apache License V2.0" spec.has_rdoc = true spec.add_dependency 'sync_attr', '>= 1.0' spec.add_dependency 'thread_safe', '>= 0.1.0' end
Patch Rubydora to deal with external datastream content.
module Rubydora class Datastream def entity_size(response) if content_length = response["content-length"] content_length.to_i else response.body.length end end end end
Add YARD_ROOT and YARD_TEMPLATE_ROOT constants for later
$LOAD_PATH.unshift File.join(File.dirname(__FILE__), 'yard') ['logger'].each do |file| require File.join(File.dirname(__FILE__), 'yard', file) end module YARD VERSION = "0.2.1" module CodeObjects; end module Generators; end module Parser module Lexer; end module Ruby; end end module Handlers; end module Tags module Library; end end end %w[ symbol_hash tags/* code_objects/base code_objects/namespace_object code_objects/* parser/**/* handlers/base handlers/* registry tag_library ].each do |file| file = File.join(File.dirname(__FILE__), 'yard', file + ".rb") Dir[file].each do |f| if require(f) log.debug "Loading #{f}..." end end end
YARD_ROOT = File.join(File.dirname(__FILE__), 'yard') YARD_TEMPLATE_ROOT = File.join(File.dirname(__FILE__), '..', 'templates') $LOAD_PATH.unshift(YARD_ROOT) ['logger'].each do |file| require File.join(File.dirname(__FILE__), 'yard', file) end module YARD VERSION = "0.2.1" module CodeObjects; end module Generators; end module Parser module Lexer; end module Ruby; end end module Handlers; end module Tags module Library; end end end %w[ symbol_hash tags/* code_objects/base code_objects/namespace_object code_objects/* parser/**/* handlers/base handlers/* registry tag_library ].each do |file| file = File.join(File.dirname(__FILE__), 'yard', file + ".rb") Dir[file].each do |f| if require(f) log.debug "Loading #{f}..." end end end
Add method missing to application controller
module Doorkeeper class ApplicationController < ActionController::Base private def authenticate_resource_owner! current_resource_owner end def current_resource_owner instance_eval(&Doorkeeper.authenticate_resource_owner) end def authenticate_admin! if block = Doorkeeper.authenticate_admin instance_eval(&block) end end end end
module Doorkeeper class ApplicationController < ActionController::Base private def authenticate_resource_owner! current_resource_owner end def current_resource_owner instance_eval(&Doorkeeper.authenticate_resource_owner) end def authenticate_admin! if block = Doorkeeper.authenticate_admin instance_eval(&block) end end def method_missing(method, *args, &block) if method =~ /_(url|path)$/ raise "Your path has not been found. Didn't you mean to call main_app.#{method} in doorkeeper configuration block?" else super end end end end
Add rake task to cache version numbers in the right places
require 'whole_edition_translator' namespace :editions do desc "Take old publications and convert to new top level editions" task :extract_to_whole_editions => :environment do WholeEdition.delete_all Publication.all.each do |publication| puts "Processing #{publication.class} #{publication.id}" if publication.panopticon_id.present? publication.editions.each do |edition| puts " Into edition #{edition.id}" whole_edition = WholeEditionTranslator.new(publication, edition).run whole_edition.save! end else puts "No panopticon ID for #{publication.name} : #{publication.id}" end end end desc "denormalise associated users" task :denormalise => :environment do WholeEdition.all.each do |edition| begin puts "Processing #{edition.class} #{edition.id}" edition.denormalise_users and edition.save! puts " Done!" rescue Exception => e puts " [Err] Could not denormalise edition: #{e}" end end end end
require 'whole_edition_translator' namespace :editions do desc "Take old publications and convert to new top level editions" task :extract_to_whole_editions => :environment do WholeEdition.delete_all Publication.all.each do |publication| puts "Processing #{publication.class} #{publication.id}" if publication.panopticon_id.present? publication.editions.each do |edition| puts " Into edition #{edition.id}" whole_edition = WholeEditionTranslator.new(publication, edition).run whole_edition.save! end else puts "No panopticon ID for #{publication.name} : #{publication.id}" end end end desc "denormalise associated users" task :denormalise => :environment do WholeEdition.all.each do |edition| begin puts "Processing #{edition.class} #{edition.id}" edition.denormalise_users and edition.save! puts " Done!" rescue Exception => e puts " [Err] Could not denormalise edition: #{e}" end end end desc "cache latest version number against editions" task :cache_version_numbers => :environment do WholeEdition.all.each do |edition| begin puts "Processing #{edition.class} #{edition.id}" if edition.subsequent_siblings.any? edition.latest_version_number = edition.subsequent_siblings.sort_by(&:version_number).last.version_number else edition.latest_version_number = edition.version_number end edition.save puts " Done!" rescue Exception => e puts " [Err] Could not denormalise edition: #{e}" end end end end
Extend strawberry to second strip
require 'ws_light/set/color_set' module WSLight module Set # Creates a strawberry set, some green, lots of pinkish red with a few greenish dots class StrawberrySet < ColorSet LENGTH_RED = 0.9 COLOR_NUT = Color.new(220, 255, 15) def frame @set ||= create_frame end def create_frame set = [] length_red = (LENGTH_RED * @length).to_i color_strawberry = Color.new(255, 7, 15) color_leaves = Color.new(15, 191, 15) @length.times do |i| set << (i < length_red ? color_strawberry : color_leaves) end set = sprinkle_nuts(set) set end def sprinkle_nuts(set) length_red = (LENGTH_RED * @length).to_i distance = 0 while distance < length_red - 21 distance += 15 + rand(5) set[distance] = COLOR_NUT end set end def pixel(number, _frame = 0) frame[number] end end end end
require 'ws_light/set/color_set' module WSLight module Set # Creates a strawberry set, some green, lots of pinkish red with a few greenish dots class StrawberrySet < ColorSet LENGTH_RED = 0.9 COLOR_NUT = Color.new(220, 255, 15) def frame @set ||= create_frame end def create_frame set = [] length_red = (LENGTH_RED * @length).to_i color_strawberry = Color.new(255, 7, 15) color_leaves = Color.new(15, 191, 15) @length.times do |i| set << (i < length_red ? color_strawberry : color_leaves) end set = sprinkle_nuts(set) type == :double ? set + set.reverse : set end def sprinkle_nuts(set) length_red = (LENGTH_RED * @length).to_i distance = 0 while distance < length_red - 21 distance += 15 + rand(5) set[distance] = COLOR_NUT end set end def pixel(number) frame[number] end end end end
Make CLI responsible for printing the result
require_relative 'math24.rb' numbers = [6,6,8,11] operators = ["+", "-", "*", "/"] solver = Math24.new(operators) solver.numbers = numbers solver.solve()
require_relative 'math24.rb' numbers = [6,6,8,11] operators = ["+", "-", "*", "/"] solver = Math24.new(operators) solver.numbers = numbers puts solver.solve()
Add spec to ensure about_us and faq pages render properly
require 'spec_helper' describe HighVoltage::PagesController, '#show' do render_views %w(about_us faq).each do |page| %w(en fr pt ru).each do |locale| context "on GET to /#{locale}/#{page}" do before do get :show, id: page, locale: locale end it { should respond_with(:success) } it { should render_template(page) } end end end end
Add tests for borrow direct library.
require 'spec_helper' require 'blacklight_cornell_requests/borrow_direct' describe BlacklightCornellRequests::BorrowDirect do describe "Primary availability function" do it "" end end
Add spec for default uploaders
require 'spec_helper' describe KnowledgeBase::Configuration do before do KnowledgeBase.reset end it 'should be configurable' do subject.categories_path = :fog expect(subject.categories_path).to eq :fog end describe '#categories_path' do it 'should default to "categories"' do expect(subject.categories_path).to eq 'categories' end end describe '#articles_path' do it 'should default to "articles"' do expect(subject.articles_path).to eq 'articles' end end describe '#section_styles' do it 'should default to an empty hash' do expect(subject.section_styles).to eq({ }) end end end
require 'spec_helper' describe KnowledgeBase::Configuration do before do KnowledgeBase.reset end it 'should be configurable' do subject.categories_path = :fog expect(subject.categories_path).to eq :fog end describe '#categories_path' do it 'should default to "categories"' do expect(subject.categories_path).to eq 'categories' end end describe '#articles_path' do it 'should default to "articles"' do expect(subject.articles_path).to eq 'articles' end end describe '#section_styles' do it 'should default to an empty hash' do expect(subject.section_styles).to eq({ }) end end describe '#text_image_uploader' do it 'should default to the KB uploader' do expect(subject.text_image_uploader).to eq KnowledgeBase::ImageUploader end end describe '#image_image_uploader' do it 'should default to the KB uploader' do expect(subject.image_image_uploader).to eq KnowledgeBase::ImageUploader end end describe '#gallery_image_uploader' do it 'should default to the KB uploader' do expect(subject.gallery_image_uploader).to eq KnowledgeBase::ImageUploader end end describe '#list_image_uploader' do it 'should default to the KB uploader' do expect(subject.list_image_uploader).to eq KnowledgeBase::ImageUploader end end end
Fix album import title casing
require "album_set_processor" namespace :import do task :all_photos, [:path] => :environment do |t, args| AlbumSetProcessor.new(args.path).syncronize_photos end task :albums => :environment do require 'yaml' root_path = "../photo-site-generator/source/albums/" index_filename = "index.markdown" paths = %w[ bangkok chiang-mai don-det luang-prabang pai pakse-and-vientiane siem-reap slow-boat-to-thailand vang-vieng ] paths.each do |name| album_data = YAML.load_file(File.join(root_path, name, index_filename)) photo = Photo.where(path: name, filename: album_data['cover']).first raise "can't find photo #{name}/#{album_data['cover']}" unless photo album = Album.where(title: album_data['title']).first_or_create album.update_attributes(cover_photo: photo) end end end
require "album_set_processor" namespace :import do task :all_photos, [:path] => :environment do |t, args| AlbumSetProcessor.new(args.path).syncronize_photos end task :albums => :environment do require 'yaml' root_path = "../photo-site-generator/source/albums/" index_filename = "index.markdown" paths = %w[ bangkok chiang-mai don-det luang-prabang pai pakse-and-vientiane siem-reap slow-boat-to-thailand vang-vieng ] paths.each do |name| album_data = YAML.load_file(File.join(root_path, name, index_filename)) photo = Photo.where(path: name, filename: album_data['cover']).first raise "can't find photo #{name}/#{album_data['cover']}" unless photo album = Album.where(title: album_data['title'].titleize).first_or_create album.update_attributes(cover_photo: photo) end end end
Convert Sass::Script::Operation docs to YARD.
require 'sass/script/string' require 'sass/script/number' require 'sass/script/color' require 'sass/script/functions' require 'sass/script/unary_operation' module Sass::Script class Operation # :nodoc: def initialize(operand1, operand2, operator) @operand1 = operand1 @operand2 = operand2 @operator = operator end def inspect "(#{@operator.inspect} #{@operand1.inspect} #{@operand2.inspect})" end def perform(environment) literal1 = @operand1.perform(environment) literal2 = @operand2.perform(environment) begin literal1.send(@operator, literal2) rescue NoMethodError => e raise e unless e.name.to_s == @operator.to_s raise Sass::SyntaxError.new("Undefined operation: \"#{literal1} #{@operator} #{literal2}\".") end end end end
require 'set' require 'sass/script/string' require 'sass/script/number' require 'sass/script/color' require 'sass/script/functions' require 'sass/script/unary_operation' module Sass::Script # A SassScript node representing a binary operation, # such as `!a + !b` or `"foo" + 1`. class Operation # @param operand1 [#perform(Sass::Environment)] A script node # @param operand2 [#perform(Sass::Environment)] A script node # @param operator [Symbol] The operator to perform. # This should be one of the binary operator names in {Lexer::OPERATORS} def initialize(operand1, operand2, operator) @operand1 = operand1 @operand2 = operand2 @operator = operator end # @return [String] A human-readable s-expression representation of the operation def inspect "(#{@operator.inspect} #{@operand1.inspect} #{@operand2.inspect})" end # Evaluates the operation. # # @param environment [Sass::Environment] The environment in which to evaluate the SassScript # @return [Literal] The SassScript object that is the value of the operation # @raise [Sass::SyntaxError] if the operation is undefined for the operands def perform(environment) literal1 = @operand1.perform(environment) literal2 = @operand2.perform(environment) begin literal1.send(@operator, literal2) rescue NoMethodError => e raise e unless e.name.to_s == @operator.to_s raise Sass::SyntaxError.new("Undefined operation: \"#{literal1} #{@operator} #{literal2}\".") end end end end
Update Rake and Rspec dependancies
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'middleman-title/version' Gem::Specification.new do |spec| spec.name = 'middleman-title' spec.version = Middleman::Title::VERSION spec.authors = ['Justin Cypret'] spec.email = ['jcypret@gmail.com'] spec.summary = 'A Middleman extension for setting the page title' spec.homepage = 'https://github.com/jcypret/middleman-title' 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 'middleman-core', '~> 3.2' spec.add_development_dependency 'bundler', '~> 1.6' spec.add_development_dependency 'rake', '~> 10.3.1' spec.add_development_dependency 'rspec', '~> 2.14.1' end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'middleman-title/version' Gem::Specification.new do |spec| spec.name = 'middleman-title' spec.version = Middleman::Title::VERSION spec.authors = ['Justin Cypret'] spec.email = ['jcypret@gmail.com'] spec.summary = 'A Middleman extension for setting the page title' spec.description = 'A Middleman extension for setting the page title' spec.homepage = 'https://github.com/jcypret/middleman-title' 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 'middleman-core', '~> 3.2' spec.add_development_dependency 'bundler', '~> 1.6' spec.add_development_dependency 'rake', '~> 10.3', '>= 10.3.1' spec.add_development_dependency 'rspec', '~> 2.14', '>= 2.14.1' end
Revert "remove the runit dependency"
name "rundeck" maintainer "Webtrends, Inc." maintainer_email "Peter Crossley <peter.crossley@webtrends.com>" license "All rights reserved" description "Installs and configures Rundeck 2.0" long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version "2.0.4" depends "sudo" depends "java" depends "apache2" depends "rundeck" %w{ debian ubuntu centos suse fedora redhat freebsd windows }.each do |os| supports os end recipe "rundeck::server", "Use this recipe to install the rundeck server on a node" recipe "rundeck::chef-rundeck", "Use this recipe to install the chef rundeck integration component, by default it is recommened to install on the chef server." recipe "rundeck::default", "Use this recipe to manage the node as a target in rundeck, this recipe is included in rundeck::server" recipe "rundeck::node_unix", "Unix\Linux platform configuration, do not use on a node, the default recipe uses this implmentation" recipe "rundeck::node_windows", "Windows platform configuration, do not use on a node, the default recipe uses this implmentation"
name "rundeck" maintainer "Webtrends, Inc." maintainer_email "Peter Crossley <peter.crossley@webtrends.com>" license "All rights reserved" description "Installs and configures Rundeck 2.0" long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version "2.0.4" depends "runit" depends "sudo" depends "java" depends "apache2" depends "rundeck" %w{ debian ubuntu centos suse fedora redhat freebsd windows }.each do |os| supports os end recipe "rundeck::server", "Use this recipe to install the rundeck server on a node" recipe "rundeck::chef-rundeck", "Use this recipe to install the chef rundeck integration component, by default it is recommened to install on the chef server." recipe "rundeck::default", "Use this recipe to manage the node as a target in rundeck, this recipe is included in rundeck::server" recipe "rundeck::node_unix", "Unix\Linux platform configuration, do not use on a node, the default recipe uses this implmentation" recipe "rundeck::node_windows", "Windows platform configuration, do not use on a node, the default recipe uses this implmentation"
Add Task model to fix yaml encoding migration
class FixYamlEncoding < ActiveRecord::Migration def self.up fix_encoding(Block, 'settings') fix_encoding(Product, 'data') fix_encoding(Environment, 'settings') fix_encoding(Profile, 'data') fix_encoding(ActionTracker::Record, 'params') fix_encoding(Article, 'setting') end def self.down puts "Warning: cannot restore original encoding" end private def self.fix_encoding(model, param) result = model.find(:all, :conditions => "#{param} LIKE '%!binary%'") puts "Fixing #{result.count} rows of #{model} (#{param})" result.each {|r| r.update_column(param, deep_fix(r.send(param)).to_yaml)} end def self.deep_fix(hash) hash.each do |value| value.force_encoding('UTF-8') if value.is_a?(String) && !value.frozen? && value.encoding == Encoding::ASCII_8BIT deep_fix(value) if value.respond_to?(:each) end end end
class FixYamlEncoding < ActiveRecord::Migration def self.up fix_encoding(Block, 'settings') fix_encoding(Product, 'data') fix_encoding(Environment, 'settings') fix_encoding(Profile, 'data') fix_encoding(ActionTracker::Record, 'params') fix_encoding(Article, 'setting') fix_encoding(Task, 'data') end def self.down puts "Warning: cannot restore original encoding" end private def self.fix_encoding(model, param) result = model.find(:all, :conditions => "#{param} LIKE '%!binary%'") puts "Fixing #{result.count} rows of #{model} (#{param})" result.each {|r| r.update_column(param, deep_fix(r.send(param)).to_yaml)} end def self.deep_fix(hash) hash.each do |value| value.force_encoding('UTF-8') if value.is_a?(String) && !value.frozen? && value.encoding == Encoding::ASCII_8BIT deep_fix(value) if value.respond_to?(:each) end end end
Fix foreign key and unique constraints
Sequel.migration do change do alter_table(:compiled_packages) do add_column :stemcell_os, String add_column :stemcell_version, String end self[:compiled_packages].each do |compiled_package| next unless compiled_package[:stemcell_id] stemcell = self[:stemcells].filter(id: compiled_package[:stemcell_id]).first self[:compiled_packages].filter(id: compiled_package[:id]).update( stemcell_os: stemcell[:operating_system], stemcell_version: stemcell[:version] ) end if [:mysql2, :mysql].include?(adapter_scheme) foreign_key = foreign_key_list(:compiled_packages).find { |constraint| constraint.fetch(:columns) == [:stemcell_id] }.fetch(:name) alter_table(:compiled_packages) do drop_constraint(foreign_key, {type: :foreign_key}) end end alter_table(:compiled_packages) do drop_column :stemcell_id end end end
Sequel.migration do change do alter_table(:compiled_packages) do add_column :stemcell_os, String add_column :stemcell_version, String end self[:compiled_packages].each do |compiled_package| next unless compiled_package[:stemcell_id] stemcell = self[:stemcells].filter(id: compiled_package[:stemcell_id]).first self[:compiled_packages].filter(id: compiled_package[:id]).update( stemcell_os: stemcell[:operating_system], stemcell_version: stemcell[:version] ) end foreign_key = foreign_key_list(:compiled_packages).find { |constraint| constraint.fetch(:columns) == [:stemcell_id] }.fetch(:name) build_index = indexes(:compiled_packages).find { |_, value| value.fetch(:columns) == [:package_id, :stemcell_id, :build] }.first dependency_key_index = indexes(:compiled_packages).find { |_, value| value.fetch(:columns) == [:package_id, :stemcell_id, :dependency_key_sha1] }.first alter_table(:compiled_packages) do drop_constraint(foreign_key, :type=>:foreign_key) drop_constraint(build_index) add_index [:package_id, :stemcell_os, :stemcell_version, :build], unique: true, name: 'package_stemcell_build_idx' add_index [:package_id, :stemcell_os, :stemcell_version, :dependency_key_sha1], unique: true, name: 'package_stemcell_dependency_idx' drop_index(nil, :name=>dependency_key_index) end alter_table(:compiled_packages) do drop_column :stemcell_id end end end
Add object tests for storage.
Shindo.tests('Fog::Storage[:hp] | object requests', [:hp]) do @directory = Fog::Storage[:hp].directories.create(:key => 'fogobjecttests') @dir_name = @directory.identity tests('success') do tests("#put_object(#{@dir_name}, 'fog_object')").succeeds do Fog::Storage[:hp].put_object(@dir_name, 'fog_object', lorem_file) end tests("#get_object(#{@dir_name}, 'fog_object')").succeeds do Fog::Storage[:hp].get_object(@dir_name, 'fog_object') end tests("#get_object(#{@dir_name}, 'fog_object', &block)").returns(lorem_file.read) do data = '' Fog::Storage[:hp].get_object(@dir_name, 'fog_object') do |chunk, remaining_bytes, total_bytes| data << chunk end data end tests("#head_object(#{@dir_name}, 'fog_object')").succeeds do Fog::Storage[:hp].head_object(@dir_name, 'fog_object') end tests("#delete_object(#{@dir_name}, 'fog_object')").succeeds do Fog::Storage[:hp].delete_object(@dir_name, 'fog_object') end end tests('failure') do tests("#get_object(#{@dir_name}, 'fog_non_object')").raises(Fog::Storage::HP::NotFound) do Fog::Storage[:hp].get_object(@dir_name, 'fog_non_object') end tests("#get_object('fognoncontainer', 'fog_non_object')").raises(Fog::Storage::HP::NotFound) do Fog::Storage[:hp].get_object('fognoncontainer', 'fog_non_object') end tests("#head_object(#{@dir_name}, 'fog_non_object')").raises(Fog::Storage::HP::NotFound) do Fog::Storage[:hp].head_object(@dir_name, 'fog_non_object') end tests("#head_object('fognoncontainer', 'fog_non_object')").raises(Fog::Storage::HP::NotFound) do Fog::Storage[:hp].head_object('fognoncontainer', 'fog_non_object') end tests("#delete_object(#{@dir_name}, 'fog_non_object')").raises(Fog::Storage::HP::NotFound) do Fog::Storage[:hp].delete_object(@dir_name, 'fog_non_object') end tests("#delete_object('fognoncontainer', 'fog_non_object')").raises(Fog::Storage::HP::NotFound) do Fog::Storage[:hp].delete_object('fognoncontainer', 'fog_non_object') end end @directory.destroy end
Remove before_action on action forbidding in routing
class Admin::LocationsController < AdminController before_action :set_location, only: [:edit, :destroy, :update] def index @locations = Location.order('created_at desc').paginate(:page => params[:page]) end def new @location = Location.new end def edit end def create @location = Location.new(location_params) if @location.save redirect_to admin_locations_path else flash[:error] = "Something went wrong :(" render 'new' end end def update @location.update(location_params) redirect_to admin_locations_path end private def set_location @location = Location.find(params[:id]) end def location_params params.require(:location).permit(:name) end end
class Admin::LocationsController < AdminController before_action :set_location, only: [:edit, :update] def index @locations = Location.order('created_at desc').paginate(:page => params[:page]) end def new @location = Location.new end def edit end def create @location = Location.new(location_params) if @location.save redirect_to admin_locations_path else flash[:error] = "Something went wrong :(" render 'new' end end def update @location.update(location_params) redirect_to admin_locations_path end private def set_location @location = Location.find(params[:id]) end def location_params params.require(:location).permit(:name) end end
Add fields "Today" and "Now"
class Applicant < ActiveRecord::Base has_one :identity, dependent: :destroy accepts_nested_attributes_for :identity has_many :landlords, dependent: :destroy accepts_nested_attributes_for :landlords, allow_destroy: true has_many :household_members, dependent: :destroy accepts_nested_attributes_for :household_members, allow_destroy: true belongs_to :user attr_accessible :identity_attributes, :landlords_attributes, :household_members_attributes def preferred_attrs_for field_names field_names.map do |field_name| begin preferred_items field_name rescue Dragoman::NoMatchError nil end end.flatten.reject(&:nil?).to_set end def description identity.description end def field field_name value_for_field(field_name).to_s end def delegate_field_to item, field_name item && item.value_for_field(field_name) || "" end def value_for_field field_name case field_name when /^HH(\d+)(.*)$/ index = $1.to_i - 1 delegate_field_to household_members[index], $2 when /^LL(\d+)(.*)$/ index = $1.to_i - 1 delegate_field_to landlords[index], $2 else identity.value_for_field(field_name) end end end
class Applicant < ActiveRecord::Base has_one :identity, dependent: :destroy accepts_nested_attributes_for :identity has_many :landlords, dependent: :destroy accepts_nested_attributes_for :landlords, allow_destroy: true has_many :household_members, dependent: :destroy accepts_nested_attributes_for :household_members, allow_destroy: true belongs_to :user attr_accessible :identity_attributes, :landlords_attributes, :household_members_attributes def preferred_attrs_for field_names field_names.map do |field_name| begin preferred_items field_name rescue Dragoman::NoMatchError nil end end.flatten.reject(&:nil?).to_set end def description identity.description end def field field_name value_for_field(field_name).to_s end def delegate_field_to item, field_name item && item.value_for_field(field_name) || "" end def value_for_field field_name case field_name when /^HH(\d+)(.*)$/ index = $1.to_i - 1 delegate_field_to household_members[index], $2 when /^LL(\d+)(.*)$/ index = $1.to_i - 1 delegate_field_to landlords[index], $2 when "Today" Date.today when "Now" now = Time.now "%d:%d" % [now.hour, now.sec] else identity.value_for_field(field_name) end end end
Use monitors for handling locking and waiting
require 'thread' module Dataflow def self.included(cls) class << cls def declare(*readers) readers.each do |name| variable = Variable.new define_method(name) { variable } end end end end def local(&block) vars = Array.new(block.arity) { Variable.new } block.call *vars end def unify(variable, value) variable.__unify__ value end class Variable MUTEX = Mutex.new instance_methods.each { |m| undef_method m unless m =~ /^__/ } def initialize @__requesters__ = [] end def __unify__(value) MUTEX.synchronize do raise UnificationError if @__value__ && @__value__ != value @__value__ = value while r = @__requesters__.shift r.wakeup if r.status == 'sleep' end @__value__ end end def method_missing(name, *args, &block) MUTEX.synchronize do @__requesters__ << Thread.current unless @__value__ end sleep unless @__value__ @__value__.__send__(name, *args, &block) end end UnificationError = Class.new StandardError end
require 'monitor' module Dataflow def self.included(cls) class << cls def declare(*readers) readers.each do |name| variable = Variable.new define_method(name) { variable } end end end end def local(&block) vars = Array.new(block.arity) { Variable.new } block.call *vars end def unify(variable, value) variable.__unify__ value end class Variable instance_methods.each { |m| undef_method m unless m =~ /^__/ } LOCK = Monitor.new def initialize @__binding__ = LOCK.new_cond end def __unify__(value) LOCK.synchronize do if @__value__ raise UnificationError if @__value__ != value else @__value__ = value @__binding__.broadcast # wakeup all method callers @__binding__ = nil # garbage collect condition end end @__value__ end def method_missing(name, *args, &block) # double-checked race condition to avoid going into synchronize LOCK.synchronize do @__binding__.wait unless @__value__ end unless @__value__ @__value__.__send__(name, *args, &block) end end UnificationError = Class.new StandardError end
Fix `Do not use prefix _ for a variable that is used.`
module Buoys class Link attr_accessor :text, :options, :options_for_config attr_reader :current CONFIG = { current_class: (Buoys::Config.current_class || 'active'), link_current: (Buoys::Config.link_current || false) }.with_indifferent_access def initialize(text, url, options) @options_for_config, @options = extract_options_and_config(options) @text = text @_url = url @current = false end def mark_as_current! options[:class] = config[:current_class] @current = true end def current? @current end def url return '' if current? && !config[:link_current] @_url || '' end def url=(str) @_url = str end private def config CONFIG.merge(options_for_config) end def extract_options_and_config(_options) options = _options.with_indifferent_access config = (options.keys & CONFIG.keys).each_with_object({}) {|key, hash| hash[key] = options.delete(key) } [config, options] end end end
module Buoys class Link attr_accessor :text, :options, :options_for_config attr_reader :current CONFIG = { current_class: (Buoys::Config.current_class || 'active'), link_current: (Buoys::Config.link_current || false) }.with_indifferent_access def initialize(text, url, options) @options_for_config, @options = extract_options_and_config(options) @text = text @_url = url @current = false end def mark_as_current! options[:class] = config[:current_class] @current = true end def current? @current end def url return '' if current? && !config[:link_current] @_url || '' end def url=(str) @_url = str end private def config CONFIG.merge(options_for_config) end def extract_options_and_config(opts) options = opts.with_indifferent_access config = (options.keys & CONFIG.keys).each_with_object({}) {|key, hash| hash[key] = options.delete(key) } [config, options] end end end
Fix failed build on master
RSpec.describe Spree::HomeController, type: :controller do routes { Spree::Core::Engine.routes } before do reset_spree_preferences SpreeI18n::Config.available_locales = [:en, :es] end context 'tries not supported fr locale' do it 'falls back do default locale' do get :index, locale: 'fr' expect(I18n.locale).to eq :en end end context 'tries supported es locale' do it 'takes this locale' do get :index, locale: 'es' expect(I18n.locale).to eq :es end end end
RSpec.describe Spree::HomeController, type: :controller do routes { Spree::Core::Engine.routes } before do reset_spree_preferences SpreeI18n::Config.available_locales = [:en, :es] end context 'tries not supported fr locale' do it 'falls back do default locale' do get :index, params: { locale: 'fr' } expect(I18n.locale).to eq :en end end context 'tries supported es locale' do it 'takes this locale' do get :index, params: { locale: 'es' } expect(I18n.locale).to eq :es end end end
Load sass and uglifier as test deps
Gem::Specification.new do |s| s.name = "sprockets-rails" s.version = "2.2.0" s.homepage = "https://github.com/rails/sprockets-rails" s.summary = "Sprockets Rails integration" s.license = "MIT" s.files = Dir["README.md", "lib/**/*.rb", "LICENSE"] s.add_dependency "sprockets", [">= 2.8", "< 4.0"] s.add_dependency "actionpack", ">= 3.0" s.add_dependency "activesupport", ">= 3.0" s.add_development_dependency "rake" s.add_development_dependency "railties", ">= 3.0" s.author = "Joshua Peek" s.email = "josh@joshpeek.com" end
Gem::Specification.new do |s| s.name = "sprockets-rails" s.version = "2.2.0" s.homepage = "https://github.com/rails/sprockets-rails" s.summary = "Sprockets Rails integration" s.license = "MIT" s.files = Dir["README.md", "lib/**/*.rb", "LICENSE"] s.add_dependency "sprockets", [">= 2.8", "< 4.0"] s.add_dependency "actionpack", ">= 3.0" s.add_dependency "activesupport", ">= 3.0" s.add_development_dependency "railties", ">= 3.0" s.add_development_dependency "rake" s.add_development_dependency "sass" s.add_development_dependency "uglifier" s.author = "Joshua Peek" s.email = "josh@joshpeek.com" end
Add brand to product title.
module Spree module ProductsHelper def property_value_for(product, property) return nil unless property = product.properties.find_by_name(property) property.value end end end
module Spree module ProductsHelper def property_value_for(product, property) return nil unless property = product.properties.find_by_name(property) return nil unless product_properties = product.product_properties.find_by_property_id(proterty.id) product_properties.value end end end
Use pty and expect to test interactive init dialog
require 'helper' class TestInit < Test::Pwm::AppTestCase # # Tests that initing with two passwords that don't match fails # def test_init_unmatching_passwords # TODO end # # Tests that force-initing an existing store results in a valid store # def test_init # TODO end # # Tests that cancelling a re-init does not change the store file # def test_init_cancel # TODO end end
require 'helper' require 'pty' require 'expect' class TestInit < Test::Pwm::AppTestCase # # Tests that initing with two passwords that don't match fails # # A session is expected to look like this (using s3cretPassw0rd at the first and secr3tPassw0rd at the second password prompt): # # $ bin/pwm init --force --verbose # Enter new master password: # ************** # Enter master password again: # ************** # Passwords do not match. # $ # def test_unmatching_passwords cmd = "bin/pwm init --force --verbose --file \"#{store_file}\"" PTY.spawn(cmd){|pwm_out, pwm_in, pid| pwm_out.expect(/Enter new master password:/, 1){|r| pwm_in.printf("s3cretPassw0rd\n") } pwm_out.expect(/Enter master password again:/, 1){|r| pwm_in.printf("secr3tPassw0rd\n") } assert_response('Passwords do not match\.', pwm_out) } end # # Tests that initing an existing store without --force does not touch the existing store # def test_exists assert_error('already exists', "init") end # # Tests that force-initing an existing store results in a valid store # def test_force # TODO end # # Tests that cancelling a forced re-init does not change the store file # def test_cancel # TODO end private def assert_response(expected, actual_io) if !actual_io.expect(/#{expected}/, 1) raise StandardError.new("Expected response '#{expected}' was not matched") end end end
Add docs about latest libcurl version.
require 'logger' require 'ffi' require 'rbconfig' require 'thread' require 'mime/types' require 'tempfile' require 'ethon/curl' require 'ethon/errors' require 'ethon/easy' require 'ethon/multi' require 'ethon/loggable' require 'ethon/version' # Ethon is a very simple libcurl. # It provides direct access to libcurl functionality # as well as some helpers for doing http requests. # # Ethon was extracted from Typhoeus. If you want to # see how others use Ethon look at the Typhoeus code. # # @see https://www.github.com/typhoeus/typhoeus Typhoeus module Ethon end
require 'logger' require 'ffi' require 'rbconfig' require 'thread' require 'mime/types' require 'tempfile' require 'ethon/curl' require 'ethon/errors' require 'ethon/easy' require 'ethon/multi' require 'ethon/loggable' require 'ethon/version' # Ethon is a very simple libcurl. # It provides direct access to libcurl functionality # as well as some helpers for doing http requests. # # Ethon was extracted from Typhoeus. If you want to # see how others use Ethon look at the Typhoeus code. # # @see https://www.github.com/typhoeus/typhoeus Typhoeus # # @note Please update to the latest libcurl version in order # to benefit from all features and bugfixes. # http://curl.haxx.se/download.html module Ethon end
Change constraint to be a protected method
# encoding: utf-8 module Axiom module Types # Abstract base class for every type class Type extend Options, DescendantsTracker accept_options :constraint constraint proc { true } def self.new raise NotImplementedError, "#{inspect} should not be instantiated" end def self.constraint(constraint = Undefined, &block) constraint = block if constraint.equal?(Undefined) return @constraint if constraint.nil? add_constraint(constraint) self end # TODO: move this into a module. separate the constraint setup from # declaration of the members, like the comparable modules. def self.includes(*members) set = IceNine.deep_freeze(members.to_set) constraint(&set.method(:include?)) end def self.include?(object) included = constraint.call(object) if included != true && included != false raise TypeError, "constraint must return true or false, but was #{included.inspect}" end included end def self.finalize IceNine.deep_freeze(@constraint) freeze end def self.finalized? frozen? end def self.add_constraint(constraint) current = @constraint @constraint = if current lambda { |object| current.call(object) && constraint.call(object) } else constraint end end private_class_method :add_constraint end # class Type end # module Types end # module Axiom
# encoding: utf-8 module Axiom module Types # Abstract base class for every type class Type extend Options, DescendantsTracker accept_options :constraint constraint proc { true } def self.new raise NotImplementedError, "#{inspect} should not be instantiated" end def self.finalize IceNine.deep_freeze(@constraint) freeze end def self.finalized? frozen? end def self.include?(object) included = constraint.call(object) if included != true && included != false raise TypeError, "constraint must return true or false, but was #{included.inspect}" end included end def self.constraint(constraint = Undefined, &block) constraint = block if constraint.equal?(Undefined) return @constraint if constraint.nil? add_constraint(constraint) self end singleton_class.class_eval { protected :constraint } # TODO: move this into a module. separate the constraint setup from # declaration of the members, like the comparable modules. def self.includes(*members) set = IceNine.deep_freeze(members.to_set) constraint(&set.method(:include?)) end def self.add_constraint(constraint) current = @constraint @constraint = if current lambda { |object| current.call(object) && constraint.call(object) } else constraint end end private_class_method :includes, :add_constraint end # class Type end # module Types end # module Axiom
Fix perform list priority number.
module QPush module Base KEY = 'qpush:v1'.freeze SUB_KEYS = [:delay, :queue, :perform, :stats, :heart, :crons, :history, :morgue] module Redis def self.included(base) base.extend(ClassMethods) end module ClassMethods def redis redis_pool.with do |conn| yield conn end end def redis_pool @redis_pool ||= build_pool(config.redis_pool, config.redis_url) end def build_keys(namespace, priorities) name = "#{QPush::Base::KEY}:#{namespace}" keys = Hash[QPush::Base::SUB_KEYS.collect { |key| [key, "#{name}:#{key}"] }] keys[:perform_list] = (1..5).collect { |num| "#{keys[:perform]}:#{num}" } keys end def build_pool(pool, url) ::ConnectionPool.new(size: pool) do ::Redis.new(url: url) end end end end end end
module QPush module Base KEY = 'qpush:v1'.freeze SUB_KEYS = [:delay, :queue, :perform, :stats, :heart, :crons, :history, :morgue] module Redis def self.included(base) base.extend(ClassMethods) end module ClassMethods def redis redis_pool.with do |conn| yield conn end end def redis_pool @redis_pool ||= build_pool(config.redis_pool, config.redis_url) end def build_keys(namespace, priorities) name = "#{QPush::Base::KEY}:#{namespace}" keys = Hash[QPush::Base::SUB_KEYS.collect { |key| [key, "#{name}:#{key}"] }] keys[:perform_list] = (1..priorities).collect { |num| "#{keys[:perform]}:#{num}" } keys end def build_pool(pool, url) ::ConnectionPool.new(size: pool) do ::Redis.new(url: url) end end end end end end
Add boolean, coin, and die instance methods to the Random class
# Magician's extensions to the Random class. class Random def boolean [true, false].sample end def coin ['heads', 'tails'].sample end def die rand 1..6 end end
Change the way MultiSpork prefork and each_run work, remove debugging instruction
require "spork" require 'parallel' module MultiSpork autoload :TestExecutor, "multi_spork/test_executor" autoload :TestResolver, "multi_spork/test_resolver" autoload :ShellExecutor, "multi_spork/shell_executor" autoload :Configuration, "multi_spork/configuration" class << self attr_accessor :each_run_block def prefork Spork.prefork do yield end if defined? ActiveRecord::Base ActiveRecord::Base.connection.disconnect! end end def each_run &block self.each_run_block = block end def config @config || Configuration.new end def configure yield config end end end Spork.each_run do if defined?(ActiveRecord::Base) && defined?(Rails) db_count = MultiSpork.config.runner_count db_index = (Spork.run_count % db_count) + 1 config = YAML.load(ERB.new(Rails.root.join('config/database.yml').read).result)['test'] config["database"] += db_index.to_s puts "Connecting to database with this config" pp config ActiveRecord::Base.establish_connection(config) end MultiSpork.each_run_block.call if MultiSpork.each_run_block end
require "spork" require 'parallel' module MultiSpork autoload :TestExecutor, "multi_spork/test_executor" autoload :TestResolver, "multi_spork/test_resolver" autoload :ShellExecutor, "multi_spork/shell_executor" autoload :Configuration, "multi_spork/configuration" class << self def prefork Spork.prefork do yield if defined? ActiveRecord::Base ActiveRecord::Base.connection.disconnect! end end end def each_run Spork.each_run do if defined?(ActiveRecord::Base) && defined?(Rails) db_count = MultiSpork.config.runner_count db_index = (Spork.run_count % db_count) + 1 config = YAML.load(ERB.new(Rails.root.join('config/database.yml').read).result)['test'] config["database"] += db_index.to_s ActiveRecord::Base.establish_connection(config) end yield end end def config @config || Configuration.new end def configure yield config end end end
Add test of top page
# -*- coding: utf-8 -*- require 'test_helper' class Toptest < ActionDispatch::IntegrationTest test "Sponserd link should be exist" do get "/" assert_select 'section.sponsers_logo a[href]',count:4 end end
Replace user_* routes with session_* routes
module ObsFactory module ApplicationHelper # Catch some url helpers used in the OBS layout and forward them to # the main application %w(home_path user_tasks_path root_path project_show_path search_path user_show_url user_show_path user_logout_path user_login_path user_register_user_path user_do_login_path news_feed_path project_toggle_watch_path project_list_public_path monitor_path projects_path new_project_path user_rss_notifications_url).each do |m| define_method(m) do |*args| main_app.send(m, *args) end end def openqa_links_helper OpenqaJob.openqa_links_url end end end
module ObsFactory module ApplicationHelper # Catch some url helpers used in the OBS layout and forward them to # the main application %w(home_path user_tasks_path root_path project_show_path search_path user_show_url user_show_path user_register_user_path news_feed_path project_toggle_watch_path project_list_public_path monitor_path projects_path new_project_path user_rss_notifications_url session_new_path session_create_path session_destroy_path).each do |m| define_method(m) do |*args| main_app.send(m, *args) end end def openqa_links_helper OpenqaJob.openqa_links_url end end end
Add pysch dependency to gemspec
# -*- encoding: utf-8 -*- Gem::Specification.new do |gem| gem.authors = ["Alister Scott", "Jeff Morgan"] gem.email = ["alister.scott@gmail.com", "jeff.morgan@leandog.com"] gem.description = %q{A helper gem to emulate populate device user agents and resolutions when using webdriver} gem.summary = %q{A helper gem to emulate populate device user agents and resolutions when using webdriver} gem.homepage = "https://github.com/alisterscott/webdriver-user-agent" gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.name = "webdriver-user-agent" gem.require_paths = ["lib"] gem.version = "7.2" gem.add_dependency 'selenium-webdriver' gem.add_dependency 'facets' gem.add_dependency 'json' gem.add_development_dependency 'rspec' gem.add_development_dependency 'watir-webdriver' end
# -*- encoding: utf-8 -*- Gem::Specification.new do |gem| gem.authors = ["Alister Scott", "Jeff Morgan"] gem.email = ["alister.scott@gmail.com", "jeff.morgan@leandog.com"] gem.description = %q{A helper gem to emulate populate device user agents and resolutions when using webdriver} gem.summary = %q{A helper gem to emulate populate device user agents and resolutions when using webdriver} gem.homepage = "https://github.com/alisterscott/webdriver-user-agent" gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.name = "webdriver-user-agent" gem.require_paths = ["lib"] gem.version = "7.2" gem.add_dependency 'selenium-webdriver' gem.add_dependency 'facets' gem.add_dependency 'json' gem.add_dependency 'psych' gem.add_development_dependency 'rspec' gem.add_development_dependency 'watir-webdriver' end
Remove spec with simple symbols
require "spec_helper" module Scanny::Checks::Session describe SessionSecureCheck do before do @runner = Scanny::Runner.new(SessionSecureCheck.new) @message = "Bad session security setting can cause problems" @issue = issue(:info, @message, 614) end it "reports \":session_secure\" correctly" do @runner.should check(":session_secure").with_issue(@issue) end it "reports \":secure\" correctly" do @runner.should check(":secure").with_issue(@issue) end it "reports \"ActionController::Base.session_options[:session_secure] = false\" correctly" do @runner.should check("ActionController::Base.session_options[:session_secure] = false"). with_issue(@issue) end it "reports \"ActionController::Base.session_options[:secure] = false\" correctly" do @runner.should check("ActionController::Base.session_options[:secure] = false"). with_issue(@issue) end end end
require "spec_helper" module Scanny::Checks::Session describe SessionSecureCheck do before do @runner = Scanny::Runner.new(SessionSecureCheck.new) @message = "Bad session security setting can cause problems" @issue = issue(:info, @message, 614) end it "reports \"ActionController::Base.session_options[:session_secure] = false\" correctly" do @runner.should check("ActionController::Base.session_options[:session_secure] = false"). with_issue(@issue) end it "reports \"ActionController::Base.session_options[:secure] = false\" correctly" do @runner.should check("ActionController::Base.session_options[:secure] = false"). with_issue(@issue) end end end
Add gulp to npm packages
#!/usr/bin/env ruby puts "Running Node version: #{`node --version`}" npms = { # module name => module command # leave command blank if they are the same "coffee-script" => "coffee", "grunt-cli" => "grunt", "dalek-cli" => "dalek", "gh" => "", "bower" => "", "yo" => "", "jshint" => "", "express" => "", "nodemon" => "", "mocha" => "", "sails" => "" } npms.each do |mod, command| cmd = (command == "" ? mod : command) if `which #{cmd}` == "" puts "Installing #{mod}" `npm install #{mod} -g --silent` end end # always run the very latest npm, not just the one that was bundled into Node `npm install npm -g --silent`
#!/usr/bin/env ruby puts "Running Node version: #{`node --version`}" npms = { # module name => module command # leave command blank if they are the same "coffee-script" => "coffee", "grunt-cli" => "grunt", "dalek-cli" => "dalek", "gulp" => "", "gh" => "", "bower" => "", "yo" => "", "jshint" => "", "express" => "", "nodemon" => "", "mocha" => "", "sails" => "" } npms.each do |mod, command| cmd = (command == "" ? mod : command) if `which #{cmd}` == "" puts "Installing #{mod}" `npm install #{mod} -g --silent` end end # always run the very latest npm, not just the one that was bundled into Node `npm install npm -g --silent`
Apply change to ssl section too.
module Moonshine module NoWWW def self.included(manifest) manifest.class_eval do extend ClassMethods end end module ClassMethods end def no_www if configuration[:passenger] rewrite_section = <<-MOD_REWRITE # WWW Redirect RewriteCond %{HTTP_HOST} ^www\.(.*) [NC] RewriteRule ^(.*)$ http://%1$1 [L,R=301] MOD_REWRITE configure :passenger => { :vhost_extra => (configuration[:passenger][:vhost_extra] || '') + rewrite_section } end if configuration[:ssl] rewrite_section = <<-MOD_REWRITE_SSL # SSL WWW Redirect RewriteCond %{HTTP_HOST} !^#{domain.gsub('.', '\.')}$ [NC] RewriteCond %{HTTP_HOST} ^www\.(.*) [NC] RewriteRule ^(.*)$ https://%1$1 [L,R=301] MOD_REWRITE_SSL configure :ssl => { :vhost_extra => (configuration[:ssl][:vhost_extra] || '') + rewrite_section } end end end end
module Moonshine module NoWWW def self.included(manifest) manifest.class_eval do extend ClassMethods end end module ClassMethods end def no_www if configuration[:passenger] rewrite_section = <<-MOD_REWRITE # WWW Redirect RewriteCond %{HTTP_HOST} ^www\.(.*) [NC] RewriteRule ^(.*)$ http://%1$1 [L,R=301] MOD_REWRITE configure :passenger => { :vhost_extra => (configuration[:passenger][:vhost_extra] || '') + rewrite_section } end if configuration[:ssl] rewrite_section = <<-MOD_REWRITE_SSL # SSL WWW Redirect RewriteCond %{HTTP_HOST} ^www\.(.*) [NC] RewriteRule ^(.*)$ https://%1$1 [L,R=301] MOD_REWRITE_SSL configure :ssl => { :vhost_extra => (configuration[:ssl][:vhost_extra] || '') + rewrite_section } end end end end
Add rake task for inserting a lot of data to db
namespace :db do desc "Create a lot of data in the database to test syncing performance" task muchdata: :environment do 10.times do |i_n| i = Instrument.create!(title: "Instrument #{i_n}", language: Settings.languages.sample, alignment: "left" ) p "Created #{i.title}" 1000.times do |q_n| question_type = Settings.question_types.sample question = i.questions.create!(text: "Question #{q_n}", question_identifier: "#{i_n}_q_#{q_n}", question_type: Settings.question_types.sample ) if Settings.question_with_options.include? question_type 5.times do |o_n| question.options.create!(text: "Option #{o_n}") end end end end end end
Add a spec for main.private when given an undefined name
require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../fixtures/classes', __FILE__) describe "main#private" do after :each do Object.send(:public, :main_public_method) end it "sets the visibility of the given method to private" do eval "private :main_public_method", TOPLEVEL_BINDING Object.should have_private_method(:main_public_method) end it "returns Object" do eval("private :main_public_method", TOPLEVEL_BINDING).should equal(Object) end end
require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../fixtures/classes', __FILE__) describe "main#private" do after :each do Object.send(:public, :main_public_method) end it "sets the visibility of the given method to private" do eval "private :main_public_method", TOPLEVEL_BINDING Object.should have_private_method(:main_public_method) end it "returns Object" do eval("private :main_public_method", TOPLEVEL_BINDING).should equal(Object) end it "raises a NameError when given an undefined name" do lambda {eval "private :main_undefined_method", TOPLEVEL_BINDING}.should( raise_error(NameError) do |err| err.should be_an_instance_of(NameError) end ) end end
Check if headers exist instead of crashing
module SinatraWebsocket module Ext module Sinatra module Request # Taken from skinny https://github.com/sj26/skinny and updated to support Firefox def websocket? env['HTTP_CONNECTION'].split(',').map(&:strip).map(&:downcase).include?('upgrade') && env['HTTP_UPGRADE'].downcase == 'websocket' end # Taken from skinny https://github.com/sj26/skinny def websocket(options={}, &blk) env['skinny.websocket'] ||= begin raise RuntimeError, "Not a WebSocket request" unless websocket? SinatraWebsocket::Connection.from_env(env, options, &blk) end end end end # module::Sinatra end # module::Ext end # module::SinatraWebsocket defined?(Sinatra) && Sinatra::Request.send(:include, SinatraWebsocket::Ext::Sinatra::Request)
module SinatraWebsocket module Ext module Sinatra module Request # Taken from skinny https://github.com/sj26/skinny and updated to support Firefox def websocket? env['HTTP_CONNECTION'] && env['HTTP_UPGRADE'] && env['HTTP_CONNECTION'].split(',').map(&:strip).map(&:downcase).include?('upgrade') && env['HTTP_UPGRADE'].downcase == 'websocket' end # Taken from skinny https://github.com/sj26/skinny def websocket(options={}, &blk) env['skinny.websocket'] ||= begin raise RuntimeError, "Not a WebSocket request" unless websocket? SinatraWebsocket::Connection.from_env(env, options, &blk) end end end end # module::Sinatra end # module::Ext end # module::SinatraWebsocket defined?(Sinatra) && Sinatra::Request.send(:include, SinatraWebsocket::Ext::Sinatra::Request)
Save the way to run the goodies
class EmailProcessor def initialize(email) @email = email end def process Email.create( to: @email.headers["X-Forwarded-To"], from: @email.from[:email], subject: @email.subject, raw_text: @email.raw_text, raw_html: @email.raw_html, raw_body: @email.raw_body, body: @email.body, headers: @email.headers.to_json, # forwarded: @email["X-Forwarded-To"], ) # pry puts "Done" end end
class EmailProcessor def initialize(email) @email = email end def process to = @email.to[0][:email] if @email.headers && !@email.headers["X-Forwarded-To"].nil? to = @email.headers["X-Forwarded-To"] end Email.create( to: to, from: @email.from[:email], subject: @email.subject, raw_text: @email.raw_text, raw_html: @email.raw_html, raw_body: @email.raw_body, body: @email.body, headers: @email.headers.to_json, # forwarded: @email["X-Forwarded-To"], ) # pry puts "Done" end end
Update Detailed Guide sync check rendering app
module SyncChecker module Formats class DetailedGuideCheck < EditionBase def root_path "/guidance/" end def checks_for_live(locale) super + [ Checks::LinksCheck.new( "related_guides", edition_expected_in_live .published_related_detailed_guides .reject(&:unpublishing) .map(&:content_id) .uniq ), Checks::LinksCheck.new( "related_mainstream_content", related_mainstream_content_ids(edition_expected_in_live) ) ] end def document_type "detailed_guide" end def expected_details_hash(edition) super.tap do |expected_details_hash| expected_details_hash.merge( national_applicability: edition.national_applicability ) if edition.nation_inapplicabilities.any? expected_details_hash.merge( related_mainstream_content: related_mainstream_content_ids(edition) ) end end private def related_mainstream_content_ids(edition) edition.related_mainstreams.pluck(:content_id) end end end end
module SyncChecker module Formats class DetailedGuideCheck < EditionBase def root_path "/guidance/" end def checks_for_live(locale) super + [ Checks::LinksCheck.new( "related_guides", edition_expected_in_live .published_related_detailed_guides .reject(&:unpublishing) .map(&:content_id) .uniq ), Checks::LinksCheck.new( "related_mainstream_content", related_mainstream_content_ids(edition_expected_in_live) ) ] end def document_type "detailed_guide" end def expected_details_hash(edition) super.tap do |expected_details_hash| expected_details_hash.merge( national_applicability: edition.national_applicability ) if edition.nation_inapplicabilities.any? expected_details_hash.merge( related_mainstream_content: related_mainstream_content_ids(edition) ) end end private def related_mainstream_content_ids(edition) edition.related_mainstreams.pluck(:content_id) end def rendering_app Whitehall::RenderingApp::GOVERNMENT_FRONTEND end end end end
Test for calling a code block
require 'rspec/given' require 'subtime/timer' module Kernel def sleep(seconds) end end describe Timer do let(:output) { double('output').as_null_object } describe "#start" do context "without messages" do let(:minutes) { 0 } let(:timer) { Timer.new(output, minutes) } it "outputs 'Starting timer for 0 minutes...'" do expect(output).to receive(:puts).with("Starting timer for #{minutes} minutes...") timer.start end end context "for 10 minutes with messages" do let(:minutes) { 10 } let(:messages) { { 5 => "something", 2 => "something else" } } let(:timer) { Timer.new(output, minutes, messages) } it "outputs 'Starting timer for 10 minutes...'" do expect(output).to receive(:puts).with("Starting timer for #{minutes} minutes...") timer.start end it "outputs each minute from 10 down to 1" do 10.downto(1) do |minute| expect(output).to receive(:puts).with(minute) end timer.start end end end end
require 'rspec/given' require 'subtime/timer' module Kernel def sleep(seconds) end end describe Timer do let(:output) { double('output').as_null_object } describe "#start" do context "without messages" do let(:minutes) { 0 } let(:timer) { Timer.new(output, minutes) } it "outputs 'Starting timer for 0 minutes...'" do expect(output).to receive(:puts).with("Starting timer for #{minutes} minutes...") timer.start end end context "for 10 minutes with code blocks" do let(:minutes) { 10 } let(:messages) { { 5 => lambda { puts "Something" }, 2 => lambda { puts "something else" } } } let(:timer) { Timer.new(output, minutes, messages) } it "outputs 'Starting timer for 10 minutes...'" do expect(output).to receive(:puts).with("Starting timer for #{minutes} minutes...") timer.start end it "outputs each minute from 10 down to 1" do 10.downto(1) do |minute| expect(output).to receive(:puts).with(minute) end timer.start end it "calls the specified code blocks" do expect(output).to receive(:puts).with("Something") expect(output).to receive(:puts).with("something else") timer.start end end end end
Fix :show urls and notify url
require 'active_support/concern' module Georgia module Concerns module Revisioning extend ActiveSupport::Concern include Helpers included do def review @revision.review notify("#{current_user.name} is asking you to review #{@revision.title}.") redirect_to [:edit, @page, @revision], notice: "You successfully submited #{@revision.title} for review." end def approve @revision.approve message = "#{current_user.name} has successfully approved and published #{@revision.title} #{instance_name}." notify(message) redirect_to [:show, @page], notice: message end def decline @revision.decline message = "#{current_user.name} has successfully published #{@revision.title} #{instance_name}." notify(message) redirect_to [:edit, @page, @revision], notice: message end def revert @revision.revert message = "#{current_user.name} has successfully published #{@revision.title} #{instance_name}." notify(message) redirect_to [:show, @page], notice: message end private def notify(message) Notifier.notify_editors(message, url_for(action: :edit, controller: controller_name, id: @page.id)).deliver end end end end end
require 'active_support/concern' module Georgia module Concerns module Revisioning extend ActiveSupport::Concern include Helpers included do def review @revision.review notify("#{current_user.name} is asking you to review #{@revision.title}.") redirect_to [:edit, @page, @revision], notice: "You successfully submited #{@revision.title} for review." end def approve @revision.approve message = "#{current_user.name} has successfully approved and published #{@revision.title} #{instance_name}." notify(message) redirect_to @page, notice: message end def decline @revision.decline message = "#{current_user.name} has successfully published #{@revision.title} #{instance_name}." notify(message) redirect_to [:edit, @page, @revision], notice: message end def revert @revision.revert message = "#{current_user.name} has successfully published #{@revision.title} #{instance_name}." notify(message) redirect_to @page, notice: message end private def notify(message) Notifier.notify_editors(message, url_for([:edit, @page, @revision])).deliver end end end end end
Add outline of users_controller tests
require 'spec_helper' require 'rails_helper' describe UsersController do describe "#new" do it "assigns a new user to @user" it "renders the #new template" end describe "#create" do context "with valid attributes" do it "saves the new user to the database" it "redirects to the login page" end context "with invalid attributes" do it "does not save the new user to the database" it "redirects to the #new page" it "assigns a flash to notify user of error" end end end
Fix url generation error on hook invalid create
class Projects::HooksController < Projects::ApplicationController # Authorize before_filter :authorize_admin_project! respond_to :html layout "project_settings" def index @hooks = @project.hooks @hook = ProjectHook.new end def create @hook = @project.hooks.new(params[:hook]) @hook.save if @hook.valid? redirect_to project_hooks_path(@project) else @hooks = @project.hooks render :index end end def test TestHookService.new.execute(hook, current_user) redirect_to :back end def destroy hook.destroy redirect_to project_hooks_path(@project) end private def hook @hook ||= @project.hooks.find(params[:id]) end end
class Projects::HooksController < Projects::ApplicationController # Authorize before_filter :authorize_admin_project! respond_to :html layout "project_settings" def index @hooks = @project.hooks @hook = ProjectHook.new end def create @hook = @project.hooks.new(params[:hook]) @hook.save if @hook.valid? redirect_to project_hooks_path(@project) else @hooks = @project.hooks.select(&:persisted?) render :index end end def test TestHookService.new.execute(hook, current_user) redirect_to :back end def destroy hook.destroy redirect_to project_hooks_path(@project) end private def hook @hook ||= @project.hooks.find(params[:id]) end end
Remove non-existent initializer config option
# Be sure to restart your server when you modify this file. # # This file contains migration options to ease your Rails 5.0 upgrade. # # Once upgraded flip defaults one by one to migrate to the new default. # # Read the Guide for Upgrading Ruby on Rails for more info on each option. Rails.application.config.raise_on_unfiltered_parameters = true # Enable per-form CSRF tokens. Previous versions had false. Rails.application.config.action_controller.per_form_csrf_tokens = false # Enable origin-checking CSRF mitigation. Previous versions had false. Rails.application.config.action_controller.forgery_protection_origin_check = false # Make Ruby 2.4 preserve the timezone of the receiver when calling `to_time`. # Previous versions had false. ActiveSupport.to_time_preserves_timezone = false # Require `belongs_to` associations by default. Previous versions had false. Rails.application.config.active_record.belongs_to_required_by_default = false # Do not halt callback chains when a callback returns false. Previous versions had true. ActiveSupport.halt_callback_chains_on_return_false = true
# Be sure to restart your server when you modify this file. # # This file contains migration options to ease your Rails 5.0 upgrade. # # Once upgraded flip defaults one by one to migrate to the new default. # # Read the Guide for Upgrading Ruby on Rails for more info on each option. Rails.application.config.raise_on_unfiltered_parameters = true # Enable per-form CSRF tokens. Previous versions had false. Rails.application.config.action_controller.per_form_csrf_tokens = false # Enable origin-checking CSRF mitigation. Previous versions had false. Rails.application.config.action_controller.forgery_protection_origin_check = false # Make Ruby 2.4 preserve the timezone of the receiver when calling `to_time`. # Previous versions had false. ActiveSupport.to_time_preserves_timezone = false # Require `belongs_to` associations by default. Previous versions had false. Rails.application.config.active_record.belongs_to_required_by_default = false
Fix bug that prevented certain split_rows from showing a segment time.
class EffortShowView attr_reader :effort, :split_rows def initialize(effort) @effort = effort @splits = effort.event.ordered_splits.to_a @split_times = effort.split_times.index_by(&:bitkey_hash) @split_rows = [] create_split_rows end def total_time_in_aid split_rows.sum { |unicorn| unicorn.time_in_aid } end private attr_reader :splits, :split_times def create_split_rows prior_time = 0 splits.each do |split| split_row = SplitRow.new(split, related_split_times(split), prior_time) split_rows << split_row prior_time = split_row.times_from_start.last end end def related_split_times(split) split.sub_split_bitkey_hashes.collect { |key_hash| split_times[key_hash] } end end
class EffortShowView attr_reader :effort, :split_rows def initialize(effort) @effort = effort @splits = effort.event.ordered_splits.to_a @split_times = effort.split_times.index_by(&:bitkey_hash) @split_rows = [] create_split_rows end def total_time_in_aid split_rows.sum { |unicorn| unicorn.time_in_aid } end private attr_reader :splits, :split_times def create_split_rows prior_time = 0 splits.each do |split| split_row = SplitRow.new(split, related_split_times(split), prior_time) split_rows << split_row prior_time = split_row.times_from_start.last if split_row.times_from_start.compact.present? end end def related_split_times(split) split.sub_split_bitkey_hashes.collect { |key_hash| split_times[key_hash] } end end
Fix file name in gemspec
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'http_content_type/version' Gem::Specification.new do |s| s.name = 'http_content_type' s.version = HttpContentType::VERSION s.license = 'MIT' s.authors = ['Rémy Coutable'] s.email = ['remy@rymai.me'] s.summary = 'Check the Content-Type of any HTTP-accessible asset.' s.description = 'This gem allows you to check the Content-Type of any HTTP-accessible asset.' s.homepage = 'http://rubygems.org/gems/http_content_type' s.files = Dir.glob('lib/**/*') + %w[CHANGELOG.md LICENSE README.md] s.test_files = Dir.glob('spec/**/*') s.require_paths = ['lib'] s.add_development_dependency 'bundler' s.add_development_dependency 'rspec' end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'http_content_type/version' Gem::Specification.new do |s| s.name = 'http_content_type' s.version = HttpContentType::VERSION s.license = 'MIT' s.authors = ['Rémy Coutable'] s.email = ['remy@rymai.me'] s.summary = 'Check the Content-Type of any HTTP-accessible asset.' s.description = 'This gem allows you to check the Content-Type of any HTTP-accessible asset.' s.homepage = 'http://rubygems.org/gems/http_content_type' s.files = Dir.glob('lib/**/*') + %w[CHANGELOG.md LICENSE.md README.md] s.test_files = Dir.glob('spec/**/*') s.require_paths = ['lib'] s.add_development_dependency 'bundler' s.add_development_dependency 'rspec' end
Fix use of format on older systems
module SuppliersPlugin::TermsHelper Terms = [:consumer, :supplier] TermsVariations = [:singular, :plural] TermsTransformations = [:capitalize] TermsKeys = Terms.map do |term| TermsVariations.map{ |variation| [term, variation].join('.') } end.flatten protected def translated_terms keys = TermsKeys, transformations = TermsTransformations @translated_terms ||= {} return @translated_terms unless @translated_terms.blank? @terms_context ||= 'suppliers_plugin' keys.each do |key| translation = I18n.t "#{@terms_context}.terms.#{key}" @translated_terms["terms.#{key}"] = translation transformations.map do |transformation| @translated_terms["terms.#{key}.#{transformation}"] = translation.send transformation end end @translated_terms end def t key, options = {} I18n.t(key, options) % translated_terms end end
module SuppliersPlugin::TermsHelper Terms = [:consumer, :supplier] # '.' ins't supported by the % format function (altought it works on some newer systems) TermsSeparator = '_' TermsVariations = [:singular, :plural] TermsTransformations = [:capitalize] TermsKeys = Terms.map do |term| TermsVariations.map{ |variation| [term, variation].join('.') } end.flatten protected def sub_separator str str.gsub '.', TermsSeparator end def sub_separator_items str str.gsub!(/\%\{[^\}]*\}/){ |x| sub_separator x } str end def translated_terms keys = TermsKeys, transformations = TermsTransformations, sep = TermsSeparator @translated_terms ||= HashWithIndifferentAccess.new return @translated_terms unless @translated_terms.blank? @terms_context ||= 'suppliers_plugin' keys.each do |key| translation = I18n.t "#{@terms_context}.terms.#{key}" new_key = sub_separator key @translated_terms["terms#{sep}#{new_key}"] = translation transformations.map do |transformation| @translated_terms["terms#{sep}#{new_key}#{sep}#{transformation}"] = translation.send transformation end end @translated_terms end def t key, options = {} translation = I18n.t key, options sub_separator_items translation translation % translated_terms end end
Allow pg 10-14+ in dev, require pg 13 in production
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.prepend Module.new { def initialize(*args) super check_version if respond_to?(:check_version) end def check_version msg = "The version of PostgreSQL being connected to is incompatible with #{Vmdb::Appliance.PRODUCT_NAME} (10 required)" if postgresql_version < 90500 raise msg end if postgresql_version < 100000 || postgresql_version >= 130000 raise msg if Rails.env.production? && !ENV["UNSAFE_PG_VERSION"] $stderr.puts msg end end }
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.prepend Module.new { def initialize(*args) super check_version if respond_to?(:check_version) end def check_version msg = "The version of PostgreSQL being connected to is incompatible with #{Vmdb::Appliance.PRODUCT_NAME} (13 required)" if postgresql_version < 100000 raise msg end if postgresql_version < 130000 || postgresql_version >= 140000 raise msg if Rails.env.production? && !ENV["UNSAFE_PG_VERSION"] $stderr.puts msg end end }
Add a basic mailer preview for the alert emails
class AlertMailerPreview < ActionMailer::Preview def alert_email user = User.first broken_scrapers = Scraper.first(2) successful_scrapers = Scraper.last(2) AlertMailer.alert_email(user, broken_scrapers, successful_scrapers) end end
Add prelim spec for route_params
require File.join(File.dirname(__FILE__), "spec_helper") require 'rack/mock' require 'stringio' Merb.start :environment => 'test', :adapter => 'runner', :merb_root => File.dirname(__FILE__) / 'fixture' describe Merb::Dispatcher, "route params" do before(:each) do env = Rack::MockRequest.env_for("/foo/bar/54") env['REQUEST_URI'] = "/foo/bar/54" # MockRequest doesn't set this @controller = Merb::Dispatcher.handle(env, StringIO.new) end it "should properly set the route params" do @controller.request.route_params[:id].should == '54' end end
Decrease importance of persistent warnings on controllers
module Concerns module PersistentWarnings extend ActiveSupport::Concern included do after_action :set_persistent_warning, unless: -> { request.xhr? } end def set_persistent_warning current_warning = persistent_warning flash.notice = current_warning if current_warning end def persistent_warning [ confirm_account, complete_profile ].detect do |possible_warnings| !possible_warnings.nil? end end protected def confirm_account if user_signed_in? && !current_user.confirmed? { message: t('devise.confirmations.confirm', link: new_user_confirmation_path), dismissible: false } end end def complete_profile if user_signed_in? && current_user.completeness_progress.to_i < 100 { message: t('controllers.users.completeness_progress', link: edit_user_path(current_user)), dismissible: false } end end end end
module Concerns module PersistentWarnings extend ActiveSupport::Concern included do before_action :set_persistent_warning, unless: -> { request.xhr? } end def set_persistent_warning current_warning = persistent_warning flash.notice = current_warning if current_warning end def persistent_warning [ confirm_account, complete_profile ].detect do |possible_warnings| !possible_warnings.nil? end end protected def confirm_account if user_signed_in? && !current_user.confirmed? { message: t('devise.confirmations.confirm', link: new_user_confirmation_path), dismissible: false } end end def complete_profile if user_signed_in? && current_user.completeness_progress.to_i < 100 { message: t('controllers.users.completeness_progress', link: edit_user_path(current_user)), dismissible: false } end end end end
Add a bit more structure.
require "sinatra/base" require "httparty" require "pry" require "myhub/version" require "myhub/github" module Myhub class App < Sinatra::Base set :logging, true # Your code here ... run! if app_file == $0 end end
require "sinatra/base" require "httparty" require "pry" require "myhub/version" require "myhub/github" module Myhub class App < Sinatra::Base set :logging, true # Your code here ... get "/" do api = Github.new # get stuff from github erb :index, locals: { issues: stuff } end put "/issue/:id" do api = Github.new api.reopen_issue(params["id"].to_i) "Cool cool cool" end delete "/issue/:id" do api = Github.new api.close_issue(params["id"].to_i) "Cool cool cool" end run! if app_file == $0 end end
Bring PurchaseOrderAccount in line with CreditCardAccount
class PurchaseOrderAccount < Account include AffiliateAccount belongs_to :facility validates_presence_of :account_number def to_s(with_owner = false) desc = super desc += " / #{facility.name}" if facility desc end def self.need_reconciling(facility) account_ids = OrderDetail.joins(:order, :account). select('DISTINCT(order_details.account_id) AS account_id'). where('orders.facility_id = ? AND accounts.type = ? AND order_details.state = ? AND statement_id IS NOT NULL', facility.id, model_name, 'complete'). all find(account_ids.collect{|a| a.account_id}) end end
class PurchaseOrderAccount < Account include AffiliateAccount belongs_to :facility validates_presence_of :account_number def to_s(with_owner = false) desc = super desc += " / #{facility.name}" if facility desc end def self.need_reconciling(facility) where(id: OrderDetail .joins(:order, :account) .select('DISTINCT(order_details.account_id) AS account_id') .where('orders.facility_id' => facility.id) .where('accounts.type' => model_name) .where('order_details.state' => 'complete') .where('statement_id IS NOT NULL') .pluck(:account_id)) end end
Update test to account for updated id format in controls.
require_relative './spec_init' describe 'Generating write events' do template = EventStore::EventGenerator::Controls::Template.example generator = EventStore::EventGenerator::Write.build template specify 'Setting stream name' do event = generator.next event.stream_name = 'someStreamName' assert event.stream_name == 'someStreamName' end specify 'Event ID' do generator.counter = 1 event_ids = [] 2.times do event = generator.next event_id = event.id event_ids << event_id end assert event_ids == %w( 00000001-0000-0000-0000-000000000000 00000002-0000-0000-0000-000000000000 ) end end
require_relative './spec_init' describe 'Generating write events' do template = EventStore::EventGenerator::Controls::Template.example generator = EventStore::EventGenerator::Write.build template specify 'Setting stream name' do event = generator.next event.stream_name = 'someStreamName' assert event.stream_name == 'someStreamName' end specify 'Event ID' do generator.counter = 1 event_ids = [] 2.times do event = generator.next event_id = event.id event_ids << event_id end assert event_ids == %w( 00000001-4000-8000-0000-000000000000 00000002-4000-8000-0000-000000000000 ) end end
Remove bootstrap attributes generated by Html renderer.
module Alf class Renderer class Html < Renderer def self.mime_type "text/html" end def each return to_enum unless block_given? yield "<table class=\"table table-condensed table-bordered table-striped\">" header = nil each_tuple do |tuple| unless header header = tuple.keys yield "<thead><tr>" header.each do |attrname| yield "<th>#{attrname}</th>" end yield "</tr></thead><tbody>" end yield "<tr>" header.each do |attrname| yield "<td>#{render_value tuple[attrname]}</td>" end yield "</tr>" end yield "</tbody></table>" end def self.render(input, output, options= {}) new(input, options).execute(output) end private def render_value(value) case value when RelationLike Html.new(value).execute("") when ->(t){ t.is_a?(Array) && t.first && t.first.is_a?(Hash) } Html.new(value).execute("") else value.to_s end end ::Alf::Renderer.register(:html, "as an html table", self) end # class Html end # class Renderer end # module Alf
module Alf class Renderer class Html < Renderer def self.mime_type "text/html" end def each return to_enum unless block_given? yield "<table>" header = nil each_tuple do |tuple| unless header header = tuple.keys yield "<thead><tr>" header.each do |attrname| yield "<th>#{attrname}</th>" end yield "</tr></thead><tbody>" end yield "<tr>" header.each do |attrname| yield "<td>#{render_value tuple[attrname]}</td>" end yield "</tr>" end yield "</tbody></table>" end def self.render(input, output, options= {}) new(input, options).execute(output) end private def render_value(value) case value when RelationLike Html.new(value).execute("") when ->(t){ t.is_a?(Array) && t.first && t.first.is_a?(Hash) } Html.new(value).execute("") else value.to_s end end ::Alf::Renderer.register(:html, "as an html table", self) end # class Html end # class Renderer end # module Alf
Remove redcarpet dependency as it not being used
$:.unshift File.expand_path("../../mustermann/lib", __FILE__) require "mustermann/version" Gem::Specification.new do |s| s.name = "support" s.version = "0.0.1" s.author = "Konstantin Haase" s.email = "konstantin.mailinglists@googlemail.com" s.homepage = "https://github.com/rkh/mustermann" s.summary = %q{support for mustermann development} s.require_path = 'lib' 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.add_dependency 'tool', '~> 0.2' s.add_dependency 'rspec' s.add_dependency 'rspec-its' s.add_dependency 'addressable' s.add_dependency 'sinatra', '~> 1.4' s.add_dependency 'rack-test' s.add_dependency 'rake' s.add_dependency 'yard' s.add_dependency 'redcarpet' s.add_dependency 'simplecov' s.add_dependency 'coveralls' end
$:.unshift File.expand_path("../../mustermann/lib", __FILE__) require "mustermann/version" Gem::Specification.new do |s| s.name = "support" s.version = "0.0.1" s.author = "Konstantin Haase" s.email = "konstantin.mailinglists@googlemail.com" s.homepage = "https://github.com/rkh/mustermann" s.summary = %q{support for mustermann development} s.require_path = 'lib' 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.add_dependency 'tool', '~> 0.2' s.add_dependency 'rspec' s.add_dependency 'rspec-its' s.add_dependency 'addressable' s.add_dependency 'sinatra', '~> 1.4' s.add_dependency 'rack-test' s.add_dependency 'rake' s.add_dependency 'yard' s.add_dependency 'simplecov' s.add_dependency 'coveralls' end
Set iOS and mac deployment targets to 7 and 10.9, respectively
Pod::Spec.new do |s| s.name = "TRVSEventSource" s.version = "0.0.1" s.summary = "Server-sent events EventSource client using NSURLSession" s.homepage = "http://github.com/travisjeffery/TRVSEventSource" s.license = 'MIT' s.author = { "Travis Jeffery" => "tj@travisjeffery.com" } s.platform = :ios, '7.0' s.source = { :git => "http://github.com/travisjeffery/TRVSEventSource.git", :tag => "0.0.1" } s.source_files = 'TRVSEventSource', 'TRVSEventSource/**/*.{h,m}' s.requires_arc = true end
Pod::Spec.new do |s| s.name = "TRVSEventSource" s.version = "0.0.1" s.summary = "Server-sent events EventSource client using NSURLSession" s.homepage = "http://github.com/travisjeffery/TRVSEventSource" s.license = 'MIT' s.author = { "Travis Jeffery" => "tj@travisjeffery.com" } s.ios.deployment_target = '7.0' s.osx.deployment_target = '10.9' s.source = { :git => "http://github.com/travisjeffery/TRVSEventSource.git", :tag => "0.0.1" } s.source_files = 'TRVSEventSource', 'TRVSEventSource/**/*.{h,m}' s.requires_arc = true end
Remove temporary todo since they are now included in the ar spec helper
# TODO: Redefine the concerns here so we don't have to require a rabbit hole. There should be a better way. This may be affected by test order. We'll come back to this module UploadsMedia; end module UploadsThumbnails; end require "active_record_spec_helper" require "./app/models/event" describe Event do subject { build(:event) } describe "validations" do it "is invalid without a name" do subject.name = nil expect(subject).to_not be_valid expect(subject.errors[:name]).to include "can't be blank" end end end
require "active_record_spec_helper" require "./app/models/event" describe Event do subject { build(:event) } describe "validations" do it "is invalid without a name" do subject.name = nil expect(subject).to_not be_valid expect(subject.errors[:name]).to include "can't be blank" end end end
Remove hook so migrations with run
class Itemizable < ActiveRecord::Base belongs_to :purchase belongs_to :item belongs_to :coach belongs_to :swap has_one :user, through: :purchase after_save :send_swap_message, if: Proc.new { |i| i.swap_id && i.swap_id_changed? } validates_presence_of :item, :purchase validates :color_code, inclusion: { in: proc { Itemizable.color_code_options }, message: "%{value} is not a valid stoplight color" }, allow_blank: true def self.color_code_options %W(red yellow green) end def servings_total quantity.to_f * item.servings_per.to_f end private def send_swap_message UserMailer.delay.replacement_suggestion(self.id) end end
class Itemizable < ActiveRecord::Base belongs_to :purchase belongs_to :item belongs_to :coach belongs_to :swap has_one :user, through: :purchase # after_save :send_swap_message, if: Proc.new { |i| i.swap_id && i.swap_id_changed? } validates_presence_of :item, :purchase validates :color_code, inclusion: { in: proc { Itemizable.color_code_options }, message: "%{value} is not a valid stoplight color" }, allow_blank: true def self.color_code_options %W(red yellow green) end def servings_total quantity.to_f * item.servings_per.to_f end private def send_swap_message UserMailer.delay.replacement_suggestion(self.id) end end
Add documentation of Article methods in public interface
# News Articles # # == Attributes # # name:: headline # id:: unique numerical id (starting at 1) # rss_log_id:: unique numerical id # created_at:: Date/time it was first created. # updated_at:: Date/time it was last updated. # user:: user who created article # # == methods # display_name:: name boldfaced for display # author:: user.name and login for display # class Article < AbstractModel belongs_to :user belongs_to :rss_log # Automatically log standard events. self.autolog_events = [:created_at!, :updated_at!, :destroyed!] # name boldfaced (in Textile). Used by show and index templates def display_name "**#{name}**" end def format_name name end def unique_format_name name + " (#{id || "?"})" end # Article creator. Used by show and index templates def author "#{user.name} (#{user.login})" end end
# News Articles # # == Attributes # # name:: headline # id:: unique numerical id (starting at 1) # rss_log_id:: unique numerical id # created_at:: Date/time it was first created. # updated_at:: Date/time it was last updated. # user:: user who created article # # == methods # author:: user.name + user.login # display_name:: name boldfaced # format_name name # unique_format_name name + id # class Article < AbstractModel belongs_to :user belongs_to :rss_log # Automatically log standard events. self.autolog_events = [:created_at!, :updated_at!, :destroyed!] # name boldfaced (in Textile). Used by show and index templates def display_name "**#{name}**" end # Article creator. Used by show and index templates def author "#{user.name} (#{user.login})" end # used by MatrixBoxPresenter to show orphaned obects def format_name name end # title + id # used by MatrixBoxPresenter to show unorphaned obects def unique_format_name name + " (#{id || "?"})" end end
Change in checking whether a number is even -> a % 2 == 0 to a.even?
a = 1 b = 2 sum = 0 while b <= 4_000_000 c = a + b a = b b = c sum += a if a % 2 == 0 end p sum
a = 1 b = 2 sum = 0 while b <= 4_000_000 c = a + b a = b b = c sum += a if a.even? end p sum
Use flash.now for coupon application error in OrdersController
module Spree class StoreController < Spree::BaseController include Spree::Core::ControllerHelpers::Order def unauthorized render 'spree/shared/unauthorized', :layout => Spree::Config[:layout], :status => 401 end protected # This method is placed here so that the CheckoutController # and OrdersController can both reference it (or any other controller # which needs it) def apply_coupon_code if params[:order] && params[:order][:coupon_code] @order.coupon_code = params[:order][:coupon_code] handler = PromotionHandler::Coupon.new(@order).apply if handler.error.present? flash[:error] = handler.error respond_with(@order) { |format| format.html { render :edit } } and return elsif handler.success flash[:success] = handler.success end end end def config_locale Spree::Frontend::Config[:locale] end end end
module Spree class StoreController < Spree::BaseController include Spree::Core::ControllerHelpers::Order def unauthorized render 'spree/shared/unauthorized', :layout => Spree::Config[:layout], :status => 401 end protected # This method is placed here so that the CheckoutController # and OrdersController can both reference it (or any other controller # which needs it) def apply_coupon_code if params[:order] && params[:order][:coupon_code] @order.coupon_code = params[:order][:coupon_code] handler = PromotionHandler::Coupon.new(@order).apply if handler.error.present? flash.now[:error] = handler.error respond_with(@order) { |format| format.html { render :edit } } and return elsif handler.success flash[:success] = handler.success end end end def config_locale Spree::Frontend::Config[:locale] end end end
Add documentation, stub methods to CompanyFetcherBot template
# encoding: UTF-8 require 'company_fetcher_bot' # you may need to require other libraries here # # require 'nokogiri' # require 'openc_bot/helpers/dates' # require 'openc_bot/helpers/incremental_search' module MyModule extend CompanyFetcherBot end
# encoding: UTF-8 require 'openc_bot' require 'openc_bot/company_fetcher_bot' # you may need to require other libraries here # # require 'nokogiri' # require 'openc_bot/helpers/dates' module MyModule extend OpencBot # This adds the CompanyFetcherBot functionality extend OpencBot::CompanyFetcherBot extend self # make these methods as Module methods, rather than instance ones # If the register has a GET'able URL based on the company_number define it here. This should mean that # #fetch_datum 'just works'. def computed_registry_url(company_number) # e.g. # "http://some,register.com/path/to/#{company_number}" end # This is the primary method for getting companies from the register. By default it uses the #fetch_data # method defined in IncrementalSearch helper module, which increments through :company_number identifiers. # See helpers/incremental_search.rb for details # Override this if a different method for iterating companies is going to done (e.g. an alpha search, or # parsing a CSV file) def fetch_data super end # This is called by #update_datum (defined in the IncrementalSearch helper module), which updates the # information for a given company_number. This allows the individual records to be updated, for example, # via the 'Update from Register' button on the company page on OpenCorporates. This method is also called # by the #fetch_data method in the case of incremental_searches. # By default it calls #fetch_registry_page with the company_number and returns the result in a hash, # with :company_page as a key. This will then be processed or parsed by the #process_datum method, # and the result will be saved by #update_datum, and also returned in a form that can be used by the # main OpenCorporates system # This hash can contain other data, such as a page of filings or shareholdings, and the hash will be # converted to json, and stored in the database in the row for that company number, under the :data key, # so that it can be reused or referred it in the future. # {:company_page => company_page_html, :filings_page => filings_page_html} def fetch_datum(company_number) super end # This method must be defined for all bots that can fetch and process individual records, including # incremental, and alpha searchers. Where the bot cannot do this (e.g. where the underlying data is # only available as a CSV file, it can be left as a stub method) def process_datum(datum_hash) end end
Remove default due time from TODOs
class ToDo < ActiveRecord::Base include MyplaceonlineActiveRecordIdentityConcern validates :short_description, presence: true def display short_description end def self.build(params = nil) result = self.dobuild(params) result.due_time = DateTime.now result end after_save { |record| DueItem.due_todos(User.current_user, record, DueItem::UPDATE_TYPE_UPDATE) } after_destroy { |record| DueItem.due_todos(User.current_user, record, DueItem::UPDATE_TYPE_DELETE) } end
class ToDo < ActiveRecord::Base include MyplaceonlineActiveRecordIdentityConcern validates :short_description, presence: true def display short_description end after_save { |record| DueItem.due_todos(User.current_user, record, DueItem::UPDATE_TYPE_UPDATE) } after_destroy { |record| DueItem.due_todos(User.current_user, record, DueItem::UPDATE_TYPE_DELETE) } end
Add feature spec to verify all 4 different states of closing issues message on Merge Request show page.
require 'spec_helper' feature 'Merge Commit Description', feature: true do let(:user) { create(:user) } let(:project) { create(:project, :public) } let(:issue_1) { create(:issue, project: project)} let(:issue_2) { create(:issue, project: project)} let(:merge_request) do create( :merge_request, :simple, source_project: project, description: merge_request_description ) end let(:merge_request_description) { 'Merge Request Description' } before do project.team << [user, :master] login_as user visit namespace_project_merge_request_path(project.namespace, project, merge_request) click_link 'Modify commit message' end context 'not closing or mentioning any issue' do it 'does not display closing issue message' do expect(page).not_to have_css('.mr-widget-footer') end end context 'closing issues but not mentioning any other issue' do let(:merge_request_description) { "Description\n\nclosing #{issue_1.to_reference}, #{issue_2.to_reference}" } it 'does not display closing issue message' do expect(page).to have_content("Accepting this merge request will close issues #{issue_1.to_reference} and #{issue_2.to_reference}") end end context 'mentioning issues but not closing them' do let(:merge_request_description) { "Description\n\nRefers to #{issue_1.to_reference} and #{issue_2.to_reference}" } it 'does not display closing issue message' do expect(page).to have_content("Issues #{issue_1.to_reference} and #{issue_2.to_reference} are mentioned but will not closed.") end end context 'closing some issues and mentioning, but not closing, others' do let(:merge_request_description) { "Description\n\ncloses #{issue_1.to_reference}\n\n refers to #{issue_2.to_reference}" } it 'does not display closing issue message' do expect(page).to have_content("Accepting this merge request will close issue #{issue_1.to_reference}. Issue #{issue_2.to_reference} is mentioned but will not closed.") end end end
Remove pry requires from spec
require 'pry' # frozen_string_literal: true require 'spec_helper' describe Admin::CfpsController do let!(:today) { Date.today } let!(:conference) { create(:conference, start_date: today + 20.days, end_date: today + 30.days) } let!(:organizer) { create(:organizer, resource: conference) } let(:cfp) { create(:cfp, program: conference.program) } before { sign_in(organizer) } describe 'POST #create' do it 'successes' do post :create, params: { conference_id: conference.short_title, cfp: { cfp_type: 'events', start_date: today, end_date: today + 6.days, description: 'We call for papers, or tabak, or you know what!' } } expect(flash[:notice]).to match('Call for papers successfully created.') end end describe 'POST #update' do it 'successes' do patch :update, params: { conference_id: conference.short_title, id: cfp.id, cfp: { end_date: today + 10.days } } expect(flash[:notice]).to match('Call for papers successfully updated.') end end end
# frozen_string_literal: true require 'spec_helper' describe Admin::CfpsController do let!(:today) { Date.today } let!(:conference) { create(:conference, start_date: today + 20.days, end_date: today + 30.days) } let!(:organizer) { create(:organizer, resource: conference) } let(:cfp) { create(:cfp, program: conference.program) } before { sign_in(organizer) } describe 'POST #create' do it 'successes' do post :create, params: { conference_id: conference.short_title, cfp: { cfp_type: 'events', start_date: today, end_date: today + 6.days, description: 'We call for papers, or tabak, or you know what!' } } expect(flash[:notice]).to match('Call for papers successfully created.') end end describe 'POST #update' do it 'successes' do patch :update, params: { conference_id: conference.short_title, id: cfp.id, cfp: { end_date: today + 10.days } } expect(flash[:notice]).to match('Call for papers successfully updated.') end end end
Add example of updating with invalid card
gem 'chargify_api_ares', '=1.3.5' require 'chargify_api_ares' Chargify.configure do |c| c.subdomain = ENV['CHARGIFY_SUBDOMAIN'] c.api_key = ENV['CHARGIFY_API_KEY'] end sub = Chargify::Subscription.find 9970657 sub.credit_card_attributes = {:full_number => "3", :expiration_year => "2020"} sub.save puts sub.inspect
Update podspec to version 0.0.8
Pod::Spec.new do |s| s.name = "DFImageManager" s.version = "0.0.7" s.summary = "Complete solution for fetching, caching and adjusting images" s.homepage = "https://github.com/kean/DFImageManager" s.license = { :type => "MIT", :file => "LICENSE" } s.author = { "Alexander Grebenyuk" => "grebenyuk.alexander@gmail.com" } s.social_media_url = "https://www.facebook.com/agrebenyuk" s.platform = :ios s.ios.deployment_target = "6.0" s.source = { :git => "https://github.com/kean/DFImageManager.git", :tag => s.version.to_s } s.source_files = "DFImageManager/DFImageManager/**/*.{h,m}" s.requires_arc = true s.dependency "DFCache", "~> 2.0" end
Pod::Spec.new do |s| s.name = "DFImageManager" s.version = "0.0.8" s.summary = "Complete solution for fetching, caching and adjusting images" s.homepage = "https://github.com/kean/DFImageManager" s.license = { :type => "MIT", :file => "LICENSE" } s.author = { "Alexander Grebenyuk" => "grebenyuk.alexander@gmail.com" } s.social_media_url = "https://www.facebook.com/agrebenyuk" s.platform = :ios s.ios.deployment_target = "6.0" s.source = { :git => "https://github.com/kean/DFImageManager.git", :tag => s.version.to_s } s.source_files = "DFImageManager/DFImageManager/**/*.{h,m}" s.requires_arc = true s.dependency "DFCache", "~> 2.0" end
Fix symbol at default data
# -*- coding: utf-8 -*- class Account < ActiveRecord::Base include WithClassName has_secure_password has_many :delegates, dependent: :destroy has_many :projects, through: :delegates accepts_nested_attributes_for :projects accepts_nested_attributes_for :delegates has_many :roles, dependent: :destroy has_many :divisions, through: :roles accepts_nested_attributes_for :divisions accepts_nested_attributes_for :roles validates :name, { presence: true, length: { in: 1..20 } } validates :email, { presence: true, uniqueness: true, } validates :password, { presence: true, length: { minimum: 8 } } validates :password_confirmation, { presence: true, length: { minimum: 8 } } def organizations { divisions: self.divisions, projects: self.projects } end end
# -*- coding: utf-8 -*- class Account < ActiveRecord::Base include WithClassName has_secure_password has_many :delegates, dependent: :destroy has_many :projects, through: :delegates accepts_nested_attributes_for :projects accepts_nested_attributes_for :delegates has_many :roles, dependent: :destroy has_many :divisions, through: :roles accepts_nested_attributes_for :divisions accepts_nested_attributes_for :roles validates :name, { presence: true, length: { in: 1..20 } } validates :email, { presence: true, uniqueness: true, } validates :password, { presence: true, length: { minimum: 8 } } validates :password_confirmation, { presence: true, length: { minimum: 8 } } def organizations { my_divisions: self.divisions, my_projects: self.projects } end end
Add version route for segment
require 'sinatra/base' require 'sinatra/respond_with' require 'llt/segmenter' require 'llt/core/api' class Api < Sinatra::Base register Sinatra::RespondWith helpers LLT::Core::Api::Helpers get '/segment' do typecast_params!(params) text = extract_text(params) segmenter = LLT::Segmenter.new(params) sentences = segmenter.segment(text) respond_to do |f| f.xml { to_xml(sentences, params) } end end end
require 'sinatra/base' require 'sinatra/respond_with' require 'llt/segmenter' require 'llt/core/api' class Api < Sinatra::Base register Sinatra::RespondWith register LLT::Core::Api::VersionRoutes helpers LLT::Core::Api::Helpers get '/segment' do typecast_params!(params) text = extract_text(params) segmenter = LLT::Segmenter.new(params) sentences = segmenter.segment(text) respond_to do |f| f.xml { to_xml(sentences, params) } end end add_version_route_for('/segment', dependencies: %i{ Core Segmenter }) end
Add Options class for option parsing
require 'optparse' module Punchlist class Options attr_reader :default_punchlist_line_regexp def initialize(default_punchlist_line_regexp) @default_punchlist_line_regexp = default_punchlist_line_regexp end def setup_options(opts) options = {} opts.banner = 'Usage: punchlist [options]' opts.on('-g', '--glob g', 'Filename glob to identify source files') do |v| options[:glob] = v end opts.on('-r', '--regexp r', 'Regexp to trigger on - ' \ 'default is XXX|TODO') do |v| options[:regexp] = v end options end def parse_options options = nil OptionParser.new do |opts| options = setup_options(opts) end.parse! options end end end
Fix plugin icon with Redmine 3.4.x
Redmine::MenuManager.map :admin_menu do |menu| menu.push :redmine_git_hosting, { controller: 'settings', action: 'plugin', id: 'redmine_git_hosting' }, caption: :redmine_git_hosting end Redmine::MenuManager.map :top_menu do |menu| menu.push :archived_repositories, { controller: '/archived_repositories', action: 'index' }, caption: :label_archived_repositories, after: :administration, if: Proc.new { User.current.logged? && User.current.admin? } end
Redmine::MenuManager.map :admin_menu do |menu| menu.push :redmine_git_hosting, { controller: 'settings', action: 'plugin', id: 'redmine_git_hosting' }, caption: :redmine_git_hosting, html: { class: 'icon' } end Redmine::MenuManager.map :top_menu do |menu| menu.push :archived_repositories, { controller: '/archived_repositories', action: 'index' }, caption: :label_archived_repositories, after: :administration, if: Proc.new { User.current.logged? && User.current.admin? } end
Remove comments of failed attempt to custom validate.
# class ChoicesSetUnlessEnding < ActiveModel::Validator #   def validate(record) #     unless record.name.starts_with? 'X' #       record.errors[:name] << 'Need a name starting with X please!' #     end #   end # end class Situation < ActiveRecord::Base validates :title, presence: true validates :sit_rep, presence: true # validates_with ChoicesSetUnlessEnding validates :choice_1, presence: true, unless: Proc.new { |a| a.ending? } validates :choice_2, presence: true, unless: Proc.new { |a| a.ending? } validates :choice_1_label, presence: true, unless: Proc.new { |a| a.ending? } validates :choice_2_label, presence: true, unless: Proc.new { |a| a.ending? } end
class Situation < ActiveRecord::Base validates :title, presence: true validates :sit_rep, presence: true validates :choice_1, presence: true, unless: Proc.new { |a| a.ending? } validates :choice_2, presence: true, unless: Proc.new { |a| a.ending? } validates :choice_1_label, presence: true, unless: Proc.new { |a| a.ending? } validates :choice_2_label, presence: true, unless: Proc.new { |a| a.ending? } end
Remove old Rails namespace from version
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'jeet/version' Gem::Specification.new do |spec| spec.name = 'jeet' spec.version = Jeet::Rails::VERSION spec.authors = ['Cory Simmons', 'Jonah Ruiz'] spec.email = ['csimmonswork@gmail.com', 'jonah@pixelhipsters.com'] spec.summary = 'A grid system for humans.' spec.description = 'The most advanced and intuitive Sass grid system on the planet.' spec.homepage = 'http://jeet.gs' 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 'sass', '~> 3.2' spec.add_development_dependency 'bundler', '~> 1.6' spec.add_development_dependency 'rake', '~> 10.0' end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'jeet/version' Gem::Specification.new do |spec| spec.name = 'jeet' spec.version = Jeet::VERSION spec.authors = ['Cory Simmons', 'Jonah Ruiz'] spec.email = ['csimmonswork@gmail.com', 'jonah@pixelhipsters.com'] spec.summary = 'A grid system for humans.' spec.description = 'The most advanced and intuitive Sass grid system on the planet.' spec.homepage = 'http://jeet.gs' 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 'sass', '~> 3.2' spec.add_development_dependency 'bundler', '~> 1.6' spec.add_development_dependency 'rake', '~> 10.0' end
Include the markdown helper into ActionView
require 'rubygems' require 'bundler/setup' Bundler.require(:default) require 'disco/markdown_helper'
require 'rubygems' require 'bundler/setup' Bundler.require(:default) require 'disco/markdown_helper' ActionView::Base.send(:include, Disco::MarkdownHelper)
Move all predicates to constants
module Might # Contains contains with all supported predicates # module FilterPredicates ON_VALUE = %w( not_eq eq does_not_match matches gt lt gteq lteq not_cont cont not_start start not_end end not_true true not_false false blank present not_null null ) ON_ARRAY = %w( not_in in not_cont_any cont_any ) ALL = ON_VALUE + ON_ARRAY end end
module Might # Contains contains with all supported predicates # module FilterPredicates NOT_EQ = 'not_eq' EQ = 'eq' DOES_NOT_MATCH = 'does_not_match' MATCHES = 'matches' GT = 'gt' LT = 'lt' GTEQ = 'gteq' LTEQ = 'lteq' NOT_CONT = 'not_cont' CONT = 'cont' NOT_START = 'not_start' START = 'start' DOES_NOT_END = 'not_end' ENDS = 'end' NOT_TRUE = 'not_true' TRUE = 'true' NOT_FALSE = 'not_false' FALSE = 'false' BLANK = 'blank' PRESENT = 'present' NOT_NULL = 'not_null' NULL = 'null' NOT_IN = 'not_in' IN = 'in' NOT_CONT_ANY = 'not_cont_any' CONT_ANY = 'cont_any' ON_VALUE = [ NOT_EQ, EQ, DOES_NOT_MATCH, MATCHES, GT, LT, GTEQ, LTEQ, NOT_CONT, CONT, NOT_START, START, DOES_NOT_END, ENDS, NOT_TRUE, TRUE, NOT_FALSE, FALSE, BLANK, PRESENT, NOT_NULL, NULL ] ON_ARRAY = [ NOT_IN, IN, NOT_CONT_ANY, CONT_ANY ] ALL = ON_VALUE + ON_ARRAY end end
Downgrade RSpec for TM1 compatability
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'cloud_files/version' Gem::Specification.new do |spec| spec.name = "cloud_files" spec.version = CloudFiles::VERSION spec.authors = ["Patrick Reagan"] spec.email = ["reaganpr@gmail.com"] spec.summary = %q{Work with Rackspace cloudfiles} spec.homepage = "http://viget.com/extend" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = 'bin' spec.executables = ['cf'] spec.require_paths = ['lib'] spec.add_dependency "fog", "~> 1.32.0" spec.add_dependency "activesupport", "~> 4.2.0" spec.add_development_dependency "bundler", "~> 1.10" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec", "~> 3.3.0" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'cloud_files/version' Gem::Specification.new do |spec| spec.name = "cloud_files" spec.version = CloudFiles::VERSION spec.authors = ["Patrick Reagan"] spec.email = ["reaganpr@gmail.com"] spec.summary = %q{Work with Rackspace cloudfiles} spec.homepage = "http://viget.com/extend" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = 'bin' spec.executables = ['cf'] spec.require_paths = ['lib'] spec.add_dependency "fog", "~> 1.32.0" spec.add_dependency "activesupport", "~> 4.2.0" spec.add_development_dependency "bundler", "~> 1.10" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec", "~> 3.2.0" end
Update gemspec to reflect Japanese support only for now
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'agate/version' Gem::Specification.new do |spec| spec.name = "agate" spec.version = Agate::VERSION spec.authors = ["Jesse B. Hannah"] spec.email = ["jesse@jbhannah.net"] spec.description = %q{Wrap ruby characters (e.g. furigana, Pinyin, Zhuyin) in text with the HTML ruby element.} spec.summary = %q{Wrap ruby characters (e.g. furigana, Pinyin, Zhuyin) in text with the HTML ruby element.} spec.homepage = "https://github.com/jbhannah/agate" spec.license = "MIT" spec.files = `git ls-files`.split($/) 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.2" spec.add_development_dependency "rake" spec.add_development_dependency "rspec", "~> 2.13.0" spec.add_development_dependency "coveralls" end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'agate/version' Gem::Specification.new do |spec| spec.name = "agate" spec.version = Agate::VERSION spec.authors = ["Jesse B. Hannah"] spec.email = ["jesse@jbhannah.net"] spec.description = %q{Wrap ruby characters (currently only furigana) in text with the HTML5 ruby element.} spec.summary = %q{Wrap ruby characters (currently only furigana) in text with the HTML5 ruby element.} spec.homepage = "https://github.com/jbhannah/agate" spec.license = "MIT" spec.files = `git ls-files`.split($/) 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.2" spec.add_development_dependency "rake" spec.add_development_dependency "rspec", "~> 2.13.0" spec.add_development_dependency "coveralls" end
Remove deprecation warning in spec test
shared_examples "with header" do |header, value| it "sets header #{header}" do expect { subject.deliver! }.to change { ActionMailer::Base.deliveries.count }.by(1) m = ActionMailer::Base.deliveries.last expect(m.header.to_s).to match(/(\r\n)?#{header}: #{value}(\r\n)?/) end end shared_examples "without header" do |header| it "does not set header #{header}" do expect { subject.deliver! }.to change { ActionMailer::Base.deliveries.count }.by(1) m = ActionMailer::Base.deliveries.last expect(m.header.to_s).not_to match(/(\r\n)?#{header}: [^\r]*(\r\n)?/) end end shared_examples "raise an exception" do |exception| it "raises #{exception}" do expect { expect { subject.deliver! }.to raise_error(exception) }.to change { ActionMailer::Base.deliveries.count }.by(0) end end
deliver_method = ActionMailer.respond_to?(:version) && ActionMailer.version.to_s.to_f >= 4.2 ? :deliver_now! : :deliver! shared_examples "with header" do |header, value| it "sets header #{header}" do expect { subject.__send__(deliver_method) }.to change { ActionMailer::Base.deliveries.count }.by(1) m = ActionMailer::Base.deliveries.last expect(m.header.to_s).to match(/(\r\n)?#{header}: #{value}(\r\n)?/) end end shared_examples "without header" do |header| it "does not set header #{header}" do expect { subject.__send__(deliver_method) }.to change { ActionMailer::Base.deliveries.count }.by(1) m = ActionMailer::Base.deliveries.last expect(m.header.to_s).not_to match(/(\r\n)?#{header}: [^\r]*(\r\n)?/) end end shared_examples "raise an exception" do |exception| it "raises #{exception}" do expect { expect { subject.__send__(deliver_method) }.to raise_error(exception) }.to change { ActionMailer::Base.deliveries.count }.by(0) end end
Create view generator in the rule engine
module UserMaintenance class ViewsGenerator < Rails::Generators::Base def copy_views ViewsGenerator.source_root File.expand_path('../../../../app/views', __FILE__) directory 'user_maintenance', 'app/views/user_maintenance' end end end
Add a first spec. We need to start somewhere, right?
require 'rails_helper' RSpec.describe Post, :type => :model do pending "add some examples to (or delete) #{__FILE__}" end
require 'rails_helper' RSpec.describe Post, :type => :model do describe '#sha' do it 'is automatically generated when validating a post instance' do post = build(:post) expect(post.sha).to be_blank post.valid? expect(post.sha).to_not be_blank end end end
Create new tag version to update the pod
Pod::Spec.new do |s| # 1 s.name = 'UrbandManager' s.version = '0.0.2' s.ios.deployment_target = '10.0' s.summary = 'By far the most fantastic urband manager I have seen in my entire life. No joke.' s.description = <<-DESC This fantastics manager allows you to control the best smartband I have seen in my entire life. DESC s.homepage = 'https://github.com/CoatlCo/UrbandManager' s.license = { :type => 'MIT', :file => 'LICENSE.md' } s.author = { 'specktro' => 'specktro@nonull.mx' } s.source = { :git => 'https://github.com/CoatlCo/UrbandManager.git', :tag => "#{s.version}" } s.framework = "CoreBluetooth" s.source_files = 'UrbandManager/manager/UrbandManager.swift', 'UrbandManager/utilities/Utilities.swift' end
Pod::Spec.new do |s| # 1 s.name = 'UrbandManager' s.version = '0.0.3' s.ios.deployment_target = '10.0' s.summary = 'By far the most fantastic urband manager I have seen in my entire life. No joke.' s.description = <<-DESC This fantastics manager allows you to control the best smartband I have seen in my entire life. DESC s.homepage = 'https://github.com/CoatlCo/UrbandManager' s.license = { :type => 'MIT', :file => 'LICENSE.md' } s.author = { 'specktro' => 'specktro@nonull.mx' } s.source = { :git => 'https://github.com/CoatlCo/UrbandManager.git', :tag => "#{s.version}" } s.framework = "CoreBluetooth" s.source_files = 'UrbandManager/manager/UrbandManager.swift', 'UrbandManager/utilities/Utilities.swift' end