Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Use class_attribute instead of deprecated class_inheritable_accessor. | module LybSidebar
module Controller
extend ActiveSupport::Concern
included do
class_inheritable_accessor :sidebars
end
module ClassMethods
def sidebar(options = true)
if options.is_a? TrueClass
self.sidebars = ["#{controller_name}/sidebar"]
end
end
end
end
end
| module LybSidebar
module Controller
extend ActiveSupport::Concern
included do
class_attribute :sidebars
end
module ClassMethods
def sidebar(options = true)
if options.is_a? TrueClass
self.sidebars = ["#{controller_name}/sidebar"]
end
end
end
end
end
|
Add rails-i18n gem as dependency | $LOAD_PATH.push File.expand_path('../lib', __FILE__)
require 'active_portal/version'
Gem::Specification.new do |s|
s.name = 'activeportal'
s.version = ActivePortal::VERSION
s.authors = ['Jozsef Nyitrai']
s.email = ['nyitrai.jozsef@gmail.com']
s.homepage = 'http://github.com/nyjt/activeportal'
s.summary = 'Ruby on Rails portal gem'
s.description = 'This gem make easier to building modern web 2.0 portals using Ruby on Rails.'
s.license = 'MIT'
s.files = Dir['{app,config,db,lib}/**/*', 'MIT-LICENSE', 'Rakefile', 'README.rdoc']
s.add_dependency 'rails', '~> 4.0'
s.add_dependency 'devise-i18n-bootstrap'
s.add_dependency 'devise'
s.add_dependency 'http_accept_language'
s.add_development_dependency 'pg'
s.add_development_dependency 'rspec', '~> 3.0.0'
s.add_development_dependency 'rspec-rails', '~> 3.0.0'
s.add_development_dependency 'capybara'
s.add_development_dependency 'factory_girl_rails'
s.add_development_dependency 'database_cleaner'
end
| $LOAD_PATH.push File.expand_path('../lib', __FILE__)
require 'active_portal/version'
Gem::Specification.new do |s|
s.name = 'activeportal'
s.version = ActivePortal::VERSION
s.authors = ['Jozsef Nyitrai']
s.email = ['nyitrai.jozsef@gmail.com']
s.homepage = 'http://github.com/nyjt/activeportal'
s.summary = 'Ruby on Rails portal gem'
s.description = 'This gem make easier to building modern web 2.0 portals using Ruby on Rails.'
s.license = 'MIT'
s.files = Dir['{app,config,db,lib}/**/*', 'MIT-LICENSE', 'Rakefile', 'README.rdoc']
s.add_dependency 'rails', '~> 4.0'
s.add_dependency 'rails-i18n', '~> 4.0'
s.add_dependency 'devise-i18n-bootstrap'
s.add_dependency 'devise'
s.add_dependency 'http_accept_language'
s.add_development_dependency 'pg'
s.add_development_dependency 'rspec', '~> 3.0.0'
s.add_development_dependency 'rspec-rails', '~> 3.0.0'
s.add_development_dependency 'capybara'
s.add_development_dependency 'factory_girl_rails'
s.add_development_dependency 'database_cleaner'
end
|
Add searching by tags to Idea model | class Idea < ActiveRecord::Base
belongs_to :owner, :class_name => 'User'
has_many :comments, -> { order(created_at: :asc) }, :dependent => :destroy
has_and_belongs_to_many :tags,
-> { order('name') },
join_table: "idea_tags"
validates :title, presence: true, uniqueness: {case_sensitive: false}
validates :description, :owner_id, presence: true
def tag_names
tags.map{ |tag| tag.name }.sort.join(', ')
end
end
| class Idea < ActiveRecord::Base
belongs_to :owner, :class_name => 'User'
has_many :comments, -> { order(created_at: :asc) }, :dependent => :destroy
has_and_belongs_to_many :tags,
-> { order('name') },
join_table: "idea_tags"
validates :title, presence: true, uniqueness: {case_sensitive: false}
validates :description, :owner_id, presence: true
include PgSearch
pg_search_scope :search_tags, :associated_against => {
:tags => :name
}
def tag_names
tags.map{ |tag| tag.name }.sort.join(', ')
end
end
|
Update podspec to support 1.0.1 | Pod::Spec.new do |s|
s.name = "CCLogSystem"
s.version = "1.0.0"
s.summary = "A Log system for iOS."
s.description = <<-DESC
This library provide an iOS Log System. We can use it to replace NSLog.
And It also can record the log to the local files.
We can directly review these logs in our app, and email to ourselves.
DESC
s.homepage = "https://github.com/yechunjun/CCLogSystem"
s.license = "MIT"
s.author = { "Chun Ye" => "chunforios@gmail.com" }
s.social_media_url = "http://chun.tips"
s.platform = :ios, "6.0"
s.source = { :git => "https://github.com/yechunjun/CCLogSystem.git", :tag => "1.0.0" }
s.source_files = "CCLogSystem/CCLogSystem/*.{h,m}"
s.frameworks = "Foundation", "UIKit"
s.requires_arc = true
end
| Pod::Spec.new do |s|
s.name = "CCLogSystem"
s.version = "1.0.1"
s.summary = "A Log system for iOS."
s.description = <<-DESC
This library provide an iOS Log System. We can use it to replace NSLog.
And It also can record the log to the local files.
We can directly review these logs in our app, and email to ourselves.
DESC
s.homepage = "https://github.com/yechunjun/CCLogSystem"
s.license = "MIT"
s.author = { "Chun Ye" => "chunforios@gmail.com" }
s.social_media_url = "http://chun.tips"
s.platform = :ios, "6.0"
s.source = { :git => "https://github.com/yechunjun/CCLogSystem.git", :tag => "1.0.1" }
s.source_files = "CCLogSystem/CCLogSystem/*.{h,m}"
s.frameworks = "Foundation", "UIKit"
s.requires_arc = true
end
|
Fix migrations, and still guarantee GrantStatus id=1 | class GrantStatus < ActiveRecord::Base; end
class AddGrantStatusData < ActiveRecord::Migration
def up
GrantStatus.delete_all
GrantStatus.create(description: "Incomplete", id: 1)
GrantStatus.create(description: "Submitted")
GrantStatus.create(description: "Approved")
GrantStatus.create(description: "Denied")
GrantStatus.create(description: "Paid")
GrantStatus.create(description: "Refund Needed")
GrantStatus.create(description: "Refund Received")
end
def down
GrantStatus.delete_all
end
end
| class GrantStatus < ActiveRecord::Base; end
class AddGrantStatusData < ActiveRecord::Migration
def up
remove_foreign_key "grants", "grant_statuses"
execute 'TRUNCATE TABLE grant_statuses'
execute 'ALTER SEQUENCE grants_id_seq RESTART WITH 1;'
GrantStatus.create(description: "Incomplete")
GrantStatus.create(description: "Submitted")
GrantStatus.create(description: "Approved")
GrantStatus.create(description: "Denied")
GrantStatus.create(description: "Paid")
GrantStatus.create(description: "Refund Needed")
GrantStatus.create(description: "Refund Received")
add_foreign_key "grants", "grant_statuses"
end
def down
GrantStatus.delete_all
end
end
|
Upgrade Opera Beta.app to v29.0.1795.35 | cask :v1 => 'opera-beta' do
version '29.0.1795.30'
sha256 '6ef44a4236ad4f29bfc2c66bc8b542fb583fb50fb7c267fbd4777ccaca59adcb'
url "http://get.geo.opera.com/pub/opera-beta/#{version}/mac/Opera_beta_#{version}_Setup.dmg"
homepage 'http://www.opera.com/computer/beta'
license :unknown
app 'Opera Beta.app'
end
| cask :v1 => 'opera-beta' do
version '29.0.1795.35'
sha256 '0b6ee1cad2b335bd95c1c77c24e13fabad80419f430a91e10ea62a4574064cac'
url "http://get.geo.opera.com/pub/opera-beta/#{version}/mac/Opera_beta_#{version}_Setup.dmg"
homepage 'http://www.opera.com/computer/beta'
license :unknown
app 'Opera Beta.app'
end
|
Rewrite load_file to use IO instead of StringIO. Way faster. |
require 'strscan'
module BEncode
# Encodes the Ruby object +obj+ into a bencoded string.
#
# @param [Hash, Array, Integer, String] obj the object to encode
# @return [String] a bencoded string
# @raise [EncodeError] if +obj+ is not a supported object type
def self.dump(obj)
obj.bencode
end
# Decodes +str+ into a Ruby structure.
#
# @param [String] str a bencoded string
# @option opts [Boolean] :ignore_trailing_junk (false) whether
# to ignore invalid bencode at the end of +str+
# @return [Object] a Ruby object
# @raise [DecodeError] if +str+ is malformed
def self.load(str, opts = {})
scanner = BEncode::Parser.new(str)
obj = scanner.parse!
raise BEncode::DecodeError unless (opts[:ignore_trailing_junk] || scanner.eos?)
obj
end
# Decodes the file located at +path+.
#
# @param [String] path path to the bencoded file
# @option (see .load)
# @return (see .load)
def self.load_file(path, opts = {})
load(File.open(path, 'rb').read, opts)
end
end
|
require 'strscan'
module BEncode
# Encodes the Ruby object +obj+ into a bencoded string.
#
# @param [Hash, Array, Integer, String] obj the object to encode
# @return [String] a bencoded string
# @raise [EncodeError] if +obj+ is not a supported object type
def self.dump(obj)
obj.bencode
end
# Decodes +str+ into a Ruby structure.
#
# @param [String] str a bencoded string
# @option opts [Boolean] :ignore_trailing_junk (false) whether
# to ignore invalid bencode at the end of +str+
# @return [Object] a Ruby object
# @raise [DecodeError] if +str+ is malformed
def self.load(str, opts = {})
scanner = BEncode::Parser.new(str)
obj = scanner.parse!
raise BEncode::DecodeError unless (opts[:ignore_trailing_junk] || scanner.eos?)
obj
end
# Decodes the file located at +path+.
#
# @param [String] path path to the bencoded file
# @option (see .load)
# @return (see .load)
def self.load_file(path, opts = {})
File.open(path, 'rb') do |io|
load(io, opts)
end
end
end
|
Add validations to Answer model | class Answer < ActiveRecord::Base
belongs_to :user
belongs_to :question
has_many :votes, as: :votable
has_many :comments, as: :commentable
validates :content, presence: true, length: { minimum: 2 }
end
| class Answer < ActiveRecord::Base
belongs_to :user
belongs_to :question
has_many :votes, as: :votable
has_many :comments, as: :commentable
validates :content, presence: true, length: { minimum: 2 }
validates :user_id, :question_id, presence: true
end
|
Update gemspec to deal with new README files | require 'rubygems'
SPEC = Gem::Specification.new do |s|
s.name = "yard"
s.version = "0.2.1"
s.date = "2007-05-20"
s.author = "Loren Segal"
s.email = "lsegal@soen.ca"
s.homepage = "http://yard.soen.ca"
s.platform = Gem::Platform::RUBY
s.summary = "A documentation tool for consistent and usable documentation in Ruby."
s.files = Dir.glob("{bin,lib,test,templates}/**/*") + ['LICENSE.txt', 'README.pdf']
s.executables = [ 'yardoc', 'yri' ]
s.add_dependency 'erubis'
# s.has_rdoc = false
end
| require 'rubygems'
SPEC = Gem::Specification.new do |s|
s.name = "yard"
s.version = "0.2.1"
s.date = "2007-05-20"
s.author = "Loren Segal"
s.email = "lsegal@soen.ca"
s.homepage = "http://yard.soen.ca"
s.platform = Gem::Platform::RUBY
s.summary = "A documentation tool for consistent and usable documentation in Ruby."
s.files = Dir.glob("{bin,lib,test,templates}/**/*") + ['LICENSE.txt', 'README.txt', 'help.pdf']
s.executables = [ 'yardoc', 'yri' ]
s.add_dependency 'erubis'
s.has_rdoc = false
end
|
Fix invalid redirect when updating user | class UsersController < ApplicationController
authorize_resource :class => false
before_action :find_user, :only => [:edit, :update, :destroy]
def index
@users = User.all
end
def new
@user = User.new
end
def edit
end
def update
@user.attributes = user_attributes
if current_user && current_user.admin?
@user.role_id = params[:user][:role_id]
end
if @user.save
redirect_to user_path(@user), notice: 'User updated'
else
render :edit
end
end
def create
@user = User.new(user_attributes)
if current_user && current_user.admin?
@user.role_id = params[:user][:role_id]
end
if @user.save
redirect_to users_path, :notice => 'User added'
else
render :new
end
end
def destroy
@user.destroy
redirect_to users_path, :notice => 'User deleted'
end
#######
private
#######
def find_user
@user = User.find(params[:id])
end
def user_attributes
params.require(:user).permit(
:company_school, :email, :group, :heared_first_at, :name,
:phone_number, :send_score, :trackable, :password, :password_confirmation
)
end
end
| class UsersController < ApplicationController
authorize_resource :class => false
before_action :find_user, :only => [:edit, :update, :destroy]
def index
@users = User.all
end
def new
@user = User.new
end
def edit
end
def update
@user.attributes = user_attributes
if current_user && current_user.admin?
@user.role_id = params[:user][:role_id]
end
if @user.save
redirect_to users_path, notice: 'User updated'
else
render :edit
end
end
def create
@user = User.new(user_attributes)
if current_user && current_user.admin?
@user.role_id = params[:user][:role_id]
end
if @user.save
redirect_to users_path, :notice => 'User added'
else
render :new
end
end
def destroy
@user.destroy
redirect_to users_path, :notice => 'User deleted'
end
#######
private
#######
def find_user
@user = User.find(params[:id])
end
def user_attributes
params.require(:user).permit(
:company_school, :email, :group, :heared_first_at, :name,
:phone_number, :send_score, :trackable, :password, :password_confirmation
)
end
end
|
Add notification configuration to model | require 'fog/core/model'
require 'fog/aws/models/glacier/archives'
require 'fog/aws/models/glacier/jobs'
module Fog
module AWS
class Glacier
class Vault < Fog::Model
identity :id, :aliases => 'VaultName'
attribute :created_at, :aliases => 'CreationDate', :type => :time
attribute :last_inventory_at, :aliases => 'LastInventoryDate', :type => :time
attribute :number_of_archives, :aliases => 'NumberOfArchives', :type => :integer
attribute :size_in_bytes, :aliases => 'SizeInBytes', :type => :integer
attribute :arn, :aliases => 'VaultARN'
def ready?
# Glacier requests are synchronous
true
end
def archives
@archives ||= Fog::AWS::Glacier::Archives.new(:vault => self, :connection => connection)
end
def jobs
@jobs ||= Fog::AWS::Glacier::Jobs.new(:vault => self, :connection => connection)
end
def save
requires :id
data = connection.create_vault(id)
reload
end
def destroy
requires :id
connection.delete_vault(id)
end
end
end
end
end
| require 'fog/core/model'
require 'fog/aws/models/glacier/archives'
require 'fog/aws/models/glacier/jobs'
module Fog
module AWS
class Glacier
class Vault < Fog::Model
identity :id, :aliases => 'VaultName'
attribute :created_at, :aliases => 'CreationDate', :type => :time
attribute :last_inventory_at, :aliases => 'LastInventoryDate', :type => :time
attribute :number_of_archives, :aliases => 'NumberOfArchives', :type => :integer
attribute :size_in_bytes, :aliases => 'SizeInBytes', :type => :integer
attribute :arn, :aliases => 'VaultARN'
def ready?
# Glacier requests are synchronous
true
end
def archives
@archives ||= Fog::AWS::Glacier::Archives.new(:vault => self, :connection => connection)
end
def jobs
@jobs ||= Fog::AWS::Glacier::Jobs.new(:vault => self, :connection => connection)
end
def set_notification_configuration(topic, events)
connection.set_vault_notification_configuration(id, topic, events)
end
def delete_notification_configuration
connection.delete_vault_notification_configuration
end
def save
requires :id
connection.create_vault(id)
reload
end
def destroy
requires :id
connection.delete_vault(id)
end
end
end
end
end
|
Fix offset and pass the test | module Hijri
class DateTime < Date
attr_reader :hour, :minute, :second, :offset, :zone
alias :min :minute
alias :sec :second
def initialize(year=1, month=1, day=1, hour=0, minute=0, second=0, zone="00:00")
super(year, month, day)
@hour = hour
@minute = minute
@second = second
@offset = zone.to_i
@zone = zone
end
def change(kargs)
@hour = kargs.fetch :hour, hour
@minute = kargs.fetch :minute, minute
@second = kargs.fetch :second, second
@zone = kargs.fetch :zone, zone
end
def to_greo
::DateTime.new *Converter.hijri_to_greo(self)
end
def to_s
zone_str = (@zone == '00:00' ? "+#{@zone}" : @zone)
"#{super}T#{sprintf('%02d', @hour)}:#{sprintf('%02d', @minute)}:#{sprintf('%02d', @second)}#{zone_str}"
end
class << self
def now
datetime = ::DateTime.now
hijri = datetime.to_hijri
hijri.change :hour => datetime.hour, :minute => datetime.minute, :second => datetime.second
hijri
end
end
end
end | module Hijri
class DateTime < Date
attr_reader :hour, :minute, :second, :offset, :zone
alias :min :minute
alias :sec :second
def initialize(year=1, month=1, day=1, hour=0, minute=0, second=0, zone="00:00")
super(year, month, day)
@hour = hour
@minute = minute
@second = second
@offset = zone.to_f / 24
@zone = zone
end
def change(kargs)
@hour = kargs.fetch :hour, hour
@minute = kargs.fetch :minute, minute
@second = kargs.fetch :second, second
@zone = kargs.fetch :zone, zone
end
def to_greo
::DateTime.new *Converter.hijri_to_greo(self)
end
def to_s
zone_str = (@zone == '00:00' ? "+#{@zone}" : @zone)
"#{super}T#{sprintf('%02d', @hour)}:#{sprintf('%02d', @minute)}:#{sprintf('%02d', @second)}#{zone_str}"
end
class << self
def now
datetime = ::DateTime.now
hijri = datetime.to_hijri
hijri.change :hour => datetime.hour, :minute => datetime.minute, :second => datetime.second
hijri
end
end
end
end |
Add task to help clean out the database | namespace :github do
task update_old_users: :environment do
GithubUser.visible.order('updated_at ASC').limit(10000).pluck(:login).each {|l| GithubUpdateUserWorker.perform_async(l);}
end
end
| namespace :github do
task update_old_users: :environment do
GithubUser.visible.order('updated_at ASC').limit(10000).pluck(:login).each {|l| GithubUpdateUserWorker.perform_async(l);}
end
task remove_uninteresting_forks: :environment do
GithubRepository.where(id: GithubRepository.fork.open_source.where('stargazers_count < 1').without_projects.without_subscriptons.without_manifests.limit(50000).pluck(:id)).find_each(&:destroy)
end
end
|
Add parentheses to formula display | class CalculationElement < ActiveRecord::Base
belongs_to :left_operand, class_name: CalculationOperand, autosave: true
validates_associated :left_operand
validates_presence_of :left_operand
accepts_nested_attributes_for :left_operand
belongs_to :right_operand, class_name: CalculationOperand, autosave: true
validates_associated :right_operand
validates_presence_of :right_operand
accepts_nested_attributes_for :right_operand
# t.integer "operator"
def self.build
new_element = CalculationElement.new
new_element.left_operand = CalculationOperand.new
new_element.right_operand = CalculationOperand.new
new_element
end
def to_human_readable
left_operand.to_human_readable + " " + CalculationElement.operator_display_map[operator] + " " + right_operand.to_human_readable
end
def self.operator_map
{
"+ (Add)" => 1,
"- (Subtract)" => 2,
"* (Multiply)" => 3,
"/ (Divide)" => 4
}
end
def self.operator_display_map
{
1 => "+",
2 => "-",
3 => "*",
4 => "/"
}
end
end
| class CalculationElement < ActiveRecord::Base
belongs_to :left_operand, class_name: CalculationOperand, autosave: true
validates_associated :left_operand
validates_presence_of :left_operand
accepts_nested_attributes_for :left_operand
belongs_to :right_operand, class_name: CalculationOperand, autosave: true
validates_associated :right_operand
validates_presence_of :right_operand
accepts_nested_attributes_for :right_operand
# t.integer "operator"
def self.build
new_element = CalculationElement.new
new_element.left_operand = CalculationOperand.new
new_element.right_operand = CalculationOperand.new
new_element
end
def to_human_readable
"(" + left_operand.to_human_readable + " " + CalculationElement.operator_display_map[operator] + " " + right_operand.to_human_readable + ")"
end
def self.operator_map
{
"+ (Add)" => 1,
"- (Subtract)" => 2,
"* (Multiply)" => 3,
"/ (Divide)" => 4
}
end
def self.operator_display_map
{
1 => "+",
2 => "-",
3 => "*",
4 => "/"
}
end
end
|
Add validation for valid categories, and the number of categories | class NameratorsController < ApplicationController
MAX_RESULTS = 50
DEFAULT_RESULTS = 5
# GET /namerators
# GET /namerators.json
def random()
@config = params[:config].split("/")
getCount()
@namerators = []
(1..@count).each do
@namerators.push(Result.new(@config))
end
render json: @namerators
end
def getCount()
@count = Integer(@config.pop) rescue DEFAULT_RESULTS
if @count > MAX_RESULTS
@count = MAX_RESULTS
end
end
# validation?
#if count > MAX_RESULTS
# render json: count, status: :unprocessable_entity
# return
#end
end
| class NameratorsController < ApplicationController
MAX_RESULTS = 50
DEFAULT_RESULTS = 5
# GET /namerators
# GET /namerators.json
def random()
@config = params[:config].split("/")
getCount()
validateCategories() or return
@namerators = []
(1..@count).each do
@namerators.push(Result.new(@config))
end
render json: @namerators
end
def validateCategories()
if(@config.size > 5 )
render json: "Maximum of 5 categories allowed", status: :unprocessable_entity and return
end
#@config.each{ |category| verifyCategory(category) or return }
return true
end
def verifyCategory(category)
return true if(category == "Category")
if Category.find_by(name: category) == nil
render json: "No category: #{category}", status: :unprocessable_entity and return
end
return true
end
def getCount()
if hasCount()
@count = Integer(@config.pop) rescue DEFAULT_RESULTS
if @count > MAX_RESULTS
@count = MAX_RESULTS
end
else
@count = DEFAULT_RESULTS
end
end
def hasCount()
count = Integer(@config.last) rescue false
if count == false
return false
end
true
end
# validation?
#if count > MAX_RESULTS
# render json: count, status: :unprocessable_entity
# return
#end
end
|
Fix easy_type load issues in specific situation | require 'pathname'
$:.unshift(Pathname.new(__FILE__).dirname)
$:.unshift(Pathname.new(__FILE__).dirname.parent.parent + 'easy_type' + 'lib')
require 'easy_type'
require 'utils/wls_access'
require 'utils/settings'
require 'utils/title_parser'
require 'facter'
| require 'pathname'
#$:.unshift(Pathname.new(__FILE__).dirname)
#$:.unshift(Pathname.new(__FILE__).dirname.parent.parent + 'easy_type' + 'lib')
$:.unshift File.dirname(__FILE__)
$:.unshift File.join(File.dirname(__FILE__), '../../easy_type/lib')
require 'easy_type'
require 'utils/wls_access'
require 'utils/settings'
require 'utils/title_parser'
require 'facter'
|
Use resources to get the latest ca bundle | #
# Cookbook Name:: gitlab
# Recipe:: gems
#
gitlab = node['gitlab']
# To prevent random failures during bundle install, get the latest ca-bundle
execute "Fetch the latest ca-bundle" do
command "curl http://curl.haxx.se/ca/cacert.pem --create-dirs -o /opt/local/etc/certs/cacert.pem"
not_if { File.exists?("/opt/local/etc/certs/cacert.pem") }
end
## Install Gems without ri and rdoc
template File.join(gitlab['home'], ".gemrc") do
source "gemrc.erb"
user gitlab['user']
group gitlab['group']
notifies :run, "execute[bundle install]", :immediately
end
### without
bundle_without = []
case gitlab['database_adapter']
when 'mysql'
bundle_without << 'postgres'
bundle_without << 'aws'
when 'postgresql'
bundle_without << 'mysql'
bundle_without << 'aws'
end
case gitlab['env']
when 'production'
bundle_without << 'development'
bundle_without << 'test'
else
bundle_without << 'production'
end
execute "bundle install" do
command <<-EOS
PATH="/usr/local/bin:$PATH"
#{gitlab['bundle_install']} --without #{bundle_without.join(" ")}
EOS
cwd gitlab['path']
user gitlab['user']
group gitlab['group']
action :nothing
end
| #
# Cookbook Name:: gitlab
# Recipe:: gems
#
gitlab = node['gitlab']
# To prevent random failures during bundle install, get the latest ca-bundle
directory "/opt/local/etc/certs/" do
owner gitlab['user']
group gitlab['group']
recursive true
mode 0755
end
remote_file "Fetch the latest ca-bundle" do
source "http://curl.haxx.se/ca/cacert.pem"
path "/opt/local/etc/certs/cacert.pem"
owner gitlab['user']
group gitlab['group']
mode 0755
action :create_if_missing
end
## Install Gems without ri and rdoc
template File.join(gitlab['home'], ".gemrc") do
source "gemrc.erb"
user gitlab['user']
group gitlab['group']
notifies :run, "execute[bundle install]", :immediately
end
### without
bundle_without = []
case gitlab['database_adapter']
when 'mysql'
bundle_without << 'postgres'
bundle_without << 'aws'
when 'postgresql'
bundle_without << 'mysql'
bundle_without << 'aws'
end
case gitlab['env']
when 'production'
bundle_without << 'development'
bundle_without << 'test'
else
bundle_without << 'production'
end
execute "bundle install" do
command <<-EOS
PATH="/usr/local/bin:$PATH"
#{gitlab['bundle_install']} --without #{bundle_without.join(" ")}
EOS
cwd gitlab['path']
user gitlab['user']
group gitlab['group']
action :nothing
end
|
Clarify time unit; no printing. | require 'spec_helper'
describe DynamoDBMutex::Lock do
let(:locker) { DynamoDBMutex::Lock }
let(:lockname) { 'test.lock' }
describe '#with_lock' do
def run(id, ms)
print "invoked worker #{id}...\n"
locker.with_lock 'test.lock' do
sleep(ms)
end
end
it 'should execute block by default' do
locked = false
locker.with_lock(lockname) do
locked = true
end
expect(locked).to eq(true)
end
it 'should raise error after block timeout' do
if pid1 = fork
sleep(1)
expect {
locker.with_lock(lockname) { sleep(1) }
}.to raise_error(DynamoDBMutex::LockError)
Process.waitall
else
run(1, 5)
end
end
it 'should expire lock if stale' do
if pid1 = fork
sleep(2)
locker.with_lock(lockname, wait_for_other: 10) do
expect(locker).to receive(:delete).with('test.lock')
end
Process.waitall
else
run(1, 5)
end
end
end
end
| require 'spec_helper'
describe DynamoDBMutex::Lock do
let(:locker) { DynamoDBMutex::Lock }
let(:lockname) { 'test.lock' }
describe '#with_lock' do
def run(id, seconds)
locker.with_lock(lockname) do
sleep(seconds)
end
end
it 'should execute block by default' do
locked = false
locker.with_lock(lockname) do
locked = true
end
expect(locked).to eq(true)
end
it 'should raise error after block timeout' do
if pid1 = fork
sleep(1)
expect {
locker.with_lock(lockname) { sleep(1) }
}.to raise_error(DynamoDBMutex::LockError)
Process.waitall
else
run(1, 5)
end
end
it 'should expire lock if stale' do
if pid1 = fork
sleep(2)
locker.with_lock(lockname, wait_for_other: 10) do
expect(locker).to receive(:delete).with('test.lock')
end
Process.waitall
else
run(1, 5)
end
end
end
end
|
Add a random option to email sequence in FactoryGirl | FactoryGirl.define do
sequence(:name) { |i| "Name_#{i}" }
sequence(:email) { |i| "user_#{i}@mail.com" }
sequence(:title) { |i| "Title_#{i}" }
end
| FactoryGirl.define do
sequence(:name) { |i| "Name_#{i}" }
sequence(:email) { |i| "user_#{SecureRandom.hex(5)}@mail.com" }
sequence(:title) { |i| "Title_#{i}" }
end
|
Test error display in presenter | require 'consolePresenter'
RSpec.describe ConsolePresenter do
context "With stubbed input and output" do
let(:input) { double("STDIN") }
let(:output) {
output = double("STDOUT")
printed = ""
allow(output).to receive(:print) { |text|
printed += text
}
flushed = ""
allow(output).to receive(:flush) {
flushed += printed
printed = ""
}
allow(output).to receive(:printed) { printed }
allow(output).to receive(:flushed) { flushed }
output
}
let (:io) { ConsoleIO.new(input: input, output: output) }
let (:word) { "pneumatic" }
let (:language) { Language.new } # Will always just do [[:langstringhere||:argshere]] syntax
let (:hangman) { Hangman.new(word: word) }
subject { ConsolePresenter.new(io: io) }
describe "Error handling" do
it "should displaying nothing when no error happend" do
subject.display_error
expect(output.printed).to be_empty
expect(output.flushed).to be_empty
end
end
end
end
| require 'consolePresenter'
RSpec.describe ConsolePresenter do
context "With stubbed input and output" do
let(:input) { double("STDIN") }
let(:output) {
output = double("STDOUT")
printed = ""
allow(output).to receive(:print) { |text|
printed += text
}
flushed = ""
allow(output).to receive(:flush) {
flushed += printed
printed = ""
}
allow(output).to receive(:printed) { printed }
allow(output).to receive(:flushed) { flushed }
output
}
let (:io) { ConsoleIO.new(input: input, output: output) }
let (:word) { "pneumatic" }
let (:language) { Language.new } # Will always just do [[:langstringhere||:argshere]] syntax, test langs seperately
let (:hangman) { Hangman.new(word: word) }
subject { ConsolePresenter.new(io: io) }
describe "Error handling" do
let(:error) { :testingerror}
it "should displaying nothing when no error happend" do
subject.display_error
expect(output.printed).to be_empty
expect(output.flushed).to be_empty
end
it "should not display the error after adding" do
subject.add_error(error)
expect(output.printed).to be_empty
expect(output.flushed).to be_empty
end
it "should display the error we add with a new line" do
subject.add_error(error)
subject.display_error
expect(output.printed).to be_empty
expect(output.flushed).to eq "[["+error.to_s+"]]\n"
end
end
end
end
|
Add dependency of groonga gem |
Gem::Specification.new do |spec|
spec.name = "embulk-output-groonga"
spec.version = "0.1.0"
spec.authors = ["Hiroyuki Sato"]
spec.summary = "Groonga output plugin for Embulk"
spec.description = "Dumps records to Groonga."
spec.email = ["hiroysato@gmail.com"]
spec.licenses = ["MIT"]
# TODO set this: spec.homepage = "https://github.com/hiroyuki-sato/embulk-output-groonga"
spec.files = `git ls-files`.split("\n") + Dir["classpath/*.jar"]
spec.test_files = spec.files.grep(%r{^(test|spec)/})
spec.require_paths = ["lib"]
spec.add_dependency 'groonga-client', ['~> 0.1']
spec.add_development_dependency 'bundler', ['~> 1.0']
spec.add_development_dependency 'rake', ['>= 10.0']
end
|
Gem::Specification.new do |spec|
spec.name = "embulk-output-groonga"
spec.version = "0.1.0"
spec.authors = ["Hiroyuki Sato"]
spec.summary = "Groonga output plugin for Embulk"
spec.description = "Dumps records to Groonga."
spec.email = ["hiroysato@gmail.com"]
spec.licenses = ["MIT"]
# TODO set this: spec.homepage = "https://github.com/hiroyuki-sato/embulk-output-groonga"
spec.files = `git ls-files`.split("\n") + Dir["classpath/*.jar"]
spec.test_files = spec.files.grep(%r{^(test|spec)/})
spec.require_paths = ["lib"]
spec.add_dependency 'groonga-command-parser', ['>= 0.1.4']
spec.add_dependency 'groonga-client', ['>= 0.1.3']
spec.add_development_dependency 'bundler', ['~> 1.0']
spec.add_development_dependency 'rake', ['>= 10.0']
end
|
Add a simple key retrieval benchmark. | #!/usr/bin/env ruby -wKU
require "benchmark"
require "thread_safe"
hash = {}
cache = ThreadSafe::Cache.new
10_000.times do |i|
hash[i] = i
cache[i] = i
end
TESTS = 40_000_000
Benchmark.bmbm do |results|
key = rand(10_000)
results.report('Hash#[]') do
TESTS.times { hash[key] }
end
results.report('Cache#[]') do
TESTS.times { cache[key] }
end
end | |
Use constants for these strings instead of freezing them. | require 'yaml'
# The following fixes a bug in Ruby where YAML dumping a subclass of Hash
# with instance variables does not actually dump those instance variables.
module Psych
module Visitors
class ToRuby
def revive_hash hash, o
o.children.each_slice(2) { |k,v|
key = accept(k)
if key == '<<'.freeze
case v
when Nodes::Alias
hash.merge! accept(v)
when Nodes::Sequence
accept(v).reverse_each do |value|
hash.merge! value
end
else
hash[key] = accept(v)
end
# We need to migrate all old YAML before we can remove this
#### Reapply the instance variables, see https://github.com/tenderlove/psych/issues/43
elsif key.to_s[0..5] == "__iv__".freeze
hash.instance_variable_set(key.to_s[6..-1], accept(v))
else
hash[key] = accept(v)
end
}
hash
end
end
end
end
| require 'yaml'
# The following fixes a bug in Ruby where YAML dumping a subclass of Hash
# with instance variables does not actually dump those instance variables.
module Psych
module Visitors
class ToRuby
SHOVEL = '<<'
IVAR_MARKER = '__iv__'
def revive_hash hash, o
o.children.each_slice(2) { |k,v|
key = accept(k)
if key == SHOVEL
case v
when Nodes::Alias
hash.merge! accept(v)
when Nodes::Sequence
accept(v).reverse_each do |value|
hash.merge! value
end
else
hash[key] = accept(v)
end
# We need to migrate all old YAML before we can remove this
#### Reapply the instance variables, see https://github.com/tenderlove/psych/issues/43
elsif key.to_s[0..5] == IVAR_MARKER
hash.instance_variable_set(key.to_s[6..-1], accept(v))
else
hash[key] = accept(v)
end
}
hash
end
end
end
end
|
Fix ActionView::MissingTemplate exception when rendering custom 404s | module Refinery
module Pages
module InstanceMethods
def error_404(exception=nil)
if (@page = ::Refinery::Page.where(:menu_match => "^/404$").includes(:parts, :slugs).first).present?
# render the application's custom 404 page with layout and meta.
render :template => '/pages/show', :format => 'html', :status => 404
else
super
end
end
protected
def find_pages_for_menu
# Compile the menu
@menu_pages = ::Refinery::Menu.new(::Refinery::Page.fast_menu)
end
def render(*args)
present(@page) unless admin? or @meta.present?
super
end
private
def store_current_location!
return super if admin?
session[:website_return_to] = main_app.url_for(@page.url) if @page.try(:present?)
end
end
end
end
| module Refinery
module Pages
module InstanceMethods
def error_404(exception=nil)
if (@page = ::Refinery::Page.where(:menu_match => "^/404$").includes(:parts, :slugs).first).present?
# render the application's custom 404 page with layout and meta.
render :template => '/refinery/pages/show', :format => 'html', :status => 404
else
super
end
end
protected
def find_pages_for_menu
# Compile the menu
@menu_pages = ::Refinery::Menu.new(::Refinery::Page.fast_menu)
end
def render(*args)
present(@page) unless admin? or @meta.present?
super
end
private
def store_current_location!
return super if admin?
session[:website_return_to] = main_app.url_for(@page.url) if @page.try(:present?)
end
end
end
end
|
Fix Question Error Messages to Be More Explicit | class QuestionsController < ApplicationController
before_action :set_question, only: [:show, :edit, :update, :destroy]
def index
@questions = Question.all
end
def show
end
def new
@question = Question.new
end
def create
@question = Question.new(question_params)
if @question.save
redirect_to @question, notice: 'Post was successfully created.'
else
render :new, notice: 'Post failed to create, try again.'
end
end
def update
if @question.update(question_params)
redirect_to @question, notice: 'Post was successfully updated.'
else
render :edit, notice: 'Post failed to update, try again.'
end
end
def destroy
@question.destroy
redirect_to questions_url, notice: 'Post was successfully destroyed.'
end
private
def set_question
@question = Question.find(params[:id])
end
def question_params
params.require(:question).permit(:title,:caption,:image_path)
end
end
| class QuestionsController < ApplicationController
before_action :set_question, only: [:show, :edit, :update, :destroy]
def index
@questions = Question.all
end
def show
end
def new
@question = Question.new
end
def create
@question = Question.new(question_params)
if @question.save
redirect_to @question, notice: 'Question was successfully created.'
else
render :new, notice: 'Question failed to create, try again.'
end
end
def update
if @question.update(question_params)
redirect_to @question, notice: 'Question was successfully updated.'
else
render :edit, notice: 'Question failed to update, try again.'
end
end
def destroy
@question.destroy
redirect_to questions_url, notice: 'Question was successfully destroyed.'
end
private
def set_question
@question = Question.find(params[:id])
end
def question_params
params.require(:question).permit(:title,:caption,:image_path)
end
end
|
Upgrade activemodel to 4.x series | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'atdis/version'
Gem::Specification.new do |spec|
spec.name = "atdis"
spec.version = Atdis::VERSION
spec.authors = ["Matthew Landauer"]
spec.email = ["matthew@openaustraliafoundation.org.au"]
spec.description = %q{A ruby interface to the application tracking data interchange specification (ATDIS) API}
spec.summary = spec.description
spec.homepage = "http://github.com/openaustralia/atdis"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_dependency "multi_json", "~> 1.7"
spec.add_dependency "rest-client"
spec.add_dependency "rgeo-geojson"
spec.add_dependency "activemodel", "~> 3"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'atdis/version'
Gem::Specification.new do |spec|
spec.name = "atdis"
spec.version = Atdis::VERSION
spec.authors = ["Matthew Landauer"]
spec.email = ["matthew@openaustraliafoundation.org.au"]
spec.description = %q{A ruby interface to the application tracking data interchange specification (ATDIS) API}
spec.summary = spec.description
spec.homepage = "http://github.com/openaustralia/atdis"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_dependency "multi_json", "~> 1.7"
spec.add_dependency "rest-client"
spec.add_dependency "rgeo-geojson"
spec.add_dependency "activemodel", "~> 4"
end
|
Refactor extended hook to be simpler | # encoding: utf-8
module Axiom
module Types
# Add a minimum and maximum value constraint to a type
module ValueComparable
# Hook called when module is extended
#
# Add #minimum and #maximum DSL methods to descendant.
#
# @param [Class<Axiom::Types::Type>] descendant
#
# @return [undefined]
#
# @api private
def self.extended(descendant)
super
descendant.class_eval do
accept_options :minimum, :maximum
end
end
# Finalize by setting up a value range constraint
#
# @return [Axiom::Types::ValueComparable]
#
# @api private
def finalize
return self if frozen?
has_value_within_range
super
end
private
# Add a constraint for a value within a range
#
# @return [undefined]
#
# @todo freeze the minimum and maximum
#
# @api private
def has_value_within_range
range = minimum..maximum
constraint(range.method(:cover?))
end
end # module ValueComparable
end # module Types
end # module Axiom
| # encoding: utf-8
module Axiom
module Types
# Add a minimum and maximum value constraint to a type
module ValueComparable
# Hook called when module is extended
#
# Add #minimum and #maximum DSL methods to descendant.
#
# @param [Class<Axiom::Types::Type>] descendant
#
# @return [undefined]
#
# @api private
def self.extended(descendant)
super
descendant.accept_options :minimum, :maximum
end
# Finalize by setting up a value range constraint
#
# @return [Axiom::Types::ValueComparable]
#
# @api private
def finalize
return self if frozen?
has_value_within_range
super
end
private
# Add a constraint for a value within a range
#
# @return [undefined]
#
# @todo freeze the minimum and maximum
#
# @api private
def has_value_within_range
range = minimum..maximum
constraint(range.method(:cover?))
end
end # module ValueComparable
end # module Types
end # module Axiom
|
Make sure state is cloned with an element |
module Bio
module BioAlignment
# Simple element that can be queried
class Element
GAP = '-'
UNDEFINED = 'X'
include State
def initialize c
@c = c
@c.freeze
end
def gap?
@c == GAP
end
def undefined?
@c == 'X'
end
def to_s
@c
end
def == other
to_s == other.to_s
end
end
# Elements is a container for Element sequences.
#
class Elements
include Enumerable
include State
attr_reader :id, :seq
def initialize id, seq
@id = id
@id.freeze
@seq = []
if seq.kind_of?(Elements)
@seq = seq.clone
elsif seq.kind_of?(String)
seq.each_char do |c|
@seq << Element.new(c)
end
else
seq.each do |s|
@seq << Element.new(s)
end
end
end
def [] index
@seq[index]
end
def length
@seq.length
end
def each
@seq.each { |e| yield e }
end
def to_s
@seq.map{|e| e.to_s }.join("")
end
def << element
@seq << element
end
def empty_copy
Elements.new(@id,"")
end
def clone
copy = Elements.new(@id,"")
@seq.each do |e|
copy << e.dup
end
copy
end
end
end
end
|
module Bio
module BioAlignment
# Simple element that can be queried
class Element
GAP = '-'
UNDEFINED = 'X'
include State
def initialize c
@c = c
@c.freeze
end
def gap?
@c == GAP
end
def undefined?
@c == 'X'
end
def to_s
@c
end
def == other
to_s == other.to_s
end
def clone
e = self.dup
if e.state != nil
e.state = e.state.clone
end
e
end
end
# Elements is a container for Element sequences.
#
class Elements
include Enumerable
include State
attr_reader :id, :seq
def initialize id, seq
@id = id
@id.freeze
@seq = []
if seq.kind_of?(Elements)
@seq = seq.clone
elsif seq.kind_of?(String)
seq.each_char do |c|
@seq << Element.new(c)
end
else
seq.each do |s|
@seq << Element.new(s)
end
end
end
def [] index
@seq[index]
end
def length
@seq.length
end
def each
@seq.each { |e| yield e }
end
def to_s
@seq.map{|e| e.to_s }.join("")
end
def << element
@seq << element
end
def empty_copy
Elements.new(@id,"")
end
def clone
copy = Elements.new(@id,"")
@seq.each do |e|
copy << e.clone
end
copy
end
end
end
end
|
Handle nil variable in check_passes. This wouldn't have compiled in Scala | class Card < ActiveRecord::Base
attr_accessible :mirror_id, :pass_id
belongs_to :pass
before_destroy :remove_from_timeline
def remove_from_timeline
HTTParty.delete('https://www.googleapis.com/mirror/v1/timeline/'+self.mirror_id, headers: { 'Content-Type' => 'application/json', 'Authorization' => 'Bearer '+self.pass.user.access_token })
end
end
| class Card < ActiveRecord::Base
attr_accessible :mirror_id, :pass_id
belongs_to :pass
before_destroy :remove_from_timeline
def remove_from_timeline
HTTParty.delete('https://www.googleapis.com/mirror/v1/timeline/'+self.mirror_id.to_s, headers: { 'Content-Type' => 'application/json', 'Authorization' => 'Bearer '+self.pass.user.access_token })
end
end
|
Use images to get registry pods instead of [internal-]services | class ContainerImageRegistry < ApplicationRecord
belongs_to :ext_management_system, :foreign_key => "ems_id"
has_many :container_images, :dependent => :nullify
has_many :containers, :through => :container_images
has_many :container_services
has_many :container_groups, :through => :container_services
acts_as_miq_taggable
virtual_column :full_name, :type => :string
def full_name
port.present? ? "#{host}:#{port}" : host
end
end
| class ContainerImageRegistry < ApplicationRecord
belongs_to :ext_management_system, :foreign_key => "ems_id"
has_many :container_images, :dependent => :nullify
has_many :containers, :through => :container_images
has_many :container_services
has_many :container_groups, :through => :container_images
acts_as_miq_taggable
virtual_column :full_name, :type => :string
def full_name
port.present? ? "#{host}:#{port}" : host
end
end
|
Add comment for include module after function definitions. | module Embeddable
class OpenResponse < ActiveRecord::Base
include Embeddable
attr_accessible :name, :prompt, :is_prediction, :give_prediction_feedback, :prediction_feedback
# PageItem instances are join models, so if the embeddable is gone the join should go too.
has_many :page_items, :as => :embeddable, :dependent => :destroy
has_many :interactive_pages, :through => :page_items
has_many :answers,
:class_name => 'Embeddable::OpenResponseAnswer',
:foreign_key => 'open_response_id'
default_value_for :prompt, "why does ..."
def to_hash
{
name: name,
prompt: prompt,
is_prediction: is_prediction,
give_prediction_feedback: give_prediction_feedback,
prediction_feedback: prediction_feedback
}
end
def duplicate
return Embeddable::OpenResponse.new(self.to_hash)
end
def self.name_as_param
:embeddable_open_response
end
def self.display_partial
:open_response
end
def self.human_description
"Multiple choice question"
end
def export
return self.as_json(only:[:name,
:prompt,
:is_prediction,
:give_prediction_feedback,
:prediction_feedback])
end
def self.import (import_hash)
return self.new(import_hash)
end
include CRater::SettingsProviderFunctionality
end
end
| module Embeddable
class OpenResponse < ActiveRecord::Base
include Embeddable
attr_accessible :name, :prompt, :is_prediction, :give_prediction_feedback, :prediction_feedback
# PageItem instances are join models, so if the embeddable is gone the join should go too.
has_many :page_items, :as => :embeddable, :dependent => :destroy
has_many :interactive_pages, :through => :page_items
has_many :answers,
:class_name => 'Embeddable::OpenResponseAnswer',
:foreign_key => 'open_response_id'
default_value_for :prompt, "why does ..."
def to_hash
{
name: name,
prompt: prompt,
is_prediction: is_prediction,
give_prediction_feedback: give_prediction_feedback,
prediction_feedback: prediction_feedback
}
end
def duplicate
return Embeddable::OpenResponse.new(self.to_hash)
end
def self.name_as_param
:embeddable_open_response
end
def self.display_partial
:open_response
end
def self.human_description
"Multiple choice question"
end
def export
return self.as_json(only:[:name,
:prompt,
:is_prediction,
:give_prediction_feedback,
:prediction_feedback])
end
def self.import (import_hash)
return self.new(import_hash)
end
# SettingsProviderFunctionality extends the functionality of duplicate, export and import using alias_method_chain. So these methods needs to be visible to the SettingsProviderFunctionality.
include CRater::SettingsProviderFunctionality
end
end
|
Use map + inject for average degree | module Zxcvbn
module Math
def bruteforce_cardinality(password)
is_type_of = {}
password.each_byte do |ordinal|
case ordinal
when (48..57)
is_type_of['digits'] = true
when (65..90)
is_type_of['upper'] = true
when (97..122)
is_type_of['lower'] = true
else
is_type_of['symbols'] = true
end
end
cardinality = 0
cardinality += 10 if is_type_of['digits']
cardinality += 26 if is_type_of['upper']
cardinality += 26 if is_type_of['lower']
cardinality += 33 if is_type_of['symbols']
cardinality
end
def lg(n)
::Math.log(n, 2)
end
def nCk(n, k)
return 0 if k > n
return 1 if k == 0
r = 1
(1..k).each do |d|
r = r * n
r = r / d
n -= 1
end
r
end
def average_degree_for_graph(graph_name)
graph = Zxcvbn::ADJACENCY_GRAPHS[graph_name]
sum = 0.0
graph.each do |key, neighbors|
sum += neighbors.compact.length
end
sum / graph.keys.length
end
def starting_positions_for_graph(graph_name)
Zxcvbn::ADJACENCY_GRAPHS[graph_name].length
end
end
end
| module Zxcvbn
module Math
def bruteforce_cardinality(password)
is_type_of = {}
password.each_byte do |ordinal|
case ordinal
when (48..57)
is_type_of['digits'] = true
when (65..90)
is_type_of['upper'] = true
when (97..122)
is_type_of['lower'] = true
else
is_type_of['symbols'] = true
end
end
cardinality = 0
cardinality += 10 if is_type_of['digits']
cardinality += 26 if is_type_of['upper']
cardinality += 26 if is_type_of['lower']
cardinality += 33 if is_type_of['symbols']
cardinality
end
def lg(n)
::Math.log(n, 2)
end
def nCk(n, k)
return 0 if k > n
return 1 if k == 0
r = 1
(1..k).each do |d|
r = r * n
r = r / d
n -= 1
end
r
end
def average_degree_for_graph(graph_name)
graph = Zxcvbn::ADJACENCY_GRAPHS[graph_name]
sum = graph.map {|_, neighbors| neighbors.compact.length }
.inject(0.0, :+)
sum / graph.keys.length
end
def starting_positions_for_graph(graph_name)
Zxcvbn::ADJACENCY_GRAPHS[graph_name].length
end
end
end
|
Add SecuritySensor to list of supported devices | class MiOS::Device::SecuritySensor < MiOS::Device::Generic
ServiceId = "urn:micasaverde-com:serviceId:SecuritySensor"
def armed
@attributes['armed'].to_i == 1
end
alias_method :armed?, :armed
def tripped
@attributes['tripped'].to_i == 1
end
alias_method :tripped?, :tripped
def last_trip
Time.at(@attributes['lasttrip'].to_i)
end
# Reload the status of this device
def reload
self.class.get("/data_request?id=status&output_format=json&DeviceNum=#{id}")["Device_Num_#{id}"]["states"].each do |h|
["armed", "tripped"].each do |var|
if h["service"] == ServiceId and h["variable"] == var.capitalize
@attributes[var] = h["value"]
end
end
end
self
end
end | |
Fix description for be_valid matcher | module RSpec::Rails::Matchers
module Validation
class IsValid
include RSpec::Matchers::BaseMatcher
def initialize(scope)
@scope = scope
end
def matches?(actual)
@actual = actual
@actual.valid?
end
# @api private
def failure_message_for_should
@actual.errors.full_messages
end
# @api private
def failure_message_for_should_not
"expected it to be invalid, but it was valid"
end
end
# Calls valid?
#
# @example
#
# model.should be_valid
def be_valid
IsValid.new(self)
end
end
end
| module RSpec::Rails::Matchers
module Validation
class IsValid
include RSpec::Matchers::BaseMatcher
def initialize(scope)
@scope = scope
end
def matches?(actual)
@actual = actual
@actual.valid?
end
def description
"be valid"
end
# @api private
def failure_message_for_should
@actual.errors.full_messages
end
# @api private
def failure_message_for_should_not
"expected it to be invalid, but it was valid"
end
end
# Calls valid?
#
# @example
#
# model.should be_valid
def be_valid
IsValid.new(self)
end
end
end
|
Remove non existent rake task load | # frozen_string_literal: true
module Release
module Notes
class Railtie < Rails::Railtie
rake_tasks do
load "tasks/update_release_notes.rake"
end
generators do
require "generators/release/notes/install/install_generator.rb"
end
end
end
end
| # frozen_string_literal: true
module Release
module Notes
class Railtie < Rails::Railtie
generators do
require "generators/release/notes/install/install_generator.rb"
end
end
end
end
|
Update for compatibility with RSpec 3. | shared_context "a controller spec", controller: true do
include TextHelpers::Translation
def translation_scope
controller_name = described_class.name.sub(/Controller\z/, '').underscore
"controllers.#{controller_name}"
end
end
shared_context "a mailer spec", mailer: true do
include TextHelpers::Translation
def translation_scope
mailer_name = described_class.name.sub(/Mailer\z/, '').underscore
"mailers.#{mailer_name}"
end
end
shared_context "a view spec", view: true do
include TextHelpers::Translation
def translation_scope
matcher = /(?<path>.*)\/_?(?<view>[^\/.]+)(?<extension>\.html\.haml)?/
info = matcher.match(example.metadata[:full_description])
path = info[:path].gsub('/', '.')
"views.#{path}.#{info[:view]}"
end
end
| shared_context "a controller spec", controller: true do
include TextHelpers::Translation
def translation_scope
controller_name = described_class.name.sub(/Controller\z/, '').underscore
"controllers.#{controller_name}"
end
end
shared_context "a mailer spec", mailer: true do
include TextHelpers::Translation
def translation_scope
mailer_name = described_class.name.sub(/Mailer\z/, '').underscore
"mailers.#{mailer_name}"
end
end
shared_context "a view spec", view: true do
include TextHelpers::Translation
def translation_scope
matcher = /(?<path>.*)\/_?(?<view>[^\/.]+)(?<extension>\.html\.haml)?/
info = matcher.match(_default_file_to_render)
path = info[:path].gsub('/', '.')
"views.#{path}.#{info[:view]}"
end
end
|
Rename MongoDB database used for testing | SPEC_DIR = File.dirname(__FILE__)
lib_path = File.expand_path("#{SPEC_DIR}/../lib")
$LOAD_PATH.unshift lib_path unless $LOAD_PATH.include?(lib_path)
require 'rubygems'
require 'bundler/setup'
require 'schreihals'
Schreihals.mongo_uri = 'mongodb://localhost/schreihals_test'
require 'awesome_print'
require 'rack/test'
require 'rspec-html-matchers'
require 'database_cleaner'
require 'factory_girl'
require File.expand_path("../factories.rb", __FILE__)
require 'timecop'
Timecop.freeze
set :environment, :test
RSpec.configure do |config|
config.before(:suite) do
DatabaseCleaner[:mongoid].strategy = :truncation
end
config.before(:each) do
DatabaseCleaner[:mongoid].start
end
config.after(:each) do
DatabaseCleaner[:mongoid].clean
end
end
| SPEC_DIR = File.dirname(__FILE__)
lib_path = File.expand_path("#{SPEC_DIR}/../lib")
$LOAD_PATH.unshift lib_path unless $LOAD_PATH.include?(lib_path)
require 'rubygems'
require 'bundler/setup'
require 'schreihals'
Schreihals.mongo_uri = 'mongodb://localhost/_schreihals_test'
require 'awesome_print'
require 'rack/test'
require 'rspec-html-matchers'
require 'database_cleaner'
require 'factory_girl'
require File.expand_path("../factories.rb", __FILE__)
require 'timecop'
Timecop.freeze
set :environment, :test
RSpec.configure do |config|
config.before(:suite) do
DatabaseCleaner[:mongoid].strategy = :truncation
end
config.before(:each) do
DatabaseCleaner[:mongoid].start
end
config.after(:each) do
DatabaseCleaner[:mongoid].clean
end
end
|
Add spec to check json and yaml file syntax | require 'rails_helper'
describe 'json files' do
`git ls-files *.json`.each_line do |json_file|
json_file.chomp!
describe(json_file) do
it 'is valid json' do
File.open(json_file) do |f|
JSON.parse(f.read)
end
end
end
end
end
describe 'yaml files' do
`git ls-files *.yml`.each_line do |yaml_file|
yaml_file.chomp!
describe(yaml_file) do
it 'is valid yaml' do
YAML.load_file(yaml_file)
end
end
end
end
| |
Call correct methods in the AxiomsController. | #
# Lists axioms of an ontology
#
class AxiomsController < InheritedResources::Base
belongs_to :ontology
actions :index
has_pagination
respond_to :html, only: %i(index)
before_filter :check_read_permissions
protected
def check_read_permissions
authorize! :show, parent.repository
end
def collection
@collection ||=
if display_all?
axioms =
if logically_translated?
parent.all_axioms
else
parent.translated_axioms
end
Kaminari.paginate_array(axioms).page(params[:page])
else
super
end
end
def logically_translated?
parent.contains_logic_translations?
end
helper_method :logically_translated?
end
| #
# Lists axioms of an ontology
#
class AxiomsController < InheritedResources::Base
belongs_to :ontology
actions :index
has_pagination
respond_to :html, only: %i(index)
before_filter :check_read_permissions
protected
def check_read_permissions
authorize! :show, parent.repository
end
def collection
@collection ||=
if display_all?
axioms =
if logically_translated?
parent.axioms
else
parent.translated_axioms
end
Kaminari.paginate_array(axioms).page(params[:page])
else
Kaminari.paginate_array(parent.axioms.original).page(params[:page])
end
end
def logically_translated?
parent.contains_logic_translations?
end
helper_method :logically_translated?
end
|
Fix URL builder for reorder route | module ActiveAdmin
module Reorderable
module TableMethods
def reorder_column
column '', :class => 'reorder-handle-col' do |resource|
reorder_handle_for(resource)
end
end
private
def reorder_handle_for(resource)
url = url_for([:reorder, active_admin_namespace.name, resource])
span(reorder_handle_content, :class => 'reorder-handle', 'data-reorder-url' => url)
end
def reorder_handle_content
'≡≡'.html_safe
end
end
::ActiveAdmin::Views::TableFor.send(:include, TableMethods)
end
end
| module ActiveAdmin
module Reorderable
module TableMethods
def reorder_column
column '', :class => 'reorder-handle-col' do |resource|
reorder_handle_for(resource)
end
end
private
def reorder_handle_for(resource)
url = [active_admin_config.route_instance_path(resource), :reorder].join('/')
span(reorder_handle_content, :class => 'reorder-handle', 'data-reorder-url' => url)
end
def reorder_handle_content
'≡≡'.html_safe
end
end
::ActiveAdmin::Views::TableFor.send(:include, TableMethods)
end
end
|
Update strings by using ruby script | #!/usr/bin/env ruby
PROJECT_PATH = "./Hodor"
STRINGS_PATH = "./zh-Hans.lproj/Localizable.strings"
def klang_strings
keys = []
Dir.entries(".").each do |path|
mfiles = File.join(path, "*.m")
Dir.glob(mfiles) do |item|
File.read(item).scan(/kLang\(@"([^"]*)/).each do |key|
keys.push(key[0])
end
end
end
keys.uniq()
end
def decode_str_file(line)
match = /^\s*((?:"(?:[^"\\]|\\.)+")|(?:[^"\s=]+))\s*=\s*"((?:[^"\\]|\\.)*)"/.match(line)
if match
key = match[1]
key = key[1..-2] if key[0] == '"' and key[-1] == '"'
key.gsub!('\\"', '"')
value = match[2]
value.gsub!('\\"', '"')
return key, value
else
return nil
end
end
def str_to_hash(file)
str_list = Hash.new
File.open(file, "r") do |f|
f.each_line do |line|
arr = decode_str_file(line)
if arr
str_list[arr[0]] = arr[1]
end
end
str_list
end
end
def update_strings_file
content = File.read(STRINGS_PATH) + "\n"
klang_strings.each do |str|
unless str_to_hash(STRINGS_PATH).keys.include? str
new_str = '"' + str + '" = "";'
content += new_str
end
end
File.write(STRINGS_PATH, content)
p "Update strings successfully ✨ ✨ ✨"
end
update_strings_file()
| |
Stop using README.md as the gem's description | require_relative './util'
# :nodoc:
module Builderator
VERSION = Util.source_path('VERSION').read rescue '0.0.1'
DESCRIPTION = Util.source_path('README.md').read rescue 'README.md not found!'
end
| require_relative './util'
# :nodoc:
module Builderator
VERSION = Util.source_path('VERSION').read rescue '0.0.1'
DESCRIPTION = 'Builderator automates many of the common steps required to build VMs '\
'and images with Chef. It provides a common configuration layer for '\
'Chef, Berkshelf, Vagrant, and Packer, and tasks to orchestrate the '\
'usage of each. https://github.com/rapid7/builderator'
end
|
Add a test expecting moves to an occupied square will be rejected | require 'spec_helper'
describe TicTacToe::Game do
let(:console) { mock_console }
let(:board) { mock_board }
let(:game) { TicTacToe::Game.new(console, board) }
def mock_console
double(:console).tap do |console|
allow(console).to receive(:gets).and_return("1")
end
end
def mock_board
double(:board).tap do |board|
allow(board).to receive(:move)
end
end
it 'can start a game' do
allow(console).to receive(:printf)
game.start
end
describe 'when playing' do
it 'changes the active player after every move' do
expect { game.do_turn }.to change { game.to_play }
expect { game.do_turn }.to change { game.to_play }
end
it 'changes the board marks based on user input' do
expect(board).to receive(:move).with(anything, 1)
game.do_turn
end
end
end
| require 'spec_helper'
describe TicTacToe::Game do
let(:console) { mock_console }
let(:board) { mock_board }
let(:game) { TicTacToe::Game.new(console, board) }
def mock_console
double(:console).tap do |console|
allow(console).to receive(:gets).and_return("1")
end
end
def mock_board
double(:board).tap do |board|
allow(board).to receive(:move)
allow(board).to receive(:legal?)
end
end
it 'can start a game' do
allow(console).to receive(:printf)
game.start
end
describe 'when playing' do
it 'changes the active player after every move' do
expect { game.do_turn }.to change { game.to_play }
expect { game.do_turn }.to change { game.to_play }
end
it 'changes the board marks based on user input' do
allow(board).to receive(:legal?).and_return(true)
expect(board).to receive(:move).with(anything, 1)
game.do_turn
end
it "Doesn't allow the same move twice." do
allow(console).to receive(:gets).and_return("1", "1")
allow(board).to receive(:legal?).and_return(true, false)
expect(board).to receive(:move).with(anything, 1)
game.do_turn
game.do_turn
end
end
end
|
Add ability to parse object paths as well as rails style routes. | require 'loaf/configuration'
module Loaf
module Helpers
class_eval do
define_method :config do |options|
Loaf.config
end
end
# Adds breadcrumbs in a view
def add_breadcrumb(name, url=nil)
_breadcrumbs.push(name, url)
end
def breadcrumbs(options={}, &block)
#builder = Loaf::Builder.new(options)
options = config.merge(options)
_breadcrumbs.each do |crumb|
name = crumb.name ? truncate(crumb.name.upcase, :length => options[:crumb_length]) : ''
url = send(crumb.url)
styles = ( request.request_uri.split('?')[0] == url ? "#{options[:style_classes]}" : '' )
block.call(name, url, styles)
end
end
end # Helpers
end # Loaf
| require 'loaf/configuration'
module Loaf
module Helpers
class_eval do
define_method :config do |options|
Loaf.config
end
end
# Adds breadcrumbs in a view
def add_breadcrumb(name, url=nil)
_breadcrumbs.push(name, url)
end
def breadcrumbs(options={}, &block)
#builder = Loaf::Builder.new(options)
options = config.merge(options)
_breadcrumbs.each do |crumb|
name = if crumb.name
formatted = options[:capitalize] ? crumb.name.capitalize : crumb.name
truncate(formatted, :length => options[:crumb_length])
else
'[name-error]'
end
url = url_for _process_url_for(crumb.url)
styles = ( request.request_uri.split('?')[0] == url ? "#{options[:style_classes]}" : '' )
block.call(name, url, styles)
end
end
private
def _process_url_for(url)
if url.is_a?(String) || url.is_a?(Symbol)
return send url
else
return url
end
end
end # Helpers
end # Loaf
|
Switch platform detection to shell out to uname -p -- Config::Config['target'] lies on Intel with Apple's Universal ruby. | require 'mkmf'
require 'rbconfig'
def symlink(old, new)
if File.exists?(new) && File.symlink?(new)
File.unlink(new)
end
File.symlink(old, new)
end
$CFLAGS += " -D_LONGLONG_TYPE -g"
have_library("dtrace", "dtrace_open")
# Update machine-dependent symlinks in the source, based on $Config::CONFIG
cpu = Config::CONFIG['target_cpu']
os = Config::CONFIG['target_os']
cpu.gsub! /^i[4-6]86/, 'i386'
os.gsub! /[0-9.]+$/, ''
dir = "#{cpu}-#{os}"
symlink "#{dir}/dtrace_probe.c", "dtrace_probe.c"
# Create makefile in the usual way
create_makefile("dtrace_api")
| require 'mkmf'
require 'rbconfig'
def symlink(old, new)
begin
File.symlink(old, new)
rescue Errno::EEXIST
File.unlink(new)
retry
end
end
$CFLAGS += " -D_LONGLONG_TYPE -g"
have_library("dtrace", "dtrace_open")
# Update machine-dependent symlinks in the source, based on $Config::CONFIG and `uname -p`
os = Config::CONFIG['target_os']
os.gsub! /[0-9.]+$/, ''
# On OSX, this is "powerpc", even on Intel...
#cpu = Config::CONFIG['target_cpu']
cpu = `uname -p`.chomp
dir = "#{cpu}-#{os}"
symlink "#{dir}/dtrace_probe.c", "dtrace_probe.c"
# Create makefile in the usual way
create_makefile("dtrace_api")
|
Revert tabs to spaces again per style | #
# Cookbook Name:: dse
# Recipe:: opscenter
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Set up the datastax repo in yum or apt depending on the OS
include_recipe 'dse::_repo'
package 'opscenter' do
version node['opscenter']['version']
action :install
case node['platform']
when 'ubuntu', 'debian'
options '-o Dpkg::Options::="--force-confold"'
end
end
package 'python-ldap' do
action :install
only_if { 'LDAP'.eql?(node['opscenter']['authentication_method']) }
end
template '/etc/opscenter/opscenterd.conf' do
source 'opscenterd.conf.erb'
mode '644'
owner 'root'
group 'root'
end
service 'opscenterd' do
action [:enable, :start]
pattern 'start_opscenter.py'
subscribes :restart, 'template[/etc/opscenter/opscenterd.conf]'
end
| #
# Cookbook Name:: dse
# Recipe:: opscenter
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Set up the datastax repo in yum or apt depending on the OS
include_recipe 'dse::_repo'
package 'opscenter' do
version node['opscenter']['version']
action :install
case node['platform']
when 'ubuntu', 'debian'
options '-o Dpkg::Options::="--force-confold"'
end
end
package 'python-ldap' do
action :install
only_if { 'LDAP'.eql?(node['opscenter']['authentication_method']) }
end
template '/etc/opscenter/opscenterd.conf' do
source 'opscenterd.conf.erb'
mode '644'
owner 'root'
group 'root'
end
service 'opscenterd' do
action [:enable, :start]
pattern 'start_opscenter.py'
subscribes :restart, 'template[/etc/opscenter/opscenterd.conf]'
end
|
Add Texture Packer Tileset example | require 'json'
module Gosu
module TexturePacker
class Tileset
def self.load_json(window, json)
self.new(window, json)
end
def initialize(window, json)
@window = window
@json = JSON.parse(File.read(json))
@source_dir = File.dirname(json)
@main_image = Gosu::Image.new(@window, image_file, true)
@tile_cache = {}
end
def frame_list
frames.keys
end
def frame(name)
tile = @tile_cache[name]
unless tile
data = frames[name]
f = data['frame']
tile = @main_image.subimage(f['x'], f['y'], f['w'], f['h'])
@tile_cache[name] = tile
end
tile
end
private
def image_file
File.join(@source_dir, meta['image'])
end
def meta
@json['meta']
end
def frames
@json['frames']
end
end
end
end
| |
Add migration file to change a column type | class ChangeColumnTypeUserIdOnJobApplications < ActiveRecord::Migration
def up
integer = 'integer USING CAST(user_id AS integer)'
change_column :job_applications, :user_id, integer
end
def down
change_column :job_applications, :user_id, :string
end
end
| |
Fix Diaspora::Camo.from_markdown with frozen strings | # frozen_string_literal: true
# implicitly requires OpenSSL
module Diaspora
module Camo
def self.from_markdown(markdown_text)
return unless markdown_text
markdown_text.gsub!(/(!\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/m) do |link|
link.gsub($4, self.image_url($4))
end
markdown_text.gsub(/src=(['"])(.+?)\1/m) do |link|
link.gsub($2, self.image_url($2))
end
end
def self.image_url(url)
return unless url
return url unless self.url_eligible?(url)
digest = OpenSSL::HMAC.hexdigest(
OpenSSL::Digest.new('sha1'),
AppConfig.privacy.camo.key,
url
)
encoded_url = url.to_enum(:each_byte).map {|byte| '%02x' % byte}.join
File.join(AppConfig.privacy.camo.root, digest, encoded_url)
end
def self.url_eligible?(url)
return false unless url.start_with?('http', '//')
return false if url.start_with?(AppConfig.environment.url.to_s,
AppConfig.privacy.camo.root.to_s)
true
end
end
end
| # frozen_string_literal: true
# implicitly requires OpenSSL
module Diaspora
module Camo
def self.from_markdown(markdown_text)
return unless markdown_text
markdown_text = markdown_text.gsub(/(!\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/m) do |link|
link.gsub($4, self.image_url($4))
end
markdown_text.gsub(/src=(['"])(.+?)\1/m) do |link|
link.gsub($2, self.image_url($2))
end
end
def self.image_url(url)
return unless url
return url unless self.url_eligible?(url)
digest = OpenSSL::HMAC.hexdigest(
OpenSSL::Digest.new('sha1'),
AppConfig.privacy.camo.key,
url
)
encoded_url = url.to_enum(:each_byte).map {|byte| '%02x' % byte}.join
File.join(AppConfig.privacy.camo.root, digest, encoded_url)
end
def self.url_eligible?(url)
return false unless url.start_with?('http', '//')
return false if url.start_with?(AppConfig.environment.url.to_s,
AppConfig.privacy.camo.root.to_s)
true
end
end
end
|
Use a constant to keep track of the default constraint (>= 0.0.0) | module Solve
require_relative 'solve/artifact'
require_relative 'solve/constraint'
require_relative 'solve/demand'
require_relative 'solve/dependency'
require_relative 'solve/gem_version'
require_relative 'solve/errors'
require_relative 'solve/graph'
require_relative 'solve/solver'
require_relative 'solve/version'
class << self
# @return [Solve::Formatter]
attr_reader :tracer
# A quick solve. Given the "world" as we know it (the graph) and a list of
# requirements (demands) which must be met. Return me the best solution of
# artifacts and verisons that I should use.
#
# If a ui object is passed in, the resolution will be traced
#
# @param [Solve::Graph] graph
# @param [Array<Solve::Demand>, Array<String, String>] demands
#
# @option options [#say] :ui (nil)
# a ui object for output
# @option options [Boolean] :sorted (false)
# should the output be a sorted list rather than a Hash
#
# @raise [NoSolutionError]
#
# @return [Hash]
def it!(graph, demands, options = {})
Solver.new(graph, demands, options[:ui]).resolve(options)
end
end
end
| module Solve
require_relative 'solve/artifact'
require_relative 'solve/constraint'
require_relative 'solve/demand'
require_relative 'solve/dependency'
require_relative 'solve/gem_version'
require_relative 'solve/errors'
require_relative 'solve/graph'
require_relative 'solve/solver'
require_relative 'solve/version'
# The default constraint.
#
# @return [String]
DEFAULT_CONSTRAINT = Constraint.new('>= 0.0.0').freeze
class << self
# @return [Solve::Formatter]
attr_reader :tracer
# A quick solve. Given the "world" as we know it (the graph) and a list of
# requirements (demands) which must be met. Return me the best solution of
# artifacts and verisons that I should use.
#
# If a ui object is passed in, the resolution will be traced
#
# @param [Solve::Graph] graph
# @param [Array<Solve::Demand>, Array<String, String>] demands
#
# @option options [#say] :ui (nil)
# a ui object for output
# @option options [Boolean] :sorted (false)
# should the output be a sorted list rather than a Hash
#
# @raise [NoSolutionError]
#
# @return [Hash]
def it!(graph, demands, options = {})
Solver.new(graph, demands, options[:ui]).resolve(options)
end
end
end
|
Add forgotten class WP25::Option of wordpress convertor | module WP25
class Option < ActiveRecord::Base
set_table_name 'wp_options'
set_primary_key 'option_id'
establish_connection configurations['wp25']
def self.prefix=(prefix)
set_table_name "#{prefix}_options"
end
end
end
| |
Add specs for Gitlab::Plugin | require 'spec_helper'
describe Gitlab::Plugin do
describe '.execute' do
let(:data) { Gitlab::DataBuilder::Push::SAMPLE_DATA }
let(:plugin) { Rails.root.join('plugins', 'test.rb') }
let(:tmp_file) { Tempfile.new('plugin-dump').path }
before do
File.write(plugin, plugin_source)
File.chmod(0o777, plugin)
end
after do
FileUtils.rm(plugin)
FileUtils.rm(tmp_file)
end
subject { described_class.execute(plugin.to_s, data) }
it { is_expected.to be true }
it 'ensures plugin received data via stdin' do
subject
expect(File.read(tmp_file)).to eq(data.to_json)
end
end
private
def plugin_source
<<-EOS
#!/usr/bin/env ruby
x = STDIN.read
File.write('#{tmp_file}', x)
EOS
end
end
| |
Handle case where a Reviewer also does transcription | class PagesController < ApplicationController
before_action :authenticate_user!
def checkout
@page = Page.not_checked_out.first
current_user.checkout(@page)
redirect_to edit_page_path(@page)
end
def start_review
@page = Page.pending_review.first
current_user.start_review(@page)
redirect_to edit_page_path(@page)
end
def edit
@page = Page.find(params[:id])
if current_user.is_reviewer? || current_user.is_admin? || @page.transcriber == current_user
else
permission_denied
end
end
def update
# TODO: Handle case where reviewer do also transcription
@page = Page.find(params[:id])
@page.content = params[:page][:content]
if current_user.is_reviewer?
@page.reviewed_at = Time.now
else
@page.submitted_at = Time.now
end
@page.save
flash[:notice] = "Merci!"
redirect_to root_path
end
end
| class PagesController < ApplicationController
before_action :authenticate_user!
def checkout
@page = Page.not_checked_out.first
current_user.checkout(@page)
redirect_to edit_page_path(@page)
end
def start_review
@page = Page.pending_review.first
current_user.start_review(@page)
redirect_to edit_page_path(@page)
end
def edit
@page = Page.find(params[:id])
if current_user.is_reviewer? || current_user.is_admin? || @page.transcriber == current_user
else
permission_denied
end
end
def update
@page = Page.find(params[:id])
@page.content = params[:page][:content]
if @page.reviewer_id == current_user.id
@page.reviewed_at = Time.now
elsif @page.transcriber_id == current_user.id
@page.submitted_at = Time.now
end
@page.save
flash[:notice] = "Merci!"
redirect_to root_path
end
end
|
Use CSS-only piecharts in the decorator for infra datastores | class StorageDecorator < MiqDecorator
def self.fonticon
'fa fa-database'
end
def fileicon
percent = v_free_space_percent_of_total == 100 ? 20 : ((v_free_space_percent_of_total + 2) / 5.25).round # val is the percentage value of free space
"100/piecharts/datastore/#{percent}.png"
end
def quadicon
{
:top_left => {
:fileicon => store_type_icon,
:tooltip => store_type.to_s
},
:top_right => {:text => v_total_vms},
:bottom_left => {:text => v_total_hosts},
:bottom_right => {
:fileicon => fileicon
}
}
end
def single_quad
{
:fileicon => fileicon
}
end
private
def store_type_icon
"100/storagetype-#{store_type.nil? ? "unknown" : ERB::Util.h(store_type.to_s.downcase)}.png"
end
end
| class StorageDecorator < MiqDecorator
def self.fonticon
'fa fa-database'
end
def quadicon
{
:top_left => {
:fileicon => store_type_icon,
:tooltip => store_type.to_s
},
:top_right => {:text => v_total_vms},
:bottom_left => {:text => v_total_hosts},
:bottom_right => {
:piechart => percent
}
}
end
def single_quad
{
:piechart => percent
}
end
private
def percent
20 - (v_free_space_percent_of_total == 100 ? 20 : ((v_free_space_percent_of_total + 2) / 5.25).round)
end
def store_type_icon
"100/storagetype-#{store_type.nil? ? "unknown" : ERB::Util.h(store_type.to_s.downcase)}.png"
end
end
|
Complete Day 14 - Reindeer Racing | require 'pp'
input = File.read 'input.txt'
speeds = {}
input.each_line do |line|
next if line =~ /^\s+$/
name, speed, run_time, rest_time = line.match(/(\w+) can fly (\d{1,2}) km\/s for (\d{1,2}) .* (\d{2,3}) sec/).captures
speeds[name] = { speed: speed.to_i, run_time: run_time.to_i, rest_time: rest_time.to_i, points: 0 }
end
(1..2503).each do |time|
max = 0
speeds.keys.each do |key|
this = speeds[key]
cycle_time = this[:run_time] + this[:rest_time]
cycles = time / cycle_time
left = time % cycle_time
distance = cycles * this[:run_time] * this[:speed]
distance += left < this[:run_time] ? left * this[:speed] : this[:run_time] * this[:speed]
this[:distance] = distance
max = distance if distance > max
# puts "#{key}: #{this}"
end
# puts "#{max}\n"
speeds.keys.each do |key|
speeds[key][:points] += 1 if speeds[key][:distance] == max
end
end
speeds.each do |k, v|
puts "#{k}: #{v}"
end
| |
Add script for changing max_team_size from 0 to 1 | class AlterMaxTeamSize
def self.run
improper_assignments = Assignment.all(:conditions => 'max_team_size = 0')
improper_assignments.map do |assignment|
assignment.max_team_size = 1
assignment.save
end
end
end | |
Add updated .rb and spec files | # I worked on this challenge [by myself, with: Marcel Galang ].
# Your Solution Below
def leap_year?(number)
if ((number % 4) == 0) && ((number % 100) != 0)
p true
# puts "This is a leap year."
elsif ((number % 400) == 0)
true
# puts "This is a leap year."
elsif ((number % 4) == 0) && ((number % 100) == 0) && ((number % 400) != 0)
false
# puts "This is not a leap year."
elsif (number %4) != 0
false
# puts "This is not a leap year."
end
end
leap_year?(4) | # I worked on this challenge with Kim Allen.
# Your Solution Below
def leap_year?(number)
if ((number % 4) == 0) && ((number % 100) != 0)
p true
# puts "This is a leap year."
elsif ((number % 400) == 0)
true
# puts "This is a leap year."
elsif ((number % 4) == 0) && ((number % 100) == 0) && ((number % 400) != 0)
false
# puts "This is not a leap year."
elsif (number %4) != 0
false
# puts "This is not a leap year."
end
end
leap_year?(4) |
Remove unused Variable in CalendarsController | #encoding: utf-8
class CalendarsController < ApplicationController
def show
raise ActionController::RoutingError.new('Not Found') if current_region.nil?
@categories = Category.all
@start_selector = StartSelector.new(start_date, 8, 5)
single_events = SingleEvent.in_next_from(4.weeks, start_date).in_region(current_region)
@calendar = Calendar.new(single_events, current_user)
end
private
def start_date
@start_date ||= begin
Date.parse(params[:start])
rescue ArgumentError, TypeError
Date.today
end
end
end
| #encoding: utf-8
class CalendarsController < ApplicationController
def show
raise ActionController::RoutingError.new('Not Found') if current_region.nil?
@start_selector = StartSelector.new(start_date, 8, 5)
single_events = SingleEvent.in_next_from(4.weeks, start_date).in_region(current_region)
@calendar = Calendar.new(single_events, current_user)
end
private
def start_date
@start_date ||= begin
Date.parse(params[:start])
rescue ArgumentError, TypeError
Date.today
end
end
end
|
Allow tag releases on ArezIntegration branch | require 'mcrt'
desc 'Publish release on maven central'
task 'publish_to_maven_central' do
project = Buildr.projects[0].root_project
password = ENV['MAVEN_CENTRAL_PASSWORD'] || (raise "Unable to locate environment variable with name 'MAVEN_CENTRAL_PASSWORD'")
MavenCentralPublishTool.buildr_release(project, 'org.realityforge', 'realityforge', password)
end
def get_head_tag_if_any
version = `git describe --exact-match --tags 2>&1`
if 0 == $?.exitstatus && version =~ /^v[0-9]/ && (ENV['TRAVIS_BUILD_ID'].nil? || ENV['TRAVIS_TAG'].to_s != '')
version.strip
else
nil
end
end
def is_tag_on_branch?(tag, branch)
output = `git tag --merged #{branch} 2>&1`
tags = output.split
tags.include?(tag)
end
def is_tag_on_candidate_branches?(tag, branches)
branches.each do |branch|
return true if is_tag_on_branch?(tag, branch)
end
false
end
desc 'Publish release to maven central iff current HEAD is a tag'
task 'publish_if_tagged' do
candidate_branches = %w(master)
tag = get_head_tag_if_any
if !tag.nil? && is_tag_on_candidate_branches?(tag, candidate_branches)
task('publish_to_maven_central').invoke
end
end
| require 'mcrt'
desc 'Publish release on maven central'
task 'publish_to_maven_central' do
project = Buildr.projects[0].root_project
password = ENV['MAVEN_CENTRAL_PASSWORD'] || (raise "Unable to locate environment variable with name 'MAVEN_CENTRAL_PASSWORD'")
MavenCentralPublishTool.buildr_release(project, 'org.realityforge', 'realityforge', password)
end
def get_head_tag_if_any
version = `git describe --exact-match --tags 2>&1`
if 0 == $?.exitstatus && version =~ /^v[0-9]/ && (ENV['TRAVIS_BUILD_ID'].nil? || ENV['TRAVIS_TAG'].to_s != '')
version.strip
else
nil
end
end
def is_tag_on_branch?(tag, branch)
output = `git tag --merged #{branch} 2>&1`
tags = output.split
tags.include?(tag)
end
def is_tag_on_candidate_branches?(tag, branches)
branches.each do |branch|
return true if is_tag_on_branch?(tag, branch)
end
false
end
desc 'Publish release to maven central iff current HEAD is a tag'
task 'publish_if_tagged' do
candidate_branches = %w(master ArezIntegration)
tag = get_head_tag_if_any
if !tag.nil? && is_tag_on_candidate_branches?(tag, candidate_branches)
task('publish_to_maven_central').invoke
end
end
|
Change version to match gem version on RubyGems | Gem::Specification.new do |s|
s.name = 'themis-attack-result'
s.version = '2.0.0'
s.date = '2015-08-08'
s.summary = 'Themis::Attack::Result constants'
s.description = 'Themis::Attack::Result constants'
s.authors = ['Alexander Pyatkin']
s.email = 'asp@thexyz.net'
s.files = ['lib/themis/attack/result.rb']
s.homepage = 'http://github.com/aspyatkin/themis-attack-result'
s.license = 'MIT'
s.required_ruby_version = '>= 2.0'
s.add_dependency 'ruby-enum'
s.add_development_dependency 'bundler'
s.add_development_dependency 'rake'
end
| Gem::Specification.new do |s|
s.name = 'themis-attack-result'
s.version = '3.0.0'
s.date = '2015-08-08'
s.summary = 'Themis::Attack::Result constants'
s.description = 'Themis::Attack::Result constants'
s.authors = ['Alexander Pyatkin']
s.email = 'asp@thexyz.net'
s.files = ['lib/themis/attack/result.rb']
s.homepage = 'http://github.com/aspyatkin/themis-attack-result'
s.license = 'MIT'
s.required_ruby_version = '>= 2.0'
s.add_dependency 'ruby-enum'
s.add_development_dependency 'bundler'
s.add_development_dependency 'rake'
end
|
Add Joe Mattiello into Podspec authors for publishing | # frozen_string_literal: true
Pod::Spec.new do |s|
s.name = 'Hero'
s.version = '1.5.0'
s.summary = 'Elegant transition library for iOS'
s.description = <<-DESC
Hero is a library for building iOS view controller transitions. It provides a declarative layer on top of the UIKit's cumbersome transition APIs. Making custom transitions an easy task for developers.
DESC
s.homepage = 'https://github.com/HeroTransitions/Hero'
s.screenshots = 'https://github.com/HeroTransitions/Hero/blob/master/Resources/Hero.png?raw=true'
s.license = 'MIT'
s.author = { 'Luke' => 'lzhaoyilun@gmail.com' }
s.source = { git: 'https://github.com/HeroTransitions/Hero.git', tag: s.version.to_s }
s.ios.deployment_target = '8.0'
s.tvos.deployment_target = '9.0'
s.ios.frameworks = 'UIKit', 'Foundation', 'QuartzCore', 'CoreGraphics', 'CoreMedia'
s.tvos.frameworks = 'UIKit', 'Foundation', 'QuartzCore', 'CoreGraphics', 'CoreMedia'
s.swift_versions = '4.2'
s.requires_arc = true
s.source_files = 'Sources/**/*.swift'
end
| # frozen_string_literal: true
Pod::Spec.new do |s|
s.name = 'Hero'
s.version = '1.5.0'
s.summary = 'Elegant transition library for iOS'
s.description = <<-DESC
Hero is a library for building iOS view controller transitions. It provides a declarative layer on top of the UIKit's cumbersome transition APIs. Making custom transitions an easy task for developers.
DESC
s.homepage = 'https://github.com/HeroTransitions/Hero'
s.screenshots = 'https://github.com/HeroTransitions/Hero/blob/master/Resources/Hero.png?raw=true'
s.license = 'MIT'
s.author = {
'Luke' => 'lzhaoyilun@gmail.com',
'Joe Mattiello' => 'git@joemattiello.com'
}
s.source = { git: 'https://github.com/HeroTransitions/Hero.git', tag: s.version.to_s }
s.ios.deployment_target = '8.0'
s.tvos.deployment_target = '9.0'
s.ios.frameworks = 'UIKit', 'Foundation', 'QuartzCore', 'CoreGraphics', 'CoreMedia'
s.tvos.frameworks = 'UIKit', 'Foundation', 'QuartzCore', 'CoreGraphics', 'CoreMedia'
s.swift_versions = '4.2'
s.requires_arc = true
s.source_files = 'Sources/**/*.swift'
end
|
Remove errant commas when extracting email addresses from From fields | class ExtractEmailAddresses < MethodObject
def call *strings
Mail::AddressList.new(strings.compact.map { |string| filter_invalid_characters(string) }.join(', ')).addresses.map(&:address)
end
def filter_invalid_characters string
string = string.to_ascii if string =~ /[^\u0000-\u007F]/
string.gsub(/:/, '')
end
end
| class ExtractEmailAddresses < MethodObject
def call *strings
Mail::AddressList.new(strings.compact.map { |string| filter_invalid_characters(string) }.join(', ')).addresses.map(&:address)
end
def filter_invalid_characters string
string = string.to_ascii if string =~ /[^\u0000-\u007F]/
string.gsub(/[:,]/, '')
end
end
|
Add plugin to report CPU usage | require_plugin 'linux::cpu'
cpu[:all] = Mash.new
status, stdout, stderr = run_command(:no_status_check => true,
:command => "mpstat -P ALL")
stdout.lines do |line|
case line
when /[0-9]*\.[0-9]{2}$/
info = line.split("\s")
cpu_num = info[1]
cpu[cpu_num][:usr] = info[2]
cpu[cpu_num][:nice] = info[3]
cpu[cpu_num][:sys] = info[4]
cpu[cpu_num][:iowait] = info[5]
cpu[cpu_num][:irg] = info[6]
cpu[cpu_num][:soft] = info[7]
cpu[cpu_num][:steal] = info[8]
cpu[cpu_num][:guest] = info[9]
cpu[cpu_num][:idle] = info[10]
end
end | |
Add therubyracer as runtime dependency (implicitly required by less-rails) | # -*- encoding: utf-8 -*-
$LOAD_PATH.push File.expand_path('../lib', __FILE__)
require 'kube/rails/version'
Gem::Specification.new do |s|
s.name = 'kube-rails'
s.version = Kube::Rails::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ['Mindaugas Mozūras']
s.email = ['mindaugas.mozuras@gmail.com']
s.homepage = 'https://github.com/mmozuras/kube-rails'
s.summary = 'Kube for Rails 4 Asset Pipeline'
s.description = <<-EOF
kube-rails project integrates Kube for Rails 4 Asset Pipeline
EOF
s.license = 'MIT'
s.rubyforge_project = 'kube-rails'
s.files = Dir['lib/**/*'] + Dir['vendor/**/*'] + ['Rakefile', 'README.md']
s.require_paths = ['lib']
s.add_runtime_dependency 'railties', '~> 4.0'
s.add_runtime_dependency 'actionpack', '~> 4.0'
s.add_runtime_dependency 'less-rails', '~> 2.7.0'
s.add_development_dependency 'rails', '~> 4.0'
end
| # -*- encoding: utf-8 -*-
$LOAD_PATH.push File.expand_path('../lib', __FILE__)
require 'kube/rails/version'
Gem::Specification.new do |s|
s.name = 'kube-rails'
s.version = Kube::Rails::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ['Mindaugas Mozūras']
s.email = ['mindaugas.mozuras@gmail.com']
s.homepage = 'https://github.com/mmozuras/kube-rails'
s.summary = 'Kube for Rails 4 Asset Pipeline'
s.description = <<-EOF
kube-rails project integrates Kube for Rails 4 Asset Pipeline
EOF
s.license = 'MIT'
s.rubyforge_project = 'kube-rails'
s.files = Dir['lib/**/*'] + Dir['vendor/**/*'] + ['Rakefile', 'README.md']
s.require_paths = ['lib']
s.add_runtime_dependency 'railties', '~> 4.0'
s.add_runtime_dependency 'actionpack', '~> 4.0'
s.add_runtime_dependency 'less-rails', '~> 2.7.0'
s.add_runtime_dependency 'therubyracer', '~> 0.12.0'
s.add_development_dependency 'rails', '~> 4.0'
end
|
Update rubocop requirement to ~> 0.54.0 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'prius/version'
Gem::Specification.new do |spec|
spec.name = "prius"
spec.version = Prius::VERSION
spec.authors = ["Harry Marr"]
spec.email = ["engineering@gocardless.com"]
spec.description = %q{Environmentally-friendly config}
spec.summary = spec.description
spec.homepage = "https://github.com/gocardless/prius"
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.required_ruby_version = ">= 2.2"
spec.add_development_dependency "rspec", "~> 3.1"
spec.add_development_dependency "rubocop", "~> 0.53.0"
spec.add_development_dependency "rspec_junit_formatter", "~> 0.3.0"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'prius/version'
Gem::Specification.new do |spec|
spec.name = "prius"
spec.version = Prius::VERSION
spec.authors = ["Harry Marr"]
spec.email = ["engineering@gocardless.com"]
spec.description = %q{Environmentally-friendly config}
spec.summary = spec.description
spec.homepage = "https://github.com/gocardless/prius"
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.required_ruby_version = ">= 2.2"
spec.add_development_dependency "rspec", "~> 3.1"
spec.add_development_dependency "rubocop", "~> 0.54.0"
spec.add_development_dependency "rspec_junit_formatter", "~> 0.3.0"
end
|
Add missing spec for transport execution | require 'spec_helper'
describe ElectricSheep::Transport do
TransportKlazz = Class.new do
include ElectricSheep::Transport
attr_reader :project, :logger, :metadata, :hosts, :done
def do
@done = true
end
end
describe TransportKlazz do
it 'performs using transport type from metadata' do
transport=subject.new(project=mock, logger=mock, metadata=mock, hosts=mock)
metadata.expects(:type).returns(:do)
transport.perform
transport.project.must_equal project
transport.logger.must_equal logger
transport.metadata.must_equal metadata
transport.hosts.must_equal hosts
transport.done.must_equal true
end
end
end
| |
Use Class.new block instead of instance_eval | class Value
def self.new(*fields)
value_class = Class.new
value_class.instance_eval do
attr_reader *fields
define_method(:initialize) do |*input_fields|
raise ArgumentError.new("wrong number of arguments, #{input_fields.size} for #{fields.size}") if fields.size != input_fields.size
fields.each_with_index do |field, index|
instance_variable_set('@' + field.to_s, input_fields[index])
end
self.freeze
end
end
return value_class
end
end
| class Value
def self.new(*fields)
return Class.new do
attr_reader *fields
define_method(:initialize) do |*input_fields|
raise ArgumentError.new("wrong number of arguments, #{input_fields.size} for #{fields.size}") if fields.size != input_fields.size
fields.each_with_index do |field, index|
instance_variable_set('@' + field.to_s, input_fields[index])
end
self.freeze
end
end
end
end
|
Remove rubyforge_project to fix deprecation warning | # -*- encoding: utf-8 -*-
$:.push File.expand_path('../lib', __FILE__)
require 'mt940/version'
Gem::Specification.new do |s|
s.name = 'mt940'
s.version = MT940::VERSION
s.authors = ['Lars Vonk', 'Michael Franken']
s.description = %q{An extended MT940 parser with implementations for Dutch banks. Based on basic parser from http://github.com/dovadi/mt940}
s.summary = %q{MT940 parser}
s.email = %q{lvonk@zilverline.com mfranken@zilverline.com}
s.homepage = %q{https://github.com/zilverline/mt940}
s.licenses = ['MIT']
s.extra_rdoc_files = [
'LICENSE.txt',
'README.md'
]
s.rubyforge_project = 'mt940'
s.add_development_dependency 'rspec'
s.add_development_dependency 'rspec-collection_matchers'
s.add_development_dependency 'rake'
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']
end
| # -*- encoding: utf-8 -*-
$:.push File.expand_path('../lib', __FILE__)
require 'mt940/version'
Gem::Specification.new do |s|
s.name = 'mt940'
s.version = MT940::VERSION
s.authors = ['Lars Vonk', 'Michael Franken']
s.description = %q{An extended MT940 parser with implementations for Dutch banks. Based on basic parser from http://github.com/dovadi/mt940}
s.summary = %q{MT940 parser}
s.email = %q{lvonk@zilverline.com mfranken@zilverline.com}
s.homepage = %q{https://github.com/zilverline/mt940}
s.licenses = ['MIT']
s.extra_rdoc_files = [
'LICENSE.txt',
'README.md'
]
s.add_development_dependency 'rspec'
s.add_development_dependency 'rspec-collection_matchers'
s.add_development_dependency 'rake'
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']
end
|
Fix punctuation in podspec summary | Pod::Spec.new do |s|
s.name = "CIOAPIClient"
s.version = "0.8.6"
s.summary = "API Client for Context.IO"
s.homepage = "https://github.com/contextio/contextio-ios"
s.license = 'MIT'
s.author = { 'Kevin Lord' => 'kevinlord@otherinbox.com' }
s.source = { :git => "https://github.com/contextio/contextio-ios.git", :tag => '0.8.6' }
s.source_files = 'CIOAPIClient', 'CIOAPIClient/OAuth', 'CIOAPIClient/OAuth/Crypto'
s.requires_arc = true
s.ios.deployment_target = '5.0'
s.ios.frameworks = 'Security'
s.osx.deployment_target = '10.7'
s.dependency 'AFNetworking', '>= 0.9'
s.dependency 'SSKeychain', '>= 0.2.1'
end
| Pod::Spec.new do |s|
s.name = "CIOAPIClient"
s.version = "0.8.6"
s.summary = "API Client for Context.IO."
s.homepage = "https://github.com/contextio/contextio-ios"
s.license = 'MIT'
s.author = { 'Kevin Lord' => 'kevinlord@otherinbox.com' }
s.source = { :git => "https://github.com/contextio/contextio-ios.git", :tag => '0.8.6' }
s.source_files = 'CIOAPIClient', 'CIOAPIClient/OAuth', 'CIOAPIClient/OAuth/Crypto'
s.requires_arc = true
s.ios.deployment_target = '5.0'
s.ios.frameworks = 'Security'
s.osx.deployment_target = '10.7'
s.dependency 'AFNetworking', '>= 0.9'
s.dependency 'SSKeychain', '>= 0.2.1'
end
|
Add rake as development dependency | # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "parsr"
Gem::Specification.new do |s|
s.name = "parsr"
s.version = Parsr::VERSION
s.authors = ["Jean Boussier"]
s.email = ["jean.boussier@gmail.com"]
s.homepage = "https://github.com/byroot/parsr/"
s.summary = %q{Simple parser to safe eval ruby literals}
s.description = %q{Parsr aim to provide a way to safely evaluate a ruby expression composed only with literals, just as Python's ast.literal_eval}
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_development_dependency "rspec"
end
| # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "parsr"
Gem::Specification.new do |s|
s.name = "parsr"
s.version = Parsr::VERSION
s.authors = ["Jean Boussier"]
s.email = ["jean.boussier@gmail.com"]
s.homepage = "https://github.com/byroot/parsr/"
s.summary = %q{Simple parser to safe eval ruby literals}
s.description = %q{Parsr aim to provide a way to safely evaluate a ruby expression composed only with literals, just as Python's ast.literal_eval}
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_development_dependency "rspec"
s.add_development_dependency "rake"
end
|
Fix for delayed_job to disable asynchronous jobs when testing | require 'active_support/basic_object'
module Delayed
class DelayProxy < ActiveSupport::BasicObject
def initialize(target, options)
@target = target
@options = options
end
def method_missing(method, *args)
Job.create({
:payload_object => PerformableMethod.new(@target, method.to_sym, args),
:priority => ::Delayed::Worker.default_priority
}.merge(@options))
end
end
module MessageSending
def delay(options = {})
DelayProxy.new(self, options)
end
alias __delay__ delay
def send_later(method, *args)
warn "[DEPRECATION] `object.send_later(:method)` is deprecated. Use `object.delay.method"
__delay__.__send__(method, *args)
end
def send_at(time, method, *args)
warn "[DEPRECATION] `object.send_at(time, :method)` is deprecated. Use `object.delay(:run_at => time).method"
__delay__(:run_at => time).__send__(method, *args)
end
module ClassMethods
def handle_asynchronously(method)
aliased_method, punctuation = method.to_s.sub(/([?!=])$/, ''), $1
with_method, without_method = "#{aliased_method}_with_delay#{punctuation}", "#{aliased_method}_without_delay#{punctuation}"
define_method(with_method) do |*args|
delay.__send__(without_method, *args)
end
alias_method_chain method, :delay
end
end
end
end
| require 'active_support/basic_object'
module Delayed
class DelayProxy < ActiveSupport::BasicObject
def initialize(target, options)
@target = target
@options = options
end
def method_missing(method, *args)
Job.create({
:payload_object => PerformableMethod.new(@target, method.to_sym, args),
:priority => ::Delayed::Worker.default_priority
}.merge(@options))
end
end
module MessageSending
def delay(options = {})
DelayProxy.new(self, options)
end
alias __delay__ delay
def send_later(method, *args)
warn "[DEPRECATION] `object.send_later(:method)` is deprecated. Use `object.delay.method"
__delay__.__send__(method, *args)
end
def send_at(time, method, *args)
warn "[DEPRECATION] `object.send_at(time, :method)` is deprecated. Use `object.delay(:run_at => time).method"
__delay__(:run_at => time).__send__(method, *args)
end
module ClassMethods
def handle_asynchronously(method)
return if Rails.env == "test"
aliased_method, punctuation = method.to_s.sub(/([?!=])$/, ''), $1
with_method, without_method = "#{aliased_method}_with_delay#{punctuation}", "#{aliased_method}_without_delay#{punctuation}"
define_method(with_method) do |*args|
delay.__send__(without_method, *args)
end
alias_method_chain method, :delay
end
end
end
end
|
Convert sensor device registration parameters to integer | # == Schema Information
#
# Table name: sensor_devices
#
# id :integer not null, primary key
# sensors :text
#
class SensorDevice < ActiveRecord::Base
inherit DeviceBase
include WlanDevice
acts_as :device
# [{ type: <sensor-type>, min: minimum value, max: maximum value }, ...]
serialize :sensors
def self.attr_accessible
Device.attr_accessible
end
def self.small_icon()
'16/thermometer.png'
end
def self.large_icon()
'32/thermometer.png'
end
def update_attributes_from_registration params
num_sensors = params[0]
sensor_defs = params[1..-1].in_groups_of(3).take num_sensors
update_attributes sensors: sensor_defs.each_with_index.map { |d| { type: d[0], min: d[1], max: d[2] } }
end
def states
@states ||= Array.new(sensors.count, 0.0)
end
def update
end
def message_received message, params
super
if message == CaretakerMessages::SENSOR_STATE
params.in_groups_of(2).each do |num, value|
states[num.to_i] = value.to_f
end
notify_change_listeners
end
end
def current_state
states
end
end
| # == Schema Information
#
# Table name: sensor_devices
#
# id :integer not null, primary key
# sensors :text
#
class SensorDevice < ActiveRecord::Base
inherit DeviceBase
include WlanDevice
acts_as :device
# [{ type: <sensor-type>, min: minimum value, max: maximum value }, ...]
serialize :sensors
def self.attr_accessible
Device.attr_accessible
end
def self.small_icon()
'16/thermometer.png'
end
def self.large_icon()
'32/thermometer.png'
end
def update_attributes_from_registration params
num_sensors = params[0].to_i
sensor_defs = params[1..-1].in_groups_of(3).take num_sensors
update_attributes sensors: sensor_defs.each_with_index.map { |d| { type: d[0].to_i, min: d[1].to_i, max: d[2].to_i } }
end
def states
@states ||= Array.new(sensors.count, 0.0)
end
def update
end
def message_received message, params
super
if message == CaretakerMessages::SENSOR_STATE
params.in_groups_of(2).each do |num, value|
states[num.to_i] = value.to_f
end
notify_change_listeners
end
end
def current_state
states
end
end
|
Add gemspec summary, description, and homepage for release | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/beso/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Jeremy Ruppel"]
gem.email = ["jeremy.ruppel@gmail.com"]
gem.description = %q{TODO: Write a gem description}
gem.summary = %q{TODO: Write a gem summary}
gem.homepage = ""
gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "beso"
gem.require_paths = ["lib"]
gem.version = Beso::VERSION
gem.add_dependency 'rails', '>= 3.0.10'
gem.add_dependency 'comma', '>= 3.0.3'
gem.add_development_dependency 'sqlite3'
gem.add_development_dependency 'appraisal', '>= 0.4.1'
gem.add_development_dependency 'rspec', '>= 2.9.0'
end
| # -*- encoding: utf-8 -*-
require File.expand_path('../lib/beso/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Jeremy Ruppel"]
gem.email = ["jeremy.ruppel@gmail.com"]
gem.description = %q{Sync your KISSmetrics history, guapo!}
gem.summary = %q{Sync your KISSmetrics history, guapo!}
gem.homepage = "https://github.com/remind101/beso"
gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "beso"
gem.require_paths = ["lib"]
gem.version = Beso::VERSION
gem.add_dependency 'rails', '>= 3.0.10'
gem.add_dependency 'comma', '>= 3.0.3'
gem.add_development_dependency 'sqlite3'
gem.add_development_dependency 'appraisal', '>= 0.4.1'
gem.add_development_dependency 'rspec', '>= 2.9.0'
end
|
Fix Faraday with default (Net::HTTP) adapter | require 'net/https'
Net::HTTP.class_eval do
alias _use_ssl= use_ssl=
def use_ssl= boolean
self.ca_file = "#{File.dirname(__FILE__)}/certs/ca-bundle.crt"
self.verify_mode = OpenSSL::SSL::VERIFY_PEER
self._use_ssl = boolean
end
end
| require 'net/https'
Net::HTTP.class_eval do
alias _use_ssl= use_ssl=
def use_ssl= boolean
self.ca_file = "#{File.dirname(__FILE__)}/certs/ca-bundle.crt"
self.verify_mode = OpenSSL::SSL::VERIFY_PEER
self._use_ssl = boolean
end
end
OpenSSL::X509::Store.class_eval do
alias _set_default_paths set_default_paths
def set_default_paths
self._set_default_paths
self.add_file "#{File.dirname(__FILE__)}/certs/ca-bundle.crt"
end
end
|
Include paperclip matchers and disable warnings on specs | $LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)
# Code coverage
require "simplecov"
SimpleCov.start
# Development dependencies
require "byebug"
require "paperclip"
require "carrierwave"
# The gem itself
require "xing/pdf_cover"
RSpec.configure do |config|
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.disable_monkey_patching!
config.warnings = true
config.profile_examples = 10
config.order = :random
config.default_formatter = "Fivemat"
config.expose_dsl_globally = true
end
| $LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)
# Code coverage
require "simplecov"
SimpleCov.start
# Development dependencies
require "byebug"
require "paperclip"
require "paperclip/matchers"
require "carrierwave"
# The gem itself
require "xing/pdf_cover"
RSpec.configure do |config|
config.include Paperclip::Shoulda::Matchers
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.disable_monkey_patching!
config.profile_examples = 10
config.order = :random
config.default_formatter = "Fivemat"
config.expose_dsl_globally = true
end
|
Fix correct path for expiring cached pages, oops | class ApplicationController < ActionController::Base
self.page_cache_directory = "#{Rails.root}/public/cached_pages"
protect_from_forgery with: :exception
def self.expire_about
expire_page('/cached_pages/about.html')
end
def self.expire_home
expire_page('/cached_pages/index.html')
end
end
| class ApplicationController < ActionController::Base
self.page_cache_directory = "#{Rails.root}/public/cached_pages"
protect_from_forgery with: :exception
def self.expire_about
expire_page('about.html')
end
def self.expire_home
expire_page('index.html')
end
end
|
Update round to default spree rounding | module Spree
Variant.class_eval do
scope :sale_off, -> { where('sale_rate > 0').where.not(sale_date: nil).where('sale_date < ?', DateTime.now) }
alias_method :orig_price_in, :price_in
def price_in(currency)
return orig_price_in(currency) unless sale_off?
orig_amount = orig_price_in(currency).amount || 0.0
sale_amount = orig_amount - (orig_amount * sale_rate.to_f)
sale_amount_rounded = BigDecimal.new(sale_amount.to_s).round(0, BigDecimal::ROUND_HALF_EVEN)
Spree::Price.new(:variant_id => self.id, :amount => sale_amount_rounded, :currency => currency)
end
before_save :calculate_sale_price
def calculate_sale_price
if sale_rate.to_f > 0
self.sale_price = Spree::Money.new(price - (price * sale_rate.to_f)).money.dollars
else
self.sale_price = nil
end
end
after_save :make_product_on_sale
def make_product_on_sale
is_on_sale = product.variants_including_master.sale_off.count > 0
# product.on_sale = is_on_sale
product.update_column(:on_sale, is_on_sale)
end
def sale_off?
!(sale_date.nil? || sale_date.future?) && sale_rate.to_f > 0
end
end
end
| module Spree
Variant.class_eval do
scope :sale_off, -> { where('sale_rate > 0').where.not(sale_date: nil).where('sale_date < ?', DateTime.now) }
alias_method :orig_price_in, :price_in
def price_in(currency)
return orig_price_in(currency) unless sale_off?
orig_amount = orig_price_in(currency).amount || 0.0
sale_amount = orig_amount - (orig_amount * sale_rate.to_f)
sale_amount_rounded = BigDecimal.new(sale_amount.to_s).round(0, BigDecimal::ROUND_HALF_UP)
Spree::Price.new(:variant_id => self.id, :amount => sale_amount_rounded, :currency => currency)
end
before_save :calculate_sale_price
def calculate_sale_price
if sale_rate.to_f > 0
self.sale_price = Spree::Money.new(price - (price * sale_rate.to_f)).money.dollars
else
self.sale_price = nil
end
end
after_save :make_product_on_sale
def make_product_on_sale
is_on_sale = product.variants_including_master.sale_off.count > 0
# product.on_sale = is_on_sale
product.update_column(:on_sale, is_on_sale)
end
def sale_off?
!(sale_date.nil? || sale_date.future?) && sale_rate.to_f > 0
end
end
end
|
Add Three20.bundle to pod resources | Pod::Spec.new do |s|
s.name = '320Categories'
s.version = '0.2.2'
s.license = 'MIT'
s.summary = 'Maintenance it based facebook three20.'
s.homepage = 'https://github.com/jimneylee/320Categories'
s.author = { 'jimneylee' => 'jimneylee@gmail.com' }
s.source = { :git => 'https://github.com/jimneylee/320Categories.git',
:tag => '0.2.2' }
s.ios.deployment_target = '5.0'
s.source_files = '320Categories'
s.requires_arc = true
end
| Pod::Spec.new do |s|
s.name = '320Categories'
s.version = '0.2.2'
s.license = 'MIT'
s.summary = 'Maintenance it based facebook three20.'
s.homepage = 'https://github.com/jimneylee/320Categories'
s.author = { 'jimneylee' => 'jimneylee@gmail.com' }
s.source = { :git => 'https://github.com/jimneylee/320Categories.git',
:tag => '0.2.2' }
s.ios.deployment_target = '5.0'
s.source_files = '320Categories'
s.resource = "320Categories/Three20.bundle"
s.requires_arc = true
end
|
Revert "reverted back to previous require 'crypt/ISAAC' (require 'crypt-isaac' doesn't work for me)" | require 'crypt/ISAAC'
# Misc utility function used throughout by the RubyCAS-Server.
module CASServer
module Utils
def random_string(max_length = 29)
rg = Crypt::ISAAC.new
max = 4294619050
r = "#{Time.now.to_i}r%X%X%X%X%X%X%X%X" %
[rg.rand(max), rg.rand(max), rg.rand(max), rg.rand(max),
rg.rand(max), rg.rand(max), rg.rand(max), rg.rand(max)]
r[0..max_length-1]
end
module_function :random_string
def log_controller_action(controller, params)
$LOG << "\n"
/`(.*)'/.match(caller[1])
method = $~[1]
if params.respond_to? :dup
params2 = params.dup
params2['password'] = '******' if params2['password']
else
params2 = params
end
$LOG.debug("Processing #{controller}::#{method} #{params2.inspect}")
end
module_function :log_controller_action
end
end
| require 'crypt-isaac'
# Misc utility function used throughout by the RubyCAS-Server.
module CASServer
module Utils
def random_string(max_length = 29)
rg = Crypt::ISAAC.new
max = 4294619050
r = "#{Time.now.to_i}r%X%X%X%X%X%X%X%X" %
[rg.rand(max), rg.rand(max), rg.rand(max), rg.rand(max),
rg.rand(max), rg.rand(max), rg.rand(max), rg.rand(max)]
r[0..max_length-1]
end
module_function :random_string
def log_controller_action(controller, params)
$LOG << "\n"
/`(.*)'/.match(caller[1])
method = $~[1]
if params.respond_to? :dup
params2 = params.dup
params2['password'] = '******' if params2['password']
else
params2 = params
end
$LOG.debug("Processing #{controller}::#{method} #{params2.inspect}")
end
module_function :log_controller_action
end
end
|
Print a failure and also the exception | class Object
def it(title, &block)
block.call
print '.'
end
end
| class Object
def it(title, &block)
block.call
print '.'
rescue Exception => e
print 'F'
puts
puts e.to_s
puts e.backtrace
end
end
|
Reorder respond_to formats in deny_access | module Clearance
module Authorization
extend ActiveSupport::Concern
included do
hide_action :authorize, :deny_access
end
def authorize
unless signed_in?
deny_access
end
end
def deny_access(flash_message = nil)
respond_to do |format|
format.html { redirect_html_request(flash_message) }
format.all { head :unauthorized }
end
end
protected
def redirect_html_request(flash_message)
store_location
if flash_message
flash[:notice] = flash_message
end
if signed_in?
redirect_to url_after_denied_access_when_signed_in
else
redirect_to url_after_denied_access_when_signed_out
end
end
def clear_return_to
session[:return_to] = nil
end
def store_location
if request.get?
session[:return_to] = request.fullpath
end
end
def redirect_back_or(default)
redirect_to(return_to || default)
clear_return_to
end
def return_to
if return_to_url
URI.parse(return_to_url).path
end
end
def return_to_url
session[:return_to] || params[:return_to]
end
def url_after_denied_access_when_signed_in
Clearance.configuration.redirect_url
end
def url_after_denied_access_when_signed_out
sign_in_url
end
end
end
| module Clearance
module Authorization
extend ActiveSupport::Concern
included do
hide_action :authorize, :deny_access
end
def authorize
unless signed_in?
deny_access
end
end
def deny_access(flash_message = nil)
respond_to do |format|
format.any(:js, :json, :xml) { head :unauthorized }
format.any { redirect_request(flash_message) }
end
end
protected
def redirect_request(flash_message)
store_location
if flash_message
flash[:notice] = flash_message
end
if signed_in?
redirect_to url_after_denied_access_when_signed_in
else
redirect_to url_after_denied_access_when_signed_out
end
end
def clear_return_to
session[:return_to] = nil
end
def store_location
if request.get?
session[:return_to] = request.fullpath
end
end
def redirect_back_or(default)
redirect_to(return_to || default)
clear_return_to
end
def return_to
if return_to_url
URI.parse(return_to_url).path
end
end
def return_to_url
session[:return_to] || params[:return_to]
end
def url_after_denied_access_when_signed_in
Clearance.configuration.redirect_url
end
def url_after_denied_access_when_signed_out
sign_in_url
end
end
end
|
Add temporary rake task to fix redirect on a document | namespace :temporary_data_hygiene do
desc "Fix redirect URL for unpublished document /disposal-of-dredged-material-at-sea"
task redirect_dredged_material: :environment do
current_user = User.find("5bfc0db3e5274a7e7111a5d7") # Bruce Bolt
edition = Edition.find_by(slug: "disposal-of-dredged-material-at-sea", state: "archived")
edition.artefact.update!(redirect_url: "/guidance/do-i-need-a-marine-licence")
UnpublishService.call(edition.artefact, current_user, edition.artefact.redirect_url)
end
end
| |
Update use newest version of CocoaAsyncSocket | Pod::Spec.new do |s|
s.name = 'NHNetworkTime'
s.version = '1.6'
s.summary = 'Network time protocol NTP for iOS.'
s.homepage = 'https://github.com/huynguyencong/NHNetworkTime'
s.license = { :type => 'Apache', :file => 'LICENSE' }
s.source = { :git => 'https://github.com/huynguyencong/NHNetworkTime.git', :tag => "#{s.version}" }
s.author = { 'Huy Nguyen Cong' => 'https://github.com/huynguyencong' }
s.ios.deployment_target = '7.0'
s.source_files = 'NHNetworkTime/*.{h,m}'
s.framework = 'CFNetwork'
s.dependency 'CocoaAsyncSocket', '~>7.4.1'
s.requires_arc = true
end
| Pod::Spec.new do |s|
s.name = 'NHNetworkTime'
s.version = '1.6'
s.summary = 'Network time protocol NTP for iOS.'
s.homepage = 'https://github.com/huynguyencong/NHNetworkTime'
s.license = { :type => 'Apache', :file => 'LICENSE' }
s.source = { :git => 'https://github.com/huynguyencong/NHNetworkTime.git', :tag => "#{s.version}" }
s.author = { 'Huy Nguyen Cong' => 'https://github.com/huynguyencong' }
s.ios.deployment_target = '7.0'
s.source_files = 'NHNetworkTime/*.{h,m}'
s.framework = 'CFNetwork'
s.dependency 'CocoaAsyncSocket', '~>7.5.0'
s.requires_arc = true
end
|
Remove unnecessary require from gemspec | $:.unshift File.expand_path("../lib", __FILE__)
require "hiera/backend/psql_backend"
Gem::Specification.new do |s|
s.version = "0.1.0"
s.name = "hiera-psql"
s.email = "erik.gustav.dalen@gmail.com"
s.authors = "Erik Dalén"
s.summary = "A PostgreSQL backend for Hiera."
s.description = "Allows hiera functions to pull data from a PostgreSQL database."
s.has_rdoc = false
s.homepage = "http://github.com/dalen/hiera-psql"
s.license = "Apache 2.0"
s.add_dependency 'hiera', '~> 1.0'
s.files = Dir["lib/**/*.rb"]
s.files += ["LICENSE"]
end
| $:.unshift File.expand_path("../lib", __FILE__)
Gem::Specification.new do |s|
s.version = "0.1.0"
s.name = "hiera-psql"
s.email = "erik.gustav.dalen@gmail.com"
s.authors = "Erik Dalén"
s.summary = "A PostgreSQL backend for Hiera."
s.description = "Allows hiera functions to pull data from a PostgreSQL database."
s.has_rdoc = false
s.homepage = "http://github.com/dalen/hiera-psql"
s.license = "Apache 2.0"
s.add_dependency 'hiera', '~> 1.0'
s.files = Dir["lib/**/*.rb"]
s.files += ["LICENSE"]
end
|
Fix broken link to resource from Tools index | class ResourcesController < ApplicationController
def index
@tools = Tool.all
@resources = Resource.all
respond_to do |format|
format.html
format.json { render json: @tools }
end
end
def new
@resource = Resource.new
end
def create
@resource = current_user.resources.build(strong)
@tool = Tool.find(params[:id])
if @resource.save
@tool.resources << @resource
redirect_to tool_path
else
flash[:notice] = 'Please fix the errors as marked.'
render 'new'
end
end
def show
@tool = Tool.find(params[:id])
@resource = Resource.find(params[:id])
respond_to do |format|
format.html
format.json { render json: @tool.resource }
end
end
def edit
@resource = Resource.find(params[:id])
end
def update
@resource = Resource.find(params[:id])
if @resource.update(strong)
redirect_to root_path
else
flash[:notice] = 'Please fix the erros as marked.'
render 'edit'
end
end
def destroy
@resource = Resource.find(params[:id])
@resource.destroy
flash[:notice] = 'Resource has been destroyed.'
redirect_to root_path
end
private
def strong
params.require(:resource).permit(:name, :summary, :tool_id, :user_id, :cat_id, :url)
end
end
| class ResourcesController < ApplicationController
def index
@tools = Tool.all
@resources = Resource.all
respond_to do |format|
format.html
format.json { render json: @tools }
end
end
def new
@resource = Resource.new
end
def create
@resource = current_user.resources.build(strong)
@tool = Tool.find(params[:id])
if @resource.save
@tool.resources << @resource
redirect_to tool_path
else
flash[:notice] = 'Please fix the errors as marked.'
render 'new'
end
end
def show
@resource = Resource.find(params[:id])
respond_to do |format|
format.html
format.json { render json: @tool.resource }
end
end
def edit
@resource = Resource.find(params[:id])
end
def update
@resource = Resource.find(params[:id])
if @resource.update(strong)
redirect_to root_path
else
flash[:notice] = 'Please fix the erros as marked.'
render 'edit'
end
end
def destroy
@resource = Resource.find(params[:id])
@resource.destroy
flash[:notice] = 'Resource has been destroyed.'
redirect_to root_path
end
private
def strong
params.require(:resource).permit(:name, :summary, :tool_id, :user_id, :cat_id, :url)
end
end
|
Use Rails 3.1 module order which has bug fixes. | require 'strobe/action_controller/haltable'
require 'strobe/action_controller/param'
module Strobe
module ActionController
# A configured ActionController::Metal that includes
# only the basic functionality.
class Metal < ::ActionController::Metal
abstract!
include ::ActionController::UrlFor
include ::ActionController::Head
include ::ActionController::Redirecting
include ::ActionController::Rendering
include ::ActionController::Renderers::All
include ::ActionController::ConditionalGet
include ::ActionController::RackDelegation
include ::ActionController::Caching
include ::ActionController::MimeResponds
include ::ActionController::ImplicitRender
# Add instrumentations hooks at the bottom, to ensure they instrument
# all the methods properly.
include ::ActionController::Instrumentation
# Before callbacks should also be executed the earliest as possible, so
# also include them at the bottom.
include ::AbstractController::Callbacks
# The same with rescue, append it at the end to wrap as much as possible.
include ::ActionController::Rescue
include Haltable
include Param
end
end
end | require 'strobe/action_controller/haltable'
require 'strobe/action_controller/param'
module Strobe
module ActionController
# A configured ActionController::Metal that includes
# only the basic functionality.
class Metal < ::ActionController::Metal
abstract!
include ::ActionController::UrlFor
include ::ActionController::Head
include ::ActionController::Redirecting
include ::ActionController::Rendering
include ::ActionController::Renderers::All
include ::ActionController::ConditionalGet
include ::ActionController::RackDelegation
include ::ActionController::Caching
include ::ActionController::MimeResponds
include ::ActionController::ImplicitRender
include ::ActionController::ForceSSL if defined?(::ActionController::ForceSSL)
include ::ActionController::HttpAuthentication::Basic::ControllerMethods
include ::ActionController::HttpAuthentication::Digest::ControllerMethods
include ::ActionController::HttpAuthentication::Token::ControllerMethods
# Before callbacks should also be executed the earliest as possible, so
# also include them at the bottom.
include ::AbstractController::Callbacks
# The same with rescue, append it at the end to wrap as much as possible.
include ::ActionController::Rescue
# Add instrumentations hooks at the bottom, to ensure they instrument
# all the methods properly.
include ::ActionController::Instrumentation
include Haltable
include Param
end
end
end |
Add documentation for the redcarpet options. | require 'redcarpet'
module Udongo
class Markdown
def self.to_html(string, options = {})
Redcarpet::Markdown.new(Redcarpet::Render::HTML, options).render(string.to_s).html_safe
end
end
end
| require 'redcarpet'
module Udongo
class Markdown
# Check out https://github.com/vmg/redcarpet for a list of all the options
def self.to_html(string, options = {})
Redcarpet::Markdown.new(Redcarpet::Render::HTML, options).render(string.to_s).html_safe
end
end
end
|
Add rake as dev dependency. | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/bundler_issue_report/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Peter Jaros"]
gem.email = ["peter.a.jaros@gmail.com"]
gem.description = %q{Builds a report with all the info the Bundler team asks for in issues.}
gem.summary = %q{Builds a report with all the info the Bundler team asks for in issues.}
gem.homepage = "https://github.com/Peeja/bundler_issue_report"
gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "bundler_issue_report"
gem.require_paths = ["lib"]
gem.version = BundlerIssueReport::VERSION
end
| # -*- encoding: utf-8 -*-
require File.expand_path('../lib/bundler_issue_report/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Peter Jaros"]
gem.email = ["peter.a.jaros@gmail.com"]
gem.description = %q{Builds a report with all the info the Bundler team asks for in issues.}
gem.summary = %q{Builds a report with all the info the Bundler team asks for in issues.}
gem.homepage = "https://github.com/Peeja/bundler_issue_report"
gem.files = `git ls-files`.split($\)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "bundler_issue_report"
gem.require_paths = ["lib"]
gem.version = BundlerIssueReport::VERSION
gem.add_development_dependency "rake"
end
|
Use camelize instead of classify Components are singularized otherwise | module MountainView
class Presenter
class_attribute :_attributes, instance_accessor: false
self._attributes = {}
attr_reader :slug, :properties
alias_method :props, :properties
def initialize(slug, properties = {})
@slug = slug
@properties = attribute_defaults.deep_merge(properties)
end
def partial
"#{slug}/#{slug}"
end
def locals
locals = build_locals
locals.merge(properties: locals)
end
private
def build_locals
attributes.inject({}) do|sum, attr|
sum[attr] = attribute_value(attr)
sum
end
end
def attributes
@attributes ||= (properties.keys + self.class._attributes.keys)
end
def attribute_value(key)
return unless attributes.include?(key)
respond_to?(key) ? send(key) : properties[key]
end
def attribute_defaults
self.class._attributes.inject({}) do |sum, (k, v)|
sum[k] = v[:default]
sum
end
end
class << self
def attributes(*args)
opts = args.extract_options!
attributes = args.inject({}) do |sum, name|
sum[name] = opts
sum
end
self._attributes = _attributes.merge(attributes)
end
alias_method :attribute, :attributes
end
def self.component_for(slug, properties = {})
klass = "#{slug.to_s.classify}Component".safe_constantize
klass ||= self
klass.new(slug, properties)
end
end
end
| module MountainView
class Presenter
class_attribute :_attributes, instance_accessor: false
self._attributes = {}
attr_reader :slug, :properties
alias_method :props, :properties
def initialize(slug, properties = {})
@slug = slug
@properties = attribute_defaults.deep_merge(properties)
end
def partial
"#{slug}/#{slug}"
end
def locals
locals = build_locals
locals.merge(properties: locals)
end
private
def build_locals
attributes.inject({}) do|sum, attr|
sum[attr] = attribute_value(attr)
sum
end
end
def attributes
@attributes ||= (properties.keys + self.class._attributes.keys)
end
def attribute_value(key)
return unless attributes.include?(key)
respond_to?(key) ? send(key) : properties[key]
end
def attribute_defaults
self.class._attributes.inject({}) do |sum, (k, v)|
sum[k] = v[:default]
sum
end
end
class << self
def attributes(*args)
opts = args.extract_options!
attributes = args.inject({}) do |sum, name|
sum[name] = opts
sum
end
self._attributes = _attributes.merge(attributes)
end
alias_method :attribute, :attributes
end
def self.component_for(slug, properties = {})
klass = "#{slug.to_s.camelize}Component".safe_constantize
klass ||= self
klass.new(slug, properties)
end
end
end
|
Make AV dependency for ActionMailer | version = File.read(File.expand_path('../../RAILS_VERSION', __FILE__)).strip
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'actionmailer'
s.version = version
s.summary = 'Email composition, delivery, and receiving framework (part of Rails).'
s.description = 'Email on Rails. Compose, deliver, receive, and test emails using the familiar controller/view pattern. First-class support for multipart email and attachments.'
s.required_ruby_version = '>= 1.9.3'
s.license = 'MIT'
s.author = 'David Heinemeier Hansson'
s.email = 'david@loudthinking.com'
s.homepage = 'http://www.rubyonrails.org'
s.files = Dir['CHANGELOG.md', 'README.rdoc', 'MIT-LICENSE', 'lib/**/*']
s.require_path = 'lib'
s.requirements << 'none'
s.add_dependency 'actionpack', version
s.add_development_dependency 'actionview', version
s.add_dependency 'mail', '~> 2.5.4'
end
| version = File.read(File.expand_path('../../RAILS_VERSION', __FILE__)).strip
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'actionmailer'
s.version = version
s.summary = 'Email composition, delivery, and receiving framework (part of Rails).'
s.description = 'Email on Rails. Compose, deliver, receive, and test emails using the familiar controller/view pattern. First-class support for multipart email and attachments.'
s.required_ruby_version = '>= 1.9.3'
s.license = 'MIT'
s.author = 'David Heinemeier Hansson'
s.email = 'david@loudthinking.com'
s.homepage = 'http://www.rubyonrails.org'
s.files = Dir['CHANGELOG.md', 'README.rdoc', 'MIT-LICENSE', 'lib/**/*']
s.require_path = 'lib'
s.requirements << 'none'
s.add_dependency 'actionpack', version
s.add_dependency 'actionview', version
s.add_dependency 'mail', '~> 2.5.4'
end
|
Include X-Avalara-Client in each request | require 'faraday_middleware'
module AvaTax
module Connection
private
def connection
options = {
:headers => {'Accept' => "application/json; charset=utf-8", 'User-Agent' => user_agent},
:url => endpoint,
:proxy => proxy,
}.merge(connection_options)
c = Faraday::Connection.new(options)
if logger
c.response :logger do |logger|
logger.filter(/(Authorization\:\ \"Basic\ )(\w+)\=/, '\1[REMOVED]')
end
end
c.use Faraday::Request::UrlEncoded
c.use Faraday::Response::ParseJson
c.basic_auth(username, password)
c
end
end
end
| require 'faraday_middleware'
module AvaTax
module Connection
private
def connection
client_id = "#{app_name};#{app_version};RubySdk;#{AvaTax::VERSION.dup};#{machine_name}"
options = {
:headers =>
{
'Accept' => "application/json; charset=utf-8",
'User-Agent' => user_agent,
'X-Avalara-Client' => client_id
},
:url => endpoint,
:proxy => proxy,
}.merge(connection_options)
c = Faraday::Connection.new(options)
if logger
c.response :logger do |logger|
logger.filter(/(Authorization\:\ \"Basic\ )(\w+)\=/, '\1[REMOVED]')
end
end
c.use Faraday::Request::UrlEncoded
c.use Faraday::Response::ParseJson
c.basic_auth(username, password)
c
end
end
end
|
Send from our new domain | class ApplicationMailer < ActionMailer::Base
default from: "larp-library@aegames.org"
layout 'mailer'
end
| class ApplicationMailer < ActionMailer::Base
default from: "noreply@larplibrary.org"
layout 'mailer'
end
|
Update React Native documentation (0.33) | module Docs
class ReactNative < React
self.name = 'React Native'
self.slug = 'react_native'
self.type = 'react'
self.release = '0.32'
self.base_url = 'https://facebook.github.io/react-native/docs/'
self.root_path = 'getting-started.html'
self.links = {
home: 'https://facebook.github.io/react-native/',
code: 'https://github.com/facebook/react-native'
}
html_filters.push 'react_native/clean_html'
options[:root_title] = 'React Native Documentation'
options[:only_patterns] = nil
options[:skip_patterns] = [/\Asample\-/]
options[:skip] = %w(
videos.html
transforms.html
troubleshooting.html
more-resources.html
)
options[:fix_urls] = ->(url) {
url.sub! 'docs/docs', 'docs'
url
}
options[:attribution] = <<-HTML
© 2016 Facebook Inc.<br>
Licensed under the Creative Commons Attribution 4.0 International Public License.
HTML
end
end
| module Docs
class ReactNative < React
self.name = 'React Native'
self.slug = 'react_native'
self.type = 'react'
self.release = '0.33'
self.base_url = 'https://facebook.github.io/react-native/docs/'
self.root_path = 'getting-started.html'
self.links = {
home: 'https://facebook.github.io/react-native/',
code: 'https://github.com/facebook/react-native'
}
html_filters.push 'react_native/clean_html'
options[:root_title] = 'React Native Documentation'
options[:only_patterns] = nil
options[:skip_patterns] = [/\Asample\-/]
options[:skip] = %w(
videos.html
transforms.html
troubleshooting.html
more-resources.html
)
options[:fix_urls] = ->(url) {
url.sub! 'docs/docs', 'docs'
url
}
options[:attribution] = <<-HTML
© 2016 Facebook Inc.<br>
Licensed under the Creative Commons Attribution 4.0 International Public License.
HTML
end
end
|
Update default drawing tool, config var. | # First portal listed is the "Default Authentication Portal"
ENV['CONCORD_CONFIGURED_PORTALS'] ||= 'LOCALHOST HAS_STAGING'
ENV['CONCORD_LOCALHOST_URL'] ||= 'http://localhost:9000/'
ENV['CONCORD_LOCALHOST_CLIENT_ID'] ||= 'localhost'
ENV['CONCORD_LOCALHOST_CLIENT_SECRET'] ||= 'XXXXXX'
ENV['CONCORD_HAS_STAGING_URL'] ||= 'http://has.staging.concord.org/'
ENV['CONCORD_HAS_STAGING_CLIENT_ID'] ||= 'localhost'
ENV['CONCORD_HAS_STAGING_CLIENT_SECRET'] ||= 'XXXXXX'
ENV['CONCORD_HAS_STAGING_DISPLAY_NAME'] ||= 'Has Staging Portal' # Optional param
# Decides whether SVG Edit ('svg-edit' or undefined) or CC Drawing Tool ('drawing-tool') should be used.
ENV['CONCORD_DRAWING_TOOL'] ||= 'svg-edit'
ENV['SECRET_TOKEN'] ||= 'use `rake secret` to generate'
ENV['S3_KEY'] ||= 'xxxxxxxxxxxxx'
ENV['S3_SECRET'] ||= 'xxxxxxxxxxxxx'
ENV['S3_BIN'] ||= 'ccshutterbug'
| # First portal listed is the "Default Authentication Portal"
ENV['CONCORD_CONFIGURED_PORTALS'] ||= 'LOCALHOST HAS_STAGING'
ENV['CONCORD_LOCALHOST_URL'] ||= 'http://localhost:9000/'
ENV['CONCORD_LOCALHOST_CLIENT_ID'] ||= 'localhost'
ENV['CONCORD_LOCALHOST_CLIENT_SECRET'] ||= 'XXXXXX'
ENV['CONCORD_HAS_STAGING_URL'] ||= 'http://has.staging.concord.org/'
ENV['CONCORD_HAS_STAGING_CLIENT_ID'] ||= 'localhost'
ENV['CONCORD_HAS_STAGING_CLIENT_SECRET'] ||= 'XXXXXX'
ENV['CONCORD_HAS_STAGING_DISPLAY_NAME'] ||= 'Has Staging Portal' # Optional param
# Decides whether SVG Edit ('svg-edit' or undefined) or CC Drawing Tool ('drawing-tool') should be used.
ENV['CONCORD_DRAWING_TOOL'] ||= 'drawing-tool'
ENV['SECRET_TOKEN'] ||= 'use `rake secret` to generate'
ENV['S3_KEY'] ||= 'xxxxxxxxxxxxx'
ENV['S3_SECRET'] ||= 'xxxxxxxxxxxxx'
ENV['S3_BIN'] ||= 'ccshutterbug'
|
Add a test for mark/cut, based on the find_boxes example. | require "test/unit"
require "ambit"
class TestAmbit < Test::Unit::TestCase
def test_simple_default
x = Ambit::choose([1, 2])
Ambit::require x.even?
assert(x == 2)
Ambit::clear!
end
def test_simple_private
nd = Ambit::Generator.new
x = nd.choose([1, 2])
nd.require x.even?
assert(x == 2)
end
def test_nested_default
a = Ambit::choose(0..5)
b = Ambit::choose(0..5)
Ambit::fail! unless a + b == 7
assert(a+b == 7)
Ambit::clear!
end
def test_nested_private
nd = Ambit::Generator.new
a = nd.choose(0..5)
b = nd.choose(0..5)
nd.fail! unless a + b == 7
assert(a+b == 7)
nd.clear!
end
def test_toplevel_fail
assert_raise Ambit::ChoicesExhausted do
Ambit::fail!
end
end
end
| require "test/unit"
require "ambit"
class TestAmbit < Test::Unit::TestCase
def test_simple_default
x = Ambit::choose([1, 2])
Ambit::require x.even?
assert(x == 2)
Ambit::clear!
end
def test_simple_private
nd = Ambit::Generator.new
x = nd.choose([1, 2])
nd.require x.even?
assert(x == 2)
end
def test_nested_default
a = Ambit::choose(0..5)
b = Ambit::choose(0..5)
Ambit::fail! unless a + b == 7
assert(a+b == 7)
Ambit::clear!
end
def test_nested_private
nd = Ambit::Generator.new
a = nd.choose(0..5)
b = nd.choose(0..5)
nd.fail! unless a + b == 7
assert(a+b == 7)
nd.clear!
end
def test_toplevel_fail
assert_raise Ambit::ChoicesExhausted do
Ambit::fail!
end
end
def test_mark_cut
nd = Ambit::Generator.new
i = 0;
a = nd.choose(1..3)
nd.mark
b = nd.choose([1, 2, 3])
c = nd.choose([1, 2, 3])
i+=1
if b == 2 && c == 2
nd.cut!
end
nd.fail!
rescue Ambit::ChoicesExhausted
assert(i==15)
end
end
|
Add libghc-zlib-dev to list of pre-installed packages | #
# Cookbook Name:: et_fog
# Recipe:: default
#
# Copyright (C) 2013 EverTrue, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
if platform_family?('debian')
include_recipe 'apt'
resources(execute: 'apt-get update').run_action(:run)
end
include_recipe 'build-essential'
include_recipe 'git'
# Dependencies required by nokogiri (for fog)
%w(libxslt-dev libxml2-dev).each do |pkg|
c_pkg = package(pkg)
c_pkg.run_action(:install)
end
# TODO: Remove this once the gem_hell cookbook is ready to roll
%w(
unf
fog
).each do |pkg|
g = chef_gem pkg do
action :nothing
end
g.run_action(:install)
end
| #
# Cookbook Name:: et_fog
# Recipe:: default
#
# Copyright (C) 2013 EverTrue, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
if platform_family?('debian')
include_recipe 'apt'
resources(execute: 'apt-get update').run_action(:run)
end
include_recipe 'build-essential'
include_recipe 'git'
# Dependencies required by nokogiri (for fog)
%w(libxslt-dev libxml2-dev libghc-zlib-dev).each do |pkg|
c_pkg = package(pkg)
c_pkg.run_action(:install)
end
# TODO: Remove this once the gem_hell cookbook is ready to roll
%w(
unf
fog
).each do |pkg|
g = chef_gem pkg do
action :nothing
end
g.run_action(:install)
end
|
Add `attained_level_title` to Dataset show method | xml.instruct! :xml, :version => "1.0"
xml.feed :xmlns => "http://www.w3.org/2005/Atom", "xmlns:dc" => "http://purl.org/dc/elements/1.1/" do
xml.author do
xml.name @dataset.user_full_name
end
xml.updated DateTime.parse(@dataset.updated_at.to_s).rfc3339
xml.id dataset_url(@dataset, format: :feed)
xml.title @dataset.title
xml.link :href=> @dataset.documentation_url, :rel => "self"
@dataset.certificates.where(published: true).by_newest.each do |certificate|
xml.entry do
xml.link :href=> dataset_certificate_url(@dataset, certificate)
xml.title certificate.name
xml.content certificate.attained_level
xml.updated DateTime.parse(certificate.updated_at.to_s).rfc3339
xml.id dataset_certificate_url(@dataset, certificate)
end
end
end | xml.instruct! :xml, :version => "1.0"
xml.feed :xmlns => "http://www.w3.org/2005/Atom", "xmlns:dc" => "http://purl.org/dc/elements/1.1/" do
xml.author do
xml.name @dataset.user_full_name
end
xml.updated DateTime.parse(@dataset.updated_at.to_s).rfc3339
xml.id dataset_url(@dataset, format: :feed)
xml.title @dataset.title
xml.link :href=> @dataset.documentation_url, :rel => "self"
@dataset.certificates.where(published: true).by_newest.each do |certificate|
xml.entry do
xml.link :href=> dataset_certificate_url(@dataset, certificate)
xml.title certificate.name
xml.content certificate.attained_level_title
xml.updated DateTime.parse(certificate.updated_at.to_s).rfc3339
xml.id dataset_certificate_url(@dataset, certificate)
end
end
end |
Add a spec for GithubPullRequestFormatter | require 'spec_helper'
module Pronto
module Formatter
describe GithubPullRequestFormatter do
let(:formatter) { described_class.new }
let(:repo) { Pronto::Git::Repository.new('spec/fixtures/test.git') }
describe '#format' do
subject { formatter.format(messages, repo) }
let(:messages) { [message, message] }
let(:message) { Message.new(patch.new_file_full_path, line, :warning, 'crucial') }
let(:patch) { repo.show_commit('64dadfd').first }
let(:line) { patch.added_lines.first }
specify do
ENV['PULL_REQUEST_ID'] = '10'
Octokit::Client.any_instance
.should_receive(:pull_comments)
.once
.and_return([])
Octokit::Client.any_instance
.should_receive(:create_pull_comment)
.once
subject
end
end
end
end
end
| |
Update the link to the download page. | module DocumentationHelper
def render_plugin_doc(file)
if File.directory?(file)
if File.exists?(file + '/README')
render :inline => markup(File.read(file + '/README'))
else
render :text => "this plugin has no README", :layout => false
end
elsif File.exists?(file)
render :inline => markup(comments(File.read(file)))
end
end
def markup(text)
RedCloth.new(text).to_html
end
def comments(text)
text = text.gsub(/^[^#].*$\n?/, '').gsub(/^# ?/, '').strip
text.empty? ? 'this plugin has no comments' : text
end
def link_to_download(text)
link_to text, "http://rubyforge.org/frs/?group_id=2918"
end
def link_to_users_mailing_list(text)
link_to text, "http://rubyforge.org/mailman/listinfo/cruisecontrolrb-users"
end
def link_to_developers_mailing_list(text)
link_to text, "http://rubyforge.org/mailman/listinfo/cruisecontrolrb-developers"
end
def link_to_issue_tracker(text)
link_to text, 'https://github.com/thoughtworks/cruisecontrol.rb/issues'
end
def link_to_issue_tracker_signup(text)
link_to text, 'https://github.com/signup/free'
end
end
| module DocumentationHelper
def render_plugin_doc(file)
if File.directory?(file)
if File.exists?(file + '/README')
render :inline => markup(File.read(file + '/README'))
else
render :text => "this plugin has no README", :layout => false
end
elsif File.exists?(file)
render :inline => markup(comments(File.read(file)))
end
end
def markup(text)
RedCloth.new(text).to_html
end
def comments(text)
text = text.gsub(/^[^#].*$\n?/, '').gsub(/^# ?/, '').strip
text.empty? ? 'this plugin has no comments' : text
end
def link_to_download(text)
link_to text, "https://github.com/thoughtworks/cruisecontrol.rb/downloads"
end
def link_to_users_mailing_list(text)
link_to text, "http://rubyforge.org/mailman/listinfo/cruisecontrolrb-users"
end
def link_to_developers_mailing_list(text)
link_to text, "http://rubyforge.org/mailman/listinfo/cruisecontrolrb-developers"
end
def link_to_issue_tracker(text)
link_to text, 'https://github.com/thoughtworks/cruisecontrol.rb/issues'
end
def link_to_issue_tracker_signup(text)
link_to text, 'https://github.com/signup/free'
end
end
|
Allow Tag creation on partial match | class Tag < ApplicationRecord
extend FriendlyId
has_many :articles_tags, dependent: :destroy
has_many :articles, through: :articles_tags, counter_cache: :articles_count
validates :name, uniqueness: { case_sensitive: false }
friendly_id :name
def to_s
name
end
def to_param
slug
end
def self.tokens(query)
tags = where(%Q["tags"."name" ILIKE ?], "%#{query}%")
if tags.empty?
[{id: "<<<#{query}>>>", name: "New: \"#{query}\""}]
else
tags.collect{ |t| Hash["id" => t.id, "name" => t.name] }
end
end
def self.ids_from_tokens(tokens)
tokens.gsub!(/<<<(.+?)>>>/) { create!(name: $1).id }
tokens.split(',')
end
def self.by_article_count
order(articles_count: :desc)
end
def self.reset_articles_count
pluck(:id).each do |tag_id|
reset_counters(tag_id, :articles)
end
end
end
| class Tag < ApplicationRecord
extend FriendlyId
has_many :articles_tags, dependent: :destroy
has_many :articles, through: :articles_tags, counter_cache: :articles_count
validates :name, uniqueness: { case_sensitive: false }
friendly_id :name
def to_s
name
end
def to_param
slug
end
def self.tokens(query)
tags = where(%Q["tags"."name" ILIKE ?], "%#{query}%")
new_tag = {id: "<<<#{query}>>>", name: "New: \"#{query}\""}
if tags.empty?
[new_tag]
else
results = tags.collect{ |t| Hash["id" => t.id, "name" => t.name] }
results.unshift(new_tag) if tags.select{|t| t.name.downcase == query.downcase}.empty?
results
end
end
def self.ids_from_tokens(tokens)
tokens.gsub!(/<<<(.+?)>>>/) { create!(name: $1).id }
tokens.split(',')
end
def self.by_article_count
order(articles_count: :desc)
end
def self.reset_articles_count
pluck(:id).each do |tag_id|
reset_counters(tag_id, :articles)
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.