Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Refactor duplicate code into method | module GitRecent
require 'thor'
class Cli < Thor
desc 'list', 'List recently checked-out git branches'
def list
recent_branch_names = GitRecent::BranchLister.new.branch_names
abort 'No recent branches' if recent_branch_names.empty?
recent_branch_names.each do |branch_name|
puts branch_name
end
end
desc 'checkout', 'Interactively checkout a recently checked-out git branch'
def checkout
recent_branch_names = GitRecent::BranchLister.new.branch_names
abort 'No recent branches' if recent_branch_names.empty?
chooser = GitRecent::BranchChooser.new recent_branch_names
selected_branch = chooser.request_choice
if selected_branch
Git.open('.').checkout(selected_branch)
end
end
end
end
| module GitRecent
require 'thor'
class Cli < Thor
desc 'list', 'List recently checked-out git branches'
def list
recent_branch_names.each do |branch_name|
puts branch_name
end
end
desc 'checkout', 'Interactively checkout a recently checked-out git branch'
def checkout
chooser = GitRecent::BranchChooser.new recent_branch_names
selected_branch = chooser.request_choice
if selected_branch
Git.open('.').checkout(selected_branch)
end
end
private
def recent_branch_names
recent_branch_names = GitRecent::BranchLister.new.branch_names
abort 'No recent branches' if recent_branch_names.empty?
recent_branch_names
end
end
end
|
Add queue_path method to Batch class | require 'active_support'
module JobBoss
class Batch
attr_accessor :batch_id
extend ActiveSupport::Memoizable
# Used to queue jobs in a batch
# Usage:
# batch.queue.math.is_prime?(42)
def queue
require 'job_boss/queuer'
Queuer.new(:batch_id => @batch_id)
end
memoize :queue
def initialize(batch_id = nil)
@batch_id = batch_id || Batch.generate_batch_id
end
# Returns ActiveRecord::Relation representing query for jobs in batch
def jobs
Job.where('batch_id = ?', @batch_id)
end
# Allow calling of Job class methods from a batch which will be called
# on in the scope of the jobs for the batch
# Examples: wait_for_jobs, result_hash, time_taken, completed_percent
def method_missing(sym, *args, &block)
jobs.send(sym, *args, &block)
end
private
class << self
def generate_batch_id(size = 32)
characters = (0..9).to_a + ('a'..'f').to_a
(1..size).collect do |i|
characters[rand(characters.size)]
end.join
end
end
end
end
| require 'active_support'
module JobBoss
class Batch
attr_accessor :batch_id
extend ActiveSupport::Memoizable
# Used to queue jobs in a batch
# Usage:
# batch.queue.math.is_prime?(42)
def queue
require 'job_boss/queuer'
Queuer.new(:batch_id => @batch_id)
end
memoize :queue
# Used to queue jobs in a batch
# Usage:
# batch.queue_path('math#in_prime?', 42)
def queue_path(path, *args)
controller, action = path.split('#')
queue.send(controller).send(action, *args)
end
def initialize(batch_id = nil)
@batch_id = batch_id || Batch.generate_batch_id
end
# Returns ActiveRecord::Relation representing query for jobs in batch
def jobs
Job.where('batch_id = ?', @batch_id)
end
# Allow calling of Job class methods from a batch which will be called
# on in the scope of the jobs for the batch
# Examples: wait_for_jobs, result_hash, time_taken, completed_percent
def method_missing(sym, *args, &block)
jobs.send(sym, *args, &block)
end
private
class << self
def generate_batch_id(size = 32)
characters = (0..9).to_a + ('a'..'f').to_a
(1..size).collect do |i|
characters[rand(characters.size)]
end.join
end
end
end
end
|
Remove most of the temporary setup. | #!/usr/bin/env ruby -I.
require 'gosu_enhanced'
require 'constants'
require 'resources'
require 'grid'
require 'drawer'
require 'animation'
module ColumnDrop
# Gem drop game
class Game < Gosu::Window
include GosuEnhanced
include Constants
def initialize
super(WIDTH, HEIGHT)
self.caption = "Goody Goody Gem Drop"
@drawer = Drawer.new(self)
reset
# TEMPorary
7.times do |value|
@grid.add_gem(Grid::Point.new(value , 6), value + 1)
@grid.add_gem(Grid::Point.new(0, value), value + 1)
end
@grid.add_gem(36, 12)
@grid.new_waiting_gem
end
def reset
@grid = Grid.new(@drawer)
end
# Indicate that we need the mouse cursor
def needs_cursor?
true
end
def update
end
def draw
@drawer.draw_all
@grid.draw
run_animations
end
def button_down(btn_id)
close if btn_id == Gosu::KbEscape
end
def add_animation(speed, &block)
@animation = Animation.new(speed, block)
end
private
def run_animations
return if @animation.nil?
@animation = nil if @animate.tick == :done
end
end
end
ColumnDrop::Game.new.show
| #!/usr/bin/env ruby -I.
require 'gosu_enhanced'
require 'constants'
require 'resources'
require 'grid'
require 'drawer'
require 'animation'
module ColumnDrop
# Gem drop game
class Game < Gosu::Window
include GosuEnhanced
include Constants
def initialize
super(WIDTH, HEIGHT)
self.caption = "Goody Goody Gem Drops"
@drawer = Drawer.new(self)
reset
end
def reset
@grid = Grid.new(@drawer)
@grid.new_waiting_gem
end
# Indicate that we need the mouse cursor
def needs_cursor?
true
end
def update
end
def draw
@drawer.draw_all
@grid.draw
run_animations
end
def button_down(btn_id)
close if btn_id == Gosu::KbEscape
end
def add_animation(speed, &block)
@animation = Animation.new(speed, block)
end
private
def run_animations
return if @animation.nil?
@animation = nil if @animate.tick == :done
end
end
end
ColumnDrop::Game.new.show
|
Set the Game owner's player name when creating a game. | class GamesController < ApplicationController
before_action :authenticate_user!, except: :events
def index
end
def create
@game = current_user.games.create
end
def start
@game = current_user.games.find(params[:id])
@game.start
end
def events
game = Game.find(params[:id])
render json: game.events(params[:prev_event])
end
def join
game = current_user.game_invites.find_by(game_id: params[:id])
game.add_player(current_user, current_user.name)
end
def bid
game = current_user.games.find(params[:id])
number = params[:number]
face_value = params[:face_value]
errors = []
errors << "The bid must include a total number." unless number
errors << "The bid must include a valid total number." unless number =~ /\A\d+\z/
errors << "The bid must include a face value." unless face_value =~ /\A\d+\z/
errors << "The bid must include a valid face value." unless face_value =~ /\A\d+\z/
render status: 400, json: {errors: errors} and return if errors.any?
bid = Bid.new(number.to_i, face_value.to_i)
game.bid(current_user, bid)
end
def bs
game = current_user.games.find(params[:id])
game.bs(current_user)
end
end
| class GamesController < ApplicationController
before_action :authenticate_user!, except: :events
def index
end
def create
@game = current_user.games.create
end
def start
@game = current_user.games.find(params[:id])
player = @game.player_for(current_user)
name = params[:name]
name = current_user.name if name.blank?
player.update_attributes(name: name)
@game.start
end
def events
game = Game.find(params[:id])
render json: game.events(params[:prev_event])
end
def join
game = current_user.game_invites.find_by(game_id: params[:id])
game.add_player(current_user, current_user.name)
end
def bid
game = current_user.games.find(params[:id])
number = params[:number]
face_value = params[:face_value]
errors = []
errors << "The bid must include a total number." unless number
errors << "The bid must include a valid total number." unless number =~ /\A\d+\z/
errors << "The bid must include a face value." unless face_value =~ /\A\d+\z/
errors << "The bid must include a valid face value." unless face_value =~ /\A\d+\z/
render status: 400, json: {errors: errors} and return if errors.any?
bid = Bid.new(number.to_i, face_value.to_i)
game.bid(current_user, bid)
end
def bs
game = current_user.games.find(params[:id])
game.bs(current_user)
end
end
|
Include a SHA256 of each file in the data list | json.array! @bot_data do |data|
json.key data.key
json.created_at data.created_at
json.updated_at data.updated_at
end
| json.array! @bot_data do |data|
json.key data.key
json.created_at data.created_at
json.updated_at data.updated_at
json.sha256 Digest::SHA256.hexdigest(data.data)
end
|
Remove unused config for tests | CarrierWave.configure do |config|
if Rails.env.production?
config.asset_host = 'http://infra.stru.ctu.re';
else
config.asset_host = 'http://localhost:4000';
end
end
if Rails.env.test?
Dir["#{Rails.root}/app/uploaders/*.rb"].each { |file| require file }
if defined?(CarrierWave)
CarrierWave::Uploader::Base.descendants.each do |klass|
next if klass.anonymous?
klass.class_eval do
def cache_dir
"#{Rails.root}/spec/support/uploads/tmp"
end
def store_dir
"#{Rails.root}/spec/support/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
end
end
end
| CarrierWave.configure do |config|
if Rails.env.production?
config.asset_host = 'http://infra.stru.ctu.re';
else
config.asset_host = 'http://localhost:4000';
end
end
|
Configure helpers admin index page. | ActiveAdmin.register User do
member_action :become, method: :get do
begin
user = User.find(params[:id])
login(user)
redirect_to root_path
rescue
redirect_to :back, notice: "Unable to become user with id #{params[:id]}"
end
end
action_item :become, only: :show do
link_to 'Become this User', become_admin_user_path
end
end
| ActiveAdmin.register User do
index do
selectable_column
column :id
column :first_name
column :last_name
column :primary_circle_id
column :language
column :is_admin
column :public_profile
column :last_login
actions
end
member_action :become, method: :get do
begin
user = User.find(params[:id])
login(user)
redirect_to root_path
rescue
redirect_to :back, notice: "Unable to become user with id #{params[:id]}"
end
end
action_item :become, only: :show do
link_to 'Become this User', become_admin_user_path
end
end
|
Replace `render :nothing` with `head` | module TwoFactorAuthentication
module Controllers
module Helpers
extend ActiveSupport::Concern
included do
before_action :handle_two_factor_authentication
end
private
def handle_two_factor_authentication
unless devise_controller?
Devise.mappings.keys.flatten.any? do |scope|
if signed_in?(scope) and warden.session(scope)[TwoFactorAuthentication::NEED_AUTHENTICATION]
handle_failed_second_factor(scope)
end
end
end
end
def handle_failed_second_factor(scope)
if request.format.present? and request.format.html?
session["#{scope}_return_to"] = request.original_fullpath if request.get?
redirect_to two_factor_authentication_path_for(scope)
else
render nothing: true, status: :unauthorized
end
end
def two_factor_authentication_path_for(resource_or_scope = nil)
scope = Devise::Mapping.find_scope!(resource_or_scope)
change_path = "#{scope}_two_factor_authentication_path"
send(change_path)
end
end
end
end
module Devise
module Controllers
module Helpers
def is_fully_authenticated?
!session["warden.user.user.session"].try(:[], TwoFactorAuthentication::NEED_AUTHENTICATION)
end
end
end
end
| module TwoFactorAuthentication
module Controllers
module Helpers
extend ActiveSupport::Concern
included do
before_action :handle_two_factor_authentication
end
private
def handle_two_factor_authentication
unless devise_controller?
Devise.mappings.keys.flatten.any? do |scope|
if signed_in?(scope) and warden.session(scope)[TwoFactorAuthentication::NEED_AUTHENTICATION]
handle_failed_second_factor(scope)
end
end
end
end
def handle_failed_second_factor(scope)
if request.format.present? and request.format.html?
session["#{scope}_return_to"] = request.original_fullpath if request.get?
redirect_to two_factor_authentication_path_for(scope)
else
head :unauthorized
end
end
def two_factor_authentication_path_for(resource_or_scope = nil)
scope = Devise::Mapping.find_scope!(resource_or_scope)
change_path = "#{scope}_two_factor_authentication_path"
send(change_path)
end
end
end
end
module Devise
module Controllers
module Helpers
def is_fully_authenticated?
!session["warden.user.user.session"].try(:[], TwoFactorAuthentication::NEED_AUTHENTICATION)
end
end
end
end
|
Remove debug comment from script loader | class BrowserScriptLoader
def run
handler = proc { find_scripts }
if $global.respond_to? :addEventListener
$global.addEventListener 'DOMContentLoaded', handler, false
elsif @global.respond_to? :attachEvent
$global.attachEvent 'onload', handler
end
end
def find_scripts
ruby_scripts.each do |script|
if src = script.src and src != ""
puts "Cannot currently load remote script: #{src}"
else
run_ruby script.innerHTML
end
end
end
def ruby_scripts
$global.document.getElementsByTagName('script').to_a.select { |s|
s.type == "text/ruby" }
end
def run_ruby str
$global.Opal.eval str
end
end
if $global.respond_to? :document
BrowserScriptLoader.new.run
end if false
| class BrowserScriptLoader
def run
handler = proc { find_scripts }
if $global.respond_to? :addEventListener
$global.addEventListener 'DOMContentLoaded', handler, false
elsif @global.respond_to? :attachEvent
$global.attachEvent 'onload', handler
end
end
def find_scripts
ruby_scripts.each do |script|
if src = script.src and src != ""
puts "Cannot currently load remote script: #{src}"
else
run_ruby script.innerHTML
end
end
end
def ruby_scripts
$global.document.getElementsByTagName('script').to_a.select { |s|
s.type == "text/ruby" }
end
def run_ruby str
$global.Opal.eval str
end
end
if $global.respond_to? :document
BrowserScriptLoader.new.run
end
|
Change POST to GET for ipn controller route | Spree::Core::Engine.routes.draw do
post 'amazon/fps' => 'amazon#fps'
post 'amazon/ipn' => 'amazon#ipn'
get 'amazon/complete' => 'amazon#complete'
get 'amazon/abort' => 'amazon#abort'
namespace :admin do
resources :orders, only: [] do
resources :payments, only: [] do
member do
get 'amazon_refund'
post 'amazon_refund'
end
end
end
end
end
| Spree::Core::Engine.routes.draw do
post 'amazon/fps' => 'amazon#fps'
get 'amazon/ipn' => 'amazon#ipn'
get 'amazon/complete' => 'amazon#complete'
get 'amazon/abort' => 'amazon#abort'
namespace :admin do
resources :orders, only: [] do
resources :payments, only: [] do
member do
get 'amazon_refund'
post 'amazon_refund'
end
end
end
end
end
|
Include rake in gemspec (available to bundle exec) | # -*- encoding: utf-8 -*-
Gem::Specification.new do |gem|
gem.authors = ["John Bintz"]
gem.email = ["john@coswellproductions.com"]
gem.description = %q{Get the vendored assets paths in gems.}
gem.summary = %q{Get the vendored assets paths in gems.}
gem.homepage = ""
gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
gem.files = `git ls-files`.split("\n")
gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
gem.name = "sprockets-vendor_gems"
gem.require_paths = ["lib"]
gem.version = '0.1.1'
gem.required_rubygems_version = '>= 1.8.0'
gem.add_dependency 'sprockets'
gem.add_development_dependency 'rspec'
gem.add_development_dependency 'mocha'
gem.add_development_dependency 'fakefs'
end
| # -*- encoding: utf-8 -*-
Gem::Specification.new do |gem|
gem.authors = ["John Bintz"]
gem.email = ["john@coswellproductions.com"]
gem.description = %q{Get the vendored assets paths in gems.}
gem.summary = %q{Get the vendored assets paths in gems.}
gem.homepage = ""
gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
gem.files = `git ls-files`.split("\n")
gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
gem.name = "sprockets-vendor_gems"
gem.require_paths = ["lib"]
gem.version = '0.1.1'
gem.required_rubygems_version = '>= 1.8.0'
gem.add_dependency 'sprockets'
gem.add_development_dependency 'rake'
gem.add_development_dependency 'rspec'
gem.add_development_dependency 'mocha'
gem.add_development_dependency 'fakefs'
end
|
Set spec type to controller | require 'rails_helper'
RSpec.describe EventsController do
describe 'create' do
end
end
| require 'rails_helper'
RSpec.describe EventsController, type: :controller do
describe 'create' do
end
end
|
Enable to load rails yaml file | # -*- coding: utf-8 -*-
require 'yaml'
module BankWorkingDay
class Holiday
def initialize(date, name)
@date = date
@name = name
end
end
class Holidays
attr_accessor :holidays, :bank_holidays
HOLIDAY_WDAYS = [0, 6].freeze
def initialize
@holidays = set_holiday('holidays.yml')
@bank_holidays = set_holiday('bank_holidays.yml')
end
def holiday?(date)
holidays[date] || bank_holidays[date] || date.wday.in?(HOLIDAY_WDAYS)
end
private
def set_holiday(yml)
yaml = YAML.load_file(File.expand_path("../../../#{yml}", __FILE__))
yaml.each_with_object({}) do |(key, value), hash|
hash[key] = Holiday.new(key, value)
end
end
end
end
| # -*- coding: utf-8 -*-
require 'yaml'
module BankWorkingDay
class Holiday
def initialize(date, name)
@date = date
@name = name
end
end
class Holidays
attr_accessor :holidays, :bank_holidays
HOLIDAY_WDAYS = [0, 6].freeze
def initialize
@holidays = set_holiday(holidays_path)
@bank_holidays = set_holiday('../../../bank_holidays.yml')
end
def holiday?(date)
holidays[date] || bank_holidays[date] || date.wday.in?(HOLIDAY_WDAYS)
end
private
# Rails側に祝日のYAMLファイルがあれば優先する
def holidays_path
path = Rails.root.to_s + '/config/holidays.yml'
File.exist?(path) ? path : '../../../holidays.yml'
end
def set_holiday(path)
yaml = YAML.load_file(File.expand_path(path, __FILE__))
yaml.each_with_object({}) do |(key, value), hash|
hash[key] = Holiday.new(key, value)
end
end
end
end
|
Update chef client to 13.9.4 | # Add the opscode APT source for chef
default[:apt][:sources] = node[:apt][:sources] | ["opscode"]
# Set the default server version
default[:chef][:server][:version] = "12.13.0-1"
# Set the default client version
default[:chef][:client][:version] = "13.8.5"
| # Add the opscode APT source for chef
default[:apt][:sources] = node[:apt][:sources] | ["opscode"]
# Set the default server version
default[:chef][:server][:version] = "12.13.0-1"
# Set the default client version
default[:chef][:client][:version] = "13.9.4"
|
Add delete method to RRCache | require_relative 'base_cache'
module Cache
# Randomly selects a candidate item and discards it to make space when necessary.
# This algorithm does not require keeping any information about the access history.
class RRCache < BaseCache
attr_accessor :size
attr_accessor :cache
def initialize(size)
super(size)
end
def [](key)
if @cache.has_key?(key)
@cache[key]
else
nil
end
end
def []=(key, value)
if @cache.size >= @size
@cache.delete(@cache.values[rand(@cache.length)])
end
@cache[key] = value
end
end
end | require_relative 'base_cache'
module Cache
# Randomly selects a candidate item and discards it to make space when necessary.
# This algorithm does not require keeping any information about the access history.
class RRCache < BaseCache
attr_accessor :size
attr_accessor :cache
def initialize(size)
super(size)
end
def [](key)
if @cache.has_key?(key)
@cache[key]
else
nil
end
end
def []=(key, value)
if @cache.size >= @size
@cache.delete(@cache.values[rand(@cache.length)])
end
@cache[key] = value
end
def delete(key)
if @cache.has_key?(key)
@cache.delete(key)
end
end
end
end |
Include config directory in gem file | # -*- encoding: utf-8 -*-
$:.push File.expand_path('../lib', __FILE__)
require 'scss_lint/constants'
require 'scss_lint/version'
Gem::Specification.new do |s|
s.name = 'scss-lint'
s.version = SCSSLint::VERSION
s.license = 'MIT'
s.platform = Gem::Platform::RUBY
s.authors = ['Causes Engineering', 'Shane da Silva']
s.email = ['eng@causes.com', 'shane@causes.com']
s.homepage = SCSSLint::REPO_URL
s.summary = 'SCSS lint tool'
s.description = 'Opinionated tool to help write clean and consistent SCSS'
s.files = Dir['lib/**/*.rb']
s.executables = ['scss-lint']
s.require_paths = ['lib']
s.required_ruby_version = '>= 1.9.3'
s.add_dependency 'colorize', '0.5.8'
s.add_dependency 'sass', '3.3.0.rc.1' # Hard dependency since we monkey patch AST
s.add_development_dependency 'nokogiri', '1.6.0'
s.add_development_dependency 'rspec', '2.13.0'
end
| # -*- encoding: utf-8 -*-
$:.push File.expand_path('../lib', __FILE__)
require 'scss_lint/constants'
require 'scss_lint/version'
Gem::Specification.new do |s|
s.name = 'scss-lint'
s.version = SCSSLint::VERSION
s.license = 'MIT'
s.platform = Gem::Platform::RUBY
s.authors = ['Causes Engineering', 'Shane da Silva']
s.email = ['eng@causes.com', 'shane@causes.com']
s.homepage = SCSSLint::REPO_URL
s.summary = 'SCSS lint tool'
s.description = 'Opinionated tool to help write clean and consistent SCSS'
s.files = Dir['config/**/*.yml'] + Dir['lib/**/*.rb']
s.executables = ['scss-lint']
s.require_paths = ['lib']
s.required_ruby_version = '>= 1.9.3'
s.add_dependency 'colorize', '0.5.8'
s.add_dependency 'sass', '3.3.0.rc.1' # Hard dependency since we monkey patch AST
s.add_development_dependency 'nokogiri', '1.6.0'
s.add_development_dependency 'rspec', '2.13.0'
end
|
Use File to grab yml redis file | # Load the redis configuration from resque.yml
Resque.redis = YAML.load_file(Rails.root.join("/config/resque.yml"))[Rails.env.to_s]
| # Load the redis configuration from resque.yml
Resque.redis = YAML.load_file(File.join(Rails.root, "config", "resque.yml"))[Rails.env.to_s]
|
Add "Seth Wright" to spec.authors | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'authlete/version'
Gem::Specification.new do |spec|
spec.name = "authlete"
spec.version = Authlete::VERSION
spec.authors = ["Takahiko Kawasaki", "Hideki Ikeda"]
spec.email = ["admin@authlete.com"]
spec.summary = "A library for Authlete Web APIs"
spec.description = "A library for Authlete Web APIs. See https://docs.authlete.com/ for details."
spec.homepage = "https://www.authlete.com/"
spec.license = "Apache License, Version 2.0"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "rest-client", ">= 1.7.2"
spec.add_development_dependency "bundler", ">= 2.2.10"
spec.add_development_dependency "rake", ">= 12.3.3"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'authlete/version'
Gem::Specification.new do |spec|
spec.name = "authlete"
spec.version = Authlete::VERSION
spec.authors = ["Takahiko Kawasaki", "Hideki Ikeda", "Seth Wright"]
spec.email = ["admin@authlete.com"]
spec.summary = "A library for Authlete Web APIs"
spec.description = "A library for Authlete Web APIs. See https://docs.authlete.com/ for details."
spec.homepage = "https://www.authlete.com/"
spec.license = "Apache License, Version 2.0"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "rest-client", ">= 1.7.2"
spec.add_development_dependency "bundler", ">= 2.2.10"
spec.add_development_dependency "rake", ">= 12.3.3"
end
|
Remove RUBY_VERSION check for ruby 1.8 | # Ubuntu does not accept arguments to ruby when called using env. To get warnings to show up the -w options is
# required. That can be set in the RUBYOPT environment variable.
# export RUBYOPT=-w
$VERBOSE = true
%w(lib ext test).each do |dir|
$LOAD_PATH.unshift File.expand_path("../../#{dir}", __FILE__)
end
require 'rubygems' if RUBY_VERSION.start_with?('1.8.')
require 'minitest'
require 'minitest/autorun'
require 'stringio'
require 'date'
require 'bigdecimal'
require 'pp'
require 'oj'
$ruby = RUBY_DESCRIPTION.split(' ')[0]
$ruby = 'ree' if 'ruby' == $ruby && RUBY_DESCRIPTION.include?('Ruby Enterprise Edition')
class Range
def to_hash()
{ 'begin' => self.begin, 'end' => self.end, 'exclude_end' => self.exclude_end? }
end
end
| # Ubuntu does not accept arguments to ruby when called using env. To get warnings to show up the -w options is
# required. That can be set in the RUBYOPT environment variable.
# export RUBYOPT=-w
$VERBOSE = true
%w(lib ext test).each do |dir|
$LOAD_PATH.unshift File.expand_path("../../#{dir}", __FILE__)
end
require 'minitest'
require 'minitest/autorun'
require 'stringio'
require 'date'
require 'bigdecimal'
require 'pp'
require 'oj'
$ruby = RUBY_DESCRIPTION.split(' ')[0]
$ruby = 'ree' if 'ruby' == $ruby && RUBY_DESCRIPTION.include?('Ruby Enterprise Edition')
class Range
def to_hash()
{ 'begin' => self.begin, 'end' => self.end, 'exclude_end' => self.exclude_end? }
end
end
|
Allow puppet-lint 2.0 as a dependency and bump check version | Gem::Specification.new do |spec|
spec.name = 'puppet-lint-no_erb_template-check'
spec.version = '0.1.0'
spec.homepage = 'https://github.com/deanwilson/puppet-lint-no_erb_template-check'
spec.license = 'MIT'
spec.author = 'Dean Wilson'
spec.email = 'dean.wilson@gmail.com'
spec.files = Dir[
'README.md',
'LICENSE',
'lib/**/*',
'spec/**/*',
]
spec.test_files = Dir['spec/**/*']
spec.summary = 'puppet-lint no_erb_template check'
spec.description = <<-EOF
Extends puppet-lint to ensure there are no calls to the template
or inline_template function as an aid to migrating to epp templates.
EOF
spec.add_dependency 'puppet-lint', '~> 1.1'
spec.add_development_dependency 'rspec', '~> 3.0'
spec.add_development_dependency 'rspec-its', '~> 1.0'
spec.add_development_dependency 'rspec-collection_matchers', '~> 1.0'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'pry'
spec.add_development_dependency 'rubocop'
end
| Gem::Specification.new do |spec|
spec.name = 'puppet-lint-no_erb_template-check'
spec.version = '0.1.1'
spec.homepage = 'https://github.com/deanwilson/puppet-lint-no_erb_template-check'
spec.license = 'MIT'
spec.author = 'Dean Wilson'
spec.email = 'dean.wilson@gmail.com'
spec.files = Dir[
'README.md',
'LICENSE',
'lib/**/*',
'spec/**/*',
]
spec.test_files = Dir['spec/**/*']
spec.summary = 'puppet-lint no_erb_template check'
spec.description = <<-EOF
Extends puppet-lint to ensure there are no calls to the template
or inline_template function as an aid to migrating to epp templates.
EOF
spec.add_dependency 'puppet-lint', '>= 1.1', '< 3.0'
spec.add_development_dependency 'rspec', '~> 3.0'
spec.add_development_dependency 'rspec-its', '~> 1.0'
spec.add_development_dependency 'rspec-collection_matchers', '~> 1.0'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'pry'
spec.add_development_dependency 'rubocop'
end
|
Replace manual requests with Octokit API in commit job. | require 'net/http'
require 'json'
require 'octokit'
projects = settings.projects || []
SCHEDULER.every '1h' do
client = Octokit::Client.new(:access_token => settings.github['token'])
user = client.user
user.login
name = projects.first['repo']
url_base = "https://api.github.com/repos/" + projects.first['repo']
# Put together the branches url
branches_url = URI(url_base + "/git/refs/heads/" + projects.first['branch'])
latest_sha = latest_committer = commit_message = commit_date = nil
# Use the branches URL to get the latest commit sha for the branch
Net::HTTP.start(branches_url.host, branches_url.port, :use_ssl => (branches_url.scheme == 'https')) do |http|
response = http.request(Net::HTTP::Get.new(branches_url.request_uri))
data = JSON.parse(response.body)
latest_sha = data['object']['sha']
end
# Commit URL
commit_url = URI(url_base + "/commits/" + latest_sha)
Net::HTTP::start(commit_url.host, commit_url.port, :use_ssl => commit_url.scheme == 'https') do |http|
response = http.request(Net::HTTP::Get.new(commit_url.request_uri))
data = JSON.parse(response.body)
latest_committer = data['commit']['committer']['name']
commit_message = data['commit']['message']
commit_message = commit_message.split[0...15].join(' ')
commit_date = Time.parse(data['commit']['committer']['date']).strftime("%a %b %e %Y")
end
send_event('commits', { project:
{name: name,
committer: latest_committer,
commit_message: commit_message,
date: commit_date
}
})
projects.rotate!
end
| require 'net/http'
require 'json'
require 'octokit'
projects = settings.projects || []
SCHEDULER.every '1h' do
client = Octokit::Client.new(:access_token => settings.github['token'])
project = projects.first['name']
latest_sha = latest_committer = commit_message = commit_date = nil
# SHA hash
data = client.ref(project, 'heads/' + projects.first['branch'])
latest_sha = data['object']['sha']
# Commit
data = client.git_commit(project, latest_sha)
latest_committer = data['committer']['name']
commit_message = data['message']
commit_message = commit_message.split[0...15].join(' ')
commit_date = Time.parse(data['committer']['date']).strftime('%a %b %e %Y')
send_event('commits',
{
project: {
name: name,
committer: latest_committer,
commit_message: commit_message,
date: commit_date
}
}
)
projects.rotate!
end
|
Use the new DM.append_extensions hook | require "rubygems"
require "pathname"
gem "dm-core", ">=0.10.0"
require "dm-core"
module DataMapper
module Is
module Polymorphic
def is_polymorphic(name, id_type=String)
self.class_eval <<-EOS, __FILE__, __LINE__
property :"#{name}_class", Klass
property :"#{name}_id", #{id_type}
def #{name}
return nil if self.#{name}_class.nil? || self.#{name}_class == NilClass
return nil if self.#{name}_id.nil?
if (self.#{name}_class.class == Class)
self.#{name}_class.get(self.#{name}_id)
else
klass = Kernel.const_get(self.#{name}_class.to_s)
if klass.ancestors.include? DataMapper::Resource
klass.get(self.#{name}_id)
else
nil
end
end
end
def #{name}=(entity)
self.#{name}_class = entity.class
self.#{name}_id = entity.id
end
EOS
end
end # Polymophic
end # Is
module Resource
module ClassMethods
include DataMapper::Is::Polymorphic
end # module ClassMethods
end # module Resource
end
require Pathname(__FILE__).dirname.expand_path / "associations.rb"
require Pathname(__FILE__).dirname.expand_path / "types.rb"
| require "rubygems"
require "pathname"
gem "dm-core", ">=0.10.0"
require "dm-core"
module DataMapper
module Is
module Polymorphic
def is_polymorphic(name, id_type=String)
self.class_eval <<-EOS, __FILE__, __LINE__
property :"#{name}_class", Klass
property :"#{name}_id", #{id_type}
def #{name}
return nil if self.#{name}_class.nil? || self.#{name}_class == NilClass
return nil if self.#{name}_id.nil?
if (self.#{name}_class.class == Class)
self.#{name}_class.get(self.#{name}_id)
else
klass = Kernel.const_get(self.#{name}_class.to_s)
if klass.ancestors.include? DataMapper::Resource
klass.get(self.#{name}_id)
else
nil
end
end
end
def #{name}=(entity)
self.#{name}_class = entity.class
self.#{name}_id = entity.id
end
EOS
end
end # Polymophic
end # Is
end
DataMapper::Model.append_extensions DataMapper::Is::Polymorphic
require Pathname(__FILE__).dirname.expand_path / "associations.rb"
require Pathname(__FILE__).dirname.expand_path / "types.rb"
|
Update front-end tests to support new connect page | require File.join(File.expand_path(File.dirname(__FILE__)), '../spec_helper.rb')
#describe 'home page', :type => :request do
describe 'dashboard' do
it 'allows people to switch between 4 views' do
visit '/'
page.should have_css('.iframeLink[data-id="You-contactsviewer"]')
page.execute_script("$('.iframeLink[data-id=\"You-contactsviewer\"]').click()")
within_frame 'appFrame' do
page.should have_content('Jeremie')
end
page.execute_script("$('.iframeLink[data-id=\"You-photosv09\"]').click()")
page.should have_css('.iframeLink.blue[data-id="You-photosv09"]')
within_frame 'appFrame' do
page.should have_content('Photos')
end
page.execute_script("$('.iframeLink[data-id=\"You-linkalatte\"]').click()")
page.should have_css('.iframeLink.blue[data-id="You-linkalatte"]')
within_frame 'appFrame' do
page.should have_content('Links')
end
page.execute_script("$('.iframeLink[data-id=\"You-helloplaces\"]').click()")
page.should have_css('.iframeLink.blue[data-id="You-helloplaces"]')
within_frame 'appFrame' do
page.should have_content('Places')
end
end
it 'should allow people to access the create interface' do
visit '/'
click_link 'CREATE'
page.should have_content('Getting Started')
end
it 'should allow access to api explorer' do
visit '/'
click_link 'CREATE'
click_link 'Getting Started'
within_frame 'appFrame' do
page.should have_content('Make your own viewer!')
click_on 'API Explorer'
page.should have_content('API Explorer')
end
end
end
| require File.join(File.expand_path(File.dirname(__FILE__)), '../spec_helper.rb')
#describe 'home page', :type => :request do
describe 'dashboard' do
it 'allows people to see the connect page' do
visit '/'
within_frame 'appFrame' do
page.should have_content('Welcome! Connect services to begin.')
end
end
it 'should allow people to access the create interface' do
visit '/'
click_link 'CREATE'
page.should have_content('Getting Started')
end
it 'should allow access to api explorer' do
visit '/'
click_link 'CREATE'
click_link 'Getting Started'
within_frame 'appFrame' do
page.should have_content('Make your own viewer!')
click_on 'API Explorer'
page.should have_content('API Explorer')
end
end
end
|
Fix pass options to provider in example | require 'pp'
require 'sinatra'
require 'omniauth'
require 'omniauth-vkontakte'
configure { set :server, :puma }
SCOPE = 'friends,audio'
use Rack::Session::Cookie
use OmniAuth::Builder do
provider :vkontakte, ENV['VKONTAKTE_KEY'], ENV['VKONTAKTE_SECRET']
{
scope: SCOPE,
display: 'web',
lang: 'en',
image_size: 'original'
}
end
get '/' do
<<-HTML
<ul>
<li><a href='/auth/vkontakte'>Sign in with VKontakte</a></li>
</ul>
HTML
end
get '/auth/:provider/callback' do
content_type 'text/plain'
pp request.env['omniauth.auth']
request.env['omniauth.auth'].info.to_hash.inspect
end
| require 'pp'
require 'sinatra'
require 'omniauth'
require 'omniauth-vkontakte'
configure { set :server, :puma }
SCOPE = 'friends,audio'
use Rack::Session::Cookie
use OmniAuth::Builder do
provider :vkontakte, ENV['VKONTAKTE_KEY'], ENV['VKONTAKTE_SECRET'],
{
scope: SCOPE,
display: 'popup',
lang: 'en',
image_size: 'original'
}
end
get '/' do
<<-HTML
<ul>
<li><a href='/auth/vkontakte'>Sign in with VKontakte</a></li>
</ul>
HTML
end
get '/auth/:provider/callback' do
content_type 'text/plain'
pp request.env['omniauth.auth']
request.env['omniauth.auth'].info.to_hash.inspect
end
|
Remove unnecessary loading of Rails env | ENV['RAILS_ENV'] = 'test'
ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
require 'test/unit'
require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb'))
| require 'rubygems'
require 'active_support'
require 'test/unit'
require File.join(File.dirname(__FILE__), '..', 'lib', 'lucy')
|
Clean up test helper script | ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
end
| # Encoding: utf-8
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
# Extension for ActiveSupport?
class ActiveSupport
# Test cases for ActiveSupport
class TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical
# order.
fixtures :all
# Add more helper methods to be used by all tests here...
end
end
|
Add 0.5 weight to VoteConnection | class VoteConnection < ActiveRecord::Base
WEIGHTS = [0, 1, 2, 4]
belongs_to :vote
belongs_to :topic
attr_accessible :vote, :vote_id, :topic, :matches, :comment, :weight, :description
validates_presence_of :vote, :topic, :weight
validates_inclusion_of :weight, :in => WEIGHTS
def matches_text
matches? ? I18n.t('app.yes') : I18n.t('app.no')
end
end
| class VoteConnection < ActiveRecord::Base
WEIGHTS = [0, 0.5, 1, 2, 4]
belongs_to :vote
belongs_to :topic
attr_accessible :vote, :vote_id, :topic, :matches, :comment, :weight, :description
validates_presence_of :vote, :topic, :weight
validates_inclusion_of :weight, :in => WEIGHTS
def matches_text
matches? ? I18n.t('app.yes') : I18n.t('app.no')
end
end
|
Use ArgumentError vs. RuntimeError, which is more precise. | require 'abstract_controller/collector'
require 'active_support/core_ext/hash/reverse_merge'
require 'active_support/core_ext/array/extract_options'
module ActionMailer #:nodoc:
class Collector
include AbstractController::Collector
attr_reader :responses
def initialize(context, &block)
@context = context
@responses = []
@default_render = block
end
def any(*args, &block)
options = args.extract_options!
raise "You have to supply at least one format" if args.empty?
args.each { |type| send(type, options.dup, &block) }
end
alias :all :any
def custom(mime, options={})
options.reverse_merge!(:content_type => mime.to_s)
@context.formats = [mime.to_sym]
options[:body] = block_given? ? yield : @default_render.call
@responses << options
end
end
end
| require 'abstract_controller/collector'
require 'active_support/core_ext/hash/reverse_merge'
require 'active_support/core_ext/array/extract_options'
module ActionMailer #:nodoc:
class Collector
include AbstractController::Collector
attr_reader :responses
def initialize(context, &block)
@context = context
@responses = []
@default_render = block
end
def any(*args, &block)
options = args.extract_options!
raise ArgumentError, "You have to supply at least one format" if args.empty?
args.each { |type| send(type, options.dup, &block) }
end
alias :all :any
def custom(mime, options={})
options.reverse_merge!(:content_type => mime.to_s)
@context.formats = [mime.to_sym]
options[:body] = block_given? ? yield : @default_render.call
@responses << options
end
end
end
|
Use company addresses for all authors | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'webpay/version'
Gem::Specification.new do |spec|
spec.name = 'webpay'
spec.version = WebPay::VERSION
spec.authors = ['webpay', 'tomykaira']
spec.email = ['administrators@webpay.jp', 'tomykaira@gmail.com']
spec.description = 'WebPay is payment gateway service in Japan. see also https://webpay.jp/'
spec.summary = 'Ruby bindings of WebPay API'
spec.homepage = 'https://webpay.jp'
spec.license = 'MIT'
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_dependency 'faraday', '~> 0.8.7'
spec.add_development_dependency 'bundler', '~> 1.3'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'yard', '~> 0.8.6.2'
spec.add_development_dependency 'redcarpet', '~> 3.0.0'
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'webpay/version'
Gem::Specification.new do |spec|
spec.name = 'webpay'
spec.version = WebPay::VERSION
spec.authors = ['webpay', 'tomykaira']
spec.email = ['administrators@webpay.jp', 'tomykaira@webpay.jp']
spec.description = 'WebPay is payment gateway service in Japan. see also https://webpay.jp/'
spec.summary = 'Ruby bindings of WebPay API'
spec.homepage = 'https://webpay.jp'
spec.license = 'MIT'
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_dependency 'faraday', '~> 0.8.7'
spec.add_development_dependency 'bundler', '~> 1.3'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'yard', '~> 0.8.6.2'
spec.add_development_dependency 'redcarpet', '~> 3.0.0'
end
|
Use require_dependency instead, so that it interacts with rails better. | load RAILS_ROOT + "/vendor/plugins/rites_portal/app/models/user.rb"
class User < ActiveRecord::Base
has_many :investigations
has_many :activities
has_many :sections
has_many :pages
has_many :data_collectors
has_many :xhtmls
has_many :open_responses
has_many :multiple_choices
has_many :data_tables
has_many :drawing_tools
has_many :mw_modeler_pages
has_many :n_logo_models
# has_many :assessment_targets
# has_many :big_ideas
# has_many :domains
# has_many :expectations
# has_many :expectation_stems
# has_many :grade_span_expectations
# has_many :knowledge_statements
# has_many :unifying_themes
include Changeable
def removed_investigation
unless self.has_investigations?
self.remove_role('author')
end
end
def has_investigations?
investigations.length > 0
end
# return the user who is the site administrator
def self.site_admin
User.find_by_email(APP_CONFIG[:admin_email])
end
end | require_dependency RAILS_ROOT + "/vendor/plugins/rites_portal/app/models/user.rb"
class User < ActiveRecord::Base
has_many :investigations
has_many :activities
has_many :sections
has_many :pages
has_many :data_collectors
has_many :xhtmls
has_many :open_responses
has_many :multiple_choices
has_many :data_tables
has_many :drawing_tools
has_many :mw_modeler_pages
has_many :n_logo_models
# has_many :assessment_targets
# has_many :big_ideas
# has_many :domains
# has_many :expectations
# has_many :expectation_stems
# has_many :grade_span_expectations
# has_many :knowledge_statements
# has_many :unifying_themes
include Changeable
def removed_investigation
unless self.has_investigations?
self.remove_role('author')
end
end
def has_investigations?
investigations.length > 0
end
# return the user who is the site administrator
def self.site_admin
User.find_by_email(APP_CONFIG[:admin_email])
end
end |
Disable index.html caching until login resolved. | class DisplaysController < ApplicationController
caches_page :index
def index
render :layout => 'full_map'
end
def kml
#Generate route information
@routes = Route.find(:all, :conditions => {:enabled => true})
#Generate stop information
@stops = Stop.find(:all, :group => :id, :joins => :routes, :conditions => {:enabled => true, 'routes.enabled' => true})
respond_to do |format|
format.kml { render :layout => false }
end
end
def locations
case params[:active]
when "Online" then
@shuttles = Shuttle.find(:all, :conditions => {:enabled => true, :active => true})
when "Offline" then
@shuttles = Shuttle.find(:all, :conditions => {:enabled => true, :active => false})
when "All" then
@shuttles = Shuttle.find(:all, :conditions => {:enabled => true})
else
@shuttles = Shuttle.find(:all, :conditions => {:enabled => true})
end
respond_to do |format|
format.xml
format.html
end
end
end
| class DisplaysController < ApplicationController
def index
render :layout => 'full_map'
end
def kml
#Generate route information
@routes = Route.find(:all, :conditions => {:enabled => true})
#Generate stop information
@stops = Stop.find(:all, :group => :id, :joins => :routes, :conditions => {:enabled => true, 'routes.enabled' => true})
respond_to do |format|
format.kml { render :layout => false }
end
end
def locations
case params[:active]
when "Online" then
@shuttles = Shuttle.find(:all, :conditions => {:enabled => true, :active => true})
when "Offline" then
@shuttles = Shuttle.find(:all, :conditions => {:enabled => true, :active => false})
when "All" then
@shuttles = Shuttle.find(:all, :conditions => {:enabled => true})
else
@shuttles = Shuttle.find(:all, :conditions => {:enabled => true})
end
respond_to do |format|
format.xml
format.html
end
end
end
|
Make it work with JRuby | # Maintain your gem's version:
require_relative 'lib/rocket_job_mission_control/version'
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = 'rocketjob_mission_control'
s.version = RocketJobMissionControl::VERSION
s.authors = ['Michael Cloutier', 'Chris Lamb']
s.email = ['']
s.homepage = 'https://github.com/mjcloutier/rocket_job_mission_control'
s.summary = 'Mission Control is the Web user interface to manage rocketjob jobs'
s.description = 'Rails Engine for adding the web interface for rocketjob to Rails apps'
s.license = 'MIT'
s.files = Dir['{app,config,db,lib,vendor}/**/*', 'MIT-LICENSE', 'Rakefile', 'README.markdown']
s.test_files = Dir['spec/**/*']
s.add_dependency 'rails', '~> 4.0'
s.add_dependency 'jquery-rails'
s.add_dependency 'bootstrap-sass', '>= 3.2.0.1'
s.add_dependency 'coffee-rails'
s.add_dependency 'sass-rails', '>=3.2'
s.add_dependency 'rocketjob', '~> 1.0'
s.add_dependency 'mongo_ha'
s.add_dependency 'mongo', '~>1.0'
s.add_dependency 'mongo_mapper', '~> 0.13'
s.add_dependency 'haml'
end
| $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require 'rocket_job_mission_control/version'
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = 'rocketjob_mission_control'
s.version = RocketJobMissionControl::VERSION
s.authors = ['Michael Cloutier', 'Chris Lamb']
s.email = ['']
s.homepage = 'https://github.com/mjcloutier/rocket_job_mission_control'
s.summary = 'Mission Control is the Web user interface to manage rocketjob jobs'
s.description = 'Rails Engine for adding the web interface for rocketjob to Rails apps'
s.license = 'MIT'
s.files = Dir['{app,config,db,lib,vendor}/**/*', 'MIT-LICENSE', 'Rakefile', 'README.markdown']
s.test_files = Dir['spec/**/*']
s.add_dependency 'rails', '~> 4.0'
s.add_dependency 'jquery-rails'
s.add_dependency 'bootstrap-sass', '>= 3.2.0.1'
s.add_dependency 'coffee-rails'
s.add_dependency 'sass-rails', '>=3.2'
s.add_dependency 'rocketjob', '~> 1.0'
s.add_dependency 'mongo_ha'
s.add_dependency 'mongo', '~>1.0'
s.add_dependency 'mongo_mapper', '~> 0.13'
s.add_dependency 'haml'
end
|
Use bundler in application, simplify devel trick (after Gemfile development gem of self, Dir.pwd is the same as loaded_spec full_gem_path), don't require progressbar. | #!/usr/bin/ruby
require 'rubygems'
gem 'github-api-client'
$:.unshift File.dirname(__FILE__) if Dir.pwd != Gem.loaded_specs['github-api-client'].full_gem_path # devel trick
require 'net/http'
require 'uri'
require 'yaml'
require 'singleton'
require 'active_record'
require 'core_ext/habtm'
require 'rainbow'
require 'progressbar'
require 'github-api-client/config'
GitHub::Config.setup
require 'github-api-client/base'
require 'github-api-client/user'
require 'github-api-client/repo'
require 'github-api-client/browser'
unless $user = GitHub::User.where(GitHub::Config::Secrets).first
$user = GitHub::User.create(GitHub::Config::Secrets)
end if GitHub::Config::Secrets
# General placeholder for all of the GitHub API sweets
module GitHub
end
| #!/usr/bin/ruby
require 'rubygems'
require 'bundler/setup'
gem 'github-api-client'
$:.unshift Gem.loaded_specs['github-api-client'].full_gem_path # devel trick
require 'net/http'
require 'uri'
require 'yaml'
require 'singleton'
require 'active_record'
require 'core_ext/habtm'
require 'rainbow'
require 'github-api-client/config'
GitHub::Config.setup
require 'github-api-client/base'
require 'github-api-client/user'
require 'github-api-client/repo'
require 'github-api-client/browser'
unless $user = GitHub::User.where(GitHub::Config::Secrets).first
$user = GitHub::User.create(GitHub::Config::Secrets)
end if GitHub::Config::Secrets
# General placeholder for all of the GitHub API sweets
module GitHub
end
|
Add a POST route to example. | $LOAD_PATH.unshift(File.dirname(__FILE__))
require './lib/dolphy'
app = DolphyApplication.app do
get '/hello' do
haml :index, :body => "hello"
end
get '/wat' do
erb :what, :body => "wat"
end
get '/' do
haml :index, :body => "index"
end
end
run app
| $LOAD_PATH.unshift(File.dirname(__FILE__))
require './lib/dolphy'
app = DolphyApplication.app do
get '/hello' do
haml :index, :body => "hello"
end
get '/wat' do
erb :what, :body => "wat"
end
get '/' do
haml :index, :body => "index"
end
post '/post' do
haml :post, :body => "hello #{params["message"]["name"]}"
end
end
run app
|
Fix unit tests for server | describe Calabash::Server do
let(:url) {'URL'}
it 'should initialize using a url as its first and only parameter' do
Calabash::Server.new(url)
end
it 'should save the url given when initialized and return it' do
server = Calabash::Server.new(url)
expect(server.url).to eq(url)
end
end
| describe Calabash::Server do
let(:endpoint) {:endpoint}
let(:test_server_port) {200}
it 'should initialize using an endpoint and a test server port as its first and second parameter' do
Calabash::Server.new(endpoint, test_server_port)
end
it 'should save the endpoint given when initialized and return it' do
server = Calabash::Server.new(endpoint, test_server_port)
expect(server.endpoint).to eq(endpoint)
end
it 'should save the test server port given when initialized and return it' do
server = Calabash::Server.new(endpoint, test_server_port)
expect(server.test_server_port).to eq(test_server_port)
end
end
|
Add code wars (7) - russian postal code checker | # http://www.codewars.com/kata/552e45cc30b0dbd01100001a/
# --- iteration 1 ---
def zipvalidate(postcode)
/\A[123460]\d{5}\Z/ === postcode
end
# --- iteration 2 ---
def zipvalidate(code)
/\A[1-46]\d{5}\z/ === code
end
| |
Remove Iterator from OneToMany since it was moved to a separate file | module DataMapper
class Relationship
class OneToMany < self
module Iterator
# Iterate over the loaded domain objects
#
# TODO: refactor this and add support for multi-include
#
# @see Mapper::Relation#each
#
# @example
#
# DataMapper[Person].include(:tasks).each do |person|
# person.tasks.each do |task|
# puts task.name
# end
# end
#
# @yield [object] the loaded domain objects
#
# @yieldparam [Object] object
# the loaded domain object that is yielded
#
# @return [self]
#
# @api public
def each
return to_enum unless block_given?
tuples = @relation.to_a
parent_key = @attributes.key
name = @attributes.detect { |attribute|
attribute.kind_of?(Mapper::Attribute::EmbeddedCollection)
}.name
parents = tuples.each_with_object({}) do |tuple, hash|
key = parent_key.map { |attribute| tuple[attribute.field] }
hash[key] = @attributes.primitives.each_with_object({}) { |attribute, parent|
parent[attribute.field] = tuple[attribute.field]
}
end
parents.each do |key, parent|
parent[name] = tuples.map do |tuple|
current_key = parent_key.map { |attribute| tuple[attribute.field] }
if key == current_key
tuple
end
end.compact
end
parents.each_value { |parent| yield(load(parent)) }
self
end
end # module Iterator
# Returns if the relationship has collection target
#
# @return [Boolean]
#
# @api private
def collection_target?
true
end
# @see Options#default_source_key
#
def default_source_key
:id
end
# @see Options#default_target_key
#
def default_target_key
self.class.foreign_key_name(source_model.name)
end
end # class OneToMany
end # class Relationship
end # module DataMapper
| module DataMapper
class Relationship
class OneToMany < self
# Returns if the relationship has collection target
#
# @return [Boolean]
#
# @api private
def collection_target?
true
end
# @see Options#default_source_key
#
def default_source_key
:id
end
# @see Options#default_target_key
#
def default_target_key
self.class.foreign_key_name(source_model.name)
end
end # class OneToMany
end # class Relationship
end # module DataMapper
|
Add logging for oEmbed error | Spree::ProductsController.class_eval do
helper 'spree/products'
def oEmbed
id = params[:url].scan(/https?:\/\/(.*)?\/products\/(.*)/).first.last
@product = Spree::Product.find_by_permalink!(id)
render :json => @product.oEmbed
end
end | Spree::ProductsController.class_eval do
helper 'spree/products'
def oEmbed
matches = params[:url].scan(/https?:\/\/(.*)?\/products\/(.*)/)
if matches.first.nil?
Rails.logger.error("oEmbedError: url: #{params[:url]}\nmatches: #{matches}")
end
id = matches.first.last
@product = Spree::Product.find_by_permalink!(id)
render :json => @product.oEmbed
end
end |
Reduce allocations in action_view cache expiry | # frozen_string_literal: true
module ActionView
class CacheExpiry
class Executor
def initialize(watcher:)
@cache_expiry = CacheExpiry.new(watcher: watcher)
end
def before(target)
@cache_expiry.clear_cache_if_necessary
end
end
def initialize(watcher:)
@watched_dirs = nil
@watcher_class = watcher
@watcher = nil
@mutex = Mutex.new
end
def clear_cache_if_necessary
@mutex.synchronize do
watched_dirs = dirs_to_watch
return if watched_dirs.empty?
if watched_dirs != @watched_dirs
@watched_dirs = watched_dirs
@watcher = @watcher_class.new([], watched_dirs) do
clear_cache
end
@watcher.execute
else
@watcher.execute_if_updated
end
end
end
def clear_cache
ActionView::LookupContext::DetailsKey.clear
end
private
def dirs_to_watch
fs_paths = all_view_paths.grep(FileSystemResolver)
fs_paths.map(&:path).sort.uniq
end
def all_view_paths
ActionView::ViewPaths.all_view_paths.flat_map(&:paths)
end
end
end
| # frozen_string_literal: true
module ActionView
class CacheExpiry
class Executor
def initialize(watcher:)
@cache_expiry = CacheExpiry.new(watcher: watcher)
end
def before(target)
@cache_expiry.clear_cache_if_necessary
end
end
def initialize(watcher:)
@watched_dirs = nil
@watcher_class = watcher
@watcher = nil
@mutex = Mutex.new
end
def clear_cache_if_necessary
@mutex.synchronize do
watched_dirs = dirs_to_watch
return if watched_dirs.empty?
if watched_dirs != @watched_dirs
@watched_dirs = watched_dirs
@watcher = @watcher_class.new([], watched_dirs) do
clear_cache
end
@watcher.execute
else
@watcher.execute_if_updated
end
end
end
def clear_cache
ActionView::LookupContext::DetailsKey.clear
end
private
def dirs_to_watch
all_view_paths.grep(FileSystemResolver).map!(&:path).tap(&:uniq!).sort!
end
def all_view_paths
ActionView::ViewPaths.all_view_paths.flat_map(&:paths)
end
end
end
|
Add a test for config where it is already in rom format | require 'spec_helper'
describe ROM::Config do
describe '.build' do
let(:raw_config) do
{ adapter: 'memory', hostname: 'localhost', database: 'test' }
end
it 'returns rom repository configuration hash' do
config = ROM::Config.build(raw_config)
expect(config).to eql(default: 'memory://localhost/test')
end
it 'builds absolute path to the database file when root is provided' do
config = ROM::Config.build(
adapter: 'memory', database: 'test', root: '/somewhere'
)
expect(config).to eql(default: 'memory:///somewhere/test')
end
it 'turns a uri into configuration hash' do
config = ROM::Config.build('test://localhost/rom')
expect(config).to eql(default: 'test://localhost/rom')
end
it 'asks adapters to normalize scheme' do
expect(ROM::Adapter[:memory]).to receive(:normalize_scheme).with('memory')
ROM::Config.build(raw_config)
end
end
end
| require 'spec_helper'
describe ROM::Config do
describe '.build' do
let(:raw_config) do
{ adapter: 'memory', hostname: 'localhost', database: 'test' }
end
it 'returns rom repository configuration hash' do
config = ROM::Config.build(raw_config)
expect(config).to eql(default: 'memory://localhost/test')
end
it 'builds absolute path to the database file when root is provided' do
config = ROM::Config.build(
adapter: 'memory', database: 'test', root: '/somewhere'
)
expect(config).to eql(default: 'memory:///somewhere/test')
end
it 'turns a uri into configuration hash' do
config = ROM::Config.build('test://localhost/rom')
expect(config).to eql(default: 'test://localhost/rom')
end
it 'returns original config hash if it is already in rom format' do
config = ROM::Config.build(test: 'test://localhost/rom')
expect(config).to eql(test: 'test://localhost/rom')
end
it 'asks adapters to normalize scheme' do
expect(ROM::Adapter[:memory]).to receive(:normalize_scheme).with('memory')
ROM::Config.build(raw_config)
end
end
end
|
Revert to params for test so Drew can experience the awesomeness | require 'spec_helper'
describe 'tomcat', :type => :class do
let :params_data do
{
:tomcat_version => '7.0.50',
:java_home => '/usr/lib/jvm/jre-1.7.0-openjdk.x86_64'
}
end
context 'When on an unsupported operating system family' do
let :facts do
{
:osfamily => 'Gentoo'
}
end
it 'should send an *unsupported* error' do
expect { should compile }.to raise_error(Puppet::Error, /Unsupported/)
end
end
context 'When on a future supported operating system family' do
let :facts do
{
:osfamily => 'debian'
}
end
it 'should send a "coming soon" message' do
expect { should compile }.to raise_error(Puppet::Error, /coming soon/)
end
end
describe 'On RedHat-ish' do
let :facts do
{ :osfamily => 'redhat', :operatingsystemrelease => '6.4'}
end
context 'When installing/managing java' do
let :hiera_data do
{ tomcat::install_java => true }
end
it 'should install a java package' do
should contain_package('java-1.7.0-openjdk')
should contain_package('java-1.7.0-openjdk-devel')
end
end
end # End RedHat-ish
end | require 'spec_helper'
describe 'tomcat', :type => :class do
let :params_data do
{
:tomcat_version => '7.0.50',
:java_home => '/usr/lib/jvm/jre-1.7.0-openjdk.x86_64'
}
end
context 'When on an unsupported operating system family' do
let :facts do
{
:osfamily => 'Gentoo'
}
end
it 'should send an *unsupported* error' do
expect { should compile }.to raise_error(Puppet::Error, /Unsupported/)
end
end
context 'When on a future supported operating system family' do
let :facts do
{
:osfamily => 'debian'
}
end
it 'should send a "coming soon" message' do
expect { should compile }.to raise_error(Puppet::Error, /coming soon/)
end
end
describe 'On RedHat-ish' do
let :facts do
{ :osfamily => 'redhat', :operatingsystemrelease => '6.4'}
end
context 'When installing/managing java' do
let :params_data do
{ :install_java => true }
end
it 'should install a java package' do
should contain_package('java-1.7.0-openjdk')
should contain_package('java-1.7.0-openjdk-devel')
end
end
end # End RedHat-ish
end |
Add a method to_rgeo for georuby linear ring | class GeoRuby::SimpleFeatures::LinearRing
class << self
def from_points_with_close_support(*arguments)
from_points_without_close_support(*arguments).close!
end
alias_method_chain :from_points, :close_support
def from_coordinates_with_close_support(*arguments)
from_coordinates_without_close_support(*arguments).close!
end
alias_method_chain :from_coordinates, :close_support
end
end
| class GeoRuby::SimpleFeatures::LinearRing
class << self
def from_points_with_close_support(*arguments)
from_points_without_close_support(*arguments).close!
end
alias_method_chain :from_points, :close_support
def from_coordinates_with_close_support(*arguments)
from_coordinates_without_close_support(*arguments).close!
end
alias_method_chain :from_coordinates, :close_support
end
def to_rgeo
rgeo_factory.linear_ring(points.collect(&:to_rgeo))
end
end
|
Revert "Fix failing test in railties" | require 'abstract_unit'
module ActionController
class Base
include ActionController::Testing
end
end
class InfoControllerTest < ActionController::TestCase
tests Rails::InfoController
def setup
Rails.application.routes.draw do
get '/rails/info/properties' => "rails/info#properties"
get '/rails/info/routes' => "rails/info#routes"
end
@controller.stubs(:local_request? => true)
@routes = Rails.application.routes
Rails::InfoController.send(:include, @routes.url_helpers)
end
test "info controller does not allow remote requests" do
@controller.stubs(local_request?: false)
get :properties
assert_response :forbidden
end
test "info controller renders an error message when request was forbidden" do
@controller.stubs(local_request?: false)
get :properties
assert_select 'p'
end
test "info controller allows requests when all requests are considered local" do
@controller.stubs(local_request?: true)
get :properties
assert_response :success
end
test "info controller allows local requests" do
get :properties
assert_response :success
end
test "info controller renders a table with properties" do
get :properties
assert_select 'table'
end
test "info controller renders with routes" do
get :routes
assert_select 'table#routeTable'
end
end
| require 'abstract_unit'
module ActionController
class Base
include ActionController::Testing
end
end
class InfoControllerTest < ActionController::TestCase
tests Rails::InfoController
def setup
Rails.application.routes.draw do
get '/rails/info/properties' => "rails/info#properties"
get '/rails/info/routes' => "rails/info#routes"
end
@controller.stubs(:local_request? => true)
@routes = Rails.application.routes
Rails::InfoController.send(:include, @routes.url_helpers)
end
test "info controller does not allow remote requests" do
@controller.stubs(local_request?: false)
get :properties
assert_response :forbidden
end
test "info controller renders an error message when request was forbidden" do
@controller.stubs(local_request?: false)
get :properties
assert_select 'p'
end
test "info controller allows requests when all requests are considered local" do
@controller.stubs(local_request?: true)
get :properties
assert_response :success
end
test "info controller allows local requests" do
get :properties
assert_response :success
end
test "info controller renders a table with properties" do
get :properties
assert_select 'table'
end
test "info controller renders with routes" do
get :routes
assert_select 'pre'
end
end
|
Add Rails 5 API controller template for the controller generator | <% if namespaced? -%>
require_dependency "<%= namespaced_file_path %>/application_controller"
<% end -%>
<% module_namespacing do -%>
class <%= controller_class_name %>Controller < ApplicationController
before_action :set_<%= singular_table_name %>, only: [:show, :update, :destroy]
respond_to :json
<% unless options[:singleton] -%>
def index
@<%= plural_table_name %> = <%= orm_class.all(class_name) %>
respond_with(@<%= plural_table_name %>)
end
<% end -%>
def show
respond_with(@<%= singular_table_name %>)
end
def create
@<%= singular_table_name %> = <%= orm_class.build(class_name, attributes_params) %>
<%= "flash[:notice] = '#{class_name} was successfully created.' if " if flash? %>@<%= orm_instance.save %>
respond_with(@<%= singular_table_name %>)
end
def update
<%= "flash[:notice] = '#{class_name} was successfully updated.' if " if flash? %>@<%= orm_instance.update(attributes_params) %>
respond_with(@<%= singular_table_name %>)
end
def destroy
@<%= orm_instance.destroy %>
respond_with(@<%= singular_table_name %>)
end
private
def set_<%= singular_table_name %>
@<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %>
end
def <%= "#{singular_table_name}_params" %>
<%- if attributes_names.empty? -%>
params[:<%= singular_table_name %>]
<%- else -%>
params.require(:<%= singular_table_name %>).permit(<%= attributes_names.map { |name| ":#{name}" }.join(', ') %>)
<%- end -%>
end
end
<% end -%>
| |
Remove "on" key from options | module Protocolist
module ModelAdditions
module ClassMethods
def fires type, options={}
#options normalization
options[:on] ||= type
data_proc = if options[:data].respond_to?(:call)
# OPTIMIZE: AFAIK instance_eval is evil
lambda{|record| record.instance_eval{ options[:data].call } }
elsif options[:data].class == Symbol
lambda{|record| record.send(options[:data]) }
end
options_for_callback = options.reject{|k,v| [:on, :data, :subject, :object].include? k }
callback_proc = lambda{|record|
if data_proc
fire type, options.merge({:data => data_proc.call(record)})
else
fire type, options
end
}
Array(options[:on]).each do |on|
send("after_#{on.to_s}".to_sym, callback_proc, options_for_callback)
end
end
end
def self.included base
base.extend ClassMethods
end
def fire type, options={}
options[:object] = self if options[:object] == nil
options[:object] = nil if options[:object] == false
Protocolist.fire type, options
end
end
end
| module Protocolist
module ModelAdditions
module ClassMethods
def fires type, options={}
#options normalization
options[:on] ||= type
data_proc = if options[:data].respond_to?(:call)
# OPTIMIZE: AFAIK instance_eval is evil
lambda{|record| record.instance_eval{ options[:data].call } }
elsif options[:data].class == Symbol
lambda{|record| record.send(options[:data]) }
end
options_for_callback = options.reject{|k,v| [:on, :data, :subject, :object].include? k }
callback_proc = lambda{|record|
if data_proc
fire type, options.reject{|k,v|:on == k }.merge({:data => data_proc.call(record)})
else
fire type, options
end
}
Array(options[:on]).each do |on|
send("after_#{on.to_s}".to_sym, callback_proc, options_for_callback)
end
end
end
def self.included base
base.extend ClassMethods
end
def fire type, options={}
options[:object] = self if options[:object] == nil
options[:object] = nil if options[:object] == false
Protocolist.fire type, options
end
end
end
|
Add test for adding work days from the dashboard | require 'rails_helper'
describe 'adding work days to a project' do
before :each do
@user = FactoryGirl.create(:user)
FactoryGirl.create(:contract, hiwi: @user)
@project = FactoryGirl.create(:project, title: 'AddWorkingHours')
@project.users << @user
login_as @user
end
it 'is possible from a project\'s index page' do
visit project_path(@project)
click_on I18n.t('projects.show.add_working_hours')
expect(current_path).to eq(new_work_day_path)
end
end
| require 'rails_helper'
describe 'adding work days to a project' do
before :each do
@user = FactoryGirl.create(:user)
FactoryGirl.create(:contract, hiwi: @user)
@project = FactoryGirl.create(:project, title: 'AddWorkingHours')
@project.users << @user
login_as @user
end
it 'is possible from a project\'s index page' do
visit project_path(@project)
click_on I18n.t('projects.show.add_working_hours')
expect(current_path).to eq(new_work_day_path)
end
it 'is possible from the dashboard' do
visit dashboard_path
click_on I18n.t('dashboard.actions.enter_work_hours', project_name: @project.title)
expect(current_path).to eq(new_work_day_path)
end
end
|
Update params in charts/crops controller specs | require 'rails_helper'
describe Charts::CropsController do
describe 'GET charts' do
let(:crop) { FactoryBot.create :crop }
describe 'sunniness' do
before { get :sunniness, params: { crop_id: crop.to_param } }
it { expect(response).to be_success }
end
describe 'planted_from' do
before { get :planted_from, params: { crop_id: crop.to_param } }
it { expect(response).to be_success }
end
describe 'harvested_for' do
before { get :harvested_for, params: { crop_id: crop.to_param } }
it { expect(response).to be_success }
end
end
end
| require 'rails_helper'
describe Charts::CropsController do
describe 'GET charts' do
let(:crop) { FactoryBot.create :crop }
describe 'sunniness' do
before { get :sunniness, params: { crop_slug: crop.to_param } }
it { expect(response).to be_success }
end
describe 'planted_from' do
before { get :planted_from, params: { crop_slug: crop.to_param } }
it { expect(response).to be_success }
end
describe 'harvested_for' do
before { get :harvested_for, params: { crop_slug: crop.to_param } }
it { expect(response).to be_success }
end
end
end
|
Add the lib dir to the load path if it not there already. | require 'terminitor/yaml'
require 'terminitor/dsl'
require 'terminitor/runner'
require 'terminitor/abstract_core'
require 'terminitor/cli'
require 'terminitor/abstract_capture'
module Terminitor
autoload :Version, 'terminitor/version'
case RUBY_PLATFORM.downcase
when %r{darwin}
require 'appscript'
autoload :MacCore, 'terminitor/cores/mac_core'
autoload :MacCapture, 'terminitor/capture/mac_capture'
when %r{linux}
require 'dbus'
autoload :KonsoleCore, 'terminitor/cores/konsole_core'
autoload :KonsoleCapture, 'terminitor/capture/konsole_capture'
end
end
| lib_dir = File.expand_path("..", __FILE__)
$:.unshift( lib_dir ) unless $:.include?( lib_dir )
require 'terminitor/yaml'
require 'terminitor/dsl'
require 'terminitor/runner'
require 'terminitor/abstract_core'
require 'terminitor/cli'
require 'terminitor/abstract_capture'
module Terminitor
autoload :Version, 'terminitor/version'
case RUBY_PLATFORM.downcase
when %r{darwin}
require 'appscript'
autoload :MacCore, 'terminitor/cores/mac_core'
autoload :MacCapture, 'terminitor/capture/mac_capture'
when %r{linux}
require 'dbus'
autoload :KonsoleCore, 'terminitor/cores/konsole_core'
autoload :KonsoleCapture, 'terminitor/capture/konsole_capture'
end
end
|
Make updating optional because of API problems | require 'rufus-scheduler'
scheduler = Rufus::Scheduler.singleton
scheduler.every("5m") do
JodelCityController.update_cities
end
| require 'rufus-scheduler'
scheduler = Rufus::Scheduler.singleton
if ENV["jodelstats_update"]
scheduler.every("5m") do
JodelCityController.update_cities
end
end
|
Upgrade VCR to ensure multipart POSTs work. | require './lib/pew_pew/version'
Gem::Specification.new do |gem|
gem.name = 'pew_pew'
gem.version = PewPew::VERSION
gem.summary = 'A Ruby library for using the Mailgun API.'
gem.homepage = 'http://github.com/tylerhunt/pew_pew'
gem.author = 'Tyler Hunt'
gem.add_dependency 'faraday_middleware', '~> 0.8.0'
gem.add_dependency 'hashie', '~> 1.1'
gem.add_dependency 'relax', '~> 0.2.0'
gem.add_development_dependency 'rspec', '~> 2.6'
gem.add_development_dependency 'vcr', '~> 2.0'
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']
end
| require './lib/pew_pew/version'
Gem::Specification.new do |gem|
gem.name = 'pew_pew'
gem.version = PewPew::VERSION
gem.summary = 'A Ruby library for using the Mailgun API.'
gem.homepage = 'http://github.com/tylerhunt/pew_pew'
gem.author = 'Tyler Hunt'
gem.add_dependency 'faraday_middleware', '~> 0.8.0'
gem.add_dependency 'hashie', '~> 1.1'
gem.add_dependency 'relax', '~> 0.2.0'
gem.add_development_dependency 'rspec', '~> 2.6'
gem.add_development_dependency 'vcr', '~> 2.2'
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']
end
|
Remove sensible but overridden private method read_attribute | module Stringex
module ActsAsUrl
module Adapter
class DataMapper < Base
def self.load
ensure_loadable
orm_class.send :include, Stringex::ActsAsUrl::ActsAsUrlInstanceMethods
::DataMapper::Model.send :include, Stringex::ActsAsUrl::ActsAsUrlClassMethods
end
private
def create_callback
klass.class_eval do
before acts_as_url_configuration.settings.sync_url ? :save : :create, :ensure_unique_url
end
end
def instance_from_db
instance.class.get(instance.id)
end
def is_blank?(object)
object.nil? || object == '' || object == []
end
def is_new?(object)
object.new?
end
def is_present?(object)
!is_blank? object
end
def klass_previous_instances(&block)
klass.all(conditions: {settings.url_attribute => [nil]}).each(&block)
end
def primary_key
instance.class.key.first.instance_variable_get '@name'
end
def read_attribute(instance, attribute)
instance.attributes[attribute]
end
def url_owners
@url_owners ||= url_owners_class.all(conditions: url_owner_conditions)
end
def read_attribute(instance, name)
instance.attribute_get name
end
def write_attribute(instance, name, value)
instance.attribute_set name, value
end
def self.orm_class
::DataMapper::Resource
end
end
end
end
end
| module Stringex
module ActsAsUrl
module Adapter
class DataMapper < Base
def self.load
ensure_loadable
orm_class.send :include, Stringex::ActsAsUrl::ActsAsUrlInstanceMethods
::DataMapper::Model.send :include, Stringex::ActsAsUrl::ActsAsUrlClassMethods
end
private
def create_callback
klass.class_eval do
before acts_as_url_configuration.settings.sync_url ? :save : :create, :ensure_unique_url
end
end
def instance_from_db
instance.class.get(instance.id)
end
def is_blank?(object)
object.nil? || object == '' || object == []
end
def is_new?(object)
object.new?
end
def is_present?(object)
!is_blank? object
end
def klass_previous_instances(&block)
klass.all(conditions: {settings.url_attribute => [nil]}).each(&block)
end
def primary_key
instance.class.key.first.instance_variable_get '@name'
end
def url_owners
@url_owners ||= url_owners_class.all(conditions: url_owner_conditions)
end
def read_attribute(instance, name)
instance.attribute_get name
end
def write_attribute(instance, name, value)
instance.attribute_set name, value
end
def self.orm_class
::DataMapper::Resource
end
end
end
end
end
|
Fix bad require following the renaming of the Events class | require 'timetable/time_helper'
require 'timetable/application'
require 'timetable/cache'
require 'timetable/calendar'
require 'timetable/config'
require 'timetable/database'
require 'timetable/downloader'
require 'timetable/events'
require 'timetable/parser'
require 'timetable/preset'
| require 'timetable/time_helper'
require 'timetable/application'
require 'timetable/cache'
require 'timetable/calendar'
require 'timetable/config'
require 'timetable/database'
require 'timetable/downloader'
require 'timetable/parser_delegate'
require 'timetable/parser'
require 'timetable/preset'
|
Remove ambiguity with regexp (to keep CodeClimate happy) | module Cinch
module Plugins
class Uno
include Cinch::Plugin
match /fart/i, method: :help
def help(m)
m.reply("Farting.")
end
end
end
end | module Cinch
module Plugins
class Uno
include Cinch::Plugin
match(/fart/i, method: :help)
def help(m)
m.reply("Farting.")
end
end
end
end |
Create cask for Geo Sans Light font | class FontGeoSansLight < Cask
url 'http://img.dafont.com/dl/?f=geo_sans_light'
homepage 'http://www.dafont.com/geo-sans-light.font'
version 'latest'
sha1 'no_checksum'
font 'GeosansLight-Oblique.ttf'
font 'GeosansLight.ttf'
end
| |
Comment to remove catch after removing 'AvailabilityMixin' module | class ApplicationHelper::Button::GenericFeatureButtonWithDisable < ApplicationHelper::Button::GenericFeatureButton
needs_record
def calculate_properties
self[:enabled] = !(self[:title] = @error_message if disabled?)
end
def disabled?
begin
begin
@error_message = @record.try(:unsupported_reason, @feature)
rescue NoMethodError
@error_message = @record.try(:is_available_now_error_message, @feature) if @error_message.nil?
end
rescue
@error_message = 'Feature is not supported.'
true
end
end
end
| class ApplicationHelper::Button::GenericFeatureButtonWithDisable < ApplicationHelper::Button::GenericFeatureButton
needs_record
def calculate_properties
self[:enabled] = !(self[:title] = @error_message if disabled?)
end
def disabled?
begin
begin
@error_message = @record.try(:unsupported_reason, @feature)
rescue NoMethodError # TODO: remove with deleting AvailabilityMixin module
@error_message = @record.try(:is_available_now_error_message, @feature) if @error_message.nil?
end
rescue
@error_message = 'Feature is not supported.'
true
end
end
end
|
Fix image tags to be no larger than 50 | # frozen_string_literal: true
module ApplicationHelper
STOCK_IMAGE_URL = 'https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50'
def display_user(user)
path = user.image_url == STOCK_IMAGE_URL ? image_path('dolphin.png') : user.image_url
safe_join([image_tag(path), user.name])
end
end
| # frozen_string_literal: true
module ApplicationHelper
STOCK_IMAGE_URL = 'https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50'
def display_user(user)
path = user.image_url == STOCK_IMAGE_URL ? image_path('dolphin.png') : user.image_url
safe_join([image_tag(path, alt: user.name, size: '50'), user.name])
end
end
|
Fix File Creator spec, updating to RSpec 3 | require "writer/file_creator"
module Writer
describe FileCreator do
let(:file) { stub(:file) }
let(:creator) { FileCreator.new }
before :each do
File.stub(:open)
.with('filename', 'w')
.and_yield(file)
File.stub(:open)
.with('filename', 'r')
.and_return(true)
end
context "with content" do
it "writes the content" do
file.should_receive(:puts).with('hi')
creator.create!('filename', 'hi')
end
end
context "without content" do
it "leaves a blank line" do
creator.stub(:template) { nil }
file.should_receive(:puts).with(nil)
creator.create!('filename')
end
it "uses a template, if it exists" do
template = stub(:read => "hello\nworld")
creator.stub(:template) { template.read }
file.should_receive(:puts).with("hello\nworld")
creator.create!('filename')
end
end
end
end
| require "writer/file_creator"
module Writer
describe FileCreator do
let(:file) { double(:file) }
subject(:creator) { described_class.new }
before :each do
allow(File).to receive(:open).with('filename', 'w').and_yield(file)
allow(File).to receive(:open).with('filename', 'r')
end
context "with content" do
it "writes the content" do
allow(file).to receive(:puts)
creator.create!('filename', 'hi')
expect(file).to have_received(:puts).with('hi')
end
end
context "without content" do
it "leaves a blank line" do
allow(creator).to receive(:template)
allow(file).to receive(:puts)
creator.create!('filename')
expect(file).to have_received(:puts).with(nil)
end
it "uses a template, if it exists" do
allow(creator).to receive(:template) { "hello\nworld" }
allow(file).to receive(:puts)
creator.create!('filename')
expect(file).to have_received(:puts).with("hello\nworld")
end
end
end
end
|
Put it to me straight: just say it. | require "active_support"
require "rails/secrets"
module Rails
module Command
class SecretsCommand < Rails::Command::Base # :nodoc:
def help
say "Usage:\n #{self.class.banner}"
say ""
say self.class.desc
end
def setup
require "rails/generators"
require "rails/generators/rails/encrypted_secrets/encrypted_secrets_generator"
Rails::Generators::EncryptedSecretsGenerator.start
end
def edit
if ENV["EDITOR"].empty?
say "No $EDITOR to open decrypted secrets in. Assign one like this:"
say ""
say %(EDITOR="mate --wait" bin/rails secrets:edit)
say ""
say "For editors that fork and exit immediately, it's important to pass a wait flag,"
say "otherwise the secrets will be saved immediately with no chance to edit."
return
end
require_application_and_environment!
Rails::Secrets.read_for_editing do |tmp_path|
puts "Waiting for secrets file to be saved. Abort with Ctrl-C."
system("\$EDITOR #{tmp_path}")
end
puts "New secrets encrypted and saved."
rescue Interrupt
puts "Aborted changing encrypted secrets: nothing saved."
rescue Rails::Secrets::MissingKeyError => error
say error.message
end
end
end
end
| require "active_support"
require "rails/secrets"
module Rails
module Command
class SecretsCommand < Rails::Command::Base # :nodoc:
def help
say "Usage:\n #{self.class.banner}"
say ""
say self.class.desc
end
def setup
require "rails/generators"
require "rails/generators/rails/encrypted_secrets/encrypted_secrets_generator"
Rails::Generators::EncryptedSecretsGenerator.start
end
def edit
if ENV["EDITOR"].empty?
say "No $EDITOR to open decrypted secrets in. Assign one like this:"
say ""
say %(EDITOR="mate --wait" bin/rails secrets:edit)
say ""
say "For editors that fork and exit immediately, it's important to pass a wait flag,"
say "otherwise the secrets will be saved immediately with no chance to edit."
return
end
require_application_and_environment!
Rails::Secrets.read_for_editing do |tmp_path|
say "Waiting for secrets file to be saved. Abort with Ctrl-C."
system("\$EDITOR #{tmp_path}")
end
say "New secrets encrypted and saved."
rescue Interrupt
say "Aborted changing encrypted secrets: nothing saved."
rescue Rails::Secrets::MissingKeyError => error
say error.message
end
end
end
end
|
Remove WORKING_STATES again - they aren't needed anymore. | module State
STATES = %w(failed no_result pending fetching processing done)
TERMINAL_STATES = %w(failed no_result done)
WORKING_STATES = STATES - TERMINAL_STATES
STATE_LABEL = {
pending: 'label-warning',
fetching: 'label-primary',
processing: 'label-primary',
done: 'label-success',
failed: 'label-danger',
}
def self.working?(state)
WORKING_STATES.include?(state)
end
def self.terminal?(state)
TERMINAL_STATES.include?(state)
end
def self.most_successful(states)
states.sort_by { |s| State.success_order(s) }.last
end
def self.success_order(state)
STATES.index(state)
end
end
| module State
STATES = %w(failed no_result pending fetching processing done)
TERMINAL_STATES = %w(failed no_result done)
STATE_LABEL = {
pending: 'label-warning',
fetching: 'label-primary',
processing: 'label-primary',
done: 'label-success',
failed: 'label-danger',
}
def self.terminal?(state)
TERMINAL_STATES.include?(state)
end
def self.most_successful(states)
states.sort_by { |s| State.success_order(s) }.last
end
def self.success_order(state)
STATES.index(state)
end
end
|
Fix a bug when showing a poll | # == Schema Information
# Schema version: 20090308232205
#
# Table name: poll_answers
#
# id :integer(4) not null, primary key
# poll_id :integer(4)
# answer :string(255)
# votes :integer(4) default(0), not null
# position :integer(4)
# created_at :datetime
# updated_at :datetime
#
class PollAnswer < ActiveRecord::Base
belongs_to :poll
acts_as_list :scope => :poll
attr_accessible :answer
named_scope :sorted, :order => "position ASC"
validates_presence_of :answer, :message => "La description de la réponse ne peut pas être vide"
def percent
return 0.0 if poll.total_votes == 0
100.0 * votes / poll.total_votes
end
def vote(ip)
self.class.increment_counter(:votes, self.id)
PollIp.create!(:ip => ip)
end
end
| # == Schema Information
# Schema version: 20090308232205
#
# Table name: poll_answers
#
# id :integer(4) not null, primary key
# poll_id :integer(4)
# answer :string(255)
# votes :integer(4) default(0), not null
# position :integer(4)
# created_at :datetime
# updated_at :datetime
#
class PollAnswer < ActiveRecord::Base
belongs_to :poll
acts_as_list :scope => :poll
attr_accessible :answer
named_scope :sorted, :order => "position ASC"
validates_presence_of :answer, :message => "La description de la réponse ne peut pas être vide"
def percent
return 0.0 if poll.total_votes == 0
"%.1f" % (100.0 * votes / poll.total_votes)
end
def vote(ip)
self.class.increment_counter(:votes, self.id)
PollIp.create!(:ip => ip)
end
end
|
Add heading tag helper to Dough | module HeadingTagHelper
def heading_tag(content_or_options_with_block = nil, options = {}, &block)
if block_given?
options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash)
value = capture(&block).strip
else
value = content_or_options_with_block
end
level = options.delete(:level) { 1 }
content_tag("h#{level}", value.html_safe, options.merge('role' => :heading, 'aria-level' => level))
end
end
| |
Correct misnamed attribute from hostname to host | Rails.application.configure do
config.action_mailer.smtp_settings = {
user_name: ENV['SMTP_USERNAME'],
password: ENV['SMTP_PASSWORD'],
address: ENV['SMTP_HOSTNAME'],
port: ENV['SMTP_PORT'],
domain: ENV['SMTP_DOMAIN'],
authentication: :login,
enable_starttls_auto: true
}
service_url = URI.parse(ENV.fetch('SERVICE_URL'))
config.action_mailer.default_url_options = {
hostname: service_url.hostname, protocol: service_url.scheme
}
config.cache_classes = true
config.eager_load = true
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
config.assets.js_compressor = :uglifier
config.assets.compile = false
config.assets.digest = true
config.log_level = :debug
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
config.log_formatter = ::Logger::Formatter.new
config.active_record.dump_schema_after_migration = false
config.logstasher.enabled = true
config.logstasher.suppress_app_log = true
config.logstasher.source = 'logstasher'
config.logstasher.backtrace = true
config.logstasher.logger_path = "#{Rails.root}/log/logstash_#{Rails.env}.json"
config.mx_checker = MxChecker.new
end
| Rails.application.configure do
config.action_mailer.smtp_settings = {
user_name: ENV['SMTP_USERNAME'],
password: ENV['SMTP_PASSWORD'],
address: ENV['SMTP_HOSTNAME'],
port: ENV['SMTP_PORT'],
domain: ENV['SMTP_DOMAIN'],
authentication: :login,
enable_starttls_auto: true
}
service_url = URI.parse(ENV.fetch('SERVICE_URL'))
config.action_mailer.default_url_options = {
host: service_url.hostname, protocol: service_url.scheme
}
config.cache_classes = true
config.eager_load = true
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
config.assets.js_compressor = :uglifier
config.assets.compile = false
config.assets.digest = true
config.log_level = :debug
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
config.log_formatter = ::Logger::Formatter.new
config.active_record.dump_schema_after_migration = false
config.logstasher.enabled = true
config.logstasher.suppress_app_log = true
config.logstasher.source = 'logstasher'
config.logstasher.backtrace = true
config.logstasher.logger_path = "#{Rails.root}/log/logstash_#{Rails.env}.json"
config.mx_checker = MxChecker.new
end
|
Remove unused method in UserInfoScrubber | class UserInfoScrubber
DELETED_USER_NAME = 'deleted_user'
DELETED_USER_EMAIL_DOMAIN = '@zooniverse.org'
class ScrubDisabledUserError < StandardError; end
def self.scrub_personal_info!(user)
@user = user
if @user.disabled?
message = "Can't scrub personal details of a disabled user with id: #{@user.id}"
raise ScrubDisabledUserError.new(message)
else
scrub_details
end
end
private
def self.scrub_details
@user.update_columns(email: nil)
end
def self.scrubbed_login(tries)
suffix = tries > 0 ? tries : nil
"#{DELETED_USER_NAME}_#{SecureRandom.uuid}#{suffix}"
end
end
| class UserInfoScrubber
DELETED_USER_NAME = 'deleted_user'
DELETED_USER_EMAIL_DOMAIN = '@zooniverse.org'
class ScrubDisabledUserError < StandardError; end
def self.scrub_personal_info!(user)
@user = user
if @user.disabled?
message = "Can't scrub personal details of a disabled user with id: #{@user.id}"
raise ScrubDisabledUserError.new(message)
else
scrub_details
end
end
private
def self.scrub_details
@user.update_columns(email: nil)
end
end
|
Remove some oldies in Type. | module Qrb
class Type
def initialize(name)
unless name.nil? or name.is_a?(String)
raise ArgumentError, "String expected for type name, got `#{name}`"
end
@name = name
end
def name
@name || default_name
end
def to_s
name.to_s
end
def up(*args)
raise NotImplementedError, "Missing #{self.class.name}#up"
end
protected
def set_equal?(s1, s2)
s1.size == s2.size and (s1-s2).empty?
end
def set_hash(arg)
arg.map(&:hash).reduce(:^)
end
def up_error_message(value)
"Invalid value `#{value}` for #{to_s}"
end
def up_error!(value, cause = nil)
raise UpError.new(up_error_message(value), cause)
end
end # class Type
end # module Qrb
require_relative 'type/builtin_type'
require_relative 'type/union_type'
require_relative 'type/sub_type'
require_relative 'type/tuple_type'
require_relative 'type/relation_type'
require_relative 'type/user_type'
| module Qrb
#
# Abstract class for Q type (generators).
#
class Type
def initialize(name)
unless name.nil? or name.is_a?(String)
raise ArgumentError, "String expected for type name, got `#{name}`"
end
@name = name
end
def name
@name || default_name
end
def to_s
name.to_s
end
def up(*args)
raise NotImplementedError, "Missing #{self.class.name}#up"
end
protected
def set_equal?(s1, s2)
s1.size == s2.size and (s1-s2).empty?
end
def set_hash(arg)
arg.map(&:hash).reduce(:^)
end
end # class Type
end # module Qrb
require_relative 'type/builtin_type'
require_relative 'type/union_type'
require_relative 'type/sub_type'
require_relative 'type/tuple_type'
require_relative 'type/relation_type'
require_relative 'type/user_type'
|
Create votes controller and create action to handle question voting | class VotesController < ApplicationController
def create
@vote = Vote.new(vote_params)
@question = Question.find(params[:vote][:votable_id])
if @vote.save
redirect_to question_path(@question)
else
flash[:notice] = @vote.errors.full_messages.join(", ")
render 'questions/show.html.erb'
end
end
def vote_params
params.require(:vote).permit(:value, :voter_id, :votable_id, :votable_type)
end
end | |
Make `TimedQueue` use `pop`/`push` for better performance. | require 'thread'
require 'timeout'
class TimedQueue
def initialize(size = 0)
@que = Array.new(size) { yield }
@mutex = Mutex.new
@resource = ConditionVariable.new
end
def push(obj)
@mutex.synchronize do
@que.unshift obj
@resource.broadcast
end
end
alias_method :<<, :push
def timed_pop(timeout=0.5)
deadline = Time.now + timeout
@mutex.synchronize do
loop do
return @que.shift unless @que.empty?
to_wait = deadline - Time.now
raise Timeout::Error, "Waited #{timeout} sec" if to_wait <= 0
@resource.wait(@mutex, to_wait)
end
end
end
def empty?
@que.empty?
end
def clear
@que.clear
end
def length
@que.length
end
end
| require 'thread'
require 'timeout'
class TimedQueue
def initialize(size = 0)
@que = Array.new(size) { yield }
@mutex = Mutex.new
@resource = ConditionVariable.new
end
def push(obj)
@mutex.synchronize do
@que.push obj
@resource.broadcast
end
end
alias_method :<<, :push
def timed_pop(timeout=0.5)
deadline = Time.now + timeout
@mutex.synchronize do
loop do
return @que.pop unless @que.empty?
to_wait = deadline - Time.now
raise Timeout::Error, "Waited #{timeout} sec" if to_wait <= 0
@resource.wait(@mutex, to_wait)
end
end
end
def empty?
@que.empty?
end
def clear
@que.clear
end
def length
@que.length
end
end
|
Use more concise, clear code, thx @cadwallion. | module Strumbar
module Instrumentation
module ActionController
def self.load(options={})
options[:rate] ||= Strumbar.default_rate
using_mongoid = options.fetch(:mongoid, false)
Strumbar.subscribe /process_action.action_controller/ do |client, event|
key = "#{event.payload[:controller]}.#{event.payload[:action]}"
db_runtime = if using_mongoid
event.payload[:mongo_runtime]
else
event.payload[:db_runtime]
end
client.timing "#{key}.total_time", event.duration, options[:rate]
client.timing "#{key}.view_time", event.payload[:view_runtime], options[:rate]
client.timing "#{key}.db_time", db_runtime, options[:rate]
client.increment "#{key}.status.#{event.payload[:status]}", options[:rate]
end
end
end
end
end
| module Strumbar
module Instrumentation
module ActionController
def self.load(options={})
options[:rate] ||= Strumbar.default_rate
using_mongoid = options.fetch(:mongoid, false)
Strumbar.subscribe /process_action.action_controller/ do |client, event|
key = "#{event.payload[:controller]}.#{event.payload[:action]}"
db_runtime_key = using_mongoid ? :mongo_runtime : :db_runtime
client.timing "#{key}.total_time", event.duration, options[:rate]
client.timing "#{key}.view_time", event.payload[:view_runtime], options[:rate]
client.timing "#{key}.db_time", event.payload[db_runtime_key], options[:rate]
client.increment "#{key}.status.#{event.payload[:status]}", options[:rate]
end
end
end
end
end
|
Fix uri expansion during remote follow | # frozen_string_literal: true
class RemoteFollowController < ApplicationController
layout 'public'
before_action :set_account
before_action :check_account_suspension
def new
@remote_follow = RemoteFollow.new
end
def create
@remote_follow = RemoteFollow.new(resource_params)
if @remote_follow.valid?
resource = Goldfinger.finger("acct:#{@remote_follow.acct}")
redirect_url_link = resource&.link('http://ostatus.org/schema/1.0/subscribe')
if redirect_url_link.nil? || redirect_url_link.template.nil?
@remote_follow.errors.add(:acct, I18n.t('remote_follow.missing_resource'))
render(:new) && return
end
redirect_to Addressable::Template.new(redirect_url_link.template).expand(uri: "acct:#{@account.username}@#{Rails.configuration.x.local_domain}").to_s
else
render :new
end
rescue Goldfinger::Error
@remote_follow.errors.add(:acct, I18n.t('remote_follow.missing_resource'))
render :new
end
private
def resource_params
params.require(:remote_follow).permit(:acct)
end
def set_account
@account = Account.find_local!(params[:account_username])
end
def check_account_suspension
head 410 if @account.suspended?
end
end
| # frozen_string_literal: true
class RemoteFollowController < ApplicationController
layout 'public'
before_action :set_account
before_action :check_account_suspension
def new
@remote_follow = RemoteFollow.new
end
def create
@remote_follow = RemoteFollow.new(resource_params)
if @remote_follow.valid?
resource = Goldfinger.finger("acct:#{@remote_follow.acct}")
redirect_url_link = resource&.link('http://ostatus.org/schema/1.0/subscribe')
if redirect_url_link.nil? || redirect_url_link.template.nil?
@remote_follow.errors.add(:acct, I18n.t('remote_follow.missing_resource'))
render(:new) && return
end
redirect_to Addressable::Template.new(redirect_url_link.template).expand(uri: "#{@account.username}@#{Rails.configuration.x.local_domain}").to_s
else
render :new
end
rescue Goldfinger::Error
@remote_follow.errors.add(:acct, I18n.t('remote_follow.missing_resource'))
render :new
end
private
def resource_params
params.require(:remote_follow).permit(:acct)
end
def set_account
@account = Account.find_local!(params[:account_username])
end
def check_account_suspension
head 410 if @account.suspended?
end
end
|
Fix gemspec issue with Bundler | # encoding: utf-8
Gem::Specification.new do |s|
s.name = 'visibilityjs'
s.version = '0.4.2'
s.platform = Gem::Platform::RUBY
s.authors = ['Andrey “A.I.” Sitnik']
s.email = ['andrey@sitnik.ru']
s.homepage = 'https://github.com/ai/visibility.js'
s.summary = 'Visibility.js – a wrapper for the Page Visibility API.'
s.description = 'Visibility.js allow you to determine whether ' +
'your web page is visible to an user, is hidden in ' +
'background tab or is prerendering. It allows you use ' +
'the page visibility state in JavaScript logic and improve ' +
'browser performance or improve user interface experience.'
s.add_dependency 'sprockets', '>= 2.0.0.beta.5'
s.files = ['vendor/assets/javascripts/visibility.js',
'vendor/assets/javascripts/visibility.fallback.js',
'lib/visibilityjs.rb',
'LICENSE', 'README.md', 'ChangeLog']
s.extra_rdoc_files = ['LICENSE', 'README.md', 'ChangeLog']
s.require_path = 'lib'
end
| # encoding: utf-8
Gem::Specification.new do |s|
s.name = 'visibilityjs'
s.version = '0.4.2'
s.platform = Gem::Platform::RUBY
s.authors = ['Andrey “A.I.” Sitnik']
s.email = ['andrey@sitnik.ru']
s.homepage = 'https://github.com/ai/visibility.js'
s.summary = 'Visibility.js – a wrapper for the Page Visibility API.'
s.description = 'Visibility.js allow you to determine whether ' +
'your web page is visible to an user, is hidden in ' +
'background tab or is prerendering. It allows you use ' +
'the page visibility state in JavaScript logic and improve ' +
'browser performance or improve user interface experience.'
s.add_dependency 'sprockets', '>= 2'
s.files = ['vendor/assets/javascripts/visibility.js',
'vendor/assets/javascripts/visibility.fallback.js',
'lib/visibilityjs.rb',
'LICENSE', 'README.md', 'ChangeLog']
s.extra_rdoc_files = ['LICENSE', 'README.md', 'ChangeLog']
s.require_path = 'lib'
end
|
Enable system_site_packages for faraday venv. | # -*- coding: utf-8 -*-
#
# Cookbook Name:: faraday
# Recipe:: sources
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
include_recipe 'faraday'
git node['faraday']['install_dir'] do
repository node['faraday']['git_repository']
reference node['faraday']['git_reference']
end
python_runtime node['faraday']['python_runtime']
python_virtualenv 'faraday-venv' do
path "#{node['faraday']['install_dir']}/.venv"
end
pip_requirements "#{node['faraday']['install_dir']}/requirements.txt" do
python node['faraday']['python_runtime']
virtualenv 'faraday-venv'
end
| # -*- coding: utf-8 -*-
#
# Cookbook Name:: faraday
# Recipe:: sources
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
include_recipe 'faraday'
git node['faraday']['install_dir'] do
repository node['faraday']['git_repository']
reference node['faraday']['git_reference']
end
python_runtime node['faraday']['python_runtime']
python_virtualenv 'faraday-venv' do
path "#{node['faraday']['install_dir']}/.venv"
system_site_packages true
end
pip_requirements "#{node['faraday']['install_dir']}/requirements.txt" do
python node['faraday']['python_runtime']
virtualenv 'faraday-venv'
end
|
Move token retrieval outside of initializer method | require "warden"
class Warden::Strategies::Doorkeeper < ::Warden::Strategies::Base
VERSION = "0.1.0"
attr_reader :token, :scope
def initialize(env, scope=nil)
super
@token = OAuth::Token.authenticate request, *Doorkeeper.configuration.access_token_methods
@scope = scope
end
def valid?
@token && @token.accessible? && @token.acceptable?(@scope)
end
def authenticate!
user = User.where(id: @token.resource_owner_id).first
if user
success!(user)
else
fail!("No such user")
end
end
# Returns the configuration data for the default user scope.
def config
scopes = env["warden"].config[:scope_defaults]
if scopes && scopes[:user]
scopes[:user][:config]
else
{}
end
end
end
| require "warden"
class Warden::Strategies::Doorkeeper < ::Warden::Strategies::Base
VERSION = "0.1.0"
attr_reader :token, :scope
def initialize(env, scope=nil)
super
@scope = scope
end
def valid?
@token = OAuth::Token.authenticate(request, *Doorkeeper.configuration.access_token_methods)
@token && @token.accessible? && @token.acceptable?(@scope)
end
def authenticate!
user = User.where(id: @token.resource_owner_id).first
if user
success!(user)
else
fail!("No such user")
end
end
# Returns the configuration data for the default user scope.
def config
scopes = env["warden"].config[:scope_defaults]
if scopes && scopes[:user]
scopes[:user][:config]
else
{}
end
end
end
|
Add rake to the gemfile | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/model_presenter/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Yi Wen"]
gem.email = ["hayafirst@gmail.com"]
gem.description = %q{TODO: Write a gem description}
gem.summary = %q{TODO: Write a gem 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.name = "model_presenter"
gem.require_paths = ["lib"]
gem.version = ModelPresenter::VERSION
gem.add_development_dependency(%q<minitest>)
gem.add_development_dependency(%q<minitest-growl>)
gem.add_development_dependency(%q<guard-minitest>)
gem.add_development_dependency(%q<minitest-wscolor>)
gem.add_development_dependency(%q<cane>)
end
| # -*- encoding: utf-8 -*-
require File.expand_path('../lib/model_presenter/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Yi Wen"]
gem.email = ["hayafirst@gmail.com"]
gem.description = %q{TODO: Write a gem description}
gem.summary = %q{TODO: Write a gem 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.name = "model_presenter"
gem.require_paths = ["lib"]
gem.version = ModelPresenter::VERSION
gem.add_development_dependency(%q<minitest>)
gem.add_development_dependency(%q<minitest-growl>)
gem.add_development_dependency(%q<guard-minitest>)
gem.add_development_dependency(%q<minitest-wscolor>)
gem.add_development_dependency(%q<cane>)
gem.add_development_dependency(%q<rake>)
end
|
Add solution for 6.5 peer and reflection | # RELEASE 2: NESTED STRUCTURE GOLF
# Hole 1
# Target element: "FORE"
array = [[1,2], ["inner", ["eagle", "par", ["FORE", "hook"]]]]
# attempts:1
# ============================================================
p array.at(1).at(1).at(2).at(0)
# ============================================================
# Hole 2
# Target element: "congrats!"
hash = {outer: {inner: {"almost" => {3 => "congrats!"}}}}
# attempts:
# ============================================================
p hash[:outer][:inner]["almost"][3]
# ============================================================
# Hole 3
# Target element: "finished"
nested_data = {array: ["array", {hash: "finished"}]}
# attempts:
# ============================================================
p nested_data[:array][1][:hash]
# ============================================================
# RELEASE 3: ITERATE OVER NESTED STRUCTURES
number_array = [5, [10, 15], [20, 25, 30], 35]
# x = 0
# while x < number_array.length
# if number_array[x].is_a? Integer
# number_array[x] += 5
# elsif number_array[x].is_a? Array
# number_array[x] = number_array[x].map {|sub| sub += 5}
# end
# x += 1
# end
number_array = number_array.map do |element|
if element.is_a? Integer
element + 5
elsif element.is_a? Array
element.map {|sub| sub + 5}
end
end
p number_array
# Bonus:
startup_names = ["bit", ["find", "fast", ["optimize", "scope"]]]
#Reflection
# What are some general rules you can apply to nested arrays? You can iterate over them like any other array. They can
#mix elements and hashes among the arrays.
# What are some ways you can iterate over nested arrays? The use of .map is helpful for returning an array. .is_a?
# help test the elements and add to the array.
# Did you find any good new methods to implement or did you re-use one you were already familiar with? What was it and why did you decide that was a good option?.map we wanted to make the new array destructive and this helped
#beacuse we set the old array equal to the new one. | |
Handle Attributes as Parameter for API Blueprint | require 'rspec_api_documentation/dsl/endpoint/set_param'
module RspecApiDocumentation
module DSL
module Endpoint
class Params
attr_reader :example_group, :example
def initialize(example_group, example, extra_params)
@example_group = example_group
@example = example
@extra_params = extra_params
end
def call
parameters = example.metadata.fetch(:parameters, {}).inject({}) do |hash, param|
SetParam.new(self, hash, param).call
end
parameters.deep_merge!(extra_params)
parameters
end
private
attr_reader :extra_params
end
end
end
end
| require 'rspec_api_documentation/dsl/endpoint/set_param'
module RspecApiDocumentation
module DSL
module Endpoint
class Params
attr_reader :example_group, :example
def initialize(example_group, example, extra_params)
@example_group = example_group
@example = example
@extra_params = extra_params
end
def call
set_param = -> hash, param {
SetParam.new(self, hash, param).call
}
example.metadata.fetch(:parameters, {}).inject({}, &set_param)
.deep_merge(
example.metadata.fetch(:attributes, {}).inject({}, &set_param)
).deep_merge(extra_params)
end
private
attr_reader :extra_params
end
end
end
end
|
Add JSON fixture for labels autocomplete source | # frozen_string_literal: true
require 'spec_helper'
describe Projects::AutocompleteSourcesController, '(JavaScript fixtures)', type: :controller do
include JavaScriptFixturesHelpers
set(:admin) { create(:admin) }
set(:group) { create(:group, name: 'frontend-fixtures') }
set(:project) { create(:project, namespace: group, path: 'autocomplete-sources-project') }
set(:issue) { create(:issue, project: project) }
before(:all) do
clean_frontend_fixtures('autocomplete_sources/')
end
before do
sign_in(admin)
end
it 'autocomplete_sources/labels.json' do |example|
issue.labels << create(:label, project: project, title: 'bug')
issue.labels << create(:label, project: project, title: 'critical')
create(:label, project: project, title: 'feature')
create(:label, project: project, title: 'documentation')
get :labels,
format: :json,
params: {
namespace_id: group.path,
project_id: project.path,
type: issue.class.name,
type_id: issue.id
}
expect(response).to be_success
store_frontend_fixture(response, example.description)
end
end
| |
Fix updated session hash var name | require File.dirname(__FILE__) + "/../.centos/session.rb"
iso = "CentOS-6.4-x86_64-netinstall.iso"
iso_url = "http://mirror.yellowfiber.net/centos/6.4/isos/x86_64/#{iso}"
session =
COMMON_SESSION.merge({ :boot_cmd_sequence =>
[
'<Esc> ',
'linux text ks=http://%IP%:%PORT%/ks.cfg ',
'<Enter>'
],
:memory_size => "512",
:iso_file => iso,
:iso_md5 => "4a5fa01c81cc300f4729136e28ebe600",
:iso_src => "#{iso_url}" })
Veewee::Session.declare session
| require File.dirname(__FILE__) + "/../.centos/session.rb"
iso = "CentOS-6.4-x86_64-netinstall.iso"
iso_url = "http://mirror.yellowfiber.net/centos/6.4/isos/x86_64/#{iso}"
session =
CENTOS_SESSION.merge({ :boot_cmd_sequence =>
[
'<Esc> ',
'linux text ks=http://%IP%:%PORT%/ks.cfg ',
'<Enter>'
],
:memory_size => "512",
:iso_file => iso,
:iso_md5 => "4a5fa01c81cc300f4729136e28ebe600",
:iso_src => "#{iso_url}" })
Veewee::Session.declare session
|
Add more solution to problem | # Shortest String
# I worked on this challenge [by myself, with: ].
# shortest_string is a method that takes an array of strings as its input
# and returns the shortest string
#
# +list_of_words+ is an array of strings
# shortest_string(array) should return the shortest string in the +list_of_words+
#
# If +list_of_words+ is empty the method should return nil
#Your Solution Below
def shortest_string(list_of_words)
# Your code goes here!
return list_of_words[0].to_s if list_of_words.length == 1
smallest_word(list_of_words)
# smallest = list_of_words[0]
# list_of_words.each do |word|
# smallest = word if word.length < smallest.length
# end
# return smallest
end
def smallest_word(array)
smallest = array[0]
array.each do |word|
smallest = word if word.length < smallest.length
end
return smallest
end | # Shortest String
# I worked on this challenge [by myself, with: ].
# shortest_string is a method that takes an array of strings as its input
# and returns the shortest string
#
# +list_of_words+ is an array of strings
# shortest_string(array) should return the shortest string in the +list_of_words+
#
# If +list_of_words+ is empty the method should return nil
#Your Solution Below
def shortest_string(list_of_words)
# Your code goes here!
return list_of_words[0].to_s if list_of_words.length == 1
smallest_word(list_of_words)
# until_loop(list_of_words)
# for_loop(list_of_words)
# smallest = list_of_words[0]
# list_of_words.each do |word|
# smallest = word if word.length < smallest.length
# end
# return smallest
end
#solved with each loop
def smallest_word(array)
smallest = array[0]
array.each do |word|
smallest = word if word.length < smallest.length
end
return smallest
end
#solved with until loop
def until_loop(array)
shortest = array[0]
until array.empty?
word = array.shift
shortest = word if shortest.length > word.length
end
return shortest
end
#solved with for loop
def for_loop(array)
shortest = array[0]
for array in array[0..array.length]
shortest = array if shortest.length > array.length
end
return shortest
end |
Set app_host to localhost:3000 in interactive mode | def session
Capybara.app_host = "http://localhost:8070"
@session ||= Capybara::Session.new(:Akephalos)
end
alias page session
module Akephalos
class Console
def self.start
require 'irb'
begin
require 'irb/completion'
rescue Exception
# No readline available, proceed anyway.
end
if ::File.exists? ".irbrc"
ENV['IRBRC'] = ".irbrc"
end
IRB.start
end
end
end
| def session
Capybara.app_host = "http://localhost:3000"
@session ||= Capybara::Session.new(:Akephalos)
end
alias page session
module Akephalos
class Console
def self.start
require 'irb'
begin
require 'irb/completion'
rescue Exception
# No readline available, proceed anyway.
end
if ::File.exists? ".irbrc"
ENV['IRBRC'] = ".irbrc"
end
IRB.start
end
end
end
|
Configure Panopticon API using env var | # This file is overridden on deploy
PANOPTICON_API_CREDENTIALS = {
bearer_token: "developmentapicredentials",
}
| # This file is overridden on deploy
PANOPTICON_API_CREDENTIALS = {
bearer_token: ENV.fetch("PANOPTICON_BEARER_TOKEN", "developmentapicredentials"),
}
|
Package version increased from 0.0.1.5 to 0.0.1.6 | # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'event_store-client'
s.version = '0.0.1.5'
s.summary = 'Common code for the EventStore client'
s.description = ' '
s.authors = ['Obsidian Software, Inc']
s.email = 'opensource@obsidianexchange.com'
s.homepage = 'https://github.com/obsidian-btc/event-store-client'
s.licenses = ['MIT']
s.require_paths = ['lib']
s.files = Dir.glob('{lib}/**/*')
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.2.3'
s.add_runtime_dependency 'identifier-uuid'
s.add_runtime_dependency 'controls'
s.add_development_dependency 'test_bench'
end
| # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'event_store-client'
s.version = '0.0.1.6'
s.summary = 'Common code for the EventStore client'
s.description = ' '
s.authors = ['Obsidian Software, Inc']
s.email = 'opensource@obsidianexchange.com'
s.homepage = 'https://github.com/obsidian-btc/event-store-client'
s.licenses = ['MIT']
s.require_paths = ['lib']
s.files = Dir.glob('{lib}/**/*')
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.2.3'
s.add_runtime_dependency 'identifier-uuid'
s.add_runtime_dependency 'controls'
s.add_development_dependency 'test_bench'
end
|
Rename "children" in MultiSelectHash to "kv_pairs" | module JMESPath
# @api private
module Nodes
class MultiSelectHash < Node
def initialize(children)
@children = children
end
def visit(value)
if value.nil?
nil
else
@children.each_with_object({}) do |pair, hash|
hash[pair.key] = pair.value.visit(value)
end
end
end
def optimize
self.class.new(@children.map(&:optimize))
end
class KeyValuePair
attr_reader :key, :value
def initialize(key, value)
@key = key
@value = value
end
def optimize
self.class.new(@key, @value.optimize)
end
end
end
end
end
| module JMESPath
# @api private
module Nodes
class MultiSelectHash < Node
def initialize(kv_pairs)
@kv_pairs = kv_pairs
end
def visit(value)
if value.nil?
nil
else
@kv_pairs.each_with_object({}) do |pair, hash|
hash[pair.key] = pair.value.visit(value)
end
end
end
def optimize
self.class.new(@kv_pairs.map(&:optimize))
end
class KeyValuePair
attr_reader :key, :value
def initialize(key, value)
@key = key
@value = value
end
def optimize
self.class.new(@key, @value.optimize)
end
end
end
end
end
|
Update podspec to make it work | Pod::Spec.new do |s|
s.name = "meetup-swatches"
s.version = "0.4.0"
s.summary = "Color swatches for Meetup"
s.homepage = "https://github.com/meetup/meetup-swatches"
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.authors = { "Adam Detrick" => "adamd@meetup.com", "Richard Boenigk" => "richard@meetup.com" }
s.platform = :ios
s.source = { :git => "https://github.com/meetup/meetup-swatches.git", :tag => "0.4.0" }
s.resources = ['ios/colors.json']
s.requires_arc = true
end
| Pod::Spec.new do |s|
s.name = "meetup-swatches"
s.version = "0.6.1"
s.summary = "Color swatches for Meetup"
s.homepage = "https://github.com/meetup/meetup-swatches"
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.authors = { "Adam Detrick" => "adamd@meetup.com", "Richard Boenigk" => "richard@meetup.com" }
s.platform = :ios
s.source = { :git => "https://github.com/meetup/meetup-swatches.git", :tag => "v0.6.1" }
s.requires_arc = true
s.source_files = "ios/**/*.{h,m}"
s.public_header_files = "ios/**/*.h"
end
|
Fix the unit tests to match the code | require 'spec_helper'
describe 's3_dir::default' do
let(:chef_run) { ChefSpec::Runner.new.converge(described_recipe) }
before do
allow(Chef::EncryptedDataBagItem).to receive(:load).with('secrets', 'aws_credentials')
.and_return(
'RailsDeploy-dev' => {
'access_key_id' => 'SAMPLE_ACCESS_KEY_ID',
'secret_access_key' => 'SECRET_ACCESS_KEY'
}
)
end
it 'includes the `et_fog::default` recipe' do
expect(chef_run).to include_recipe 'et_fog::default'
end
it 'downloads `/tmp/provisioning` from S3' do
expect(chef_run).to create_s3_dir('/tmp/provisioning').with(
bucket: 'provisioning.evertrue.com',
dir: '/s3_dir_test',
access_key_id: 'SAMPLE_ACCESS_KEY_ID',
secret_access_key: 'SECRET_ACCESS_KEY'
)
end
end
| require 'spec_helper'
describe 's3_dir::default' do
let(:chef_run) { ChefSpec::Runner.new.converge(described_recipe) }
it 'includes the `et_fog::default` recipe' do
expect(chef_run).to include_recipe 'et_fog::default'
end
it 'downloads `/tmp/provisioning` from S3' do
expect(chef_run).to create_s3_dir('/tmp/provisioning').with(
bucket: 'test-directory',
dir: '/s3_dir_test',
access_key_id: 'TEST_KEY',
secret_access_key: 'TEST_SECRET'
)
end
end
|
Make PodSpec more concise (ARC is disabled by default) | Pod::Spec.new do |s|
s.name = 'BlocksKit'
s.version = '1.0.0'
s.license = 'MIT'
s.summary = 'The Objective-C block utilities you always wish you had.'
s.homepage = 'https://github.com/zwaldowski/BlocksKit'
s.author = { 'Zachary Waldowski' => 'zwaldowski@gmail.com',
'Alexsander Akers' => 'a2@pandamonia.us' }
s.source = { :git => 'https://github.com/zwaldowski/BlocksKit.git', :tag => 'v1.0.0' }
s.source_files = 'BlocksKit/*.{h,m}'
s.dependency = 'A2DynamicDelegate'
s.frameworks = 'MessageUI'
s.requires_arc = false
s.clean_paths = 'GHUnitIOS.framework/', 'Tests/', 'BlocksKit.xcodeproj/', '.gitignore'
def s.post_install(target)
prefix_header = config.project_pods_root + target.prefix_header_filename
prefix_header.open('a') do |file|
file.puts(%{#ifdef __OBJC__\n#import "BlocksKit.h"\n#endif})
end
end
end
| Pod::Spec.new do |s|
s.name = 'BlocksKit'
s.version = '1.0.0'
s.license = 'MIT'
s.summary = 'The Objective-C block utilities you always wish you had.'
s.homepage = 'https://github.com/zwaldowski/BlocksKit'
s.author = { 'Zachary Waldowski' => 'zwaldowski@gmail.com',
'Alexsander Akers' => 'a2@pandamonia.us' }
s.source = { :git => 'https://github.com/zwaldowski/BlocksKit.git', :tag => 'v1.0.0' }
s.source_files = 'BlocksKit/*.{h,m}'
s.dependency = 'A2DynamicDelegate'
s.frameworks = 'MessageUI'
s.clean_paths = 'GHUnitIOS.framework/', 'Tests/', 'BlocksKit.xcodeproj/', '.gitignore'
def s.post_install(target)
prefix_header = config.project_pods_root + target.prefix_header_filename
prefix_header.open('a') do |file|
file.puts(%{#ifdef __OBJC__\n#import "BlocksKit.h"\n#endif})
end
end
end
|
Raise an ArgumentError('Invalid date range') when start > end | class Api::DonationsController < ApplicationController
respond_to :json
# Fetches the sum of all donations (one off and recurring) for a given date range
# If a date range is not provided, it will default to donations in the current
# calendar month
def total
params.permit(:start, :end)
start_date = params.fetch(:start, Date.today.beginning_of_month).to_date
end_date = params.fetch(:end, Date.today.end_of_month).to_date
response = {
meta: { start: start_date.to_s, end: end_date.to_s },
data: {
total_donations: TransactionService.totals(start_date...end_date)
}
}
respond_with response
rescue ArgumentError
head :bad_request
end
end
| class Api::DonationsController < ApplicationController
respond_to :json
# Fetches the sum of all donations (one off and recurring) for a given date range
# If a date range is not provided, it will default to donations in the current
# calendar month
def total
params.permit(:start, :end)
start_date = params.fetch(:start, Date.today.beginning_of_month).to_date
end_date = params.fetch(:end, Date.today.end_of_month).to_date
raise ArgumentError, 'Invalid date range' if start_date > end_date
response = {
meta: { start: start_date.to_s, end: end_date.to_s },
data: {
total_donations: TransactionService.totals(start_date...end_date)
}
}
respond_with response
rescue ArgumentError
head :bad_request
end
end
|
Change error messages format from json to plain | class Api::V1::TokensController < Api::V1::ApplicationController
def create
user = User.find_by(email: params[:email].downcase)
if user && user.authenticate(params[:password])
if user.activated?
@token = User.new_token(urlsafe: false)
user.update_attribute(:api_digest, User.digest(@token))
@current_user = user
render status: 201
else
render(
json: { error: 'アカウントが有効化されていません。メールを確認してください' },
status: 401
)
end
else
render(
json: { error: '無効なメールアドレスとパスワードの組み合わせです' },
status: 401
)
end
end
end
| class Api::V1::TokensController < Api::V1::ApplicationController
def create
user = User.find_by(email: params[:email].downcase)
if user && user.authenticate(params[:password])
if user.activated?
@token = User.new_token(urlsafe: false)
user.update_attribute(:api_digest, User.digest(@token))
@current_user = user
render status: 201
else
render(
status: 401
plain: 'アカウントが有効化されていません。メールを確認してください',
)
end
else
render(
status: 401
plain: '無効なメールアドレスとパスワードの組み合わせです',
)
end
end
end
|
Use dpkg-query to get cdh version facts | require 'puppet'
Facter.add('cdh_version') do
setcode "/usr/bin/hadoop version | head -n 1 | awk -F '-cdh' '{print $2}'"
end
Facter.add('hadoop_version') do
setcode "/usr/bin/hadoop version | head -n 1 | awk '{print $2}' | awk -F '-cdh' '{print $1}'"
end
Facter.add('hive_version') do
setcode "/usr/bin/hive -e 'set system:sun.java.command;' 2> /dev/null | awk '{print $2}' | awk -F '-' '{print $3}'"
end
Facter.add('oozie_version') do
setcode "/usr/bin/oozie admin -version | awk -F ': ' '{print $2}' | awk -F '-' '{print $1}'"
end
| require 'puppet'
Facter.add('cdh_version') do
setcode "/usr/bin/dpkg-query --show hadoop | awk -F '+' '{print $2}'"
end
Facter.add('hadoop_version') do
setcode "/usr/bin/dpkg-query --show hadoop | awk '{print $2}' | awk -F '+' '{print $1}'"
end
Facter.add('hive_version') do
setcode "/usr/bin/dpkg-query --show hive | awk '{print $2}' | awk -F '+' '{print $1}'"
end
Facter.add('oozie_version') do
setcode "/usr/bin/dpkg-query --show oozie | awk '{print $2}' | awk -F '+' '{print $1}'"
end
|
Move active_record_extension.rb from begin...rescue for better debug message | module PluckAll
class Hooks
def self.init
# ActiveRecord
begin
require 'active_record'
require 'pluck_all/models/active_record_extension'
rescue LoadError, Gem::LoadError
end
# Mongoid
begin
require 'mongoid'
require 'pluck_all/models/mongoid_extension'
rescue LoadError, Gem::LoadError
end
end
end
end
PluckAll::Hooks.init
| module PluckAll
class Hooks
class << self
def init
require 'pluck_all/models/active_record_extension' if require_if_exists('active_record')
require 'pluck_all/models/mongoid_extension' if require_if_exists('mongoid')
end
private
def require_if_exists(path)
begin
require path
return true
rescue LoadError, Gem::LoadError
return false
end
end
end
end
end
PluckAll::Hooks.init
|
Add locale validation to test suite | RSpec.describe "locales files" do
it "should meet all locale validation requirements" do
checker = RailsTranslationManager::LocaleChecker.new("config/locales/*/*.yml")
expect(checker.validate_locales).to be_truthy
end
end
| |
Add a cask for Trailer.app. | class Trailer < Cask
url 'http://dev.housetrip.com/trailer/trailer107.zip'
homepage 'http://dev.housetrip.com/trailer/'
version '1.0.7'
sha1 '880b14ce4d4e6299f767aa997a30d83cd6e60575'
link 'Trailer.app'
end
| |
Fix the URL for your API token | module Cucumber
module Pro
module Error
AccessDenied = Class.new(StandardError) {
def initialize
super "Access denied."
end
}
MissingToken = Class.new(StandardError) {
def initialize
super "Missing access token. Please visit https://app.cucumber.pro/api-token for instructions."
end
}
Timeout = Class.new(StandardError) {
def initialize
super "Timed out waiting for a reply from the Cucumber Pro server."
end
}
end
end
end
| module Cucumber
module Pro
module Error
AccessDenied = Class.new(StandardError) {
def initialize
super "Access denied."
end
}
MissingToken = Class.new(StandardError) {
def initialize
super "Missing access token. Please visit https://app.cucumber.pro/my/profile for instructions."
end
}
Timeout = Class.new(StandardError) {
def initialize
super "Timed out waiting for a reply from the Cucumber Pro server."
end
}
end
end
end
|
Fix error handling configuration path when configuration file doesn't exist | module ActiveRecord::Turntable
class Railtie < Rails::Railtie
rake_tasks do
require "active_record/turntable/active_record_ext/database_tasks"
load "active_record/turntable/railties/databases.rake"
end
# rails loading hook
ActiveSupport.on_load(:before_initialize) do
ActiveSupport.on_load(:active_record) do
ActiveRecord::Base.include(ActiveRecord::Turntable)
end
end
# initialize
initializer "turntable.initialize_clusters" do |app|
app.paths.add "config/turntable", with: "config/turntable.rb"
app.paths.add "config/turntable", with: "config/turntable.yml"
ActiveSupport.on_load(:active_record) do
path = app.paths["config/turntable"].existent.first
self.turntable_configuration_file = path
if File.exist?(path)
reset_turntable_configuration(Configuration.load(turntable_configuration_file, Rails.env))
else
warn("[activerecord-turntable] config/turntable.{rb,yml} is not found. skipped initliazing cluster.")
end
end
end
# set QueryCache executor hooks for turntable clusters
initializer "turntable.set_executor_hooks" do
ActiveSupport.on_load(:active_record) do
ActiveRecord::Turntable::ActiveRecordExt::QueryCache.install_turntable_executor_hooks
end
end
end
end
| module ActiveRecord::Turntable
class Railtie < Rails::Railtie
rake_tasks do
require "active_record/turntable/active_record_ext/database_tasks"
load "active_record/turntable/railties/databases.rake"
end
# rails loading hook
ActiveSupport.on_load(:before_initialize) do
ActiveSupport.on_load(:active_record) do
ActiveRecord::Base.include(ActiveRecord::Turntable)
end
end
# initialize
initializer "turntable.initialize_clusters" do |app|
app.paths.add "config/turntable", with: "config/turntable.rb"
app.paths.add "config/turntable", with: "config/turntable.yml"
ActiveSupport.on_load(:active_record) do
path = app.paths["config/turntable"].existent.first
self.turntable_configuration_file = path
if path
reset_turntable_configuration(Configuration.load(turntable_configuration_file, Rails.env))
else
# FIXME: suppress this warning during rails g turntable:install
warn("[activerecord-turntable] config/turntable.{rb,yml} is not found. skipped initliazing cluster.")
end
end
end
# set QueryCache executor hooks for turntable clusters
initializer "turntable.set_executor_hooks" do
ActiveSupport.on_load(:active_record) do
ActiveRecord::Turntable::ActiveRecordExt::QueryCache.install_turntable_executor_hooks
end
end
end
end
|
Use the new "sexy" validations for Url | # A Url represents a page that can have Snapshots taken on it.
class Url < ActiveRecord::Base
validates_format_of :address, with: %r[\Ahttps?://.+]
belongs_to :project
validates_presence_of :project
has_many :snapshots
default_scope { order(:address) }
# @return [String]
def to_s
address
end
def title
accepted_snapshot = snapshots.where('accepted_at is not null').first
if accepted_snapshot.try(:title)
accepted_snapshot.title
else
simplified_address
end
end
# @return [Snapshot]
def baseline(viewport)
snapshots
.order('accepted_at DESC')
.where(viewport: viewport)
.where('accepted_at IS NOT NULL')
.first
end
def simplified_address
address.gsub(%r[(?:\Ahttp://|/\Z)], '')
end
# Get the two latest snapshots
#
# @return [Hash] (at most) two snapshots grouped by viewport
def last_snapshots_by_viewport
project.viewports.reduce({}) do |hash, viewport|
hash[viewport] = snapshots.where(viewport_id: viewport).first(2)
hash
end
end
end
| # A Url represents a page that can have Snapshots taken on it.
class Url < ActiveRecord::Base
validates :address, format: { with: %r[\Ahttps?://.+] }
belongs_to :project
validates :project, presence: true
has_many :snapshots
default_scope { order(:address) }
# @return [String]
def to_s
address
end
def title
accepted_snapshot = snapshots.where('accepted_at is not null').first
if accepted_snapshot.try(:title)
accepted_snapshot.title
else
simplified_address
end
end
# @return [Snapshot]
def baseline(viewport)
snapshots
.order('accepted_at DESC')
.where(viewport: viewport)
.where('accepted_at IS NOT NULL')
.first
end
def simplified_address
address.gsub(%r[(?:\Ahttp://|/\Z)], '')
end
# Get the two latest snapshots
#
# @return [Hash] (at most) two snapshots grouped by viewport
def last_snapshots_by_viewport
project.viewports.reduce({}) do |hash, viewport|
hash[viewport] = snapshots.where(viewport_id: viewport).first(2)
hash
end
end
end
|
Clean up token generator test | require_relative '../../../utils/sli_utils.rb'
require 'open3'
Given /^I used the long lived session token generator script to create a token for user "(.*?)" with role "(.*?)" for edorg "(.*?)" in tenant "(.*?)" for realm "(.*?)" that will expire in "(.*?)" seconds with client_id "(.*?)"$/ do |user, role, edorg, tenant, realm, expiration_in_seconds, client_id|
#Open3.capture2 seems to run a command from the directory the script was started in but we need to know exactly where
#the generator script is so we get the directory of this test with File.dirname(__FILE__) and go up a lot to get to the script
script_loc = File.dirname(__FILE__) + "/../../../../../../opstools/token-generator/generator.rb"
out, status = Open3.capture2("ruby #{script_loc} -e #{expiration_in_seconds} -c #{client_id} -u #{user} -r \"#{role}\" -E \"#{edorg}\" -t \"#{tenant}\" -R \"#{realm}\"")
match = /token is (.*)/.match(out)
@sessionId = match[1]
puts("The generated token is #{@sessionId}") if $SLI_DEBUG
end
Then /^I should see that my role is "(.*?)"$/ do |role|
restHttpGet("/system/session/check", "application/json")
check = JSON.parse(@res.body)
assert(check["sliRoles"].include?(role), "Expected #{role} got #{check["sliRoles"]}")
end
Then /^I should receive (\d+) section$/ do |arg1|
pending # express the regexp above with the code you wish you had
end
| require_relative '../../../utils/sli_utils.rb'
require 'open3'
Given /^I used the long lived session token generator script to create a token for user "(.*?)" with role "(.*?)" for edorg "(.*?)" in tenant "(.*?)" for realm "(.*?)" that will expire in "(.*?)" seconds with client_id "(.*?)"$/ do |user, role, edorg, tenant, realm, expiration_in_seconds, client_id|
#Open3.capture2 seems to run a command from the directory the script was started in but we need to know exactly where
#the generator script is so we get the directory of this test with File.dirname(__FILE__) and go up a lot to get to the script
script_loc = File.dirname(__FILE__) + '/../../../../../../opstools/token-generator/generator.rb'
out, status = Open3.capture2("ruby #{script_loc} -e #{expiration_in_seconds} -c #{client_id} -u #{user} -r \"#{role}\" -E \"#{edorg}\" -t \"#{tenant}\" -R \"#{realm}\"")
@sessionId = /token is (.*)/.match(out)[1]
puts("The generated token is #{@sessionId}") if $SLI_DEBUG
end
Then /^I should see that my role is "(.*?)"$/ do |role|
restHttpGet('/system/session/check')
check = JSON.parse(@res.body)
check['sliRoles'].should include(role)
end |
Update test: now paperclick don't parameterize filename | require 'test_helper'
class AttachmentFileTest < ActiveSupport::TestCase
def teardown
@attachment.destroy rescue nil
end
test "Set file content_type and size" do
@attachment = create_attachment
# TODO: fix filename parameterization
if CKEDITOR_BACKEND == :paperclip
assert_equal "rails_tar.gz", @attachment.data_file_name
else
assert_equal "rails.tar.gz", @attachment.data_file_name
end
assert_match /application\/(x-)?gzip/, @attachment.data_content_type
assert_equal 6823, @attachment.data_file_size
assert_equal "ckeditor/filebrowser/thumbs/gz.gif", @attachment.url_thumb
end
end
| require 'test_helper'
class AttachmentFileTest < ActiveSupport::TestCase
def teardown
@attachment.destroy rescue nil
end
test 'Set file content_type and size' do
@attachment = create_attachment
assert_equal "rails.tar.gz", @attachment.data_file_name
assert_match /application\/(x-)?gzip/, @attachment.data_content_type
assert_equal 6823, @attachment.data_file_size
assert_equal "ckeditor/filebrowser/thumbs/gz.gif", @attachment.url_thumb
end
end
|
Add Course Association for Club | class Club < ActiveRecord::Base
attr_accessible :name, :description, :price_cents, :logo
monetize :price_cents
validates :name, :presence => { :message => "for club can't be blank" }
validates :description, :presence => { :message => "for club can't be blank" }
validates :logo, :presence => true
validates :price_cents, :presence => true
validates :user_id, :presence => true
validates_numericality_of :price_cents, :greater_than_or_equal_to => Settings.clubs[:min_price_cents],
:message => "must be at least $#{Settings.clubs[:min_price_cents]/100}"
belongs_to :user
def assign_defaults
self.name = Settings.clubs[:default_name]
self.description = Settings.clubs[:default_description]
self.logo = Settings.clubs[:default_logo]
self.price_cents = Settings.clubs[:default_price_cents]
end
end
| class Club < ActiveRecord::Base
attr_accessible :name, :description, :price_cents, :logo
monetize :price_cents
validates :name, :presence => { :message => "for club can't be blank" }
validates :description, :presence => { :message => "for club can't be blank" }
validates :logo, :presence => true
validates :price_cents, :presence => true
validates :user_id, :presence => true
validates_numericality_of :price_cents, :greater_than_or_equal_to => Settings.clubs[:min_price_cents],
:message => "must be at least $#{Settings.clubs[:min_price_cents]/100}"
belongs_to :user
has_many :courses, :dependent => :destroy
def assign_defaults
self.name = Settings.clubs[:default_name]
self.description = Settings.clubs[:default_description]
self.logo = Settings.clubs[:default_logo]
self.price_cents = Settings.clubs[:default_price_cents]
end
end
|
Add Devise timeout to combat Rails session cookie issues | class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :invitable, :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable
end
| class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :invitable, :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable, :timeoutable
end
|
Add check for serialized attributes vulnerability | require 'brakeman/checks/base_check'
class Brakeman::CheckModelSerialize < Brakeman::BaseCheck
Brakeman::Checks.add self
@description = "Report uses of serialize in versions vulnerable to CVE-2013-0277"
def run_check
@upgrade_version = case
when version_between?("2.0.0", "2.3.16")
"2.3.17"
when version_between?("3.0.0", "3.0.99")
"3.2.11"
else
nil
end
return unless @upgrade_version
tracker.models.each do |name, model|
check_for_serialize model
end
end
#High confidence warning on serialized, unprotected attributes.
#Medium confidence warning for serialized, protected attributes.
def check_for_serialize model
if serialized_attrs = model[:options] && model[:options][:serialize]
attrs = Set.new
serialized_attrs.each do |arglist|
arglist.each do |arg|
attrs << arg if symbol? arg
end
end
if unsafe_attrs = model[:attr_accessible]
attrs.select! { |attr| unsafe_attrs.include? attr.value }
elsif protected_attrs = model[:options][:attr_protected]
safe_attrs = Set.new
protected_attrs.each do |arglist|
arglist.each do |arg|
safe_attrs << arg if symbol? arg
end
end
attrs.reject! { |attr| safe_attrs.include? attr }
end
if attrs.empty?
confidence = CONFIDENCE[:med]
else
confidence = CONFIDENCE[:high]
end
warn :model => model[:name],
:warning_type => "Remote Code Execution",
:message => "Serialized attributes are vulnerable in Rails #{tracker.config[:rails_version]}, upgrade to #{@upgrade_version} or patch.",
:confidence => confidence,
:link => "https://groups.google.com/d/topic/rubyonrails-security/KtmwSbEpzrU/discussion"
end
end
end
| |
Fix crash when posting invalid comments | # frozen_string_literal: true
class CommentsController < ApplicationController
before_action :authenticate_user!
def create
@ad = Ad.find params[:ad_id]
@comment = @ad.comments.build(comment_params)
if @comment.save
if @ad.user != current_user
CommentsMailer.create(@ad.id, @comment.body).deliver_later
end
redirect_to @ad, notice: t('nlt.comments.flash_ok')
else
render 'ads/show'
end
end
private
def comment_params
params.require(:comment)
.permit(:body)
.merge(user_owner: current_user.id, ip: request.remote_ip)
end
end
| # frozen_string_literal: true
class CommentsController < ApplicationController
before_action :authenticate_user!
def create
@ad = Ad.find params[:ad_id]
@comment = @ad.comments.build(comment_params)
if @comment.save
if @ad.user != current_user
CommentsMailer.create(@ad.id, @comment.body).deliver_later
end
flash[:notice] = t('nlt.comments.flash_ok')
else
flash[:alert] = t('nlt.comments.flash_ko')
end
redirect_to @ad
end
private
def comment_params
params.require(:comment)
.permit(:body)
.merge(user_owner: current_user.id, ip: request.remote_ip)
end
end
|
Use Time.now instead of Date.today for graphs. | class GraphsController < ApplicationController
# GET /graphs/running.xml
def running
@period = (Date.today - 30)..Date.today
respond_to do |format|
format.xml
end
end
# GET /graphs/spending.xml
def spending
@period = (Date.today - 30)..Date.today
respond_to do |format|
format.xml
end
end
end | class GraphsController < ApplicationController
# GET /graphs/running.xml
def running
@period = (Time.now.to_date - 30)..Time.now.to_date
respond_to do |format|
format.xml
end
end
# GET /graphs/spending.xml
def spending
@period = (Time.now.to_date - 30)..Time.now.to_date
respond_to do |format|
format.xml
end
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.