CombinedText stringlengths 4 3.42M |
|---|
# frozen_string_literal: true
lib = File.expand_path("lib", __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "roadie/rails/version"
Gem::Specification.new do |spec|
spec.name = "roadie-rails"
spec.version = Roadie::Rails::VERSION
spec.authors = ["Magnus Bergmark"]
spec.email = ["magnus.bergmark@gmail.com"]
spec.homepage = "http://github.com/Mange/roadie-rails"
spec.summary = "Making HTML emails comfortable for the Rails rockstars"
spec.description = "Hooks Roadie into your Rails application to help with email generation."
spec.license = "MIT"
spec.required_ruby_version = ">= 2.5"
spec.files = `git ls-files | grep -v ^spec`.split($INPUT_RECORD_SEPARATOR)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.extra_rdoc_files = %w[README.md Changelog.md LICENSE.txt]
spec.require_paths = ["lib"]
spec.add_dependency "railties", ">= 5.1", "< 7.0"
spec.add_dependency "roadie", ">= 3.1", "< 5.0"
spec.add_development_dependency "bundler", "~> 2.2"
spec.add_development_dependency "rails", ">= 5.1", "< 7.0"
spec.add_development_dependency "rspec", "~> 3.10"
spec.add_development_dependency "rspec-collection_matchers"
spec.add_development_dependency "rspec-rails"
end
Loosen Rails requirement to allow for bundling with Rails 7
# frozen_string_literal: true
lib = File.expand_path("lib", __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "roadie/rails/version"
Gem::Specification.new do |spec|
spec.name = "roadie-rails"
spec.version = Roadie::Rails::VERSION
spec.authors = ["Magnus Bergmark"]
spec.email = ["magnus.bergmark@gmail.com"]
spec.homepage = "http://github.com/Mange/roadie-rails"
spec.summary = "Making HTML emails comfortable for the Rails rockstars"
spec.description = "Hooks Roadie into your Rails application to help with email generation."
spec.license = "MIT"
spec.required_ruby_version = ">= 2.5"
spec.files = `git ls-files | grep -v ^spec`.split($INPUT_RECORD_SEPARATOR)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.extra_rdoc_files = %w[README.md Changelog.md LICENSE.txt]
spec.require_paths = ["lib"]
spec.add_dependency "railties", ">= 5.1", "< 7.1"
spec.add_dependency "roadie", ">= 3.1", "< 5.0"
spec.add_development_dependency "bundler", "~> 2.2"
spec.add_development_dependency "rails", ">= 5.1", "< 7.1"
spec.add_development_dependency "rspec", "~> 3.10"
spec.add_development_dependency "rspec-collection_matchers"
spec.add_development_dependency "rspec-rails"
end
|
add Dijkstra Algorithm implementation
module SearchRouteAlgorithms
# Dijkstra Algorithm implementation
module Dijkstra
# Edge class implementation
class Edge
attr_accessor :src, :dst, :length
def initialize(src, dst, length = 1)
@src = src
@dst = dst
@length = length
end
end
# Graph class implementation
class Graph < Array
attr_reader :edges
def initialize
@edges = []
end
def connect(src, dst, length = 1)
raise ArgumentError, "No such vertex: #{src}" unless include?(src)
raise ArgumentError, "No such vertex: #{dst}" unless include?(dst)
@edges.push Edge.new(src, dst, length)
end
def neighbors(vertex)
neighbors = []
@edges.each do |edge|
neighbors.push edge.dst if edge.src == vertex
end
neighbors.uniq
end
def length_between(src, dst)
@edges.each do |edge|
return edge.length if edge.src == src && edge.dst == dst
end
nil
end
def dijkstra(src, dst = nil)
distances = {}
previouses = {}
each do |vertex|
distances[vertex] = nil # Infinity
previouses[vertex] = nil
end
distances[src] = 0
vertices = clone
until vertices.empty?
nearest_vertex = vertices.inject do |a, b|
next b unless distances[a]
next a unless distances[b]
next a if distances[a] < distances[b]
b
end
break unless distances[nearest_vertex] # Infinity
return distances[dst] if dst && nearest_vertex == dst
neighbors = vertices.neighbors(nearest_vertex)
neighbors.each do |vertex|
alt = distances[nearest_vertex] +
vertices.length_between(nearest_vertex, vertex)
if distances[vertex].nil? || alt < distances[vertex]
distances[vertex] = alt
previouses[vertices] = nearest_vertex
# decrease-key v in Q # ???
end
end
vertices.delete nearest_vertex
end
dst ? nil : distances
end
end
end
end
|
module Trinidad
module Sandbox
module Helpers
module Auth
require 'sinatra/authorization'
include Sinatra::Authorization
def authorize(user, pass)
user == sandbox_username && pass == sandbox_password
end
def authorized?
sandbox_username && sandbox_password ? request.env['REMOTE_USER'] && !request.env['REMOTE_USER'].empty? : true
end
def authorization_realm; "Trinidad's sandbox"; end
private
def sandbox_username
@sandbox_username ||= $servlet_context.getAttribute('sandbox_username')
end
def sandbox_password
@sandbox_password ||= $servlet_context.getAttribute('sandbox_password')
end
end
module Context
def sandbox_context
@sandbox_context ||= $servlet_context.getAttribute('sandbox_context')
end
def context_not_found(name)
flash[:warning] = "application not found: #{name}"
$servlet_context.log "application not found: #{name}"
respond_to_home 404
end
def repo_not_found
message = "the git repository is a mandatory parameter"
flash[:warning] = message
$servlet_context.log message
respond_to_home 400
end
def host
$servlet_context.getAttribute('tomcat_host')
end
def redirect_to_home(status_code)
respond_to do |wants|
wants.html { redirect sandbox_context.path }
wants.xml { status status_code }
end
end
end
end
end
end
fix method name
module Trinidad
module Sandbox
module Helpers
module Auth
require 'sinatra/authorization'
include Sinatra::Authorization
def authorize(user, pass)
user == sandbox_username && pass == sandbox_password
end
def authorized?
sandbox_username && sandbox_password ? request.env['REMOTE_USER'] && !request.env['REMOTE_USER'].empty? : true
end
def authorization_realm; "Trinidad's sandbox"; end
private
def sandbox_username
@sandbox_username ||= $servlet_context.getAttribute('sandbox_username')
end
def sandbox_password
@sandbox_password ||= $servlet_context.getAttribute('sandbox_password')
end
end
module Context
def sandbox_context
@sandbox_context ||= $servlet_context.getAttribute('sandbox_context')
end
def context_not_found(name)
flash[:warning] = "application not found: #{name}"
$servlet_context.log "application not found: #{name}"
redirect_to_home 404
end
def repo_not_found
message = "the git repository is a mandatory parameter"
flash[:warning] = message
$servlet_context.log message
redirect_to_home 400
end
def host
$servlet_context.getAttribute('tomcat_host')
end
def redirect_to_home(status_code)
respond_to do |wants|
wants.html { redirect sandbox_context.path }
wants.xml { status status_code }
end
end
end
end
end
end
|
class Contact
include ActiveModel::Conversion
attr_accessor :id, :name, :age, :created_at, :awesome, :preferences
def social
%w(twitter github)
end
def network
{:git => :github}
end
def initialize(options = {})
options.each { |name, value| send("#{name}=", value) }
end
def pseudonyms
nil
end
def persisted?
id
end
end
fix failing isolated tests
class Contact
extend ActiveModel::Naming
include ActiveModel::Conversion
attr_accessor :id, :name, :age, :created_at, :awesome, :preferences
def social
%w(twitter github)
end
def network
{:git => :github}
end
def initialize(options = {})
options.each { |name, value| send("#{name}=", value) }
end
def pseudonyms
nil
end
def persisted?
id
end
end
|
require 'rubygems'
gem 'dm-core', '=0.9.4'
require 'dm-core'
module DataMapper
module Timestamp
TIMESTAMP_PROPERTIES = {
:updated_at => lambda { |r| r.updated_at = DateTime.now },
:updated_on => lambda { |r| r.updated_on = Date.today },
:created_at => lambda { |r| r.created_at = DateTime.now if r.new_record? && r.created_at.nil? },
:created_on => lambda { |r| r.created_on = Date.today if r.new_record? && r.created_on.nil?},
}
def self.included(model)
model.before :save, :set_timestamp_properties
end
private
def set_timestamp_properties
if dirty?
self.class.properties.slice(*TIMESTAMP_PROPERTIES.keys).compact.each do |property|
TIMESTAMP_PROPERTIES[property.name][self]
end
end
end
end # module Timestamp
Resource::append_inclusions Timestamp
end
dm-timestamps: do not modify dirty attributes
require 'rubygems'
gem 'dm-core', '=0.9.4'
require 'dm-core'
module DataMapper
module Timestamp
TIMESTAMP_PROPERTIES = {
:updated_at => lambda { |r| r.updated_at = DateTime.now },
:updated_on => lambda { |r| r.updated_on = Date.today },
:created_at => lambda { |r| r.created_at = DateTime.now if r.new_record? && r.created_at.nil? },
:created_on => lambda { |r| r.created_on = Date.today if r.new_record? && r.created_on.nil?},
}
def self.included(model)
model.before :save, :set_timestamp_properties
end
private
def set_timestamp_properties
if dirty?
self.class.properties.slice(*TIMESTAMP_PROPERTIES.keys).compact.each do |property|
TIMESTAMP_PROPERTIES[property.name][self] unless attribute_dirty?(property.name)
end
end
end
end # module Timestamp
Resource::append_inclusions Timestamp
end
|
require 'database_cleaner'
DatabaseCleaner.clean_with :truncation
puts "Creating Settings"
Setting.create(key: 'official_level_1_name', value: 'Empleados públicos')
Setting.create(key: 'official_level_2_name', value: 'Organización Municipal')
Setting.create(key: 'official_level_3_name', value: 'Directores generales')
Setting.create(key: 'official_level_4_name', value: 'Concejales')
Setting.create(key: 'official_level_5_name', value: 'Alcaldesa')
Setting.create(key: 'max_ratio_anon_votes_on_debates', value: '50')
Setting.create(key: 'max_votes_for_debate_edit', value: '1000')
Setting.create(key: 'max_votes_for_proposal_edit', value: '1000')
Setting.create(key: 'proposal_code_prefix', value: 'MAD')
Setting.create(key: 'votes_for_proposal_success', value: '100')
Setting.create(key: 'months_to_archive_proposals', value: '12')
Setting.create(key: 'comments_body_max_length', value: '1000')
Setting.create(key: 'twitter_handle', value: '@consul_dev')
Setting.create(key: 'twitter_hashtag', value: '#consul_dev')
Setting.create(key: 'facebook_handle', value: 'consul')
Setting.create(key: 'youtube_handle', value: 'consul')
Setting.create(key: 'blog_url', value: '/blog')
Setting.create(key: 'url', value: 'http://localhost:3000')
Setting.create(key: 'org_name', value: 'Consul')
Setting.create(key: 'place_name', value: 'City')
Setting.create(key: 'feature.debates', value: "true")
Setting.create(key: 'feature.spending_proposals', value: "true")
Setting.create(key: 'feature.spending_proposal_features.voting_allowed', value: "true")
Setting.create(key: 'feature.twitter_login', value: "true")
Setting.create(key: 'feature.facebook_login', value: "true")
Setting.create(key: 'feature.google_login', value: "true")
Setting.create(key: 'per_page_code', value: "")
Setting.create(key: 'comments_body_max_length', value: '1000')
puts "Creating Geozones"
('A'..'Z').each{ |i| Geozone.create(name: "District #{i}") }
puts "Creating Users"
def create_user(email, username = Faker::Name.name)
pwd = '12345678'
puts " #{username}"
User.create!(username: username, email: email, password: pwd, password_confirmation: pwd, confirmed_at: Time.now, terms_of_service: "1")
end
admin = create_user('admin@consul.dev', 'admin')
admin.create_administrator
moderator = create_user('mod@consul.dev', 'mod')
moderator.create_moderator
valuator = create_user('valuator@consul.dev', 'valuator')
valuator.create_valuator
level_2 = create_user('leveltwo@consul.dev', 'level 2')
level_2.update(residence_verified_at: Time.now, confirmed_phone: Faker::PhoneNumber.phone_number, document_number: "2222222222", document_type: "1" )
verified = create_user('verified@consul.dev', 'verified')
verified.update(residence_verified_at: Time.now, confirmed_phone: Faker::PhoneNumber.phone_number, document_type: "1", verified_at: Time.now, document_number: "3333333333")
(1..10).each do |i|
org_name = Faker::Company.name
org_user = create_user("org#{i}@consul.dev", org_name)
org_responsible_name = Faker::Name.name
org = org_user.create_organization(name: org_name, responsible_name: org_responsible_name)
verified = [true, false].sample
if verified then
org.verify
else
org.reject
end
end
(1..5).each do |i|
official = create_user("official#{i}@consul.dev")
official.update(official_level: i, official_position: "Official position #{i}")
end
(1..40).each do |i|
user = create_user("user#{i}@consul.dev")
level = [1,2,3].sample
if level >= 2 then
user.update(residence_verified_at: Time.now, confirmed_phone: Faker::PhoneNumber.phone_number, document_number: Faker::Number.number(10), document_type: "1" )
end
if level == 3 then
user.update(verified_at: Time.now, document_number: Faker::Number.number(10) )
end
end
org_user_ids = User.organizations.pluck(:id)
not_org_users = User.where(['users.id NOT IN(?)', org_user_ids])
puts "Creating Tags Categories"
ActsAsTaggableOn::Tag.create!(name: "Asociaciones", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Cultura", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Deportes", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Derechos Sociales", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Economía", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Empleo", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Equidad", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Sostenibilidad", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Participación", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Movilidad", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Medios", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Salud", featured: true , kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Transparencia", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Seguridad y Emergencias", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Medio Ambiente", featured: true, kind: "category")
puts "Creating Debates"
tags = Faker::Lorem.words(25)
(1..30).each do |i|
author = User.reorder("RANDOM()").first
description = "<p>#{Faker::Lorem.paragraphs.join('</p><p>')}</p>"
debate = Debate.create!(author: author,
title: Faker::Lorem.sentence(3).truncate(60),
created_at: rand((Time.now - 1.week) .. Time.now),
description: description,
tag_list: tags.sample(3).join(','),
geozone: Geozone.reorder("RANDOM()").first,
terms_of_service: "1")
puts " #{debate.title}"
end
tags = ActsAsTaggableOn::Tag.where(kind: 'category')
(1..30).each do |i|
author = User.reorder("RANDOM()").first
description = "<p>#{Faker::Lorem.paragraphs.join('</p><p>')}</p>"
debate = Debate.create!(author: author,
title: Faker::Lorem.sentence(3).truncate(60),
created_at: rand((Time.now - 1.week) .. Time.now),
description: description,
tag_list: tags.sample(3).join(','),
geozone: Geozone.reorder("RANDOM()").first,
terms_of_service: "1")
puts " #{debate.title}"
end
puts "Creating Proposals"
tags = Faker::Lorem.words(25)
(1..30).each do |i|
author = User.reorder("RANDOM()").first
description = "<p>#{Faker::Lorem.paragraphs.join('</p><p>')}</p>"
proposal = Proposal.create!(author: author,
title: Faker::Lorem.sentence(3).truncate(60),
question: Faker::Lorem.sentence(3) + "?",
summary: Faker::Lorem.sentence(3),
responsible_name: Faker::Name.name,
external_url: Faker::Internet.url,
description: description,
created_at: rand((Time.now - 1.week) .. Time.now),
tag_list: tags.sample(3).join(','),
geozone: Geozone.reorder("RANDOM()").first,
terms_of_service: "1")
puts " #{proposal.title}"
end
puts "Creating Archived Proposals"
tags = Faker::Lorem.words(25)
(1..5).each do |i|
author = User.reorder("RANDOM()").first
description = "<p>#{Faker::Lorem.paragraphs.join('</p><p>')}</p>"
proposal = Proposal.create!(author: author,
title: Faker::Lorem.sentence(3).truncate(60),
question: Faker::Lorem.sentence(3) + "?",
summary: Faker::Lorem.sentence(3),
responsible_name: Faker::Name.name,
external_url: Faker::Internet.url,
description: description,
created_at: rand((Time.now - 1.week) .. Time.now),
tag_list: tags.sample(3).join(','),
geozone: Geozone.reorder("RANDOM()").first,
terms_of_service: "1",
created_at: Setting["months_to_archive_proposals"].to_i.months.ago)
puts " #{proposal.title}"
end
tags = ActsAsTaggableOn::Tag.where(kind: 'category')
(1..30).each do |i|
author = User.reorder("RANDOM()").first
description = "<p>#{Faker::Lorem.paragraphs.join('</p><p>')}</p>"
proposal = Proposal.create!(author: author,
title: Faker::Lorem.sentence(3).truncate(60),
question: Faker::Lorem.sentence(3) + "?",
summary: Faker::Lorem.sentence(3),
responsible_name: Faker::Name.name,
external_url: Faker::Internet.url,
description: description,
created_at: rand((Time.now - 1.week) .. Time.now),
tag_list: tags.sample(3).join(','),
geozone: Geozone.reorder("RANDOM()").first,
terms_of_service: "1")
puts " #{proposal.title}"
end
puts "Commenting Debates"
(1..100).each do |i|
author = User.reorder("RANDOM()").first
debate = Debate.reorder("RANDOM()").first
Comment.create!(user: author,
created_at: rand(debate.created_at .. Time.now),
commentable: debate,
body: Faker::Lorem.sentence)
end
puts "Commenting Proposals"
(1..100).each do |i|
author = User.reorder("RANDOM()").first
proposal = Proposal.reorder("RANDOM()").first
Comment.create!(user: author,
created_at: rand(proposal.created_at .. Time.now),
commentable: proposal,
body: Faker::Lorem.sentence)
end
puts "Commenting Comments"
(1..200).each do |i|
author = User.reorder("RANDOM()").first
parent = Comment.reorder("RANDOM()").first
Comment.create!(user: author,
created_at: rand(parent.created_at .. Time.now),
commentable_id: parent.commentable_id,
commentable_type: parent.commentable_type,
body: Faker::Lorem.sentence,
parent: parent)
end
puts "Voting Debates, Proposals & Comments"
(1..100).each do |i|
voter = not_org_users.reorder("RANDOM()").first
vote = [true, false].sample
debate = Debate.reorder("RANDOM()").first
debate.vote_by(voter: voter, vote: vote)
end
(1..100).each do |i|
voter = not_org_users.reorder("RANDOM()").first
vote = [true, false].sample
comment = Comment.reorder("RANDOM()").first
comment.vote_by(voter: voter, vote: vote)
end
(1..100).each do |i|
voter = User.level_two_or_three_verified.reorder("RANDOM()").first
proposal = Proposal.reorder("RANDOM()").first
proposal.vote_by(voter: voter, vote: true)
end
puts "Flagging Debates & Comments"
(1..40).each do |i|
debate = Debate.reorder("RANDOM()").first
flagger = User.where(["users.id <> ?", debate.author_id]).reorder("RANDOM()").first
Flag.flag(flagger, debate)
end
(1..40).each do |i|
comment = Comment.reorder("RANDOM()").first
flagger = User.where(["users.id <> ?", comment.user_id]).reorder("RANDOM()").first
Flag.flag(flagger, comment)
end
(1..40).each do |i|
proposal = Proposal.reorder("RANDOM()").first
flagger = User.where(["users.id <> ?", proposal.author_id]).reorder("RANDOM()").first
Flag.flag(flagger, proposal)
end
puts "Creating Spending Proposals"
tags = Faker::Lorem.words(10)
(1..60).each do |i|
geozone = Geozone.reorder("RANDOM()").first
author = User.reorder("RANDOM()").first
description = "<p>#{Faker::Lorem.paragraphs.join('</p><p>')}</p>"
feasible_explanation = "<p>#{Faker::Lorem.paragraphs.join('</p><p>')}</p>"
valuation_finished = [true, false].sample
feasible = [true, false].sample
spending_proposal = SpendingProposal.create!(author: author,
title: Faker::Lorem.sentence(3).truncate(60),
external_url: Faker::Internet.url,
description: description,
created_at: rand((Time.now - 1.week) .. Time.now),
geozone: [geozone, nil].sample,
feasible: feasible,
feasible_explanation: feasible_explanation,
valuation_finished: valuation_finished,
tag_list: tags.sample(3).join(','),
price: rand(1000000),
terms_of_service: "1")
puts " #{spending_proposal.title}"
end
puts "Creating Valuation Assignments"
(1..17).to_a.sample.times do
SpendingProposal.reorder("RANDOM()").first.valuators << valuator.valuator
end
puts "Creating Legislation"
Legislation.create!(title: 'Participatory Democracy', body: 'In order to achieve...')
puts "Ignoring flags in Debates, comments & proposals"
Debate.flagged.reorder("RANDOM()").limit(10).each(&:ignore_flag)
Comment.flagged.reorder("RANDOM()").limit(30).each(&:ignore_flag)
Proposal.flagged.reorder("RANDOM()").limit(10).each(&:ignore_flag)
puts "Hiding debates, comments & proposals"
Comment.with_hidden.flagged.reorder("RANDOM()").limit(30).each(&:hide)
Debate.with_hidden.flagged.reorder("RANDOM()").limit(5).each(&:hide)
Proposal.with_hidden.flagged.reorder("RANDOM()").limit(10).each(&:hide)
puts "Confirming hiding in debates, comments & proposals"
Comment.only_hidden.flagged.reorder("RANDOM()").limit(10).each(&:confirm_hide)
Debate.only_hidden.flagged.reorder("RANDOM()").limit(5).each(&:confirm_hide)
Proposal.only_hidden.flagged.reorder("RANDOM()").limit(5).each(&:confirm_hide)
puts "Creating banners"
Proposal.last(3).each do |proposal|
title = Faker::Lorem.sentence(word_count = 3)
description = Faker::Lorem.sentence(word_count = 12)
banner = Banner.create!(title: title,
description: description,
style: ["banner-style banner-style-one", "banner-style banner-style-two",
"banner-style banner-style-three"].sample,
image: ["banner-img banner-img-one", "banner-img banner-img-two",
"banner-img banner-img-three"].sample,
target_url: Rails.application.routes.url_helpers.proposal_path(proposal),
post_started_at: rand((Time.now - 1.week) .. (Time.now - 1.day)),
post_ended_at: rand((Time.now - 1.day) .. (Time.now + 1.week)),
created_at: rand((Time.now - 1.week) .. Time.now))
puts " #{banner.title}"
end
updates dev_seeds with polls
require 'database_cleaner'
DatabaseCleaner.clean_with :truncation
puts "Creating Settings"
Setting.create(key: 'official_level_1_name', value: 'Empleados públicos')
Setting.create(key: 'official_level_2_name', value: 'Organización Municipal')
Setting.create(key: 'official_level_3_name', value: 'Directores generales')
Setting.create(key: 'official_level_4_name', value: 'Concejales')
Setting.create(key: 'official_level_5_name', value: 'Alcaldesa')
Setting.create(key: 'max_ratio_anon_votes_on_debates', value: '50')
Setting.create(key: 'max_votes_for_debate_edit', value: '1000')
Setting.create(key: 'max_votes_for_proposal_edit', value: '1000')
Setting.create(key: 'proposal_code_prefix', value: 'MAD')
Setting.create(key: 'votes_for_proposal_success', value: '100')
Setting.create(key: 'months_to_archive_proposals', value: '12')
Setting.create(key: 'comments_body_max_length', value: '1000')
Setting.create(key: 'twitter_handle', value: '@consul_dev')
Setting.create(key: 'twitter_hashtag', value: '#consul_dev')
Setting.create(key: 'facebook_handle', value: 'consul')
Setting.create(key: 'youtube_handle', value: 'consul')
Setting.create(key: 'blog_url', value: '/blog')
Setting.create(key: 'url', value: 'http://localhost:3000')
Setting.create(key: 'org_name', value: 'Consul')
Setting.create(key: 'place_name', value: 'City')
Setting.create(key: 'feature.debates', value: "true")
Setting.create(key: 'feature.spending_proposals', value: "true")
Setting.create(key: 'feature.spending_proposal_features.voting_allowed', value: "true")
Setting.create(key: 'feature.twitter_login', value: "true")
Setting.create(key: 'feature.facebook_login', value: "true")
Setting.create(key: 'feature.google_login', value: "true")
Setting.create(key: 'per_page_code', value: "")
Setting.create(key: 'comments_body_max_length', value: '1000')
puts "Creating Geozones"
('A'..'Z').each{ |i| Geozone.create(name: "District #{i}") }
puts "Creating Users"
def create_user(email, username = Faker::Name.name)
pwd = '12345678'
puts " #{username}"
User.create!(username: username, email: email, password: pwd, password_confirmation: pwd, confirmed_at: Time.now, terms_of_service: "1")
end
admin = create_user('admin@consul.dev', 'admin')
admin.create_administrator
moderator = create_user('mod@consul.dev', 'mod')
moderator.create_moderator
valuator = create_user('valuator@consul.dev', 'valuator')
valuator.create_valuator
level_2 = create_user('leveltwo@consul.dev', 'level 2')
level_2.update(residence_verified_at: Time.now, confirmed_phone: Faker::PhoneNumber.phone_number, document_number: "2222222222", document_type: "1" )
verified = create_user('verified@consul.dev', 'verified')
verified.update(residence_verified_at: Time.now, confirmed_phone: Faker::PhoneNumber.phone_number, document_type: "1", verified_at: Time.now, document_number: "3333333333")
(1..10).each do |i|
org_name = Faker::Company.name
org_user = create_user("org#{i}@consul.dev", org_name)
org_responsible_name = Faker::Name.name
org = org_user.create_organization(name: org_name, responsible_name: org_responsible_name)
verified = [true, false].sample
if verified then
org.verify
else
org.reject
end
end
(1..5).each do |i|
official = create_user("official#{i}@consul.dev")
official.update(official_level: i, official_position: "Official position #{i}")
end
(1..40).each do |i|
user = create_user("user#{i}@consul.dev")
level = [1,2,3].sample
if level >= 2 then
user.update(residence_verified_at: Time.now, confirmed_phone: Faker::PhoneNumber.phone_number, document_number: Faker::Number.number(10), document_type: "1" )
end
if level == 3 then
user.update(verified_at: Time.now, document_number: Faker::Number.number(10) )
end
end
org_user_ids = User.organizations.pluck(:id)
not_org_users = User.where(['users.id NOT IN(?)', org_user_ids])
puts "Creating Tags Categories"
ActsAsTaggableOn::Tag.create!(name: "Asociaciones", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Cultura", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Deportes", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Derechos Sociales", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Economía", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Empleo", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Equidad", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Sostenibilidad", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Participación", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Movilidad", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Medios", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Salud", featured: true , kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Transparencia", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Seguridad y Emergencias", featured: true, kind: "category")
ActsAsTaggableOn::Tag.create!(name: "Medio Ambiente", featured: true, kind: "category")
puts "Creating Debates"
tags = Faker::Lorem.words(25)
(1..30).each do |i|
author = User.reorder("RANDOM()").first
description = "<p>#{Faker::Lorem.paragraphs.join('</p><p>')}</p>"
debate = Debate.create!(author: author,
title: Faker::Lorem.sentence(3).truncate(60),
created_at: rand((Time.now - 1.week) .. Time.now),
description: description,
tag_list: tags.sample(3).join(','),
geozone: Geozone.reorder("RANDOM()").first,
terms_of_service: "1")
puts " #{debate.title}"
end
tags = ActsAsTaggableOn::Tag.where(kind: 'category')
(1..30).each do |i|
author = User.reorder("RANDOM()").first
description = "<p>#{Faker::Lorem.paragraphs.join('</p><p>')}</p>"
debate = Debate.create!(author: author,
title: Faker::Lorem.sentence(3).truncate(60),
created_at: rand((Time.now - 1.week) .. Time.now),
description: description,
tag_list: tags.sample(3).join(','),
geozone: Geozone.reorder("RANDOM()").first,
terms_of_service: "1")
puts " #{debate.title}"
end
puts "Creating Proposals"
tags = Faker::Lorem.words(25)
(1..30).each do |i|
author = User.reorder("RANDOM()").first
description = "<p>#{Faker::Lorem.paragraphs.join('</p><p>')}</p>"
proposal = Proposal.create!(author: author,
title: Faker::Lorem.sentence(3).truncate(60),
question: Faker::Lorem.sentence(3) + "?",
summary: Faker::Lorem.sentence(3),
responsible_name: Faker::Name.name,
external_url: Faker::Internet.url,
description: description,
created_at: rand((Time.now - 1.week) .. Time.now),
tag_list: tags.sample(3).join(','),
geozone: Geozone.reorder("RANDOM()").first,
terms_of_service: "1")
puts " #{proposal.title}"
end
puts "Creating Archived Proposals"
tags = Faker::Lorem.words(25)
(1..5).each do |i|
author = User.reorder("RANDOM()").first
description = "<p>#{Faker::Lorem.paragraphs.join('</p><p>')}</p>"
proposal = Proposal.create!(author: author,
title: Faker::Lorem.sentence(3).truncate(60),
question: Faker::Lorem.sentence(3) + "?",
summary: Faker::Lorem.sentence(3),
responsible_name: Faker::Name.name,
external_url: Faker::Internet.url,
description: description,
created_at: rand((Time.now - 1.week) .. Time.now),
tag_list: tags.sample(3).join(','),
geozone: Geozone.reorder("RANDOM()").first,
terms_of_service: "1",
created_at: Setting["months_to_archive_proposals"].to_i.months.ago)
puts " #{proposal.title}"
end
tags = ActsAsTaggableOn::Tag.where(kind: 'category')
(1..30).each do |i|
author = User.reorder("RANDOM()").first
description = "<p>#{Faker::Lorem.paragraphs.join('</p><p>')}</p>"
proposal = Proposal.create!(author: author,
title: Faker::Lorem.sentence(3).truncate(60),
question: Faker::Lorem.sentence(3) + "?",
summary: Faker::Lorem.sentence(3),
responsible_name: Faker::Name.name,
external_url: Faker::Internet.url,
description: description,
created_at: rand((Time.now - 1.week) .. Time.now),
tag_list: tags.sample(3).join(','),
geozone: Geozone.reorder("RANDOM()").first,
terms_of_service: "1")
puts " #{proposal.title}"
end
puts "Commenting Debates"
(1..100).each do |i|
author = User.reorder("RANDOM()").first
debate = Debate.reorder("RANDOM()").first
Comment.create!(user: author,
created_at: rand(debate.created_at .. Time.now),
commentable: debate,
body: Faker::Lorem.sentence)
end
puts "Commenting Proposals"
(1..100).each do |i|
author = User.reorder("RANDOM()").first
proposal = Proposal.reorder("RANDOM()").first
Comment.create!(user: author,
created_at: rand(proposal.created_at .. Time.now),
commentable: proposal,
body: Faker::Lorem.sentence)
end
puts "Commenting Comments"
(1..200).each do |i|
author = User.reorder("RANDOM()").first
parent = Comment.reorder("RANDOM()").first
Comment.create!(user: author,
created_at: rand(parent.created_at .. Time.now),
commentable_id: parent.commentable_id,
commentable_type: parent.commentable_type,
body: Faker::Lorem.sentence,
parent: parent)
end
puts "Voting Debates, Proposals & Comments"
(1..100).each do |i|
voter = not_org_users.reorder("RANDOM()").first
vote = [true, false].sample
debate = Debate.reorder("RANDOM()").first
debate.vote_by(voter: voter, vote: vote)
end
(1..100).each do |i|
voter = not_org_users.reorder("RANDOM()").first
vote = [true, false].sample
comment = Comment.reorder("RANDOM()").first
comment.vote_by(voter: voter, vote: vote)
end
(1..100).each do |i|
voter = User.level_two_or_three_verified.reorder("RANDOM()").first
proposal = Proposal.reorder("RANDOM()").first
proposal.vote_by(voter: voter, vote: true)
end
puts "Flagging Debates & Comments"
(1..40).each do |i|
debate = Debate.reorder("RANDOM()").first
flagger = User.where(["users.id <> ?", debate.author_id]).reorder("RANDOM()").first
Flag.flag(flagger, debate)
end
(1..40).each do |i|
comment = Comment.reorder("RANDOM()").first
flagger = User.where(["users.id <> ?", comment.user_id]).reorder("RANDOM()").first
Flag.flag(flagger, comment)
end
(1..40).each do |i|
proposal = Proposal.reorder("RANDOM()").first
flagger = User.where(["users.id <> ?", proposal.author_id]).reorder("RANDOM()").first
Flag.flag(flagger, proposal)
end
puts "Creating Spending Proposals"
tags = Faker::Lorem.words(10)
(1..60).each do |i|
geozone = Geozone.reorder("RANDOM()").first
author = User.reorder("RANDOM()").first
description = "<p>#{Faker::Lorem.paragraphs.join('</p><p>')}</p>"
feasible_explanation = "<p>#{Faker::Lorem.paragraphs.join('</p><p>')}</p>"
valuation_finished = [true, false].sample
feasible = [true, false].sample
spending_proposal = SpendingProposal.create!(author: author,
title: Faker::Lorem.sentence(3).truncate(60),
external_url: Faker::Internet.url,
description: description,
created_at: rand((Time.now - 1.week) .. Time.now),
geozone: [geozone, nil].sample,
feasible: feasible,
feasible_explanation: feasible_explanation,
valuation_finished: valuation_finished,
tag_list: tags.sample(3).join(','),
price: rand(1000000),
terms_of_service: "1")
puts " #{spending_proposal.title}"
end
puts "Creating Valuation Assignments"
(1..17).to_a.sample.times do
SpendingProposal.reorder("RANDOM()").first.valuators << valuator.valuator
end
puts "Creating Legislation"
Legislation.create!(title: 'Participatory Democracy', body: 'In order to achieve...')
puts "Ignoring flags in Debates, comments & proposals"
Debate.flagged.reorder("RANDOM()").limit(10).each(&:ignore_flag)
Comment.flagged.reorder("RANDOM()").limit(30).each(&:ignore_flag)
Proposal.flagged.reorder("RANDOM()").limit(10).each(&:ignore_flag)
puts "Hiding debates, comments & proposals"
Comment.with_hidden.flagged.reorder("RANDOM()").limit(30).each(&:hide)
Debate.with_hidden.flagged.reorder("RANDOM()").limit(5).each(&:hide)
Proposal.with_hidden.flagged.reorder("RANDOM()").limit(10).each(&:hide)
puts "Confirming hiding in debates, comments & proposals"
Comment.only_hidden.flagged.reorder("RANDOM()").limit(10).each(&:confirm_hide)
Debate.only_hidden.flagged.reorder("RANDOM()").limit(5).each(&:confirm_hide)
Proposal.only_hidden.flagged.reorder("RANDOM()").limit(5).each(&:confirm_hide)
puts "Creating banners"
Proposal.last(3).each do |proposal|
title = Faker::Lorem.sentence(word_count = 3)
description = Faker::Lorem.sentence(word_count = 12)
banner = Banner.create!(title: title,
description: description,
style: ["banner-style banner-style-one", "banner-style banner-style-two",
"banner-style banner-style-three"].sample,
image: ["banner-img banner-img-one", "banner-img banner-img-two",
"banner-img banner-img-three"].sample,
target_url: Rails.application.routes.url_helpers.proposal_path(proposal),
post_started_at: rand((Time.now - 1.week) .. (Time.now - 1.day)),
post_ended_at: rand((Time.now - 1.day) .. (Time.now + 1.week)),
created_at: rand((Time.now - 1.week) .. Time.now))
puts " #{banner.title}"
end
puts "Creating polls"
3.times.each_with_index do |i|
Poll.create(name: "Poll #{i}")
end |
# -*- encoding: utf-8 -*-
$:.push File.expand_path('../lib', __FILE__)
require 'openrtb/version'
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'openrtb-client'
s.version = OpenRTB::VERSION
s.summary = %Q{OpenRTB Ruby Client}
s.description = %Q{OpenRTB Ruby Client}
s.author = 'Realmedia Latin America'
s.email = 'dev@realmediadigital.com'
s.homepage = 'http://github.com/realmedia/openrtb-ruby-client'
s.license = 'MIT'
s.required_ruby_version = '>= 1.9.3'
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_dependency 'addressable', '~> 2.3.6'
s.add_dependency 'hashie', '~> 3.2.0'
s.add_dependency 'multi_json', '~> 1.10.1'
s.add_dependency 'naught', '~> 1.0.0'
s.add_dependency 'nesty', '~> 1.0.2'
s.add_dependency 'typhoeus', '~> 0.6.9'
s.add_development_dependency 'minitest', '~> 5.4.0'
s.add_development_dependency 'webmock', '~> 1.18.0'
end
add rake as dev dependency
# -*- encoding: utf-8 -*-
$:.push File.expand_path('../lib', __FILE__)
require 'openrtb/version'
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'openrtb-client'
s.version = OpenRTB::VERSION
s.summary = %Q{OpenRTB Ruby Client}
s.description = %Q{OpenRTB Ruby Client}
s.author = 'Realmedia Latin America'
s.email = 'dev@realmediadigital.com'
s.homepage = 'http://github.com/realmedia/openrtb-ruby-client'
s.license = 'MIT'
s.required_ruby_version = '>= 1.9.3'
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_dependency 'addressable', '~> 2.3.6'
s.add_dependency 'hashie', '~> 3.2.0'
s.add_dependency 'multi_json', '~> 1.10.1'
s.add_dependency 'naught', '~> 1.0.0'
s.add_dependency 'nesty', '~> 1.0.2'
s.add_dependency 'typhoeus', '~> 0.6.9'
s.add_development_dependency 'rake', '~> 10.3'
s.add_development_dependency 'minitest', '~> 5.2'
s.add_development_dependency 'webmock', '~> 1.18'
end |
# coding: utf-8
require File.expand_path('../lib/activeadmin/hstore_editor/version', __FILE__)
Gem::Specification.new do |spec|
spec.name = "activeadmin_hstore_editor"
spec.version = ActiveAdmin::HstoreEditor::VERSION
spec.authors = ["wild"]
spec.email = ["wild.exe@gmail.com"]
spec.summary = %q{add "hstore_input" field type to active_admin that allow to edit Postgresql hstore values}
spec.description = %q{"hstore_input" field allow to edit hstore value as json array with using jsoneditor.js from http://jsoneditoronline.org}
spec.homepage = "https://github.com/wild-r/activeadmin_hstore_editor"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
# spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.required_rubygems_version = ">= 1.3.6"
spec.add_development_dependency "bundler", "~> 1.5"
spec.add_dependency "railties", ">= 3.0", "< 5.0"
#spec.add_development_dependency "rake", "~> 0"
#spec.add_dependency "active_admin", "~> 1.0.0"
end
Add Rails 5.0.1 support
# coding: utf-8
require File.expand_path('../lib/activeadmin/hstore_editor/version', __FILE__)
Gem::Specification.new do |spec|
spec.name = "activeadmin_hstore_editor"
spec.version = ActiveAdmin::HstoreEditor::VERSION
spec.authors = ["wild"]
spec.email = ["wild.exe@gmail.com"]
spec.summary = %q{add "hstore_input" field type to active_admin that allow to edit Postgresql hstore values}
spec.description = %q{"hstore_input" field allow to edit hstore value as json array with using jsoneditor.js from http://jsoneditoronline.org}
spec.homepage = "https://github.com/wild-r/activeadmin_hstore_editor"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
# spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.required_rubygems_version = ">= 1.3.6"
spec.add_development_dependency "bundler", "~> 1.5"
spec.add_dependency "railties", ">= 3.0", "< 5.1"
#spec.add_development_dependency "rake", "~> 0"
#spec.add_dependency "active_admin", "~> 1.0.0"
end
|
require File.expand_path('../../../../load_paths', __FILE__)
require 'config'
require 'active_support/testing/autorun'
require 'active_support/testing/method_call_assertions'
require 'stringio'
require 'active_record'
require 'cases/test_case'
require 'active_support/dependencies'
require 'active_support/logger'
require 'active_support/core_ext/string/strip'
require 'support/config'
require 'support/connection'
# TODO: Move all these random hacks into the ARTest namespace and into the support/ dir
Thread.abort_on_exception = true
# Show backtraces for deprecated behavior for quicker cleanup.
ActiveSupport::Deprecation.debug = true
# Disable available locale checks to avoid warnings running the test suite.
I18n.enforce_available_locales = false
# Connect to the database
ARTest.connect
# Quote "type" if it's a reserved word for the current connection.
QUOTED_TYPE = ActiveRecord::Base.connection.quote_column_name('type')
# FIXME: Remove this when the deprecation cycle on TZ aware types by default ends.
ActiveRecord::Base.time_zone_aware_types << :time
def current_adapter?(*types)
types.any? do |type|
ActiveRecord::ConnectionAdapters.const_defined?(type) &&
ActiveRecord::Base.connection.is_a?(ActiveRecord::ConnectionAdapters.const_get(type))
end
end
def in_memory_db?
current_adapter?(:SQLite3Adapter) &&
ActiveRecord::Base.connection_pool.spec.config[:database] == ":memory:"
end
def subsecond_precision_supported?
!current_adapter?(:MysqlAdapter, :Mysql2Adapter) || ActiveRecord::Base.connection.version >= '5.6.4'
end
def mysql_enforcing_gtid_consistency?
current_adapter?(:MysqlAdapter, :Mysql2Adapter) && 'ON' == ActiveRecord::Base.connection.show_variable('enforce_gtid_consistency')
end
def supports_savepoints?
ActiveRecord::Base.connection.supports_savepoints?
end
def with_env_tz(new_tz = 'US/Eastern')
old_tz, ENV['TZ'] = ENV['TZ'], new_tz
yield
ensure
old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
end
def with_timezone_config(cfg)
verify_default_timezone_config
old_default_zone = ActiveRecord::Base.default_timezone
old_awareness = ActiveRecord::Base.time_zone_aware_attributes
old_zone = Time.zone
if cfg.has_key?(:default)
ActiveRecord::Base.default_timezone = cfg[:default]
end
if cfg.has_key?(:aware_attributes)
ActiveRecord::Base.time_zone_aware_attributes = cfg[:aware_attributes]
end
if cfg.has_key?(:zone)
Time.zone = cfg[:zone]
end
yield
ensure
ActiveRecord::Base.default_timezone = old_default_zone
ActiveRecord::Base.time_zone_aware_attributes = old_awareness
Time.zone = old_zone
end
# This method makes sure that tests don't leak global state related to time zones.
EXPECTED_ZONE = nil
EXPECTED_DEFAULT_TIMEZONE = :utc
EXPECTED_TIME_ZONE_AWARE_ATTRIBUTES = false
def verify_default_timezone_config
if Time.zone != EXPECTED_ZONE
$stderr.puts <<-MSG
\n#{self}
Global state `Time.zone` was leaked.
Expected: #{EXPECTED_ZONE}
Got: #{Time.zone}
MSG
end
if ActiveRecord::Base.default_timezone != EXPECTED_DEFAULT_TIMEZONE
$stderr.puts <<-MSG
\n#{self}
Global state `ActiveRecord::Base.default_timezone` was leaked.
Expected: #{EXPECTED_DEFAULT_TIMEZONE}
Got: #{ActiveRecord::Base.default_timezone}
MSG
end
if ActiveRecord::Base.time_zone_aware_attributes != EXPECTED_TIME_ZONE_AWARE_ATTRIBUTES
$stderr.puts <<-MSG
\n#{self}
Global state `ActiveRecord::Base.time_zone_aware_attributes` was leaked.
Expected: #{EXPECTED_TIME_ZONE_AWARE_ATTRIBUTES}
Got: #{ActiveRecord::Base.time_zone_aware_attributes}
MSG
end
end
def enable_extension!(extension, connection)
return false unless connection.supports_extensions?
return connection.reconnect! if connection.extension_enabled?(extension)
connection.enable_extension extension
connection.commit_db_transaction if connection.transaction_open?
connection.reconnect!
end
def disable_extension!(extension, connection)
return false unless connection.supports_extensions?
return true unless connection.extension_enabled?(extension)
connection.disable_extension extension
connection.reconnect!
end
require "cases/validations_repair_helper"
class ActiveSupport::TestCase
include ActiveRecord::TestFixtures
include ActiveRecord::ValidationsRepairHelper
include ActiveSupport::Testing::MethodCallAssertions
self.fixture_path = FIXTURES_ROOT
self.use_instantiated_fixtures = false
self.use_transactional_tests = true
def create_fixtures(*fixture_set_names, &block)
ActiveRecord::FixtureSet.create_fixtures(ActiveSupport::TestCase.fixture_path, fixture_set_names, fixture_class_names, &block)
end
end
def load_schema
# silence verbose schema loading
original_stdout = $stdout
$stdout = StringIO.new
adapter_name = ActiveRecord::Base.connection.adapter_name.downcase
adapter_specific_schema_file = SCHEMA_ROOT + "/#{adapter_name}_specific_schema.rb"
load SCHEMA_ROOT + "/schema.rb"
if File.exist?(adapter_specific_schema_file)
load adapter_specific_schema_file
end
ensure
$stdout = original_stdout
end
load_schema
class SQLSubscriber
attr_reader :logged
attr_reader :payloads
def initialize
@logged = []
@payloads = []
end
def start(name, id, payload)
@payloads << payload
@logged << [payload[:sql].squish, payload[:name], payload[:binds]]
end
def finish(name, id, payload); end
end
module InTimeZone
private
def in_time_zone(zone)
old_zone = Time.zone
old_tz = ActiveRecord::Base.time_zone_aware_attributes
Time.zone = zone ? ActiveSupport::TimeZone[zone] : nil
ActiveRecord::Base.time_zone_aware_attributes = !zone.nil?
yield
ensure
Time.zone = old_zone
ActiveRecord::Base.time_zone_aware_attributes = old_tz
end
end
require 'mocha/setup' # FIXME: stop using mocha
Use adapter supports_datetime_with_precision to support 3rd party adapter tests
require File.expand_path('../../../../load_paths', __FILE__)
require 'config'
require 'active_support/testing/autorun'
require 'active_support/testing/method_call_assertions'
require 'stringio'
require 'active_record'
require 'cases/test_case'
require 'active_support/dependencies'
require 'active_support/logger'
require 'active_support/core_ext/string/strip'
require 'support/config'
require 'support/connection'
# TODO: Move all these random hacks into the ARTest namespace and into the support/ dir
Thread.abort_on_exception = true
# Show backtraces for deprecated behavior for quicker cleanup.
ActiveSupport::Deprecation.debug = true
# Disable available locale checks to avoid warnings running the test suite.
I18n.enforce_available_locales = false
# Connect to the database
ARTest.connect
# Quote "type" if it's a reserved word for the current connection.
QUOTED_TYPE = ActiveRecord::Base.connection.quote_column_name('type')
# FIXME: Remove this when the deprecation cycle on TZ aware types by default ends.
ActiveRecord::Base.time_zone_aware_types << :time
def current_adapter?(*types)
types.any? do |type|
ActiveRecord::ConnectionAdapters.const_defined?(type) &&
ActiveRecord::Base.connection.is_a?(ActiveRecord::ConnectionAdapters.const_get(type))
end
end
def in_memory_db?
current_adapter?(:SQLite3Adapter) &&
ActiveRecord::Base.connection_pool.spec.config[:database] == ":memory:"
end
def subsecond_precision_supported?
ActiveRecord::Base.connection.supports_datetime_with_precision?
end
def mysql_enforcing_gtid_consistency?
current_adapter?(:MysqlAdapter, :Mysql2Adapter) && 'ON' == ActiveRecord::Base.connection.show_variable('enforce_gtid_consistency')
end
def supports_savepoints?
ActiveRecord::Base.connection.supports_savepoints?
end
def with_env_tz(new_tz = 'US/Eastern')
old_tz, ENV['TZ'] = ENV['TZ'], new_tz
yield
ensure
old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
end
def with_timezone_config(cfg)
verify_default_timezone_config
old_default_zone = ActiveRecord::Base.default_timezone
old_awareness = ActiveRecord::Base.time_zone_aware_attributes
old_zone = Time.zone
if cfg.has_key?(:default)
ActiveRecord::Base.default_timezone = cfg[:default]
end
if cfg.has_key?(:aware_attributes)
ActiveRecord::Base.time_zone_aware_attributes = cfg[:aware_attributes]
end
if cfg.has_key?(:zone)
Time.zone = cfg[:zone]
end
yield
ensure
ActiveRecord::Base.default_timezone = old_default_zone
ActiveRecord::Base.time_zone_aware_attributes = old_awareness
Time.zone = old_zone
end
# This method makes sure that tests don't leak global state related to time zones.
EXPECTED_ZONE = nil
EXPECTED_DEFAULT_TIMEZONE = :utc
EXPECTED_TIME_ZONE_AWARE_ATTRIBUTES = false
def verify_default_timezone_config
if Time.zone != EXPECTED_ZONE
$stderr.puts <<-MSG
\n#{self}
Global state `Time.zone` was leaked.
Expected: #{EXPECTED_ZONE}
Got: #{Time.zone}
MSG
end
if ActiveRecord::Base.default_timezone != EXPECTED_DEFAULT_TIMEZONE
$stderr.puts <<-MSG
\n#{self}
Global state `ActiveRecord::Base.default_timezone` was leaked.
Expected: #{EXPECTED_DEFAULT_TIMEZONE}
Got: #{ActiveRecord::Base.default_timezone}
MSG
end
if ActiveRecord::Base.time_zone_aware_attributes != EXPECTED_TIME_ZONE_AWARE_ATTRIBUTES
$stderr.puts <<-MSG
\n#{self}
Global state `ActiveRecord::Base.time_zone_aware_attributes` was leaked.
Expected: #{EXPECTED_TIME_ZONE_AWARE_ATTRIBUTES}
Got: #{ActiveRecord::Base.time_zone_aware_attributes}
MSG
end
end
def enable_extension!(extension, connection)
return false unless connection.supports_extensions?
return connection.reconnect! if connection.extension_enabled?(extension)
connection.enable_extension extension
connection.commit_db_transaction if connection.transaction_open?
connection.reconnect!
end
def disable_extension!(extension, connection)
return false unless connection.supports_extensions?
return true unless connection.extension_enabled?(extension)
connection.disable_extension extension
connection.reconnect!
end
require "cases/validations_repair_helper"
class ActiveSupport::TestCase
include ActiveRecord::TestFixtures
include ActiveRecord::ValidationsRepairHelper
include ActiveSupport::Testing::MethodCallAssertions
self.fixture_path = FIXTURES_ROOT
self.use_instantiated_fixtures = false
self.use_transactional_tests = true
def create_fixtures(*fixture_set_names, &block)
ActiveRecord::FixtureSet.create_fixtures(ActiveSupport::TestCase.fixture_path, fixture_set_names, fixture_class_names, &block)
end
end
def load_schema
# silence verbose schema loading
original_stdout = $stdout
$stdout = StringIO.new
adapter_name = ActiveRecord::Base.connection.adapter_name.downcase
adapter_specific_schema_file = SCHEMA_ROOT + "/#{adapter_name}_specific_schema.rb"
load SCHEMA_ROOT + "/schema.rb"
if File.exist?(adapter_specific_schema_file)
load adapter_specific_schema_file
end
ensure
$stdout = original_stdout
end
load_schema
class SQLSubscriber
attr_reader :logged
attr_reader :payloads
def initialize
@logged = []
@payloads = []
end
def start(name, id, payload)
@payloads << payload
@logged << [payload[:sql].squish, payload[:name], payload[:binds]]
end
def finish(name, id, payload); end
end
module InTimeZone
private
def in_time_zone(zone)
old_zone = Time.zone
old_tz = ActiveRecord::Base.time_zone_aware_attributes
Time.zone = zone ? ActiveSupport::TimeZone[zone] : nil
ActiveRecord::Base.time_zone_aware_attributes = !zone.nil?
yield
ensure
Time.zone = old_zone
ActiveRecord::Base.time_zone_aware_attributes = old_tz
end
end
require 'mocha/setup' # FIXME: stop using mocha
|
$:.push File.expand_path("../lib", __FILE__)
require "activerecord_translatable"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "activerecord_translatable"
s.version = ActiveRecordTranslatable::VERSION
s.authors = ["Philipp Fehre"]
s.email = ["philipp.fehre@gmail.com"]
s.homepage = "http://github.com/sideshowcoder/activerecord_translatable"
s.summary = "make attributes of active record translatable via the normal i18n backend"
s.description = "translatable activerecord attributes"
s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"]
s.test_files = Dir["spec/**/*"]
s.add_dependency "rails", "~> 3.2.8"
s.add_development_dependency "pg"
s.add_development_dependency "activerecord-postgres-array"
s.add_development_dependency "rspec-rails"
end
Added Activerecord as explicit dependency
$:.push File.expand_path("../lib", __FILE__)
require "activerecord_translatable"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "activerecord_translatable"
s.version = ActiveRecordTranslatable::VERSION
s.authors = ["Philipp Fehre"]
s.email = ["philipp.fehre@gmail.com"]
s.homepage = "http://github.com/sideshowcoder/activerecord_translatable"
s.summary = "make attributes of active record translatable via the normal i18n backend"
s.description = "translatable activerecord attributes"
s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"]
s.test_files = Dir["spec/**/*"]
s.add_dependency "rails", "~> 3.2.8"
s.add_dependency "activerecord"
s.add_development_dependency "pg"
s.add_development_dependency "activerecord-postgres-array"
s.add_development_dependency "rspec-rails"
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "otrs_connector"
s.version = "1.1.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Brian Goff"]
s.date = "2012-06-11"
s.description = "Connect your RAILS app to OTRS/ITSM"
s.email = "cpuguy83@gmail.com"
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = [
".document",
"Gemfile",
"Gemfile.lock",
"LICENSE.txt",
"README.rdoc",
"Rakefile",
"VERSION",
"lib/otrs_connector.rb",
"lib/otrs_connector/otrs.rb",
"lib/otrs_connector/otrs/change.rb",
"lib/otrs_connector/otrs/change/state.rb",
"lib/otrs_connector/otrs/change/work_order.rb",
"lib/otrs_connector/otrs/config_item.rb",
"lib/otrs_connector/otrs/general_catalog.rb",
"lib/otrs_connector/otrs/link.rb",
"lib/otrs_connector/otrs/relation.rb",
"lib/otrs_connector/otrs/service.rb",
"lib/otrs_connector/otrs/ticket.rb",
"lib/otrs_connector/otrs/ticket/article.rb",
"lib/otrs_connector/otrs/ticket/state.rb",
"lib/otrs_connector/otrs/ticket/ticket_queue.rb",
"lib/otrs_connector/otrs/ticket/type.rb",
"otrs_connector.gemspec",
"test/helper.rb",
"test/test_otrs_connector.rb"
]
s.homepage = "http://github.com/cpuguy83/otrs_connector"
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = "1.8.24"
s.summary = "Connects OTRS API to create tikets, manipulate CI's, etc."
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<rails>, [">= 3.0.0"])
s.add_runtime_dependency(%q<require_all>, [">= 1.2"])
s.add_development_dependency(%q<shoulda>, [">= 0"])
s.add_development_dependency(%q<rdoc>, ["~> 3.12"])
s.add_development_dependency(%q<bundler>, ["~> 1.1.1"])
s.add_development_dependency(%q<jeweler>, ["~> 1.8.3"])
else
s.add_dependency(%q<rails>, [">= 3.0.0"])
s.add_dependency(%q<require_all>, [">= 1.2"])
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<rdoc>, ["~> 3.12"])
s.add_dependency(%q<bundler>, ["~> 1.1.1"])
s.add_dependency(%q<jeweler>, ["~> 1.8.3"])
end
else
s.add_dependency(%q<rails>, [">= 3.0.0"])
s.add_dependency(%q<require_all>, [">= 1.2"])
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<rdoc>, ["~> 3.12"])
s.add_dependency(%q<bundler>, ["~> 1.1.1"])
s.add_dependency(%q<jeweler>, ["~> 1.8.3"])
end
end
Regenerate gemspec for version 1.1.1
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "otrs_connector"
s.version = "1.1.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Brian Goff"]
s.date = "2012-06-11"
s.description = "Connect your RAILS app to OTRS/ITSM"
s.email = "cpuguy83@gmail.com"
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = [
".document",
"Gemfile",
"Gemfile.lock",
"LICENSE.txt",
"README.rdoc",
"Rakefile",
"VERSION",
"lib/otrs_connector.rb",
"lib/otrs_connector/otrs.rb",
"lib/otrs_connector/otrs/change.rb",
"lib/otrs_connector/otrs/change/state.rb",
"lib/otrs_connector/otrs/change/work_order.rb",
"lib/otrs_connector/otrs/config_item.rb",
"lib/otrs_connector/otrs/general_catalog.rb",
"lib/otrs_connector/otrs/link.rb",
"lib/otrs_connector/otrs/relation.rb",
"lib/otrs_connector/otrs/service.rb",
"lib/otrs_connector/otrs/ticket.rb",
"lib/otrs_connector/otrs/ticket/article.rb",
"lib/otrs_connector/otrs/ticket/state.rb",
"lib/otrs_connector/otrs/ticket/ticket_queue.rb",
"lib/otrs_connector/otrs/ticket/type.rb",
"otrs_connector.gemspec",
"test/helper.rb",
"test/test_otrs_connector.rb"
]
s.homepage = "http://github.com/cpuguy83/otrs_connector"
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = "1.8.24"
s.summary = "Connects OTRS API to create tikets, manipulate CI's, etc."
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<rails>, [">= 3.0.0"])
s.add_runtime_dependency(%q<require_all>, [">= 1.2"])
s.add_development_dependency(%q<shoulda>, [">= 0"])
s.add_development_dependency(%q<rdoc>, ["~> 3.12"])
s.add_development_dependency(%q<bundler>, ["~> 1.1.1"])
s.add_development_dependency(%q<jeweler>, ["~> 1.8.3"])
else
s.add_dependency(%q<rails>, [">= 3.0.0"])
s.add_dependency(%q<require_all>, [">= 1.2"])
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<rdoc>, ["~> 3.12"])
s.add_dependency(%q<bundler>, ["~> 1.1.1"])
s.add_dependency(%q<jeweler>, ["~> 1.8.3"])
end
else
s.add_dependency(%q<rails>, [">= 3.0.0"])
s.add_dependency(%q<require_all>, [">= 1.2"])
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<rdoc>, ["~> 3.12"])
s.add_dependency(%q<bundler>, ["~> 1.1.1"])
s.add_dependency(%q<jeweler>, ["~> 1.8.3"])
end
end
|
require "yaml"
require "twitter"
require "ostruct"
keys = YAML.load_file File.expand_path(".", "config.yml")
waifu = YAML.load_file File.expand_path(".", "waifu.yml")
client = Twitter::REST::Client.new do |config|
config.consumer_key = keys['consumer_key']
config.consumer_secret = keys['consumer_secret']
config.access_token = keys['access_token']
config.access_token_secret = keys['access_token_secret']
end
streamer = Twitter::Streaming::Client.new do |config|
config.consumer_key = keys['consumer_key']
config.consumer_secret = keys['consumer_secret']
config.access_token = keys['access_token']
config.access_token_secret = keys['access_token_secret']
end
begin
current_user = client.current_user
rescue Exception => e
puts "Exception: #{e.message}"
# best hack:
current_user = OpenStruct.new
current_user.id = config["access_token"].split("-")[0]
end
puts "yourwaifu - serving #{waifu.count} entries"
puts "-------------------------------"
loop do
streamer.user do |object|
if object.is_a? Twitter::Tweet
unless current_user.id == object.user.id
unless object.text.start_with? "RT @"
chosen_one = waifu.sample
puts "[#{Time.new.to_s}] #{object.user.screen_name}: #{chosen_one["name"]} - #{chosen_one["series"]}"
begin
begin
client.update_with_media "@#{object.user.screen_name} Your waifu is #{chosen_one["name"]} (#{chosen_one["series"]})", File.new("/img/#{chosen_one["series"]}/#{chosen_one["name"]}.png"), in_reply_to_status:object
rescue Exception => m
puts "\034[31;1m[#{Time.new.to_s}] #{m.message} Trying to post tweet without image!\034[0m"
client.update "@#{object.user.screen_name} Your waifu is #{chosen_one["name"]} (#{chosen_one["series"]})", in_reply_to_status:object
rescue Exception => e
puts "\033[31;1m[#{Time.new.to_s}] #{e.message}\033[0m"
end
end
end
end
end
sleep 1
end
forgot to add an end
require "yaml"
require "twitter"
require "ostruct"
keys = YAML.load_file File.expand_path(".", "config.yml")
waifu = YAML.load_file File.expand_path(".", "waifu.yml")
client = Twitter::REST::Client.new do |config|
config.consumer_key = keys['consumer_key']
config.consumer_secret = keys['consumer_secret']
config.access_token = keys['access_token']
config.access_token_secret = keys['access_token_secret']
end
streamer = Twitter::Streaming::Client.new do |config|
config.consumer_key = keys['consumer_key']
config.consumer_secret = keys['consumer_secret']
config.access_token = keys['access_token']
config.access_token_secret = keys['access_token_secret']
end
begin
current_user = client.current_user
rescue Exception => e
puts "Exception: #{e.message}"
# best hack:
current_user = OpenStruct.new
current_user.id = config["access_token"].split("-")[0]
end
puts "yourwaifu - serving #{waifu.count} entries"
puts "-------------------------------"
loop do
streamer.user do |object|
if object.is_a? Twitter::Tweet
unless current_user.id == object.user.id
unless object.text.start_with? "RT @"
chosen_one = waifu.sample
puts "[#{Time.new.to_s}] #{object.user.screen_name}: #{chosen_one["name"]} - #{chosen_one["series"]}"
begin
begin
client.update_with_media "@#{object.user.screen_name} Your waifu is #{chosen_one["name"]} (#{chosen_one["series"]})", File.new("/img/#{chosen_one["series"]}/#{chosen_one["name"]}.png"), in_reply_to_status:object
rescue Exception => m
puts "\034[31;1m[#{Time.new.to_s}] #{m.message} Trying to post tweet without image!\034[0m"
client.update "@#{object.user.screen_name} Your waifu is #{chosen_one["name"]} (#{chosen_one["series"]})", in_reply_to_status:object
end
rescue Exception => e
puts "\033[31;1m[#{Time.new.to_s}] #{e.message}\033[0m"
end
end
end
end
end
sleep 1
end
|
$LOAD_PATH << '..'
require 'musikbot'
MIN_ARTICLE_COUNT = 25
MAINTENANCE_CATEGORIES = [
'All_articles_lacking_sources',
'All_articles_needing_additional_references',
'All_unreferenced_BLPs',
'All_BLP_articles_lacking_sources',
'All_articles_lacking_reliable_references',
'All_articles_with_a_promotional_tone',
'All_articles_with_topics_of_unclear_notability'
]
REPORT_PAGE = 'Wikipedia:Database reports/Editors eligible for Autopatrol privilege'
module AutopatrolledCandidates
def self.run
@mb = MusikBot::Session.new(inspect, true)
users = {}
page_creators.each_with_index do |user, i|
username = user['user_name']
articles = articles_created(username)
# Skip if they don't meet article count prerequisite
next if articles.length < MIN_ARTICLE_COUNT
user_data = {
created: articles.length,
edits: user['user_editcount'],
deleted: deleted_counts(username),
blocks: block_count(username),
tagged: maintenance_count(articles),
perm_revoked: autopatrolled_revoked?(username)
}
users[username] = user_data
puts "#{i} of #{page_creators.length}: #{username} = #{articles.length}"
end
generate_report(users)
end
# Generate markup for the report and write it to REPORT_PAGE
def self.generate_report(users)
cat_str = MAINTENANCE_CATEGORIES.collect { |c| "[[:Category:#{c}|#{c.descore}]]" }.join(', ')
markup = <<~END
<div style='font-size:24px'>Users eligible to be autopatrolled as of #{I18n.l(@mb.today, format: :heading)}</div>
{{FORMATNUM:#{users.length}}} users who have created an article in the past month, and are eligible for the autopatrolled privilege but don't have it yet.
== Key ==
* '''Articles''': Number of live, non-redirect articles
* '''Tagged''': Number of articles with maintenance tags<ref name=tags />
* '''Deleted''': Number of deleted articles in the past year (may include redirects)<ref name='deleted' />
* '''Edit count''': Raw edit count of the user
* '''Blocks''': Number of blocks in the past year
* '''Revoked?''': Whether or not the autopatrolled permission was previously revoked
{{pb}}
;Notes
{{reflist|refs="
<ref name='tags'>Supported maintenance categories include: #{cat_str}</ref>
<ref name='deleted'>[[WP:G6|G6]] (technical) and [[WP:G7|G7]] (user-requested) speedy deletions are not included. The number of speedy, (BLP)PROD and AfDs deletions are shown if detected via the deletion summary.</ref>
}}
== Report ==
{| class='wikitable sortable'
! Username
! Articles
! Tagged
! Deleted
! Edit count
! Blocks
! Revoked?
! Links
|-
END
users.each do |username, data|
user_rights_log = "https://en.wikipedia.org/w/index.php?title=Special:Log&page=User:#{username.score}&type=rights"
block_log = "https://en.wikipedia.org/w/index.php?title=Special:Log&action=view&page=#{username.score}&type=block"
xtools_link = "[https://tools.wmflabs.org/xtools/pages/?user=#{URI.escape(username)}" \
"&project=en.wikipedia.org&namespace=0&redirects=noredirects {{FORMATNUM:#{data[:created]}}}]"
deleted_str = '0'
# Generate string that lists the different types of deletions that were detected
if data[:deleted][:total] > 0
deleted_str = "#{data[:deleted][:total]} total"
deletion_stats = []
[:Speedy, :PROD, :AfD].each do |type|
if data[:deleted][type] > 0
deletion_stats << "#{type}: {{FORMATNUM:#{data[:deleted][type]}}}"
end
end
deleted_str += " (#{deletion_stats.join(', ')})"
end
block_str = data[:blocks] > 0 ? "[#{block_log} {{FORMATNUM:#{data[:blocks]}}}]" : '0'
revoked_str = data[:perm_revoked] ? "[#{user_rights_log} Yes]" : 'No'
links = [
"[[Special:UserRights/#{username}|User rights]]",
"[https://tools.wmflabs.org/xtools-ec/?user=#{URI.encode(username)}&project=en.wikipedia.org EC]",
"[https://tools.wmflabs.org/musikanimal/blp_edits?username=#{URI.encode(username)}&offset=0&contribs=on BLP edits]"
].join(' · ')
markup += <<~END
| [[User:#{username}|#{username}]]
| #{xtools_link}
| {{FORMATNUM:#{data[:tagged]}}}
| data-sort-value=#{data[:deleted][:total]} | #{deleted_str}
| {{FORMATNUM:#{data[:edits]}}}
| #{block_str}
| #{revoked_str}
| #{links}
|-
END
end
markup = markup.chomp("\n|-") + "|}\n\n"
@mb.edit(REPORT_PAGE,
content: markup,
summary: "Reporting #{users.length} users eligible for autopatrolled"
)
end
# Get data about pages the user created that were deleted
# Returns:
# {
# total: total number of articles deleted
# Speedy: total number of articles deleted under [[WP:CSD]]
# PROD: total number of articles deleted under [[WP:PROD]] or [[WP:BLPPROD]]
# AfD: total number of articles deleted under [[WP:AfD]]
# }
def self.deleted_counts(username)
sql = %{
SELECT log_comment
FROM logging_logindex
LEFT JOIN archive_userindex ON ar_page_id = log_page
WHERE log_type = 'delete'
AND ar_user_text = ?
AND ar_namespace = 0
AND ar_parent_id = 0
AND ar_timestamp > #{@mb.db_date(@mb.now - 365)}
}
counts = {
total: 0,
Speedy: 0,
PROD: 0,
AfD: 0
}
@mb.repl_query(sql, username).to_a.each do |data|
# don't count technical or user-requested deletions
next if data['log_comment'] =~ /\[\[WP:CSD#G(6|7)\|/
counts[:total] += 1
case data['log_comment']
when /\[\[WP:CSD#/
counts[:Speedy] += 1
when /\[\[WP:(BLP)?PROD/
counts[:PROD] += 1
when /\[\[(Wikipedia|WP):Articles for deletion\//
counts[:AfD] += 1
end
end
counts
end
# Get the number of blocks the user had in the past year
def self.block_count(username)
sql = %{
SELECT COUNT(*) AS count
FROM logging_logindex
WHERE log_type = 'block'
AND log_title = ?
AND log_timestamp > #{@mb.db_date(@mb.now - 365)}
}
@mb.repl_query(sql, username).to_a.first['count']
end
# Check if the user has had the autopatrolled permission revoked in the past
def self.autopatrolled_revoked?(username)
sql = %{
SELECT COUNT(*) AS count
FROM logging_logindex
WHERE log_type = 'rights'
AND log_title = ?
AND log_params REGEXP "oldgroups.*?autoreviewer.*?newgroups(?!.*?autoreviewer)"
}
@mb.repl_query(sql, username).to_a.first['count'] > 0
end
# Get the page title, ID and creation date of articles created by the given user
def self.articles_created(username)
sql = %{
SELECT page_title, page_id, rev_timestamp
FROM revision_userindex
LEFT JOIN page ON page_id = rev_page
WHERE page_namespace = 0
AND rev_parent_id = 0
AND rev_user_text = ?
AND rev_deleted = 0
AND page_is_redirect = 0
}
@mb.repl_query(sql, username).to_a
end
# Get the number of articles created by the user that are in maintenance categories
def self.maintenance_count(articles)
# Create list of categories to be used in the `cl_to IN ()` clause
categories_sql = MAINTENANCE_CATEGORIES.collect { |c| "'#{c}'" }.join(',')
# Create list of article IDs to be used in the `cl_from IN ()` clause
article_ids = articles
.select { |a| @mb.parse_date(a['rev_timestamp']) > @mb.now - 365 }
.collect { |a| a['page_id'] }
sql = %{
SELECT COUNT(DISTINCT(cl_from)) AS count
FROM categorylinks
WHERE cl_from IN (#{article_ids.join(',')})
AND cl_to IN (#{categories_sql})
AND cl_type = 'page'
}
@mb.repl.query(sql).to_a.first['count']
end
# Get the usernames and edit counts of users who have created a page in the past month
def self.page_creators
# Cache so this can be re-called without repeating the query
return @page_creators if @page_creators
sql = %{
SELECT DISTINCT(user_name), user_editcount
FROM recentchanges
LEFT JOIN user
ON rc_user = user_id
LEFT JOIN page
ON rc_cur_id = page_id
WHERE
rc_timestamp > #{@mb.db_date(@mb.now - 3)} AND
rc_namespace = 0 AND
rc_bot = 0 AND
rc_new = 1 AND
page_is_redirect = 0 AND
NOT EXISTS
(
SELECT 1
FROM user_groups
WHERE ug_user = user_id
AND ( ug_group = 'autoreviewer' OR ug_group = 'sysop' )
)
}
@page_creators = @mb.repl.query(sql).to_a
end
end
AutopatrolledCandidates.run
AutopatrolledCandidates: add signature, use {{no ping}}
$LOAD_PATH << '..'
require 'musikbot'
MIN_ARTICLE_COUNT = 25
MAINTENANCE_CATEGORIES = [
'All_articles_lacking_sources',
'All_articles_needing_additional_references',
'All_unreferenced_BLPs',
'All_BLP_articles_lacking_sources',
'All_articles_lacking_reliable_references',
'All_articles_with_a_promotional_tone',
'All_articles_with_topics_of_unclear_notability'
]
REPORT_PAGE = 'Wikipedia:Database reports/Editors eligible for Autopatrol privilege'
module AutopatrolledCandidates
def self.run
@mb = MusikBot::Session.new(inspect, true)
users = {}
page_creators.each_with_index do |user, i|
username = user['user_name']
articles = articles_created(username)
# Skip if they don't meet article count prerequisite
next if articles.length < MIN_ARTICLE_COUNT
user_data = {
created: articles.length,
edits: user['user_editcount'],
deleted: deleted_counts(username),
blocks: block_count(username),
tagged: maintenance_count(articles),
perm_revoked: autopatrolled_revoked?(username)
}
users[username] = user_data
puts "#{i} of #{page_creators.length}: #{username} = #{articles.length}"
end
generate_report(users)
end
# Generate markup for the report and write it to REPORT_PAGE
def self.generate_report(users)
cat_str = MAINTENANCE_CATEGORIES.collect { |c| "[[:Category:#{c}|#{c.descore}]]" }.join(', ')
markup = <<~END
<div style='font-size:24px'>Users eligible to be autopatrolled as of #{I18n.l(@mb.today, format: :heading)}</div>
{{FORMATNUM:#{users.length}}} users who have created an article in the past month, and are eligible for the autopatrolled privilege but don't have it yet.
Prepared by ~~~~
== Key ==
* '''Articles''': Number of live, non-redirect articles
* '''Tagged''': Number of articles with maintenance tags<ref name=tags />
* '''Deleted''': Number of deleted articles in the past year (may include redirects)<ref name='deleted' />
* '''Edit count''': Raw edit count of the user
* '''Blocks''': Number of blocks in the past year
* '''Revoked?''': Whether or not the autopatrolled permission was previously revoked
{{pb}}
;Notes
{{reflist|refs="
<ref name='tags'>Supported maintenance categories include: #{cat_str}</ref>
<ref name='deleted'>[[WP:G6|G6]] (technical) and [[WP:G7|G7]] (user-requested) speedy deletions are not included. The number of speedy, (BLP)PROD and AfDs deletions are shown if detected via the deletion summary.</ref>
}}
== Report ==
{| class='wikitable sortable'
! Username
! Articles
! Tagged
! Deleted
! Edit count
! Blocks
! Revoked?
! Links
|-
END
users.each do |username, data|
user_rights_log = "https://en.wikipedia.org/w/index.php?title=Special:Log&page=User:#{username.score}&type=rights"
block_log = "https://en.wikipedia.org/w/index.php?title=Special:Log&action=view&page=#{username.score}&type=block"
xtools_link = "[https://tools.wmflabs.org/xtools/pages/?user=#{URI.escape(username)}" \
"&project=en.wikipedia.org&namespace=0&redirects=noredirects {{FORMATNUM:#{data[:created]}}}]"
deleted_str = '0'
# Generate string that lists the different types of deletions that were detected
if data[:deleted][:total] > 0
deleted_str = "#{data[:deleted][:total]} total"
deletion_stats = []
[:Speedy, :PROD, :AfD].each do |type|
if data[:deleted][type] > 0
deletion_stats << "#{type}: {{FORMATNUM:#{data[:deleted][type]}}}"
end
end
deleted_str += " (#{deletion_stats.join(', ')})"
end
block_str = data[:blocks] > 0 ? "[#{block_log} {{FORMATNUM:#{data[:blocks]}}}]" : '0'
revoked_str = data[:perm_revoked] ? "[#{user_rights_log} Yes]" : 'No'
links = [
"[[Special:UserRights/#{username}|User rights]]",
"[https://tools.wmflabs.org/xtools-ec/?user=#{URI.encode(username)}&project=en.wikipedia.org EC]",
"[https://tools.wmflabs.org/musikanimal/blp_edits?username=#{URI.encode(username)}&offset=0&contribs=on BLP edits]"
].join(' · ')
markup += <<~END
| [[User:#{username}|#{username}]]
| #{xtools_link}
| {{FORMATNUM:#{data[:tagged]}}}
| data-sort-value=#{data[:deleted][:total]} | #{deleted_str}
| {{FORMATNUM:#{data[:edits]}}}
| #{block_str}
| #{revoked_str}
| #{links}
|-
END
end
markup = markup.chomp("\n|-") + "|}\n\n"
@mb.edit(REPORT_PAGE,
content: markup,
summary: "Reporting #{users.length} users eligible for autopatrolled"
)
end
# Get data about pages the user created that were deleted
# Returns:
# {
# total: total number of articles deleted
# Speedy: total number of articles deleted under [[WP:CSD]]
# PROD: total number of articles deleted under [[WP:PROD]] or [[WP:BLPPROD]]
# AfD: total number of articles deleted under [[WP:AfD]]
# }
def self.deleted_counts(username)
sql = %{
SELECT log_comment
FROM logging_logindex
LEFT JOIN archive_userindex ON ar_page_id = log_page
WHERE log_type = 'delete'
AND ar_user_text = ?
AND ar_namespace = 0
AND ar_parent_id = 0
AND ar_timestamp > #{@mb.db_date(@mb.now - 365)}
}
counts = {
total: 0,
Speedy: 0,
PROD: 0,
AfD: 0
}
@mb.repl_query(sql, username).to_a.each do |data|
# don't count technical or user-requested deletions
next if data['log_comment'] =~ /\[\[WP:CSD#G(6|7)\|/
counts[:total] += 1
case data['log_comment']
when /\[\[WP:CSD#/
counts[:Speedy] += 1
when /\[\[WP:(BLP)?PROD/
counts[:PROD] += 1
when /\[\[(Wikipedia|WP):Articles for deletion\//
counts[:AfD] += 1
end
end
counts
end
# Get the number of blocks the user had in the past year
def self.block_count(username)
sql = %{
SELECT COUNT(*) AS count
FROM logging_logindex
WHERE log_type = 'block'
AND log_title = ?
AND log_timestamp > #{@mb.db_date(@mb.now - 365)}
}
@mb.repl_query(sql, username).to_a.first['count']
end
# Check if the user has had the autopatrolled permission revoked in the past
def self.autopatrolled_revoked?(username)
sql = %{
SELECT COUNT(*) AS count
FROM logging_logindex
WHERE log_type = 'rights'
AND log_title = ?
AND log_params REGEXP "oldgroups.*?autoreviewer.*?newgroups(?!.*?autoreviewer)"
}
@mb.repl_query(sql, username).to_a.first['count'] > 0
end
# Get the page title, ID and creation date of articles created by the given user
def self.articles_created(username)
sql = %{
SELECT page_title, page_id, rev_timestamp
FROM revision_userindex
LEFT JOIN page ON page_id = rev_page
WHERE page_namespace = 0
AND rev_parent_id = 0
AND rev_user_text = ?
AND rev_deleted = 0
AND page_is_redirect = 0
}
@mb.repl_query(sql, username).to_a
end
# Get the number of articles created by the user that are in maintenance categories
def self.maintenance_count(articles)
# Create list of categories to be used in the `cl_to IN ()` clause
categories_sql = MAINTENANCE_CATEGORIES.collect { |c| "'#{c}'" }.join(',')
# Create list of article IDs to be used in the `cl_from IN ()` clause
article_ids = articles
.select { |a| @mb.parse_date(a['rev_timestamp']) > @mb.now - 365 }
.collect { |a| a['page_id'] }
sql = %{
SELECT COUNT(DISTINCT(cl_from)) AS count
FROM categorylinks
WHERE cl_from IN (#{article_ids.join(',')})
AND cl_to IN (#{categories_sql})
AND cl_type = 'page'
}
@mb.repl.query(sql).to_a.first['count']
end
# Get the usernames and edit counts of users who have created a page in the past month
def self.page_creators
# Cache so this can be re-called without repeating the query
return @page_creators if @page_creators
sql = %{
SELECT DISTINCT(user_name), user_editcount
FROM recentchanges
LEFT JOIN user
ON rc_user = user_id
LEFT JOIN page
ON rc_cur_id = page_id
WHERE
rc_timestamp > #{@mb.db_date(@mb.now - 3)} AND
rc_namespace = 0 AND
rc_bot = 0 AND
rc_new = 1 AND
page_is_redirect = 0 AND
NOT EXISTS
(
SELECT 1
FROM user_groups
WHERE ug_user = user_id
AND ( ug_group = 'autoreviewer' OR ug_group = 'sysop' )
)
}
@page_creators = @mb.repl.query(sql).to_a
end
end
AutopatrolledCandidates.run
|
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{devise_cas_authenticatable}
s.version = "1.3.6"
s.required_rubygems_version = Gem::Requirement.new("> 1.3.1") if s.respond_to? :required_rubygems_version=
s.authors = ["Nat Budin", "Jeremy Haile"]
s.description = %q{CAS authentication module for Devise}
s.license = "MIT"
s.email = %q{natbudin@gmail.com}
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.extra_rdoc_files = [
"README.md"
]
s.homepage = %q{http://github.com/nbudin/devise_cas_authenticatable}
s.require_paths = ["lib"]
s.rubygems_version = %q{1.5.0}
s.summary = %q{CAS authentication module for Devise}
s.add_runtime_dependency(%q<devise>, [">= 1.2.0"])
s.add_runtime_dependency(%q<rubycas-client>, [">= 2.2.1"])
s.add_development_dependency("rails", ">= 3.0.7")
s.add_development_dependency("rspec-rails")
s.add_development_dependency("mocha")
s.add_development_dependency("shoulda", "~> 3.4.0")
s.add_development_dependency("sqlite3-ruby")
s.add_development_dependency("sham_rack")
s.add_development_dependency("capybara", "~> 1.1.4")
s.add_development_dependency('crypt-isaac')
s.add_development_dependency('launchy')
s.add_development_dependency('timecop')
s.add_development_dependency('pry')
end
Relax Capybara version requirement to hopefully make RSpec happy on Travis
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{devise_cas_authenticatable}
s.version = "1.3.6"
s.required_rubygems_version = Gem::Requirement.new("> 1.3.1") if s.respond_to? :required_rubygems_version=
s.authors = ["Nat Budin", "Jeremy Haile"]
s.description = %q{CAS authentication module for Devise}
s.license = "MIT"
s.email = %q{natbudin@gmail.com}
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.extra_rdoc_files = [
"README.md"
]
s.homepage = %q{http://github.com/nbudin/devise_cas_authenticatable}
s.require_paths = ["lib"]
s.rubygems_version = %q{1.5.0}
s.summary = %q{CAS authentication module for Devise}
s.add_runtime_dependency(%q<devise>, [">= 1.2.0"])
s.add_runtime_dependency(%q<rubycas-client>, [">= 2.2.1"])
s.add_development_dependency("rails", ">= 3.0.7")
s.add_development_dependency("rspec-rails")
s.add_development_dependency("mocha")
s.add_development_dependency("shoulda", "~> 3.4.0")
s.add_development_dependency("sqlite3-ruby")
s.add_development_dependency("sham_rack")
s.add_development_dependency("capybara")
s.add_development_dependency('crypt-isaac')
s.add_development_dependency('launchy')
s.add_development_dependency('timecop')
s.add_development_dependency('pry')
end
|
################################################################################
#
# Author: Stephen Nelson-Smith <stephen@atalanta-systems.com>
# Author: Zachary Patten <zachary@jovelabs.com>
# Copyright: Copyright (c) 2011-2013 Atalanta Systems Ltd
# License: Apache License, Version 2.0
#
# 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.
#
################################################################################
require File.expand_path("../lib/cucumber/chef/version", __FILE__)
Gem::Specification.new do |s|
s.name = "cucumber-chef"
s.version = Cucumber::Chef::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Stephen Nelson-Smith", "Zachary Patten"]
s.email = ["stephen@atalanta-systems.com", "zachary@jovelabs.com"]
s.homepage = "http://www.cucumber-chef.org"
s.summary = "Test Driven Infrastructure"
s.description = "Framework for test-driven infrastructure development."
s.required_ruby_version = ">= 1.8.7"
s.required_rubygems_version = ">= 1.3.6"
s.licenses = ["Apache 2.0"]
# Providers
s.add_dependency("fog", ">= 1.3.1")
# TDD
s.add_dependency("cucumber", ">= 0")
s.add_dependency("rspec", ">= 0")
# Support
s.add_dependency("mixlib-config", ">= 1.1.2")
s.add_dependency("rake", ">= 0.9.2")
s.add_dependency("thor", ">= 0.15.2")
s.add_dependency("ubuntu_ami", ">= 0.4.0")
s.add_dependency("ztk", ">= 1.0.9")
s.add_development_dependency("simplecov", ">= 0.6.4")
s.add_development_dependency("pry", ">= 0")
s.add_development_dependency("yard", ">= 0")
s.add_development_dependency("redcarpet", ">= 0")
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_path = 'lib'
end
cleanup gemspec
################################################################################
#
# Author: Stephen Nelson-Smith <stephen@atalanta-systemspec.com>
# Author: Zachary Patten <zachary@jovelabspec.com>
# Copyright: Copyright (c) 2011-2013 Atalanta Systems Ltd
# License: Apache License, Version 2.0
#
# 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.
#
################################################################################
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'cucumber/chef/version'
Gem::Specification.new do |spec|
spec.name = "cucumber-chef"
spec.version = Cucumber::Chef::VERSION
spec.authors = ["Stephen Nelson-Smith", "Zachary Patten"]
spec.email = ["stephen@atalanta-systemspec.com", "zachary@jovelabspec.com"]
spec.description = "Framework for test-driven infrastructure development."
spec.summary = "Test Driven Infrastructure"
spec.homepage = "http://www.cucumber-chef.org"
spec.license = "Apache 2.0"
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"]
# Providers
spec.add_dependency("fog", ">= 1.3.1")
# TDD
spec.add_dependency("cucumber")
spec.add_dependency("rspec")
# Support
spec.add_dependency("mixlib-config", ">= 1.1.2")
spec.add_dependency("rake", ">= 0.9.2")
spec.add_dependency("thor", ">= 0.15.2")
spec.add_dependency("ubuntu_ami", ">= 0.4.0")
spec.add_dependency("ztk", ">= 1.0.9")
spec.add_development_dependency("simplecov")
spec.add_development_dependency("pry")
spec.add_development_dependency("yard")
spec.add_development_dependency("redcarpet")
end
|
examples: added digiblink example, but I haven't tested it, so hopefully it works! when my sparks arrive I'll have to give it a go ^_^
# A little example program for driving the digirgb example code
require 'digiusb'
light = DigiUSB.sparks.last # get the spark most recently plugged in (or maybe just a random one? not sure)
# some colour strings to lookup
color_table = {
red: [255, 0, 0],
green: [0, 255, 0],
blue: [0, 0, 255],
yellow: [255, 255, 0],
aqua: [0, 255, 255],
violet: [255, 0, 255],
purple: [255, 0, 255],
black: [0, 0, 0],
grey: [127, 127, 127],
white: [255, 255, 255]
}
if color_table.has_key? ARGV.first.to_sym
color = color_table[ARGV.first.to_sym]
else
color = ARGV.map { |string| string.to_i }
end
# send out each byte
light.putc 115 # start character 's'
light.putc color[0]
light.putc color[1]
light.putc color[2]
puts "Light should now be #{ARGV.join ':'}" |
require 'rake'
require 'rake/clean'
namespace(:dependencies) do
namespace(:openssl) do
package = RubyInstaller::OpenSsl
directory package.target
CLEAN.include(package.target)
CLEAN.include(package.install_target)
# Put files for the :download task
dt = checkpoint(:openssl, :download)
package.files.each do |f|
file_source = "#{package.url}/#{f}"
file_target = "downloads/#{f}"
download file_target => file_source
# depend on downloads directory
file file_target => "downloads"
# download task need these files as pre-requisites
dt.enhance [file_target]
end
task :download => dt
# Prepare the :sandbox, it requires the :download task
et = checkpoint(:openssl, :extract) do
dt.prerequisites.each { |f|
extract(File.join(RubyInstaller::ROOT, f), package.target, :noerror => true)
}
end
task :extract => [:extract_utils, :download, package.target, et]
# Apply patches
pt = checkpoint(:openssl, :prepare) do
patches = Dir.glob("#{package.patches}/*.patch").sort
patches.each do |patch|
sh "git apply --directory #{package.target} #{patch}"
end
end
task :prepare => [:extract, pt]
# Prepare sources for compilation
ct = checkpoint(:openssl, :configure) do
# set TERM to MSYS to generate symlinks
old_term = ENV['TERM']
ENV['TERM'] = 'msys'
install_target = File.join(RubyInstaller::ROOT, package.install_target)
cd package.target do
sh "perl ./Configure #{package.configure_options.join(' ')} --prefix=#{install_target}"
end
ENV['TERM'] = old_term
end
task :configure => [:prepare, :compiler, :zlib, ct]
mt = checkpoint(:openssl, :make) do
cd package.target do
# ensure dllwrap uses the correct compiler executable as its driver
compiler = DevKitInstaller::COMPILERS[ENV['DKVER']]
driver = compiler.program_prefix.nil? ? '': "--driver-name #{compiler.program_prefix}-gcc"
sh "make"
sh "perl util/mkdef.pl 32 libeay > libeay32.def"
sh "dllwrap --dllname #{package.dllnames[:libcrypto]} #{driver} --output-lib libcrypto.dll.a --def libeay32.def libcrypto.a -lwsock32 -lgdi32"
sh "perl util/mkdef.pl 32 ssleay > ssleay32.def"
sh "dllwrap --dllname #{package.dllnames[:libssl]} #{driver} --output-lib libssl.dll.a --def ssleay32.def libssl.a libcrypto.dll.a"
end
end
task :compile => [:configure, mt]
it = checkpoint(:openssl, :install) do
target = File.join(RubyInstaller::ROOT, RubyInstaller::OpenSsl.install_target)
cd package.target do
sh "make install_sw"
# these are not handled by make install
mkdir_p "#{target}/bin"
cp package.dllnames[:libcrypto], "#{target}/bin"
cp package.dllnames[:libssl], "#{target}/bin"
mkdir_p "#{target}/lib"
cp "libcrypto.dll.a", "#{target}/lib"
cp "libssl.dll.a", "#{target}/lib"
end
end
task :install => [:compile, it]
task :activate => [:compile] do
puts "Activating OpenSSL version #{package.version}"
activate(package.install_target)
end
end
end
task :openssl => [
'dependencies:openssl:download',
'dependencies:openssl:extract',
'dependencies:openssl:prepare',
'dependencies:openssl:compile',
'dependencies:openssl:install',
'dependencies:openssl:activate'
]
Teach OpenSSL recipe to use prefixed dllwrap.
require 'rake'
require 'rake/clean'
namespace(:dependencies) do
namespace(:openssl) do
package = RubyInstaller::OpenSsl
directory package.target
CLEAN.include(package.target)
CLEAN.include(package.install_target)
# Put files for the :download task
dt = checkpoint(:openssl, :download)
package.files.each do |f|
file_source = "#{package.url}/#{f}"
file_target = "downloads/#{f}"
download file_target => file_source
# depend on downloads directory
file file_target => "downloads"
# download task need these files as pre-requisites
dt.enhance [file_target]
end
task :download => dt
# Prepare the :sandbox, it requires the :download task
et = checkpoint(:openssl, :extract) do
dt.prerequisites.each { |f|
extract(File.join(RubyInstaller::ROOT, f), package.target, :noerror => true)
}
end
task :extract => [:extract_utils, :download, package.target, et]
# Apply patches
pt = checkpoint(:openssl, :prepare) do
patches = Dir.glob("#{package.patches}/*.patch").sort
patches.each do |patch|
sh "git apply --directory #{package.target} #{patch}"
end
end
task :prepare => [:extract, pt]
# Prepare sources for compilation
ct = checkpoint(:openssl, :configure) do
# set TERM to MSYS to generate symlinks
old_term = ENV['TERM']
ENV['TERM'] = 'msys'
install_target = File.join(RubyInstaller::ROOT, package.install_target)
cd package.target do
sh "perl ./Configure #{package.configure_options.join(' ')} --prefix=#{install_target}"
end
ENV['TERM'] = old_term
end
task :configure => [:prepare, :compiler, :zlib, ct]
mt = checkpoint(:openssl, :make) do
cd package.target do
# ensure dllwrap uses the correct compiler executable as its driver
compiler = DevKitInstaller::COMPILERS[ENV['DKVER']]
driver = compiler.program_prefix.nil? ? '': "--driver-name #{compiler.program_prefix}-gcc"
dllwrap = compiler.programs.include?(:dllwrap) && !compiler.program_prefix.nil? ?
"#{compiler.program_prefix}-dllwrap" :
'dllwrap'
sh "make"
sh "perl util/mkdef.pl 32 libeay > libeay32.def"
sh "#{dllwrap} --dllname #{package.dllnames[:libcrypto]} #{driver} --output-lib libcrypto.dll.a --def libeay32.def libcrypto.a -lwsock32 -lgdi32"
sh "perl util/mkdef.pl 32 ssleay > ssleay32.def"
sh "#{dllwrap} --dllname #{package.dllnames[:libssl]} #{driver} --output-lib libssl.dll.a --def ssleay32.def libssl.a libcrypto.dll.a"
end
end
task :compile => [:configure, mt]
it = checkpoint(:openssl, :install) do
target = File.join(RubyInstaller::ROOT, RubyInstaller::OpenSsl.install_target)
cd package.target do
sh "make install_sw"
# these are not handled by make install
mkdir_p "#{target}/bin"
cp package.dllnames[:libcrypto], "#{target}/bin"
cp package.dllnames[:libssl], "#{target}/bin"
mkdir_p "#{target}/lib"
cp "libcrypto.dll.a", "#{target}/lib"
cp "libssl.dll.a", "#{target}/lib"
end
end
task :install => [:compile, it]
task :activate => [:compile] do
puts "Activating OpenSSL version #{package.version}"
activate(package.install_target)
end
end
end
task :openssl => [
'dependencies:openssl:download',
'dependencies:openssl:extract',
'dependencies:openssl:prepare',
'dependencies:openssl:compile',
'dependencies:openssl:install',
'dependencies:openssl:activate'
]
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'siren_client/version'
Gem::Specification.new do |spec|
spec.name = "siren_client"
spec.version = SirenClient::VERSION
spec.authors = ["Chason Choate"]
spec.email = ["cha55son@gmail.com"]
spec.summary = %q{A client to traverse Siren APIs https://github.com/kevinswiber/siren}
spec.description = %q{SirenClient provides an ActiveRecord-like syntax to traverse Siren APIs.}
spec.homepage = "https://github.com/cha55son/siren_client"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.test_files = spec.files.grep(%r{^(spec)/})
spec.require_paths = ["lib"]
spec.add_dependency "httparty", "~> 0.13"
spec.add_dependency "activesupport", "~> 4"
spec.add_development_dependency "bundler", "~> 1.5"
spec.add_development_dependency "rack"
spec.add_development_dependency "rake"
spec.add_development_dependency "sinatra"
spec.add_development_dependency "rspec"
spec.add_development_dependency "byebug" if RUBY_VERSION > "2"
spec.add_development_dependency "guard"
spec.add_development_dependency "guard-rspec"
spec.add_development_dependency "coveralls"
end
Exclude byebug for java builds.
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'siren_client/version'
Gem::Specification.new do |spec|
spec.name = "siren_client"
spec.version = SirenClient::VERSION
spec.authors = ["Chason Choate"]
spec.email = ["cha55son@gmail.com"]
spec.summary = %q{A client to traverse Siren APIs https://github.com/kevinswiber/siren}
spec.description = %q{SirenClient provides an ActiveRecord-like syntax to traverse Siren APIs.}
spec.homepage = "https://github.com/cha55son/siren_client"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.test_files = spec.files.grep(%r{^(spec)/})
spec.require_paths = ["lib"]
spec.add_dependency "httparty", "~> 0.13"
spec.add_dependency "activesupport", "~> 4"
spec.add_development_dependency "bundler", "~> 1.5"
spec.add_development_dependency "rack"
spec.add_development_dependency "rake"
spec.add_development_dependency "sinatra"
spec.add_development_dependency "rspec"
spec.add_development_dependency "byebug" if RUBY_VERSION > "2" && RUBY_PLATFORM != "java"
spec.add_development_dependency "guard"
spec.add_development_dependency "guard-rspec"
spec.add_development_dependency "coveralls"
end
|
require 'rspec'
require 'capybara'
require 'ostruct'
require_relative 'visitor_agent'
require_relative 'app_descriptor'
# Set longer wait time since we're hitting external services
Capybara.default_wait_time = 30
MAGIC_NUMBERS = OpenStruct.new({
valid: "+15005550006",
invalid: "+15005550001",
unrouteable: "+15005550002",
})
# Get handle to world so we can stop the server at exit
class SuitorWorld
def server
@server
end
end
world = SuitorWorld.new
World { world }
After do
if @visitor and @visitor.session
@visitor.session.driver.browser.close
end
end
# Stop server at exit
at_exit do
if world.server
puts ""
puts "killing test suitor server...\n"
world.server.stop
end
end
Closing browser sessions is causing timing issues with tests; just leave them open for now.
require 'rspec'
require 'capybara'
require 'ostruct'
require_relative 'visitor_agent'
require_relative 'app_descriptor'
# Set longer wait time since we're hitting external services
Capybara.default_wait_time = 30
MAGIC_NUMBERS = OpenStruct.new({
valid: "+15005550006",
invalid: "+15005550001",
unrouteable: "+15005550002",
})
# Get handle to world so we can stop the server at exit
class SuitorWorld
def server
@server
end
end
world = SuitorWorld.new
World { world }
# Stop server at exit
at_exit do
if world.server
puts ""
puts "killing test suitor server...\n"
world.server.stop
end
end
|
require "vagrant-spec/acceptance/output"
module Vagrant
module Spec
# Default plugins within plugin list when run mode
# is set as "plugin"
DEFAULT_PLUGINS = ["vagrant-share".freeze].freeze
# Tests the Vagrant plugin list output has no plugins
OutputTester[:plugin_list_none] = lambda do |text|
text =~ /^No plugins/
end
# Tests that plugin list shows a plugin
OutputTester[:plugin_list_plugin] = lambda do |text, name, version|
text =~ /^#{name} \(#{version}\, global)$/
end
# Tests that Vagrant plugin install fails to a plugin not found
OutputTester[:plugin_install_not_found] = lambda do |text, name|
text =~ /Unable to resolve dependency:.* '#{name}/
end
# Tests that Vagrant plugin install fails to a plugin not found
OutputTester[:plugin_installed] = lambda do |text, name, version|
if version.nil?
text =~ /^Installed the plugin '#{name} \(/
else
text =~ /^Installed the plugin '#{name} \(#{version}\)'/
end
end
end
end
Properly escape the closing paren
require "vagrant-spec/acceptance/output"
module Vagrant
module Spec
# Default plugins within plugin list when run mode
# is set as "plugin"
DEFAULT_PLUGINS = ["vagrant-share".freeze].freeze
# Tests the Vagrant plugin list output has no plugins
OutputTester[:plugin_list_none] = lambda do |text|
text =~ /^No plugins/
end
# Tests that plugin list shows a plugin
OutputTester[:plugin_list_plugin] = lambda do |text, name, version|
text =~ /^#{name} \(#{version}, global\)$/
end
# Tests that Vagrant plugin install fails to a plugin not found
OutputTester[:plugin_install_not_found] = lambda do |text, name|
text =~ /Unable to resolve dependency:.* '#{name}/
end
# Tests that Vagrant plugin install fails to a plugin not found
OutputTester[:plugin_installed] = lambda do |text, name, version|
if version.nil?
text =~ /^Installed the plugin '#{name} \(/
else
text =~ /^Installed the plugin '#{name} \(#{version}\)'/
end
end
end
end
|
module ActionView #:nodoc:
class ActionViewError < StandardError #:nodoc:
end
class MissingTemplate < ActionViewError #:nodoc:
attr_reader :path
def initialize(paths, path, template_format = nil)
@path = path
full_template_path = path.include?('.') ? path : "#{path}.erb"
display_paths = paths.compact.join(":")
template_type = (path =~ /layouts/i) ? 'layout' : 'template'
super("Missing #{template_type} #{full_template_path} in view path #{display_paths}")
end
end
# Action View templates can be written in three ways. If the template file has a <tt>.erb</tt> (or <tt>.rhtml</tt>) extension then it uses a mixture of ERb
# (included in Ruby) and HTML. If the template file has a <tt>.builder</tt> (or <tt>.rxml</tt>) extension then Jim Weirich's Builder::XmlMarkup library is used.
# If the template file has a <tt>.rjs</tt> extension then it will use ActionView::Helpers::PrototypeHelper::JavaScriptGenerator.
#
# = ERb
#
# You trigger ERb by using embeddings such as <% %>, <% -%>, and <%= %>. The <%= %> tag set is used when you want output. Consider the
# following loop for names:
#
# <b>Names of all the people</b>
# <% for person in @people %>
# Name: <%= person.name %><br/>
# <% end %>
#
# The loop is setup in regular embedding tags <% %> and the name is written using the output embedding tag <%= %>. Note that this
# is not just a usage suggestion. Regular output functions like print or puts won't work with ERb templates. So this would be wrong:
#
# Hi, Mr. <% puts "Frodo" %>
#
# If you absolutely must write from within a function, you can use the TextHelper#concat.
#
# <%- and -%> suppress leading and trailing whitespace, including the trailing newline, and can be used interchangeably with <% and %>.
#
# == Using sub templates
#
# Using sub templates allows you to sidestep tedious replication and extract common display structures in shared templates. The
# classic example is the use of a header and footer (even though the Action Pack-way would be to use Layouts):
#
# <%= render "shared/header" %>
# Something really specific and terrific
# <%= render "shared/footer" %>
#
# As you see, we use the output embeddings for the render methods. The render call itself will just return a string holding the
# result of the rendering. The output embedding writes it to the current template.
#
# But you don't have to restrict yourself to static includes. Templates can share variables amongst themselves by using instance
# variables defined using the regular embedding tags. Like this:
#
# <% @page_title = "A Wonderful Hello" %>
# <%= render "shared/header" %>
#
# Now the header can pick up on the <tt>@page_title</tt> variable and use it for outputting a title tag:
#
# <title><%= @page_title %></title>
#
# == Passing local variables to sub templates
#
# You can pass local variables to sub templates by using a hash with the variable names as keys and the objects as values:
#
# <%= render "shared/header", { :headline => "Welcome", :person => person } %>
#
# These can now be accessed in <tt>shared/header</tt> with:
#
# Headline: <%= headline %>
# First name: <%= person.first_name %>
#
# If you need to find out whether a certain local variable has been assigned a value in a particular render call,
# you need to use the following pattern:
#
# <% if local_assigns.has_key? :headline %>
# Headline: <%= headline %>
# <% end %>
#
# Testing using <tt>defined? headline</tt> will not work. This is an implementation restriction.
#
# == Template caching
#
# By default, Rails will compile each template to a method in order to render it. When you alter a template, Rails will
# check the file's modification time and recompile it.
#
# == Builder
#
# Builder templates are a more programmatic alternative to ERb. They are especially useful for generating XML content. An XmlMarkup object
# named +xml+ is automatically made available to templates with a <tt>.builder</tt> extension.
#
# Here are some basic examples:
#
# xml.em("emphasized") # => <em>emphasized</em>
# xml.em { xml.b("emph & bold") } # => <em><b>emph & bold</b></em>
# xml.a("A Link", "href"=>"http://onestepback.org") # => <a href="http://onestepback.org">A Link</a>
# xml.target("name"=>"compile", "option"=>"fast") # => <target option="fast" name="compile"\>
# # NOTE: order of attributes is not specified.
#
# Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following:
#
# xml.div {
# xml.h1(@person.name)
# xml.p(@person.bio)
# }
#
# would produce something like:
#
# <div>
# <h1>David Heinemeier Hansson</h1>
# <p>A product of Danish Design during the Winter of '79...</p>
# </div>
#
# A full-length RSS example actually used on Basecamp:
#
# xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
# xml.channel do
# xml.title(@feed_title)
# xml.link(@url)
# xml.description "Basecamp: Recent items"
# xml.language "en-us"
# xml.ttl "40"
#
# for item in @recent_items
# xml.item do
# xml.title(item_title(item))
# xml.description(item_description(item)) if item_description(item)
# xml.pubDate(item_pubDate(item))
# xml.guid(@person.firm.account.url + @recent_items.url(item))
# xml.link(@person.firm.account.url + @recent_items.url(item))
#
# xml.tag!("dc:creator", item.author_name) if item_has_creator?(item)
# end
# end
# end
# end
#
# More builder documentation can be found at http://builder.rubyforge.org.
#
# == JavaScriptGenerator
#
# JavaScriptGenerator templates end in <tt>.rjs</tt>. Unlike conventional templates which are used to
# render the results of an action, these templates generate instructions on how to modify an already rendered page. This makes it easy to
# modify multiple elements on your page in one declarative Ajax response. Actions with these templates are called in the background with Ajax
# and make updates to the page where the request originated from.
#
# An instance of the JavaScriptGenerator object named +page+ is automatically made available to your template, which is implicitly wrapped in an ActionView::Helpers::PrototypeHelper#update_page block.
#
# When an <tt>.rjs</tt> action is called with +link_to_remote+, the generated JavaScript is automatically evaluated. Example:
#
# link_to_remote :url => {:action => 'delete'}
#
# The subsequently rendered <tt>delete.rjs</tt> might look like:
#
# page.replace_html 'sidebar', :partial => 'sidebar'
# page.remove "person-#{@person.id}"
# page.visual_effect :highlight, 'user-list'
#
# This refreshes the sidebar, removes a person element and highlights the user list.
#
# See the ActionView::Helpers::PrototypeHelper::GeneratorMethods documentation for more details.
class Base
include Helpers, Partials, ::ERB::Util
extend ActiveSupport::Memoizable
attr_accessor :base_path, :assigns, :template_extension
attr_accessor :controller
attr_writer :template_format
attr_accessor :output_buffer
class << self
delegate :erb_trim_mode=, :to => 'ActionView::TemplateHandlers::ERB'
delegate :logger, :to => 'ActionController::Base'
end
@@debug_rjs = false
##
# :singleton-method:
# Specify whether RJS responses should be wrapped in a try/catch block
# that alert()s the caught exception (and then re-raises it).
cattr_accessor :debug_rjs
# Specify whether templates should be cached. Otherwise the file we be read everytime it is accessed.
# Automatically reloading templates are not thread safe and should only be used in development mode.
@@cache_template_loading = nil
cattr_accessor :cache_template_loading
def self.cache_template_loading?
ActionController::Base.allow_concurrency || (cache_template_loading.nil? ? !ActiveSupport::Dependencies.load? : cache_template_loading)
end
attr_internal :request
delegate :request_forgery_protection_token, :template, :params, :session, :cookies, :response, :headers,
:flash, :logger, :action_name, :controller_name, :to => :controller
module CompiledTemplates #:nodoc:
# holds compiled template code
end
include CompiledTemplates
def self.process_view_paths(value)
ActionView::PathSet.new(Array(value))
end
attr_reader :helpers
class ProxyModule < Module
def initialize(receiver)
@receiver = receiver
end
def include(*args)
super(*args)
@receiver.extend(*args)
end
end
def initialize(view_paths = [], assigns_for_first_render = {}, controller = nil)#:nodoc:
@assigns = assigns_for_first_render
@assigns_added = nil
@controller = controller
@helpers = ProxyModule.new(self)
self.view_paths = view_paths
@_first_template = nil
@_current_template = nil
end
attr_reader :view_paths
def view_paths=(paths)
@view_paths = self.class.process_view_paths(paths)
# we might be using ReloadableTemplates, so we need to let them know this a new request
@view_paths.load!
end
# Returns the result of a render that's dictated by the options hash. The primary options are:
#
# * <tt>:partial</tt> - See ActionView::Partials.
# * <tt>:update</tt> - Calls update_page with the block given.
# * <tt>:file</tt> - Renders an explicit template file (this used to be the old default), add :locals to pass in those.
# * <tt>:inline</tt> - Renders an inline template similar to how it's done in the controller.
# * <tt>:text</tt> - Renders the text passed in out.
#
# If no options hash is passed or :update specified, the default is to render a partial and use the second parameter
# as the locals hash.
def render(options = {}, local_assigns = {}, &block) #:nodoc:
local_assigns ||= {}
case options
when Hash
options = options.reverse_merge(:locals => {})
if options[:layout]
_render_with_layout(options, local_assigns, &block)
elsif options[:file]
template = self.view_paths.find_template(options[:file], template_format)
template.render_template(self, options[:locals])
elsif options[:partial]
render_partial(options)
elsif options[:inline]
InlineTemplate.new(options[:inline], options[:type]).render(self, options[:locals])
elsif options[:text]
options[:text]
end
when :update
update_page(&block)
else
render_partial(:partial => options, :locals => local_assigns)
end
end
# The format to be used when choosing between multiple templates with
# the same name but differing formats. See +Request#template_format+
# for more details.
def template_format
if defined? @template_format
@template_format
elsif controller && controller.respond_to?(:request)
@template_format = controller.request.template_format.to_sym
else
@template_format = :html
end
end
# Access the current template being rendered.
# Returns a ActionView::Template object.
def template
@_current_template
end
def template=(template) #:nodoc:
@_first_template ||= template
@_current_template = template
end
def with_template(current_template)
last_template, self.template = template, current_template
yield
ensure
self.template = last_template
end
private
# Evaluates the local assigns and controller ivars, pushes them to the view.
def _evaluate_assigns_and_ivars #:nodoc:
unless @assigns_added
@assigns.each { |key, value| instance_variable_set("@#{key}", value) }
_copy_ivars_from_controller
@assigns_added = true
end
end
def _copy_ivars_from_controller #:nodoc:
if @controller
variables = @controller.instance_variable_names
variables -= @controller.protected_instance_variables if @controller.respond_to?(:protected_instance_variables)
variables.each { |name| instance_variable_set(name, @controller.instance_variable_get(name)) }
end
end
def _set_controller_content_type(content_type) #:nodoc:
if controller.respond_to?(:response)
controller.response.content_type ||= content_type
end
end
def _render_with_layout(options, local_assigns, &block) #:nodoc:
partial_layout = options.delete(:layout)
if block_given?
begin
@_proc_for_layout = block
concat(render(options.merge(:partial => partial_layout)))
ensure
@_proc_for_layout = nil
end
else
begin
original_content_for_layout = @content_for_layout if defined?(@content_for_layout)
@content_for_layout = render(options)
if (options[:inline] || options[:file] || options[:text])
@cached_content_for_layout = @content_for_layout
render(:file => partial_layout, :locals => local_assigns)
else
render(options.merge(:partial => partial_layout))
end
ensure
@content_for_layout = original_content_for_layout
end
end
end
end
end
Change naming to match 2.2 so life is easier on plugin developers
module ActionView #:nodoc:
class ActionViewError < StandardError #:nodoc:
end
class MissingTemplate < ActionViewError #:nodoc:
attr_reader :path
def initialize(paths, path, template_format = nil)
@path = path
full_template_path = path.include?('.') ? path : "#{path}.erb"
display_paths = paths.compact.join(":")
template_type = (path =~ /layouts/i) ? 'layout' : 'template'
super("Missing #{template_type} #{full_template_path} in view path #{display_paths}")
end
end
# Action View templates can be written in three ways. If the template file has a <tt>.erb</tt> (or <tt>.rhtml</tt>) extension then it uses a mixture of ERb
# (included in Ruby) and HTML. If the template file has a <tt>.builder</tt> (or <tt>.rxml</tt>) extension then Jim Weirich's Builder::XmlMarkup library is used.
# If the template file has a <tt>.rjs</tt> extension then it will use ActionView::Helpers::PrototypeHelper::JavaScriptGenerator.
#
# = ERb
#
# You trigger ERb by using embeddings such as <% %>, <% -%>, and <%= %>. The <%= %> tag set is used when you want output. Consider the
# following loop for names:
#
# <b>Names of all the people</b>
# <% for person in @people %>
# Name: <%= person.name %><br/>
# <% end %>
#
# The loop is setup in regular embedding tags <% %> and the name is written using the output embedding tag <%= %>. Note that this
# is not just a usage suggestion. Regular output functions like print or puts won't work with ERb templates. So this would be wrong:
#
# Hi, Mr. <% puts "Frodo" %>
#
# If you absolutely must write from within a function, you can use the TextHelper#concat.
#
# <%- and -%> suppress leading and trailing whitespace, including the trailing newline, and can be used interchangeably with <% and %>.
#
# == Using sub templates
#
# Using sub templates allows you to sidestep tedious replication and extract common display structures in shared templates. The
# classic example is the use of a header and footer (even though the Action Pack-way would be to use Layouts):
#
# <%= render "shared/header" %>
# Something really specific and terrific
# <%= render "shared/footer" %>
#
# As you see, we use the output embeddings for the render methods. The render call itself will just return a string holding the
# result of the rendering. The output embedding writes it to the current template.
#
# But you don't have to restrict yourself to static includes. Templates can share variables amongst themselves by using instance
# variables defined using the regular embedding tags. Like this:
#
# <% @page_title = "A Wonderful Hello" %>
# <%= render "shared/header" %>
#
# Now the header can pick up on the <tt>@page_title</tt> variable and use it for outputting a title tag:
#
# <title><%= @page_title %></title>
#
# == Passing local variables to sub templates
#
# You can pass local variables to sub templates by using a hash with the variable names as keys and the objects as values:
#
# <%= render "shared/header", { :headline => "Welcome", :person => person } %>
#
# These can now be accessed in <tt>shared/header</tt> with:
#
# Headline: <%= headline %>
# First name: <%= person.first_name %>
#
# If you need to find out whether a certain local variable has been assigned a value in a particular render call,
# you need to use the following pattern:
#
# <% if local_assigns.has_key? :headline %>
# Headline: <%= headline %>
# <% end %>
#
# Testing using <tt>defined? headline</tt> will not work. This is an implementation restriction.
#
# == Template caching
#
# By default, Rails will compile each template to a method in order to render it. When you alter a template, Rails will
# check the file's modification time and recompile it.
#
# == Builder
#
# Builder templates are a more programmatic alternative to ERb. They are especially useful for generating XML content. An XmlMarkup object
# named +xml+ is automatically made available to templates with a <tt>.builder</tt> extension.
#
# Here are some basic examples:
#
# xml.em("emphasized") # => <em>emphasized</em>
# xml.em { xml.b("emph & bold") } # => <em><b>emph & bold</b></em>
# xml.a("A Link", "href"=>"http://onestepback.org") # => <a href="http://onestepback.org">A Link</a>
# xml.target("name"=>"compile", "option"=>"fast") # => <target option="fast" name="compile"\>
# # NOTE: order of attributes is not specified.
#
# Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following:
#
# xml.div {
# xml.h1(@person.name)
# xml.p(@person.bio)
# }
#
# would produce something like:
#
# <div>
# <h1>David Heinemeier Hansson</h1>
# <p>A product of Danish Design during the Winter of '79...</p>
# </div>
#
# A full-length RSS example actually used on Basecamp:
#
# xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
# xml.channel do
# xml.title(@feed_title)
# xml.link(@url)
# xml.description "Basecamp: Recent items"
# xml.language "en-us"
# xml.ttl "40"
#
# for item in @recent_items
# xml.item do
# xml.title(item_title(item))
# xml.description(item_description(item)) if item_description(item)
# xml.pubDate(item_pubDate(item))
# xml.guid(@person.firm.account.url + @recent_items.url(item))
# xml.link(@person.firm.account.url + @recent_items.url(item))
#
# xml.tag!("dc:creator", item.author_name) if item_has_creator?(item)
# end
# end
# end
# end
#
# More builder documentation can be found at http://builder.rubyforge.org.
#
# == JavaScriptGenerator
#
# JavaScriptGenerator templates end in <tt>.rjs</tt>. Unlike conventional templates which are used to
# render the results of an action, these templates generate instructions on how to modify an already rendered page. This makes it easy to
# modify multiple elements on your page in one declarative Ajax response. Actions with these templates are called in the background with Ajax
# and make updates to the page where the request originated from.
#
# An instance of the JavaScriptGenerator object named +page+ is automatically made available to your template, which is implicitly wrapped in an ActionView::Helpers::PrototypeHelper#update_page block.
#
# When an <tt>.rjs</tt> action is called with +link_to_remote+, the generated JavaScript is automatically evaluated. Example:
#
# link_to_remote :url => {:action => 'delete'}
#
# The subsequently rendered <tt>delete.rjs</tt> might look like:
#
# page.replace_html 'sidebar', :partial => 'sidebar'
# page.remove "person-#{@person.id}"
# page.visual_effect :highlight, 'user-list'
#
# This refreshes the sidebar, removes a person element and highlights the user list.
#
# See the ActionView::Helpers::PrototypeHelper::GeneratorMethods documentation for more details.
class Base
include Helpers, Partials, ::ERB::Util
extend ActiveSupport::Memoizable
attr_accessor :base_path, :assigns, :template_extension
attr_accessor :controller
attr_writer :template_format
attr_accessor :output_buffer
class << self
delegate :erb_trim_mode=, :to => 'ActionView::TemplateHandlers::ERB'
delegate :logger, :to => 'ActionController::Base'
end
@@debug_rjs = false
##
# :singleton-method:
# Specify whether RJS responses should be wrapped in a try/catch block
# that alert()s the caught exception (and then re-raises it).
cattr_accessor :debug_rjs
# Specify whether templates should be cached. Otherwise the file we be read everytime it is accessed.
# Automatically reloading templates are not thread safe and should only be used in development mode.
@@cache_template_loading = nil
cattr_accessor :cache_template_loading
def self.cache_template_loading?
ActionController::Base.allow_concurrency || (cache_template_loading.nil? ? !ActiveSupport::Dependencies.load? : cache_template_loading)
end
attr_internal :request
delegate :request_forgery_protection_token, :template, :params, :session, :cookies, :response, :headers,
:flash, :logger, :action_name, :controller_name, :to => :controller
module CompiledTemplates #:nodoc:
# holds compiled template code
end
include CompiledTemplates
def self.process_view_paths(value)
ActionView::PathSet.new(Array(value))
end
attr_reader :helpers
class ProxyModule < Module
def initialize(receiver)
@receiver = receiver
end
def include(*args)
super(*args)
@receiver.extend(*args)
end
end
def initialize(view_paths = [], assigns_for_first_render = {}, controller = nil)#:nodoc:
@assigns = assigns_for_first_render
@assigns_added = nil
@controller = controller
@helpers = ProxyModule.new(self)
self.view_paths = view_paths
@_first_render = nil
@_current_render = nil
end
attr_reader :view_paths
def view_paths=(paths)
@view_paths = self.class.process_view_paths(paths)
# we might be using ReloadableTemplates, so we need to let them know this a new request
@view_paths.load!
end
# Returns the result of a render that's dictated by the options hash. The primary options are:
#
# * <tt>:partial</tt> - See ActionView::Partials.
# * <tt>:update</tt> - Calls update_page with the block given.
# * <tt>:file</tt> - Renders an explicit template file (this used to be the old default), add :locals to pass in those.
# * <tt>:inline</tt> - Renders an inline template similar to how it's done in the controller.
# * <tt>:text</tt> - Renders the text passed in out.
#
# If no options hash is passed or :update specified, the default is to render a partial and use the second parameter
# as the locals hash.
def render(options = {}, local_assigns = {}, &block) #:nodoc:
local_assigns ||= {}
case options
when Hash
options = options.reverse_merge(:locals => {})
if options[:layout]
_render_with_layout(options, local_assigns, &block)
elsif options[:file]
template = self.view_paths.find_template(options[:file], template_format)
template.render_template(self, options[:locals])
elsif options[:partial]
render_partial(options)
elsif options[:inline]
InlineTemplate.new(options[:inline], options[:type]).render(self, options[:locals])
elsif options[:text]
options[:text]
end
when :update
update_page(&block)
else
render_partial(:partial => options, :locals => local_assigns)
end
end
# The format to be used when choosing between multiple templates with
# the same name but differing formats. See +Request#template_format+
# for more details.
def template_format
if defined? @template_format
@template_format
elsif controller && controller.respond_to?(:request)
@template_format = controller.request.template_format.to_sym
else
@template_format = :html
end
end
# Access the current template being rendered.
# Returns a ActionView::Template object.
def template
@_current_render
end
def template=(template) #:nodoc:
@_first_render ||= template
@_current_render = template
end
def with_template(current_template)
last_template, self.template = template, current_template
yield
ensure
self.template = last_template
end
private
# Evaluates the local assigns and controller ivars, pushes them to the view.
def _evaluate_assigns_and_ivars #:nodoc:
unless @assigns_added
@assigns.each { |key, value| instance_variable_set("@#{key}", value) }
_copy_ivars_from_controller
@assigns_added = true
end
end
def _copy_ivars_from_controller #:nodoc:
if @controller
variables = @controller.instance_variable_names
variables -= @controller.protected_instance_variables if @controller.respond_to?(:protected_instance_variables)
variables.each { |name| instance_variable_set(name, @controller.instance_variable_get(name)) }
end
end
def _set_controller_content_type(content_type) #:nodoc:
if controller.respond_to?(:response)
controller.response.content_type ||= content_type
end
end
def _render_with_layout(options, local_assigns, &block) #:nodoc:
partial_layout = options.delete(:layout)
if block_given?
begin
@_proc_for_layout = block
concat(render(options.merge(:partial => partial_layout)))
ensure
@_proc_for_layout = nil
end
else
begin
original_content_for_layout = @content_for_layout if defined?(@content_for_layout)
@content_for_layout = render(options)
if (options[:inline] || options[:file] || options[:text])
@cached_content_for_layout = @content_for_layout
render(:file => partial_layout, :locals => local_assigns)
else
render(options.merge(:partial => partial_layout))
end
ensure
@content_for_layout = original_content_for_layout
end
end
end
end
end
|
# somatics.rb
# app_name = ask 'Type your Application Name for the Heroku project, followed by [ENTER]:'
#
# repo_entered = ask 'Type your repository for the project (SVN), followed by [ENTER]:'
gem 'will_paginate', :git => 'git://github.com/mislav/will_paginate.git', :branch => "rails3"
gem 'prawn', :version => '0.6.3'
gem 'somatics3-generators'
gem 'json'
plugin 'action_mailer_optional_tls',
:git => 'git://github.com/collectiveidea/action_mailer_optional_tls.git'
plugin 'faster_csv',
:git => 'git://github.com/circle/fastercsv.git'
plugin 'prawnto',
:git => 'git://github.com/thorny-sun/prawnto.git'
plugin 'redmine_filter',
:git => 'git://github.com/inspiresynergy/redmine_filter.git'
plugin 'restful_authentication',
:git => 'git://github.com/Satish/restful-authentication.git'
# :git => 'git://github.com/technoweenie/restful-authentication.git'
# plugin 'somatics_generator',
# :git => 'git://github.com/inspiresynergy/somatics_generator.git'
# theme_support break my rails 2.3.5
# http://inspiresynergy.lighthouseapp.com/projects/53315-somatics/tickets/14-theme_support-break-my-rails-235
# plugin 'theme_support',
# :git => 'git://github.com/aussiegeek/theme_support.git'
plugin 'tinymce_hammer',
:git => 'git://github.com/trevorrowe/tinymce_hammer.git'
plugin 'to_xls',
:git => 'git://github.com/arydjmal/to_xls.git'
plugin 'dynamic_form',
:git => 'git://github.com/rails/dynamic_form.git'
rakefile "setup_svn.rake" do
<<-TASK
desc "Configure Subversion for Rails"
task :setup_svn do
system "svn info"
if $? != 0
puts 'Please Import your project to svn before executing this task'
exit(0)
end
system "svn commit -m 'initial commit'"
puts "Add .gems"
system "svn add .gems"
system "svn commit -m 'add .gems'"
puts "Add .gitignore"
system "echo '.svn' > .gitignore"
system "svn add .gitignore"
system "svn commit -m 'add .gitignore'"
puts "Ignoring .git"
system "svn propset svn:ignore '.git' ."
puts "Removing /log"
system "svn remove log/*"
system "svn commit -m 'removing all log files from subversion'"
system 'svn propset svn:ignore "*.log" log/'
system "svn update log/"
system "svn commit -m 'Ignoring all files in /log/ ending in .log'"
puts "Ignoring /db"
system 'svn propset svn:ignore "*.db" db/'
system "svn update db/"
system "svn commit -m 'Ignoring all files in /db/ ending in .db'"
puts "Renaming database.yml database.example"
system "svn move config/database.yml config/database.example"
system "svn commit -m 'Moving database.yml to database.example to provide a template for anyone who checks out the code'"
system 'svn propset svn:ignore "database.yml" config/'
system "svn update config/"
system "svn commit -m 'Ignoring database.yml'"
puts "Ignoring /tmp"
system 'svn propset svn:ignore "*" tmp/'
system "svn update tmp/"
system "svn commit -m 'Ignoring all files in /tmp/'"
puts "Ignoring /doc"
system 'svn propset svn:ignore "*" doc/'
system "svn update doc/"
system "svn commit -m 'Ignoring all files in /doc/'"
end
TASK
end
# rake "gems:install", :sudo => true
generate "somatics:install"
environment 'config.autoload_paths += %W(#{config.root}/lib)'
generate "somatics:authenticated user"
generate "somatics:authenticated_controller admin/user --model=User"
#
# generate "tinymce_installation"
# generate "admin_controllers"
# generate "admin_scaffold user --admin-authenticated"
# generate "admin_setting"
#
# rake "db:create"
# rake "db:migrate"
# unless app_name.blank?
# run "git init"
# rake "heroku:gems"
# run "heroku create #{app_name}"
# run "git add ."
# run "git commit -a -m 'Initial Commit' "
# run "heroku addons:add cron:daily"
# run "heroku addons:add deployhooks:email \
# recipient=heroku@inspiresynergy.com \
# subject=\"#{app_name} Deployed\" \
# body=\"{{user}} deployed app\""
# run "heroku addons:add piggyback_ssl"
# run "heroku addons:add newrelic:bronze"
# run "heroku addons:add cron:daily"
# run "git push heroku master"
# run "heroku rake db:migrate"
# end
#
# unless repo_entered.blank?
# run "svn co #{repo_entered}"
# rake "setup_svn"
# end
change to will_paginate 3.0.pre2
# somatics.rb
# app_name = ask 'Type your Application Name for the Heroku project, followed by [ENTER]:'
#
# repo_entered = ask 'Type your repository for the project (SVN), followed by [ENTER]:'
gem 'will_paginate', :version => "~> 3.0.pre2"
gem 'prawn', :version => '0.6.3'
gem 'somatics3-generators'
gem 'json'
plugin 'action_mailer_optional_tls',
:git => 'git://github.com/collectiveidea/action_mailer_optional_tls.git'
plugin 'faster_csv',
:git => 'git://github.com/circle/fastercsv.git'
plugin 'prawnto',
:git => 'git://github.com/thorny-sun/prawnto.git'
plugin 'redmine_filter',
:git => 'git://github.com/inspiresynergy/redmine_filter.git'
plugin 'restful_authentication',
:git => 'git://github.com/Satish/restful-authentication.git'
# :git => 'git://github.com/technoweenie/restful-authentication.git'
# plugin 'somatics_generator',
# :git => 'git://github.com/inspiresynergy/somatics_generator.git'
# theme_support break my rails 2.3.5
# http://inspiresynergy.lighthouseapp.com/projects/53315-somatics/tickets/14-theme_support-break-my-rails-235
# plugin 'theme_support',
# :git => 'git://github.com/aussiegeek/theme_support.git'
plugin 'tinymce_hammer',
:git => 'git://github.com/trevorrowe/tinymce_hammer.git'
plugin 'to_xls',
:git => 'git://github.com/arydjmal/to_xls.git'
plugin 'dynamic_form',
:git => 'git://github.com/rails/dynamic_form.git'
rakefile "setup_svn.rake" do
<<-TASK
desc "Configure Subversion for Rails"
task :setup_svn do
system "svn info"
if $? != 0
puts 'Please Import your project to svn before executing this task'
exit(0)
end
system "svn commit -m 'initial commit'"
puts "Add .gems"
system "svn add .gems"
system "svn commit -m 'add .gems'"
puts "Add .gitignore"
system "echo '.svn' > .gitignore"
system "svn add .gitignore"
system "svn commit -m 'add .gitignore'"
puts "Ignoring .git"
system "svn propset svn:ignore '.git' ."
puts "Removing /log"
system "svn remove log/*"
system "svn commit -m 'removing all log files from subversion'"
system 'svn propset svn:ignore "*.log" log/'
system "svn update log/"
system "svn commit -m 'Ignoring all files in /log/ ending in .log'"
puts "Ignoring /db"
system 'svn propset svn:ignore "*.db" db/'
system "svn update db/"
system "svn commit -m 'Ignoring all files in /db/ ending in .db'"
puts "Renaming database.yml database.example"
system "svn move config/database.yml config/database.example"
system "svn commit -m 'Moving database.yml to database.example to provide a template for anyone who checks out the code'"
system 'svn propset svn:ignore "database.yml" config/'
system "svn update config/"
system "svn commit -m 'Ignoring database.yml'"
puts "Ignoring /tmp"
system 'svn propset svn:ignore "*" tmp/'
system "svn update tmp/"
system "svn commit -m 'Ignoring all files in /tmp/'"
puts "Ignoring /doc"
system 'svn propset svn:ignore "*" doc/'
system "svn update doc/"
system "svn commit -m 'Ignoring all files in /doc/'"
end
TASK
end
# rake "gems:install", :sudo => true
generate "somatics:install"
environment 'config.autoload_paths += %W(#{config.root}/lib)'
generate "somatics:authenticated user"
generate "somatics:authenticated_controller admin/user --model=User"
#
# generate "tinymce_installation"
# generate "admin_controllers"
# generate "admin_scaffold user --admin-authenticated"
# generate "admin_setting"
#
# rake "db:create"
# rake "db:migrate"
# unless app_name.blank?
# run "git init"
# rake "heroku:gems"
# run "heroku create #{app_name}"
# run "git add ."
# run "git commit -a -m 'Initial Commit' "
# run "heroku addons:add cron:daily"
# run "heroku addons:add deployhooks:email \
# recipient=heroku@inspiresynergy.com \
# subject=\"#{app_name} Deployed\" \
# body=\"{{user}} deployed app\""
# run "heroku addons:add piggyback_ssl"
# run "heroku addons:add newrelic:bronze"
# run "heroku addons:add cron:daily"
# run "git push heroku master"
# run "heroku rake db:migrate"
# end
#
# unless repo_entered.blank?
# run "svn co #{repo_entered}"
# rake "setup_svn"
# end
|
#!/usr/bin/env ruby
MSPEC_HOME = File.expand_path(File.dirname(__FILE__) + '/../../..')
require 'mspec/version'
require 'mspec/utils/options'
require 'mspec/utils/script'
require 'mspec/helpers/tmp'
require 'mspec/runner/actions/timer'
class MSpecMain < MSpecScript
def initialize
config[:includes] = []
config[:requires] = []
config[:target] = ENV['RUBY'] || 'ruby'
config[:flags] = []
config[:command] = nil
config[:options] = []
end
def options(argv=ARGV)
config[:command] = argv.shift if ["ci", "run", "tag"].include?(argv[0])
options = MSpecOptions.new "mspec [COMMAND] [options] (FILE|DIRECTORY|GLOB)+", 30, config
options.doc " The mspec command sets up and invokes the sub-commands"
options.doc " (see below) to enable, for instance, running the specs"
options.doc " with different implementations like ruby, jruby, rbx, etc.\n"
options.configure do |f|
load f
config[:options] << '-B' << f
end
options.targets
options.on("-D", "--gdb", "Run under gdb") do
config[:use_gdb] = true
end
options.on("-A", "--valgrind", "Run under valgrind") do
config[:flags] << '--valgrind'
end
options.on("--warnings", "Don't supress warnings") do
config[:flags] << '-w'
ENV['OUTPUT_WARNINGS'] = '1'
end
options.on("-j", "--multi", "Run multiple (possibly parallel) subprocesses") do
config[:multi] = true
config[:options] << "-fy"
end
options.on("--agent", "Start the Rubinius agent") do
config[:agent] = true
end
options.version MSpec::VERSION do
if config[:command]
config[:options] << "-v"
else
puts "#{File.basename $0} #{MSpec::VERSION}"
exit
end
end
options.help do
if config[:command]
config[:options] << "-h"
else
puts options
exit 1
end
end
options.doc "\n Custom options"
custom_options options
# The rest of the help output
options.doc "\n where COMMAND is one of:\n"
options.doc " run - Run the specified specs (default)"
options.doc " ci - Run the known good specs"
options.doc " tag - Add or remove tags\n"
options.doc " mspec COMMAND -h for more options\n"
options.on_extra { |o| config[:options] << o }
config[:options].concat options.parse(argv)
end
def register; end
def parallel
@parallel ||= !(Object.const_defined?(:JRUBY_VERSION) ||
/(mswin|mingw)/ =~ RUBY_PLATFORM)
end
def fork(&block)
parallel ? Kernel.fork(&block) : block.call
end
def report(files, timer)
require 'yaml'
exceptions = []
tally = Tally.new
files.each do |file|
d = File.open(file, "r") { |f| YAML.load f }
File.delete file
exceptions += Array(d['exceptions'])
tally.files! d['files']
tally.examples! d['examples']
tally.expectations! d['expectations']
tally.errors! d['errors']
tally.failures! d['failures']
end
print "\n"
exceptions.each_with_index do |exc, index|
print "\n#{index+1})\n", exc, "\n"
end
print "\n#{timer.format}\n\n#{tally.format}\n"
end
def multi_exec(argv)
timer = TimerAction.new
timer.start
files = config[:ci_files].inject([]) do |list, item|
name = tmp "mspec-ci-multi-#{list.size}"
rest = argv + ["-o", name, item]
fork { system [config[:target], *rest].join(" ") }
list << name
end
Process.waitall
timer.finish
report files, timer
end
def run
ENV['MSPEC_RUNNER'] = '1'
ENV['RUBY_EXE'] = config[:target]
ENV['RUBY_FLAGS'] = config[:flags].join " "
argv = []
if config[:agent]
argv << "-Xagent.start"
end
argv.concat config[:flags]
argv.concat config[:includes]
argv.concat config[:requires]
argv << "-v"
argv << "#{MSPEC_HOME}/bin/mspec-#{ config[:command] || "run" }"
argv.concat config[:options]
if config[:multi] and config[:command] == "ci"
multi_exec argv
else
if config[:use_gdb]
more = ["--args", config[:target]] + argv
exec "gdb", *more
else
exec config[:target], *argv
end
end
end
end
Remove --agent from default mspec.
#!/usr/bin/env ruby
MSPEC_HOME = File.expand_path(File.dirname(__FILE__) + '/../../..')
require 'mspec/version'
require 'mspec/utils/options'
require 'mspec/utils/script'
require 'mspec/helpers/tmp'
require 'mspec/runner/actions/timer'
class MSpecMain < MSpecScript
def initialize
config[:includes] = []
config[:requires] = []
config[:target] = ENV['RUBY'] || 'ruby'
config[:flags] = []
config[:command] = nil
config[:options] = []
end
def options(argv=ARGV)
config[:command] = argv.shift if ["ci", "run", "tag"].include?(argv[0])
options = MSpecOptions.new "mspec [COMMAND] [options] (FILE|DIRECTORY|GLOB)+", 30, config
options.doc " The mspec command sets up and invokes the sub-commands"
options.doc " (see below) to enable, for instance, running the specs"
options.doc " with different implementations like ruby, jruby, rbx, etc.\n"
options.configure do |f|
load f
config[:options] << '-B' << f
end
options.targets
options.on("-D", "--gdb", "Run under gdb") do
config[:use_gdb] = true
end
options.on("-A", "--valgrind", "Run under valgrind") do
config[:flags] << '--valgrind'
end
options.on("--warnings", "Don't supress warnings") do
config[:flags] << '-w'
ENV['OUTPUT_WARNINGS'] = '1'
end
options.on("-j", "--multi", "Run multiple (possibly parallel) subprocesses") do
config[:multi] = true
config[:options] << "-fy"
end
options.version MSpec::VERSION do
if config[:command]
config[:options] << "-v"
else
puts "#{File.basename $0} #{MSpec::VERSION}"
exit
end
end
options.help do
if config[:command]
config[:options] << "-h"
else
puts options
exit 1
end
end
options.doc "\n Custom options"
custom_options options
# The rest of the help output
options.doc "\n where COMMAND is one of:\n"
options.doc " run - Run the specified specs (default)"
options.doc " ci - Run the known good specs"
options.doc " tag - Add or remove tags\n"
options.doc " mspec COMMAND -h for more options\n"
options.on_extra { |o| config[:options] << o }
config[:options].concat options.parse(argv)
end
def register; end
def parallel
@parallel ||= !(Object.const_defined?(:JRUBY_VERSION) ||
/(mswin|mingw)/ =~ RUBY_PLATFORM)
end
def fork(&block)
parallel ? Kernel.fork(&block) : block.call
end
def report(files, timer)
require 'yaml'
exceptions = []
tally = Tally.new
files.each do |file|
d = File.open(file, "r") { |f| YAML.load f }
File.delete file
exceptions += Array(d['exceptions'])
tally.files! d['files']
tally.examples! d['examples']
tally.expectations! d['expectations']
tally.errors! d['errors']
tally.failures! d['failures']
end
print "\n"
exceptions.each_with_index do |exc, index|
print "\n#{index+1})\n", exc, "\n"
end
print "\n#{timer.format}\n\n#{tally.format}\n"
end
def multi_exec(argv)
timer = TimerAction.new
timer.start
files = config[:ci_files].inject([]) do |list, item|
name = tmp "mspec-ci-multi-#{list.size}"
rest = argv + ["-o", name, item]
fork { system [config[:target], *rest].join(" ") }
list << name
end
Process.waitall
timer.finish
report files, timer
end
def run
ENV['MSPEC_RUNNER'] = '1'
ENV['RUBY_EXE'] = config[:target]
ENV['RUBY_FLAGS'] = config[:flags].join " "
argv = []
argv.concat config[:flags]
argv.concat config[:includes]
argv.concat config[:requires]
argv << "-v"
argv << "#{MSPEC_HOME}/bin/mspec-#{ config[:command] || "run" }"
argv.concat config[:options]
if config[:multi] and config[:command] == "ci"
multi_exec argv
else
if config[:use_gdb]
more = ["--args", config[:target]] + argv
exec "gdb", *more
else
exec config[:target], *argv
end
end
end
end
|
#!/bin/ruby
require 'date'
require 'json'
require 'shellwords'
if ARGV.length < 1
STDERR.puts('Usage: ' + __FILE__ + ' PATH')
exit(1)
end
remote_log_path = '/srv/www/tmp.sakuya.pl/public_html/mal/watched.lst'
remote_host = 'burza'
local_host = `hostname`.strip!
video_path = File.realpath(ARGV[0])
json = {
time: Time.now.to_datetime.rfc3339,
path: video_path,
host: local_host
}.to_json
ssh_command = format('echo %s >> %s',
Shellwords.escape(json),
Shellwords.escape(remote_log_path))
`mplayer #{Shellwords.escape(video_path)}`
`ssh #{remote_host} #{Shellwords.escape(ssh_command)}`
Switched to MPV
#!/bin/ruby
require 'date'
require 'json'
require 'shellwords'
if ARGV.length < 1
STDERR.puts('Usage: ' + __FILE__ + ' PATH')
exit(1)
end
remote_log_path = '/srv/www/tmp.sakuya.pl/public_html/mal/watched.lst'
remote_host = 'burza'
local_host = `hostname`.strip!
video_path = File.realpath(ARGV[0])
json = {
time: Time.now.to_datetime.rfc3339,
path: video_path,
host: local_host
}.to_json
ssh_command = format('echo %s >> %s',
Shellwords.escape(json),
Shellwords.escape(remote_log_path))
`mpv #{Shellwords.escape(video_path)}`
`ssh #{remote_host} #{Shellwords.escape(ssh_command)}`
|
Added watchr script to auto-generate file
def expand_requirements(path)
File.read(path).gsub(%r{^([ \t]*)// require '([^']+)'$}) do |m|
[m, indent(expand_requirements(File.join(File.dirname(path), $2 + '.js')), $1)].join("\n")
end
end
def indent(string, whitespace)
string.gsub(/^/, whitespace)
end
watch('lib/mutil/(.+)\.js') do
File.open('lib/mutil.js', 'w') do |f|
f.write expand_requirements('lib/mutil/base.js')
end
print "\r-- Compiled lib/mutil.js [#{Time.now}]"
STDOUT.flush
end |
require 'rake'
require 'rake/clean'
require 'pathname'
require 'ipaddr'
class String
COLORS = {
red: 31, green: 32, brown: 33, blue: 34, magenta: 35, cyan: 36, gray: 37,
}
def color(c)
colors = {
}
"\e[#{COLORS[c]}m#{self}\e[0m"
end
def bold
"\e[1m#{self}\e[0m"
end
end
class IPAddr
def to_define
if self.ipv4?
"#{self.to_string.gsub(".",",")}"
else
"#{
self.to_string.gsub(":","")
.split(/(..)/)
.delete_if{|x| x.empty?}
.map{|d| "0x" + d}
.join(',')
}"
end
end
end
class Triple
attr_accessor :arch, :vendor, :os, :abi
def initialize(arch, vendor, os, abi)
@arch, @vendor, @os, @abi = arch, vendor, os, abi
end
def to_s
[ @arch, @vendor, @os, @abi ].delete_if{|f| f.nil?}.join('-')
end
def self.parse(str)
fields = str.split('-')
case fields.size
when 1 then Triple.new(fields[0], nil, nil, nil)
when 2 then Triple.new(fields[0], nil, fields[1], nil)
when 3 then Triple.new(fields[0], nil, fields[1], fields[2])
when 4 then Triple.new(fields[0], fields[1], fields[2], fields[3])
else
fail "Cannot parse triple: #{str}"
end
end
def self.current
arch, vendor = RbConfig::CONFIG['target_cpu'], RbConfig::CONFIG['target_vendor']
os, abi = RbConfig::CONFIG['target_os'].split('-')
Triple.new(arch, vendor, os, abi)
end
end
CC = "cc"
OUTPUT_DIR = "bins"
SHELLCODE_DIR = "shellcodes"
INCLUDE_DIRS = %w{include}
LD_SCRIPT_ELF = File.join(File.dirname(__FILE__), "factory-elf.lds")
LD_SCRIPT_PE = File.join(File.dirname(__FILE__), "factory-pe.lds")
OUTPUT_SECTIONS = %w{.text .rodata .data}
CFLAGS = %W{-std=c++1y
-Wall
-Wno-unused-function
-Wextra
-Wfatal-errors
-ffreestanding
-fshort-wchar
-fshort-enums
-fno-common
-fno-rtti
-fno-exceptions
-fno-non-call-exceptions
-fno-asynchronous-unwind-tables
-fomit-frame-pointer
-ffunction-sections
-fdata-sections
-fno-stack-protector
-nostdlib
}
COMPILER_CFLAGS =
{
/^g\+\+|gcc/ =>
%w{-fno-toplevel-reorder
-finline-functions
-fno-jump-tables
-fno-leading-underscore
-flto
-nodefaultlibs
-Os
},
/^clang/ =>
%w{-Oz
-Wno-invalid-noreturn
}
}
OS_CFLAGS =
{
/linux/ =>
%W{-Wl,-T#{LD_SCRIPT_ELF}
-Wl,--gc-sections
-Wl,-N
-Wl,--build-id=none
},
/bsd/ =>
%W{-Wl,-T#{LD_SCRIPT_ELF}
-Wl,--gc-sections
-Wl,-N
},
/darwin/ =>
%w{
-Wl,-e -Wl,__start
-Wl,-dead_strip
-Wl,-no_eh_labels
-static
},
/cygwin|w32|w64/ =>
%W{-Wl,-T#{LD_SCRIPT_PE}
-Wl,-N
-Wl,--gc-sections
-Wa,--no-pad-sections
},
/none/ =>
%W{-Wl,-T#{LD_SCRIPT_ELF}
-Wl,--gc-sections
-Wl,-N
-U__STDC_HOSTED__
}
}
# Architecture-dependent flags.
ARCH_CFLAGS =
{
/mips/ => %w{-mshared -mno-abicalls -mno-plt -mno-gpopt -mno-long-calls -G 0},
/.*/ => %w{-fPIC}
}
FILE_EXT =
{
:exec => {
/darwin/ => 'macho',
/cygwin|w32|w64/ => 'exe',
/.*/ => 'elf'
},
:shared => {
/darwin/ => 'dylib',
/cygwin|w32|w64/ => 'dll',
/.*/ => 'so'
}
}
def detect_compiler(cmd)
version = %x{#{cmd} -v 2>&1}
case version
when /gcc version (\S+)/ then ["gcc", $1]
when /clang version (\S+)/, /Apple LLVM version (\S+)/ then ["clang", $1]
else
[cmd, '']
end
end
def show_info(str, list = {})
STDERR.puts "[".bold + "*".bold.color(:green) + "] ".bold + str
list.each_with_index do |item, i|
name, value = item
branch = (i == list.size - 1) ? '└' : '├'
STDERR.puts " #{branch.bold} #{(name + ?:).color(:green)} #{value}"
end
end
def show_error(str)
STDERR.puts "[".bold + "*".bold.color(:red) + "] ".bold + 'Error: '.color(:cyan) + str
abort
end
def cc_invoke(cc, triple, sysroot = nil)
if triple.empty?
return cc if sysroot.nil?
return "#{cc} --sysroot=#{sysroot}"
end
triple_cc =
case cc
when /^g\+\+|gcc/
"#{triple}-#{cc}"
when /^clang/
sysroot ||= "/usr/#{triple}"
"#{cc} -target #{triple} --sysroot=#{sysroot}"
end
triple_cc << " --sysroot=#{sysroot}" unless sysroot.nil?
triple_cc
end
# Returns [ source_path, output_basename ]
def target_to_source(target)
path = Pathname.new(target.to_s).cleanpath
if path.relative? and path.each_filename.to_a.size == 1
path = Pathname.new(SHELLCODE_DIR).join(path)
end
path.split
end
def compile(target, triple, output_dir, *opts)
common_opts = %w{CHANNEL RHOST LHOST HOST RPORT LPORT PORT HANDLE NO_BUILTIN FORK_ON_ACCEPT REUSE_ADDR RELAX_INLINE NO_ASSERTS HEAP_BASE HEAP_SIZE NO_ERROR_CHECKS THREAD_SAFE}
options = common_opts + opts
defines = ENV.select{|e| options.include?(e)}
options = common_opts + opts
cc = ENV['CC'] || CC
if cc == 'cc'
cc, ver = detect_compiler(cc)
else
_, ver = detect_compiler(cc)
end
cflags = CFLAGS.dup
source_dir, target_name = target_to_source(target)
source_file = source_dir.join("#{target_name}.cc")
sysroot = ENV['SYSROOT']
file_type = :exec
unless File.exists?(source_file)
show_error("Cannot find source for target '#{target.to_s.color(:red)}'.")
end
host_triple = Triple.current
target_triple = triple.empty? ? Triple.current : Triple.parse(triple)
show_info("#{'Generating target'.color(:cyan)} '#{target.to_s.color(:red)}'",
'Compiler' => "#{cc} #{ver}",
'Host architecture' => host_triple,
'Target architecture' => target_triple,
'Options' => defines
)
STDERR.puts
ARCH_CFLAGS.each_pair do |arch, flags|
if target_triple.arch =~ arch
cflags += flags
break
end
end
OS_CFLAGS.each_pair do |os, flags|
if target_triple.os =~ os
cflags += flags
break
end
end
COMPILER_CFLAGS.each_pair do |comp, flags|
if cc =~ comp
cflags += flags
break
end
end
if ENV['VERBOSE'].to_i == 1
cflags << '-v'
end
if ENV['STACK_REALIGN'].to_i == 1
cflags << "-mstackrealign"
end
if ENV['LD']
cflags << "-fuse-ld=#{ENV['LD'].inspect}"
end
if ENV['CFLAGS']
cflags += [ ENV['CFLAGS'] ]
end
if ENV['ARCH']
cflags << "-march=#{ENV['ARCH']}"
end
if ENV['CPU']
cflags << "-mcpu=#{ENV['CPU']}"
end
if ENV['32BIT'].to_i == 1
cflags << '-m32'
if target_triple.os =~ /cygwin|w32|w64/
cflags << '-Wl,--format=pe-i386' << '-Wl,--oformat=pei-i386'
end
end
if ENV['IMAGEBASE']
base_addr = ENV['IMAGEBASE']
if target_triple.os =~ /darwin/
cflags << "-Wl,-segaddr" << "-Wl,__TEXT" << "-Wl,#{base_addr}"
else
cflags << "-Ttext=#{base_addr}"
end
end
if ENV['THUMB'].to_i == 1
cflags << "-mthumb"
end
if ENV['CODE_MODEL']
cmodel = ENV['CODE_MODEL']
cflags << "-mcmodel=#{cmodel}"
end
if ENV['DISABLE_LTO'].to_i == 1
cflags.delete("-flto")
cflags << "-fno-lto"
end
unless ENV['WITH_WARNINGS'].to_i == 1
cflags << '-w'
end
if defines['NO_BUILTIN'].to_i == 1
cflags << "-fno-builtin"
end
if ENV['OUTPUT_LIB'].to_i == 1
file_type = :shared
cflags << '-shared'
end
cflags += INCLUDE_DIRS.map{|d| "-I#{d}"}
defines = defines.map{|k,v|
v = IPAddr.new(v).to_define if %w{HOST RHOST LHOST}.include?(k)
"-D#{k}=#{v}"
}
if ENV['OUTPUT_STRIP'].to_i == 1
cflags << "-s"
end
if ENV['OUTPUT_DEBUG'].to_i == 1 or ENV['OUTPUT_LLVM'].to_i == 1
asm_cflags = ['-S'] + cflags + ['-fno-lto']
asm_cflags += ['-emit-llvm'] if ENV['OUTPUT_LLVM'].to_i == 1
output_file = output_dir.join("#{target_name}.S")
sh "#{cc_invoke(cc,triple,sysroot)} #{asm_cflags.join(" ")} #{source_file} -o #{output_file} #{defines.join(' ')}" do |ok, _|
(STDERR.puts; show_error("Compilation failed.")) unless ok
end
cflags << '-g'
end
output_ext = FILE_EXT[file_type].select{|os, ext| target_triple.os =~ os}.values.first
output_file = output_dir.join("#{target_name}.#{output_ext}")
sh "#{cc_invoke(cc,triple,sysroot)} #{cflags.join(' ')} #{source_file} -o #{output_file} #{defines.join(' ')}" do |ok, _|
(STDERR.puts; show_error("Compilation failed.")) unless ok
end
output_file
end
def generate_shellcode(object_file, target, triple, output_dir)
_, target_name = target_to_source(target)
triple_info = triple.empty? ? Triple.current : Triple.parse(triple)
output_file = output_dir.join("#{target_name}.#{triple_info.arch}-#{triple_info.os}.bin")
# Extract shellcode.
if triple_info.os =~ /darwin/
segments = %w{__TEXT __DATA}.map{|s| "-S #{s}"}.join(' ')
sh "#{File.dirname(__FILE__)}/tools/mach-o-extract #{segments} #{object_file} #{output_file}" do |ok, res|
STDERR.puts
show_error("Cannot extract shellcode from #{object_file}") unless ok
end
else
triple += '-' unless triple.empty?
sections = OUTPUT_SECTIONS.map{|s| "-j #{s}"}.join(' ')
sh "#{triple}objcopy -O binary #{sections} #{object_file} #{output_file}" do |ok, res|
STDERR.puts
show_error("Cannot extract shellcode from #{object_file}") unless ok
end
end
# Read shellcode.
data = File.binread(output_file)
output = {}
output['Contents'] = "\"#{data.unpack("C*").map{|b| "\\x%02x" % b}.join.color(:brown)}\"" if ENV['OUTPUT_HEX'].to_i == 1
show_info("#{'Generated target:'.color(:cyan)} #{data.size} bytes.", output)
print data unless STDOUT.tty?
end
def build(target, *opts)
output_dir = Pathname.new(OUTPUT_DIR)
triple = ''
triple = ENV['TRIPLE'] if ENV['TRIPLE']
make_directory(output_dir)
object_file = compile(target, triple, output_dir, *opts)
generate_shellcode(object_file, target, triple, output_dir)
end
def make_directory(path)
Dir.mkdir(path) unless Dir.exists?(path)
end
task :shellexec do
build(:shellexec, "COMMAND", "SET_ARGV0")
end
task :memexec do
build(:memexec, "PAYLOAD_SIZE")
end
desc 'Show help'
task :help do
STDERR.puts <<-USAGE
#{'Shellcode generation:'.color(:cyan)}
#{'rake <shellcode> [OPTION1=VALUE1] [OPTION2=VALUE2] ...'.bold}
#{'Compilation options:'.color(:cyan)}
#{'CC:'.color(:green)} Let you choose the compiler. Only supported are g++ and clang++.
#{'LD:'.color(:green)} Let you choose the linker. Supported values are "bfd" and "gold".
#{'TRIPLE:'.color(:green)} Cross compilation target. For example: "aarch64-linux-gnu".
#{'ARCH'.color(:green)} Specify a specific architecture to compile to (e.g. armv7-r).
#{'CPU'.color(:green)} Specify a specific CPU to compile to (e.g. cortex-a15).
#{'CFLAGS:'.color(:green)} Add custom flags to the compiler. For example "-m32".
#{'SYSROOT:'.color(:green)} Use the specified directory as the filesystem root for finding headers.
#{'NO_BUILTIN:'.color(:green)} Does not use the compiler builtins for common memory operations.
#{'OUTPUT_LIB:'.color(:green)} Compiles to a shared library instead of a standard executable.
#{'OUTPUT_DEBUG:'.color(:green)} Instructs the compiler to emit an assembly file and debug symbols.
#{'OUTPUT_LLVM:'.color(:green)} Instructs the compiler to emit LLVM bytecode (clang only).
#{'OUTPUT_STRIP:'.color(:green)} Strip symbols from output file.
#{'OUTPUT_HEX:'.color(:green)} Prints the resulting shellcode as an hexadecimal string.
#{'VERBOSE:'.color(:green)} Set to 1 for verbose compilation commands.
#{'WITH_WARNINGS:'.color(:green)} Set to 1 to enable compiler warnings.
#{'RELAX_INLINE:'.color(:green)} Set to 1, 2 or 3 to let the compiler uninline some functions.
#{'IMAGEBASE:'.color(:green)} Address where code is executed (for ELF and Mach-O).
#{'THREAD_SAFE:'.color(:green)} Set to 1 to enable thread safety.
#{'DISABLE_LTO:'.color(:green)} Set to 1 to disable link-time optimization.
#{'Target specific options:'.color(:cyan)}
#{'32BIT:'.color(:green)} Set to 1 to compile for a 32-bit environment.
#{'STACK_REALIGN:'.color(:green)} Set to 1 to ensure stack alignment to a 16 bytes boundary (Intel only).
#{'THUMB:'.color(:green)} Set to 1 to compile to Thumb mode (ARM only).
#{'CODE_MODEL:'.color(:green)} Select target code model: tiny, small, large (AArch64 only).
#{'Shellcode customization options:'.color(:cyan)}
#{'CHANNEL:'.color(:green)} Shellcode communication channel.
Supported options: {TCP,SCTP}[6]_{CONNECT,LISTEN}, UDP[6]_CONNECT,
USE_STDOUT, USE_STDERR, REUSE_SOCKET, REUSE_FILE
#{'[R,L]HOST:'.color(:green)} Remote host or local address for socket bind.
#{'[R,L]PORT:'.color(:green)} Remote port or local port for socket bind.
#{'HANDLE:'.color(:green)} File descriptor (for REUSE_SOCKET and REUSE_FILE only).
#{'FORK_ON_ACCEPT:'.color(:green)} Keeps listening when accepting connections.
#{'REUSE_ADDR:'.color(:green)} Bind sockets with SO_REUSEADDR.
#{'HEAP_BASE:'.color(:green)} Base address for heap allocations.
#{'HEAP_SIZE:'.color(:green)} Size of heap, defaults to 64k.
#{'NO_ASSERTS:'.color(:green)} Set to 1 to disable runtime asserts.
#{'NO_ERROR_CHECKS:'.color(:green)} Set to 1 to short-circuit error checks (more compact, less stable).
USAGE
exit
end
task :default => :help
rule '' do |task|
if task.name != 'default'
build(task.name)
end
end
CLEAN.include("bins/*.{elf,bin}")
Rakefile: fix compiler version when cross-compiling
require 'rake'
require 'rake/clean'
require 'pathname'
require 'ipaddr'
class String
COLORS = {
red: 31, green: 32, brown: 33, blue: 34, magenta: 35, cyan: 36, gray: 37,
}
def color(c)
colors = {
}
"\e[#{COLORS[c]}m#{self}\e[0m"
end
def bold
"\e[1m#{self}\e[0m"
end
end
class IPAddr
def to_define
if self.ipv4?
"#{self.to_string.gsub(".",",")}"
else
"#{
self.to_string.gsub(":","")
.split(/(..)/)
.delete_if{|x| x.empty?}
.map{|d| "0x" + d}
.join(',')
}"
end
end
end
class Triple
attr_accessor :arch, :vendor, :os, :abi
def initialize(arch, vendor, os, abi)
@arch, @vendor, @os, @abi = arch, vendor, os, abi
end
def to_s
[ @arch, @vendor, @os, @abi ].delete_if{|f| f.nil?}.join('-')
end
def self.parse(str)
fields = str.split('-')
case fields.size
when 1 then Triple.new(fields[0], nil, nil, nil)
when 2 then Triple.new(fields[0], nil, fields[1], nil)
when 3 then Triple.new(fields[0], nil, fields[1], fields[2])
when 4 then Triple.new(fields[0], fields[1], fields[2], fields[3])
else
fail "Cannot parse triple: #{str}"
end
end
def self.current
arch, vendor = RbConfig::CONFIG['target_cpu'], RbConfig::CONFIG['target_vendor']
os, abi = RbConfig::CONFIG['target_os'].split('-')
Triple.new(arch, vendor, os, abi)
end
end
CC = "cc"
OUTPUT_DIR = "bins"
SHELLCODE_DIR = "shellcodes"
INCLUDE_DIRS = %w{include}
LD_SCRIPT_ELF = File.join(File.dirname(__FILE__), "factory-elf.lds")
LD_SCRIPT_PE = File.join(File.dirname(__FILE__), "factory-pe.lds")
OUTPUT_SECTIONS = %w{.text .rodata .data}
CFLAGS = %W{-std=c++1y
-Wall
-Wno-unused-function
-Wextra
-Wfatal-errors
-ffreestanding
-fshort-wchar
-fshort-enums
-fno-common
-fno-rtti
-fno-exceptions
-fno-non-call-exceptions
-fno-asynchronous-unwind-tables
-fomit-frame-pointer
-ffunction-sections
-fdata-sections
-fno-stack-protector
-nostdlib
}
COMPILER_CFLAGS =
{
/^g\+\+|gcc/ =>
%w{-fno-toplevel-reorder
-finline-functions
-fno-jump-tables
-fno-leading-underscore
-flto
-nodefaultlibs
-Os
},
/^clang/ =>
%w{-Oz
-Wno-invalid-noreturn
}
}
OS_CFLAGS =
{
/linux/ =>
%W{-Wl,-T#{LD_SCRIPT_ELF}
-Wl,--gc-sections
-Wl,-N
-Wl,--build-id=none
},
/bsd/ =>
%W{-Wl,-T#{LD_SCRIPT_ELF}
-Wl,--gc-sections
-Wl,-N
},
/darwin/ =>
%w{
-Wl,-e -Wl,__start
-Wl,-dead_strip
-Wl,-no_eh_labels
-static
},
/cygwin|w32|w64/ =>
%W{-Wl,-T#{LD_SCRIPT_PE}
-Wl,-N
-Wl,--gc-sections
-Wa,--no-pad-sections
},
/none/ =>
%W{-Wl,-T#{LD_SCRIPT_ELF}
-Wl,--gc-sections
-Wl,-N
-U__STDC_HOSTED__
}
}
# Architecture-dependent flags.
ARCH_CFLAGS =
{
/mips/ => %w{-mshared -mno-abicalls -mno-plt -mno-gpopt -mno-long-calls -G 0},
/.*/ => %w{-fPIC}
}
FILE_EXT =
{
:exec => {
/darwin/ => 'macho',
/cygwin|w32|w64/ => 'exe',
/.*/ => 'elf'
},
:shared => {
/darwin/ => 'dylib',
/cygwin|w32|w64/ => 'dll',
/.*/ => 'so'
}
}
def compiler_binary(cc, triple)
return cc if triple.empty?
case cc
when /^g\+\+|gcc/ then "#{triple}-#{cc}"
else
cc
end
end
def detect_compiler(cc, triple)
version = %x{#{compiler_binary(cc, triple)} -v 2>&1}
case version
when /gcc version (\S+)/ then ["gcc", $1]
when /clang version (\S+)/, /Apple LLVM version (\S+)/ then ["clang", $1]
else
[cmd, '']
end
end
def show_info(str, list = {})
STDERR.puts "[".bold + "*".bold.color(:green) + "] ".bold + str
list.each_with_index do |item, i|
name, value = item
branch = (i == list.size - 1) ? '└' : '├'
STDERR.puts " #{branch.bold} #{(name + ?:).color(:green)} #{value}"
end
end
def show_error(str)
STDERR.puts "[".bold + "*".bold.color(:red) + "] ".bold + 'Error: '.color(:cyan) + str
abort
end
def cc_invoke(cc, triple, sysroot = nil)
cmd = compiler_binary(cc, triple)
if triple.empty?
return cmd if sysroot.nil?
return "#{cmd} --sysroot=#{sysroot}"
end
triple_cc =
case cmd
when /^clang/
sysroot ||= "/usr/#{triple}"
"#{cmd} -target #{triple} --sysroot=#{sysroot}"
else
cmd
end
triple_cc << " --sysroot=#{sysroot}" unless sysroot.nil?
triple_cc
end
# Returns [ source_path, output_basename ]
def target_to_source(target)
path = Pathname.new(target.to_s).cleanpath
if path.relative? and path.each_filename.to_a.size == 1
path = Pathname.new(SHELLCODE_DIR).join(path)
end
path.split
end
def compile(target, triple, output_dir, *opts)
common_opts = %w{CHANNEL RHOST LHOST HOST RPORT LPORT PORT HANDLE NO_BUILTIN FORK_ON_ACCEPT REUSE_ADDR RELAX_INLINE NO_ASSERTS HEAP_BASE HEAP_SIZE NO_ERROR_CHECKS THREAD_SAFE}
options = common_opts + opts
defines = ENV.select{|e| options.include?(e)}
options = common_opts + opts
cc = ENV['CC'] || CC
cflags = CFLAGS.dup
source_dir, target_name = target_to_source(target)
source_file = source_dir.join("#{target_name}.cc")
sysroot = ENV['SYSROOT']
file_type = :exec
unless File.exists?(source_file)
show_error("Cannot find source for target '#{target.to_s.color(:red)}'.")
end
host_triple = Triple.current
target_triple = triple.empty? ? Triple.current : Triple.parse(triple)
cc, _ = detect_compiler(cc, '') if cc == 'cc' # Detect the system compiler if not specified.
_, ver = detect_compiler(cc, triple)
show_info("#{'Generating target'.color(:cyan)} '#{target.to_s.color(:red)}'",
'Compiler' => "#{cc} #{ver}",
'Host architecture' => host_triple,
'Target architecture' => target_triple,
'Options' => defines
)
STDERR.puts
ARCH_CFLAGS.each_pair do |arch, flags|
if target_triple.arch =~ arch
cflags += flags
break
end
end
OS_CFLAGS.each_pair do |os, flags|
if target_triple.os =~ os
cflags += flags
break
end
end
COMPILER_CFLAGS.each_pair do |comp, flags|
if cc =~ comp
cflags += flags
break
end
end
if ENV['VERBOSE'].to_i == 1
cflags << '-v'
end
if ENV['STACK_REALIGN'].to_i == 1
cflags << "-mstackrealign"
end
if ENV['LD']
cflags << "-fuse-ld=#{ENV['LD'].inspect}"
end
if ENV['CFLAGS']
cflags += [ ENV['CFLAGS'] ]
end
if ENV['ARCH']
cflags << "-march=#{ENV['ARCH']}"
end
if ENV['CPU']
cflags << "-mcpu=#{ENV['CPU']}"
end
if ENV['32BIT'].to_i == 1
cflags << '-m32'
if target_triple.os =~ /cygwin|w32|w64/
cflags << '-Wl,--format=pe-i386' << '-Wl,--oformat=pei-i386'
end
end
if ENV['IMAGEBASE']
base_addr = ENV['IMAGEBASE']
if target_triple.os =~ /darwin/
cflags << "-Wl,-segaddr" << "-Wl,__TEXT" << "-Wl,#{base_addr}"
else
cflags << "-Ttext=#{base_addr}"
end
end
if ENV['THUMB'].to_i == 1
cflags << "-mthumb"
end
if ENV['CODE_MODEL']
cmodel = ENV['CODE_MODEL']
cflags << "-mcmodel=#{cmodel}"
end
if ENV['DISABLE_LTO'].to_i == 1
cflags.delete("-flto")
cflags << "-fno-lto"
end
unless ENV['WITH_WARNINGS'].to_i == 1
cflags << '-w'
end
if defines['NO_BUILTIN'].to_i == 1
cflags << "-fno-builtin"
end
if ENV['OUTPUT_LIB'].to_i == 1
file_type = :shared
cflags << '-shared'
end
cflags += INCLUDE_DIRS.map{|d| "-I#{d}"}
defines = defines.map{|k,v|
v = IPAddr.new(v).to_define if %w{HOST RHOST LHOST}.include?(k)
"-D#{k}=#{v}"
}
if ENV['OUTPUT_STRIP'].to_i == 1
cflags << "-s"
end
if ENV['OUTPUT_DEBUG'].to_i == 1 or ENV['OUTPUT_LLVM'].to_i == 1
asm_cflags = ['-S'] + cflags + ['-fno-lto']
asm_cflags += ['-emit-llvm'] if ENV['OUTPUT_LLVM'].to_i == 1
output_file = output_dir.join("#{target_name}.S")
sh "#{cc_invoke(cc,triple,sysroot)} #{asm_cflags.join(" ")} #{source_file} -o #{output_file} #{defines.join(' ')}" do |ok, _|
(STDERR.puts; show_error("Compilation failed.")) unless ok
end
cflags << '-g'
end
output_ext = FILE_EXT[file_type].select{|os, ext| target_triple.os =~ os}.values.first
output_file = output_dir.join("#{target_name}.#{output_ext}")
sh "#{cc_invoke(cc,triple,sysroot)} #{cflags.join(' ')} #{source_file} -o #{output_file} #{defines.join(' ')}" do |ok, _|
(STDERR.puts; show_error("Compilation failed.")) unless ok
end
output_file
end
def generate_shellcode(object_file, target, triple, output_dir)
_, target_name = target_to_source(target)
triple_info = triple.empty? ? Triple.current : Triple.parse(triple)
output_file = output_dir.join("#{target_name}.#{triple_info.arch}-#{triple_info.os}.bin")
# Extract shellcode.
if triple_info.os =~ /darwin/
segments = %w{__TEXT __DATA}.map{|s| "-S #{s}"}.join(' ')
sh "#{File.dirname(__FILE__)}/tools/mach-o-extract #{segments} #{object_file} #{output_file}" do |ok, res|
STDERR.puts
show_error("Cannot extract shellcode from #{object_file}") unless ok
end
else
triple += '-' unless triple.empty?
sections = OUTPUT_SECTIONS.map{|s| "-j #{s}"}.join(' ')
sh "#{triple}objcopy -O binary #{sections} #{object_file} #{output_file}" do |ok, res|
STDERR.puts
show_error("Cannot extract shellcode from #{object_file}") unless ok
end
end
# Read shellcode.
data = File.binread(output_file)
output = {}
output['Contents'] = "\"#{data.unpack("C*").map{|b| "\\x%02x" % b}.join.color(:brown)}\"" if ENV['OUTPUT_HEX'].to_i == 1
show_info("#{'Generated target:'.color(:cyan)} #{data.size} bytes.", output)
print data unless STDOUT.tty?
end
def build(target, *opts)
output_dir = Pathname.new(OUTPUT_DIR)
triple = ''
triple = ENV['TRIPLE'] if ENV['TRIPLE']
make_directory(output_dir)
object_file = compile(target, triple, output_dir, *opts)
generate_shellcode(object_file, target, triple, output_dir)
end
def make_directory(path)
Dir.mkdir(path) unless Dir.exists?(path)
end
task :shellexec do
build(:shellexec, "COMMAND", "SET_ARGV0")
end
task :memexec do
build(:memexec, "PAYLOAD_SIZE")
end
desc 'Show help'
task :help do
STDERR.puts <<-USAGE
#{'Shellcode generation:'.color(:cyan)}
#{'rake <shellcode> [OPTION1=VALUE1] [OPTION2=VALUE2] ...'.bold}
#{'Compilation options:'.color(:cyan)}
#{'CC:'.color(:green)} Let you choose the compiler. Only supported are g++ and clang++.
#{'LD:'.color(:green)} Let you choose the linker. Supported values are "bfd" and "gold".
#{'TRIPLE:'.color(:green)} Cross compilation target. For example: "aarch64-linux-gnu".
#{'ARCH'.color(:green)} Specify a specific architecture to compile to (e.g. armv7-r).
#{'CPU'.color(:green)} Specify a specific CPU to compile to (e.g. cortex-a15).
#{'CFLAGS:'.color(:green)} Add custom flags to the compiler. For example "-m32".
#{'SYSROOT:'.color(:green)} Use the specified directory as the filesystem root for finding headers.
#{'NO_BUILTIN:'.color(:green)} Does not use the compiler builtins for common memory operations.
#{'OUTPUT_LIB:'.color(:green)} Compiles to a shared library instead of a standard executable.
#{'OUTPUT_DEBUG:'.color(:green)} Instructs the compiler to emit an assembly file and debug symbols.
#{'OUTPUT_LLVM:'.color(:green)} Instructs the compiler to emit LLVM bytecode (clang only).
#{'OUTPUT_STRIP:'.color(:green)} Strip symbols from output file.
#{'OUTPUT_HEX:'.color(:green)} Prints the resulting shellcode as an hexadecimal string.
#{'VERBOSE:'.color(:green)} Set to 1 for verbose compilation commands.
#{'WITH_WARNINGS:'.color(:green)} Set to 1 to enable compiler warnings.
#{'RELAX_INLINE:'.color(:green)} Set to 1, 2 or 3 to let the compiler uninline some functions.
#{'IMAGEBASE:'.color(:green)} Address where code is executed (for ELF and Mach-O).
#{'THREAD_SAFE:'.color(:green)} Set to 1 to enable thread safety.
#{'DISABLE_LTO:'.color(:green)} Set to 1 to disable link-time optimization.
#{'Target specific options:'.color(:cyan)}
#{'32BIT:'.color(:green)} Set to 1 to compile for a 32-bit environment.
#{'STACK_REALIGN:'.color(:green)} Set to 1 to ensure stack alignment to a 16 bytes boundary (Intel only).
#{'THUMB:'.color(:green)} Set to 1 to compile to Thumb mode (ARM only).
#{'CODE_MODEL:'.color(:green)} Select target code model: tiny, small, large (AArch64 only).
#{'Shellcode customization options:'.color(:cyan)}
#{'CHANNEL:'.color(:green)} Shellcode communication channel.
Supported options: {TCP,SCTP}[6]_{CONNECT,LISTEN}, UDP[6]_CONNECT,
USE_STDOUT, USE_STDERR, REUSE_SOCKET, REUSE_FILE
#{'[R,L]HOST:'.color(:green)} Remote host or local address for socket bind.
#{'[R,L]PORT:'.color(:green)} Remote port or local port for socket bind.
#{'HANDLE:'.color(:green)} File descriptor (for REUSE_SOCKET and REUSE_FILE only).
#{'FORK_ON_ACCEPT:'.color(:green)} Keeps listening when accepting connections.
#{'REUSE_ADDR:'.color(:green)} Bind sockets with SO_REUSEADDR.
#{'HEAP_BASE:'.color(:green)} Base address for heap allocations.
#{'HEAP_SIZE:'.color(:green)} Size of heap, defaults to 64k.
#{'NO_ASSERTS:'.color(:green)} Set to 1 to disable runtime asserts.
#{'NO_ERROR_CHECKS:'.color(:green)} Set to 1 to short-circuit error checks (more compact, less stable).
USAGE
exit
end
task :default => :help
rule '' do |task|
if task.name != 'default'
build(task.name)
end
end
CLEAN.include("bins/*.{elf,bin}")
|
task :default => [:build, :ui_tests]
task :build do
sh 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe canopy.sln'
end
task :server do
sh "start ruby testpages/app.rb"
end
task :ui_tests do
sh 'basictests\bin\debug\basictests.exe'
end
rename rake task to ui
task :default => [:build, :ui]
task :build do
sh 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe canopy.sln'
end
task :server do
sh "start ruby testpages/app.rb"
end
task :ui do
sh 'basictests\bin\debug\basictests.exe'
end
|
#!/usr/bin/ruby -wKU
#
# = Regular Expression Construction.
#
# Complex regular expressions are hard to construct and even harder to
# read. The Re library allows users to construct complex regular
# expressions from simpler expressions. For example, consider the
# following regular expression that will parse dates:
#
# /\A((?:19|20)[0-9]{2})[\- \/.](0[1-9]|1[012])[\- \/.](0[1-9]|[12][0-9]|3[01])\z/
#
# Using the Re library, That regular expression can be built
# incrementaly from smaller, easier to understand expressions.
# Perhaps something like this:
#
# require 're'
#
# include Re
#
# delim = re.any("- /.")
# century_prefix = re("19") | re("20")
# under_ten = re("0") + re.any("1-9")
# ten_to_twelve = re("1") + re.any("012")
# ten_and_under_thirty = re.any("12") + re.any("0-9")
# thirties = re("3") + re.any("01")
#
# year = (century_prefix + re.digit.repeat(2)).capture(:year)
# month = (under_ten | ten_to_twelve).capture(:month)
# day = (under_ten | ten_and_under_thirty | thirties).capture(:day)
#
# date = (year + delim + month + delim + day).all
#
# Although it is more code, the individual pieces are smaller and
# easier to independently verify. As an additional bonus, the capture
# groups can be retrieved by name:
#
# result = date.match("2009-01-23")
# result.data(:year) # => "2009"
# result.data(:month) # => "01"
# result.data(:day) # => "23"
#
# == Usage:
#
# include Re
#
# number = re.any("0-9").all
# if number =~ string
# puts "Matches!"
# else
# puts "No Match"
# end
#
# == Examples:
#
# re("a") -- matches "a"
# re("a") + re("b") -- matches "ab"
# re("a") | re("b") -- matches "a" or "b"
# re("a").many -- matches "", "a", "aaaaaa"
# re("a").one_or_more -- matches "a", "aaaaaa", but not ""
# re("a").optional -- matches "" or "a"
# re("a").all -- matches "a", but not "xab"
#
# See Re::Rexp for a complete list of expressions.
#
# Using re without an argument allows access to a number of common
# regular expression constants. For example:
#
# re.space / re.spaces -- matches " ", "\n" or "\t"
# re.digit / re.digits -- matches a digit / sequence of digits
#
# Also, re without arguments can also be used to construct character
# classes:
#
# re.any -- Matches any charactor
# re.any("abc") -- Matches "a", "b", or "c"
# re.any("0-9") -- Matches the digits 0 through 9
# re.any("A-Z", "a-z", "0-9", "_")
# -- Matches alphanumeric or an underscore
#
# See Re::ConstructionMethods for a complete list of common constants
# and character class functions.
#
# See Re.re, Re::Rexp, and Re::ConstructionMethods for details.
#
# == License and Copyright:
#
# Copyright 2009 by Jim Weirich (jim.weirich@gmail.com)
#
# Re is provided under the MIT open source license (see MIT-LICENSE)
#
# == Links:
#
# Documentation :: http://re-lib.rubyforge.org
# Source :: http://github.com/jimweirich/re
# GemCutter :: http://gemcutter.org/gems/re
# Bug Tracker :: http://www.pivotaltracker.com/projects/47758
# Author :: jim.weirich@gmail.com
#
module Re
module Version
NUMBERS = [
MAJOR = 0,
MINOR = 0,
BUILD = 3,
BETA = nil,
].compact
end
VERSION = Version::NUMBERS.join('.')
# Re::Result captures the result of a match and allows lookup of the
# captured groups by name.
class Result
# Create a Re result object with the match data and the origina
# Re::Rexp object.
def initialize(match_data, rexp)
@match_data = match_data
@rexp = rexp
end
# Return the full match
def full_match
@match_data[0]
end
# Return the named capture data.
def [](name)
index = @rexp.capture_keys.index(name)
index ? @match_data[index+1] : nil
end
end
# Precedence levels for regular expressions:
GROUPED = 4 # (r), [chars] :nodoc:
POSTFIX = 3 # r*, r+, r? :nodoc:
CONCAT = 2 # r + r, literal :nodoc:
ALT = 1 # r | r :nodoc:
# Mode Bits
MULTILINE_MODE = Regexp::MULTILINE
IGNORE_CASE_MODE = Regexp::IGNORECASE
# Constructed regular expressions.
class Rexp
attr_reader :level, :options, :capture_keys
# Create a regular expression from the string. The regular
# expression will have a precedence of +level+ and will recognized
# +keys+ as a list of capture keys.
def initialize(string, level, keys, options=0)
@raw_string = string
@level = level
@capture_keys = keys
@options = options
end
def string
if options == 0
@raw_string
else
"(?#{encode_options}:" + @raw_string + ")"
end
end
# Encode the options into a string (e.g "", "m", "i", or "mi")
def encode_options # :nodoc:
(multiline? ? "m" : "") +
(ignore_case? ? "i" : "")
end
private :encode_options
# Return a Regexp from the the constructed regular expression.
def regexp
@regexp ||= Regexp.new(string)
end
# Does it match a string? (returns Re::Result if match, nil otherwise)
def match(string)
md = regexp.match(string)
md ? Result.new(md, self) : nil
end
alias =~ match
# New regular expresion that matches the concatenation of self and
# other.
def +(other)
Rexp.new(parenthesize(CONCAT) + other.parenthesize(CONCAT),
CONCAT,
capture_keys + other.capture_keys)
end
# New regular expresion that matches either self or other.
def |(other)
Rexp.new(parenthesize(ALT) + "|" + other.parenthesize(ALT),
ALT,
capture_keys + other.capture_keys)
end
# New regular expression where self is optional.
def optional
Rexp.new(parenthesize(POSTFIX) + "?", POSTFIX, capture_keys)
end
# New regular expression that matches self many (zero or more)
# times.
def many
Rexp.new(parenthesize(POSTFIX) + "*", POSTFIX, capture_keys)
end
# New regular expression that matches self many (zero or more)
# times (non-greedy version).
def many!
Rexp.new(parenthesize(POSTFIX) + "*?", POSTFIX, capture_keys)
end
# New regular expression that matches self one or more times.
def one_or_more
Rexp.new(parenthesize(POSTFIX) + "+", POSTFIX, capture_keys)
end
# New regular expression that matches self one or more times
# (non-greedy version).
def one_or_more!
Rexp.new(parenthesize(POSTFIX) + "+?", POSTFIX, capture_keys)
end
# New regular expression that matches self between +min+ and +max+
# times (inclusive). If +max+ is omitted, then it must match self
# exactly exactly +min+ times.
def repeat(min, max=nil)
if min && max
Rexp.new(parenthesize(POSTFIX) + "{#{min},#{max}}", POSTFIX, capture_keys)
else
Rexp.new(parenthesize(POSTFIX) + "{#{min}}", POSTFIX, capture_keys)
end
end
# New regular expression that matches self at least +min+ times.
def at_least(min)
Rexp.new(parenthesize(POSTFIX) + "{#{min},}", POSTFIX, capture_keys)
end
# New regular expression that matches self at most +max+ times.
def at_most(max)
Rexp.new(parenthesize(POSTFIX) + "{0,#{max}}", POSTFIX, capture_keys)
end
# New regular expression that matches a single character that is
# not in the given set of characters.
def none(chars)
Rexp.new("[^" + Rexp.escape_any(chars) + "]", GROUPED, [])
end
# New regular expression that matches self across the complete
# string.
def all
self.begin.very_end
end
# New regular expression that matches self across most of the
# entire string (trailing new lines are not required to match).
def almost_all
self.begin.end
end
# New regular expression that matches self at the beginning of a line.
def bol
Rexp.new("^" + parenthesize(CONCAT), CONCAT, capture_keys)
end
# New regular expression that matches self at the end of the line.
def eol
Rexp.new(parenthesize(CONCAT) + "$", CONCAT, capture_keys)
end
# New regular expression that matches self at the beginning of a string.
def begin
Rexp.new("\\A" + parenthesize(CONCAT), CONCAT, capture_keys)
end
# New regular expression that matches self at the end of a string
# (trailing new lines are allowed to not match).
def end
Rexp.new(parenthesize(CONCAT) + "\\Z", CONCAT, capture_keys)
end
# New regular expression that matches self at the very end of a string
# (trailing new lines are required to match).
def very_end
Rexp.new(parenthesize(CONCAT) + "\\z", CONCAT, capture_keys)
end
# New expression that matches self across an entire line.
def line
self.bol.eol
end
# New regular expression that is grouped, but does not cause the
# capture of a match. The Re library normally handles grouping
# automatically, so this method shouldn't be needed by client
# software for normal operations.
def group
Rexp.new("(?:" + string + ")", GROUPED, capture_keys)
end
# New regular expression that captures text matching self. The
# matching text may be retrieved from the Re::Result object using
# the +name+ (a symbol) as the keyword.
def capture(name)
Rexp.new("(" + string + ")", GROUPED, [name] + capture_keys)
end
# New regular expression that matches self in multiline mode.
def multiline
Rexp.new(@raw_string, GROUPED, capture_keys, options | MULTILINE_MODE)
end
# Is this a multiline regular expression? The multiline mode of
# interior regular expressions are not reflected in value returned
# by this method.
def multiline?
(options & MULTILINE_MODE) != 0
end
# New regular expression that matches self while ignoring case.
def ignore_case
Rexp.new(@raw_string, GROUPED, capture_keys, options | IGNORE_CASE_MODE)
end
# Does this regular expression ignore case? Note that this only
# queries the outer most regular expression. The ignore case mode
# of interior regular expressions are not reflected in value
# returned by this method.
def ignore_case?
(options & IGNORE_CASE_MODE) != 0
end
# String representation of the constructed regular expression.
def to_s
regexp.to_s
end
protected
# String representation with grouping if needed.
#
# If the precedence of the current Regexp is less than the new
# precedence level, return the encoding wrapped in a non-capturing
# group. Otherwise just return the encoding.
if level >= new_level
string
else
group.string
end
end
# The string encoding of current regular expression. The encoding
# will include option flags if specified.
# New regular expression that matches the literal characters in
# +chars+. For example, Re.literal("a(b)") will be equivalent to
# /a\(b\)/. Note that characters with special meanings in regular
# expressions will be quoted.
def self.literal(chars)
new(Regexp.escape(chars), CONCAT, [])
end
# New regular expression constructed from a string representing a
# ruby regular expression. The raw string should represent a
# regular expression with the highest level of precedence (you
# should use parenthesis if it is not).
def self.raw(re_string) # :no-doc:
new(re_string, GROUPED, [])
end
def self.escape_any(chars)
# Escape special characters found in character classes.
chars.gsub(/([\[\]\^\-])/) { "\\#{$1}" }
end
end
# Construct a regular expression from the literal string. Special
# Regexp characters will be escaped before constructing the regular
# expression. If no literal is given, then the NULL regular
# expression is returned.
#
# See Re for example usage.
#
def re(exp=nil)
exp ? Rexp.literal(exp) : NULL
end
extend self
# This module defines a number of methods returning common
# pre-packaged regular expressions along with methods to create
# regular expressions from character classes and other objects.
# ConstructionMethods is mixed into the NULL Rexp object so that
# re() without arguments can be used to access the methods.
module ConstructionMethods
# :call-seq:
# re.null
#
# Regular expression that matches the null string
def null
self
end
# :call-seq:
# re.any
# re.any(chars)
# re.any(range)
# re.any(chars, range, ...)
#
# Regular expression that matches a character from a character
# class.
#
# +Any+ without any arguments will match any single character.
# +Any+ with one or more arguments will construct a character
# class for the arguments. If the argument is a three character
# string where the middle character is "-", then the argument
# represents a range of characters. Otherwise the arguments are
# treated as a list of characters to be added to the character
# class.
#
# Examples:
#
# re.any -- match any character
# re.any("aieouy") -- match vowels
# re.any("0-9") -- match digits
# re.any("A-Z", "a-z", "0-9") -- match alphanumerics
# re.any("A-Z", "a-z", "0-9", "_") -- match alphanumerics
#
def any(*chars)
if chars.empty?
@dot ||= Rexp.raw(".")
else
any_chars = ''
chars.each do |chs|
if /^.-.$/ =~ chs
any_chars << chs
else
any_chars << Rexp.escape_any(chs)
end
end
Rexp.new("[" + any_chars + "]", GROUPED, [])
end
end
# :call-seq:
# re.space
#
# Regular expression that matches any white space character.
# (equivalent to /\s/)
def space
@space ||= Rexp.raw("\\s")
end
# :call-seq:
# re.spaces
#
# Regular expression that matches any sequence of white space
# characters. (equivalent to /\s+/)
def spaces
@spaces ||= space.one_or_more
end
# :call-seq:
# re.nonspace
#
# Regular expression that matches any non-white space character.
# (equivalent to /\S/)
def nonspace
@nonspace ||= Rexp.raw("\\S")
end
# :call-seq:
# re.nonspaces
#
# Regular expression that matches any sequence of non-white space
# characters. (equivalent to /\S+/)
def nonspaces
@nonspaces ||= Rexp.raw("\\S").one_or_more
end
# :call-seq:
# re.word_char
#
# Regular expression that matches any word character. (equivalent
# to /\w/)
def word_char
@word_char ||= Rexp.raw("\\w")
end
# :call-seq:
# re.word
#
# Regular expression that matches any sequence of word characters.
# (equivalent to /\w+/)
def word
@word ||= word_char.one_or_more
end
# :call-seq:
# re.break
#
# Regular expression that matches any break between word/non-word
# characters. This is a zero length match. (equivalent to /\b/)
def break
@break ||= Rexp.raw("\\b")
end
# :call-seq:
# re.digit
#
# Regular expression that matches a single digit. (equivalent to
# /\d/)
def digit
@digit ||= any("0-9")
end
# :call-seq:
# re.digits
#
# Regular expression that matches a sequence of digits.
# (equivalent to /\d+/)
def digits
@digits ||= digit.one_or_more
end
# :call-seq:
# re.hex_digit
#
# Regular expression that matches a single hex digit. (equivalent
# to /[A-Fa-f0-9]/)
def hex_digit
@hex_digit ||= any("0-9", "a-f", "A-F")
end
# :call-seq:
# re.hex_digits
#
# Regular expression that matches a sequence of hex digits
# (equivalent to /[A-Fa-f0-9]+/)
def hex_digits
@hex_digits ||= hex_digit.one_or_more
end
end
# Matches an empty string. Additional common regular expression
# construction methods are defined on NULL. See
# Re::ConstructionMethods for details.
NULL = Rexp.literal("")
NULL.extend(ConstructionMethods)
end
Renamed string to encoding (and related changes)
#!/usr/bin/ruby -wKU
#
# = Regular Expression Construction.
#
# Complex regular expressions are hard to construct and even harder to
# read. The Re library allows users to construct complex regular
# expressions from simpler expressions. For example, consider the
# following regular expression that will parse dates:
#
# /\A((?:19|20)[0-9]{2})[\- \/.](0[1-9]|1[012])[\- \/.](0[1-9]|[12][0-9]|3[01])\z/
#
# Using the Re library, That regular expression can be built
# incrementaly from smaller, easier to understand expressions.
# Perhaps something like this:
#
# require 're'
#
# include Re
#
# delim = re.any("- /.")
# century_prefix = re("19") | re("20")
# under_ten = re("0") + re.any("1-9")
# ten_to_twelve = re("1") + re.any("012")
# ten_and_under_thirty = re.any("12") + re.any("0-9")
# thirties = re("3") + re.any("01")
#
# year = (century_prefix + re.digit.repeat(2)).capture(:year)
# month = (under_ten | ten_to_twelve).capture(:month)
# day = (under_ten | ten_and_under_thirty | thirties).capture(:day)
#
# date = (year + delim + month + delim + day).all
#
# Although it is more code, the individual pieces are smaller and
# easier to independently verify. As an additional bonus, the capture
# groups can be retrieved by name:
#
# result = date.match("2009-01-23")
# result.data(:year) # => "2009"
# result.data(:month) # => "01"
# result.data(:day) # => "23"
#
# == Usage:
#
# include Re
#
# number = re.any("0-9").all
# if number =~ string
# puts "Matches!"
# else
# puts "No Match"
# end
#
# == Examples:
#
# re("a") -- matches "a"
# re("a") + re("b") -- matches "ab"
# re("a") | re("b") -- matches "a" or "b"
# re("a").many -- matches "", "a", "aaaaaa"
# re("a").one_or_more -- matches "a", "aaaaaa", but not ""
# re("a").optional -- matches "" or "a"
# re("a").all -- matches "a", but not "xab"
#
# See Re::Rexp for a complete list of expressions.
#
# Using re without an argument allows access to a number of common
# regular expression constants. For example:
#
# re.space / re.spaces -- matches " ", "\n" or "\t"
# re.digit / re.digits -- matches a digit / sequence of digits
#
# Also, re without arguments can also be used to construct character
# classes:
#
# re.any -- Matches any charactor
# re.any("abc") -- Matches "a", "b", or "c"
# re.any("0-9") -- Matches the digits 0 through 9
# re.any("A-Z", "a-z", "0-9", "_")
# -- Matches alphanumeric or an underscore
#
# See Re::ConstructionMethods for a complete list of common constants
# and character class functions.
#
# See Re.re, Re::Rexp, and Re::ConstructionMethods for details.
#
# == License and Copyright:
#
# Copyright 2009 by Jim Weirich (jim.weirich@gmail.com)
#
# Re is provided under the MIT open source license (see MIT-LICENSE)
#
# == Links:
#
# Documentation :: http://re-lib.rubyforge.org
# Source :: http://github.com/jimweirich/re
# GemCutter :: http://gemcutter.org/gems/re
# Bug Tracker :: http://www.pivotaltracker.com/projects/47758
# Author :: jim.weirich@gmail.com
#
module Re
module Version
NUMBERS = [
MAJOR = 0,
MINOR = 0,
BUILD = 3,
BETA = nil,
].compact
end
VERSION = Version::NUMBERS.join('.')
# Re::Result captures the result of a match and allows lookup of the
# captured groups by name.
class Result
# Create a Re result object with the match data and the origina
# Re::Rexp object.
def initialize(match_data, rexp)
@match_data = match_data
@rexp = rexp
end
# Return the full match
def full_match
@match_data[0]
end
# Return the named capture data.
def [](name)
index = @rexp.capture_keys.index(name)
index ? @match_data[index+1] : nil
end
end
# Precedence levels for regular expressions:
GROUPED = 4 # (r), [chars] :nodoc:
POSTFIX = 3 # r*, r+, r? :nodoc:
CONCAT = 2 # r + r, literal :nodoc:
ALT = 1 # r | r :nodoc:
# Mode Bits
MULTILINE_MODE = Regexp::MULTILINE
IGNORE_CASE_MODE = Regexp::IGNORECASE
# Constructed regular expressions.
class Rexp
attr_reader :level, :options, :capture_keys
# Create a regular expression from the string. The regular
# expression will have a precedence of +level+ and will recognized
# +keys+ as a list of capture keys.
def initialize(string, level, keys, options=0)
@raw_string = string
@level = level
@capture_keys = keys
@options = options
end
# Return a Regexp from the the constructed regular expression.
def regexp
@regexp ||= Regexp.new(encoding)
end
# Does it match a string? (returns Re::Result if match, nil otherwise)
def match(string)
md = regexp.match(string)
md ? Result.new(md, self) : nil
end
alias =~ match
# New regular expresion that matches the concatenation of self and
# other.
def +(other)
Rexp.new(parenthesized_encoding(CONCAT) + other.parenthesized_encoding(CONCAT),
CONCAT,
capture_keys + other.capture_keys)
end
# New regular expresion that matches either self or other.
def |(other)
Rexp.new(parenthesized_encoding(ALT) + "|" + other.parenthesized_encoding(ALT),
ALT,
capture_keys + other.capture_keys)
end
# New regular expression where self is optional.
def optional
Rexp.new(parenthesized_encoding(POSTFIX) + "?", POSTFIX, capture_keys)
end
# New regular expression that matches self many (zero or more)
# times.
def many
Rexp.new(parenthesized_encoding(POSTFIX) + "*", POSTFIX, capture_keys)
end
# New regular expression that matches self many (zero or more)
# times (non-greedy version).
def many!
Rexp.new(parenthesized_encoding(POSTFIX) + "*?", POSTFIX, capture_keys)
end
# New regular expression that matches self one or more times.
def one_or_more
Rexp.new(parenthesized_encoding(POSTFIX) + "+", POSTFIX, capture_keys)
end
# New regular expression that matches self one or more times
# (non-greedy version).
def one_or_more!
Rexp.new(parenthesized_encoding(POSTFIX) + "+?", POSTFIX, capture_keys)
end
# New regular expression that matches self between +min+ and +max+
# times (inclusive). If +max+ is omitted, then it must match self
# exactly exactly +min+ times.
def repeat(min, max=nil)
if min && max
Rexp.new(parenthesized_encoding(POSTFIX) + "{#{min},#{max}}", POSTFIX, capture_keys)
else
Rexp.new(parenthesized_encoding(POSTFIX) + "{#{min}}", POSTFIX, capture_keys)
end
end
# New regular expression that matches self at least +min+ times.
def at_least(min)
Rexp.new(parenthesized_encoding(POSTFIX) + "{#{min},}", POSTFIX, capture_keys)
end
# New regular expression that matches self at most +max+ times.
def at_most(max)
Rexp.new(parenthesized_encoding(POSTFIX) + "{0,#{max}}", POSTFIX, capture_keys)
end
# New regular expression that matches a single character that is
# not in the given set of characters.
def none(chars)
Rexp.new("[^" + Rexp.escape_any(chars) + "]", GROUPED, [])
end
# New regular expression that matches self across the complete
# string.
def all
self.begin.very_end
end
# New regular expression that matches self across most of the
# entire string (trailing new lines are not required to match).
def almost_all
self.begin.end
end
# New regular expression that matches self at the beginning of a line.
def bol
Rexp.new("^" + parenthesized_encoding(CONCAT), CONCAT, capture_keys)
end
# New regular expression that matches self at the end of the line.
def eol
Rexp.new(parenthesized_encoding(CONCAT) + "$", CONCAT, capture_keys)
end
# New regular expression that matches self at the beginning of a string.
def begin
Rexp.new("\\A" + parenthesized_encoding(CONCAT), CONCAT, capture_keys)
end
# New regular expression that matches self at the end of a string
# (trailing new lines are allowed to not match).
def end
Rexp.new(parenthesized_encoding(CONCAT) + "\\Z", CONCAT, capture_keys)
end
# New regular expression that matches self at the very end of a string
# (trailing new lines are required to match).
def very_end
Rexp.new(parenthesized_encoding(CONCAT) + "\\z", CONCAT, capture_keys)
end
# New expression that matches self across an entire line.
def line
self.bol.eol
end
# New regular expression that is grouped, but does not cause the
# capture of a match. The Re library normally handles grouping
# automatically, so this method shouldn't be needed by client
# software for normal operations.
def group
Rexp.new("(?:" + encoding + ")", GROUPED, capture_keys)
end
# New regular expression that captures text matching self. The
# matching text may be retrieved from the Re::Result object using
# the +name+ (a symbol) as the keyword.
def capture(name)
Rexp.new("(" + encoding + ")", GROUPED, [name] + capture_keys)
end
# New regular expression that matches self in multiline mode.
def multiline
Rexp.new(@raw_string, GROUPED, capture_keys, options | MULTILINE_MODE)
end
# Is this a multiline regular expression? The multiline mode of
# interior regular expressions are not reflected in value returned
# by this method.
def multiline?
(options & MULTILINE_MODE) != 0
end
# New regular expression that matches self while ignoring case.
def ignore_case
Rexp.new(@raw_string, GROUPED, capture_keys, options | IGNORE_CASE_MODE)
end
# Does this regular expression ignore case? Note that this only
# queries the outer most regular expression. The ignore case mode
# of interior regular expressions are not reflected in value
# returned by this method.
def ignore_case?
(options & IGNORE_CASE_MODE) != 0
end
# String representation of the constructed regular expression.
def to_s
regexp.to_s
end
protected
# String representation with grouping if needed.
#
# If the precedence of the current Regexp is less than the new
# precedence level, return the encoding wrapped in a non-capturing
# group. Otherwise just return the encoding.
def parenthesized_encoding(new_level)
if level >= new_level
encoding
else
group.encoding
end
end
# The string encoding of current regular expression. The encoding
# will include option flags if specified.
def encoding
if options == 0
@raw_string
else
"(?#{encode_options}:" + @raw_string + ")"
end
end
# Encode the options into a string (e.g "", "m", "i", or "mi")
def encode_options # :nodoc:
(multiline? ? "m" : "") +
(ignore_case? ? "i" : "")
end
private :encode_options
# New regular expression that matches the literal characters in
# +chars+. For example, Re.literal("a(b)") will be equivalent to
# /a\(b\)/. Note that characters with special meanings in regular
# expressions will be quoted.
def self.literal(chars)
new(Regexp.escape(chars), CONCAT, [])
end
# New regular expression constructed from a string representing a
# ruby regular expression. The raw string should represent a
# regular expression with the highest level of precedence (you
# should use parenthesis if it is not).
def self.raw(re_string) # :no-doc:
new(re_string, GROUPED, [])
end
# Escape special characters found in character classes.
def self.escape_any(chars) # :nodoc:
chars.gsub(/([\[\]\^\-])/) { "\\#{$1}" }
end
end
# Construct a regular expression from the literal string. Special
# Regexp characters will be escaped before constructing the regular
# expression. If no literal is given, then the NULL regular
# expression is returned.
#
# See Re for example usage.
#
def re(exp=nil)
exp ? Rexp.literal(exp) : NULL
end
extend self
# This module defines a number of methods returning common
# pre-packaged regular expressions along with methods to create
# regular expressions from character classes and other objects.
# ConstructionMethods is mixed into the NULL Rexp object so that
# re() without arguments can be used to access the methods.
module ConstructionMethods
# :call-seq:
# re.null
#
# Regular expression that matches the null string
def null
self
end
# :call-seq:
# re.any
# re.any(chars)
# re.any(range)
# re.any(chars, range, ...)
#
# Regular expression that matches a character from a character
# class.
#
# +Any+ without any arguments will match any single character.
# +Any+ with one or more arguments will construct a character
# class for the arguments. If the argument is a three character
# string where the middle character is "-", then the argument
# represents a range of characters. Otherwise the arguments are
# treated as a list of characters to be added to the character
# class.
#
# Examples:
#
# re.any -- match any character
# re.any("aieouy") -- match vowels
# re.any("0-9") -- match digits
# re.any("A-Z", "a-z", "0-9") -- match alphanumerics
# re.any("A-Z", "a-z", "0-9", "_") -- match alphanumerics
#
def any(*chars)
if chars.empty?
@dot ||= Rexp.raw(".")
else
any_chars = ''
chars.each do |chs|
if /^.-.$/ =~ chs
any_chars << chs
else
any_chars << Rexp.escape_any(chs)
end
end
Rexp.new("[" + any_chars + "]", GROUPED, [])
end
end
# :call-seq:
# re.space
#
# Regular expression that matches any white space character.
# (equivalent to /\s/)
def space
@space ||= Rexp.raw("\\s")
end
# :call-seq:
# re.spaces
#
# Regular expression that matches any sequence of white space
# characters. (equivalent to /\s+/)
def spaces
@spaces ||= space.one_or_more
end
# :call-seq:
# re.nonspace
#
# Regular expression that matches any non-white space character.
# (equivalent to /\S/)
def nonspace
@nonspace ||= Rexp.raw("\\S")
end
# :call-seq:
# re.nonspaces
#
# Regular expression that matches any sequence of non-white space
# characters. (equivalent to /\S+/)
def nonspaces
@nonspaces ||= Rexp.raw("\\S").one_or_more
end
# :call-seq:
# re.word_char
#
# Regular expression that matches any word character. (equivalent
# to /\w/)
def word_char
@word_char ||= Rexp.raw("\\w")
end
# :call-seq:
# re.word
#
# Regular expression that matches any sequence of word characters.
# (equivalent to /\w+/)
def word
@word ||= word_char.one_or_more
end
# :call-seq:
# re.break
#
# Regular expression that matches any break between word/non-word
# characters. This is a zero length match. (equivalent to /\b/)
def break
@break ||= Rexp.raw("\\b")
end
# :call-seq:
# re.digit
#
# Regular expression that matches a single digit. (equivalent to
# /\d/)
def digit
@digit ||= any("0-9")
end
# :call-seq:
# re.digits
#
# Regular expression that matches a sequence of digits.
# (equivalent to /\d+/)
def digits
@digits ||= digit.one_or_more
end
# :call-seq:
# re.hex_digit
#
# Regular expression that matches a single hex digit. (equivalent
# to /[A-Fa-f0-9]/)
def hex_digit
@hex_digit ||= any("0-9", "a-f", "A-F")
end
# :call-seq:
# re.hex_digits
#
# Regular expression that matches a sequence of hex digits
# (equivalent to /[A-Fa-f0-9]+/)
def hex_digits
@hex_digits ||= hex_digit.one_or_more
end
end
# Matches an empty string. Additional common regular expression
# construction methods are defined on NULL. See
# Re::ConstructionMethods for details.
NULL = Rexp.literal("")
NULL.extend(ConstructionMethods)
end
|
## This is the rakegem gemspec template. Make sure you read and understand
## all of the comments. Some sections require modification, and others can
## be deleted if you don't need them. Once you understand the contents of
## this file, feel free to delete any comments that begin with two hash marks.
## You can find comprehensive Gem::Specification documentation, at
## http://docs.rubygems.org/read/chapter/20
Gem::Specification.new do |s|
s.specification_version = 2 if s.respond_to? :specification_version=
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.rubygems_version = '1.3.5'
## Leave these as is they will be modified for you by the rake gemspec task.
## If your rubyforge_project name is different, then edit it and comment out
## the sub! line in the Rakefile
s.name = 'smartermeter'
s.version = '0.4.4'
s.date = '2014-05-17'
s.rubyforge_project = 'smartermeter'
## Make sure your summary is short. The description may be as long
## as you like.
s.summary = "Fetches SmartMeter data from PG&E"
s.description = "Fetches SmartMeter data from PG&E and can upload to Pachube"
## List the primary authors. If there are a bunch of authors, it's probably
## better to set the email to an email list or something. If you don't have
## a custom homepage, consider using your GitHub URL or the like.
s.authors = ["Matt Colyer"]
s.email = 'matt.removethis@nospam.colyer.name'
s.homepage = 'http://github.com/mcolyer/smartermeter'
## This gets added to the $LOAD_PATH so that 'lib/NAME.rb' can be required as
## require 'NAME.rb' or'/lib/NAME/file.rb' can be as require 'NAME/file.rb'
s.require_paths = %w[lib]
## This sections is only necessary if you have C extensions.
#s.require_paths << 'ext'
#s.extensions = %w[ext/extconf.rb]
## If your gem includes any executables, list them here.
s.executables = ["smartermeter"]
s.default_executable = 'smartermeter'
## Specify any RDoc options here. You'll want to add your README and
## LICENSE files to the extra_rdoc_files list.
#s.rdoc_options = ["--charset=UTF-8"]
#s.extra_rdoc_files = %w[README.md]
## List your runtime dependencies here. Runtime dependencies are those
## that are needed for an end user to actually USE your code.
s.add_dependency('mechanize', ["= 2.6.0"])
s.add_dependency('crypt19-rb', ["= 1.3.1"])
s.add_dependency('rest-client', ["= 1.6.7"])
s.add_dependency('json_pure', ["= 1.7.7"])
s.add_dependency('rubyzip', ["= 0.9.9"])
s.add_dependency('trollop', ["= 2.0"])
## List your development dependencies here. Development dependencies are
## those that are only needed during development
s.add_development_dependency('rake', ["~> 10.0.0"])
s.add_development_dependency('rspec', ["~> 2.13.0"])
s.add_development_dependency('vcr', ["~> 2.4.0"])
s.add_development_dependency('webmock', ["~> 1.9.0"])
s.add_development_dependency('minitar', ["~> 0.5.4"])
## Leave this section as-is. It will be automatically generated from the
## contents of your Git repository via the gemspec task. DO NOT REMOVE
## THE MANIFEST COMMENTS, they are used as delimiters by the task.
# = MANIFEST =
s.files = %w[
CHANGELOG.md
Gemfile
LICENSE
README.md
Rakefile
bin/smartermeter
icons/smartermeter-16x16.png
icons/smartermeter-32x32.png
icons/smartermeter.ico
icons/smartermeter.svg
installer/launch4j.xml
installer/main.rb
installer/nsis.nsi
lib/smartermeter.rb
lib/smartermeter/daemon.rb
lib/smartermeter/interfaces/cli.rb
lib/smartermeter/interfaces/swing.rb
lib/smartermeter/sample.rb
lib/smartermeter/samples.rb
lib/smartermeter/service.rb
lib/smartermeter/services/brighterplanet.rb
lib/smartermeter/services/cacert.pem
lib/smartermeter/services/pachube.erb
lib/smartermeter/services/pachube.rb
smartermeter.gemspec
]
# = MANIFEST =
## Test files will be grabbed from the file list. Make sure the path glob
## matches what you actually use.
s.test_files = s.files.select { |path| path =~ /^spec\/*_spec.rb/ }
end
Update minitar
## This is the rakegem gemspec template. Make sure you read and understand
## all of the comments. Some sections require modification, and others can
## be deleted if you don't need them. Once you understand the contents of
## this file, feel free to delete any comments that begin with two hash marks.
## You can find comprehensive Gem::Specification documentation, at
## http://docs.rubygems.org/read/chapter/20
Gem::Specification.new do |s|
s.specification_version = 2 if s.respond_to? :specification_version=
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.rubygems_version = '1.3.5'
## Leave these as is they will be modified for you by the rake gemspec task.
## If your rubyforge_project name is different, then edit it and comment out
## the sub! line in the Rakefile
s.name = 'smartermeter'
s.version = '0.4.4'
s.date = '2014-05-17'
s.rubyforge_project = 'smartermeter'
## Make sure your summary is short. The description may be as long
## as you like.
s.summary = "Fetches SmartMeter data from PG&E"
s.description = "Fetches SmartMeter data from PG&E and can upload to Pachube"
## List the primary authors. If there are a bunch of authors, it's probably
## better to set the email to an email list or something. If you don't have
## a custom homepage, consider using your GitHub URL or the like.
s.authors = ["Matt Colyer"]
s.email = 'matt.removethis@nospam.colyer.name'
s.homepage = 'http://github.com/mcolyer/smartermeter'
## This gets added to the $LOAD_PATH so that 'lib/NAME.rb' can be required as
## require 'NAME.rb' or'/lib/NAME/file.rb' can be as require 'NAME/file.rb'
s.require_paths = %w[lib]
## This sections is only necessary if you have C extensions.
#s.require_paths << 'ext'
#s.extensions = %w[ext/extconf.rb]
## If your gem includes any executables, list them here.
s.executables = ["smartermeter"]
s.default_executable = 'smartermeter'
## Specify any RDoc options here. You'll want to add your README and
## LICENSE files to the extra_rdoc_files list.
#s.rdoc_options = ["--charset=UTF-8"]
#s.extra_rdoc_files = %w[README.md]
## List your runtime dependencies here. Runtime dependencies are those
## that are needed for an end user to actually USE your code.
s.add_dependency('mechanize', ["= 2.6.0"])
s.add_dependency('crypt19-rb', ["= 1.3.1"])
s.add_dependency('rest-client', ["= 1.6.7"])
s.add_dependency('json_pure', ["= 1.7.7"])
s.add_dependency('rubyzip', ["= 0.9.9"])
s.add_dependency('trollop', ["= 2.0"])
## List your development dependencies here. Development dependencies are
## those that are only needed during development
s.add_development_dependency('rake', ["~> 10.0.0"])
s.add_development_dependency('rspec', ["~> 2.13.0"])
s.add_development_dependency('vcr', ["~> 2.4.0"])
s.add_development_dependency('webmock', ["~> 1.9.0"])
s.add_development_dependency('minitar', ["~> 0.6.0"])
## Leave this section as-is. It will be automatically generated from the
## contents of your Git repository via the gemspec task. DO NOT REMOVE
## THE MANIFEST COMMENTS, they are used as delimiters by the task.
# = MANIFEST =
s.files = %w[
CHANGELOG.md
Gemfile
LICENSE
README.md
Rakefile
bin/smartermeter
icons/smartermeter-16x16.png
icons/smartermeter-32x32.png
icons/smartermeter.ico
icons/smartermeter.svg
installer/launch4j.xml
installer/main.rb
installer/nsis.nsi
lib/smartermeter.rb
lib/smartermeter/daemon.rb
lib/smartermeter/interfaces/cli.rb
lib/smartermeter/interfaces/swing.rb
lib/smartermeter/sample.rb
lib/smartermeter/samples.rb
lib/smartermeter/service.rb
lib/smartermeter/services/brighterplanet.rb
lib/smartermeter/services/cacert.pem
lib/smartermeter/services/pachube.erb
lib/smartermeter/services/pachube.rb
smartermeter.gemspec
]
# = MANIFEST =
## Test files will be grabbed from the file list. Make sure the path glob
## matches what you actually use.
s.test_files = s.files.select { |path| path =~ /^spec\/*_spec.rb/ }
end
|
module VagrantPlugins
module Ansible
class Provisioner < Vagrant.plugin("2", :provisioner)
def provision
ssh = @machine.ssh_info
# Connect with Vagrant user (unless --user or --private-key are overidden by 'raw_arguments')
options = %W[--private-key=#{ssh[:private_key_path]} --user=#{ssh[:username]}]
# Joker! Not (yet) supported arguments can be passed this way.
options << "#{config.raw_arguments}" if config.raw_arguments
# Append Provisioner options (higher precedence):
options << "--extra-vars=" + config.extra_vars.map{|k,v| "#{k}=#{v}"}.join(' ') if config.extra_vars
options << "--inventory-file=#{config.inventory_file}" if config.inventory_file
options << "--ask-sudo-pass" if config.ask_sudo_pass
options << "--tags=#{as_list_argument(config.tags)}" if config.tags
options << "--limit=#{as_list_argument(config.limit)}" if config.limit
options << "--sudo" if config.sudo
options << "--sudo-user=#{config.sudo_user}" if config.sudo_user
options << "--verbose" if config.verbose
# Assemble the full ansible-playbook command
command = (%w(ansible-playbook) << options << config.playbook).flatten
# Write stdout and stderr data, since it's the regular Ansible output
command << {
:env => { "ANSIBLE_FORCE_COLOR" => "true" },
:notify => [:stdout, :stderr]
}
begin
Vagrant::Util::Subprocess.execute(*command) do |type, data|
if type == :stdout || type == :stderr
@machine.env.ui.info(data.chomp, :prefix => false)
end
end
rescue Vagrant::Util::Subprocess::LaunchError
raise Vagrant::Errors::AnsiblePlaybookAppNotFound
end
end
private
def as_list_argument(v)
v.kind_of?(Array) ? v.join(',') : v
end
end
end
end
Support different verbosity levels with 'ansible.verbose'
module VagrantPlugins
module Ansible
class Provisioner < Vagrant.plugin("2", :provisioner)
def provision
ssh = @machine.ssh_info
# Connect with Vagrant user (unless --user or --private-key are overidden by 'raw_arguments')
options = %W[--private-key=#{ssh[:private_key_path]} --user=#{ssh[:username]}]
# Joker! Not (yet) supported arguments can be passed this way.
options << "#{config.raw_arguments}" if config.raw_arguments
# Append Provisioner options (higher precedence):
options << "--extra-vars=" + config.extra_vars.map{|k,v| "#{k}=#{v}"}.join(' ') if config.extra_vars
options << "--inventory-file=#{config.inventory_file}" if config.inventory_file
options << "--ask-sudo-pass" if config.ask_sudo_pass
options << "--tags=#{as_list_argument(config.tags)}" if config.tags
options << "--limit=#{as_list_argument(config.limit)}" if config.limit
options << "--sudo" if config.sudo
options << "--sudo-user=#{config.sudo_user}" if config.sudo_user
if config.verbose
if config.verbose.is_a? String
if config.verbose =~ /v+$/
options << "--#{config.verbose}"
end
else
options << "--verbose"
end
end
# Assemble the full ansible-playbook command
command = (%w(ansible-playbook) << options << config.playbook).flatten
# Write stdout and stderr data, since it's the regular Ansible output
command << {
:env => { "ANSIBLE_FORCE_COLOR" => "true" },
:notify => [:stdout, :stderr]
}
begin
Vagrant::Util::Subprocess.execute(*command) do |type, data|
if type == :stdout || type == :stderr
@machine.env.ui.info(data.chomp, :prefix => false)
end
end
rescue Vagrant::Util::Subprocess::LaunchError
raise Vagrant::Errors::AnsiblePlaybookAppNotFound
end
end
private
def as_list_argument(v)
v.kind_of?(Array) ? v.join(',') : v
end
end
end
end
|
# tree.rb
#
# $Revision$ by $Author$
# $Name$
#
# = tree.rb - Generic Multi-way Tree implementation
#
# Provides a generic tree data structure with ability to
# store keyed node elements in the tree. The implementation
# mixes in the Enumerable module.
#
# Author:: Anupam Sengupta (anupamsg@gmail.com)
#
# Copyright (c) 2006, 2007 Anupam Sengupta
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# - Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# - Neither the name of the organization nor the names of its contributors may
# be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# This module provides a TreeNode class which is the primary class for all
# nodes represented in the Tree.
# This module mixes in the Enumerable module.
module Tree
# Rubytree Package Version
VERSION = '0.5.0'
# == TreeNode Class Description
#
# The node class for the tree representation. the nodes are named and have a
# place-holder for the node data (i.e., the `content' of the node). The node
# names are expected to be unique. In addition, the node provides navigation
# methods to traverse the tree.
#
# The nodes can have any number of child nodes attached to it. Note that while
# this implementation does not support directed graphs, the class itself makes
# no restrictions on associating a node's CONTENT with multiple parent nodes.
#
#
# == Example
#
# The following code-snippet implements this tree structure:
#
# +------------+
# | ROOT |
# +-----+------+
# +-------------+------------+
# | |
# +-------+-------+ +-------+-------+
# | CHILD 1 | | CHILD 2 |
# +-------+-------+ +---------------+
# |
# |
# +-------+-------+
# | GRANDCHILD 1 |
# +---------------+
#
# require 'tree'
#
# myTreeRoot = Tree::TreeNode.new("ROOT", "Root Content")
#
# myTreeRoot << Tree::TreeNode.new("CHILD1", "Child1 Content") << Tree::TreeNode.new("GRANDCHILD1", "GrandChild1 Content")
#
# myTreeRoot << Tree::TreeNode.new("CHILD2", "Child2 Content")
#
# myTreeRoot.printTree
#
# child1 = myTreeRoot["CHILD1"]
#
# grandChild1 = myTreeRoot["CHILD1"]["GRANDCHILD1"]
#
# siblingsOfChild1Array = child1.siblings
#
# immediateChildrenArray = myTreeRoot.children
#
# # Process all nodes
#
# myTreeRoot.each { |node| node.content.reverse }
#
# myTreeRoot.remove!(child1) # Remove the child
class TreeNode
include Enumerable
attr_reader :content, :name, :parent
attr_writer :content
# Constructor which expects the name of the node
#
# Name of the node is expected to be unique across the
# tree.
#
# The content can be of any type, and is defaulted to _nil_.
def initialize(name, content = nil)
raise "Node name HAS to be provided" if name == nil
@name = name
@content = content
self.setAsRoot!
@childrenHash = Hash.new
@children = []
end
# Returns a copy of this node, with the parent and children links removed.
def detached_copy
Tree::TreeNode.new(@name, @content ? @content.clone : nil)
end
# Print the string representation of this node.
def to_s
"Node Name: #{@name}" +
" Content: " + (@content || "<Empty>") +
" Parent: " + (isRoot?() ? "<None>" : @parent.name) +
" Children: #{@children.length}" +
" Total Nodes: #{size()}"
end
# Returns an array of ancestors in reversed order (the first element is the
# immediate parent). Returns nil if this is a root node.
def parentage
return nil if isRoot?
parentageArray = []
prevParent = self.parent
while (prevParent)
parentageArray << prevParent
prevParent = prevParent.parent
end
parentageArray
end
# Protected method to set the parent node.
# This method should NOT be invoked by client code.
def parent=(parent)
@parent = parent
end
# Convenience synonym for TreeNode#add method. This method allows a convenient
# method to add children hierarchies in the tree.
#
# E.g. root << child << grand_child
def <<(child)
add(child)
end
# Adds the specified child node to the receiver node. The child node's
# parent is set to be the receiver. The child is added as the last child in
# the current list of children for the receiver node.
def add(child)
raise "Child already added" if @childrenHash.has_key?(child.name)
@childrenHash[child.name] = child
@children << child
child.parent = self
return child
end
# Removes the specified child node from the receiver node. The removed
# children nodes are orphaned but available if an alternate reference
# exists.
#
# Returns the child node.
def remove!(child)
@childrenHash.delete(child.name)
@children.delete(child)
child.setAsRoot! unless child == nil
return child
end
# Removes this node from its parent. If this is the root node, then does
# nothing.
def removeFromParent!
@parent.remove!(self) unless isRoot?
end
# Removes all children from the receiver node.
def removeAll!
for child in @children
child.setAsRoot!
end
@childrenHash.clear
@children.clear
self
end
# Indicates whether this node has any associated content.
def hasContent?
@content != nil
end
# Protected method which sets this node as a root node.
def setAsRoot!
@parent = nil
end
# Indicates whether this node is a root node. Note that
# orphaned children will also be reported as root nodes.
def isRoot?
@parent == nil
end
# Indicates whether this node has any immediate child nodes.
def hasChildren?
@children.length != 0
end
# Indicates whether this node is a 'leaf' - i.e., one without
# any children
def isLeaf?
!hasChildren?
end
# Returns an array of all the immediate children. If a block is given,
# yields each child node to the block.
def children
if block_given?
@children.each {|child| yield child}
else
@children
end
end
# Returns the first child of this node. Will return nil if no children are
# present.
def firstChild
children.first
end
# Returns the last child of this node. Will return nil if no children are
# present.
def lastChild
children.last
end
# Returns every node (including the receiver node) from the tree to the
# specified block. The traversal is depth first and from left to right in
# pre-ordered sequence.
def each &block
yield self
children { |child| child.each(&block) }
end
# Traverses the tree in a pre-ordered sequence. This is equivalent to
# TreeNode#each
def preordered_each &block
each(&block)
end
# Performs breadth first traversal of the tree rooted at this node. The
# traversal in a given level is from left to right.
def breadth_each &block
node_queue = [self] # Create a queue with self as the initial entry
# Use a queue to do breadth traversal
until node_queue.empty?
node_to_traverse = node_queue.shift
yield node_to_traverse
# Enqueue the children from left to right.
node_to_traverse.children { |child| node_queue.push child }
end
end
# Yields all leaf nodes from this node to the specified block. May yield
# this node as well if this is a leaf node. Leaf traversal depth first and
# left to right.
def each_leaf &block
self.each { |node| yield(node) if node.isLeaf? }
end
# Returns the requested node from the set of immediate children.
#
# If the parameter is _numeric_, then the in-sequence array of children is
# accessed (see Tree#children). If the parameter is not _numeric_, then it
# is assumed to be the *name* of the child node to be returned.
def [](name_or_index)
raise "Name_or_index needs to be provided" if name_or_index == nil
if name_or_index.kind_of?(Integer)
@children[name_or_index]
else
@childrenHash[name_or_index]
end
end
# Returns the total number of nodes in this tree, rooted at the receiver
# node.
def size
@children.inject(1) {|sum, node| sum + node.size}
end
# Convenience synonym for Tree#size
def length
size()
end
# Pretty prints the tree starting with the receiver node.
def printTree(level = 0)
if isRoot?
print "*"
else
print "|" unless parent.isLastSibling?
print(' ' * (level - 1) * 4)
print(isLastSibling? ? "+" : "|")
print "---"
print(hasChildren? ? "+" : ">")
end
puts " #{name}"
children { |child| child.printTree(level + 1)}
end
# Returns the root for this tree. Root's root is itself.
def root
root = self
root = root.parent while !root.isRoot?
root
end
# Returns the first sibling for this node. If this is the root node, returns
# itself.
def firstSibling
if isRoot?
self
else
parent.children.first
end
end
# Returns true if this node is the first sibling.
def isFirstSibling?
firstSibling == self
end
# Returns the last sibling for this node. If this node is the root, returns
# itself.
def lastSibling
if isRoot?
self
else
parent.children.last
end
end
# Returns true if his node is the last sibling
def isLastSibling?
lastSibling == self
end
# Returns an array of siblings for this node.
# If a block is provided, yields each of the sibling
# nodes to the block. The root always has nil siblings.
def siblings
return nil if isRoot?
if block_given?
for sibling in parent.children
yield sibling if sibling != self
end
else
siblings = []
parent.children {|sibling| siblings << sibling if sibling != self}
siblings
end
end
# Returns true if this node is the only child of its parent
def isOnlyChild?
parent.children.size == 1
end
# Returns the next sibling for this node. Will return nil if no subsequent
# node is present.
def nextSibling
if myidx = parent.children.index(self)
parent.children.at(myidx + 1)
end
end
# Returns the previous sibling for this node. Will return nil if no
# subsequent node is present.
def previousSibling
if myidx = parent.children.index(self)
parent.children.at(myidx - 1) if myidx > 0
end
end
# Provides a comparision operation for the nodes. Comparision
# is based on the natural character-set ordering for the
# node names.
def <=>(other)
return +1 if other == nil
self.name <=> other.name
end
# Freezes all nodes in the tree
def freezeTree!
each {|node| node.freeze}
end
# Creates the marshal-dump represention of the tree rooted at this node.
def marshal_dump
self.collect { |node| node.createDumpRep }
end
# Creates a dump representation and returns the same as a hash
def createDumpRep
{ :name => @name, :parent => (isRoot? ? nil : @parent.name), :content => Marshal.dump(@content)}
end
# Loads a marshalled dump of the tree and returns the root node of the
# reconstructed tree. See the Marshal class for additional details.
def marshal_load(dumped_tree_array)
nodes = { }
for node_hash in dumped_tree_array do
name = node_hash[:name]
parent_name = node_hash[:parent]
content = Marshal.load(node_hash[:content])
if parent_name then
nodes[name] = current_node = Tree::TreeNode.new(name, content)
nodes[parent_name].add current_node
else
# This is the root node, hence initialize self.
initialize(name, content)
nodes[name] = self # Add self to the
end
end
end
# Returns depth of the tree from this node. A single leaf node has a
# depth of 1.
def depth
return 1 if isLeaf?
1 + @children.collect { |child| child.depth }.max
end
# Returns breadth of the tree at this node level. A single node has a
# breadth of 1.
def breadth
return 1 if isRoot?
parent.children.size
end
protected :parent=, :setAsRoot!, :createDumpRep
end
end
# $Log$
# Revision 1.26 2007/12/20 02:50:04 anupamsg
# (Tree::TreeNode): Removed the spurious self_initialize from the protected list.
#
# Revision 1.25 2007/12/19 20:28:05 anupamsg
# Removed the unnecesary self_initialize method.
#
# Revision 1.24 2007/12/19 06:39:17 anupamsg
# Removed the unnecessary field and record separator constants. Also updated the
# history.txt file.
#
# Revision 1.23 2007/12/19 06:25:00 anupamsg
# (Tree::TreeNode): Minor fix to the comments. Also fixed the private/protected
# scope issue with the createDumpRep method.
#
# Revision 1.22 2007/12/19 06:22:03 anupamsg
# Updated the marshalling logic to correctly handle non-string content. This
# should fix the bug # 15614 ("When dumping with an Object as the content, you get
# a delimiter collision")
#
# Revision 1.21 2007/12/19 02:24:17 anupamsg
# Updated the marshalling logic to handle non-string contents on the nodes.
#
# Revision 1.20 2007/10/10 08:42:57 anupamsg
# Release 0.4.3
#
# Revision 1.19 2007/08/31 01:16:27 anupamsg
# Added breadth and pre-order traversals for the tree. Also added a method
# to return the detached copy of a node from the tree.
#
# Revision 1.18 2007/07/21 05:14:44 anupamsg
# Added a VERSION constant to the Tree module,
# and using the same in the Rakefile.
#
# Revision 1.17 2007/07/21 03:24:25 anupamsg
# Minor edits to parameter names. User visible functionality does not change.
#
# Revision 1.16 2007/07/18 23:38:55 anupamsg
# Minor updates to tree.rb
#
# Revision 1.15 2007/07/18 22:11:50 anupamsg
# Added depth and breadth methods for the TreeNode.
#
# Revision 1.14 2007/07/18 19:33:27 anupamsg
# Added a new binary tree implementation.
#
# Revision 1.13 2007/07/18 07:17:34 anupamsg
# Fixed a issue where TreeNode.ancestors was shadowing Module.ancestors. This method
# has been renamed to TreeNode.parentage.
#
# Revision 1.12 2007/07/17 03:39:28 anupamsg
# Moved the CVS Log keyword to end of the files.
#
Minor code changes. Removed self_initialize from the protected methods' list.
git-svn-id: 829087911343bbb8fc19dec46c41ea854bd61efa@96 086f654a-3896-4ada-bbbd-7c2a7a138609
# tree.rb
#
# $Revision$ by $Author$
# $Name$
#
# = tree.rb - Generic Multi-way Tree implementation
#
# Provides a generic tree data structure with ability to
# store keyed node elements in the tree. The implementation
# mixes in the Enumerable module.
#
# Author:: Anupam Sengupta (anupamsg@gmail.com)
#
# Copyright (c) 2006, 2007 Anupam Sengupta
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# - Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# - Neither the name of the organization nor the names of its contributors may
# be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# This module provides a TreeNode class which is the primary class for all
# nodes represented in the Tree.
# This module mixes in the Enumerable module.
module Tree
# Rubytree Package Version
VERSION = '0.5.0'
# == TreeNode Class Description
#
# The node class for the tree representation. the nodes are named and have a
# place-holder for the node data (i.e., the `content' of the node). The node
# names are expected to be unique. In addition, the node provides navigation
# methods to traverse the tree.
#
# The nodes can have any number of child nodes attached to it. Note that while
# this implementation does not support directed graphs, the class itself makes
# no restrictions on associating a node's CONTENT with multiple parent nodes.
#
#
# == Example
#
# The following code-snippet implements this tree structure:
#
# +------------+
# | ROOT |
# +-----+------+
# +-------------+------------+
# | |
# +-------+-------+ +-------+-------+
# | CHILD 1 | | CHILD 2 |
# +-------+-------+ +---------------+
# |
# |
# +-------+-------+
# | GRANDCHILD 1 |
# +---------------+
#
# require 'tree'
#
# myTreeRoot = Tree::TreeNode.new("ROOT", "Root Content")
#
# myTreeRoot << Tree::TreeNode.new("CHILD1", "Child1 Content") << Tree::TreeNode.new("GRANDCHILD1", "GrandChild1 Content")
#
# myTreeRoot << Tree::TreeNode.new("CHILD2", "Child2 Content")
#
# myTreeRoot.printTree
#
# child1 = myTreeRoot["CHILD1"]
#
# grandChild1 = myTreeRoot["CHILD1"]["GRANDCHILD1"]
#
# siblingsOfChild1Array = child1.siblings
#
# immediateChildrenArray = myTreeRoot.children
#
# # Process all nodes
#
# myTreeRoot.each { |node| node.content.reverse }
#
# myTreeRoot.remove!(child1) # Remove the child
class TreeNode
include Enumerable
attr_reader :content, :name, :parent
attr_writer :content
# Constructor which expects the name of the node
#
# Name of the node is expected to be unique across the
# tree.
#
# The content can be of any type, and is defaulted to _nil_.
def initialize(name, content = nil)
raise "Node name HAS to be provided" if name == nil
@name = name
@content = content
self.setAsRoot!
@childrenHash = Hash.new
@children = []
end
# Returns a copy of this node, with the parent and children links removed.
def detached_copy
Tree::TreeNode.new(@name, @content ? @content.clone : nil)
end
# Print the string representation of this node.
def to_s
"Node Name: #{@name}" +
" Content: " + (@content || "<Empty>") +
" Parent: " + (isRoot?() ? "<None>" : @parent.name) +
" Children: #{@children.length}" +
" Total Nodes: #{size()}"
end
# Returns an array of ancestors in reversed order (the first element is the
# immediate parent). Returns nil if this is a root node.
def parentage
return nil if isRoot?
parentageArray = []
prevParent = self.parent
while (prevParent)
parentageArray << prevParent
prevParent = prevParent.parent
end
parentageArray
end
# Protected method to set the parent node.
# This method should NOT be invoked by client code.
def parent=(parent)
@parent = parent
end
# Convenience synonym for TreeNode#add method. This method allows a convenient
# method to add children hierarchies in the tree.
#
# E.g. root << child << grand_child
def <<(child)
add(child)
end
# Adds the specified child node to the receiver node. The child node's
# parent is set to be the receiver. The child is added as the last child in
# the current list of children for the receiver node.
def add(child)
raise "Child already added" if @childrenHash.has_key?(child.name)
@childrenHash[child.name] = child
@children << child
child.parent = self
return child
end
# Removes the specified child node from the receiver node. The removed
# children nodes are orphaned but available if an alternate reference
# exists.
#
# Returns the child node.
def remove!(child)
@childrenHash.delete(child.name)
@children.delete(child)
child.setAsRoot! unless child == nil
return child
end
# Removes this node from its parent. If this is the root node, then does
# nothing.
def removeFromParent!
@parent.remove!(self) unless isRoot?
end
# Removes all children from the receiver node.
def removeAll!
for child in @children
child.setAsRoot!
end
@childrenHash.clear
@children.clear
self
end
# Indicates whether this node has any associated content.
def hasContent?
@content != nil
end
# Protected method which sets this node as a root node.
def setAsRoot!
@parent = nil
end
# Indicates whether this node is a root node. Note that
# orphaned children will also be reported as root nodes.
def isRoot?
@parent == nil
end
# Indicates whether this node has any immediate child nodes.
def hasChildren?
@children.length != 0
end
# Indicates whether this node is a 'leaf' - i.e., one without
# any children
def isLeaf?
!hasChildren?
end
# Returns an array of all the immediate children. If a block is given,
# yields each child node to the block.
def children
if block_given?
@children.each {|child| yield child}
else
@children
end
end
# Returns the first child of this node. Will return nil if no children are
# present.
def firstChild
children.first
end
# Returns the last child of this node. Will return nil if no children are
# present.
def lastChild
children.last
end
# Returns every node (including the receiver node) from the tree to the
# specified block. The traversal is depth first and from left to right in
# pre-ordered sequence.
def each &block
yield self
children { |child| child.each(&block) }
end
# Traverses the tree in a pre-ordered sequence. This is equivalent to
# TreeNode#each
def preordered_each &block
each(&block)
end
# Performs breadth first traversal of the tree rooted at this node. The
# traversal in a given level is from left to right.
def breadth_each &block
node_queue = [self] # Create a queue with self as the initial entry
# Use a queue to do breadth traversal
until node_queue.empty?
node_to_traverse = node_queue.shift
yield node_to_traverse
# Enqueue the children from left to right.
node_to_traverse.children { |child| node_queue.push child }
end
end
# Yields all leaf nodes from this node to the specified block. May yield
# this node as well if this is a leaf node. Leaf traversal depth first and
# left to right.
def each_leaf &block
self.each { |node| yield(node) if node.isLeaf? }
end
# Returns the requested node from the set of immediate children.
#
# If the parameter is _numeric_, then the in-sequence array of children is
# accessed (see Tree#children). If the parameter is not _numeric_, then it
# is assumed to be the *name* of the child node to be returned.
def [](name_or_index)
raise "Name_or_index needs to be provided" if name_or_index == nil
if name_or_index.kind_of?(Integer)
@children[name_or_index]
else
@childrenHash[name_or_index]
end
end
# Returns the total number of nodes in this tree, rooted at the receiver
# node.
def size
@children.inject(1) {|sum, node| sum + node.size}
end
# Convenience synonym for Tree#size
def length
size()
end
# Pretty prints the tree starting with the receiver node.
def printTree(level = 0)
if isRoot?
print "*"
else
print "|" unless parent.isLastSibling?
print(' ' * (level - 1) * 4)
print(isLastSibling? ? "+" : "|")
print "---"
print(hasChildren? ? "+" : ">")
end
puts " #{name}"
children { |child| child.printTree(level + 1)}
end
# Returns the root for this tree. Root's root is itself.
def root
root = self
root = root.parent while !root.isRoot?
root
end
# Returns the first sibling for this node. If this is the root node, returns
# itself.
def firstSibling
if isRoot?
self
else
parent.children.first
end
end
# Returns true if this node is the first sibling.
def isFirstSibling?
firstSibling == self
end
# Returns the last sibling for this node. If this node is the root, returns
# itself.
def lastSibling
if isRoot?
self
else
parent.children.last
end
end
# Returns true if his node is the last sibling
def isLastSibling?
lastSibling == self
end
# Returns an array of siblings for this node.
# If a block is provided, yields each of the sibling
# nodes to the block. The root always has nil siblings.
def siblings
return nil if isRoot?
if block_given?
for sibling in parent.children
yield sibling if sibling != self
end
else
siblings = []
parent.children {|sibling| siblings << sibling if sibling != self}
siblings
end
end
# Returns true if this node is the only child of its parent
def isOnlyChild?
parent.children.size == 1
end
# Returns the next sibling for this node. Will return nil if no subsequent
# node is present.
def nextSibling
if myidx = parent.children.index(self)
parent.children.at(myidx + 1)
end
end
# Returns the previous sibling for this node. Will return nil if no
# subsequent node is present.
def previousSibling
if myidx = parent.children.index(self)
parent.children.at(myidx - 1) if myidx > 0
end
end
# Provides a comparision operation for the nodes. Comparision
# is based on the natural character-set ordering for the
# node names.
def <=>(other)
return +1 if other == nil
self.name <=> other.name
end
# Freezes all nodes in the tree
def freezeTree!
each {|node| node.freeze}
end
# Creates the marshal-dump represention of the tree rooted at this node.
def marshal_dump
self.collect { |node| node.createDumpRep }
end
# Creates a dump representation and returns the same as a hash.
def createDumpRep
{ :name => @name, :parent => (isRoot? ? nil : @parent.name), :content => Marshal.dump(@content)}
end
# Loads a marshalled dump of the tree and returns the root node of the
# reconstructed tree. See the Marshal class for additional details.
def marshal_load(dumped_tree_array)
nodes = { }
for node_hash in dumped_tree_array do
name = node_hash[:name]
parent_name = node_hash[:parent]
content = Marshal.load(node_hash[:content])
if parent_name then
nodes[name] = current_node = Tree::TreeNode.new(name, content)
nodes[parent_name].add current_node
else
# This is the root node, hence initialize self.
initialize(name, content)
nodes[name] = self # Add self to the
end
end
end
# Returns depth of the tree from this node. A single leaf node has a
# depth of 1.
def depth
return 1 if isLeaf?
1 + @children.collect { |child| child.depth }.max
end
# Returns breadth of the tree at this node level. A single node has a
# breadth of 1.
def breadth
return 1 if isRoot?
parent.children.size
end
protected :parent=, :setAsRoot!, :createDumpRep
end
end
# $Log$
# Revision 1.27 2007/12/20 03:00:03 anupamsg
# Minor code changes. Removed self_initialize from the protected methods' list.
#
# Revision 1.26 2007/12/20 02:50:04 anupamsg
# (Tree::TreeNode): Removed the spurious self_initialize from the protected list.
#
# Revision 1.25 2007/12/19 20:28:05 anupamsg
# Removed the unnecesary self_initialize method.
#
# Revision 1.24 2007/12/19 06:39:17 anupamsg
# Removed the unnecessary field and record separator constants. Also updated the
# history.txt file.
#
# Revision 1.23 2007/12/19 06:25:00 anupamsg
# (Tree::TreeNode): Minor fix to the comments. Also fixed the private/protected
# scope issue with the createDumpRep method.
#
# Revision 1.22 2007/12/19 06:22:03 anupamsg
# Updated the marshalling logic to correctly handle non-string content. This
# should fix the bug # 15614 ("When dumping with an Object as the content, you get
# a delimiter collision")
#
# Revision 1.21 2007/12/19 02:24:17 anupamsg
# Updated the marshalling logic to handle non-string contents on the nodes.
#
# Revision 1.20 2007/10/10 08:42:57 anupamsg
# Release 0.4.3
#
# Revision 1.19 2007/08/31 01:16:27 anupamsg
# Added breadth and pre-order traversals for the tree. Also added a method
# to return the detached copy of a node from the tree.
#
# Revision 1.18 2007/07/21 05:14:44 anupamsg
# Added a VERSION constant to the Tree module,
# and using the same in the Rakefile.
#
# Revision 1.17 2007/07/21 03:24:25 anupamsg
# Minor edits to parameter names. User visible functionality does not change.
#
# Revision 1.16 2007/07/18 23:38:55 anupamsg
# Minor updates to tree.rb
#
# Revision 1.15 2007/07/18 22:11:50 anupamsg
# Added depth and breadth methods for the TreeNode.
#
# Revision 1.14 2007/07/18 19:33:27 anupamsg
# Added a new binary tree implementation.
#
# Revision 1.13 2007/07/18 07:17:34 anupamsg
# Fixed a issue where TreeNode.ancestors was shadowing Module.ancestors. This method
# has been renamed to TreeNode.parentage.
#
# Revision 1.12 2007/07/17 03:39:28 anupamsg
# Moved the CVS Log keyword to end of the files.
#
|
require 'mkmf'
uname = `uname -s`.chop.split
dir_config 'blink1'
case uname[0]
when 'Darwin'
$CFLAGS <<
' -arch x86_64 -pthread '
$LIBS <<
' -framework IOKit -framework CoreFoundation '
# RbConfig::MAKEFILE_CONFIG['CC'] = 'gcc'
$HID_C = "#{$srcdir}/hid.c.mac"
when 'Windows_NT'
$CFLAGS <<
' -arch i386 -arch x86_64 ' <<
' -pthread '
$LIBS <<
' -lsetupapi -Wl,--enable-auto-import -static-libgcc -static-libstdc++ '
$HID_C = "#{$srcdir}/hid.c.windows"
when 'Linux'
$CFLAGS <<
" #{ `pkg-config libusb-1.0 --cflags` } "
$LIBS <<
" #{ `pkg-config libusb-1.0 --libs` }"
' -lrt -lpthread -ldl -static '
$HID_C = "#{$srcdir}/hid.c.libusb"
when 'FreeBSD'
$LIBS <<
' -L/usr/local/lib -lusb -lrt -lpthread -liconv -static '
$HID_C = "#{$srcdir}/hid.c.libusb"
end
FileUtils.copy $HID_C, "#{$srcdir}/hid.c"
$CFLAGS << ' -std=gnu99'
create_makefile('blink1')
strip LIBS/CFLAGS
require 'mkmf'
uname = `uname -s`.chop.split
dir_config 'blink1'
case uname[0]
when 'Darwin'
$CFLAGS <<
' -arch x86_64 -pthread '
$LIBS <<
' -framework IOKit -framework CoreFoundation '
# RbConfig::MAKEFILE_CONFIG['CC'] = 'gcc'
$HID_C = "#{$srcdir}/hid.c.mac"
when 'Windows_NT'
$CFLAGS <<
' -arch i386 -arch x86_64 ' <<
' -pthread '
$LIBS <<
' -lsetupapi -Wl,--enable-auto-import -static-libgcc -static-libstdc++ '
$HID_C = "#{$srcdir}/hid.c.windows"
when 'Linux'
$CFLAGS <<
" #{ `pkg-config libusb-1.0 --cflags`.strip } "
$LIBS <<
" #{ `pkg-config libusb-1.0 --libs`.strip }"
' -lrt -lpthread -ldl -static '
$HID_C = "#{$srcdir}/hid.c.libusb"
when 'FreeBSD'
$LIBS <<
' -L/usr/local/lib -lusb -lrt -lpthread -liconv -static '
$HID_C = "#{$srcdir}/hid.c.libusb"
end
FileUtils.copy $HID_C, "#{$srcdir}/hid.c"
$CFLAGS << ' -std=gnu99'
create_makefile('blink1')
|
# encoding: UTF-8
require 'mkmf'
def asplode lib
abort "-----\n#{lib} is missing. please check your installation of mysql and try again.\n-----"
end
# 2.0-only
have_header('ruby/thread.h') && have_func('rb_thread_call_without_gvl', 'ruby/thread.h')
# 1.9-only
have_func('rb_thread_blocking_region')
have_func('rb_wait_for_single_fd')
have_func('rb_hash_dup')
have_func('rb_intern3')
# borrowed from mysqlplus
# http://github.com/oldmoe/mysqlplus/blob/master/ext/extconf.rb
dirs = ENV['PATH'].split(File::PATH_SEPARATOR) + %w[
/opt
/opt/local
/opt/local/mysql
/opt/local/lib/mysql5
/usr
/usr/mysql
/usr/local
/usr/local/mysql
/usr/local/mysql-*
/usr/local/lib/mysql5
].map{|dir| "#{dir}/bin" }
GLOB = "{#{dirs.join(',')}}/{mysql_config,mysql_config5}"
# If the user has provided a --with-mysql-dir argument, we must respect it or fail.
inc, lib = dir_config('mysql')
if inc && lib
# Ruby versions not incorporating the mkmf fix at
# https://bugs.ruby-lang.org/projects/ruby-trunk/repository/revisions/39717
# do not properly search for lib directories, and must be corrected
unless lib && lib[-3, 3] == 'lib'
@libdir_basename = 'lib'
inc, lib = dir_config('mysql')
end
abort "-----\nCannot find include dir at #{inc}\n-----" unless inc && File.directory?(inc)
abort "-----\nCannot find library dir at #{lib}\n-----" unless lib && File.directory?(lib)
warn "-----\nUsing --with-mysql-dir=#{File.dirname inc}\n-----"
rpath_dir = lib
elsif mc = (with_config('mysql-config') || Dir[GLOB].first)
# If the user has provided a --with-mysql-config argument, we must respect it or fail.
# If the user gave --with-mysql-config with no argument means we should try to find it.
mc = Dir[GLOB].first if mc == true
abort "-----\nCannot find mysql_config at #{mc}\n-----" unless mc && File.exists?(mc)
abort "-----\nCannot execute mysql_config at #{mc}\n-----" unless File.executable?(mc)
warn "-----\nUsing mysql_config at #{mc}\n-----"
ver = `#{mc} --version`.chomp.to_f
includes = `#{mc} --include`.chomp
exit 1 if $? != 0
libs = `#{mc} --libs_r`.chomp
# MySQL 5.5 and above already have re-entrant code in libmysqlclient (no _r).
if ver >= 5.5 || libs.empty?
libs = `#{mc} --libs`.chomp
end
exit 1 if $? != 0
$INCFLAGS += ' ' + includes
$libs = libs + " " + $libs
rpath_dir = libs
else
inc, lib = dir_config('mysql', '/usr/local')
libs = ['m', 'z', 'socket', 'nsl', 'mygcc']
while not find_library('mysqlclient', 'mysql_query', lib, "#{lib}/mysql") do
exit 1 if libs.empty?
have_library(libs.shift)
end
rpath_dir = lib
end
if RUBY_PLATFORM =~ /mswin|mingw/
exit 1 unless have_library('libmysql')
end
if have_header('mysql.h')
prefix = nil
elsif have_header('mysql/mysql.h')
prefix = 'mysql'
else
asplode 'mysql.h'
end
%w{ errmsg.h mysqld_error.h }.each do |h|
header = [prefix, h].compact.join '/'
asplode h unless have_header h
end
# GCC | Clang | XCode specific flags
if RbConfig::MAKEFILE_CONFIG['CC'] =~ /gcc|clang|xcrun/
$CFLAGS << ' -Wall -funroll-loops'
if libdir = rpath_dir[%r{(-L)?(/[^ ]+)}, 2]
# The following comment and test is borrowed from the Pg gem:
# Try to use runtime path linker option, even if RbConfig doesn't know about it.
# The rpath option is usually set implicit by dir_config(), but so far not on Mac OS X.
if RbConfig::CONFIG["RPATHFLAG"].to_s.empty? && try_link('int main() {return 0;}', " -Wl,-rpath,#{libdir}")
warn "-----\nSetting rpath to #{libdir}\n-----"
$LDFLAGS << " -Wl,-rpath,#{libdir}"
else
# Make sure that LIBPATH gets set if we didn't explicitly set the rpath.
$LIBPATH << libdir unless $LIBPATH.include?(libdir)
end
end
end
create_makefile('mysql2/mysql2')
Use try_link to test compiler flags instead of checking for gcc specifically.
# encoding: UTF-8
require 'mkmf'
def asplode lib
abort "-----\n#{lib} is missing. please check your installation of mysql and try again.\n-----"
end
# 2.0-only
have_header('ruby/thread.h') && have_func('rb_thread_call_without_gvl', 'ruby/thread.h')
# 1.9-only
have_func('rb_thread_blocking_region')
have_func('rb_wait_for_single_fd')
have_func('rb_hash_dup')
have_func('rb_intern3')
# borrowed from mysqlplus
# http://github.com/oldmoe/mysqlplus/blob/master/ext/extconf.rb
dirs = ENV['PATH'].split(File::PATH_SEPARATOR) + %w[
/opt
/opt/local
/opt/local/mysql
/opt/local/lib/mysql5
/usr
/usr/mysql
/usr/local
/usr/local/mysql
/usr/local/mysql-*
/usr/local/lib/mysql5
].map{|dir| "#{dir}/bin" }
GLOB = "{#{dirs.join(',')}}/{mysql_config,mysql_config5}"
# If the user has provided a --with-mysql-dir argument, we must respect it or fail.
inc, lib = dir_config('mysql')
if inc && lib
# Ruby versions not incorporating the mkmf fix at
# https://bugs.ruby-lang.org/projects/ruby-trunk/repository/revisions/39717
# do not properly search for lib directories, and must be corrected
unless lib && lib[-3, 3] == 'lib'
@libdir_basename = 'lib'
inc, lib = dir_config('mysql')
end
abort "-----\nCannot find include dir at #{inc}\n-----" unless inc && File.directory?(inc)
abort "-----\nCannot find library dir at #{lib}\n-----" unless lib && File.directory?(lib)
warn "-----\nUsing --with-mysql-dir=#{File.dirname inc}\n-----"
rpath_dir = lib
elsif mc = (with_config('mysql-config') || Dir[GLOB].first)
# If the user has provided a --with-mysql-config argument, we must respect it or fail.
# If the user gave --with-mysql-config with no argument means we should try to find it.
mc = Dir[GLOB].first if mc == true
abort "-----\nCannot find mysql_config at #{mc}\n-----" unless mc && File.exists?(mc)
abort "-----\nCannot execute mysql_config at #{mc}\n-----" unless File.executable?(mc)
warn "-----\nUsing mysql_config at #{mc}\n-----"
ver = `#{mc} --version`.chomp.to_f
includes = `#{mc} --include`.chomp
exit 1 if $? != 0
libs = `#{mc} --libs_r`.chomp
# MySQL 5.5 and above already have re-entrant code in libmysqlclient (no _r).
if ver >= 5.5 || libs.empty?
libs = `#{mc} --libs`.chomp
end
exit 1 if $? != 0
$INCFLAGS += ' ' + includes
$libs = libs + " " + $libs
rpath_dir = libs
else
inc, lib = dir_config('mysql', '/usr/local')
libs = ['m', 'z', 'socket', 'nsl', 'mygcc']
while not find_library('mysqlclient', 'mysql_query', lib, "#{lib}/mysql") do
exit 1 if libs.empty?
have_library(libs.shift)
end
rpath_dir = lib
end
if RUBY_PLATFORM =~ /mswin|mingw/
exit 1 unless have_library('libmysql')
end
if have_header('mysql.h')
prefix = nil
elsif have_header('mysql/mysql.h')
prefix = 'mysql'
else
asplode 'mysql.h'
end
%w{ errmsg.h mysqld_error.h }.each do |h|
header = [prefix, h].compact.join '/'
asplode h unless have_header h
end
# These gcc style flags are also supported by clang and xcode compilers,
# so we'll use a does-it-work test instead of an is-it-gcc test.
gcc_flags = ' -Wall -funroll-loops'
if try_link('int main() {return 0;}', gcc_flags)
$CFLAGS << gcc_flags
end
if libdir = rpath_dir[%r{(-L)?(/[^ ]+)}, 2]
rpath_flags = " -Wl,-rpath,#{libdir}"
if RbConfig::CONFIG["RPATHFLAG"].to_s.empty? && try_link('int main() {return 0;}', rpath_flags)
# Usually Ruby sets RPATHFLAG the right way for each system, but not on OS X.
warn "-----\nSetting rpath to #{libdir}\n-----"
$LDFLAGS << rpath_flags
else
if RbConfig::CONFIG["RPATHFLAG"].to_s.empty?
# If we got here because try_link failed, warn the user
warn "-----\nDon't know how to set rpath on your system, if MySQL libraries are not in path mysql2 may not load\n-----"
end
# Make sure that LIBPATH gets set if we didn't explicitly set the rpath.
warn "-----\nSetting libpath to #{libdir}\n-----"
$LIBPATH << libdir unless $LIBPATH.include?(libdir)
end
end
create_makefile('mysql2/mysql2')
|
module ActionController
# This module provides a method which will redirects browser to use HTTPS
# protocol. This will ensure that user's sensitive information will be
# transferred safely over the internet. You _should_ always force browser
# to use HTTPS when you're transferring sensitive information such as
# user authentication, account information, or credit card information.
#
# Note that if you really concern about your application safety, you might
# consider using +config.force_ssl+ in your configuration config file instead.
# That will ensure all the data transferred via HTTPS protocol and prevent
# user from getting session hijacked when accessing the site under unsecured
# HTTP protocol.
module ForceSSL
extend ActiveSupport::Concern
include AbstractController::Callbacks
module ClassMethods
# Force the request to this particular controller or specified actions to be
# under HTTPS protocol.
#
# Note that this method will not be effective on development environment.
#
# ==== Options
# * <tt>only</tt> - The callback should be run only for this action
# * <tt>except<tt> - The callback should be run for all actions except this action
def force_ssl(options = {})
before_filter(options) do
if !request.ssl? && !Rails.env.development?
redirect_to :protocol => 'https://', :status => :moved_permanently
end
end
end
end
end
end
fix minor spelling mistakes in comments
module ActionController
# This module provides a method which will redirect browser to use HTTPS
# protocol. This will ensure that user's sensitive information will be
# transferred safely over the internet. You _should_ always force browser
# to use HTTPS when you're transferring sensitive information such as
# user authentication, account information, or credit card information.
#
# Note that if you are really concerned about your application security,
# you might consider using +config.force_ssl+ in your config file instead.
# That will ensure all the data transferred via HTTPS protocol and prevent
# user from getting session hijacked when accessing the site under unsecured
# HTTP protocol.
module ForceSSL
extend ActiveSupport::Concern
include AbstractController::Callbacks
module ClassMethods
# Force the request to this particular controller or specified actions to be
# under HTTPS protocol.
#
# Note that this method will not be effective on development environment.
#
# ==== Options
# * <tt>only</tt> - The callback should be run only for this action
# * <tt>except<tt> - The callback should be run for all actions except this action
def force_ssl(options = {})
before_filter(options) do
if !request.ssl? && !Rails.env.development?
redirect_to :protocol => 'https://', :status => :moved_permanently
end
end
end
end
end
end |
require 'delegate'
require 'active_support/core_ext/string/strip'
module ActionDispatch
module Routing
class RouteWrapper < SimpleDelegator
def endpoint
app.dispatcher? ? "#{controller}##{action}" : rack_app.inspect
end
def constraints
requirements.except(:controller, :action)
end
def rack_app
app.app
end
def path
super.spec.to_s
end
def name
super.to_s
end
def reqs
@reqs ||= begin
reqs = endpoint
reqs += " #{constraints}" unless constraints.empty?
reqs
end
end
def controller
requirements[:controller] || ':controller'
end
def action
requirements[:action] || ':action'
end
def internal?
controller.to_s =~ %r{\Arails/(info|mailers|welcome)}
end
def engine?
rack_app.respond_to?(:routes)
end
end
##
# This class is just used for displaying route information when someone
# executes `rake routes` or looks at the RoutingError page.
# People should not use this class.
class RoutesInspector # :nodoc:
def initialize(routes)
@engines = {}
@routes = routes
end
def format(formatter, filter = nil)
filter_options = normalize_filter(filter)
routes_to_display = filter_routes(filter_options)
routes = collect_routes(routes_to_display)
if routes.none?
formatter.no_routes(collect_routes(@routes))
return formatter.result
end
formatter.header routes
formatter.section routes
@engines.each do |name, engine_routes|
formatter.section_title "Routes for #{name}"
formatter.section engine_routes
end
formatter.result
end
private
def normalize_filter(filter)
if filter.is_a?(Hash) && filter[:controller]
{controller: /#{filter[:controller].downcase.sub(/_?controller\z/, '').sub('::', '/')}/}
elsif filter.is_a?(String)
{controller: /#{filter}/, action: /#{filter}/}
else
nil
end
end
def filter_routes(filter_options)
if filter_options
@routes.select do |route|
filter_options.any? { |default, filter| route.defaults[default] =~ filter }
end
else
@routes
end
end
def collect_routes(routes)
routes.collect do |route|
RouteWrapper.new(route)
end.reject(&:internal?).collect do |route|
collect_engine_routes(route)
{ name: route.name,
verb: route.verb,
path: route.path,
reqs: route.reqs }
end
end
def collect_engine_routes(route)
name = route.endpoint
return unless route.engine?
return if @engines[name]
routes = route.rack_app.routes
if routes.is_a?(ActionDispatch::Routing::RouteSet)
@engines[name] = collect_routes(routes.routes)
end
end
end
class ConsoleFormatter
def initialize
@buffer = []
end
def result
@buffer.join("\n")
end
def section_title(title)
@buffer << "\n#{title}:"
end
def section(routes)
@buffer << draw_section(routes)
end
def header(routes)
@buffer << draw_header(routes)
end
def no_routes(routes)
@buffer <<
if routes.none?
<<-MESSAGE.strip_heredoc
You don't have any routes defined!
Please add some routes in config/routes.rb.
MESSAGE
else
"No routes were found for this controller"
end
@buffer << "For more information about routes, see the Rails guide: http://guides.rubyonrails.org/routing.html."
end
private
def draw_section(routes)
header_lengths = ['Prefix', 'Verb', 'URI Pattern'].map(&:length)
name_width, verb_width, path_width = widths(routes).zip(header_lengths).map(&:max)
routes.map do |r|
"#{r[:name].rjust(name_width)} #{r[:verb].ljust(verb_width)} #{r[:path].ljust(path_width)} #{r[:reqs]}"
end
end
def draw_header(routes)
name_width, verb_width, path_width = widths(routes)
"#{"Prefix".rjust(name_width)} #{"Verb".ljust(verb_width)} #{"URI Pattern".ljust(path_width)} Controller#Action"
end
def widths(routes)
[routes.map { |r| r[:name].length }.max || 0,
routes.map { |r| r[:verb].length }.max || 0,
routes.map { |r| r[:path].length }.max || 0]
end
end
class HtmlTableFormatter
def initialize(view)
@view = view
@buffer = []
end
def section_title(title)
@buffer << %(<tr><th colspan="4">#{title}</th></tr>)
end
def section(routes)
@buffer << @view.render(partial: "routes/route", collection: routes)
end
# the header is part of the HTML page, so we don't construct it here.
def header(routes)
end
def no_routes(*)
@buffer << <<-MESSAGE.strip_heredoc
<p>You don't have any routes defined!</p>
<ul>
<li>Please add some routes in <tt>config/routes.rb</tt>.</li>
<li>
For more information about routes, please see the Rails guide
<a href="http://guides.rubyonrails.org/routing.html">Rails Routing from the Outside In</a>.
</li>
</ul>
MESSAGE
end
def result
@view.raw @view.render(layout: "routes/table") {
@view.raw @buffer.join("\n")
}
end
end
end
end
Simplify filter normalization.
Assume the filter is a string, if it wasn't a hash and isn't nil. Remove needless else
and rely on Ruby's default nil return.
Add spaces within hash braces.
require 'delegate'
require 'active_support/core_ext/string/strip'
module ActionDispatch
module Routing
class RouteWrapper < SimpleDelegator
def endpoint
app.dispatcher? ? "#{controller}##{action}" : rack_app.inspect
end
def constraints
requirements.except(:controller, :action)
end
def rack_app
app.app
end
def path
super.spec.to_s
end
def name
super.to_s
end
def reqs
@reqs ||= begin
reqs = endpoint
reqs += " #{constraints}" unless constraints.empty?
reqs
end
end
def controller
requirements[:controller] || ':controller'
end
def action
requirements[:action] || ':action'
end
def internal?
controller.to_s =~ %r{\Arails/(info|mailers|welcome)}
end
def engine?
rack_app.respond_to?(:routes)
end
end
##
# This class is just used for displaying route information when someone
# executes `rake routes` or looks at the RoutingError page.
# People should not use this class.
class RoutesInspector # :nodoc:
def initialize(routes)
@engines = {}
@routes = routes
end
def format(formatter, filter = nil)
filter_options = normalize_filter(filter)
routes_to_display = filter_routes(filter_options)
routes = collect_routes(routes_to_display)
if routes.none?
formatter.no_routes(collect_routes(@routes))
return formatter.result
end
formatter.header routes
formatter.section routes
@engines.each do |name, engine_routes|
formatter.section_title "Routes for #{name}"
formatter.section engine_routes
end
formatter.result
end
private
def normalize_filter(filter)
if filter.is_a?(Hash) && filter[:controller]
{ controller: /#{filter[:controller].downcase.sub(/_?controller\z/, '').sub('::', '/')}/ }
elsif filter
{ controller: /#{filter}/, action: /#{filter}/ }
end
end
def filter_routes(filter_options)
if filter_options
@routes.select do |route|
filter_options.any? { |default, filter| route.defaults[default] =~ filter }
end
else
@routes
end
end
def collect_routes(routes)
routes.collect do |route|
RouteWrapper.new(route)
end.reject(&:internal?).collect do |route|
collect_engine_routes(route)
{ name: route.name,
verb: route.verb,
path: route.path,
reqs: route.reqs }
end
end
def collect_engine_routes(route)
name = route.endpoint
return unless route.engine?
return if @engines[name]
routes = route.rack_app.routes
if routes.is_a?(ActionDispatch::Routing::RouteSet)
@engines[name] = collect_routes(routes.routes)
end
end
end
class ConsoleFormatter
def initialize
@buffer = []
end
def result
@buffer.join("\n")
end
def section_title(title)
@buffer << "\n#{title}:"
end
def section(routes)
@buffer << draw_section(routes)
end
def header(routes)
@buffer << draw_header(routes)
end
def no_routes(routes)
@buffer <<
if routes.none?
<<-MESSAGE.strip_heredoc
You don't have any routes defined!
Please add some routes in config/routes.rb.
MESSAGE
else
"No routes were found for this controller"
end
@buffer << "For more information about routes, see the Rails guide: http://guides.rubyonrails.org/routing.html."
end
private
def draw_section(routes)
header_lengths = ['Prefix', 'Verb', 'URI Pattern'].map(&:length)
name_width, verb_width, path_width = widths(routes).zip(header_lengths).map(&:max)
routes.map do |r|
"#{r[:name].rjust(name_width)} #{r[:verb].ljust(verb_width)} #{r[:path].ljust(path_width)} #{r[:reqs]}"
end
end
def draw_header(routes)
name_width, verb_width, path_width = widths(routes)
"#{"Prefix".rjust(name_width)} #{"Verb".ljust(verb_width)} #{"URI Pattern".ljust(path_width)} Controller#Action"
end
def widths(routes)
[routes.map { |r| r[:name].length }.max || 0,
routes.map { |r| r[:verb].length }.max || 0,
routes.map { |r| r[:path].length }.max || 0]
end
end
class HtmlTableFormatter
def initialize(view)
@view = view
@buffer = []
end
def section_title(title)
@buffer << %(<tr><th colspan="4">#{title}</th></tr>)
end
def section(routes)
@buffer << @view.render(partial: "routes/route", collection: routes)
end
# the header is part of the HTML page, so we don't construct it here.
def header(routes)
end
def no_routes(*)
@buffer << <<-MESSAGE.strip_heredoc
<p>You don't have any routes defined!</p>
<ul>
<li>Please add some routes in <tt>config/routes.rb</tt>.</li>
<li>
For more information about routes, please see the Rails guide
<a href="http://guides.rubyonrails.org/routing.html">Rails Routing from the Outside In</a>.
</li>
</ul>
MESSAGE
end
def result
@view.raw @view.render(layout: "routes/table") {
@view.raw @buffer.join("\n")
}
end
end
end
end
|
require 'action_dispatch/journey'
require 'forwardable'
require 'thread_safe'
require 'active_support/core_ext/object/to_query'
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/module/remove_method'
require 'active_support/core_ext/array/extract_options'
require 'action_controller/metal/exceptions'
module ActionDispatch
module Routing
class RouteSet #:nodoc:
# Since the router holds references to many parts of the system
# like engines, controllers and the application itself, inspecting
# the route set can actually be really slow, therefore we default
# alias inspect to to_s.
alias inspect to_s
PARAMETERS_KEY = 'action_dispatch.request.path_parameters'
class Dispatcher #:nodoc:
def initialize(options={})
@defaults = options[:defaults]
@glob_param = options.delete(:glob)
@controller_class_names = ThreadSafe::Cache.new
end
def call(env)
params = env[PARAMETERS_KEY]
# If any of the path parameters has a invalid encoding then
# raise since it's likely to trigger errors further on.
params.each do |key, value|
next unless value.respond_to?(:valid_encoding?)
unless value.valid_encoding?
raise ActionController::BadRequest, "Invalid parameter: #{key} => #{value}"
end
end
prepare_params!(params)
# Just raise undefined constant errors if a controller was specified as default.
unless controller = controller(params, @defaults.key?(:controller))
return [404, {'X-Cascade' => 'pass'}, []]
end
dispatch(controller, params[:action], env)
end
def prepare_params!(params)
normalize_controller!(params)
merge_default_action!(params)
split_glob_param!(params) if @glob_param
end
# If this is a default_controller (i.e. a controller specified by the user)
# we should raise an error in case it's not found, because it usually means
# a user error. However, if the controller was retrieved through a dynamic
# segment, as in :controller(/:action), we should simply return nil and
# delegate the control back to Rack cascade. Besides, if this is not a default
# controller, it means we should respect the @scope[:module] parameter.
def controller(params, default_controller=true)
if params && params.key?(:controller)
controller_param = params[:controller]
controller_reference(controller_param)
end
rescue NameError => e
raise ActionController::RoutingError, e.message, e.backtrace if default_controller
end
private
def controller_reference(controller_param)
const_name = @controller_class_names[controller_param] ||= "#{controller_param.camelize}Controller"
ActiveSupport::Dependencies.constantize(const_name)
end
def dispatch(controller, action, env)
controller.action(action).call(env)
end
def normalize_controller!(params)
params[:controller] = params[:controller].underscore if params.key?(:controller)
end
def merge_default_action!(params)
params[:action] ||= 'index'
end
def split_glob_param!(params)
params[@glob_param] = params[@glob_param].split('/').map { |v| URI.parser.unescape(v) }
end
end
# A NamedRouteCollection instance is a collection of named routes, and also
# maintains an anonymous module that can be used to install helpers for the
# named routes.
class NamedRouteCollection #:nodoc:
include Enumerable
attr_reader :routes, :helpers, :module
def initialize
@routes = {}
@helpers = []
@module = Module.new
end
def helper_names
@helpers.map(&:to_s)
end
def clear!
@helpers.each do |helper|
@module.remove_possible_method helper
end
@routes.clear
@helpers.clear
end
def add(name, route)
routes[name.to_sym] = route
define_named_route_methods(name, route)
end
def get(name)
routes[name.to_sym]
end
alias []= add
alias [] get
alias clear clear!
def each
routes.each { |name, route| yield name, route }
self
end
def names
routes.keys
end
def length
routes.length
end
class UrlHelper # :nodoc:
def self.create(route, options)
if optimize_helper?(route)
OptimizedUrlHelper.new(route, options)
else
new route, options
end
end
def self.optimize_helper?(route)
route.requirements.except(:controller, :action).empty?
end
class OptimizedUrlHelper < UrlHelper # :nodoc:
attr_reader :arg_size
def initialize(route, options)
super
@path_parts = @route.required_parts
@arg_size = @path_parts.size
@string_route = @route.optimized_path
end
def call(t, args)
if args.size == arg_size && !args.last.is_a?(Hash) && optimize_routes_generation?(t)
options = @options.dup
options.merge!(t.url_options) if t.respond_to?(:url_options)
options[:path] = optimized_helper(args)
ActionDispatch::Http::URL.url_for(options)
else
super
end
end
private
def optimized_helper(args)
path = @string_route.dup
klass = Journey::Router::Utils
@path_parts.zip(args) do |part, arg|
parameterized_arg = arg.to_param
if parameterized_arg.nil? || parameterized_arg.empty?
raise_generation_error(args)
end
# Replace each route parameter
# e.g. :id for regular parameter or *path for globbing
# with ruby string interpolation code
path.gsub!(/(\*|:)#{part}/, klass.escape_fragment(parameterized_arg))
end
path
end
def optimize_routes_generation?(t)
t.send(:optimize_routes_generation?)
end
def raise_generation_error(args)
parts, missing_keys = [], []
@path_parts.zip(args) do |part, arg|
parameterized_arg = arg.to_param
if parameterized_arg.nil? || parameterized_arg.empty?
missing_keys << part
end
parts << [part, arg]
end
message = "No route matches #{Hash[parts].inspect}"
message << " missing required keys: #{missing_keys.inspect}"
raise ActionController::UrlGenerationError, message
end
end
def initialize(route, options)
@options = options
@segment_keys = route.segment_keys
@route = route
end
def call(t, args)
t.url_for(handle_positional_args(t, args, @options, @segment_keys))
end
def handle_positional_args(t, args, options, keys)
inner_options = args.extract_options!
result = options.dup
if args.size > 0
if args.size < keys.size - 1 # take format into account
keys -= t.url_options.keys if t.respond_to?(:url_options)
keys -= options.keys
end
keys -= inner_options.keys
result.merge!(Hash[keys.zip(args)])
end
result.merge!(inner_options)
end
end
private
# Create a url helper allowing ordered parameters to be associated
# with corresponding dynamic segments, so you can do:
#
# foo_url(bar, baz, bang)
#
# Instead of:
#
# foo_url(bar: bar, baz: baz, bang: bang)
#
# Also allow options hash, so you can do:
#
# foo_url(bar, baz, bang, sort_by: 'baz')
#
def define_url_helper(route, name, options)
helper = UrlHelper.create(route, options.dup)
@module.remove_possible_method name
@module.module_eval do
define_method(name) do |*args|
helper.call self, args
end
end
helpers << name
end
def define_named_route_methods(name, route)
define_url_helper route, :"#{name}_path",
route.defaults.merge(:use_route => name, :only_path => true)
define_url_helper route, :"#{name}_url",
route.defaults.merge(:use_route => name, :only_path => false)
end
end
attr_accessor :formatter, :set, :named_routes, :default_scope, :router
attr_accessor :disable_clear_and_finalize, :resources_path_names
attr_accessor :default_url_options, :request_class
alias :routes :set
def self.default_resources_path_names
{ :new => 'new', :edit => 'edit' }
end
def initialize(request_class = ActionDispatch::Request)
self.named_routes = NamedRouteCollection.new
self.resources_path_names = self.class.default_resources_path_names.dup
self.default_url_options = {}
self.request_class = request_class
@append = []
@prepend = []
@disable_clear_and_finalize = false
@finalized = false
@set = Journey::Routes.new
@router = Journey::Router.new(@set, {
:parameters_key => PARAMETERS_KEY,
:request_class => request_class})
@formatter = Journey::Formatter.new @set
end
def draw(&block)
clear! unless @disable_clear_and_finalize
eval_block(block)
finalize! unless @disable_clear_and_finalize
nil
end
def append(&block)
@append << block
end
def prepend(&block)
@prepend << block
end
def eval_block(block)
if block.arity == 1
raise "You are using the old router DSL which has been removed in Rails 3.1. " <<
"Please check how to update your routes file at: http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/"
end
mapper = Mapper.new(self)
if default_scope
mapper.with_default_scope(default_scope, &block)
else
mapper.instance_exec(&block)
end
end
def finalize!
return if @finalized
@append.each { |blk| eval_block(blk) }
@finalized = true
end
def clear!
@finalized = false
named_routes.clear
set.clear
formatter.clear
@prepend.each { |blk| eval_block(blk) }
end
module MountedHelpers #:nodoc:
extend ActiveSupport::Concern
include UrlFor
end
# Contains all the mounted helpers accross different
# engines and the `main_app` helper for the application.
# You can include this in your classes if you want to
# access routes for other engines.
def mounted_helpers
MountedHelpers
end
def define_mounted_helper(name)
return if MountedHelpers.method_defined?(name)
routes = self
MountedHelpers.class_eval do
define_method "_#{name}" do
RoutesProxy.new(routes, _routes_context)
end
end
MountedHelpers.class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
def #{name}
@_#{name} ||= _#{name}
end
RUBY
end
def url_helpers
@url_helpers ||= begin
routes = self
Module.new do
extend ActiveSupport::Concern
include UrlFor
# Define url_for in the singleton level so one can do:
# Rails.application.routes.url_helpers.url_for(args)
@_routes = routes
class << self
delegate :url_for, :optimize_routes_generation?, :to => '@_routes'
end
# Make named_routes available in the module singleton
# as well, so one can do:
# Rails.application.routes.url_helpers.posts_path
extend routes.named_routes.module
# Any class that includes this module will get all
# named routes...
include routes.named_routes.module
# plus a singleton class method called _routes ...
included do
singleton_class.send(:redefine_method, :_routes) { routes }
end
# And an instance method _routes. Note that
# UrlFor (included in this module) add extra
# conveniences for working with @_routes.
define_method(:_routes) { @_routes || routes }
end
end
end
def empty?
routes.empty?
end
def add_route(app, conditions = {}, requirements = {}, defaults = {}, name = nil, anchor = true)
raise ArgumentError, "Invalid route name: '#{name}'" unless name.blank? || name.to_s.match(/^[_a-z]\w*$/i)
if name && named_routes[name]
raise ArgumentError, "Invalid route name, already in use: '#{name}' \n" \
"You may have defined two routes with the same name using the `:as` option, or " \
"you may be overriding a route already defined by a resource with the same naming. " \
"For the latter, you can restrict the routes created with `resources` as explained here: \n" \
"http://guides.rubyonrails.org/routing.html#restricting-the-routes-created"
end
path = build_path(conditions.delete(:path_info), requirements, SEPARATORS, anchor)
conditions = build_conditions(conditions, path.names.map { |x| x.to_sym })
route = @set.add_route(app, path, conditions, defaults, name)
named_routes[name] = route if name
route
end
def build_path(path, requirements, separators, anchor)
strexp = Journey::Router::Strexp.new(
path,
requirements,
SEPARATORS,
anchor)
pattern = Journey::Path::Pattern.new(strexp)
builder = Journey::GTG::Builder.new pattern.spec
# Get all the symbol nodes followed by literals that are not the
# dummy node.
symbols = pattern.spec.grep(Journey::Nodes::Symbol).find_all { |n|
builder.followpos(n).first.literal?
}
# Get all the symbol nodes preceded by literals.
symbols.concat pattern.spec.find_all(&:literal?).map { |n|
builder.followpos(n).first
}.find_all(&:symbol?)
symbols.each { |x|
x.regexp = /(?:#{Regexp.union(x.regexp, '-')})+/
}
pattern
end
private :build_path
def build_conditions(current_conditions, path_values)
conditions = current_conditions.dup
# Rack-Mount requires that :request_method be a regular expression.
# :request_method represents the HTTP verb that matches this route.
#
# Here we munge values before they get sent on to rack-mount.
verbs = conditions[:request_method] || []
unless verbs.empty?
conditions[:request_method] = %r[^#{verbs.join('|')}$]
end
conditions.keep_if do |k, _|
k == :action || k == :controller || k == :required_defaults ||
@request_class.public_method_defined?(k) || path_values.include?(k)
end
end
private :build_conditions
class Generator #:nodoc:
PARAMETERIZE = lambda do |name, value|
if name == :controller
value
elsif value.is_a?(Array)
value.map { |v| v.to_param }.join('/')
elsif param = value.to_param
param
end
end
attr_reader :options, :recall, :set, :named_route
def initialize(options, recall, set)
@named_route = options.delete(:use_route)
@options = options.dup
@recall = recall.dup
@set = set
normalize_options!
normalize_controller_action_id!
use_relative_controller!
normalize_controller!
handle_nil_action!
end
def controller
@options[:controller]
end
def current_controller
@recall[:controller]
end
def use_recall_for(key)
if @recall[key] && (!@options.key?(key) || @options[key] == @recall[key])
if !named_route_exists? || segment_keys.include?(key)
@options[key] = @recall.delete(key)
end
end
end
def normalize_options!
# If an explicit :controller was given, always make :action explicit
# too, so that action expiry works as expected for things like
#
# generate({controller: 'content'}, {controller: 'content', action: 'show'})
#
# (the above is from the unit tests). In the above case, because the
# controller was explicitly given, but no action, the action is implied to
# be "index", not the recalled action of "show".
if options[:controller]
options[:action] ||= 'index'
options[:controller] = options[:controller].to_s
end
if options[:action]
options[:action] = options[:action].to_s
end
end
# This pulls :controller, :action, and :id out of the recall.
# The recall key is only used if there is no key in the options
# or if the key in the options is identical. If any of
# :controller, :action or :id is not found, don't pull any
# more keys from the recall.
def normalize_controller_action_id!
@recall[:action] ||= 'index' if current_controller
use_recall_for(:controller) or return
use_recall_for(:action) or return
use_recall_for(:id)
end
# if the current controller is "foo/bar/baz" and controller: "baz/bat"
# is specified, the controller becomes "foo/baz/bat"
def use_relative_controller!
if !named_route && different_controller? && !controller.start_with?("/")
old_parts = current_controller.split('/')
size = controller.count("/") + 1
parts = old_parts[0...-size] << controller
@options[:controller] = parts.join("/")
end
end
# Remove leading slashes from controllers
def normalize_controller!
@options[:controller] = controller.sub(%r{^/}, '') if controller
end
# This handles the case of action: nil being explicitly passed.
# It is identical to action: "index"
def handle_nil_action!
if options.has_key?(:action) && options[:action].nil?
options[:action] = 'index'
end
recall[:action] = options.delete(:action) if options[:action] == 'index'
end
# Generates a path from routes, returns [path, params].
# If no route is generated the formatter will raise ActionController::UrlGenerationError
def generate
@set.formatter.generate(:path_info, named_route, options, recall, PARAMETERIZE)
end
def different_controller?
return false unless current_controller
controller.to_param != current_controller.to_param
end
private
def named_route_exists?
named_route && set.named_routes[named_route]
end
def segment_keys
set.named_routes[named_route].segment_keys
end
end
# Generate the path indicated by the arguments, and return an array of
# the keys that were not used to generate it.
def extra_keys(options, recall={})
generate_extras(options, recall).last
end
def generate_extras(options, recall={})
path, params = generate(options, recall)
return path, params.keys
end
def generate(options, recall = {})
Generator.new(options, recall, self).generate
end
RESERVED_OPTIONS = [:host, :protocol, :port, :subdomain, :domain, :tld_length,
:trailing_slash, :anchor, :params, :only_path, :script_name,
:original_script_name]
def mounted?
false
end
def optimize_routes_generation?
!mounted? && default_url_options.empty?
end
def _generate_prefix(options = {})
nil
end
# The +options+ argument must be +nil+ or a hash whose keys are *symbols*.
def url_for(options)
options = default_url_options.merge(options || {})
user, password = extract_authentication(options)
recall = options.delete(:_recall)
original_script_name = options.delete(:original_script_name).presence
script_name = options.delete(:script_name).presence || _generate_prefix(options)
if script_name && original_script_name
script_name = original_script_name + script_name
end
path_options = options.except(*RESERVED_OPTIONS)
path_options = yield(path_options) if block_given?
path, params = generate(path_options, recall || {})
params.merge!(options[:params] || {})
ActionDispatch::Http::URL.url_for(options.merge!({
:path => path,
:script_name => script_name,
:params => params,
:user => user,
:password => password
}))
end
def call(env)
@router.call(env)
end
def recognize_path(path, environment = {})
method = (environment[:method] || "GET").to_s.upcase
path = Journey::Router::Utils.normalize_path(path) unless path =~ %r{://}
extras = environment[:extras] || {}
begin
env = Rack::MockRequest.env_for(path, {:method => method})
rescue URI::InvalidURIError => e
raise ActionController::RoutingError, e.message
end
req = @request_class.new(env)
@router.recognize(req) do |route, _matches, params|
params.merge!(extras)
params.each do |key, value|
if value.is_a?(String)
value = value.dup.force_encoding(Encoding::BINARY)
params[key] = URI.parser.unescape(value)
end
end
old_params = env[::ActionDispatch::Routing::RouteSet::PARAMETERS_KEY]
env[::ActionDispatch::Routing::RouteSet::PARAMETERS_KEY] = (old_params || {}).merge(params)
dispatcher = route.app
while dispatcher.is_a?(Mapper::Constraints) && dispatcher.matches?(env) do
dispatcher = dispatcher.app
end
if dispatcher.is_a?(Dispatcher)
if dispatcher.controller(params, false)
dispatcher.prepare_params!(params)
return params
else
raise ActionController::RoutingError, "A route matches #{path.inspect}, but references missing controller: #{params[:controller].camelize}Controller"
end
end
end
raise ActionController::RoutingError, "No route matches #{path.inspect}"
end
private
def extract_authentication(options)
if options[:user] && options[:password]
[options.delete(:user), options.delete(:password)]
else
nil
end
end
end
end
end
Refactor handling of action normalization
Reference:
Bloody mess internals
http://gusiev.com/slides/rails_contribution/static/#40
require 'action_dispatch/journey'
require 'forwardable'
require 'thread_safe'
require 'active_support/core_ext/object/to_query'
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/module/remove_method'
require 'active_support/core_ext/array/extract_options'
require 'action_controller/metal/exceptions'
module ActionDispatch
module Routing
class RouteSet #:nodoc:
# Since the router holds references to many parts of the system
# like engines, controllers and the application itself, inspecting
# the route set can actually be really slow, therefore we default
# alias inspect to to_s.
alias inspect to_s
PARAMETERS_KEY = 'action_dispatch.request.path_parameters'
class Dispatcher #:nodoc:
def initialize(options={})
@defaults = options[:defaults]
@glob_param = options.delete(:glob)
@controller_class_names = ThreadSafe::Cache.new
end
def call(env)
params = env[PARAMETERS_KEY]
# If any of the path parameters has a invalid encoding then
# raise since it's likely to trigger errors further on.
params.each do |key, value|
next unless value.respond_to?(:valid_encoding?)
unless value.valid_encoding?
raise ActionController::BadRequest, "Invalid parameter: #{key} => #{value}"
end
end
prepare_params!(params)
# Just raise undefined constant errors if a controller was specified as default.
unless controller = controller(params, @defaults.key?(:controller))
return [404, {'X-Cascade' => 'pass'}, []]
end
dispatch(controller, params[:action], env)
end
def prepare_params!(params)
normalize_controller!(params)
merge_default_action!(params)
split_glob_param!(params) if @glob_param
end
# If this is a default_controller (i.e. a controller specified by the user)
# we should raise an error in case it's not found, because it usually means
# a user error. However, if the controller was retrieved through a dynamic
# segment, as in :controller(/:action), we should simply return nil and
# delegate the control back to Rack cascade. Besides, if this is not a default
# controller, it means we should respect the @scope[:module] parameter.
def controller(params, default_controller=true)
if params && params.key?(:controller)
controller_param = params[:controller]
controller_reference(controller_param)
end
rescue NameError => e
raise ActionController::RoutingError, e.message, e.backtrace if default_controller
end
private
def controller_reference(controller_param)
const_name = @controller_class_names[controller_param] ||= "#{controller_param.camelize}Controller"
ActiveSupport::Dependencies.constantize(const_name)
end
def dispatch(controller, action, env)
controller.action(action).call(env)
end
def normalize_controller!(params)
params[:controller] = params[:controller].underscore if params.key?(:controller)
end
def merge_default_action!(params)
params[:action] ||= 'index'
end
def split_glob_param!(params)
params[@glob_param] = params[@glob_param].split('/').map { |v| URI.parser.unescape(v) }
end
end
# A NamedRouteCollection instance is a collection of named routes, and also
# maintains an anonymous module that can be used to install helpers for the
# named routes.
class NamedRouteCollection #:nodoc:
include Enumerable
attr_reader :routes, :helpers, :module
def initialize
@routes = {}
@helpers = []
@module = Module.new
end
def helper_names
@helpers.map(&:to_s)
end
def clear!
@helpers.each do |helper|
@module.remove_possible_method helper
end
@routes.clear
@helpers.clear
end
def add(name, route)
routes[name.to_sym] = route
define_named_route_methods(name, route)
end
def get(name)
routes[name.to_sym]
end
alias []= add
alias [] get
alias clear clear!
def each
routes.each { |name, route| yield name, route }
self
end
def names
routes.keys
end
def length
routes.length
end
class UrlHelper # :nodoc:
def self.create(route, options)
if optimize_helper?(route)
OptimizedUrlHelper.new(route, options)
else
new route, options
end
end
def self.optimize_helper?(route)
route.requirements.except(:controller, :action).empty?
end
class OptimizedUrlHelper < UrlHelper # :nodoc:
attr_reader :arg_size
def initialize(route, options)
super
@path_parts = @route.required_parts
@arg_size = @path_parts.size
@string_route = @route.optimized_path
end
def call(t, args)
if args.size == arg_size && !args.last.is_a?(Hash) && optimize_routes_generation?(t)
options = @options.dup
options.merge!(t.url_options) if t.respond_to?(:url_options)
options[:path] = optimized_helper(args)
ActionDispatch::Http::URL.url_for(options)
else
super
end
end
private
def optimized_helper(args)
path = @string_route.dup
klass = Journey::Router::Utils
@path_parts.zip(args) do |part, arg|
parameterized_arg = arg.to_param
if parameterized_arg.nil? || parameterized_arg.empty?
raise_generation_error(args)
end
# Replace each route parameter
# e.g. :id for regular parameter or *path for globbing
# with ruby string interpolation code
path.gsub!(/(\*|:)#{part}/, klass.escape_fragment(parameterized_arg))
end
path
end
def optimize_routes_generation?(t)
t.send(:optimize_routes_generation?)
end
def raise_generation_error(args)
parts, missing_keys = [], []
@path_parts.zip(args) do |part, arg|
parameterized_arg = arg.to_param
if parameterized_arg.nil? || parameterized_arg.empty?
missing_keys << part
end
parts << [part, arg]
end
message = "No route matches #{Hash[parts].inspect}"
message << " missing required keys: #{missing_keys.inspect}"
raise ActionController::UrlGenerationError, message
end
end
def initialize(route, options)
@options = options
@segment_keys = route.segment_keys
@route = route
end
def call(t, args)
t.url_for(handle_positional_args(t, args, @options, @segment_keys))
end
def handle_positional_args(t, args, options, keys)
inner_options = args.extract_options!
result = options.dup
if args.size > 0
if args.size < keys.size - 1 # take format into account
keys -= t.url_options.keys if t.respond_to?(:url_options)
keys -= options.keys
end
keys -= inner_options.keys
result.merge!(Hash[keys.zip(args)])
end
result.merge!(inner_options)
end
end
private
# Create a url helper allowing ordered parameters to be associated
# with corresponding dynamic segments, so you can do:
#
# foo_url(bar, baz, bang)
#
# Instead of:
#
# foo_url(bar: bar, baz: baz, bang: bang)
#
# Also allow options hash, so you can do:
#
# foo_url(bar, baz, bang, sort_by: 'baz')
#
def define_url_helper(route, name, options)
helper = UrlHelper.create(route, options.dup)
@module.remove_possible_method name
@module.module_eval do
define_method(name) do |*args|
helper.call self, args
end
end
helpers << name
end
def define_named_route_methods(name, route)
define_url_helper route, :"#{name}_path",
route.defaults.merge(:use_route => name, :only_path => true)
define_url_helper route, :"#{name}_url",
route.defaults.merge(:use_route => name, :only_path => false)
end
end
attr_accessor :formatter, :set, :named_routes, :default_scope, :router
attr_accessor :disable_clear_and_finalize, :resources_path_names
attr_accessor :default_url_options, :request_class
alias :routes :set
def self.default_resources_path_names
{ :new => 'new', :edit => 'edit' }
end
def initialize(request_class = ActionDispatch::Request)
self.named_routes = NamedRouteCollection.new
self.resources_path_names = self.class.default_resources_path_names.dup
self.default_url_options = {}
self.request_class = request_class
@append = []
@prepend = []
@disable_clear_and_finalize = false
@finalized = false
@set = Journey::Routes.new
@router = Journey::Router.new(@set, {
:parameters_key => PARAMETERS_KEY,
:request_class => request_class})
@formatter = Journey::Formatter.new @set
end
def draw(&block)
clear! unless @disable_clear_and_finalize
eval_block(block)
finalize! unless @disable_clear_and_finalize
nil
end
def append(&block)
@append << block
end
def prepend(&block)
@prepend << block
end
def eval_block(block)
if block.arity == 1
raise "You are using the old router DSL which has been removed in Rails 3.1. " <<
"Please check how to update your routes file at: http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/"
end
mapper = Mapper.new(self)
if default_scope
mapper.with_default_scope(default_scope, &block)
else
mapper.instance_exec(&block)
end
end
def finalize!
return if @finalized
@append.each { |blk| eval_block(blk) }
@finalized = true
end
def clear!
@finalized = false
named_routes.clear
set.clear
formatter.clear
@prepend.each { |blk| eval_block(blk) }
end
module MountedHelpers #:nodoc:
extend ActiveSupport::Concern
include UrlFor
end
# Contains all the mounted helpers accross different
# engines and the `main_app` helper for the application.
# You can include this in your classes if you want to
# access routes for other engines.
def mounted_helpers
MountedHelpers
end
def define_mounted_helper(name)
return if MountedHelpers.method_defined?(name)
routes = self
MountedHelpers.class_eval do
define_method "_#{name}" do
RoutesProxy.new(routes, _routes_context)
end
end
MountedHelpers.class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
def #{name}
@_#{name} ||= _#{name}
end
RUBY
end
def url_helpers
@url_helpers ||= begin
routes = self
Module.new do
extend ActiveSupport::Concern
include UrlFor
# Define url_for in the singleton level so one can do:
# Rails.application.routes.url_helpers.url_for(args)
@_routes = routes
class << self
delegate :url_for, :optimize_routes_generation?, :to => '@_routes'
end
# Make named_routes available in the module singleton
# as well, so one can do:
# Rails.application.routes.url_helpers.posts_path
extend routes.named_routes.module
# Any class that includes this module will get all
# named routes...
include routes.named_routes.module
# plus a singleton class method called _routes ...
included do
singleton_class.send(:redefine_method, :_routes) { routes }
end
# And an instance method _routes. Note that
# UrlFor (included in this module) add extra
# conveniences for working with @_routes.
define_method(:_routes) { @_routes || routes }
end
end
end
def empty?
routes.empty?
end
def add_route(app, conditions = {}, requirements = {}, defaults = {}, name = nil, anchor = true)
raise ArgumentError, "Invalid route name: '#{name}'" unless name.blank? || name.to_s.match(/^[_a-z]\w*$/i)
if name && named_routes[name]
raise ArgumentError, "Invalid route name, already in use: '#{name}' \n" \
"You may have defined two routes with the same name using the `:as` option, or " \
"you may be overriding a route already defined by a resource with the same naming. " \
"For the latter, you can restrict the routes created with `resources` as explained here: \n" \
"http://guides.rubyonrails.org/routing.html#restricting-the-routes-created"
end
path = build_path(conditions.delete(:path_info), requirements, SEPARATORS, anchor)
conditions = build_conditions(conditions, path.names.map { |x| x.to_sym })
route = @set.add_route(app, path, conditions, defaults, name)
named_routes[name] = route if name
route
end
def build_path(path, requirements, separators, anchor)
strexp = Journey::Router::Strexp.new(
path,
requirements,
SEPARATORS,
anchor)
pattern = Journey::Path::Pattern.new(strexp)
builder = Journey::GTG::Builder.new pattern.spec
# Get all the symbol nodes followed by literals that are not the
# dummy node.
symbols = pattern.spec.grep(Journey::Nodes::Symbol).find_all { |n|
builder.followpos(n).first.literal?
}
# Get all the symbol nodes preceded by literals.
symbols.concat pattern.spec.find_all(&:literal?).map { |n|
builder.followpos(n).first
}.find_all(&:symbol?)
symbols.each { |x|
x.regexp = /(?:#{Regexp.union(x.regexp, '-')})+/
}
pattern
end
private :build_path
def build_conditions(current_conditions, path_values)
conditions = current_conditions.dup
# Rack-Mount requires that :request_method be a regular expression.
# :request_method represents the HTTP verb that matches this route.
#
# Here we munge values before they get sent on to rack-mount.
verbs = conditions[:request_method] || []
unless verbs.empty?
conditions[:request_method] = %r[^#{verbs.join('|')}$]
end
conditions.keep_if do |k, _|
k == :action || k == :controller || k == :required_defaults ||
@request_class.public_method_defined?(k) || path_values.include?(k)
end
end
private :build_conditions
class Generator #:nodoc:
PARAMETERIZE = lambda do |name, value|
if name == :controller
value
elsif value.is_a?(Array)
value.map { |v| v.to_param }.join('/')
elsif param = value.to_param
param
end
end
attr_reader :options, :recall, :set, :named_route
def initialize(options, recall, set)
@named_route = options.delete(:use_route)
@options = options.dup
@recall = recall.dup
@set = set
normalize_recall!
normalize_options!
normalize_controller_action_id!
use_relative_controller!
normalize_controller!
normalize_action!
end
def controller
@options[:controller]
end
def current_controller
@recall[:controller]
end
def use_recall_for(key)
if @recall[key] && (!@options.key?(key) || @options[key] == @recall[key])
if !named_route_exists? || segment_keys.include?(key)
@options[key] = @recall.delete(key)
end
end
end
# Set 'index' as default action for recall
def normalize_recall!
@recall[:action] ||= 'index'
end
def normalize_options!
# If an explicit :controller was given, always make :action explicit
# too, so that action expiry works as expected for things like
#
# generate({controller: 'content'}, {controller: 'content', action: 'show'})
#
# (the above is from the unit tests). In the above case, because the
# controller was explicitly given, but no action, the action is implied to
# be "index", not the recalled action of "show".
if options[:controller]
options[:action] ||= 'index'
options[:controller] = options[:controller].to_s
end
if options.key?(:action)
options[:action] = (options[:action] || 'index').to_s
end
end
# This pulls :controller, :action, and :id out of the recall.
# The recall key is only used if there is no key in the options
# or if the key in the options is identical. If any of
# :controller, :action or :id is not found, don't pull any
# more keys from the recall.
def normalize_controller_action_id!
use_recall_for(:controller) or return
use_recall_for(:action) or return
use_recall_for(:id)
end
# if the current controller is "foo/bar/baz" and controller: "baz/bat"
# is specified, the controller becomes "foo/baz/bat"
def use_relative_controller!
if !named_route && different_controller? && !controller.start_with?("/")
old_parts = current_controller.split('/')
size = controller.count("/") + 1
parts = old_parts[0...-size] << controller
@options[:controller] = parts.join("/")
end
end
# Remove leading slashes from controllers
def normalize_controller!
@options[:controller] = controller.sub(%r{^/}, '') if controller
end
# Move 'index' action from options to recall
def normalize_action!
if @options[:action] == 'index'
@recall[:action] = @options.delete(:action)
end
end
# Generates a path from routes, returns [path, params].
# If no route is generated the formatter will raise ActionController::UrlGenerationError
def generate
@set.formatter.generate(:path_info, named_route, options, recall, PARAMETERIZE)
end
def different_controller?
return false unless current_controller
controller.to_param != current_controller.to_param
end
private
def named_route_exists?
named_route && set.named_routes[named_route]
end
def segment_keys
set.named_routes[named_route].segment_keys
end
end
# Generate the path indicated by the arguments, and return an array of
# the keys that were not used to generate it.
def extra_keys(options, recall={})
generate_extras(options, recall).last
end
def generate_extras(options, recall={})
path, params = generate(options, recall)
return path, params.keys
end
def generate(options, recall = {})
Generator.new(options, recall, self).generate
end
RESERVED_OPTIONS = [:host, :protocol, :port, :subdomain, :domain, :tld_length,
:trailing_slash, :anchor, :params, :only_path, :script_name,
:original_script_name]
def mounted?
false
end
def optimize_routes_generation?
!mounted? && default_url_options.empty?
end
def _generate_prefix(options = {})
nil
end
# The +options+ argument must be +nil+ or a hash whose keys are *symbols*.
def url_for(options)
options = default_url_options.merge(options || {})
user, password = extract_authentication(options)
recall = options.delete(:_recall)
original_script_name = options.delete(:original_script_name).presence
script_name = options.delete(:script_name).presence || _generate_prefix(options)
if script_name && original_script_name
script_name = original_script_name + script_name
end
path_options = options.except(*RESERVED_OPTIONS)
path_options = yield(path_options) if block_given?
path, params = generate(path_options, recall || {})
params.merge!(options[:params] || {})
ActionDispatch::Http::URL.url_for(options.merge!({
:path => path,
:script_name => script_name,
:params => params,
:user => user,
:password => password
}))
end
def call(env)
@router.call(env)
end
def recognize_path(path, environment = {})
method = (environment[:method] || "GET").to_s.upcase
path = Journey::Router::Utils.normalize_path(path) unless path =~ %r{://}
extras = environment[:extras] || {}
begin
env = Rack::MockRequest.env_for(path, {:method => method})
rescue URI::InvalidURIError => e
raise ActionController::RoutingError, e.message
end
req = @request_class.new(env)
@router.recognize(req) do |route, _matches, params|
params.merge!(extras)
params.each do |key, value|
if value.is_a?(String)
value = value.dup.force_encoding(Encoding::BINARY)
params[key] = URI.parser.unescape(value)
end
end
old_params = env[::ActionDispatch::Routing::RouteSet::PARAMETERS_KEY]
env[::ActionDispatch::Routing::RouteSet::PARAMETERS_KEY] = (old_params || {}).merge(params)
dispatcher = route.app
while dispatcher.is_a?(Mapper::Constraints) && dispatcher.matches?(env) do
dispatcher = dispatcher.app
end
if dispatcher.is_a?(Dispatcher)
if dispatcher.controller(params, false)
dispatcher.prepare_params!(params)
return params
else
raise ActionController::RoutingError, "A route matches #{path.inspect}, but references missing controller: #{params[:controller].camelize}Controller"
end
end
end
raise ActionController::RoutingError, "No route matches #{path.inspect}"
end
private
def extract_authentication(options)
if options[:user] && options[:password]
[options.delete(:user), options.delete(:password)]
else
nil
end
end
end
end
end
|
require 'action_dispatch/journey'
require 'forwardable'
require 'thread_safe'
require 'active_support/core_ext/object/to_query'
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/module/remove_method'
require 'active_support/core_ext/array/extract_options'
require 'action_controller/metal/exceptions'
module ActionDispatch
module Routing
class RouteSet #:nodoc:
# Since the router holds references to many parts of the system
# like engines, controllers and the application itself, inspecting
# the route set can actually be really slow, therefore we default
# alias inspect to to_s.
alias inspect to_s
PARAMETERS_KEY = 'action_dispatch.request.path_parameters'
class Dispatcher #:nodoc:
def initialize(options={})
@defaults = options[:defaults]
@glob_param = options.delete(:glob)
@controller_class_names = ThreadSafe::Cache.new
end
def call(env)
params = env[PARAMETERS_KEY]
# If any of the path parameters has an invalid encoding then
# raise since it's likely to trigger errors further on.
params.each do |key, value|
next unless value.respond_to?(:valid_encoding?)
unless value.valid_encoding?
raise ActionController::BadRequest, "Invalid parameter: #{key} => #{value}"
end
end
prepare_params!(params)
# Just raise undefined constant errors if a controller was specified as default.
unless controller = controller(params, @defaults.key?(:controller))
return [404, {'X-Cascade' => 'pass'}, []]
end
dispatch(controller, params[:action], env)
end
def prepare_params!(params)
normalize_controller!(params)
merge_default_action!(params)
split_glob_param!(params) if @glob_param
end
# If this is a default_controller (i.e. a controller specified by the user)
# we should raise an error in case it's not found, because it usually means
# a user error. However, if the controller was retrieved through a dynamic
# segment, as in :controller(/:action), we should simply return nil and
# delegate the control back to Rack cascade. Besides, if this is not a default
# controller, it means we should respect the @scope[:module] parameter.
def controller(params, default_controller=true)
if params && params.key?(:controller)
controller_param = params[:controller]
controller_reference(controller_param)
end
rescue NameError => e
raise ActionController::RoutingError, e.message, e.backtrace if default_controller
end
private
def controller_reference(controller_param)
const_name = @controller_class_names[controller_param] ||= "#{controller_param.camelize}Controller"
ActiveSupport::Dependencies.constantize(const_name)
end
def dispatch(controller, action, env)
controller.action(action).call(env)
end
def normalize_controller!(params)
params[:controller] = params[:controller].underscore if params.key?(:controller)
end
def merge_default_action!(params)
params[:action] ||= 'index'
end
def split_glob_param!(params)
params[@glob_param] = params[@glob_param].split('/').map { |v| URI.parser.unescape(v) }
end
end
# A NamedRouteCollection instance is a collection of named routes, and also
# maintains an anonymous module that can be used to install helpers for the
# named routes.
class NamedRouteCollection #:nodoc:
include Enumerable
attr_reader :routes, :helpers, :module
def initialize
@routes = {}
@helpers = []
@module = Module.new
end
def helper_names
@helpers.map(&:to_s)
end
def clear!
@helpers.each do |helper|
@module.remove_possible_method helper
end
@routes.clear
@helpers.clear
end
def add(name, route)
routes[name.to_sym] = route
define_named_route_methods(name, route)
end
def get(name)
routes[name.to_sym]
end
alias []= add
alias [] get
alias clear clear!
def each
routes.each { |name, route| yield name, route }
self
end
def names
routes.keys
end
def length
routes.length
end
class UrlHelper # :nodoc:
def self.create(route, options)
if optimize_helper?(route)
OptimizedUrlHelper.new(route, options)
else
new route, options
end
end
def self.optimize_helper?(route)
!route.glob? && route.requirements.except(:controller, :action, :host).empty?
end
class OptimizedUrlHelper < UrlHelper # :nodoc:
attr_reader :arg_size
def initialize(route, options)
super
@klass = Journey::Router::Utils
@required_parts = @route.required_parts
@arg_size = @required_parts.size
@optimized_path = @route.optimized_path
end
def call(t, args)
if args.size == arg_size && !args.last.is_a?(Hash) && optimize_routes_generation?(t)
options = t.url_options.merge @options
options[:path] = optimized_helper(args)
ActionDispatch::Http::URL.url_for(options)
else
super
end
end
private
def optimized_helper(args)
params = Hash[parameterize_args(args)]
missing_keys = missing_keys(params)
unless missing_keys.empty?
raise_generation_error(params, missing_keys)
end
@optimized_path.map{ |segment| replace_segment(params, segment) }.join
end
def replace_segment(params, segment)
Symbol === segment ? @klass.escape_segment(params[segment]) : segment
end
def optimize_routes_generation?(t)
t.send(:optimize_routes_generation?)
end
def parameterize_args(args)
@required_parts.zip(args.map(&:to_param))
end
def missing_keys(args)
args.select{ |part, arg| arg.nil? || arg.empty? }.keys
end
def raise_generation_error(args, missing_keys)
constraints = Hash[@route.requirements.merge(args).sort]
message = "No route matches #{constraints.inspect}"
message << " missing required keys: #{missing_keys.sort.inspect}"
raise ActionController::UrlGenerationError, message
end
end
def initialize(route, options)
@options = options
@segment_keys = route.segment_keys.uniq
@route = route
end
def call(t, args)
options = t.url_options.merge @options
hash = handle_positional_args(t, args, options, @segment_keys)
t._routes.url_for(hash)
end
def handle_positional_args(t, args, result, keys)
inner_options = args.extract_options!
if args.size > 0
if args.size < keys.size - 1 # take format into account
keys -= t.url_options.keys
keys -= result.keys
end
keys -= inner_options.keys
result.merge!(Hash[keys.zip(args)])
end
result.merge!(inner_options)
end
end
private
# Create a url helper allowing ordered parameters to be associated
# with corresponding dynamic segments, so you can do:
#
# foo_url(bar, baz, bang)
#
# Instead of:
#
# foo_url(bar: bar, baz: baz, bang: bang)
#
# Also allow options hash, so you can do:
#
# foo_url(bar, baz, bang, sort_by: 'baz')
#
def define_url_helper(route, name, options)
helper = UrlHelper.create(route, options.dup)
@module.remove_possible_method name
@module.module_eval do
define_method(name) do |*args|
helper.call self, args
end
end
helpers << name
end
def define_named_route_methods(name, route)
define_url_helper route, :"#{name}_path",
route.defaults.merge(:use_route => name, :only_path => true)
define_url_helper route, :"#{name}_url",
route.defaults.merge(:use_route => name, :only_path => false)
end
end
attr_accessor :formatter, :set, :named_routes, :default_scope, :router
attr_accessor :disable_clear_and_finalize, :resources_path_names
attr_accessor :default_url_options, :request_class
alias :routes :set
def self.default_resources_path_names
{ :new => 'new', :edit => 'edit' }
end
def initialize(request_class = ActionDispatch::Request)
self.named_routes = NamedRouteCollection.new
self.resources_path_names = self.class.default_resources_path_names.dup
self.default_url_options = {}
self.request_class = request_class
@append = []
@prepend = []
@disable_clear_and_finalize = false
@finalized = false
@set = Journey::Routes.new
@router = Journey::Router.new(@set, {
:parameters_key => PARAMETERS_KEY,
:request_class => request_class})
@formatter = Journey::Formatter.new @set
end
def draw(&block)
clear! unless @disable_clear_and_finalize
eval_block(block)
finalize! unless @disable_clear_and_finalize
nil
end
def append(&block)
@append << block
end
def prepend(&block)
@prepend << block
end
def eval_block(block)
if block.arity == 1
raise "You are using the old router DSL which has been removed in Rails 3.1. " <<
"Please check how to update your routes file at: http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/"
end
mapper = Mapper.new(self)
if default_scope
mapper.with_default_scope(default_scope, &block)
else
mapper.instance_exec(&block)
end
end
def finalize!
return if @finalized
@append.each { |blk| eval_block(blk) }
@finalized = true
end
def clear!
@finalized = false
named_routes.clear
set.clear
formatter.clear
@prepend.each { |blk| eval_block(blk) }
end
module MountedHelpers #:nodoc:
extend ActiveSupport::Concern
include UrlFor
end
# Contains all the mounted helpers across different
# engines and the `main_app` helper for the application.
# You can include this in your classes if you want to
# access routes for other engines.
def mounted_helpers
MountedHelpers
end
def define_mounted_helper(name)
return if MountedHelpers.method_defined?(name)
routes = self
MountedHelpers.class_eval do
define_method "_#{name}" do
RoutesProxy.new(routes, _routes_context)
end
end
MountedHelpers.class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
def #{name}
@_#{name} ||= _#{name}
end
RUBY
end
def url_helpers
@url_helpers ||= begin
routes = self
Module.new do
extend ActiveSupport::Concern
include UrlFor
# Define url_for in the singleton level so one can do:
# Rails.application.routes.url_helpers.url_for(args)
@_routes = routes
class << self
delegate :url_for, :optimize_routes_generation?, :to => '@_routes'
attr_reader :_routes
def url_options; {}; end
end
# Make named_routes available in the module singleton
# as well, so one can do:
# Rails.application.routes.url_helpers.posts_path
extend routes.named_routes.module
# Any class that includes this module will get all
# named routes...
include routes.named_routes.module
# plus a singleton class method called _routes ...
included do
singleton_class.send(:redefine_method, :_routes) { routes }
end
# And an instance method _routes. Note that
# UrlFor (included in this module) add extra
# conveniences for working with @_routes.
define_method(:_routes) { @_routes || routes }
end
end
end
def empty?
routes.empty?
end
def add_route(app, conditions = {}, requirements = {}, defaults = {}, name = nil, anchor = true)
raise ArgumentError, "Invalid route name: '#{name}'" unless name.blank? || name.to_s.match(/^[_a-z]\w*$/i)
if name && named_routes[name]
raise ArgumentError, "Invalid route name, already in use: '#{name}' \n" \
"You may have defined two routes with the same name using the `:as` option, or " \
"you may be overriding a route already defined by a resource with the same naming. " \
"For the latter, you can restrict the routes created with `resources` as explained here: \n" \
"http://guides.rubyonrails.org/routing.html#restricting-the-routes-created"
end
path = build_path(conditions.delete(:path_info), requirements, SEPARATORS, anchor)
conditions = build_conditions(conditions, path.names.map { |x| x.to_sym })
route = @set.add_route(app, path, conditions, defaults, name)
named_routes[name] = route if name
route
end
def build_path(path, requirements, separators, anchor)
strexp = Journey::Router::Strexp.new(
path,
requirements,
SEPARATORS,
anchor)
pattern = Journey::Path::Pattern.new(strexp)
builder = Journey::GTG::Builder.new pattern.spec
# Get all the symbol nodes followed by literals that are not the
# dummy node.
symbols = pattern.spec.grep(Journey::Nodes::Symbol).find_all { |n|
builder.followpos(n).first.literal?
}
# Get all the symbol nodes preceded by literals.
symbols.concat pattern.spec.find_all(&:literal?).map { |n|
builder.followpos(n).first
}.find_all(&:symbol?)
symbols.each { |x|
x.regexp = /(?:#{Regexp.union(x.regexp, '-')})+/
}
pattern
end
private :build_path
def build_conditions(current_conditions, path_values)
conditions = current_conditions.dup
# Rack-Mount requires that :request_method be a regular expression.
# :request_method represents the HTTP verb that matches this route.
#
# Here we munge values before they get sent on to rack-mount.
verbs = conditions[:request_method] || []
unless verbs.empty?
conditions[:request_method] = %r[^#{verbs.join('|')}$]
end
conditions.keep_if do |k, _|
k == :action || k == :controller || k == :required_defaults ||
@request_class.public_method_defined?(k) || path_values.include?(k)
end
end
private :build_conditions
class Generator #:nodoc:
PARAMETERIZE = lambda do |name, value|
if name == :controller
value
elsif value.is_a?(Array)
value.map { |v| v.to_param }.join('/')
elsif param = value.to_param
param
end
end
attr_reader :options, :recall, :set, :named_route
def initialize(options, recall, set)
@named_route = options.delete(:use_route)
@options = options.dup
@recall = recall.dup
@set = set
normalize_recall!
normalize_options!
normalize_controller_action_id!
use_relative_controller!
normalize_controller!
normalize_action!
end
def controller
@options[:controller]
end
def current_controller
@recall[:controller]
end
def use_recall_for(key)
if @recall[key] && (!@options.key?(key) || @options[key] == @recall[key])
if !named_route_exists? || segment_keys.include?(key)
@options[key] = @recall.delete(key)
end
end
end
# Set 'index' as default action for recall
def normalize_recall!
@recall[:action] ||= 'index'
end
def normalize_options!
# If an explicit :controller was given, always make :action explicit
# too, so that action expiry works as expected for things like
#
# generate({controller: 'content'}, {controller: 'content', action: 'show'})
#
# (the above is from the unit tests). In the above case, because the
# controller was explicitly given, but no action, the action is implied to
# be "index", not the recalled action of "show".
if options[:controller]
options[:action] ||= 'index'
options[:controller] = options[:controller].to_s
end
if options.key?(:action)
options[:action] = (options[:action] || 'index').to_s
end
end
# This pulls :controller, :action, and :id out of the recall.
# The recall key is only used if there is no key in the options
# or if the key in the options is identical. If any of
# :controller, :action or :id is not found, don't pull any
# more keys from the recall.
def normalize_controller_action_id!
use_recall_for(:controller) or return
use_recall_for(:action) or return
use_recall_for(:id)
end
# if the current controller is "foo/bar/baz" and controller: "baz/bat"
# is specified, the controller becomes "foo/baz/bat"
def use_relative_controller!
if !named_route && different_controller? && !controller.start_with?("/")
old_parts = current_controller.split('/')
size = controller.count("/") + 1
parts = old_parts[0...-size] << controller
@options[:controller] = parts.join("/")
end
end
# Remove leading slashes from controllers
def normalize_controller!
@options[:controller] = controller.sub(%r{^/}, '') if controller
end
# Move 'index' action from options to recall
def normalize_action!
if @options[:action] == 'index'
@recall[:action] = @options.delete(:action)
end
end
# Generates a path from routes, returns [path, params].
# If no route is generated the formatter will raise ActionController::UrlGenerationError
def generate
@set.formatter.generate(:path_info, named_route, options, recall, PARAMETERIZE)
end
def different_controller?
return false unless current_controller
controller.to_param != current_controller.to_param
end
private
def named_route_exists?
named_route && set.named_routes[named_route]
end
def segment_keys
set.named_routes[named_route].segment_keys
end
end
# Generate the path indicated by the arguments, and return an array of
# the keys that were not used to generate it.
def extra_keys(options, recall={})
generate_extras(options, recall).last
end
def generate_extras(options, recall={})
path, params = generate(options, recall)
return path, params.keys
end
def generate(options, recall = {})
Generator.new(options, recall, self).generate
end
RESERVED_OPTIONS = [:host, :protocol, :port, :subdomain, :domain, :tld_length,
:trailing_slash, :anchor, :params, :only_path, :script_name,
:original_script_name]
def mounted?
false
end
def optimize_routes_generation?
!mounted? && default_url_options.empty?
end
def find_script_name(options)
options.delete :script_name
end
# The +options+ argument must be a hash whose keys are *symbols*.
def url_for(options)
options = default_url_options.merge options
user = password = nil
if options[:user] && options[:password]
user = options.delete :user
password = options.delete :password
end
recall = options.delete(:_recall)
original_script_name = options.delete(:original_script_name)
script_name = find_script_name options
if script_name && original_script_name
script_name = original_script_name + script_name
end
path_options = options.dup
RESERVED_OPTIONS.each { |ro| path_options.delete ro }
path_options = yield(path_options) if block_given?
path, params = generate(path_options, recall || {})
params.merge!(options[:params] || {})
ActionDispatch::Http::URL.url_for(options.merge!({
:path => path,
:script_name => script_name,
:params => params,
:user => user,
:password => password
}))
end
def call(env)
@router.call(env)
end
def recognize_path(path, environment = {})
method = (environment[:method] || "GET").to_s.upcase
path = Journey::Router::Utils.normalize_path(path) unless path =~ %r{://}
extras = environment[:extras] || {}
begin
env = Rack::MockRequest.env_for(path, {:method => method})
rescue URI::InvalidURIError => e
raise ActionController::RoutingError, e.message
end
req = @request_class.new(env)
@router.recognize(req) do |route, _matches, params|
params.merge!(extras)
params.each do |key, value|
if value.is_a?(String)
value = value.dup.force_encoding(Encoding::BINARY)
params[key] = URI.parser.unescape(value)
end
end
old_params = env[::ActionDispatch::Routing::RouteSet::PARAMETERS_KEY]
env[::ActionDispatch::Routing::RouteSet::PARAMETERS_KEY] = (old_params || {}).merge(params)
dispatcher = route.app
while dispatcher.is_a?(Mapper::Constraints) && dispatcher.matches?(env) do
dispatcher = dispatcher.app
end
if dispatcher.is_a?(Dispatcher)
if dispatcher.controller(params, false)
dispatcher.prepare_params!(params)
return params
else
raise ActionController::RoutingError, "A route matches #{path.inspect}, but references missing controller: #{params[:controller].camelize}Controller"
end
end
end
raise ActionController::RoutingError, "No route matches #{path.inspect}"
end
end
end
end
we never call url_for with a block, so rm
require 'action_dispatch/journey'
require 'forwardable'
require 'thread_safe'
require 'active_support/core_ext/object/to_query'
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/module/remove_method'
require 'active_support/core_ext/array/extract_options'
require 'action_controller/metal/exceptions'
module ActionDispatch
module Routing
class RouteSet #:nodoc:
# Since the router holds references to many parts of the system
# like engines, controllers and the application itself, inspecting
# the route set can actually be really slow, therefore we default
# alias inspect to to_s.
alias inspect to_s
PARAMETERS_KEY = 'action_dispatch.request.path_parameters'
class Dispatcher #:nodoc:
def initialize(options={})
@defaults = options[:defaults]
@glob_param = options.delete(:glob)
@controller_class_names = ThreadSafe::Cache.new
end
def call(env)
params = env[PARAMETERS_KEY]
# If any of the path parameters has an invalid encoding then
# raise since it's likely to trigger errors further on.
params.each do |key, value|
next unless value.respond_to?(:valid_encoding?)
unless value.valid_encoding?
raise ActionController::BadRequest, "Invalid parameter: #{key} => #{value}"
end
end
prepare_params!(params)
# Just raise undefined constant errors if a controller was specified as default.
unless controller = controller(params, @defaults.key?(:controller))
return [404, {'X-Cascade' => 'pass'}, []]
end
dispatch(controller, params[:action], env)
end
def prepare_params!(params)
normalize_controller!(params)
merge_default_action!(params)
split_glob_param!(params) if @glob_param
end
# If this is a default_controller (i.e. a controller specified by the user)
# we should raise an error in case it's not found, because it usually means
# a user error. However, if the controller was retrieved through a dynamic
# segment, as in :controller(/:action), we should simply return nil and
# delegate the control back to Rack cascade. Besides, if this is not a default
# controller, it means we should respect the @scope[:module] parameter.
def controller(params, default_controller=true)
if params && params.key?(:controller)
controller_param = params[:controller]
controller_reference(controller_param)
end
rescue NameError => e
raise ActionController::RoutingError, e.message, e.backtrace if default_controller
end
private
def controller_reference(controller_param)
const_name = @controller_class_names[controller_param] ||= "#{controller_param.camelize}Controller"
ActiveSupport::Dependencies.constantize(const_name)
end
def dispatch(controller, action, env)
controller.action(action).call(env)
end
def normalize_controller!(params)
params[:controller] = params[:controller].underscore if params.key?(:controller)
end
def merge_default_action!(params)
params[:action] ||= 'index'
end
def split_glob_param!(params)
params[@glob_param] = params[@glob_param].split('/').map { |v| URI.parser.unescape(v) }
end
end
# A NamedRouteCollection instance is a collection of named routes, and also
# maintains an anonymous module that can be used to install helpers for the
# named routes.
class NamedRouteCollection #:nodoc:
include Enumerable
attr_reader :routes, :helpers, :module
def initialize
@routes = {}
@helpers = []
@module = Module.new
end
def helper_names
@helpers.map(&:to_s)
end
def clear!
@helpers.each do |helper|
@module.remove_possible_method helper
end
@routes.clear
@helpers.clear
end
def add(name, route)
routes[name.to_sym] = route
define_named_route_methods(name, route)
end
def get(name)
routes[name.to_sym]
end
alias []= add
alias [] get
alias clear clear!
def each
routes.each { |name, route| yield name, route }
self
end
def names
routes.keys
end
def length
routes.length
end
class UrlHelper # :nodoc:
def self.create(route, options)
if optimize_helper?(route)
OptimizedUrlHelper.new(route, options)
else
new route, options
end
end
def self.optimize_helper?(route)
!route.glob? && route.requirements.except(:controller, :action, :host).empty?
end
class OptimizedUrlHelper < UrlHelper # :nodoc:
attr_reader :arg_size
def initialize(route, options)
super
@klass = Journey::Router::Utils
@required_parts = @route.required_parts
@arg_size = @required_parts.size
@optimized_path = @route.optimized_path
end
def call(t, args)
if args.size == arg_size && !args.last.is_a?(Hash) && optimize_routes_generation?(t)
options = t.url_options.merge @options
options[:path] = optimized_helper(args)
ActionDispatch::Http::URL.url_for(options)
else
super
end
end
private
def optimized_helper(args)
params = Hash[parameterize_args(args)]
missing_keys = missing_keys(params)
unless missing_keys.empty?
raise_generation_error(params, missing_keys)
end
@optimized_path.map{ |segment| replace_segment(params, segment) }.join
end
def replace_segment(params, segment)
Symbol === segment ? @klass.escape_segment(params[segment]) : segment
end
def optimize_routes_generation?(t)
t.send(:optimize_routes_generation?)
end
def parameterize_args(args)
@required_parts.zip(args.map(&:to_param))
end
def missing_keys(args)
args.select{ |part, arg| arg.nil? || arg.empty? }.keys
end
def raise_generation_error(args, missing_keys)
constraints = Hash[@route.requirements.merge(args).sort]
message = "No route matches #{constraints.inspect}"
message << " missing required keys: #{missing_keys.sort.inspect}"
raise ActionController::UrlGenerationError, message
end
end
def initialize(route, options)
@options = options
@segment_keys = route.segment_keys.uniq
@route = route
end
def call(t, args)
options = t.url_options.merge @options
hash = handle_positional_args(t, args, options, @segment_keys)
t._routes.url_for(hash)
end
def handle_positional_args(t, args, result, keys)
inner_options = args.extract_options!
if args.size > 0
if args.size < keys.size - 1 # take format into account
keys -= t.url_options.keys
keys -= result.keys
end
keys -= inner_options.keys
result.merge!(Hash[keys.zip(args)])
end
result.merge!(inner_options)
end
end
private
# Create a url helper allowing ordered parameters to be associated
# with corresponding dynamic segments, so you can do:
#
# foo_url(bar, baz, bang)
#
# Instead of:
#
# foo_url(bar: bar, baz: baz, bang: bang)
#
# Also allow options hash, so you can do:
#
# foo_url(bar, baz, bang, sort_by: 'baz')
#
def define_url_helper(route, name, options)
helper = UrlHelper.create(route, options.dup)
@module.remove_possible_method name
@module.module_eval do
define_method(name) do |*args|
helper.call self, args
end
end
helpers << name
end
def define_named_route_methods(name, route)
define_url_helper route, :"#{name}_path",
route.defaults.merge(:use_route => name, :only_path => true)
define_url_helper route, :"#{name}_url",
route.defaults.merge(:use_route => name, :only_path => false)
end
end
attr_accessor :formatter, :set, :named_routes, :default_scope, :router
attr_accessor :disable_clear_and_finalize, :resources_path_names
attr_accessor :default_url_options, :request_class
alias :routes :set
def self.default_resources_path_names
{ :new => 'new', :edit => 'edit' }
end
def initialize(request_class = ActionDispatch::Request)
self.named_routes = NamedRouteCollection.new
self.resources_path_names = self.class.default_resources_path_names.dup
self.default_url_options = {}
self.request_class = request_class
@append = []
@prepend = []
@disable_clear_and_finalize = false
@finalized = false
@set = Journey::Routes.new
@router = Journey::Router.new(@set, {
:parameters_key => PARAMETERS_KEY,
:request_class => request_class})
@formatter = Journey::Formatter.new @set
end
def draw(&block)
clear! unless @disable_clear_and_finalize
eval_block(block)
finalize! unless @disable_clear_and_finalize
nil
end
def append(&block)
@append << block
end
def prepend(&block)
@prepend << block
end
def eval_block(block)
if block.arity == 1
raise "You are using the old router DSL which has been removed in Rails 3.1. " <<
"Please check how to update your routes file at: http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/"
end
mapper = Mapper.new(self)
if default_scope
mapper.with_default_scope(default_scope, &block)
else
mapper.instance_exec(&block)
end
end
def finalize!
return if @finalized
@append.each { |blk| eval_block(blk) }
@finalized = true
end
def clear!
@finalized = false
named_routes.clear
set.clear
formatter.clear
@prepend.each { |blk| eval_block(blk) }
end
module MountedHelpers #:nodoc:
extend ActiveSupport::Concern
include UrlFor
end
# Contains all the mounted helpers across different
# engines and the `main_app` helper for the application.
# You can include this in your classes if you want to
# access routes for other engines.
def mounted_helpers
MountedHelpers
end
def define_mounted_helper(name)
return if MountedHelpers.method_defined?(name)
routes = self
MountedHelpers.class_eval do
define_method "_#{name}" do
RoutesProxy.new(routes, _routes_context)
end
end
MountedHelpers.class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
def #{name}
@_#{name} ||= _#{name}
end
RUBY
end
def url_helpers
@url_helpers ||= begin
routes = self
Module.new do
extend ActiveSupport::Concern
include UrlFor
# Define url_for in the singleton level so one can do:
# Rails.application.routes.url_helpers.url_for(args)
@_routes = routes
class << self
delegate :url_for, :optimize_routes_generation?, :to => '@_routes'
attr_reader :_routes
def url_options; {}; end
end
# Make named_routes available in the module singleton
# as well, so one can do:
# Rails.application.routes.url_helpers.posts_path
extend routes.named_routes.module
# Any class that includes this module will get all
# named routes...
include routes.named_routes.module
# plus a singleton class method called _routes ...
included do
singleton_class.send(:redefine_method, :_routes) { routes }
end
# And an instance method _routes. Note that
# UrlFor (included in this module) add extra
# conveniences for working with @_routes.
define_method(:_routes) { @_routes || routes }
end
end
end
def empty?
routes.empty?
end
def add_route(app, conditions = {}, requirements = {}, defaults = {}, name = nil, anchor = true)
raise ArgumentError, "Invalid route name: '#{name}'" unless name.blank? || name.to_s.match(/^[_a-z]\w*$/i)
if name && named_routes[name]
raise ArgumentError, "Invalid route name, already in use: '#{name}' \n" \
"You may have defined two routes with the same name using the `:as` option, or " \
"you may be overriding a route already defined by a resource with the same naming. " \
"For the latter, you can restrict the routes created with `resources` as explained here: \n" \
"http://guides.rubyonrails.org/routing.html#restricting-the-routes-created"
end
path = build_path(conditions.delete(:path_info), requirements, SEPARATORS, anchor)
conditions = build_conditions(conditions, path.names.map { |x| x.to_sym })
route = @set.add_route(app, path, conditions, defaults, name)
named_routes[name] = route if name
route
end
def build_path(path, requirements, separators, anchor)
strexp = Journey::Router::Strexp.new(
path,
requirements,
SEPARATORS,
anchor)
pattern = Journey::Path::Pattern.new(strexp)
builder = Journey::GTG::Builder.new pattern.spec
# Get all the symbol nodes followed by literals that are not the
# dummy node.
symbols = pattern.spec.grep(Journey::Nodes::Symbol).find_all { |n|
builder.followpos(n).first.literal?
}
# Get all the symbol nodes preceded by literals.
symbols.concat pattern.spec.find_all(&:literal?).map { |n|
builder.followpos(n).first
}.find_all(&:symbol?)
symbols.each { |x|
x.regexp = /(?:#{Regexp.union(x.regexp, '-')})+/
}
pattern
end
private :build_path
def build_conditions(current_conditions, path_values)
conditions = current_conditions.dup
# Rack-Mount requires that :request_method be a regular expression.
# :request_method represents the HTTP verb that matches this route.
#
# Here we munge values before they get sent on to rack-mount.
verbs = conditions[:request_method] || []
unless verbs.empty?
conditions[:request_method] = %r[^#{verbs.join('|')}$]
end
conditions.keep_if do |k, _|
k == :action || k == :controller || k == :required_defaults ||
@request_class.public_method_defined?(k) || path_values.include?(k)
end
end
private :build_conditions
class Generator #:nodoc:
PARAMETERIZE = lambda do |name, value|
if name == :controller
value
elsif value.is_a?(Array)
value.map { |v| v.to_param }.join('/')
elsif param = value.to_param
param
end
end
attr_reader :options, :recall, :set, :named_route
def initialize(options, recall, set)
@named_route = options.delete(:use_route)
@options = options.dup
@recall = recall.dup
@set = set
normalize_recall!
normalize_options!
normalize_controller_action_id!
use_relative_controller!
normalize_controller!
normalize_action!
end
def controller
@options[:controller]
end
def current_controller
@recall[:controller]
end
def use_recall_for(key)
if @recall[key] && (!@options.key?(key) || @options[key] == @recall[key])
if !named_route_exists? || segment_keys.include?(key)
@options[key] = @recall.delete(key)
end
end
end
# Set 'index' as default action for recall
def normalize_recall!
@recall[:action] ||= 'index'
end
def normalize_options!
# If an explicit :controller was given, always make :action explicit
# too, so that action expiry works as expected for things like
#
# generate({controller: 'content'}, {controller: 'content', action: 'show'})
#
# (the above is from the unit tests). In the above case, because the
# controller was explicitly given, but no action, the action is implied to
# be "index", not the recalled action of "show".
if options[:controller]
options[:action] ||= 'index'
options[:controller] = options[:controller].to_s
end
if options.key?(:action)
options[:action] = (options[:action] || 'index').to_s
end
end
# This pulls :controller, :action, and :id out of the recall.
# The recall key is only used if there is no key in the options
# or if the key in the options is identical. If any of
# :controller, :action or :id is not found, don't pull any
# more keys from the recall.
def normalize_controller_action_id!
use_recall_for(:controller) or return
use_recall_for(:action) or return
use_recall_for(:id)
end
# if the current controller is "foo/bar/baz" and controller: "baz/bat"
# is specified, the controller becomes "foo/baz/bat"
def use_relative_controller!
if !named_route && different_controller? && !controller.start_with?("/")
old_parts = current_controller.split('/')
size = controller.count("/") + 1
parts = old_parts[0...-size] << controller
@options[:controller] = parts.join("/")
end
end
# Remove leading slashes from controllers
def normalize_controller!
@options[:controller] = controller.sub(%r{^/}, '') if controller
end
# Move 'index' action from options to recall
def normalize_action!
if @options[:action] == 'index'
@recall[:action] = @options.delete(:action)
end
end
# Generates a path from routes, returns [path, params].
# If no route is generated the formatter will raise ActionController::UrlGenerationError
def generate
@set.formatter.generate(:path_info, named_route, options, recall, PARAMETERIZE)
end
def different_controller?
return false unless current_controller
controller.to_param != current_controller.to_param
end
private
def named_route_exists?
named_route && set.named_routes[named_route]
end
def segment_keys
set.named_routes[named_route].segment_keys
end
end
# Generate the path indicated by the arguments, and return an array of
# the keys that were not used to generate it.
def extra_keys(options, recall={})
generate_extras(options, recall).last
end
def generate_extras(options, recall={})
path, params = generate(options, recall)
return path, params.keys
end
def generate(options, recall = {})
Generator.new(options, recall, self).generate
end
RESERVED_OPTIONS = [:host, :protocol, :port, :subdomain, :domain, :tld_length,
:trailing_slash, :anchor, :params, :only_path, :script_name,
:original_script_name]
def mounted?
false
end
def optimize_routes_generation?
!mounted? && default_url_options.empty?
end
def find_script_name(options)
options.delete :script_name
end
# The +options+ argument must be a hash whose keys are *symbols*.
def url_for(options)
options = default_url_options.merge options
user = password = nil
if options[:user] && options[:password]
user = options.delete :user
password = options.delete :password
end
recall = options.delete(:_recall)
original_script_name = options.delete(:original_script_name)
script_name = find_script_name options
if script_name && original_script_name
script_name = original_script_name + script_name
end
path_options = options.dup
RESERVED_OPTIONS.each { |ro| path_options.delete ro }
path, params = generate(path_options, recall || {})
params.merge!(options[:params] || {})
ActionDispatch::Http::URL.url_for(options.merge!({
:path => path,
:script_name => script_name,
:params => params,
:user => user,
:password => password
}))
end
def call(env)
@router.call(env)
end
def recognize_path(path, environment = {})
method = (environment[:method] || "GET").to_s.upcase
path = Journey::Router::Utils.normalize_path(path) unless path =~ %r{://}
extras = environment[:extras] || {}
begin
env = Rack::MockRequest.env_for(path, {:method => method})
rescue URI::InvalidURIError => e
raise ActionController::RoutingError, e.message
end
req = @request_class.new(env)
@router.recognize(req) do |route, _matches, params|
params.merge!(extras)
params.each do |key, value|
if value.is_a?(String)
value = value.dup.force_encoding(Encoding::BINARY)
params[key] = URI.parser.unescape(value)
end
end
old_params = env[::ActionDispatch::Routing::RouteSet::PARAMETERS_KEY]
env[::ActionDispatch::Routing::RouteSet::PARAMETERS_KEY] = (old_params || {}).merge(params)
dispatcher = route.app
while dispatcher.is_a?(Mapper::Constraints) && dispatcher.matches?(env) do
dispatcher = dispatcher.app
end
if dispatcher.is_a?(Dispatcher)
if dispatcher.controller(params, false)
dispatcher.prepare_params!(params)
return params
else
raise ActionController::RoutingError, "A route matches #{path.inspect}, but references missing controller: #{params[:controller].camelize}Controller"
end
end
end
raise ActionController::RoutingError, "No route matches #{path.inspect}"
end
end
end
end
|
module ActionView
module Helpers
# Provides methods for converting a number into a formatted string that currently represents
# one of the following forms: phone number, percentage, money, or precision level.
module NumberHelper
# Formats a +number+ into a US phone number string. The +options+ can be hash used to customize the format of the output.
# The area code can be surrounded by parenthesis by setting +:area_code+ to true; default is false
# The delimeter can be set using +:delimter+; default is "-"
# Examples:
# number_to_phone(1235551234) => 123-555-1234
# number_to_phone(1235551234, {:area_code => true}) => (123) 555-1234
# number_to_phone(1235551234, {:delimter => " "}) => 123 555 1234
def number_to_phone(number, options = {})
options = options.stringify_keys
area_code = options.delete("area_code") { false }
delimeter = options.delete("delimeter") { "-" }
begin
str = number.to_s
if area_code == true
str.gsub!(/([0-9]{3})([0-9]{3})([0-9]{4})/,"(\\1) \\2#{delimeter}\\3")
else
str.gsub!(/([0-9]{3})([0-9]{3})([0-9]{4})/,"\\1#{delimeter}\\2#{delimeter}\\3")
end
rescue
number
end
end
# Formates a +number+ into a currency string. The +options+ hash can be used to customize the format of the output.
# The +number+ can contain a level of precision using the +precision+ key; default is 2
# The currency type can be set using the +unit+ key; default is "$"
# The unit separator can be set using the +separator+ key; default is "."
# The delimter can be set using the +delimeter+ key; default is ","
# Examples:
# number_to_currency(1234567890.50) => $1,234,567,890.50
# number_to_currency(1234567890.506) => $1,234,567,890.51
# number_to_currency(1234567890.50, {:unit => "£", :separator => ",", :delimeter => ""}) => £123456789,50
def number_to_currency(number, options = {})
options = options.stringify_keys
precision, unit, separator, delimeter = options.delete("precision") { 2 }, options.delete("unit") { "$" }, options.delete("separator") { "." }, options.delete("delimeter") { "," }
begin
parts = number_with_precision(number, precision).split('.')
unit + number_with_delimeter(parts[0]) + separator + parts[1].to_s
rescue
number
end
end
# Formats a +number+ as into a percentage string. The +options+ hash can be used to customize the format of the output.
# The +number+ can contain a level of precision using the +precision+ key; default is 3
# The unit separator can be set using the +separator+ key; default is "."
# Examples:
# number_to_precision(100) => 100.000%
# number_to_precision(100, {:precision => 0}) => 100%
# number_to_precision(302.0574, {:precision => 2}) => 302.06%
def number_to_percentage(number, options = {})
options = options.stringify_keys
precision, separator = options.delete("precision") { 3 }, options.delete("separator") { "." }
begin
number = number_with_precision(number, precision)
parts = number.split('.')
if parts.at(1).nil?
parts[0] + "%"
else
parts[0] + separator + parts[1].to_s + "%"
end
rescue
number
end
end
# Formats a +number+ with a +delimeter+.
# Example:
# number_with_delimeter(12345678) => 1,235,678
def number_with_delimeter(number, delimeter=",")
number.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{delimeter}"
end
# Formats a +number+ with a level of +precision+.
# Example:
# number_with_precision(111.2345) => 111.235
def number_with_precision(number, precision=3)
sprintf("%01.#{precision}f", number)
end
end
end
end
Fixed syntax error
git-svn-id: afc9fed30c1a09d8801d1e4fbe6e01c29c67d11f@1112 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
module ActionView
module Helpers
# Provides methods for converting a number into a formatted string that currently represents
# one of the following forms: phone number, percentage, money, or precision level.
module NumberHelper
# Formats a +number+ into a US phone number string. The +options+ can be hash used to customize the format of the output.
# The area code can be surrounded by parenthesis by setting +:area_code+ to true; default is false
# The delimeter can be set using +:delimter+; default is "-"
# Examples:
# number_to_phone(1235551234) => 123-555-1234
# number_to_phone(1235551234, {:area_code => true}) => (123) 555-1234
# number_to_phone(1235551234, {:delimter => " "}) => 123 555 1234
def number_to_phone(number, options = {})
options = options.stringify_keys
area_code = options.delete("area_code") { false }
delimeter = options.delete("delimeter") { "-" }
begin
str = number.to_s
if area_code == true
str.gsub!(/([0-9]{3})([0-9]{3})([0-9]{4})/,"(\\1) \\2#{delimeter}\\3")
else
str.gsub!(/([0-9]{3})([0-9]{3})([0-9]{4})/,"\\1#{delimeter}\\2#{delimeter}\\3")
end
rescue
number
end
end
# Formates a +number+ into a currency string. The +options+ hash can be used to customize the format of the output.
# The +number+ can contain a level of precision using the +precision+ key; default is 2
# The currency type can be set using the +unit+ key; default is "$"
# The unit separator can be set using the +separator+ key; default is "."
# The delimter can be set using the +delimeter+ key; default is ","
# Examples:
# number_to_currency(1234567890.50) => $1,234,567,890.50
# number_to_currency(1234567890.506) => $1,234,567,890.51
# number_to_currency(1234567890.50, {:unit => "£", :separator => ",", :delimeter => ""}) => £123456789,50
def number_to_currency(number, options = {})
options = options.stringify_keys
precision, unit, separator, delimeter = options.delete("precision") { 2 }, options.delete("unit") { "$" }, options.delete("separator") { "." }, options.delete("delimeter") { "," }
begin
parts = number_with_precision(number, precision).split('.')
unit + number_with_delimeter(parts[0]) + separator + parts[1].to_s
rescue
number
end
end
# Formats a +number+ as into a percentage string. The +options+ hash can be used to customize the format of the output.
# The +number+ can contain a level of precision using the +precision+ key; default is 3
# The unit separator can be set using the +separator+ key; default is "."
# Examples:
# number_to_precision(100) => 100.000%
# number_to_precision(100, {:precision => 0}) => 100%
# number_to_precision(302.0574, {:precision => 2}) => 302.06%
def number_to_percentage(number, options = {})
options = options.stringify_keys
precision, separator = options.delete("precision") { 3 }, options.delete("separator") { "." }
begin
number = number_with_precision(number, precision)
parts = number.split('.')
if parts.at(1).nil?
parts[0] + "%"
else
parts[0] + separator + parts[1].to_s + "%"
end
rescue
number
end
end
# Formats a +number+ with a +delimeter+.
# Example:
# number_with_delimeter(12345678) => 1,235,678
def number_with_delimeter(number, delimeter=",")
number.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{delimeter}")
end
# Formats a +number+ with a level of +precision+.
# Example:
# number_with_precision(111.2345) => 111.235
def number_with_precision(number, precision=3)
sprintf("%01.#{precision}f", number)
end
end
end
end |
require 'active_support/core_ext/enumerable'
require 'active_support/core_ext/string/filters'
require 'mutex_m'
require 'concurrent/map'
module ActiveRecord
# = Active Record Attribute Methods
module AttributeMethods
extend ActiveSupport::Concern
include ActiveModel::AttributeMethods
included do
initialize_generated_modules
include Read
include Write
include BeforeTypeCast
include Query
include PrimaryKey
include TimeZoneConversion
include Dirty
include Serialization
delegate :column_for_attribute, to: :class
end
AttrNames = Module.new {
def self.set_name_cache(name, value)
const_name = "ATTR_#{name}"
unless const_defined? const_name
const_set const_name, value.dup.freeze
end
end
}
BLACKLISTED_CLASS_METHODS = %w(private public protected allocate new name parent superclass)
class GeneratedAttributeMethods < Module; end # :nodoc:
module ClassMethods
def inherited(child_class) #:nodoc:
child_class.initialize_generated_modules
super
end
def initialize_generated_modules # :nodoc:
@generated_attribute_methods = GeneratedAttributeMethods.new { extend Mutex_m }
@attribute_methods_generated = false
include @generated_attribute_methods
super
end
# Generates all the attribute related methods for columns in the database
# accessors, mutators and query methods.
def define_attribute_methods # :nodoc:
return false if @attribute_methods_generated
# Use a mutex; we don't want two threads simultaneously trying to define
# attribute methods.
generated_attribute_methods.synchronize do
return false if @attribute_methods_generated
superclass.define_attribute_methods unless self == base_class
super(attribute_names)
@attribute_methods_generated = true
end
true
end
def undefine_attribute_methods # :nodoc:
generated_attribute_methods.synchronize do
super if defined?(@attribute_methods_generated) && @attribute_methods_generated
@attribute_methods_generated = false
end
end
# Raises an ActiveRecord::DangerousAttributeError exception when an
# \Active \Record method is defined in the model, otherwise +false+.
#
# class Person < ActiveRecord::Base
# def save
# 'already defined by Active Record'
# end
# end
#
# Person.instance_method_already_implemented?(:save)
# # => ActiveRecord::DangerousAttributeError: save is defined by Active Record. Check to make sure that you don't have an attribute or method with the same name.
#
# Person.instance_method_already_implemented?(:name)
# # => false
def instance_method_already_implemented?(method_name)
if dangerous_attribute_method?(method_name)
raise DangerousAttributeError, "#{method_name} is defined by Active Record. Check to make sure that you don't have an attribute or method with the same name."
end
if superclass == Base
super
else
# If ThisClass < ... < SomeSuperClass < ... < Base and SomeSuperClass
# defines its own attribute method, then we don't want to overwrite that.
defined = method_defined_within?(method_name, superclass, Base) &&
! superclass.instance_method(method_name).owner.is_a?(GeneratedAttributeMethods)
defined || super
end
end
# A method name is 'dangerous' if it is already (re)defined by Active Record, but
# not by any ancestors. (So 'puts' is not dangerous but 'save' is.)
def dangerous_attribute_method?(name) # :nodoc:
method_defined_within?(name, Base)
end
def method_defined_within?(name, klass, superklass = klass.superclass) # :nodoc:
if klass.method_defined?(name) || klass.private_method_defined?(name)
if superklass.method_defined?(name) || superklass.private_method_defined?(name)
klass.instance_method(name).owner != superklass.instance_method(name).owner
else
true
end
else
false
end
end
# A class method is 'dangerous' if it is already (re)defined by Active Record, but
# not by any ancestors. (So 'puts' is not dangerous but 'new' is.)
def dangerous_class_method?(method_name)
BLACKLISTED_CLASS_METHODS.include?(method_name.to_s) || class_method_defined_within?(method_name, Base)
end
def class_method_defined_within?(name, klass, superklass = klass.superclass) # :nodoc:
if klass.respond_to?(name, true)
if superklass.respond_to?(name, true)
klass.method(name).owner != superklass.method(name).owner
else
true
end
else
false
end
end
# Returns +true+ if +attribute+ is an attribute method and table exists,
# +false+ otherwise.
#
# class Person < ActiveRecord::Base
# end
#
# Person.attribute_method?('name') # => true
# Person.attribute_method?(:age=) # => true
# Person.attribute_method?(:nothing) # => false
def attribute_method?(attribute)
super || (table_exists? && column_names.include?(attribute.to_s.sub(/=$/, '')))
end
# Returns an array of column names as strings if it's not an abstract class and
# table exists. Otherwise it returns an empty array.
#
# class Person < ActiveRecord::Base
# end
#
# Person.attribute_names
# # => ["id", "created_at", "updated_at", "name", "age"]
def attribute_names
@attribute_names ||= if !abstract_class? && table_exists?
attribute_types.keys
else
[]
end
end
# Returns true if the given attribute exists, otherwise false.
#
# class Person < ActiveRecord::Base
# end
#
# Person.has_attribute?('name') # => true
# Person.has_attribute?(:age) # => true
# Person.has_attribute?(:nothing) # => false
def has_attribute?(attr_name)
attribute_types.key?(attr_name.to_s)
end
# Returns the column object for the named attribute.
# Returns a +ActiveRecord::ConnectionAdapters::NullColumn+ if the
# named attribute does not exist.
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.new
# person.column_for_attribute(:name) # the result depends on the ConnectionAdapter
# # => #<ActiveRecord::ConnectionAdapters::Column:0x007ff4ab083980 @name="name", @sql_type="varchar(255)", @null=true, ...>
#
# person.column_for_attribute(:nothing)
# # => #<ActiveRecord::ConnectionAdapters::NullColumn:0xXXX @name=nil, @sql_type=nil, @cast_type=#<Type::Value>, ...>
def column_for_attribute(name)
name = name.to_s
columns_hash.fetch(name) do
ConnectionAdapters::NullColumn.new(name)
end
end
end
# A Person object with a name attribute can ask <tt>person.respond_to?(:name)</tt>,
# <tt>person.respond_to?(:name=)</tt>, and <tt>person.respond_to?(:name?)</tt>
# which will all return +true+. It also defines the attribute methods if they have
# not been generated.
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.new
# person.respond_to(:name) # => true
# person.respond_to(:name=) # => true
# person.respond_to(:name?) # => true
# person.respond_to('age') # => true
# person.respond_to('age=') # => true
# person.respond_to('age?') # => true
# person.respond_to(:nothing) # => false
def respond_to?(name, include_private = false)
return false unless super
case name
when :to_partial_path
name = "to_partial_path".freeze
when :to_model
name = "to_model".freeze
else
name = name.to_s
end
# If the result is true then check for the select case.
# For queries selecting a subset of columns, return false for unselected columns.
# We check defined?(@attributes) not to issue warnings if called on objects that
# have been allocated but not yet initialized.
if defined?(@attributes) && self.class.column_names.include?(name)
return has_attribute?(name)
end
return true
end
# Returns +true+ if the given attribute is in the attributes hash, otherwise +false+.
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.new
# person.has_attribute?(:name) # => true
# person.has_attribute?('age') # => true
# person.has_attribute?(:nothing) # => false
def has_attribute?(attr_name)
@attributes.key?(attr_name.to_s)
end
# Returns an array of names for the attributes available on this object.
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.new
# person.attribute_names
# # => ["id", "created_at", "updated_at", "name", "age"]
def attribute_names
@attributes.keys
end
# Returns a hash of all the attributes with their names as keys and the values of the attributes as values.
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.create(name: 'Francesco', age: 22)
# person.attributes
# # => {"id"=>3, "created_at"=>Sun, 21 Oct 2012 04:53:04, "updated_at"=>Sun, 21 Oct 2012 04:53:04, "name"=>"Francesco", "age"=>22}
def attributes
@attributes.to_hash
end
# Returns an <tt>#inspect</tt>-like string for the value of the
# attribute +attr_name+. String attributes are truncated up to 50
# characters, Date and Time attributes are returned in the
# <tt>:db</tt> format, Array attributes are truncated up to 10 values.
# Other attributes return the value of <tt>#inspect</tt> without
# modification.
#
# person = Person.create!(name: 'David Heinemeier Hansson ' * 3)
#
# person.attribute_for_inspect(:name)
# # => "\"David Heinemeier Hansson David Heinemeier Hansson ...\""
#
# person.attribute_for_inspect(:created_at)
# # => "\"2012-10-22 00:15:07\""
#
# person.attribute_for_inspect(:tag_ids)
# # => "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...]"
def attribute_for_inspect(attr_name)
value = read_attribute(attr_name)
if value.is_a?(String) && value.length > 50
"#{value[0, 50]}...".inspect
elsif value.is_a?(Date) || value.is_a?(Time)
%("#{value.to_s(:db)}")
elsif value.is_a?(Array) && value.size > 10
inspected = value.first(10).inspect
%(#{inspected[0...-1]}, ...])
else
value.inspect
end
end
# Returns +true+ if the specified +attribute+ has been set by the user or by a
# database load and is neither +nil+ nor <tt>empty?</tt> (the latter only applies
# to objects that respond to <tt>empty?</tt>, most notably Strings). Otherwise, +false+.
# Note that it always returns +true+ with boolean attributes.
#
# class Task < ActiveRecord::Base
# end
#
# task = Task.new(title: '', is_done: false)
# task.attribute_present?(:title) # => false
# task.attribute_present?(:is_done) # => true
# task.title = 'Buy milk'
# task.is_done = true
# task.attribute_present?(:title) # => true
# task.attribute_present?(:is_done) # => true
def attribute_present?(attribute)
value = _read_attribute(attribute)
!value.nil? && !(value.respond_to?(:empty?) && value.empty?)
end
# Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
# "2004-12-12" in a date column is cast to a date object, like Date.new(2004, 12, 12)). It raises
# <tt>ActiveModel::MissingAttributeError</tt> if the identified attribute is missing.
#
# Note: +:id+ is always present.
#
# Alias for the #read_attribute method.
#
# class Person < ActiveRecord::Base
# belongs_to :organization
# end
#
# person = Person.new(name: 'Francesco', age: '22')
# person[:name] # => "Francesco"
# person[:age] # => 22
#
# person = Person.select('id').first
# person[:name] # => ActiveModel::MissingAttributeError: missing attribute: name
# person[:organization_id] # => ActiveModel::MissingAttributeError: missing attribute: organization_id
def [](attr_name)
read_attribute(attr_name) { |n| missing_attribute(n, caller) }
end
# Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
# (Alias for the protected #write_attribute method).
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.new
# person[:age] = '22'
# person[:age] # => 22
# person[:age].class # => Integer
def []=(attr_name, value)
write_attribute(attr_name, value)
end
# Returns the name of all database fields which have been read from this
# model. This can be useful in development mode to determine which fields
# need to be selected. For performance critical pages, selecting only the
# required fields can be an easy performance win (assuming you aren't using
# all of the fields on the model).
#
# For example:
#
# class PostsController < ActionController::Base
# after_action :print_accessed_fields, only: :index
#
# def index
# @posts = Post.all
# end
#
# private
#
# def print_accessed_fields
# p @posts.first.accessed_fields
# end
# end
#
# Which allows you to quickly change your code to:
#
# class PostsController < ActionController::Base
# def index
# @posts = Post.select(:id, :title, :author_id, :updated_at)
# end
# end
def accessed_fields
@attributes.accessed
end
protected
def clone_attribute_value(reader_method, attribute_name) # :nodoc:
value = send(reader_method, attribute_name)
value.duplicable? ? value.clone : value
rescue TypeError, NoMethodError
value
end
def arel_attributes_with_values_for_create(attribute_names) # :nodoc:
arel_attributes_with_values(attributes_for_create(attribute_names))
end
def arel_attributes_with_values_for_update(attribute_names) # :nodoc:
arel_attributes_with_values(attributes_for_update(attribute_names))
end
def attribute_method?(attr_name) # :nodoc:
# We check defined? because Syck calls respond_to? before actually calling initialize.
defined?(@attributes) && @attributes.key?(attr_name)
end
private
# Returns a Hash of the Arel::Attributes and attribute values that have been
# typecasted for use in an Arel insert/update method.
def arel_attributes_with_values(attribute_names)
attrs = {}
arel_table = self.class.arel_table
attribute_names.each do |name|
attrs[arel_table[name]] = typecasted_attribute_value(name)
end
attrs
end
# Filters the primary keys and readonly attributes from the attribute names.
def attributes_for_update(attribute_names)
attribute_names.reject do |name|
readonly_attribute?(name)
end
end
# Filters out the primary keys, from the attribute names, when the primary
# key is to be generated (e.g. the id attribute has no value).
def attributes_for_create(attribute_names)
attribute_names.reject do |name|
pk_attribute?(name) && id.nil?
end
end
def readonly_attribute?(name)
self.class.readonly_attributes.include?(name)
end
def pk_attribute?(name)
name == self.class.primary_key
end
def typecasted_attribute_value(name)
_read_attribute(name)
end
end
end
[] and read_attribute are not aliases [ci skip]
The `#[]` method *used to be* an alias of `#read_attribute`, but since Rails 4
(10f6f90d9d1bbc9598bffea90752fc6bd76904cd), it will raise an exception for
missing attributes. Saying that it is an alias is confusing.
require 'active_support/core_ext/enumerable'
require 'active_support/core_ext/string/filters'
require 'mutex_m'
require 'concurrent/map'
module ActiveRecord
# = Active Record Attribute Methods
module AttributeMethods
extend ActiveSupport::Concern
include ActiveModel::AttributeMethods
included do
initialize_generated_modules
include Read
include Write
include BeforeTypeCast
include Query
include PrimaryKey
include TimeZoneConversion
include Dirty
include Serialization
delegate :column_for_attribute, to: :class
end
AttrNames = Module.new {
def self.set_name_cache(name, value)
const_name = "ATTR_#{name}"
unless const_defined? const_name
const_set const_name, value.dup.freeze
end
end
}
BLACKLISTED_CLASS_METHODS = %w(private public protected allocate new name parent superclass)
class GeneratedAttributeMethods < Module; end # :nodoc:
module ClassMethods
def inherited(child_class) #:nodoc:
child_class.initialize_generated_modules
super
end
def initialize_generated_modules # :nodoc:
@generated_attribute_methods = GeneratedAttributeMethods.new { extend Mutex_m }
@attribute_methods_generated = false
include @generated_attribute_methods
super
end
# Generates all the attribute related methods for columns in the database
# accessors, mutators and query methods.
def define_attribute_methods # :nodoc:
return false if @attribute_methods_generated
# Use a mutex; we don't want two threads simultaneously trying to define
# attribute methods.
generated_attribute_methods.synchronize do
return false if @attribute_methods_generated
superclass.define_attribute_methods unless self == base_class
super(attribute_names)
@attribute_methods_generated = true
end
true
end
def undefine_attribute_methods # :nodoc:
generated_attribute_methods.synchronize do
super if defined?(@attribute_methods_generated) && @attribute_methods_generated
@attribute_methods_generated = false
end
end
# Raises an ActiveRecord::DangerousAttributeError exception when an
# \Active \Record method is defined in the model, otherwise +false+.
#
# class Person < ActiveRecord::Base
# def save
# 'already defined by Active Record'
# end
# end
#
# Person.instance_method_already_implemented?(:save)
# # => ActiveRecord::DangerousAttributeError: save is defined by Active Record. Check to make sure that you don't have an attribute or method with the same name.
#
# Person.instance_method_already_implemented?(:name)
# # => false
def instance_method_already_implemented?(method_name)
if dangerous_attribute_method?(method_name)
raise DangerousAttributeError, "#{method_name} is defined by Active Record. Check to make sure that you don't have an attribute or method with the same name."
end
if superclass == Base
super
else
# If ThisClass < ... < SomeSuperClass < ... < Base and SomeSuperClass
# defines its own attribute method, then we don't want to overwrite that.
defined = method_defined_within?(method_name, superclass, Base) &&
! superclass.instance_method(method_name).owner.is_a?(GeneratedAttributeMethods)
defined || super
end
end
# A method name is 'dangerous' if it is already (re)defined by Active Record, but
# not by any ancestors. (So 'puts' is not dangerous but 'save' is.)
def dangerous_attribute_method?(name) # :nodoc:
method_defined_within?(name, Base)
end
def method_defined_within?(name, klass, superklass = klass.superclass) # :nodoc:
if klass.method_defined?(name) || klass.private_method_defined?(name)
if superklass.method_defined?(name) || superklass.private_method_defined?(name)
klass.instance_method(name).owner != superklass.instance_method(name).owner
else
true
end
else
false
end
end
# A class method is 'dangerous' if it is already (re)defined by Active Record, but
# not by any ancestors. (So 'puts' is not dangerous but 'new' is.)
def dangerous_class_method?(method_name)
BLACKLISTED_CLASS_METHODS.include?(method_name.to_s) || class_method_defined_within?(method_name, Base)
end
def class_method_defined_within?(name, klass, superklass = klass.superclass) # :nodoc:
if klass.respond_to?(name, true)
if superklass.respond_to?(name, true)
klass.method(name).owner != superklass.method(name).owner
else
true
end
else
false
end
end
# Returns +true+ if +attribute+ is an attribute method and table exists,
# +false+ otherwise.
#
# class Person < ActiveRecord::Base
# end
#
# Person.attribute_method?('name') # => true
# Person.attribute_method?(:age=) # => true
# Person.attribute_method?(:nothing) # => false
def attribute_method?(attribute)
super || (table_exists? && column_names.include?(attribute.to_s.sub(/=$/, '')))
end
# Returns an array of column names as strings if it's not an abstract class and
# table exists. Otherwise it returns an empty array.
#
# class Person < ActiveRecord::Base
# end
#
# Person.attribute_names
# # => ["id", "created_at", "updated_at", "name", "age"]
def attribute_names
@attribute_names ||= if !abstract_class? && table_exists?
attribute_types.keys
else
[]
end
end
# Returns true if the given attribute exists, otherwise false.
#
# class Person < ActiveRecord::Base
# end
#
# Person.has_attribute?('name') # => true
# Person.has_attribute?(:age) # => true
# Person.has_attribute?(:nothing) # => false
def has_attribute?(attr_name)
attribute_types.key?(attr_name.to_s)
end
# Returns the column object for the named attribute.
# Returns a +ActiveRecord::ConnectionAdapters::NullColumn+ if the
# named attribute does not exist.
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.new
# person.column_for_attribute(:name) # the result depends on the ConnectionAdapter
# # => #<ActiveRecord::ConnectionAdapters::Column:0x007ff4ab083980 @name="name", @sql_type="varchar(255)", @null=true, ...>
#
# person.column_for_attribute(:nothing)
# # => #<ActiveRecord::ConnectionAdapters::NullColumn:0xXXX @name=nil, @sql_type=nil, @cast_type=#<Type::Value>, ...>
def column_for_attribute(name)
name = name.to_s
columns_hash.fetch(name) do
ConnectionAdapters::NullColumn.new(name)
end
end
end
# A Person object with a name attribute can ask <tt>person.respond_to?(:name)</tt>,
# <tt>person.respond_to?(:name=)</tt>, and <tt>person.respond_to?(:name?)</tt>
# which will all return +true+. It also defines the attribute methods if they have
# not been generated.
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.new
# person.respond_to(:name) # => true
# person.respond_to(:name=) # => true
# person.respond_to(:name?) # => true
# person.respond_to('age') # => true
# person.respond_to('age=') # => true
# person.respond_to('age?') # => true
# person.respond_to(:nothing) # => false
def respond_to?(name, include_private = false)
return false unless super
case name
when :to_partial_path
name = "to_partial_path".freeze
when :to_model
name = "to_model".freeze
else
name = name.to_s
end
# If the result is true then check for the select case.
# For queries selecting a subset of columns, return false for unselected columns.
# We check defined?(@attributes) not to issue warnings if called on objects that
# have been allocated but not yet initialized.
if defined?(@attributes) && self.class.column_names.include?(name)
return has_attribute?(name)
end
return true
end
# Returns +true+ if the given attribute is in the attributes hash, otherwise +false+.
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.new
# person.has_attribute?(:name) # => true
# person.has_attribute?('age') # => true
# person.has_attribute?(:nothing) # => false
def has_attribute?(attr_name)
@attributes.key?(attr_name.to_s)
end
# Returns an array of names for the attributes available on this object.
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.new
# person.attribute_names
# # => ["id", "created_at", "updated_at", "name", "age"]
def attribute_names
@attributes.keys
end
# Returns a hash of all the attributes with their names as keys and the values of the attributes as values.
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.create(name: 'Francesco', age: 22)
# person.attributes
# # => {"id"=>3, "created_at"=>Sun, 21 Oct 2012 04:53:04, "updated_at"=>Sun, 21 Oct 2012 04:53:04, "name"=>"Francesco", "age"=>22}
def attributes
@attributes.to_hash
end
# Returns an <tt>#inspect</tt>-like string for the value of the
# attribute +attr_name+. String attributes are truncated up to 50
# characters, Date and Time attributes are returned in the
# <tt>:db</tt> format, Array attributes are truncated up to 10 values.
# Other attributes return the value of <tt>#inspect</tt> without
# modification.
#
# person = Person.create!(name: 'David Heinemeier Hansson ' * 3)
#
# person.attribute_for_inspect(:name)
# # => "\"David Heinemeier Hansson David Heinemeier Hansson ...\""
#
# person.attribute_for_inspect(:created_at)
# # => "\"2012-10-22 00:15:07\""
#
# person.attribute_for_inspect(:tag_ids)
# # => "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...]"
def attribute_for_inspect(attr_name)
value = read_attribute(attr_name)
if value.is_a?(String) && value.length > 50
"#{value[0, 50]}...".inspect
elsif value.is_a?(Date) || value.is_a?(Time)
%("#{value.to_s(:db)}")
elsif value.is_a?(Array) && value.size > 10
inspected = value.first(10).inspect
%(#{inspected[0...-1]}, ...])
else
value.inspect
end
end
# Returns +true+ if the specified +attribute+ has been set by the user or by a
# database load and is neither +nil+ nor <tt>empty?</tt> (the latter only applies
# to objects that respond to <tt>empty?</tt>, most notably Strings). Otherwise, +false+.
# Note that it always returns +true+ with boolean attributes.
#
# class Task < ActiveRecord::Base
# end
#
# task = Task.new(title: '', is_done: false)
# task.attribute_present?(:title) # => false
# task.attribute_present?(:is_done) # => true
# task.title = 'Buy milk'
# task.is_done = true
# task.attribute_present?(:title) # => true
# task.attribute_present?(:is_done) # => true
def attribute_present?(attribute)
value = _read_attribute(attribute)
!value.nil? && !(value.respond_to?(:empty?) && value.empty?)
end
# Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
# "2004-12-12" in a date column is cast to a date object, like Date.new(2004, 12, 12)). It raises
# <tt>ActiveModel::MissingAttributeError</tt> if the identified attribute is missing.
#
# Note: +:id+ is always present.
#
# class Person < ActiveRecord::Base
# belongs_to :organization
# end
#
# person = Person.new(name: 'Francesco', age: '22')
# person[:name] # => "Francesco"
# person[:age] # => 22
#
# person = Person.select('id').first
# person[:name] # => ActiveModel::MissingAttributeError: missing attribute: name
# person[:organization_id] # => ActiveModel::MissingAttributeError: missing attribute: organization_id
def [](attr_name)
read_attribute(attr_name) { |n| missing_attribute(n, caller) }
end
# Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
# (Alias for the protected #write_attribute method).
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.new
# person[:age] = '22'
# person[:age] # => 22
# person[:age].class # => Integer
def []=(attr_name, value)
write_attribute(attr_name, value)
end
# Returns the name of all database fields which have been read from this
# model. This can be useful in development mode to determine which fields
# need to be selected. For performance critical pages, selecting only the
# required fields can be an easy performance win (assuming you aren't using
# all of the fields on the model).
#
# For example:
#
# class PostsController < ActionController::Base
# after_action :print_accessed_fields, only: :index
#
# def index
# @posts = Post.all
# end
#
# private
#
# def print_accessed_fields
# p @posts.first.accessed_fields
# end
# end
#
# Which allows you to quickly change your code to:
#
# class PostsController < ActionController::Base
# def index
# @posts = Post.select(:id, :title, :author_id, :updated_at)
# end
# end
def accessed_fields
@attributes.accessed
end
protected
def clone_attribute_value(reader_method, attribute_name) # :nodoc:
value = send(reader_method, attribute_name)
value.duplicable? ? value.clone : value
rescue TypeError, NoMethodError
value
end
def arel_attributes_with_values_for_create(attribute_names) # :nodoc:
arel_attributes_with_values(attributes_for_create(attribute_names))
end
def arel_attributes_with_values_for_update(attribute_names) # :nodoc:
arel_attributes_with_values(attributes_for_update(attribute_names))
end
def attribute_method?(attr_name) # :nodoc:
# We check defined? because Syck calls respond_to? before actually calling initialize.
defined?(@attributes) && @attributes.key?(attr_name)
end
private
# Returns a Hash of the Arel::Attributes and attribute values that have been
# typecasted for use in an Arel insert/update method.
def arel_attributes_with_values(attribute_names)
attrs = {}
arel_table = self.class.arel_table
attribute_names.each do |name|
attrs[arel_table[name]] = typecasted_attribute_value(name)
end
attrs
end
# Filters the primary keys and readonly attributes from the attribute names.
def attributes_for_update(attribute_names)
attribute_names.reject do |name|
readonly_attribute?(name)
end
end
# Filters out the primary keys, from the attribute names, when the primary
# key is to be generated (e.g. the id attribute has no value).
def attributes_for_create(attribute_names)
attribute_names.reject do |name|
pk_attribute?(name) && id.nil?
end
end
def readonly_attribute?(name)
self.class.readonly_attributes.include?(name)
end
def pk_attribute?(name)
name == self.class.primary_key
end
def typecasted_attribute_value(name)
_read_attribute(name)
end
end
end
|
require 'active_support/core_ext/enumerable'
require 'mutex_m'
require 'thread_safe'
module ActiveRecord
# = Active Record Attribute Methods
module AttributeMethods
extend ActiveSupport::Concern
include ActiveModel::AttributeMethods
included do
initialize_generated_modules
include Read
include Write
include BeforeTypeCast
include Query
include PrimaryKey
include TimeZoneConversion
include Dirty
include Serialization
delegate :column_for_attribute, to: :class
end
AttrNames = Module.new {
def self.set_name_cache(name, value)
const_name = "ATTR_#{name}"
unless const_defined? const_name
const_set const_name, value.dup.freeze
end
end
}
BLACKLISTED_CLASS_METHODS = %w(private public protected)
class AttributeMethodCache
def initialize
@module = Module.new
@method_cache = ThreadSafe::Cache.new
end
def [](name)
@method_cache.compute_if_absent(name) do
safe_name = name.unpack('h*').first
temp_method = "__temp__#{safe_name}"
ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name
@module.module_eval method_body(temp_method, safe_name), __FILE__, __LINE__
@module.instance_method temp_method
end
end
private
# Override this method in the subclasses for method body.
def method_body(method_name, const_name)
raise NotImplementedError, "Subclasses must implement a method_body(method_name, const_name) method."
end
end
module ClassMethods
def inherited(child_class) #:nodoc:
child_class.initialize_generated_modules
super
end
def initialize_generated_modules # :nodoc:
@generated_attribute_methods = Module.new { extend Mutex_m }
@attribute_methods_generated = false
include @generated_attribute_methods
end
# Generates all the attribute related methods for columns in the database
# accessors, mutators and query methods.
def define_attribute_methods # :nodoc:
return false if @attribute_methods_generated
# Use a mutex; we don't want two thread simultaneously trying to define
# attribute methods.
generated_attribute_methods.synchronize do
return false if @attribute_methods_generated
superclass.define_attribute_methods unless self == base_class
super(column_names)
@attribute_methods_generated = true
end
true
end
def undefine_attribute_methods # :nodoc:
generated_attribute_methods.synchronize do
super if @attribute_methods_generated
@attribute_methods_generated = false
end
end
# Raises a <tt>ActiveRecord::DangerousAttributeError</tt> exception when an
# \Active \Record method is defined in the model, otherwise +false+.
#
# class Person < ActiveRecord::Base
# def save
# 'already defined by Active Record'
# end
# end
#
# Person.instance_method_already_implemented?(:save)
# # => ActiveRecord::DangerousAttributeError: save is defined by ActiveRecord
#
# Person.instance_method_already_implemented?(:name)
# # => false
def instance_method_already_implemented?(method_name)
if dangerous_attribute_method?(method_name)
raise DangerousAttributeError, "#{method_name} is defined by Active Record"
end
if superclass == Base
super
else
# If B < A and A defines its own attribute method, then we don't want to overwrite that.
defined = method_defined_within?(method_name, superclass, superclass.generated_attribute_methods)
base_defined = Base.method_defined?(method_name) || Base.private_method_defined?(method_name)
defined && !base_defined || super
end
end
# A method name is 'dangerous' if it is already (re)defined by Active Record, but
# not by any ancestors. (So 'puts' is not dangerous but 'save' is.)
def dangerous_attribute_method?(name) # :nodoc:
method_defined_within?(name, Base)
end
def method_defined_within?(name, klass, superklass = klass.superclass) # :nodoc:
if klass.method_defined?(name) || klass.private_method_defined?(name)
if superklass.method_defined?(name) || superklass.private_method_defined?(name)
klass.instance_method(name).owner != superklass.instance_method(name).owner
else
true
end
else
false
end
end
# A class method is 'dangerous' if it is already (re)defined by Active Record, but
# not by any ancestors. (So 'puts' is not dangerous but 'new' is.)
def dangerous_class_method?(method_name)
BLACKLISTED_CLASS_METHODS.include?(method_name.to_s) || class_method_defined_within?(method_name, Base)
end
def class_method_defined_within?(name, klass, superklass = klass.superclass) # :nodoc
if klass.respond_to?(name, true)
if superklass.respond_to?(name, true)
klass.method(name).owner != superklass.method(name).owner
else
true
end
else
false
end
end
def find_generated_attribute_method(method_name) # :nodoc:
klass = self
until klass == Base
gen_methods = klass.generated_attribute_methods
return gen_methods.instance_method(method_name) if method_defined_within?(method_name, gen_methods, Object)
klass = klass.superclass
end
nil
end
# Returns +true+ if +attribute+ is an attribute method and table exists,
# +false+ otherwise.
#
# class Person < ActiveRecord::Base
# end
#
# Person.attribute_method?('name') # => true
# Person.attribute_method?(:age=) # => true
# Person.attribute_method?(:nothing) # => false
def attribute_method?(attribute)
super || (table_exists? && column_names.include?(attribute.to_s.sub(/=$/, '')))
end
# Returns an array of column names as strings if it's not an abstract class and
# table exists. Otherwise it returns an empty array.
#
# class Person < ActiveRecord::Base
# end
#
# Person.attribute_names
# # => ["id", "created_at", "updated_at", "name", "age"]
def attribute_names
@attribute_names ||= if !abstract_class? && table_exists?
column_names
else
[]
end
end
# Returns the column object for the named attribute.
# Returns a +ActiveRecord::ConnectionAdapters::NullColumn+ if the
# named attribute does not exist.
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.new
# person.column_for_attribute(:name) # the result depends on the ConnectionAdapter
# # => #<ActiveRecord::ConnectionAdapters::SQLite3Column:0x007ff4ab083980 @name="name", @sql_type="varchar(255)", @null=true, ...>
#
# person.column_for_attribute(:nothing)
# # => #<ActiveRecord::ConnectionAdapters::NullColumn:0xXXX @name=nil, @sql_type=nil, @cast_type=#<Type::Value>, ...>
def column_for_attribute(name)
name = name.to_s
columns_hash.fetch(name) do
ConnectionAdapters::NullColumn.new(name)
end
end
end
# If we haven't generated any methods yet, generate them, then
# see if we've created the method we're looking for.
def method_missing(method, *args, &block) # :nodoc:
self.class.define_attribute_methods
if respond_to_without_attributes?(method)
# make sure to invoke the correct attribute method, as we might have gotten here via a `super`
# call in a overwritten attribute method
if attribute_method = self.class.find_generated_attribute_method(method)
# this is probably horribly slow, but should only happen at most once for a given AR class
attribute_method.bind(self).call(*args, &block)
else
return super unless respond_to_missing?(method, true)
send(method, *args, &block)
end
else
super
end
end
# A Person object with a name attribute can ask <tt>person.respond_to?(:name)</tt>,
# <tt>person.respond_to?(:name=)</tt>, and <tt>person.respond_to?(:name?)</tt>
# which will all return +true+. It also define the attribute methods if they have
# not been generated.
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.new
# person.respond_to(:name) # => true
# person.respond_to(:name=) # => true
# person.respond_to(:name?) # => true
# person.respond_to('age') # => true
# person.respond_to('age=') # => true
# person.respond_to('age?') # => true
# person.respond_to(:nothing) # => false
def respond_to?(name, include_private = false)
name = name.to_s
self.class.define_attribute_methods
result = super
# If the result is false the answer is false.
return false unless result
# If the result is true then check for the select case.
# For queries selecting a subset of columns, return false for unselected columns.
# We check defined?(@attributes) not to issue warnings if called on objects that
# have been allocated but not yet initialized.
if defined?(@attributes) && @attributes.any? && self.class.column_names.include?(name)
return has_attribute?(name)
end
return true
end
# Returns +true+ if the given attribute is in the attributes hash, otherwise +false+.
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.new
# person.has_attribute?(:name) # => true
# person.has_attribute?('age') # => true
# person.has_attribute?(:nothing) # => false
def has_attribute?(attr_name)
@attributes.has_key?(attr_name.to_s)
end
# Returns an array of names for the attributes available on this object.
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.new
# person.attribute_names
# # => ["id", "created_at", "updated_at", "name", "age"]
def attribute_names
@attributes.keys
end
# Returns a hash of all the attributes with their names as keys and the values of the attributes as values.
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.create(name: 'Francesco', age: 22)
# person.attributes
# # => {"id"=>3, "created_at"=>Sun, 21 Oct 2012 04:53:04, "updated_at"=>Sun, 21 Oct 2012 04:53:04, "name"=>"Francesco", "age"=>22}
def attributes
attribute_names.each_with_object({}) { |name, attrs|
attrs[name] = read_attribute(name)
}
end
# Returns an <tt>#inspect</tt>-like string for the value of the
# attribute +attr_name+. String attributes are truncated upto 50
# characters, Date and Time attributes are returned in the
# <tt>:db</tt> format, Array attributes are truncated upto 10 values.
# Other attributes return the value of <tt>#inspect</tt> without
# modification.
#
# person = Person.create!(name: 'David Heinemeier Hansson ' * 3)
#
# person.attribute_for_inspect(:name)
# # => "\"David Heinemeier Hansson David Heinemeier Hansson ...\""
#
# person.attribute_for_inspect(:created_at)
# # => "\"2012-10-22 00:15:07\""
#
# person.attribute_for_inspect(:tag_ids)
# # => "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...]"
def attribute_for_inspect(attr_name)
value = read_attribute(attr_name)
if value.is_a?(String) && value.length > 50
"#{value[0, 50]}...".inspect
elsif value.is_a?(Date) || value.is_a?(Time)
%("#{value.to_s(:db)}")
elsif value.is_a?(Array) && value.size > 10
inspected = value.first(10).inspect
%(#{inspected[0...-1]}, ...])
else
value.inspect
end
end
# Returns +true+ if the specified +attribute+ has been set by the user or by a
# database load and is neither +nil+ nor <tt>empty?</tt> (the latter only applies
# to objects that respond to <tt>empty?</tt>, most notably Strings). Otherwise, +false+.
# Note that it always returns +true+ with boolean attributes.
#
# class Task < ActiveRecord::Base
# end
#
# task = Task.new(title: '', is_done: false)
# task.attribute_present?(:title) # => false
# task.attribute_present?(:is_done) # => true
# task.title = 'Buy milk'
# task.is_done = true
# task.attribute_present?(:title) # => true
# task.attribute_present?(:is_done) # => true
def attribute_present?(attribute)
value = read_attribute(attribute)
!value.nil? && !(value.respond_to?(:empty?) && value.empty?)
end
# Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
# "2004-12-12" in a date column is cast to a date object, like Date.new(2004, 12, 12)). It raises
# <tt>ActiveModel::MissingAttributeError</tt> if the identified attribute is missing.
#
# Note: +:id+ is always present.
#
# Alias for the <tt>read_attribute</tt> method.
#
# class Person < ActiveRecord::Base
# belongs_to :organization
# end
#
# person = Person.new(name: 'Francesco', age: '22')
# person[:name] # => "Francesco"
# person[:age] # => 22
#
# person = Person.select('id').first
# person[:name] # => ActiveModel::MissingAttributeError: missing attribute: name
# person[:organization_id] # => ActiveModel::MissingAttributeError: missing attribute: organization_id
def [](attr_name)
read_attribute(attr_name) { |n| missing_attribute(n, caller) }
end
# Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
# (Alias for the protected <tt>write_attribute</tt> method).
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.new
# person[:age] = '22'
# person[:age] # => 22
# person[:age] # => Fixnum
def []=(attr_name, value)
write_attribute(attr_name, value)
end
protected
def clone_attributes # :nodoc:
@attributes.each_with_object({}) do |(name, attr), h|
h[name] = attr.dup
end
end
def clone_attribute_value(reader_method, attribute_name) # :nodoc:
value = send(reader_method, attribute_name)
value.duplicable? ? value.clone : value
rescue TypeError, NoMethodError
value
end
def arel_attributes_with_values_for_create(attribute_names) # :nodoc:
arel_attributes_with_values(attributes_for_create(attribute_names))
end
def arel_attributes_with_values_for_update(attribute_names) # :nodoc:
arel_attributes_with_values(attributes_for_update(attribute_names))
end
def attribute_method?(attr_name) # :nodoc:
# We check defined? because Syck calls respond_to? before actually calling initialize.
defined?(@attributes) && @attributes.include?(attr_name)
end
private
# Returns a Hash of the Arel::Attributes and attribute values that have been
# typecasted for use in an Arel insert/update method.
def arel_attributes_with_values(attribute_names)
attrs = {}
arel_table = self.class.arel_table
attribute_names.each do |name|
attrs[arel_table[name]] = typecasted_attribute_value(name)
end
attrs
end
# Filters the primary keys and readonly attributes from the attribute names.
def attributes_for_update(attribute_names)
attribute_names.reject do |name|
readonly_attribute?(name)
end
end
# Filters out the primary keys, from the attribute names, when the primary
# key is to be generated (e.g. the id attribute has no value).
def attributes_for_create(attribute_names)
attribute_names.reject do |name|
pk_attribute?(name) && id.nil?
end
end
def readonly_attribute?(name)
self.class.readonly_attributes.include?(name)
end
def pk_attribute?(name)
name == self.class.primary_key
end
def typecasted_attribute_value(name)
read_attribute(name)
end
end
end
Remove unused `method_missing` definition
We always define attribute methods in the constructor or in `init_with`.
require 'active_support/core_ext/enumerable'
require 'mutex_m'
require 'thread_safe'
module ActiveRecord
# = Active Record Attribute Methods
module AttributeMethods
extend ActiveSupport::Concern
include ActiveModel::AttributeMethods
included do
initialize_generated_modules
include Read
include Write
include BeforeTypeCast
include Query
include PrimaryKey
include TimeZoneConversion
include Dirty
include Serialization
delegate :column_for_attribute, to: :class
end
AttrNames = Module.new {
def self.set_name_cache(name, value)
const_name = "ATTR_#{name}"
unless const_defined? const_name
const_set const_name, value.dup.freeze
end
end
}
BLACKLISTED_CLASS_METHODS = %w(private public protected)
class AttributeMethodCache
def initialize
@module = Module.new
@method_cache = ThreadSafe::Cache.new
end
def [](name)
@method_cache.compute_if_absent(name) do
safe_name = name.unpack('h*').first
temp_method = "__temp__#{safe_name}"
ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name
@module.module_eval method_body(temp_method, safe_name), __FILE__, __LINE__
@module.instance_method temp_method
end
end
private
# Override this method in the subclasses for method body.
def method_body(method_name, const_name)
raise NotImplementedError, "Subclasses must implement a method_body(method_name, const_name) method."
end
end
module ClassMethods
def inherited(child_class) #:nodoc:
child_class.initialize_generated_modules
super
end
def initialize_generated_modules # :nodoc:
@generated_attribute_methods = Module.new { extend Mutex_m }
@attribute_methods_generated = false
include @generated_attribute_methods
end
# Generates all the attribute related methods for columns in the database
# accessors, mutators and query methods.
def define_attribute_methods # :nodoc:
return false if @attribute_methods_generated
# Use a mutex; we don't want two thread simultaneously trying to define
# attribute methods.
generated_attribute_methods.synchronize do
return false if @attribute_methods_generated
superclass.define_attribute_methods unless self == base_class
super(column_names)
@attribute_methods_generated = true
end
true
end
def undefine_attribute_methods # :nodoc:
generated_attribute_methods.synchronize do
super if @attribute_methods_generated
@attribute_methods_generated = false
end
end
# Raises a <tt>ActiveRecord::DangerousAttributeError</tt> exception when an
# \Active \Record method is defined in the model, otherwise +false+.
#
# class Person < ActiveRecord::Base
# def save
# 'already defined by Active Record'
# end
# end
#
# Person.instance_method_already_implemented?(:save)
# # => ActiveRecord::DangerousAttributeError: save is defined by ActiveRecord
#
# Person.instance_method_already_implemented?(:name)
# # => false
def instance_method_already_implemented?(method_name)
if dangerous_attribute_method?(method_name)
raise DangerousAttributeError, "#{method_name} is defined by Active Record"
end
if superclass == Base
super
else
# If B < A and A defines its own attribute method, then we don't want to overwrite that.
defined = method_defined_within?(method_name, superclass, superclass.generated_attribute_methods)
base_defined = Base.method_defined?(method_name) || Base.private_method_defined?(method_name)
defined && !base_defined || super
end
end
# A method name is 'dangerous' if it is already (re)defined by Active Record, but
# not by any ancestors. (So 'puts' is not dangerous but 'save' is.)
def dangerous_attribute_method?(name) # :nodoc:
method_defined_within?(name, Base)
end
def method_defined_within?(name, klass, superklass = klass.superclass) # :nodoc:
if klass.method_defined?(name) || klass.private_method_defined?(name)
if superklass.method_defined?(name) || superklass.private_method_defined?(name)
klass.instance_method(name).owner != superklass.instance_method(name).owner
else
true
end
else
false
end
end
# A class method is 'dangerous' if it is already (re)defined by Active Record, but
# not by any ancestors. (So 'puts' is not dangerous but 'new' is.)
def dangerous_class_method?(method_name)
BLACKLISTED_CLASS_METHODS.include?(method_name.to_s) || class_method_defined_within?(method_name, Base)
end
def class_method_defined_within?(name, klass, superklass = klass.superclass) # :nodoc
if klass.respond_to?(name, true)
if superklass.respond_to?(name, true)
klass.method(name).owner != superklass.method(name).owner
else
true
end
else
false
end
end
# Returns +true+ if +attribute+ is an attribute method and table exists,
# +false+ otherwise.
#
# class Person < ActiveRecord::Base
# end
#
# Person.attribute_method?('name') # => true
# Person.attribute_method?(:age=) # => true
# Person.attribute_method?(:nothing) # => false
def attribute_method?(attribute)
super || (table_exists? && column_names.include?(attribute.to_s.sub(/=$/, '')))
end
# Returns an array of column names as strings if it's not an abstract class and
# table exists. Otherwise it returns an empty array.
#
# class Person < ActiveRecord::Base
# end
#
# Person.attribute_names
# # => ["id", "created_at", "updated_at", "name", "age"]
def attribute_names
@attribute_names ||= if !abstract_class? && table_exists?
column_names
else
[]
end
end
# Returns the column object for the named attribute.
# Returns a +ActiveRecord::ConnectionAdapters::NullColumn+ if the
# named attribute does not exist.
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.new
# person.column_for_attribute(:name) # the result depends on the ConnectionAdapter
# # => #<ActiveRecord::ConnectionAdapters::SQLite3Column:0x007ff4ab083980 @name="name", @sql_type="varchar(255)", @null=true, ...>
#
# person.column_for_attribute(:nothing)
# # => #<ActiveRecord::ConnectionAdapters::NullColumn:0xXXX @name=nil, @sql_type=nil, @cast_type=#<Type::Value>, ...>
def column_for_attribute(name)
name = name.to_s
columns_hash.fetch(name) do
ConnectionAdapters::NullColumn.new(name)
end
end
end
# A Person object with a name attribute can ask <tt>person.respond_to?(:name)</tt>,
# <tt>person.respond_to?(:name=)</tt>, and <tt>person.respond_to?(:name?)</tt>
# which will all return +true+. It also define the attribute methods if they have
# not been generated.
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.new
# person.respond_to(:name) # => true
# person.respond_to(:name=) # => true
# person.respond_to(:name?) # => true
# person.respond_to('age') # => true
# person.respond_to('age=') # => true
# person.respond_to('age?') # => true
# person.respond_to(:nothing) # => false
def respond_to?(name, include_private = false)
return false unless super
name = name.to_s
# If the result is true then check for the select case.
# For queries selecting a subset of columns, return false for unselected columns.
# We check defined?(@attributes) not to issue warnings if called on objects that
# have been allocated but not yet initialized.
if defined?(@attributes) && @attributes.any? && self.class.column_names.include?(name)
return has_attribute?(name)
end
return true
end
# Returns +true+ if the given attribute is in the attributes hash, otherwise +false+.
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.new
# person.has_attribute?(:name) # => true
# person.has_attribute?('age') # => true
# person.has_attribute?(:nothing) # => false
def has_attribute?(attr_name)
@attributes.has_key?(attr_name.to_s)
end
# Returns an array of names for the attributes available on this object.
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.new
# person.attribute_names
# # => ["id", "created_at", "updated_at", "name", "age"]
def attribute_names
@attributes.keys
end
# Returns a hash of all the attributes with their names as keys and the values of the attributes as values.
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.create(name: 'Francesco', age: 22)
# person.attributes
# # => {"id"=>3, "created_at"=>Sun, 21 Oct 2012 04:53:04, "updated_at"=>Sun, 21 Oct 2012 04:53:04, "name"=>"Francesco", "age"=>22}
def attributes
attribute_names.each_with_object({}) { |name, attrs|
attrs[name] = read_attribute(name)
}
end
# Returns an <tt>#inspect</tt>-like string for the value of the
# attribute +attr_name+. String attributes are truncated upto 50
# characters, Date and Time attributes are returned in the
# <tt>:db</tt> format, Array attributes are truncated upto 10 values.
# Other attributes return the value of <tt>#inspect</tt> without
# modification.
#
# person = Person.create!(name: 'David Heinemeier Hansson ' * 3)
#
# person.attribute_for_inspect(:name)
# # => "\"David Heinemeier Hansson David Heinemeier Hansson ...\""
#
# person.attribute_for_inspect(:created_at)
# # => "\"2012-10-22 00:15:07\""
#
# person.attribute_for_inspect(:tag_ids)
# # => "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...]"
def attribute_for_inspect(attr_name)
value = read_attribute(attr_name)
if value.is_a?(String) && value.length > 50
"#{value[0, 50]}...".inspect
elsif value.is_a?(Date) || value.is_a?(Time)
%("#{value.to_s(:db)}")
elsif value.is_a?(Array) && value.size > 10
inspected = value.first(10).inspect
%(#{inspected[0...-1]}, ...])
else
value.inspect
end
end
# Returns +true+ if the specified +attribute+ has been set by the user or by a
# database load and is neither +nil+ nor <tt>empty?</tt> (the latter only applies
# to objects that respond to <tt>empty?</tt>, most notably Strings). Otherwise, +false+.
# Note that it always returns +true+ with boolean attributes.
#
# class Task < ActiveRecord::Base
# end
#
# task = Task.new(title: '', is_done: false)
# task.attribute_present?(:title) # => false
# task.attribute_present?(:is_done) # => true
# task.title = 'Buy milk'
# task.is_done = true
# task.attribute_present?(:title) # => true
# task.attribute_present?(:is_done) # => true
def attribute_present?(attribute)
value = read_attribute(attribute)
!value.nil? && !(value.respond_to?(:empty?) && value.empty?)
end
# Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
# "2004-12-12" in a date column is cast to a date object, like Date.new(2004, 12, 12)). It raises
# <tt>ActiveModel::MissingAttributeError</tt> if the identified attribute is missing.
#
# Note: +:id+ is always present.
#
# Alias for the <tt>read_attribute</tt> method.
#
# class Person < ActiveRecord::Base
# belongs_to :organization
# end
#
# person = Person.new(name: 'Francesco', age: '22')
# person[:name] # => "Francesco"
# person[:age] # => 22
#
# person = Person.select('id').first
# person[:name] # => ActiveModel::MissingAttributeError: missing attribute: name
# person[:organization_id] # => ActiveModel::MissingAttributeError: missing attribute: organization_id
def [](attr_name)
read_attribute(attr_name) { |n| missing_attribute(n, caller) }
end
# Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
# (Alias for the protected <tt>write_attribute</tt> method).
#
# class Person < ActiveRecord::Base
# end
#
# person = Person.new
# person[:age] = '22'
# person[:age] # => 22
# person[:age] # => Fixnum
def []=(attr_name, value)
write_attribute(attr_name, value)
end
protected
def clone_attributes # :nodoc:
@attributes.each_with_object({}) do |(name, attr), h|
h[name] = attr.dup
end
end
def clone_attribute_value(reader_method, attribute_name) # :nodoc:
value = send(reader_method, attribute_name)
value.duplicable? ? value.clone : value
rescue TypeError, NoMethodError
value
end
def arel_attributes_with_values_for_create(attribute_names) # :nodoc:
arel_attributes_with_values(attributes_for_create(attribute_names))
end
def arel_attributes_with_values_for_update(attribute_names) # :nodoc:
arel_attributes_with_values(attributes_for_update(attribute_names))
end
def attribute_method?(attr_name) # :nodoc:
# We check defined? because Syck calls respond_to? before actually calling initialize.
defined?(@attributes) && @attributes.include?(attr_name)
end
private
# Returns a Hash of the Arel::Attributes and attribute values that have been
# typecasted for use in an Arel insert/update method.
def arel_attributes_with_values(attribute_names)
attrs = {}
arel_table = self.class.arel_table
attribute_names.each do |name|
attrs[arel_table[name]] = typecasted_attribute_value(name)
end
attrs
end
# Filters the primary keys and readonly attributes from the attribute names.
def attributes_for_update(attribute_names)
attribute_names.reject do |name|
readonly_attribute?(name)
end
end
# Filters out the primary keys, from the attribute names, when the primary
# key is to be generated (e.g. the id attribute has no value).
def attributes_for_create(attribute_names)
attribute_names.reject do |name|
pk_attribute?(name) && id.nil?
end
end
def readonly_attribute?(name)
self.class.readonly_attributes.include?(name)
end
def pk_attribute?(name)
name == self.class.primary_key
end
def typecasted_attribute_value(name)
read_attribute(name)
end
end
end
|
require 'cases/helper'
require 'models/post'
require 'models/comment'
module ActiveRecord
class DelegationTest < ActiveRecord::TestCase
fixtures :posts
def assert_responds(target, method)
assert target.respond_to?(method)
assert_nothing_raised do
method_arity = target.to_a.method(method).arity
if method_arity.zero?
target.send(method)
elsif method_arity < 0
if method == :shuffle!
target.send(method)
else
target.send(method, 1)
end
else
raise NotImplementedError
end
end
end
end
class DelegationAssociationTest < DelegationTest
def target
Post.first.comments
end
[:map, :collect].each do |method|
test "##{method} is delgated" do
assert_responds(target, method)
assert_equal(target.pluck(:body), target.send(method) {|post| post.body })
end
test "##{method}! is not delgated" do
assert_deprecated do
assert_responds(target, "#{method}!")
end
end
end
[:compact!, :flatten!, :reject!, :reverse!, :rotate!,
:shuffle!, :slice!, :sort!, :sort_by!].each do |method|
test "##{method} delegation is deprecated" do
assert_deprecated do
assert_responds(target, method)
end
end
end
[:select!, :uniq!].each do |method|
test "##{method} is implemented" do
assert_responds(target, method)
end
end
end
class DelegationRelationTest < DelegationTest
def target
Comment.where.not(body: nil)
end
[:map, :collect].each do |method|
test "##{method} is delgated" do
assert_responds(target, method)
assert_equal(target.pluck(:body), target.send(method) {|post| post.body })
end
test "##{method}! is not delgated" do
assert_deprecated do
assert_responds(target, "#{method}!")
end
end
end
[:compact!, :flatten!, :reject!, :reverse!, :rotate!,
:shuffle!, :slice!, :sort!, :sort_by!].each do |method|
test "##{method} delegation is deprecated" do
assert_deprecated do
assert_responds(target, method)
end
end
end
[:select!, :uniq!].each do |method|
test "##{method} is triggers an immutable error" do
assert_raises ActiveRecord::ImmutableRelation do
assert_responds(target, method)
end
end
end
end
end
A tiny grammatical fix
[ci skip]
require 'cases/helper'
require 'models/post'
require 'models/comment'
module ActiveRecord
class DelegationTest < ActiveRecord::TestCase
fixtures :posts
def assert_responds(target, method)
assert target.respond_to?(method)
assert_nothing_raised do
method_arity = target.to_a.method(method).arity
if method_arity.zero?
target.send(method)
elsif method_arity < 0
if method == :shuffle!
target.send(method)
else
target.send(method, 1)
end
else
raise NotImplementedError
end
end
end
end
class DelegationAssociationTest < DelegationTest
def target
Post.first.comments
end
[:map, :collect].each do |method|
test "##{method} is delgated" do
assert_responds(target, method)
assert_equal(target.pluck(:body), target.send(method) {|post| post.body })
end
test "##{method}! is not delgated" do
assert_deprecated do
assert_responds(target, "#{method}!")
end
end
end
[:compact!, :flatten!, :reject!, :reverse!, :rotate!,
:shuffle!, :slice!, :sort!, :sort_by!].each do |method|
test "##{method} delegation is deprecated" do
assert_deprecated do
assert_responds(target, method)
end
end
end
[:select!, :uniq!].each do |method|
test "##{method} is implemented" do
assert_responds(target, method)
end
end
end
class DelegationRelationTest < DelegationTest
def target
Comment.where.not(body: nil)
end
[:map, :collect].each do |method|
test "##{method} is delgated" do
assert_responds(target, method)
assert_equal(target.pluck(:body), target.send(method) {|post| post.body })
end
test "##{method}! is not delgated" do
assert_deprecated do
assert_responds(target, "#{method}!")
end
end
end
[:compact!, :flatten!, :reject!, :reverse!, :rotate!,
:shuffle!, :slice!, :sort!, :sort_by!].each do |method|
test "##{method} delegation is deprecated" do
assert_deprecated do
assert_responds(target, method)
end
end
end
[:select!, :uniq!].each do |method|
test "##{method} triggers an immutable error" do
assert_raises ActiveRecord::ImmutableRelation do
assert_responds(target, method)
end
end
end
end
end
|
module ActiveSupport
# Usually key value pairs are handled something like this:
#
# h = {}
# h[:boy] = 'John'
# h[:girl] = 'Mary'
# h[:boy] # => 'John'
# h[:girl] # => 'Mary'
#
# Using +OrderedOptions+, the above code could be reduced to:
#
# h = ActiveSupport::OrderedOptions.new
# h.boy = 'John'
# h.girl = 'Mary'
# h.boy # => 'John'
# h.girl # => 'Mary'
class OrderedOptions < Hash
alias_method :_get, :[] # preserve the original #[] method
protected :_get # make it protected
def []=(key, value)
super(key.to_sym, value)
end
def [](key)
super(key.to_sym)
end
def method_missing(name, *args)
name_string = name.to_s
if name_string.chomp!('=')
self[name_string] = args.first
else
self[name]
end
end
def respond_to_missing?(name, include_private)
true
end
end
class InheritableOptions < OrderedOptions
def initialize(parent = nil)
if parent.kind_of?(OrderedOptions)
# use the faster _get when dealing with OrderedOptions
super() { |h,k| parent._get(k) }
elsif parent
super() { |h,k| parent[k] }
else
super()
end
end
def inheritable_copy
self.class.new(self)
end
end
end
added docs for InheritedOptions class [ci skip]
module ActiveSupport
# Usually key value pairs are handled something like this:
#
# h = {}
# h[:boy] = 'John'
# h[:girl] = 'Mary'
# h[:boy] # => 'John'
# h[:girl] # => 'Mary'
#
# Using +OrderedOptions+, the above code could be reduced to:
#
# h = ActiveSupport::OrderedOptions.new
# h.boy = 'John'
# h.girl = 'Mary'
# h.boy # => 'John'
# h.girl # => 'Mary'
class OrderedOptions < Hash
alias_method :_get, :[] # preserve the original #[] method
protected :_get # make it protected
def []=(key, value)
super(key.to_sym, value)
end
def [](key)
super(key.to_sym)
end
def method_missing(name, *args)
name_string = name.to_s
if name_string.chomp!('=')
self[name_string] = args.first
else
self[name]
end
end
def respond_to_missing?(name, include_private)
true
end
end
# +InheritableOptions+ provides a constructor to build an +OrderedOptions+
# hash inherited from the another hash.
#
# Use this if you already have some hash and you want to create a new one based on it.
#
# h = ActiveSupport::InheritableOptions.new({ girl: 'Mary', boy: 'John' })
# h.girl # => 'Mary'
# h.boy # => 'John'
class InheritableOptions < OrderedOptions
def initialize(parent = nil)
if parent.kind_of?(OrderedOptions)
# use the faster _get when dealing with OrderedOptions
super() { |h,k| parent._get(k) }
elsif parent
super() { |h,k| parent[k] }
else
super()
end
end
def inheritable_copy
self.class.new(self)
end
end
end
|
add minitest for redis_cache adapter
require 'test_helper'
require 'flipper/adapters/memory'
require 'flipper/adapters/redis_cache'
class DalliTest < MiniTest::Test
prepend Flipper::Test::SharedAdapterTests
def setup
url = ENV.fetch('BOXEN_REDIS_URL', 'localhost:6379')
@cache = Redis.new({url: url}).tap { |c| c.flushdb }
memory_adapter = Flipper::Adapters::Memory.new
@adapter = Flipper::Adapters::RedisCache.new(memory_adapter, @cache)
end
def teardown
@cache.flushdb
end
end
|
require './rooms.rb'
class World
attr_reader :history
def initialize
@room = Start.new
@history = []
end
def to_s
@room.to_s
end
def do(action)
if action == :q
throw :quit
end
# change room?
if @room.exits.has_key? action
go(@room.exits[action])
end
end
private
def go(r)
if r.is_a? Enumerable
get_next_room(r)
end
raise "World.go requires a Room" unless r.is_a? Room.class
@room = r.new
@room.on_enter
@history.push @room
end
# enemerates over room history to find next room
def get_next_room(r)
i = 0
# count previous r's visited, todo fixme
@history.reverse_each do |h|
if h.class != r[0]
break
end
i += 1
end
if i >= r.count
throw :quit # todo modify methods
end
r = r[i]
end
end
Fix World.get_next_room
require './rooms.rb'
class World
attr_reader :history
def initialize
@room = Start.new
@history = []
end
def to_s
@room.to_s
end
def do(action)
if action == :q
throw :quit
end
# change room?
if @room.exits.has_key? action
go(@room.exits[action])
end
end
private
def go(r)
if r.is_a? Enumerable
r = get_next_room(r)
end
raise "World.go requires a Room" unless r.is_a? Room.class
@room = r.new
@room.on_enter
@history.push @room
end
# enemerates over room history to find next room
def get_next_room(rooms)
r = rooms.shift
# count previous r's visited, todo fixme
@history.reverse_each do |h|
if h.class != r
break
end
r = rooms.shift
end
if not r
throw :quit
end
# todo modify methods
r
end
end
|
#!/usr/bin/env ruby
def mem(pid); `ps p #{pid} -o rss`.split.last.to_i; end
t = Time.now
pid = Process.spawn(*ARGV.to_a)
mm = 0
Thread.new do
mm = mem(pid)
while true
sleep 0.3
m = mem(pid)
mm = m if m > mm
end
end
Process.waitall
STDERR.puts "== %.2fs, %.1fMb ==" % [Time.now - t, mm / 1024.0]
Use monotonic time for measuring wall-clock time
#!/usr/bin/env ruby
def mem(pid); `ps p #{pid} -o rss`.split.last.to_i; end
t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
pid = Process.spawn(*ARGV.to_a)
mm = 0
Thread.new do
mm = mem(pid)
while true
sleep 0.3
m = mem(pid)
mm = m if m > mm
end
end
Process.waitall
t1 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
STDERR.puts "== %.2fs, %.1fMb ==" % [t1 - t0, mm / 1024.0]
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'parse_sberbank_html/version'
Gem::Specification.new do |spec|
spec.name = "parse_sberbank_html"
spec.version = ParseSberbankHtml::VERSION
spec.authors = ["Nikita B. Zuev"]
spec.email = ["nikitazu@gmail.com"]
spec.summary = %q{Parses Sberbank Online html}
spec.description = %q{Parses Sberbank Online html}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "nokogiri", "~> 1.6"
spec.add_development_dependency "bundler", "~> 1.6"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 2.13"
end
More specific nokogiri version
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'parse_sberbank_html/version'
Gem::Specification.new do |spec|
spec.name = "parse_sberbank_html"
spec.version = ParseSberbankHtml::VERSION
spec.authors = ["Nikita B. Zuev"]
spec.email = ["nikitazu@gmail.com"]
spec.summary = %q{Parses Sberbank Online html}
spec.description = %q{Parses Sberbank Online html}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "nokogiri", "~> 1.6.3"
spec.add_development_dependency "bundler", "~> 1.6"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 2.13"
end
|
#Exception Notifier.
# Note its not much use without the action_mailer.rb template!
plugin 'exception_notifier', :git => 'git://github.com/rails/exception_notification.git'
gsub_file("app/controllers/application_controller.rb", /class ApplicationController < ActionController::Base/mi) do
"class ApplicationController < ActionController::Base\n include ExceptionNotifiable"
end
app_name = ENV['_APP']
domain = ENV['_APP_DOMAIN']
recipients = ENV['_APP_EMAILS']
if recipients.nil?
recipients = ask(" Enter your exception notification recpients (space separated list) : ")
end
file '/config/exception.yml', <<-EOS.gsub(/^ /, '')
development:
recipients: #{recipients}
sender: "Application Error <dev.app.error@#{domain}>"
prefix: "[#{app_name} Devel] "
test:
recipients: #{recipients}
sender: "Application Error <test.app.error@#{domain}>"
prefix: "[#{app_name} Test] "
staging:
recipients: #{recipients}
sender: "Application Error <staging.app.error@#{domain}>"
prefix: "[#{app_name} Staging] "
production:
recipients: #{recipients}
sender: "Application Error <prod.app.error@#{domain}>"
prefix: "[#{app_name} Prod] "
EOS
initializer "exception_notifier.rb", <<-EOS.gsub(/^ /, '')
env = ENV['RAILS_ENV'] || RAILS_ENV
EXCEPTION_NOTIFIER = YAML.load_file(RAILS_ROOT + '/config/exception.yml')[env]
ExceptionNotifier.exception_recipients = EXCEPTION_NOTIFIER['recipients']
ExceptionNotifier.sender_address = EXCEPTION_NOTIFIER['sender']
ExceptionNotifier.email_prefix = EXCEPTION_NOTIFIER['prefix']
EOS
add cucumber to exception notif config
#Exception Notifier.
# Note its not much use without the action_mailer.rb template!
plugin 'exception_notifier', :git => 'git://github.com/rails/exception_notification.git'
gsub_file("app/controllers/application_controller.rb", /class ApplicationController < ActionController::Base/mi) do
"class ApplicationController < ActionController::Base\n include ExceptionNotifiable"
end
app_name = ENV['_APP']
domain = ENV['_APP_DOMAIN']
recipients = ENV['_APP_EMAILS']
if recipients.nil?
recipients = ask(" Enter your exception notification recpients (space separated list) : ")
end
file '/config/exception.yml', <<-EOS.gsub(/^ /, '')
development:
recipients: #{recipients}
sender: "Application Error <dev.app.error@#{domain}>"
prefix: "[#{app_name} Devel] "
test:
recipients: #{recipients}
sender: "Application Error <test.app.error@#{domain}>"
prefix: "[#{app_name} Test] "
cucumber:
recipients: #{recipients}
sender: "Application Error <test.app.error@#{domain}>"
prefix: "[#{app_name} Test] "
staging:
recipients: #{recipients}
sender: "Application Error <staging.app.error@#{domain}>"
prefix: "[#{app_name} Staging] "
production:
recipients: #{recipients}
sender: "Application Error <prod.app.error@#{domain}>"
prefix: "[#{app_name} Prod] "
EOS
initializer "exception_notifier.rb", <<-EOS.gsub(/^ /, '')
env = ENV['RAILS_ENV'] || RAILS_ENV
EXCEPTION_NOTIFIER = YAML.load_file(RAILS_ROOT + '/config/exception.yml')[env]
ExceptionNotifier.exception_recipients = EXCEPTION_NOTIFIER['recipients']
ExceptionNotifier.sender_address = EXCEPTION_NOTIFIER['sender']
ExceptionNotifier.email_prefix = EXCEPTION_NOTIFIER['prefix']
EOS
|
test/cli: Add tests for `kbsecret sessions`
# frozen_string_literal: true
require "helpers"
# Tests for KBSecret::CLI::Command::Sessions
class KBSecretCommandSessionsTest < Minitest::Test
include Helpers
include Helpers::CLI
def test_sessions_help
sessions_helps = [
%w[sessions --help],
%w[sessions -h],
%w[help sessions],
]
sessions_helps.each do |sessions_help|
stdout, = kbsecret(*sessions_help)
assert_match(/Usage:/, stdout)
end
end
def test_sessions_outputs_list
stdout, = kbsecret "sessions"
stdout.lines.each do |session|
session.chomp!
assert KBSecret::Config.session?(session)
end
end
def test_sessions_outputs_all
stdout, = kbsecret "sessions", "-a"
user_team_count = stdout.lines.count { |line| line =~ /(Team|Users):/ }
secrets_root_count = stdout.lines.count { |lines| lines =~ /Secrets root:/ }
assert_equal KBSecret::Config.session_labels.size, user_team_count.size
assert_equal KBSecret::Config.session_labels.size, secrets_root_count.size
end
end
|
Pod::Spec.new do |s|
s.name = 'CargoBay'
s.version = '2.0.2'
s.license = 'MIT'
s.summary = 'The Essential StoreKit Companion.'
s.homepage = 'https://github.com/mattt/CargoBay'
s.social_media_url = 'https://twitter.com/mattt'
s.authors = { 'Mattt Thompson' => 'm@mattt.me' }
s.source = { :git => 'https://github.com/mattt/CargoBay.git', :tag => '2.0.2' }
s.source_files = 'CargoBay'
s.requires_arc = true
s.ios.deployment_target = '6.0'
s.osx.deployment_target = '10.8'
s.frameworks = 'StoreKit', 'Security'
s.dependency 'AFNetworking', '~> 2.0'
end
Bumping version to 2.0.3
Pod::Spec.new do |s|
s.name = 'CargoBay'
s.version = '2.0.3'
s.license = 'MIT'
s.summary = 'The Essential StoreKit Companion.'
s.homepage = 'https://github.com/mattt/CargoBay'
s.social_media_url = 'https://twitter.com/mattt'
s.authors = { 'Mattt Thompson' => 'm@mattt.me' }
s.source = { :git => 'https://github.com/mattt/CargoBay.git', :tag => '2.0.3' }
s.source_files = 'CargoBay'
s.requires_arc = true
s.ios.deployment_target = '6.0'
s.osx.deployment_target = '10.8'
s.frameworks = 'StoreKit', 'Security'
s.dependency 'AFNetworking', '~> 2.1'
end
|
class Airfile < Cask
version '2.2.0'
sha256 '49328695c65ce15e034956dc556c3c4770436ede86ad1dff1fd1da3d216b08a3'
url "https://s3.amazonaws.com/airfile-static/__apps__/airfile/AirFile-#{version}.zip"
homepage 'http://airfileapp.tumblr.com/'
link 'AirFile.app'
end
use app instead of link in airfile.rb
class Airfile < Cask
version '2.2.0'
sha256 '49328695c65ce15e034956dc556c3c4770436ede86ad1dff1fd1da3d216b08a3'
url "https://s3.amazonaws.com/airfile-static/__apps__/airfile/AirFile-#{version}.zip"
homepage 'http://airfileapp.tumblr.com/'
app 'AirFile.app'
end
|
# encoding: UTF-8
cask :v1 => 'aliedit' do
version :latest
sha256 :no_check
# todo enable name
# name '支付宝控件'
url 'https://d.alipayobjects.com/sec/edit/wkaliedit.dmg'
homepage 'https://110.alipay.com/sc/aliedit/intro.htm'
license :closed
pkg 'installer.pkg'
uninstall :pkgutil => 'com.alipay.www',
:launchctl => [
'com.alipay.DispatcherService',
'com.alipay.refresher.agent',
],
:delete => [
'/Library/Application Support/Alipay',
'/Library/Google/Chrome/NativeMessagingHosts/com.alipay.cert.json',
'/Library/Google/Chrome/NativeMessagingHosts/com.alipay.edit.json',
'/Library/Google/Chrome/NativeMessagingHosts/com.alipay.security.json',
'/Library/LaunchDaemons/com.alipay.DispatcherService.plist',
# the files under ~/Library are installed by the pkg, and logically should be removed by uninstall
Pathname.new(File.expand_path('~')).join('Library/Alipay'),
Pathname.new(File.expand_path('~')).join('Internet Plug-Ins/aliedit.plugin'),
Pathname.new(File.expand_path('~')).join('Internet Plug-Ins/npalicdo.plugin'),
Pathname.new(File.expand_path('~')).join('LaunchAgents/com.alipay.refresher.plist'),
]
end
enable name stanza in aliedit
# encoding: UTF-8
cask :v1 => 'aliedit' do
version :latest
sha256 :no_check
name '支付宝控件'
url 'https://d.alipayobjects.com/sec/edit/wkaliedit.dmg'
homepage 'https://110.alipay.com/sc/aliedit/intro.htm'
license :closed
pkg 'installer.pkg'
uninstall :pkgutil => 'com.alipay.www',
:launchctl => [
'com.alipay.DispatcherService',
'com.alipay.refresher.agent',
],
:delete => [
'/Library/Application Support/Alipay',
'/Library/Google/Chrome/NativeMessagingHosts/com.alipay.cert.json',
'/Library/Google/Chrome/NativeMessagingHosts/com.alipay.edit.json',
'/Library/Google/Chrome/NativeMessagingHosts/com.alipay.security.json',
'/Library/LaunchDaemons/com.alipay.DispatcherService.plist',
# the files under ~/Library are installed by the pkg, and logically should be removed by uninstall
Pathname.new(File.expand_path('~')).join('Library/Alipay'),
Pathname.new(File.expand_path('~')).join('Internet Plug-Ins/aliedit.plugin'),
Pathname.new(File.expand_path('~')).join('Internet Plug-Ins/npalicdo.plugin'),
Pathname.new(File.expand_path('~')).join('LaunchAgents/com.alipay.refresher.plist'),
]
end
|
cask 'alt-tab' do
version '3.23.1'
sha256 '72db485e12a93bd354799d5854f3c68220009587c504f4dbf8fd982953ccfce3'
url "https://github.com/lwouis/alt-tab-macos/releases/download/v#{version}/AltTab-#{version}.zip"
appcast 'https://github.com/lwouis/alt-tab-macos/releases.atom'
name 'alt-tab'
homepage 'https://github.com/lwouis/alt-tab-macos'
auto_updates true
depends_on macos: '>= :sierra'
app 'AltTab.app'
uninstall quit: 'com.lwouis.alt-tab-macos'
zap trash: [
'~/Library/Caches/com.lwouis.alt-tab-macos',
'~/Library/Cookies/com.lwouis.alt-tab-macos.binarycookies',
'~/Library/Preferences/com.lwouis.alt-tab-macos.plist',
]
end
Update alt-tab from 3.23.1 to 3.23.2 (#82993)
Co-authored-by: Travis CI <e6cc0fb2b8dad4110ef62e9a33e5a8aa4e0f86d7@Traviss-Mac.local>
cask 'alt-tab' do
version '3.23.2'
sha256 '6f54e391f5b0d8eecc7e8b3aa621caf33c6f28ff46052a29e57f4248e1f77685'
url "https://github.com/lwouis/alt-tab-macos/releases/download/v#{version}/AltTab-#{version}.zip"
appcast 'https://github.com/lwouis/alt-tab-macos/releases.atom'
name 'alt-tab'
homepage 'https://github.com/lwouis/alt-tab-macos'
auto_updates true
depends_on macos: '>= :sierra'
app 'AltTab.app'
uninstall quit: 'com.lwouis.alt-tab-macos'
zap trash: [
'~/Library/Caches/com.lwouis.alt-tab-macos',
'~/Library/Cookies/com.lwouis.alt-tab-macos.binarycookies',
'~/Library/Preferences/com.lwouis.alt-tab-macos.plist',
]
end
|
cask 'aptible' do
version '0.10.0+20170516175454,141'
sha256 'd349560c9d42c64e0e5630f6f532a2d34b77d31db7bac78d8a9aed9cfa79d081'
# omnibus-aptible-toolbelt.s3.amazonaws.com was verified as official when first introduced to the cask
url "https://omnibus-aptible-toolbelt.s3.amazonaws.com/aptible/omnibus-aptible-toolbelt/master/#{version.after_comma}/pkg/aptible-toolbelt-#{version.before_comma.sub('+', '%2B')}-mac-os-x.10.11.6-1.pkg"
name 'Aptible Toolbelt'
homepage 'https://www.aptible.com/support/toolbelt/'
pkg "aptible-toolbelt-#{version.before_comma}-mac-os-x.10.11.6-1.pkg"
uninstall pkgutil: 'com.aptible.toolbelt'
end
Update aptible to 0.11.0 (#35008)
cask 'aptible' do
version '0.11.0+20170530075306,143'
sha256 '41b1fdd464c049105e0fadfc18b6041aa88ba17ab903c84280e584c74e9ecea1'
# omnibus-aptible-toolbelt.s3.amazonaws.com was verified as official when first introduced to the cask
url "https://omnibus-aptible-toolbelt.s3.amazonaws.com/aptible/omnibus-aptible-toolbelt/master/#{version.after_comma}/pkg/aptible-toolbelt-#{version.before_comma.sub('+', '%2B')}-mac-os-x.10.11.6-1.pkg"
name 'Aptible Toolbelt'
homepage 'https://www.aptible.com/support/toolbelt/'
pkg "aptible-toolbelt-#{version.before_comma}-mac-os-x.10.11.6-1.pkg"
uninstall pkgutil: 'com.aptible.toolbelt'
end
|
cask 'arduino' do
version '1.8.7'
sha256 'bc5fae3e0b54f000d335d93f2e6da66fc8549def015e3b136d34a10e171c1501'
url "https://downloads.arduino.cc/arduino-#{version}-macosx.zip"
appcast 'https://www.arduino.cc/en/Main/ReleaseNotes'
name 'Arduino'
homepage 'https://www.arduino.cc/'
app 'Arduino.app'
binary "#{appdir}/Arduino.app/Contents/Java/arduino-builder"
zap trash: [
'~/Library/Arduino15',
'~/Library/Preferences/cc.arduino.Arduino.plist',
]
caveats do
depends_on_java
end
end
Bump Arduino IDE to v.1.8.8 (#55824)
This commit bumps the Arduino IDE to v.1.8.8
Release notes: https://www.arduino.cc/en/Main/ReleaseNotes
Official download URL: https://www.arduino.cc/en/Main/Software
<!-- If there’s a checkbox you can’t complete for any reason, that's okay, just explain in detail why you weren’t able to do so. -->
After making all changes to the cask:
- [x] `brew cask audit --download {{cask_file}}` is error-free.
- [x] `brew cask style --fix {{cask_file}}` reports no offenses.
- [x] The commit message includes the cask’s name and version.
- [x] The submission is for [a stable version](https://github.com/Homebrew/homebrew-cask/blob/master/doc/development/adding_a_cask.md#finding-a-home-for-your-cask) or [documented exception](https://github.com/Homebrew/homebrew-cask/blob/master/doc/development/adding_a_cask.md#but-there-is-no-stable-version).
cask 'arduino' do
version '1.8.8'
sha256 'b1628a0ca7ee5c8d75ee98cfee3d29f61c03d180894ff12636abe3d30ef67258'
url "https://downloads.arduino.cc/arduino-#{version}-macosx.zip"
appcast 'https://www.arduino.cc/en/Main/ReleaseNotes'
name 'Arduino'
homepage 'https://www.arduino.cc/'
app 'Arduino.app'
binary "#{appdir}/Arduino.app/Contents/Java/arduino-builder"
zap trash: [
'~/Library/Arduino15',
'~/Library/Preferences/cc.arduino.Arduino.plist',
]
caveats do
depends_on_java
end
end
|
cask 'avocode' do
version '2.6.0'
sha256 '3f3a2512bc2309488270e0cd491223ac7d82e7aec7e7edf7840f1e9d2cb901af'
url "http://mediacdn.avocode.com/download/avocode-app/#{version}/avocode-app-mac-#{version}.zip"
name 'Avocode'
homepage 'https://avocode.com/'
app 'Avocode.app'
zap delete: [
'~/Library/Preferences/com.madebysource.avocode.plist',
'~/Library/Application Support/Avocode',
'~/Library/Saved Application State/com.madebysource.avocode.savedState',
'~/Library/Caches/Avocode',
'~/.avcd',
]
end
Update avocode to 2.11.1 (#27114)
cask 'avocode' do
version '2.11.1'
sha256 '5d8dd411562761f51044256d496c8a03e6299d3c34ca929c0e56bd3b055899f1'
url "http://mediacdn.avocode.com/download/avocode-app/#{version}/avocode-app-mac-#{version}.zip"
name 'Avocode'
homepage 'https://avocode.com/'
app 'Avocode.app'
zap delete: [
'~/Library/Preferences/com.madebysource.avocode.plist',
'~/Library/Application Support/Avocode',
'~/Library/Saved Application State/com.madebysource.avocode.savedState',
'~/Library/Caches/Avocode',
'~/.avcd',
]
end
|
cask "avocode" do
version "4.15.0"
sha256 "29b0e1cafde2833ea040e934f4568f09cb2f591bd6ccb7f84438b1a902f774ea"
url "https://media.avocode.com/download/avocode-app/#{version}/Avocode-#{version}-mac.zip"
name "Avocode"
desc "Collaborate on design files"
homepage "https://avocode.com/"
livecheck do
url "https://manager.avocode.com/download/avocode-app/mac-dmg/"
strategy :header_match
end
auto_updates true
depends_on macos: ">= :el_capitan"
app "Avocode.app"
zap trash: [
"~/.avocode",
"~/Library/Application Support/Avocode",
"~/Library/Caches/com.madebysource.avocode",
"~/Library/Caches/com.madebysource.avocode.ShipIt",
"~/Library/Preferences/com.madebysource.avocode.helper.plist",
"~/Library/Preferences/com.madebysource.avocode.plist",
"~/Library/Saved Application State/com.madebysource.avocode.savedState",
]
end
Update avocode from 4.15.0 to 4.15.1 (#110209)
cask "avocode" do
version "4.15.1"
sha256 "ea512b41decdd6a9ba05a191c78012cccefd3dddbbdd65aa6e75c250a81893b9"
url "https://media.avocode.com/download/avocode-app/#{version}/Avocode-#{version}-mac.zip"
name "Avocode"
desc "Collaborate on design files"
homepage "https://avocode.com/"
livecheck do
url "https://manager.avocode.com/download/avocode-app/mac-dmg/"
strategy :header_match
end
auto_updates true
depends_on macos: ">= :el_capitan"
app "Avocode.app"
zap trash: [
"~/.avocode",
"~/Library/Application Support/Avocode",
"~/Library/Caches/com.madebysource.avocode",
"~/Library/Caches/com.madebysource.avocode.ShipIt",
"~/Library/Preferences/com.madebysource.avocode.helper.plist",
"~/Library/Preferences/com.madebysource.avocode.plist",
"~/Library/Saved Application State/com.madebysource.avocode.savedState",
]
end
|
Add Avocode.app version 2.0.0
The smartest way to share designs, export assets and collaborate with your team. http://avocode.com/
cask :v1 => 'avocode' do
version '2.0.0'
sha256 '29d4d79c6b7f719cf1f945e1747c150a71fc368758b38f25ad4390f7bc4493b5'
url "http://mediacdn.avocode.com/download/avocode-app/#{version}/avocode-app-mac-#{version}.zip"
name 'Avocode'
homepage 'http://avocode.com/'
license :commercial
app 'Avocode.app'
end
|
cask "blender" do
arch arm: "arm64", intel: "x64"
version "3.2.2"
sha256 arm: "6148f65ca5ec62f360cb0e3f1f80c6bb703c3c76e6eaf4ccf1ad1257f447937a",
intel: "b398701443bdd8826fa83c2852ae8461f04f71b6666a070cb55adc8d2ca2ff91"
url "https://download.blender.org/release/Blender#{version.major_minor}/blender-#{version}-macos-#{arch}.dmg"
name "Blender"
desc "3D creation suite"
homepage "https://www.blender.org/"
livecheck do
url "https://www.blender.org/download/"
regex(%r{href=.*?/blender[._-]v?(\d+(?:\.\d+)+)[._-]macos[._-]#{arch}\.dmg}i)
end
conflicts_with cask: "homebrew/cask-versions/blender-lts"
depends_on macos: ">= :high_sierra"
app "Blender.app"
# shim script (https://github.com/Homebrew/homebrew-cask/issues/18809)
shimscript = "#{staged_path}/blender.wrapper.sh"
binary shimscript, target: "blender"
preflight do
# make __pycache__ directories writable, otherwise uninstall fails
FileUtils.chmod "u+w", Dir.glob("#{staged_path}/*.app/**/__pycache__")
File.write shimscript, <<~EOS
#!/bin/bash
'#{appdir}/Blender.app/Contents/MacOS/Blender' "$@"
EOS
end
zap trash: [
"~/Library/Application Support/Blender",
"~/Library/Saved Application State/org.blenderfoundation.blender.savedState",
]
end
Update blender from 3.2.2 to 3.3.0 (#131169)
cask "blender" do
arch arm: "arm64", intel: "x64"
version "3.3.0"
sha256 arm: "5ac37f0c088528fd30f15f283a50daebc50c022b45a834d7bdd5951687f910ea",
intel: "73dd1ede9fd57cf436aa9b9e82fdbe9685cafdc99066081de8e4bdee1790ba0b"
url "https://download.blender.org/release/Blender#{version.major_minor}/blender-#{version}-macos-#{arch}.dmg"
name "Blender"
desc "3D creation suite"
homepage "https://www.blender.org/"
livecheck do
url "https://www.blender.org/download/"
regex(%r{href=.*?/blender[._-]v?(\d+(?:\.\d+)+)[._-]macos[._-]#{arch}\.dmg}i)
end
conflicts_with cask: "homebrew/cask-versions/blender-lts"
depends_on macos: ">= :high_sierra"
app "Blender.app"
# shim script (https://github.com/Homebrew/homebrew-cask/issues/18809)
shimscript = "#{staged_path}/blender.wrapper.sh"
binary shimscript, target: "blender"
preflight do
# make __pycache__ directories writable, otherwise uninstall fails
FileUtils.chmod "u+w", Dir.glob("#{staged_path}/*.app/**/__pycache__")
File.write shimscript, <<~EOS
#!/bin/bash
'#{appdir}/Blender.app/Contents/MacOS/Blender' "$@"
EOS
end
zap trash: [
"~/Library/Application Support/Blender",
"~/Library/Saved Application State/org.blenderfoundation.blender.savedState",
]
end
|
cask 'calibre' do
if MacOS.version <= :lion
version '1.48.0'
sha256 '0533283965fbc9a6618d0b27c85bdf3671fe75ff0e89eeff406fe1457ee61b14'
else
version '2.65.1'
sha256 '60851b4f859bdc502c5209efc04573faf4b071219844b51cc959b2b29c3a0772'
appcast 'https://github.com/kovidgoyal/calibre/releases.atom',
checkpoint: '70a8bcacc9c10e6b684eaedb351b785658afd4ec8c257a43e4ba28194d216723'
end
url "https://download.calibre-ebook.com/#{version}/calibre-#{version}.dmg"
name 'calibre'
homepage 'https://calibre-ebook.com/'
license :gpl
app 'calibre.app'
binary "#{appdir}/calibre.app/Contents/MacOS/calibre"
binary "#{appdir}/calibre.app/Contents/MacOS/calibre-complete"
binary "#{appdir}/calibre.app/Contents/MacOS/calibre-customize"
binary "#{appdir}/calibre.app/Contents/MacOS/calibre-debug"
binary "#{appdir}/calibre.app/Contents/MacOS/calibre-parallel"
binary "#{appdir}/calibre.app/Contents/MacOS/calibre-server"
binary "#{appdir}/calibre.app/Contents/MacOS/calibre-smtp"
binary "#{appdir}/calibre.app/Contents/MacOS/calibredb"
binary "#{appdir}/calibre.app/Contents/MacOS/ebook-convert"
binary "#{appdir}/calibre.app/Contents/MacOS/ebook-device"
binary "#{appdir}/calibre.app/Contents/MacOS/ebook-edit"
binary "#{appdir}/calibre.app/Contents/MacOS/ebook-meta"
binary "#{appdir}/calibre.app/Contents/MacOS/ebook-polish"
binary "#{appdir}/calibre.app/Contents/MacOS/ebook-viewer"
binary "#{appdir}/calibre.app/Contents/MacOS/fetch-ebook-metadata"
binary "#{appdir}/calibre.app/Contents/MacOS/lrf2lrs"
binary "#{appdir}/calibre.app/Contents/MacOS/lrfviewer"
binary "#{appdir}/calibre.app/Contents/MacOS/lrs2lrf"
binary "#{appdir}/calibre.app/Contents/MacOS/markdown-calibre"
binary "#{appdir}/calibre.app/Contents/MacOS/web2disk"
zap delete: [
'~/Library/Preferences/net.kovidgoyal.calibre.plist',
'~/Library/Preferences/calibre',
'~/Library/Caches/calibre',
]
end
Update calibre to 2.66.0 (#24309)
cask 'calibre' do
if MacOS.version <= :lion
version '1.48.0'
sha256 '0533283965fbc9a6618d0b27c85bdf3671fe75ff0e89eeff406fe1457ee61b14'
else
version '2.66.0'
sha256 'a83cc65bf7436fe767a984728e0a592de8d5a7255de01e11d02b9f0506b2944f'
appcast 'https://github.com/kovidgoyal/calibre/releases.atom',
checkpoint: '29193b770b3c0a0a5d9ebeda9e25348274dc88dfbe9b70040fcb0884b503f7f2'
end
url "https://download.calibre-ebook.com/#{version}/calibre-#{version}.dmg"
name 'calibre'
homepage 'https://calibre-ebook.com/'
license :gpl
app 'calibre.app'
binary "#{appdir}/calibre.app/Contents/MacOS/calibre"
binary "#{appdir}/calibre.app/Contents/MacOS/calibre-complete"
binary "#{appdir}/calibre.app/Contents/MacOS/calibre-customize"
binary "#{appdir}/calibre.app/Contents/MacOS/calibre-debug"
binary "#{appdir}/calibre.app/Contents/MacOS/calibre-parallel"
binary "#{appdir}/calibre.app/Contents/MacOS/calibre-server"
binary "#{appdir}/calibre.app/Contents/MacOS/calibre-smtp"
binary "#{appdir}/calibre.app/Contents/MacOS/calibredb"
binary "#{appdir}/calibre.app/Contents/MacOS/ebook-convert"
binary "#{appdir}/calibre.app/Contents/MacOS/ebook-device"
binary "#{appdir}/calibre.app/Contents/MacOS/ebook-edit"
binary "#{appdir}/calibre.app/Contents/MacOS/ebook-meta"
binary "#{appdir}/calibre.app/Contents/MacOS/ebook-polish"
binary "#{appdir}/calibre.app/Contents/MacOS/ebook-viewer"
binary "#{appdir}/calibre.app/Contents/MacOS/fetch-ebook-metadata"
binary "#{appdir}/calibre.app/Contents/MacOS/lrf2lrs"
binary "#{appdir}/calibre.app/Contents/MacOS/lrfviewer"
binary "#{appdir}/calibre.app/Contents/MacOS/lrs2lrf"
binary "#{appdir}/calibre.app/Contents/MacOS/markdown-calibre"
binary "#{appdir}/calibre.app/Contents/MacOS/web2disk"
zap delete: [
'~/Library/Preferences/net.kovidgoyal.calibre.plist',
'~/Library/Preferences/calibre',
'~/Library/Caches/calibre',
]
end
|
cask 'cerebro' do
version '0.3.1'
sha256 '83fe4fa5baae56052eb44ae0a94a93880e2d99e52ad5d2e0d4201ddd2f960889'
# github.com/KELiON/cerebro was verified as official when first introduced to the cask
url "https://github.com/KELiON/cerebro/releases/download/v#{version}/cerebro-#{version}.dmg"
appcast 'https://github.com/KELiON/cerebro/releases.atom',
checkpoint: '0e51537bf31af3bff4797bbaed69cc3df6c2a68c99a5440f1e287ed59939d704'
name 'Cerebro'
homepage 'https://cerebroapp.com/'
app 'Cerebro.app'
zap trash: [
'~/Library/Application Support/Cerebro',
'~/Library/Preferences/com.cerebroapp.Cerebro.helper.plist',
'~/Library/Preferences/com.cerebroapp.Cerebro.plist',
'~/Library/Saved Application State/com.cerebroapp.Cerebro.savedState',
]
end
Update cerebro to 0.3.2 (#43659)
cask 'cerebro' do
version '0.3.2'
sha256 'a4df90aca836d6110ac65cd5c1427fb9121f93bdd36ed8527816befbda3dc833'
# github.com/KELiON/cerebro was verified as official when first introduced to the cask
url "https://github.com/KELiON/cerebro/releases/download/v#{version}/cerebro-#{version}.dmg"
appcast 'https://github.com/KELiON/cerebro/releases.atom',
checkpoint: '0e51537bf31af3bff4797bbaed69cc3df6c2a68c99a5440f1e287ed59939d704'
name 'Cerebro'
homepage 'https://cerebroapp.com/'
app 'Cerebro.app'
zap trash: [
'~/Library/Application Support/Cerebro',
'~/Library/Preferences/com.cerebroapp.Cerebro.helper.plist',
'~/Library/Preferences/com.cerebroapp.Cerebro.plist',
'~/Library/Saved Application State/com.cerebroapp.Cerebro.savedState',
]
end
|
Add Cerebro.app v0.1.0 (#27667)
cask 'cerebro' do
version '0.1.0'
sha256 '0a2acec0d520cd632172c00cabd0a160184dcbc29302eae28478832c930021ca'
# github.com/KELiON/cerebro was verified as official when first introduced to the cask
url "https://github.com/KELiON/cerebro/releases/download/#{version}/Cerebro.dmg"
appcast 'https://github.com/KELiON/cerebro/releases.atom',
checkpoint: 'd0a372db626b46ceb8125c351c69a2733bc84fe82772bda007b91a0f649a1561'
name 'Cerebro'
homepage 'https://cerebroapp.com'
app 'Cerebro.app'
end
|
cask 'chronos' do
version '3.2.0'
sha256 '12f84f5af60797e701262a35954e8ed31422035c35040bd9af6592354614c6ce'
url "https://github.com/web-pal/chronos-timetracker/releases/download/v#{version}/Chronos-#{version}-mac.zip"
appcast 'https://github.com/web-pal/chronos-timetracker/releases.atom'
name 'Chronos Timetracker'
homepage 'https://github.com/web-pal/chronos-timetracker'
app 'Chronos.app'
end
Update chronos from 3.2.0 to 3.2.1 (#62358)
cask 'chronos' do
version '3.2.1'
sha256 '3a7b055e1870e8f53823395a7882de33165b12c759e65d756f9bf371d343de83'
url "https://github.com/web-pal/chronos-timetracker/releases/download/v#{version}/Chronos-#{version}-mac.zip"
appcast 'https://github.com/web-pal/chronos-timetracker/releases.atom'
name 'Chronos Timetracker'
homepage 'https://github.com/web-pal/chronos-timetracker'
app 'Chronos.app'
end
|
Add ClamXav (Version 2.3.6) Cask
class Clamxav < Cask
url 'http://www.clamxav.com/downloads/ClamXav_2.3.6.dmg'
homepage 'http://www.clamxav.com/'
version '2.3.6'
sha1 '4e59947bc049109c375613979fb6092ffe67aa55'
link :app, 'ClamXav.app'
end
|
class Dockmod < Cask
version '2.04'
sha256 '86c92aa446d436296a800ee832466afa845048316a09df15d0e793f5a4cad55d'
url 'http://spyresoft.com/dockmod/download.php?version=2.04'
appcast 'http://spyresoft.com/dockmod/updates.xml'
homepage 'http://spyresoft.com/dockmod/'
link 'DockMod.app'
end
app stanza in dockmod.rb
class Dockmod < Cask
version '2.04'
sha256 '86c92aa446d436296a800ee832466afa845048316a09df15d0e793f5a4cad55d'
url 'http://spyresoft.com/dockmod/download.php?version=2.04'
appcast 'http://spyresoft.com/dockmod/updates.xml'
homepage 'http://spyresoft.com/dockmod/'
app 'DockMod.app'
end
|
cask "dropbox" do
arch = Hardware::CPU.intel? ? "" : "&arch=arm64"
version "142.4.4197"
sha256 :no_check
url "https://www.dropbox.com/download?plat=mac&full=1#{arch}"
name "Dropbox"
desc "Client for the Dropbox cloud storage service"
homepage "https://www.dropbox.com/"
livecheck do
url :url
strategy :header_match
end
auto_updates true
conflicts_with cask: "homebrew/cask-versions/dropbox-beta"
app "Dropbox.app"
uninstall launchctl: "com.dropbox.DropboxMacUpdate.agent",
kext: "com.getdropbox.dropbox.kext",
delete: [
"/Library/DropboxHelperTools",
"/Library/Preferences/com.getdropbox.dropbox.dbkextd.plist",
]
zap trash: [
"~/.dropbox",
"~/Library/Application Scripts/com.dropbox.foldertagger",
"~/Library/Application Scripts/com.getdropbox.dropbox.garcon",
"~/Library/Application Support/Dropbox",
"~/Library/Caches/CloudKit/com.apple.bird/iCloud.com.getdropbox.Dropbox",
"~/Library/Caches/com.dropbox.DropboxMacUpdate",
"~/Library/Caches/com.getdropbox.dropbox",
"~/Library/Caches/com.getdropbox.DropboxMetaInstaller",
"~/Library/Caches/com.plausiblelabs.crashreporter.data/com.dropbox.DropboxMacUpdate",
"~/Library/Containers/com.dropbox.activityprovider",
"~/Library/Containers/com.dropbox.foldertagger",
"~/Library/Containers/com.getdropbox.dropbox.garcon",
"~/Library/Dropbox",
"~/Library/Group Containers/com.dropbox.client.crashpad",
"~/Library/Group Containers/com.getdropbox.dropbox.garcon",
"~/Library/LaunchAgents/com.dropbox.DropboxMacUpdate.agent.plist",
"~/Library/Logs/Dropbox_debug.log",
"~/Library/Preferences/com.dropbox.DropboxMacUpdate.plist",
"~/Library/Preferences/com.dropbox.DropboxMonitor.plist",
"~/Library/Preferences/com.dropbox.tungsten.helper.plist",
"~/Library/Preferences/com.getdropbox.dropbox.plist",
]
end
Update dropbox from 142.4.4197 to 143.4.4161 (#119948)
Co-authored-by: Johannes Klein <bc971dabce894e03ec43051a284d7c367442557d@lineupr.com>
cask "dropbox" do
arch = Hardware::CPU.intel? ? "" : "&arch=arm64"
version "143.4.4161"
sha256 :no_check
url "https://www.dropbox.com/download?plat=mac&full=1#{arch}"
name "Dropbox"
desc "Client for the Dropbox cloud storage service"
homepage "https://www.dropbox.com/"
livecheck do
url :url
strategy :header_match
end
auto_updates true
conflicts_with cask: "homebrew/cask-versions/dropbox-beta"
app "Dropbox.app"
uninstall launchctl: "com.dropbox.DropboxMacUpdate.agent",
kext: "com.getdropbox.dropbox.kext",
delete: [
"/Library/DropboxHelperTools",
"/Library/Preferences/com.getdropbox.dropbox.dbkextd.plist",
]
zap trash: [
"~/.dropbox",
"~/Library/Application Scripts/com.dropbox.foldertagger",
"~/Library/Application Scripts/com.getdropbox.dropbox.garcon",
"~/Library/Application Support/Dropbox",
"~/Library/Caches/CloudKit/com.apple.bird/iCloud.com.getdropbox.Dropbox",
"~/Library/Caches/com.dropbox.DropboxMacUpdate",
"~/Library/Caches/com.getdropbox.dropbox",
"~/Library/Caches/com.getdropbox.DropboxMetaInstaller",
"~/Library/Caches/com.plausiblelabs.crashreporter.data/com.dropbox.DropboxMacUpdate",
"~/Library/Containers/com.dropbox.activityprovider",
"~/Library/Containers/com.dropbox.foldertagger",
"~/Library/Containers/com.getdropbox.dropbox.garcon",
"~/Library/Dropbox",
"~/Library/Group Containers/com.dropbox.client.crashpad",
"~/Library/Group Containers/com.getdropbox.dropbox.garcon",
"~/Library/LaunchAgents/com.dropbox.DropboxMacUpdate.agent.plist",
"~/Library/Logs/Dropbox_debug.log",
"~/Library/Preferences/com.dropbox.DropboxMacUpdate.plist",
"~/Library/Preferences/com.dropbox.DropboxMonitor.plist",
"~/Library/Preferences/com.dropbox.tungsten.helper.plist",
"~/Library/Preferences/com.getdropbox.dropbox.plist",
]
end
|
cask "eaccess" do
version "1.13.3"
sha256 "b496682ccaa4b90bdb7a9ae81b631e714235f81481d985c3c752c313dc7d7058"
url "https://glutz.com/service/downloads/?dwnldid=97899"
appcast "https://glutz.com/service/downloads/soft-und-firmware/"
name "eAccess Desktop"
desc "Software for eAccess devices"
homepage "https://glutz.com/service/download/software-and-firmware/"
app "eAccess Desktop.app"
binary "#{appdir}/eAccess Desktop.app/Contents/MacOS/eAccessServer"
uninstall quit: "com.glutz.eaccessdesktop"
zap trash: [
"~/Library/Caches/com.glutz.eaccessdesktop",
"~/Library/Preferences/com.glutz.eAccess Desktop.plist",
"~/Library/Saved Application State/com.glutz.eaccessdesktop.savedState",
]
end
eaccess: use `sha256 :no_check` for unversioned URL
cask "eaccess" do
version "1.13.3"
sha256 :no_check
url "https://glutz.com/service/downloads/?dwnldid=97899"
appcast "https://glutz.com/service/downloads/soft-und-firmware/"
name "eAccess Desktop"
desc "Software for eAccess devices"
homepage "https://glutz.com/service/download/software-and-firmware/"
app "eAccess Desktop.app"
binary "#{appdir}/eAccess Desktop.app/Contents/MacOS/eAccessServer"
uninstall quit: "com.glutz.eaccessdesktop"
zap trash: [
"~/Library/Caches/com.glutz.eaccessdesktop",
"~/Library/Preferences/com.glutz.eAccess Desktop.plist",
"~/Library/Saved Application State/com.glutz.eaccessdesktop.savedState",
]
end
|
cask "element" do
version "1.7.26"
sha256 "faec8b868f0a50a6be6c06a75c70612a920f1384737de37d5ca97f8bb4e5c659"
url "https://packages.riot.im/desktop/install/macos/Element-#{version}.dmg",
verified: "packages.riot.im/desktop/"
name "Element"
desc "Matrix collaboration client"
homepage "https://element.io/get-started"
livecheck do
url "https://github.com/vector-im/riot-desktop"
strategy :github_latest
end
auto_updates true
app "Element.app"
zap trash: [
"~/Library/Application Support/Element",
"~/Library/Application Support/Riot",
"~/Library/Caches/im.riot.app",
"~/Library/Caches/im.riot.app.ShipIt",
"~/Library/Logs/Riot",
"~/Library/Preferences/im.riot.app.helper.plist",
"~/Library/Preferences/im.riot.app.plist",
"~/Library/Saved Application State/im.riot.app.savedState",
]
end
Update element from 1.7.26 to 1.7.27 (#105508)
cask "element" do
version "1.7.27"
sha256 "203c3b6735d06d8e180a232abf5eeb420d45caac4a896def6feb93260578891d"
url "https://packages.riot.im/desktop/install/macos/Element-#{version}.dmg",
verified: "packages.riot.im/desktop/"
name "Element"
desc "Matrix collaboration client"
homepage "https://element.io/get-started"
livecheck do
url "https://github.com/vector-im/riot-desktop"
strategy :github_latest
end
auto_updates true
app "Element.app"
zap trash: [
"~/Library/Application Support/Element",
"~/Library/Application Support/Riot",
"~/Library/Caches/im.riot.app",
"~/Library/Caches/im.riot.app.ShipIt",
"~/Library/Logs/Riot",
"~/Library/Preferences/im.riot.app.helper.plist",
"~/Library/Preferences/im.riot.app.plist",
"~/Library/Saved Application State/im.riot.app.savedState",
]
end
|
cask 'endicia' do
version '2.17v738'
sha256 'a0dbe49e53494d451caef05701e445b9dd0454f45faf293fe54ce1feead913da'
url "https://download.endiciaformac.com/EndiciaForMac#{version.no_dots}.dmg"
appcast 'https://s3.amazonaws.com/endiciaformac/EndiciaForMacSparkle.xml',
checkpoint: '27b61b03cf0d412974146e6507df1fd2348625df78e82ba43bdb4261fd94407b'
name 'Endicia for Mac'
homepage 'https://endiciaformac.com/'
app 'Endicia.app'
end
Update endicia to 2171v742 (#39458)
cask 'endicia' do
version '2171v742'
sha256 '0fd8d6a038d0ac03a258aa11cd3b4dfb8c68006eb4d69e5c0ada3219fe12b340'
url "https://download.endiciaformac.com/EndiciaForMac#{version.no_dots}.dmg"
appcast 'https://s3.amazonaws.com/endiciaformac/EndiciaForMacSparkle.xml',
checkpoint: '67c9d689919f4690d1f007f3cbe0f59d9543562dc4a101685992c208ab11dff5'
name 'Endicia for Mac'
homepage 'https://endiciaformac.com/'
app 'Endicia.app'
end
|
cask 'fauxpas' do
version '1.6'
sha256 '6a5d518df5a67ffef360cdcaef41dd10365bc90390354d5cde19e310d6ad9da6'
url "http://files.fauxpasapp.com/FauxPas-#{version}.tar.bz2"
appcast 'http://api.fauxpasapp.com/appcast',
:sha256 => '478477793b0b317edeae2cda359bc0d180e8749ac72d11a5c71a5d9dab4a0f93'
name 'Faux Pas'
homepage 'http://fauxpasapp.com'
license :commercial
app 'FauxPas.app'
end
fauxpas.rb: appcast sha256 without pubDate
cask 'fauxpas' do
version '1.6'
sha256 '6a5d518df5a67ffef360cdcaef41dd10365bc90390354d5cde19e310d6ad9da6'
url "http://files.fauxpasapp.com/FauxPas-#{version}.tar.bz2"
appcast 'http://api.fauxpasapp.com/appcast',
:sha256 => '43efce1b93652e1adfbaa6df61534216972524f763d163e9fc1f5a48b89bcf54'
name 'Faux Pas'
homepage 'http://fauxpasapp.com'
license :commercial
app 'FauxPas.app'
end
|
cask "firefox" do
version "95.0.2"
language "cs" do
sha256 "3581f1658a505ea2876f179bc31f820c16ebb5bf3c4c6bfe900f0b07f4f97216"
"cs"
end
language "de" do
sha256 "41d0d5e26af6cb128a0bee920837a880c91bf40a01bed949b897a6e99b6cf72e"
"de"
end
language "en-CA" do
sha256 "ab64cf822734b3f38fe1b3e2e1ec7a8850d136b1e46f49bd7960a11bcff7468a"
"en-CA"
end
language "en-GB" do
sha256 "040fe7d737a8eae784f70ccb372f96df3c1d577ee0c3bde8757330da961255d7"
"en-GB"
end
language "en", default: true do
sha256 "e823901d77c1db20afcd5270d159256a340974d808f98a3f2e8560dc04c58c57"
"en-US"
end
language "eo" do
sha256 "03f73e2581036f8664e4ab0d11fe4c04e394045c36a283fb81f7cbec6736fa46"
"eo"
end
language "es-AR" do
sha256 "799a256806376a9375bf6254ea18f9bc418df07a383c04e047a7ab942551e7bc"
"es-AR"
end
language "es-CL" do
sha256 "6d0cba0339ea5a38a50485bd5e1b8be2b00a394846981d4ffdce7008b86ddf71"
"es-CL"
end
language "es-ES" do
sha256 "db1da4dc124b8535387315c81d5933cd788239ce834e32569ec0fcbafbc3f3b1"
"es-ES"
end
language "fi" do
sha256 "c17f8b77d18a6f12ea9f7b95dddfec5d4a8a897222975cd480a254d0db53de10"
"fi"
end
language "fr" do
sha256 "0c876f1d67066f833facda46a4aa5378471879fc1d89cb08384f5f3e38298ac7"
"fr"
end
language "gl" do
sha256 "b7d8d5a807d3667233e72d633773966509dba718bcd1105226d18992326480d3"
"gl"
end
language "in" do
sha256 "8c4948d3a7ff5cc3457cf2bad37b66925e47fb0425af7a0e5471597421b13704"
"hi-IN"
end
language "it" do
sha256 "30db78893bc18cb06faaba75f27202fbb06343a07d7a0d8531a9625b061418b1"
"it"
end
language "ja" do
sha256 "71ca766367aa04c0ef7ce5201399ac1013ffc4194c05ff59f91904a6e1bdd263"
"ja-JP-mac"
end
language "ko" do
sha256 "d99d08d24bf53bc1c1ea19276ee5c905be7767233d67632cf1ff5413b334f414"
"ko"
end
language "nl" do
sha256 "982c2e7804af6aca05f47f6d19119f0f6c39f0add684a5cae36447b3cf13978a"
"nl"
end
language "pl" do
sha256 "fa2c3447b9b6381dc0c0fa053e0d7637c23918f59230f4866bd6e5a2428df2ea"
"pl"
end
language "pt-BR" do
sha256 "eb1637734b3f79f890ca8d4079a865307381cf205703404b4524c08a4b3f149a"
"pt-BR"
end
language "pt" do
sha256 "7c4570575e0b6ba2141663aab3baa08f170c7c36b75a440bddd04f92d70e6ec9"
"pt-PT"
end
language "ru" do
sha256 "8d7aa4a111b2bdeee69cfdbe62855c21b60da230e034a987330c72c8ea1d7929"
"ru"
end
language "sv" do
sha256 "2377f630cdc6ca7a98a6cb7211c593981a718e1a09c3035970eab510530917b7"
"sv-SE"
end
language "tr" do
sha256 "aff40fbb9ffef41c5d858d6d7a86daeff949c7313fb609e26c9edede372a55b7"
"tr"
end
language "uk" do
sha256 "d071d9bb234403e2deb9a5931339bc3e2505315b10a0b53421a27c543cbce85f"
"uk"
end
language "zh-TW" do
sha256 "1ab49a28763178132b4f49fa5cd8426a631df599f6ba33e916a0ed250376ae33"
"zh-TW"
end
language "zh" do
sha256 "5b5c44464894743586f21573033fdbb0b44d3dc8801f51ec05e61e934fa4d949"
"zh-CN"
end
url "https://download-installer.cdn.mozilla.net/pub/firefox/releases/#{version}/mac/#{language}/Firefox%20#{version}.dmg",
verified: "download-installer.cdn.mozilla.net/pub/firefox/releases/"
name "Mozilla Firefox"
desc "Web browser"
homepage "https://www.mozilla.org/firefox/"
livecheck do
url "https://download.mozilla.org/?product=firefox-latest-ssl&os=osx"
strategy :header_match
end
auto_updates true
conflicts_with cask: [
"homebrew/cask-versions/firefox-beta",
"homebrew/cask-versions/firefox-esr",
]
depends_on macos: ">= :sierra"
app "Firefox.app"
zap trash: [
"/Library/Logs/DiagnosticReports/firefox_*",
"~/Library/Application Support/Firefox",
"~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/org.mozilla.firefox.sfl*",
"~/Library/Application Support/CrashReporter/firefox_*",
"~/Library/Caches/Firefox",
"~/Library/Caches/Mozilla/updates/Applications/Firefox",
"~/Library/Caches/org.mozilla.firefox",
"~/Library/Caches/org.mozilla.crashreporter",
"~/Library/Preferences/org.mozilla.firefox.plist",
"~/Library/Preferences/org.mozilla.crashreporter.plist",
"~/Library/Saved Application State/org.mozilla.firefox.savedState",
"~/Library/WebKit/org.mozilla.firefox",
],
rmdir: [
"~/Library/Application Support/Mozilla", # May also contain non-Firefox data
"~/Library/Caches/Mozilla/updates/Applications",
"~/Library/Caches/Mozilla/updates",
"~/Library/Caches/Mozilla",
]
end
Update firefox.rb (#116910)
* Update firefox.rb
* Update firefox.rb
* Update firefox.rb
Co-authored-by: Miccal Matthews <a53b0df86fcdccc56e90f3003dd9230c49f140c6@gmail.com>
cask "firefox" do
version "95.0.2"
language "cs" do
sha256 "3581f1658a505ea2876f179bc31f820c16ebb5bf3c4c6bfe900f0b07f4f97216"
"cs"
end
language "de" do
sha256 "41d0d5e26af6cb128a0bee920837a880c91bf40a01bed949b897a6e99b6cf72e"
"de"
end
language "en-CA" do
sha256 "ab64cf822734b3f38fe1b3e2e1ec7a8850d136b1e46f49bd7960a11bcff7468a"
"en-CA"
end
language "en-GB" do
sha256 "040fe7d737a8eae784f70ccb372f96df3c1d577ee0c3bde8757330da961255d7"
"en-GB"
end
language "en", default: true do
sha256 "e823901d77c1db20afcd5270d159256a340974d808f98a3f2e8560dc04c58c57"
"en-US"
end
language "eo" do
sha256 "03f73e2581036f8664e4ab0d11fe4c04e394045c36a283fb81f7cbec6736fa46"
"eo"
end
language "es-AR" do
sha256 "799a256806376a9375bf6254ea18f9bc418df07a383c04e047a7ab942551e7bc"
"es-AR"
end
language "es-CL" do
sha256 "6d0cba0339ea5a38a50485bd5e1b8be2b00a394846981d4ffdce7008b86ddf71"
"es-CL"
end
language "es-ES" do
sha256 "db1da4dc124b8535387315c81d5933cd788239ce834e32569ec0fcbafbc3f3b1"
"es-ES"
end
language "fi" do
sha256 "c17f8b77d18a6f12ea9f7b95dddfec5d4a8a897222975cd480a254d0db53de10"
"fi"
end
language "fr" do
sha256 "0c876f1d67066f833facda46a4aa5378471879fc1d89cb08384f5f3e38298ac7"
"fr"
end
language "gl" do
sha256 "b7d8d5a807d3667233e72d633773966509dba718bcd1105226d18992326480d3"
"gl"
end
language "in" do
sha256 "8c4948d3a7ff5cc3457cf2bad37b66925e47fb0425af7a0e5471597421b13704"
"hi-IN"
end
language "it" do
sha256 "30db78893bc18cb06faaba75f27202fbb06343a07d7a0d8531a9625b061418b1"
"it"
end
language "ja" do
sha256 "71ca766367aa04c0ef7ce5201399ac1013ffc4194c05ff59f91904a6e1bdd263"
"ja-JP-mac"
end
language "ko" do
sha256 "d99d08d24bf53bc1c1ea19276ee5c905be7767233d67632cf1ff5413b334f414"
"ko"
end
language "nl" do
sha256 "982c2e7804af6aca05f47f6d19119f0f6c39f0add684a5cae36447b3cf13978a"
"nl"
end
language "pl" do
sha256 "fa2c3447b9b6381dc0c0fa053e0d7637c23918f59230f4866bd6e5a2428df2ea"
"pl"
end
language "pt-BR" do
sha256 "eb1637734b3f79f890ca8d4079a865307381cf205703404b4524c08a4b3f149a"
"pt-BR"
end
language "pt" do
sha256 "7c4570575e0b6ba2141663aab3baa08f170c7c36b75a440bddd04f92d70e6ec9"
"pt-PT"
end
language "ru" do
sha256 "8d7aa4a111b2bdeee69cfdbe62855c21b60da230e034a987330c72c8ea1d7929"
"ru"
end
language "sv" do
sha256 "2377f630cdc6ca7a98a6cb7211c593981a718e1a09c3035970eab510530917b7"
"sv-SE"
end
language "tr" do
sha256 "aff40fbb9ffef41c5d858d6d7a86daeff949c7313fb609e26c9edede372a55b7"
"tr"
end
language "uk" do
sha256 "d071d9bb234403e2deb9a5931339bc3e2505315b10a0b53421a27c543cbce85f"
"uk"
end
language "zh-TW" do
sha256 "1ab49a28763178132b4f49fa5cd8426a631df599f6ba33e916a0ed250376ae33"
"zh-TW"
end
language "zh" do
sha256 "5b5c44464894743586f21573033fdbb0b44d3dc8801f51ec05e61e934fa4d949"
"zh-CN"
end
url "https://download-installer.cdn.mozilla.net/pub/firefox/releases/#{version}/mac/#{language}/Firefox%20#{version}.dmg",
verified: "download-installer.cdn.mozilla.net/pub/firefox/releases/"
name "Mozilla Firefox"
desc "Web browser"
homepage "https://www.mozilla.org/firefox/"
livecheck do
url "https://download.mozilla.org/?product=firefox-latest-ssl&os=osx"
strategy :header_match
end
auto_updates true
conflicts_with cask: [
"homebrew/cask-versions/firefox-beta",
"homebrew/cask-versions/firefox-esr",
]
depends_on macos: ">= :sierra"
app "Firefox.app"
uninstall quit: "org.mozilla.firefox",
delete: "/Library/Logs/DiagnosticReports/firefox_*"
zap trash: [
"~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/org.mozilla.firefox.sfl*",
"~/Library/Application Support/CrashReporter/firefox_*",
"~/Library/Application Support/Firefox",
"~/Library/Caches/Firefox",
"~/Library/Caches/Mozilla/updates/Applications/Firefox",
"~/Library/Caches/org.mozilla.crashreporter",
"~/Library/Caches/org.mozilla.firefox",
"~/Library/Preferences/org.mozilla.crashreporter.plist",
"~/Library/Preferences/org.mozilla.firefox.plist",
"~/Library/Saved Application State/org.mozilla.firefox.savedState",
"~/Library/WebKit/org.mozilla.firefox",
],
rmdir: [
"~/Library/Application Support/Mozilla", # May also contain non-Firefox data
"~/Library/Caches/Mozilla/updates/Applications",
"~/Library/Caches/Mozilla/updates",
"~/Library/Caches/Mozilla",
]
end
|
cask "flipper" do
version "0.165.1"
sha256 "73e21ab46464c4b2dd50db50fd5bf13991a640422a31632381f33182fa7932ae"
url "https://github.com/facebook/flipper/releases/download/v#{version}/Flipper-mac.dmg",
verified: "github.com/facebook/flipper/"
name "Facebook Flipper"
desc "Desktop debugging platform for mobile developers"
homepage "https://fbflipper.com/"
app "Flipper.app"
zap trash: [
"~/.flipper",
"~/Library/Application Support/Flipper",
"~/Library/Preferences/rs.flipper-launcher",
]
end
flipper 0.166.0
Update flipper from 0.165.1 to 0.166.0
Closes #131982.
Signed-off-by: Sean Molenaar <2b250e3fea88cfef248b497ad5fc17f7dc435154@users.noreply.github.com>
Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com>
cask "flipper" do
version "0.166.0"
sha256 "7fb7c939786dcd8fcaad0ea06c24ae2d71f805726759a738b010365d9a0db5af"
url "https://github.com/facebook/flipper/releases/download/v#{version}/Flipper-mac.dmg",
verified: "github.com/facebook/flipper/"
name "Facebook Flipper"
desc "Desktop debugging platform for mobile developers"
homepage "https://fbflipper.com/"
app "Flipper.app"
zap trash: [
"~/.flipper",
"~/Library/Application Support/Flipper",
"~/Library/Preferences/rs.flipper-launcher",
]
end
|
cask "flutter" do
arch = Hardware::CPU.intel? ? "_" : "_arm64_"
version "3.0.1"
if Hardware::CPU.intel?
sha256 "20d96acdc49f877e533697300228b58108b18a970e29184d8477c01889218ce9"
else
sha256 "f34e34f8cf247d4f6fde3f7e9e6753d15ff7f6e88bda232df13c009514896163"
end
url "https://storage.googleapis.com/flutter_infra_release/releases/stable/macos/flutter_macos#{arch}#{version}-stable.zip",
verified: "storage.googleapis.com/flutter_infra_release/releases/stable/macos/"
name "Flutter SDK"
desc "UI toolkit for building applications for mobile, web and desktop"
homepage "https://flutter.dev/"
livecheck do
url "https://storage.googleapis.com/flutter_infra_release/releases/releases_macos.json"
regex(%r{/flutter[._-]macos[._-]v?(\d+(?:\.\d+)+)[._-]stable\.zip}i)
end
auto_updates true
binary "flutter/bin/dart"
binary "flutter/bin/flutter"
zap trash: "~/.flutter"
end
flutter 3.0.2
Update flutter from 3.0.1 to 3.0.2
Closes #125421.
Signed-off-by: Bevan Kay <a88b7dcd1a9e3e17770bbaa6d7515b31a2d7e85d@bevankay.me>
Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com>
cask "flutter" do
arch = Hardware::CPU.intel? ? "_" : "_arm64_"
version "3.0.2"
if Hardware::CPU.intel?
sha256 "7fc88b2944495c20e013c83c4e0bfcd40d258d9fb52ddbde5c0771e207c9ff29"
else
sha256 "734874caac4928d86a7bba8aa843e5c0577ccb1051df551db41dd1e4d64b6d9e"
end
url "https://storage.googleapis.com/flutter_infra_release/releases/stable/macos/flutter_macos#{arch}#{version}-stable.zip",
verified: "storage.googleapis.com/flutter_infra_release/releases/stable/macos/"
name "Flutter SDK"
desc "UI toolkit for building applications for mobile, web and desktop"
homepage "https://flutter.dev/"
livecheck do
url "https://storage.googleapis.com/flutter_infra_release/releases/releases_macos.json"
regex(%r{/flutter[._-]macos[._-]v?(\d+(?:\.\d+)+)[._-]stable\.zip}i)
end
auto_updates true
binary "flutter/bin/dart"
binary "flutter/bin/flutter"
zap trash: "~/.flutter"
end
|
cask :v1 => 'gnucash' do
version '2.6.6-5'
sha256 'fa4f240d2ad9266038c360f5a2cfc1c492425cca3fcfa82e19820e5cb7b590f5'
# sourceforge.net is the official download host per the vendor homepage
url "http://downloads.sourceforge.net/sourceforge/gnucash/Gnucash-Intel-#{version}.dmg"
name 'GnuCash'
homepage 'http://www.gnucash.org'
license :gpl
app 'Gnucash.app'
app 'FinanceQuote Update.app'
end
Update gnucash sha256.
cask :v1 => 'gnucash' do
version '2.6.6-5'
sha256 'c0ac1ea91e1a71519d8a4664190b8e4c7b0af60cb68a610f7ce7de30e3feaed8'
# sourceforge.net is the official download host per the vendor homepage
url "http://downloads.sourceforge.net/sourceforge/gnucash/Gnucash-Intel-#{version}.dmg"
name 'GnuCash'
homepage 'http://www.gnucash.org'
license :gpl
app 'Gnucash.app'
app 'FinanceQuote Update.app'
end
|
cask :v1 => 'gnucash' do
version '2.6.5-6'
sha256 '84a55674ef9a78b0aebf530017cca31204d1270110675c916bee0fb8d838030a'
# sourceforge.net is the official download host per the vendor homepage
url "http://downloads.sourceforge.net/sourceforge/gnucash/Gnucash-Intel-#{version}.dmg"
homepage 'http://www.gnucash.org'
license :oss
app 'Gnucash.app'
app 'FinanceQuote Update.app'
end
Update gnucash license from oss to gpl
http://www.gnucash.org/
cask :v1 => 'gnucash' do
version '2.6.5-6'
sha256 '84a55674ef9a78b0aebf530017cca31204d1270110675c916bee0fb8d838030a'
# sourceforge.net is the official download host per the vendor homepage
url "http://downloads.sourceforge.net/sourceforge/gnucash/Gnucash-Intel-#{version}.dmg"
homepage 'http://www.gnucash.org'
license :gpl
app 'Gnucash.app'
app 'FinanceQuote Update.app'
end
|
cask 'harmony' do
version '0.4.6'
sha256 '19d5f0fcc2660947a68de98dba277ad14f475377e2c4536bb015e7d908a3e719'
# github.com/vincelwt/harmony was verified as official when first introduced to the cask
url "https://github.com/vincelwt/harmony/releases/download/v#{version}/harmony-#{version}.dmg"
appcast 'https://github.com/vincelwt/harmony/releases.atom',
checkpoint: '8cf4fd4fe82838ef8cc2b77272bfda6ec55e5d7c4d47b96cba83ba7abaa68d38'
name 'Harmony'
homepage 'http://getharmony.xyz/'
app 'Harmony.app'
end
Update harmony to 0.4.7 (#30654)
* Update harmony to 0.4.7
* Add zap delete
cask 'harmony' do
version '0.4.7'
sha256 'b17649067dcb9f1810bdd684e08d70cf04289120945e34f271fdccd2db582fb2'
# github.com/vincelwt/harmony was verified as official when first introduced to the cask
url "https://github.com/vincelwt/harmony/releases/download/v#{version}/harmony-#{version}.dmg"
appcast 'https://github.com/vincelwt/harmony/releases.atom',
checkpoint: 'c5f8e370155c76a02a08da9194809d405f5c257c1233628e0321c39b3f432970'
name 'Harmony'
homepage 'http://getharmony.xyz/'
app 'Harmony.app'
zap delete: [
'~/Library/Application Support/Harmony',
'~/Library/Preferences/com.vincelwt.harmony.helper.plist',
'~/Library/Preferences/com.vincelwt.harmony.plist',
'~/Library/Saved Application State/com.vincelwt.harmony.savedState',
]
end
|
cask 'harvest' do
version '2.1.8'
sha256 'e0205cb5831ef9e3db3bbd7ab1dcc44210e3e6ca35011b646fa52e7bccf5cb2b'
url "https://www.getharvest.com/harvest/mac/Harvest.#{version}.zip"
appcast 'https://www.getharvest.com/harvest/mac/appcast.xml'
name 'Harvest'
homepage 'https://www.getharvest.com/mac-time-tracking'
auto_updates true
app 'Harvest.app'
end
Update harvest to 2.1.9 (#50754)
cask 'harvest' do
version '2.1.9'
sha256 '5c1ca460705b7a473d955dffe28a3329707bf196c203b1653667e2a917368023'
url "https://www.getharvest.com/harvest/mac/Harvest.#{version}.zip"
appcast 'https://www.getharvest.com/harvest/mac/appcast.xml'
name 'Harvest'
homepage 'https://www.getharvest.com/mac-time-tracking'
auto_updates true
app 'Harvest.app'
end
|
cask 'hipchat' do
version '4.26.1-698'
sha256 'cc9ed1c5690a9620847ee7a42ec27d110964f33ea0fc76c4b4b5eeed6866fed8'
# amazonaws.com/downloads.hipchat.com/osx was verified as official when first introduced to the cask
url "https://s3.amazonaws.com/downloads.hipchat.com/osx/HipChat-#{version}.zip"
appcast 'https://www.hipchat.com/release_notes/appcast/mac',
checkpoint: 'db093193a2d23e18bd8786271aa65f70946cd4e2eb214cd7de8f9bb99c09581b'
name 'HipChat'
homepage 'https://www.hipchat.com/'
license :freemium
auto_updates true
app 'HipChat.app'
postflight do
suppress_move_to_applications
end
zap delete: [
# TODO: expand/glob for '~/Library/<userid>/HipChat/'
'~/Library/Application Support/HipChat',
'~/Library/Caches/com.hipchat.HipChat',
'~/Library/HipChat',
'~/Library/Logs/HipChat',
'~/Library/Preferences/com.hipchat.HipChat.plist',
'~/Library/Saved Application State/com.hipchat.HipChat.savedState',
'~/Library/chat.hipchat.com',
]
end
updated hipchat (4.27.0-702) (#24317)
cask 'hipchat' do
version '4.27.0-702'
sha256 '443f58ad9838b2791a4d28ab190f3cd59de07f2c4da6029775f3e45a1ecc0e91'
# amazonaws.com/downloads.hipchat.com/osx was verified as official when first introduced to the cask
url "https://s3.amazonaws.com/downloads.hipchat.com/osx/HipChat-#{version}.zip"
appcast 'https://www.hipchat.com/release_notes/appcast/mac',
checkpoint: 'a24ed4d5d9d220b75cb6c96e083589b956e5e4f13b111e8b73583dc51afeabcf'
name 'HipChat'
homepage 'https://www.hipchat.com/'
license :freemium
auto_updates true
app 'HipChat.app'
postflight do
suppress_move_to_applications
end
zap delete: [
# TODO: expand/glob for '~/Library/<userid>/HipChat/'
'~/Library/Application Support/HipChat',
'~/Library/Caches/com.hipchat.HipChat',
'~/Library/HipChat',
'~/Library/Logs/HipChat',
'~/Library/Preferences/com.hipchat.HipChat.plist',
'~/Library/Saved Application State/com.hipchat.HipChat.savedState',
'~/Library/chat.hipchat.com',
]
end
|
cask 'hipchat' do
version '4.0.8-626'
sha256 'a9fe74d310dfcd33a0b16c801440841b768a9999d3538fbf0513b4202ee59194'
# amazonaws.com/downloads.hipchat.com/osx was verified as official when first introduced to the cask
url "https://s3.amazonaws.com/downloads.hipchat.com/osx/HipChat-#{version}.zip"
appcast 'https://www.hipchat.com/release_notes/appcast/mac',
checkpoint: 'a4d76813cdaa6b6b936f1df115faf09b689ddbad41d97ec6690ac478bcc29962'
name 'HipChat'
homepage 'https://www.hipchat.com/'
license :freemium
auto_updates true
app 'HipChat.app'
postflight do
suppress_move_to_applications
end
zap delete: [
# TODO: expand/glob for '~/Library/<userid>/HipChat/'
'~/Library/Application Support/HipChat',
'~/Library/Caches/com.hipchat.HipChat',
'~/Library/HipChat',
'~/Library/Logs/HipChat',
'~/Library/Preferences/com.hipchat.HipChat.plist',
'~/Library/Saved Application State/com.hipchat.HipChat.savedState',
'~/Library/chat.hipchat.com',
]
end
updated hipchat (4.0.9-637) (#20984)
cask 'hipchat' do
version '4.0.9-637'
sha256 'c7e03739b7cb0ed198525b5f27dbadedc04cafdc2b63805fb1e5693225270402'
# amazonaws.com/downloads.hipchat.com/osx was verified as official when first introduced to the cask
url "https://s3.amazonaws.com/downloads.hipchat.com/osx/HipChat-#{version}.zip"
appcast 'https://www.hipchat.com/release_notes/appcast/mac',
checkpoint: '52983f8c4c4183a2f417ec273c2ce5f244e23882dc54c80fb19dadbbfd3838fd'
name 'HipChat'
homepage 'https://www.hipchat.com/'
license :freemium
auto_updates true
app 'HipChat.app'
postflight do
suppress_move_to_applications
end
zap delete: [
# TODO: expand/glob for '~/Library/<userid>/HipChat/'
'~/Library/Application Support/HipChat',
'~/Library/Caches/com.hipchat.HipChat',
'~/Library/HipChat',
'~/Library/Logs/HipChat',
'~/Library/Preferences/com.hipchat.HipChat.plist',
'~/Library/Saved Application State/com.hipchat.HipChat.savedState',
'~/Library/chat.hipchat.com',
]
end
|
class Jiggler < Cask
url 'http://downloads.sticksoftware.com/Jiggler.dmg'
homepage 'http://www.sticksoftware.com/software/Jiggler.html'
version 'latest'
sha256 :no_check
link 'Jiggler.app'
end
Reformat jiggler.rb according to readability conventions
class Jiggler < Cask
version 'latest'
sha256 :no_check
url 'http://downloads.sticksoftware.com/Jiggler.dmg'
homepage 'http://www.sticksoftware.com/software/Jiggler.html'
link 'Jiggler.app'
end
|
cask 'jmetrik' do
version '4.1.1'
sha256 'a6b7fa7870232f9bf615704c810c8046b3b5ebc02ec3a920fb96e0f255b61321'
url "https://itemanalysis.com/jmetrik/v#{version.dots_to_underscores}/jmetrik_macos_#{version.dots_to_underscores}_java7.dmg"
name 'jMetrik'
homepage 'http://itemanalysis.com/'
installer script: {
executable: 'jMetrik Installer.app/Contents/MacOS/JavaApplicationStub',
# For future Cask maintainers, if any of these variables
# change in future versions, you can run the installer
# manually and then check the values in the following
# file generated by the installation:
# /Applications/jmetrik/.install4j/response.varfile
args: [
'-q', # Silent mode
'-VcreateDesktopLinkAction$Boolean=false', # Do not create a desktop icon
'-VexecutionLauncherAction$Boolean=false', # Do not launch jMetrik after installing
"-Vsys.installationDir=#{appdir}/jMetrik", # Install to subdirectory of /Applications
],
sudo: true,
}
uninstall script: {
executable: "#{appdir}/jMetrik/jMetrik Uninstaller.app/Contents/MacOS/JavaApplicationStub",
args: ['-q'],
sudo: true,
}
zap trash: '~/jmetrik'
caveats do
depends_on_java '7+'
end
end
Update jmetrik (#61522)
cask 'jmetrik' do
version '4.1.1'
sha256 'a6b7fa7870232f9bf615704c810c8046b3b5ebc02ec3a920fb96e0f255b61321'
url "https://itemanalysis.com/jmetrik/v#{version.dots_to_underscores}/jmetrik_macos_#{version.dots_to_underscores}_java7.dmg"
appcast 'https://itemanalysis.com/jmetrik-download/'
name 'jMetrik'
homepage 'http://itemanalysis.com/'
installer script: {
executable: 'jMetrik Installer.app/Contents/MacOS/JavaApplicationStub',
# For future Cask maintainers, if any of these variables
# change in future versions, you can run the installer
# manually and then check the values in the following
# file generated by the installation:
# /Applications/jmetrik/.install4j/response.varfile
args: [
'-q', # Silent mode
'-VcreateDesktopLinkAction$Boolean=false', # Do not create a desktop icon
'-VexecutionLauncherAction$Boolean=false', # Do not launch jMetrik after installing
"-Vsys.installationDir=#{appdir}/jMetrik", # Install to subdirectory of /Applications
],
sudo: true,
}
uninstall script: {
executable: "#{appdir}/jMetrik/jMetrik Uninstaller.app/Contents/MacOS/JavaApplicationStub",
args: ['-q'],
sudo: true,
}
zap trash: '~/jmetrik'
caveats do
depends_on_java '7+'
end
end
|
class Jumpcut < Cask
version '0.63'
sha256 '19c84eefbc7f173af45affe3a9ca6fd9ec58d9bdf6bacef165085e63e82d54e1'
url "https://downloads.sourceforge.net/project/jumpcut/jumpcut/#{version}/Jumpcut_#{version}.tgz"
appcast 'http://jumpcut.sf.net/jumpcut.appcast.xml'
homepage 'http://jumpcut.sourceforge.net/'
license :oss
app 'Jumpcut.app'
end
add appcast :sha256 in jumpcut
class Jumpcut < Cask
version '0.63'
sha256 '19c84eefbc7f173af45affe3a9ca6fd9ec58d9bdf6bacef165085e63e82d54e1'
url "https://downloads.sourceforge.net/project/jumpcut/jumpcut/#{version}/Jumpcut_#{version}.tgz"
appcast 'http://jumpcut.sf.net/jumpcut.appcast.xml',
:sha256 => '908a13b8cf3ef67128d6bd1a09ef6f7e70a60e7c39f67e36d1a178fcb30bb38c'
homepage 'http://jumpcut.sourceforge.net/'
license :oss
app 'Jumpcut.app'
end
|
cask 'keybase' do
version '2.12.4-20181228150844,7724569b6d'
sha256 '40d1d9641ab06dd6357c8dbc8514ea875b7e90796fd08a5ca318c36cd752b8f1'
url "https://prerelease.keybase.io/darwin-updates/Keybase-#{version.before_comma}%2B#{version.after_comma}.zip"
appcast 'https://prerelease.keybase.io/update-darwin-prod-v2.json'
name 'Keybase'
homepage 'https://keybase.io/'
auto_updates true
app 'Keybase.app'
postflight do
system_command "#{appdir}/Keybase.app/Contents/SharedSupport/bin/keybase",
args: ['install-auto']
end
uninstall delete: '/Library/PrivilegedHelperTools/keybase.Helper',
launchctl: 'keybase.Helper',
login_item: 'Keybase',
signal: [
['TERM', 'keybase.Electron'],
['TERM', 'keybase.ElectronHelper'],
['KILL', 'keybase.Electron'],
['KILL', 'keybase.ElectronHelper'],
],
script: {
executable: "#{appdir}/Keybase.app/Contents/SharedSupport/bin/keybase",
args: ['uninstall'],
}
zap trash: [
'~/Library/Application Support/Keybase',
'~/Library/Caches/Keybase',
'~/Library/Group Containers/keybase',
'~/Library/Logs/Keybase*',
'~/Library/Logs/keybase*',
'~/Library/Preferences/keybase*',
'/Library/Logs/keybase*',
],
rmdir: '/keybase'
end
Update keybase to 2.12.5-20190101204726,c4dec09f95 (#56860)
cask 'keybase' do
version '2.12.5-20190101204726,c4dec09f95'
sha256 'b8804ef86bb3a189563de38cfbdd185825d449e59eb962da374a9ef416247b1f'
url "https://prerelease.keybase.io/darwin-updates/Keybase-#{version.before_comma}%2B#{version.after_comma}.zip"
appcast 'https://prerelease.keybase.io/update-darwin-prod-v2.json'
name 'Keybase'
homepage 'https://keybase.io/'
auto_updates true
app 'Keybase.app'
postflight do
system_command "#{appdir}/Keybase.app/Contents/SharedSupport/bin/keybase",
args: ['install-auto']
end
uninstall delete: '/Library/PrivilegedHelperTools/keybase.Helper',
launchctl: 'keybase.Helper',
login_item: 'Keybase',
signal: [
['TERM', 'keybase.Electron'],
['TERM', 'keybase.ElectronHelper'],
['KILL', 'keybase.Electron'],
['KILL', 'keybase.ElectronHelper'],
],
script: {
executable: "#{appdir}/Keybase.app/Contents/SharedSupport/bin/keybase",
args: ['uninstall'],
}
zap trash: [
'~/Library/Application Support/Keybase',
'~/Library/Caches/Keybase',
'~/Library/Group Containers/keybase',
'~/Library/Logs/Keybase*',
'~/Library/Logs/keybase*',
'~/Library/Preferences/keybase*',
'/Library/Logs/keybase*',
],
rmdir: '/keybase'
end
|
cask :v1 => 'm3unify' do
version '1.4.0'
sha256 '861921244bf6dd530bedc65cf65b3f8858beacb02bd8227d1f17b0b9391ee4df'
url "http://dougscripts.com/itunes/scrx/m3unifyv#{version.delete('.')}.zip"
name 'M3Unify'
appcast 'http://dougscripts.com/itunes/itinfo/m3unify_appcast.xml',
:sha256 => '9e120bf105c1089546f88ca341817430cb5514e98b5e60b77d901e5f94cf444b'
homepage 'http://dougscripts.com/itunes/itinfo/m3unify.php'
license :commercial
app 'M3Unify.app'
end
Update M3Unify to 1.4.1
cask :v1 => 'm3unify' do
version '1.4.1'
sha256 'aceda65ecb588fd51380e4dc77cd6c1b95070b60fd30e65b50ba093b11efcc1f'
url "http://dougscripts.com/itunes/scrx/m3unifyv#{version.delete('.')}.zip"
name 'M3Unify'
appcast 'http://dougscripts.com/itunes/itinfo/m3unify_appcast.xml',
:sha256 => '9e120bf105c1089546f88ca341817430cb5514e98b5e60b77d901e5f94cf444b'
homepage 'http://dougscripts.com/itunes/itinfo/m3unify.php'
license :commercial
app 'M3Unify.app'
end
|
class Macgdbp < Cask
version '1.5'
sha256 '90697835c77c0a294cea7aec62276fbf6920763968e5c77a0791199c7d718744'
url "https://www.bluestatic.org/downloads/macgdbp/macgdbp-#{version}.zip"
appcast 'https://www.bluestatic.org/versioncast.php/macgdbp'
homepage 'https://www.bluestatic.org/software/macgdbp/'
license :unknown
app 'MacGDBp.app'
end
add appcast :sha256 in macgdbp
class Macgdbp < Cask
version '1.5'
sha256 '90697835c77c0a294cea7aec62276fbf6920763968e5c77a0791199c7d718744'
url "https://www.bluestatic.org/downloads/macgdbp/macgdbp-#{version}.zip"
appcast 'https://www.bluestatic.org/versioncast.php/macgdbp',
:sha256 => '5c1c3548e8e993df1bd38d0d0c5149e8e4312566da858bbfdbbe83ca93793048'
homepage 'https://www.bluestatic.org/software/macgdbp/'
license :unknown
app 'MacGDBp.app'
end
|
cask :v1 => 'mailbox' do
version '0.4.2_150316'
sha256 '5431ef92b83f5752193cbdaf2ae82a0798537c8b84426bc09c5367a7345875c7'
# amazonaws.com is the official download host per the vendor homepage
url "https://mb-dtop.s3.amazonaws.com/external-beta/Mailbox_EXT_Beta_#{version}.zip"
appcast 'https://mb-dtop.s3.amazonaws.com/external-beta/external-beta-appcast.xml',
:sha256 => '7f1958d4be2af3ea5283bc586f97d73df07cb559ae954f4914815529d99e62dc'
name 'Mailbox'
homepage 'https://www.mailboxapp.com/'
license :gratis
app 'Mailbox (Beta).app'
zap :delete => '~/Library/Caches/com.dropbox.mbd.external-beta/'
end
Update Mailbox to 0.7.2
cask :v1 => 'mailbox' do
version '0.7.2'
sha256 '4472d761e05b99dc15f0476c7092ad6138bb8de1399c907452cfc5bf08196391'
# hockeyapp.net is the official download host per the appcast feed
url 'https://rink.hockeyapp.net/api/2/apps/0de2e5766e01cde1f6c0fd5b9862c730/app_versions/4?format=zip&avtoken=b70a5f71b15fc402ec1db83426c0ecd6d2601f6b'
appcast 'https://rink.hockeyapp.net/api/2/apps/0de2e5766e01cde1f6c0fd5b9862c730',
:sha256 => '0a511ea99347c010c1df7ce45027ba412bedf47bde35de089bc5d13c3ba6c779'
name 'Mailbox'
homepage 'https://www.mailboxapp.com/'
license :gratis
app 'Mailbox (Beta).app'
zap :delete => [
'~/Library/Caches/com.dropbox.mailbox/',
'~/Library/Containers/com.dropbox.mailbox/'
]
end
|
cask "molotov" do
version "4.4.4"
sha256 "bb719e48fc2ac61e3f5491135547fe3eab89fccadc29fbb73e4b4b3f60b7375c"
url "https://desktop-auto-upgrade.molotov.tv/mac/Molotov-v#{version}.dmg"
name "Molotov"
desc "French TV streaming service"
homepage "https://www.molotov.tv/"
livecheck do
url "https://desktop-auto-upgrade.molotov.tv/mac/manifest.json"
strategy :page_match
regex(%r{/Molotov-v?(\d+(?:\.\d+)*)-mac\.zip}i)
end
app "Molotov.app"
end
Update molotov from 4.4.4 to 4.4.6 (#111830)
cask "molotov" do
version "4.4.6"
sha256 "8d133568386e88fbf90f85e827ccb809d79cfd068a9ed5b3dee3fd29450a54b4"
url "https://desktop-auto-upgrade.molotov.tv/mac/Molotov-#{version}-mac.zip"
name "Molotov"
desc "French TV streaming service"
homepage "https://www.molotov.tv/"
livecheck do
url "https://desktop-auto-upgrade.molotov.tv/mac/manifest.json"
strategy :page_match
regex(%r{/Molotov-v?(\d+(?:\.\d+)*)-mac\.zip}i)
end
app "Molotov.app"
end
|
cask 'mt32emu' do
version '2.0.0'
sha256 'b0a8434a6de660725723bd822c00a2bbb24c06ee9f2fd994961fa3dbb1b1bbd1'
url "https://downloads.sourceforge.net/munt/munt/#{version}/OS%20X/MT32Emu-qt-1.4.0.dmg"
appcast 'https://sourceforge.net/projects/munt/rss?path=/munt',
checkpoint: 'bec1a2eb6dd50e93a10a8f1e479860531cb1e61f7cd8f55a2992c774a995833c'
name 'MT32Emu'
homepage 'https://sourceforge.net/projects/munt/'
app 'MT32Emu.app'
end
Update mt32emu to 2.1.0 (#32575)
cask 'mt32emu' do
version '2.1.0'
sha256 'c9c39386ac04a97a29d7ec661021e43b2b365bbd7dcecb1edd7de135182b20bc'
url "https://downloads.sourceforge.net/munt/munt/#{version}/OS%20X/MT32Emu-qt-1.5.0.dmg"
appcast 'https://sourceforge.net/projects/munt/rss?path=/munt',
checkpoint: '372b2206914571d17f480d2cc11dc718bbf4d134d9992f1bd592c91396288eba'
name 'MT32Emu'
homepage 'https://sourceforge.net/projects/munt/'
app 'MT32Emu.app'
end
|
cask 'noiz2sa' do
version '0.51.5'
sha256 'eb4d7f0a133b5e1541edb3b13209af58093f9a6a9fcc1296fec88552a967306d'
url "https://workram.com/downloads/Noiz2sa-for-OS-X-#{version}.dmg"
appcast 'https://workram.com/games/noiz2sa/',
checkpoint: '7d75d2d0426fbf93afc384cff783faf59f5feecf592abc194146eeb13bd01f15'
name 'Noiz2sa'
homepage 'https://workram.com/games/noiz2sa/'
app 'Noiz2sa.app'
end
Update noiz2sa to 0.51.5 (#34124)
cask 'noiz2sa' do
version '0.51.5'
sha256 'eb4d7f0a133b5e1541edb3b13209af58093f9a6a9fcc1296fec88552a967306d'
url "https://workram.com/downloads/Noiz2sa-for-OS-X-#{version}.dmg"
appcast 'https://workram.com/games/noiz2sa/',
checkpoint: '3c92353aee8455acd1d51f88410a69d9ebac3d53368501e0ed24a14cba05bbfa'
name 'Noiz2sa'
homepage 'https://workram.com/games/noiz2sa/'
app 'Noiz2sa.app'
end
|
cask :v1 => 'opacity' do
version :latest
sha256 :no_check
url 'http://downloads.likethought.com/opacity.zip'
homepage 'http://likethought.com/opacity/'
license :unknown # todo: improve this machine-generated value
app 'Opacity.app'
end
opacity.rb: change ':unknown' license comment
cask :v1 => 'opacity' do
version :latest
sha256 :no_check
url 'http://downloads.likethought.com/opacity.zip'
homepage 'http://likethought.com/opacity/'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
app 'Opacity.app'
end
|
cask "opencpn" do
version "5.2.4,1.6b314e6"
sha256 "05152e347480519bc010bb334b27601520671ae32953d8e915131ed54da738ca"
url "https://github.com/OpenCPN/OpenCPN/releases/download/Release_#{version.csv.first}/OpenCPN_#{version.csv.first}+#{version.csv.second}.pkg",
verified: "github.com/OpenCPN/OpenCPN/"
name "OpenCPN"
desc "Full-featured and concise ChartPlotter/Navigator"
homepage "https://www.opencpn.org/"
livecheck do
url "https://github.com/OpenCPN/OpenCPN/releases/latest"
strategy :page_match do |page|
match = page.match(%r{href=.*?/OpenCPN_(\d+(?:\.\d+)*)\+(.*?)\.pkg}i)
next if match.blank?
"#{match[1]},#{match[2]}"
end
end
pkg "OpenCPN_#{version.csv.first}+#{version.csv.second}.pkg"
uninstall pkgutil: [
"org.opencpn.pkg.OpenCPN",
"org.opencpn",
]
end
Update opencpn from 5.2.4 to 5.6.0 (#120083)
* Update opencpn from 5.2.4 to 5.6.0
* opencpn: fix livecheck
cask "opencpn" do
version "5.6.0"
sha256 "29d0a9fb9f140dcf900404015888873293e0a34cd80032fe0cf1acc47140c579"
url "https://github.com/OpenCPN/OpenCPN/releases/download/Release_#{version}/OpenCPN_#{version}.pkg",
verified: "github.com/OpenCPN/OpenCPN/"
name "OpenCPN"
desc "Full-featured and concise ChartPlotter/Navigator"
homepage "https://www.opencpn.org/"
livecheck do
url :url
regex(/v?(\d+(?:\.\d+)+)$/i)
end
pkg "OpenCPN_#{version}.pkg"
uninstall pkgutil: [
"org.opencpn.pkg.OpenCPN",
"org.opencpn",
]
end
|
cask "permute" do
version "3.9.2,2600"
sha256 "3bbd116aba4f819374b791befda25388f12be59ae038e48f8dfa64eb77d2a8ba"
url "https://software.charliemonroe.net/trial/permute/v#{version.major}/Permute_#{version.major}_#{version.csv.second}.dmg"
name "Permute"
desc "Converts and edits video, audio or image files"
homepage "https://software.charliemonroe.net/permute/"
livecheck do
url "https://software.charliemonroe.net/trial/permute/v#{version.major}/updates.xml"
strategy :sparkle
end
auto_updates true
depends_on macos: ">= :sierra"
app "Permute #{version.major}.app"
zap trash: [
"~/Library/Containers/com.charliemonroe.Permute-#{version.major}",
"~/Library/Preferences/com.charliemonroe.Permute-#{version.major}.plist",
]
end
permute 3.9.3,2605
Update permute from 3.9.2 to 3.9.3
Closes #124215.
Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com>
cask "permute" do
version "3.9.3,2605"
sha256 "a061f748eb0b0132a2ef3efd2962755000e13e36b56d85395fcf87f415b1baa1"
url "https://software.charliemonroe.net/trial/permute/v#{version.major}/Permute_#{version.major}_#{version.csv.second}.dmg"
name "Permute"
desc "Converts and edits video, audio or image files"
homepage "https://software.charliemonroe.net/permute/"
livecheck do
url "https://software.charliemonroe.net/trial/permute/v#{version.major}/updates.xml"
strategy :sparkle
end
auto_updates true
depends_on macos: ">= :sierra"
app "Permute #{version.major}.app"
zap trash: [
"~/Library/Containers/com.charliemonroe.Permute-#{version.major}",
"~/Library/Preferences/com.charliemonroe.Permute-#{version.major}.plist",
]
end
|
cask "permute" do
version "3.9,2591"
sha256 "4784da93e0b72567b8a9f05b66369302d42c6a9e57145882d3a0e963c6da8521"
url "https://software.charliemonroe.net/trial/permute/v#{version.major}/Permute_#{version.major}_#{version.csv.second}.dmg"
name "Permute"
desc "Converts and edits video, audio or image files"
homepage "https://software.charliemonroe.net/permute/"
livecheck do
url "https://software.charliemonroe.net/trial/permute/v#{version.major}/updates.xml"
strategy :sparkle
end
auto_updates true
depends_on macos: ">= :sierra"
app "Permute #{version.major}.app"
zap trash: [
"~/Library/Containers/com.charliemonroe.Permute-#{version.major}",
"~/Library/Preferences/com.charliemonroe.Permute-#{version.major}.plist",
]
end
permute 3.9.1,2595
Update permute from 3.9 to 3.9.1
Closes #122508.
Signed-off-by: Sean Molenaar <2b250e3fea88cfef248b497ad5fc17f7dc435154@users.noreply.github.com>
Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com>
cask "permute" do
version "3.9.1,2595"
sha256 "79e3bce6fdcb0332d8f142c91c6a46e362609eeaa2f12d958dbfb0eb4bb74502"
url "https://software.charliemonroe.net/trial/permute/v#{version.major}/Permute_#{version.major}_#{version.csv.second}.dmg"
name "Permute"
desc "Converts and edits video, audio or image files"
homepage "https://software.charliemonroe.net/permute/"
livecheck do
url "https://software.charliemonroe.net/trial/permute/v#{version.major}/updates.xml"
strategy :sparkle
end
auto_updates true
depends_on macos: ">= :sierra"
app "Permute #{version.major}.app"
zap trash: [
"~/Library/Containers/com.charliemonroe.Permute-#{version.major}",
"~/Library/Preferences/com.charliemonroe.Permute-#{version.major}.plist",
]
end
|
cask 'pomello' do
version '0.10.6'
sha256 '55c4ffd8f2e49f9fac3b754f5f40c14fc5ccc9371b96610168fb73f9b1641678'
url 'https://pomelloapp.com/download/mac/latest'
appcast 'https://pomelloapp.com/download/mac'
name 'Pomello'
homepage 'https://pomelloapp.com/'
app 'Pomello.app'
end
Update pomello from 0.10.6 to 0.10.7 (#61793)
cask 'pomello' do
version '0.10.7'
sha256 '9535536d27a12947572343909d71510bdfd678a32e47720ffb1ff455b07adc7f'
url 'https://pomelloapp.com/download/mac/latest'
appcast 'https://pomelloapp.com/download/mac'
name 'Pomello'
homepage 'https://pomelloapp.com/'
app 'Pomello.app'
end
|
Add Postico.app v0.19
cask :v1 => 'postico' do
version '0.19'
sha256 'd312e2c64872f8c45b1cd1ed1bff88f944c007f9e634c21aac0bee5f0b185503'
url "https://eggerapps.at/postico/download/postico-#{version}.zip"
name 'Postico'
homepage 'https://eggerapps.at/postico/'
license :freemium
app 'Postico.app'
depends_on :macos => '>= :mountain_lion'
end
|
cask "postico" do
version "1.5.16"
sha256 "23c79a6ddcb4a7fcb5a2ebba8a482aefb80dfaa6d421c037735573fac2abe5b1"
url "https://eggerapps-downloads.s3.amazonaws.com/postico-#{version}.zip",
verified: "eggerapps-downloads.s3.amazonaws.com/"
appcast "https://eggerapps.at/postico/docs/?file=changelist.html"
name "Postico"
desc "GUI client for PostgreSQL databases"
homepage "https://eggerapps.at/postico/"
app "Postico.app"
zap trash: [
"~/Library/Application Scripts/at.eggerapps.Postico",
"~/Library/Containers/at.eggerapps.Postico",
"~/Library/Preferences/at.eggerapps.Postico.plist",
"~/Library/Saved Application State/at.eggerapps.Postico.savedState",
]
end
Update postico from 1.5.16 to 1.5.17 (#96084)
cask "postico" do
version "1.5.17"
sha256 "a83e95f0b6ec6086b84ec7c97c159aaca8d2449e9fa59f5d1ee982cfd27e0143"
url "https://eggerapps-downloads.s3.amazonaws.com/postico-#{version}.zip",
verified: "eggerapps-downloads.s3.amazonaws.com/"
appcast "https://eggerapps.at/postico/docs/?file=changelist.html"
name "Postico"
desc "GUI client for PostgreSQL databases"
homepage "https://eggerapps.at/postico/"
app "Postico.app"
zap trash: [
"~/Library/Application Scripts/at.eggerapps.Postico",
"~/Library/Containers/at.eggerapps.Postico",
"~/Library/Preferences/at.eggerapps.Postico.plist",
"~/Library/Saved Application State/at.eggerapps.Postico.savedState",
]
end
|
cask "pro-fit" do
version "7.0.17"
sha256 "761aaf7f1688d736b4544387aae9dfa20007f552ea3017925864bc3c096ce625"
url "https://quantum-soft.com/profit/pro_Fit_#{version.dots_to_underscores}.dmg",
verified: "quantum-soft.com/"
appcast "https://www.quansoft.com/hist.html"
name "pro Fit"
homepage "https://www.quansoft.com/"
app "pro Fit #{version.major}.app"
end
Delete pro-fit.rb (#110496)
|
class Pycharm < Cask
url 'http://download.jetbrains.com/python/pycharm-professional-3.1.3.dmg'
homepage 'http://www.jetbrains.com/pycharm/'
version '3.1.3'
sha256 '3c1025db0520e19cdec3d8f7e4497b5de55f103b9a677770097f64e4f1c69c48'
link 'PyCharm.app'
end
Fix Pycharm sha256 metadata
class Pycharm < Cask
url 'http://download.jetbrains.com/python/pycharm-professional-3.1.3.dmg'
homepage 'http://www.jetbrains.com/pycharm/'
version '3.1.3'
sha256 'a1cd576dde0d49b6212b19932adc1192743b7fb50034396168e1521fe39f37cc'
link 'PyCharm.app'
end
|
cask "remnote" do
version "1.8.1"
sha256 "f9c26cb9e9649549d9c7d799bc642f65828d191ff50caf21bffd8d25df8a9e69"
url "https://download.remnote.io/RemNote-#{version}.dmg",
verified: "remnote.io"
name "RemNote"
desc "Spaced-repetition powered note-taking tool"
homepage "https://www.remnote.com/"
livecheck do
url "https://s3.amazonaws.com/download.remnote.io/latest-mac.yml"
strategy :electron_builder
end
app "RemNote.app"
zap trash: [
"~/Library/Application Support/RemNote",
"~/Library/Preferences/io.remnote.plist",
"~/Library/Saved Application State/io.remnote.savedState",
]
end
remnote 1.8.2
Update remnote from 1.8.1 to 1.8.2
Closes #127303.
Signed-off-by: Sean Molenaar <2b250e3fea88cfef248b497ad5fc17f7dc435154@users.noreply.github.com>
Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com>
cask "remnote" do
version "1.8.2"
sha256 "76e015c6987afd313b4520cbbf7a6288d4218f4c8ee0dad9d6b4935cc16bcaf7"
url "https://download.remnote.io/RemNote-#{version}.dmg",
verified: "remnote.io"
name "RemNote"
desc "Spaced-repetition powered note-taking tool"
homepage "https://www.remnote.com/"
livecheck do
url "https://s3.amazonaws.com/download.remnote.io/latest-mac.yml"
strategy :electron_builder
end
app "RemNote.app"
zap trash: [
"~/Library/Application Support/RemNote",
"~/Library/Preferences/io.remnote.plist",
"~/Library/Saved Application State/io.remnote.savedState",
]
end
|
cask 'renamer' do
version :latest
sha256 :no_check
# creativebe.com is the official download host per the vendor homepage
url 'http://creativebe.com/download/renamer'
appcast 'https://storage.googleapis.com/incrediblebee/appcasts/renamer.xml',
:checkpoint => '01b82d78af9bb61ddcec8bd09da3bd29464b678b84ec61c16da4692b868cf732'
name 'Renamer'
homepage 'http://renamer.com'
license :commercial
app 'Renamer.app'
end
updated renamer (4.3.3)
cask 'renamer' do
version '4.3.3'
sha256 'cd4308d8555ad7e17851c45a71904b5695e2467f9ad499d64de36a9be0f522b0'
# creativebe.com is the official download host per the vendor homepage
url 'http://creativebe.com/download/renamer'
appcast 'https://storage.googleapis.com/incrediblebee/appcasts/renamer.xml',
:checkpoint => '01b82d78af9bb61ddcec8bd09da3bd29464b678b84ec61c16da4692b868cf732'
name 'Renamer'
homepage 'http://renamer.com'
license :commercial
app 'Renamer.app'
end
|
cask 'restool' do
version '0.3.0'
sha256 'a5b85a8483006adcf91bf9ebdc1d21084ae0616a56d582ece1335db4d8786746'
url "https://github.com/Nikola-K/RESTool/releases/download/v#{version}/RESTool_#{version}_osx.zip"
appcast 'https://github.com/Nikola-K/RESTool/releases.atom',
checkpoint: 'a6287fdb9b482425d972a87911fcbe7a80bc6097b15ccca065f9a3daf60d74e7'
name 'RESTool'
homepage 'https://nikola-k.github.io/RESTool/'
license :apache
app 'RESTool.app'
end
restool.rb: updated vendor comment
cask 'restool' do
version '0.3.0'
sha256 'a5b85a8483006adcf91bf9ebdc1d21084ae0616a56d582ece1335db4d8786746'
# github.com/Nikola-K/RESTool was verified as official when first introduced to the cask
url "https://github.com/Nikola-K/RESTool/releases/download/v#{version}/RESTool_#{version}_osx.zip"
appcast 'https://github.com/Nikola-K/RESTool/releases.atom',
checkpoint: 'a6287fdb9b482425d972a87911fcbe7a80bc6097b15ccca065f9a3daf60d74e7'
name 'RESTool'
homepage 'https://nikola-k.github.io/RESTool/'
license :apache
app 'RESTool.app'
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.