Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add full_name field to the reverse_dependencies payload | class Api::V1::VersionsController < Api::BaseController
respond_to :json, :xml, :yaml
before_filter :find_rubygem
def show
if @rubygem.public_versions.count.nonzero?
if stale?(@rubygem)
respond_with(@rubygem.public_versions, :yamlish => true)
end
else
render :text => "This rubygem could not be found.", :status => 404
end
end
def reverse_dependencies
respond_with(Version.reverse_dependencies(params[:id]), :yamlish => true)
end
end
| class Api::V1::VersionsController < Api::BaseController
respond_to :json, :xml, :yaml
before_filter :find_rubygem
def show
if @rubygem.public_versions.count.nonzero?
if stale?(@rubygem)
respond_with(@rubygem.public_versions, :yamlish => true)
end
else
render :text => "This rubygem could not be found.", :status => 404
end
end
def reverse_dependencies
versions = Version.reverse_dependencies(params[:id])
respond_to do |format|
format.json { render :json => versions.map { |v| v.as_json.merge("full_name" => v.full_name) } }
format.xml { render :xml => versions.map { |v| v.payload.merge("full_name" => v.full_name) } }
format.yaml { render :text => versions.map { |v| v.payload.merge("full_name" => v.full_name) }.to_yaml }
end
end
end
|
Add compatibility with rails >= 4 | # Plugin's routes
# See: http://guides.rubyonrails.org/routing.html
match 'meeting_room_calendar/', :to => 'meeting_room_calendar#index'
match 'meeting_room_calendar/:project_id', :to => 'meeting_room_calendar#index', :project_id => /\d+/
match 'meeting_room_calendar/index', :to => 'meeting_room_calendar#index'
match 'meeting_room_calendar/index/:project_id', :to => 'meeting_room_calendar#index', :project_id => /\d+/
match 'meeting_room_calendar/missing_config', :to => 'meeting_room_calendar#missing_config'
match 'meeting_room_calendar/create', :to => 'meeting_room_calendar#create'
match 'meeting_room_calendar/update', :to => 'meeting_room_calendar#update'
match 'meeting_room_calendar/delete', :to => 'meeting_room_calendar#delete' | # Plugin's routes
# See: http://guides.rubyonrails.org/routing.html
get 'meeting_room_calendar/', :to => 'meeting_room_calendar#index'
get 'meeting_room_calendar/:project_id', :to => 'meeting_room_calendar#index', :project_id => /\d+/
get 'meeting_room_calendar/index', :to => 'meeting_room_calendar#index'
get 'meeting_room_calendar/index/:project_id', :to => 'meeting_room_calendar#index', :project_id => /\d+/
get 'meeting_room_calendar/missing_config', :to => 'meeting_room_calendar#missing_config'
get 'meeting_room_calendar/create', :to => 'meeting_room_calendar#create'
get 'meeting_room_calendar/update', :to => 'meeting_room_calendar#update'
get 'meeting_room_calendar/delete', :to => 'meeting_room_calendar#delete' |
Create category object to test the uniqueness of name | require 'spec_helper'
describe Category do
describe 'associations' do
it { should have_many :projects }
end
describe 'validations' do
it { should validate_presence_of :name_pt }
it { should validate_uniqueness_of :name_pt }
end
describe '.with_projects' do
let(:category) { create(:category) }
context 'when category has a project' do
let!(:project) { create(:project, category: category) }
it 'returns categories with projects' do
expect(described_class.with_projects).to eq [category]
end
end
context 'when category has no project' do
it 'returns an empty array' do
expect(described_class.with_projects).to eq []
end
end
end
describe '.array' do
it 'returns an array with categories' do
category = create(:category)
expect(described_class.array).to eq [['Select an option', ''],
[category.name_en, category.id]]
end
end
end
| require 'spec_helper'
describe Category do
describe 'associations' do
it { should have_many :projects }
end
describe 'validations' do
it { should validate_presence_of :name_pt }
it do
create(:category)
should validate_uniqueness_of :name_pt
end
end
describe '.with_projects' do
let(:category) { create(:category) }
context 'when category has a project' do
let!(:project) { create(:project, category: category) }
it 'returns categories with projects' do
expect(described_class.with_projects).to eq [category]
end
end
context 'when category has no project' do
it 'returns an empty array' do
expect(described_class.with_projects).to eq []
end
end
end
describe '.array' do
it 'returns an array with categories' do
category = create(:category)
expect(described_class.array).to eq [['Select an option', ''],
[category.name_en, category.id]]
end
end
end
|
Add oauth_company to app instance | json.id app_instance.id
json.uid app_instance.uid
json.stack app_instance.stack
json.name app_instance.name
json.status app_instance.status
json.oauth_keys_valid app_instance.oauth_keys_valid
#json.http_url app_instance.http_url
#json.microsoft_trial_url app_instance.microsoft_trial_url
json.created_at app_instance.created_at
if app_instance.connector_stack? && app_instance.oauth_keys_valid && app_instance.oauth_company
json.oauth_company_name app_instance.oauth_company
end
#
# if app_instance.connector_stack? && app_instance.oauth_keys && app_instance.oauth_keys[:version]
# json.connector_version app_instance.oauth_keys[:version]
# end
app_instance.app.tap do |a|
json.app_name a.name
json.app_nid a.nid
json.logo a.logo
end
| json.id app_instance.id
json.uid app_instance.uid
json.stack app_instance.stack
json.name app_instance.name
json.status app_instance.status
json.oauth_keys_valid app_instance.oauth_keys_valid
#json.http_url app_instance.http_url
#json.microsoft_trial_url app_instance.microsoft_trial_url
json.created_at app_instance.created_at
if app_instance.oauth_company
json.oauth_company_name app_instance.oauth_company
end
#
# if app_instance.connector_stack? && app_instance.oauth_keys && app_instance.oauth_keys[:version]
# json.connector_version app_instance.oauth_keys[:version]
# end
app_instance.app.tap do |a|
json.app_name a.name
json.app_nid a.nid
json.logo a.logo
end
|
Change load order to match PHP app | module DataLoader
class Debates
# The options hash takes:
# :from_date - Date to parse from (just specify this date if you only want one )
# :to_date - A single date
def self.load!(options = {})
dates = if options[:to_date]
Date.parse(options[:from_date])..Date.parse(options[:to_date])
else
[Date.parse(options[:from_date])]
end
dates.each do |date|
House.australian.each do |house|
# TODO: Check for the file first rather than catching the exception
begin
xml_data = File.read("#{Settings.xml_data_directory}/scrapedxml/#{house}_debates/#{date}.xml")
rescue Errno::ENOENT
Rails.logger.info "No XML file found for #{house} on #{date}"
next
end
debates = DebatesXML.new(xml_data, house)
Rails.logger.info "No debates found in XML for #{house} on #{date}" if debates.divisions.empty?
debates.divisions.each do |division|
Rails.logger.info "Saving division: #{division.house} #{division.date} #{division.number}"
division.save!
end
end
end
end
end
end
| module DataLoader
class Debates
# The options hash takes:
# :from_date - Date to parse from (just specify this date if you only want one )
# :to_date - A single date
def self.load!(options = {})
dates = if options[:to_date]
Date.parse(options[:from_date])..Date.parse(options[:to_date])
else
[Date.parse(options[:from_date])]
end
House.australian.each do |house|
dates.each do |date|
# TODO: Check for the file first rather than catching the exception
begin
xml_data = File.read("#{Settings.xml_data_directory}/scrapedxml/#{house}_debates/#{date}.xml")
rescue Errno::ENOENT
Rails.logger.info "No XML file found for #{house} on #{date}"
next
end
debates = DebatesXML.new(xml_data, house)
Rails.logger.info "No debates found in XML for #{house} on #{date}" if debates.divisions.empty?
debates.divisions.each do |division|
Rails.logger.info "Saving division: #{division.house} #{division.date} #{division.number}"
division.save!
end
end
end
end
end
end
|
Add tasks for delayed job | Capistrano::Configuration.instance.load do
set(:delayed_job_application_name) { "#{application}_delayed_job" }
namespace :delayed_job do
namespace :upstart do
%w(restart start stop status).each do |t|
desc "Perform #{t} of the delayed_job service"
task t, roles: :app, except: { no_release: true } do
sudo "#{t} #{delayed_job_application_name}"
end
end
end
end
end
| |
Add error for exiting the application | module LetsencryptWebfaction
class Error < StandardError; end
class InvalidConfigValueError < Error; end
end
| module LetsencryptWebfaction
class Error < StandardError; end
class InvalidConfigValueError < Error; end
class AppExitError < Error; end
end
|
Add some convenience methods to Yaks::Resource::Form and ::Field | module Yaks
class Resource
class Form
include Yaks::Mapper::Form.attributes
class Field
include Yaks::Mapper::Form::Field.attributes
end
end
end
end
| module Yaks
class Resource
class Form
include Yaks::Mapper::Form.attributes
def [](name)
fields.find {|field| field.name == name}.value
end
def values
fields.each_with_object({}) do |field, values|
values[field.name] = field.value
end
end
class Field
include Yaks::Mapper::Form::Field.attributes.add(:error => nil)
def value(arg = Undefined)
return @value if arg.eql?(Undefined)
if type == :select
selected = options.find { |option| option.selected }
selected.value if selected
else
update(value: arg)
end
end
end
end
end
end
|
Make this ruby 2.0 compatible | module Servizio::Service::InheritedHandler
def inherited(subclass)
subclass.instance_eval do
alias :original_new :new
def self.inherited(subsubclass)
subsubclass.extend(Servizio::Service::InheritedHandler)
end
def self.new(*args, &block)
(obj = original_new(*args, &block)).singleton_class.prepend(Servizio::Service::Call)
return obj
end
end
end
end
| module Servizio::Service::InheritedHandler
def inherited(subclass)
subclass.instance_eval do
alias :original_new :new
def self.inherited(subsubclass)
subsubclass.extend(Servizio::Service::InheritedHandler)
end
def self.new(*args, &block)
(obj = original_new(*args, &block)).singleton_class.send(:prepend, Servizio::Service::Call)
return obj
end
end
end
end
|
Fix argument splatting on Ruby 1.8 | require "date"
require "active_support"
require "active_support/core_ext/class/attribute"
require "i18n"
require "i18n_alchemy/date_parser"
require "i18n_alchemy/time_parser"
require "i18n_alchemy/numeric_parser"
require "i18n_alchemy/attribute"
require "i18n_alchemy/association_parser"
require "i18n_alchemy/attributes_parsing"
require "i18n_alchemy/proxy"
module I18n
module Alchemy
extend ActiveSupport::Concern
def localized(attributes=nil, *args)
I18n::Alchemy::Proxy.new(self, attributes, *args)
end
included do
class_attribute :localized_methods,
:instance_reader => false, :instance_writer => false
self.localized_methods = {}
end
module ClassMethods
def localize(*methods, options)
parser = options[:using]
methods = methods.each_with_object(localized_methods) do |method_name, hash|
hash[method_name] = parser
end
self.localized_methods = methods
end
end
end
end
| require "date"
require "active_support"
require "active_support/core_ext/class/attribute"
require "i18n"
require "i18n_alchemy/date_parser"
require "i18n_alchemy/time_parser"
require "i18n_alchemy/numeric_parser"
require "i18n_alchemy/attribute"
require "i18n_alchemy/association_parser"
require "i18n_alchemy/attributes_parsing"
require "i18n_alchemy/proxy"
module I18n
module Alchemy
extend ActiveSupport::Concern
def localized(attributes=nil, *args)
I18n::Alchemy::Proxy.new(self, attributes, *args)
end
included do
class_attribute :localized_methods,
:instance_reader => false, :instance_writer => false
self.localized_methods = {}
end
module ClassMethods
def localize(*methods)
options = methods.extract_options!
parser = options[:using]
methods = methods.each_with_object(localized_methods) do |method_name, hash|
hash[method_name] = parser
end
self.localized_methods = methods
end
end
end
end
|
Rename pass_hash to md5_pass_hash, modify md5_pass_hash, add target_to_str method. | require 'sms_gear_api/version'
require 'net/http'
require 'digest/md5'
module SmsGearApi
class Base
attr_accessor :login, :passw
def initialize(params = {})
@login = params[:login]
@passw = params[:passw]
end
def send_sms(params = {})
true
end
private
def pass_hash
return @pass_hash if @pass_hash
@pass_hash = Digest::MD5.hexdigest @pass
end
end
end
| require 'sms_gear_api/version'
require 'net/http'
require 'digest/md5'
module SmsGearApi
class Base
attr_accessor :login, :passw
def initialize(params = {})
@login = params[:login]
@passw = params[:passw]
end
def send_sms(params = {})
true
end
private
def md5_pass_hash
return @pass_hash if @pass_hash
@pass_hash = Digest::MD5.hexdigest @passw if @passw
end
def target_to_str(target)
target.respond_to?(:join) ? target.join(', ') : target
end
end
end
|
Update local domain for chrome | require 'uri'
class SuperSearch
def self.url
"http://search.alaska.dev/"
end
def self.query_param_for(item_name)
# item_name.gsub(/\s+/, '+')
URI.encode item_name
end
def self.url_for(item_name)
"#{SuperSearch.url}index.php?q=#{SuperSearch.query_param_for(item_name)}"
end
def self.url_for_engine(engine_key, item_name)
SuperSearch.url + engine_key + '/' + SuperSearch.query_param_for(item_name)
end
end | require 'uri'
class SuperSearch
def self.url
"http://search.alaska.test/"
end
def self.query_param_for(item_name)
# item_name.gsub(/\s+/, '+')
URI.encode item_name
end
def self.url_for(item_name)
"#{SuperSearch.url}index.php?q=#{SuperSearch.query_param_for(item_name)}"
end
def self.url_for_engine(engine_key, item_name)
SuperSearch.url + engine_key + '/' + SuperSearch.query_param_for(item_name)
end
end
|
Make some dependancies dev dependancies. | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'locationary/version'
Gem::Specification.new do |spec|
spec.name = "locationary"
spec.version = Locationary::VERSION
spec.authors = ["Oren Mazor"]
spec.email = ["oren.mazor@gmail.com"]
spec.description = "Gem to normalize and auto-correct location information"
spec.summary = "Gem to normalize and auto-correct location information"
spec.homepage = "https://github.com/Shopify/locationary"
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_runtime_dependency "bundler"
spec.add_runtime_dependency "rake"
spec.add_runtime_dependency "msgpack"
spec.add_runtime_dependency "minitest"
spec.add_runtime_dependency "zipruby", "0.3.6"
spec.add_runtime_dependency "snappy"
spec.add_runtime_dependency "pry"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'locationary/version'
Gem::Specification.new do |spec|
spec.name = "locationary"
spec.version = Locationary::VERSION
spec.authors = ["Oren Mazor"]
spec.email = ["oren.mazor@gmail.com"]
spec.description = "Gem to normalize and auto-correct location information"
spec.summary = "Gem to normalize and auto-correct location information"
spec.homepage = "https://github.com/Shopify/locationary"
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_runtime_dependency "msgpack"
spec.add_runtime_dependency "zipruby", "0.3.6"
spec.add_runtime_dependency "snappy"
spec.add_development_dependency "bundler"
spec.add_development_dependency "rake"
spec.add_development_dependency 'minitest'
spec.add_development_dependency "pry"
end
|
Remove spec files from gemspec | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "rb-fsevent/version"
Gem::Specification.new do |s|
s.name = 'rb-fsevent'
s.version = FSEvent::VERSION
s.authors = ['Thibaud Guillaume-Gentil', 'Travis Tilley']
s.email = ['thibaud@thibaud.gg', 'ttilley@gmail.com']
s.homepage = 'http://rubygems.org/gems/rb-fsevent'
s.summary = 'Very simple & usable FSEvents API'
s.description = 'FSEvents API with Signals catching (without RubyCocoa)'
s.license = 'MIT'
s.files = `git ls-files`.split($/)
s.test_files = s.files.grep(%r{^spec/})
s.require_path = 'lib'
s.add_development_dependency 'bundler', '~> 1.0'
s.add_development_dependency 'rspec', '~> 2.11'
s.add_development_dependency 'guard-rspec', '~> 4.2'
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "rb-fsevent/version"
Gem::Specification.new do |s|
s.name = 'rb-fsevent'
s.version = FSEvent::VERSION
s.authors = ['Thibaud Guillaume-Gentil', 'Travis Tilley']
s.email = ['thibaud@thibaud.gg', 'ttilley@gmail.com']
s.homepage = 'http://rubygems.org/gems/rb-fsevent'
s.summary = 'Very simple & usable FSEvents API'
s.description = 'FSEvents API with Signals catching (without RubyCocoa)'
s.license = 'MIT'
s.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^spec/}) }
s.require_path = 'lib'
s.add_development_dependency 'bundler', '~> 1.0'
s.add_development_dependency 'rspec', '~> 2.11'
s.add_development_dependency 'guard-rspec', '~> 4.2'
end
|
Remove unused and untested methods | # View Helpers for Hydra Batch Edit functionality
module BatchSelectHelper
# determines if the given document id is in the batch
# def item_in_batch?(doc_id)
# session[:batch_document_ids] && session[:batch_document_ids].include?(doc_id) ? true : false
# end
# Displays the batch edit tools. Put this in your search result page template. We recommend putting it in catalog/_sort_and_per_page.html.erb
def batch_select_tools
render partial: '/batch_select/tools'
end
# Displays the button to select/deselect items for your batch. Call this in the index partial that's rendered for each search result.
# @param [Hash] document the Hash (aka Solr hit) for one Solr document
def button_for_add_to_batch(document)
render partial: '/batch_select/add_button', locals: { document: document }
end
# Displays the check all button to select/deselect items for your batch. Put this in your search result page template. We put it in catalog/index.html
def batch_check_all(label = 'Use all results')
render partial: '/batch_select/check_all', locals: { label: label }
end
end
| # View Helpers for Hydra Batch Edit functionality
module BatchSelectHelper
# Displays the button to select/deselect items for your batch. Call this in the index partial that's rendered for each search result.
# @param [Hash] document the Hash (aka Solr hit) for one Solr document
def button_for_add_to_batch(document)
render partial: '/batch_select/add_button', locals: { document: document }
end
end
|
Support the latest rollout version | # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "rollout_ui/version"
Gem::Specification.new do |gem|
gem.name = "rollout_ui"
gem.version = RolloutUi::Version
gem.authors = ["John Allison"]
gem.email = ["jrallison@gmail.com"]
gem.description = %q{A UI for James Golick's rollout gem}
gem.summary = %q{A UI for James Golick's rollout gem}
gem.homepage = "http://github.com/jrallison/rollout_ui"
gem.files = Dir["lib/**/*"] + ["Rakefile", "README.markdown"]
gem.test_files = Dir["spec/**/*"]
gem.require_paths = ["lib"]
gem.add_runtime_dependency('rollout', '~> 1.0.0')
gem.add_development_dependency('rake')
gem.add_development_dependency('rails')
gem.add_development_dependency('sinatra')
gem.add_development_dependency('uglifier')
gem.add_development_dependency('mysql')
gem.add_development_dependency('rspec-rails')
gem.add_development_dependency('capybara')
gem.add_development_dependency('launchy')
gem.add_development_dependency('rack-test')
gem.add_development_dependency('redis-namespace')
end
| # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "rollout_ui/version"
Gem::Specification.new do |gem|
gem.name = "rollout_ui"
gem.version = RolloutUi::Version
gem.authors = ["John Allison"]
gem.email = ["jrallison@gmail.com"]
gem.description = %q{A UI for James Golick's rollout gem}
gem.summary = %q{A UI for James Golick's rollout gem}
gem.homepage = "http://github.com/jrallison/rollout_ui"
gem.files = Dir["lib/**/*"] + ["Rakefile", "README.markdown"]
gem.test_files = Dir["spec/**/*"]
gem.require_paths = ["lib"]
gem.add_runtime_dependency('rollout', '~> 1.1.0')
gem.add_development_dependency('rake')
gem.add_development_dependency('rails')
gem.add_development_dependency('sinatra')
gem.add_development_dependency('uglifier')
gem.add_development_dependency('mysql')
gem.add_development_dependency('rspec-rails')
gem.add_development_dependency('capybara')
gem.add_development_dependency('launchy')
gem.add_development_dependency('rack-test')
gem.add_development_dependency('redis-namespace')
end
|
Fix wrong documentation in the Space API | module BacklogKit
class Client
# Methods for the Space API
module Space
# Get a space
#
# @return [BacklogKit::Response] The space information
def get_space
get('space')
end
# Get list of groups
#
# @param params [Hash] Request parameters
# @return [BacklogKit::Response] List of recent updates in your space
def get_space_activities(params = {})
get('space/activities', params)
end
# Download a space logo image
#
# @return [BacklogKit::Response] Binary image data
def download_space_icon
get('space/image')
end
# Get a space notification
#
# @return [BacklogKit::Response] The notification information
def get_space_notification
get('space/notification')
end
# Update a space notification
#
# @param content [String] Content of the notification
# @return [BacklogKit::Response] The notification information
def update_space_notification(content)
put('space/notification', content: content)
end
# Get a space disk usage
#
# @return [BacklogKit::Response] The disk usage
def get_space_disk_usage
get('space/diskUsage')
end
# Upload attachment file for issue or wiki
#
# @param file_path [String] Path of the file
# @return [BacklogKit::Response] The file information
def upload_attachment(file_path)
payload = { file: Faraday::UploadIO.new(file_path, 'application/octet-stream') }
post('space/attachment', payload)
end
end
end
end
| module BacklogKit
class Client
# Methods for the Space API
module Space
# Get a space
#
# @return [BacklogKit::Response] The space information
def get_space
get('space')
end
# Get list of space activities
#
# @param params [Hash] Request parameters
# @return [BacklogKit::Response] List of recent updates in your space
def get_space_activities(params = {})
get('space/activities', params)
end
# Download a space logo image
#
# @return [BacklogKit::Response] Binary image data
def download_space_icon
get('space/image')
end
# Get a space notification
#
# @return [BacklogKit::Response] The notification information
def get_space_notification
get('space/notification')
end
# Update a space notification
#
# @param content [String] Content of the notification
# @return [BacklogKit::Response] The notification information
def update_space_notification(content)
put('space/notification', content: content)
end
# Get a space disk usage
#
# @return [BacklogKit::Response] The disk usage
def get_space_disk_usage
get('space/diskUsage')
end
# Upload attachment file for issue or wiki
#
# @param file_path [String] Path of the file
# @return [BacklogKit::Response] The file information
def upload_attachment(file_path)
payload = { file: Faraday::UploadIO.new(file_path, 'application/octet-stream') }
post('space/attachment', payload)
end
end
end
end
|
Fix StrictMassAssignment specs on 1.8 where symbols cannot be sorted. | require "active_attr/mass_assignment"
require "active_attr/unknown_attributes_error"
require "active_support/concern"
module ActiveAttr
# StrictMassAssignment allows mass assignment of attributes, but raises an
# exception when assigning unknown attributes
#
# Attempting to assign any unknown or private attribute through any of the
# mass assignment methods ({#assign_attributes}, {#attributes=}, and
# {#initialize}) will raise an {ActiveAttr::UnknownAttributesError}
# exception.
#
# @example Usage
# class Person
# include ActiveAttr::StrictMassAssignment
# end
#
# @since 0.2.0
module StrictMassAssignment
extend ActiveSupport::Concern
include MassAssignment
# Mass update a model's attributes, but raise an error if an attempt is
# made to assign an unknown attribute
#
# @param (see MassAssignment#assign_attributes)
#
# @raise [ActiveAttr::UnknownAttributesError]
#
# @since 0.2.0
def assign_attributes(new_attributes, options={})
unknown_attribute_names = (new_attributes || {}).reject do |name, value|
respond_to? "#{name}="
end.map { |name, value| name }.sort
if unknown_attribute_names.any?
raise UnknownAttributesError, "unknown attribute(s): #{unknown_attribute_names.join(", ")}"
else
super
end
end
end
end
| require "active_attr/mass_assignment"
require "active_attr/unknown_attributes_error"
require "active_support/concern"
module ActiveAttr
# StrictMassAssignment allows mass assignment of attributes, but raises an
# exception when assigning unknown attributes
#
# Attempting to assign any unknown or private attribute through any of the
# mass assignment methods ({#assign_attributes}, {#attributes=}, and
# {#initialize}) will raise an {ActiveAttr::UnknownAttributesError}
# exception.
#
# @example Usage
# class Person
# include ActiveAttr::StrictMassAssignment
# end
#
# @since 0.2.0
module StrictMassAssignment
extend ActiveSupport::Concern
include MassAssignment
# Mass update a model's attributes, but raise an error if an attempt is
# made to assign an unknown attribute
#
# @param (see MassAssignment#assign_attributes)
#
# @raise [ActiveAttr::UnknownAttributesError]
#
# @since 0.2.0
def assign_attributes(new_attributes, options={})
unknown_attribute_names = (new_attributes || {}).reject do |name, value|
respond_to? "#{name}="
end.map { |name, value| name.to_s }.sort
if unknown_attribute_names.any?
raise UnknownAttributesError, "unknown attribute(s): #{unknown_attribute_names.join(", ")}"
else
super
end
end
end
end
|
Update sniff dependency to 1.x | # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "motorcycle/version"
Gem::Specification.new do |s|
s.name = %q{motorcycle}
s.version = BrighterPlanet::Motorcycle::VERSION
s.authors = ["Andy Rossmeissl", "Seamus Abshere", "Ian Hough", "Matt Kling", "Derek Kastner"]
s.date = "2012-06-12"
s.summary = %q{A carbon model}
s.description = %q{A software model in Ruby for the greenhouse gas emissions of an motorcycle}
s.email = %q{andy@rossmeissl.net}
s.homepage = %q{http://github.com/brighterplanet/motorcycle}
s.extra_rdoc_files = [
"LICENSE",
"README.rdoc"
]
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.add_runtime_dependency 'earth', '~>0.12.0'
s.add_dependency 'emitter', '~> 1.0.0'
s.add_development_dependency 'sniff', '~>0.11.3'
s.add_development_dependency 'sqlite3'
end
| # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "motorcycle/version"
Gem::Specification.new do |s|
s.name = %q{motorcycle}
s.version = BrighterPlanet::Motorcycle::VERSION
s.authors = ["Andy Rossmeissl", "Seamus Abshere", "Ian Hough", "Matt Kling", "Derek Kastner"]
s.date = "2012-06-12"
s.summary = %q{A carbon model}
s.description = %q{A software model in Ruby for the greenhouse gas emissions of an motorcycle}
s.email = %q{andy@rossmeissl.net}
s.homepage = %q{http://github.com/brighterplanet/motorcycle}
s.extra_rdoc_files = [
"LICENSE",
"README.rdoc"
]
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.add_runtime_dependency 'earth', '~>0.12.0'
s.add_dependency 'emitter', '~> 1.0.0'
s.add_development_dependency 'sniff', '~> 1.0.0'
s.add_development_dependency 'sqlite3'
end
|
Remove carriage return from the current rev sha t:5 | require 'net/http'
require 'uri'
unless Capistrano::Configuration.respond_to?(:instance)
abort "capistrano_deploy_webhook requires Capistrano 2"
end
GIT_USER_EMAIL = `git config --get user.email`
GIT_CURRENT_REV = `git rev-parse HEAD`
GIT_CURRENT_REV_SHORT = GIT_CURRENT_REV[0,7]
Capistrano::Configuration.instance.load do
after :deploy, "notify:post_request"
namespace :notify do
task :post_request do
application_name = `pwd`.chomp.split('/').last
puts "*** Notification POST to #{self[:notify_url]} for #{application_name}"
url = URI.parse("#{self[:notify_url]}")
req = Net::HTTP::Post.new(url.path)
req.set_form_data(
{'app' => application_name,
'user' => GIT_USER_EMAIL.chomp,
'head' => GIT_CURRENT_REV_SHORT,
'head_long' => GIT_CURRENT_REV,
'prev_head' => self[:previous_revision],
'url' => self[:url]},
';')
res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
end
end
end
| require 'net/http'
require 'uri'
unless Capistrano::Configuration.respond_to?(:instance)
abort "capistrano_deploy_webhook requires Capistrano 2"
end
GIT_USER_EMAIL = `git config --get user.email`
GIT_CURRENT_REV = `git rev-parse HEAD`
GIT_CURRENT_REV_SHORT = GIT_CURRENT_REV[0,7]
Capistrano::Configuration.instance.load do
after :deploy, "notify:post_request"
namespace :notify do
task :post_request do
application_name = `pwd`.chomp.split('/').last
puts "*** Notification POST to #{self[:notify_url]} for #{application_name}"
url = URI.parse("#{self[:notify_url]}")
req = Net::HTTP::Post.new(url.path)
req.set_form_data(
{'app' => application_name,
'user' => GIT_USER_EMAIL.chomp,
'head' => GIT_CURRENT_REV_SHORT,
'head_long' => GIT_CURRENT_REV.chomp,
'prev_head' => self[:previous_revision],
'url' => self[:url]},
';')
res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
end
end
end
|
Add foreign key constraint to data bag items | require File.expand_path('../settings', __FILE__)
Sequel.migration do
change do
alter_table(:data_bag_items) do
add_foreign_key [:org_id, :data_bag_name], :data_bags, :key => [:org_id, :name], :on_delete => :cascade, :on_update => :cascade
end
end
end
| |
Remove java dependency for netacuity | maintainer "Webtrends, Inc."
maintainer_email "tim.smith@webtrends.com"
license "All rights reserved"
description "Installs/Configures NetAcuity with a Webtrends license"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version "1.0.9"
depends "java" | maintainer "Webtrends, Inc."
maintainer_email "tim.smith@webtrends.com"
license "All rights reserved"
description "Installs/Configures NetAcuity with a Webtrends license"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version "1.0.9" |
Rollback min password length to 4 | class User < ActiveRecord::Base
acts_as_authentic do |config|
config.crypto_provider = Authlogic::CryptoProviders::BCrypt
end
has_many :territorial_authorities, foreign_key: :coordinator_id
scope :coordinators, -> { where(admin: false) }
scope :unassigned_coordinators, -> {
coordinators.
joins('LEFT OUTER JOIN territorial_authorities ON territorial_authorities.coordinator_id = users.id').
where('territorial_authorities.coordinator_id IS NULL')
}
validates :name, :email, presence: true
def new_contacts
Customer.contactable.for_districts(territorial_authorities.pluck(:id))
end
end
| class User < ActiveRecord::Base
acts_as_authentic do |config|
config.validates_length_of_password_field_options = { minimum: 4 }
config.crypto_provider = Authlogic::CryptoProviders::BCrypt
end
has_many :territorial_authorities, foreign_key: :coordinator_id
scope :coordinators, -> { where(admin: false) }
scope :unassigned_coordinators, -> {
coordinators.
joins('LEFT OUTER JOIN territorial_authorities ON territorial_authorities.coordinator_id = users.id').
where('territorial_authorities.coordinator_id IS NULL')
}
validates :name, :email, presence: true
def new_contacts
Customer.contactable.for_districts(territorial_authorities.pluck(:id))
end
end
|
Fix foreign key from commenter_id to responder_id | class User < ActiveRecord::Base
has_many :questions, foreign_key: :asker_id
has_many :answers, foreign_key: :responder_id
has_many :votes, foreign_key: :voter_id
has_many :responses, foreign_key: :commenter_id
end
| class User < ActiveRecord::Base
has_many :questions, foreign_key: :asker_id
has_many :answers, foreign_key: :responder_id
has_many :votes, foreign_key: :voter_id
has_many :responses, foreign_key: :responder_id
end
|
Add webpacker dev server to CSP initializer | # Be sure to restart your server when you modify this file.
# Define an application-wide content security policy
# For further information see the following documentation
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
# Rails.application.config.content_security_policy do |policy|
# policy.default_src :self, :https
# policy.font_src :self, :https, :data
# policy.img_src :self, :https, :data
# policy.object_src :none
# policy.script_src :self, :https
# policy.style_src :self, :https
# # Specify URI for violation reports
# # policy.report_uri "/csp-violation-report-endpoint"
# end
# If you are using UJS then enable automatic nonce generation
# Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
# Report CSP violations to a specified URI
# For further information see the following documentation:
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only
# Rails.application.config.content_security_policy_report_only = true
| # Be sure to restart your server when you modify this file.
# Define an application-wide content security policy
# For further information see the following documentation
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
# Rails.application.config.content_security_policy do |policy|
# policy.default_src :self, :https
# policy.font_src :self, :https, :data
# policy.img_src :self, :https, :data
# policy.object_src :none
# policy.script_src :self, :https
# policy.style_src :self, :https
# # Specify URI for violation reports
# # policy.report_uri "/csp-violation-report-endpoint"
# end
# If you are using UJS then enable automatic nonce generation
# Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
# Report CSP violations to a specified URI
# For further information see the following documentation:
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only
# Rails.application.config.content_security_policy_report_only = true
Rails.application.config.content_security_policy do |policy|
policy.connect_src :self, :https, 'http://localhost:3035', 'ws://localhost:3035' if Rails.env.development?
end
|
Replace unused instance variable with method | module Suwabara
class StoredImage < StoredFile
attr_reader :width, :height
def initialize_from_io(file, original_name)
image = MiniMagick::Image.read(file)
@width = image[:width]
@height = image[:height]
super
end
def initialize_from_hash(hash)
@width = hash["width"]
@height = hash["height"]
super
end
def to_hash
{
"width" => @width,
"height" => @height,
}.merge(super)
end
def url(transform = nil)
transform = ImageTransform.parse(transform)
if transform.present?
path = Pathname.new(@storage)
path_with_transform = path.parent.join(transform.to_s, path.basename)
url_for(path_with_transform)
else
super()
end
end
end
end
| module Suwabara
class StoredImage < StoredFile
attr_reader :width, :height
def initialize_from_io(file, original_name)
image = MiniMagick::Image.read(file)
@width = image[:width]
@height = image[:height]
super
end
def initialize_from_hash(hash)
@width = hash["width"]
@height = hash["height"]
super
end
def to_hash
{
"width" => @width,
"height" => @height,
}.merge(super)
end
def url(transform = nil)
transform = ImageTransform.parse(transform)
if transform.present?
path = Pathname.new(storage)
path_with_transform = path.parent.join(transform.to_s, path.basename)
url_for(path_with_transform)
else
super()
end
end
end
end
|
Use better filename for PPA apt sources | define :ppa,
:key_id => nil,
:distribution => nil do
# ppa name should have the form "user/archive"
unless params[:name].count('/') == 1
raise "Invalid PPA name"
end
ppa = params[:name]
user, archive = ppa.split('/')
key_id = params[:key_id]
distribution = params[:distribution] || node[:lsb][:codename]
unless key_id
# use the Launchpad API to get the correct archive signing key id
require 'open-uri'
base_url = 'https://api.launchpad.net/1.0'
archive_url = "#{base_url}/~#{user}/+archive/#{archive}"
key_fingerprint_url = "#{archive_url}/signing_key_fingerprint"
key_id_long = open(key_fingerprint_url).read.tr('"', '')
key_id = key_id_long[-8..-1]
end
# let the apt_repo definition do the heavy lifting
apt_repo "#{user}-#{archive}-#{distribution}" do
key_id key_id
distribution distribution
keyserver "keyserver.ubuntu.com"
url "http://ppa.launchpad.net/#{ppa}/ubuntu"
end
end
| define :ppa,
:key_id => nil,
:distribution => nil do
# ppa name should have the form "user/archive"
unless params[:name].count('/') == 1
raise "Invalid PPA name"
end
ppa = params[:name]
user, archive = ppa.split('/')
key_id = params[:key_id]
unless key_id
# use the Launchpad API to get the correct archive signing key id
require 'open-uri'
base_url = 'https://api.launchpad.net/1.0'
archive_url = "#{base_url}/~#{user}/+archive/#{archive}"
key_fingerprint_url = "#{archive_url}/signing_key_fingerprint"
key_id_long = open(key_fingerprint_url).read.tr('"', '')
key_id = key_id_long[-8..-1]
end
# let the apt_repo definition do the heavy lifting
apt_repo "#{user}_#{archive}.ppa" do
key_id key_id
distribution params[:distribution]
keyserver "keyserver.ubuntu.com"
url "http://ppa.launchpad.net/#{ppa}/ubuntu"
end
end
|
Fix a broken `uri` call | require 'net/http'
class Twitch
module User
def self.find_by_oauth_token(oauth_token)
HTTParty.get(uri(oauth_token: oauth_token)).parsed_response
end
end
module Follows
def self.find_by_user(user)
Rails.cache.fetch([:follows, user]) do
HTTParty.get(
URI::parse("https://api.twitch.tv/kraken/users/#{user.name}/follows/channels").tap do |uri|
uri.query = {oauth_token: user.twitch_token, limit: 500}.to_query
end.to_s
)["follows"].map { |follow| follow["channel"]["_id"] }
end
end
end
private
def self.uri(query)
URI.parse('https://api.twitch.tv/kraken/user').tap do |uri|
uri.query = query.to_query
end
end
end
| require 'net/http'
class Twitch
module User
def self.find_by_oauth_token(oauth_token)
HTTParty.get(uri(oauth_token: oauth_token)).parsed_response
end
def self.uri(query) URI.parse('https://api.twitch.tv/kraken/user').tap do |uri|
uri.query = query.to_query
end
end
end
module Follows
def self.find_by_user(user)
Rails.cache.fetch([:follows, user]) do
HTTParty.get(
URI::parse("https://api.twitch.tv/kraken/users/#{user.name}/follows/channels").tap do |uri|
uri.query = {oauth_token: user.twitch_token, limit: 500}.to_query
end.to_s
)["follows"].map { |follow| follow["channel"]["_id"] }
end
end
end
end
|
Remove use of Rails slice method | module Pansophy
module Remote
class CreateFile
include Adamantium::Flat
ALLOWED_ATTRS = %i[
cache_control
content_disposition
content_encoding
content_length
content_md5
content_type
etag
expires
last_modified
metadata
owner
storage_class
encryption
encryption_key
version
].freeze
def initialize(bucket, path, body)
@bucket = bucket
@pathname = Pathname.new(path)
@body = body
end
def call(options = {})
prevent_overwrite! unless options[:overwrite]
params = options.slice(*ALLOWED_ATTRS).merge(key: @pathname.to_s, body: @body.dup)
directory.files.create(params)
end
private
def exist?
directory.files.any? { |file| file.key == @pathname.to_s }
end
def prevent_overwrite!
return unless exist?
fail ArgumentError,
"#{@pathname} already exists, pass ':overwrite => true' to overwrite"
end
def directory
ReadDirectory.new(@bucket, @pathname).call
end
memoize :directory
end
end
end
| module Pansophy
module Remote
class CreateFile
include Adamantium::Flat
ALLOWED_ATTRS = %i[
cache_control
content_disposition
content_encoding
content_length
content_md5
content_type
etag
expires
last_modified
metadata
owner
storage_class
encryption
encryption_key
version
].freeze
def initialize(bucket, path, body)
@bucket = bucket
@pathname = Pathname.new(path)
@body = body
end
def call(options = {})
prevent_overwrite! unless options[:overwrite]
file_attributes = options.delete_if { |k,v| !ALLOWED_ATTRS.include?(k) }
directory.files.create(file_attributes.merge(key: @pathname.to_s, body: @body.dup))
end
private
def exist?
directory.files.any? { |file| file.key == @pathname.to_s }
end
def prevent_overwrite!
return unless exist?
fail ArgumentError,
"#{@pathname} already exists, pass ':overwrite => true' to overwrite"
end
def directory
ReadDirectory.new(@bucket, @pathname).call
end
memoize :directory
end
end
end
|
Fix Travis specs and protect data | require 'bundler/setup'
require 'simplecov'
require 'coveralls'
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
]
SimpleCov.start
require 'pry' unless ENV["TRAVIS"]
require 'vcr'
require 'sermonaudio'
def env(environment = {}, &blk)
old = ->(key) { "__old_#{key}" }
environment.each_pair do |key, value|
ENV[old.(key)] = ENV[key] if ENV[key]
ENV[key] = value
end
yield
ensure
environment.each_pair do |key, value|
if ENV[old.(key)]
ENV.delete key
ENV[key] = ENV[old.(key)]
ENV.delete old.(key)
else
ENV.delete key
end
end
end
VCR.configure do |c|
c.cassette_library_dir = 'spec/cassettes'
c.hook_into :webmock # or :fakeweb
c.configure_rspec_metadata!
c.filter_sensitive_data('<SA_MEMBER_ID>') { ENV["SERMONAUDIO_MEMBER_ID"] }
c.filter_sensitive_data('<SA_PASSWORD>') { ENV["SERMONAUDIO_PASSWORD"] }
end
RSpec.configure do |config|
# some (optional) config here
config.mock_framework = :rspec
end
| require 'bundler/setup'
require 'simplecov'
require 'coveralls'
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
]
SimpleCov.start
require 'pry' unless ENV["TRAVIS"]
require 'vcr'
require 'sermonaudio'
def env(environment = {}, &blk)
old = ->(key) { "__old_#{key}" }
environment.each_pair do |key, value|
ENV[old.(key)] = ENV[key] if ENV[key]
ENV[key] = value
end
yield
ensure
environment.each_pair do |key, value|
if ENV[old.(key)]
ENV.delete key
ENV[key] = ENV[old.(key)]
ENV.delete old.(key)
else
ENV.delete key
end
end
end
VCR.configure do |c|
c.cassette_library_dir = 'spec/cassettes'
c.hook_into :webmock # or :fakeweb
c.configure_rspec_metadata!
c.filter_sensitive_data('<SA_PASSWORD>') { ENV["SERMONAUDIO_PASSWORD"] }
end
RSpec.configure do |config|
# some (optional) config here
config.mock_framework = :rspec
end
|
Enable future parser in serverspec | require 'rspec-puppet'
require 'puppetlabs_spec_helper/puppetlabs_spec_helper'
fixture_path = File.expand_path(File.join(__FILE__, '..', 'fixtures'))
RSpec.configure do |c|
c.module_path = File.join(fixture_path, 'modules')
c.manifest_dir = File.join(fixture_path, 'manifests')
end
at_exit { RSpec::Puppet::Coverage.report! }
| require 'rspec-puppet'
require 'puppetlabs_spec_helper/puppetlabs_spec_helper'
fixture_path = File.expand_path(File.join(__FILE__, '..', 'fixtures'))
RSpec.configure do |c|
c.module_path = File.join(fixture_path, 'modules')
c.manifest_dir = File.join(fixture_path, 'manifests')
c.parser = 'future' if Puppet.version.to_f >= 4.0
c.environmentpath = File.expand_path(File.join(Dir.pwd, 'spec')) if Puppet.version.to_f >= 4.0
end
at_exit { RSpec::Puppet::Coverage.report! }
|
Sort file names before comparing them. | class Archive
attr_reader :path, :opts
REQUIRED_ARCHIVE_FILES = %w(dom.json metadata.json screenshot.png source.html)
def initialize(path, opts={})
@path = path
@opts = opts
end
def meta_data
@meta_data = parse_json_file("#{path}/metadata.json")
end
def browser
meta_data[:browser]
end
def page_url
meta_data[:page_url]
end
def dom_elements
@dom_elements ||= File.open("#{path}/dom.json", 'rb') {|f| f.read}
end
def page_source
@page_source ||= File.open("#{path}/source.html") {|f| f.read}
end
def screenshot
@file ||= File.open("#{path}/screenshot.png")
end
def self.is_valid_page_archive?(file)
is_valid = false
if File.directory? file
dir_files = Dir.entries(file).delete_if {|name| name == '.' || name == '..'}
is_valid = true if dir_files == REQUIRED_ARCHIVE_FILES
end
is_valid
end
private
def parse_json_file(path)
json_str = File.open(path, 'rb') {|f| f.read}
JSON.parse(json_str, symbolize_names: true)
end
end
| class Archive
attr_reader :path, :opts
REQUIRED_ARCHIVE_FILES = %w(dom.json metadata.json screenshot.png source.html)
def initialize(path, opts={})
@path = path
@opts = opts
end
def meta_data
@meta_data = parse_json_file("#{path}/metadata.json")
end
def browser
meta_data[:browser]
end
def page_url
meta_data[:page_url]
end
def dom_elements
@dom_elements ||= File.open("#{path}/dom.json", 'rb') {|f| f.read}
end
def page_source
@page_source ||= File.open("#{path}/source.html") {|f| f.read}
end
def screenshot
@file ||= File.open("#{path}/screenshot.png")
end
def self.is_valid_page_archive?(file)
is_valid = false
if File.directory? file
dir_files = Dir.entries(file).delete_if {|name| name == '.' || name == '..'}
is_valid = dir_files.sort == REQUIRED_ARCHIVE_FILES.sort
end
is_valid
end
private
def parse_json_file(path)
json_str = File.open(path, 'rb') {|f| f.read}
JSON.parse(json_str, symbolize_names: true)
end
end
|
Replace eval with a 'saver' string to array convert mechanism | module DataStore
class Base
# Set the default values with the globally defined values
# * :compression_schema
# * :frequency
# * :maximum_datapoints
# * :data_type
# See {Configuration}
def before_save
set_default_values
end
# Convert serialized compression schema as a string back into the array object itself.
# For example: "[5,4,3]" => [5,4,3]
def compression_schema
value = self.values[:compression_schema]
eval(value) if value.is_a?(String) #convert string into array
end
private
def default_values
['compression_schema', 'frequency', 'maximum_datapoints', 'data_type']
end
def set_default_values
default_values.each do |variable|
value = DataStore.configuration.send(variable)
self.send(variable+ '=', value) if self.send(variable).nil?
end
end
end
end | module DataStore
class Base
# Set the default values with the globally defined values
# * :compression_schema
# * :frequency
# * :maximum_datapoints
# * :data_type
# See {Configuration}
def before_save
set_default_values
end
# Convert serialized compression schema as a string back into the array object itself.
# For example: "[5,4,3]" => [5,4,3]
def compression_schema
value = self.values[:compression_schema]
value.gsub(/\[|\]/,'').split(',').map(&:to_i) unless value.nil?
end
private
def default_values
['compression_schema', 'frequency', 'maximum_datapoints', 'data_type']
end
def set_default_values
default_values.each do |variable|
value = DataStore.configuration.send(variable)
self.send(variable+ '=', value) if self.send(variable).nil?
end
end
end
end |
Use alias_method instead of deprecated alias_method_chain | if Rails.env.development? || Rails.env.test?
require "silent-postgres/railtie"
require "silent-postgres/schema_plus"
module SilentPostgres
SILENCED_METHODS = %w(tables table_exists? indexes column_definitions pk_and_sequence_for last_insert_id)
def self.included(base)
SILENCED_METHODS.each do |m|
base.send :alias_method_chain, m, :silencer
end
end
SILENCED_METHODS.each do |m|
m1, m2 = if m =~ /^(.*)\?$/
[$1, '?']
else
[m, nil]
end
eval <<-METHOD
def #{m1}_with_silencer#{m2}(*args)
@logger.silence do
#{m1}_without_silencer#{m2}(*args)
end
end
METHOD
end
end
end
| if Rails.env.development? || Rails.env.test?
require "silent-postgres/railtie"
require "silent-postgres/schema_plus"
module SilentPostgres
SILENCED_METHODS = %w(tables table_exists? indexes column_definitions pk_and_sequence_for last_insert_id)
def self.included(base)
SILENCED_METHODS.each do |m|
base.send :alias_method, "#{m}_without_silencer", m
base.send :alias_method, m, "#{m}_with_silencer"
end
end
SILENCED_METHODS.each do |m|
m1, m2 = if m =~ /^(.*)\?$/
[$1, '?']
else
[m, nil]
end
eval <<-METHOD
def #{m1}_with_silencer#{m2}(*args)
@logger.silence do
#{m1}_without_silencer#{m2}(*args)
end
end
METHOD
end
end
end
|
Add ext/ to loadpath so BinaryProtocolAccelerated specs pass | require 'rubygems'
# require at least 1.1.4 to fix a bug with describing Modules
gem 'rspec', '>= 1.1.4'
require 'spec'
# pretend we already loaded fastthread, otherwise the nonblockingserver_spec
# will get screwed up
# $" << 'fastthread.bundle'
# turn on deprecation so we can test it
module Thrift
# squelch any warnings if we happen to get required twice
remove_const(:DEPRECATION) if const_defined? :DEPRECATION
DEPRECATION = true
end
require File.dirname(__FILE__) + '/../lib/thrift'
class Object
# tee is a useful method, so let's let our tests have it
def tee(&block)
block.call(self)
self
end
end
Spec::Runner.configure do |configuration|
configuration.before(:each) do
Thrift.type_checking = true
end
end
| require 'rubygems'
# require at least 1.1.4 to fix a bug with describing Modules
gem 'rspec', '>= 1.1.4'
require 'spec'
$:.unshift File.join(File.dirname(__FILE__), *%w[.. ext])
# pretend we already loaded fastthread, otherwise the nonblockingserver_spec
# will get screwed up
# $" << 'fastthread.bundle'
# turn on deprecation so we can test it
module Thrift
# squelch any warnings if we happen to get required twice
remove_const(:DEPRECATION) if const_defined? :DEPRECATION
DEPRECATION = true
end
require File.dirname(__FILE__) + '/../lib/thrift'
class Object
# tee is a useful method, so let's let our tests have it
def tee(&block)
block.call(self)
self
end
end
Spec::Runner.configure do |configuration|
configuration.before(:each) do
Thrift.type_checking = true
end
end
|
Change class variable to class constant | require "tic_tac_toe/version"
module TicTacToe
class Game
def initialize display
end
def start
end
end
class Board
@@win_places = [[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]]
def self.win_places
@@win_places
end
def initialize
@_marks = Array.new(9, " ")
end
def pos index
@_marks[index]
end
def move index, mark
@_marks[index] = mark
end
def who_won?
@@win_places.map do |places|
marks = places.map { |n| @_marks.at n }
marks[0] if marks.all? { |m| m == marks[0] } and marks[0] != " "
end.find(&:itself)
end
def draw?
(who_won? == nil) and @_marks.none? { |m| m == " " } ? true : false
end
end
end
| require "tic_tac_toe/version"
module TicTacToe
class Game
def initialize display
end
def start
end
end
class Board
WIN_PLACES = [[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]]
def self.win_places
WIN_PLACES
end
def initialize
@_marks = Array.new(9, " ")
end
def pos index
@_marks[index]
end
def move index, mark
@_marks[index] = mark
end
def who_won?
WIN_PLACES.map do |places|
marks = places.map { |n| @_marks.at n }
marks[0] if marks.all? { |m| m == marks[0] } and marks[0] != " "
end.find(&:itself)
end
def draw?
(who_won? == nil) and @_marks.none? { |m| m == " " } ? true : false
end
end
end
|
Remove ? in struct method for 1.9.2 compatibility | module GitFame
class Result < Struct.new(:data, :success?)
def to_s
data
end
end
end | module GitFame
class Result < Struct.new(:data, :success)
def to_s; data; end
def success?; success; end
end
end |
Make it Rails 4.0 compatible | require File.expand_path(File.join(File.dirname(__FILE__), 'env'))
require 'active_model'
require 'active_support/core_ext/object'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/hash/deep_dup'
require 'active_support/core_ext/enumerable'
require 'active_support/core_ext/module/delegation'
require 'active_support/dependencies'
require 'active_support/inflector'
require 'ostruct'
require 'delegate'
require 'braintree'
require 'braintree/exceptions'
require 'braintree_rails/array_ext'
require 'braintree_rails/module_ext'
require 'braintree_rails/braintree_ext'
require 'braintree_rails/exceptions'
require 'braintree_rails/braintree_rails'
| require File.expand_path(File.join(File.dirname(__FILE__), 'env'))
require 'active_model'
require 'active_support/core_ext'
require 'active_support/dependencies'
require 'active_support/inflector'
require 'ostruct'
require 'delegate'
require 'braintree'
require 'braintree/exceptions'
require 'braintree_rails/array_ext'
require 'braintree_rails/module_ext'
require 'braintree_rails/braintree_ext'
require 'braintree_rails/exceptions'
require 'braintree_rails/braintree_rails'
|
Make use of `download` capability to download initial .deb and allow caching with vagrant-cachier | module VagrantPlugins
module Ventriloquist
module Cap
module Debian
module ErlangInstall
def self.erlang_install(machine)
machine.communicate.tap do |comm|
if ! comm.test('which erlang > /dev/null')
machine.env.ui.info('Installing Erlang')
comm.execute('wget https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb')
comm.sudo('dpkg -i erlang-solutions_1.0_all.deb')
comm.sudo('apt-get update')
comm.sudo('apt-get -y install erlang')
end
end
end
end
end
end
end
end
| module VagrantPlugins
module Ventriloquist
module Cap
module Debian
module ErlangInstall
ERLANG_SOLUTIONS_PKG = "https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb"
def self.erlang_install(machine)
machine.communicate.tap do |comm|
if ! comm.test('which erlang > /dev/null')
machine.env.ui.info('Installing Erlang')
path = download_path(comm)
unless comm.test("-f #{path}")
machine.capability(:download, ERLANG_SOLUTIONS_PKG, path)
end
comm.sudo("dpkg -i #{path}")
comm.sudo('apt-get update')
comm.sudo('apt-get -y install erlang')
end
end
end
private
def self.download_path(comm)
# If vagrant-cachier apt cache bucket is available, drop it there
if comm.test("test -d /tmp/vagrant-cache/apt")
"/tmp/vagrant-cache/apt/erlang-solutions_1.0_all.deb"
else
"/tmp/erlang-solutions_1.0_all.deb"
end
end
end
end
end
end
end
|
Update rubocop requirement to ~> 0.56.0 | # frozen_string_literal: true
require File.expand_path("lib/active_record/safer_migrations/version", __dir__)
Gem::Specification.new do |gem|
gem.name = "activerecord-safer_migrations"
gem.version = ActiveRecord::SaferMigrations::VERSION
gem.summary = "ActiveRecord migration helpers to avoid downtime"
gem.description = ""
gem.authors = ["GoCardless Engineering"]
gem.email = "developers@gocardless.com"
gem.files = `git ls-files`.split("\n")
gem.require_paths = ["lib"]
gem.homepage = "https://github.com/gocardless/activerecord-safer_migrations"
gem.license = "MIT"
gem.required_ruby_version = "~> 2.2"
gem.add_runtime_dependency "activerecord", ">= 4.0"
gem.add_development_dependency "pg", "~> 0.21.0"
gem.add_development_dependency "rspec", "~> 3.7.0"
gem.add_development_dependency "rubocop", "~> 0.55.0"
end
| # frozen_string_literal: true
require File.expand_path("lib/active_record/safer_migrations/version", __dir__)
Gem::Specification.new do |gem|
gem.name = "activerecord-safer_migrations"
gem.version = ActiveRecord::SaferMigrations::VERSION
gem.summary = "ActiveRecord migration helpers to avoid downtime"
gem.description = ""
gem.authors = ["GoCardless Engineering"]
gem.email = "developers@gocardless.com"
gem.files = `git ls-files`.split("\n")
gem.require_paths = ["lib"]
gem.homepage = "https://github.com/gocardless/activerecord-safer_migrations"
gem.license = "MIT"
gem.required_ruby_version = "~> 2.2"
gem.add_runtime_dependency "activerecord", ">= 4.0"
gem.add_development_dependency "pg", "~> 0.21.0"
gem.add_development_dependency "rspec", "~> 3.7.0"
gem.add_development_dependency "rubocop", "~> 0.56.0"
end
|
Fix date format bug in gemspec | require File.expand_path('../lib/kbam/version', __FILE__)
Gem::Specification.new do |spec|
spec.name = 'kbam'
spec.version = Kbam::VERSION
spec.date = Date.today.strptime("%Y-%m-%d")
spec.summary = "K'bam!"
spec.description = "Simple gem that makes working with raw MySQL in Ruby efficient and fun! It's basically a query string builder (not an ORM!) that takes care of sanatization and sql chaining."
spec.author = "Leopold Burdyl"
spec.email = 'nerd@whiteslash.eu'
spec.files = Dir["lib/**/**"]
spec.homepage = 'https://github.com/vilnius-leopold/kbam'
spec.license = 'MIT'
# Ruby version
spec.required_ruby_version = '>= 2.0.0'
# Dependencies
spec.add_runtime_dependency "mysql2",
[">= 0.3.13"] # only tested for this version. but probably compatable with others too!
spec.add_runtime_dependency "colorize",
[">= 0.5.8"] # REALLY?! O.k. not really but I wanted it to look nice ;)
end | require File.expand_path('../lib/kbam/version', __FILE__)
Gem::Specification.new do |spec|
spec.name = 'kbam'
spec.version = Kbam::VERSION
spec.date = Date.today.strftime("%Y-%m-%d")
spec.summary = "K'bam!"
spec.description = "Simple gem that makes working with raw MySQL in Ruby efficient and fun! It's basically a query string builder (not an ORM!) that takes care of sanatization and sql chaining."
spec.author = "Leopold Burdyl"
spec.email = 'nerd@whiteslash.eu'
spec.files = Dir["lib/**/**"]
spec.homepage = 'https://github.com/vilnius-leopold/kbam'
spec.license = 'MIT'
# Ruby version
spec.required_ruby_version = '>= 2.0.0'
# Dependencies
spec.add_runtime_dependency "mysql2",
[">= 0.3.13"] # only tested for this version. but probably compatable with others too!
spec.add_runtime_dependency "colorize",
[">= 0.5.8"] # REALLY?! O.k. not really but I wanted it to look nice ;)
end |
Add a new :duration factory. | FactoryGirl.define do
factory :project, class: Server::Project do
name
path
end
factory :file, class: Server::File do
project
path
end
factory :time_entry, class: Server::TimeEntry do
file
mtime { Time.now }
end
sequence :name do |n|
"project_#{n}"
end
sequence :path do |n|
"/path/to/project_#{n}"
end
end | FactoryGirl.define do
factory :project, class: Server::Project do
name
path
end
factory :file, class: Server::File do
project
path
end
factory :time_entry, class: Server::TimeEntry do
file
mtime { Time.now }
end
factory :duration, class: Server::Duration do
file
date { Time.now }
duration { Random.rand(1000) }
end
sequence :name do |n|
"project_#{n}"
end
sequence :path do |n|
"/path/to/project_#{n}"
end
end |
Set ENV['STACK'] to an empty string if not set. | puts "-------> Buildpack version #{`cat #{File.dirname(__FILE__)}/../../../VERSION`}"
DEPENDENCIES_PATH = File.expand_path("../../dependencies", File.expand_path($0))
DEPENDENCIES_TRANSLATION_REGEX = /[:\/]/
DEPENDENCIES_TRANSLATION_DELIMITER = '_'
require 'cloud_foundry/language_pack/fetcher'
require 'cloud_foundry/language_pack/ruby'
require 'cloud_foundry/language_pack/helpers/plugins_installer'
require 'cloud_foundry/language_pack/helpers/readline_symlink'
module LanguagePack
module Extensions
def self.translate(host_url, original_filename)
prefix = host_url.to_s.gsub(DEPENDENCIES_TRANSLATION_REGEX, DEPENDENCIES_TRANSLATION_DELIMITER)
"#{prefix}#{delimiter_for(prefix)}#{original_filename}"
end
def self.delimiter_for(prefix)
(prefix.end_with? '_') ? '' : DEPENDENCIES_TRANSLATION_DELIMITER
end
end
end
| puts "-------> Buildpack version #{`cat #{File.dirname(__FILE__)}/../../../VERSION`}"
DEPENDENCIES_PATH = File.expand_path("../../dependencies", File.expand_path($0))
DEPENDENCIES_TRANSLATION_REGEX = /[:\/]/
DEPENDENCIES_TRANSLATION_DELIMITER = '_'
require 'cloud_foundry/language_pack/fetcher'
require 'cloud_foundry/language_pack/ruby'
require 'cloud_foundry/language_pack/helpers/plugins_installer'
require 'cloud_foundry/language_pack/helpers/readline_symlink'
ENV['STACK'] ||= ''
module LanguagePack
module Extensions
def self.translate(host_url, original_filename)
prefix = host_url.to_s.gsub(DEPENDENCIES_TRANSLATION_REGEX, DEPENDENCIES_TRANSLATION_DELIMITER)
"#{prefix}#{delimiter_for(prefix)}#{original_filename}"
end
def self.delimiter_for(prefix)
(prefix.end_with? '_') ? '' : DEPENDENCIES_TRANSLATION_DELIMITER
end
end
end
|
Change result from [0,1] to | module DescriptiveStatistics
def percentile_rank(p)
sorted = self.sort
return sorted.find_index{ |x| x >= p} / sorted.length.to_f
end
end
| module DescriptiveStatistics
def percentile_rank(p)
sorted = self.sort
return sorted.find_index{ |x| x >= p} / sorted.length.to_f * 100.0
end
end
|
Update podspec to copy lproj files | Pod::Spec.new do |s|
s.name = "MHPrettyDate"
s.version = "1.0.1"
s.summary = "An iOS framework that provides a simple mechanism to get \"Pretty Dates\" (\"Yesterday\", \"Today\", etc.) from NSDate objects."
s.homepage = "https://github.com/bobjustbob/MHPrettyDate"
s.license = 'MIT'
s.author = { "Bobby Williams" => "bjackw@mac.com" }
s.source = { :git => "https://github.com/bobjustbob/MHPrettyDate.git", :tag => "v1.0.1" }
s.platform = :ios, '5.0'
s.source_files = 'MHPrettyDate/**/*.{h,m}'
s.requires_arc = true
s.framework = 'Foundation'
end
| Pod::Spec.new do |s|
s.name = "MHPrettyDate"
s.version = "1.0.1"
s.summary = "An iOS framework that provides a simple mechanism to get \"Pretty Dates\" (\"Yesterday\", \"Today\", etc.) from NSDate objects."
s.homepage = "https://github.com/bobjustbob/MHPrettyDate"
s.license = 'MIT'
s.author = { "Bobby Williams" => "bjackw@mac.com" }
s.source = { :git => "https://github.com/bobjustbob/MHPrettyDate.git", :tag => "v1.0.1" }
s.platform = :ios, '5.0'
s.source_files = 'MHPrettyDate/**/*.{h,m}'
s.resources = "#{s.name}/**/*.{lproj}"
s.requires_arc = true
s.framework = 'Foundation'
end
|
Apply new framework defaults for Rails 5.1 | # Be sure to restart your server when you modify this file.
#
# This file contains migration options to ease your Rails 5.1 upgrade.
#
# Once upgraded flip defaults one by one to migrate to the new default.
#
# Read the Guide for Upgrading Ruby on Rails for more info on each option.
# Make `form_with` generate non-remote forms.
Rails.application.config.action_view.form_with_generates_remote_forms = false
# Unknown asset fallback will return the path passed in when the given
# asset is not present in the asset pipeline.
# Rails.application.config.assets.unknown_asset_fallback = false
| # Be sure to restart your server when you modify this file.
#
# This file contains migration options to ease your Rails 5.1 upgrade.
#
# Once upgraded flip defaults one by one to migrate to the new default.
#
# Read the Guide for Upgrading Ruby on Rails for more info on each option.
# Make `form_with` generate non-remote forms.
Rails.application.config.action_view.form_with_generates_remote_forms = true
# Unknown asset fallback will return the path passed in when the given
# asset is not present in the asset pipeline.
# Rails.application.config.assets.unknown_asset_fallback = false
|
Make the catch-all pages route for marketable URLs be controlled by the configuration switch. | ::Refinery::Application.routes.draw do
match '*path' => 'pages#show'
end
# Add any parts of routes as reserved words.
if Page.use_marketable_urls?
route_paths = ::Refinery::Application.routes.named_routes.routes.map{|name, route| route.path}
Page.friendly_id_config.reserved_words |= route_paths.map { |path|
path.to_s.gsub(/^\//, '').to_s.split('(').first.to_s.split(':').first.to_s.split('/')
}.flatten.reject{|w| w =~ /\_/}.uniq
end
|
if Page.use_marketable_urls?
::Refinery::Application.routes.draw do
match '*path' => 'pages#show'
end
# Add any parts of routes as reserved words.
route_paths = ::Refinery::Application.routes.named_routes.routes.map{|name, route| route.path}
Page.friendly_id_config.reserved_words |= route_paths.map { |path|
path.to_s.gsub(/^\//, '').to_s.split('(').first.to_s.split(':').first.to_s.split('/')
}.flatten.reject{|w| w =~ /\_/}.uniq
end
|
Make specs green by removing linter message prefixes. | require 'cocoapods-core'
module Pod
module TrunkApp
class SpecificationWrapper
def self.from_json(json)
hash = JSON.parse(json)
if hash.is_a?(Hash)
new(Specification.from_hash(hash))
end
rescue JSON::ParserError
# TODO: report error?
nil
end
def initialize(specification)
@specification = specification
end
def name
@specification.name
end
def version
@specification.version.to_s
end
def to_s
@specification.to_s
end
def to_json(*a)
@specification.to_json(*a)
end
def valid?
linter.lint
end
def validation_errors
results = {}
results['warnings'] = linter.warnings.map(&:message) unless linter.warnings.empty?
results['errors'] = linter.errors.map(&:message) unless linter.errors.empty?
results
end
private
def linter
@linter ||= Specification::Linter.new(@specification)
end
end
end
end
| require 'cocoapods-core'
module Pod
module TrunkApp
class SpecificationWrapper
def self.from_json(json)
hash = JSON.parse(json)
if hash.is_a?(Hash)
new(Specification.from_hash(hash))
end
rescue JSON::ParserError
# TODO: report error?
nil
end
def initialize(specification)
@specification = specification
end
def name
@specification.name
end
def version
@specification.version.to_s
end
def to_s
@specification.to_s
end
def to_json(*a)
@specification.to_json(*a)
end
def valid?
linter.lint
end
def validation_errors
results = {}
results['warnings'] = remove_prefixes(linter.warnings) unless linter.warnings.empty?
results['errors'] = remove_prefixes(linter.errors) unless linter.errors.empty?
results
end
private
def linter
@linter ||= Specification::Linter.new(@specification)
end
def remove_prefixes(results)
results.map do |result|
result.message.sub(/^\[.+?\]\s*/, '')
end
end
end
end
end
|
Rewrite the nokogiri script to go from page to page | desc "Fetch merchant infos"
task :fetch_infos => :environment do
require 'open-uri'
url = "http://www.yp.com.hk/Medical-Beauty-Health-Care-Services-b/Beauty-Health/Beauty-Salons/p1/en/"
doc = Nokogiri::HTML(open(url))
doc.css(".listing_div").each do |merchant|
name = merchant.at_css(".cname").text
address = merchant.at_css(".addr").text
phone = merchant.at_css(".blacklink").text
if merchant.at_css("div > .bluelink.overunder") != nil
website = merchant.at_css("div > .bluelink.overunder").text
end
puts "#{name} - #{address} - #{phone} - #{website}"
end
end | desc "Fetch merchant infos"
task :fetch_infos => :environment do
require 'open-uri'
list = [ {url: "Beauty-Health/Beauty-Salons/p1/en/", name: Category.create(name: 'Beauty Salon')},
{url: "Personal-Services/Massage/p1/en/", name: Category.create(name: 'Massage')}]
list.each do |category|
fetch_merchants(category[:url], category[:name])
end
end
def fetch_merchants(nextUrl, category)
prefix = "http://www.yp.com.hk/Medical-Beauty-Health-Care-Services-b/"
nextLinkText = "Next"
while (!nextUrl.empty?)
doc = Nokogiri::HTML(open(prefix+nextUrl))
doc.css(".listing_div").each do |m|
extract_merchant(m, category)
end
nextUrl = doc.xpath("//a[text()='#{nextLinkText}']/@href").first.to_s
pause 1
end
end
def extract_merchant(merchant, category)
m = Merchant.new
m.name = extract_css(merchant, '.cname')
m.address = extract_css(merchant, '.addr')
m.phone = extract_css(merchant, '.blacklink')
m.website = extract_css(merchant, 'div > .bluelink.overunder')
m.category = category
m.save
puts "[MerchantSaved][#{}] #{m.name} - #{m.address} - #{m.phone} - #{m.website}"
end
def extract_css(merchant, cssClass)
return (merchant.at_css(cssClass) == nil) ? nil : merchant.at_css(cssClass).text
end |
Update seed, can login with seeding account | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
user = User.first_or_create! do |u|
u.email = "testpoint@gmail.com"
u.name = "testpoint"
u.password = u.password_confirmation = "testpoint"
u.superadmin = true
end
if Project.none?
project = Project.create!(name: "Default Project")
Component.create!(name: "Default Component", project: project)
Platform.create!(name: "Default Platform", project: project)
Member.create!(role: "owner", project: project, user: user)
end
| # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
user = User.first_or_create! do |u|
u.email = "testpoint@gmail.com"
u.name = "testpoint"
u.password = u.password_confirmation = "testpoint"
u.superadmin = true
u.skip_confirmation!
end
if Project.none?
project = Project.create!(name: "Default Project")
Component.create!(name: "Default Component", project: project)
Platform.create!(name: "Default Platform", project: project)
Member.create!(role: "owner", project: project, user: user)
end
|
Make it possible to add multiple CORS origins in discourse.conf and docker yml files | if GlobalSetting.enable_cors
require 'rack/cors'
Rails.configuration.middleware.use Rack::Cors do
allow do
origins GlobalSetting.cors_origin
resource '*', headers: :any, methods: [:get, :post, :options]
end
end
end
| if GlobalSetting.enable_cors
require 'rack/cors'
Rails.configuration.middleware.use Rack::Cors do
allow do
origins GlobalSetting.cors_origin.split(',').map(&:strip)
resource '*', headers: :any, methods: [:get, :post, :options]
end
end
end
|
Add crud routes for users | # Index action
get '/users' do
@users = User.all
erb :'users/index'
end
# Show action
get '/users/:id' do
@user = User.find(params[:id])
erb :'users/show'
end
# Edit action
get '/users/:id/edit' do
@user = User.find(params[:id])
erb :'users/edit'
end
# Update action
put '/users/:id' do
@user = User.find(params[:id])
@user.assign_attributes(params[:user])
if @user.save
redirect '/users'
else
erb :'users/edit?errors=Oops! The user was not updated.'
end
end
# New action
get '/users/new' do
erb :'users/new'
end
# Create action
post '/users' do
@user = User.new(params[:user])
if @user.save
redirect '/users'
else
redirect '/users/new?error=Oops! The user was not created.'
end
end
# Destroy action
delete 'users/:id' do
@user = User.find(params[:id])
if @user.destroy
redirect '/users'
else
redirect '/users?errors=User was not destroyed.'
end
end
| |
Add watchOS as a deployment target | #
# Be sure to run `pod lib lint MKLog.podspec' to ensure this is a
# valid spec and remove all comments before submitting the spec.
#
# Any lines starting with a # are optional, but encouraged
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = "MKLog"
s.version = "0.1.1"
s.summary = "Lightweight log with multiple log levels"
s.description = <<-DESC
A lightweight logger implementation for Objective-C with multiple log levels.
DESC
s.homepage = "https://github.com/mikumi/MKLog"
s.license = 'MIT'
s.author = { "Michael Kuck" => "me@michael-kuck.com" }
s.source = { :git => "https://github.com/mikumi/MKLog.git", :tag => s.version.to_s }
s.platform = :ios, '7.0'
s.requires_arc = true
s.source_files = 'Pod/Classes/**/*'
s.resource_bundles = {
'MKLog' => ['Pod/Assets/*.png']
}
s
end
| #
# Be sure to run `pod lib lint MKLog.podspec' to ensure this is a
# valid spec and remove all comments before submitting the spec.
#
# Any lines starting with a # are optional, but encouraged
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = "MKLog"
s.version = "0.1.1"
s.summary = "Lightweight log with multiple log levels"
s.description = <<-DESC
A lightweight logger implementation for Objective-C with multiple log levels.
DESC
s.homepage = "https://github.com/mikumi/MKLog"
s.license = 'MIT'
s.author = { "Michael Kuck" => "me@michael-kuck.com" }
s.source = { :git => "https://github.com/mikumi/MKLog.git", :tag => s.version.to_s }
s.platform = :ios, '7.0'
s.requires_arc = true
s.watchos.deployment_target = '2.0'
s.source_files = 'Pod/Classes/**/*'
s.resource_bundles = {
'MKLog' => ['Pod/Assets/*.png']
}
s
end
|
Fix geoge-book redirect url for 1.9.0 | #Licensed to the Apache Software Foundation (ASF) under one or more
#contributor license agreements. See the NOTICE file distributed with
#this work for additional information regarding copyright ownership.
#The ASF licenses this file to You under the Apache License, Version 2.0
#(the "License"); you may not use this file except in compliance with
#the License. You may obtain a copy of the License at
#
#http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
#express or implied. See the License for the specific language governing
#permissions and limitations under the License.
r301 %r{/releases/latest/javadoc/(.*)}, 'http://geode.apache.org/releases/latest/javadoc/$1'
rewrite '/', '/docs/guide/110/about_geode.html'
rewrite '/index.html', '/docs/guide/110/about_geode.html'
| #Licensed to the Apache Software Foundation (ASF) under one or more
#contributor license agreements. See the NOTICE file distributed with
#this work for additional information regarding copyright ownership.
#The ASF licenses this file to You under the Apache License, Version 2.0
#(the "License"); you may not use this file except in compliance with
#the License. You may obtain a copy of the License at
#
#http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
#express or implied. See the License for the specific language governing
#permissions and limitations under the License.
r301 %r{/releases/latest/javadoc/(.*)}, 'http://geode.apache.org/releases/latest/javadoc/$1'
rewrite '/', '/docs/guide/19/about_geode.html'
rewrite '/index.html', '/docs/guide/19/about_geode.html'
|
Comment broken spec in order to transpec | describe(OmniAuth::Identity::Models::Mongoid, :db => true, type: :model) do
class MongoidTestIdentity
include Mongoid::Document
include OmniAuth::Identity::Models::Mongoid
auth_key :ham_sandwich
end
it 'should delegate locate to the where query method' do
MongoidTestIdentity.should_receive(:where).with('ham_sandwich' => 'open faced', 'category' => 'sandwiches').and_return(['wakka'])
MongoidTestIdentity.locate('ham_sandwich' => 'open faced', 'category' => 'sandwiches').should == 'wakka'
end
it 'should not use STI rules for its collection name' do
MongoidTestIdentity.collection.name.should == 'mongoid_test_identities'
end
end
| describe(OmniAuth::Identity::Models::Mongoid, :db => true, type: :model) do
class MongoidTestIdentity
include Mongoid::Document
include OmniAuth::Identity::Models::Mongoid
auth_key :ham_sandwich
end
it 'should delegate locate to the where query method' do
MongoidTestIdentity.should_receive(:where).with('ham_sandwich' => 'open faced', 'category' => 'sandwiches').and_return(['wakka'])
MongoidTestIdentity.locate('ham_sandwich' => 'open faced', 'category' => 'sandwiches').should == 'wakka'
end
# it 'should not use STI rules for its collection name' do
# MongoidTestIdentity.collection.name.should == 'mongoid_test_identities'
# end
end
|
Remove turbolinks from the site bar links. | module Refinery
module SiteBarHelper
# Generates the link to determine where the site bar switch button returns to.
def site_bar_switch_link
link_to_if(admin?, t('.switch_to_your_website', site_bar_translate_locale_args),
refinery.root_path(site_bar_translate_locale_args)) do
link_to t('.switch_to_your_website_editor', site_bar_translate_locale_args),
refinery.admin_root_path
end
end
def site_bar_translate_locale_args
{ :locale => Refinery::I18n.current_locale }
end
end
end
| module Refinery
module SiteBarHelper
# Generates the link to determine where the site bar switch button returns to.
def site_bar_switch_link
link_to_if(admin?, t('.switch_to_your_website', site_bar_translate_locale_args),
refinery.root_path(site_bar_translate_locale_args),
'data-no-turbolink' => true) do
link_to t('.switch_to_your_website_editor', site_bar_translate_locale_args),
refinery.admin_root_path, 'data-no-turbolink' => true
end
end
def site_bar_translate_locale_args
{ :locale => Refinery::I18n.current_locale }
end
end
end
|
Add a spec for Namespace. | require File.expand_path('../../spec_helper', __FILE__)
describe "A Namespace" do
before do
@namespace = Namespace.new('full_name' => 'Object')
end
it "should know what it responds to" do
@namespace.respond_to?(:full_name).should == true
@namespace.respond_to?(:binding).should == true
@namespace.respond_to?(:respond_to?).should == true
@namespace.respond_to?(:unknown).should == false
end
it "should respond to namespace keys" do
@namespace.full_name.should == 'Object'
end
it "should throw an exception on unknown keys" do
lambda {
@namespace.unknown
}.should.raise(NoMethodError)
end
it "should be able to assign new keys to the namespace" do
@namespace.respond_to?(:name).should == false
@namespace.assign('name', '…')
@namespace.respond_to?(:name).should == true
end
it "should have a public binding" do
lambda {
@namespace.binding
}.should.not.raise
end
end | |
Fix failing spec by changing the JRUBY_VERSION in the guard method | module Spec
module ExampleGroupMethods
def testing_block_passing_broken?
RUBY_PLATFORM.include?('java') && JRUBY_VERSION <= '1.6.5' && RUBY_VERSION >= '1.9.2'
end
end
end
| module Spec
module ExampleGroupMethods
def testing_block_passing_broken?
RUBY_PLATFORM.include?('java') && JRUBY_VERSION <= '1.7.0.dev' && RUBY_VERSION >= '1.9.2'
end
end
end
|
Add test for Novell bugzilla plugin | require File.join(File.dirname(__FILE__), 'helper')
class NovellPlugin_test < Test::Unit::TestCase
def test_urls_are_correct
client = Bicho::Client.new('https://bugzilla.novell.com')
assert_raises NoMethodError do
client.url
end
assert_equal 'https://apibugzilla.novell.com/tr_xmlrpc.cgi', "#{client.api_url.scheme}://#{client.api_url.host}#{client.api_url.path}"
assert_equal 'https://bugzilla.novell.com', "#{client.site_url.scheme}://#{client.site_url.host}#{client.site_url.path}"
end
end
| |
Improve Plist Acknowledgements unit testing a little | require File.expand_path("../../../../spec_helper", __FILE__)
describe Pod::Generator::Plist do
before do
@podfile = Pod::Podfile.new do
platform :ios
xcodeproj "dummy"
end
@target_definition = @podfile.target_definitions[:default]
@sandbox = temporary_sandbox
@pods = [Pod::LocalPod.new(fixture_spec("banana-lib/BananaLib.podspec"), @sandbox, Pod::Platform.ios)]
copy_fixture_to_pod("banana-lib", @pods[0])
@plist = Pod::Generator::Plist.new(@target_definition, @pods)
end
it "returns the correct number of licenses (including header and footnote)" do
@plist.licenses.count.should == 3
end
# TODO Test with a pod that has no licence
it "returns a correctly formed license hash for each pod" do
@plist.hash_for_pod(@pods[0]).should == {
:Type => "PSGroupSpecifier",
:Title => "BananaLib",
:FooterText => "Permission is hereby granted ..."
}
end
it "returns a plist containg the licenses" do
@plist.plist.should == {
:Title => "Acknowledgements",
:StringsTable => "Acknowledgements",
:PreferenceSpecifiers => @plist.licenses
}
end
it "writes a plist to disk" do
path = @sandbox.root + "#{@target_definition.label}-Acknowledgements.plist"
@plist.save_as(path).should.be.true
end
end
| require File.expand_path("../../../../spec_helper", __FILE__)
describe Pod::Generator::Plist do
before do
@podfile = Pod::Podfile.new do
platform :ios
xcodeproj "dummy"
end
@target_definition = @podfile.target_definitions[:default]
@sandbox = temporary_sandbox
@pods = [Pod::LocalPod.new(fixture_spec("banana-lib/BananaLib.podspec"), @sandbox, Pod::Platform.ios)]
copy_fixture_to_pod("banana-lib", @pods[0])
@plist = Pod::Generator::Plist.new(@target_definition, @pods)
end
it "returns the correct number of licenses (including header and footnote)" do
@plist.licenses.count.should == 3
end
# TODO Test with a pod that has no licence
it "returns a correctly formed license hash for each pod" do
@plist.hash_for_pod(@pods[0]).should == {
:Type => "PSGroupSpecifier",
:Title => "BananaLib",
:FooterText => "Permission is hereby granted ..."
}
end
it "returns a plist containg the licenses" do
@plist.plist.should == {
:Title => "Acknowledgements",
:StringsTable => "Acknowledgements",
:PreferenceSpecifiers => @plist.licenses
}
end
it "writes a plist to disk at the given path" do
path = @sandbox.root + "#{@target_definition.label}-Acknowledgements.plist"
Xcodeproj.expects(:write_plist).with(equals(@plist.plist), equals(path))
@plist.save_as(path)
end
end
|
Update Podspec for Swift 4.1 | Pod::Spec.new do |s|
s.name = "PremierKit"
s.version = "4.0.0"
s.summary = "Base code for iOS apps"
s.homepage = "https://github.com/ricardopereira/PremierKit"
s.license = 'MIT'
s.author = { "Ricardo Pereira" => "m@ricardopereira.eu" }
s.source = { :git => "https://github.com/ricardopereira/PremierKit.git", :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/ricardopereiraw'
s.platform = :ios, '9.0'
s.requires_arc = true
s.swift_version = '3.1'
s.source_files = 'PremierKit/*.{h}', 'Source/**/*.{h,swift}'
s.frameworks = 'UIKit'
end
| Pod::Spec.new do |s|
s.name = "PremierKit"
s.version = "4.0.0"
s.summary = "Base code for iOS apps"
s.homepage = "https://github.com/ricardopereira/PremierKit"
s.license = 'MIT'
s.author = { "Ricardo Pereira" => "m@ricardopereira.eu" }
s.source = { :git => "https://github.com/ricardopereira/PremierKit.git", :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/ricardopereiraw'
s.platform = :ios, '9.0'
s.requires_arc = true
s.swift_version = '4.1'
s.source_files = 'PremierKit/*.{h}', 'Source/**/*.{h,swift}'
s.frameworks = 'UIKit'
end
|
Use deep merge to support multiple tags | require 'raven'
require 'active_support/core_ext/module/aliasing'
class Exception
attr_accessor :extra, :level
def with_extra(extra)
self.extra ||= {}
self.extra.merge!(extra)
self
end
def with_level(level)
self.level = level
self
end
end
class Object
def decorating_exceptions_with(extra, level=nil)
yield
rescue Exception => e
raise e.with_extra(extra).with_level(level)
end
end
module Raven
class Event
def parse_exception_with_extra(exception)
parse_exception_without_extra(exception)
if exception.respond_to?(:extra) && extra = exception.extra
self.extra ||= {}
self.extra.merge!(extra)
end
end
def parse_exception_with_level(exception)
parse_exception_without_level(exception)
if exception.respond_to?(:level) && level = exception.level
self.level = level
end
end
alias_method_chain :parse_exception, :extra
alias_method_chain :parse_exception, :level
end
end
| require 'raven'
require 'active_support/core_ext/module/aliasing'
class Exception
attr_accessor :extra, :level
def with_extra(extra)
self.extra ||= {}
self.extra.deep_merge!(extra)
self
end
def with_level(level)
self.level = level
self
end
end
class Object
def decorating_exceptions_with(extra, level=nil)
yield
rescue Exception => e
raise e.with_extra(extra).with_level(level)
end
end
module Raven
class Event
def parse_exception_with_extra(exception)
parse_exception_without_extra(exception)
if exception.respond_to?(:extra) && extra = exception.extra
self.extra ||= {}
self.extra.deep_merge!(extra)
end
end
def parse_exception_with_level(exception)
parse_exception_without_level(exception)
if exception.respond_to?(:level) && level = exception.level
self.level = level
end
end
alias_method_chain :parse_exception, :extra
alias_method_chain :parse_exception, :level
end
end
|
Add more descriptive comment for PostScraper | # Creates Post objects out of an HTML page
class PostScraper
def initialize(page, link)
@page = page
@link = link
end
def new_post
Post.new(
image: image,
title: title,
price: price,
location: location,
description: description,
url: link
)
end
private
attr_reader :page, :link
def posting_title
page.at('span.postingtitletext')
end
def image
image = page.at('img')
image ? image['src'] : ''
end
def title
posting_title.text.gsub(/ ?- ?\$\d+ ?\(.+\)/, '')
end
def price
price = posting_title.at('span.price')
price ? price.text.gsub(/\$/, '').to_i : 0
end
def location
location = posting_title.at('small')
location ? location.text.gsub(/ ?[\(\)]/, '') : ''
end
def description
page.at('section#postingbody').text
end
end
| # Scrapes craigslist posts and packages data in Post objects
class PostScraper
def initialize(page, link)
@page = page
@link = link
end
def new_post
Post.new(
image: image,
title: title,
price: price,
location: location,
description: description,
url: link
)
end
private
attr_reader :page, :link
def posting_title
page.at('span.postingtitletext')
end
def image
image = page.at('img')
image ? image['src'] : ''
end
def title
posting_title.text.gsub(/ ?- ?\$\d+ ?\(.+\)/, '')
end
def price
price = posting_title.at('span.price')
price ? price.text.gsub(/\$/, '').to_i : 0
end
def location
location = posting_title.at('small')
location ? location.text.gsub(/ ?[\(\)]/, '') : ''
end
def description
page.at('section#postingbody').text
end
end
|
Order admin categories list by ordinal | module Forem
class CategoriesController < Forem::ApplicationController
helper 'forem/forums'
load_and_authorize_resource
end
end
| module Forem
class CategoriesController < Forem::ApplicationController
helper 'forem/forums'
load_and_authorize_resource
def index
@categories = Forem::Category.all.order("ordinal ASC")
end
end
end
|
Send a blank response with 304 | # Allow the metal piece to run in isolation
require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)
# Servers theme files from the them directory without touching Rails too much
class ThemeServer
def initialize(app)
@app = app
end
def call(env)
if env["PATH_INFO"] =~ /^\/theme/
relative_path = env["PATH_INFO"].gsub(/^\/theme\//, '')
if (file_path = Rails.root.join("themes", RefinerySetting[:theme], relative_path)).exist?
# generate an etag for client-side caching.
etag = Digest::MD5.hexdigest("#{file_path.to_s}#{file_path.mtime}")
unless (env["HTTP_IF_NONE_MATCH"] == etag and RefinerySetting.find_or_set(:themes_use_etags, false))
[200, {
"Content-Type" => Rack::Mime.mime_type(file_path.extname),
"ETag" => etag
}, file_path.open]
else
[304, {"Content-Type" => Rack::Mime.mime_type(file_path.extname)}, "Not Modified"]
end
else
[404, {"Content-Type" => "text/html"}, ["Not Found"]]
end
else
status, headers, response = @app.call(env)
[status, headers, response]
end
end
end | # Allow the metal piece to run in isolation
require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)
# Serves theme files from the theme directory without touching Rails too much
class ThemeServer
def initialize(app)
@app = app
end
def call(env)
if env["PATH_INFO"] =~ /^\/theme/
relative_path = env["PATH_INFO"].gsub(/^\/theme\//, '')
if (file_path = Rails.root.join("themes", RefinerySetting[:theme], relative_path)).exist?
# generate an etag for client-side caching.
etag = Digest::MD5.hexdigest("#{file_path.to_s}#{file_path.mtime}")
unless (env["HTTP_IF_NONE_MATCH"] == etag and RefinerySetting.find_or_set(:themes_use_etags, false) == true)
[200, {
"Content-Type" => Rack::Mime.mime_type(file_path.extname),
"Cache-Control" => "public",
"ETag" => etag
}, file_path.open]
else
[304, {}, []]
end
else
[404, {"Content-Type" => "text/html"}, ["Not Found"]]
end
else
status, headers, response = @app.call(env)
[status, headers, response]
end
end
end |
Fix bug where current_user is not set correctly by JR | # frozen_string_literal: true
##
# REST resource
#
class ApplicationResource < JSONAPI::Resource
abstract
##
# Callbacks
#
##
# Methods
#
def fetchable_fields
# Omit null values
super.collect do |field|
field unless self.class._attributes.key?(field) && public_send(field).nil?
end
end
def records_for(relation_name)
record_or_records = @model.public_send(relation_name)
relationship = self.class._relationships[relation_name]
case relationship
when JSONAPI::Relationship::ToOne
record_or_records
when JSONAPI::Relationship::ToMany
::Pundit.policy_scope!(context[:current_user], record_or_records)
else
raise "Unknown relationship type #{relationship.inspect}"
end
end
class << self
def records(options = {})
::Pundit.policy_scope!(options[:context][:user], _model_class)
end
end
end
| # frozen_string_literal: true
##
# REST resource
#
class ApplicationResource < JSONAPI::Resource
abstract
##
# Callbacks
#
##
# Methods
#
def fetchable_fields
# Omit null values
super.collect do |field|
field unless self.class._attributes.key?(field) && public_send(field).nil?
end
end
def records_for(relation_name)
record_or_records = @model.public_send(relation_name)
relationship = self.class._relationships[relation_name]
case relationship
when JSONAPI::Relationship::ToOne
record_or_records
when JSONAPI::Relationship::ToMany
::Pundit.policy_scope!(context[:current_user], record_or_records)
else
raise "Unknown relationship type #{relationship.inspect}"
end
end
class << self
def records(options = {})
::Pundit.policy_scope!(options[:context][:user] || options[:context][:current_user], _model_class)
end
end
end
|
Make the port a command line argument | require 'socket'
project = ARGV[0]
status = ARGV[1]
sock = TCPSocket.new('127.0.0.1', 8083)
data = <<eos
{
"name": "#{project}",
"url": "job/#{project}/",
"build": {
"full_url": "http://localhost:8080/job/#{project}/48/",
"number": 48,
"phase": "FINALIZED",
"status": "#{status}",
"url": "job/#{project}/48/",
"scm": {
"url": "git@github.com:jenkinsci/#{project}.git",
"branch": "origin/master",
"commit": "4886d1ff4821879410f4f4a93168e6cc179a8eb3"
},
"artifacts": {
"test.jar": [
"http://localhost:8080/job/test/48/artifact/target/test.jar"
],
"test.hpi": [
"http://localhost:8080/job/test/48/artifact/target/test.hpi"
]
}
}
}
eos
sock.write data
sock.close
| require 'socket'
project = ARGV[0]
status = ARGV[1]
port = ARGV[2] ? ARGV[2] : 4712
socket = TCPSocket.new('127.0.0.1', port)
data = <<eos
{
"name": "#{project}",
"url": "job/#{project}/",
"build": {
"full_url": "http://localhost:8080/job/#{project}/48/",
"number": 48,
"phase": "FINALIZED",
"status": "#{status}",
"url": "job/#{project}/48/",
"scm": {
"url": "git@github.com:jenkinsci/#{project}.git",
"branch": "origin/master",
"commit": "4886d1ff4821879410f4f4a93168e6cc179a8eb3"
},
"artifacts": {
"test.jar": [
"http://localhost:8080/job/test/48/artifact/target/test.jar"
],
"test.hpi": [
"http://localhost:8080/job/test/48/artifact/target/test.hpi"
]
}
}
}
eos
socket.write data
socket.close
|
Fix miss spell of extension for Engine class | require "sprint/rails/version"
module Sprint
module Rails
class Engine << ::Rails::Engine
end
end
end
| require "sprint/rails/version"
module Sprint
module Rails
class Engine < ::Rails::Engine
end
end
end
|
Fix the query matching in SubscriberTest | require "cases/helper"
require "models/developer"
require "rails/subscriber/test_helper"
require "active_record/railties/subscriber"
module SubscriberTest
Rails::Subscriber.add(:active_record, ActiveRecord::Railties::Subscriber.new)
def setup
@old_logger = ActiveRecord::Base.logger
super
end
def teardown
super
ActiveRecord::Base.logger = @old_logger
end
def set_logger(logger)
ActiveRecord::Base.logger = logger
end
def test_basic_query_logging
Developer.all
wait
assert_equal 1, @logger.logged(:debug).size
assert_match /Developer Load/, @logger.logged(:debug).last
assert_match /SELECT \* FROM "developers"/, @logger.logged(:debug).last
end
def test_cached_queries
ActiveRecord::Base.cache do
Developer.all
Developer.all
end
wait
assert_equal 2, @logger.logged(:debug).size
assert_match /CACHE/, @logger.logged(:debug).last
assert_match /SELECT \* FROM "developers"/, @logger.logged(:debug).last
end
class SyncSubscriberTest < ActiveSupport::TestCase
include Rails::Subscriber::SyncTestHelper
include SubscriberTest
end
class AsyncSubscriberTest < ActiveSupport::TestCase
include Rails::Subscriber::AsyncTestHelper
include SubscriberTest
end
end | require "cases/helper"
require "models/developer"
require "rails/subscriber/test_helper"
require "active_record/railties/subscriber"
module SubscriberTest
Rails::Subscriber.add(:active_record, ActiveRecord::Railties::Subscriber.new)
def setup
@old_logger = ActiveRecord::Base.logger
super
end
def teardown
super
ActiveRecord::Base.logger = @old_logger
end
def set_logger(logger)
ActiveRecord::Base.logger = logger
end
def test_basic_query_logging
Developer.all
wait
assert_equal 1, @logger.logged(:debug).size
assert_match /Developer Load/, @logger.logged(:debug).last
assert_match /SELECT .*?FROM .?developers.?/, @logger.logged(:debug).last
end
def test_cached_queries
ActiveRecord::Base.cache do
Developer.all
Developer.all
end
wait
assert_equal 2, @logger.logged(:debug).size
assert_match /CACHE/, @logger.logged(:debug).last
assert_match /SELECT .*?FROM .?developers.?/, @logger.logged(:debug).last
end
class SyncSubscriberTest < ActiveSupport::TestCase
include Rails::Subscriber::SyncTestHelper
include SubscriberTest
end
class AsyncSubscriberTest < ActiveSupport::TestCase
include Rails::Subscriber::AsyncTestHelper
include SubscriberTest
end
end |
Use binstubs for correct shebang line | # Add ppa with newer Ruby version
apt_repository "brightbox-ruby-ng" do
action :add
uri "http://ppa.launchpad.net/brightbox/ruby-ng/ubuntu"
distribution "precise"
components ["main"]
keyserver "keyserver.ubuntu.com"
key "C3173AA6"
end
# Install Ruby and other required packages
%w{ruby2.1 ruby2.1-dev ruby-switch curl}.each do |pkg|
package pkg do
action :install
end
end
# Make Ruby 2.1 the default Ruby
script "ruby-switch" do
interpreter "bash"
code "sudo ruby-switch --set ruby2.1"
end
# Install bundler
gem_package "bundler" do
gem_binary "/usr/bin/gem"
end
# Install required gems via bundler
# store them in vendor/bundle
script "bundle" do
interpreter "bash"
cwd "/vagrant"
code "bundle install --path vendor/bundle"
end
# Package required gems in vendor folder
script "bundle" do
interpreter "bash"
cwd "/vagrant"
code "bundle package --all"
end | # Add ppa with newer Ruby version
apt_repository "brightbox-ruby-ng" do
action :add
uri "http://ppa.launchpad.net/brightbox/ruby-ng/ubuntu"
distribution "precise"
components ["main"]
keyserver "keyserver.ubuntu.com"
key "C3173AA6"
end
# Install Ruby and other required packages
%w{ruby2.1 ruby2.1-dev curl}.each do |pkg|
package pkg do
action :install
end
end
gem_package "bundler" do
gem_binary "/usr/bin/gem"
end
# Install required gems via bundler
# Store them in vendor/bundle
# Need workaround with binstubs for correct shebang line
script "bundle" do
interpreter "bash"
cwd "/vagrant"
code "bundle install --path=vendor/bundle --binstubs=vendor/bundle/ruby/2.1.0/bin"
end
# Package required gems in vendor folder
script "bundle" do
interpreter "bash"
cwd "/vagrant"
code "bundle package --all"
end |
Handle missing github repos better | class GithubRepositoriesController < ApplicationController
def show
@github_repository = GithubRepository.find_by_full_name([params[:owner], params[:name]].join('/'))
@contributors = @github_repository.github_contributions.order('count DESC').limit(20).includes(:github_user)
@projects = @github_repository.projects.includes(:versions)
end
end
| class GithubRepositoriesController < ApplicationController
def show
@github_repository = GithubRepository.find_by_full_name([params[:owner], params[:name]].join('/'))
raise ActiveRecord::RecordNotFound if @github_repository.nil?
@contributors = @github_repository.github_contributions.order('count DESC').limit(20).includes(:github_user)
@projects = @github_repository.projects.includes(:versions)
end
end
|
Add randomisation to exp of manual_exp_record factory | FactoryGirl.define do
factory :course_experience_points_record, class: Course::ExperiencePointsRecord.name do
creator
updater
course_user
points_awarded 100
reason 'EXP for some event'
end
end
| FactoryGirl.define do
factory :course_experience_points_record, class: Course::ExperiencePointsRecord.name do
creator
updater
course_user
points_awarded { rand(1..20) * 100 }
reason 'EXP for some event'
end
end
|
Add mtime and munit to flor_pointers |
Sequel.migration do
up do
alter_table :flor_messages do
add_column :cunit, String
add_column :munit, String
end
alter_table :flor_executions do
add_column :cunit, String
add_column :munit, String
end
alter_table :flor_timers do
add_column :cunit, String
add_column :munit, String
end
alter_table :flor_traps do
add_column :cunit, String
add_column :munit, String
end
alter_table :flor_pointers do
add_column :cunit, String
end
alter_table :flor_traces do
add_column :cunit, String
end
end
down do
alter_table :flor_messages do
drop_column :cunit
drop_column :munit
end
alter_table :flor_executions do
drop_column :cunit
drop_column :munit
end
alter_table :flor_timers do
drop_column :cunit
drop_column :munit
end
alter_table :flor_traps do
drop_column :cunit
drop_column :munit
end
alter_table :flor_pointers do
drop_column :cunit
end
alter_table :flor_traces do
drop_column :cunit
end
end
end
|
Sequel.migration do
up do
alter_table :flor_messages do
add_column :cunit, String
add_column :munit, String
end
alter_table :flor_executions do
add_column :cunit, String
add_column :munit, String
end
alter_table :flor_timers do
add_column :cunit, String
add_column :munit, String
end
alter_table :flor_traps do
add_column :cunit, String
add_column :munit, String
end
alter_table :flor_pointers do
add_column :cunit, String
add_column :mtime, String
add_column :munit, String
#
# those 2 could prove useful later on
end
alter_table :flor_traces do
add_column :cunit, String
end
end
down do
alter_table :flor_messages do
drop_column :cunit
drop_column :munit
end
alter_table :flor_executions do
drop_column :cunit
drop_column :munit
end
alter_table :flor_timers do
drop_column :cunit
drop_column :munit
end
alter_table :flor_traps do
drop_column :cunit
drop_column :munit
end
alter_table :flor_pointers do
drop_column :cunit
drop_column :mtime
drop_column :munit
end
alter_table :flor_traces do
drop_column :cunit
end
end
end
|
Allow setting namespace with STAGE env variable | require 'rubygems'
require 'benchmark'
require 'statsd'
require 'resque/plugins/statsd'
require 'resque'
# Set up the client
$resque_statsd = Statsd.new(ENV['GRAPHITE_HOST'], 8125)
$resque_statsd.namespace="#{ENV['APP_NAME']}_#{ENV['RAILS_ENV']}.resque"
module Resque
class << self
alias_method :push_without_timestamps, :push
def push(queue, item)
if item.respond_to?(:[]=)
item[:created_at] = Time.now.to_f
end
push_without_timestamps queue, item
end
end
class Job
def initialize(queue, payload)
@queue = queue
@payload = payload
if $resque_statsd && @payload["created_at"]
$resque_statsd.timing "#{@queue}.queue_time", (1000 * (Time.now.to_f - @payload["created_at"].to_i)).round
$resque_statsd.timing "#{payload_class}.queue_time", (1000 * (Time.now.to_f - @payload["created_at"].to_i)).round
end
end
end
module Plugins
module Statsd
VERSION = "0.1.0"
end
end
end
| require 'rubygems'
require 'benchmark'
require 'statsd'
require 'resque/plugins/statsd'
require 'resque'
# Set up the client
$resque_statsd = Statsd.new(ENV['GRAPHITE_HOST'], 8125)
$resque_statsd.namespace="#{ENV['APP_NAME']}_#{ENV["STAGE"] || ENV['RAILS_ENV']}.resque"
module Resque
class << self
alias_method :push_without_timestamps, :push
def push(queue, item)
if item.respond_to?(:[]=)
item[:created_at] = Time.now.to_f
end
push_without_timestamps queue, item
end
end
class Job
def initialize(queue, payload)
@queue = queue
@payload = payload
if $resque_statsd && @payload["created_at"]
$resque_statsd.timing "#{@queue}.queue_time", (1000 * (Time.now.to_f - @payload["created_at"].to_i)).round
$resque_statsd.timing "#{payload_class}.queue_time", (1000 * (Time.now.to_f - @payload["created_at"].to_i)).round
end
end
end
module Plugins
module Statsd
VERSION = "0.1.0"
end
end
end
|
Implement demand helpers for FuelType. | class FuelType < ActiveRecord::Base
belongs_to :market
has_many :generator_types
has_many :generators, :through => :generator_types
has_many :market_prices, :through => :market
has_friendly_id :name, :use_slug => true
validates :name, :presence => true
def average_demand game, time=nil
end
def demand game
end
def to_s
name
end
end
| class FuelType < ActiveRecord::Base
belongs_to :market
has_many :generator_types
has_many :generators, :through => :generator_types do
def find_by_game game
# Raw SQL to get around the fact that rails doesn't create the double
# join here properly.
find(:all, :joins => "INNER JOIN cities ON technical_component_instances.city_id = cities.id INNER JOIN states ON cities.state_id = states.id",
:conditions => {:states => {:game_id => game}})
end
end
has_many :market_prices, :through => :market
has_friendly_id :name, :use_slug => true
validates :name, :presence => true
def average_demand game, time=nil
generators.find_by_game(game).inject(0) {|demand, generator|
demand + generator.average_fuel_burn_rate(time)
}
end
def demand game
generators.find_by_game(game).inject(0) {|demand, generator|
demand + generator.fuel_burn_rate
}
end
def to_s
name
end
end
|
Remove creation of accessor methods in attr_accessible | class MassObject
def self.my_attr_accessible(*attributes)
attributes.each do |attribute|
attr_accessor attribute
self.attributes << attribute.to_s
end
end
def self.attributes
@attributes ||= []
end
def self.parse_all(results)
results.map do |params|
self.new(params)
end
end
def initialize(params = {})
params.each do |attribute, value|
attribute = attribute.to_s
if self.class.attributes.include?(attribute)
self.send("#{attribute}=", value)
else
raise "[#{self.class}]: mass assignment to unregistered attribute #{attribute}"
end
end
end
end
| class MassObject
def self.my_attr_accessible(*attributes)
attributes.each do |attribute|
self.attributes << attribute.to_s
end
end
def self.attributes
@attributes ||= []
end
def self.parse_all(results)
results.map do |params|
obj = self.new
params.each do |k, v|
obj.instance_variable_set("@#{k}", v)
end
obj
end
end
def initialize(params = {})
params.each do |attribute, value|
attribute = attribute.to_s
if self.class.attributes.include?(attribute)
self.send("#{attribute}=", value)
else
raise "[#{self.class}]: mass assignment to unregistered attribute #{attribute}"
end
end
end
end
|
Increase logging threshold and revert sql log condition | if Rails.env.production? && ENV["STAT_ACCOUNT"].present?
instLog ||= Logger.new("#{Rails.root}/log/perf.log")
ActiveSupport::Notifications.subscribe "process_action.action_controller" do |name, start, finish, id, payload|
duration = (finish - start) * 1000
unless payload[:view_runtime].nil?
view_time = payload[:view_runtime]
StatHat::API.ez_post_value("View Rendering", ENV["STAT_ACCOUNT"], view_time)
end
StatHat::API.ez_post_value("Response Time", ENV["STAT_ACCOUNT"], duration)
if duration > 500
StatHat::API.ez_post_count("Slow Requests", ENV["STAT_ACCOUNT"], 1)
end
if duration > 100
instLog.debug("[action] #{payload[:method]} #{payload[:path]} #{duration}ms")
end
end
ActiveSupport::Notifications.subscribe "sql.active_record" do |name, start, finish, id, payload|
if payload[:sql]
duration = (finish - start) * 1000
StatHat::API.ez_post_value("DB Query", ENV["STAT_ACCOUNT"], duration)
if duration > 50
instLog.debug("[sql] #{payload[:name]} '#{payload[:sql]}' #{duration}ms")
end
end
end
end
| if Rails.env.production? && ENV["STAT_ACCOUNT"].present?
instLog ||= Logger.new("#{Rails.root}/log/perf.log")
ActiveSupport::Notifications.subscribe "process_action.action_controller" do |name, start, finish, id, payload|
duration = (finish - start) * 1000
unless payload[:view_runtime].nil?
view_time = payload[:view_runtime]
StatHat::API.ez_post_value("View Rendering", ENV["STAT_ACCOUNT"], view_time)
end
StatHat::API.ez_post_value("Response Time", ENV["STAT_ACCOUNT"], duration)
if duration > 500
StatHat::API.ez_post_count("Slow Requests", ENV["STAT_ACCOUNT"], 1)
instLog.debug("[action] #{payload[:method]} #{payload[:path]} #{duration}ms")
end
end
ActiveSupport::Notifications.subscribe "sql.active_record" do |name, start, finish, id, payload|
if payload[:name] == 'SQL'
duration = (finish - start) * 1000
StatHat::API.ez_post_value("DB Query", ENV["STAT_ACCOUNT"], duration)
if duration > 500
instLog.debug("[sql] #{payload[:name]} '#{payload[:sql]}' #{duration}ms")
end
end
end
end
|
Allow eval in prod environment, to support use of Vue templates | # Be sure to restart your server when you modify this file.
# Define an application-wide content security policy
# For further information see the following documentation
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
Rails.application.config.content_security_policy do |policy|
# policy.default_src :self, :https
# policy.font_src :self, :https, :data
# policy.img_src :self, :https, :data
# policy.object_src :none
# policy.script_src :self, :https
# policy.style_src :self, :https
# # Specify URI for violation reports
# # policy.report_uri "/csp-violation-report-endpoint"
policy.script_src :self, :https, :unsafe_inline
end
# If you are using UJS then enable automatic nonce generation
# Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
# Report CSP violations to a specified URI
# For further information see the following documentation:
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only
# Rails.application.config.content_security_policy_report_only = true
| # Be sure to restart your server when you modify this file.
# Define an application-wide content security policy
# For further information see the following documentation
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
Rails.application.config.content_security_policy do |policy|
# policy.default_src :self, :https
# policy.font_src :self, :https, :data
# policy.img_src :self, :https, :data
# policy.object_src :none
# policy.script_src :self, :https
# policy.style_src :self, :https
# # Specify URI for violation reports
# # policy.report_uri "/csp-violation-report-endpoint"
policy.script_src :self, :https, :unsafe_inline, :unsafe_eval
end
# If you are using UJS then enable automatic nonce generation
# Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
# Report CSP violations to a specified URI
# For further information see the following documentation:
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only
# Rails.application.config.content_security_policy_report_only = true
|
Create activity type public api | require 'grape'
module Api
class ActivityTypesPublicApi < Grape::API
desc "Get the activity type details"
get '/activity_types/:id' do
ActivityType.find(params[:id])
end
desc 'Get all the activity types'
get '/activity_types' do
ActivityType.all
end
end
end | |
Fix typo in English language names [merges branch 'randomecho/copyedits'] | Localization.define('en_US') do |l|
l.store "Login successful", "Login successful"
l.store "da_DK", "Danish"
l.store "de_DE", "German"
l.store "en_US", "English (US)"
l.store "es_MX", "Spanish (Mexican)"
l.store "fr_FR", "French"
l.store "he_IL", "Hebrew"
l.store "it_IT", "Italian"
l.store "ja_JP", "Japanese"
l.store "lt_LT", "Lituanian"
l.store "nb_NO", "Norwegian"
l.store "nl_NL", "Nederland"
l.store "pl_PL", "Polish"
l.store "ro_RO", "Romanian"
l.store "zh_TW", "Chinese"
end
| Localization.define('en_US') do |l|
l.store "Login successful", "Login successful"
l.store "da_DK", "Danish"
l.store "de_DE", "German"
l.store "en_US", "English (US)"
l.store "es_MX", "Spanish (Mexican)"
l.store "fr_FR", "French"
l.store "he_IL", "Hebrew"
l.store "it_IT", "Italian"
l.store "ja_JP", "Japanese"
l.store "lt_LT", "Lithuanian"
l.store "nb_NO", "Norwegian"
l.store "nl_NL", "Nederland"
l.store "pl_PL", "Polish"
l.store "ro_RO", "Romanian"
l.store "zh_TW", "Chinese"
end
|
Remove “Pardon our dust...” message | Rails.application.routes.draw do
resources :visits
resource :trending
resources :dependencies
resources :logs
root 'errors#pardon'
get '/*any_route', to: 'errors#pardon', as: 'pardon'
resources :searches, path: 's'
resources :models
resources :packages
resources :releases
resources :downloads
resources :subscriptions
resources :feeds
resources :settings
resources :blurbs
resources :references
resources :trending_weekly_news_items
resources :trending_daily_news_items
resources :trending_monthly_news_items
resources :stack_overflow_news_items
resources :discourse_news_items
resources :github_news_items
resources :reddit_news_items
resources :activities
resources :batches
resources :infos
resources :profiles
resources :labels
resources :organizations
resources :contributions
resources :users
resources :dummies
resources :categories
resources :daters
resources :counters
resources :versions
resources :repositories
resources :news, as: :news_items, controller: :news_items
resources :searches do
get 'autocomplete', on: :collection
end
resource :trending, path: 't'
resources :users, path: 'u'
resources :packages, path: 'p'
resources :organizations, path: 'o'
resources :statics, only: [], path: '' do
collection do
get 'about'
end
end
root 'trendings#index'
get '/*bad_route', to: 'errors#index', as: 'errors'
end
| Rails.application.routes.draw do
resources :visits
resource :trending
resources :dependencies
resources :logs
# root 'errors#pardon'
# get '/*any_route', to: 'errors#pardon', as: 'pardon'
resources :searches, path: 's'
resources :models
resources :packages
resources :releases
resources :downloads
resources :subscriptions
resources :feeds
resources :settings
resources :blurbs
resources :references
resources :trending_weekly_news_items
resources :trending_daily_news_items
resources :trending_monthly_news_items
resources :stack_overflow_news_items
resources :discourse_news_items
resources :github_news_items
resources :reddit_news_items
resources :activities
resources :batches
resources :infos
resources :profiles
resources :labels
resources :organizations
resources :contributions
resources :users
resources :dummies
resources :categories
resources :daters
resources :counters
resources :versions
resources :repositories
resources :news, as: :news_items, controller: :news_items
resources :searches do
get 'autocomplete', on: :collection
end
resource :trending, path: 't'
resources :users, path: 'u'
resources :packages, path: 'p'
resources :organizations, path: 'o'
resources :statics, only: [], path: '' do
collection do
get 'about'
end
end
root 'trendings#index'
get '/*bad_route', to: 'errors#index', as: 'errors'
end
|
Add an integration spec for Struct as an EV | require 'spec_helper'
describe 'Using Struct as an embedded value attribute' do
before do
module Examples
Point = Struct.new(:x, :y)
class Rectangle
include Virtus
attribute :top_left, Point
attribute :bottom_right, Point
end
end
end
subject do
Examples::Rectangle.new(top_left: [ 3, 5 ], bottom_right: [ 8, 7 ])
end
specify 'initialize a struct object with correct attributes' do
subject.top_left.x.should be(3)
subject.top_left.y.should be(5)
subject.bottom_right.x.should be(8)
subject.bottom_right.y.should be(7)
end
end
| |
Add Query API Method To Be Used By API Controllers | class ApiController < ApplicationController
before_action :change_query_order, only: :index
@@order = :id
def change_query_order
unless params[:order] == nil
orders = params[:order].split(",")
orders.map! do |order|
order_direction = order.strip.split(".")
(order_direction.length == 1) ? order_direction[0].to_sym : "#{order_direction[0]} #{order_direction[1]}"
end
@@order = orders
end
end
end
| class ApiController < ApplicationController
before_action :change_query_order, :add_querying, only: :index
@@order = :id
@@query = nil
def add_querying
@@query = "%#{params[:q].downcase}%" unless params[:q] == nil
end
def change_query_order
unless params[:order] == nil
orders = params[:order].split(",")
orders.map! do |order|
order_direction = order.strip.split(".")
(order_direction.length == 1) ? order_direction[0].to_sym : "#{order_direction[0]} #{order_direction[1]}"
end
@@order = orders
end
end
end
|
Update RSpec focus config syntax | $LOAD_PATH.unshift File.expand_path('../lib', __dir__)
require 'enumerate_it'
require 'active_support/all'
require 'active_record'
Dir['./spec/support/**/*.rb'].each { |f| require f }
I18n.config.enforce_available_locales = false
I18n.load_path = Dir['spec/i18n/*.yml']
RSpec.configure do |config|
config.filter_run :focus
config.run_all_when_everything_filtered = true
end
| $LOAD_PATH.unshift File.expand_path('../lib', __dir__)
require 'enumerate_it'
require 'active_support/all'
require 'active_record'
Dir['./spec/support/**/*.rb'].each { |f| require f }
I18n.config.enforce_available_locales = false
I18n.load_path = Dir['spec/i18n/*.yml']
RSpec.configure do |config|
config.filter_run_when_matching :focus
end
|
Implement unconditional collecting of samples | # frozen_string_literal: true
module ApiSampler
# This class provides rack-compatible middleware to collect and tag API
# endpoint samples.
class Middleware
def initialize(app)
@app = app
end
def call(env)
@app.call(env)
end
end
end
| # frozen_string_literal: true
module ApiSampler
# This class provides rack-compatible middleware to collect and tag API
# endpoint samples.
class Middleware
def initialize(app)
@app = app
end
def call(env)
request = Rack::Request.new(env)
status, headers, response = @app.call(env)
collect_sample(request, response)
[status, headers, response]
end
# Collects a sample of the current request.
#
# @param request [Rack::Request] current request.
# @param response [ActiveDispatch::Response::RackBody] response body.
def collect_sample(request, response)
endpoint = ApiSampler::Endpoint.find_or_create_by!(path: request.path)
endpoint.samples.create!(request_method: request.request_method,
query: request.query_string,
request_body: request.body.read,
response_body: response.body)
rescue ActiveRecord::RecordInvalid => error
Rails.logger.error "api_sampler :: collect_sample :: #{error}"
end
end
end
|
Add link to specfic area from id and name in area table. | class AreasController < ApplicationController
def index
@areas = Area.all
@areas_grid = AreasGrid.new(params[:areas_grid]) do |scope|
scope.page(params[:page])
end
end
def show
@area = Area.find(params[:id])
@initiatives = Initiative.where(area_id: @area)
end
def new
end
end
class AreasGrid
include Datagrid
scope do
Area
end
column(:id, :mandatory => true)
column(:name, :mandatory => true)
column(:description, :mandatory => true)
end
| class AreasController < ApplicationController
def index
@areas = Area.all
@areas_grid = AreasGrid.new(params[:areas_grid]) do |scope|
scope.page(params[:page])
end
end
def show
@area = Area.find(params[:id])
@initiatives = Initiative.where(area_id: @area)
end
def new
end
end
class AreasGrid
include Datagrid
scope do
Area
end
column(:id, :mandatory => true) do |model|
format(model.id) do |value|
link_to value, model
end
end
column(:name, :mandatory => true) do |model|
format(model.name) do |value|
link_to value, model
end
end
column(:description, :mandatory => true)
end
|
Migrate xhr helper functions in rspec tests | module AuthenticationHelper
def user_params(attrs = {})
args = { user_name: 'test',
first_name: 'Mark',
last_name: 'Us' }.merge(attrs)
ActionController::Parameters.new(user: args)
end
def get_as(user, action, params = nil, flash = nil)
session_vars = { 'uid' => user.id, 'timeout' => 3.days.from_now }
xhr :get, action, params, session_vars, flash
end
# Performs POST request as the supplied user for authentication
def post_as(user, action, params = nil, flash = nil)
session_vars = { 'uid' => user.id, 'timeout' => 3.days.from_now }
xhr :post, action, params, session_vars, flash
end
# Performs PUT request as the supplied user for authentication
def put_as(user, action, params = nil, flash = nil)
session_vars = { 'uid' => user.id, 'timeout' => 3.days.from_now }
xhr :put, action, params, session_vars, flash
end
# Performs DELETE request as the supplied user for authentication
def delete_as(user, action, params = nil, flash = nil)
session_vars = { 'uid' => user.id, 'timeout' => 3.days.from_now }
xhr :delete, action, params, session_vars, flash
end
end
| module AuthenticationHelper
def user_params(attrs = {})
args = { user_name: 'test',
first_name: 'Mark',
last_name: 'Us' }.merge(attrs)
ActionController::Parameters.new(user: args)
end
def sign_in(user)
real_controller = @controller
@controller = MainController.new
post :login, params: { user_login: user.user_name, user_password: 'x' }
@controller = real_controller
end
def get_as(user, action, params = nil)
sign_in user
get action, xhr: true, params: params
end
# Performs POST request as the supplied user for authentication
def post_as(user, action, params = nil)
sign_in user
post action, xhr: true, params: params
end
# Performs PUT request as the supplied user for authentication
def put_as(user, action, params = nil)
sign_in user
put action, xhr: true, params: params
end
# Performs DELETE request as the supplied user for authentication
def delete_as(user, action, params = nil)
sign_in user
delete action, xhr: true, params: params
end
end
|
Use a constant for the default robots.txt filename | class RobotsController < ApplicationController
def robots
filename = if subdomain && subdomain != 'www'
"config/robots.#{ subdomain }.txt"
end
file_to_render = File.exists?(filename.to_s) ? filename : 'config/robots.txt'
render file: file_to_render, layout: false, content_type: 'text/plain'
end
private
def subdomain
request.subdomain.present? ? request.subdomain : nil
end
end
| class RobotsController < ApplicationController
DEFAULT_FILENAME = 'config/robots.txt'.freeze
def robots
filename = if subdomain && subdomain != 'www'
"config/robots.#{ subdomain }.txt"
end
file_to_render = File.exists?(filename.to_s) ? filename : DEFAULT_FILENAME
render file: file_to_render, layout: false, content_type: 'text/plain'
end
private
def subdomain
request.subdomain.present? ? request.subdomain : nil
end
end
|
Replace temporary user solution with current_user helper | class SkillsController < ApplicationController
def index
@new_skill = Skill.new
end
def new
end
def create
skill = User.first.skills.build(skills_params)
if skill.save
respond_to do |format|
format.html {redirect_to skill_path(skill)}
format.json {render json: skill.as_json({only: :title})}
end
end
end
def refresh
skill = Skill.find(params[:format])
skill.refresh_expiration_time
redirect_to root_path
end
def destroy
end
private
def skills_params
params.require(:skill).permit(:title, :user_id)
end
end | class SkillsController < ApplicationController
def index
@new_skill = Skill.new
end
def new
end
def create
skill = current_user.skills.build(skills_params)
if skill.save
respond_to do |format|
format.html {redirect_to skill_path(skill)}
format.json {render json: skill.as_json({only: :title})}
end
end
end
def refresh
skill = Skill.find(params[:format])
skill.refresh_expiration_time
redirect_to root_path
end
def destroy
end
private
def skills_params
params.require(:skill).permit(:title, :user_id)
end
end |
Use integer id for finding records, because strings will trigger the slug search of friendly_id | require 'hashie'
module Refinery
module Elasticsearch
class Result
def initialize(attributes={})
@result = Hashie::Mash.new(attributes)
end
def has_highlight?
@result.respond_to?(:highlight)
end
def klass
@klass ||= @result['_type'].gsub('-', '/').camelize.constantize
end
def record
@record ||= klass.find(@result['_id']) rescue nil
end
# Delegate methods to `@result` or `@result._source`
#
def method_missing(method_name, *arguments)
case
when @result.respond_to?(method_name.to_sym)
@result.__send__ method_name.to_sym, *arguments
when @result._source && @result._source.respond_to?(method_name.to_sym)
@result._source.__send__ method_name.to_sym, *arguments
else
super
end
end
# Respond to methods from `@result` or `@result._source`
#
def respond_to?(method_name, include_private = false)
@result.respond_to?(method_name.to_sym) || \
@result._source && @result._source.respond_to?(method_name.to_sym) || \
super
end
def as_json(options={})
@result.as_json(options)
end
end
end
end
| require 'hashie'
module Refinery
module Elasticsearch
class Result
def initialize(attributes={})
@result = Hashie::Mash.new(attributes)
end
def has_highlight?
@result.respond_to?(:highlight)
end
def klass
@klass ||= @result['_type'].gsub('-', '/').camelize.constantize
end
def record
@record ||= klass.find(@result['_id'].to_i) rescue nil
end
# Delegate methods to `@result` or `@result._source`
#
def method_missing(method_name, *arguments)
case
when @result.respond_to?(method_name.to_sym)
@result.__send__ method_name.to_sym, *arguments
when @result._source && @result._source.respond_to?(method_name.to_sym)
@result._source.__send__ method_name.to_sym, *arguments
else
super
end
end
# Respond to methods from `@result` or `@result._source`
#
def respond_to?(method_name, include_private = false)
@result.respond_to?(method_name.to_sym) || \
@result._source && @result._source.respond_to?(method_name.to_sym) || \
super
end
def as_json(options={})
@result.as_json(options)
end
end
end
end
|
Fix pagination bug where the limit parsed to an array value | class NationBuilder::Paginator
attr_reader :body
def initialize(client, body)
@client = client
@body = body
end
[:next, :prev].each do |page_type|
define_method(:"#{page_type}?") do
@body[page_type.to_s]
end
define_method(:"#{page_type}") do |call_body = {}|
return nil unless send(:"#{page_type}?")
path = send(:"#{page_type}?").split('/api/v1').last
call_body[:limit] ||= CGI.parse(path)['limit']
results = @client.raw_call(path, :get, call_body)
return self.class.new(@client, results)
end
end
end
| class NationBuilder::Paginator
attr_reader :body
def initialize(client, body)
@client = client
@body = body
end
[:next, :prev].each do |page_type|
define_method(:"#{page_type}?") do
@body[page_type.to_s]
end
define_method(:"#{page_type}") do |call_body = {}|
return nil unless send(:"#{page_type}?")
path = send(:"#{page_type}?").split('/api/v1').last
call_body[:limit] ||= CGI.parse(path)['limit'][0]
results = @client.raw_call(path, :get, call_body)
return self.class.new(@client, results)
end
end
end
|
Add response headers to request stubs. | require 'cucumber/formatter/unicode' # Remove this line if you don't want Cucumber Unicode support
require 'pry'
require 'json_spec/cucumber'
require 'petstore'
module Petstore
class Client
def initialize(opts = {})
@conn = Faraday.new do |builder|
builder.adapter :test do |stub|
stub.get('/pet/1') { |env| [200, {}, "{\"id\": 1}"] }
stub.get('/pet/findByStatus?status=sold') { |env| [200, {}, "[{\"id\": 1}, {\"id\": 2}]"] }
stub.get('/pet/findByTags?tags=tag1%2Ctag2') { |env| [200, {}, "[{\"id\": 1}]"] }
stub.post('/pet', {"id"=>"1", "name"=>"Rex"}) { |env| [200, {}, "{\"code\": 200, \"message\": \"SUCCESS\"}"] }
stub.put('/pet', {"id"=>"2", "name"=>"RinTinTin"}) { |env| [200, {}, "{\"id\": 2, \"name\": \"RinTinTin\"}"] }
stub.delete('/pet/1') { |env| [200, {}, "no content"] }
end
end
end
end
end | require 'cucumber/formatter/unicode' # Remove this line if you don't want Cucumber Unicode support
require 'pry'
require 'json_spec/cucumber'
require 'petstore'
module Petstore
class Client
def initialize(opts = {})
resp_headers = {"Content-Type" => "application/json",
"Connection" => "close",
"Access-Control-Allow-Headers" => "Content-Type, api_key, Authorization",
"Access-Control-Allow-Methods" => "GET, POST, DELETE, PUT, PATCH, OPTIONS"}
@conn = Faraday.new do |builder|
builder.adapter :test do |stub|
stub.get('/pet/1') { |env| [200, {}, "{\"id\": 1}"] }
stub.get('/pet/findByStatus?status=sold') { |env| [200, resp_headers, "[{\"id\": 1}, {\"id\": 2}]"] }
stub.get('/pet/findByTags?tags=tag1%2Ctag2') { |env| [200, resp_headers, "[{\"id\": 1}]"] }
stub.post('/pet', {"id"=>"1", "name"=>"Rex"}) { |env| [200, resp_headers, "{\"code\": 200, \"message\": \"SUCCESS\"}"] }
stub.put('/pet', {"id"=>"2", "name"=>"RinTinTin"}) { |env| [200, resp_headers, "{\"id\": 2, \"name\": \"RinTinTin\"}"] }
stub.delete('/pet/1') { |env| [200, {}, "no content"] }
end
end
end
end
end |
Add remote image URL support | class Catch < ActiveRecord::Base
scope :recent, -> { order 'caught_at DESC' }
scope :top_10, -> { limit 10 }
scope :for_competition, ->(competition) { where competition: competition }
has_attached_file :image, styles: { medium: '300x300#',
thumbnail: '60x60#' },
default_url: '/images/:style/missing.png'
belongs_to :competition, inverse_of: 'catches', counter_cache: true
belongs_to :user, inverse_of: 'catches', counter_cache: true
validates :competition, presence: true
validates :user, presence: true
validates :bait_used, presence: true
validates :location_description, presence: true
validates_attachment_presence :image
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
validates :length_in_inches,
presence: true,
numericality: { only_integer: true, greater_than_or_equal_to: 0 },
allow_blank: true
# Overidden
def to_param
"#{id} #{species}".parameterize
end
end
| class Catch < ActiveRecord::Base
scope :recent, -> { order 'caught_at DESC' }
scope :top_10, -> { limit 10 }
scope :for_competition, ->(competition) { where competition: competition }
attr_reader :image_remote_url
has_attached_file :image, styles: { medium: '300x300#',
thumbnail: '60x60#' },
default_url: '/images/:style/missing.png'
belongs_to :competition, inverse_of: 'catches', counter_cache: true
belongs_to :user, inverse_of: 'catches', counter_cache: true
validates :competition, presence: true
validates :user, presence: true
validates :bait_used, presence: true
validates :location_description, presence: true
validates_attachment_presence :image
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
validates :length_in_inches,
presence: true,
numericality: { only_integer: true, greater_than_or_equal_to: 0 },
allow_blank: true
# Overidden
def to_param
"#{id} #{species}".parameterize
end
# see: https://github.com/thoughtbot/paperclip/wiki/Attachment-downloaded-from-a-URL
def image_remote_url=(url_value)
self.image = URI.parse url_value
# Assuming url_value is http://example.com/photos/face.png
# avatar_file_name == "face.png"
# avatar_content_type == "image/png"
@image_remote_url = url_value
end
end
|
Update rake requirement from ~> 10.0 to ~> 12.3 | # coding: utf-8
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "activemodel_email_address_validator/version"
Gem::Specification.new do |spec|
spec.name = "activemodel-email_address_validator"
spec.version = ActiveModelEmailAddressValidator::VERSION
spec.authors = ["Jakob Skjerning"]
spec.email = ["jakob@mentalized.net"]
spec.summary = "ActiveModel-style email address format validator"
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "activemodel", ">= 4.0", "< 6.0"
spec.add_development_dependency "bundler", "~> 2.0"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "minitest"
end
| # coding: utf-8
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "activemodel_email_address_validator/version"
Gem::Specification.new do |spec|
spec.name = "activemodel-email_address_validator"
spec.version = ActiveModelEmailAddressValidator::VERSION
spec.authors = ["Jakob Skjerning"]
spec.email = ["jakob@mentalized.net"]
spec.summary = "ActiveModel-style email address format validator"
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "activemodel", ">= 4.0", "< 6.0"
spec.add_development_dependency "bundler", "~> 2.0"
spec.add_development_dependency "rake", "~> 12.3"
spec.add_development_dependency "minitest"
end
|
Use github for latest data. | # encoding: UTF-8
require 'money'
require 'date'
require 'yajl'
require 'open-uri'
class Money
module Bank
module OpenExchangeRatesLoader
HIST_URL = 'https://raw.github.com/currencybot/open-exchange-rates/master/historical/'
OER_URL = 'http://openexchangerates.org/latest.php'
# Tries to load data from OpenExchangeRates for the given rate.
# Won't do anything if there's no data available for that date
# in OpenExchangeRates (short) history.
def load_data(date)
rates_source = if date == Date.today
OER_URL
else
# Should we use strftime, does to_s have better performance ? Or is it localized accross systems ?
HIST_URL + date.to_s + '.json'
end
doc = Yajl::Parser.parse(open(rates_source).read)
base_currency = doc['base'] || 'USD'
doc['rates'].each do |currency, rate|
# Don't use set_rate here, since this method can only be called from
# get_rate, which already aquired a mutex.
internal_set_rate(date, base_currency, currency, rate)
end
end
end
end
end
| # encoding: UTF-8
require 'money'
require 'date'
require 'yajl'
require 'open-uri'
class Money
module Bank
module OpenExchangeRatesLoader
HIST_URL = 'https://raw.github.com/currencybot/open-exchange-rates/master/historical/'
OER_URL = 'https://github.com/currencybot/open-exchange-rates/blob/master/latest.json'
# Tries to load data from OpenExchangeRates for the given rate.
# Won't do anything if there's no data available for that date
# in OpenExchangeRates (short) history.
def load_data(date)
rates_source = if date == Date.today
OER_URL
else
# Should we use strftime, does to_s have better performance ? Or is it localized accross systems ?
HIST_URL + date.to_s + '.json'
end
doc = Yajl::Parser.parse(open(rates_source).read)
base_currency = doc['base'] || 'USD'
doc['rates'].each do |currency, rate|
# Don't use set_rate here, since this method can only be called from
# get_rate, which already aquired a mutex.
internal_set_rate(date, base_currency, currency, rate)
end
end
end
end
end
|
Fix tests so that we don't get sequencing issues | ENV['RACK_ENV'] = 'test'
require File.expand_path('../../panopticon', __FILE__)
require 'test/unit'
require 'rack/test'
class PanopticonTest < Test::Unit::TestCase
include Rack::Test::Methods
def app
Sinatra::Application
end
def test_it_returns_an_http_201_for_success
params = {:name => 'james', :owning_app => 'guides', :kind => 'guide'}
post '/slugs', :slug => params
assert_equal 201, last_response.status
end
def test_it_returns_an_http_406_for_duplicate_slug
params = {:name => 'james', :owning_app => 'guides', :kind => 'blah'}
post '/slugs', :slug => params
post '/slugs', :slug => params
assert_equal 406, last_response.status
end
def test_get_returns_details_as_json
params = {:name => 'another-james', :owning_app => 'guides', :kind => 'blah'}
post '/slugs', :slug => params
get '/slugs/another-james'
assert_equal 200, last_response.status
assert_equal 'blah', JSON.parse(last_response.body)['kind']
end
def test_get_returns_an_http_404_for_unknown_slug
get '/slugs/something-new'
assert_equal 404, last_response.status
end
end
| ENV['RACK_ENV'] = 'test'
require File.expand_path('../../panopticon', __FILE__)
require 'test/unit'
require 'rack/test'
class PanopticonTest < Test::Unit::TestCase
include Rack::Test::Methods
def app
Sinatra::Application
end
def test_it_returns_an_http_201_for_success
params = {:name => 'james1', :owning_app => 'guides', :kind => 'guide'}
post '/slugs', :slug => params
assert_equal 201, last_response.status
end
def test_it_returns_an_http_406_for_duplicate_slug
params = {:name => 'james2', :owning_app => 'guides', :kind => 'blah'}
post '/slugs', :slug => params
post '/slugs', :slug => params
assert_equal 406, last_response.status
end
def test_get_returns_details_as_json
params = {:name => 'james3', :owning_app => 'guides', :kind => 'blah'}
post '/slugs', :slug => params
get '/slugs/another-james'
assert_equal 200, last_response.status
assert_equal 'blah', JSON.parse(last_response.body)['kind']
end
def test_get_returns_an_http_404_for_unknown_slug
get '/slugs/something-new'
assert_equal 404, last_response.status
end
end
|
Change kuviz presenter to return id instead of visualization field | module Carto
module Api
module Public
class KuvizPresenter
def initialize(context, user, kuviz)
@context = context
@user = user
@kuviz = kuviz
end
def to_hash
{
visualization: @kuviz.id,
name: @kuviz.name,
privacy: @kuviz.privacy,
created_at: @kuviz.created_at,
updated_at: @kuviz.updated_at,
url: CartoDB.url(@context, 'kuviz_show',
params: { id: @kuviz.id },
user: @user)
}
end
end
end
end
end
| module Carto
module Api
module Public
class KuvizPresenter
def initialize(context, user, kuviz)
@context = context
@user = user
@kuviz = kuviz
end
def to_hash
{
id: @kuviz.id,
name: @kuviz.name,
privacy: @kuviz.privacy,
created_at: @kuviz.created_at,
updated_at: @kuviz.updated_at,
url: CartoDB.url(@context, 'kuviz_show',
params: { id: @kuviz.id },
user: @user)
}
end
end
end
end
end
|
Add key and encrypted value to failed decryption error message | require 'chamber/errors/decryption_failure'
module Chamber
module Filters
class FailedDecryptionFilter
SECURE_KEY_TOKEN = /\A_secure_/
BASE64_STRING_PATTERN = %r{\A[A-Za-z0-9\+/]{342}==\z}
def initialize(options = {})
self.data = options.fetch(:data).dup
end
def self.execute(options = {})
new(options).send(:execute)
end
protected
attr_accessor :data
def execute(raw_data = data)
settings = raw_data
raw_data.each_pair do |key, value|
if value.respond_to? :each_pair
execute(value)
elsif key.match(SECURE_KEY_TOKEN) &&
value.respond_to?(:match) &&
value.match(BASE64_STRING_PATTERN)
fail Chamber::Errors::DecryptionFailure,
'Failed to decrypt values in your settings.'
end
end
settings
end
end
end
end
| require 'chamber/errors/decryption_failure'
module Chamber
module Filters
class FailedDecryptionFilter
SECURE_KEY_TOKEN = /\A_secure_/
BASE64_STRING_PATTERN = %r{\A[A-Za-z0-9\+/]{342}==\z}
def initialize(options = {})
self.data = options.fetch(:data).dup
end
def self.execute(options = {})
new(options).send(:execute)
end
protected
attr_accessor :data
def execute(raw_data = data)
settings = raw_data
raw_data.each_pair do |key, value|
if value.respond_to? :each_pair
execute(value)
elsif key.match(SECURE_KEY_TOKEN) &&
value.respond_to?(:match) &&
value.match(BASE64_STRING_PATTERN)
fail Chamber::Errors::DecryptionFailure,
"Failed to decrypt #{key} (with an encrypted value of '#{value}') " \
'in your settings.'
end
end
settings
end
end
end
end
|
Fix pathing issue with image upload | get '/' do
erb :index
end
get '/upload' do
haml :"/partials/_upload"
end
post '/images' do
p "*" * 100
p params
p "*" * 100
return params[:file]
end
# Handle POST-request (Receive and save the uploaded file)
post "/" do
p "*" * 100
p params
p "*" * 100
File.open(File.dirname(__FILE__) + '/../../public/uploads/' + params['myfile'][:filename], "w") do |f|
f.write(File.open(params['myfile'][:tempfile], "r").read)
end
new_image = Imagefile.create( filename: params['myfile'][:filename],
url: '/uploads/' + params['myfile'][:filename])
if request.xhr?
return File.dirname(__FILE__) + '/../../public/uploads/' + params['myfile'][:filename]
else
redirect "/review/#{new_image.id}"
end
end
get '/review/:id' do
@image = Imagefile.find_by(id: params[:id])
if request.xhr?
# haml :"/partials/_review"
"HAML"
else
erb :"/partials/_review"
end
end | get '/' do
erb :index
end
get '/upload' do
haml :"/partials/_upload"
end
post '/images' do
p "*" * 100
p params
p "*" * 100
return params[:file]
end
# Handle POST-request (Receive and save the uploaded file)
post "/" do
p "*" * 100
p APP_ROOT.join(Dir.pwd + '/public/uploads/' + params['myfile'][:filename]).to_s
p "*" * 100
File.open(APP_ROOT.join(Dir.pwd + '/public/uploads/' + params['myfile'][:filename]).to_s, "w") do |f|
f.write(File.open(params['myfile'][:tempfile], "r").read)
end
new_image = Imagefile.create( filename: params['myfile'][:filename],
url: '/uploads/' + params['myfile'][:filename])
if request.xhr?
return File.dirname(__FILE__) + '/../../public/uploads/' + params['myfile'][:filename]
else
redirect "/review/#{new_image.id}"
end
end
get '/review/:id' do
@image = Imagefile.find_by(id: params[:id])
if request.xhr?
# haml :"/partials/_review"
"HAML"
else
erb :"/partials/_review"
end
end |
Generalize return parameters img_title and img_alt | module Scrapers
VERSION = "0.4.1"
DESCRIPTION = "A library of web site scrapers utilizing mechanize and other goodies. Helpful in gathering images, moving things, saving things, etc."
SUMMARY = "Web site scrapers"
LICENSE = "MIT"
WEBSITE = "http://github.com/tamouse/scrapers"
end
| module Scrapers
VERSION = "0.4.2"
DESCRIPTION = "A library of web site scrapers utilizing mechanize and other goodies. Helpful in gathering images, moving things, saving things, etc."
SUMMARY = "Web site scrapers"
LICENSE = "MIT"
WEBSITE = "http://github.com/tamouse/scrapers"
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.