Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix const reloading in development
# Common subscribers (`Subscribers::Base` pattern) Subscribers::SiteActivity.attach_to('activities/sites') Subscribers::AdminActivity.attach_to('activities/admins') Subscribers::CensusActivity.attach_to('activities/census') Subscribers::UserActivity.attach_to('activities/users') Subscribers::GobiertoPeopleActivity.attach_to('trackable') Subscribers::GobiertoCmsPageActivity.attach_to('activities/gobierto_cms_pages') # Custom subscribers ActiveSupport::Notifications.subscribe(/trackable/) do |*args| event = ActiveSupport::Notifications::Event.new(*args) Rails.logger.debug("Consuming event \"#{event.name}\" with payload: #{event.payload}") User::Subscription::NotificationBuilder.new(event).call end
# Common subscribers (`Subscribers::Base` pattern) ::Subscribers::SiteActivity.attach_to('activities/sites') ::Subscribers::AdminActivity.attach_to('activities/admins') ::Subscribers::CensusActivity.attach_to('activities/census') ::Subscribers::UserActivity.attach_to('activities/users') ::Subscribers::GobiertoPeopleActivity.attach_to('trackable') ::Subscribers::GobiertoCmsPageActivity.attach_to('activities/gobierto_cms_pages') # Custom subscribers ActiveSupport::Notifications.subscribe(/trackable/) do |*args| event = ActiveSupport::Notifications::Event.new(*args) Rails.logger.debug("Consuming event \"#{event.name}\" with payload: #{event.payload}") User::Subscription::NotificationBuilder.new(event).call end
Fix pagination in API controllers
class Api::ApiController < ActionController::Base include Authentication protect_from_forgery with: :exception before_action :check_permanent_user around_action :set_timezone around_action :handle_param_validation resource_description do formats ['json'] meta author: {name: 'Marri'} app_info 'The public API for the Glowfic Constellation' end protected def login_required return if logged_in? error = {message: "You must be logged in to view that page."} render json: {errors: [error]}, status: :unauthorized and return end def set_timezone Time.use_zone("UTC") { yield } end def handle_param_validation yield rescue Apipie::ParamMissing, Apipie::ParamInvalid => error error_hash = {message: Glowfic::Sanitizers.full(error.message.tr('"', "'"))} render json: {errors: [error_hash]}, status: :unprocessable_entity end def access_denied error = {message: "You do not have permission to perform this action."} render json: {errors: [error]}, status: :forbidden end def per_page per = params[:per_page].to_i return 25 if per < 1 return 100 if per > 100 per end end
class Api::ApiController < ActionController::Base include Rails::Pagination include Authentication protect_from_forgery with: :exception before_action :check_permanent_user around_action :set_timezone around_action :handle_param_validation resource_description do formats ['json'] meta author: {name: 'Marri'} app_info 'The public API for the Glowfic Constellation' end protected def login_required return if logged_in? error = {message: "You must be logged in to view that page."} render json: {errors: [error]}, status: :unauthorized and return end def set_timezone Time.use_zone("UTC") { yield } end def handle_param_validation yield rescue Apipie::ParamMissing, Apipie::ParamInvalid => error error_hash = {message: Glowfic::Sanitizers.full(error.message.tr('"', "'"))} render json: {errors: [error_hash]}, status: :unprocessable_entity end def access_denied error = {message: "You do not have permission to perform this action."} render json: {errors: [error]}, status: :forbidden end def per_page per = params[:per_page].to_i return 25 if per < 1 return 100 if per > 100 per end end
Add upload_logo Action to Courses Controller
class CoursesController < ApplicationController before_filter :authenticate_user! before_filter :get_club, :only => [ :show_all ] before_filter :get_course, :only => [ :edit, :update, :change_logo ] def create @club = Club.find params[:club_id] @course = @club.courses.new authorize! :create, @course @course.assign_defaults @course.save render :edit end def edit authorize! :edit, @course @club = @course.club end def update authorize! :update, @course @course.update_attributes params[:course] respond_with_bip @course end def change_logo authorize! :update, @course end def show_all @courses = @club.courses end private def get_club @club = Club.find params[:club_id] end def get_course @course = Course.find params[:id] end end
class CoursesController < ApplicationController before_filter :authenticate_user! before_filter :get_club, :only => [ :show_all ] before_filter :get_course, :only => [ :edit, :update, :change_logo, :upload_logo ] def create @club = Club.find params[:club_id] @course = @club.courses.new authorize! :create, @course @course.assign_defaults @course.save render :edit end def edit authorize! :edit, @course @club = @course.club end def update authorize! :update, @course @course.update_attributes params[:course] respond_with_bip @course end def change_logo authorize! :update, @course end def upload_logo authorize! :update, @course if @course.update_attributes params[:course] redirect_to edit_course_path(@course) else render :change_logo, :formats => [ :js ] end end def show_all @courses = @club.courses end private def get_club @club = Club.find params[:club_id] end def get_course @course = Course.find params[:id] end end
Break out into separate method
module Ebooks class Twitter def initialize(credentials = {}) @consumer_key = credentials.fetch(:consumer_key) @consumer_secret = credentials.fetch(:consumer_secret) @access_token = credentials.fetch(:oauth_token) @access_token_secret = credentials.fetch(:oauth_token_secret) end def tweet(tweet_text) twitter_client = ::Twitter::REST::Client.new do |config| config.consumer_key = @consumer_key config.consumer_secret = @consumer_secret config.access_token = @access_token config.access_token_secret = @access_token_secret end tweet_text = tweet_text.gsub('@', '')[0..139] p "#{Time.now}: #{tweet_text}" twitter_client.update(tweet_text) end end end
module Ebooks class Twitter def initialize(credentials = {}) @consumer_key = credentials.fetch(:consumer_key) @consumer_secret = credentials.fetch(:consumer_secret) @access_token = credentials.fetch(:oauth_token) @access_token_secret = credentials.fetch(:oauth_token_secret) end def twitter_client ::Twitter::REST::Client.new do |config| config.consumer_key = @consumer_key config.consumer_secret = @consumer_secret config.access_token = @access_token config.access_token_secret = @access_token_secret end end def tweet(tweet_text) tweet_text = tweet_text.gsub('@', '')[0..139] p "#{Time.now}: #{tweet_text}" twitter_client.update(tweet_text) end end end
Add last_anme and first_name parameters to controller
require_dependency 'stash_datacite/application_controller' module StashDatacite class CreatorsController < ApplicationController before_action :set_creator, only: [:update, :destroy] respond_to :json # GET /creators/new def new @creator = Creator.new end # POST /creators def create @creator = Creator.new(creator_params) respond_to do |format| if @creator.save format.js else format.html { render :new } end end end # PATCH/PUT /creators/1 def update respond_to do |format| if @creator.update(creator_params) format.js { render template: 'stash_datacite/shared/update.js.erb' } else format.html { render :edit } end end end # DELETE /creators/1 def destroy @creator.destroy redirect_to creators_url, notice: 'Creator was successfully destroyed.' end private # Use callbacks to share common setup or constraints between actions. def set_creator @creator = Creator.find(creator_params[:id]) end # Only allow a trusted parameter "white list" through. def creator_params params.require(:creator).permit(:id, :creator_name, :name_identifier_id, :affliation_id, :resource_id) end end end
require_dependency 'stash_datacite/application_controller' module StashDatacite class CreatorsController < ApplicationController before_action :set_creator, only: [:update, :destroy] respond_to :json # GET /creators/new def new @creator = Creator.new end # POST /creators def create @creator = Creator.new(creator_params) respond_to do |format| if @creator.save format.js else format.html { render :new } end end end # PATCH/PUT /creators/1 def update respond_to do |format| if @creator.update(creator_params) format.js { render template: 'stash_datacite/shared/update.js.erb' } else format.html { render :edit } end end end # DELETE /creators/1 def destroy @creator.destroy redirect_to creators_url, notice: 'Creator was successfully destroyed.' end private # Use callbacks to share common setup or constraints between actions. def set_creator @creator = Creator.find(creator_params[:id]) end # Only allow a trusted parameter "white list" through. def creator_params params.require(:creator).permit(:id, :creator_first_name, :creator_last_name, :creator_middle_name, :name_identifier_id, :affliation_id, :resource_id) end end end
Fix dependencies so gem works with rails 5.2.1 and all other 5.2.x versions
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "inherited_resources/version" Gem::Specification.new do |s| s.name = "inherited_resources" s.version = InheritedResources::VERSION.dup s.platform = Gem::Platform::RUBY s.summary = "Inherited Resources speeds up development by making your controllers inherit all restful actions so you just have to focus on what is important." s.homepage = "http://github.com/activeadmin/inherited_resources" s.description = "Inherited Resources speeds up development by making your controllers inherit all restful actions so you just have to focus on what is important." s.authors = ['José Valim', 'Rafael Mendonça França'] s.license = "MIT" s.rubyforge_project = "inherited_resources" s.files = Dir["app/**/*", "lib/**/*", "README.md", "MIT-LICENSE"] s.require_paths = ["lib"] s.required_ruby_version = '>= 2.2' s.add_dependency("responders") s.add_dependency("actionpack", ">= 4.2", "<= 5.2") s.add_dependency("railties", ">= 4.2", "<= 5.2") s.add_dependency("has_scope", "~> 0.6") end
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "inherited_resources/version" Gem::Specification.new do |s| s.name = "inherited_resources" s.version = InheritedResources::VERSION.dup s.platform = Gem::Platform::RUBY s.summary = "Inherited Resources speeds up development by making your controllers inherit all restful actions so you just have to focus on what is important." s.homepage = "http://github.com/activeadmin/inherited_resources" s.description = "Inherited Resources speeds up development by making your controllers inherit all restful actions so you just have to focus on what is important." s.authors = ['José Valim', 'Rafael Mendonça França'] s.license = "MIT" s.rubyforge_project = "inherited_resources" s.files = Dir["app/**/*", "lib/**/*", "README.md", "MIT-LICENSE"] s.require_paths = ["lib"] s.required_ruby_version = '>= 2.2' s.add_dependency("responders") s.add_dependency("actionpack", ">= 4.2", "< 5.3") s.add_dependency("railties", ">= 4.2", "< 5.3") s.add_dependency("has_scope", "~> 0.6") end
Improve the module definition to get rid of the extra include
# frozen_string_literal: true # # Licensed to CRATE Technology GmbH ("Crate") under one or more contributor # license agreements. See the NOTICE file distributed with this work for # additional information regarding copyright ownership. Crate licenses # this file to you under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. You may # obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # However, if you have executed another commercial license agreement # with Crate these terms will supersede the license and you may use the # software solely pursuant to the terms of the relevant commercial agreement. require 'crate_ruby/version' require 'crate_ruby/error' require 'crate_ruby/result_set' require 'crate_ruby/client' include CrateRuby module CrateRuby def self.logger @logger ||= begin require 'logger' log = Logger.new($stderr) log.level = Logger::INFO log end end def self.logger=(logger) @logger = logger end end
# frozen_string_literal: true # # Licensed to CRATE Technology GmbH ("Crate") under one or more contributor # license agreements. See the NOTICE file distributed with this work for # additional information regarding copyright ownership. Crate licenses # this file to you under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. You may # obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # However, if you have executed another commercial license agreement # with Crate these terms will supersede the license and you may use the # software solely pursuant to the terms of the relevant commercial agreement. module CrateRuby require 'crate_ruby/version' require 'crate_ruby/error' require 'crate_ruby/result_set' require 'crate_ruby/client' def self.logger @logger ||= begin require 'logger' log = Logger.new($stderr) log.level = Logger::INFO log end end def self.logger=(logger) @logger = logger end end
Set this method to private
module Octokit class EnterpriseAdminClient < Octokit::Client # Methods for the Enterprise Management Console API # # @see https://enterprise.github.com/help/articles/license-api module ManagementConsole # Get information about the Enterprise installation # # @return [Sawyer::Resource] The installation information def config_status get "/setup/api/configcheck", license_hash end alias :config_check :config_status # Get information about the Enterprise installation # # @return [Sawyer::Resource] The installation information def settings get "/setup/api/settings", license_hash end alias :get_settings :settings def license_hash { :query => { :license_md5 => @license_md5 } } end end end end
module Octokit class EnterpriseAdminClient < Octokit::Client # Methods for the Enterprise Management Console API # # @see https://enterprise.github.com/help/articles/license-api module ManagementConsole # Get information about the Enterprise installation # # @return [Sawyer::Resource] The installation information def config_status get "/setup/api/configcheck", license_hash end alias :config_check :config_status # Get information about the Enterprise installation # # @return [Sawyer::Resource] The installation information def settings get "/setup/api/settings", license_hash end alias :get_settings :settings private def license_hash { :query => { :license_md5 => @license_md5 } } end end end end
Move rest of BulletLogger code to presenter
module Bullet module Presenter class BulletLogger < Base LOG_FILE = File.join( Rails.root, 'log/bullet.log' ) @logger_file = nil @logger = nil def self.setup @logger_file = File.open( LOG_FILE, 'a+' ) @logger = Bullet::BulletLogger.new( @logger_file ) end def self.active? Bullet.bullet_logger end def self.out_of_channel( notice ) return unless active? @logger.info notice.full_notice @logger_file.flush end end end end
module Bullet module Presenter class BulletLogger < Base LOG_FILE = File.join( Rails.root, 'log/bullet.log' ) @logger_file = nil @logger = nil def self.setup @logger_file = File.open( LOG_FILE, 'a+' ) @logger = Logger.new( @logger_file ) def @logger.format_message( severity, timestamp, progname, msg ) "#{timestamp.to_formatted_s(:db)}[#{severity}] #{msg}\n" end end def self.active? Bullet.bullet_logger end def self.out_of_channel( notice ) return unless active? @logger.info notice.full_notice @logger_file.flush end end end end
Change session store app name
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_patient-4_session'
Rails.application.config.session_store :cookie_store, key: '_openlis_session'
Add private method for generating verification codes; refactor send_verification_code by also creating private methods for setup_sms and send_sms behavior to be reused in other routes
# require 'twilio-ruby' class UsersController < ActionController::API def send_verification_code account_sid = ENV['TWILIO_ACCOUNT_SID'] auth_token = ENV['TWILIO_AUTH_TOKEN'] @client = Twilio::REST::Client.new(account_sid, auth_token) @client.messages.create( from: ENV['TWILIO_NUMBER'], to: params[:number], body: 'Random number!' ) puts "it should have worked." end end
# require 'twilio-ruby' class UsersController < ActionController::API include UsersHelper def send_verification_code setup_sms send_sms(params[:number], "Your verification code is: " + generate_verification_code) end private def generate_verification_code totp = ROTP::TOTP.new("base32secret3232") totp.now.to_s end def setup_sms account_sid = ENV['TWILIO_ACCOUNT_SID'] auth_token = ENV['TWILIO_AUTH_TOKEN'] @client = Twilio::REST::Client.new(account_sid, auth_token) end def send_sms(deliver_to, body) @client.messages.create( from: ENV['TWILIO_NUMBER'], to: deliver_to, body: body) end end
Refactor how test formulas are installed in tests
# frozen_string_literal: true require "utils/livecheck_formula" require "formula_installer" describe LivecheckFormula do describe "init" do let(:f) { formula { url "foo-1.0" } } let(:options) { FormulaInstaller.new(f).display_options(f) } let(:action) { "#{f.full_name} #{options}".strip } it "runs livecheck command for Formula" do formatted_response = described_class.init(action) expect(formatted_response).not_to be_nil expect(formatted_response).to be_a(Hash) expect(formatted_response.size).not_to eq(0) end end describe "parse_livecheck_response" do it "returns a hash of Formula version data" do example_raw_command_response = "aacgain : 7834 ==> 1.8" formatted_response = described_class.parse_livecheck_response(example_raw_command_response) expect(formatted_response).not_to be_nil expect(formatted_response).to be_a(Hash) expect(formatted_response).to include(:name) expect(formatted_response).to include(:formula_version) expect(formatted_response).to include(:livecheck_version) expect(formatted_response[:name]).to eq("aacgain") expect(formatted_response[:formula_version]).to eq("7834") expect(formatted_response[:livecheck_version]).to eq("1.8") end end end
# frozen_string_literal: true require "utils/livecheck_formula" require "formula_installer" describe LivecheckFormula do describe "init" do let(:f) { formula { url "foo-1.0" } } let(:options) { FormulaInstaller.new(f).display_options(f) } let(:action) { "#{f.full_name} #{options}".strip } it "runs livecheck command for Formula" do formatted_response = described_class.init(action) expect(formatted_response).not_to be_nil expect(formatted_response).to be_a(Hash) expect(formatted_response.size).not_to eq(0) end end describe "parse_livecheck_response" do it "returns a hash of Formula version data" do example_raw_command_response = "aacgain : 7834 ==> 1.8" formatted_response = described_class.parse_livecheck_response(example_raw_command_response) expect(formatted_response).not_to be_nil expect(formatted_response).to be_a(Hash) expect(formatted_response).to include(:name) expect(formatted_response).to include(:formula_version) expect(formatted_response).to include(:livecheck_version) expect(formatted_response[:name]).to eq("aacgain") expect(formatted_response[:formula_version]).to eq("7834") expect(formatted_response[:livecheck_version]).to eq("1.8") end end end
Remove todo in Reporter class
require 'pry' module Apilint class Reporter def self.create_reporter(type) type.new end def report(offenses) # TODO: puts 210 requests inspected, 12285 offenses detected if offenses.empty? puts "No offenses" else offense_based(offenses) offenses.each do |offense| puts "----" puts "#{offense.smart_path}: #{offense.msg}" puts "\t Offense in #{offense.obj.class} #{offense.attr}. #{offense.obj.send(offense.attr)}" end end end def flush(offenses) # nop end end end
require 'pry' module Apilint class Reporter def self.create_reporter(type) type.new end def report(offenses) if offenses.empty? puts "No offenses" else offense_based(offenses) offenses.each do |offense| puts "----" puts "#{offense.smart_path}: #{offense.msg}" puts "\t Offense in #{offense.obj.class} #{offense.attr}. #{offense.obj.send(offense.attr)}" end end end def flush(offenses) # nop end end end
Add issue invoice amendment probably
module BillForward class IssueInvoiceAmendment < Amendment @resource_path = BillForward::ResourcePath.new("amendments", "amendment") def initialize(*args) super set_state_param('@type', 'IssueInvoiceAmendment') end end end
Remove todo comment, wont do
require_relative 'conditions' require_relative 'parser' module Json module Streamer class JsonStreamer attr_reader :parser def initialize(file_io = nil, chunk_size = 1000, event_generator = :default) @event_generator = make_event_generator(event_generator) @file_io = file_io @chunk_size = chunk_size end def <<(data) parser << data end def get(nesting_level: -1, key: nil, yield_values: true, symbolize_keys: false) conditions = Conditions.new(yield_level: nesting_level, yield_key: key) conditions.yield_value = ->(aggregator:, value:) { false } unless yield_values # TODO: deprecate symbolize_keys and move to initialize @parser = Parser.new(@event_generator, symbolize_keys: symbolize_keys) parser.get(conditions) do |obj| yield obj end process_io end def get_with_conditions(conditions, options = {}) @parser = Parser.new(@event_generator, symbolize_keys: options[:symbolize_keys]) parser.get(conditions) do |obj| yield obj end process_io end def aggregator parser.aggregator end private def process_io @file_io.each(@chunk_size) { |chunk| parser << chunk } if @file_io end def make_event_generator(generator) case generator when :default require 'json/stream' JSON::Stream::Parser.new else generator end end end end end
require_relative 'conditions' require_relative 'parser' module Json module Streamer class JsonStreamer attr_reader :parser def initialize(file_io = nil, chunk_size = 1000, event_generator = :default) @event_generator = make_event_generator(event_generator) @file_io = file_io @chunk_size = chunk_size end def <<(data) parser << data end def get(nesting_level: -1, key: nil, yield_values: true, symbolize_keys: false) conditions = Conditions.new(yield_level: nesting_level, yield_key: key) conditions.yield_value = ->(aggregator:, value:) { false } unless yield_values @parser = Parser.new(@event_generator, symbolize_keys: symbolize_keys) parser.get(conditions) do |obj| yield obj end process_io end def get_with_conditions(conditions, options = {}) @parser = Parser.new(@event_generator, symbolize_keys: options[:symbolize_keys]) parser.get(conditions) do |obj| yield obj end process_io end def aggregator parser.aggregator end private def process_io @file_io.each(@chunk_size) { |chunk| parser << chunk } if @file_io end def make_event_generator(generator) case generator when :default require 'json/stream' JSON::Stream::Parser.new else generator end end end end end
Simplify set creation in Graph::Edge
class Graph class Edge attr_reader :name attr_reader :left attr_reader :right def initialize(name, left, right) @name = name.to_sym @left = left @right = right @nodes = Set.new([ @left, @right ]) end def connects?(node) @nodes.include?(node) end end end
class Graph class Edge attr_reader :name attr_reader :left attr_reader :right def initialize(name, left, right) @name = name.to_sym @left = left @right = right @nodes = Set[ left, right ] end def connects?(node) @nodes.include?(node) end end end
Fix references to invalid hash keys.
require 'geocoder/results/base' module Geocoder::Result class Ipgeolocation < Base def address(format = :full) s = region_code.empty? ? "" : ", #{region_code}" "#{city}#{s} #{zip}, #{country_name}".sub(/^[ ,]*/, "") end def state @data['region_name'] end def state_code @data['region_code'] end def country @data['country_name'] end def postal_code @data['zip'] || @data['zipcode'] || @data['zip_code'] end def self.response_attributes [ ['ip', ''], ['hostname', ''], ['continent_code', ''], ['continent_name', ''], ['country_code2', ''], ['country_code3', ''], ['country_name', ''], ['country_capital',''], ['district',''], ['state_prov',''], ['city', ''], ['zipcode', ''], ['latitude', 0], ['longitude', 0], ['time_zone', {}], ['currency', {}] ] end response_attributes.each do |attr, default| define_method attr do @data[attr] || default end end end end
require 'geocoder/results/base' module Geocoder::Result class Ipgeolocation < Base def address(format = :full) "#{city}, #{state} #{postal_code}, #{country_name}".sub(/^[ ,]*/, "") end def state @data['state_prov'] end def state_code @data['state_prov'] end def country @data['country_name'] end def postal_code @data['zipcode'] end def self.response_attributes [ ['ip', ''], ['hostname', ''], ['continent_code', ''], ['continent_name', ''], ['country_code2', ''], ['country_code3', ''], ['country_name', ''], ['country_capital',''], ['district',''], ['state_prov',''], ['city', ''], ['zipcode', ''], ['latitude', 0], ['longitude', 0], ['time_zone', {}], ['currency', {}] ] end response_attributes.each do |attr, default| define_method attr do @data[attr] || default end end end end
REFACTOR - GridColumn module refactors, add +remove_column+ method, add only and except option
module WulinMaster module GridColumns extend ActiveSupport::Concern included do class_eval do class_attribute :columns end end module ClassMethods # Private - executed when class is subclassed def initialize_columns if self.columns.nil? self.columns = [Column.new(:id, self, {:visible => false, :editable => false, :sortable => true})] end end # Add a column def column(name, options={}) self.columns += [Column.new(name, self, options)] end end # Instance Methods # Returns columns def columns self.class.columns end end end
module WulinMaster module GridColumns extend ActiveSupport::Concern included do class_eval do class << self attr_accessor :columns end end end module ClassMethods # Private - executed when class is subclassed def initialize_columns self.columns ||= [Column.new(:id, self, {:visible => false, :editable => false, :sortable => true})] end # Add a column def column(name, options={}) self.columns += [Column.new(name, self, options)] end # Remove columns for exactly screens def remove_columns(r_columns, scope={}) return unless scope[:screen].present? r_columns = r_columns.map(&:to_s) self.columns.each do |column| if r_columns.include? column.name.to_s column.options[:except] = scope[:screen] end end end end # Instance Methods # Returns columns def columns screen_name = params[:screen] columns_pool = self.class.columns.dup columns_pool.select do |column| valid_column?(column, screen_name) end end private def valid_column?(column, screen_name) screen_name = screen_name.to_s (column.options[:only].blank? and column.options[:except].blank?) || (column.options[:only].present? and column.options[:only].map(&:to_s).include?(screen_name)) || (column.options[:except].present? and column.options[:except].map(&:to_s).exclude?(screen_name)) end end end
Insert UrlRewrite middleware before Rack::Sendfile
require_relative "middleware/url_redirect" module Koi class Engine < ::Rails::Engine isolate_namespace Koi initializer "static assets" do |app| app.middleware.use ::ActionDispatch::Static, "#{root}/public" app.middleware.use Koi::UrlRedirect app.config.assets.precompile += %w( koi.js koi/nav_items.js koi/assets.js koi/application.css koi/ckeditor.js ) end end end
require_relative "middleware/url_redirect" module Koi class Engine < ::Rails::Engine isolate_namespace Koi initializer "static assets" do |app| app.middleware.use ::ActionDispatch::Static, "#{root}/public" app.middleware.insert_before Rack::Sendfile, Koi::UrlRedirect app.config.assets.precompile += %w( koi.js koi/nav_items.js koi/assets.js koi/application.css koi/ckeditor.js ) end end end
Add a dependency on Nokogiri
# -*- encoding: utf-8 -*- require File.dirname(__FILE__) + '/lib/mimemagic/version' require 'date' Gem::Specification.new do |s| s.name = 'mimemagic' s.version = MimeMagic::VERSION s.authors = ['Daniel Mendler'] s.date = Date.today.to_s s.email = ['mail@daniel-mendler.de'] s.files = `git ls-files`.split("\n").reject { |f| f.match(%r{^(test|script)/}) } s.require_paths = %w(lib) s.extensions = %w(ext/mimemagic/Rakefile) s.summary = 'Fast mime detection by extension or content' s.description = 'Fast mime detection by extension or content in pure ruby (Uses freedesktop.org.xml shared-mime-info database)' s.homepage = 'https://github.com/minad/mimemagic' s.license = 'MIT' s.add_development_dependency('minitest', '~> 5.14') s.add_development_dependency('rake', '~> 13.0') if s.respond_to?(:metadata) s.metadata['changelog_uri'] = "https://github.com/minad/mimemagic/blob/master/CHANGELOG.md" s.metadata['source_code_uri'] = "https://github.com/minad/mimemagic" s.metadata['bug_tracker_uri'] = "https://github.com/minad/mimemagic/issues" end end
# -*- encoding: utf-8 -*- require File.dirname(__FILE__) + '/lib/mimemagic/version' require 'date' Gem::Specification.new do |s| s.name = 'mimemagic' s.version = MimeMagic::VERSION s.authors = ['Daniel Mendler'] s.date = Date.today.to_s s.email = ['mail@daniel-mendler.de'] s.files = `git ls-files`.split("\n").reject { |f| f.match(%r{^(test|script)/}) } s.require_paths = %w(lib) s.extensions = %w(ext/mimemagic/Rakefile) s.summary = 'Fast mime detection by extension or content' s.description = 'Fast mime detection by extension or content in pure ruby (Uses freedesktop.org.xml shared-mime-info database)' s.homepage = 'https://github.com/minad/mimemagic' s.license = 'MIT' s.add_dependency('nokogiri', '~> 1.11.2') s.add_development_dependency('minitest', '~> 5.14') s.add_development_dependency('rake', '~> 13.0') if s.respond_to?(:metadata) s.metadata['changelog_uri'] = "https://github.com/minad/mimemagic/blob/master/CHANGELOG.md" s.metadata['source_code_uri'] = "https://github.com/minad/mimemagic" s.metadata['bug_tracker_uri'] = "https://github.com/minad/mimemagic/issues" end end
Update the tests so they are easier to read and understand.
$:.unshift(File.expand_path(File.join(File.dirname(__FILE__), '../lib'))) unless defined?(Gem) then require 'rubygems' end require 'minitest/autorun' require 'minitest/pride' require 'clippy' class TestClippy < MiniTest::Unit::TestCase def test1_version Clippy.version.split(/\./).delete_if do |val| val =~ /pre\d{0,2}/ end.length.must_equal(3) end def test2_copy test1 = Clippy.copy("Test1") test1.must_equal("Test1") Clippy.paste.must_equal("Test1") end def test3_paste test1 = Clippy.copy("Test2") test1.must_equal("Test2") Clippy.paste.must_equal("Test2") end def test4_clear Clippy.copy("Test2") Clippy.clear.must_equal(false) Clippy.paste.must_equal(false) end end
$:.unshift(File.expand_path(File.join(File.dirname(__FILE__), '../lib'))) unless defined?(Gem) then require 'rubygems' end require 'minitest/autorun' require 'minitest/pride' require 'minitest/spec' require 'clippy' describe Clippy do subject { Clippy } it "must have a proper version" do Clippy.version.split(".").delete_if { |val| val =~ /pre\d+/ }.length.must_equal(3) end describe ".copy" do it "must be able to copy" do subject.copy("example").must_equal("example") end end describe ".paste" do it "must be able to paste" do subject.copy("example") subject.paste.must_equal("example") end end describe ".clear" do it "should be able to clear the clipboard" do subject.copy("example") subject.clear.must_equal(true) end end end
Set the pagination to 30 per page
module PopulateAdmins def create_admins Admin.delete_all puts "Creating the root user tom.cat@example.com/password ..." Admin.create! email: "tom.cat@example.com", role: 5, password: "password", password_confirmation: "password" puts "Creating the admin user jerry.mouse@example.com/password ..." Admin.create! email: "jerry.mouse@example.com", role: 4, password: "password", password_confirmation: "password" end end
module PopulateAdmins def create_admins Admin.delete_all puts "Creating the root user tom.cat@example.com/password ..." Admin.create! email: "tom.cat@example.com", role: 5, password: "password", password_confirmation: "password" puts "Creating the admin user jerry.mouse@example.com/password ..." Admin.create! email: "jerry.mouse@example.com", role: 4, password: "password", password_confirmation: "password" end end
Update Telegram.app to 0.8.3 Updated sha256sum signature for tsetup.0.8.3.dmg
cask :v1 => 'telegram' do version '0.7.17' sha256 '8c724f209947f224b7fea4a88f56e8c54c593fd50b28455cebf6a3462f47d395' # tdesktop.com is the official download host per the vendor homepage url "https://updates.tdesktop.com/tmac/tsetup.#{version}.dmg" name 'Telegram' homepage 'https://telegram.org/' license :gpl app 'Telegram.app' end
cask :v1 => 'telegram' do version '0.8.3' sha256 'e1ece44ceba78952f113759ad425cf9ebddae357fd6ca6eebd559195fadbc704' # tdesktop.com is the official download host per the vendor homepage url "https://updates.tdesktop.com/tmac/tsetup.#{version}.dmg" name 'Telegram' homepage 'https://telegram.org/' license :gpl app 'Telegram.app' end
Update to allow knife show to display encoded values
require 'chef/knife/secure_bag_base' require 'chef/knife/data_bag_show' class Chef class Knife class SecureBagShow < Knife::DataBagShow include Knife::SecureBagBase banner "knife secure bag show BAG [ITEM] (options)" category "secure bag" def load_item(bag, item_name) item = SecureDataBag::Item.load( bag, item_name, key: read_secret, fields: encoded_fields ) item.encoded_fields(encoded_fields) data = item.to_hash(encoded:false) data = data_for_edit(data) data end def run display = case @name_args.length when 2 item = load_item(@name_args[0], @name_args[1]) display = format_for_display(item) when 1 format_list_for_display(Chef::DataBag.load(@name_args[0])) else stdout.puts opt_parser exit(1) end output(display) end end end end
require 'chef/knife/secure_bag_base' require 'chef/knife/data_bag_show' class Chef class Knife class SecureBagShow < Knife::DataBagShow include Knife::SecureBagBase banner "knife secure bag show BAG [ITEM] (options)" category "secure bag" option :encoded, long: "--encoded", boolean: true, description: "Whether we wish to display encoded values", default: false def load_item(bag, item_name) item = SecureDataBag::Item.load( bag, item_name, key: read_secret, fields: encoded_fields ) item.encoded_fields(encoded_fields) data = item.to_hash(encoded:config[:encoded]) data = data_for_edit(data) unless config[:encoded] data end def run display = case @name_args.length when 2 item = load_item(@name_args[0], @name_args[1]) display = format_for_display(item) when 1 format_list_for_display(Chef::DataBag.load(@name_args[0])) else stdout.puts opt_parser exit(1) end output(display) end end end end
Set resource for comments index, new, and create actions.
class CommentsController < ApplicationController def new @resource = Resource.find_by(id: params[:resource_id]) @comment = @resource.comments.build end def create @resource = Resource.find_by(id: params[:resource_id]) @comment = @resource.comments.build(comment_params) @comment.user = current_user if @resource.save redirect_to resource_path(@resource) else flash[:error] = @comment.errors.full_messages redirect_to resource_path(@resource) end end def destroy @comment = Comment.find_by(id: params[:id]) @resource = @comment.resource @comment.destroy if correct_user? redirect_to resource_path(@resource) end private def comment_params params.require(:comment).permit(:content) end end
class CommentsController < ApplicationController before_action :set_resource, only: [:index, :new, :create] def index end def new @comment = @resource.comments.build end def create @comment = @resource.comments.build(comment_params) @comment.user = current_user if @resource.save redirect_to resource_path(@resource) else flash[:error] = @comment.errors.full_messages redirect_to resource_path(@resource) end end def edit end def destroy @comment = Comment.find_by(id: params[:id]) @resource = @comment.resource @comment.destroy if correct_user? redirect_to resource_path(@resource) end private def set_resource @resource = Resource.find_by(id: params[:id]) end def comment_params params.require(:comment).permit(:content) end end
Make sure Event show is tested for requiring login
include AuthenticationHelper describe 'Events index' do let(:user) { FactoryGirl.create(:user) } before do confirm_and_sign_in user visit events_path end subject { page } it { is_expected.to have_content 'Upcoming events' } it { is_expected.to have_content 'No events found' } context 'with events' do before { 5.times { FactoryGirl.create(:event) } } it 'should show all events' do visit events_path expect(subject).to have_selector('.event', count: 5) end end end
include AuthenticationHelper describe 'Events index' do let(:user) { FactoryGirl.create(:user) } context 'signed in' do before do confirm_and_sign_in user visit events_path end subject { page } it { is_expected.to have_content 'Upcoming events' } it { is_expected.to have_content 'No events found' } context 'with events' do before { 5.times { FactoryGirl.create(:event) } } it 'should show all events' do visit events_path expect(subject).to have_selector('.event', count: 5) end end end context 'not signed in' do before { visit events_path } it 'should require login' do expect(current_path).to eql(new_user_session_path) end end end
Revert "Watch OS deployment target to meet RxSwift"
Pod::Spec.new do |s| s.name = "RxAlamofire" s.version = "5.0.0" s.license = "MIT" s.summary = "RxSwift wrapper around the elegant HTTP networking in Swift Alamofire" s.homepage = "https://github.com/RxSwiftCommunity/RxAlamofire" s.authors = { "RxSwift Community" => "community@rxswift.org" } s.source = { :git => "https://github.com/RxSwiftCommunity/RxAlamofire.git", :tag => s.version } s.swift_version = "5.0" s.ios.deployment_target = "8.0" s.osx.deployment_target = "10.10" s.tvos.deployment_target = "9.0" s.watchos.deployment_target = "3.0" s.requires_arc = true s.default_subspec = "Core" s.subspec "Core" do |ss| ss.source_files = "Sources/*.swift" ss.dependency "RxSwift", "~> 4.4" ss.dependency "Alamofire", "~> 4.8" ss.framework = "Foundation" end s.subspec "RxCocoa" do |ss| ss.source_files = "Sources/Cocoa/*.swift" ss.dependency "RxCocoa", "~> 4.4" ss.dependency "RxAlamofire/Core" end end
Pod::Spec.new do |s| s.name = "RxAlamofire" s.version = "5.0.0" s.license = "MIT" s.summary = "RxSwift wrapper around the elegant HTTP networking in Swift Alamofire" s.homepage = "https://github.com/RxSwiftCommunity/RxAlamofire" s.authors = { "RxSwift Community" => "community@rxswift.org" } s.source = { :git => "https://github.com/RxSwiftCommunity/RxAlamofire.git", :tag => s.version } s.swift_version = "5.0" s.ios.deployment_target = "8.0" s.osx.deployment_target = "10.10" s.tvos.deployment_target = "9.0" s.watchos.deployment_target = "2.0" s.requires_arc = true s.default_subspec = "Core" s.subspec "Core" do |ss| ss.source_files = "Sources/*.swift" ss.dependency "RxSwift", "~> 4.4" ss.dependency "Alamofire", "~> 4.8" ss.framework = "Foundation" end s.subspec "RxCocoa" do |ss| ss.source_files = "Sources/Cocoa/*.swift" ss.dependency "RxCocoa", "~> 4.4" ss.dependency "RxAlamofire/Core" end end
Change rspec version requirement to ~> 2.13
Gem::Specification.new do |s| s.name = 'haproxy_log_parser' s.version = IO.read('VERSION').chomp s.authors = ['Toby Hsieh'] s.homepage = 'https://github.com/tobyhs/haproxy_log_parser' s.summary = 'Parser for HAProxy logs in the HTTP log format' s.description = s.summary s.license = 'MIT' s.add_dependency 'treetop' s.add_development_dependency 'rspec' s.files = Dir.glob('lib/**/*') + [ 'README.rdoc', 'VERSION', 'haproxy_log_parser.gemspec' ] s.test_files = Dir.glob('spec/**/*') end
Gem::Specification.new do |s| s.name = 'haproxy_log_parser' s.version = IO.read('VERSION').chomp s.authors = ['Toby Hsieh'] s.homepage = 'https://github.com/tobyhs/haproxy_log_parser' s.summary = 'Parser for HAProxy logs in the HTTP log format' s.description = s.summary s.license = 'MIT' s.add_dependency 'treetop' s.add_development_dependency 'rspec', '~> 2.13' s.files = Dir.glob('lib/**/*') + [ 'README.rdoc', 'VERSION', 'haproxy_log_parser.gemspec' ] s.test_files = Dir.glob('spec/**/*') end
Fix bug requesting data for workflow with unassigned batch host
json.extract! @workflow, :name, :batch_host, :script_path, :staged_script_name, :staged_dir, :created_at, :updated_at, :status, :account json.set! 'status_label', status_label(@workflow) json.set! 'active', @workflow.active? json.set! 'fs_root', Filesystem.new.fs(@workflow.staged_dir) json.set! 'host_title', cluster_title(@workflow.batch_host) json.folder_contents (@workflow.folder_contents) do |content| json.set! 'path', content json.set! 'name', Pathname(content).basename.to_s json.set! 'type', Pathname(content).file? ? 'file' : 'dir' json.set! 'fsurl', Filesystem.new.fs(content) json.set! 'fs_base', Filesystem.new.fs(File.dirname(content)) hostname = OODClusters[@workflow.batch_host].login.host if OODClusters[@workflow.batch_host] && OODClusters[@workflow.batch_host].login_allow? json.set! 'terminal_base', OodAppkit.shell.url(path: File.dirname(content), host: hostname).to_s json.set! 'apiurl', Filesystem.new.api(content) json.set! 'editor_url', Filesystem.new.editor(content) end
json.extract! @workflow, :name, :batch_host, :script_path, :staged_script_name, :staged_dir, :created_at, :updated_at, :status, :account json.set! 'status_label', status_label(@workflow) json.set! 'active', @workflow.active? json.set! 'fs_root', Filesystem.new.fs(@workflow.staged_dir) json.set! 'host_title', cluster_title(@workflow.batch_host) json.folder_contents (@workflow.folder_contents) do |content| json.set! 'path', content json.set! 'name', Pathname(content).basename.to_s json.set! 'type', Pathname(content).file? ? 'file' : 'dir' json.set! 'fsurl', Filesystem.new.fs(content) json.set! 'fs_base', Filesystem.new.fs(File.dirname(content)) if @workflow.batch_host hostname = OODClusters[@workflow.batch_host].login.host if OODClusters[@workflow.batch_host] && OODClusters[@workflow.batch_host].login_allow? end json.set! 'terminal_base', OodAppkit.shell.url(path: File.dirname(content), host: hostname).to_s json.set! 'apiurl', Filesystem.new.api(content) json.set! 'editor_url', Filesystem.new.editor(content) end
Fix privacy spec to test described object
require 'rails_helper' shared_examples_for 'content with privacy' do context 'model is public' do let(:model) { build(:character, name: 'Ellen', privacy: 'public')} describe '.public_content?' do subject { model.public_content? } it { is_expected.to be true } end end end RSpec.describe Character, type: :model do it_behaves_like 'content with privacy' end
require 'rails_helper' shared_examples_for 'content with privacy' do context 'model is public' do let(:model) { build( described_class.model_name.param_key.to_sym, name: 'Public model', privacy: 'public' ) } describe '.public_content?' do subject { model.public_content? } it { is_expected.to be true } end end end RSpec.describe Character, type: :model do it_behaves_like 'content with privacy' end
Use StandardError as the base class for Socketry::Error
# frozen_string_literal: true module Socketry # Generic catch all for all Socketry errors Error = Class.new(::IOError) # Invalid address AddressError = Class.new(Socketry::Error) # Timeouts performing an I/O operation TimeoutError = Class.new(Socketry::Error) # Cannot perform operation in current state StateError = Class.new(Socketry::Error) # Internal consistency error within the library InternalError = Class.new(Socketry::Error) module Resolver # DNS resolution errors Error = Class.new(Socketry::AddressError) end module SSL # Errors related to SSL Error = Class.new(Socketry::Error) # Hostname verification error HostnameError = Class.new(Socketry::SSL::Error) end end
# frozen_string_literal: true module Socketry # Generic catch all for all Socketry errors Error = Class.new(StandardError) # Invalid address AddressError = Class.new(Socketry::Error) # Timeouts performing an I/O operation TimeoutError = Class.new(Socketry::Error) # Cannot perform operation in current state StateError = Class.new(Socketry::Error) # Internal consistency error within the library InternalError = Class.new(Socketry::Error) module Resolver # DNS resolution errors Error = Class.new(Socketry::AddressError) end module SSL # Errors related to SSL Error = Class.new(Socketry::Error) # Hostname verification error HostnameError = Class.new(Socketry::SSL::Error) end end
Rename parameter ast to form
require "lasp/parser" require "lasp/env" module Lasp module_function def eval(ast, env) case ast when Symbol then env.fetch(ast) when Array then eval_form(ast, env) else ast end end def eval_form(form, env) head, *tail = *form case head when :def key, value = tail env[key] = Lasp::eval(value, env) when :fn params, func = tail -> (*args) { Lasp::eval(func, env.merge(Hash[params.zip(args)])) } when :do tail.map { |form| Lasp::eval(form, env) }.last when :if conditional, true_form, false_form = tail Lasp::eval(conditional, env) ? Lasp::eval(true_form, env) : Lasp::eval(false_form, env) when Proc head.(*tail) else fn = Lasp::eval(head, env) fn.(*tail.map { |form| Lasp::eval(form, env) }) end end end
require "lasp/parser" require "lasp/env" module Lasp module_function def eval(form, env) case form when Symbol then env.fetch(form) when Array then eval_form(form, env) else form end end def eval_form(form, env) head, *tail = *form case head when :def key, value = tail env[key] = Lasp::eval(value, env) when :fn params, func = tail -> (*args) { Lasp::eval(func, env.merge(Hash[params.zip(args)])) } when :do tail.map { |form| Lasp::eval(form, env) }.last when :if conditional, true_form, false_form = tail Lasp::eval(conditional, env) ? Lasp::eval(true_form, env) : Lasp::eval(false_form, env) when Proc head.(*tail) else fn = Lasp::eval(head, env) fn.(*tail.map { |form| Lasp::eval(form, env) }) end end end
Fix keyword search on infrastructure components.
class KeywordSearchIndex < ActiveRecord::Base belongs_to :organization #validates :organization, :presence => true validates :object_key, :presence => true validates :object_class, :presence => true validates :search_text, :presence => true def to_s name end # Return the Rails path to this object def name if InfrastructureComponent.find_by(object_key: object_key) "inventory_path(:id => '#{InfrastructureComponent.find_by(object_key: object_key).parent.object_key}')" elsif object_class == Rails.application.config.asset_base_class_name "inventory_path(:id => '#{object_key}')" else "#{object_class.underscore}_path(:id => '#{object_key}')" end end end
Fix rubocop warnings in CloudResourceQuotaHelper
module CloudResourceQuotaHelper # lookup a cloud_resource_quota by name for the tenant and service def lookup_quota(cloud_tenant_id, service_name, quota_name) return unless cloud_tenant_id && service_name && quota_name service_name = service_name.to_s quota_name = quota_name.to_s CloudResourceQuota.where( :cloud_tenant_id => cloud_tenant_id, :service_name => service_name, :name => quota_name).first end end
module CloudResourceQuotaHelper # lookup a cloud_resource_quota by name for the tenant and service def lookup_quota(cloud_tenant_id, service_name, quota_name) return unless cloud_tenant_id && service_name && quota_name service_name = service_name.to_s quota_name = quota_name.to_s CloudResourceQuota.where( :cloud_tenant_id => cloud_tenant_id, :service_name => service_name, :name => quota_name ).first end end
Decrease public object population number
module SocialStream module Population class ActivityObject def initialize(klass, &block) puts "#{ klass.name } population" start_time = Time.now 50.times do author = Actor.all[rand(Actor.all.size)] owner = author relation_ids = [Relation::Public.instance.id] populate klass, author, owner, relation_ids, &block end if SocialStream.relation_model == :custom PowerLaw.new(Tie.allowing('create', 'activity').all) do |t| author = t.receiver owner = t.sender relation_ids = Array(t.relation_id) populate klass, author, owner, relation_ids, &block end end end_time = Time.now puts ' -> ' + (end_time - start_time).round(4).to_s + 's' end def populate klass, author, owner, relation_ids, &block user_author = ( author.subject_type == "User" ? author : author.user_author ) timestamps = Timestamps.new o = klass.new o.created_at = timestamps.created o.updated_at = timestamps.updated o.author_id = author.id o.owner_id = owner.id o.user_author_id = user_author.id o.relation_ids = relation_ids yield o o.save! o.post_activity.update_attributes(:created_at => o.created_at, :updated_at => o.updated_at) o end end end end
module SocialStream module Population class ActivityObject def initialize(klass, &block) puts "#{ klass.name } population" start_time = Time.now 10.times do author = Actor.all[rand(Actor.all.size)] owner = author relation_ids = [Relation::Public.instance.id] populate klass, author, owner, relation_ids, &block end if SocialStream.relation_model == :custom PowerLaw.new(Tie.allowing('create', 'activity').all) do |t| author = t.receiver owner = t.sender relation_ids = Array(t.relation_id) populate klass, author, owner, relation_ids, &block end end end_time = Time.now puts ' -> ' + (end_time - start_time).round(4).to_s + 's' end def populate klass, author, owner, relation_ids, &block user_author = ( author.subject_type == "User" ? author : author.user_author ) timestamps = Timestamps.new o = klass.new o.created_at = timestamps.created o.updated_at = timestamps.updated o.author_id = author.id o.owner_id = owner.id o.user_author_id = user_author.id o.relation_ids = relation_ids yield o o.save! o.post_activity.update_attributes(:created_at => o.created_at, :updated_at => o.updated_at) o end end end end
Fix spec completeness user concern spec
require 'spec_helper' describe User::Completeness do subject { User::Completeness::Calculator.new(user).progress } context 'when the profile type is personal' do let(:user) { create(:user, name: 'Some name', bio: nil, address: '', uploaded_image: nil, authorizations: [], profile_type: 'personal') } it 'completeness progress should be 20' do expect(subject).to eq 20 end end context 'when the profile type is organization' do let(:user) { create(:user, bio: 'Some Bio', address: '', authorizations: [], organization: create(:organization, name: 'Some Org', image: nil), profile_type: 'organization') } it 'completeness progress should be 40' do expect(subject).to eq 40 end end context 'when the profile type is channel' do let(:user) { create(:channel, name: 'Some Channel', description: 'Some other text here', user: create(:user, other_url: nil, address: 'Kansas City, MO', profile_type: 'channel')).user } it 'completeness progress should be 42' do expect(subject).to eq 42 end end describe '#update_completeness_progress' do let(:user) { create(:user, name: 'Some name', profile_type: 'personal') } before { user.update_completeness_progress! } it { expect(user.reload.completeness_progress).to_not eq 0 } end end
require 'spec_helper' describe User::Completeness do subject { User::Completeness::Calculator.new(user).progress } context 'when the profile type is personal' do let(:user) { create(:user, name: 'Some name', bio: nil, address: '', uploaded_image: nil, authorizations: [], profile_type: 'personal') } it 'completeness progress should be 20' do expect(subject).to eq 20 end end context 'when the profile type is organization' do let(:user) { create(:user, bio: 'Some Bio', address: '', authorizations: [], organization: create(:organization, name: 'Some Org', image: nil), profile_type: 'organization') } it 'completeness progress should be 40' do expect(subject).to eq 40 end end context 'when the profile type is channel' do let(:user) { create(:channel, name: 'Some Channel', description: 'Some other text here', user: create(:user, name: nil, other_url: nil, address: 'Kansas City, MO', profile_type: 'channel')).user.reload } it 'completeness progress should be 42' do expect(subject).to eq 42 end end describe '#update_completeness_progress' do let(:user) { create(:user, name: 'Some name', profile_type: 'personal') } before { user.update_completeness_progress! } it { expect(user.reload.completeness_progress).to_not eq 0 } end end
Add spec for configuration redirect_root_path method
describe Adminable::Configuration do describe '#resources' do it 'return array of resources' do resources = Adminable::Configuration.resources expect(resources).to all(be_a(Adminable::Resource)) expect(resources.map(&:name)).to eq(%w(blog/comments blog/posts users)) end end end
describe Adminable::Configuration do describe '#resources' do it 'return array of resources' do resources = Adminable::Configuration.resources expect(resources).to all(be_a(Adminable::Resource)) expect(resources.map(&:name)).to eq(%w(blog/comments blog/posts users)) end end describe '#redirect_root_path' do describe 'if resources exists' do it 'returns first resource url' do expect(Adminable::Configuration.redirect_root_path).to eq( 'blog/comments' ) end end describe 'if no resources exists' do it 'returns main app root path' do allow(Adminable::Configuration).to receive(:resources).and_return([]) expect(Adminable::Configuration.redirect_root_path).to eq('/') end end end end
Update gemspec to include credit for @ayaman
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "realtime/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "realtime" s.version = Realtime::VERSION s.authors = ["Mike Atlas"] s.email = ["mike.atlas@gmail.com"] s.homepage = "http://mikeatlas.github.io/realtime-rails/" s.summary = "Realtime support for Rails applications." s.description = "Provides a simple Realtime framework for Rails applications." s.license = "MIT" s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", ">= 4.0" #s.add_dependency "redis" #s.add_dependency "zmq" #s.add_dependency "em-zmq" end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "realtime/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "realtime" s.version = Realtime::VERSION s.authors = ["Mike Atlas", "Ahmad Abdel-Yaman (@ayaman)"] s.email = ["mike.atlas@gmail.com"] s.homepage = "http://mikeatlas.github.io/realtime-rails/" s.summary = "Realtime support for Rails applications." s.description = "Provides a simple Realtime framework for Rails applications." s.license = "MIT" s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", ">= 4.0" #s.add_dependency "redis" #s.add_dependency "zmq" #s.add_dependency "em-zmq" end
Add Slovenian language to refinery_i18n_locale
[ {:name => "site_name", :value => "Company Name"}, {:name => "new_page_parts", :value => false}, {:name => "activity_show_limit", :value => 18}, {:name => "preferred_image_view", :value => :grid}, {:name => "analytics_page_code", :value => "UA-xxxxxx-x"}, {:name => "theme", :value => "demolicious"}, {:name => "image_thumbnails", :value => { :dialog_thumb => 'c106x106', :grid => 'c135x135', :thumb => '50x50>', :medium => '225x255>', :side_body => '300x500>', :preview => 'c96x96' } }, {:name => 'refinery_i18n_locales', :value => { :en => 'English', :fr => 'Français', :nl => 'Nederlands', :'pt-BR' => 'Português', :da => 'Dansk', :nb => 'Norsk Bokmål' } } ].each do |setting| RefinerySetting.create(:name => setting[:name].to_s, :value => setting[:value], :destroyable => false) end
[ {:name => "site_name", :value => "Company Name"}, {:name => "new_page_parts", :value => false}, {:name => "activity_show_limit", :value => 18}, {:name => "preferred_image_view", :value => :grid}, {:name => "analytics_page_code", :value => "UA-xxxxxx-x"}, {:name => "theme", :value => "demolicious"}, {:name => "image_thumbnails", :value => { :dialog_thumb => 'c106x106', :grid => 'c135x135', :thumb => '50x50>', :medium => '225x255>', :side_body => '300x500>', :preview => 'c96x96' } }, {:name => 'refinery_i18n_locales', :value => { :en => 'English', :fr => 'Français', :nl => 'Nederlands', :'pt-BR' => 'Português', :da => 'Dansk', :nb => 'Norsk Bokmål', :sl => 'Slovenian' } } ].each do |setting| RefinerySetting.create(:name => setting[:name].to_s, :value => setting[:value], :destroyable => false) end
Optimize a db query on the game index page
class GamesController < ApplicationController def index @games = Game.page(params[:page]).decorate end def show @game = Game.find(params[:id]).decorate end end
class GamesController < ApplicationController def index @games = Game.includes(:pictures).page(params[:page]).decorate end def show @game = Game.find(params[:id]).decorate end end
Make save page a protected method like comfy code
class PagesController < Comfy::Admin::Cms::PagesController before_action :build_file, only: [:new, :edit] before_action :set_categories, only: [:new, :edit] before_action :set_pages, only: :index before_action :set_activity_log, only: [:new, :edit] def save_page PageRegister.new(@page, params: params, current_user: current_user).save end protected def set_activity_log @activity_logs = ActivityLogPresenter.collect(ActivityLog.fetch(from: @page)) end def set_pages @all_pages = Comfy::Cms::Page.includes(:layout, :site) end def apply_filters @pages = @all_pages.filter(params.slice(:category, :layout, :last_edit, :status, :language)) if params[:search].present? Comfy::Cms::Search.new(@pages, params[:search]).results else @last_published_pages = @all_pages.status(:published).reorder(updated_at: :desc).limit(4) @pages.reorder(updated_at: :desc).page(params[:page]) end end def build_file @file = Comfy::Cms::File.new end def set_categories @categories = Comfy::Cms::CategoriesListPresenter.new(@site.categories.of_type('Comfy::Cms::Page')) end end
class PagesController < Comfy::Admin::Cms::PagesController before_action :build_file, only: [:new, :edit] before_action :set_categories, only: [:new, :edit] before_action :set_pages, only: :index before_action :set_activity_log, only: [:new, :edit] protected def save_page PageRegister.new(@page, params: params, current_user: current_user).save end def set_activity_log @activity_logs = ActivityLogPresenter.collect(ActivityLog.fetch(from: @page)) end def set_pages @all_pages = Comfy::Cms::Page.includes(:layout, :site) end def apply_filters @pages = @all_pages.filter(params.slice(:category, :layout, :last_edit, :status, :language)) if params[:search].present? Comfy::Cms::Search.new(@pages, params[:search]).results else @last_published_pages = @all_pages.status(:published).reorder(updated_at: :desc).limit(4) @pages.reorder(updated_at: :desc).page(params[:page]) end end def build_file @file = Comfy::Cms::File.new end def set_categories @categories = Comfy::Cms::CategoriesListPresenter.new(@site.categories.of_type('Comfy::Cms::Page')) end end
Refactor user controller.. now its lookin reaaaalll nice
class UsersController < ApplicationController def index render json: User.to_json_with_favorites end def show user = User.find_by_id(params['id']) if user render json: user.to_json(include: :favorite_parks) else send_status(:not_found) end end def create user = new_user if user.save render json: user else send_status(:bad_request) end end def destroy if User.find_and_destroy(params['id']) send_status(:no_content) else send_status(:bad_request) end end private def user_params JSON.parse(params['user']) end def new_user User.new( name: user_params['name'], email: user_params['email']) end end
class UsersController < ApplicationController def index render json: User.to_json_with_favorites end def show user = User.find(params['id']) render json: user.to_json( include: :favorite_parks) end def create user = User.new(user_params) if user.save render json: user else send_status(:unprocessable_entity) end end def destroy User.destroy(params['id']) send_status(:no_content) end private def user_params { name: JSON.parse(params['user'])['name'], email: JSON.parse(params['user'])['email'] } end end
Change adjust redirect back from Paypal and change cmd from _xclick to _s-xclick
class Order < ActiveRecord::Base has_many :paypal_notifications belongs_to :selected, class_name: "Lead" belongs_to :selector, class_name: "User" validates :selected_id, presence: true validates :selector_id, presence: true def paypal_url(return_url, notify_url) values = { :business => 'nina.breznik@sosed.si', :cmd => '_xclick', :upload => 1, :return => return_url, :invoice => id, :notify_url => notify_url, :currency_code => 'EUR' } values.merge!({ "amount" => 10, "item_name" => 'Kontakt', "item_number" => 1 "quantity" => 1 }) "https://www.paypal.com/cgi-bin/webscr?" + values.to_query end # def paypal_payment_notification #IPN - instant payment notification (by PayPal) # if status == "Completed" # self.update_attributes(:paid => true) # end # end end
class Order < ActiveRecord::Base has_many :paypal_notifications belongs_to :selected, class_name: "Lead" belongs_to :selector, class_name: "User" validates :selected_id, presence: true validates :selector_id, presence: true def paypal_url(return_url, notify_url) values = { :business => 'nina.breznik@sosed.si', :cmd => '_xclick', :upload => 1, :return => return_url, :invoice => id, :notify_url => notify_url, :currency_code => 'EUR' } values.merge!({ "amount" => 10, "item_name" => 'Kontakt', "item_number" => 1, "quantity" => 1 }) "https://www.paypal.com/cgi-bin/webscr?" + values.to_query end # def paypal_payment_notification #IPN - instant payment notification (by PayPal) # if status == "Completed" # self.update_attributes(:paid => true) # end # end end
Use simpler server-side timed-out test.
# frozen_string_literal: true require_relative '../test_base' class RunTimedOutTest < TestBase def self.id58_prefix 'c7A' end # - - - - - - - - - - - - - - - - - - - - - c_assert_test 'g55', %w( timeout ) do stdout_tgz = TGZ.of({'stderr' => 'any'}) set_context( logger:StdoutLoggerSpy.new, piper:PiperStub.new(stdout_tgz), process:process=ProcessSpawnerStub.new ) puller.add(image_name) process.spawn { 42 } process.detach { ThreadTimedOutStub.new } process.kill { nil } run_cyber_dojo_sh(max_seconds:3) assert timed_out?, run_result assert_equal Runner::STATUS[:timed_out], status.to_i assert_equal '', stdout assert_equal '', stderr end private class ThreadTimedOutStub def initialize @n = 0 @stubs = { 1 => lambda { raise Timeout::Error }, 2 => lambda { 137 } } end def value @n += 1 @stubs[@n].call end def join(_seconds) nil end end end
# frozen_string_literal: true require_relative '../test_base' class RunTimedOutTest < TestBase def self.id58_prefix 'c7A' end # - - - - - - - - - - - - - - - - - - - - - test 'g55', %w( timeout ) do stdout_tgz = TGZ.of({'stderr' => 'any'}) set_context( logger:StdoutLoggerSpy.new, piper:PiperStub.new(stdout_tgz), process:process=ProcessSpawnerStub.new ) puller.add(image_name) process.spawn { 42 } process.detach { ThreadTimedOutStub.new } process.kill { nil } run_cyber_dojo_sh(max_seconds:3) assert timed_out?, run_result assert_equal Runner::STATUS[:timed_out], status.to_i assert_equal '', stdout assert_equal '', stderr end private class ThreadTimedOutStub def initialize @n = 0 @stubs = { 1 => lambda { raise Timeout::Error }, 2 => lambda { 137 } } end def value @n += 1 @stubs[@n].call end def join(_seconds) nil end end end
Add calculated fields to User model
class User < ActiveRecord::Base has_many :timeslots, foreign_key: 'tutor_id' has_many :bookings, class_name: 'Timeslot', foreign_key: 'student_id' has_many :shares has_many :user_roles has_many :roles, through: :user_roles validates_presence_of :name validates_inclusion_of :email_notify, in: [true, false], message: "can't be blank" validates_inclusion_of :text_notify, in: [true, false], message: "can't be blank" validates_presence_of :cellphone, message: "must be present for text notifications", if: 'text_notify' def cellphone=(cellphone_number) write_attribute(:cellphone, cellphone_number.gsub(/\D/, '')) unless cellphone_number.nil? end def track_event(event_name, options={}) attributes = {:event_name => event_name, :email => self.email, :user_id => self.id} attributes[:created_at] = options[:created_at] || Time.now.to_i attributes[:metadata] = options[:metadata] unless options[:metadata].nil? Event.create(attributes) end def is_mentor? self.roles.include?(Role.find_by(name: "mentor")) end end
class User < ActiveRecord::Base has_many :timeslots, foreign_key: 'tutor_id' has_many :bookings, class_name: 'Timeslot', foreign_key: 'student_id' has_many :shares has_many :user_roles has_many :roles, through: :user_roles validates_presence_of :name validates_inclusion_of :email_notify, in: [true, false], message: "can't be blank" validates_inclusion_of :text_notify, in: [true, false], message: "can't be blank" validates_presence_of :cellphone, message: "must be present for text notifications", if: 'text_notify' def self.leaderboard # Returns an array of Users, *not* an ActiveRecord::Relation self.where(id: Timeslot.recent.booked.group(:tutor_id).pluck(:tutor_id)) .sort_by(&:recent_count)[-10..-1].reverse end def completed_count self.timeslots.booked.count end def recent_count self.timeslots.recent.booked.count end def cellphone=(cellphone_number) write_attribute(:cellphone, cellphone_number.gsub(/\D/, '')) unless cellphone_number.nil? end def track_event(event_name, options={}) attributes = {:event_name => event_name, :email => self.email, :user_id => self.id} attributes[:created_at] = options[:created_at] || Time.now.to_i attributes[:metadata] = options[:metadata] unless options[:metadata].nil? Event.create(attributes) end def is_mentor? self.roles.include?(Role.find_by(name: "mentor")) end end
Change podspec version to 0.0.14
Pod::Spec.new do |s| s.name = "CoreData-Views-Collection-ios" s.version = "0.0.13" s.summary = "Collection of Core Data based Cocoa Touch views base classes" s.description = <<-DESC Cocoa Touch view controller classes based/inspired by Stanford CS193p examples Base classes for view controllers driven by data from Core Data. DESC s.homepage = "https://github.com/michal-olszewski/coredata-views-collection-ios" s.license = 'MIT' s.author = { "Michal Olszewski" => "michal@olszewski.co" } s.social_media_url = "http://twitter.com/MichalOlszewski" s.platform = :ios, "6.0" s.requires_arc = true s.source = { :git => "https://github.com/michal-olszewski/coredata-views-collection-ios.git", :tag => "#{s.version}" } s.source_files = "CoreData-Views-Collection-ios/Classes", "CoreData-Views-Collection-ios/Classes/**/*.{h,m}" s.exclude_files = "CoreData-Views-Collection-ios/Classes/Exclude" s.framework = "CoreData", "UIKit", "Foundation" s.dependency 'CocoaLumberjack' end
Pod::Spec.new do |s| s.name = "CoreData-Views-Collection-ios" s.version = "0.0.14" s.summary = "Collection of Core Data based Cocoa Touch views base classes" s.description = <<-DESC Cocoa Touch view controller classes based/inspired by Stanford CS193p examples Base classes for view controllers driven by data from Core Data. DESC s.homepage = "https://github.com/michal-olszewski/coredata-views-collection-ios" s.license = 'MIT' s.author = { "Michal Olszewski" => "michal@olszewski.co" } s.social_media_url = "http://twitter.com/MichalOlszewski" s.platform = :ios, "6.0" s.requires_arc = true s.source = { :git => "https://github.com/michal-olszewski/coredata-views-collection-ios.git", :tag => "#{s.version}" } s.source_files = "CoreData-Views-Collection-ios/Classes", "CoreData-Views-Collection-ios/Classes/**/*.{h,m}" s.exclude_files = "CoreData-Views-Collection-ios/Classes/Exclude" s.framework = "CoreData", "UIKit", "Foundation" s.dependency 'CocoaLumberjack' end
Reduce posts in front page from 6 to 4
class WelcomeController < ApplicationController etag { can? :manage, Entity } # Don't cache admin content together with the rest def index # Highlight manually curated articles in the frontpage @highlights = Post.where(featured: true).includes(:photo).order("updated_at desc") @highlights = @highlights.published() unless can? :manage, Post # Show the latests posts... @posts = (can? :manage, Post) ? Post.all : Post.published @posts = @posts.where(featured: false).includes(:photo).order("updated_at DESC").limit(6) # ...and photos @photos = (can? :manage, Photo) ? Photo.all : Photo.published @photos = @photos.order("updated_at DESC").limit(6) fresh_when last_modified: [@highlights.maximum(:updated_at), @posts.maximum(:updated_at), @photos.maximum(:updated_at)].max, public: current_user.nil? end end
class WelcomeController < ApplicationController etag { can? :manage, Entity } # Don't cache admin content together with the rest def index # Highlight manually curated articles in the frontpage @highlights = Post.where(featured: true).includes(:photo).order("updated_at desc") @highlights = @highlights.published() unless can? :manage, Post # Show the latests posts... @posts = (can? :manage, Post) ? Post.all : Post.published @posts = @posts.where(featured: false).includes(:photo).order("updated_at DESC").limit(4) # ...and photos @photos = (can? :manage, Photo) ? Photo.all : Photo.published @photos = @photos.order("updated_at DESC").limit(6) fresh_when last_modified: [@highlights.maximum(:updated_at), @posts.maximum(:updated_at), @photos.maximum(:updated_at)].max, public: current_user.nil? end end
Rebuild initialize in Container class
class GreekString class Container require 'forwardable' extend Forwardable def_delegators :@container, :[], :<<, :each, :map, :flat_map def initialize @container = [] end def to_a @container end def to_s(type) @container.flat_map(&type) end end end
class GreekString class Container require 'forwardable' extend Forwardable def_delegators :@container, :[], :<<, :each, :map, :flat_map def initialize(letters=nil) @container = letters || [] end def to_a @container end def method_missing(meth, *args) @container.map! { |l| l if l.send(meth) }.flatten! @container.delete_if { |el| !el == true } self.class.new(@container) end end end
Make down for migration 082 complete.
class AddUsersOptions < ActiveRecord::Migration class User < ActiveRecord::Base end def self.up add_column :users, :firstname, :string add_column :users, :lastname, :string add_column :users, :nickname, :string add_column :users, :url, :string add_column :users, :msn, :string add_column :users, :aim, :string add_column :users, :yahoo, :string add_column :users, :twitter, :string add_column :users, :description, :text remove_column :users, :notify_via_jabber unless $schema_generator users = User.find(:all) users.each do |user| user.nickname = user.name user.save! end end end def self.down remove_column :users, :firstname remove_column :users, :lastname remove_column :users, :nickname remove_column :users, :url remove_column :users, :msn remove_column :users, :aim remove_column :users, :jabber remove_column :users, :yahoo remove_column :users, :description add_column :users, :notify_via_jabber, :tinyint end end
class AddUsersOptions < ActiveRecord::Migration class User < ActiveRecord::Base end def self.up add_column :users, :firstname, :string add_column :users, :lastname, :string add_column :users, :nickname, :string add_column :users, :url, :string add_column :users, :msn, :string add_column :users, :aim, :string add_column :users, :yahoo, :string add_column :users, :twitter, :string add_column :users, :description, :text remove_column :users, :notify_via_jabber unless $schema_generator users = User.find(:all) users.each do |user| user.nickname = user.name user.save! end end end def self.down remove_column :users, :firstname remove_column :users, :lastname remove_column :users, :nickname remove_column :users, :url remove_column :users, :msn remove_column :users, :aim remove_column :users, :jabber remove_column :users, :twitter remove_column :users, :yahoo remove_column :users, :description add_column :users, :notify_via_jabber, :tinyint end end
Remove fog dependency since we're not using it now
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'stemcell/version' Gem::Specification.new do |gem| gem.name = "stemcell" gem.version = Stemcell::VERSION gem.authors = ["Martin Rhoads"] gem.email = ["martin.rhoads@airbnb.com"] gem.description = %q{stemcell launches instances} gem.summary = %q{no summary} gem.homepage = "" 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.require_paths = ["lib"] gem.add_runtime_dependency 'trollop', '~> 2.0' gem.add_runtime_dependency 'aws-sdk', '~> 1.9' gem.add_runtime_dependency 'fog', '~> 1.10' end
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'stemcell/version' Gem::Specification.new do |gem| gem.name = "stemcell" gem.version = Stemcell::VERSION gem.authors = ["Martin Rhoads"] gem.email = ["martin.rhoads@airbnb.com"] gem.description = %q{stemcell launches instances} gem.summary = %q{no summary} gem.homepage = "" 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.require_paths = ["lib"] gem.add_runtime_dependency 'trollop', '~> 2.0' gem.add_runtime_dependency 'aws-sdk', '~> 1.9' end
Allow to use symbolic CS name in constructor of Fhir::Coding.
# A reference to a code defined by a terminology system. class Fhir::Coding < Fhir::DataType # Identity of the terminology system attribute :system, Fhir::URI # Symbol in syntax defined by the system attribute :code, Fhir::Code # Representation defined by the system attribute :display, String def initialize(raw_attrs) attrs = raw_attrs.dup if attrs[:system].respond_to?(:uri) attrs[:system] = attrs[:system].uri end super(attrs) end def system_oid self.system.sub(/^urn\:oid\:/, '') end def get_system Fhir::CodeSystem.find_by_uri(self.system) end def to_concept Fhir::CodeableConcept.new( text: self.display, codings: [self] ) end end
# A reference to a code defined by a terminology system. class Fhir::Coding < Fhir::DataType # Identity of the terminology system attribute :system, Fhir::URI # Symbol in syntax defined by the system attribute :code, Fhir::Code # Representation defined by the system attribute :display, String def initialize(raw_attrs) attrs = raw_attrs.dup system = attrs[:system] attrs[:system] = if system.respond_to?(:uri) system.uri elsif system.is_a?(Symbol) Fhir::CodeSystem[system].uri else system end super(attrs) end def system_oid self.system.sub(/^urn\:oid\:/, '') end def get_system Fhir::CodeSystem.find_by_uri(self.system) end def to_concept Fhir::CodeableConcept.new( text: self.display, codings: [self] ) end end
Change use of 'node' configuration to avoid Chef warning
raise "DiffMerge for Mac only" unless node["platform"] == "mac_os_x" dmg_package "DiffMerge" do volumes_dir "DiffMerge 3.3.2.1139" source "http://download-us.sourcegear.com/DiffMerge/3.3.2/DiffMerge.3.3.2.1139.dmg" action :install end # Link the sample file from the diffmerge application directory # for use as the diffmerge command-line script link "/usr/local/bin/diffmerge" do to "/Applications/DiffMerge.app/Contents/Resources/diffmerge.sh" end # Configure git unless otherwise requested node["diffmerge"] ||= {} node["diffmerge"]["configure-git"] ||= 1 if node["diffmerge"]["configure-git"] != 0 [ %q[git config --global diff.tool diffmerge], %q[git config --global difftool.diffmerge.cmd 'diffmerge "$LOCAL" "$REMOTE"'], %q[git config --global difftool.prompt false], %q[git config --global merge.tool diffmerge], %q[git config --global mergetool.diffmerge.cmd 'diffmerge --merge --result="$MERGED" "$LOCAL" "$(if test -f "$BASE"; then echo "$BASE"; else echo "$LOCAL"; fi)" "$REMOTE"'], %q[git config --global mergetool.diffmerge.trustExitCode true], ].each do |cmd| execute cmd do command cmd end end end
raise "DiffMerge for Mac only" unless node["platform"] == "mac_os_x" dmg_package "DiffMerge" do volumes_dir "DiffMerge 3.3.2.1139" source "http://download-us.sourcegear.com/DiffMerge/3.3.2/DiffMerge.3.3.2.1139.dmg" action :install end # Link the sample file from the diffmerge application directory # for use as the diffmerge command-line script link "/usr/local/bin/diffmerge" do to "/Applications/DiffMerge.app/Contents/Resources/diffmerge.sh" end # Configure git unless otherwise requested diffmerge = node["diffmerge"] || {} if (diffmerge["configure-git"] || 1) != 0 [ %q[git config --global diff.tool diffmerge], %q[git config --global difftool.diffmerge.cmd 'diffmerge "$LOCAL" "$REMOTE"'], %q[git config --global difftool.prompt false], %q[git config --global merge.tool diffmerge], %q[git config --global mergetool.diffmerge.cmd 'diffmerge --merge --result="$MERGED" "$LOCAL" "$(if test -f "$BASE"; then echo "$BASE"; else echo "$LOCAL"; fi)" "$REMOTE"'], %q[git config --global mergetool.diffmerge.trustExitCode true], ].each do |cmd| execute cmd do command cmd end end end
Change Array to Text in migration
class CreateLostMissingLongOverdues < ActiveRecord::Migration def change create_table :lost_missing_long_overdues do |t| t.integer :item_number t.integer :bib_number t.string :title t.string :imprint t.string :isbn t.string :status t.integer :checkouts t.string :location t.array :note t.string :call_number t.string :volume t.string :barcode t.date :due_date t.date :last_checkout t.timestamps end end end
class CreateLostMissingLongOverdues < ActiveRecord::Migration def change create_table :lost_missing_long_overdues do |t| t.integer :item_number t.integer :bib_number t.string :title t.string :imprint t.string :isbn t.string :status t.integer :checkouts t.string :location t.text :note t.string :call_number t.string :volume t.string :barcode t.date :due_date t.date :last_checkout t.timestamps end end end
Make child component name accessible by +config.name+
module Netzke::Core class ComponentConfig < ActiveSupport::OrderedOptions def initialize(name) @name = name.to_s end def set_defaults! self.item_id ||= @name # default item_id self.klass ||= @name.camelize.constantize # default klass end end end
module Netzke::Core class ComponentConfig < ActiveSupport::OrderedOptions def initialize(name) self.name = name.to_s end def set_defaults! self.item_id ||= name # default item_id self.klass ||= name.camelize.constantize # default klass end end end
Fix URI.escape is obsolete warnings
module GMOPaymentCarrier module Http class Client DEFAULT_HEADERS = { "Accept" => "application/json", "User-Agent" => "note" }.freeze def initialize(endpoint:, request: :url_encoded, response: :logger) @endpoint = endpoint @request = request @response = response end def connection @connection ||= Faraday.new(faraday_client_options) do |connection| connection.request @request if @request.present? connection.response @response if @response.present? connection.adapter Faraday.default_adapter end end def get(path:, params: nil, headers: nil) process(:get, path, params, headers) end def post(path:, params: nil, headers: nil) process(:post, path, params, headers) end def patch(path:, params: nil, headers: nil) process(:patch, path, params, headers) end def put(path:, params: nil, headers: nil) process(:put, path, params, headers) end def delete(path:, params: nil, headers: nil) process(:delete, path, params, headers) end private def process(request_method, path, params, headers) Response.new( connection.send( request_method, URI.escape(path), params, headers, ) ) end def default_headers DEFAULT_HEADERS.clone end def faraday_client_options { headers: default_headers, url: @endpoint, } end end end end
module GMOPaymentCarrier module Http class Client DEFAULT_HEADERS = { "Accept" => "application/json", "User-Agent" => "note" }.freeze def initialize(endpoint:, request: :url_encoded, response: :logger) @endpoint = endpoint @request = request @response = response end def connection @connection ||= Faraday.new(faraday_client_options) do |connection| connection.request @request if @request.present? connection.response @response if @response.present? connection.adapter Faraday.default_adapter end end def get(path:, params: nil, headers: nil) process(:get, path, params, headers) end def post(path:, params: nil, headers: nil) process(:post, path, params, headers) end def patch(path:, params: nil, headers: nil) process(:patch, path, params, headers) end def put(path:, params: nil, headers: nil) process(:put, path, params, headers) end def delete(path:, params: nil, headers: nil) process(:delete, path, params, headers) end private def process(request_method, path, params, headers) Response.new( connection.send( request_method, path, params, headers, ) ) end def default_headers DEFAULT_HEADERS.clone end def faraday_client_options { headers: default_headers, url: @endpoint, } end end end end
Include linter name in XMLReporter
module SCSSLint # Reports lints in an XML format. class Reporter::XMLReporter < Reporter def report_lints output = '<?xml version="1.0" encoding="utf-8"?>' output << '<lint>' lints.group_by(&:filename).each do |filename, file_lints| output << "<file name=#{filename.encode(xml: :attr)}>" file_lints.each do |lint| output << "<issue line=\"#{lint.location.line}\" " \ "column=\"#{lint.location.column}\" " \ "length=\"#{lint.location.length}\" " \ "severity=\"#{lint.severity}\" " \ "reason=#{lint.description.encode(xml: :attr)} />" end output << '</file>' end output << '</lint>' output end end end
module SCSSLint # Reports lints in an XML format. class Reporter::XMLReporter < Reporter def report_lints output = '<?xml version="1.0" encoding="utf-8"?>' output << '<lint>' lints.group_by(&:filename).each do |filename, file_lints| output << "<file name=#{filename.encode(xml: :attr)}>" file_lints.each do |lint| output << "<issue linter=\"#{lint.linter.name if lint.linter}\" " \ "line=\"#{lint.location.line}\" " \ "column=\"#{lint.location.column}\" " \ "length=\"#{lint.location.length}\" " \ "severity=\"#{lint.severity}\" " \ "reason=#{lint.description.encode(xml: :attr)} />" end output << '</file>' end output << '</lint>' output end end end
Add whois and domain code :watch:
require 'json' get '/' do erb :index end post '/dns' do # A, CNAME, AAAA, MX, NS respond_message "DNS Lookup" end post '/domain/' do # is domain taken or not, suggest to use whois if not respond_message "domain" end post '/whois' do respond_message "whois" end post '/ping' do respond_message "ping" end post '/net' do respond_message "Help & feedback" end def respond_message message content_type :json {:text => message}.to_json end
require 'json' require 'whois' get '/' do erb :index end post '/dns/' do # A, CNAME, AAAA, MX, NS respond_message "DNS Lookup" end post '/domain/' do # is domain taken or not, suggest to use whois if not respond_message "domain" end post '/whois/' do respond_message "whois" end post '/ping/' do respond_message "ping" end post '/net/' do respond_message "Help & feedback" end # for now only get '/whois/?' do result = Whois.whois("simplepoll.rocks") puts result result.to_json end get '/ping/?' do # can't work on this, because windows :( check = Net::Ping::External.new(host) puts check "Done" end get '/domain/:domain/?' do result = Whois.whois(params[:domain]) is_available = result.available? ? "yes" : "no" "Is " + params[:domain] + " available? " + is_available.to_s # this is some really messed up shit end def respond_message message content_type :json {:text => message}.to_json end
Remove a redundant helper method
module Merb module EditsHelper #-- # FIXME This method explodes if Version is nil, or Version does not have # any contents def link_to_page_or_nothing(version) if(page = version.page) link_to page.name, url(:page, page) else "New Page: #{version.content.split(':').last}" end end def mark_as_ham_or_spam(version) [ open_tag('button', :type => 'submit'), spam_or_ham_label(version), "</button>" ].join("") end private def spam_or_ham_label(version) version.spam ? 'This Is Ham' : 'This Is Spam' end end end
module Merb module EditsHelper #-- # FIXME This method explodes if Version is nil, or Version does not have # any contents def link_to_page_or_nothing(version) if(page = version.page) link_to page.name, url(:page, page) else "New Page: #{version.content.split(':').last}" end end def mark_as_ham_or_spam(version) [ open_tag('button', :type => 'submit'), "This is #{version.spam_or_ham.capitalize}", "</button>" ].join("") end end end
Make the Unpublish state gray
module GuideHelper STATE_CSS_CLASSES = { "draft" => "danger", "review_requested" => "warning", "ready" => "success", "published" => "info", "unpublished" => "primary", } def state_label(guide) state = guide.latest_edition.try(:state) title = state.titleize css_class = STATE_CSS_CLASSES[state] content_tag :span, title, title: 'State', class: "label label-#{css_class}" end def latest_author_name(guide) guide.latest_edition.author.try(:name).to_s end def guide_community_options_for_select # TODO: N+1 on loading the most recent edition GuideCommunity.all. sort_by{ |guide| guide.title }. map{ |g| [g.title, g.id] } end def guide_form_for(guide, *args, &block) options = args.extract_options! url = url_for(guide.becomes(Guide)) form_for(guide, *args << options.merge(as: :guide, url: url), &block) end def guide_community_title(guide_community) guide_community.title.gsub(/ [cC]ommunity$/, "") end end
module GuideHelper STATE_CSS_CLASSES = { "draft" => "danger", "review_requested" => "warning", "ready" => "success", "published" => "info", "unpublished" => "default", } def state_label(guide) state = guide.latest_edition.try(:state) title = state.titleize css_class = STATE_CSS_CLASSES[state] content_tag :span, title, title: 'State', class: "label label-#{css_class}" end def latest_author_name(guide) guide.latest_edition.author.try(:name).to_s end def guide_community_options_for_select # TODO: N+1 on loading the most recent edition GuideCommunity.all. sort_by{ |guide| guide.title }. map{ |g| [g.title, g.id] } end def guide_form_for(guide, *args, &block) options = args.extract_options! url = url_for(guide.becomes(Guide)) form_for(guide, *args << options.merge(as: :guide, url: url), &block) end def guide_community_title(guide_community) guide_community.title.gsub(/ [cC]ommunity$/, "") end end
Add code wars (8) unexpected parsing
# http://www.codewars.com/kata/54fdaa4a50f167b5c000005f/ # --- iterations --- def get_status(is_busy) status = is_busy ? "busy" : "available" return { "status" => status } end
Move flay result calculation out of to_h
module MetricFu class FlayGenerator < Generator def self.metric :flay end def emit args = "#{minimum_duplication_mass} #{dirs_to_flay}" @output = run!(args) end def analyze @matches = @output.chomp.split("\n\n").map{|m| m.split("\n ") } end def to_h target = [] total_score = @matches.shift.first.split('=').last.strip @matches.each do |problem| reason = problem.shift.strip lines_info = problem.map do |full_line| name, line = full_line.split(":").map(&:strip) {:name => name, :line => line} end target << [:reason => reason, :matches => lines_info] end {:flay => {:total_score => total_score, :matches => target.flatten}} end private def minimum_duplication_mass flay_mass = options[:minimum_score] return "" unless flay_mass "--mass #{flay_mass} " end def dirs_to_flay options[:dirs_to_flay].join(" ") end end end
module MetricFu class FlayGenerator < Generator def self.metric :flay end def emit args = "#{minimum_duplication_mass} #{dirs_to_flay}" @output = run!(args) end def analyze @matches = @output.chomp.split("\n\n").map{|m| m.split("\n ") } end def to_h {:flay => calculate_result(@matches)} end # TODO: move into analyze method def calculate_result(matches) total_score = matches.shift.first.split('=').last.strip target = [] matches.each do |problem| reason = problem.shift.strip lines_info = problem.map do |full_line| name, line = full_line.split(":").map(&:strip) {:name => name, :line => line} end target << [:reason => reason, :matches => lines_info] end { :total_score => total_score, :matches => target.flatten } end private def minimum_duplication_mass flay_mass = options[:minimum_score] return "" unless flay_mass "--mass #{flay_mass} " end def dirs_to_flay options[:dirs_to_flay].join(" ") end end end
Fix path to license file
Pod::Spec.new do |spec| spec.name = 'BTree' spec.version = '3.1.0' spec.osx.deployment_target = "10.9" spec.ios.deployment_target = "8.0" spec.tvos.deployment_target = "9.0" spec.watchos.deployment_target = "2.0" spec.summary = 'In-memory B-trees and ordered collections in Swift' spec.author = 'Károly Lőrentey' spec.homepage = 'https://github.com/lorentey/BTree' spec.license = { :type => 'MIT', :file => 'LICENCE.md' } spec.source = { :git => 'https://github.com/lorentey/BTree.git', :tag => 'v3.1.0' } spec.source_files = 'Sources/*.swift' spec.social_media_url = 'https://twitter.com/lorentey' spec.documentation_url = 'http://lorentey.github.io/BTree/api/' end
Pod::Spec.new do |spec| spec.name = 'BTree' spec.version = '3.1.0' spec.osx.deployment_target = "10.9" spec.ios.deployment_target = "8.0" spec.tvos.deployment_target = "9.0" spec.watchos.deployment_target = "2.0" spec.summary = 'In-memory B-trees and ordered collections in Swift' spec.author = 'Károly Lőrentey' spec.homepage = 'https://github.com/lorentey/BTree' spec.license = { :type => 'MIT', :file => 'LICENSE.md' } spec.source = { :git => 'https://github.com/lorentey/BTree.git', :tag => 'v3.1.0' } spec.source_files = 'Sources/*.swift' spec.social_media_url = 'https://twitter.com/lorentey' spec.documentation_url = 'http://lorentey.github.io/BTree/api/' end
Update Revisions to versions 2.0.2
cask :v1 => 'revisions' do version '2.0.1' sha256 'd9eaa948cdc9cf40ffa8c56e5ea03c5afd54f254aa5f18ee1054d551e406f262' url "https://revisionsapp.com/downloads/revisions-#{version}.dmg" name 'Revisions' homepage 'https://revisionsapp.com/' license :commercial app 'Revisions.app' end
cask :v1 => 'revisions' do version '2.0.2' sha256 'df6a238771d30d686cae91b72dd95a31ebe35e73354a08c162eb4ea4b9235836' url "https://revisionsapp.com/downloads/revisions-#{version}.dmg" name 'Revisions' homepage 'https://revisionsapp.com/' license :commercial app 'Revisions.app' end
Support for mime_type and json on android
module Net class Response def initialize(connection, response) @connection = connection @response = response end def status @connection.getResponseCode end def body @response.toString end def status_message end def headers end end end
module Net class Response def initialize(connection, response) @connection = connection @response = response end def status @connection.getResponseCode end def body @body ||= build_body end def status_message end def headers end def json? mime_type.match /application\/json/ end def mime_type @connection.getContentType end private def build_body if json? return JSON.load(@response.toString) end @response.toString end end end
Update running average calculator specs to new format
require 'spec_helper' describe ProgressBar::Calculators::RunningAverage do describe '.calculate' do it 'calculates properly' do expect(ProgressBar::Calculators::RunningAverage.calculate(4.5, 12, 0.1)).to be_within(0.001).of 11.25 expect(ProgressBar::Calculators::RunningAverage.calculate(8.2, 51, 0.7)).to be_within(0.001).of 21.04 expect(ProgressBar::Calculators::RunningAverage.calculate(41.8, 100, 0.59)).to be_within(0.001).of 65.662 end end end
require 'rspectacular' require 'ruby-progressbar/calculators/running_average' class ProgressBar module Calculators describe RunningAverage do it 'can properly calculate a running average' do first_average = RunningAverage.calculate(4.5, 12, 0.1) expect(first_average).to be_within(0.001).of 11.25 second_average = RunningAverage.calculate(8.2, 51, 0.7) expect(second_average).to be_within(0.001).of 21.04 third_average = RunningAverage.calculate(41.8, 100, 0.59) expect(third_average).to be_within(0.001).of 65.662 end end end end
Add cask for Near Lock application
cask :v1 => 'near-lock' do version :latest sha256 :no_check url 'http://nearlock.me/downloads/nearlock.dmg' name 'Near Lock' homepage 'http://nearlock.me/' license :gratis app 'Near Lock.app' end
Add index for cog uk id
class AddLighthouseSampleCogUkIdIndex < ActiveRecord::Migration[6.0] def change change_table :lighthouse_sample, bulk: true do |t| t.index :cog_uk_id end end end
# frozen_string_literal: true # # Add index for cog uk id class AddLighthouseSampleCogUkIdIndex < ActiveRecord::Migration[6.0] def change change_table :lighthouse_sample, bulk: true do |t| t.index :cog_uk_id end end end
Add data migration to backfill edition references
# Populate latest_edition_id and live_edition_id for documents that don't have them defined all_documents = Document.where(latest_edition_id: nil, live_edition_id: nil) total = all_documents.count @logger.info "There are #{total} documents to populate" done = 0 all_documents.find_in_batches do |documents| documents.each(&:update_edition_references) done += documents.count @logger.info "Done #{done}/#{total} (#{((done / total.to_f) * 100).to_i}%)" end
Test message sending to an AWS SQS queue
require 'spec_helper' require 'digest' describe Aws::SQS::Client do subject(:aws_client) { Aws::SQS::Client.new( access_key_id: ENV['AWS_ACCESS_KEY_ID'], secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'], region: ENV['AWS_REGION'] ) } it "is configured with valid credentials and region" do expect { aws_client.list_queues }.to_not raise_error end describe "message dispatching" do let(:queue_name) { "RailsEbJob-integration-testing" } let(:queue_url) do response = aws_client.create_queue(queue_name: queue_name) response.queue_url end let(:message_content) { "this is the content of the message" } let(:md5_digest) { Digest::MD5.hexdigest(message_content) } describe "#send_message" do it "is successful" do response = aws_client.send_message( message_body: message_content, queue_url: queue_url ) expect(response.md5_of_message_body).to match(md5_digest) end end end end
Add back support for pre Cucumber 0.4
class Spork::Server::Cucumber < Spork::Server CUCUMBER_PORT = 8990 CUCUMBER_HELPER_FILE = File.join(Dir.pwd, "features/support/env.rb") class << self def port CUCUMBER_PORT end def helper_file CUCUMBER_HELPER_FILE end end def run_tests(argv, stderr, stdout) require 'cucumber/cli/main' ::Cucumber::Cli::Main.new(argv, stdout, stderr).execute!(::Cucumber::StepMother.new) end end
class Spork::Server::Cucumber < Spork::Server CUCUMBER_PORT = 8990 CUCUMBER_HELPER_FILE = File.join(Dir.pwd, "features/support/env.rb") class << self def port CUCUMBER_PORT end def helper_file CUCUMBER_HELPER_FILE end # REMOVE WHEN SUPPORT FOR PRE-0.4 IS DROPPED attr_accessor :step_mother end # REMOVE WHEN SUPPORT FOR PRE-0.4 IS DROPPED def step_mother self.class.step_mother end def run_tests(argv, stderr, stdout) begin require 'cucumber/cli/main' ::Cucumber::Cli::Main.new(argv, stdout, stderr).execute!(::Cucumber::StepMother.new) rescue NoMethodError => pre_cucumber_0_4 # REMOVE WHEN SUPPORT FOR PRE-0.4 IS DROPPED ::Cucumber::Cli::Main.step_mother = step_mother ::Cucumber::Cli::Main.new(argv, stdout, stderr).execute!(step_mother) end end end Spork::Server::Cucumber.step_mother = self # REMOVE WHEN SUPPORT FOR PRE-0.4 IS DROPPED
Add better error messages for missing creds
require 'thor' require 'aws_cred_vault' require 'aws-sdk' module Omc class Cli < Thor desc 'ssh', 'Connect to an instance on a stack on an account' def ssh(account, stack) iam_account = vault.account account user = iam_account.users.first ops = ::AWS::OpsWorks::Client.new user.credentials ops_stack = get_by_name ops.describe_stacks[:stacks], stack instances = ops.describe_instances(stack_id: ops_stack[:stack_id])[:instances] instances.reject!{|i| i[:status] != "online" } instance = instances.first system "ssh #{user.name}@#{instance[:public_ip]}" end private def vault AwsCredVault::Toml.new File.join(ENV['HOME'], '.aws_cred_vault') end def get_by_name collection, name collection.detect do |x| x[:name] == name end || abort("Can't find #{name.inspect} among #{collection.map{|x| x[:name] }.inspect}") end end end
require 'thor' require 'aws_cred_vault' require 'aws-sdk' module Omc class Cli < Thor desc 'ssh', 'Connect to an instance on a stack on an account' def ssh(account, stack) iam_account = vault.account(account) || abort("Account #{account.inspect} not configured") user = iam_account.users.first || abort("No users configured under #{account.inspect}") ops = ::AWS::OpsWorks::Client.new user.credentials ops_stack = get_by_name ops.describe_stacks[:stacks], stack instances = ops.describe_instances(stack_id: ops_stack[:stack_id])[:instances] instances.reject!{|i| i[:status] != "online" } instance = instances.first || abort("No running instances") system "ssh #{user.name}@#{instance[:public_ip]}" end private def vault AwsCredVault::Toml.new File.join(ENV['HOME'], '.aws_cred_vault') end def get_by_name collection, name collection.detect do |x| x[:name] == name end || abort("Can't find #{name.inspect} among #{collection.map{|x| x[:name] }.inspect}") end end end
Add test script to test entry capabilities
#!/usr/bin/env ruby require "../target/debug/liblibimagruby.so" color = true verbose = true debug = false RImag.init_logger debug, verbose, color store_handle = RStoreHandle::new(false, "/tmp/store") id = RStoreId::new_baseless("test") test_handle = store_handle.retrieve(id) puts "Header: #{test_handle.header.to_s}" puts "Content: '#{test_handle.content}'" test_handle.content = "Foo" test_handle.header = { "imag" => { "links" => [], "version" => "0.2.0" }, "example" => { "test" => "foo" } }
Update to work with new appium_lib gem
# encoding: utf-8 require 'rubygems' Gem::Specification.class_eval { def self.warn( args ); end } require 'pry' module Appium; end unless defined? Appium def define_reload Pry.send(:define_singleton_method, :reload) do files = load_appium_txt file: Dir.pwd + '/appium.txt' files.each do |file| # If a page obj is deleted then load will error. begin load file rescue # LoadError: cannot load such file end end end nil end module Appium::Console require 'appium_lib' AwesomePrint.pry! to_require = load_appium_txt file: Dir.pwd + '/appium.txt', verbose: true start = File.expand_path '../start.rb', __FILE__ cmd = ['-r', start] if to_require && !to_require.empty? define_reload load_files = to_require.map { |f| %(require "#{f}";) }.join "\n" cmd += [ '-e', load_files ] end $stdout.puts "pry #{cmd.join(' ')}" Pry::CLI.parse_options cmd end # module Appium::Console
# encoding: utf-8 require 'rubygems' Gem::Specification.class_eval { def self.warn( args ); end } require 'pry' module Appium; end unless defined? Appium def define_reload Pry.send(:define_singleton_method, :reload) do parsed = load_appium_txt file: Dir.pwd + '/appium.txt' return unless parsed && parsed[:appium_lib] && parsed[:appium_lib][:requires] requires = parsed[:appium_lib][:requires] requires.each do |file| # If a page obj is deleted then load will error. begin load file rescue # LoadError: cannot load such file end end end nil end module Appium::Console require 'appium_lib' AwesomePrint.pry! to_require = load_appium_txt file: Dir.pwd + '/appium.txt', verbose: true start = File.expand_path '../start.rb', __FILE__ cmd = ['-r', start] if to_require && !to_require.empty? define_reload load_files = to_require.map { |f| %(require "#{f}";) }.join "\n" cmd += [ '-e', load_files ] end $stdout.puts "pry #{cmd.join(' ')}" Pry::CLI.parse_options cmd end # module Appium::Console
Stop registering routes for browse
namespace :router do task :router_environment => :environment do require 'plek' require 'gds_api/router' @router_api = GdsApi::Router.new(Plek.current.find('router-api')) end task :register_backend => :router_environment do @router_api.add_backend('frontend', Plek.current.find('frontend', :force_http => true) + "/") end task :register_routes => :router_environment do routes = [ %w(/ exact), %w(/browse prefix), %w(/browse.json exact), %w(/business exact), %w(/search exact), %w(/search.json exact), %w(/search/opensearch.xml exact), %w(/homepage exact), %w(/tour exact), %w(/ukwelcomes exact), %w(/visas-immigration exact), ] routes.each do |path, type| @router_api.add_route(path, type, 'frontend', :skip_commit => true) end @router_api.commit_routes end desc "Register frontend application and routes with the router" task :register => [ :register_backend, :register_routes ] end
namespace :router do task :router_environment => :environment do require 'plek' require 'gds_api/router' @router_api = GdsApi::Router.new(Plek.current.find('router-api')) end task :register_backend => :router_environment do @router_api.add_backend('frontend', Plek.current.find('frontend', :force_http => true) + "/") end task :register_routes => :router_environment do routes = [ %w(/ exact), %w(/search exact), %w(/search.json exact), %w(/search/opensearch.xml exact), %w(/homepage exact), %w(/tour exact), %w(/ukwelcomes exact), ] routes.each do |path, type| @router_api.add_route(path, type, 'frontend', :skip_commit => true) end @router_api.commit_routes end desc "Register frontend application and routes with the router" task :register => [ :register_backend, :register_routes ] end
Refactor build deck to account for neighborhoods
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :histories has_many :neighborhood_users has_many :neighborhoods, through: :neighborhood_users validates :user_name, presence: true, case_sensitive: false validates :zipcode, presence: true, length: { :is => 5 } def favorites favs = [] self.histories.each do |history| state = history.identify_state favs.push(history) if state == "Favorite" end end def start_card card_sample = [] if self.neighborhoods.empty? return Food.all.sample else self.neighborhoods each do |neighborhood| neighborhood.places each do |place| card_sample << place end end end card_sample.sample end def build_deck json = [] @deck = Food.all.sample(10) @deck.each do |food| json_food = { id: food.id, name: food.place.name, url: food.url, place_id: food.place.id } json << json_food end json end end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :histories has_many :neighborhood_users has_many :neighborhoods, through: :neighborhood_users validates :user_name, presence: true, case_sensitive: false validates :zipcode, presence: true, length: { :is => 5 } def favorites favs = [] self.histories.each do |history| state = history.identify_state favs.push(history) if state == "Favorite" end end def start_card card_sample = [] if self.neighborhoods.empty? return Food.all.sample else self.neighborhoods each do |neighborhood| neighborhood.places each do |place| card_sample << place end end end card_sample.sample end def build_deck json = [] if self.neighborhoods.empty? Food.all.each do |food| json_food = { id: food.id, name: food.place.name, url: food.url, place_id: food.place.id } json << json_food end else self.neighborhoods each do |neighborhood| neighborhood.places each do |place| place.foods each do |food| json_food = { id: food.id, name: food.place.name, url: food.url, place_id: food.place.id } json << json_food end end end end json end end
Disable CSRF protection unless in Production
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. if Rails.env.production? protect_from_forgery with: :exception end end
Write tests for Reddit client
require 'spec_helper' module USaidWat module Client describe Client do before(:each) do root = File.expand_path("../../../test/responses", __FILE__) stub_request(:get, "http://www.reddit.com/user/mipadi/comments.json"). to_return(:body => IO.read(File.join(root, "comments_1.json"))) stub_request(:get, "http://www.reddit.com/user/mipadi/comments.json?count=25&after=t1_c77kq1t"). to_return(:body => IO.read(File.join(root, "comments_2.json"))) stub_request(:get, "http://www.reddit.com/user/mipadi/comments.json?count=50&after=t1_c74e76h"). to_return(:body => IO.read(File.join(root, "comments_3.json"))) stub_request(:get, "http://www.reddit.com/user/mipadi/comments.json?count=75&after=t1_c73pvjp"). to_return(:body => IO.read(File.join(root, "comments_4.json"))) end let(:redditor) { Client::Redditor.new("mipadi") } describe "#username" do it "returns the Redditor's username" do redditor.username.should == "mipadi" end end describe "#comments" do it "gets 100 comments" do redditor.comments.count.should == 100 end end end end end
Add Haswell to CPU tests
require 'testing_env' require 'hardware' class HardwareTests < Test::Unit::TestCase # these will raise if we don't recognise your mac, but that prolly # indicates something went wrong rather than we don't know def test_hardware_cpu_type assert [:intel, :ppc].include?(Hardware::CPU.type) end def test_hardware_intel_family if Hardware::CPU.type == :intel assert [:core, :core2, :penryn, :nehalem, :arrandale, :sandybridge, :ivybridge].include?(Hardware::CPU.family) end end end
require 'testing_env' require 'hardware' class HardwareTests < Test::Unit::TestCase # these will raise if we don't recognise your mac, but that prolly # indicates something went wrong rather than we don't know def test_hardware_cpu_type assert [:intel, :ppc].include?(Hardware::CPU.type) end def test_hardware_intel_family if Hardware::CPU.type == :intel assert [:core, :core2, :penryn, :nehalem, :arrandale, :sandybridge, :ivybridge, :haswell].include?(Hardware::CPU.family) end end end
Make content of automatic request spec almost empty
require 'rails_helper' RSpec.describe "<%= class_name.pluralize %>", <%= type_metatag(:request) %> do describe "GET /<%= name.underscore.pluralize %>" do it "works! (now write some real specs)" do get <%= index_helper %>_path expect(response).to have_http_status(200) end end end
require 'rails_helper' RSpec.describe "<%= class_name.pluralize %>", <%= type_metatag(:request) %> do describe "GET /<%= name.underscore.pluralize %>" do it "works! (now write some real specs)" do end end end
Add request creation error handling
class RequestsController < ApplicationController def index @requests = Request.all end def new @request = Request.new end def create redirect_to new_request and return unless logged_in? @request = Request.new(request_attributes) @request.requester = current_user if @request.save redirect_to request(@request) else @errors = @request.errors.full_messages render 'new' end end private def request_attributes params.require(:request).permit(:content) end end
class RequestsController < ApplicationController def index @requests = Request.all end def new @request = Request.new end def create redirect_to new_request and return unless logged_in? @request = Request.new(request_attributes) @request.requester = current_user if @request.save redirect_to request(@request) else flash.new[:alert] = @request.errors.full_messages.join(", ") render 'new' end end private def request_attributes params.require(:request).permit(:content) end end
Update PryntTrimmerView version in Podspec
Pod::Spec.new do |s| s.name = 'YPImagePicker' s.version = "4.3.1" s.summary = "Instagram-like image picker & filters for iOS" s.homepage = "https://github.com/Yummypets/YPImagePicker" s.license = { :type => "MIT", :file => "LICENSE" } s.author = 'S4cha, NikKovIos' s.platform = :ios s.source = { :git => "https://github.com/Yummypets/YPImagePicker.git", :tag => s.version.to_s } s.social_media_url = 'https://twitter.com/sachadso' s.requires_arc = true s.ios.deployment_target = "9.0" s.source_files = 'Source/**/*.swift' s.dependency 'SteviaLayout', '~> 4.7.3' s.dependency 'PryntTrimmerView', '~> 4.0.0' s.resources = ['Resources/*', 'Source/**/*.xib'] s.description = "Instagram-like image picker & filters for iOS supporting videos and albums" s.swift_versions = ['3', '4.1', '4.2', '5.0', '5.1', '5.2'] end
Pod::Spec.new do |s| s.name = 'YPImagePicker' s.version = "4.3.1" s.summary = "Instagram-like image picker & filters for iOS" s.homepage = "https://github.com/Yummypets/YPImagePicker" s.license = { :type => "MIT", :file => "LICENSE" } s.author = 'S4cha, NikKovIos' s.platform = :ios s.source = { :git => "https://github.com/Yummypets/YPImagePicker.git", :tag => s.version.to_s } s.social_media_url = 'https://twitter.com/sachadso' s.requires_arc = true s.ios.deployment_target = "9.0" s.source_files = 'Source/**/*.swift' s.dependency 'SteviaLayout', '~> 4.7.3' s.dependency 'PryntTrimmerView', '~> 4.0.2' s.resources = ['Resources/*', 'Source/**/*.xib'] s.description = "Instagram-like image picker & filters for iOS supporting videos and albums" s.swift_versions = ['3', '4.1', '4.2', '5.0', '5.1', '5.2'] end
Add notice to redirect when destroying Snapshots
class SnapshotsController < ApplicationController before_filter :set_snapshot, only: %i[show destroy set_as_baseline] def index if params[:url] @url = Url.find(params[:url]) @snapshots = @url.snapshots else @snapshots = Snapshot.all end end def show render end def create url = Url.find(params.delete(:url)) @snapshot = Snapshot.new @snapshot.url = url @snapshot.save! redirect_to url, notice: 'Snapshot was successfully created.' end def destroy @snapshot.destroy redirect_to @snapshot.url end def set_as_baseline baseline = Baseline.where(url_id: @snapshot.url.id).first || Baseline.new(url_id: @snapshot.url.id) baseline.snapshot = @snapshot baseline.save! flash[:notice] = <<-EOS This Snapshot will now be used as the baseline in future diffs for the same URL. EOS redirect_to @snapshot end private def set_snapshot @snapshot = Snapshot.find(params[:id]) end end
class SnapshotsController < ApplicationController before_filter :set_snapshot, only: %i[show destroy set_as_baseline] def index if params[:url] @url = Url.find(params[:url]) @snapshots = @url.snapshots else @snapshots = Snapshot.all end end def show render end def create url = Url.find(params.delete(:url)) @snapshot = Snapshot.new @snapshot.url = url @snapshot.save! redirect_to url, notice: 'Snapshot was successfully created.' end def destroy @snapshot.destroy redirect_to @snapshot.url, notice: 'Snapshot was successfully destroyed.' end def set_as_baseline baseline = Baseline.where(url_id: @snapshot.url.id).first || Baseline.new(url_id: @snapshot.url.id) baseline.snapshot = @snapshot baseline.save! flash[:notice] = <<-EOS This Snapshot will now be used as the baseline in future diffs for the same URL. EOS redirect_to @snapshot end private def set_snapshot @snapshot = Snapshot.find(params[:id]) end end
Add remember token to migration generator
require 'rails/generators/base' module Authem class ModelGenerator < Rails::Generators::Base argument :model_name, type: :string, default: "user" def generate_model generate("model #{model_name} email:string, password_digest:string, reset_password_token:string, session_token:string") end def update_model_to_include_authem insert_into_file "app/models/#{model_name}.rb", "\n include Authem::User\n\n", after: "class #{model_name.camelize} < ActiveRecord::Base\n" end def add_initializer create_file 'config/initializers/authem.rb' do %Q(Authem.configure do |config|\n config.user_class = #{model_name.camelize}\nend) end end end end
require 'rails/generators/base' module Authem class ModelGenerator < Rails::Generators::Base argument :model_name, type: :string, default: "user" def generate_model generate("model #{model_name} email:string, password_digest:string, reset_password_token:string, session_token:string, remember_token:string") end def update_model_to_include_authem insert_into_file "app/models/#{model_name}.rb", "\n include Authem::User\n\n", after: "class #{model_name.camelize} < ActiveRecord::Base\n" end def add_initializer create_file 'config/initializers/authem.rb' do %Q(Authem.configure do |config|\n config.user_class = #{model_name.camelize}\nend) end end end end
Add task to regenerate search documents of budget lines by site and year
# frozen_string_literal: true namespace :gobierto_budgets do namespace :pg_search do desc "Rebuild multisearch indexes of Budget lines by domain and year" task :reindex, [:site_domain, :year] => [:environment] do |_t, args| site = Site.find_by!(domain: args[:site_domain]) year = args[:year].to_i organization_id = site.organization_id puts "== Reindexing records for site #{site.domain}==" # Delete all Budget Line PgSearch documents within this site site.pg_search_documents.where(searchable_type: "GobiertoBudgets::BudgetLine").where("meta @> ?", { year: year }.to_json).destroy_all GobiertoBudgets::BudgetArea.all_areas.each do |area| area.available_kinds.each do |kind| puts "\n[INFO] area = '#{area.area_name}' kind = '#{kind}'" puts "---------------------------------------------------" forecast_hits = request_budget_lines_from_elasticsearch( GobiertoBudgets::SearchEngineConfiguration::BudgetLine.index_forecast, area, organization_id, year ) puts "[INFO] Found #{forecast_hits.size} forecast #{area.area_name} #{kind} BudgetLine records" forecast_budget_lines = forecast_hits.map do |h| create_budget_line(site, "index_forecast", h) end GobiertoBudgets::BudgetLine.pg_search_reindex_collection(forecast_budget_lines) end end end def create_budget_line(site, index, elasticsearch_hit) GobiertoBudgets::BudgetLine.new( site: site, index: index, area_name: elasticsearch_hit["_type"], kind: elasticsearch_hit["_source"]["kind"], code: elasticsearch_hit["_source"]["code"], year: elasticsearch_hit["_source"]["year"], amount: elasticsearch_hit["_source"]["amount"] ) end def request_budget_lines_from_elasticsearch(index, area, organization_id, year) query = { query: { filtered: { filter: { bool: { must: [ { term: { organization_id: organization_id } }, { term: { year: year } } ] } } } }, size: 10_000 } GobiertoBudgets::SearchEngine.client.search( index: index, type: area.area_name, body: query )["hits"]["hits"] end end end
Tag validates name and slugs
# == Schema Information # # Table name: tags # # id :integer not null, primary key # title :string # slug :string # created_at :datetime not null # updated_at :datetime not null # class Tag < ApplicationRecord has_and_belongs_to_many :products end
# == Schema Information # # Table name: tags # # id :integer not null, primary key # title :string # slug :string # created_at :datetime not null # updated_at :datetime not null # class Tag < ApplicationRecord validates :name, :slug, presence: true has_and_belongs_to_many :products end
Add test for validating empty schemas
require 'test_helper' module Schemacop class EmptyTest < Minitest::Test def test_empty_hash schema = Schema.new do type Hash end assert_nothing_raised { schema.validate!({}) } assert_verr { schema.validate!(foo: :bar) } end end end
Modify output to not assume view logic
module Cortex module Snippets module Client module Helper def snippet(options = {}, &block) snippets = webpage[:snippets] || [] snippet = snippets.find { |snippet| snippet[:document][:name] == options[:id] } if snippet.nil? || snippet[:document][:body].nil? || snippet[:document][:body].empty? content_tag(:snippet, capture(&block), options) else content_tag(:snippet, snippet[:document][:body].html_safe, options) end end def seo_title webpage[:seo_title] end def seo_description webpage[:seo_description] end def seo_keywords webpage[:seo_keyword_list] end def seo_robots build_robot_information end def noindex webpage[:noindex] end def nofollow webpage[:nofollow] end def noodp webpage[:noodp] end def nosnippet webpage[:nosnippet] end def noarchive webpage[:noarchive] end def noimageindex webpage[:noimageindex] end private def webpage Cortex::Snippets::Client::current_webpage(request) end def build_robot_information robot_information = [] index_options = [:noindex, :nofollow, :noodp, :nosnippet, :noarchive, :noimageindex] index_options.each do |index_option| robot_information << index_option if valid_index_option?(index_option) end robot_information.join(", ") end def valid_index_option?(index_option) webpage[index_option] end end end end end
module Cortex module Snippets module Client module Helper def snippet(options = {}, &block) snippets = webpage[:snippets] || [] snippet = snippets.find { |snippet| snippet[:document][:name] == options[:id] } if snippet.nil? || snippet[:document][:body].nil? || snippet[:document][:body].empty? content_tag(:snippet, capture(&block), options) else content_tag(:snippet, snippet[:document][:body].html_safe, options) end end def seo_title webpage[:seo_title] end def seo_description webpage[:seo_description] end def seo_keywords webpage[:seo_keyword_list] end def seo_robots robot_information = [] index_options = [:noindex, :nofollow, :noodp, :nosnippet, :noarchive, :noimageindex] index_options.each do |index_option| robot_information << index_option if webpage[index_option] end robot_information end def noindex webpage[:noindex] end def nofollow webpage[:nofollow] end def noodp webpage[:noodp] end def nosnippet webpage[:nosnippet] end def noarchive webpage[:noarchive] end def noimageindex webpage[:noimageindex] end private def webpage Cortex::Snippets::Client::current_webpage(request) end end end end end
Include transitive dependencies in gemfile and be more generous about the files we include in the package
# -*- encoding: utf-8 -*- $:.push File.expand_path('../lib', __FILE__) require "tapestry/version" Gem::Specification.new do |gem| gem.name = "tapestry" gem.version = Tapestry::VERSION gem.platform = Gem::Platform::RUBY gem.summary = "Fiber adapter for doing non-blocking I/O" gem.description = gem.summary gem.licenses = ['MIT'] gem.authors = ['Logan Bowers'] gem.email = ['logan@datacurrent.com'] gem.homepage = 'https://github.com/loganb/tapestry' gem.required_rubygems_version = '>= 1.3.6' gem.files = Dir['README.md', 'lib/**/*'] gem.require_path = 'lib' gem.add_development_dependency 'rake' gem.add_development_dependency 'rspec' gem.add_development_dependency 'rdoc' end
# -*- encoding: utf-8 -*- $:.push File.expand_path('../lib', __FILE__) require "tapestry/version" Gem::Specification.new do |gem| gem.name = "tapestry" gem.version = Tapestry::VERSION gem.platform = Gem::Platform::RUBY gem.summary = "Fiber adapter for doing non-blocking I/O" gem.description = gem.summary gem.licenses = ['MIT'] gem.authors = ['Logan Bowers'] gem.email = ['logan@datacurrent.com'] gem.homepage = 'https://github.com/loganb/tapestry' gem.required_rubygems_version = '>= 1.3.6' gem.files = Dir['README.md', 'lib/**/*', '*.gemspec', '**/*.rb', '**/*.rake'] gem.require_path = 'lib' gem.add_development_dependency 'rake' gem.add_development_dependency 'rspec' gem.add_development_dependency 'rdoc' gem.add_dependency 'cool.io' gem.add_dependency 'iobuffer' end
Remove :whats_new contant from apps.
module MarketBot module Play class App ATTRIBUTES = [ :category, :category_url, :content_rating, :cover_image_url, :current_version, :description, :developer, :email, :full_screenshot_urls, :html, :installs, :more_from_developer, :price, :rating, :rating_distribution, :requires_android, :reviews, :screenshot_urls, :similar, :size, :title, :updated, :votes, :website_url, :whats_new ] end end end
module MarketBot module Play class App ATTRIBUTES = [ :category, :category_url, :content_rating, :cover_image_url, :current_version, :description, :developer, :email, :full_screenshot_urls, :html, :installs, :more_from_developer, :price, :rating, :rating_distribution, :requires_android, :reviews, :screenshot_urls, :similar, :size, :title, :updated, :votes, :website_url, ] end end end
Add perform method to collisions
class CollisionsDetectorTask < Base @queue = :collisions_detector_task attr_reader :document def perform(id) self.new(id).call end def initialize(id) @document = Document.find(id) end def call addresses = document.named_entities.where(ne_class: :addresses) other_entities = document.named_entities.ne(ne_class: :addresses) other_entities.each do |ne| addresses.each do |ae| collision = (ne.inner_pos['from_pos']...ne.inner_pos['to_pos']).to_a & (ae.inner_pos['from_pos']...ae.inner_pos['to_pos']).to_a unless collision.empty? logger.debug "[COLLISION] #{ne.text}" ne.update_attribute :collisioned, true end end end end end
class CollisionsDetectorTask < Base @queue = :collisions_detector_task attr_reader :document def self.perform(id) self.new(id).call end def initialize(id) @document = Document.find(id) end def call addresses = document.named_entities.where(ne_class: :addresses) other_entities = document.named_entities.ne(ne_class: :addresses) other_entities.each do |ne| addresses.each do |ae| collision = (ne.inner_pos['from_pos']...ne.inner_pos['to_pos']).to_a & (ae.inner_pos['from_pos']...ae.inner_pos['to_pos']).to_a unless collision.empty? logger.debug "[COLLISION] #{ne.text}" ne.update_attribute :collisioned, true end end end end end
Update the relationships with other models
class Client < ActiveRecord::Base has_many :facts, :dependent => :destroy has_many :configs, :dependent => :destroy has_many :results, :dependent => :destroy validates_presence_of :name validates_uniqueness_of :name validates_numericality_of :status, :only_integer => true, :allow_nil => true end
class Client < ActiveRecord::Base has_many :facts, :dependent => :destroy has_many :originals, :dependent => :destroy has_many :etch_configs, :dependent => :destroy has_many :results, :dependent => :destroy validates_presence_of :name validates_uniqueness_of :name validates_numericality_of :status, :only_integer => true, :allow_nil => true end
Make sure we call Kernel's raise when in a Thread
module Kernel def method_missing(meth, *args) # Exclude method_missing from the backtrace since it only confuses # people. myself = MethodContext.current ctx = myself.sender if myself.send_private? raise NameError, "undefined local variable or method `#{meth}' for #{inspect}" elsif self.__kind_of__ Class or self.__kind_of__ Module raise NoMethodError.new("No method '#{meth}' on #{self} (#{self.__class__})", ctx, args) else raise NoMethodError.new("No method '#{meth}' on an instance of #{self.__class__}.", ctx, args) end end private :method_missing # Add in $! in as a hook, to just do $!. This is for accesses to $! # that the compiler can't see. get = proc { $! } Globals.set_hook(:$!, get, nil) # Same as $!, for any accesses we might miss. # HACK. I doubt this is correct, because of how it will be called. get = proc { Regex.last_match } Globals.set_hook(:$~, get, nil) get = proc { ARGV } Globals.set_hook(:$*, get, nil) get = proc { $! ? $!.backtrace : nil } Globals.set_hook(:$@, get, nil) get = proc { Process.pid } Globals.set_hook(:$$, get, nil) end
module Kernel def method_missing(meth, *args) # Exclude method_missing from the backtrace since it only confuses # people. myself = MethodContext.current ctx = myself.sender if myself.send_private? Kernel.raise NameError, "undefined local variable or method `#{meth}' for #{inspect}" elsif self.__kind_of__ Class or self.__kind_of__ Module Kernel.raise NoMethodError.new("No method '#{meth}' on #{self} (#{self.__class__})", ctx, args) else Kernel.raise NoMethodError.new("No method '#{meth}' on an instance of #{self.__class__}.", ctx, args) end end private :method_missing # Add in $! in as a hook, to just do $!. This is for accesses to $! # that the compiler can't see. get = proc { $! } Globals.set_hook(:$!, get, nil) # Same as $!, for any accesses we might miss. # HACK. I doubt this is correct, because of how it will be called. get = proc { Regex.last_match } Globals.set_hook(:$~, get, nil) get = proc { ARGV } Globals.set_hook(:$*, get, nil) get = proc { $! ? $!.backtrace : nil } Globals.set_hook(:$@, get, nil) get = proc { Process.pid } Globals.set_hook(:$$, get, nil) end
Fix the after sign in/out path to redirect
module Comable module Apartment class ApplicationController < ActionController::Base include Comable::ApplicationHelper helper_method :current_comable_user before_filter :authenticate_root_user! layout 'comable/apartment/application' def current_ability Comable::Ability.new(current_comable_user) end def current_comable_user current_root_user || Comable::User.new end private rescue_from CanCan::AccessDenied, with: :unauthorized def unauthorized if current_comable_user.signed_in? flash[:alert] = Comable::Apartment.t(:access_denied) redirect_to after_access_denied_path else store_location redirect_to comable_apartment.new_root_user_session_path end end # TODO: Implement this method after add the page for sign in as a another user def after_access_denied_path fail 'Please implement this method' end def after_sign_in_path_for(_resource) comable_apartment.root_path end def after_sign_out_path_for(_resource) comable_apartment.new_root_user_session_path end end end end
module Comable module Apartment class ApplicationController < ActionController::Base include Comable::ApplicationHelper helper_method :current_comable_user before_filter :authenticate_root_user! layout 'comable/apartment/application' def current_ability Comable::Ability.new(current_comable_user) end def current_comable_user current_root_user || Comable::User.new end private rescue_from CanCan::AccessDenied, with: :unauthorized def unauthorized if current_comable_user.signed_in? flash[:alert] = Comable::Apartment.t(:access_denied) redirect_to after_access_denied_path else store_location redirect_to comable_apartment.new_root_user_session_path end end # TODO: Implement this method after add the page for sign in as a another user def after_access_denied_path fail 'Please implement this method' end def after_sign_in_path_for(_resource_or_scope) case resource_name when :root_user comable_apartment.root_path # TODO: Delegate to Comable::ApplicationHelper when :admin_user comable.admin_root_path else session.delete(:user_return_to) || comable.root_path end end def after_sign_out_path_for(scope) after_sign_in_path_for(scope) end end end end
Add code wars (7) - split in parts
# http://www.codewars.com/kata/5650ab06d11d675371000003 # --- iteration 1 --- def split_in_parts (str, len) str.chars .each_slice(len) .to_a .map(&:join) .join(" ") end
Make change to comply with circle ci tests
require 'rails_helper' describe TagsController do before(:each) do @tag = create(:tag) @tag.questions << create(:question) end describe "#index" do it "has a 200 status code" do get :index expect(response.status).to eq(200) end it "renders index template" do get :index expect(response).to render_template("index") end end describe "#show" do it "has a 200 status code" do get :show, {id: 2} expect(response.status).to eq(200) end it "renders show template" do get :show, {id: 2} expect(response).to render_template("show") end it "assigns tags correctly" do get :show, {id: 5} expect(assigns(:tag)).to eq(Tag.find(5)) end end end
require 'rails_helper' describe TagsController do before(:each) do @tag = create(:tag) @tag.questions << create(:question) end describe "#index" do it "has a 200 status code" do get :index expect(response.status).to eq(200) end it "renders index template" do get :index expect(response).to render_template("index") end end describe "#show" do it "has a 200 status code" do get :show, {id: 5} expect(response.status).to eq(200) end it "renders show template" do get :show, {id: 5} expect(response).to render_template("show") end it "assigns tags correctly" do get :show, {id: 5} expect(assigns(:tag)).to eq(Tag.find(5)) end end end
Include default value in factory
FactoryGirl.define do factory :owner factory :user factory :scraper do name 'my_scraper' owner end factory :organization end
FactoryGirl.define do factory :owner factory :user factory :scraper do name 'my_scraper' full_name 'mlandauer/my_scraper' owner end factory :organization end
Fix misleading tooltip in orchestration template toolbar
class ApplicationHelper::Button::OrchestrationTemplateEditRemove < ApplicationHelper::Button::Basic def calculate_properties super if @view_context.x_active_tree == :ot_tree && @record self[:enabled] = !@record.in_use? self[:title] = if self[:id] =~ /_edit$/ _('Orchestration Templates that are in use cannot be edited') else _('Orchestration Templates that are in use cannot be removed') end end end end
class ApplicationHelper::Button::OrchestrationTemplateEditRemove < ApplicationHelper::Button::Basic def calculate_properties super if @view_context.x_active_tree == :ot_tree && @record if @record.in_use? self[:enabled] = false self[:title] = if self[:id] =~ /_edit$/ _('Orchestration Templates that are in use cannot be edited') else _('Orchestration Templates that are in use cannot be removed') end end end end end
Fix bug where blank websites got a http prefix
class Post include Mongoid::Document include Mongoid::Timestamps include Mongoid::Slug attr_protected :_id, :slug references_many :comments field :title slug :title, :permanent => true field :body field :published_at, :type => Time field :post_type, :type => Array field :tags, :type => Array field :private, :type => Boolean, :default => false field :draft, :type => Boolean, :default => true field :display_title, :type => Boolean, :default => true index :slug index :published_at index :post_type index :tags index :private index :draft validates_uniqueness_of :slug, :allow_nil => true scope :visible, :where => {:private => false, :draft => false} end class Comment include Mongoid::Document include Mongoid::Timestamps referenced_in :post attr_protected :hidden, :ip field :author field :author_url field :body field :hidden, :type => Boolean, :default => false field :mine, :type => Boolean, :default => false field :ip index :author index :hidden index :ip index :mine validates_presence_of :body validates_presence_of :author scope :visible, :where => {:hidden => false} before_create :adjust_url def adjust_url if self.author_url !~ /^http:\/\// self.author_url = "http://#{author_url}" end end end
class Post include Mongoid::Document include Mongoid::Timestamps include Mongoid::Slug attr_protected :_id, :slug references_many :comments field :title slug :title, :permanent => true field :body field :published_at, :type => Time field :post_type, :type => Array field :tags, :type => Array field :private, :type => Boolean, :default => false field :draft, :type => Boolean, :default => true field :display_title, :type => Boolean, :default => true index :slug index :published_at index :post_type index :tags index :private index :draft validates_uniqueness_of :slug, :allow_nil => true scope :visible, :where => {:private => false, :draft => false} end class Comment include Mongoid::Document include Mongoid::Timestamps referenced_in :post attr_protected :hidden, :ip field :author field :author_url field :body field :hidden, :type => Boolean, :default => false field :mine, :type => Boolean, :default => false field :ip index :author index :hidden index :ip index :mine validates_presence_of :body validates_presence_of :author scope :visible, :where => {:hidden => false} before_create :adjust_url def adjust_url if self.author_url.present? and (self.author_url !~ /^http:\/\//) self.author_url = "http://#{author_url}" end end end
Fix validate_quota method to properly set the request.message for quota exceeded and modified tests to check request.message.
module MiqAeMethodService class MiqAeServiceMiqRequest < MiqAeServiceModelBase require_relative "mixins/miq_ae_service_miq_request_mixin" include MiqAeServiceMiqRequestMixin expose :miq_request_tasks, :association => true expose :requester, :association => true expose :resource, :association => true expose :source, :association => true expose :destination, :association => true expose :tenant, :association => true expose :authorized? expose :approve, :override_return => true expose :deny, :override_return => true expose :pending, :override_return => true # For backward compatibility def miq_request self end association :miq_request def approvers ar_method { wrap_results @object.miq_approvals.collect { |a| a.approver.kind_of?(User) ? a.approver : nil }.compact } end association :approvers def set_message(value) object_send(:update_attributes, :message => value) end def description=(new_description) object_send(:update_attributes, :description => new_description) end end end
module MiqAeMethodService class MiqAeServiceMiqRequest < MiqAeServiceModelBase require_relative "mixins/miq_ae_service_miq_request_mixin" include MiqAeServiceMiqRequestMixin expose :miq_request_tasks, :association => true expose :requester, :association => true expose :resource, :association => true expose :source, :association => true expose :destination, :association => true expose :tenant, :association => true expose :authorized? expose :approve, :override_return => true expose :deny, :override_return => true expose :pending, :override_return => true # For backward compatibility def miq_request self end association :miq_request def approvers ar_method { wrap_results @object.miq_approvals.collect { |a| a.approver.kind_of?(User) ? a.approver : nil }.compact } end association :approvers def set_message(value) object_send(:update_attributes, :message => value.try!(:truncate, 255)) end def description=(new_description) object_send(:update_attributes, :description => new_description) end end end
Sort users list by name
class UsersController < ApplicationController def create @user = User.new(params[:user]) if @user.save redirect_to users_path else render :action => :new end end def edit @user = User.find(params[:id]) end def index @users = User.all end def new @user = User.new @star = Star.new(:to => @user) end def show @user = User.find(params[:id]) @star = Star.new(:to => @user) end def update @user = User.find(params[:id]) if @user.update_attributes(params[:user]) redirect_to users_path else render :action => :edit end end end
class UsersController < ApplicationController def create @user = User.new(params[:user]) if @user.save redirect_to users_path else render :action => :new end end def edit @user = User.find(params[:id]) end def index @users = User.all.sort_by(&:name) end def new @user = User.new @star = Star.new(:to => @user) end def show @user = User.find(params[:id]) @star = Star.new(:to => @user) end def update @user = User.find(params[:id]) if @user.update_attributes(params[:user]) redirect_to users_path else render :action => :edit end end end