CombinedText stringlengths 4 3.42M |
|---|
require 'base64'
require 'openssl'
module Pickme
class Policy
attr_accessor :expiry, :call, :handle, :maxsize, :minsize, :path
def initialize(options = {})
[:expiry, :call, :handle, :maxsize, :minsize, :path].each do |input|
send("#{input}=", options[input]) unless options[input].nil?
end
end
def policy
@policy ||= Base64.urlsafe_encode64(json_policy)
end
def signature
OpenSSL::HMAC.hexdigest('sha256', Pickme.config.secret_key, policy)
end
def apply(call = [:read, :convert], keys = ['policy', 'signature'])
raise SecretKeyMissing if Pickme.config.secret_key.nil?
self.call = call
{
keys[0] => policy,
keys[1] => signature
}
end
private
def json_policy
hash = { expiry: Pickme.config.expiry.call }
[:expiry, :call, :handle, :maxsize, :minsize, :path].each do |input|
hash[input] = send(input) unless send(input).nil?
end
MultiJson.dump(hash)
end
end
end
Remove Expiry from Recalculation Every Time
require 'base64'
require 'openssl'
module Pickme
class Policy
attr_accessor :expiry, :call, :handle, :maxsize, :minsize, :path
def initialize(options = {})
[:expiry, :call, :handle, :maxsize, :minsize, :path].each do |input|
send("#{input}=", options[input]) unless options[input].nil?
end
end
def policy
@policy ||= Base64.urlsafe_encode64(json_policy)
end
def signature
OpenSSL::HMAC.hexdigest('sha256', Pickme.config.secret_key, policy)
end
def apply(call = [:read, :convert], keys = ['policy', 'signature'])
raise SecretKeyMissing if Pickme.config.secret_key.nil?
self.call = call
{
keys[0] => policy,
keys[1] => signature
}
end
private
def json_policy
hash = { expiry: Pickme.config.expiry.call }
[:call, :handle, :maxsize, :minsize, :path].each do |input|
hash[input] = send(input) unless send(input).nil?
end
MultiJson.dump(hash)
end
end
end
|
require 'json'
module PkgForge
##
# Add state methods to Forge
class Forge
Contract String => nil
def load_state(statefile)
state = JSON.parse(File.read(statefile))
@tmpfiles = state[:tmpfiles]
@tmpdirs = state[:tmpdirs]
end
Contract String => nil
def write_state!(statefile)
File.open(statefile, 'w') do |fh|
fh << {
tmpfiles: @tmpfiles,
tmpdirs: @tmpdirs
}.to_json
end
end
end
end
update to meet contract
require 'json'
module PkgForge
##
# Add state methods to Forge
class Forge
Contract String => nil
def load_state(statefile)
state = JSON.parse(File.read(statefile))
@tmpfiles = state[:tmpfiles]
@tmpdirs = state[:tmpdirs]
end
Contract String => nil
def write_state!(statefile)
File.open(statefile, 'w') do |fh|
fh << {
tmpfiles: @tmpfiles,
tmpdirs: @tmpdirs
}.to_json
end
nil
end
end
end
|
class Class
def inject(*deps)
check_pinball
if @dependencies
@dependencies.concat(deps)
else
@dependencies = deps
end
end
def check_pinball
unless self.is_a? Pinball
self.extend Pinball
end
end
end
class_inject
class Class
def inject(*deps)
check_pinball
if @dependencies
@dependencies.concat(deps)
else
@dependencies = deps
end
end
def class_inject(*deps)
deps.each do |dep|
define_singleton_method dep do
Pinball::Container.instance.items[dep].fetch(self)
end
end
end
def check_pinball
unless self.is_a? Pinball
self.extend Pinball
end
end
end |
require 'pkgr/buildpack'
require 'pkgr/process'
require 'pkgr/distributions/base'
require 'pkgr/fpm_command'
module Pkgr
module Distributions
# Contains the various components required to make a packaged app integrate well with a Debian system.
class Debian < Base
# Only keep major digits
def release
@release[/^[0-9]+/]
end
def runner
@runner ||= case release
when /^8/, /^9/, /^10/
Runner.new("systemd", "default", "systemctl")
else
Runner.new("sysv", "lsb-3.1", "update-rc.d")
end
end
def package_test_command(package)
"dpkg -s '#{package}' > /dev/null 2>&1"
end
def package_install_command(packages)
"sudo apt-get update && sudo apt-get install --force-yes -y #{packages.map{|package| "\"#{package}\""}.join(" ")}"
end
def installer_dependencies
super.push("debianutils").uniq
end
def fpm_command(build_dir)
DebianFpmCommand.new(self, build_dir).command
end
def verify(output_dir)
Dir.glob(File.join(output_dir, "*deb")).each do |package|
puts "-----> Verifying package #{File.basename(package)}"
Dir.mktmpdir do |dir|
verify_package = Mixlib::ShellOut.new %{dpkg-deb -x #{package} #{dir}}
verify_package.logger = Pkgr.logger
verify_package.run_command
verify_package.error!
end
end
end
def debconfig
@debconfig ||= begin
tmpfile = Tempfile.new("debconfig")
tmpfile.puts "#!/bin/bash"
tmpfile.rewind
tmpfile
end
@debconfig
end
def debtemplates
@debtemplates ||= Tempfile.new("debtemplates")
end
class DebianFpmCommand < FpmCommand
def args
list = super
list << "-t" << "deb"
list << "--deb-user" << "root"
list << "--deb-group" << "root"
list
end
end
end
end
end
require 'pkgr/distributions/ubuntu'
Fix #90
require 'pkgr/buildpack'
require 'pkgr/process'
require 'pkgr/distributions/base'
require 'pkgr/fpm_command'
module Pkgr
module Distributions
# Contains the various components required to make a packaged app integrate well with a Debian system.
class Debian < Base
# Only keep major digits
def release
@release[/^[0-9]+/]
end
def runner
@runner ||= case release
when /^8/, /^9/, /^10/
Runner.new("systemd", "default", "systemctl")
else
Runner.new("sysv", "lsb-3.1", "update-rc.d")
end
end
def package_test_command(package)
"dpkg -s '#{package}' > /dev/null 2>&1"
end
def package_install_command(packages)
"sudo apt-get update && sudo apt-get install --force-yes -y #{packages.map{|package| "\"#{package}\""}.join(" ")}"
end
def installer_dependencies
super.push("debianutils").uniq
end
def fpm_command(build_dir)
DebianFpmCommand.new(self, build_dir).command
end
def verify(output_dir)
Dir.glob(File.join(output_dir, "*deb")).each do |package|
puts "-----> Verifying package #{File.basename(package)}"
Dir.mktmpdir do |dir|
verify_package = Mixlib::ShellOut.new %{dpkg-deb -x "#{package}" "#{dir}"}
verify_package.logger = Pkgr.logger
verify_package.run_command
verify_package.error!
end
end
end
def debconfig
@debconfig ||= begin
tmpfile = Tempfile.new("debconfig")
tmpfile.puts "#!/bin/bash"
tmpfile.rewind
tmpfile
end
@debconfig
end
def debtemplates
@debtemplates ||= Tempfile.new("debtemplates")
end
class DebianFpmCommand < FpmCommand
def args
list = super
list << "-t" << "deb"
list << "--deb-user" << "root"
list << "--deb-group" << "root"
list
end
end
end
end
end
require 'pkgr/distributions/ubuntu'
|
require 'nokogiri'
require 'open-uri'
require 'pry-byebug'
require_relative 'ad'
require_relative 'ad_box'
require_relative 'helper'
# Group of place.ge real estate ads
class PlaceGeAdGroup
def initialize(start_date, end_date)
set_dates(start_date, end_date)
@finished_scraping = false
@found_simple_ad = false
scrape_ad_ids
end
def set_dates(start_date, end_date)
@start_date = start_date
@end_date = end_date
check_dates_are_valid
end
def check_dates_are_valid
if @start_date > @end_date
puts "\nERROR: The start date cannot be after the end date\n\n"
fail
elsif @start_date > Date.today
puts "\nERROR: The start date cannot be after today\n\n"
fail
elsif @end_date > Date.today
puts "\nERROR: The end date cannot be after today\n\n"
fail
end
end
def to_s
"Found #{@ad_ids.size} ads posted between #{@start_date} and #{@end_date}"
end
def scrape_ad_ids
if @start_date == @end_date
puts "\n---> Finding ids of ads posted on #{@start_date}"
else
puts "\n---> Finding ids of ads posted between #{@start_date} and #{@end_date}"
end
@ad_ids = []
page_num = 1
limit = 1000
while not_finished_scraping?
link = "http://place.ge/ge/ads/page:#{page_num}?object_type=all¤cy_id=2&mode=list&order_by=date&limit=#{limit}"
scrape_ad_ids_from_page(link)
page_num += 1
end
puts "\nFinished scraping ad ids; found #{@ad_ids.size} ads\n"
puts '--------------------------------------------------'
end
def scrape_ad_ids_from_page(link)
puts '--------------------------------------------------'
puts "-----> Scraping #{link}"
page = Nokogiri.HTML(open(link))
ad_boxes = page.css('.tr-line')
ad_boxes.each do |ad_box_html|
process_ad_box(PlaceGeAdBox.new(ad_box_html))
if finished_scraping?
break
end
end
puts "\n-----> Found #{@ad_ids.size} ads posted between #{@start_date} and #{@end_date} so far"
end
def process_ad_box(ad_box)
if ad_box.between_dates?(@start_date, @end_date)
# Save ad id if it has not been saved to @ad_ids yet
unless @ad_ids.include?(ad_box.id)
@ad_ids.push(ad_box.id)
puts "-------> Found #{ad_box.id} (posted on #{ad_box.pub_date})"
end
# Record when the first simple ad is found to allow scraping to finish
@found_simple_ad = true if not_found_simple_ad? && ad_box.simple?
else
# First must find simple ad, then stop when the next simple ad is found
@finished_scraping = true if found_simple_ad? && ad_box.simple?
end
end
def finished_scraping?
@finished_scraping
end
def not_finished_scraping?
!@finished_scraping
end
def found_simple_ad?
@found_simple_ad
end
def not_found_simple_ad?
!@found_simple_ad
end
end
Added function to ad group to scrape full ad info using PlaceGeAd class.
require 'nokogiri'
require 'open-uri'
require 'pry-byebug'
require_relative 'ad'
require_relative 'ad_box'
require_relative 'helper'
# Group of place.ge real estate ads
class PlaceGeAdGroup
def initialize(start_date, end_date)
set_dates(start_date, end_date)
scrape_ad_ids
scrape_ads
end
def set_dates(start_date, end_date)
@start_date = start_date
@end_date = end_date
check_dates_are_valid
end
def check_dates_are_valid
if @start_date > @end_date
puts "\nERROR: The start date cannot be after the end date\n\n"
fail
elsif @start_date > Date.today
puts "\nERROR: The start date cannot be after today\n\n"
fail
elsif @end_date > Date.today
puts "\nERROR: The end date cannot be after today\n\n"
fail
end
end
def to_s
"Found #{@ad_ids.size} ads posted between #{@start_date} and #{@end_date}"
end
########################################################################
# Scrape ad ids #
def scrape_ad_ids
if @start_date == @end_date
puts "\n---> Finding ids of ads posted on #{@start_date}"
else
puts "\n---> Finding ids of ads posted between #{@start_date} and #{@end_date}"
end
@finished_scraping_ids = false
@found_simple_ad_box = false
@ad_ids = []
page_num = 1
limit = 1000
while not_finished_scraping_ids?
link = "http://place.ge/ge/ads/page:#{page_num}?object_type=all¤cy_id=2&mode=list&order_by=date&limit=#{limit}"
scrape_ad_ids_from_page(link)
page_num += 1
end
puts "\nFinished scraping ad ids; found #{@ad_ids.size} ads\n"
puts '--------------------------------------------------'
end
def scrape_ad_ids_from_page(link)
puts '--------------------------------------------------'
puts "-----> Scraping #{link}"
page = Nokogiri.HTML(open(link))
ad_boxes = page.css('.tr-line')
ad_boxes.each do |ad_box_html|
process_ad_box(PlaceGeAdBox.new(ad_box_html))
if finished_scraping_ids?
break
end
end
if @start_date == @end_date
puts "\n-----> Found #{@ad_ids.size} ads posted on #{@start_date} so far"
else
puts "\n-----> Found #{@ad_ids.size} ads posted between #{@start_date} and #{@end_date} so far"
end
end
def process_ad_box(ad_box)
if ad_box.between_dates?(@start_date, @end_date)
# Save ad id if it has not been saved to @ad_ids yet
unless @ad_ids.include?(ad_box.id)
@ad_ids.push(ad_box.id)
puts "-------> Found #{ad_box.id} (posted on #{ad_box.pub_date})"
end
# Record when the first simple ad is found to allow scraping to finish
@found_simple_ad_box = true if not_found_simple_ad_box? && ad_box.simple?
else
# First must find simple ad, then stop when the next simple ad is found
@finished_scraping_ids = true if found_simple_ad_box? && ad_box.simple?
end
end
def finished_scraping_ids?
@finished_scraping_ids
end
def not_finished_scraping_ids?
!@finished_scraping_ids
end
def found_simple_ad_box?
@found_simple_ad_box
end
def not_found_simple_ad_box?
!@found_simple_ad_box
end
########################################################################
# Scraping full ad info #
def scrape_ads
if @start_date == @end_date
puts "\n---> Scraping info of ads posted on #{@start_date}"
else
puts "\n---> Scraping info of ads posted between #{@start_date} and #{@end_date}"
end
@ads = []
@ad_ids.each do |ad_id|
puts "\n-----> Scraping info for ad with id #{ad_id}"
@ads.push(PlaceGeAd.new(ad_id))
end
end
end
|
module Pixiv
VERSION = "0.0.2"
end
Bump version to 0.0.3.pre
module Pixiv
VERSION = "0.0.3.pre"
end
|
require 'application/configuration'
require 'application/test_helpers'
include lib/ in requires
require 'lib/application/configuration'
require 'lib/application/test_helpers'
|
module PolicyAssertions
VERSION = '0.0.1'
end
version bump 0.0.2
module PolicyAssertions
VERSION = '0.0.2'
end
|
module PostageApp::FailedRequest
# Stores request object into a file for future re-send
# returns true if stored, false if not (due to undefined project path)
def self.store(request)
return false if !store_path || !PostageApp.configuration.requests_to_resend.member?(request.method.to_s)
open(file_path(request.uid), 'w') do |f|
f.write(Marshal.dump(request))
end unless File.exists?(file_path(request.uid))
PostageApp.logger.info "STORING FAILED REQUEST [#{request.uid}]"
true
end
# Attempting to resend failed requests
def self.resend_all
return false if !store_path
Dir.foreach(store_path) do |filename|
next if !filename.match /^\w{40}$/
request = initialize_request(filename)
receipt_response = PostageApp::Request.new(:get_message_receipt, :uid => filename).send(true)
if receipt_response.ok?
PostageApp.logger.info "NOT RESENDING FAILED REQUEST [#{filename}]"
File.delete(file_path(filename))
elsif receipt_response.not_found?
PostageApp.logger.info "RESENDING FAILED REQUEST [#{filename}]"
response = request.send(true)
# Not a fail, so we can remove this file, if it was then
# there will be another attempt to resend
File.delete(file_path(filename)) if !response.fail?
end
end
return
end
# Initializing PostageApp::Request object from the file
def self.initialize_request(uid)
return false if !store_path
Marshal.load(File.read(file_path(uid))) if File.exists?(file_path(uid))
end
protected
def self.store_path
return if !PostageApp.configuration.project_root
dir = File.join(File.expand_path(PostageApp.configuration.project_root), 'tmp/postageapp_failed_requests')
FileUtils.mkdir_p(dir) unless File.exists?(dir)
return dir
end
def self.file_path(uid)
File.join(store_path, uid)
end
end
adding a rescue when already deleted file wants to be deleted again
module PostageApp::FailedRequest
# Stores request object into a file for future re-send
# returns true if stored, false if not (due to undefined project path)
def self.store(request)
return false if !store_path || !PostageApp.configuration.requests_to_resend.member?(request.method.to_s)
open(file_path(request.uid), 'w') do |f|
f.write(Marshal.dump(request))
end unless File.exists?(file_path(request.uid))
PostageApp.logger.info "STORING FAILED REQUEST [#{request.uid}]"
true
end
# Attempting to resend failed requests
def self.resend_all
return false if !store_path
Dir.foreach(store_path) do |filename|
next if !filename.match /^\w{40}$/
request = initialize_request(filename)
receipt_response = PostageApp::Request.new(:get_message_receipt, :uid => filename).send(true)
if receipt_response.ok?
PostageApp.logger.info "NOT RESENDING FAILED REQUEST [#{filename}]"
File.delete(file_path(filename)) rescue nil
elsif receipt_response.not_found?
PostageApp.logger.info "RESENDING FAILED REQUEST [#{filename}]"
response = request.send(true)
# Not a fail, so we can remove this file, if it was then
# there will be another attempt to resend
File.delete(file_path(filename)) rescue nil if !response.fail?
end
end
return
end
# Initializing PostageApp::Request object from the file
def self.initialize_request(uid)
return false if !store_path
Marshal.load(File.read(file_path(uid))) if File.exists?(file_path(uid))
end
protected
def self.store_path
return if !PostageApp.configuration.project_root
dir = File.join(File.expand_path(PostageApp.configuration.project_root), 'tmp/postageapp_failed_requests')
FileUtils.mkdir_p(dir) unless File.exists?(dir)
return dir
end
def self.file_path(uid)
File.join(store_path, uid)
end
end |
require 'fileutils'
require 'provision/storage'
require 'provision/log'
class Provision::Storage::Service
include Provision::Log
def initialize(storage_options)
@storage_types = {}
storage_options.each do |storage_type, settings|
arch = settings[:arch] || raise("Storage service requires each storage type to specify the 'arch' setting")
options = settings[:options] || raise("Storage service requires each storage type to specify the 'options' setting")
require "provision/storage/#{arch.downcase}"
instance = Provision::Storage.const_get(arch).new(options)
@storage_types[storage_type] = instance
end
end
def prepare_storage(name, storage_spec, temp_dir)
create_storage(name, storage_spec)
init_filesystems(name, storage_spec)
mount_filesystems(name, storage_spec, temp_dir)
end
def finish_preparing_storage(name, storage_spec, temp_dir)
create_fstab(storage_spec, temp_dir)
unmount_filesystems(name, storage_spec, temp_dir)
end
def cleanup(name)
Provision::Storage.cleanup(name)
end
def get_storage(type)
return @storage_types[type]
end
def create_storage(name, storage_spec)
ordered_keys = order_keys(storage_spec.keys)
ordered_keys.each do |mount_point|
settings = storage_spec[mount_point]
type = settings[:type].to_sym
size = settings[:size]
get_storage(type).create(name, size)
end
end
def init_filesystems(name, storage_spec)
ordered_keys = order_keys(storage_spec.keys)
ordered_keys.each do |mount_point|
settings = storage_spec[mount_point]
storage = get_storage(settings[:type].to_sym)
prepare = settings[:prepare] || {}
case mount_point.to_s
when '/'
prepare.merge!({:method => :image}) if prepare[:method].nil?
settings[:prepare] = prepare
end
storage.init_filesystem(name, settings)
end
end
def mount_filesystems(name, storage_spec, tempdir)
ordered_keys = order_keys(storage_spec.keys)
ordered_keys.each do |mount_point|
actual_mount_point = "#{tempdir}#{mount_point}"
settings = storage_spec[mount_point]
type = settings[:type].to_sym
case mount_point
when '/'
get_storage(type).mount(name, actual_mount_point, true)
else
unless File.exists? actual_mount_point
FileUtils.mkdir_p actual_mount_point
end
get_storage(type).mount(name, actual_mount_point, false)
end
end
end
def unmount_filesystems(name, storage_spec, tempdir)
ordered_keys = order_keys(storage_spec.keys)
ordered_keys.reverse.each do |mount_point|
actual_mount_point = "#{tempdir}#{mount_point}"
settings = storage_spec[mount_point]
type = settings[:type].to_sym
case mount_point
when '/'
get_storage(type).unmount(name, actual_mount_point, true)
else
get_storage(type).unmount(name, actual_mount_point, false)
end
end
end
def remove_storage(name, storage_spec)
ordered_keys = order_keys(storage_spec.keys)
ordered_keys.reverse.each do |mount_point|
settings = storage_spec[mount_point]
type = settings[:type].to_sym
get_storage(type).remove(name)
end
end
def spec_to_xml(name, storage_spec)
template_file = "#{Provision.base}/templates/disk.template"
xml_output = ""
drive_letters = ('a'..'z').to_a
current_drive_letter = 0
ordered_keys = order_keys(storage_spec.keys)
ordered_keys.each do |mount_point|
settings = storage_spec[mount_point]
type = settings[:type].to_sym
storage = get_storage(type)
source = storage.libvirt_source(name)
target = "dev='vd#{drive_letters[current_drive_letter]}'"
template = ERB.new(File.read(template_file))
xml_output = xml_output + template.result(binding)
current_drive_letter = current_drive_letter + 1
end
xml_output
end
def create_fstab(storage_spec, tempdir)
fstab = "#{tempdir}/etc/fstab"
drive_letters = ('a'..'z').to_a
current_drive_letter = 0
ordered_keys = order_keys(storage_spec.keys)
File.open(fstab, 'a') do |f|
fstype = 'ext4'
ordered_keys.each do |mount_point|
begin
fstype = storage_spec[mount_point][:prepare][:options][:type]
rescue NoMethodError=>e
if e.name == '[]'.to_sym
log.debug "fstype not found, using default value: #{fstype}"
else
raise e
end
end
f.puts("/dev/vd#{drive_letters[current_drive_letter]}1 #{mount_point} #{fstype} defaults 0 0")
current_drive_letter = current_drive_letter + 1
end
end
end
private
def order_keys(keys)
keys.map! do |key|
key.to_s
end
keys.sort!
keys.map! do |key|
key.to_sym
end
keys
end
end
Create a way to NOT create fstab files as part of the storage_service.
require 'fileutils'
require 'provision/storage'
require 'provision/log'
class Provision::Storage::Service
include Provision::Log
def initialize(storage_options)
@storage_types = {}
storage_options.each do |storage_type, settings|
arch = settings[:arch] || raise("Storage service requires each storage type to specify the 'arch' setting")
options = settings[:options] || raise("Storage service requires each storage type to specify the 'options' setting")
require "provision/storage/#{arch.downcase}"
instance = Provision::Storage.const_get(arch).new(options)
@storage_types[storage_type] = instance
end
end
def prepare_storage(name, storage_spec, temp_dir)
create_storage(name, storage_spec)
init_filesystems(name, storage_spec)
mount_filesystems(name, storage_spec, temp_dir)
end
def finish_preparing_storage(name, storage_spec, temp_dir)
create_fstab(storage_spec, temp_dir)
unmount_filesystems(name, storage_spec, temp_dir)
end
def cleanup(name)
Provision::Storage.cleanup(name)
end
def get_storage(type)
return @storage_types[type]
end
def create_storage(name, storage_spec)
ordered_keys = order_keys(storage_spec.keys)
ordered_keys.each do |mount_point|
settings = storage_spec[mount_point]
type = settings[:type].to_sym
size = settings[:size]
get_storage(type).create(name, size)
end
end
def init_filesystems(name, storage_spec)
ordered_keys = order_keys(storage_spec.keys)
ordered_keys.each do |mount_point|
settings = storage_spec[mount_point]
storage = get_storage(settings[:type].to_sym)
prepare = settings[:prepare] || {}
case mount_point.to_s
when '/'
prepare.merge!({:method => :image}) if prepare[:method].nil?
settings[:prepare] = prepare
end
storage.init_filesystem(name, settings)
end
end
def mount_filesystems(name, storage_spec, tempdir)
ordered_keys = order_keys(storage_spec.keys)
ordered_keys.each do |mount_point|
actual_mount_point = "#{tempdir}#{mount_point}"
settings = storage_spec[mount_point]
type = settings[:type].to_sym
case mount_point
when '/'
get_storage(type).mount(name, actual_mount_point, true)
else
unless File.exists? actual_mount_point
FileUtils.mkdir_p actual_mount_point
end
get_storage(type).mount(name, actual_mount_point, false)
end
end
end
def unmount_filesystems(name, storage_spec, tempdir)
ordered_keys = order_keys(storage_spec.keys)
ordered_keys.reverse.each do |mount_point|
actual_mount_point = "#{tempdir}#{mount_point}"
settings = storage_spec[mount_point]
type = settings[:type].to_sym
case mount_point
when '/'
get_storage(type).unmount(name, actual_mount_point, true)
else
get_storage(type).unmount(name, actual_mount_point, false)
end
end
end
def remove_storage(name, storage_spec)
ordered_keys = order_keys(storage_spec.keys)
ordered_keys.reverse.each do |mount_point|
settings = storage_spec[mount_point]
type = settings[:type].to_sym
get_storage(type).remove(name)
end
end
def spec_to_xml(name, storage_spec)
template_file = "#{Provision.base}/templates/disk.template"
xml_output = ""
drive_letters = ('a'..'z').to_a
current_drive_letter = 0
ordered_keys = order_keys(storage_spec.keys)
ordered_keys.each do |mount_point|
settings = storage_spec[mount_point]
type = settings[:type].to_sym
storage = get_storage(type)
source = storage.libvirt_source(name)
target = "dev='vd#{drive_letters[current_drive_letter]}'"
template = ERB.new(File.read(template_file))
xml_output = xml_output + template.result(binding)
current_drive_letter = current_drive_letter + 1
end
xml_output
end
def create_fstab(storage_spec, tempdir)
prepare_options = storage_spec[mount_point][:prepare][:options]
create_fstab = prepare_options[:create_fstab].nil? ? true : prepare_options[:create_fstab]
unless prepare_options[:create_fstab] = false
fstab = "#{tempdir}/etc/fstab"
drive_letters = ('a'..'z').to_a
current_drive_letter = 0
ordered_keys = order_keys(storage_spec.keys)
File.open(fstab, 'a') do |f|
fstype = 'ext4'
ordered_keys.each do |mount_point|
begin
fstype = prepare_options[:type]
rescue NoMethodError=>e
if e.name == '[]'.to_sym
log.debug "fstype not found, using default value: #{fstype}"
else
raise e
end
end
f.puts("/dev/vd#{drive_letters[current_drive_letter]}1 #{mount_point} #{fstype} defaults 0 0")
current_drive_letter = current_drive_letter + 1
end
end
end
end
private
def order_keys(keys)
keys.map! do |key|
key.to_s
end
keys.sort!
keys.map! do |key|
key.to_sym
end
keys
end
end
|
# The PublicBodyCategories structure works like this:
# [
# "Main category name",
# [ "tag_to_use_as_category", "Sub category title", "sentence that can describes things in this subcategory" ],
# [ "another_tag", "Second sub category title", "another descriptive sentence for things in this subcategory"],
# "Another main category name",
# [ "another_tag_2", "Another sub category title", "another descriptive sentence"]
# ])
PublicBodyCategories.add(:en,
[ "Federal",
[ "agriculture", "Agriculture", "part of the Agriculture portfolio" ],
[ "attorney-general","Attorney-General","part of the Attorney-General portfolio" ],
[ "communications","Communications","part of the Communications portfolio" ],
[ "defence","Defence","part of the Defence portfolio" ],
[ "education_and_training","Education and Training","part of the Education and Training portfolio" ],
[ "employment","Employment","part of the Employment portfolio" ],
[ "environment","Environment","part of the Environment portfolio" ],
[ "finance","Finance","part of the Finance portfolio" ],
[ "foreign_affairs_and_trade","Foreign Affairs and Trade","part of the Foreign Affairs and Trade portfolio" ],
[ "health","Health","part of the Health portfolio" ],
[ "immigration_and_border_protection","Immigration & Border Protection","part of the Immigration & Border Protection portfolio" ],
[ "industry_science","Industry and Science","part of the Industry and Science portfolio" ],
[ "infrastructure_and_regional_development","Infrastructure and Regional Development","part of the Infrastructure and Regional Development portfolio" ],
[ "environment","Environment","part of the Environment portfolio" ],
[ "prime_ministert","Prime Minister","part of the Prime Minister portfolio" ],
[ "social_services","Social Services","part of the Social Services portfolio" ],
[ "treasury","Treasury","part of the Treasury portfolio" ],
[ "veterans_affairs","Veterans' Affairs","part of the Veterans' Affairs portfolio" ],
[ "minister","Ministers","Politicians who run Government Departments" ],
[ "federal", "All Federal Authorities", "part of the Federal Government"],
"States and Territories",
[ "ACT_state","ACT Authorities","Description of ACT Authorities" ],
[ "NSW_state","NSW Authorities","Includes education, health, the environment, and emergency services in ACT" ],
[ "NSW_council","NSW Councils","Includes garbage collections, public parks and sporting grounds, libraries, and local planning" ],
[ "NT_state","NT Authorities","" ],
[ "QLD_state","QLD Authorities","State Authorities, including Schools" ],
[ "QLD_council","QLD Councils","description of local authorities" ],
[ "TAS_state","TAS Authorities","including schools" ],
[ "TAS_council","TAS Councils","description of local authorities" ],
[ "SA_state","SA Authorities","including schools" ],
[ "SA_council","SA Councils","description of local authorities" ],
[ "VIC_state","VIC Authorities","including schools" ],
[ "VIC_council","VIC Councils","description of local authorities" ],
[ "WA_state","WA Authorities","including schools" ],
[ "WA_council","WA Councils","description of local authorities" ],
]
)
Change tag
# The PublicBodyCategories structure works like this:
# [
# "Main category name",
# [ "tag_to_use_as_category", "Sub category title", "sentence that can describes things in this subcategory" ],
# [ "another_tag", "Second sub category title", "another descriptive sentence for things in this subcategory"],
# "Another main category name",
# [ "another_tag_2", "Another sub category title", "another descriptive sentence"]
# ])
PublicBodyCategories.add(:en,
[ "Federal",
[ "agriculture", "Agriculture", "part of the Agriculture portfolio" ],
[ "attorney-general","Attorney-General","part of the Attorney-General portfolio" ],
[ "communications","Communications","part of the Communications portfolio" ],
[ "defence","Defence","part of the Defence portfolio" ],
[ "education_and_training","Education and Training","part of the Education and Training portfolio" ],
[ "employment","Employment","part of the Employment portfolio" ],
[ "environment","Environment","part of the Environment portfolio" ],
[ "finance","Finance","part of the Finance portfolio" ],
[ "foreign_affairs_and_trade","Foreign Affairs and Trade","part of the Foreign Affairs and Trade portfolio" ],
[ "health","Health","part of the Health portfolio" ],
[ "immigration_and_border_protection","Immigration & Border Protection","part of the Immigration & Border Protection portfolio" ],
[ "industry_and_science","Industry and Science","part of the Industry and Science portfolio" ],
[ "infrastructure_and_regional_development","Infrastructure and Regional Development","part of the Infrastructure and Regional Development portfolio" ],
[ "environment","Environment","part of the Environment portfolio" ],
[ "prime_ministert","Prime Minister","part of the Prime Minister portfolio" ],
[ "social_services","Social Services","part of the Social Services portfolio" ],
[ "treasury","Treasury","part of the Treasury portfolio" ],
[ "veterans_affairs","Veterans' Affairs","part of the Veterans' Affairs portfolio" ],
[ "minister","Ministers","Politicians who run Government Departments" ],
[ "federal", "All Federal Authorities", "part of the Federal Government"],
"States and Territories",
[ "ACT_state","ACT Authorities","Description of ACT Authorities" ],
[ "NSW_state","NSW Authorities","Includes education, health, the environment, and emergency services in ACT" ],
[ "NSW_council","NSW Councils","Includes garbage collections, public parks and sporting grounds, libraries, and local planning" ],
[ "NT_state","NT Authorities","" ],
[ "QLD_state","QLD Authorities","State Authorities, including Schools" ],
[ "QLD_council","QLD Councils","description of local authorities" ],
[ "TAS_state","TAS Authorities","including schools" ],
[ "TAS_council","TAS Councils","description of local authorities" ],
[ "SA_state","SA Authorities","including schools" ],
[ "SA_council","SA Councils","description of local authorities" ],
[ "VIC_state","VIC Authorities","including schools" ],
[ "VIC_council","VIC Councils","description of local authorities" ],
[ "WA_state","WA Authorities","including schools" ],
[ "WA_council","WA Councils","description of local authorities" ],
]
)
|
PublicBodyCategories.add(:es, [
"Poder Ejecutivo",
["presidencia","Presidencia y Org. Asociados", "una agencia de presidencia"],
["ministerio","Ministerios", "un ministerio"],
["direcciones", "Direcciones", "una direccion de ministerio"],
["museos", " Museos", "un museo"],
["embajadas", "Embajadas", "Una Embajada Uruguaya"],
["consulados", "Consulados", "Un Consulado Uruguayo"],
"Poder Legislativo",
["camara_de_senadores", "Camara de Senadores", "Una Camara del Legislativo"],
["camara_de_diputados", "Camara de Diputados", "Una Camara del Legislativo"],
["comision_administradora", "Comision Administradora","Una Comision Administradora del Legislativo"],
"Poder Judicial",
["justicia", " SCJ", "una unidad del Poder Judicial"],
["tribunal", "Tribunales", "un tribunal del poder judicial"],
["forense", "ITF", "un instituto del poder judicial"],
["juzgados", "Juzgados", "un juzgado del poder judicial"],
"Corte Electoral",
["corte_electoral", "Corte electoral", "una corte electoral"],
"Tribunal de lo Contencioso Administrativo",
["tribunal_contencioso_admnistrativo", "TCA", "un tribunal"],
"Tribunal de Cuentas",
["tribunal_cuentas", "TC", "un tribunal de cuentas"],
"Entes Autonomos",
["entes", "Entes", "un ente autonomo"],
["bcu", "BCU","un banco central"],
"Servicios Descentralizados",
["INAU", "INAU", "Un instituto Nacional del Nino y el Adolescente"],
"Gobiernos Departamentales",
["intendencia_montevideo", "Intendencia de Montevideo", "una intendencia"],
"Junta Departamental",
["junta_montevideo", " Junta de Montevideo", "una Junta Departamental"]
])
Se agrega IMC a Gobiernos departamentales
PublicBodyCategories.add(:es, [
"Poder Ejecutivo",
["presidencia","Presidencia y Org. Asociados", "una agencia de presidencia"],
["ministerio","Ministerios", "un ministerio"],
["direcciones", "Direcciones", "una direccion de ministerio"],
["museos", " Museos", "un museo"],
["embajadas", "Embajadas", "Una Embajada Uruguaya"],
["consulados", "Consulados", "Un Consulado Uruguayo"],
"Poder Legislativo",
["camara_de_senadores", "Camara de Senadores", "Una Camara del Legislativo"],
["camara_de_diputados", "Camara de Diputados", "Una Camara del Legislativo"],
["comision_administradora", "Comision Administradora","Una Comision Administradora del Legislativo"],
"Poder Judicial",
["justicia", " SCJ", "una unidad del Poder Judicial"],
["tribunal", "Tribunales", "un tribunal del poder judicial"],
["forense", "ITF", "un instituto del poder judicial"],
["juzgados", "Juzgados", "un juzgado del poder judicial"],
"Corte Electoral",
["corte_electoral", "Corte electoral", "una corte electoral"],
"Tribunal de lo Contencioso Administrativo",
["tribunal_contencioso_admnistrativo", "TCA", "un tribunal"],
"Tribunal de Cuentas",
["tribunal_cuentas", "TC", "un tribunal de cuentas"],
"Entes Autonomos",
["entes", "Entes", "un ente autonomo"],
["bcu", "BCU","un banco central"],
"Servicios Descentralizados",
["INAU", "INAU", "Un instituto Nacional del Nino y el Adolescente"],
"Gobiernos Departamentales",
["intendencia_montevideo", "Intendencia de Montevideo", "una intendencia"],
["intendencia_canelones", "Intendencia de Canelones", "una intendencia"]
"Junta Departamental",
["junta_montevideo", " Junta de Montevideo", "una Junta Departamental"]
])
|
# Type for IOA Interface
# Parameters are
# name - Interface Name
# shutdown - The shutdown flag of the interface, true means Shutdown else no shutdown
# vlan_tagged - Tag the given vlan numbers to the interface
# vlan_untagged - UnTag the given vlan numbers to the interface
Puppet::Type.newtype(:ioa_interface) do
@doc = "This represents Dell IOA interface."
apply_to_device
newparam(:name) do
desc "Interface name, represents interface."
isrequired
newvalues(/^\A+tengigabitethernet\s*\S+/i, /te\s*\S+$/i,/^fortygige\s*\S+$/i,/^fo\s*\S+$/i)
isnamevar
end
newproperty(:shutdown) do
desc "The shutdown flag of the interface, true means Shutdown else no shutdown"
defaultto(:false)
newvalues(:false,:true)
end
newproperty(:vlan_tagged) do
desc "Tag the given vlan numbers to the interface."
validate do |value|
return if value == :absent
all_valid_characters = value =~ /^[0-9]+$/
paramsarray=value.match(/(\d*)\s*[,-]\s*(\d*)/)
if paramsarray.nil?
raise ArgumentError, "An invalid VLAN ID #{value} is entered.The VLAN ID must be between 1 and 4094. And it should be in a format like 67,89 or 50-100 or 89" unless all_valid_characters && value.to_i >= 1 && value.to_i <= 4094
else
param1 = paramsarray[1]
param2 = paramsarray[2]
all_valid_characters = param1 =~ /^[0-9]+$/
raise ArgumentError, "An invalid VLAN ID #{param1} is entered.The VLAN ID must be between 1 and 4094." unless all_valid_characters && param1.to_i >= 1 && param1.to_i <= 4094
all_valid_characters = param2=~ /^[0-9]+$/
raise ArgumentError, "An invalid VLAN ID #{param2} is entered.The VLAN ID must be between 1 and 4094." unless all_valid_characters && param2.to_i >= 1 && param2.to_i <= 4094
end
raise ArgumentError, "An invalid VLAN ID #{value} is entered. The VLAN ID must be between 1 and 4094." unless all_valid_characters && value.to_i >= 1 && value.to_i <= 4094
end
end
newproperty(:vlan_untagged) do
desc "UnTag the given vlan numbers to the interface."
validate do |value|
return if value == :absent
all_valid_characters = value =~ /^[0-9]+$/
raise ArgumentError, "An invalid VLAN ID #{value} is entered. The VLAN ID must be between 1 and 4094." unless all_valid_characters && value.to_i >= 1 && value.to_i <= 4094
end
end
end
Rspec integration review comments dell_iom incorporated
# Type for IOA Interface
# Parameters are
# name - Interface Name
# shutdown - The shutdown flag of the interface, true means Shutdown else no shutdown
# vlan_tagged - Tag the given vlan numbers to the interface
# vlan_untagged - UnTag the given vlan numbers to the interface
Puppet::Type.newtype(:ioa_interface) do
@doc = "This represents Dell IOA interface."
apply_to_device
newparam(:name) do
desc "Interface name, represents interface."
isrequired
newvalues(/^\Atengigabitethernet\s*\S+/i, /te\s*\S+$/i,/^fortygige\s*\S+$/i,/^fo\s*\S+$/i)
isnamevar
end
newproperty(:shutdown) do
desc "The shutdown flag of the interface, true means Shutdown else no shutdown"
defaultto(:false)
newvalues(:false,:true)
end
newproperty(:vlan_tagged) do
desc "Tag the given vlan numbers to the interface."
validate do |value|
return if value == :absent
all_valid_characters = value =~ /^[0-9]+$/
paramsarray=value.match(/(\d*)\s*[,-]\s*(\d*)/)
if paramsarray.nil?
raise ArgumentError, "An invalid VLAN ID #{value} is entered.The VLAN ID must be between 1 and 4094. And it should be in a format like 67,89 or 50-100 or 89" unless all_valid_characters && value.to_i >= 1 && value.to_i <= 4094
else
param1 = paramsarray[1]
param2 = paramsarray[2]
all_valid_characters = param1 =~ /^[0-9]+$/
raise ArgumentError, "An invalid VLAN ID #{param1} is entered.The VLAN ID must be between 1 and 4094." unless all_valid_characters && param1.to_i >= 1 && param1.to_i <= 4094
all_valid_characters = param2=~ /^[0-9]+$/
raise ArgumentError, "An invalid VLAN ID #{param2} is entered.The VLAN ID must be between 1 and 4094." unless all_valid_characters && param2.to_i >= 1 && param2.to_i <= 4094
end
raise ArgumentError, "An invalid VLAN ID #{value} is entered. The VLAN ID must be between 1 and 4094." unless all_valid_characters && value.to_i >= 1 && value.to_i <= 4094
end
end
newproperty(:vlan_untagged) do
desc "UnTag the given vlan numbers to the interface."
validate do |value|
return if value == :absent
all_valid_characters = value =~ /^[0-9]+$/
raise ArgumentError, "An invalid VLAN ID #{value} is entered. The VLAN ID must be between 1 and 4094." unless all_valid_characters && value.to_i >= 1 && value.to_i <= 4094
end
end
end
|
# == Business Rules
# * The DisplayName, GivenName, MiddleName, FamilyName, and PrintOnCheckName attributes must not contain a colon,":".
# * The DisplayName attribute must be unique across all other customers, employees, vendors, and other names.
# * The PrimaryEmailAddress attribute must contain an at sign, "@," and dot, ".".
# * Nested customer objects can be used to define sub-customers, jobs, or a combination of both, under a parent.
# * Up to four levels of nesting can be defined under a top-level customer object.
# * The Job attribute defines whether the object is a top-level customer or nested sub-customer/job.
# * Either the DisplayName attribute or at least one of Title, GivenName, MiddleName, FamilyName, Suffix, or FullyQualifiedName attributes are required during create.
module Quickbooks
module Model
class Customer < BaseModel
XML_COLLECTION_NODE = "Customer"
XML_NODE = "Customer"
REST_RESOURCE = 'customer'
include NameEntity::Quality
include NameEntity::PermitAlterations
MINORVERSION = 33
xml_name XML_NODE
xml_accessor :id, :from => 'Id'
xml_accessor :sync_token, :from => 'SyncToken', :as => Integer
xml_accessor :meta_data, :from => 'MetaData', :as => MetaData
xml_accessor :title, :from => 'Title'
xml_accessor :given_name, :from => 'GivenName'
xml_accessor :middle_name, :from => 'MiddleName'
xml_accessor :family_name, :from => 'FamilyName'
xml_accessor :company_name, :from => 'CompanyName'
xml_accessor :display_name, :from => 'DisplayName'
xml_accessor :print_on_check_name, :from => 'PrintOnCheckName'
xml_accessor :active?, :from => 'Active'
xml_accessor :primary_phone, :from => 'PrimaryPhone', :as => TelephoneNumber
xml_accessor :alternate_phone, :from => 'AlternatePhone', :as => TelephoneNumber
xml_accessor :mobile_phone, :from => 'Mobile', :as => TelephoneNumber
xml_accessor :fax_phone, :from => 'Fax', :as => TelephoneNumber
xml_accessor :primary_email_address, :from => 'PrimaryEmailAddr', :as => EmailAddress
xml_accessor :web_site, :from => 'WebAddr', :as => WebSiteAddress
xml_accessor :billing_address, :from => 'BillAddr', :as => PhysicalAddress
xml_accessor :shipping_address, :from => 'ShipAddr', :as => PhysicalAddress
xml_accessor :job, :from => 'Job'
xml_accessor :bill_with_parent, :from => 'BillWithParent'
xml_accessor :parent_ref, :from => 'ParentRef', :as => BaseReference
xml_accessor :level, :from => 'Level'
xml_accessor :sales_term_ref, :from => 'SalesTermRef', :as => BaseReference
xml_accessor :payment_method_ref, :from => 'PaymentMethodRef', :as => BaseReference
xml_accessor :balance, :from => 'Balance', :as => BigDecimal, :to_xml => to_xml_big_decimal
xml_accessor :open_balance_date, :from => 'OpenBalanceDate', :as => Date
xml_accessor :balance_with_jobs, :from => 'BalanceWithJobs', :as => BigDecimal, :to_xml => to_xml_big_decimal
xml_accessor :preferred_delivery_method, :from => 'PreferredDeliveryMethod'
xml_accessor :resale_num, :from => 'ResaleNum'
xml_accessor :suffix, :from => 'Suffix'
xml_accessor :fully_qualified_name, :from => 'FullyQualifiedName'
xml_accessor :taxable, :from => 'Taxable'
xml_accessor :default_tax_code_ref, :from => 'DefaultTaxCodeRef', :as => BaseReference
xml_accessor :notes, :from => 'Notes'
xml_accessor :currency_ref, :from => 'CurrencyRef', :as => BaseReference
#== Validations
validate :names_cannot_contain_invalid_characters
validate :email_address_is_valid
reference_setters :parent_ref, :sales_term_ref, :payment_method_ref, :default_tax_code_ref, :currency_ref
def job?
job.to_s == 'true'
end
def bill_with_parent?
bill_with_parent.to_s == 'true'
end
def taxable?
taxable.to_s == 'true'
end
end
end
end
Added customer.tax_exemption_reason_id (#495)
# == Business Rules
# * The DisplayName, GivenName, MiddleName, FamilyName, and PrintOnCheckName attributes must not contain a colon,":".
# * The DisplayName attribute must be unique across all other customers, employees, vendors, and other names.
# * The PrimaryEmailAddress attribute must contain an at sign, "@," and dot, ".".
# * Nested customer objects can be used to define sub-customers, jobs, or a combination of both, under a parent.
# * Up to four levels of nesting can be defined under a top-level customer object.
# * The Job attribute defines whether the object is a top-level customer or nested sub-customer/job.
# * Either the DisplayName attribute or at least one of Title, GivenName, MiddleName, FamilyName, Suffix, or FullyQualifiedName attributes are required during create.
module Quickbooks
module Model
class Customer < BaseModel
XML_COLLECTION_NODE = "Customer"
XML_NODE = "Customer"
REST_RESOURCE = 'customer'
include NameEntity::Quality
include NameEntity::PermitAlterations
MINORVERSION = 33
xml_name XML_NODE
xml_accessor :id, :from => 'Id'
xml_accessor :sync_token, :from => 'SyncToken', :as => Integer
xml_accessor :meta_data, :from => 'MetaData', :as => MetaData
xml_accessor :title, :from => 'Title'
xml_accessor :given_name, :from => 'GivenName'
xml_accessor :middle_name, :from => 'MiddleName'
xml_accessor :family_name, :from => 'FamilyName'
xml_accessor :company_name, :from => 'CompanyName'
xml_accessor :display_name, :from => 'DisplayName'
xml_accessor :print_on_check_name, :from => 'PrintOnCheckName'
xml_accessor :active?, :from => 'Active'
xml_accessor :primary_phone, :from => 'PrimaryPhone', :as => TelephoneNumber
xml_accessor :alternate_phone, :from => 'AlternatePhone', :as => TelephoneNumber
xml_accessor :mobile_phone, :from => 'Mobile', :as => TelephoneNumber
xml_accessor :fax_phone, :from => 'Fax', :as => TelephoneNumber
xml_accessor :primary_email_address, :from => 'PrimaryEmailAddr', :as => EmailAddress
xml_accessor :web_site, :from => 'WebAddr', :as => WebSiteAddress
xml_accessor :billing_address, :from => 'BillAddr', :as => PhysicalAddress
xml_accessor :shipping_address, :from => 'ShipAddr', :as => PhysicalAddress
xml_accessor :job, :from => 'Job'
xml_accessor :bill_with_parent, :from => 'BillWithParent'
xml_accessor :parent_ref, :from => 'ParentRef', :as => BaseReference
xml_accessor :level, :from => 'Level'
xml_accessor :sales_term_ref, :from => 'SalesTermRef', :as => BaseReference
xml_accessor :payment_method_ref, :from => 'PaymentMethodRef', :as => BaseReference
xml_accessor :balance, :from => 'Balance', :as => BigDecimal, :to_xml => to_xml_big_decimal
xml_accessor :open_balance_date, :from => 'OpenBalanceDate', :as => Date
xml_accessor :balance_with_jobs, :from => 'BalanceWithJobs', :as => BigDecimal, :to_xml => to_xml_big_decimal
xml_accessor :preferred_delivery_method, :from => 'PreferredDeliveryMethod'
xml_accessor :resale_num, :from => 'ResaleNum'
xml_accessor :suffix, :from => 'Suffix'
xml_accessor :fully_qualified_name, :from => 'FullyQualifiedName'
xml_accessor :taxable, :from => 'Taxable'
xml_accessor :default_tax_code_ref, :from => 'DefaultTaxCodeRef', :as => BaseReference
xml_accessor :notes, :from => 'Notes'
xml_accessor :currency_ref, :from => 'CurrencyRef', :as => BaseReference
xml_accessor :tax_exemption_reason_id, :from => 'TaxExemptionReasonId'
#== Validations
validate :names_cannot_contain_invalid_characters
validate :email_address_is_valid
reference_setters :parent_ref, :sales_term_ref, :payment_method_ref, :default_tax_code_ref, :currency_ref
def job?
job.to_s == 'true'
end
def bill_with_parent?
bill_with_parent.to_s == 'true'
end
def taxable?
taxable.to_s == 'true'
end
end
end
end
|
module Rambulance
class ExceptionsApp < ActionController::Base
def self.call(env)
action(:render_error).call(env)
end
def render_error
@_status = env["PATH_INFO"][1..-1].to_i
@_response.status = @_status
@_body = { :status => @_status, :error => Rack::Utils::HTTP_STATUS_CODES.fetch(@_status.to_i, Rack::Utils::HTTP_STATUS_CODES[500]) }
public_send(status_in_words) if respond_to?(status_in_words)
if response_body.blank?
render(template: template_path, layout: Rambulance.layout_name)
end
end
private
def status_in_words
Rack::Utils::SYMBOL_TO_STATUS_CODE.invert[status.to_i]
end
def exception
env["action_dispatch.exception"]
end
def template_path
"#{Rambulance.view_path}/#{status_in_words}"
end
end
end
:scissors:
module Rambulance
class ExceptionsApp < ActionController::Base
def self.call(env)
action(:render_error).call(env)
end
def render_error
@_status = env["PATH_INFO"][1..-1].to_i
@_response.status = @_status
@_body = { :status => @_status, :error => Rack::Utils::HTTP_STATUS_CODES.fetch(@_status.to_i, Rack::Utils::HTTP_STATUS_CODES[500]) }
public_send(status_in_words) if respond_to?(status_in_words)
if response_body.blank?
render(template: template_path, layout: Rambulance.layout_name)
end
end
private
def status_in_words
Rack::Utils::SYMBOL_TO_STATUS_CODE.invert[status.to_i]
end
def exception
env["action_dispatch.exception"]
end
def template_path
"#{Rambulance.view_path}/#{status_in_words}"
end
end
end
|
#
# Copyright 2015, Noah Kantrowitz
#
# 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 'poise_service/options_resource'
require 'poise_service/providers'
require 'poise_service/resource'
module PoiseService
end
Load the user resource.
#
# Copyright 2015, Noah Kantrowitz
#
# 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 'poise_service/options_resource'
require 'poise_service/providers'
require 'poise_service/resource'
require 'poise_service/user_resource'
module PoiseService
end
|
module Powify
class Client
class << self
def run(args = [])
begin
if args[0] && args[0].strip != 'help'
return Powify::Server.run(args[1..-1]) if args[0].strip == 'server'
return Powify::Server.run(args[1..-1]) if args[0].strip == 'utils'
return Powify::App.run(args)
end
rescue Exception => e
$stdout.puts e
end
help
end
def help
$stdout.puts ""
$stdout.puts " [SERVER COMMANDS]"
$stdout.puts " powify server install install pow server"
$stdout.puts " powify server reinstall reinstall pow server"
$stdout.puts " powify server update update pow server"
$stdout.puts " powify server uninstall uninstall pow server"
$stdout.puts " powify server list list all pow apps"
$stdout.puts " powify server start start the pow server"
$stdout.puts " powify server stop stop the pow server"
$stdout.puts " powify server restart restart the pow server"
$stdout.puts " powify server status print the current server status"
$stdout.puts " powify server config print the current server configuration"
$stdout.puts " powify server logs tails the pow server logs"
$stdout.puts ""
$stdout.puts " [UTILS COMMANDS]"
$stdout.puts " powify utils install install powify.dev server management tool"
$stdout.puts " powify utils reinstall reinstall powify.dev server management tool"
$stdout.puts " powify utils uninstall uninstall powify.dev server management tool"
$stdout.puts ""
$stdout.puts " [APP COMMANDS]"
$stdout.puts " powify create [NAME] creates a pow app from the current directory"
$stdout.puts " powify destroy [NAME] destroys the pow app linked to the current directory"
$stdout.puts " powify restart [NAME] restarts the pow app linked to the current directory"
$stdout.puts " powify always_restart [NAME] reload the pow app after each request"
$stdout.puts " powify rename [NAME] rename the pow app to [NAME]"
$stdout.puts " powify rename [OLD] [NEW] rename the pow app [OLD] to [NEW]"
$stdout.puts " powify environment [ENV] run the this pow app in a different environment (aliased `env`)"
$stdout.puts " powify browse [NAME] opens and navigates the default browser to this app"
$stdout.puts " powify logs [NAME] tail the application logs"
$stdout.puts ""
end
end
end
end
actually run from Utils class #copypastefail
module Powify
class Client
class << self
def run(args = [])
begin
if args[0] && args[0].strip != 'help'
return Powify::Server.run(args[1..-1]) if args[0].strip == 'server'
return Powify::Utils.run(args[1..-1]) if args[0].strip == 'utils'
return Powify::App.run(args)
end
rescue Exception => e
$stdout.puts e
end
help
end
def help
$stdout.puts ""
$stdout.puts " [SERVER COMMANDS]"
$stdout.puts " powify server install install pow server"
$stdout.puts " powify server reinstall reinstall pow server"
$stdout.puts " powify server update update pow server"
$stdout.puts " powify server uninstall uninstall pow server"
$stdout.puts " powify server list list all pow apps"
$stdout.puts " powify server start start the pow server"
$stdout.puts " powify server stop stop the pow server"
$stdout.puts " powify server restart restart the pow server"
$stdout.puts " powify server status print the current server status"
$stdout.puts " powify server config print the current server configuration"
$stdout.puts " powify server logs tails the pow server logs"
$stdout.puts ""
$stdout.puts " [UTILS COMMANDS]"
$stdout.puts " powify utils install install powify.dev server management tool"
$stdout.puts " powify utils reinstall reinstall powify.dev server management tool"
$stdout.puts " powify utils uninstall uninstall powify.dev server management tool"
$stdout.puts ""
$stdout.puts " [APP COMMANDS]"
$stdout.puts " powify create [NAME] creates a pow app from the current directory"
$stdout.puts " powify destroy [NAME] destroys the pow app linked to the current directory"
$stdout.puts " powify restart [NAME] restarts the pow app linked to the current directory"
$stdout.puts " powify always_restart [NAME] reload the pow app after each request"
$stdout.puts " powify rename [NAME] rename the pow app to [NAME]"
$stdout.puts " powify rename [OLD] [NEW] rename the pow app [OLD] to [NEW]"
$stdout.puts " powify environment [ENV] run the this pow app in a different environment (aliased `env`)"
$stdout.puts " powify browse [NAME] opens and navigates the default browser to this app"
$stdout.puts " powify logs [NAME] tail the application logs"
$stdout.puts ""
end
end
end
end |
require 'tempfile'
module Pronto
class Runner
include Plugin
def self.runners
repository
end
def create_tempfile(blob)
return if blob.nil?
file = Tempfile.new(blob.oid)
file.write(blob.text)
file.close
file
end
end
end
Add ability for create_tempfile do deal with a block
require 'tempfile'
module Pronto
class Runner
include Plugin
def self.runners
repository
end
def create_tempfile(blob)
return if blob.nil?
file = Tempfile.new(blob.oid)
file.write(blob.text)
begin
if block_given?
file.flush
yield(file)
else
file
end
ensure
file.close unless file.closed?
end
end
end
end
|
require 'pubnub/configuration'
require 'pubnub/parser'
require 'pubnub/single_request'
require 'pubnub/subscription'
require 'pubnub/envelope'
require 'pubnub/crypto'
require 'pubnub/uuid'
require 'pubnub/exceptions'
require 'pubnub/middleware/response'
require 'pubnub/middleware/request'
# TODO Split every operation as separate modules?
module Pubnub
class Client
include Configuration
include Subscription
include SingleRequest
VERSION = Pubnub::VERSION
attr_reader :env
# While creating new Pubnub::Client instance it checks for
def initialize(options)
check_required_parameters(:initialize, options)
setup_env(options)
run_em unless EM.reactor_running?
register_faraday_middleware
setup_connections(@env) # We're using @env not options because it has default values that could be necessary
end
# TODO well documented subscribe examples
def subscribe(options, &block)
$logger.debug('Calling subscribe')
options.merge!({ :action => :subscribe })
options.merge!({ :callback => block }) if block_given?
check_required_parameters(:subscribe, options)
options[:channel] = options[:channels] if options[:channel].blank? && !options[:channels].blank?
options[:channel] = Subscription.format_channels(options[:channel])
options[:channel] = options[:channel].gsub('+','%20')
preform_subscribe(@env.merge(options))
end
# TODO well documented presence examples
def presence(options, &block)
$logger.debug('Calling presence')
options.merge!({ :action => :presence })
options.merge!({ :callback => block }) if block_given?
check_required_parameters(:presence, options)
options[:channel] = Subscription.format_channels_for_presence(options[:channel])
options[:channel] = options[:channel].gsub('+','%20')
preform_subscribe(@env.merge(options))
end
# TODO well documented leave examples
def leave(options, &block)
$logger.debug('Calling leave')
options.merge!({ :action => :leave })
options.merge!({ :callback => block }) if block_given?
check_required_parameters(:leave, options)
options[:channel] = options[:channel].to_s.gsub('+','%20')
preform_single_request(@env.merge(options))
end
# TODO well documented leave examples
def publish(options, &block)
$logger.debug('Calling publish')
options.merge!({ :action => :publish })
options.merge!({ :callback => block }) if block_given?
check_required_parameters(:publish, options)
options[:channel] = options[:channel].to_s.gsub('+','%20')
preform_single_request(@env.merge(options))
end
# TODO well documented history examples
def history(options, &block)
$logger.debug('Calling history')
options.merge!({ :action => :history })
options.merge!({ :callback => block }) if block_given?
check_required_parameters(:history, options)
options[:channel] = options[:channel].to_s.gsub('+','%20')
preform_single_request(@env.merge(options))
end
# TODO well documented here_now examples
def here_now(options, &block)
$logger.debug('Calling here_now')
options.merge!({ :action => :here_now })
options.merge!({ :callback => block }) if block_given?
check_required_parameters(:here_now, options)
options[:channel] = options[:channel].to_s.gsub('+','%20')
preform_single_request(@env.merge(options))
end
# TODO well documented audit examples
def audit(options, &block)
$logger.debug('Calling audit')
options.merge!({ :action => :audit })
options.merge!({ :callback => block }) if block_given?
check_required_parameters(:audit, options)
options[:channel] = options[:channel].to_s.gsub('+','%20')
options = treat_auth_key_param_as_param(options)
preform_single_request(@env.merge(options))
end
# TODO well documented grant examples
def grant(options, &block)
$logger.debug('Calling grant')
options.merge!({ :action => :grant })
options.merge!({ :callback => block }) if block_given?
check_required_parameters(:grant, options)
options[:channel] = options[:channel].to_s.gsub('+','%20')
options = treat_auth_key_param_as_param(options)
preform_single_request(@env.merge(options))
end
# TODO well documented revoke examples
def revoke(options, &block)
$logger.debug('Calling revoke')
options.merge!({ :action => :grant })
options.merge!({ :callback => block }) if block_given?
check_required_parameters(:grant, options)
options[:channel] = options[:channel].to_s.gsub('+','%20')
options = treat_auth_key_param_as_param(options)
options[:read] = false if options[:read]
options[:write] = false if options[:write]
preform_single_request(@env.merge(options))
end
# Returns current timetoken from server
def time(options, &block)
$logger.debug('Calling time')
options.merge!({ :action => :time })
options.merge!({ :callback => block }) if block_given?
check_required_parameters(:time, options)
preform_single_request(@env.merge(options))
end
def set_secret_key(secret_key)
@env[:secret_key] = secret_key
end
alias_method 'secret=', 'set_secret_key'
alias_method 'secret_key=', 'set_secret_key'
def set_uuid(uuid)
$logger.debug('Setting new UUID')
@env[:uuid] = uuid
end
alias_method 'uuid=', 'set_uuid'
alias_method 'session_uuid=', 'set_uuid'
def set_ssl(ssl)
$logger.debug('Setting SSL')
@env[:ssl] = ssl
end
alias_method 'ssl=', 'set_ssl'
def set_cipher_key(cipher_key)
@env[:cipher_key] = cipher_key
end
alias_method 'cipher_key=', 'set_cipher_key'
def set_auth_key(auth_key)
@env[:auth_key] = auth_key
end
alias_method 'auth_key=', 'set_auth_key'
# For some backwards compatibility
def uuid
@env[:uuid]
end
# For some backwards compatibility
def ssl
@env[:ssl]
end
# For some backwards compatibility
def secret_key
@env[:secret_key]
end
# Gracefully closes all connections
def exit
binding.pry
end
private
# Sterts event machine reactor in new thread
def run_em
$logger.debug('Starting EventMachine')
Thread.new { EM.run }
# block thread until EM starts
until EM.reactor_running? do end
end
def register_faraday_middleware
$logger.debug('Registering faraday middleware')
Faraday::Response.register_middleware :response, :pubnub => Pubnub::Middleware::Response
Faraday::Request.register_middleware :request, :pubnub => Pubnub::Middleware::Request
end
# Returns url for connections depending on origin and enabled ssl
def url_for_connection(options)
"http#{options[:ssl] ? 's' : ''}://#{options[:origin]}"
end
def origin_already_registered?(origin)
!@subscribe_connections_pool[origin].nil?
end
def setup_subscribe_connection(options)
$logger.debug('Setting subscribe connection')
@subscribe_connections_pool = Hash.new if @subscribe_connections_pool.nil?
@subscribe_connections_pool[options[:origin]] = Faraday.new(:url => url_for_connection(options)) do |faraday|
faraday.adapter :net_http_persistent
faraday.response :pubnub
faraday.request :pubnub
end
$logger.debug('Created subscribe connection')
end
def setup_single_event_connection(options)
@single_event_connections_pool = Hash.new if @single_event_connections_pool.nil?
@single_event_connections_pool[options[:origin]] = Faraday.new(:url => url_for_connection(options)) do |faraday|
faraday.adapter :net_http_persistent
faraday.response :pubnub
faraday.request :pubnub
end
$logger.debug('Created single event connection')
end
# Sets up two persistent connections via Faraday with pubnub middleware
def setup_connections(options)
setup_subscribe_connection(options)
setup_single_event_connection(options)
end
# Returns converted env hash with all non-symbol keys in given env hash into symbols
def symbolize_options(options)
$logger.debug('Symbolizing options')
symbolized_options = {}
options.each_key { |k| symbolized_options.merge!({ k.to_sym => options[k] }) }
symbolized_options
end
# Checks if given key is already set, if not, sets default value
def set_default_value_if_not_set(key, default_value)
@env[key] = default_value if @env[key].nil?
end
# Create valid and complete @env variable
# @env holds whole configuration and is merged with options that are passed to REST actions
# so values form env overridden by request options are available in every action
def setup_env(options)
# Setup logger or let's create default one
$logger = options[:logger] || Logger.new('pubnub.log', 'weekly')
# We must be sure if every key is symbol
@env = symbolize_options options
set_default_values
$logger.debug('Created environment')
end
def set_default_values
defaults = {
:error_callback => DEFAULT_ERROR_CALLBACK,
:connect_callback => DEFAULT_CONNECT_CALLBACK,
:ssl => DEFAULT_SSL,
:timetoken => DEFAULT_TIMETOKEN,
:uuid => UUID.new.generate,
:port => DEFAULT_CONNECTION_PORT,
:origin => DEFAULT_ORIGIN,
:subscribe_timeout => DEFAULT_SUBSCRIBE_TIMEOUT,
:timeout => DEFAULT_NON_SUBSCRIBE_TIMEOUT,
:max_retries => MAX_RETRIES,
:non_subscribe_timeout => DEFAULT_NON_SUBSCRIBE_TIMEOUT,
:reconnect_max_attempts => DEFAULT_RECONNECT_ATTEMPTS,
:reconnect_retry_interval => DEFAULT_RECONNECT_INTERVAL,
:reconnect_response_timeout => DEFAULT_RECONNECT_RESPONSE_TIMEOUT,
:ttl => DEFAULT_TTL
}
# Let's fill missing keys with default values
$logger.debug('Setting default values')
defaults.each do |key,default_value|
set_default_value_if_not_set(key, default_value)
end
end
# Handles error response
# TODO Move to another module? So from single_request it will be usable
def handle_error_response(response)
@env[:error_callback].call response
end
def origin(options)
origin = options[:ssl] ? 'https://' : 'http://'
origin << options[:origin]
end
def treat_auth_key_param_as_param(options)
options[:auth_key_parameter] = options.delete(:auth_key)
options
end
# Checks if passed arguments are valid for client operation.
# It's not DRY for better readability
def check_required_parameters(operation, parameters)
channel_or_channels = parameters[:channel] || parameters[:channels]
raise InitializationError.new(:object => self), 'Origin parameter is not valid. Should be type of String or Symbol' unless [String, Symbol].include?(parameters[:origin].class) || parameters[:origin].blank?
case operation
when :initialize
# Check subscribe key
raise InitializationError.new(:object => self), 'Missing required :subscribe_key parameter' unless parameters[:subscribe_key]
raise InitializationError.new(:object => self), 'Subscribe key parameter is not valid. Should be type of String or Symbol' unless [String, Symbol].include?(parameters[:subscribe_key].class)
# Check publish key
raise InitializationError.new(:object => self), 'Publish key parameter is not valid. Should be type of String or Symbol' unless [String, Symbol].include?(parameters[:publish_key].class) || parameters[:publish_key].blank?
when :subscribe
# Check channels
raise ArgumentError.new(:object => self), 'Subscribe requires :channel or :channels argument' unless channel_or_channels
raise ArgumentError.new(:object => self), 'Subscribe can\'t be given both :channel and channels parameter' if parameters[:channel] && parameters[:channels]
raise ArgumentError.new(:object => self), 'Invalid channel(s) format! Should be type of: String, Symbol, or Array of both' unless Subscription::valid_channels?(channel_or_channels)
# check callback
raise ArgumentError.new(:object => self), 'Callback parameter is required while using async subscribe' if !parameters[:http_sync] && parameters[:callback].blank?
when :presence
# Check channels
raise ArgumentError.new(:object => self), 'Presence requires :channel or :channels argument' unless channel_or_channels
raise ArgumentError.new(:object => self), 'Presence can\'t be given both :channel and channels parameter' if parameters[:channel] && parameters[:channels]
raise ArgumentError.new(:object => self), 'Invalid channel(s) format! Should be type of: String, Symbol, or Array of both' unless Subscription::valid_channels?(channel_or_channels)
# check callback
raise ArgumentError.new(:object => self), 'Callback parameter is required while using async presence' if !parameters[:http_sync] && parameters[:callback].blank?
when :leave
# check channel
raise ArgumentError.new(:object => self), 'Leave requires :channel argument' unless parameters[:channel]
raise ArgumentError.new(:object => self), 'Invalid channel format! Should be type of: String, Symbol, or Array of both' unless [String, Symbol].include?(parameters[:channel].class)
# check callback
raise ArgumentError.new(:object => self), 'Callback parameter is required while using async leave/unsubscribe' if !parameters[:http_sync] && parameters[:callback].blank?
when :publish
# check message
raise ArgumentError.new(:object => self), 'Publish requires :message argument' unless parameters[:message]
# check channel/channels
raise ArgumentError.new(:object => self), 'Publish requires :channel or :channels argument' unless parameters[:channel] || parameters[:channels]
raise ArgumentError.new(:object => self), 'Invalid channel(s) format! Should be type of: String, Symbol, or Array of both' unless Subscription::valid_channels?(channel_or_channels)
# check callback
raise ArgumentError.new(:object => self), 'Callback parameter is required while using async publish' if !parameters[:http_sync] && parameters[:callback].blank?
when :history
# check channel
raise ArgumentError.new(:object => self), 'History requires :channel argument' unless parameters[:channel]
raise ArgumentError.new(:object => self), 'Invalid channel format! Should be type of: String, Symbol' unless [String, Symbol].include?(parameters[:channel].class)
# check if history parameters are valid
# start
raise ArgumentError.new(:object => self), 'Invalid :start parameter, should be type of Integer, Fixnum or String' unless [String, Fixnum, Integer, NilClass].include?(parameters[:start].class)
raise ArgumentError.new(:object => self), 'Invalid :start parameter, should be positive integer number' if !parameters[:start].to_i.integer? && parameters[:start].to_i <= 0
# end
raise ArgumentError.new(:object => self), 'Invalid :end parameter, should be type of Integer, Fixnum or String' unless [String, Fixnum, Integer, NilClass].include?(parameters[:end].class)
raise ArgumentError.new(:object => self), 'Invalid :end parameter, should be positive integer number' if !parameters[:end].to_i.integer? && parameters[:end].to_i <= 0
raise ArgumentError.new(:object => self), 'Invalid :end parameter, should be bigger than :start parameter.
If you want to get messages in reverse order, use :reverse => true at call.' if parameters[:start].to_i >= parameters[:end].to_i && !parameters[:start].nil? && parameters[:end].nil?
# count
raise ArgumentError.new(:object => self), 'Invalid :count parameter, should be type of Integer, Fixnum or String' unless [String, Fixnum, Integer, NilClass].include?(parameters[:count].class)
raise ArgumentError.new(:object => self), 'Invalid :count parameter, should be positive integer number' if !parameters[:count].to_i.integer? && parameters[:count].to_i <= 0
# check callback
raise ArgumentError.new(:object => self), 'Callback parameter is required while using async history' if !parameters[:http_sync] && parameters[:callback].blank?
when :here_now
# check channel
raise ArgumentError.new(:object => self), 'History requires :channel argument' unless parameters[:channel]
raise ArgumentError.new(:object => self), 'Invalid channel format! Should be type of: String, Symbol' unless [String, Symbol].include?(parameters[:channel].class)
# check callback
raise ArgumentError.new(:object => self), 'Callback parameter is required while using async here_now' if !parameters[:http_sync] && parameters[:callback].blank?
when :time
# check callback
raise ArgumentError.new(:object => self), 'Callback parameter is required while using async time' if !parameters[:http_sync] && parameters[:callback].blank?
when :audit
raise ArgumentError.new(:object => self), 'publish_key is required by Audit' unless parameters[:publish_key] || @env[:publish_key]
raise ArgumentError.new(:object => self), 'Parameter secret_key is required by Audit' unless parameters[:secret_key] || @env[:secret_key]
when :grant
raise ArgumentError.new(:object => self), 'publish_key is required by Grant' unless parameters[:publish_key] || @env[:publish_key]
raise ArgumentError.new(:object => self), 'Parameter secret_key is required by Grant' unless parameters[:secret_key] || @env[:secret_key]
raise ArgumentError.new(:object => self), 'write parameter accept only one of: 1, "1", 0, "0", true, false values' unless [nil, 1, "1", 0, "0", true, false].include?(parameters[:write])
raise ArgumentError.new(:object => self), 'read parameter accept only: 1, "1", 0, "0", true, false values' unless [nil, 1, "1", 0, "0", true, false].include?(parameters[:read])
raise ArgumentError.new(:object => self), 'ttl parameter is too big, max value is: 525600' unless parameters[:ttl].to_i <= 525600 || parameters[:ttl].nil?
raise ArgumentError.new(:object => self), 'ttl parameter is too small, min value is: 1' unless parameters[:ttl].to_i >= 1 || parameters[:ttl].nil?
else
raise 'Can\'t determine operation'
end
end
end
end
Fixed missing alias to leave
require 'pubnub/configuration'
require 'pubnub/parser'
require 'pubnub/single_request'
require 'pubnub/subscription'
require 'pubnub/envelope'
require 'pubnub/crypto'
require 'pubnub/uuid'
require 'pubnub/exceptions'
require 'pubnub/middleware/response'
require 'pubnub/middleware/request'
# TODO Split every operation as separate modules?
module Pubnub
class Client
include Configuration
include Subscription
include SingleRequest
VERSION = Pubnub::VERSION
attr_reader :env
# While creating new Pubnub::Client instance it checks for
def initialize(options)
check_required_parameters(:initialize, options)
setup_env(options)
run_em unless EM.reactor_running?
register_faraday_middleware
setup_connections(@env) # We're using @env not options because it has default values that could be necessary
end
# TODO well documented subscribe examples
def subscribe(options, &block)
$logger.debug('Calling subscribe')
options.merge!({ :action => :subscribe })
options.merge!({ :callback => block }) if block_given?
check_required_parameters(:subscribe, options)
options[:channel] = options[:channels] if options[:channel].blank? && !options[:channels].blank?
options[:channel] = Subscription.format_channels(options[:channel])
options[:channel] = options[:channel].gsub('+','%20')
preform_subscribe(@env.merge(options))
end
# TODO well documented presence examples
def presence(options, &block)
$logger.debug('Calling presence')
options.merge!({ :action => :presence })
options.merge!({ :callback => block }) if block_given?
check_required_parameters(:presence, options)
options[:channel] = Subscription.format_channels_for_presence(options[:channel])
options[:channel] = options[:channel].gsub('+','%20')
preform_subscribe(@env.merge(options))
end
# TODO well documented leave examples
def leave(options, &block)
$logger.debug('Calling leave')
options.merge!({ :action => :leave })
options.merge!({ :callback => block }) if block_given?
check_required_parameters(:leave, options)
options[:channel] = options[:channel].to_s.gsub('+','%20')
preform_single_request(@env.merge(options))
end
alias_method 'unsubscribe', 'leave'
# TODO well documented leave examples
def publish(options, &block)
$logger.debug('Calling publish')
options.merge!({ :action => :publish })
options.merge!({ :callback => block }) if block_given?
check_required_parameters(:publish, options)
options[:channel] = options[:channel].to_s.gsub('+','%20')
preform_single_request(@env.merge(options))
end
# TODO well documented history examples
def history(options, &block)
$logger.debug('Calling history')
options.merge!({ :action => :history })
options.merge!({ :callback => block }) if block_given?
check_required_parameters(:history, options)
options[:channel] = options[:channel].to_s.gsub('+','%20')
preform_single_request(@env.merge(options))
end
# TODO well documented here_now examples
def here_now(options, &block)
$logger.debug('Calling here_now')
options.merge!({ :action => :here_now })
options.merge!({ :callback => block }) if block_given?
check_required_parameters(:here_now, options)
options[:channel] = options[:channel].to_s.gsub('+','%20')
preform_single_request(@env.merge(options))
end
# TODO well documented audit examples
def audit(options, &block)
$logger.debug('Calling audit')
options.merge!({ :action => :audit })
options.merge!({ :callback => block }) if block_given?
check_required_parameters(:audit, options)
options[:channel] = options[:channel].to_s.gsub('+','%20')
options = treat_auth_key_param_as_param(options)
preform_single_request(@env.merge(options))
end
# TODO well documented grant examples
def grant(options, &block)
$logger.debug('Calling grant')
options.merge!({ :action => :grant })
options.merge!({ :callback => block }) if block_given?
check_required_parameters(:grant, options)
options[:channel] = options[:channel].to_s.gsub('+','%20')
options = treat_auth_key_param_as_param(options)
preform_single_request(@env.merge(options))
end
# TODO well documented revoke examples
def revoke(options, &block)
$logger.debug('Calling revoke')
options.merge!({ :action => :grant })
options.merge!({ :callback => block }) if block_given?
check_required_parameters(:grant, options)
options[:channel] = options[:channel].to_s.gsub('+','%20')
options = treat_auth_key_param_as_param(options)
options[:read] = false if options[:read]
options[:write] = false if options[:write]
preform_single_request(@env.merge(options))
end
# Returns current timetoken from server
def time(options, &block)
$logger.debug('Calling time')
options.merge!({ :action => :time })
options.merge!({ :callback => block }) if block_given?
check_required_parameters(:time, options)
preform_single_request(@env.merge(options))
end
def set_secret_key(secret_key)
@env[:secret_key] = secret_key
end
alias_method 'secret=', 'set_secret_key'
alias_method 'secret_key=', 'set_secret_key'
def set_uuid(uuid)
$logger.debug('Setting new UUID')
@env[:uuid] = uuid
end
alias_method 'uuid=', 'set_uuid'
alias_method 'session_uuid=', 'set_uuid'
def set_ssl(ssl)
$logger.debug('Setting SSL')
@env[:ssl] = ssl
end
alias_method 'ssl=', 'set_ssl'
def set_cipher_key(cipher_key)
@env[:cipher_key] = cipher_key
end
alias_method 'cipher_key=', 'set_cipher_key'
def set_auth_key(auth_key)
@env[:auth_key] = auth_key
end
alias_method 'auth_key=', 'set_auth_key'
# For some backwards compatibility
def uuid
@env[:uuid]
end
# For some backwards compatibility
def ssl
@env[:ssl]
end
# For some backwards compatibility
def secret_key
@env[:secret_key]
end
# Gracefully closes all connections
def exit
binding.pry
end
private
# Sterts event machine reactor in new thread
def run_em
$logger.debug('Starting EventMachine')
Thread.new { EM.run }
# block thread until EM starts
until EM.reactor_running? do end
end
def register_faraday_middleware
$logger.debug('Registering faraday middleware')
Faraday::Response.register_middleware :response, :pubnub => Pubnub::Middleware::Response
Faraday::Request.register_middleware :request, :pubnub => Pubnub::Middleware::Request
end
# Returns url for connections depending on origin and enabled ssl
def url_for_connection(options)
"http#{options[:ssl] ? 's' : ''}://#{options[:origin]}"
end
def origin_already_registered?(origin)
!@subscribe_connections_pool[origin].nil?
end
def setup_subscribe_connection(options)
$logger.debug('Setting subscribe connection')
@subscribe_connections_pool = Hash.new if @subscribe_connections_pool.nil?
@subscribe_connections_pool[options[:origin]] = Faraday.new(:url => url_for_connection(options)) do |faraday|
faraday.adapter :net_http_persistent
faraday.response :pubnub
faraday.request :pubnub
end
$logger.debug('Created subscribe connection')
end
def setup_single_event_connection(options)
@single_event_connections_pool = Hash.new if @single_event_connections_pool.nil?
@single_event_connections_pool[options[:origin]] = Faraday.new(:url => url_for_connection(options)) do |faraday|
faraday.adapter :net_http_persistent
faraday.response :pubnub
faraday.request :pubnub
end
$logger.debug('Created single event connection')
end
# Sets up two persistent connections via Faraday with pubnub middleware
def setup_connections(options)
setup_subscribe_connection(options)
setup_single_event_connection(options)
end
# Returns converted env hash with all non-symbol keys in given env hash into symbols
def symbolize_options(options)
$logger.debug('Symbolizing options')
symbolized_options = {}
options.each_key { |k| symbolized_options.merge!({ k.to_sym => options[k] }) }
symbolized_options
end
# Checks if given key is already set, if not, sets default value
def set_default_value_if_not_set(key, default_value)
@env[key] = default_value if @env[key].nil?
end
# Create valid and complete @env variable
# @env holds whole configuration and is merged with options that are passed to REST actions
# so values form env overridden by request options are available in every action
def setup_env(options)
# Setup logger or let's create default one
$logger = options[:logger] || Logger.new('pubnub.log', 'weekly')
# We must be sure if every key is symbol
@env = symbolize_options options
set_default_values
$logger.debug('Created environment')
end
def set_default_values
defaults = {
:error_callback => DEFAULT_ERROR_CALLBACK,
:connect_callback => DEFAULT_CONNECT_CALLBACK,
:ssl => DEFAULT_SSL,
:timetoken => DEFAULT_TIMETOKEN,
:uuid => UUID.new.generate,
:port => DEFAULT_CONNECTION_PORT,
:origin => DEFAULT_ORIGIN,
:subscribe_timeout => DEFAULT_SUBSCRIBE_TIMEOUT,
:timeout => DEFAULT_NON_SUBSCRIBE_TIMEOUT,
:max_retries => MAX_RETRIES,
:non_subscribe_timeout => DEFAULT_NON_SUBSCRIBE_TIMEOUT,
:reconnect_max_attempts => DEFAULT_RECONNECT_ATTEMPTS,
:reconnect_retry_interval => DEFAULT_RECONNECT_INTERVAL,
:reconnect_response_timeout => DEFAULT_RECONNECT_RESPONSE_TIMEOUT,
:ttl => DEFAULT_TTL
}
# Let's fill missing keys with default values
$logger.debug('Setting default values')
defaults.each do |key,default_value|
set_default_value_if_not_set(key, default_value)
end
end
# Handles error response
# TODO Move to another module? So from single_request it will be usable
def handle_error_response(response)
@env[:error_callback].call response
end
def origin(options)
origin = options[:ssl] ? 'https://' : 'http://'
origin << options[:origin]
end
def treat_auth_key_param_as_param(options)
options[:auth_key_parameter] = options.delete(:auth_key)
options
end
# Checks if passed arguments are valid for client operation.
# It's not DRY for better readability
def check_required_parameters(operation, parameters)
channel_or_channels = parameters[:channel] || parameters[:channels]
raise InitializationError.new(:object => self), 'Origin parameter is not valid. Should be type of String or Symbol' unless [String, Symbol].include?(parameters[:origin].class) || parameters[:origin].blank?
case operation
when :initialize
# Check subscribe key
raise InitializationError.new(:object => self), 'Missing required :subscribe_key parameter' unless parameters[:subscribe_key]
raise InitializationError.new(:object => self), 'Subscribe key parameter is not valid. Should be type of String or Symbol' unless [String, Symbol].include?(parameters[:subscribe_key].class)
# Check publish key
raise InitializationError.new(:object => self), 'Publish key parameter is not valid. Should be type of String or Symbol' unless [String, Symbol].include?(parameters[:publish_key].class) || parameters[:publish_key].blank?
when :subscribe
# Check channels
raise ArgumentError.new(:object => self), 'Subscribe requires :channel or :channels argument' unless channel_or_channels
raise ArgumentError.new(:object => self), 'Subscribe can\'t be given both :channel and channels parameter' if parameters[:channel] && parameters[:channels]
raise ArgumentError.new(:object => self), 'Invalid channel(s) format! Should be type of: String, Symbol, or Array of both' unless Subscription::valid_channels?(channel_or_channels)
# check callback
raise ArgumentError.new(:object => self), 'Callback parameter is required while using async subscribe' if !parameters[:http_sync] && parameters[:callback].blank?
when :presence
# Check channels
raise ArgumentError.new(:object => self), 'Presence requires :channel or :channels argument' unless channel_or_channels
raise ArgumentError.new(:object => self), 'Presence can\'t be given both :channel and channels parameter' if parameters[:channel] && parameters[:channels]
raise ArgumentError.new(:object => self), 'Invalid channel(s) format! Should be type of: String, Symbol, or Array of both' unless Subscription::valid_channels?(channel_or_channels)
# check callback
raise ArgumentError.new(:object => self), 'Callback parameter is required while using async presence' if !parameters[:http_sync] && parameters[:callback].blank?
when :leave
# check channel
raise ArgumentError.new(:object => self), 'Leave requires :channel argument' unless parameters[:channel]
raise ArgumentError.new(:object => self), 'Invalid channel format! Should be type of: String, Symbol, or Array of both' unless [String, Symbol].include?(parameters[:channel].class)
# check callback
raise ArgumentError.new(:object => self), 'Callback parameter is required while using async leave/unsubscribe' if !parameters[:http_sync] && parameters[:callback].blank?
when :publish
# check message
raise ArgumentError.new(:object => self), 'Publish requires :message argument' unless parameters[:message]
# check channel/channels
raise ArgumentError.new(:object => self), 'Publish requires :channel or :channels argument' unless parameters[:channel] || parameters[:channels]
raise ArgumentError.new(:object => self), 'Invalid channel(s) format! Should be type of: String, Symbol, or Array of both' unless Subscription::valid_channels?(channel_or_channels)
# check callback
raise ArgumentError.new(:object => self), 'Callback parameter is required while using async publish' if !parameters[:http_sync] && parameters[:callback].blank?
when :history
# check channel
raise ArgumentError.new(:object => self), 'History requires :channel argument' unless parameters[:channel]
raise ArgumentError.new(:object => self), 'Invalid channel format! Should be type of: String, Symbol' unless [String, Symbol].include?(parameters[:channel].class)
# check if history parameters are valid
# start
raise ArgumentError.new(:object => self), 'Invalid :start parameter, should be type of Integer, Fixnum or String' unless [String, Fixnum, Integer, NilClass].include?(parameters[:start].class)
raise ArgumentError.new(:object => self), 'Invalid :start parameter, should be positive integer number' if !parameters[:start].to_i.integer? && parameters[:start].to_i <= 0
# end
raise ArgumentError.new(:object => self), 'Invalid :end parameter, should be type of Integer, Fixnum or String' unless [String, Fixnum, Integer, NilClass].include?(parameters[:end].class)
raise ArgumentError.new(:object => self), 'Invalid :end parameter, should be positive integer number' if !parameters[:end].to_i.integer? && parameters[:end].to_i <= 0
raise ArgumentError.new(:object => self), 'Invalid :end parameter, should be bigger than :start parameter.
If you want to get messages in reverse order, use :reverse => true at call.' if parameters[:start].to_i >= parameters[:end].to_i && !parameters[:start].nil? && parameters[:end].nil?
# count
raise ArgumentError.new(:object => self), 'Invalid :count parameter, should be type of Integer, Fixnum or String' unless [String, Fixnum, Integer, NilClass].include?(parameters[:count].class)
raise ArgumentError.new(:object => self), 'Invalid :count parameter, should be positive integer number' if !parameters[:count].to_i.integer? && parameters[:count].to_i <= 0
# check callback
raise ArgumentError.new(:object => self), 'Callback parameter is required while using async history' if !parameters[:http_sync] && parameters[:callback].blank?
when :here_now
# check channel
raise ArgumentError.new(:object => self), 'History requires :channel argument' unless parameters[:channel]
raise ArgumentError.new(:object => self), 'Invalid channel format! Should be type of: String, Symbol' unless [String, Symbol].include?(parameters[:channel].class)
# check callback
raise ArgumentError.new(:object => self), 'Callback parameter is required while using async here_now' if !parameters[:http_sync] && parameters[:callback].blank?
when :time
# check callback
raise ArgumentError.new(:object => self), 'Callback parameter is required while using async time' if !parameters[:http_sync] && parameters[:callback].blank?
when :audit
raise ArgumentError.new(:object => self), 'publish_key is required by Audit' unless parameters[:publish_key] || @env[:publish_key]
raise ArgumentError.new(:object => self), 'Parameter secret_key is required by Audit' unless parameters[:secret_key] || @env[:secret_key]
when :grant
raise ArgumentError.new(:object => self), 'publish_key is required by Grant' unless parameters[:publish_key] || @env[:publish_key]
raise ArgumentError.new(:object => self), 'Parameter secret_key is required by Grant' unless parameters[:secret_key] || @env[:secret_key]
raise ArgumentError.new(:object => self), 'write parameter accept only one of: 1, "1", 0, "0", true, false values' unless [nil, 1, "1", 0, "0", true, false].include?(parameters[:write])
raise ArgumentError.new(:object => self), 'read parameter accept only: 1, "1", 0, "0", true, false values' unless [nil, 1, "1", 0, "0", true, false].include?(parameters[:read])
raise ArgumentError.new(:object => self), 'ttl parameter is too big, max value is: 525600' unless parameters[:ttl].to_i <= 525600 || parameters[:ttl].nil?
raise ArgumentError.new(:object => self), 'ttl parameter is too small, min value is: 1' unless parameters[:ttl].to_i >= 1 || parameters[:ttl].nil?
else
raise 'Can\'t determine operation'
end
end
end
end |
module Qbrick
class ImageSizeDelegator
def method_missing(method, *args, &block)
Qbrick::ImageSize.send(method, *args, &block)
rescue NoMethodError
super
end
end
class Engine < ::Rails::Engine
isolate_namespace Qbrick
config.i18n.fallbacks = [:de]
config.i18n.load_path += Dir[Qbrick::Engine.root.join('config/locales/**/*.{yml}').to_s]
# defaults to nil
config.sublime_video_token = nil
# delegate image size config to ImageSize class
config.image_sizes = ImageSizeDelegator.new
initializer 'qbrick.initialize_haml_dependency_tracker' do
require 'action_view/dependency_tracker'
ActionView::DependencyTracker.register_tracker :haml, ActionView::DependencyTracker::ERBTracker
end
def app_config
Rails.application.config
end
def hosts
[Socket.gethostname].tap do |result|
result.concat [app_config.hosts].flatten if app_config.respond_to? :hosts
result.concat [app_config.host].flatten if app_config.respond_to? :host
end
end
def host
return hosts.first unless app_config.respond_to? :host
app_config.host
end
def scheme
return 'http' unless app_config.respond_to? :scheme
app_config.scheme
end
def port
return 80 unless app_config.respond_to? :port
app_config.port
end
end
end
don't return empty host values & add localhost
module Qbrick
class ImageSizeDelegator
def method_missing(method, *args, &block)
Qbrick::ImageSize.send(method, *args, &block)
rescue NoMethodError
super
end
end
class Engine < ::Rails::Engine
isolate_namespace Qbrick
config.i18n.fallbacks = [:de]
config.i18n.load_path += Dir[Qbrick::Engine.root.join('config/locales/**/*.{yml}').to_s]
# defaults to nil
config.sublime_video_token = nil
# delegate image size config to ImageSize class
config.image_sizes = ImageSizeDelegator.new
initializer 'qbrick.initialize_haml_dependency_tracker' do
require 'action_view/dependency_tracker'
ActionView::DependencyTracker.register_tracker :haml, ActionView::DependencyTracker::ERBTracker
end
def app_config
Rails.application.config
end
def hosts
[Socket.gethostname, 'localhost'].tap do |result|
result.concat [app_config.hosts].flatten if app_config.respond_to? :hosts
result.concat [app_config.host].flatten if app_config.respond_to? :host
result.compact!
result.uniq!
end
end
def host
return hosts.first unless app_config.respond_to? :host
app_config.host
end
def scheme
return 'http' unless app_config.respond_to? :scheme
app_config.scheme
end
def port
return 80 unless app_config.respond_to? :port
app_config.port
end
end
end
|
module Qiita
VERSION = "0.0.2"
end
Bump up v0.0.3
module Qiita
VERSION = "0.0.3"
end
|
module RDF; class Literal
##
# An integer literal.
#
# @example Arithmetic with integer literals
# RDF::Literal(40) + 2 #=> RDF::Literal(42)
# RDF::Literal(45) - 3 #=> RDF::Literal(42)
# RDF::Literal(6) * 7 #=> RDF::Literal(42)
# RDF::Literal(84) / 2 #=> RDF::Literal(42)
#
# @see http://www.w3.org/TR/xmlschema-2/#integer
# @see http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/#integer
# @since 0.2.1
class Integer < Decimal
DATATYPE = XSD.integer
GRAMMAR = /^[\+\-]?\d+$/.freeze
##
# @param [Integer, #to_i] value
# @option options [String] :lexical (nil)
def initialize(value, options = {})
@datatype = RDF::URI(options[:datatype] || self.class.const_get(:DATATYPE))
@string = options[:lexical] if options.has_key?(:lexical)
@string ||= value if value.is_a?(String)
@object = case
when value.is_a?(::String) then Integer(value) rescue nil
when value.is_a?(::Integer) then value
when value.respond_to?(:to_i) then value.to_i
else Integer(value.to_s) rescue nil
end
end
##
# Converts this literal into its canonical lexical representation.
#
# @return [RDF::Literal] `self`
# @see http://www.w3.org/TR/xmlschema-2/#integer
def canonicalize!
@string = @object.to_s if @object
self
end
##
# Returns the successor value of `self`.
#
# @return [RDF::Literal]
# @since 0.2.3
def pred
RDF::Literal(to_i.pred)
end
##
# Returns the predecessor value of `self`.
#
# @return [RDF::Literal]
# @since 0.2.3
def succ
RDF::Literal(to_i.succ)
end
alias_method :next, :succ
##
# Returns `true` if the value is even.
#
# @return [Boolean]
# @since 0.2.3
def even?
to_i.even?
end
##
# Returns `true` if the value is odd.
#
# @return [Boolean]
# @since 0.2.3
def odd?
to_i.odd?
end
##
# Returns the absolute value of `self`.
#
# @return [RDF::Literal]
# @since 0.2.3
def abs
(n = to_i) && n > 0 ? self : self.class.new(n.abs)
end
##
# Returns `self`.
#
# @return [RDF::Literal]
def round
self
end
##
# Returns `true` if the value is zero.
#
# @return [Boolean]
# @since 0.2.3
def zero?
to_i.zero?
end
##
# Returns `self` if the value is not zero, `nil` otherwise.
#
# @return [Boolean]
# @since 0.2.3
def nonzero?
to_i.nonzero? ? self : nil
end
##
# Returns the value as a string.
#
# @return [String]
def to_s
@string || @object.to_s
end
##
# Returns the value as an `OpenSSL::BN` instance.
#
# @return [OpenSSL::BN]
# @see http://ruby-doc.org/stdlib/libdoc/openssl/rdoc/classes/OpenSSL/BN.html
# @since 0.2.4
def to_bn
require 'openssl' unless defined?(OpenSSL::BN)
OpenSSL::BN.new(to_s)
end
end # Integer
end; end # RDF::Literal
Fix doc for RDF::Literal::Integer#pred and #succ
module RDF; class Literal
##
# An integer literal.
#
# @example Arithmetic with integer literals
# RDF::Literal(40) + 2 #=> RDF::Literal(42)
# RDF::Literal(45) - 3 #=> RDF::Literal(42)
# RDF::Literal(6) * 7 #=> RDF::Literal(42)
# RDF::Literal(84) / 2 #=> RDF::Literal(42)
#
# @see http://www.w3.org/TR/xmlschema-2/#integer
# @see http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/#integer
# @since 0.2.1
class Integer < Decimal
DATATYPE = XSD.integer
GRAMMAR = /^[\+\-]?\d+$/.freeze
##
# @param [Integer, #to_i] value
# @option options [String] :lexical (nil)
def initialize(value, options = {})
@datatype = RDF::URI(options[:datatype] || self.class.const_get(:DATATYPE))
@string = options[:lexical] if options.has_key?(:lexical)
@string ||= value if value.is_a?(String)
@object = case
when value.is_a?(::String) then Integer(value) rescue nil
when value.is_a?(::Integer) then value
when value.respond_to?(:to_i) then value.to_i
else Integer(value.to_s) rescue nil
end
end
##
# Converts this literal into its canonical lexical representation.
#
# @return [RDF::Literal] `self`
# @see http://www.w3.org/TR/xmlschema-2/#integer
def canonicalize!
@string = @object.to_s if @object
self
end
##
# Returns the predecessor value of `self`.
#
# @return [RDF::Literal]
# @since 0.2.3
def pred
RDF::Literal(to_i.pred)
end
##
# Returns the successor value of `self`.
#
# @return [RDF::Literal]
# @since 0.2.3
def succ
RDF::Literal(to_i.succ)
end
alias_method :next, :succ
##
# Returns `true` if the value is even.
#
# @return [Boolean]
# @since 0.2.3
def even?
to_i.even?
end
##
# Returns `true` if the value is odd.
#
# @return [Boolean]
# @since 0.2.3
def odd?
to_i.odd?
end
##
# Returns the absolute value of `self`.
#
# @return [RDF::Literal]
# @since 0.2.3
def abs
(n = to_i) && n > 0 ? self : self.class.new(n.abs)
end
##
# Returns `self`.
#
# @return [RDF::Literal]
def round
self
end
##
# Returns `true` if the value is zero.
#
# @return [Boolean]
# @since 0.2.3
def zero?
to_i.zero?
end
##
# Returns `self` if the value is not zero, `nil` otherwise.
#
# @return [Boolean]
# @since 0.2.3
def nonzero?
to_i.nonzero? ? self : nil
end
##
# Returns the value as a string.
#
# @return [String]
def to_s
@string || @object.to_s
end
##
# Returns the value as an `OpenSSL::BN` instance.
#
# @return [OpenSSL::BN]
# @see http://ruby-doc.org/stdlib/libdoc/openssl/rdoc/classes/OpenSSL/BN.html
# @since 0.2.4
def to_bn
require 'openssl' unless defined?(OpenSSL::BN)
OpenSSL::BN.new(to_s)
end
end # Integer
end; end # RDF::Literal
|
# frozen_string_literal: true
require 'forwardable'
module Reek
# @public
module Smells
#
# Reports a warning that a smell has been found.
#
# @public
#
# :reek:TooManyInstanceVariables: { max_instance_variables: 6 }
class SmellWarning
include Comparable
extend Forwardable
# @public
attr_reader :context, :lines, :message, :parameters, :smell_detector, :source
def_delegators :smell_detector, :smell_type
# @note When using Reek's public API, you should not create SmellWarning
# objects yourself. This is why the initializer is not part of the
# public API.
#
# :reek:LongParameterList: { max_params: 6 }
def initialize(smell_detector, context: '', lines:, message:,
source:, parameters: {})
@smell_detector = smell_detector
@source = source
@context = context.to_s
@lines = lines
@message = message
@parameters = parameters
end
# @public
def hash
sort_key.hash
end
# @public
def <=>(other)
sort_key <=> other.sort_key
end
# @public
def eql?(other)
(self <=> other).zero?
end
# @public
def to_hash
stringified_params = Hash[parameters.map { |key, val| [key.to_s, val] }]
base_hash.merge(stringified_params)
end
alias yaml_hash to_hash
def base_message
"#{smell_type}: #{context} #{message}"
end
def smell_class
smell_detector.class
end
protected
def sort_key
[smell_type, context, message, lines]
end
private
def base_hash
{
'context' => context,
'lines' => lines,
'message' => message,
'smell_type' => smell_type,
'source' => source
}
end
end
end
end
Rename SmellWarning#sort_key to #identifying_values
The array returned by #sort_key determines whether two SmellWarnings
are equivalent to each other. In other words, the smell warning object
is behaving as a value object. These values *also* determine sort order
but naming this method after how it affects sorting sells it short.
# frozen_string_literal: true
require 'forwardable'
module Reek
# @public
module Smells
#
# Reports a warning that a smell has been found.
#
# @public
#
# :reek:TooManyInstanceVariables: { max_instance_variables: 6 }
class SmellWarning
include Comparable
extend Forwardable
# @public
attr_reader :context, :lines, :message, :parameters, :smell_detector, :source
def_delegators :smell_detector, :smell_type
# @note When using Reek's public API, you should not create SmellWarning
# objects yourself. This is why the initializer is not part of the
# public API.
#
# :reek:LongParameterList: { max_params: 6 }
def initialize(smell_detector, context: '', lines:, message:,
source:, parameters: {})
@smell_detector = smell_detector
@source = source
@context = context.to_s
@lines = lines
@message = message
@parameters = parameters
end
# @public
def hash
identifying_values.hash
end
# @public
def <=>(other)
identifying_values <=> other.identifying_values
end
# @public
def eql?(other)
(self <=> other).zero?
end
# @public
def to_hash
stringified_params = Hash[parameters.map { |key, val| [key.to_s, val] }]
base_hash.merge(stringified_params)
end
alias yaml_hash to_hash
def base_message
"#{smell_type}: #{context} #{message}"
end
def smell_class
smell_detector.class
end
protected
def identifying_values
[smell_type, context, message, lines]
end
private
def base_hash
{
'context' => context,
'lines' => lines,
'message' => message,
'smell_type' => smell_type,
'source' => source
}
end
end
end
end
|
module Remi
module DataSource
class CsvFile
include DataSource
using Remi::Refinements::Daru
def self.default_csv_options
CSV::DEFAULT_OPTIONS.merge({
headers: true,
header_converters: Remi::FieldSymbolizers[:standard],
col_sep: ',',
encoding: 'UTF-8',
quote_char: '"'
})
end
def initialize(fields: {}, extractor:, csv_options: {}, filename_field: nil, logger: Remi::Settings.logger)
@fields = fields
self.extractor = extractor
@csv_options = self.class.default_csv_options.merge(csv_options)
@filename_field = filename_field
@logger = logger
end
attr_accessor :fields
attr_reader :extractor
attr_reader :csv_options
def field_symbolizer
self.class.default_csv_options[:header_converters]
end
def extract
@extracted = Array(@extractor.extract)
end
def extracted
@extracted || extract
end
def extractor=(arg)
case arg
when Extractor::SftpFile, Extractor::LocalFile
@extractor = arg
when String
@extractor = Extractor::LocalFile.new(path: arg)
when Regexp
raise "Adding regex matching to local files would be easy, not done yet"
else
raise "Unknown extractor of type #{arg.class}: #{arg}"
end
end
# Only going to support single file for now
def source_filename
raise "Multiple source files detected" if extracted.size > 1
@source_filename ||= extracted.first
end
def first_line
# Readline assumes \n line endings. Strip out \r if it is a DOS file.
@first_line ||= File.open(source_filename) do |f|
f.readline.gsub(/\r/,'')
end
end
def headers
@headers ||= CSV.open(source_filename, 'r', source_csv_options) { |csv| csv.first }.headers
end
def valid_headers?
(fields.keys - headers).empty?
end
def to_dataframe
# Assumes that each file has exactly the same structure
result_df = nil
extracted.each_with_index do |filename, idx|
@logger.info "Converting #{filename} to a dataframe"
csv_df = Daru::DataFrame.from_csv filename, @csv_options
csv_df[@filename_field] = Daru::Vector.new([filename] * csv_df.size, index: csv_df.index) if @filename_field
if idx == 0
result_df = csv_df
else
result_df = result_df.concat csv_df
end
end
result_df
end
def df
@dataframe ||= to_dataframe
end
end
end
end
MISC - Disables all default CSV conversions.
This is way too risky when we have the possibility of leading zeroes and other things.
We'll need to develop a way to do error handling and such on conversions.
module Remi
module DataSource
class CsvFile
include DataSource
using Remi::Refinements::Daru
def self.default_csv_options
CSV::DEFAULT_OPTIONS.merge({
headers: true,
header_converters: Remi::FieldSymbolizers[:standard],
converters: [],
col_sep: ',',
encoding: 'UTF-8',
quote_char: '"'
})
end
def initialize(fields: {}, extractor:, csv_options: {}, filename_field: nil, logger: Remi::Settings.logger)
@fields = fields
self.extractor = extractor
@csv_options = self.class.default_csv_options.merge(csv_options)
@filename_field = filename_field
@logger = logger
end
attr_accessor :fields
attr_reader :extractor
attr_reader :csv_options
def field_symbolizer
self.class.default_csv_options[:header_converters]
end
def extract
@extracted = Array(@extractor.extract)
end
def extracted
@extracted || extract
end
def extractor=(arg)
case arg
when Extractor::SftpFile, Extractor::LocalFile
@extractor = arg
when String
@extractor = Extractor::LocalFile.new(path: arg)
when Regexp
raise "Adding regex matching to local files would be easy, not done yet"
else
raise "Unknown extractor of type #{arg.class}: #{arg}"
end
end
# Only going to support single file for now
def source_filename
raise "Multiple source files detected" if extracted.size > 1
@source_filename ||= extracted.first
end
def first_line
# Readline assumes \n line endings. Strip out \r if it is a DOS file.
@first_line ||= File.open(source_filename) do |f|
f.readline.gsub(/\r/,'')
end
end
def headers
@headers ||= CSV.open(source_filename, 'r', source_csv_options) { |csv| csv.first }.headers
end
def valid_headers?
(fields.keys - headers).empty?
end
def to_dataframe
# Assumes that each file has exactly the same structure
result_df = nil
extracted.each_with_index do |filename, idx|
@logger.info "Converting #{filename} to a dataframe"
csv_df = Daru::DataFrame.from_csv filename, @csv_options
csv_df[@filename_field] = Daru::Vector.new([filename] * csv_df.size, index: csv_df.index) if @filename_field
if idx == 0
result_df = csv_df
else
result_df = result_df.concat csv_df
end
end
result_df
end
def df
@dataframe ||= to_dataframe
end
end
end
end
|
module RemoteController
VERSION = "0.1.1".freeze
end
Incrementing version.
module RemoteController
VERSION = "0.1.2".freeze
end
|
#encoding:utf-8
module Reports
module Financial
class Backers
class << self
def report(project_id)
@project = Project.find(project_id)
@backers = @project.backers.includes(:payment_detail, :user).confirmed
@csv = CSV.generate(:col_sep => ',') do |csv_string|
# TODO: Change this later *order and names to use i18n*
# for moment header only in portuguese.
csv_string << [
'Nome do apoiador',
'Valor do apoio',
'Recompensa selecionada (valor)',
'Serviço de pagamento',
'Forma de pagamento',
'Taxa do meio de pagamento',
'ID da transacao',
'Data do apoio',
'Data do pagamento confirmado',
'Email (conta do apoiador)',
'Email (conta em que fez o pagamento)',
'Login do usuario no MoIP',
'CPF'
]
@backers.each do |backer|
csv_string << [
backer.user.name,
backer.value.to_s.gsub(/\./,","),
(backer.reward.minimum_value.to_s.gsub(/\./,",") if backer.reward),
backer.payment_method,
(backer.payment_detail.payment_method if backer.payment_detail),
(backer.payment_service_fee).to_s.gsub(/\./,","),
backer.key,
I18n.l(backer.created_at.to_date),
I18n.l(backer.confirmed_at.to_date),
backer.user.email,
(backer.payment_detail.payer_email if backer.payment_detail),
(backer.payment_detail.payer_name if backer.payment_detail),
backer.user.cpf
]
end
end
end
end
end
end
end
adjust to use dot
#encoding:utf-8
module Reports
module Financial
class Backers
class << self
def report(project_id)
@project = Project.find(project_id)
@backers = @project.backers.includes(:payment_detail, :user).confirmed
@csv = CSV.generate(:col_sep => ',') do |csv_string|
# TODO: Change this later *order and names to use i18n*
# for moment header only in portuguese.
csv_string << [
'Nome do apoiador',
'Valor do apoio',
'Recompensa selecionada (valor)',
'Serviço de pagamento',
'Forma de pagamento',
'Taxa do meio de pagamento',
'ID da transacao',
'Data do apoio',
'Data do pagamento confirmado',
'Email (conta do apoiador)',
'Email (conta em que fez o pagamento)',
'Login do usuario no MoIP',
'CPF'
]
@backers.each do |backer|
csv_string << [
backer.user.name,
backer.value,
(backer.reward.minimum_value if backer.reward),
backer.payment_method,
(backer.payment_detail.payment_method if backer.payment_detail),
(backer.payment_service_fee),
backer.key,
I18n.l(backer.created_at.to_date),
I18n.l(backer.confirmed_at.to_date),
backer.user.email,
(backer.payment_detail.payer_email if backer.payment_detail),
(backer.payment_detail.payer_name if backer.payment_detail),
backer.user.cpf
]
end
end
end
end
end
end
end |
require 'rest-core'
require 'crack/xml'
RestCore::MadMimi = RestCore::Builder.client(:data, :username, :api_key,
:promotion_name) do
s = self.class # this is only for ruby 1.8!
use s::Timeout , 300
use s::DefaultSite , 'https://api.madmimi.com/'
use s::DefaultQuery , {}
use s::Cache , {}, 60 do
use s::ErrorHandler, lambda { |env|
raise RestCore::MadMimi::Error.call(env) }
use s::ErrorDetectorHttp
end
use s::Defaults , :data => {}
end
class RestCore::MadMimi::Error < RestCore::Error
def self.call(env)
raise RestCore::MadMimi::Error,
"#{env[RestCore::RESPONSE_STATUS]} #{env[RestCore::RESPONSE_BODY]}"
end
end
require 'rest-core/client/mad_mimi/audience_list'
module RestCore::MadMimi::Client
include RestCore
POSSIBLE_STATUSES = %w[ignorant sending failed sent received clicked_through
bounced retried retry_failed forwarded opted_out
abused]
# https://madmimi.com/developer/mailer/transactional
#
# Usage:
#
# client.mailer('ayaya@example.com',
# :subject => 'Subject',
# :raw_html => 'the mail body [[tracking_beacon]]')
#
# The transaction code is convert to integer
def mailer(recipient, options = {})
options = {:recipients => recipient}.merge(options)
response = post('mailer', options)
# response was a string that included RestClient::AbstractResponse,
# and it overrided #to_i method (which returns status code)
String.new(response).to_i
end
# https://madmimi.com/developer/mailer/send-to-a-list
#
# Usage:
#
# client.mailer_to_list('list_name',
# :subject => 'Subject',
# :raw_html => 'the mail body [[tracking_beacon]]')
#
# The transaction code is convert to integer
def mailer_to_list(list, options = {})
list = list.join(',') if list.is_a?(Array)
options = {:list_name => list}.merge(options)
response = post('mailer/to_list', options)
# response was a string that included RestClient::AbstractResponse,
# and it overrided #to_i method (which returns status code)
String.new(response).to_i
end
# https://madmimi.com/developer/mailer/status
#
# Usage:
#
# id = client.mailer(...)
# client.status(id)
def status(id)
get("mailers/status/#{id.to_i}")
end
# https://madmimi.com/developer/lists
# Audience lists apis
def audience_lists
response = get('audience_lists/lists.xml')
Crack::XML.parse(response)['lists']['list'].map do |list|
RestCore::MadMimi::AudienceList.new(self, list)
end
end
def create_audience_list(name)
post('audience_lists', :name => name).tap{}
RestCore::MadMimi::AudienceList.new(self, :name => name)
end
def rename_audience_list(name, new_name)
post("audience_lists/#{CGI.escape(name)}/rename", :name => new_name).tap{}
RestCore::MadMimi::AudienceList.new(self, :name => new_name)
end
def destroy_audience_list(name)
post("audience_lists/#{CGI.escape(name)}", :_method => 'delete').tap{}
end
# https://madmimi.com/developer/lists
# Audience lists apis (members)
def add_member_to_audience_list(list, email, options = {})
options = {:email => email}.merge(options)
post("audience_lists/#{CGI.escape(list)}/add", options).tap{}
end
def remove_member_from_audience_list(list, email, options = {})
options = {:email => email}.merge(options)
post("audience_lists/#{CGI.escape(list)}/remove", options).tap{}
end
def query
{'username' => username,
'api_key' => api_key,
'promotion_name' => promotion_name}
end
end
RestCore::MadMimi.send(:include, RestCore::MadMimi::Client)
Reference Facebbok error class, which provides accessor to error details
require 'rest-core'
require 'crack/xml'
RestCore::MadMimi = RestCore::Builder.client(:data, :username, :api_key,
:promotion_name) do
s = self.class # this is only for ruby 1.8!
use s::Timeout , 300
use s::DefaultSite , 'https://api.madmimi.com/'
use s::DefaultQuery , {}
use s::Cache , {}, 60 do
use s::ErrorHandler, lambda { |env|
raise RestCore::MadMimi::Error.call(env) }
use s::ErrorDetectorHttp
end
use s::Defaults , :data => {}
end
class RestCore::MadMimi::Error < RestCore::Error
include RestCore
attr_reader :error, :code, :url
def initialize error, code, url=''
@error, @code, @url = error, code, url
super("[#{code}] #{error.inspect} from #{url}")
end
def self.call env
error, code, url = env[RESPONSE_BODY], env[RESPONSE_STATUS],
Middleware.request_uri(env)
new(error, code, url)
end
end
require 'rest-core/client/mad_mimi/audience_list'
module RestCore::MadMimi::Client
include RestCore
POSSIBLE_STATUSES = %w[ignorant sending failed sent received clicked_through
bounced retried retry_failed forwarded opted_out
abused]
# https://madmimi.com/developer/mailer/transactional
#
# Usage:
#
# client.mailer('ayaya@example.com',
# :subject => 'Subject',
# :raw_html => 'the mail body [[tracking_beacon]]')
#
# The transaction code is convert to integer
def mailer(recipient, options = {})
options = {:recipients => recipient}.merge(options)
response = post('mailer', options)
# response was a string that included RestClient::AbstractResponse,
# and it overrided #to_i method (which returns status code)
String.new(response).to_i
end
# https://madmimi.com/developer/mailer/send-to-a-list
#
# Usage:
#
# client.mailer_to_list('list_name',
# :subject => 'Subject',
# :raw_html => 'the mail body [[tracking_beacon]]')
#
# The transaction code is convert to integer
def mailer_to_list(list, options = {})
list = list.join(',') if list.is_a?(Array)
options = {:list_name => list}.merge(options)
response = post('mailer/to_list', options)
# response was a string that included RestClient::AbstractResponse,
# and it overrided #to_i method (which returns status code)
String.new(response).to_i
end
# https://madmimi.com/developer/mailer/status
#
# Usage:
#
# id = client.mailer(...)
# client.status(id)
def status(id)
get("mailers/status/#{id.to_i}")
end
# https://madmimi.com/developer/lists
# Audience lists apis
def audience_lists
response = get('audience_lists/lists.xml')
Crack::XML.parse(response)['lists']['list'].map do |list|
RestCore::MadMimi::AudienceList.new(self, list)
end
end
def create_audience_list(name)
post('audience_lists', :name => name).tap{}
RestCore::MadMimi::AudienceList.new(self, :name => name)
end
def rename_audience_list(name, new_name)
post("audience_lists/#{CGI.escape(name)}/rename", :name => new_name).tap{}
RestCore::MadMimi::AudienceList.new(self, :name => new_name)
end
def destroy_audience_list(name)
post("audience_lists/#{CGI.escape(name)}", :_method => 'delete').tap{}
end
# https://madmimi.com/developer/lists
# Audience lists apis (members)
def add_member_to_audience_list(list, email, options = {})
options = {:email => email}.merge(options)
post("audience_lists/#{CGI.escape(list)}/add", options).tap{}
end
def remove_member_from_audience_list(list, email, options = {})
options = {:email => email}.merge(options)
post("audience_lists/#{CGI.escape(list)}/remove", options).tap{}
end
def query
{'username' => username,
'api_key' => api_key,
'promotion_name' => promotion_name}
end
end
RestCore::MadMimi.send(:include, RestCore::MadMimi::Client)
|
# Configuration defaults
DEFAULT_POOL = "default"
DEFAULT_SFTP_TIMEOUT = 600 # 10mn
DEFAULT_PAGE_SIZE = 50 # 50 lines
DEFAULT_RETRY_AFTER = 10 # 10s
TARGET_BLANK = "_blank"
# Internal job constants
JOB_RANDOM_LEN = 8
JOB_IDENT_LEN = 4
JOB_TEMPFILE_LEN = 8
JOB_FTP_CHUNKMB = 2048 # 2 MB
JOB_FFMPEG_THREADS = 2
JOB_FFMPEG_ATTRIBUTES = [:video_codec, :video_bitrate, :video_bitrate_tolerance, :frame_rate, :resolution, :aspect, :keyframe_interval, :x264_vprofile, :x264_preset, :audio_codec, :audio_bitrate, :audio_sample_rate, :audio_channels]
# Internal job infos
INFO_PARAMS = :params
INFO_ERROR_MESSAGE = :error_message
INFO_ERROR_EXCEPTION = :error_exception
INFO_ERROR_BACKTRACE = :error_backtrace
INFO_SOURCE_COUNT = :source_count
INFO_SOURCE_PROCESSED = :source_processed
INFO_SOURCE_CURRENT = :source_current
INFO_SOURCE_FILES = :source_files
INFO_TRANSFER_TOTAL = :transfer_total
INFO_TRANFER_SENT = :transfer_sent
INFO_TRANFER_PROGRESS = :progress
INFO_TRANFER_BITRATE = :bitrate
INFO_TARGET_FILES = :target_files
# Constants: logger
LOG_FORMAT_PROGNAME = "%d\t%s"
LOG_HEADER_TIME = "%Y-%m-%d %H:%M:%S"
LOG_HEADER_FORMAT = "%s \t%d\t%-8s %-10s "
LOG_MESSAGE_TRIM = 200
LOG_MESSAGE_TEXT = "%s%s"
LOG_MESSAGE_ARRAY = "%s - %s"
LOG_MESSAGE_HASH = "%s * %-20s %s"
# Constants: logger app-specific prefix
LOG_PREFIX_WID = 8
LOG_PREFIX_JID = JOB_IDENT_LEN + 4
LOG_PREFIX_ID = 5
LOG_PREFIX_FORMAT = "%#{-LOG_PREFIX_WID.to_i}s %#{-LOG_PREFIX_JID.to_i}s %#{-LOG_PREFIX_ID.to_i}s "
# Constants: logger to be cleaned up
LOG_PIPE_LEN = 10
LOG_INDENT = "\t"
# Jobs statuses
JOB_STATUS_PREPARING = "preparing"
JOB_STATUS_WORKING = "working"
JOB_STATUS_TRANSFORMING = "transforming"
JOB_STATUS_CHECKING_SRC = "checking_source"
JOB_STATUS_CONNECTING = "remote_connect"
JOB_STATUS_CHDIR = "remote_chdir"
JOB_STATUS_UPLOADING = "uploading"
JOB_STATUS_RENAMING = "renaming"
JOB_STATUS_PREPARED = "prepared"
JOB_STATUS_DISCONNECTING= "remote_disconnect"
JOB_STATUS_FINISHED = "finished"
JOB_STATUS_FAILED = "failed"
JOB_STATUS_QUEUED = "queued"
JOB_STYLES = {
JOB_STATUS_QUEUED => :active,
JOB_STATUS_FAILED => :warning,
JOB_STATUS_FINISHED => :success,
JOB_STATUS_TRANSFORMING => :info,
JOB_STATUS_UPLOADING => :info,
JOB_STATUS_RENAMING => :info,
}
# Jobs statuses
JOB_METHOD_FTP = "ftp"
JOB_METHOD_FTPS = "ftps"
JOB_METHOD_SFTP = "sftp"
JOB_METHOD_FILE = "file"
# Jobs types
JOB_TYPE_TRANSFER = "transfer"
JOB_TYPE_VIDEO = "video"
JOB_TYPE_DUMMY = "dummy"
JOB_TYPES = [JOB_TYPE_TRANSFER, JOB_TYPE_VIDEO, JOB_TYPE_DUMMY]
# Worker statuses
WORKER_STATUS_STARTING = "starting"
WORKER_STATUS_WAITING = "waiting"
WORKER_STATUS_RUNNING = "running"
WORKER_STATUS_FINISHED = "finished"
WORKER_STATUS_RETRYING = "retrying"
WORKER_STATUS_TIMEOUT = "timeout"
WORKER_STATUS_CRASHED = "crashed"
WORKER_STATUS_CLEANING = "cleaning"
WORKER_STATUS_REPORTING = "reporting"
WORKER_STYLES = {
WORKER_STATUS_WAITING => nil,
WORKER_STATUS_RUNNING => :info,
WORKER_STATUS_REPORTING => :info,
WORKER_STATUS_CLEANING => :info,
WORKER_STATUS_RETRYING => :warning,
WORKER_STATUS_CRASHED => :danger,
WORKER_STATUS_FINISHED => :success,
}
# API mountpoints
MOUNT_SWAGGER_JSON = "/swagger.json"
MOUNT_SWAGGER_UI = "/swagger.html"
MOUNT_JOBS = "/jobs"
MOUNT_BOARD = "/board"
MOUNT_STATUS = "/status"
MOUNT_DEBUG = "/debug"
MOUNT_CONFIG = "/config"
# Notifications
NOTIFY_PREFIX = "rftpd"
NOTIFY_IDENTIFIER_LEN = 4
bmc-daemon-lib 0.4.0: logger: move constants to LOGGER_FORMATS
# Configuration defaults
DEFAULT_POOL = "default"
DEFAULT_SFTP_TIMEOUT = 600 # 10mn
DEFAULT_PAGE_SIZE = 50 # 50 lines
DEFAULT_RETRY_AFTER = 10 # 10s
TARGET_BLANK = "_blank"
# Internal job constants
JOB_RANDOM_LEN = 8
JOB_IDENT_LEN = 4
JOB_TEMPFILE_LEN = 8
JOB_FTP_CHUNKMB = 2048 # 2 MB
JOB_FFMPEG_THREADS = 2
JOB_FFMPEG_ATTRIBUTES = [:video_codec, :video_bitrate, :video_bitrate_tolerance, :frame_rate, :resolution, :aspect, :keyframe_interval, :x264_vprofile, :x264_preset, :audio_codec, :audio_bitrate, :audio_sample_rate, :audio_channels]
# Internal job infos
INFO_PARAMS = :params
INFO_ERROR_MESSAGE = :error_message
INFO_ERROR_EXCEPTION = :error_exception
INFO_ERROR_BACKTRACE = :error_backtrace
INFO_SOURCE_COUNT = :source_count
INFO_SOURCE_PROCESSED = :source_processed
INFO_SOURCE_CURRENT = :source_current
INFO_SOURCE_FILES = :source_files
INFO_TRANSFER_TOTAL = :transfer_total
INFO_TRANFER_SENT = :transfer_sent
INFO_TRANFER_PROGRESS = :progress
INFO_TRANFER_BITRATE = :bitrate
INFO_TARGET_FILES = :target_files
# Constants: logger
LOG_PREFIX_WID = 8
LOG_PREFIX_JID = JOB_IDENT_LEN + 4
LOG_PREFIX_ID = 5
LOGGER_FORMAT = {
# context: "%#{-LOG_PREFIX_WID.to_i}s %#{-LOG_PREFIX_JID.to_i}s %#{-LOG_PREFIX_ID.to_i}s ",
# context: "wid:%-8{wid} jid:%-12{jid} id:%-5{id}",
context: {
caller: "%-17s",
wid: "%-10s",
jid: "%-10s",
id: "%-8s",
}
}
# Constants: logger to be cleaned up
LOG_PIPE_LEN = 10
LOG_INDENT = "\t"
# Jobs statuses
JOB_STATUS_PREPARING = "preparing"
JOB_STATUS_WORKING = "working"
JOB_STATUS_TRANSFORMING = "transforming"
JOB_STATUS_CHECKING_SRC = "checking_source"
JOB_STATUS_CONNECTING = "remote_connect"
JOB_STATUS_CHDIR = "remote_chdir"
JOB_STATUS_UPLOADING = "uploading"
JOB_STATUS_RENAMING = "renaming"
JOB_STATUS_PREPARED = "prepared"
JOB_STATUS_DISCONNECTING= "remote_disconnect"
JOB_STATUS_FINISHED = "finished"
JOB_STATUS_FAILED = "failed"
JOB_STATUS_QUEUED = "queued"
JOB_STYLES = {
JOB_STATUS_QUEUED => :active,
JOB_STATUS_FAILED => :warning,
JOB_STATUS_FINISHED => :success,
JOB_STATUS_TRANSFORMING => :info,
JOB_STATUS_UPLOADING => :info,
JOB_STATUS_RENAMING => :info,
}
# Jobs statuses
JOB_METHOD_FTP = "ftp"
JOB_METHOD_FTPS = "ftps"
JOB_METHOD_SFTP = "sftp"
JOB_METHOD_FILE = "file"
# Jobs types
JOB_TYPE_TRANSFER = "transfer"
JOB_TYPE_VIDEO = "video"
JOB_TYPE_DUMMY = "dummy"
JOB_TYPES = [JOB_TYPE_TRANSFER, JOB_TYPE_VIDEO, JOB_TYPE_DUMMY]
# Worker statuses
WORKER_STATUS_STARTING = "starting"
WORKER_STATUS_WAITING = "waiting"
WORKER_STATUS_RUNNING = "running"
WORKER_STATUS_FINISHED = "finished"
WORKER_STATUS_RETRYING = "retrying"
WORKER_STATUS_TIMEOUT = "timeout"
WORKER_STATUS_CRASHED = "crashed"
WORKER_STATUS_CLEANING = "cleaning"
WORKER_STATUS_REPORTING = "reporting"
WORKER_STYLES = {
WORKER_STATUS_WAITING => nil,
WORKER_STATUS_RUNNING => :info,
WORKER_STATUS_REPORTING => :info,
WORKER_STATUS_CLEANING => :info,
WORKER_STATUS_RETRYING => :warning,
WORKER_STATUS_CRASHED => :danger,
WORKER_STATUS_FINISHED => :success,
}
# API mountpoints
MOUNT_SWAGGER_JSON = "/swagger.json"
MOUNT_SWAGGER_UI = "/swagger.html"
MOUNT_JOBS = "/jobs"
MOUNT_BOARD = "/board"
MOUNT_STATUS = "/status"
MOUNT_DEBUG = "/debug"
MOUNT_CONFIG = "/config"
# Notifications
NOTIFY_PREFIX = "rftpd"
NOTIFY_IDENTIFIER_LEN = 4
|
require 'thread'
require 'securerandom'
module RestFtpDaemon
class JobQueue < Queue
attr_reader :queued
attr_reader :popped
def initialize
# Instance variables
@queued = []
@popped = []
@waiting = []
@queued.taint # enable tainted communication
@waiting.taint
self.taint
@mutex = Mutex.new
# # Logger
# @logger = RestFtpDaemon::Logger.new(:queue, "QUEUE")
@logger = RestFtpDaemon::LoggerPool.instance.get :queue
# Identifiers generator
@last_id = 0
#@prefix = SecureRandom.hex(IDENT_JOB_LEN)
@prefix = Helpers.identifier IDENT_JOB_LEN
info "queue initialized with prefix: #{@prefix}"
# Mutex for counters
@counters = {}
@mutex_counters = Mutex.new
# Conchita configuration
@conchita = Settings.conchita
if @conchita.nil?
info "conchita: missing conchita.* configuration"
elsif @conchita[:timer].nil?
info "conchita: missing conchita.timer value"
else
Thread.new {
begin
conchita_loop
rescue Exception => e
info "CONCHITA EXCEPTION: #{e.inspect}"
end
}
end
end
def generate_id
rand(36**8).to_s(36)
@last_id ||= 0
@last_id += 1
prefixed_id @last_id
end
def counter_add name, value
@mutex_counters.synchronize do
@counters[name] ||= 0
@counters[name] += value
end
end
def counter_inc name
counter_add name, 1
end
def counter_get name
@counters[name]
end
def counters
@mutex_counters.synchronize do
@counters.clone
end
end
def popped_reverse_sorted_by_status status
return [] if status.nil?
# Select jobs from the queue if their status is (status)
ordered_popped.reverse.select { |item| item.status == status.to_sym }
end
def counts_by_status
statuses = {}
all.group_by { |job| job.status }.map { |status, jobs| statuses[status] = jobs.size }
statuses
end
def all
# queued2 = @queued.clone
# return queued2.merge(@popped)
@queued + @popped
end
def all_size
@queued.length + @popped.length
end
def find_by_id id, prefixed = false
# Build a prefixed id if expected
id = prefixed_id(id) if prefixed
info "find_by_id (#{id}, #{prefixed}) > #{id}"
# Search in both queues
@queued.select { |item| item.id == id }.last || @popped.select { |item| item.id == id }.last
end
def push job
# Check that item responds to "priorty" method
raise "JobQueue.push: job should respond to priority method" unless job.respond_to? :priority
raise "JobQueue.push: job should respond to id method" unless job.respond_to? :id
@mutex.synchronize do
# Push job into the queue
@queued.push job
#info "JobQueue.push: #{job.id}"
# Tell the job it's been queued
job.set_queued if job.respond_to? :set_queued
# Try to wake a worker up
begin
t = @waiting.shift
t.wakeup if t
rescue ThreadError
retry
end
end
end
alias << push
alias enq push
def pop(non_block=false)
# info "JobQueue.pop"
@mutex.synchronize do
while true
if @queued.empty?
# info "JobQueue.pop: empty"
raise ThreadError, "queue empty" if non_block
@waiting.push Thread.current
@mutex.sleep
else
# info "JobQueue.pop: great, I'm not empty!!"
return pick_one
end
end
end
end
alias shift pop
alias deq pop
def empty?
@queued.empty?
end
def clear
@queued.clear
end
def num_waiting
@waiting.size
end
def ordered_queue
@queued.sort_by { |item| [item.priority.to_i, - item.id.to_i] }
end
def ordered_popped
@popped.sort_by { |item| [item.updated_at] }
end
protected
def prefixed_id id
"#{@prefix}.#{id}"
end
def conchita_loop
info "conchita starting with: #{@conchita.inspect}"
loop do
conchita_clean :finished
conchita_clean :failed
sleep @conchita[:timer]
end
end
def conchita_clean status
# Init
return if status.nil?
key = "clean_#{status.to_s}"
# Read config state
max_age = @conchita[key.to_s]
return if [nil, false].include? max_age
# Delete jobs from the queue if their status is (status)
@popped.delete_if do |job|
# Skip it if wrong status
next unless job.status == status.to_sym
# Skip it if updated_at invalid
updated_at = job.updated_at
next if updated_at.nil?
# Skip it if not aged enough yet
age = Time.now - updated_at
next if age < max_age
# Ok, we have to clean it up ..
info "conchita_clean #{status.inspect} max_age:#{max_age} job:#{job.id} age:#{age}"
true
end
end
def pick_one # called inside a mutex/sync
# Sort jobs by priority and get the biggest one
picked = ordered_queue.last
return nil if picked.nil?
# Move it away from the queue to the @popped array
@queued.delete_if { |item| item == picked }
@popped.push picked
# Return picked
#info "JobQueue.pick_one: #{picked.id}"
picked
end
private
def info message
return if @logger.nil?
@logger.info_with_id message
end
end
end
added mutexes around queue sorting operations in JobQueue
require 'thread'
require 'securerandom'
module RestFtpDaemon
class JobQueue < Queue
attr_reader :queued
attr_reader :popped
def initialize
# Instance variables
@queued = []
@popped = []
@waiting = []
@queued.taint # enable tainted communication
@waiting.taint
self.taint
@mutex = Mutex.new
# # Logger
# @logger = RestFtpDaemon::Logger.new(:queue, "QUEUE")
@logger = RestFtpDaemon::LoggerPool.instance.get :queue
# Identifiers generator
@last_id = 0
#@prefix = SecureRandom.hex(IDENT_JOB_LEN)
@prefix = Helpers.identifier IDENT_JOB_LEN
info "queue initialized with prefix: #{@prefix}"
# Mutex for counters
@counters = {}
@mutex_counters = Mutex.new
# Conchita configuration
@conchita = Settings.conchita
if @conchita.nil?
info "conchita: missing conchita.* configuration"
elsif @conchita[:timer].nil?
info "conchita: missing conchita.timer value"
else
Thread.new {
begin
conchita_loop
rescue Exception => e
info "CONCHITA EXCEPTION: #{e.inspect}"
end
}
end
end
def generate_id
rand(36**8).to_s(36)
@last_id ||= 0
@last_id += 1
prefixed_id @last_id
end
def counter_add name, value
@mutex_counters.synchronize do
@counters[name] ||= 0
@counters[name] += value
end
end
def counter_inc name
counter_add name, 1
end
def counter_get name
@mutex_counters.synchronize do
@counters[name]
end
end
def counters
@mutex_counters.synchronize do
@counters
end
end
def popped_reverse_sorted_by_status status
return [] if status.nil?
# Select jobs from the queue if their status is (status)
ordered_popped.reverse.select { |item| item.status == status.to_sym }
end
def counts_by_status
statuses = {}
all.group_by { |job| job.status }.map { |status, jobs| statuses[status] = jobs.size }
statuses
end
def all
@queued + @popped
end
def all_size
@queued.length + @popped.length
end
def find_by_id id, prefixed = false
# Build a prefixed id if expected
id = prefixed_id(id) if prefixed
info "find_by_id (#{id}, #{prefixed}) > #{id}"
# Search in both queues
@queued.select { |item| item.id == id }.last || @popped.select { |item| item.id == id }.last
end
def push job
# Check that item responds to "priorty" method
raise "JobQueue.push: job should respond to priority method" unless job.respond_to? :priority
raise "JobQueue.push: job should respond to id method" unless job.respond_to? :id
@mutex.synchronize do
# Push job into the queue
@queued.push job
# Tell the job it's been queued
job.set_queued if job.respond_to? :set_queued
# Try to wake a worker up
begin
t = @waiting.shift
t.wakeup if t
rescue ThreadError
retry
end
end
end
alias << push
alias enq push
def pop(non_block=false)
# info "JobQueue.pop"
@mutex.synchronize do
while true
if @queued.empty?
# info "JobQueue.pop: empty"
raise ThreadError, "queue empty" if non_block
@waiting.push Thread.current
@mutex.sleep
else
# info "JobQueue.pop: great, I'm not empty!!"
return pick_one
end
end
end
end
alias shift pop
alias deq pop
def empty?
@queued.empty?
end
def clear
@queued.clear
end
def num_waiting
@waiting.size
end
def ordered_queue
@mutex_counters.synchronize do
@queued.sort_by { |item| [item.priority.to_i, - item.id.to_i] }
end
end
def ordered_popped
@mutex_counters.synchronize do
@popped.sort_by { |item| [item.updated_at] }
end
end
protected
def prefixed_id id
"#{@prefix}.#{id}"
end
def conchita_loop
info "conchita starting with: #{@conchita.inspect}"
loop do
conchita_clean :finished
conchita_clean :failed
sleep @conchita[:timer]
end
end
def conchita_clean status
# Init
return if status.nil?
key = "clean_#{status.to_s}"
# Read config state
max_age = @conchita[key.to_s]
return if [nil, false].include? max_age
# Delete jobs from the queue if their status is (status)
@popped.delete_if do |job|
# Skip it if wrong status
next unless job.status == status.to_sym
# Skip it if updated_at invalid
updated_at = job.updated_at
next if updated_at.nil?
# Skip it if not aged enough yet
age = Time.now - updated_at
next if age < max_age
# Ok, we have to clean it up ..
info "conchita_clean #{status.inspect} max_age:#{max_age} job:#{job.id} age:#{age}"
true
end
end
def pick_one # called inside a mutex/sync
# Sort jobs by priority and get the biggest one
picked = ordered_queue.last
return nil if picked.nil?
# Move it away from the queue to the @popped array
@queued.delete_if { |item| item == picked }
@popped.push picked
# Return picked
#info "JobQueue.pick_one: #{picked.id}"
picked
end
private
def info message
return if @logger.nil?
@logger.info_with_id message
end
end
end
|
module RestoreStrategies
# Restore Strategies client
class Client
attr_reader :entry_point
def initialize(token, secret, host = nil, port = nil)
@entry_point = '/api'
@token = token
@secret = secret
@host = host
@port = port
@credentials = {
id: @token,
key: @secret,
algorithm: 'sha256'
}
RestoreStrategies.client = self
end
def api_request(path, verb, payload = nil)
verb.downcase!
auth = Hawk::Client.build_authorization_header(
credentials: @credentials,
ts: Time.now,
method: verb,
request_uri: path,
host: @host,
port: @port,
payload: payload,
nonce: SecureRandom.uuid[0..5]
)
header = {
'Content-type' => 'application/vnd.collection+json',
'api-version' => '1',
'Authorization' => auth
}
http = Net::HTTP.new(@host, @port)
response = if verb == 'post'
http.post(path, payload, header)
else
http.get(path, header)
end
code = response.code
case code
when '500'
# internal server error
raise InternalServerError.new(response), '500 internal server error'
when /^5/
# 5xx server side error
raise ServerError.new(response), '5xx level, server side error'
when '400'
# bad request
raise RequestError.new(response), '400 error, bad request'
when '401'
# unauthorized
raise UnauthorizedError.new(response), '401 error, unauthorized'
when '403'
# forbidden
raise ForbiddenError.new(response), '403 error, forbidden'
when '404'
# not found
# pass thru 404 errors so the caller can handle them
Response.new(response, response.body)
when /^4/
# 4xx client side error
raise ClientError.new(response, "client side #{code} error"),
"client side #{code} error"
else
Response.new(response, response.body)
end
end
def get_opportunity(id)
api_request("/api/opportunities/#{id}", 'GET')
end
def list_opportunities
request = get_entry.data
json_obj = JSON.parse(request)['collection']['links']
href = get_rel_href('opportunities', json_obj)
api_request(href, 'GET')
end
def search(params)
params_str = self.class.params_to_string(params)
request = get_entry.data
json_obj = JSON.parse(request)['collection']['links']
href = get_rel_href('search', json_obj) + '?' + params_str
api_request(href, 'GET')
end
def get_signup(id)
href = get_signup_href(id)
return nil if href.nil?
api_request(href, 'GET')
end
def submit_signup(id, payload)
href = get_signup_href(id)
return nil if href.nil?
api_request(href, 'POST', payload)
end
def get_entry
api_request(entry_point, 'GET')
end
def get_signup_href(id)
request = get_opportunity(id).data
json_obj = JSON.parse(request)
return nil if json_obj.nil?
get_rel_href('signup', json_obj['collection']['items'][0]['links'])
end
def self.params_to_string(params)
query = []
return nil unless params.is_a? Hash
params.each do |key, value|
if (value.is_a? Hash) || (value.is_a? Array)
value.each do |sub_value|
value = if sub_value.is_a? Numeric
sub_value.to_s
else
CGI.escape(sub_value)
end
query.push(key + '[]=' + value)
end
else
query.push(key + '=' +
((value.is_a? Numeric) ? value.to_s : CGI.escape(value)))
end
end
query.join('&')
end
def get_rel_href(rel, json_obj)
return get_rel_href_helper(rel, json_obj) unless json_obj.is_a? Array
json_obj.each do |data|
href = get_rel_href_helper(rel, data)
return href unless href.nil?
end
nil
end
def get_rel_href_helper(rel, json_obj)
return json_obj['href'] if json_obj['rel'] == rel
nil
end
end
end
Removes request for entry point [#120024717]
module RestoreStrategies
# Restore Strategies client
class Client
attr_reader :entry_point
def initialize(token, secret, host = nil, port = nil)
@entry_point = '/api'
@token = token
@secret = secret
@host = host
@port = port
@credentials = {
id: @token,
key: @secret,
algorithm: 'sha256'
}
RestoreStrategies.client = self
end
def api_request(path, verb, payload = nil)
verb.downcase!
auth = Hawk::Client.build_authorization_header(
credentials: @credentials,
ts: Time.now,
method: verb,
request_uri: path,
host: @host,
port: @port,
payload: payload,
nonce: SecureRandom.uuid[0..5]
)
header = {
'Content-type' => 'application/vnd.collection+json',
'api-version' => '1',
'Authorization' => auth
}
http = Net::HTTP.new(@host, @port)
response = if verb == 'post'
http.post(path, payload, header)
else
http.get(path, header)
end
code = response.code
case code
when '500'
# internal server error
raise InternalServerError.new(response), '500 internal server error'
when /^5/
# 5xx server side error
raise ServerError.new(response), '5xx level, server side error'
when '400'
# bad request
raise RequestError.new(response), '400 error, bad request'
when '401'
# unauthorized
raise UnauthorizedError.new(response), '401 error, unauthorized'
when '403'
# forbidden
raise ForbiddenError.new(response), '403 error, forbidden'
when '404'
# not found
# pass thru 404 errors so the caller can handle them
Response.new(response, response.body)
when /^4/
# 4xx client side error
raise ClientError.new(response, "client side #{code} error"),
"client side #{code} error"
else
Response.new(response, response.body)
end
end
def get_opportunity(id)
api_request("/api/opportunities/#{id}", 'GET')
end
def list_opportunities
api_request('/api/opportunities', 'GET')
end
def search(params)
params_str = self.class.params_to_string(params)
api_request("/api/search?#{params_str}", 'GET')
end
def get_signup(id)
href = get_signup_href(id)
return nil if href.nil?
api_request(href, 'GET')
end
def submit_signup(id, payload)
href = get_signup_href(id)
return nil if href.nil?
api_request(href, 'POST', payload)
end
def get_signup_href(id)
request = get_opportunity(id).data
json_obj = JSON.parse(request)
return nil if json_obj.nil?
get_rel_href('signup', json_obj['collection']['items'][0]['links'])
end
def self.params_to_string(params)
query = []
return nil unless params.is_a? Hash
params.each do |key, value|
if (value.is_a? Hash) || (value.is_a? Array)
value.each do |sub_value|
value = if sub_value.is_a? Numeric
sub_value.to_s
else
CGI.escape(sub_value)
end
query.push(key + '[]=' + value)
end
else
query.push(key + '=' +
((value.is_a? Numeric) ? value.to_s : CGI.escape(value)))
end
end
query.join('&')
end
def get_rel_href(rel, json_obj)
return get_rel_href_helper(rel, json_obj) unless json_obj.is_a? Array
json_obj.each do |data|
href = get_rel_href_helper(rel, data)
return href unless href.nil?
end
nil
end
def get_rel_href_helper(rel, json_obj)
return json_obj['href'] if json_obj['rel'] == rel
nil
end
end
end
|
# -*- coding: utf-8 -*-
require 'weakref'
module RobustExcelOle
# This class essentially wraps a Win32Ole Workbook object.
# You can apply all VBA methods (starting with a capital letter)
# that you would apply for a Workbook object.
# See https://docs.microsoft.com/en-us/office/vba/api/excel.workbook#methods
class Workbook < RangeOwners
#include General
attr_accessor :excel
attr_accessor :ole_workbook
attr_accessor :stored_filename
attr_accessor :color_if_modified
attr_accessor :was_open
attr_reader :workbook
alias ole_object ole_workbook
DEFAULT_OPEN_OPTS = {
:default => {:excel => :current},
:force => {},
:update_links => :never,
:if_unsaved => :raise,
:if_obstructed => :raise,
:if_absent => :raise,
:if_exists => :raise,
:check_compatibility => false
}.freeze
CORE_DEFAULT_OPEN_OPTS = {
:default => {:excel => :current}, :force => {}, :update_links => :never
}.freeze
ABBREVIATIONS = [[:default,:d], [:force, :f], [:excel, :e], [:visible, :v],
[:if_obstructed, :if_blocked]].freeze
# opens a workbook.
# @param [String] file_or_workbook a file name or WIN32OLE workbook
# @param [Hash] opts the options
# @option opts [Hash] :default or :d
# @option opts [Hash] :force or :f
# @option opts [Symbol] :if_unsaved :raise (default), :forget, :save, :accept, :alert, :excel, or :new_excel
# @option opts [Symbol] :if_blocked :raise (default), :forget, :save, :close_if_saved, or _new_excel
# @option opts [Symbol] :if_absent :raise (default) or :create
# @option opts [Boolean] :read_only true (default) or false
# @option opts [Boolean] :update_links :never (default), :always, :alert
# @option opts [Boolean] :calculation :manual, :automatic, or nil (default)
# options:
# :default : if the workbook was already open before, then use (unchange) its properties,
# otherwise, i.e. if the workbook cannot be reopened, use the properties stated in :default
# :force : no matter whether the workbook was already open before, use the properties stated in :force
# :default and :force contain: :excel
# :excel :current (or :active or :reuse)
# -> connects to a running (the first opened) Excel instance,
# excluding the hidden Excel instance, if it exists,
# otherwise opens in a new Excel instance.
# :new -> opens in a new Excel instance
# <excel-instance> -> opens in the given Excel instance
# :visible true, false, or nil (default)
# alternatives: :default_excel, :force_excel, :visible, :d, :f, :e, :v
# :if_unsaved if an unsaved workbook with the same name is open, then
# :raise -> raises an exception
# :forget -> close the unsaved workbook, open the new workbook
# :accept -> lets the unsaved workbook open
# :alert or :excel -> gives control to Excel
# :new_excel -> opens the new workbook in a new Excel instance
# :if_obstructed if a workbook with the same name in a different path is open, then
# or :raise -> raises an exception
# :if_blocked :forget -> closes the old workbook, open the new workbook
# :save -> saves the old workbook, close it, open the new workbook
# :close_if_saved -> closes the old workbook and open the new workbook, if the old workbook is saved,
# otherwise raises an exception.
# :new_excel -> opens the new workbook in a new Excel instance
# :if_absent :raise -> raises an exception , if the file does not exists
# :create -> creates a new Excel file, if it does not exists
# :read_only true -> opens in read-only mode
# :visible true -> makes the workbook visible
# :check_compatibility true -> check compatibility when saving
# :update_links true -> user is being asked how to update links, false -> links are never updated
# @return [Workbook] a representation of a workbook
def self.new(file_or_workbook, opts = { }, &block)
options = process_options(opts)
if file_or_workbook.is_a? WIN32OLE
file = file_or_workbook.Fullname.tr('\\','/')
else
file = file_or_workbook
raise(FileNameNotGiven, 'filename is nil') if file.nil?
raise(FileNotFound, "file #{General.absolute_path(file).inspect} is a directory") if File.directory?(file)
end
# try to fetch the workbook from the bookstore
book = nil
if options[:force][:excel] != :new
# if readonly is true, then prefer a book that is given in force_excel if this option is set
forced_excel =
(options[:force][:excel].nil? || options[:force][:excel] == :current) ?
(excel_class.new(:reuse => true) if !::JRUBY_BUG_CONNECT) : excel_of(options[:force][:excel])
begin
book = if File.exists?(file)
bookstore.fetch(file, :prefer_writable => !(options[:read_only]),
:prefer_excel => (options[:read_only] ? forced_excel : nil))
end
rescue
trace "#{$!.message}"
end
if book
# hack (unless condition): calling Worksheet[]= causes calling Worksheet#workbook which calls Workbook#new(ole_workbook)
book.was_open = book.alive? unless file_or_workbook.is_a? WIN32OLE
# drop the fetched workbook if it shall be opened in another Excel instance
# or the workbook is an unsaved workbook that should not be accepted
if (options[:force][:excel].nil? || options[:force][:excel] == :current || forced_excel == book.excel) &&
!(book.alive? && !book.saved && (options[:if_unsaved] != :accept))
options[:force][:excel] = book.excel if book.excel && book.excel.alive?
book.ensure_workbook(file,options)
book.set_options(file,options)
return book
end
end
end
super(file_or_workbook, options, &block)
end
def self.open(file_or_workbook, opts = { }, &block)
new(file_or_workbook, opts, &block)
end
# creates a new Workbook object, if a file name is given
# Promotes the win32ole workbook to a Workbook object, if a win32ole-workbook is given
# @param [Variant] file_or_workbook file name or workbook
# @param [Hash] opts
# @option opts [Symbol] see above
# @return [Workbook] a workbook
def initialize(file_or_workbook, options = { }, &block)
if file_or_workbook.is_a? WIN32OLE
@ole_workbook = file_or_workbook
ole_excel = begin
WIN32OLE.connect(@ole_workbook.Fullname).Application
rescue
raise ExcelREOError, 'could not determine the Excel instance'
end
@excel = excel_class.new(ole_excel)
filename = file_or_workbook.Fullname.tr('\\','/')
else
filename = file_or_workbook
ensure_workbook(filename, options)
end
set_options(filename, options)
bookstore.store(self)
@workbook = @excel.workbook = self
r1c1_letters = @ole_workbook.Worksheets.Item(1).Cells.Item(1,1).Address(true,true,XlR1C1).gsub(/[0-9]/,'') #('ReferenceStyle' => XlR1C1).gsub(/[0-9]/,'')
address_class.new(r1c1_letters)
if block
begin
yield self
ensure
close
end
end
end
private
# translates abbreviations and synonyms and merges with default options
def self.process_options(options, proc_opts = {:use_defaults => true})
translator = proc do |opts|
erg = {}
opts.each do |key,value|
new_key = key
ABBREVIATIONS.each { |long,short| new_key = long if key == short }
if value.is_a?(Hash)
erg[new_key] = {}
value.each do |k,v|
new_k = k
ABBREVIATIONS.each { |l,s| new_k = l if k == s }
erg[new_key][new_k] = v
end
else
erg[new_key] = value
end
end
erg[:default] ||= {}
erg[:force] ||= {}
force_list = [:visible, :excel]
erg.each { |key,value| erg[:force][key] = value if force_list.include?(key) }
erg[:default][:excel] = erg[:default_excel] unless erg[:default_excel].nil?
erg[:force][:excel] = erg[:force_excel] unless erg[:force_excel].nil?
erg[:default][:excel] = :current if erg[:default][:excel] == :reuse || erg[:default][:excel] == :active
erg[:force][:excel] = :current if erg[:force][:excel] == :reuse || erg[:force][:excel] == :active
erg
end
opts = translator.call(options)
default_open_opts = proc_opts[:use_defaults] ? DEFAULT_OPEN_OPTS : CORE_DEFAULT_OPEN_OPTS
default_opts = translator.call(default_open_opts)
opts = default_opts.merge(opts)
opts[:default] = default_opts[:default].merge(opts[:default]) unless opts[:default].nil?
opts[:force] = default_opts[:force].merge(opts[:force]) unless opts[:force].nil?
opts
end
# returns an Excel object when given Excel, Workbook or Win32ole object representing a Workbook or an Excel
# @private
def self.excel_of(object)
begin
object = object.to_reo if object.is_a? WIN32OLE
object.excel
rescue
raise TypeREOError, 'given object is neither an Excel, a Workbook, nor a Win32ole'
end
end
public
# @private
# ensures an excel but not for jruby if current Excel shall be used
def ensure_excel(options)
return if @excel && @excel.alive?
excel_option = options[:force][:excel].nil? ? options[:default][:excel] : options[:force][:excel]
@excel = if excel_option == :new
excel_class.new(:reuse => false)
elsif excel_option.nil? || excel_option == :current
excel_class.new(:reuse => true)
else
self.class.excel_of(excel_option)
end
raise ExcelREOError, "excel is not alive" unless @excel && @excel.alive?
end
# @private
def ensure_workbook(filename, options)
return if (@ole_workbook && alive? && (options[:read_only].nil? || @ole_workbook.ReadOnly == options[:read_only]))
filename = @stored_filename ? @stored_filename : filename
manage_nonexisting_file(filename,options)
excel_option = options[:force][:excel].nil? ? options[:default][:excel] : options[:force][:excel]
ensure_excel(options)
workbooks = @excel.Workbooks
@ole_workbook = workbooks.Item(File.basename(filename)) rescue nil if @ole_workbook.nil?
if @ole_workbook
@was_open = true if @was_open.nil? # necessary?
manage_blocking_or_unsaved_workbook(filename,options)
open_or_create_workbook(filename,options) if @ole_workbook.ReadOnly != options[:read_only]
else
if excel_option.nil? || excel_option == :current &&
(!::JRUBY_BUG_CONNECT || filename[0] != '/')
workbooks_number_before_connect = @excel.Workbooks.Count
connect(filename,options)
@was_open = @excel.Workbooks.Count == workbooks_number_before_connect
else
open_or_create_workbook(filename,options)
end
end
end
# @private
def set_options(filename, options)
# changing read-only mode
if (!options[:read_only].nil?) && options[:read_only] != @ole_workbook.ReadOnly
ensure_workbook(filename, options)
end
retain_saved do
self.visible = options[:force][:visible].nil? ?
(@excel.Visible && @ole_workbook.Windows(@ole_workbook.Name).Visible) : options[:force][:visible]
@excel.calculation = options[:calculation] unless options[:calculation].nil?
@ole_workbook.CheckCompatibility = options[:check_compatibility] unless options[:check_compatibility].nil?
end
end
private
# @private
# connects to an unknown workbook
def connect(filename,options)
excels_number = excel_class.excels_number
workbooks_number = if excels_number>0
excel_class.current.Workbooks.Count
else 0
end
abs_filename = General.absolute_path(filename)
@ole_workbook = begin
WIN32OLE.connect(abs_filename)
rescue
if $!.message =~ /moniker/
raise WorkbookConnectingBlockingError
else
raise WorkbookConnectingUnknownError
end
end
ole_excel = begin
@ole_workbook.Application
rescue
if $!.message =~ /dispid/
raise WorkbookConnectingUnsavedError
else
raise WorkbookConnectingUnknownError
end
end
@excel = excel_class.new(ole_excel)
end
# @private
def manage_nonexisting_file(filename,options)
return if File.exist?(filename)
abs_filename = General.absolute_path(filename)
if options[:if_absent] == :create
ensure_excel(options) unless @excel && @excel.alive?
@excel.Workbooks.Add
empty_ole_workbook = excel.Workbooks.Item(excel.Workbooks.Count)
begin
empty_ole_workbook.SaveAs(abs_filename)
rescue WIN32OLERuntimeError, Java::OrgRacobCom::ComFailException => msg
raise FileNotFound, "could not save workbook with filename #{filename.inspect}"
end
else
raise FileNotFound, "file #{abs_filename.inspect} not found" +
"\nHint: If you want to create a new file, use option :if_absent => :create or Workbook::create"
end
end
# @private
def manage_blocking_or_unsaved_workbook(filename,options)
obstructed_by_other_book = if (File.basename(filename) == File.basename(@ole_workbook.Fullname))
General.absolute_path(filename) != @ole_workbook.Fullname
end
if obstructed_by_other_book
# workbook is being obstructed by a workbook with same name and different path
manage_blocking_workbook(filename,options)
else
unless @ole_workbook.Saved
# workbook open and writable, not obstructed by another workbook, but not saved
manage_unsaved_workbook(filename,options)
end
end
end
# @private
def manage_blocking_workbook(filename,options)
case options[:if_obstructed]
when :raise
raise WorkbookBlocked, "can't open workbook #{filename},
because it is being blocked by #{@ole_workbook.Fullname.tr('\\','/')} with the same name in a different path." +
"\nHint: Use the option :if_blocked with values :forget or :save,
to allow automatic closing of the old workbook (without or with saving before, respectively),
before the new workbook is being opened."
when :forget
manage_forgetting_workbook(filename, options)
when :save
manage_saving_workbook(filename, options)
when :close_if_saved
if !@ole_workbook.Saved
raise WorkbookBlocked, "workbook with the same name in a different path is unsaved: #{@ole_workbook.Fullname.tr('\\','/')}"
else
manage_forgetting_workbook(filename, options)
end
when :new_excel
manage_new_excel(filename, options)
else
raise OptionInvalid, ":if_blocked: invalid option: #{options[:if_obstructed].inspect}" +
"\nHint: Valid values are :raise, :forget, :save, :close_if_saved, :new_excel"
end
end
# @private
def manage_unsaved_workbook(filename,options)
case options[:if_unsaved]
when :raise
raise WorkbookNotSaved, "workbook is already open but not saved: #{File.basename(filename).inspect}" +
"\nHint: Save the workbook or open the workbook using option :if_unsaved with values :forget and :accept to
close the unsaved workbook and reopen it, or to let the unsaved workbook open, respectively"
when :forget
manage_forgetting_workbook(filename,options)
when :accept
# do nothing
when :save
manage_saving_workbook(filename, options)
when :alert, :excel
@excel.with_displayalerts(true) { open_or_create_workbook(filename,options) }
when :new_excel
manage_new_excel(filename, options)
else
raise OptionInvalid, ":if_unsaved: invalid option: #{options[:if_unsaved].inspect}" +
"\nHint: Valid values are :raise, :forget, :save, :accept, :alert, :excel, :new_excel"
end
end
# @private
def manage_forgetting_workbook(filename, options)
@excel.with_displayalerts(false) { @ole_workbook.Close }
@ole_workbook = nil
open_or_create_workbook(filename, options)
end
# @private
def manage_saving_workbook(filename, options)
save unless @ole_workbook.Saved
manage_forgetting_workbook(filename, options)
end
# @private
def manage_new_excel(filename, options)
@excel = excel_class.new(:reuse => false)
@ole_workbook = nil
open_or_create_workbook(filename, options)
end
# @private
def open_or_create_workbook(filename, options)
return if @ole_workbook && options[:if_unsaved] != :alert && options[:if_unsaved] != :excel &&
(options[:read_only].nil? || options[:read_only]==@ole_workbook.ReadOnly )
begin
abs_filename = General.absolute_path(filename)
begin
@was_open = false if @was_open.nil?
workbooks = @excel.Workbooks
rescue WIN32OLERuntimeError, Java::OrgRacobCom::ComFailException => msg
raise UnexpectedREOError, "cannot access workbooks: #{msg.message} #{msg.backtrace}"
end
begin
with_workaround_linked_workbooks_excel2007(options) do
# temporary workaround until jruby-win32ole implements named parameters (Java::JavaLang::RuntimeException (createVariant() not implemented for class org.jruby.RubyHash)
workbooks.Open(abs_filename,
updatelinks_vba(options[:update_links]),
options[:read_only] )
end
rescue WIN32OLERuntimeError => msg
# for Excel2007: for option :if_unsaved => :alert and user cancels: this error appears?
# if yes: distinguish these events
raise UnexpectedREOError, "cannot open workbook: #{msg.message} #{msg.backtrace}"
end
begin
# workaround for bug in Excel 2010: workbook.Open does not always return the workbook when given file name
begin
@ole_workbook = workbooks.Item(File.basename(filename))
rescue WIN32OLERuntimeError => msg
raise UnexpectedREOError, "WIN32OLERuntimeError: #{msg.message}"
end
rescue WIN32OLERuntimeError => msg
raise UnexpectedREOError, "WIN32OLERuntimeError: #{msg.message} #{msg.backtrace}"
end
end
end
# @private
# translating the option UpdateLinks from REO to VBA
# setting UpdateLinks works only if calculation mode is automatic,
# parameter 'UpdateLinks' has no effect
def updatelinks_vba(updatelinks_reo)
case updatelinks_reo
when :alert then RobustExcelOle::XlUpdateLinksUserSetting
when :never then RobustExcelOle::XlUpdateLinksNever
when :always then RobustExcelOle::XlUpdateLinksAlways
else RobustExcelOle::XlUpdateLinksNever
end
end
# @private
# workaround for linked workbooks for Excel 2007:
# opening and closing a dummy workbook if Excel has no workbooks.
# delay: with visible: 0.2 sec, without visible almost none
def with_workaround_linked_workbooks_excel2007(options)
old_visible_value = @excel.Visible
workbooks = @excel.Workbooks
workaround_condition = @excel.Version.split('.').first.to_i == 12 && workbooks.Count == 0
if workaround_condition
workbooks.Add
@excel.calculation = options[:calculation].nil? ? @excel.calculation : options[:calculation]
end
begin
# @excel.with_displayalerts(update_links_opt == :alert ? true : @excel.displayalerts) do
yield self
ensure
@excel.with_displayalerts(false) { workbooks.Item(1).Close } if workaround_condition
@excel.visible = old_visible_value
end
end
public
# creates, i.e., opens a new, empty workbook, and saves it under a given filename
# @param [String] filename the filename under which the new workbook should be saved
# @param [Hash] opts the options as in Workbook::open
def self.create(filename, opts = { })
open(filename, :if_absent => :create)
end
# closes the workbook, if it is alive
# @param [Hash] opts the options
# @option opts [Symbol] :if_unsaved :raise (default), :save, :forget, :keep_open, or :alert
# options:
# :if_unsaved if the workbook is unsaved
# :raise -> raises an exception
# :save -> saves the workbook before it is closed
# :forget -> closes the workbook
# :keep_open -> keep the workbook open
# :alert or :excel -> gives control to excel
# @raise WorkbookNotSaved if the option :if_unsaved is :raise and the workbook is unsaved
# @raise OptionInvalid if the options is invalid
def close(opts = {:if_unsaved => :raise})
if alive? && !@ole_workbook.Saved && writable
case opts[:if_unsaved]
when :raise
raise WorkbookNotSaved, "workbook is unsaved: #{File.basename(self.stored_filename).inspect}" +
"\nHint: Use option :save or :forget to close the workbook with or without saving"
when :save
save
close_workbook
when :forget
@excel.with_displayalerts(false) { close_workbook }
when :keep_open
# nothing
when :alert, :excel
@excel.with_displayalerts(true) { close_workbook }
else
raise OptionInvalid, ":if_unsaved: invalid option: #{opts[:if_unsaved].inspect}" +
"\nHint: Valid values are :raise, :save, :keep_open, :alert, :excel"
end
else
close_workbook
end
# trace "close: canceled by user" if alive? &&
# (opts[:if_unsaved] == :alert || opts[:if_unsaved] == :excel) && (not @ole_workbook.Saved)
end
private
# @private
def close_workbook
@ole_workbook.Close if alive?
@ole_workbook = nil unless alive?
end
public
# keeps the saved-status unchanged
def retain_saved
saved = self.Saved
begin
yield self
ensure
self.Saved = saved
end
end
def for_reading(*args, &block)
args = args.dup
opts = args.last.is_a?(Hash) ? args.pop : {}
opts = {:writable => false}.merge(opts)
args.push opts
unobtrusively(*args, &block)
end
def for_modifying(*args, &block)
args = args.dup
opts = args.last.is_a?(Hash) ? args.pop : {}
opts = {:writable => true}.merge(opts)
args.push opts
unobtrusively(*args, &block)
end
def self.for_reading(*args, &block)
args = args.dup
opts = args.last.is_a?(Hash) ? args.pop : {}
opts = {:writable => false}.merge(opts)
args.push opts
unobtrusively(*args, &block)
end
def self.for_modifying(*args, &block)
args = args.dup
opts = args.last.is_a?(Hash) ? args.pop : {}
opts = {:writable => true}.merge(opts)
args.push opts
unobtrusively(*args, &block)
end
# allows to read or modify a workbook such that its state remains unchanged
# the state comprises, whether the workbok was open, saved, writable, visible,
# includes calculation mode, and check compatibility
# @param [String] file_or_workbook a file name or WIN32OLE workbook
# @param [Hash] opts the options
# @option opts [Variant] :if_closed Excel where to open the workbook, if the workbook was closed
# :current (default), :new or an Excel instance (this option is for known workbooks only)
# @option opts [Boolean] :read_only true/false (default), open the workbook in read-only/read-write modus (save changes)
# @option opts [Boolean] :writable true (default)/false changes of the workbook shall be saved/not saved
# @option opts [Boolean] :keep_open whether the workbook shall be kept open after unobtrusively opening (default: false)
# @return [Workbook] a workbook
def self.unobtrusively(file_or_workbook, opts = { })
file = (file_or_workbook.is_a? WIN32OLE) ? file_or_workbook.Fullname.tr('\\','/') : file_or_workbook
opts = process_options(opts)
raise OptionInvalid, 'contradicting options' if opts[:writable] && opts[:read_only]
opts = {:if_closed => :current, :keep_open => false}.merge(opts)
prefer_writable = ((!(opts[:read_only]) || opts[:writable] == true) &&
!(opts[:read_only].nil? && opts[:writable] == false))
book = bookstore.fetch(file, :prefer_writable => prefer_writable)
excel_opts = (book.nil? || (book && !book.alive?)) ? {:force => {:excel => opts[:if_closed]}} :
{:force => {:excel => opts[:force][:excel]}, :default => {:excel => opts[:default][:excel]}}
open_opts = excel_opts.merge({:if_unsaved => :accept})
begin
book = open(file, open_opts)
was_visible = book.visible
was_writable = book.writable
was_saved = book.saved
was_check_compatibility = book.check_compatibility
was_calculation = book.excel.calculation
book.set_options(file,opts)
yield book
ensure
if book && book.alive?
do_not_write = opts[:read_only] || opts[:writable]==false
book.save unless book.saved || do_not_write || book.ReadOnly
if (opts[:read_only] && was_writable) || (!opts[:read_only] && !was_writable)
book.set_options(file, opts.merge({:read_only => !was_writable,
:if_unsaved => (opts[:writable]==false ? :forget : :save)}))
end
if book.was_open
book.visible = was_visible
book.CheckCompatibility = was_check_compatibility
book.excel.calculation = was_calculation
end
book.Saved = (was_saved || !book.was_open)
book.close unless book.was_open || opts[:keep_open]
end
end
end
=begin
# allows to read or modify a workbook such that its state remains unchanged
# state comprises: open, saved, writable, visible, calculation mode, check compatibility
# @param [String] file_or_workbook a file name or WIN32OLE workbook
# @param [Hash] opts the options
# @option opts [Variant] :if_closed :current (default), :new or an Excel instance
# @option opts [Boolean] :read_only true/false (default), open the workbook in read-only/read-write modus (save changes)
# @option opts [Boolean] :writable true (default)/false changes of the workbook shall be saved/not saved
# @option opts [Boolean] :keep_open whether the workbook shall be kept open after unobtrusively opening (default: false)
# @return [Workbook] a workbook
def self.unobtrusively(file_or_workbook, opts = { })
file = (file_or_workbook.is_a? WIN32OLE) ? file_or_workbook.Fullname.tr('\\','/') : file_or_workbook
opts = process_options(opts)
raise OptionInvalid, 'contradicting options' if opts[:writable] && opts[:read_only]
opts = {:if_closed => :current, :keep_open => false}.merge(opts)
prefer_writable = ((!(opts[:read_only]) || opts[:writable] == true) &&
!(opts[:read_only].nil? && opts[:writable] == false))
book = bookstore.fetch(file, :prefer_writable => prefer_writable)
excel_opts = (book.nil? || (book && !book.alive?)) ? {:force => {:excel => opts[:if_closed]}} :
{:force => {:excel => opts[:force][:excel]}, :default => {:excel => opts[:default][:excel]}}
open_opts = excel_opts.merge({:if_unsaved => :accept})
begin
book = open(file, open_opts)
book.unobtrusively
end
end
=end
def unobtrusively(opts = { })
file = stored_filename
opts = self.class.process_options(opts)
raise OptionInvalid, 'contradicting options' if opts[:writable] && opts[:read_only]
opts = {:if_closed => :current, :keep_open => false}.merge(opts)
excel_opts = !alive? ? {:force => {:excel => opts[:if_closed]}} :
{:force => {:excel => opts[:force][:excel]}, :default => {:excel => opts[:default][:excel]}}
open_opts = excel_opts.merge({:if_unsaved => :accept})
begin
was_open = alive?
was_visible = visible
was_writable = writable
was_saved = saved
was_check_compatibility = check_compatibility
was_calculation = calculation
set_options(file,opts)
yield self
ensure
if was_open
do_not_write = opts[:read_only] || opts[:writable]==false
save unless saved || do_not_write || !writable
if (opts[:read_only] && was_writable) || (!opts[:read_only] && !was_writable)
set_options(file, opts.merge({:read_only => !was_writable,
:if_unsaved => (opts[:writable]==false ? :forget : :save)}))
end
if was_open
visible = was_visible
@ole_workbook.CheckCompatibility = was_check_compatibility
@excel.calculation = was_calculation
end
@ole_workbook.Saved = (was_saved || !was_open)
close unless was_open || opts[:keep_open]
end
end
end
# reopens a closed workbook
# @options options
def reopen(options = { })
book = self.class.open(@stored_filename, options)
raise WorkbookREOError('cannot reopen book') unless book && book.alive?
book
end
# simple save of a workbook.
# @return [Boolean] true, if successfully saved, nil otherwise
def save(opts = { }) # option opts is deprecated #
raise ObjectNotAlive, 'workbook is not alive' unless alive?
raise WorkbookReadOnly, 'Not opened for writing (opened with :read_only option)' if @ole_workbook.ReadOnly
# if you have open the workbook with :read_only => true,
# then you could close the workbook and open it again with option :read_only => false
# otherwise the workbook may already be open writable in an another Excel instance
# then you could use this workbook or close the workbook there
begin
@ole_workbook.Save
rescue WIN32OLERuntimeError, Java::OrgRacobCom::ComFailException => msg
if msg.message =~ /SaveAs/ && msg.message =~ /Workbook/
raise WorkbookNotSaved, 'workbook not saved'
else
raise UnexpectedREOError, "unknown WIN32OLERuntimeError:\n#{msg.message}"
end
end
true
end
# saves a workbook with a given file name.
# @param [String] file file name
# @param [Hash] opts the options
# @option opts [Symbol] :if_exists :raise (default), :overwrite, or :alert, :excel
# @option opts [Symbol] :if_obstructed :raise (default), :forget, :save, or :close_if_saved
# options:
# :if_exists if a file with the same name exists, then
# :raise -> raises an exception, dont't write the file (default)
# :overwrite -> writes the file, delete the old file
# :alert or :excel -> gives control to Excel
# :if_obstructed if a workbook with the same name and different path is already open and blocks the saving, then
# or :raise -> raises an exception
# :if_blocked :forget -> closes the blocking workbook
# :save -> saves the blocking workbook and closes it
# :close_if_saved -> closes the blocking workbook, if it is saved,
# otherwise raises an exception
# @return [Workbook], the book itself, if successfully saved, raises an exception otherwise
def save_as(file, opts = { })
raise FileNameNotGiven, 'filename is nil' if file.nil?
raise ObjectNotAlive, 'workbook is not alive' unless alive?
raise WorkbookReadOnly, 'Not opened for writing (opened with :read_only option)' if @ole_workbook.ReadOnly
raise(FileNotFound, "file #{General.absolute_path(file).inspect} is a directory") if File.directory?(file)
options = self.class.process_options(opts)
if File.exist?(file)
case options[:if_exists]
when :overwrite
if file == self.filename
save
return self
else
begin
File.delete(file)
rescue Errno::EACCES
raise WorkbookBeingUsed, 'workbook is open and being used in an Excel instance'
end
end
when :alert, :excel
@excel.with_displayalerts true do
save_as_workbook(file, options)
end
return self
when :raise
raise FileAlreadyExists, "file already exists: #{File.basename(file).inspect}" +
"\nHint: Use option :if_exists => :overwrite, if you want to overwrite the file"
else
raise OptionInvalid, ":if_exists: invalid option: #{options[:if_exists].inspect}" +
"\nHint: Valid values are :raise, :overwrite, :alert, :excel"
end
end
other_workbook = @excel.Workbooks.Item(File.basename(file)) rescue nil
if other_workbook && self.filename != other_workbook.Fullname.tr('\\','/')
case options[:if_obstructed]
when :raise
raise WorkbookBlocked, "blocked by another workbook: #{other_workbook.Fullname.tr('\\','/')}" +
"\nHint: Use the option :if_blocked with values :forget or :save to
close or save and close the blocking workbook"
when :forget
# nothing
when :save
other_workbook.Save
when :close_if_saved
unless other_workbook.Saved
raise WorkbookBlocked, "blocking workbook is unsaved: #{File.basename(file).inspect}" +
"\nHint: Use option :if_blocked => :save to save the blocking workbooks"
end
else
raise OptionInvalid, ":if_blocked: invalid option: #{options[:if_obstructed].inspect}" +
"\nHint: Valid values are :raise, :forget, :save, :close_if_saved"
end
other_workbook.Close
end
save_as_workbook(file, options)
self
end
private
# @private
def save_as_workbook(file, options)
dirname, basename = File.split(file)
file_format =
case File.extname(basename)
when '.xls' then RobustExcelOle::XlExcel8
when '.xlsx' then RobustExcelOle::XlOpenXMLWorkbook
when '.xlsm' then RobustExcelOle::XlOpenXMLWorkbookMacroEnabled
end
@ole_workbook.SaveAs(General.absolute_path(file), file_format)
bookstore.store(self)
rescue WIN32OLERuntimeError, Java::OrgRacobCom::ComFailException => msg
if msg.message =~ /SaveAs/ && msg.message =~ /Workbook/
# trace "save: canceled by user" if options[:if_exists] == :alert || options[:if_exists] == :excel
# another possible semantics. raise WorkbookREOError, "could not save Workbook"
else
raise UnexpectedREOError, "unknown WIN32OELERuntimeError:\n#{msg.message}"
end
end
public
# closes a given file if it is open
# @options opts [Symbol] :if_unsaved
def self.close(file, opts = {:if_unsaved => :raise})
book = begin
bookstore.fetch(file)
rescue
nil
end
book.close(opts) if book && book.alive?
end
# saves a given file if it is open
def self.save(file)
book = bookstore.fetch(file) rescue nil
book.save if book && book.alive?
end
# saves a given file under a new name if it is open
def self.save_as(file, new_file, opts = { })
book = begin
bookstore.fetch(file)
rescue
nil
end
book.save_as(new_file, opts) if book && book.alive?
end
# returns a sheet, if a sheet name or a number is given
# @param [String] or [Number]
# @returns [Worksheet]
def sheet(name)
worksheet_class.new(@ole_workbook.Worksheets.Item(name))
rescue WIN32OLERuntimeError, Java::OrgRacobCom::ComFailException => msg
raise NameNotFound, "could not return a sheet with name #{name.inspect}"
end
def each
@ole_workbook.Worksheets.each do |sheet|
yield worksheet_class.new(sheet)
end
end
def each_with_index(offset = 0)
i = offset
@ole_workbook.Worksheets.each do |sheet|
yield worksheet_class.new(sheet), i
i += 1
end
end
# copies a sheet to another position if a sheet is given, or adds an empty sheet
# default: copied or empty sheet is appended, i.e. added behind the last sheet
# @param [Worksheet] sheet a sheet that shall be copied (optional)
# @param [Hash] opts the options
# @option opts [Symbol] :as new name of the copied or added sheet
# @option opts [Symbol] :before a sheet before which the sheet shall be inserted
# @option opts [Symbol] :after a sheet after which the sheet shall be inserted
# @return [Worksheet] the copied or added sheet
def add_or_copy_sheet(sheet = nil, opts = { })
if sheet.is_a? Hash
opts = sheet
sheet = nil
end
new_sheet_name = opts.delete(:as)
last_sheet_local = last_sheet
after_or_before, base_sheet = opts.to_a.first || [:after, last_sheet_local]
begin
if !::JRUBY_BUG_COPYSHEETS
if sheet
sheet.Copy({ after_or_before.to_s => base_sheet.ole_worksheet })
else
@ole_workbook.Worksheets.Add({ after_or_before.to_s => base_sheet.ole_worksheet })
#@ole_workbook.Worksheets.Item(ole_workbook.Worksheets.Count).Activate
end
else
if after_or_before == :before
if sheet
sheet.Copy(base_sheet.ole_worksheet)
else
ole_workbook.Worksheets.Add(base_sheet.ole_worksheet)
end
else
#not_given = WIN32OLE_VARIANT.new(nil, WIN32OLE::VARIANT::VT_NULL)
#ole_workbook.Worksheets.Add(not_given,base_sheet.ole_worksheet)
if base_sheet.name != last_sheet_local.name
if sheet
sheet.Copy(base_sheet.Next)
else
ole_workbook.Worksheets.Add(base_sheet.Next)
end
else
if sheet
sheet.Copy(base_sheet.ole_worksheet)
else
ole_workbook.Worksheets.Add(base_sheet.ole_worksheet)
end
base_sheet.Move(ole_workbook.Worksheets.Item(ole_workbook.Worksheets.Count-1))
ole_workbook.Worksheets.Item(ole_workbook.Worksheets.Count).Activate
end
end
end
rescue WIN32OLERuntimeError, NameNotFound, Java::OrgRacobCom::ComFailException
raise WorksheetREOError, "could not add given worksheet #{sheet.inspect}"
end
#ole_sheet = @excel.Activesheet
ole_sheet = ole_workbook.Activesheet
#ole_sheet = ole_sheet.nil? ? ole_workbook.Worksheets.Item(ole_workbook.Worksheets.Count) : ole_sheet
new_sheet = worksheet_class.new(ole_sheet)
new_sheet.name = new_sheet_name if new_sheet_name
new_sheet
end
# for compatibility to older versions
def add_sheet(sheet = nil, opts = { })
add_or_copy_sheet(sheet, opts)
end
# for compatibility to older versions
def copy_sheet(sheet, opts = { })
add_or_copy_sheet(sheet, opts)
end
def last_sheet
worksheet_class.new(@ole_workbook.Worksheets.Item(@ole_workbook.Worksheets.Count))
end
def first_sheet
worksheet_class.new(@ole_workbook.Worksheets.Item(1))
end
# returns the value of a range
# @param [String] name the name of a range
# @returns [Variant] the value of the range
def [] name
namevalue_glob(name)
end
# sets the value of a range
# @param [String] name the name of the range
# @param [Variant] value the contents of the range
def []= (name, value)
old_color_if_modified = @color_if_modified
workbook.color_if_modified = 42 # 42 - aqua-marin, 4-green
set_namevalue_glob(name,value)
workbook.color_if_modified = old_color_if_modified
end
# sets options
# @param [Hash] opts
def for_this_workbook(opts)
return unless alive?
opts = self.class.process_options(opts, :use_defaults => false)
visible_before = visible
check_compatibility_before = check_compatibility
unless opts[:read_only].nil?
# if the ReadOnly status shall be changed, then close and reopen it
if (!writable && !(opts[:read_only])) || (writable && opts[:read_only])
opts[:check_compatibility] = check_compatibility if opts[:check_compatibility].nil?
close(:if_unsaved => true)
open_or_create_workbook(@stored_filename, opts)
end
end
self.visible = opts[:force][:visible].nil? ? visible_before : opts[:force][:visible]
self.CheckCompatibility = opts[:check_compatibility].nil? ? check_compatibility_before : opts[:check_compatibility]
@excel.calculation = opts[:calculation] unless opts[:calculation].nil?
end
# brings workbook to foreground, makes it available for heyboard inputs, makes the Excel instance visible
def focus
self.visible = true
@excel.focus
@ole_workbook.Activate
end
# returns true, if the workbook reacts to methods, false otherwise
def alive?
@ole_workbook.Name
true
rescue
@ole_workbook = nil # dead object won't be alive again
# t $!.message
false
end
# returns the full file name of the workbook
def filename
@ole_workbook.Fullname.tr('\\','/') rescue nil
end
# @private
def writable
!@ole_workbook.ReadOnly if @ole_workbook
end
# @private
def saved
@ole_workbook.Saved if @ole_workbook
end
def calculation
@excel.calculation if @ole_workbook
end
# @private
def check_compatibility
@ole_workbook.CheckCompatibility if @ole_workbook
end
# returns true, if the workbook is visible, false otherwise
def visible
@excel.Visible && @ole_workbook.Windows(@ole_workbook.Name).Visible
end
# makes both the Excel instance and the window of the workbook visible, or the window invisible
# does not do anything if geben visible_value is nil
# @param [Boolean] visible_value determines whether the workbook shall be visible
def visible= visible_value
return if visible_value.nil?
@excel.visible = true if visible_value
self.window_visible = @excel.Visible ? visible_value : true
end
# returns true, if the window of the workbook is set to visible, false otherwise
def window_visible
@ole_workbook.Windows(@ole_workbook.Name).Visible
end
# makes the window of the workbook visible or invisible
# @param [Boolean] visible_value determines whether the window of the workbook shall be visible
def window_visible= visible_value
retain_saved do
@ole_workbook.Windows(@ole_workbook.Name).Visible = visible_value if @ole_workbook.Windows.Count > 0
end
end
# @return [Boolean] true, if the full workbook names and excel Instances are identical, false otherwise
def == other_book
other_book.is_a?(Workbook) &&
@excel == other_book.excel &&
self.filename == other_book.filename
end
def self.books
bookstore.books
end
# @private
def self.bookstore
@@bookstore ||= Bookstore.new
end
# @private
def bookstore
self.class.bookstore
end
# @private
def to_s
self.filename.to_s
end
# @private
def inspect
'#<Workbook: ' + ('not alive ' unless alive?).to_s + (File.basename(self.filename) if alive?).to_s + " #{@ole_workbook} #{@excel}" + '>'
end
# @private
def self.excel_class
@excel_class ||= begin
module_name = self.parent_name
"#{module_name}::Excel".constantize
rescue NameError => e
# trace "excel_class: NameError: #{e}"
Excel
end
end
# @private
def self.worksheet_class
@worksheet_class ||= begin
module_name = self.parent_name
"#{module_name}::Worksheet".constantize
rescue NameError => e
Worksheet
end
end
# @private
def self.address_class
@address_class ||= begin
module_name = self.parent_name
"#{module_name}::Address".constantize
rescue NameError => e
Address
end
end
# @private
def excel_class
self.class.excel_class
end
# @private
def worksheet_class
self.class.worksheet_class
end
# @private
def address_class
self.class.address_class
end
include MethodHelpers
private
def method_missing(name, *args)
if name.to_s[0,1] =~ /[A-Z]/
raise ObjectNotAlive, 'method missing: workbook not alive' unless alive?
if ::JRUBY_BUG_ERRORMESSAGE
begin
@ole_workbook.send(name, *args)
rescue Java::OrgRacobCom::ComFailException
raise VBAMethodMissingError, "unknown VBA property or method #{name.inspect}"
end
else
begin
@ole_workbook.send(name, *args)
rescue NoMethodError
raise VBAMethodMissingError, "unknown VBA property or method #{name.inspect}"
end
end
else
super
end
end
end
public
Book = Workbook
end
Workbook.unobtrusively via #unobtrusively
# -*- coding: utf-8 -*-
require 'weakref'
module RobustExcelOle
# This class essentially wraps a Win32Ole Workbook object.
# You can apply all VBA methods (starting with a capital letter)
# that you would apply for a Workbook object.
# See https://docs.microsoft.com/en-us/office/vba/api/excel.workbook#methods
class Workbook < RangeOwners
#include General
attr_accessor :excel
attr_accessor :ole_workbook
attr_accessor :stored_filename
attr_accessor :color_if_modified
attr_accessor :was_open
attr_reader :workbook
alias ole_object ole_workbook
DEFAULT_OPEN_OPTS = {
:default => {:excel => :current},
:force => {},
:update_links => :never,
:if_unsaved => :raise,
:if_obstructed => :raise,
:if_absent => :raise,
:if_exists => :raise,
:check_compatibility => false
}.freeze
CORE_DEFAULT_OPEN_OPTS = {
:default => {:excel => :current}, :force => {}, :update_links => :never
}.freeze
ABBREVIATIONS = [[:default,:d], [:force, :f], [:excel, :e], [:visible, :v],
[:if_obstructed, :if_blocked]].freeze
# opens a workbook.
# @param [String] file_or_workbook a file name or WIN32OLE workbook
# @param [Hash] opts the options
# @option opts [Hash] :default or :d
# @option opts [Hash] :force or :f
# @option opts [Symbol] :if_unsaved :raise (default), :forget, :save, :accept, :alert, :excel, or :new_excel
# @option opts [Symbol] :if_blocked :raise (default), :forget, :save, :close_if_saved, or _new_excel
# @option opts [Symbol] :if_absent :raise (default) or :create
# @option opts [Boolean] :read_only true (default) or false
# @option opts [Boolean] :update_links :never (default), :always, :alert
# @option opts [Boolean] :calculation :manual, :automatic, or nil (default)
# options:
# :default : if the workbook was already open before, then use (unchange) its properties,
# otherwise, i.e. if the workbook cannot be reopened, use the properties stated in :default
# :force : no matter whether the workbook was already open before, use the properties stated in :force
# :default and :force contain: :excel
# :excel :current (or :active or :reuse)
# -> connects to a running (the first opened) Excel instance,
# excluding the hidden Excel instance, if it exists,
# otherwise opens in a new Excel instance.
# :new -> opens in a new Excel instance
# <excel-instance> -> opens in the given Excel instance
# :visible true, false, or nil (default)
# alternatives: :default_excel, :force_excel, :visible, :d, :f, :e, :v
# :if_unsaved if an unsaved workbook with the same name is open, then
# :raise -> raises an exception
# :forget -> close the unsaved workbook, open the new workbook
# :accept -> lets the unsaved workbook open
# :alert or :excel -> gives control to Excel
# :new_excel -> opens the new workbook in a new Excel instance
# :if_obstructed if a workbook with the same name in a different path is open, then
# or :raise -> raises an exception
# :if_blocked :forget -> closes the old workbook, open the new workbook
# :save -> saves the old workbook, close it, open the new workbook
# :close_if_saved -> closes the old workbook and open the new workbook, if the old workbook is saved,
# otherwise raises an exception.
# :new_excel -> opens the new workbook in a new Excel instance
# :if_absent :raise -> raises an exception , if the file does not exists
# :create -> creates a new Excel file, if it does not exists
# :read_only true -> opens in read-only mode
# :visible true -> makes the workbook visible
# :check_compatibility true -> check compatibility when saving
# :update_links true -> user is being asked how to update links, false -> links are never updated
# @return [Workbook] a representation of a workbook
def self.new(file_or_workbook, opts = { }, &block)
options = process_options(opts)
if file_or_workbook.is_a? WIN32OLE
file = file_or_workbook.Fullname.tr('\\','/')
else
file = file_or_workbook
raise(FileNameNotGiven, 'filename is nil') if file.nil?
raise(FileNotFound, "file #{General.absolute_path(file).inspect} is a directory") if File.directory?(file)
end
# try to fetch the workbook from the bookstore
book = nil
if options[:force][:excel] != :new
# if readonly is true, then prefer a book that is given in force_excel if this option is set
forced_excel =
(options[:force][:excel].nil? || options[:force][:excel] == :current) ?
(excel_class.new(:reuse => true) if !::JRUBY_BUG_CONNECT) : excel_of(options[:force][:excel])
begin
book = if File.exists?(file)
bookstore.fetch(file, :prefer_writable => !(options[:read_only]),
:prefer_excel => (options[:read_only] ? forced_excel : nil))
end
rescue
trace "#{$!.message}"
end
if book
# hack (unless condition): calling Worksheet[]= causes calling Worksheet#workbook which calls Workbook#new(ole_workbook)
book.was_open = book.alive? unless file_or_workbook.is_a? WIN32OLE
# drop the fetched workbook if it shall be opened in another Excel instance
# or the workbook is an unsaved workbook that should not be accepted
if (options[:force][:excel].nil? || options[:force][:excel] == :current || forced_excel == book.excel) &&
!(book.alive? && !book.saved && (options[:if_unsaved] != :accept))
options[:force][:excel] = book.excel if book.excel && book.excel.alive?
book.ensure_workbook(file,options)
book.set_options(file,options)
return book
end
end
end
super(file_or_workbook, options, &block)
end
def self.open(file_or_workbook, opts = { }, &block)
new(file_or_workbook, opts, &block)
end
# creates a new Workbook object, if a file name is given
# Promotes the win32ole workbook to a Workbook object, if a win32ole-workbook is given
# @param [Variant] file_or_workbook file name or workbook
# @param [Hash] opts
# @option opts [Symbol] see above
# @return [Workbook] a workbook
def initialize(file_or_workbook, options = { }, &block)
if file_or_workbook.is_a? WIN32OLE
@ole_workbook = file_or_workbook
ole_excel = begin
WIN32OLE.connect(@ole_workbook.Fullname).Application
rescue
raise ExcelREOError, 'could not determine the Excel instance'
end
@excel = excel_class.new(ole_excel)
filename = file_or_workbook.Fullname.tr('\\','/')
else
filename = file_or_workbook
ensure_workbook(filename, options)
end
set_options(filename, options)
bookstore.store(self)
@workbook = @excel.workbook = self
r1c1_letters = @ole_workbook.Worksheets.Item(1).Cells.Item(1,1).Address(true,true,XlR1C1).gsub(/[0-9]/,'') #('ReferenceStyle' => XlR1C1).gsub(/[0-9]/,'')
address_class.new(r1c1_letters)
if block
begin
yield self
ensure
close
end
end
end
private
# translates abbreviations and synonyms and merges with default options
def self.process_options(options, proc_opts = {:use_defaults => true})
translator = proc do |opts|
erg = {}
opts.each do |key,value|
new_key = key
ABBREVIATIONS.each { |long,short| new_key = long if key == short }
if value.is_a?(Hash)
erg[new_key] = {}
value.each do |k,v|
new_k = k
ABBREVIATIONS.each { |l,s| new_k = l if k == s }
erg[new_key][new_k] = v
end
else
erg[new_key] = value
end
end
erg[:default] ||= {}
erg[:force] ||= {}
force_list = [:visible, :excel]
erg.each { |key,value| erg[:force][key] = value if force_list.include?(key) }
erg[:default][:excel] = erg[:default_excel] unless erg[:default_excel].nil?
erg[:force][:excel] = erg[:force_excel] unless erg[:force_excel].nil?
erg[:default][:excel] = :current if erg[:default][:excel] == :reuse || erg[:default][:excel] == :active
erg[:force][:excel] = :current if erg[:force][:excel] == :reuse || erg[:force][:excel] == :active
erg
end
opts = translator.call(options)
default_open_opts = proc_opts[:use_defaults] ? DEFAULT_OPEN_OPTS : CORE_DEFAULT_OPEN_OPTS
default_opts = translator.call(default_open_opts)
opts = default_opts.merge(opts)
opts[:default] = default_opts[:default].merge(opts[:default]) unless opts[:default].nil?
opts[:force] = default_opts[:force].merge(opts[:force]) unless opts[:force].nil?
opts
end
# returns an Excel object when given Excel, Workbook or Win32ole object representing a Workbook or an Excel
# @private
def self.excel_of(object)
begin
object = object.to_reo if object.is_a? WIN32OLE
object.excel
rescue
raise TypeREOError, 'given object is neither an Excel, a Workbook, nor a Win32ole'
end
end
public
# @private
# ensures an excel but not for jruby if current Excel shall be used
def ensure_excel(options)
return if @excel && @excel.alive?
excel_option = options[:force][:excel].nil? ? options[:default][:excel] : options[:force][:excel]
@excel = if excel_option == :new
excel_class.new(:reuse => false)
elsif excel_option.nil? || excel_option == :current
excel_class.new(:reuse => true)
else
self.class.excel_of(excel_option)
end
raise ExcelREOError, "excel is not alive" unless @excel && @excel.alive?
end
# @private
def ensure_workbook(filename, options)
return if (@ole_workbook && alive? && (options[:read_only].nil? || @ole_workbook.ReadOnly == options[:read_only]))
filename = @stored_filename ? @stored_filename : filename
manage_nonexisting_file(filename,options)
excel_option = options[:force][:excel].nil? ? options[:default][:excel] : options[:force][:excel]
ensure_excel(options)
workbooks = @excel.Workbooks
@ole_workbook = workbooks.Item(File.basename(filename)) rescue nil if @ole_workbook.nil?
if @ole_workbook
@was_open = true if @was_open.nil? # necessary?
manage_blocking_or_unsaved_workbook(filename,options)
open_or_create_workbook(filename,options) if @ole_workbook.ReadOnly != options[:read_only]
else
if excel_option.nil? || excel_option == :current &&
(!::JRUBY_BUG_CONNECT || filename[0] != '/')
workbooks_number_before_connect = @excel.Workbooks.Count
connect(filename,options)
@was_open = @excel.Workbooks.Count == workbooks_number_before_connect
else
open_or_create_workbook(filename,options)
end
end
end
# @private
def set_options(filename, options)
# changing read-only mode
if (!options[:read_only].nil?) && options[:read_only] != @ole_workbook.ReadOnly
ensure_workbook(filename, options)
end
retain_saved do
self.visible = options[:force][:visible].nil? ?
(@excel.Visible && @ole_workbook.Windows(@ole_workbook.Name).Visible) : options[:force][:visible]
@excel.calculation = options[:calculation] unless options[:calculation].nil?
@ole_workbook.CheckCompatibility = options[:check_compatibility] unless options[:check_compatibility].nil?
end
end
private
# @private
# connects to an unknown workbook
def connect(filename,options)
excels_number = excel_class.excels_number
workbooks_number = if excels_number>0
excel_class.current.Workbooks.Count
else 0
end
abs_filename = General.absolute_path(filename)
@ole_workbook = begin
WIN32OLE.connect(abs_filename)
rescue
if $!.message =~ /moniker/
raise WorkbookConnectingBlockingError
else
raise WorkbookConnectingUnknownError
end
end
ole_excel = begin
@ole_workbook.Application
rescue
if $!.message =~ /dispid/
raise WorkbookConnectingUnsavedError
else
raise WorkbookConnectingUnknownError
end
end
@excel = excel_class.new(ole_excel)
end
# @private
def manage_nonexisting_file(filename,options)
return if File.exist?(filename)
abs_filename = General.absolute_path(filename)
if options[:if_absent] == :create
ensure_excel(options) unless @excel && @excel.alive?
@excel.Workbooks.Add
empty_ole_workbook = excel.Workbooks.Item(excel.Workbooks.Count)
begin
empty_ole_workbook.SaveAs(abs_filename)
rescue WIN32OLERuntimeError, Java::OrgRacobCom::ComFailException => msg
raise FileNotFound, "could not save workbook with filename #{filename.inspect}"
end
else
raise FileNotFound, "file #{abs_filename.inspect} not found" +
"\nHint: If you want to create a new file, use option :if_absent => :create or Workbook::create"
end
end
# @private
def manage_blocking_or_unsaved_workbook(filename,options)
obstructed_by_other_book = if (File.basename(filename) == File.basename(@ole_workbook.Fullname))
General.absolute_path(filename) != @ole_workbook.Fullname
end
if obstructed_by_other_book
# workbook is being obstructed by a workbook with same name and different path
manage_blocking_workbook(filename,options)
else
unless @ole_workbook.Saved
# workbook open and writable, not obstructed by another workbook, but not saved
manage_unsaved_workbook(filename,options)
end
end
end
# @private
def manage_blocking_workbook(filename,options)
case options[:if_obstructed]
when :raise
raise WorkbookBlocked, "can't open workbook #{filename},
because it is being blocked by #{@ole_workbook.Fullname.tr('\\','/')} with the same name in a different path." +
"\nHint: Use the option :if_blocked with values :forget or :save,
to allow automatic closing of the old workbook (without or with saving before, respectively),
before the new workbook is being opened."
when :forget
manage_forgetting_workbook(filename, options)
when :save
manage_saving_workbook(filename, options)
when :close_if_saved
if !@ole_workbook.Saved
raise WorkbookBlocked, "workbook with the same name in a different path is unsaved: #{@ole_workbook.Fullname.tr('\\','/')}"
else
manage_forgetting_workbook(filename, options)
end
when :new_excel
manage_new_excel(filename, options)
else
raise OptionInvalid, ":if_blocked: invalid option: #{options[:if_obstructed].inspect}" +
"\nHint: Valid values are :raise, :forget, :save, :close_if_saved, :new_excel"
end
end
# @private
def manage_unsaved_workbook(filename,options)
case options[:if_unsaved]
when :raise
raise WorkbookNotSaved, "workbook is already open but not saved: #{File.basename(filename).inspect}" +
"\nHint: Save the workbook or open the workbook using option :if_unsaved with values :forget and :accept to
close the unsaved workbook and reopen it, or to let the unsaved workbook open, respectively"
when :forget
manage_forgetting_workbook(filename,options)
when :accept
# do nothing
when :save
manage_saving_workbook(filename, options)
when :alert, :excel
@excel.with_displayalerts(true) { open_or_create_workbook(filename,options) }
when :new_excel
manage_new_excel(filename, options)
else
raise OptionInvalid, ":if_unsaved: invalid option: #{options[:if_unsaved].inspect}" +
"\nHint: Valid values are :raise, :forget, :save, :accept, :alert, :excel, :new_excel"
end
end
# @private
def manage_forgetting_workbook(filename, options)
@excel.with_displayalerts(false) { @ole_workbook.Close }
@ole_workbook = nil
open_or_create_workbook(filename, options)
end
# @private
def manage_saving_workbook(filename, options)
save unless @ole_workbook.Saved
manage_forgetting_workbook(filename, options)
end
# @private
def manage_new_excel(filename, options)
@excel = excel_class.new(:reuse => false)
@ole_workbook = nil
open_or_create_workbook(filename, options)
end
# @private
def open_or_create_workbook(filename, options)
return if @ole_workbook && options[:if_unsaved] != :alert && options[:if_unsaved] != :excel &&
(options[:read_only].nil? || options[:read_only]==@ole_workbook.ReadOnly )
begin
abs_filename = General.absolute_path(filename)
begin
@was_open = false if @was_open.nil?
workbooks = @excel.Workbooks
rescue WIN32OLERuntimeError, Java::OrgRacobCom::ComFailException => msg
raise UnexpectedREOError, "cannot access workbooks: #{msg.message} #{msg.backtrace}"
end
begin
with_workaround_linked_workbooks_excel2007(options) do
# temporary workaround until jruby-win32ole implements named parameters (Java::JavaLang::RuntimeException (createVariant() not implemented for class org.jruby.RubyHash)
workbooks.Open(abs_filename,
updatelinks_vba(options[:update_links]),
options[:read_only] )
end
rescue WIN32OLERuntimeError => msg
# for Excel2007: for option :if_unsaved => :alert and user cancels: this error appears?
# if yes: distinguish these events
raise UnexpectedREOError, "cannot open workbook: #{msg.message} #{msg.backtrace}"
end
begin
# workaround for bug in Excel 2010: workbook.Open does not always return the workbook when given file name
begin
@ole_workbook = workbooks.Item(File.basename(filename))
rescue WIN32OLERuntimeError => msg
raise UnexpectedREOError, "WIN32OLERuntimeError: #{msg.message}"
end
rescue WIN32OLERuntimeError => msg
raise UnexpectedREOError, "WIN32OLERuntimeError: #{msg.message} #{msg.backtrace}"
end
end
end
# @private
# translating the option UpdateLinks from REO to VBA
# setting UpdateLinks works only if calculation mode is automatic,
# parameter 'UpdateLinks' has no effect
def updatelinks_vba(updatelinks_reo)
case updatelinks_reo
when :alert then RobustExcelOle::XlUpdateLinksUserSetting
when :never then RobustExcelOle::XlUpdateLinksNever
when :always then RobustExcelOle::XlUpdateLinksAlways
else RobustExcelOle::XlUpdateLinksNever
end
end
# @private
# workaround for linked workbooks for Excel 2007:
# opening and closing a dummy workbook if Excel has no workbooks.
# delay: with visible: 0.2 sec, without visible almost none
def with_workaround_linked_workbooks_excel2007(options)
old_visible_value = @excel.Visible
workbooks = @excel.Workbooks
workaround_condition = @excel.Version.split('.').first.to_i == 12 && workbooks.Count == 0
if workaround_condition
workbooks.Add
@excel.calculation = options[:calculation].nil? ? @excel.calculation : options[:calculation]
end
begin
# @excel.with_displayalerts(update_links_opt == :alert ? true : @excel.displayalerts) do
yield self
ensure
@excel.with_displayalerts(false) { workbooks.Item(1).Close } if workaround_condition
@excel.visible = old_visible_value
end
end
public
# creates, i.e., opens a new, empty workbook, and saves it under a given filename
# @param [String] filename the filename under which the new workbook should be saved
# @param [Hash] opts the options as in Workbook::open
def self.create(filename, opts = { })
open(filename, :if_absent => :create)
end
# closes the workbook, if it is alive
# @param [Hash] opts the options
# @option opts [Symbol] :if_unsaved :raise (default), :save, :forget, :keep_open, or :alert
# options:
# :if_unsaved if the workbook is unsaved
# :raise -> raises an exception
# :save -> saves the workbook before it is closed
# :forget -> closes the workbook
# :keep_open -> keep the workbook open
# :alert or :excel -> gives control to excel
# @raise WorkbookNotSaved if the option :if_unsaved is :raise and the workbook is unsaved
# @raise OptionInvalid if the options is invalid
def close(opts = {:if_unsaved => :raise})
if alive? && !@ole_workbook.Saved && writable
case opts[:if_unsaved]
when :raise
raise WorkbookNotSaved, "workbook is unsaved: #{File.basename(self.stored_filename).inspect}" +
"\nHint: Use option :save or :forget to close the workbook with or without saving"
when :save
save
close_workbook
when :forget
@excel.with_displayalerts(false) { close_workbook }
when :keep_open
# nothing
when :alert, :excel
@excel.with_displayalerts(true) { close_workbook }
else
raise OptionInvalid, ":if_unsaved: invalid option: #{opts[:if_unsaved].inspect}" +
"\nHint: Valid values are :raise, :save, :keep_open, :alert, :excel"
end
else
close_workbook
end
# trace "close: canceled by user" if alive? &&
# (opts[:if_unsaved] == :alert || opts[:if_unsaved] == :excel) && (not @ole_workbook.Saved)
end
private
# @private
def close_workbook
@ole_workbook.Close if alive?
@ole_workbook = nil unless alive?
end
public
# keeps the saved-status unchanged
def retain_saved
saved = self.Saved
begin
yield self
ensure
self.Saved = saved
end
end
def for_reading(*args, &block)
args = args.dup
opts = args.last.is_a?(Hash) ? args.pop : {}
opts = {:writable => false}.merge(opts)
args.push opts
unobtrusively(*args, &block)
end
def for_modifying(*args, &block)
args = args.dup
opts = args.last.is_a?(Hash) ? args.pop : {}
opts = {:writable => true}.merge(opts)
args.push opts
unobtrusively(*args, &block)
end
def self.for_reading(*args, &block)
args = args.dup
opts = args.last.is_a?(Hash) ? args.pop : {}
opts = {:writable => false}.merge(opts)
args.push opts
unobtrusively(*args, &block)
end
def self.for_modifying(*args, &block)
args = args.dup
opts = args.last.is_a?(Hash) ? args.pop : {}
opts = {:writable => true}.merge(opts)
args.push opts
unobtrusively(*args, &block)
end
# allows to read or modify a workbook such that its state remains unchanged
# the state comprises, whether the workbok was open, saved, writable, visible,
# includes calculation mode, and check compatibility
# @param [String] file_or_workbook a file name or WIN32OLE workbook
# @param [Hash] opts the options
# @option opts [Variant] :if_closed Excel where to open the workbook, if the workbook was closed
# :current (default), :new or an Excel instance (this option is for known workbooks only)
# @option opts [Boolean] :read_only true/false (default), open the workbook in read-only/read-write modus (save changes)
# @option opts [Boolean] :writable true (default)/false changes of the workbook shall be saved/not saved
# @option opts [Boolean] :keep_open whether the workbook shall be kept open after unobtrusively opening (default: false)
# @return [Workbook] a workbook
=begin
def self.unobtrusively(file_or_workbook, opts = { })
file = (file_or_workbook.is_a? WIN32OLE) ? file_or_workbook.Fullname.tr('\\','/') : file_or_workbook
opts = process_options(opts)
raise OptionInvalid, 'contradicting options' if opts[:writable] && opts[:read_only]
opts = {:if_closed => :current, :keep_open => false}.merge(opts)
prefer_writable = ((!(opts[:read_only]) || opts[:writable] == true) &&
!(opts[:read_only].nil? && opts[:writable] == false))
book = bookstore.fetch(file, :prefer_writable => prefer_writable)
excel_opts = (book.nil? || (book && !book.alive?)) ? {:force => {:excel => opts[:if_closed]}} :
{:force => {:excel => opts[:force][:excel]}, :default => {:excel => opts[:default][:excel]}}
open_opts = excel_opts.merge({:if_unsaved => :accept})
begin
book = open(file, open_opts)
was_visible = book.visible
was_writable = book.writable
was_saved = book.saved
was_check_compatibility = book.check_compatibility
was_calculation = book.excel.calculation
book.set_options(file,opts)
yield book
ensure
if book && book.alive?
do_not_write = opts[:read_only] || opts[:writable]==false
book.save unless book.saved || do_not_write || book.ReadOnly
if (opts[:read_only] && was_writable) || (!opts[:read_only] && !was_writable)
book.set_options(file, opts.merge({:read_only => !was_writable,
:if_unsaved => (opts[:writable]==false ? :forget : :save)}))
end
if book.was_open
book.visible = was_visible
book.CheckCompatibility = was_check_compatibility
book.excel.calculation = was_calculation
end
book.Saved = (was_saved || !book.was_open)
book.close unless book.was_open || opts[:keep_open]
end
end
end
=end
# allows to read or modify a workbook such that its state remains unchanged
# state comprises: open, saved, writable, visible, calculation mode, check compatibility
# @param [String] file_or_workbook a file name or WIN32OLE workbook
# @param [Hash] opts the options
# @option opts [Variant] :if_closed :current (default), :new or an Excel instance
# @option opts [Boolean] :read_only true/false (default), open the workbook in read-only/read-write modus (save changes)
# @option opts [Boolean] :writable true (default)/false changes of the workbook shall be saved/not saved
# @option opts [Boolean] :keep_open whether the workbook shall be kept open after unobtrusively opening (default: false)
# @return [Workbook] a workbook
def self.unobtrusively(file_or_workbook, opts = { }, &block)
file = (file_or_workbook.is_a? WIN32OLE) ? file_or_workbook.Fullname.tr('\\','/') : file_or_workbook
opts = process_options(opts)
raise OptionInvalid, 'contradicting options' if opts[:writable] && opts[:read_only]
opts = {:if_closed => :current, :keep_open => false}.merge(opts)
prefer_writable = ((!(opts[:read_only]) || opts[:writable] == true) &&
!(opts[:read_only].nil? && opts[:writable] == false))
book = bookstore.fetch(file, :prefer_writable => prefer_writable)
excel_opts = (book.nil? || (book && !book.alive?)) ? {:force => {:excel => opts[:if_closed]}} :
{:force => {:excel => opts[:force][:excel]}, :default => {:excel => opts[:default][:excel]}}
open_opts = excel_opts.merge({:if_unsaved => :accept})
begin
book = open(file, open_opts)
book.unobtrusively(opts, &block)
end
end
def unobtrusively(opts = { })
file = stored_filename
opts = self.class.process_options(opts)
raise OptionInvalid, 'contradicting options' if opts[:writable] && opts[:read_only]
opts = {:keep_open => false}.merge(opts)
begin
was_open = alive?
was_visible = visible
was_writable = writable
was_saved = saved
was_check_compatibility = check_compatibility
was_calculation = calculation
set_options(file,opts)
yield self
ensure
if was_open
do_not_write = opts[:read_only] || opts[:writable]==false
save unless saved || do_not_write || !writable
if (opts[:read_only] && was_writable) || (!opts[:read_only] && !was_writable)
set_options(file, opts.merge({:read_only => !was_writable,
:if_unsaved => (opts[:writable]==false ? :forget : :save)}))
end
if was_open
visible = was_visible
@ole_workbook.CheckCompatibility = was_check_compatibility
@excel.calculation = was_calculation
end
@ole_workbook.Saved = (was_saved || !was_open)
close unless was_open || opts[:keep_open]
end
end
end
# reopens a closed workbook
# @options options
def reopen(options = { })
book = self.class.open(@stored_filename, options)
raise WorkbookREOError('cannot reopen book') unless book && book.alive?
book
end
# simple save of a workbook.
# @return [Boolean] true, if successfully saved, nil otherwise
def save(opts = { }) # option opts is deprecated #
raise ObjectNotAlive, 'workbook is not alive' unless alive?
raise WorkbookReadOnly, 'Not opened for writing (opened with :read_only option)' if @ole_workbook.ReadOnly
# if you have open the workbook with :read_only => true,
# then you could close the workbook and open it again with option :read_only => false
# otherwise the workbook may already be open writable in an another Excel instance
# then you could use this workbook or close the workbook there
begin
@ole_workbook.Save
rescue WIN32OLERuntimeError, Java::OrgRacobCom::ComFailException => msg
if msg.message =~ /SaveAs/ && msg.message =~ /Workbook/
raise WorkbookNotSaved, 'workbook not saved'
else
raise UnexpectedREOError, "unknown WIN32OLERuntimeError:\n#{msg.message}"
end
end
true
end
# saves a workbook with a given file name.
# @param [String] file file name
# @param [Hash] opts the options
# @option opts [Symbol] :if_exists :raise (default), :overwrite, or :alert, :excel
# @option opts [Symbol] :if_obstructed :raise (default), :forget, :save, or :close_if_saved
# options:
# :if_exists if a file with the same name exists, then
# :raise -> raises an exception, dont't write the file (default)
# :overwrite -> writes the file, delete the old file
# :alert or :excel -> gives control to Excel
# :if_obstructed if a workbook with the same name and different path is already open and blocks the saving, then
# or :raise -> raises an exception
# :if_blocked :forget -> closes the blocking workbook
# :save -> saves the blocking workbook and closes it
# :close_if_saved -> closes the blocking workbook, if it is saved,
# otherwise raises an exception
# @return [Workbook], the book itself, if successfully saved, raises an exception otherwise
def save_as(file, opts = { })
raise FileNameNotGiven, 'filename is nil' if file.nil?
raise ObjectNotAlive, 'workbook is not alive' unless alive?
raise WorkbookReadOnly, 'Not opened for writing (opened with :read_only option)' if @ole_workbook.ReadOnly
raise(FileNotFound, "file #{General.absolute_path(file).inspect} is a directory") if File.directory?(file)
options = self.class.process_options(opts)
if File.exist?(file)
case options[:if_exists]
when :overwrite
if file == self.filename
save
return self
else
begin
File.delete(file)
rescue Errno::EACCES
raise WorkbookBeingUsed, 'workbook is open and being used in an Excel instance'
end
end
when :alert, :excel
@excel.with_displayalerts true do
save_as_workbook(file, options)
end
return self
when :raise
raise FileAlreadyExists, "file already exists: #{File.basename(file).inspect}" +
"\nHint: Use option :if_exists => :overwrite, if you want to overwrite the file"
else
raise OptionInvalid, ":if_exists: invalid option: #{options[:if_exists].inspect}" +
"\nHint: Valid values are :raise, :overwrite, :alert, :excel"
end
end
other_workbook = @excel.Workbooks.Item(File.basename(file)) rescue nil
if other_workbook && self.filename != other_workbook.Fullname.tr('\\','/')
case options[:if_obstructed]
when :raise
raise WorkbookBlocked, "blocked by another workbook: #{other_workbook.Fullname.tr('\\','/')}" +
"\nHint: Use the option :if_blocked with values :forget or :save to
close or save and close the blocking workbook"
when :forget
# nothing
when :save
other_workbook.Save
when :close_if_saved
unless other_workbook.Saved
raise WorkbookBlocked, "blocking workbook is unsaved: #{File.basename(file).inspect}" +
"\nHint: Use option :if_blocked => :save to save the blocking workbooks"
end
else
raise OptionInvalid, ":if_blocked: invalid option: #{options[:if_obstructed].inspect}" +
"\nHint: Valid values are :raise, :forget, :save, :close_if_saved"
end
other_workbook.Close
end
save_as_workbook(file, options)
self
end
private
# @private
def save_as_workbook(file, options)
dirname, basename = File.split(file)
file_format =
case File.extname(basename)
when '.xls' then RobustExcelOle::XlExcel8
when '.xlsx' then RobustExcelOle::XlOpenXMLWorkbook
when '.xlsm' then RobustExcelOle::XlOpenXMLWorkbookMacroEnabled
end
@ole_workbook.SaveAs(General.absolute_path(file), file_format)
bookstore.store(self)
rescue WIN32OLERuntimeError, Java::OrgRacobCom::ComFailException => msg
if msg.message =~ /SaveAs/ && msg.message =~ /Workbook/
# trace "save: canceled by user" if options[:if_exists] == :alert || options[:if_exists] == :excel
# another possible semantics. raise WorkbookREOError, "could not save Workbook"
else
raise UnexpectedREOError, "unknown WIN32OELERuntimeError:\n#{msg.message}"
end
end
public
# closes a given file if it is open
# @options opts [Symbol] :if_unsaved
def self.close(file, opts = {:if_unsaved => :raise})
book = begin
bookstore.fetch(file)
rescue
nil
end
book.close(opts) if book && book.alive?
end
# saves a given file if it is open
def self.save(file)
book = bookstore.fetch(file) rescue nil
book.save if book && book.alive?
end
# saves a given file under a new name if it is open
def self.save_as(file, new_file, opts = { })
book = begin
bookstore.fetch(file)
rescue
nil
end
book.save_as(new_file, opts) if book && book.alive?
end
# returns a sheet, if a sheet name or a number is given
# @param [String] or [Number]
# @returns [Worksheet]
def sheet(name)
worksheet_class.new(@ole_workbook.Worksheets.Item(name))
rescue WIN32OLERuntimeError, Java::OrgRacobCom::ComFailException => msg
raise NameNotFound, "could not return a sheet with name #{name.inspect}"
end
def each
@ole_workbook.Worksheets.each do |sheet|
yield worksheet_class.new(sheet)
end
end
def each_with_index(offset = 0)
i = offset
@ole_workbook.Worksheets.each do |sheet|
yield worksheet_class.new(sheet), i
i += 1
end
end
# copies a sheet to another position if a sheet is given, or adds an empty sheet
# default: copied or empty sheet is appended, i.e. added behind the last sheet
# @param [Worksheet] sheet a sheet that shall be copied (optional)
# @param [Hash] opts the options
# @option opts [Symbol] :as new name of the copied or added sheet
# @option opts [Symbol] :before a sheet before which the sheet shall be inserted
# @option opts [Symbol] :after a sheet after which the sheet shall be inserted
# @return [Worksheet] the copied or added sheet
def add_or_copy_sheet(sheet = nil, opts = { })
if sheet.is_a? Hash
opts = sheet
sheet = nil
end
new_sheet_name = opts.delete(:as)
last_sheet_local = last_sheet
after_or_before, base_sheet = opts.to_a.first || [:after, last_sheet_local]
begin
if !::JRUBY_BUG_COPYSHEETS
if sheet
sheet.Copy({ after_or_before.to_s => base_sheet.ole_worksheet })
else
@ole_workbook.Worksheets.Add({ after_or_before.to_s => base_sheet.ole_worksheet })
#@ole_workbook.Worksheets.Item(ole_workbook.Worksheets.Count).Activate
end
else
if after_or_before == :before
if sheet
sheet.Copy(base_sheet.ole_worksheet)
else
ole_workbook.Worksheets.Add(base_sheet.ole_worksheet)
end
else
#not_given = WIN32OLE_VARIANT.new(nil, WIN32OLE::VARIANT::VT_NULL)
#ole_workbook.Worksheets.Add(not_given,base_sheet.ole_worksheet)
if base_sheet.name != last_sheet_local.name
if sheet
sheet.Copy(base_sheet.Next)
else
ole_workbook.Worksheets.Add(base_sheet.Next)
end
else
if sheet
sheet.Copy(base_sheet.ole_worksheet)
else
ole_workbook.Worksheets.Add(base_sheet.ole_worksheet)
end
base_sheet.Move(ole_workbook.Worksheets.Item(ole_workbook.Worksheets.Count-1))
ole_workbook.Worksheets.Item(ole_workbook.Worksheets.Count).Activate
end
end
end
rescue WIN32OLERuntimeError, NameNotFound, Java::OrgRacobCom::ComFailException
raise WorksheetREOError, "could not add given worksheet #{sheet.inspect}"
end
#ole_sheet = @excel.Activesheet
ole_sheet = ole_workbook.Activesheet
#ole_sheet = ole_sheet.nil? ? ole_workbook.Worksheets.Item(ole_workbook.Worksheets.Count) : ole_sheet
new_sheet = worksheet_class.new(ole_sheet)
new_sheet.name = new_sheet_name if new_sheet_name
new_sheet
end
# for compatibility to older versions
def add_sheet(sheet = nil, opts = { })
add_or_copy_sheet(sheet, opts)
end
# for compatibility to older versions
def copy_sheet(sheet, opts = { })
add_or_copy_sheet(sheet, opts)
end
def last_sheet
worksheet_class.new(@ole_workbook.Worksheets.Item(@ole_workbook.Worksheets.Count))
end
def first_sheet
worksheet_class.new(@ole_workbook.Worksheets.Item(1))
end
# returns the value of a range
# @param [String] name the name of a range
# @returns [Variant] the value of the range
def [] name
namevalue_glob(name)
end
# sets the value of a range
# @param [String] name the name of the range
# @param [Variant] value the contents of the range
def []= (name, value)
old_color_if_modified = @color_if_modified
workbook.color_if_modified = 42 # 42 - aqua-marin, 4-green
set_namevalue_glob(name,value)
workbook.color_if_modified = old_color_if_modified
end
# sets options
# @param [Hash] opts
def for_this_workbook(opts)
return unless alive?
opts = self.class.process_options(opts, :use_defaults => false)
visible_before = visible
check_compatibility_before = check_compatibility
unless opts[:read_only].nil?
# if the ReadOnly status shall be changed, then close and reopen it
if (!writable && !(opts[:read_only])) || (writable && opts[:read_only])
opts[:check_compatibility] = check_compatibility if opts[:check_compatibility].nil?
close(:if_unsaved => true)
open_or_create_workbook(@stored_filename, opts)
end
end
self.visible = opts[:force][:visible].nil? ? visible_before : opts[:force][:visible]
self.CheckCompatibility = opts[:check_compatibility].nil? ? check_compatibility_before : opts[:check_compatibility]
@excel.calculation = opts[:calculation] unless opts[:calculation].nil?
end
# brings workbook to foreground, makes it available for heyboard inputs, makes the Excel instance visible
def focus
self.visible = true
@excel.focus
@ole_workbook.Activate
end
# returns true, if the workbook reacts to methods, false otherwise
def alive?
@ole_workbook.Name
true
rescue
@ole_workbook = nil # dead object won't be alive again
# t $!.message
false
end
# returns the full file name of the workbook
def filename
@ole_workbook.Fullname.tr('\\','/') rescue nil
end
# @private
def writable
!@ole_workbook.ReadOnly if @ole_workbook
end
# @private
def saved
@ole_workbook.Saved if @ole_workbook
end
def calculation
@excel.calculation if @ole_workbook
end
# @private
def check_compatibility
@ole_workbook.CheckCompatibility if @ole_workbook
end
# returns true, if the workbook is visible, false otherwise
def visible
@excel.Visible && @ole_workbook.Windows(@ole_workbook.Name).Visible
end
# makes both the Excel instance and the window of the workbook visible, or the window invisible
# does not do anything if geben visible_value is nil
# @param [Boolean] visible_value determines whether the workbook shall be visible
def visible= visible_value
return if visible_value.nil?
@excel.visible = true if visible_value
self.window_visible = @excel.Visible ? visible_value : true
end
# returns true, if the window of the workbook is set to visible, false otherwise
def window_visible
@ole_workbook.Windows(@ole_workbook.Name).Visible
end
# makes the window of the workbook visible or invisible
# @param [Boolean] visible_value determines whether the window of the workbook shall be visible
def window_visible= visible_value
retain_saved do
@ole_workbook.Windows(@ole_workbook.Name).Visible = visible_value if @ole_workbook.Windows.Count > 0
end
end
# @return [Boolean] true, if the full workbook names and excel Instances are identical, false otherwise
def == other_book
other_book.is_a?(Workbook) &&
@excel == other_book.excel &&
self.filename == other_book.filename
end
def self.books
bookstore.books
end
# @private
def self.bookstore
@@bookstore ||= Bookstore.new
end
# @private
def bookstore
self.class.bookstore
end
# @private
def to_s
self.filename.to_s
end
# @private
def inspect
'#<Workbook: ' + ('not alive ' unless alive?).to_s + (File.basename(self.filename) if alive?).to_s + " #{@ole_workbook} #{@excel}" + '>'
end
# @private
def self.excel_class
@excel_class ||= begin
module_name = self.parent_name
"#{module_name}::Excel".constantize
rescue NameError => e
# trace "excel_class: NameError: #{e}"
Excel
end
end
# @private
def self.worksheet_class
@worksheet_class ||= begin
module_name = self.parent_name
"#{module_name}::Worksheet".constantize
rescue NameError => e
Worksheet
end
end
# @private
def self.address_class
@address_class ||= begin
module_name = self.parent_name
"#{module_name}::Address".constantize
rescue NameError => e
Address
end
end
# @private
def excel_class
self.class.excel_class
end
# @private
def worksheet_class
self.class.worksheet_class
end
# @private
def address_class
self.class.address_class
end
include MethodHelpers
private
def method_missing(name, *args)
if name.to_s[0,1] =~ /[A-Z]/
raise ObjectNotAlive, 'method missing: workbook not alive' unless alive?
if ::JRUBY_BUG_ERRORMESSAGE
begin
@ole_workbook.send(name, *args)
rescue Java::OrgRacobCom::ComFailException
raise VBAMethodMissingError, "unknown VBA property or method #{name.inspect}"
end
else
begin
@ole_workbook.send(name, *args)
rescue NoMethodError
raise VBAMethodMissingError, "unknown VBA property or method #{name.inspect}"
end
end
else
super
end
end
end
public
Book = Workbook
end
|
require 'rack/utils'
require 'rack/cerberus/version'
module Rack
class Cerberus
class NoSessionError < RuntimeError; end
def self.new(*); ::Rack::MethodOverride.new(super); end
def initialize app, options={}, &block
@app = app
defaults = {
company_name: 'Cerberus',
bg_color: '#93a1a1',
fg_color: '#002b36',
text_color: '#fdf6e3',
session_key: 'cerberus_user',
forgot_password_uri: nil
}
@options = defaults.merge(options)
@options[:icon] = @options[:icon_url].nil? ?
'' :
"<img src='#{@options[:icon_url]}' /><br />"
@options[:css] = @options[:css_location].nil? ?
'' :
"<link href='#{@options[:css_location]}' rel='stylesheet' type='text/css'>"
@block = block
end
def call env
dup._call(env)
end
def _call env
ensure_session env
req = Rack::Request.new env
if (logged?(req) and !logging_out?(req)) or authorized?(req)
ensure_logged! req
if logging_out? req
logout_response req
else
@app.call env
end
else
form_response req
end
end
private
def ensure_session env
if env['rack.session'].nil?
raise(NoSessionError, 'Cerberus cannot work without Session')
end
end
def h text
Rack::Utils.escape_html text
end
def login req
req.params['cerberus_login']
end
def pass req
req.params['cerberus_pass']
end
def logged? req
req.env['rack.session'][@options[:session_key]]!=nil
end
def provided_fields? req
login(req) and pass(req)
end
def authorized? req
provided_fields?(req) and
@block.call login(req), pass(req), req
end
def ensure_logged! req
req.env['rack.session'][@options[:session_key]] ||= login(req)
end
def ensure_logged_out! req
req.env['rack.session'].delete @options[:session_key]
end
def logging_out? req
req.path_info=='/logout'
end
def logout_response req
res = Rack::Response.new
res.redirect(req.script_name=='' ? '/' : req.script_name)
res.finish
end
def form_response req
if provided_fields? req
error = "<p class='err'>Wrong login or password</p>"
unless @options[:forgot_password_uri].nil?
forgot_password = FORGOT_PASSWORD % {
action: @options[:forgot_password_uri],
login: h(login(req))
}
end
end
ensure_logged_out! req
[
401, {'Content-Type' => 'text/html'},
[AUTH_PAGE % @options.merge({
error: error, submit_path: h(req.env['REQUEST_URI']),
forgot_password: forgot_password,
request_method: req.request_method,
login: h(login(req)),
pass: h(pass(req))
})]
]
end
AUTH_PAGE = <<-PAGE
<!DOCTYPE html>
<html><head>
<title>%{company_name} Authentication</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style type='text/css'>
* {
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
}
body { background-color: %{bg_color}; font-family: sans-serif; text-align: center; margin: 0px; }
h1, p { color: %{text_color}; }
.err {
padding: 1em;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
color: white;
background-color: #dc322f;
}
div {
text-align: left;
width: 500px;
margin: 0px auto;
padding: 2em;
-webkit-border-bottom-left-radius: 3px;
-moz-border-radius-bottomleft: 3px;
border-bottom-left-radius: 3px;
-webkit-border-bottom-right-radius: 3px;
-moz-border-radius-bottomright: 3px;
border-bottom-right-radius: 3px;
-moz-box-shadow: 0px 0px 5px #333;
-webkit-box-shadow: 0px 0px 5px #555;
box-shadow: 0px 0px 5px #555;
background-color: %{fg_color}; }
input[type=text], input[type=password] {
display: block; width: 100%%; padding: 0.5em;
border: 0px; font-size: 1.25em;
background-color: %{text_color};
}
input[type=submit] {
background-color: %{bg_color};
color: %{fg_color};
padding: 0.5em;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
border: 0;
cursor: pointer;
}
input[type=submit]:hover { background-color: %{text_color}; }
::-webkit-input-placeholder { color: %{bg_color}; }
:-moz-placeholder { color: %{bg_color}; }
::-moz-placeholder { color: %{bg_color}; }
:-ms-input-placeholder { color: %{bg_color}; }
</style>
%{css}
</head><body>
<div>
<h1>%{company_name}</h1>
%{icon}
%{error}
<p>Please Sign In</p>
<form action="%{submit_path}" method="post" accept-charset="utf-8">
<input type="text" name="cerberus_login" value="%{login}" id='login' title='Login' placeholder='Login'><br />
<input type="password" name="cerberus_pass" value="%{pass}" id='pass' title='Password' placeholder='Password'>
<input type="hidden" name="_method" value="%{request_method}">
<p><input type="submit" value="SIGN IN →"></p>
</form>
%{forgot_password}
</div>
</body></html>
PAGE
FORGOT_PASSWORD = <<-FORM
<form action="%{action}" method="post" accept-charset="utf-8">
<input type="hidden" name="cerberus_login" value="%{login}" />
<p><input type="submit" value="Forgot your password? →"></p>
</form>
FORM
end
end
Tidy up indentation of html part
require 'rack/utils'
require 'rack/cerberus/version'
module Rack
class Cerberus
class NoSessionError < RuntimeError; end
def self.new(*); ::Rack::MethodOverride.new(super); end
def initialize app, options={}, &block
@app = app
defaults = {
company_name: 'Cerberus',
bg_color: '#93a1a1',
fg_color: '#002b36',
text_color: '#fdf6e3',
session_key: 'cerberus_user',
forgot_password_uri: nil
}
@options = defaults.merge(options)
@options[:icon] = @options[:icon_url].nil? ?
'' :
"<img src='#{@options[:icon_url]}' /><br />"
@options[:css] = @options[:css_location].nil? ?
'' :
"<link href='#{@options[:css_location]}' rel='stylesheet' type='text/css'>"
@block = block
end
def call env
dup._call(env)
end
def _call env
ensure_session env
req = Rack::Request.new env
if (logged?(req) and !logging_out?(req)) or authorized?(req)
ensure_logged! req
if logging_out? req
logout_response req
else
@app.call env
end
else
form_response req
end
end
private
def ensure_session env
if env['rack.session'].nil?
raise(NoSessionError, 'Cerberus cannot work without Session')
end
end
def h text
Rack::Utils.escape_html text
end
def login req
req.params['cerberus_login']
end
def pass req
req.params['cerberus_pass']
end
def logged? req
req.env['rack.session'][@options[:session_key]]!=nil
end
def provided_fields? req
login(req) and pass(req)
end
def authorized? req
provided_fields?(req) and
@block.call login(req), pass(req), req
end
def ensure_logged! req
req.env['rack.session'][@options[:session_key]] ||= login(req)
end
def ensure_logged_out! req
req.env['rack.session'].delete @options[:session_key]
end
def logging_out? req
req.path_info=='/logout'
end
def logout_response req
res = Rack::Response.new
res.redirect(req.script_name=='' ? '/' : req.script_name)
res.finish
end
def form_response req
if provided_fields? req
error = "<p class='err'>Wrong login or password</p>"
unless @options[:forgot_password_uri].nil?
forgot_password = FORGOT_PASSWORD % {
action: @options[:forgot_password_uri],
login: h(login(req))
}
end
end
ensure_logged_out! req
[
401, {'Content-Type' => 'text/html'},
[AUTH_PAGE % @options.merge({
error: error, submit_path: h(req.env['REQUEST_URI']),
forgot_password: forgot_password,
request_method: req.request_method,
login: h(login(req)),
pass: h(pass(req))
})]
]
end
AUTH_PAGE = <<-PAGE
<!DOCTYPE html>
<html>
<head>
<title>%{company_name} Authentication</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style type='text/css'>
* {
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
}
body {
background-color: %{bg_color};
font-family: sans-serif;
text-align: center;
margin: 0px;
}
h1, p { color: %{text_color}; }
.err {
padding: 1em;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
border-radius: 3px;
background-color: #dc322f; color: white;
}
div {
text-align: left;
width: 500px;
margin: 0px auto; padding: 2em;
-webkit-border-bottom-left-radius: 3px;
-moz-border-radius-bottomleft: 3px;
border-bottom-left-radius: 3px;
-webkit-border-bottom-right-radius: 3px;
-moz-border-radius-bottomright: 3px;
border-bottom-right-radius: 3px;
-moz-box-shadow: 0px 0px 5px #333;
-webkit-box-shadow: 0px 0px 5px #555;
box-shadow: 0px 0px 5px #555;
background-color: %{fg_color};
}
input[type=text], input[type=password] {
display: block;
width: 100%%;
padding: 0.5em;
border: 0px;
font-size: 1.25em;
background-color: %{text_color};
}
input[type=submit] {
background-color: %{bg_color}; color: %{fg_color};
padding: 0.5em; border: 0;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
cursor: pointer;
}
input[type=submit]:hover { background-color: %{text_color}; }
::-webkit-input-placeholder { color: %{bg_color}; }
:-moz-placeholder { color: %{bg_color}; }
::-moz-placeholder { color: %{bg_color}; }
:-ms-input-placeholder { color: %{bg_color}; }
</style>
%{css}
</head>
<body>
<div>
<h1>%{company_name}</h1>
%{icon}
%{error}
<p>Please Sign In</p>
<form action="%{submit_path}" method="post" accept-charset="utf-8">
<input type="text" name="cerberus_login" value="%{login}" id='login' title='Login' placeholder='Login'><br />
<input type="password" name="cerberus_pass" value="%{pass}" id='pass' title='Password' placeholder='Password'>
<input type="hidden" name="_method" value="%{request_method}">
<p><input type="submit" value="SIGN IN →"></p>
</form>
%{forgot_password}
</div>
</body>
</html>
PAGE
FORGOT_PASSWORD = <<-FORM
<form action="%{action}" method="post" accept-charset="utf-8">
<input type="hidden" name="cerberus_login" value="%{login}" />
<p><input type="submit" value="Forgot your password? →"></p>
</form>
FORM
end
end
|
$LOAD_PATH.unshift File.expand_path('../lib', __FILE__)
require 'has_phone_numbers/version'
Gem::Specification.new do |s|
s.name = "has_phone_numbers"
s.version = HasPhoneNumbers::VERSION
s.authors = ["Aaron Pfeifer"]
s.email = "aaron@pluginaweek.org"
s.homepage = "http://www.pluginaweek.org"
s.description = "Demonstrates a reference implementation for handling phone numbers in ActiveRecord"
s.summary = "Phone numbers in ActiveRecord"
s.require_paths = ["lib"]
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- test/*`.split("\n")
s.rdoc_options = %w(--line-numbers --inline-source --title has_phone_numbers --main README.rdoc)
s.extra_rdoc_files = %w(README.rdoc CHANGELOG.rdoc LICENSE)
end
Add missing dependencies to gemspec
$LOAD_PATH.unshift File.expand_path('../lib', __FILE__)
require 'has_phone_numbers/version'
Gem::Specification.new do |s|
s.name = "has_phone_numbers"
s.version = HasPhoneNumbers::VERSION
s.authors = ["Aaron Pfeifer"]
s.email = "aaron@pluginaweek.org"
s.homepage = "http://www.pluginaweek.org"
s.description = "Demonstrates a reference implementation for handling phone numbers in ActiveRecord"
s.summary = "Phone numbers in ActiveRecord"
s.require_paths = ["lib"]
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- test/*`.split("\n")
s.rdoc_options = %w(--line-numbers --inline-source --title has_phone_numbers --main README.rdoc)
s.extra_rdoc_files = %w(README.rdoc CHANGELOG.rdoc LICENSE)
s.add_development_dependency("rake")
s.add_development_dependency("plugin_test_helper", ">= 0.3.2")
end
|
module Rodzilla
module Resource
# Bugzilla::Webservice::Product - The Product API
# This part of the Bugzilla API allows you to list the available Products and get information about them.
class Product < Base
# Returns a list of the ids of the products the user can search on.
def get_selectable_products
rpc_call( rpc_method: "get_selectable_products" )
end
def get_enterable_products
rpc_call( rpc_method: "get_enterable_products" )
end
def get_accessible_products
rpc_call( rpc_method: "get_accessible_products" )
end
def get_products(ids)
rpc_call( rpc_method: "get", ids: ids )
end
end
end
end
Add options for get_products
module Rodzilla
module Resource
# Bugzilla::Webservice::Product - The Product API
# This part of the Bugzilla API allows you to list the available Products and get information about them.
class Product < Base
# Returns a list of the ids of the products the user can search on.
def get_selectable_products
rpc_call( rpc_method: "get_selectable_products" )
end
def get_enterable_products
rpc_call( rpc_method: "get_enterable_products" )
end
def get_accessible_products
rpc_call( rpc_method: "get_accessible_products" )
end
def get_products(options={})
rpc_call( options.merge( rpc_method: 'get' ) )
end
end
end
end |
require 'rack'
require 'rack/contrib'
require 'sinatra/base'
require 'sinatra/param'
require 'rack'
require 'sequel'
module Rack
class Passbook < Sinatra::Base
VERSION = '0.1.0'
use Rack::PostBodyContentTypeParser
helpers Sinatra::Param
Sequel.extension :core_extensions, :migration, :pg_hstore, :pg_hstore_ops
autoload :Pass, ::File.join(::File.dirname(__FILE__), 'passbook/models/pass')
autoload :Registration, ::File.join(::File.dirname(__FILE__), 'passbook/models/registration')
disable :raise_errors, :show_exceptions
configure do
if ENV['DATABASE_URL']
DB = Sequel.connect(ENV['DATABASE_URL'])
Sequel::Migrator.run(DB, ::File.join(::File.dirname(__FILE__), "passbook/migrations"), table: 'passbook_schema_info')
end
end
before do
content_type :json
end
# Get the latest version of a pass.
get '/passes/:pass_type_identifier/:serial_number/?' do
@pass = Pass.filter(pass_type_identifier: params[:pass_type_identifier], serial_number: params[:serial_number]).first
halt 404 if @pass.nil?
filter_authorization_for_pass!(@pass)
last_modified @pass.updated_at.utc
@pass.to_json
end
# Get the serial numbers for passes associated with a device.
# This happens the first time a device communicates with our web service.
# Additionally, when a device gets a push notification, it asks our
# web service for the serial numbers of passes that have changed since
# a given update tag (timestamp).
get '/devices/:device_library_identifier/registrations/:pass_type_identifier/?' do
@passes = Pass.filter(pass_type_identifier: params[:pass_type_identifier]).join(Registration.dataset, device_library_identifier: params[:device_library_identifier])
halt 404 if @passes.empty?
@passes = @passes.filter('passes.updated_at > ?', params[:passesUpdatedSince]) if params[:passesUpdatedSince]
if @passes.any?
{
lastUpdated: @passes.collect(&:updated_at).max,
serialNumbers: @passes.collect(&:serial_number).collect(&:to_s)
}.to_json
else
halt 204
end
end
# Register a device to receive push notifications for a pass.
post '/devices/:device_library_identifier/registrations/:pass_type_identifier/:serial_number/?' do
@pass = Pass.where(pass_type_identifier: params[:pass_type_identifier], serial_number: params[:serial_number]).first
halt 404 if @pass.nil?
filter_authorization_for_pass!(@pass)
param :pushToken, String, required: true
@registration = @pass.registrations.detect{|registration| registration.device_library_identifier == params[:device_library_identifier]}
@registration ||= Registration.new(pass_id: @pass.id, device_library_identifier: params[:device_library_identifier])
@registration.push_token = params[:pushToken]
status = @registration.new? ? 201 : 200
@registration.save
halt 406 unless @registration.valid?
halt status
end
# Unregister a device so it no longer receives push notifications for a pass.
delete '/devices/:device_library_identifier/registrations/:pass_type_identifier/:serial_number/?' do
@pass = Pass.filter(pass_type_identifier: params[:pass_type_identifier], serial_number: params[:serial_number]).first
halt 404 if @pass.nil?
filter_authorization_for_pass!(@pass)
@registration = @pass.registrations.detect{|registration| registration.device_library_identifier == params[:device_library_identifier]}
halt 404 if @registration.nil?
@registration.destroy
halt 200
end
private
def filter_authorization_for_pass!(pass)
halt 401 if request.env['HTTP_AUTHORIZATION'] != "ApplePass #{pass.authentication_token}"
end
end
end
Bumping version to 0.1.1
require 'rack'
require 'rack/contrib'
require 'sinatra/base'
require 'sinatra/param'
require 'rack'
require 'sequel'
module Rack
class Passbook < Sinatra::Base
VERSION = '0.1.1'
use Rack::PostBodyContentTypeParser
helpers Sinatra::Param
Sequel.extension :core_extensions, :migration, :pg_hstore, :pg_hstore_ops
autoload :Pass, ::File.join(::File.dirname(__FILE__), 'passbook/models/pass')
autoload :Registration, ::File.join(::File.dirname(__FILE__), 'passbook/models/registration')
disable :raise_errors, :show_exceptions
configure do
if ENV['DATABASE_URL']
DB = Sequel.connect(ENV['DATABASE_URL'])
Sequel::Migrator.run(DB, ::File.join(::File.dirname(__FILE__), "passbook/migrations"), table: 'passbook_schema_info')
end
end
before do
content_type :json
end
# Get the latest version of a pass.
get '/passes/:pass_type_identifier/:serial_number/?' do
@pass = Pass.filter(pass_type_identifier: params[:pass_type_identifier], serial_number: params[:serial_number]).first
halt 404 if @pass.nil?
filter_authorization_for_pass!(@pass)
last_modified @pass.updated_at.utc
@pass.to_json
end
# Get the serial numbers for passes associated with a device.
# This happens the first time a device communicates with our web service.
# Additionally, when a device gets a push notification, it asks our
# web service for the serial numbers of passes that have changed since
# a given update tag (timestamp).
get '/devices/:device_library_identifier/registrations/:pass_type_identifier/?' do
@passes = Pass.filter(pass_type_identifier: params[:pass_type_identifier]).join(Registration.dataset, device_library_identifier: params[:device_library_identifier])
halt 404 if @passes.empty?
@passes = @passes.filter('passes.updated_at > ?', params[:passesUpdatedSince]) if params[:passesUpdatedSince]
if @passes.any?
{
lastUpdated: @passes.collect(&:updated_at).max,
serialNumbers: @passes.collect(&:serial_number).collect(&:to_s)
}.to_json
else
halt 204
end
end
# Register a device to receive push notifications for a pass.
post '/devices/:device_library_identifier/registrations/:pass_type_identifier/:serial_number/?' do
@pass = Pass.where(pass_type_identifier: params[:pass_type_identifier], serial_number: params[:serial_number]).first
halt 404 if @pass.nil?
filter_authorization_for_pass!(@pass)
param :pushToken, String, required: true
@registration = @pass.registrations.detect{|registration| registration.device_library_identifier == params[:device_library_identifier]}
@registration ||= Registration.new(pass_id: @pass.id, device_library_identifier: params[:device_library_identifier])
@registration.push_token = params[:pushToken]
status = @registration.new? ? 201 : 200
@registration.save
halt 406 unless @registration.valid?
halt status
end
# Unregister a device so it no longer receives push notifications for a pass.
delete '/devices/:device_library_identifier/registrations/:pass_type_identifier/:serial_number/?' do
@pass = Pass.filter(pass_type_identifier: params[:pass_type_identifier], serial_number: params[:serial_number]).first
halt 404 if @pass.nil?
filter_authorization_for_pass!(@pass)
@registration = @pass.registrations.detect{|registration| registration.device_library_identifier == params[:device_library_identifier]}
halt 404 if @registration.nil?
@registration.destroy
halt 200
end
private
def filter_authorization_for_pass!(pass)
halt 401 if request.env['HTTP_AUTHORIZATION'] != "ApplePass #{pass.authentication_token}"
end
end
end
|
module RomanConverter
class RuleUtil
attr_reader :roman_array
def initialize(roman_array)
@roman_array = roman_array
end
# Checks whether all the elements have proper roman numerals
# => true / false
def is_invalid_numerals?
(@roman_array & RomanConverter::Rules::Mapper::VALUES.keys) != @roman_array.size
end
# Returns true if there is more than **MAX_SUCCESSIVE** successive elements
# => true/false
def is_repeating_succession?
!generate_occurrence_list.find{|chunk| chunk.last > RomanConverter::Rules::MAX_SUCCESSIVE}.nil?
end
# Returns true if there are never repeatable elements occuring more than once
# => true/false
def invalidate_never_repeatable_elements?
chunk_hash = generate_occurrence_hash
RomanConverter::Rules::Mapper::NEVER_REPEATABLE.each do |roman_literal|
return true if chunk_hash[roman_literal] > 1
end
return false
end
# Returns true if there are repeatable elements occuring more than **MAX_OCCURENCE**
# Also, checks if there occurs repeatable elements occurring **MAX_OCCURENCE** times and respecting the condition
# that it needs to be interleaved.
# => true/false
def invalidate_repeatable_elements?
chunk_hash = generate_occurrence_hash
chunk_list = generate_occurrence_list
RomanConverter::Rules::Mapper::REPEATABLE.each do |roman_literal|
if chunk_hash[roman_literal] > RomanConverter::Rules::MAX_OCCURENCE
return true
elsif chunk_hash[roman_literal] == Rules::MAX_OCCURENCE
chunk_list_index = chunk_list.find_index{|chunk_array| chunk_array.first == roman_literal}
next_index = chunk_list_index + 1
return true if chunk_list[next_index].nil? || compare_mapper_values?(chunk_list[next_index].first, roman_literal)
end
end
return false
end
# invalidates the subtraction rules
# This method assumes that the **NEVER_REPEATABLE** elements occur only once.
# Thus this method must be called after the **invalidate_never_repeatable_elements?**
# => true / false
def invalidate_subtractable_elements?
RomanConverter::Rules::Mapper::NEVER_REPEATABLE.each do |roman_literal|
next_element = get_next_elements(roman_literal).first
return true if !next_element.nil? && compare_mapper_values?(next_element, roman_literal, false)
end
RomanConverter::Rules::Mapper::SUBTRACTABLE_ELEMENTS.each do |roman_literal|
next_elements = get_next_elements(roman_literal)
next_elements.each do |next_element|
return true if !next_element.nil? && !RomanConverter::Rules::Mapper::SUBTRACTABLE_ELIGIBLE[roman_literal].include?(next_element)
end
end
return false
end
private
def compare_mapper_values?(key1, key2, lesser = true)
lesser ? mapper_value_less_than?(key1, key2) : mapper_value_greater_than?(key1, key2)
end
def mapper_value_greater_than?(key1, key2)
RomanConverter::Rules::Mapper::VALUES[key1] > RomanConverter::Rules::Mapper::VALUES[key2]
end
def mapper_value_less_than?(key1, key2)
RomanConverter::Rules::Mapper::VALUES[key1] < RomanConverter::Rules::Mapper::VALUES[key2]
end
# Returns the next elements of the matched elements with **roman_literal** in the array
# => **@roman_array** = [1, 2, 3, 4, 5, 7, 1]
# => get_next_elements(1)
# => [2, nil]
# => get_next_elements(2)
# => [3]
def get_next_elements(roman_literal)
index_map = @roman_array.map.with_index.to_a
selected_array = index_map.select { |index_array| index_array.first == roman_literal }
selected_array.collect{ |index_array| @roman_array[index_array.last + 1]}
end
# => generate_occurrence_hash([1,2,3,4,6,6,6,1,6])
# => {1=>2, 2=>1, 3=>1, 4=>1, 6=>4}
def generate_occurrence_hash
occurrence_hash = {}
generate_chunks do |category, chunk_array|
num = occurrence_hash[category]
occurrence_hash[category] = num.to_i + chunk_array.size
end
occurrence_hash
end
# => generate_occurrence_list([1,2,3,4,6,6,6,1,6])
# => [[1, 1], [2, 1], [3, 1], [4, 1], [6, 3], [1, 1], [6, 1]]
def generate_occurrence_list
generate_chunks do |category, chunk_array|
[category, chunk_array.size]
end
end
# The method below categorises the successive elements and groups and returns based on the block
# => generate_chunks([1,2,3,4,6,6,6]){|a, b| [a, b.size]}
# => [[1, 1], [2, 1], [3, 1], [4, 1], [6, 3]]
def generate_chunks(&block)
@roman_array.chunk{|y| y}.map do |category, chunk_array|
block.call(category, chunk_array)
end
end
end
end
fixing a minor bug
module RomanConverter
class RuleUtil
attr_reader :roman_array
def initialize(roman_array)
@roman_array = roman_array
end
# Checks whether all the elements have proper roman numerals
# => true / false
def is_invalid_numerals?
(@roman_array & RomanConverter::Rules::Mapper::VALUES.keys).size != 0
end
# Returns true if there is more than **MAX_SUCCESSIVE** successive elements
# => true/false
def is_repeating_succession?
!generate_occurrence_list.find{|chunk| chunk.last > RomanConverter::Rules::MAX_SUCCESSIVE}.nil?
end
# Returns true if there are never repeatable elements occuring more than once
# => true/false
def invalidate_never_repeatable_elements?
chunk_hash = generate_occurrence_hash
RomanConverter::Rules::Mapper::NEVER_REPEATABLE.each do |roman_literal|
return true if chunk_hash[roman_literal] > 1
end
return false
end
# Returns true if there are repeatable elements occuring more than **MAX_OCCURENCE**
# Also, checks if there occurs repeatable elements occurring **MAX_OCCURENCE** times and respecting the condition
# that it needs to be interleaved.
# => true/false
def invalidate_repeatable_elements?
chunk_hash = generate_occurrence_hash
chunk_list = generate_occurrence_list
RomanConverter::Rules::Mapper::REPEATABLE.each do |roman_literal|
if chunk_hash[roman_literal] > RomanConverter::Rules::MAX_OCCURENCE
return true
elsif chunk_hash[roman_literal] == Rules::MAX_OCCURENCE
chunk_list_index = chunk_list.find_index{|chunk_array| chunk_array.first == roman_literal}
next_index = chunk_list_index + 1
return true if chunk_list[next_index].nil? || compare_mapper_values?(chunk_list[next_index].first, roman_literal)
end
end
return false
end
# invalidates the subtraction rules
# This method assumes that the **NEVER_REPEATABLE** elements occur only once.
# Thus this method must be called after the **invalidate_never_repeatable_elements?**
# => true / false
def invalidate_subtractable_elements?
RomanConverter::Rules::Mapper::NEVER_REPEATABLE.each do |roman_literal|
next_element = get_next_elements(roman_literal).first
return true if !next_element.nil? && compare_mapper_values?(next_element, roman_literal, false)
end
RomanConverter::Rules::Mapper::SUBTRACTABLE_ELEMENTS.each do |roman_literal|
next_elements = get_next_elements(roman_literal)
next_elements.each do |next_element|
return true if !next_element.nil? && !RomanConverter::Rules::Mapper::SUBTRACTABLE_ELIGIBLE[roman_literal].include?(next_element)
end
end
return false
end
private
def compare_mapper_values?(key1, key2, lesser = true)
lesser ? mapper_value_less_than?(key1, key2) : mapper_value_greater_than?(key1, key2)
end
def mapper_value_greater_than?(key1, key2)
RomanConverter::Rules::Mapper::VALUES[key1] > RomanConverter::Rules::Mapper::VALUES[key2]
end
def mapper_value_less_than?(key1, key2)
RomanConverter::Rules::Mapper::VALUES[key1] < RomanConverter::Rules::Mapper::VALUES[key2]
end
# Returns the next elements of the matched elements with **roman_literal** in the array
# => **@roman_array** = [1, 2, 3, 4, 5, 7, 1]
# => get_next_elements(1)
# => [2, nil]
# => get_next_elements(2)
# => [3]
def get_next_elements(roman_literal)
index_map = @roman_array.map.with_index.to_a
selected_array = index_map.select { |index_array| index_array.first == roman_literal }
selected_array.collect{ |index_array| @roman_array[index_array.last + 1]}
end
# => generate_occurrence_hash([1,2,3,4,6,6,6,1,6])
# => {1=>2, 2=>1, 3=>1, 4=>1, 6=>4}
def generate_occurrence_hash
occurrence_hash = {}
generate_chunks do |category, chunk_array|
num = occurrence_hash[category]
occurrence_hash[category] = num.to_i + chunk_array.size
end
occurrence_hash
end
# => generate_occurrence_list([1,2,3,4,6,6,6,1,6])
# => [[1, 1], [2, 1], [3, 1], [4, 1], [6, 3], [1, 1], [6, 1]]
def generate_occurrence_list
generate_chunks do |category, chunk_array|
[category, chunk_array.size]
end
end
# The method below categorises the successive elements and groups and returns based on the block
# => generate_chunks([1,2,3,4,6,6,6]){|a, b| [a, b.size]}
# => [[1, 1], [2, 1], [3, 1], [4, 1], [6, 3]]
def generate_chunks(&block)
@roman_array.chunk{|y| y}.map do |category, chunk_array|
block.call(category, chunk_array)
end
end
end
end |
# encoding: UTF-8
require 'net/https'
require 'json'
module Rackspace
# Provides methods for generating HTTP requests to all API's,
# wrapping the fairly awful Net::HTTP stuff. Only JSON is supported.
class API
# Logging the error message and exiting:
#
# begin
# # some api call
# rescue Rackspace::API::Error => ex
# puts ex
# exit 1
# end
#
# Accessing parsed response JSON directly:
#
# begin
# # some api call
# rescue Rackspace::API::Error => ex
# puts ex.json
# end
class Error < StandardError
attr_reader :response
def initialize(response)
@response = response
super(response.body)
end
def to_s
"<Rackspace::API::Error #{@response.code} - #{@response.message}: \"#{@response.body}\">"
end
alias_method :inspect, :to_s
def json
@json ||= JSON.parse(@response.body)
end
end
attr_accessor :endpoint, :auth_token, :verbose
def initialize(endpoint, auth_token, options = {})
@endpoint = endpoint
@auth_token = auth_token
@verbose = options.delete(:verbose) { false }
end
def get(*args)
request(Net::HTTP::Get, *args)
end
def post(*args)
request(Net::HTTP::Post, *args)
end
private
def request(request_klass, path, params = {}, body = nil)
uri = URI("#{endpoint}/#{path}")
# encode URL parameters
if params && params.any?
uri.query = URI.encode_www_form(params)
end
# serialize body to JSON
if body && !body.is_a?(String)
body = JSON.generate(body)
end
req = request_klass.new(uri)
req.body = body if body
req['Accept'] = 'application/json'
req['Content-Type'] = 'application/json'
req['X-Auth-Token'] = auth_token if auth_token
puts "Request:\n #{req.inspect} #{uri}:#{uri.port}\n #{req.body}" if verbose
puts "Response:" if verbose
response = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.port == 443) {|http|
http.request(req)
}
if response.is_a?(Net::HTTPSuccess)
json = JSON.parse(response.body)
pp json if verbose
json
else
raise Error.new(response)
end
end
end
end
add http delete request shortcut
# encoding: UTF-8
require 'net/https'
require 'json'
module Rackspace
# Provides methods for generating HTTP requests to all API's,
# wrapping the fairly awful Net::HTTP stuff. Only JSON is supported.
class API
# Logging the error message and exiting:
#
# begin
# # some api call
# rescue Rackspace::API::Error => ex
# puts ex
# exit 1
# end
#
# Accessing parsed response JSON directly:
#
# begin
# # some api call
# rescue Rackspace::API::Error => ex
# puts ex.json
# end
class Error < StandardError
attr_reader :response
def initialize(response)
@response = response
super(response.body)
end
def to_s
"<Rackspace::API::Error #{@response.code} - #{@response.message}: \"#{@response.body}\">"
end
alias_method :inspect, :to_s
def json
@json ||= JSON.parse(@response.body)
end
end
attr_accessor :endpoint, :auth_token, :verbose
def initialize(endpoint, auth_token, options = {})
@endpoint = endpoint
@auth_token = auth_token
@verbose = options.delete(:verbose) { false }
end
def get(*args)
request(Net::HTTP::Get, *args)
end
def post(*args)
request(Net::HTTP::Post, *args)
end
def delete(*args)
request(Net::HTTP::Delete, *args)
end
private
def request(request_klass, path, params = {}, body = nil)
uri = URI("#{endpoint}/#{path}")
# encode URL parameters
if params && params.any?
uri.query = URI.encode_www_form(params)
end
# serialize body to JSON
if body && !body.is_a?(String)
body = JSON.generate(body)
end
req = request_klass.new(uri)
req.body = body if body
req['Accept'] = 'application/json'
req['Content-Type'] = 'application/json'
req['X-Auth-Token'] = auth_token if auth_token
puts "Request:\n #{req.inspect} #{uri}:#{uri.port}\n #{req.body}" if verbose
puts "Response:" if verbose
response = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.port == 443) {|http|
http.request(req)
}
if response.is_a?(Net::HTTPSuccess)
json = JSON.parse(response.body)
pp json if verbose
json
else
raise Error.new(response)
end
end
end
end
|
module RSpec
module Mocks
# @private
class MethodDouble
# @private
attr_reader :method_name, :object, :expectations, :stubs
# @private
def initialize(object, method_name, proxy)
@method_name = method_name
@object = object
@proxy = proxy
@original_visibility = nil
@method_stasher = InstanceMethodStasher.new(object, method_name)
@method_is_proxied = false
@expectations = []
@stubs = []
end
def original_method
# If original method is not present, uses the `method_missing`
# handler of the object. This accounts for cases where the user has not
# correctly defined `respond_to?`, and also 1.8 which does not provide
# method handles for missing methods even if `respond_to?` is correct.
@original_method ||=
@method_stasher.original_method ||
@proxy.method_handle_for(method_name) ||
Proc.new do |*args, &block|
@object.__send__(:method_missing, @method_name, *args, &block)
end
end
alias_method :save_original_method!, :original_method
# @private
def visibility
@proxy.visibility_for(@method_name)
end
# @private
def object_singleton_class
class << @object; self; end
end
# @private
def configure_method
@original_visibility = [visibility, method_name]
@method_stasher.stash unless @method_is_proxied
define_proxy_method
end
# @private
def define_proxy_method
return if @method_is_proxied
save_original_method!
object_singleton_class.class_exec(self, method_name, visibility) do |method_double, method_name, visibility|
define_method(method_name) do |*args, &block|
method_double.proxy_method_invoked(self, *args, &block)
end
self.__send__ visibility, method_name
end
@method_is_proxied = true
end
# The implementation of the proxied method. Subclasses may override this
# method to perform additional operations.
#
# @private
def proxy_method_invoked(obj, *args, &block)
@proxy.message_received method_name, *args, &block
end
# @private
def restore_original_method
return show_frozen_warning if object_singleton_class.frozen?
return unless @method_is_proxied
object_singleton_class.__send__(:remove_method, @method_name)
if @method_stasher.method_is_stashed?
@method_stasher.restore
end
restore_original_visibility
@method_is_proxied = false
end
# @private
def show_frozen_warning
RSpec.warn_with(
"WARNING: rspec-mocks was unable to restore the original `#{@method_name}` method on #{@object.inspect} because it has been frozen. If you reuse this object, `#{@method_name}` will continue to respond with its stub implementation.",
:call_site => nil,
:use_spec_location_as_call_site => true
)
end
# @private
def restore_original_visibility
return unless @original_visibility &&
MethodReference.method_defined_at_any_visibility?(object_singleton_class, @method_name)
object_singleton_class.__send__(*@original_visibility)
end
# @private
def verify
expectations.each {|e| e.verify_messages_received}
end
# @private
def reset
restore_original_method
clear
end
# @private
def clear
expectations.clear
stubs.clear
end
# The type of message expectation to create has been extracted to its own
# method so that subclasses can override it.
#
# @private
def message_expectation_class
MessageExpectation
end
# @private
def add_expectation(error_generator, expectation_ordering, expected_from, opts, &implementation)
configure_method
expectation = message_expectation_class.new(error_generator, expectation_ordering,
expected_from, self, 1, opts, &implementation)
expectations << expectation
expectation
end
# @private
def build_expectation(error_generator, expectation_ordering)
expected_from = IGNORED_BACKTRACE_LINE
message_expectation_class.new(error_generator, expectation_ordering, expected_from, self)
end
# @private
def add_stub(error_generator, expectation_ordering, expected_from, opts={}, &implementation)
configure_method
stub = message_expectation_class.new(error_generator, expectation_ordering, expected_from,
self, :any, opts, &implementation)
stubs.unshift stub
stub
end
# A simple stub can only return a concrete value for a message, and
# cannot match on arguments. It is used as an optimization over
# `add_stub` / `add_expectation` where it is known in advance that this
# is all that will be required of a stub, such as when passing attributes
# to the `double` example method. They do not stash or restore existing method
# definitions.
#
# @private
def add_simple_stub(method_name, response)
setup_simple_method_double method_name, response, stubs
end
# @private
def add_simple_expectation(method_name, response, error_generator, backtrace_line)
setup_simple_method_double method_name, response, expectations, error_generator, backtrace_line
end
# @private
def setup_simple_method_double(method_name, response, collection, error_generator = nil, backtrace_line = nil)
define_proxy_method
me = SimpleMessageExpectation.new(method_name, response, error_generator, backtrace_line)
collection.unshift me
me
end
# @private
def add_default_stub(*args, &implementation)
return if stubs.any?
add_stub(*args, &implementation)
end
# @private
def remove_stub
raise_method_not_stubbed_error if stubs.empty?
expectations.empty? ? reset : stubs.clear
end
# @private
def remove_single_stub(stub)
stubs.delete(stub)
restore_original_method if stubs.empty? && expectations.empty?
end
# @private
def raise_method_not_stubbed_error
raise MockExpectationError, "The method `#{method_name}` was not stubbed or was already unstubbed"
end
# @private
IGNORED_BACKTRACE_LINE = 'this backtrace line is ignored'
end
end
end
Remove duplicate constant that we don't need.
module RSpec
module Mocks
# @private
class MethodDouble
# @private
attr_reader :method_name, :object, :expectations, :stubs
# @private
def initialize(object, method_name, proxy)
@method_name = method_name
@object = object
@proxy = proxy
@original_visibility = nil
@method_stasher = InstanceMethodStasher.new(object, method_name)
@method_is_proxied = false
@expectations = []
@stubs = []
end
def original_method
# If original method is not present, uses the `method_missing`
# handler of the object. This accounts for cases where the user has not
# correctly defined `respond_to?`, and also 1.8 which does not provide
# method handles for missing methods even if `respond_to?` is correct.
@original_method ||=
@method_stasher.original_method ||
@proxy.method_handle_for(method_name) ||
Proc.new do |*args, &block|
@object.__send__(:method_missing, @method_name, *args, &block)
end
end
alias_method :save_original_method!, :original_method
# @private
def visibility
@proxy.visibility_for(@method_name)
end
# @private
def object_singleton_class
class << @object; self; end
end
# @private
def configure_method
@original_visibility = [visibility, method_name]
@method_stasher.stash unless @method_is_proxied
define_proxy_method
end
# @private
def define_proxy_method
return if @method_is_proxied
save_original_method!
object_singleton_class.class_exec(self, method_name, visibility) do |method_double, method_name, visibility|
define_method(method_name) do |*args, &block|
method_double.proxy_method_invoked(self, *args, &block)
end
self.__send__ visibility, method_name
end
@method_is_proxied = true
end
# The implementation of the proxied method. Subclasses may override this
# method to perform additional operations.
#
# @private
def proxy_method_invoked(obj, *args, &block)
@proxy.message_received method_name, *args, &block
end
# @private
def restore_original_method
return show_frozen_warning if object_singleton_class.frozen?
return unless @method_is_proxied
object_singleton_class.__send__(:remove_method, @method_name)
if @method_stasher.method_is_stashed?
@method_stasher.restore
end
restore_original_visibility
@method_is_proxied = false
end
# @private
def show_frozen_warning
RSpec.warn_with(
"WARNING: rspec-mocks was unable to restore the original `#{@method_name}` method on #{@object.inspect} because it has been frozen. If you reuse this object, `#{@method_name}` will continue to respond with its stub implementation.",
:call_site => nil,
:use_spec_location_as_call_site => true
)
end
# @private
def restore_original_visibility
return unless @original_visibility &&
MethodReference.method_defined_at_any_visibility?(object_singleton_class, @method_name)
object_singleton_class.__send__(*@original_visibility)
end
# @private
def verify
expectations.each {|e| e.verify_messages_received}
end
# @private
def reset
restore_original_method
clear
end
# @private
def clear
expectations.clear
stubs.clear
end
# The type of message expectation to create has been extracted to its own
# method so that subclasses can override it.
#
# @private
def message_expectation_class
MessageExpectation
end
# @private
def add_expectation(error_generator, expectation_ordering, expected_from, opts, &implementation)
configure_method
expectation = message_expectation_class.new(error_generator, expectation_ordering,
expected_from, self, 1, opts, &implementation)
expectations << expectation
expectation
end
# @private
def build_expectation(error_generator, expectation_ordering)
expected_from = IGNORED_BACKTRACE_LINE
message_expectation_class.new(error_generator, expectation_ordering, expected_from, self)
end
# @private
def add_stub(error_generator, expectation_ordering, expected_from, opts={}, &implementation)
configure_method
stub = message_expectation_class.new(error_generator, expectation_ordering, expected_from,
self, :any, opts, &implementation)
stubs.unshift stub
stub
end
# A simple stub can only return a concrete value for a message, and
# cannot match on arguments. It is used as an optimization over
# `add_stub` / `add_expectation` where it is known in advance that this
# is all that will be required of a stub, such as when passing attributes
# to the `double` example method. They do not stash or restore existing method
# definitions.
#
# @private
def add_simple_stub(method_name, response)
setup_simple_method_double method_name, response, stubs
end
# @private
def add_simple_expectation(method_name, response, error_generator, backtrace_line)
setup_simple_method_double method_name, response, expectations, error_generator, backtrace_line
end
# @private
def setup_simple_method_double(method_name, response, collection, error_generator = nil, backtrace_line = nil)
define_proxy_method
me = SimpleMessageExpectation.new(method_name, response, error_generator, backtrace_line)
collection.unshift me
me
end
# @private
def add_default_stub(*args, &implementation)
return if stubs.any?
add_stub(*args, &implementation)
end
# @private
def remove_stub
raise_method_not_stubbed_error if stubs.empty?
expectations.empty? ? reset : stubs.clear
end
# @private
def remove_single_stub(stub)
stubs.delete(stub)
restore_original_method if stubs.empty? && expectations.empty?
end
# @private
def raise_method_not_stubbed_error
raise MockExpectationError, "The method `#{method_name}` was not stubbed or was already unstubbed"
end
end
end
end
|
# A visitor for converting a Sass tree into CSS.
class Sass::Tree::Visitors::ToCss < Sass::Tree::Visitors::Base
# The source mapping for the generated CSS file. This is only set if
# `build_source_mapping` is passed to the constructor and \{Sass::Engine#render} has been
# run.
attr_reader :source_mapping
# @param build_source_mapping [Boolean] Whether to build a
# \{Sass::Source::Map} while creating the CSS output. The mapping will
# be available from \{#source\_mapping} after the visitor has completed.
def initialize(build_source_mapping = false)
@tabs = 0
@line = 1
@offset = 1
@result = ""
@source_mapping = Sass::Source::Map.new if build_source_mapping
end
# Runs the visitor on `node`.
#
# @param node [Sass::Tree::Node] The root node of the tree to convert to CSS>
# @return [String] The CSS output.
def visit(node)
super
rescue Sass::SyntaxError => e
e.modify_backtrace(:filename => node.filename, :line => node.line)
raise e
end
protected
def with_tabs(tabs)
old_tabs, @tabs = @tabs, tabs
yield
ensure
@tabs = old_tabs
end
# Associate all output produced in a block with a given node. Used for source
# mapping.
def for_node(node, attr_prefix = nil)
return yield unless @source_mapping
start_pos = Sass::Source::Position.new(@line, @offset)
yield
range_attr = attr_prefix ? :"#{attr_prefix}_source_range" : :source_range
return if node.invisible? || !node.send(range_attr)
source_range = node.send(range_attr)
target_end_pos = Sass::Source::Position.new(@line, @offset)
target_range = Sass::Source::Range.new(start_pos, target_end_pos, nil)
@source_mapping.add(source_range, target_range)
end
# Move the output cursor back `chars` characters.
def erase!(chars)
return if chars == 0
str = @result.slice!(-chars..-1)
newlines = str.count("\n")
if newlines > 0
@line -= newlines
@offset = @result[@result.rindex("\n") || 0..-1].size
else
@offset -= chars
end
end
# Avoid allocating lots of new strings for `#output`. This is important
# because `#output` is called all the time.
NEWLINE = "\n"
# Add `s` to the output string and update the line and offset information
# accordingly.
def output(s)
if @lstrip
s = s.gsub(/\A\s+/, "")
@lstrip = false
end
newlines = s.count(NEWLINE)
if newlines > 0
@line += newlines
@offset = s[s.rindex(NEWLINE)..-1].size
else
@offset += s.size
end
@result << s
end
# Strip all trailing whitespace from the output string.
def rstrip!
erase! @result.length - 1 - (@result.rindex(/[^\s]/) || -1)
end
# lstrip the first output in the given block.
def lstrip
old_lstrip = @lstrip
@lstrip = true
yield
ensure
@lstrip = @lstrip && old_lstrip
end
# Prepend `prefix` to the output string.
def prepend!(prefix)
@result.insert 0, prefix
return unless @source_mapping
line_delta = prefix.count("\n")
offset_delta = prefix.gsub(/.*\n/, '').size
@source_mapping.shift_output_offsets(offset_delta)
@source_mapping.shift_output_lines(line_delta)
end
def visit_root(node)
node.children.each do |child|
next if child.invisible?
visit(child)
unless node.style == :compressed
output "\n"
if child.is_a?(Sass::Tree::DirectiveNode) && child.has_children && !child.bubbles?
output "\n"
end
end
end
rstrip!
return "" if @result.empty?
output "\n"
return @result if Sass::Util.ruby1_8? || @result.ascii_only?
if node.children.first.is_a?(Sass::Tree::CharsetNode)
begin
encoding = node.children.first.name
# Default to big-endian encoding, because we have to decide somehow
encoding << 'BE' if encoding =~ /\Autf-(16|32)\Z/i
@result = @result.encode(Encoding.find(encoding))
rescue EncodingError
end
end
prepend! "@charset \"#{@result.encoding.name}\";#{
node.style == :compressed ? '' : "\n"
}".encode(@result.encoding)
@result
rescue Sass::SyntaxError => e
e.sass_template ||= node.template
raise e
end
def visit_charset(node)
for_node(node) {output("@charset \"#{node.name}\";")}
end
def visit_comment(node)
return if node.invisible?
spaces = (' ' * [@tabs - node.resolved_value[/^ */].size, 0].max)
content = node.resolved_value.gsub(/^/, spaces)
if node.type == :silent
content.gsub!(%r{^(\s*)//(.*)$}) {|md| "#{$1}/*#{$2} */"}
end
if (node.style == :compact || node.style == :compressed) && node.type != :loud
content.gsub!(/\n +(\* *(?!\/))?/, ' ')
end
for_node(node) {output(content)}
end
# @comment
# rubocop:disable MethodLength
def visit_directive(node)
was_in_directive = @in_directive
tab_str = ' ' * @tabs
if !node.has_children || node.children.empty?
output(tab_str)
for_node(node) {output(node.resolved_value)}
output(!node.has_children ? ";" : " {}")
return
end
@in_directive = @in_directive || !node.is_a?(Sass::Tree::MediaNode)
output(tab_str) if node.style != :compressed
for_node(node) {output(node.resolved_value)}
output(node.style == :compressed ? "{" : " {")
output(node.style == :compact ? ' ' : "\n") if node.style != :compressed
was_prop = false
first = true
node.children.each do |child|
next if child.invisible?
if node.style == :compact
if child.is_a?(Sass::Tree::PropNode)
with_tabs(first || was_prop ? 0 : @tabs + 1) do
visit(child)
output(' ')
end
else
if was_prop
erase! 1
output "\n"
end
if first
lstrip {with_tabs(@tabs + 1) {visit(child)}}
else
with_tabs(@tabs + 1) {visit(child)}
end
rstrip!
output "\n"
end
was_prop = child.is_a?(Sass::Tree::PropNode)
first = false
elsif node.style == :compressed
output(was_prop ? ";" : "")
with_tabs(0) {visit(child)}
was_prop = child.is_a?(Sass::Tree::PropNode)
else
with_tabs(@tabs + 1) {visit(child)}
output "\n"
end
end
rstrip!
if node.style == :expanded
output("\n#{tab_str}")
elsif node.style != :compressed
output(" ")
end
output("}")
ensure
@in_directive = was_in_directive
end
# @comment
# rubocop:enable MethodLength
def visit_media(node)
with_tabs(@tabs + node.tabs) {visit_directive(node)}
output("\n") if node.group_end
end
def visit_supports(node)
visit_media(node)
end
def visit_cssimport(node)
visit_directive(node)
end
def visit_prop(node)
return if node.resolved_value.empty?
tab_str = ' ' * (@tabs + node.tabs)
output(tab_str)
for_node(node, :name) {output(node.resolved_name)}
if node.style == :compressed
output(":");
for_node(node, :value) {output(node.resolved_value)}
else
output(": ")
for_node(node, :value) {output(node.resolved_value)}
output(";")
end
end
# @comment
# rubocop:disable MethodLength
# rubocop:disable BlockNesting
def visit_rule(node)
with_tabs(@tabs + node.tabs) do
rule_separator = node.style == :compressed ? ',' : ', '
line_separator =
case node.style
when :nested, :expanded; "\n"
when :compressed; ""
else; " "
end
rule_indent = ' ' * @tabs
per_rule_indent, total_indent = if [:nested, :expanded].include?(node.style)
[rule_indent, '']
else
['', rule_indent]
end
joined_rules = node.resolved_rules.members.map do |seq|
next if seq.has_placeholder?
rule_part = seq.to_a.join
if node.style == :compressed
rule_part.gsub!(/([^,])\s*\n\s*/m, '\1 ')
rule_part.gsub!(/\s*([,+>])\s*/m, '\1')
rule_part.strip!
end
rule_part
end.compact.join(rule_separator)
joined_rules.lstrip!
joined_rules.gsub!(/\s*\n\s*/, "#{line_separator}#{per_rule_indent}")
old_spaces = ' ' * @tabs
if node.style != :compressed
if node.options[:debug_info] && !@in_directive
visit(debug_info_rule(node.debug_info, node.options))
output "\n"
elsif node.options[:trace_selectors]
output("#{old_spaces}/* ")
output(node.stack_trace.gsub("\n", "\n #{old_spaces}"))
output(" */\n")
elsif node.options[:line_comments]
output("#{old_spaces}/* line #{node.line}")
if node.filename
relative_filename = if node.options[:css_filename]
begin
Pathname.new(node.filename).relative_path_from(
Pathname.new(File.dirname(node.options[:css_filename]))).to_s
rescue ArgumentError
nil
end
end
relative_filename ||= node.filename
output(", #{relative_filename}")
end
output(" */\n")
end
end
end_props, trailer, tabs = '', '', 0
if node.style == :compact
separator, end_props, bracket = ' ', ' ', ' { '
trailer = "\n" if node.group_end
elsif node.style == :compressed
separator, bracket = ';', '{'
else
tabs = @tabs + 1
separator, bracket = "\n", " {\n"
trailer = "\n" if node.group_end
end_props = (node.style == :expanded ? "\n" + old_spaces : ' ')
end
output(total_indent + per_rule_indent)
for_node(node, :selector) {output(joined_rules)}
output(bracket)
with_tabs(tabs) do
node.children.each_with_index do |child, i|
output(separator) if i > 0
visit(child)
end
end
output(end_props)
output("}" + trailer)
end
end
# @comment
# rubocop:enable MethodLength
# rubocop:enable BlockNesting
private
def debug_info_rule(debug_info, options)
node = Sass::Tree::DirectiveNode.resolved("@media -sass-debug-info")
Sass::Util.hash_to_a(debug_info.map {|k, v| [k.to_s, v.to_s]}).each do |k, v|
rule = Sass::Tree::RuleNode.new([""])
rule.resolved_rules = Sass::Selector::CommaSequence.new(
[Sass::Selector::Sequence.new(
[Sass::Selector::SimpleSequence.new(
[Sass::Selector::Element.new(k.to_s.gsub(/[^\w-]/, "\\\\\\0"), nil)],
false)
])
])
prop = Sass::Tree::PropNode.new([""], Sass::Script::Value::String.new(''), :new)
prop.resolved_name = "font-family"
prop.resolved_value = Sass::SCSS::RX.escape_ident(v.to_s)
rule << prop
node << rule
end
node.options = options.merge(:debug_info => false,
:line_comments => false,
:style => :compressed)
node
end
end
The when clause should align with the case statement.
# A visitor for converting a Sass tree into CSS.
class Sass::Tree::Visitors::ToCss < Sass::Tree::Visitors::Base
# The source mapping for the generated CSS file. This is only set if
# `build_source_mapping` is passed to the constructor and \{Sass::Engine#render} has been
# run.
attr_reader :source_mapping
# @param build_source_mapping [Boolean] Whether to build a
# \{Sass::Source::Map} while creating the CSS output. The mapping will
# be available from \{#source\_mapping} after the visitor has completed.
def initialize(build_source_mapping = false)
@tabs = 0
@line = 1
@offset = 1
@result = ""
@source_mapping = Sass::Source::Map.new if build_source_mapping
end
# Runs the visitor on `node`.
#
# @param node [Sass::Tree::Node] The root node of the tree to convert to CSS>
# @return [String] The CSS output.
def visit(node)
super
rescue Sass::SyntaxError => e
e.modify_backtrace(:filename => node.filename, :line => node.line)
raise e
end
protected
def with_tabs(tabs)
old_tabs, @tabs = @tabs, tabs
yield
ensure
@tabs = old_tabs
end
# Associate all output produced in a block with a given node. Used for source
# mapping.
def for_node(node, attr_prefix = nil)
return yield unless @source_mapping
start_pos = Sass::Source::Position.new(@line, @offset)
yield
range_attr = attr_prefix ? :"#{attr_prefix}_source_range" : :source_range
return if node.invisible? || !node.send(range_attr)
source_range = node.send(range_attr)
target_end_pos = Sass::Source::Position.new(@line, @offset)
target_range = Sass::Source::Range.new(start_pos, target_end_pos, nil)
@source_mapping.add(source_range, target_range)
end
# Move the output cursor back `chars` characters.
def erase!(chars)
return if chars == 0
str = @result.slice!(-chars..-1)
newlines = str.count("\n")
if newlines > 0
@line -= newlines
@offset = @result[@result.rindex("\n") || 0..-1].size
else
@offset -= chars
end
end
# Avoid allocating lots of new strings for `#output`. This is important
# because `#output` is called all the time.
NEWLINE = "\n"
# Add `s` to the output string and update the line and offset information
# accordingly.
def output(s)
if @lstrip
s = s.gsub(/\A\s+/, "")
@lstrip = false
end
newlines = s.count(NEWLINE)
if newlines > 0
@line += newlines
@offset = s[s.rindex(NEWLINE)..-1].size
else
@offset += s.size
end
@result << s
end
# Strip all trailing whitespace from the output string.
def rstrip!
erase! @result.length - 1 - (@result.rindex(/[^\s]/) || -1)
end
# lstrip the first output in the given block.
def lstrip
old_lstrip = @lstrip
@lstrip = true
yield
ensure
@lstrip = @lstrip && old_lstrip
end
# Prepend `prefix` to the output string.
def prepend!(prefix)
@result.insert 0, prefix
return unless @source_mapping
line_delta = prefix.count("\n")
offset_delta = prefix.gsub(/.*\n/, '').size
@source_mapping.shift_output_offsets(offset_delta)
@source_mapping.shift_output_lines(line_delta)
end
def visit_root(node)
node.children.each do |child|
next if child.invisible?
visit(child)
unless node.style == :compressed
output "\n"
if child.is_a?(Sass::Tree::DirectiveNode) && child.has_children && !child.bubbles?
output "\n"
end
end
end
rstrip!
return "" if @result.empty?
output "\n"
return @result if Sass::Util.ruby1_8? || @result.ascii_only?
if node.children.first.is_a?(Sass::Tree::CharsetNode)
begin
encoding = node.children.first.name
# Default to big-endian encoding, because we have to decide somehow
encoding << 'BE' if encoding =~ /\Autf-(16|32)\Z/i
@result = @result.encode(Encoding.find(encoding))
rescue EncodingError
end
end
prepend! "@charset \"#{@result.encoding.name}\";#{
node.style == :compressed ? '' : "\n"
}".encode(@result.encoding)
@result
rescue Sass::SyntaxError => e
e.sass_template ||= node.template
raise e
end
def visit_charset(node)
for_node(node) {output("@charset \"#{node.name}\";")}
end
def visit_comment(node)
return if node.invisible?
spaces = (' ' * [@tabs - node.resolved_value[/^ */].size, 0].max)
content = node.resolved_value.gsub(/^/, spaces)
if node.type == :silent
content.gsub!(%r{^(\s*)//(.*)$}) {|md| "#{$1}/*#{$2} */"}
end
if (node.style == :compact || node.style == :compressed) && node.type != :loud
content.gsub!(/\n +(\* *(?!\/))?/, ' ')
end
for_node(node) {output(content)}
end
# @comment
# rubocop:disable MethodLength
def visit_directive(node)
was_in_directive = @in_directive
tab_str = ' ' * @tabs
if !node.has_children || node.children.empty?
output(tab_str)
for_node(node) {output(node.resolved_value)}
output(!node.has_children ? ";" : " {}")
return
end
@in_directive = @in_directive || !node.is_a?(Sass::Tree::MediaNode)
output(tab_str) if node.style != :compressed
for_node(node) {output(node.resolved_value)}
output(node.style == :compressed ? "{" : " {")
output(node.style == :compact ? ' ' : "\n") if node.style != :compressed
was_prop = false
first = true
node.children.each do |child|
next if child.invisible?
if node.style == :compact
if child.is_a?(Sass::Tree::PropNode)
with_tabs(first || was_prop ? 0 : @tabs + 1) do
visit(child)
output(' ')
end
else
if was_prop
erase! 1
output "\n"
end
if first
lstrip {with_tabs(@tabs + 1) {visit(child)}}
else
with_tabs(@tabs + 1) {visit(child)}
end
rstrip!
output "\n"
end
was_prop = child.is_a?(Sass::Tree::PropNode)
first = false
elsif node.style == :compressed
output(was_prop ? ";" : "")
with_tabs(0) {visit(child)}
was_prop = child.is_a?(Sass::Tree::PropNode)
else
with_tabs(@tabs + 1) {visit(child)}
output "\n"
end
end
rstrip!
if node.style == :expanded
output("\n#{tab_str}")
elsif node.style != :compressed
output(" ")
end
output("}")
ensure
@in_directive = was_in_directive
end
# @comment
# rubocop:enable MethodLength
def visit_media(node)
with_tabs(@tabs + node.tabs) {visit_directive(node)}
output("\n") if node.group_end
end
def visit_supports(node)
visit_media(node)
end
def visit_cssimport(node)
visit_directive(node)
end
def visit_prop(node)
return if node.resolved_value.empty?
tab_str = ' ' * (@tabs + node.tabs)
output(tab_str)
for_node(node, :name) {output(node.resolved_name)}
if node.style == :compressed
output(":");
for_node(node, :value) {output(node.resolved_value)}
else
output(": ")
for_node(node, :value) {output(node.resolved_value)}
output(";")
end
end
# @comment
# rubocop:disable MethodLength
# rubocop:disable BlockNesting
def visit_rule(node)
with_tabs(@tabs + node.tabs) do
rule_separator = node.style == :compressed ? ',' : ', '
line_separator =
case node.style
when :nested, :expanded; "\n"
when :compressed; ""
else; " "
end
rule_indent = ' ' * @tabs
per_rule_indent, total_indent = if [:nested, :expanded].include?(node.style)
[rule_indent, '']
else
['', rule_indent]
end
joined_rules = node.resolved_rules.members.map do |seq|
next if seq.has_placeholder?
rule_part = seq.to_a.join
if node.style == :compressed
rule_part.gsub!(/([^,])\s*\n\s*/m, '\1 ')
rule_part.gsub!(/\s*([,+>])\s*/m, '\1')
rule_part.strip!
end
rule_part
end.compact.join(rule_separator)
joined_rules.lstrip!
joined_rules.gsub!(/\s*\n\s*/, "#{line_separator}#{per_rule_indent}")
old_spaces = ' ' * @tabs
if node.style != :compressed
if node.options[:debug_info] && !@in_directive
visit(debug_info_rule(node.debug_info, node.options))
output "\n"
elsif node.options[:trace_selectors]
output("#{old_spaces}/* ")
output(node.stack_trace.gsub("\n", "\n #{old_spaces}"))
output(" */\n")
elsif node.options[:line_comments]
output("#{old_spaces}/* line #{node.line}")
if node.filename
relative_filename = if node.options[:css_filename]
begin
Pathname.new(node.filename).relative_path_from(
Pathname.new(File.dirname(node.options[:css_filename]))).to_s
rescue ArgumentError
nil
end
end
relative_filename ||= node.filename
output(", #{relative_filename}")
end
output(" */\n")
end
end
end_props, trailer, tabs = '', '', 0
if node.style == :compact
separator, end_props, bracket = ' ', ' ', ' { '
trailer = "\n" if node.group_end
elsif node.style == :compressed
separator, bracket = ';', '{'
else
tabs = @tabs + 1
separator, bracket = "\n", " {\n"
trailer = "\n" if node.group_end
end_props = (node.style == :expanded ? "\n" + old_spaces : ' ')
end
output(total_indent + per_rule_indent)
for_node(node, :selector) {output(joined_rules)}
output(bracket)
with_tabs(tabs) do
node.children.each_with_index do |child, i|
output(separator) if i > 0
visit(child)
end
end
output(end_props)
output("}" + trailer)
end
end
# @comment
# rubocop:enable MethodLength
# rubocop:enable BlockNesting
private
def debug_info_rule(debug_info, options)
node = Sass::Tree::DirectiveNode.resolved("@media -sass-debug-info")
Sass::Util.hash_to_a(debug_info.map {|k, v| [k.to_s, v.to_s]}).each do |k, v|
rule = Sass::Tree::RuleNode.new([""])
rule.resolved_rules = Sass::Selector::CommaSequence.new(
[Sass::Selector::Sequence.new(
[Sass::Selector::SimpleSequence.new(
[Sass::Selector::Element.new(k.to_s.gsub(/[^\w-]/, "\\\\\\0"), nil)],
false)
])
])
prop = Sass::Tree::PropNode.new([""], Sass::Script::Value::String.new(''), :new)
prop.resolved_name = "font-family"
prop.resolved_value = Sass::SCSS::RX.escape_ident(v.to_s)
rule << prop
node << rule
end
node.options = options.merge(:debug_info => false,
:line_comments => false,
:style => :compressed)
node
end
end
|
require 'warden'
# Satellite warden strategy will authenticate user for a
# 'satellite' client app for the configured provider,
# which for our purposes is likely to be 'devpost'
#
module Satellite
class WardenStrategy < Warden::Strategies::Base
# cookies[:production_user_jwt] provided when logged in on platform app
# env['omniauth.auth'] provided when completed omniauth callback
#
def valid?
user_cookie.present? && env['omniauth.auth']
end
def authenticate!
user = user_class.find_or_create_with_omniauth(env['omniauth.auth'])
if valid_session?(user)
success! user
else
Rails.logger.info "Warden failure!!! #{env['omniauth.auth'].inspect}" if defined?(Rails)
fail!("Could not log in")
end
end
private
def cookies
env['action_dispatch.cookies']
end
def user_cookie
@user_cookie ||= Satellite::UserCookie.new(cookies)
end
def user_decoder
@user_decoder ||= Satellite::JWT::UserDecoder.new(user_cookie.to_cookie)
end
def valid_session?(user)
user && user.provider_key?(cookie_provider_key)
end
def cookie_provider_key
[Satellite.configuration.provider, user_decoder.user_uid]
end
def user_class
Satellite.configuration.user_class
end
end
end
Warden::Strategies.add(:satellite, Satellite::WardenStrategy)
Warden::Manager.serialize_into_session do |user|
[user.class.name, user.id]
end
Warden::Manager.serialize_from_session do |serialized|
class_name, id = serialized
class_name.constantize.find(id)
end
renamed JWT::UserDecoder
require 'warden'
# Satellite warden strategy will authenticate user for a
# 'satellite' client app for the configured provider,
# which for our purposes is likely to be 'devpost'
#
module Satellite
class WardenStrategy < Warden::Strategies::Base
# cookies[:production_user_jwt] provided when logged in on platform app
# env['omniauth.auth'] provided when completed omniauth callback
#
def valid?
user_cookie.present? && env['omniauth.auth']
end
def authenticate!
user = user_class.find_or_create_with_omniauth(env['omniauth.auth'])
if valid_session?(user)
success! user
else
Rails.logger.info "Warden failure!!! #{env['omniauth.auth'].inspect}" if defined?(Rails)
fail!("Could not log in")
end
end
private
def cookies
env['action_dispatch.cookies']
end
def user_cookie
@user_cookie ||= Satellite::UserCookie.new(cookies)
end
def user_decoder
@user_decoder ||= Satellite::JWTUserDecoder.new(user_cookie.to_cookie)
end
def valid_session?(user)
user && user.provider_key?(cookie_provider_key)
end
def cookie_provider_key
[Satellite.configuration.provider, user_decoder.user_uid]
end
def user_class
Satellite.configuration.user_class
end
end
end
Warden::Strategies.add(:satellite, Satellite::WardenStrategy)
Warden::Manager.serialize_into_session do |user|
[user.class.name, user.id]
end
Warden::Manager.serialize_from_session do |serialized|
class_name, id = serialized
class_name.constantize.find(id)
end
|
module SexyButtons
module ViewHelpers
# Returns a stylesheet link tags for the sexy button styles
#
# Provide themes you want to load. For example this will load themes "one", "two", "theme_three"
#
# sexy_buttons_stylesheet_link_tag "one", "two", "theme_three"
#
# If you want to load all themes from public/stylesheets/sexy_buttons/themes dir use <tt>:all</tt> as themes
#
# sexy_buttons_stylesheet_link_tag :all
#
# If you ommit themes only default theme will be loaded
#
# See http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html#M001687 for more info
def sexy_buttons_stylesheet_link_tag(*themes)
if themes.first.to_s == "all"
themes = Dir.entries("#{SexyButtons.public_root}/themes").delete_if { |e| !File.directory?("#{SexyButtons.public_root}/themes/#{e}") or e.match(/^\./) }
end
themes.delete(SexyButtons.default_theme)
themes.unshift(SexyButtons.default_theme)
themes = themes.collect { |t| "#{SexyButtons.public_url}/themes/#{t}/style" }
themes.unshift("#{SexyButtons.public_url}/style")
links = stylesheet_link_tag(*themes)
end
# Returns styled <tt>button</tt> tag
#
# To use specific theme use <tt>:theme</tt> options
#
# sexy_button "Click Me", :theme => "my-theme"
#
# For theme to work, you must add theme to public/stylesheets/sexy_buttons/themes first
def sexy_button(value="Submit", options={})
default_options = {
:type => "submit",
:value => value,
:class => "sexy-button"
}
if options[:theme] or SexyButtons.default_theme != "default"
theme = options[:theme] ? options.delete(:theme) : SexyButtons.default_theme
default_options[:class] << " sexy-button-#{theme}"
end
if options[:class]
options[:class] << " #{default_options[:class]}"
end
content_tag(:button, "<span>#{value}</span>", default_options.merge(options))
end
# Returens styled <tt>a</tt> tag
#
# themes are selected similar to sexy_button method
#
# sexy_link_to "Click here", "/my_url", :theme => "my-theme"
def sexy_link_to(name, options={}, html_options={})
default_html_options = {
:class => "sexy-button"
}
if html_options[:theme] or SexyButtons.default_theme != "default"
theme = html_options[:theme] ? html_options.delete(:theme) : SexyButtons.default_theme
default_html_options[:class] << " sexy-button-#{theme}"
end
if html_options[:class]
html_options[:class] << " #{default_options[:class]}"
end
link_to("<span>#{name}</span>", options, default_html_options.merge(html_options))
end
end
end
use content_tag :span so we don't have to use html_safe all the time
module SexyButtons
module ViewHelpers
# Returns a stylesheet link tags for the sexy button styles
#
# Provide themes you want to load. For example this will load themes "one", "two", "theme_three"
#
# sexy_buttons_stylesheet_link_tag "one", "two", "theme_three"
#
# If you want to load all themes from public/stylesheets/sexy_buttons/themes dir use <tt>:all</tt> as themes
#
# sexy_buttons_stylesheet_link_tag :all
#
# If you ommit themes only default theme will be loaded
#
# See http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html#M001687 for more info
def sexy_buttons_stylesheet_link_tag(*themes)
if themes.first.to_s == "all"
themes = Dir.entries("#{SexyButtons.public_root}/themes").delete_if { |e| !File.directory?("#{SexyButtons.public_root}/themes/#{e}") or e.match(/^\./) }
end
themes.delete(SexyButtons.default_theme)
themes.unshift(SexyButtons.default_theme)
themes = themes.collect { |t| "#{SexyButtons.public_url}/themes/#{t}/style" }
themes.unshift("#{SexyButtons.public_url}/style")
links = stylesheet_link_tag(*themes)
end
# Returns styled <tt>button</tt> tag
#
# To use specific theme use <tt>:theme</tt> options
#
# sexy_button "Click Me", :theme => "my-theme"
#
# For theme to work, you must add theme to public/stylesheets/sexy_buttons/themes first
def sexy_button(value="Submit", options={})
default_options = {
:type => "submit",
:value => value,
:class => "sexy-button"
}
if options[:theme] or SexyButtons.default_theme != "default"
theme = options[:theme] ? options.delete(:theme) : SexyButtons.default_theme
default_options[:class] << " sexy-button-#{theme}"
end
if options[:class]
options[:class] << " #{default_options[:class]}"
end
content_tag(:button, content_tag(:span, value), default_options.merge(options))
end
# Returens styled <tt>a</tt> tag
#
# themes are selected similar to sexy_button method
#
# sexy_link_to "Click here", "/my_url", :theme => "my-theme"
def sexy_link_to(name, options={}, html_options={})
default_html_options = {
:class => "sexy-button"
}
if html_options[:theme] or SexyButtons.default_theme != "default"
theme = html_options[:theme] ? html_options.delete(:theme) : SexyButtons.default_theme
default_html_options[:class] << " sexy-button-#{theme}"
end
if html_options[:class]
html_options[:class] << " #{default_options[:class]}"
end
link_to(content_tag(:span, name), options, default_html_options.merge(html_options))
end
end
end |
# encoding: utf-8
module Beggar
class Base
def initialize(config)
Basecamp.establish_connection!("#{config['company']}.basecamphq.com", config['token'], 'X', true)
Hours.project_id = config['project']['id']
Salary.rate = config['project']['rate']
end
def me
@@me ||= Basecamp::Person.me
end
def summary
[CurrentMonth, Hours, Salary].join(' || ')
end
end
end
Fix me method
# encoding: utf-8
module Beggar
class Base
def initialize(config)
Basecamp.establish_connection!("#{config['company']}.basecamphq.com", config['token'], 'X', true)
Hours.project_id = config['project']['id']
Salary.rate = config['project']['rate']
end
def self.me
@@me ||= Basecamp::Person.me
end
def summary
[CurrentMonth, Hours, Salary].join(' || ')
end
end
end
|
module Bem
VERSION = '1.0.0'
end
Bump version to 1.1.0
module Bem
VERSION = '1.1.0'
end
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2014 Ruby-GNOME2 Project Team
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
class TestGdkEvent < Test::Unit::TestCase
class TestConstant < self
def test_propagate
assert_false(Gdk::Event::PROPAGATE)
end
def test_stop
assert_true(Gdk::Event::STOP)
end
end
module TestAnyMethods
def test_window
assert_nil(event.window)
attributes = Gdk::WindowAttr.new(100, 100, :input_only, :temp)
window = Gdk::Window.new(nil, attributes, 0)
event.window = window
assert_equal(window, event.window)
end
def test_send_event
assert_false(event.send_event?)
end
end
class TestAny < self
include TestAnyMethods
def setup
@event = Gdk::EventAny.new(:delete)
end
def event
@event
end
def test_delete
assert_equal("GDK_DELETE",
Gdk::EventAny.new(:delete).type.name)
end
def test_destroy
assert_equal("GDK_DESTROY",
Gdk::EventAny.new(:destroy).type.name)
end
end
class TestKey < self
include TestAnyMethods
def setup
@key = Gdk::EventKey.new(:key_press)
end
def event
@key
end
def test_key_press
assert_equal("GDK_KEY_PRESS",
Gdk::EventKey.new(:key_press).type.name)
end
def test_key_release
assert_equal("GDK_KEY_RELEASE",
Gdk::EventKey.new(:key_release).type.name)
end
def test_time
assert_kind_of(Integer, @key.time)
end
def test_state
assert_not_nil(@key.state)
end
def test_keyval
assert_kind_of(Integer, @key.keyval)
end
end
class TestButton < self
include TestAnyMethods
def setup
@button = Gdk::EventButton.new(:button_press)
end
def event
@button
end
def test_button_press
assert_equal("GDK_BUTTON_PRESS",
Gdk::EventButton.new(:button_press).type.name)
end
def test_button2_press
assert_equal("GDK_2BUTTON_PRESS",
Gdk::EventButton.new(:button2_press).type.name)
end
def test_button3_press
assert_equal("GDK_3BUTTON_PRESS",
Gdk::EventButton.new(:button3_press).type.name)
end
def test_button_release
assert_equal("GDK_BUTTON_RELEASE",
Gdk::EventButton.new(:button_release).type.name)
end
def test_time
assert_kind_of(Integer, @button.time)
end
def test_x
assert_kind_of(Float, @button.x)
end
def test_y
assert_kind_of(Float, @button.y)
end
def test_state
assert_not_nil(@button.state)
end
def test_button
assert_kind_of(Integer, @button.button)
end
def test_x_root
assert_kind_of(Float, @button.x_root)
end
def test_y_root
assert_kind_of(Float, @button.y_root)
end
end
class TestTouch < self
include TestAnyMethods
def setup
@touch = Gdk::EventTouch.new(:touch_begin)
end
def event
@touch
end
def test_time
assert_kind_of(Integer, @touch.time)
end
def test_x
assert_kind_of(Float, @touch.x)
end
def test_y
assert_kind_of(Float, @touch.y)
end
def test_axes
assert_nothing_raised do
@touch.axes
end
end
def test_state
assert_not_nil(@touch.state)
end
def test_touch_begin
assert_equal("GDK_TOUCH_BEGIN",
Gdk::EventTouch.new(:touch_begin).type.name)
end
def test_touch_update
assert_equal("GDK_TOUCH_UPDATE",
Gdk::EventTouch.new(:touch_update).type.name)
end
def test_touch_cancel
assert_equal("GDK_TOUCH_CANCEL",
Gdk::EventTouch.new(:touch_cancel).type.name)
end
def test_touch_end
assert_equal("GDK_TOUCH_END",
Gdk::EventTouch.new(:touch_end).type.name)
end
def test_emulating_pointer
assert_nothing_raised do
@touch.emulating_pointer
end
end
def test_device
assert_nothing_raised do
@touch.device
end
end
def test_x_root
assert_kind_of(Float, @touch.x_root)
end
def test_y_root
assert_kind_of(Float, @touch.y_root)
end
end
class TestScroll < self
include TestAnyMethods
def setup
@scroll = Gdk::EventScroll.new(:scroll)
end
def event
@scroll
end
def test_time
assert_kind_of(Integer, @scroll.time)
end
def test_x
assert_kind_of(Float, @scroll.x)
end
def test_y
assert_kind_of(Float, @scroll.y)
end
def test_state
assert_not_nil(@scroll.state)
end
def test_direction
assert_kind_of(Gdk::ScrollDirection, @scroll.direction)
end
def test_x_root
assert_kind_of(Float, @scroll.x_root)
end
def test_y_root
assert_kind_of(Float, @scroll.y_root)
end
end
class TestMotion < self
include TestAnyMethods
def setup
@motion = Gdk::EventMotion.new(:motion_notify)
end
def event
@motion
end
def test_time
assert_kind_of(Integer, @motion.time)
end
def test_x
assert_kind_of(Float, @motion.x)
end
def test_y
assert_kind_of(Float, @motion.y)
end
def test_state
assert_not_nil(@motion.state)
end
def test_x_root
assert_kind_of(Float, @motion.x_root)
end
def test_y_root
assert_kind_of(Float, @motion.y_root)
end
def test_request
assert_nothing_raised do
@motion.request
end
end
end
class TestVisibility < self
include TestAnyMethods
def setup
@visibility = Gdk::EventVisibility.new(:visibility_notify)
end
def event
@visibility
end
def test_state
assert_kind_of(Gdk::VisibilityState, @visibility.state)
end
end
class TestCrossing < self
include TestAnyMethods
def setup
@crossing = Gdk::EventCrossing.new(:enter_notify)
end
def event
@crossing
end
def test_enter_notify
assert_equal("GDK_ENTER_NOTIFY",
Gdk::EventCrossing.new(:enter_notify).type.name)
end
def test_leave_notify
assert_equal("GDK_LEAVE_NOTIFY",
Gdk::EventCrossing.new(:leave_notify).type.name)
end
def test_time
assert_kind_of(Integer, @crossing.time)
end
def test_x
assert_kind_of(Float, @crossing.x)
end
def test_y
assert_kind_of(Float, @crossing.y)
end
def test_x_root
assert_kind_of(Float, @crossing.x_root)
end
def test_y_root
assert_kind_of(Float, @crossing.y_root)
end
def test_mode
assert_kind_of(Gdk::CrossingMode, @crossing.mode)
end
def test_detail
assert_not_nil(@crossing.detail)
end
def test_state
assert_not_nil(@crossing.state)
end
end
class TestFocus < self
include TestAnyMethods
def setup
@focus = Gdk::EventFocus.new(:focus_change)
end
def event
@focus
end
def test_in
assert_false(@focus.in?)
end
end
class TestConfigure < self
include TestAnyMethods
def setup
@configure = Gdk::EventConfigure.new(:configure)
end
def event
@configure
end
def test_x
assert_kind_of(Integer, @configure.x)
end
def test_y
assert_kind_of(Integer, @configure.y)
end
def test_width
assert_kind_of(Integer, @configure.width)
end
def test_height
assert_kind_of(Integer, @configure.height)
end
end
class TestProperty < self
include TestAnyMethods
def setup
@property = Gdk::EventProperty.new(:property_notify)
end
def event
@property
end
def test_atom
assert_nothing_raised do
@property.atom
end
end
def test_time
assert_kind_of(Integer, @property.time)
end
def test_state
assert_equal(Gdk::PropertyState::NEW_VALUE, @property.state)
end
end
class TestSelection < self
include TestAnyMethods
def setup
@selection = Gdk::EventSelection.new(:selection_clear)
end
def event
@selection
end
def test_selection_clear
assert_equal("GDK_SELECTION_CLEAR",
Gdk::EventSelection.new(:selection_clear).type.name)
end
def test_selection_notify
assert_equal("GDK_SELECTION_NOTIFY",
Gdk::EventSelection.new(:selection_notify).type.name)
end
def test_selection_request
assert_equal("GDK_SELECTION_REQUEST",
Gdk::EventSelection.new(:selection_request).type.name)
end
def test_selection
assert_nothing_raised do
@selection.selection
end
end
def test_target
assert_nothing_raised do
@selection.target
end
end
def test_property
assert_nothing_raised do
@selection.property
end
end
def test_time
assert_kind_of(Integer, @selection.time)
end
end
class TestDND < self
include TestAnyMethods
def setup
@dnd = Gdk::EventDND.new(:drag_enter)
end
def event
@dnd
end
def test_drag_enter
assert_equal("GDK_DRAG_ENTER",
Gdk::EventDND.new(:drag_enter).type.name)
end
def test_drag_leave
assert_equal("GDK_DRAG_LEAVE",
Gdk::EventDND.new(:drag_leave).type.name)
end
def test_drag_motion
assert_equal("GDK_DRAG_MOTION",
Gdk::EventDND.new(:drag_motion).type.name)
end
def test_drag_status
assert_equal("GDK_DRAG_STATUS",
Gdk::EventDND.new(:drag_status).type.name)
end
def test_drop_start
assert_equal("GDK_DROP_START",
Gdk::EventDND.new(:drop_start).type.name)
end
def test_drop_finished
assert_equal("GDK_DROP_FINISHED",
Gdk::EventDND.new(:drop_finished).type.name)
end
def test_context
assert_nothing_raised do
@dnd.context
end
end
def test_time
assert_kind_of(Integer, @dnd.time)
end
def test_x_root
assert_kind_of(Integer, @dnd.x_root)
end
def test_y_root
assert_kind_of(Integer, @dnd.y_root)
end
end
class TestProximity < self
include TestAnyMethods
def setup
@proximity = Gdk::EventProximity.new(:proximity_in)
end
def event
@proximity
end
def test_proximity_in
assert_equal("GDK_PROXIMITY_IN",
Gdk::EventProximity.new(:proximity_in).type.name)
end
def test_proximity_out
assert_equal("GDK_PROXIMITY_OUT",
Gdk::EventProximity.new(:proximity_out).type.name)
end
def test_time
assert_kind_of(Integer, @proximity.time)
end
def test_device
assert_nothing_raised do
@proximity.device
end
end
end
class TestWindowState < self
include TestAnyMethods
def setup
@window_state = Gdk::EventWindowState.new(:window_state)
end
def event
@window_state
end
def test_changed_mask
assert_nothing_raised do
@window_state.changed_mask
end
end
def test_new_window_state
assert_nothing_raised do
@window_state.new_window_state
end
end
end
class TestSetting < self
include TestAnyMethods
def setup
@setting = Gdk::EventSetting.new(:setting)
end
def event
@setting
end
def test_action
assert_nothing_raised do
@setting.action
end
end
def test_name
assert_nothing_raised do
@setting.name
end
end
end
class TestOwnerChange < self
def setup
@owner_change = Gdk::EventOwnerChange.new(:owner_change)
end
def event
@owner_change
end
def test_owner
assert_nothing_raised do
@owner_change.owner
end
end
def test_reason
assert_nothing_raised do
@owner_change.reason
end
end
def test_selection
assert_nothing_raised do
@owner_change.selection
end
end
def test_time
assert_kind_of(Integer, @owner_change.time)
end
def test_selection_time
assert_kind_of(Integer, @owner_change.selection_time)
end
end
class TestGrabBroken < self
include TestAnyMethods
def setup
@grab_broken = Gdk::EventGrabBroken.new(:grab_broken)
end
def event
@grab_broken
end
def test_keyboard
assert_boolean(@grab_broken.keyboard?)
end
def test_implicit
assert_boolean(@grab_broken.implicit?)
end
def test_grab_window
assert_nil(@grab_broken.grab_window)
end
end
end
gdk3 test: In Gdk Event, #send_event?, #in?, #implicit? and #keyboard? are not defined.
Currently, in Gdk Event, #send_event, #in, #implicit and #keyboard are defined.
These are not Rubyish methods naming....
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2014 Ruby-GNOME2 Project Team
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
class TestGdkEvent < Test::Unit::TestCase
class TestConstant < self
def test_propagate
assert_false(Gdk::Event::PROPAGATE)
end
def test_stop
assert_true(Gdk::Event::STOP)
end
end
module TestAnyMethods
def test_window
assert_nil(event.window)
attributes = Gdk::WindowAttr.new(100, 100, :input_only, :temp)
window = Gdk::Window.new(nil, attributes, 0)
event.window = window
assert_equal(window, event.window)
end
def test_send_event
assert_equal(0, event.send_event)
end
end
class TestAny < self
include TestAnyMethods
def setup
@event = Gdk::EventAny.new(:delete)
end
def event
@event
end
def test_delete
assert_equal("GDK_DELETE",
Gdk::EventAny.new(:delete).type.name)
end
def test_destroy
assert_equal("GDK_DESTROY",
Gdk::EventAny.new(:destroy).type.name)
end
end
class TestKey < self
include TestAnyMethods
def setup
@key = Gdk::EventKey.new(:key_press)
end
def event
@key
end
def test_key_press
assert_equal("GDK_KEY_PRESS",
Gdk::EventKey.new(:key_press).type.name)
end
def test_key_release
assert_equal("GDK_KEY_RELEASE",
Gdk::EventKey.new(:key_release).type.name)
end
def test_time
assert_kind_of(Integer, @key.time)
end
def test_state
assert_not_nil(@key.state)
end
def test_keyval
assert_kind_of(Integer, @key.keyval)
end
end
class TestButton < self
include TestAnyMethods
def setup
@button = Gdk::EventButton.new(:button_press)
end
def event
@button
end
def test_button_press
assert_equal("GDK_BUTTON_PRESS",
Gdk::EventButton.new(:button_press).type.name)
end
def test_button2_press
assert_equal("GDK_2BUTTON_PRESS",
Gdk::EventButton.new(:button2_press).type.name)
end
def test_button3_press
assert_equal("GDK_3BUTTON_PRESS",
Gdk::EventButton.new(:button3_press).type.name)
end
def test_button_release
assert_equal("GDK_BUTTON_RELEASE",
Gdk::EventButton.new(:button_release).type.name)
end
def test_time
assert_kind_of(Integer, @button.time)
end
def test_x
assert_kind_of(Float, @button.x)
end
def test_y
assert_kind_of(Float, @button.y)
end
def test_state
assert_not_nil(@button.state)
end
def test_button
assert_kind_of(Integer, @button.button)
end
def test_x_root
assert_kind_of(Float, @button.x_root)
end
def test_y_root
assert_kind_of(Float, @button.y_root)
end
end
class TestTouch < self
include TestAnyMethods
def setup
@touch = Gdk::EventTouch.new(:touch_begin)
end
def event
@touch
end
def test_time
assert_kind_of(Integer, @touch.time)
end
def test_x
assert_kind_of(Float, @touch.x)
end
def test_y
assert_kind_of(Float, @touch.y)
end
def test_axes
assert_nothing_raised do
@touch.axes
end
end
def test_state
assert_not_nil(@touch.state)
end
def test_touch_begin
assert_equal("GDK_TOUCH_BEGIN",
Gdk::EventTouch.new(:touch_begin).type.name)
end
def test_touch_update
assert_equal("GDK_TOUCH_UPDATE",
Gdk::EventTouch.new(:touch_update).type.name)
end
def test_touch_cancel
assert_equal("GDK_TOUCH_CANCEL",
Gdk::EventTouch.new(:touch_cancel).type.name)
end
def test_touch_end
assert_equal("GDK_TOUCH_END",
Gdk::EventTouch.new(:touch_end).type.name)
end
def test_emulating_pointer
assert_nothing_raised do
@touch.emulating_pointer
end
end
def test_device
assert_nothing_raised do
@touch.device
end
end
def test_x_root
assert_kind_of(Float, @touch.x_root)
end
def test_y_root
assert_kind_of(Float, @touch.y_root)
end
end
class TestScroll < self
include TestAnyMethods
def setup
@scroll = Gdk::EventScroll.new(:scroll)
end
def event
@scroll
end
def test_time
assert_kind_of(Integer, @scroll.time)
end
def test_x
assert_kind_of(Float, @scroll.x)
end
def test_y
assert_kind_of(Float, @scroll.y)
end
def test_state
assert_not_nil(@scroll.state)
end
def test_direction
assert_kind_of(Gdk::ScrollDirection, @scroll.direction)
end
def test_x_root
assert_kind_of(Float, @scroll.x_root)
end
def test_y_root
assert_kind_of(Float, @scroll.y_root)
end
end
class TestMotion < self
include TestAnyMethods
def setup
@motion = Gdk::EventMotion.new(:motion_notify)
end
def event
@motion
end
def test_time
assert_kind_of(Integer, @motion.time)
end
def test_x
assert_kind_of(Float, @motion.x)
end
def test_y
assert_kind_of(Float, @motion.y)
end
def test_state
assert_not_nil(@motion.state)
end
def test_x_root
assert_kind_of(Float, @motion.x_root)
end
def test_y_root
assert_kind_of(Float, @motion.y_root)
end
def test_request
assert_nothing_raised do
@motion.request
end
end
end
class TestVisibility < self
include TestAnyMethods
def setup
@visibility = Gdk::EventVisibility.new(:visibility_notify)
end
def event
@visibility
end
def test_state
assert_kind_of(Gdk::VisibilityState, @visibility.state)
end
end
class TestCrossing < self
include TestAnyMethods
def setup
@crossing = Gdk::EventCrossing.new(:enter_notify)
end
def event
@crossing
end
def test_enter_notify
assert_equal("GDK_ENTER_NOTIFY",
Gdk::EventCrossing.new(:enter_notify).type.name)
end
def test_leave_notify
assert_equal("GDK_LEAVE_NOTIFY",
Gdk::EventCrossing.new(:leave_notify).type.name)
end
def test_time
assert_kind_of(Integer, @crossing.time)
end
def test_x
assert_kind_of(Float, @crossing.x)
end
def test_y
assert_kind_of(Float, @crossing.y)
end
def test_x_root
assert_kind_of(Float, @crossing.x_root)
end
def test_y_root
assert_kind_of(Float, @crossing.y_root)
end
def test_mode
assert_kind_of(Gdk::CrossingMode, @crossing.mode)
end
def test_detail
assert_not_nil(@crossing.detail)
end
def test_state
assert_not_nil(@crossing.state)
end
end
class TestFocus < self
include TestAnyMethods
def setup
@focus = Gdk::EventFocus.new(:focus_change)
end
def event
@focus
end
def test_in
assert_equal(0, @focus.in)
end
end
class TestConfigure < self
include TestAnyMethods
def setup
@configure = Gdk::EventConfigure.new(:configure)
end
def event
@configure
end
def test_x
assert_kind_of(Integer, @configure.x)
end
def test_y
assert_kind_of(Integer, @configure.y)
end
def test_width
assert_kind_of(Integer, @configure.width)
end
def test_height
assert_kind_of(Integer, @configure.height)
end
end
class TestProperty < self
include TestAnyMethods
def setup
@property = Gdk::EventProperty.new(:property_notify)
end
def event
@property
end
def test_atom
assert_nothing_raised do
@property.atom
end
end
def test_time
assert_kind_of(Integer, @property.time)
end
def test_state
assert_equal(Gdk::PropertyState::NEW_VALUE, @property.state)
end
end
class TestSelection < self
include TestAnyMethods
def setup
@selection = Gdk::EventSelection.new(:selection_clear)
end
def event
@selection
end
def test_selection_clear
assert_equal("GDK_SELECTION_CLEAR",
Gdk::EventSelection.new(:selection_clear).type.name)
end
def test_selection_notify
assert_equal("GDK_SELECTION_NOTIFY",
Gdk::EventSelection.new(:selection_notify).type.name)
end
def test_selection_request
assert_equal("GDK_SELECTION_REQUEST",
Gdk::EventSelection.new(:selection_request).type.name)
end
def test_selection
assert_nothing_raised do
@selection.selection
end
end
def test_target
assert_nothing_raised do
@selection.target
end
end
def test_property
assert_nothing_raised do
@selection.property
end
end
def test_time
assert_kind_of(Integer, @selection.time)
end
end
class TestDND < self
include TestAnyMethods
def setup
@dnd = Gdk::EventDND.new(:drag_enter)
end
def event
@dnd
end
def test_drag_enter
assert_equal("GDK_DRAG_ENTER",
Gdk::EventDND.new(:drag_enter).type.name)
end
def test_drag_leave
assert_equal("GDK_DRAG_LEAVE",
Gdk::EventDND.new(:drag_leave).type.name)
end
def test_drag_motion
assert_equal("GDK_DRAG_MOTION",
Gdk::EventDND.new(:drag_motion).type.name)
end
def test_drag_status
assert_equal("GDK_DRAG_STATUS",
Gdk::EventDND.new(:drag_status).type.name)
end
def test_drop_start
assert_equal("GDK_DROP_START",
Gdk::EventDND.new(:drop_start).type.name)
end
def test_drop_finished
assert_equal("GDK_DROP_FINISHED",
Gdk::EventDND.new(:drop_finished).type.name)
end
def test_context
assert_nothing_raised do
@dnd.context
end
end
def test_time
assert_kind_of(Integer, @dnd.time)
end
def test_x_root
assert_kind_of(Integer, @dnd.x_root)
end
def test_y_root
assert_kind_of(Integer, @dnd.y_root)
end
end
class TestProximity < self
include TestAnyMethods
def setup
@proximity = Gdk::EventProximity.new(:proximity_in)
end
def event
@proximity
end
def test_proximity_in
assert_equal("GDK_PROXIMITY_IN",
Gdk::EventProximity.new(:proximity_in).type.name)
end
def test_proximity_out
assert_equal("GDK_PROXIMITY_OUT",
Gdk::EventProximity.new(:proximity_out).type.name)
end
def test_time
assert_kind_of(Integer, @proximity.time)
end
def test_device
assert_nothing_raised do
@proximity.device
end
end
end
class TestWindowState < self
include TestAnyMethods
def setup
@window_state = Gdk::EventWindowState.new(:window_state)
end
def event
@window_state
end
def test_changed_mask
assert_nothing_raised do
@window_state.changed_mask
end
end
def test_new_window_state
assert_nothing_raised do
@window_state.new_window_state
end
end
end
class TestSetting < self
include TestAnyMethods
def setup
@setting = Gdk::EventSetting.new(:setting)
end
def event
@setting
end
def test_action
assert_nothing_raised do
@setting.action
end
end
def test_name
assert_nothing_raised do
@setting.name
end
end
end
class TestOwnerChange < self
def setup
@owner_change = Gdk::EventOwnerChange.new(:owner_change)
end
def event
@owner_change
end
def test_owner
assert_nothing_raised do
@owner_change.owner
end
end
def test_reason
assert_nothing_raised do
@owner_change.reason
end
end
def test_selection
assert_nothing_raised do
@owner_change.selection
end
end
def test_time
assert_kind_of(Integer, @owner_change.time)
end
def test_selection_time
assert_kind_of(Integer, @owner_change.selection_time)
end
end
class TestGrabBroken < self
include TestAnyMethods
def setup
@grab_broken = Gdk::EventGrabBroken.new(:grab_broken)
end
def event
@grab_broken
end
def test_keyboard
assert_boolean(@grab_broken.keyboard)
end
def test_implicit
assert_boolean(@grab_broken.implicit)
end
def test_grab_window
assert_nil(@grab_broken.grab_window)
end
end
end
|
module SimplerWorkflow
class Workflow
attr_reader :task_list, :domain, :name, :version, :options, :initial_activity_type
def initialize(domain, name, version, options = {})
Workflow.workflows[[name, version]] ||= begin
default_options = {
:default_task_list => name,
:default_task_start_to_close_timeout => 2 * 60,
:default_execution_start_to_close_timeout => 2 * 60,
:default_child_policy => :terminate
}
@options = default_options.merge(options)
@domain = domain
@name = name
@version = version
self
end
end
def initial_activity(name, version = nil)
if activity = Activity[name.to_sym, version]
@initial_activity_type = activity.to_activity_type
elsif activity = domain.activity_types[name.to_s, version]
@initial_activity_type = activity
end
end
def decision_loop
logger.info("Starting decision loop for #{name.to_s}, #{version} listening to #{task_list}")
domain.decision_tasks.poll(task_list) do |decision_task|
logger.info("Received decision task")
decision_task.new_events.each do |event|
logger.info("Processing #{event.event_type}")
case event.event_type
when 'WorkflowExecutionStarted'
start_execution(decision_task, event)
when 'ActivityTaskCompleted'
activity_completed(decision_task, event)
when 'ActivityTaskFailed'
activity_failed(decision_task, event)
when 'ActivityTaskTimedOut'
activity_timed_out(decision_task, event)
end
end
end
rescue Timeout::Error => e
retry
end
def task_list
@options[:default_task_list][:name].to_s
end
def start_execution(decision_task, event)
logger.info "Starting the execution of the job."
if @on_start_execution && @on_start_execution.respond_to?(:call)
@on_start_execution.call(decision_task, event)
else
decision_task.schedule_activity_task initial_activity_type, :input => event.attributes.input
end
end
def activity_completed(decision_task, event)
if @on_activity_completed && @on_activity_completed.respond_to?(:call)
@on_activity_completed.call(decision_task, event)
else
if event.attributes.keys.include?(:result)
result = Map.from_json(event.attributes.result)
next_activity = result[:next_activity]
activity_type = domain.activity_types[next_activity[:name], next_activity[:version]]
decision_task.schedule_activity_task activity_type, :input => scheduled_event(decision_task, event).attributes.input
else
logger.info("Workflow #{name}, #{version} completed")
decision_task.complete_workflow_execution :result => 'success'
end
end
end
def activity_failed(decision_task, event)
logger.info("Activity failed.")
if @on_activity_failed && @on_activity_failed.respond_to?(:call)
@on_activity_failed.call(decision_task, event)
else
if event.attributes.keys.include?(:details)
details = Map.from_json(event.attributes.details)
case details.failure_policy.to_sym
when :abort
decision_task.cancel_workflow_execution
when :retry
logger.info("Retrying activity #{last_activity(decision_task, event).name} #{last_activity(decision_task, event).version}")
decision_task.schedule_activity_task last_activity(decision_task, event), :input => last_input(decision_task, event)
end
else
decision_task.cancel_workflow_execution
end
end
end
def activity_timed_out(decision_task, event)
logger.info("Activity timed out.")
if @on_activity_timed_out && @on_activity_timed_out.respond_to?(:call)
@on_activity_timed_out.call(decision_task, event)
else
case event.attributes.timeoutType
when 'START_TO_CLOSE', 'SCHEDULE_TO_START', 'SCHEDULE_TO_CLOSE'
logger.info("Retrying activity #{last_activity(decision_task, event).name} #{last_activity(decision_task, event).version} due to timeout.")
decisision_task.schedule_activity_task last_activity(decision_task, event), :input => last_input(decision_task, event)
when 'HEARTBEAT'
decision_task.cancel_workflow_execution
end
end
end
def start_workflow(input, options = {})
options[:input] = input
domain.workflow_types[name.to_s, version].start_execution(options)
end
def on_start_execution(&block)
@on_start_execution = block
end
def on_activity_completed(&block)
@on_activity_completed = block
end
def on_activity_failed(&block)
@on_activity_failed = block
end
def on_activity_timed_out(&block)
@on_activity_timed_out = block
end
def self.[](name, version)
workflows[[name, version]]
end
def self.register(name, version, workflow)
workflows[[name, version]] = workflow
end
def method_missing(meth_name, *args)
if @options.has_key?(meth_name.to_sym)
@options[meth_name.to_sym] = args[0]
else
super
end
end
protected
def self.workflows
@workflows ||= {}
end
def self.swf
SimplerWorkflow.swf
end
def scheduled_event(decision_task, event)
decision_task.events.to_a[event.attributes.scheduled_event_id - 1]
end
def last_activity(decision_task, event)
scheduled_event(decision_task, event).attributes.activity_type
end
def last_input(decision_task, event)
scheduled_event(decision_task, event).attributes.input
end
end
end
Fixed typo.
module SimplerWorkflow
class Workflow
attr_reader :task_list, :domain, :name, :version, :options, :initial_activity_type
def initialize(domain, name, version, options = {})
Workflow.workflows[[name, version]] ||= begin
default_options = {
:default_task_list => name,
:default_task_start_to_close_timeout => 2 * 60,
:default_execution_start_to_close_timeout => 2 * 60,
:default_child_policy => :terminate
}
@options = default_options.merge(options)
@domain = domain
@name = name
@version = version
self
end
end
def initial_activity(name, version = nil)
if activity = Activity[name.to_sym, version]
@initial_activity_type = activity.to_activity_type
elsif activity = domain.activity_types[name.to_s, version]
@initial_activity_type = activity
end
end
def decision_loop
logger.info("Starting decision loop for #{name.to_s}, #{version} listening to #{task_list}")
domain.decision_tasks.poll(task_list) do |decision_task|
logger.info("Received decision task")
decision_task.new_events.each do |event|
logger.info("Processing #{event.event_type}")
case event.event_type
when 'WorkflowExecutionStarted'
start_execution(decision_task, event)
when 'ActivityTaskCompleted'
activity_completed(decision_task, event)
when 'ActivityTaskFailed'
activity_failed(decision_task, event)
when 'ActivityTaskTimedOut'
activity_timed_out(decision_task, event)
end
end
end
rescue Timeout::Error => e
retry
end
def task_list
@options[:default_task_list][:name].to_s
end
def start_execution(decision_task, event)
logger.info "Starting the execution of the job."
if @on_start_execution && @on_start_execution.respond_to?(:call)
@on_start_execution.call(decision_task, event)
else
decision_task.schedule_activity_task initial_activity_type, :input => event.attributes.input
end
end
def activity_completed(decision_task, event)
if @on_activity_completed && @on_activity_completed.respond_to?(:call)
@on_activity_completed.call(decision_task, event)
else
if event.attributes.keys.include?(:result)
result = Map.from_json(event.attributes.result)
next_activity = result[:next_activity]
activity_type = domain.activity_types[next_activity[:name], next_activity[:version]]
decision_task.schedule_activity_task activity_type, :input => scheduled_event(decision_task, event).attributes.input
else
logger.info("Workflow #{name}, #{version} completed")
decision_task.complete_workflow_execution :result => 'success'
end
end
end
def activity_failed(decision_task, event)
logger.info("Activity failed.")
if @on_activity_failed && @on_activity_failed.respond_to?(:call)
@on_activity_failed.call(decision_task, event)
else
if event.attributes.keys.include?(:details)
details = Map.from_json(event.attributes.details)
case details.failure_policy.to_sym
when :abort
decision_task.cancel_workflow_execution
when :retry
logger.info("Retrying activity #{last_activity(decision_task, event).name} #{last_activity(decision_task, event).version}")
decision_task.schedule_activity_task last_activity(decision_task, event), :input => last_input(decision_task, event)
end
else
decision_task.cancel_workflow_execution
end
end
end
def activity_timed_out(decision_task, event)
logger.info("Activity timed out.")
if @on_activity_timed_out && @on_activity_timed_out.respond_to?(:call)
@on_activity_timed_out.call(decision_task, event)
else
case event.attributes.timeoutType
when 'START_TO_CLOSE', 'SCHEDULE_TO_START', 'SCHEDULE_TO_CLOSE'
logger.info("Retrying activity #{last_activity(decision_task, event).name} #{last_activity(decision_task, event).version} due to timeout.")
decision_task.schedule_activity_task last_activity(decision_task, event), :input => last_input(decision_task, event)
when 'HEARTBEAT'
decision_task.cancel_workflow_execution
end
end
end
def start_workflow(input, options = {})
options[:input] = input
domain.workflow_types[name.to_s, version].start_execution(options)
end
def on_start_execution(&block)
@on_start_execution = block
end
def on_activity_completed(&block)
@on_activity_completed = block
end
def on_activity_failed(&block)
@on_activity_failed = block
end
def on_activity_timed_out(&block)
@on_activity_timed_out = block
end
def self.[](name, version)
workflows[[name, version]]
end
def self.register(name, version, workflow)
workflows[[name, version]] = workflow
end
def method_missing(meth_name, *args)
if @options.has_key?(meth_name.to_sym)
@options[meth_name.to_sym] = args[0]
else
super
end
end
protected
def self.workflows
@workflows ||= {}
end
def self.swf
SimplerWorkflow.swf
end
def scheduled_event(decision_task, event)
decision_task.events.to_a[event.attributes.scheduled_event_id - 1]
end
def last_activity(decision_task, event)
scheduled_event(decision_task, event).attributes.activity_type
end
def last_input(decision_task, event)
scheduled_event(decision_task, event).attributes.input
end
end
end
|
#
# bio/pathway.rb - Binary relations and Graph algorithms
#
# Copyright (C) 2001 KATAYAMA Toshiaki <k@bioruby.org>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# $Id: pathway.rb,v 1.7 2001/11/13 02:26:11 katayama Exp $
#
require 'bio/matrix'
module Bio
class Pathway
# Graph (adjacency list) generation from the list of Relation
def initialize(list, undirected = nil)
@undirected = undirected
@index = {}
@label = {}
@graph = {}
list.each do |rel|
append(rel)
end
end
attr_accessor :label
attr_reader :graph, :index
def append(rel)
if @graph[rel.from].nil?
@graph[rel.from] = {}
end
if @graph[rel.to].nil?
@graph[rel.to] = {}
end
@graph[rel.from][rel.to] = rel.relation
@graph[rel.to][rel.from] = rel.relation if @undirected
end
def nodes
@graph.keys.length
end
def edges
edges = 0
@graph.each_value do |v|
edges += v.size
end
edges
end
# Convert adjacency list to adjacency matrix
def to_matrix
@graph.keys.each_with_index do |k, i|
@index[k] = i
end
# note : following code only makes reference to the same []
#
# matrix = Array.new(nodes, Array.new(nodes))
#
# so create each Array object as follows:
matrix = Array.new
nodes.times do |i|
matrix.push(Array.new(nodes))
end
@graph.each do |from, hash|
hash.each do |to, relation|
x = @index[from]
y = @index[to]
matrix[x][y] = relation
end
end
Matrix[*matrix]
end
# Select labeled nodes and generate subgraph
def subgraph
sub_graph = Pathway.new([], @undirected)
@graph.each do |from, hash|
next unless @label[from]
hash.each do |to, relation|
next unless @label[to]
sub_graph.append(Relation.new(from, to, relation))
end
end
return sub_graph
end
def common_subgraph(graph)
raise NotImplementedError
end
def clique
raise NotImplementedError
end
# returns frequency of the nodes having same number of edges as hash
def small_world
freq = Hash.new(0)
@graph.each_value do |v|
freq[v.size] += 1
end
return freq
end
# breadth first search implementation from the textbook
def breadth_first_search(root)
white = -1; gray = 0; black = 1
color = Hash.new(white)
distance = {}
predecessor = {}
color[root] = gray
distance[root] = 0
predecessor[root] = nil
queue = [ root ]
while from = queue.shift
@graph[from].keys.each do |to|
if color[to] == white
color[to] = gray
distance[to] = distance[from] + 1
predecessor[to] = from
queue.push(to)
end
end
color[from] = black
end
return distance, predecessor
end
alias bfs breadth_first_search
# simplified version of bfs (not use colors, not return predecessor)
def bfs_distance(root)
seen = {}
distance = {}
seen[root] = true
distance[root] = 0
queue = [ root ]
while from = queue.shift
@graph[from].keys.each do |to|
unless seen[to]
seen[to] = true
distance[to] = distance[from] + 1
queue.push(to)
end
end
end
return distance
end
# simple application of bfs
def shortest_path(node1, node2)
distance, route = breadth_first_search(node1)
step = distance[node2]
node = node2
path = [ node2 ]
while node != node1 and route[node]
node = route[node]
path.unshift(node)
end
return step, path
end
def dijkstra
raise NotImplementedError
end
def floyd
raise NotImplementedError
end
end
class Relation
def initialize(node1, node2, edge)
@node = [node1, node2]
@edge = edge
end
attr_accessor :node, :edge
def from
@node[0]
end
def to
@node[1]
end
def relation
@edge
end
end
end
if __FILE__ == $0
data = <<END
a b 1
a c 1
b d 1
c e 1
END
ary = []
data.each_line do |line|
ary << Bio::Relation.new(*line.split(/\s+/))
end
p ary
graph = Bio::Pathway.new(ary)
p graph
puts graph.to_matrix
end
=begin
= Bio::Pathway
--- Bio::Pathway#new(list, undirected = nil)
--- Bio::Pathway#label
--- Bio::Pathway#label=(hash)
--- Bio::Pathway#graph
--- Bio::Pathway#index
--- Bio::Pathway#append(rel)
--- Bio::Pathway#nodes
--- Bio::Pathway#edges
--- Bio::Pathway#to_matrix
--- Bio::Pathway#subgraph
--- Bio::Pathway#common_subgraph(graph)
--- Bio::Pathway#clique
--- Bio::Pathway#small_world
--- Bio::Pathway#breadth_first_search(root)
--- Bio::Pathway#bfs(root)
--- Bio::Pathway#bfs_distance(root)
--- Bio::Pathway#shortest_path(node1, node2)
--- Bio::Pathway#dijkstra
--- Bio::Pathway#floyd
= Bio::Relation
--- Bio::Relation#new(node1, node2, edge)
--- Bio::Relation#node
--- Bio::Relation#edge
--- Bio::Relation#from
--- Bio::Relation#to
--- Bio::Relation#relation
=end
add a new method dijkstra (and related initialize_single_source)
#
# bio/pathway.rb - Binary relations and Graph algorithms
#
# Copyright (C) 2001 KATAYAMA Toshiaki <k@bioruby.org>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# $Id: pathway.rb,v 1.8 2001/11/13 07:45:59 shuichi Exp $
#
require 'bio/matrix'
module Bio
class Pathway
INF = 999999
# Graph (adjacency list) generation from the list of Relation
def initialize(list, undirected = nil)
@undirected = undirected
@index = {}
@label = {}
@graph = {}
list.each do |rel|
append(rel)
end
end
attr_accessor :label
attr_reader :graph, :index
def append(rel)
if @graph[rel.from].nil?
@graph[rel.from] = {}
end
if @graph[rel.to].nil?
@graph[rel.to] = {}
end
@graph[rel.from][rel.to] = rel.relation
@graph[rel.to][rel.from] = rel.relation if @undirected
end
def nodes
@graph.keys.length
end
def edges
edges = 0
@graph.each_value do |v|
edges += v.size
end
edges
end
# Convert adjacency list to adjacency matrix
def to_matrix
@graph.keys.each_with_index do |k, i|
@index[k] = i
end
# note : following code only makes reference to the same []
#
# matrix = Array.new(nodes, Array.new(nodes))
#
# so create each Array object as follows:
matrix = Array.new
nodes.times do |i|
matrix.push(Array.new(nodes))
end
@graph.each do |from, hash|
hash.each do |to, relation|
x = @index[from]
y = @index[to]
matrix[x][y] = relation
end
end
Matrix[*matrix]
end
# Select labeled nodes and generate subgraph
def subgraph
sub_graph = Pathway.new([], @undirected)
@graph.each do |from, hash|
next unless @label[from]
hash.each do |to, relation|
next unless @label[to]
sub_graph.append(Relation.new(from, to, relation))
end
end
return sub_graph
end
def common_subgraph(graph)
raise NotImplementedError
end
def clique
raise NotImplementedError
end
# returns frequency of the nodes having same number of edges as hash
def small_world
freq = Hash.new(0)
@graph.each_value do |v|
freq[v.size] += 1
end
return freq
end
# breadth first search implementation from the textbook
def breadth_first_search(root)
white = -1; gray = 0; black = 1
color = Hash.new(white)
distance = {}
predecessor = {}
color[root] = gray
distance[root] = 0
predecessor[root] = nil
queue = [ root ]
while from = queue.shift
@graph[from].keys.each do |to|
if color[to] == white
color[to] = gray
distance[to] = distance[from] + 1
predecessor[to] = from
queue.push(to)
end
end
color[from] = black
end
return distance, predecessor
end
alias bfs breadth_first_search
# simplified version of bfs (not use colors, not return predecessor)
def bfs_distance(root)
seen = {}
distance = {}
seen[root] = true
distance[root] = 0
queue = [ root ]
while from = queue.shift
@graph[from].keys.each do |to|
unless seen[to]
seen[to] = true
distance[to] = distance[from] + 1
queue.push(to)
end
end
end
return distance
end
# simple application of bfs
def shortest_path(node1, node2)
distance, route = breadth_first_search(node1)
step = distance[node2]
node = node2
path = [ node2 ]
while node != node1 and route[node]
node = route[node]
path.unshift(node)
end
return step, path
end
def dijkstra(root)
distance, predecessor = initialize_single_source(root)
@graph[root].each do |k, v|
distance[k] = v
predecessor[k] = root
end
queue = distance.dup
queue.delete(root)
while queue.size != 0
ary = queue.to_a.sort{|a, b| a[1] <=> b[1]} # extranct a node having minimal distance
u = ary[0][0]
@graph[u].each do |k, v|
if distance[k] > distance[u] + @graph[u][k] # relaxing procedure of root -> 'u' -> 'k'
distance[k] = distance[u] + @graph[u][k]
predecessor[k] = u
end
end
queue.delete(u)
end
return distance, predecessor
end
def floyd
raise NotImplementedError
end
def initialize_single_source(root)
distance = {}
predecessor = {}
@graph.keys.each do |k|
distance[k] = INF
predecessor[k] = nil
end
distance[root] = 0
return distance, predecessor
end
end
class Relation
def initialize(node1, node2, edge)
@node = [node1, node2]
@edge = edge
end
attr_accessor :node, :edge
def from
@node[0]
end
def to
@node[1]
end
def relation
@edge
end
end
end
if __FILE__ == $0
data = <<END
a b 1
a c 1
b d 1
c e 1
END
ary = []
data.each_line do |line|
ary << Bio::Relation.new(*line.split(/\s+/))
end
p ary
graph = Bio::Pathway.new(ary)
p graph
puts graph.to_matrix
end
=begin
= Bio::Pathway
--- Bio::Pathway#new(list, undirected = nil)
--- Bio::Pathway#label
--- Bio::Pathway#label=(hash)
--- Bio::Pathway#graph
--- Bio::Pathway#index
--- Bio::Pathway#append(rel)
--- Bio::Pathway#nodes
--- Bio::Pathway#edges
--- Bio::Pathway#to_matrix
--- Bio::Pathway#subgraph
--- Bio::Pathway#common_subgraph(graph)
--- Bio::Pathway#clique
--- Bio::Pathway#small_world
--- Bio::Pathway#breadth_first_search(root)
--- Bio::Pathway#bfs(root)
--- Bio::Pathway#bfs_distance(root)
--- Bio::Pathway#shortest_path(node1, node2)
--- Bio::Pathway#dijkstra
--- Bio::Pathway#floyd
= Bio::Relation
--- Bio::Relation#new(node1, node2, edge)
--- Bio::Relation#node
--- Bio::Relation#edge
--- Bio::Relation#from
--- Bio::Relation#to
--- Bio::Relation#relation
=end
|
module Sisimai::Bite::Email
# Sisimai::Bite::Email::GSuite parses a bounce email which created by G Suite.
# Methods in the module are called from only Sisimai::Message.
module GSuite
class << self
# Imported from p5-Sisimail/lib/Sisimai/Bite/Email/GSuite.pm
require 'sisimai/bite/email'
Indicators = Sisimai::Bite::Email.INDICATORS
MarkingsOf = {
message: %r/\A[*][*][ ].+[ ][*][*]\z/,
rfc822: %r{\AContent-Type:[ ]*(?:message/rfc822|text/rfc822-headers)\z},
error: %r/\AThe[ ]response([ ]from[ ]the[ ]remote[ ]server)?[ ]was:\z/,
html: %r{\AContent-Type:[ ]*text/html;[ ]*charset=['"]?(?:UTF|utf)[-]8['"]?\z},
}.freeze
MessagesOf = {
userunknown: ["because the address couldn't be found"],
notaccept: ['Null MX'],
networkerror: [' responded with code NXDOMAIN'],
}.freeze
def description; return 'G Suite: https://gsuite.google.com'; end
def smtpagent; return Sisimai::Bite.smtpagent(self); end
def headerlist; return ['X-Gm-Message-State']; end
# Parse bounce messages from G Suite (Transfer from G Suite to a destinaion host)
# @param [Hash] mhead Message headers of a bounce email
# @options mhead [String] from From header
# @options mhead [String] date Date header
# @options mhead [String] subject Subject header
# @options mhead [Array] received Received headers
# @options mhead [String] others Other required headers
# @param [String] mbody Message body of a bounce email
# @return [Hash, Nil] Bounce data list and message/rfc822
# part or nil if it failed to parse or
# the arguments are missing
def scan(mhead, mbody)
return nil unless mhead
return nil unless mbody
return nil unless mhead['from'].end_with?('<mailer-daemon@googlemail.com>')
return nil unless mhead['subject'].start_with?('Delivery Status Notification')
return nil unless mhead['x-gm-message-state']
require 'sisimai/address'
dscontents = [Sisimai::Bite.DELIVERYSTATUS]
hasdivided = mbody.split("\n")
rfc822list = [] # (Array) Each line in message/rfc822 part string
blanklines = 0 # (Integer) The number of blank lines
readcursor = 0 # (Integer) Points the current cursor position
recipients = 0 # (Integer) The number of 'Final-Recipient' header
endoferror = false # (Integer) Flag for a blank line after error messages
anotherset = {} # (Hash) Another error information
emptylines = 0 # (Integer) The number of empty lines
connvalues = 0 # (Integer) Flag, 1 if all the value of connheader have been set
connheader = {
'date' => '', # The value of Arrival-Date header
'lhost' => '', # The value of Reporting-MTA header
}
v = nil
while e = hasdivided.shift do
if readcursor.zero?
# Beginning of the bounce message or delivery status part
readcursor |= Indicators[:deliverystatus] if e =~ MarkingsOf[:message]
end
if (readcursor & Indicators[:'message-rfc822']).zero?
# Beginning of the original message part
if e =~ MarkingsOf[:rfc822]
readcursor |= Indicators[:'message-rfc822']
next
end
end
if readcursor & Indicators[:'message-rfc822'] > 0
# After "message/rfc822"
if e.empty?
blanklines += 1
break if blanklines > 1
next
end
rfc822list << e
else
# Before "message/rfc822"
next if (readcursor & Indicators[:deliverystatus]).zero?
if connvalues == connheader.keys.size
# Final-Recipient: rfc822; kijitora@example.de
# Action: failed
# Status: 5.0.0
# Remote-MTA: dns; 192.0.2.222 (192.0.2.222, the server for the domain.)
# Diagnostic-Code: smtp; 550 #5.1.0 Address rejected.
# Last-Attempt-Date: Fri, 24 Mar 2017 23:34:10 -0700 (PDT)
v = dscontents[-1]
if cv = e.match(/\AFinal-Recipient:[ ]*(?:RFC|rfc)822;[ ]*(.+)\z/)
# Final-Recipient: rfc822; kijitora@example.de
if v['recipient']
# There are multiple recipient addresses in the message body.
dscontents << Sisimai::Bite.DELIVERYSTATUS
v = dscontents[-1]
end
v['recipient'] = cv[1]
recipients += 1
elsif cv = e.match(/\AAction:[ ]*(.+)\z/)
# Action: failed
v['action'] = cv[1].downcase
elsif cv = e.match(/\AStatus:[ ]*(\d[.]\d+[.]\d+)/)
# Status: 5.0.0
v['status'] = cv[1]
elsif cv = e.match(/\ARemote-MTA:[ ]*(?:DNS|dns);[ ]*(.+)\z/)
# Remote-MTA: dns; 192.0.2.222 (192.0.2.222, the server for the domain.)
v['rhost'] = cv[1].downcase
v['rhost'] = '' if v['rhost'] =~ /\A\s+\z/ # Remote-MTA: DNS;
elsif cv = e.match(/\ALast-Attempt-Date:[ ]*(.+)\z/)
# Last-Attempt-Date: Fri, 24 Mar 2017 23:34:10 -0700 (PDT)
v['date'] = cv[1]
else
if cv = e.match(/\ADiagnostic-Code:[ ]*(.+?);[ ]*(.+)\z/)
# Diagnostic-Code: smtp; 550 #5.1.0 Address rejected.
v['spec'] = cv[1].upcase
v['diagnosis'] = cv[2]
else
# Append error messages continued from the previous line
if endoferror == false && v['diagnosis'].to_s.size > 0
endoferror ||= true if e.empty?
endoferror ||= true if e.start_with?('--')
next if endoferror
next unless e.start_with?(' ')
v['diagnosis'] << e
end
end
end
else
# Reporting-MTA: dns; googlemail.com
# Received-From-MTA: dns; sironeko@example.jp
# Arrival-Date: Fri, 24 Mar 2017 23:34:07 -0700 (PDT)
# X-Original-Message-ID: <06C1ED5C-7E02-4036-AEE1-AA448067FB2C@example.jp>
if cv = e.match(/\AReporting-MTA:[ ]*(?:DNS|dns);[ ]*(.+)\z/)
# Reporting-MTA: dns; mx.example.jp
next if connheader['lhost'].size > 0
connheader['lhost'] = cv[1].downcase
connvalues += 1
elsif cv = e.match(/\AArrival-Date:[ ]*(.+)\z/)
# Arrival-Date: Wed, 29 Apr 2009 16:03:18 +0900
next if connheader['date'].size > 0
connheader['date'] = cv[1]
connvalues += 1
else
# Detect SMTP session error or connection error
if e =~ MarkingsOf[:error]
# The response from the remote server was:
anotherset['diagnosis'] << e
else
# ** Address not found **
#
# Your message wasn't delivered to * because the address couldn't be found.
# Check for typos or unnecessary spaces and try again.
#
# The response from the remote server was:
# 550 #5.1.0 Address rejected.
next if e =~ MarkingsOf[:html]
if anotherset['diagnosis']
# Continued error messages from the previous line like
# "550 #5.1.0 Address rejected."
next if emptylines > 5
if e.empty?
# Count and next()
emptylines += 1
next
end
anotherset['diagnosis'] << ' ' << e
else
# ** Address not found **
#
# Your message wasn't delivered to * because the address couldn't be found.
# Check for typos or unnecessary spaces and try again.
next if e.empty?
next unless e =~ MarkingsOf[:message]
anotherset['diagnosis'] = e
end
end
end
end
end
end
return nil if recipients.zero?
require 'sisimai/string'
require 'sisimai/smtp/reply'
require 'sisimai/smtp/status'
dscontents.map do |e|
# Set default values if each value is empty.
connheader.each_key { |a| e[a] ||= connheader[a] || '' }
if anotherset['diagnosis']
# Copy alternative error message
e['diagnosis'] = anotherset['diagnosis'] unless e['diagnosis']
if e['diagnosis'] =~ /\A\d+\z/
e['diagnosis'] = anotherset['diagnosis']
else
# More detailed error message is in "anotherset"
as = nil # status
ar = nil # replycode
e['status'] ||= ''
e['replycode'] ||= ''
if e['status'] == '' || e['status'].start_with?('4.0.0', '5.0.0')
# Check the value of D.S.N. in anotherset
as = Sisimai::SMTP::Status.find(anotherset['diagnosis'])
if as.size > 0 && as[-3, 3] != '0.0'
# The D.S.N. is neither an empty nor *.0.0
e['status'] = as
end
end
if e['replycode'].empty? || e['replycode'].start_with?('400', '500')
# Check the value of SMTP reply code in anotherset
ar = Sisimai::SMTP::Reply.find(anotherset['diagnosis'])
if ar.size > 0 && ar[-2, 2].to_i != 0
# The SMTP reply code is neither an empty nor *00
e['replycode'] = ar
end
end
if (as || ar) && (anotherset['diagnosis'].size > e['diagnosis'].size)
# Update the error message in e['diagnosis']
e['diagnosis'] = anotherset['diagnosis']
end
end
end
e['diagnosis'] = Sisimai::String.sweep(e['diagnosis'])
e['agent'] = self.smtpagent
MessagesOf.each_key do |r|
# Guess an reason of the bounce
next unless MessagesOf[r].find { |a| e['diagnosis'].include?(a) }
e['reason'] = r.to_s
break
end
end
rfc822part = Sisimai::RFC5322.weedout(rfc822list)
return { 'ds' => dscontents, 'rfc822' => rfc822part }
end
end
end
end
Update an error message pattern for "userunknown" on GSuite
module Sisimai::Bite::Email
# Sisimai::Bite::Email::GSuite parses a bounce email which created by G Suite.
# Methods in the module are called from only Sisimai::Message.
module GSuite
class << self
# Imported from p5-Sisimail/lib/Sisimai/Bite/Email/GSuite.pm
require 'sisimai/bite/email'
Indicators = Sisimai::Bite::Email.INDICATORS
MarkingsOf = {
message: %r/\A[*][*][ ].+[ ][*][*]\z/,
rfc822: %r{\AContent-Type:[ ]*(?:message/rfc822|text/rfc822-headers)\z},
error: %r/\AThe[ ]response([ ]from[ ]the[ ]remote[ ]server)?[ ]was:\z/,
html: %r{\AContent-Type:[ ]*text/html;[ ]*charset=['"]?(?:UTF|utf)[-]8['"]?\z},
}.freeze
MessagesOf = {
userunknown: ["because the address couldn't be found. Check for typos or unnecessary spaces and try again."],
notaccept: ['Null MX'],
networkerror: [' responded with code NXDOMAIN'],
}.freeze
def description; return 'G Suite: https://gsuite.google.com'; end
def smtpagent; return Sisimai::Bite.smtpagent(self); end
def headerlist; return ['X-Gm-Message-State']; end
# Parse bounce messages from G Suite (Transfer from G Suite to a destinaion host)
# @param [Hash] mhead Message headers of a bounce email
# @options mhead [String] from From header
# @options mhead [String] date Date header
# @options mhead [String] subject Subject header
# @options mhead [Array] received Received headers
# @options mhead [String] others Other required headers
# @param [String] mbody Message body of a bounce email
# @return [Hash, Nil] Bounce data list and message/rfc822
# part or nil if it failed to parse or
# the arguments are missing
def scan(mhead, mbody)
return nil unless mhead
return nil unless mbody
return nil unless mhead['from'].end_with?('<mailer-daemon@googlemail.com>')
return nil unless mhead['subject'].start_with?('Delivery Status Notification')
return nil unless mhead['x-gm-message-state']
require 'sisimai/address'
dscontents = [Sisimai::Bite.DELIVERYSTATUS]
hasdivided = mbody.split("\n")
rfc822list = [] # (Array) Each line in message/rfc822 part string
blanklines = 0 # (Integer) The number of blank lines
readcursor = 0 # (Integer) Points the current cursor position
recipients = 0 # (Integer) The number of 'Final-Recipient' header
endoferror = false # (Integer) Flag for a blank line after error messages
anotherset = {} # (Hash) Another error information
emptylines = 0 # (Integer) The number of empty lines
connvalues = 0 # (Integer) Flag, 1 if all the value of connheader have been set
connheader = {
'date' => '', # The value of Arrival-Date header
'lhost' => '', # The value of Reporting-MTA header
}
v = nil
while e = hasdivided.shift do
if readcursor.zero?
# Beginning of the bounce message or delivery status part
readcursor |= Indicators[:deliverystatus] if e =~ MarkingsOf[:message]
end
if (readcursor & Indicators[:'message-rfc822']).zero?
# Beginning of the original message part
if e =~ MarkingsOf[:rfc822]
readcursor |= Indicators[:'message-rfc822']
next
end
end
if readcursor & Indicators[:'message-rfc822'] > 0
# After "message/rfc822"
if e.empty?
blanklines += 1
break if blanklines > 1
next
end
rfc822list << e
else
# Before "message/rfc822"
next if (readcursor & Indicators[:deliverystatus]).zero?
if connvalues == connheader.keys.size
# Final-Recipient: rfc822; kijitora@example.de
# Action: failed
# Status: 5.0.0
# Remote-MTA: dns; 192.0.2.222 (192.0.2.222, the server for the domain.)
# Diagnostic-Code: smtp; 550 #5.1.0 Address rejected.
# Last-Attempt-Date: Fri, 24 Mar 2017 23:34:10 -0700 (PDT)
v = dscontents[-1]
if cv = e.match(/\AFinal-Recipient:[ ]*(?:RFC|rfc)822;[ ]*(.+)\z/)
# Final-Recipient: rfc822; kijitora@example.de
if v['recipient']
# There are multiple recipient addresses in the message body.
dscontents << Sisimai::Bite.DELIVERYSTATUS
v = dscontents[-1]
end
v['recipient'] = cv[1]
recipients += 1
elsif cv = e.match(/\AAction:[ ]*(.+)\z/)
# Action: failed
v['action'] = cv[1].downcase
elsif cv = e.match(/\AStatus:[ ]*(\d[.]\d+[.]\d+)/)
# Status: 5.0.0
v['status'] = cv[1]
elsif cv = e.match(/\ARemote-MTA:[ ]*(?:DNS|dns);[ ]*(.+)\z/)
# Remote-MTA: dns; 192.0.2.222 (192.0.2.222, the server for the domain.)
v['rhost'] = cv[1].downcase
v['rhost'] = '' if v['rhost'] =~ /\A\s+\z/ # Remote-MTA: DNS;
elsif cv = e.match(/\ALast-Attempt-Date:[ ]*(.+)\z/)
# Last-Attempt-Date: Fri, 24 Mar 2017 23:34:10 -0700 (PDT)
v['date'] = cv[1]
else
if cv = e.match(/\ADiagnostic-Code:[ ]*(.+?);[ ]*(.+)\z/)
# Diagnostic-Code: smtp; 550 #5.1.0 Address rejected.
v['spec'] = cv[1].upcase
v['diagnosis'] = cv[2]
else
# Append error messages continued from the previous line
if endoferror == false && v['diagnosis'].to_s.size > 0
endoferror ||= true if e.empty?
endoferror ||= true if e.start_with?('--')
next if endoferror
next unless e.start_with?(' ')
v['diagnosis'] << e
end
end
end
else
# Reporting-MTA: dns; googlemail.com
# Received-From-MTA: dns; sironeko@example.jp
# Arrival-Date: Fri, 24 Mar 2017 23:34:07 -0700 (PDT)
# X-Original-Message-ID: <06C1ED5C-7E02-4036-AEE1-AA448067FB2C@example.jp>
if cv = e.match(/\AReporting-MTA:[ ]*(?:DNS|dns);[ ]*(.+)\z/)
# Reporting-MTA: dns; mx.example.jp
next if connheader['lhost'].size > 0
connheader['lhost'] = cv[1].downcase
connvalues += 1
elsif cv = e.match(/\AArrival-Date:[ ]*(.+)\z/)
# Arrival-Date: Wed, 29 Apr 2009 16:03:18 +0900
next if connheader['date'].size > 0
connheader['date'] = cv[1]
connvalues += 1
else
# Detect SMTP session error or connection error
if e =~ MarkingsOf[:error]
# The response from the remote server was:
anotherset['diagnosis'] << e
else
# ** Address not found **
#
# Your message wasn't delivered to * because the address couldn't be found.
# Check for typos or unnecessary spaces and try again.
#
# The response from the remote server was:
# 550 #5.1.0 Address rejected.
next if e =~ MarkingsOf[:html]
if anotherset['diagnosis']
# Continued error messages from the previous line like
# "550 #5.1.0 Address rejected."
next if emptylines > 5
if e.empty?
# Count and next()
emptylines += 1
next
end
anotherset['diagnosis'] << ' ' << e
else
# ** Address not found **
#
# Your message wasn't delivered to * because the address couldn't be found.
# Check for typos or unnecessary spaces and try again.
next if e.empty?
next unless e =~ MarkingsOf[:message]
anotherset['diagnosis'] = e
end
end
end
end
end
end
return nil if recipients.zero?
require 'sisimai/string'
require 'sisimai/smtp/reply'
require 'sisimai/smtp/status'
dscontents.map do |e|
# Set default values if each value is empty.
connheader.each_key { |a| e[a] ||= connheader[a] || '' }
if anotherset['diagnosis']
# Copy alternative error message
e['diagnosis'] = anotherset['diagnosis'] unless e['diagnosis']
if e['diagnosis'] =~ /\A\d+\z/
e['diagnosis'] = anotherset['diagnosis']
else
# More detailed error message is in "anotherset"
as = nil # status
ar = nil # replycode
e['status'] ||= ''
e['replycode'] ||= ''
if e['status'] == '' || e['status'].start_with?('4.0.0', '5.0.0')
# Check the value of D.S.N. in anotherset
as = Sisimai::SMTP::Status.find(anotherset['diagnosis'])
if as.size > 0 && as[-3, 3] != '0.0'
# The D.S.N. is neither an empty nor *.0.0
e['status'] = as
end
end
if e['replycode'].empty? || e['replycode'].start_with?('400', '500')
# Check the value of SMTP reply code in anotherset
ar = Sisimai::SMTP::Reply.find(anotherset['diagnosis'])
if ar.size > 0 && ar[-2, 2].to_i != 0
# The SMTP reply code is neither an empty nor *00
e['replycode'] = ar
end
end
if (as || ar) && (anotherset['diagnosis'].size > e['diagnosis'].size)
# Update the error message in e['diagnosis']
e['diagnosis'] = anotherset['diagnosis']
end
end
end
e['diagnosis'] = Sisimai::String.sweep(e['diagnosis'])
e['agent'] = self.smtpagent
MessagesOf.each_key do |r|
# Guess an reason of the bounce
next unless MessagesOf[r].find { |a| e['diagnosis'].include?(a) }
e['reason'] = r.to_s
break
end
end
rfc822part = Sisimai::RFC5322.weedout(rfc822list)
return { 'ds' => dscontents, 'rfc822' => rfc822part }
end
end
end
end
|
# encoding: utf-8
module SmsWrapper
module ClassMethods
def gate(klass, *args)
gates[klass.to_s] = {
klass: klass,
args: args
}
use_gate(klass) unless exists?
self
end # gate
def default(klass)
use_gate(klass)
self
end # default
def get(klass)
gates[klass.to_s]
end # get
def turn_on
@active = true
active_gate.turn_on if exists?
self
end # turn_on
def turn_off
@active = false
active_gate.turn_off if exists?
self
end # turn_off
def debug_on
@debug = true
active_gate.debug_on if exists?
self
end # debug_on
def debug_off
@debug = false
active_gate.debug_off if exists?
self
end # debug_off
def turn_on?
@active === true
end # turn_on?
def debug_on?
@debug === true
end # debug_on?
def message(*args)
if exists?
res = active_gate.message(args)
if active_gate.error?(res)
puts "[SMS]. Ошибка при оправки сообщения (#{active_gate.name})"
puts "[SMS]. #{res.inspect}"
else
if block_given?
yield(active_gate, res)
return
else
return active_gate, res
end
end # unless
end # if
gates.each do |klass, value|
use_gate(klass)
res = active_gate.message(args)
if active_gate.error?(res)
puts "[SMS]. Ошибка при оправки сообщения (#{active_gate.name})"
puts "[SMS]. #{res.inspect}"
else
if block_given?
yield(active_gate, res)
return
else
return active_gate, res
end
end # unless
end # each
nil
end # message
def error?(req)
exists? ? active_gate.error?(req) : req.is_a?(::StandardError)
end # error?
private
def use_gate(klass)
@active_gate.logout if @active_gate
@active_gate = new(klass)
self
end # use_gate
def exists?
!@active_gate.nil?
end # exists?
def active_gate
exists? ? @active_gate : nil
end # active_gate
def gates
@gates ||= {}
@gates
end # gates
end # ClassMethods
end # SmsWrapper
Исправление ошибок
# encoding: utf-8
module SmsWrapper
module ClassMethods
def gate(klass, *args)
gates[klass.to_s] = {
klass: klass,
args: args
}
use_gate(klass) unless exists?
self
end # gate
def default(klass)
use_gate(klass)
self
end # default
def get(klass)
gates[klass.to_s]
end # get
def turn_on
@active = true
active_gate.turn_on if exists?
self
end # turn_on
def turn_off
@active = false
active_gate.turn_off if exists?
self
end # turn_off
def debug_on
@debug = true
active_gate.debug_on if exists?
self
end # debug_on
def debug_off
@debug = false
active_gate.debug_off if exists?
self
end # debug_off
def turn_on?
@active === true
end # turn_on?
def debug_on?
@debug === true
end # debug_on?
def message(*args)
if exists?
res = active_gate.send(:message, *args)
if active_gate.error?(res)
puts "[SMS]. Ошибка при оправки сообщения (#{active_gate.name})"
puts "[SMS]. #{res.inspect}"
else
if block_given?
yield(active_gate, res)
return
else
return active_gate, res
end
end # unless
end # if
gates.each do |klass, value|
use_gate(klass)
res = active_gate.send(:message, *args)
if active_gate.error?(res)
puts "[SMS]. Ошибка при оправки сообщения (#{active_gate.name})"
puts "[SMS]. #{res.inspect}"
else
if block_given?
yield(active_gate, res)
return
else
return active_gate, res
end
end # unless
end # each
nil
end # message
def error?(req)
exists? ? active_gate.error?(req) : req.is_a?(::StandardError)
end # error?
private
def use_gate(klass)
@active_gate.logout if @active_gate
@active_gate = new(klass)
self
end # use_gate
def exists?
!@active_gate.nil?
end # exists?
def active_gate
exists? ? @active_gate : nil
end # active_gate
def gates
@gates ||= {}
@gates
end # gates
end # ClassMethods
end # SmsWrapper
|
#############################################################################
# Copyright © 2010 Dan Wanek <dan.wanek@gmail.com>
#
#
# This file is part of Viewpoint.
#
# Viewpoint is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# Viewpoint is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with Viewpoint. If not, see <http://www.gnu.org/licenses/>.
#############################################################################
require 'handsoap'
require 'soap/handsoap/builder'
require 'soap/handsoap/parser'
Handsoap.http_driver = :http_client
module Viewpoint
module EWS
module SOAP
class ExchangeWebService < Handsoap::Service
include Viewpoint::EWS::SOAP
SOAP_ACTION_PREFIX = "http://schemas.microsoft.com/exchange/services/2006/messages"
@@raw_soap = false
@@http_options = nil
def initialize()
if $DEBUG
@debug = File.new('ews_debug.out', 'w')
@debug.sync = true
end
end
def self.set_auth(user,pass)
@@user = user
@@pass = pass
end
# Turn off parsing and just return the soap response
def self.raw_soap!
@@raw_soap = true
end
# Set various HTTP options like ssl_ca_trust, etc
def self.set_http_options(option_hash)
if @@http_options.nil?
@@http_options = option_hash
else
@@http_options.merge!(option_hash)
end
end
# ********* Begin Hooks *********
def on_create_document(doc)
doc.alias NS_EWS_TYPES, 'http://schemas.microsoft.com/exchange/services/2006/types'
doc.alias NS_EWS_MESSAGES, 'http://schemas.microsoft.com/exchange/services/2006/messages'
header = doc.find('Header')
header.add("#{NS_EWS_TYPES}:RequestServerVersion") { |rsv| rsv.set_attr('Version','Exchange2007_SP1') }
end
# Adds knowledge of namespaces to the response object. These have to be identical to the
# URIs returned in the XML response. For example, I had some issues with the 'soap'
# namespace because my original URI did not end in a '/'
# @example
# Won't work: http://schemas.xmlsoap.org/soap/envelope
# Works: http://schemas.xmlsoap.org/soap/envelope/
def on_response_document(doc)
doc.add_namespace NS_SOAP, 'http://schemas.xmlsoap.org/soap/envelope/'
doc.add_namespace NS_EWS_TYPES, 'http://schemas.microsoft.com/exchange/services/2006/types'
doc.add_namespace NS_EWS_MESSAGES, 'http://schemas.microsoft.com/exchange/services/2006/messages'
end
def on_after_create_http_request(req)
begin
req.set_auth @@user, @@pass
rescue NameError => e
raise EwsLoginError, "Please remember to set your credential information."
end
end
def on_http_error(response)
raise EwsLoginError, "Failed to login to EWS at #{uri}. Please check your credentials." if(response.status == 401)
end
# ********** End Hooks **********
# Resolve ambiguous e-mail addresses and display names
# @see http://msdn.microsoft.com/en-us/library/aa565329.aspx ResolveNames
# @see http://msdn.microsoft.com/en-us/library/aa581054.aspx UnresolvedEntry
#
# @param [String] name an unresolved entry
# @param [Boolean] full_contact_data whether or not to return full contact info
# @param [Hash] opts optional parameters to this method
# @option opts [String] :search_scope where to seach for this entry, one of
# SOAP::Contacts, SOAP::ActiveDirectory, SOAP::ActiveDirectoryContacts (default),
# SOAP::ContactsActiveDirectory
# @option opts [String, FolderId] :parent_folder_id either the name of a folder or
# it's numerical ID. @see http://msdn.microsoft.com/en-us/library/aa565998.aspx
def resolve_names(name, full_contact_data = true, opts = {})
action = "#{SOAP_ACTION_PREFIX}/ResolveNames"
resp = invoke("#{NS_EWS_MESSAGES}:ResolveNames", action) do |root|
build!(root) do
root.set_attr('ReturnFullContactData',full_contact_data)
root.add("#{NS_EWS_MESSAGES}:UnresolvedEntry",name)
end
end
parse!(resp)
end
# Exposes the full membership of distribution lists.
# @see http://msdn.microsoft.com/en-us/library/aa494152.aspx ExpandDL
#
# @param [String] dist_email The e-mail address associated with the Distribution List
# @todo Fully support all of the ExpandDL operations. Today it just supports
# taking an e-mail address as an argument
def expand_dl(dist_email)
action = "#{SOAP_ACTION_PREFIX}/ExpandDL"
resp = invoke("#{NS_EWS_MESSAGES}:ExpandDL", action) do |root|
build!(root) do
mailbox!(root, {:email_address => {:text => dist_email}})
end
end
parse!(resp)
end
# Find subfolders of an identified folder
# @see http://msdn.microsoft.com/en-us/library/aa563918.aspx
#
# @param [Array] parent_folder_ids An Array of folder ids, either a
# DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @param [String] traversal Shallow/Deep/SoftDeleted
# @param [Hash] folder_shape defines the FolderShape node
# See: http://msdn.microsoft.com/en-us/library/aa494311.aspx
# @option folder_shape [String] :base_shape IdOnly/Default/AllProperties
# @option folder_shape :additional_properties
# See: http://msdn.microsoft.com/en-us/library/aa563810.aspx
# @param [Hash] opts optional parameters to this method
def find_folder(parent_folder_ids = [:root], traversal = 'Shallow', folder_shape = {:base_shape => 'Default'}, opts = {})
action = "#{SOAP_ACTION_PREFIX}/FindFolder"
resp = invoke("#{NS_EWS_MESSAGES}:FindFolder", action) do |root|
build!(root) do
restriction = opts.delete(:restriction)
root.set_attr('Traversal', traversal)
folder_shape!(root, folder_shape)
root.add("#{NS_EWS_MESSAGES}:Restriction") do |r|
add_hierarchy!(r, restriction)
end unless restriction.nil?
parent_folder_ids!(root, parent_folder_ids)
end
end
parse!(resp)
end
# Identifies items that are located in a specified folder
# @see http://msdn.microsoft.com/en-us/library/aa566107.aspx
#
# @param [Array] parent_folder_ids An Array of folder ids, either a
# DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @param [String] traversal Shallow/Deep/SoftDeleted
# @param [Hash] item_shape defines the FolderShape node
# See: http://msdn.microsoft.com/en-us/library/aa494311.aspx
# @option item_shape [String] :base_shape IdOnly/Default/AllProperties
# @option item_shape :additional_properties
# See: http://msdn.microsoft.com/en-us/library/aa563810.aspx
# @param [Hash] opts optional parameters to this method
# @option opts [Hash] :calendar_view Limit FindItem by a start and end date
# {:calendar_view => {:max_entries_returned => 2, :start => <DateTime Obj>, :end => <DateTime Obj>}}
def find_item(parent_folder_ids, traversal = 'Shallow', item_shape = {:base_shape => 'Default'}, opts = {})
action = "#{SOAP_ACTION_PREFIX}/FindItem"
resp = invoke("#{NS_EWS_MESSAGES}:FindItem", action) do |root|
build!(root) do
root.set_attr('Traversal', traversal)
item_shape!(root, item_shape)
query_strings = opts.delete(:query_string)
restriction = opts.delete(:restriction)
if(opts.has_key?(:calendar_view))
cal_view = opts[:calendar_view]
cal_view.each_pair do |k,v|
cal_view[k] = v.to_s
end
end
add_hierarchy!(root, opts, NS_EWS_MESSAGES)
#query_strings!(query_strings)
root.add("#{NS_EWS_MESSAGES}:Restriction") do |r|
add_hierarchy!(r, restriction)
end unless restriction.nil?
parent_folder_ids!(root, parent_folder_ids)
end
end
parse!(resp)
end
# Gets folders from the Exchange store
# @see http://msdn.microsoft.com/en-us/library/aa580274.aspx
#
# @param [Array] folder_ids An Array of folder ids, either a
# DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @param [Hash] folder_shape defines the FolderShape node
# See: http://msdn.microsoft.com/en-us/library/aa494311.aspx
# @option folder_shape [String] :base_shape IdOnly/Default/AllProperties
# @option folder_shape :additional_properties
# See: http://msdn.microsoft.com/en-us/library/aa563810.aspx
# @param [String,nil] act_as User to act on behalf as. This user must have been
# given delegate access to this folder or else this operation will fail.
# @param [Hash] opts optional parameters to this method
def get_folder(folder_ids, folder_shape = {:base_shape => 'Default'}, act_as = nil)
action = "#{SOAP_ACTION_PREFIX}/GetFolder"
resp = invoke("#{NS_EWS_MESSAGES}:GetFolder", action) do |root|
build!(root) do
folder_shape!(root, folder_shape)
folder_ids!(root, folder_ids, act_as)
end
end
parse!(resp)
end
def convert_id
action = "#{SOAP_ACTION_PREFIX}/ConvertId"
resp = invoke("#{NS_EWS_MESSAGES}:ConvertId", action) do |convert_id|
build_convert_id!(convert_id)
end
parse_convert_id(resp)
end
# Creates folders, calendar folders, contacts folders, tasks folders, and search folders.
# @see http://msdn.microsoft.com/en-us/library/aa563574.aspx CreateFolder
#
# @param [String,Symbol] parent_folder_id either the name of a folder or it's
# numerical ID. See: http://msdn.microsoft.com/en-us/library/aa565998.aspx
# @param [Array,String] folder_name The display name for the new folder or folders
def create_folder(parent_folder_id, folder_name)
action = "#{SOAP_ACTION_PREFIX}/CreateFolder"
resp = invoke("#{NS_EWS_MESSAGES}:CreateFolder", action) do |root|
build!(root) do
root.add("#{NS_EWS_MESSAGES}:ParentFolderId") do |pfid|
folder_id!(pfid, parent_folder_id)
end
folder_name = (folder_name.is_a?(Array)) ? folder_name : [folder_name]
root.add("#{NS_EWS_MESSAGES}:Folders") do |fids|
folder_name.each do |f|
add_hierarchy!(fids, {:folder => {:display_name => {:text => f}}})
end
end
end
end
parse!(resp)
end
# Deletes folders from a mailbox.
# @see http://msdn.microsoft.com/en-us/library/aa564767.aspx DeleteFolder
#
# @param [Array,String,Symbol] folder_id either the name of a folder or it's
# numerical ID. See: http://msdn.microsoft.com/en-us/library/aa565998.aspx
# @param [String,nil] delete_type Type of delete to do: HardDelete/SoftDelete/MoveToDeletedItems
def delete_folder(folder_id, delete_type = 'MoveToDeletedItems')
action = "#{SOAP_ACTION_PREFIX}/DeleteFolder"
resp = invoke("#{NS_EWS_MESSAGES}:DeleteFolder", action) do |root|
build!(root) do
root.set_attr('DeleteType', delete_type)
folder_id = (folder_id.is_a?(Array)) ? folder_id : [folder_id]
folder_ids!(root, folder_id)
end
end
parse!(resp)
end
def update_folder
action = "#{SOAP_ACTION_PREFIX}/UpdateFolder"
resp = invoke("#{NS_EWS_MESSAGES}:UpdateFolder", action) do |update_folder|
build_update_folder!(update_folder)
end
parse_update_folder(resp)
end
def move_folder
action = "#{SOAP_ACTION_PREFIX}/MoveFolder"
resp = invoke("#{NS_EWS_MESSAGES}:MoveFolder", action) do |move_folder|
build_move_folder!(move_folder)
end
parse_move_folder(resp)
end
def copy_folder
action = "#{SOAP_ACTION_PREFIX}/CopyFolder"
resp = invoke("#{NS_EWS_MESSAGES}:CopyFolder", action) do |copy_folder|
build_copy_folder!(copy_folder)
end
parse_copy_folder(resp)
end
# Used to subscribe client applications to either push or pull notifications.
# @see http://msdn.microsoft.com/en-us/library/aa566188.aspx Subscribe on MSDN
#
# @param [Array] folder_ids An Array of folder ids, either a
# DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @param [Array] event_types An Array of EventTypes that we should track.
# Available types are, CopiedEvent, CreatedEvent, DeletedEvent, ModifiedEvent,
# MovedEvent, NewMailEvent, FreeBusyChangedEvent
# @param [Integer] timeout The number of minutes in which the subscription
# will timeout after not receiving a get_events operation.
# @todo Decide how/if to handle the optional SubscribeToAllFolders attribute of
# the PullSubscriptionRequest element.
def subscribe(folder_ids, event_types, timeout = 10)
action = "#{SOAP_ACTION_PREFIX}/Subscribe"
resp = invoke("#{NS_EWS_MESSAGES}:Subscribe", action) do |root|
build!(root) do
pull_subscription_request!(folder_ids, event_types, timeout)
end
end
parse!(resp)
end
# Used to subscribe client applications to either push or pull notifications.
# @see http://msdn.microsoft.com/en-us/library/aa566188.aspx Subscribe on MSDN
def push_subscribe(folder_ids, event_types, url, watermark=nil, status_frequency=5)
action = "#{SOAP_ACTION_PREFIX}/Subscribe"
resp = invoke("#{NS_EWS_MESSAGES}:Subscribe", action) do |root|
build!(root) do
push_subscription_request!(folder_ids, event_types, url, watermark, status_frequency)
end
end
parse!(resp)
end
# End a pull notification subscription.
# @see http://msdn.microsoft.com/en-us/library/aa564263.aspx
#
# @param [String] subscription_id The Id of the subscription
def unsubscribe(subscription_id)
action = "#{SOAP_ACTION_PREFIX}/Unsubscribe"
resp = invoke("#{NS_EWS_MESSAGES}:Unsubscribe", action) do |root|
build!(root) do
subscription_id!(root, subscription_id)
end
end
parse!(resp)
end
# Used by pull subscription clients to request notifications from the Client Access server
# @see http://msdn.microsoft.com/en-us/library/aa566199.aspx GetEvents on MSDN
#
# @param [String] subscription_id Subscription identifier
# @param [String] watermark Event bookmark in the events queue
def get_events(subscription_id, watermark)
action = "#{SOAP_ACTION_PREFIX}/GetEvents"
resp = invoke("#{NS_EWS_MESSAGES}:GetEvents", action) do |root|
build!(root) do
subscription_id!(root, subscription_id)
watermark!(root, watermark)
end
end
parse!(resp)
end
# Defines a request to synchronize a folder hierarchy on a client
# @see http://msdn.microsoft.com/en-us/library/aa580990.aspx
def sync_folder_hierarchy
sync_state = nil
folder_id = :publicfoldersroot
action = "#{SOAP_ACTION_PREFIX}/SyncFolderHierarchy"
resp = invoke("#{NS_EWS_MESSAGES}:SyncFolderHierarchy", action) do |root|
build!(root) do
folder_shape!(root, {:base_shape => 'Default'})
root.add("#{NS_EWS_MESSAGES}:SyncFolderId") do |sfid|
folder_id!(sfid, folder_id)
end
sync_state!(root, sync_state) unless sync_state.nil?
end
end
parse!(resp)
end
# Synchronizes items between the Exchange server and the client
# @see http://msdn.microsoft.com/en-us/library/aa563967.aspx
#
# @param [String, Symbol] folder_id either a DistinguishedFolderId
# (must me a Symbol) or a FolderId (String)
# @param [String] sync_state Base-64 encoded string used to determine
# where we are in the sync process.
# @param [Integer] max_changes The amount of items to sync per call
# to SyncFolderItems
# @param [Hash] item_shape defines the ItemShape node
# See: http://msdn.microsoft.com/en-us/library/aa565261.aspx
# @option item_shape [String] :base_shape IdOnly/Default/AllProperties
# @option item_shape :additional_properties
# See: http://msdn.microsoft.com/en-us/library/aa565261.aspx
# @param [Hash] opts optional parameters to this method
def sync_folder_items(folder_id, sync_state = nil, max_changes = 256, item_shape = {:base_shape => 'Default'}, opts = {})
action = "#{SOAP_ACTION_PREFIX}/SyncFolderItems"
resp = invoke("#{NS_EWS_MESSAGES}:SyncFolderItems", action) do |root|
build!(root) do
item_shape!(root, item_shape)
root.add("#{NS_EWS_MESSAGES}:SyncFolderId") do |sfid|
folder_id!(sfid, folder_id)
end
sync_state!(root, sync_state) unless sync_state.nil?
root.add("#{NS_EWS_MESSAGES}:MaxChangesReturned", max_changes)
end
end
parse!(resp)
end
# Gets items from the Exchange store
# @see http://msdn.microsoft.com/en-us/library/aa565934.aspx
#
# @param [Array] item_ids An Array of item ids
# @param [Hash] item_shape defines the ItemShape node
# See: http://msdn.microsoft.com/en-us/library/aa565261.aspx
# @option item_shape [String] :base_shape ('Default') IdOnly/Default/AllProperties
# @option item_shape :additional_properties
# See: http://msdn.microsoft.com/en-us/library/aa563810.aspx
# @param [Hash] opts optional parameters to this method
def get_item(item_ids, item_shape = {})
action = "#{SOAP_ACTION_PREFIX}/GetItem"
item_shape[:base_shape] = 'Default' unless item_shape.has_key?(:base_shape)
resp = invoke("#{NS_EWS_MESSAGES}:GetItem", action) do |root|
build!(root) do
item_shape!(root, item_shape)
item_ids!(root, item_ids)
end
end
parse!(resp)
end
# Operation is used to create e-mail messages
# This is actually a CreateItem operation but they differ for different types
# of Exchange objects so it is named appropriately here.
# @see http://msdn.microsoft.com/en-us/library/aa566468.aspx
#
# @param [String, Symbol] folder_id The folder to save this message in. Either a
# DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @param [Hash, Array] items An array of item Hashes or a single item Hash. Hash
# This Hash will eventually be passed to add_hierarchy! in the builder so it is in that format.
# Values should be based on values found here: http://msdn.microsoft.com/en-us/library/aa494306.aspx
# @param [String] message_disposition "SaveOnly/SendOnly/SendAndSaveCopy"
# See: http://msdn.microsoft.com/en-us/library/aa565209.aspx
def create_message_item(folder_id, items, message_disposition = 'SaveOnly')
action = "#{SOAP_ACTION_PREFIX}/CreateItem"
resp = invoke("#{NS_EWS_MESSAGES}:CreateItem", action) do |node|
build!(node) do
create_item!(folder_id, items, message_disposition, send_invites=false, 'message')
end
end
parse!(resp)
end
# Operation is used to create calendar items
# @see http://msdn.microsoft.com/en-us/library/aa564690.aspx
#
# @param [String, Symbol] folder_id The folder to create this item in. Either a
# DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @param [Hash, Array] items An array of item Hashes or a single item Hash. Hash
# This Hash will eventually be passed to add_hierarchy! in the builder so it is in that format.
# Values should be based on values found here: http://msdn.microsoft.com/en-us/library/aa564765.aspx
# @param [String] send_invites "SendToNone/SendOnlyToAll/SendToAllAndSaveCopy"
def create_calendar_item(folder_id, items, send_invites = 'SendToAllAndSaveCopy')
action = "#{SOAP_ACTION_PREFIX}/CreateItem"
resp = invoke("#{NS_EWS_MESSAGES}:CreateItem", action) do |node|
build!(node) do
create_item!(folder_id, items, message_disposition=false, send_invites, 'calendar')
end
end
parse!(resp)
end
# Operation is used to create task items
# This is actually a CreateItem operation but they differ for different types
# of Exchange objects so it is named appropriately here.
# @see http://msdn.microsoft.com/en-us/library/aa563439.aspx
#
# @param [String, Symbol] folder_id The folder to save this task in. Either a
# DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @param [Hash, Array] items An array of item Hashes or a single item Hash. Hash
# values should be based on values found here: http://msdn.microsoft.com/en-us/library/aa494306.aspx
# This Hash will eventually be passed to add_hierarchy! in the builder so it is in that format.
# @param [String] message_disposition "SaveOnly/SendOnly/SendAndSaveCopy"
# See: http://msdn.microsoft.com/en-us/library/aa565209.aspx
def create_task_item(folder_id, items, message_disposition = 'SaveOnly')
action = "#{SOAP_ACTION_PREFIX}/CreateItem"
resp = invoke("#{NS_EWS_MESSAGES}:CreateItem", action) do |node|
build!(node) do
create_item!(folder_id, items, message_disposition, false, 'task')
end
end
parse!(resp)
end
# Operation is used to create contact items
# This is actually a CreateItem operation but they differ for different types
# of Exchange objects so it is named appropriately here.
# @see # http://msdn.microsoft.com/en-us/library/aa580529.aspx
#
# @param [String, Symbol] folder_id The folder to save this task in. Either a
# DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @param [Hash, Array] items An array of item Hashes or a single item Hash. Hash
# values should be based on values found here: http://msdn.microsoft.com/en-us/library/aa581315.aspx
# This Hash will eventually be passed to add_hierarchy! in the builder so it is in that format.
def create_contact_item(folder_id, items)
action = "#{SOAP_ACTION_PREFIX}/CreateItem"
resp = invoke("#{NS_EWS_MESSAGES}:CreateItem", action) do |node|
build!(node) do
create_item!(folder_id, items, nil, false, 'contact')
end
end
parse!(resp)
end
# Delete an item from a mailbox in the Exchange store
# @see http://msdn.microsoft.com/en-us/library/aa562961.aspx
# @param [Array] item_ids An Array of item ids
# @param [String] delete_type Type of deletion: "HardDelete/SoftDelete/MoveToDeletedItems"
# @param [String, nil] send_meeting_cancellations "SendToNone/SendOnlyToAll/SendToAllAndSaveCopy"
# This is only applicable to CalendarItems and should be nil otherwise, which is the default
# @param [String, nil] affected_task_occurrences "AllOccurrences/SpecifiedOccurrenceOnly"
# This is really only related to tasks and can be nil otherwise, which is the default.
def delete_item(item_ids, delete_type, send_meeting_cancellations = nil, affected_task_occurrences = nil)
action = "#{SOAP_ACTION_PREFIX}/DeleteItem"
resp = invoke("#{NS_EWS_MESSAGES}:DeleteItem", action) do |root|
build!(root) do
root.set_attr('DeleteType', delete_type)
root.set_attr('SendMeetingCancellations', send_meeting_cancellations) unless send_meeting_cancellations.nil?
root.set_attr('AffectedTaskOccurrences', affected_task_occurrences) unless affected_task_occurrences.nil?
item_ids!(root, item_ids)
end
end
parse!(resp)
end
# Used to modify the properties of an existing item in the Exchange store
# @see http://msdn.microsoft.com/en-us/library/aa581084.aspx
# @param [Array] item_ids An Array of item ids
# @param [Hash] changes a Hash of changes to be fed to auto_hierarchy!
# @param [Hash] opts various attributes to set for this update. See the Technet docs for more info
def update_item(item_ids, changes, opts = {:message_disposition => 'SaveOnly', :conflict_resolution => 'AutoResolve'})
action = "#{SOAP_ACTION_PREFIX}/UpdateItem"
resp = invoke("#{NS_EWS_MESSAGES}:UpdateItem", action) do |root|
build!(root) do
root.set_attr('MessageDisposition', opts[:message_disposition]) if opts.has_key?(:message_disposition)
root.set_attr('ConflictResolution', opts[:conflict_resolution]) if opts.has_key?(:message_disposition)
root.set_attr('SendMeetingInvitationsOrCancellations', opts[:send_meeting_invitations_or_cancellations]) if opts.has_key?(:send_meeting_invitations_or_cancellations)
item_changes!(root, item_ids, changes)
end
end
parse!(resp)
end
# Used to send e-mail messages that are located in the Exchange store.
# @see http://msdn.microsoft.com/en-us/library/aa580238.aspx
# @param [Array<Hash>] item_ids An Array of item ids. These item_ids should be a Hash of
# :id and :change_key.
# @param [Boolean] save_item Save item after sending (Think sent-items)
# @param [String, Symbol,nil] saved_item_folder The folder to save this item in. Either a
# DistinguishedFolderId (must me a Symbol) or a FolderId (String). Just leave
# it blank for the default :sentitems
def send_item(item_ids, save_item=true, saved_item_folder=nil)
action = "#{SOAP_ACTION_PREFIX}/SendItem"
resp = invoke("#{NS_EWS_MESSAGES}:SendItem", action) do |root|
build!(root) do
root.set_attr('SaveItemToFolder', save_item)
item_ids!(root,item_ids)
saved_item_folder_id!(root,saved_item_folder) unless saved_item_folder.nil?
end
end
parse!(resp)
end
# Used to move one or more items to a single destination folder.
# @see http://msdn.microsoft.com/en-us/library/aa565781.aspx
# @param [Array] item_ids An Array of item ids
# @param [String, Symbol] folder_id either a DistinguishedFolderId
# (must me a Symbol) or a FolderId (String)
def move_item(item_ids, folder_id)
action = "#{SOAP_ACTION_PREFIX}/MoveItem"
resp = invoke("#{NS_EWS_MESSAGES}:MoveItem", action) do |root|
build!(root) do
to_folder_id!(root, folder_id)
item_ids!(root, item_ids)
end
end
parse!(resp)
end
# Copies items and puts the items in a different folder
# @see http://msdn.microsoft.com/en-us/library/aa565012.aspx
# @param [Array] item_ids An Array of item ids
# @param [String, Symbol] folder_id either a DistinguishedFolderId
# (must me a Symbol) or a FolderId (String)
def copy_item(item_ids, folder_id)
action = "#{SOAP_ACTION_PREFIX}/CopyItem"
resp = invoke("#{NS_EWS_MESSAGES}:CopyItem", action) do |root|
build!(root) do
to_folder_id!(root, folder_id)
item_ids!(root, item_ids)
end
end
parse!(resp)
end
# Creates either an item or file attachment and attaches it to the specified item.
# @see http://msdn.microsoft.com/en-us/library/aa565877.aspx
# @param [String,Hash] parent_id The id of the Item. If this is a Hash
# it should contain the Id and the ChangeKey.
# @option parent_id [String] :id The item Id
# @option parent_id [String] :change_key The ChangeKey
# @param [Array<Hash>] files An Array of Base64 encoded Strings with an associated name
# hash format= :name => <name>, :content => <Base64 encoded string>
# @param [Array] items Exchange Items to attach to this Item
# @todo Need to implement attachment of Item types
def create_attachment(parent_id, files = [], items = [])
action = "#{SOAP_ACTION_PREFIX}/CreateAttachment"
resp = invoke("#{NS_EWS_MESSAGES}:CreateAttachment", action) do |root|
build!(root) do
item_id!(root, parent_id, "#{NS_EWS_MESSAGES}:ParentItemId")
attachments!(root, files, items)
end
end
parse!(resp)
end
def delete_attachment
action = "#{SOAP_ACTION_PREFIX}/DeleteAttachment"
resp = invoke("#{NS_EWS_MESSAGES}:DeleteAttachment", action) do |delete_attachment|
build_delete_attachment!(delete_attachment)
end
parse_delete_attachment(resp)
end
# Used to retrieve existing attachments on items in the Exchange store
# @see http://msdn.microsoft.com/en-us/library/aa494316.aspx
# @param [Array] attachment_ids Attachment Ids to fetch
def get_attachment(attachment_ids)
action = "#{SOAP_ACTION_PREFIX}/GetAttachment"
resp = invoke("#{NS_EWS_MESSAGES}:GetAttachment", action) do |root|
build!(root) do
attachment_shape!(root)
attachment_ids!(root, attachment_ids)
end
end
parse!(resp)
end
def create_managed_folder
action = "#{SOAP_ACTION_PREFIX}/CreateManagedFolder"
resp = invoke("#{NS_EWS_MESSAGES}:CreateManagedFolder", action) do |create_managed_folder|
build_create_managed_folder!(create_managed_folder)
end
parse_create_managed_folder(resp)
end
# Retrieves the delegate settings for a specific mailbox.
# @see http://msdn.microsoft.com/en-us/library/bb799735.aspx
#
# @param [String] owner The user that is delegating permissions
def get_delegate(owner)
action = "#{SOAP_ACTION_PREFIX}/GetDelegate"
resp = invoke("#{NS_EWS_MESSAGES}:GetDelegate", action) do |root|
root.set_attr('IncludePermissions', 'true')
build!(root) do
mailbox!(root, {:email_address => {:text => owner}})
end
end
parse!(resp)
end
# Adds one or more delegates to a principal's mailbox and sets specific access permissions.
# @see http://msdn.microsoft.com/en-us/library/bb856527.aspx
#
# @param [String] owner The user that is delegating permissions
# @param [String] delegate The user that is being given delegate permission
# @param [Hash] permissions A hash of permissions that will be delegated.
# This Hash will eventually be passed to add_hierarchy! in the builder so it is in that format.
def add_delegate(owner, delegate, permissions)
action = "#{SOAP_ACTION_PREFIX}/AddDelegate"
resp = invoke("#{NS_EWS_MESSAGES}:AddDelegate", action) do |root|
build!(root) do
add_delegate!(owner, delegate, permissions)
end
end
parse!(resp)
end
# Removes one or more delegates from a user's mailbox.
# @see http://msdn.microsoft.com/en-us/library/bb856564.aspx
#
# @param [String] owner The user that is delegating permissions
# @param [String] delegate The user that is being given delegate permission
def remove_delegate(owner, delegate)
action = "#{SOAP_ACTION_PREFIX}/RemoveDelegate"
resp = invoke("#{NS_EWS_MESSAGES}:RemoveDelegate", action) do |root|
build!(root) do
remove_delegate!(owner, delegate)
end
end
parse!(resp)
end
# Updates delegate permissions on a principal's mailbox
# @see http://msdn.microsoft.com/en-us/library/bb856529.aspx
#
# @param [String] owner The user that is delegating permissions
# @param [String] delegate The user that is being given delegate permission
# @param [Hash] permissions A hash of permissions that will be delegated.
# This Hash will eventually be passed to add_hierarchy! in the builder so it is in that format.
def update_delegate(owner, delegate, permissions)
action = "#{SOAP_ACTION_PREFIX}/UpdateDelegate"
resp = invoke("#{NS_EWS_MESSAGES}:UpdateDelegate", action) do |root|
build!(root) do
add_delegate!(owner, delegate, permissions)
end
end
parse!(resp)
end
# Provides detailed information about the availability of a set of users, rooms, and resources
# within a specified time window.
# @see http://msdn.microsoft.com/en-us/library/aa564001.aspx
def get_user_availability
action = "#{SOAP_ACTION_PREFIX}/GetUserAvailability"
resp = invoke("#{NS_EWS_MESSAGES}:GetUserAvailability", action) do |get_user_availability|
build_get_user_availability!(get_user_availability)
end
parse_get_user_availability(resp)
end
# Gets a mailbox user's Out of Office (OOF) settings and messages.
# @see http://msdn.microsoft.com/en-us/library/aa563465.aspx
def get_user_oof_settings(mailbox)
action = "#{SOAP_ACTION_PREFIX}/GetUserOofSettings"
resp = invoke("#{NS_EWS_MESSAGES}:GetUserOofSettingsRequest", action) do |root|
build!(root) do
mailbox!(root,mailbox[:mailbox],NS_EWS_TYPES)
end
end
parse!(resp)
end
# Sets a mailbox user's Out of Office (OOF) settings and message.
# @see http://msdn.microsoft.com/en-us/library/aa580294.aspx
def set_user_oof_settings(mailbox, oof_state, ext_audience, dt_start, dt_end, int_msg, ext_mg)
action = "#{SOAP_ACTION_PREFIX}/SetUserOofSettings"
resp = invoke("#{NS_EWS_MESSAGES}:SetUserOofSettings", action) do |root|
build!(root)
end
parse!(resp)
end
# Private Methods (Builders and Parsers)
private
def build!(node, opts = {}, &block)
EwsBuilder.new(node, opts, &block)
end
def parse!(response, opts = {})
return response if @@raw_soap
EwsParser.new(response).parse(opts)
end
# Override the superclasses' invoke so we can add http_options to each request
def invoke(msg, action)
raise EwsError, "EWS Endpoint not set." if uri.nil?
begin
super(msg, {:soap_action => action, :http_options => @@http_options})
rescue SocketError
raise EwsError, "Could not connect to endpoint: #{uri}"
end
end
end # class ExchangeWebService
end # module SOAP
end # EWS
end # Viewpoint
raise an EwsError exception when parsing an empty response
#############################################################################
# Copyright © 2010 Dan Wanek <dan.wanek@gmail.com>
#
#
# This file is part of Viewpoint.
#
# Viewpoint is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# Viewpoint is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with Viewpoint. If not, see <http://www.gnu.org/licenses/>.
#############################################################################
require 'handsoap'
require 'soap/handsoap/builder'
require 'soap/handsoap/parser'
Handsoap.http_driver = :http_client
module Viewpoint
module EWS
module SOAP
class ExchangeWebService < Handsoap::Service
include Viewpoint::EWS::SOAP
SOAP_ACTION_PREFIX = "http://schemas.microsoft.com/exchange/services/2006/messages"
@@raw_soap = false
@@http_options = nil
def initialize()
if $DEBUG
@debug = File.new('ews_debug.out', 'w')
@debug.sync = true
end
end
def self.set_auth(user,pass)
@@user = user
@@pass = pass
end
# Turn off parsing and just return the soap response
def self.raw_soap!
@@raw_soap = true
end
# Set various HTTP options like ssl_ca_trust, etc
def self.set_http_options(option_hash)
if @@http_options.nil?
@@http_options = option_hash
else
@@http_options.merge!(option_hash)
end
end
# ********* Begin Hooks *********
def on_create_document(doc)
doc.alias NS_EWS_TYPES, 'http://schemas.microsoft.com/exchange/services/2006/types'
doc.alias NS_EWS_MESSAGES, 'http://schemas.microsoft.com/exchange/services/2006/messages'
header = doc.find('Header')
header.add("#{NS_EWS_TYPES}:RequestServerVersion") { |rsv| rsv.set_attr('Version','Exchange2007_SP1') }
end
# Adds knowledge of namespaces to the response object. These have to be identical to the
# URIs returned in the XML response. For example, I had some issues with the 'soap'
# namespace because my original URI did not end in a '/'
# @example
# Won't work: http://schemas.xmlsoap.org/soap/envelope
# Works: http://schemas.xmlsoap.org/soap/envelope/
def on_response_document(doc)
doc.add_namespace NS_SOAP, 'http://schemas.xmlsoap.org/soap/envelope/'
doc.add_namespace NS_EWS_TYPES, 'http://schemas.microsoft.com/exchange/services/2006/types'
doc.add_namespace NS_EWS_MESSAGES, 'http://schemas.microsoft.com/exchange/services/2006/messages'
end
def on_after_create_http_request(req)
begin
req.set_auth @@user, @@pass
rescue NameError => e
raise EwsLoginError, "Please remember to set your credential information."
end
end
def on_http_error(response)
raise EwsLoginError, "Failed to login to EWS at #{uri}. Please check your credentials." if(response.status == 401)
end
# ********** End Hooks **********
# Resolve ambiguous e-mail addresses and display names
# @see http://msdn.microsoft.com/en-us/library/aa565329.aspx ResolveNames
# @see http://msdn.microsoft.com/en-us/library/aa581054.aspx UnresolvedEntry
#
# @param [String] name an unresolved entry
# @param [Boolean] full_contact_data whether or not to return full contact info
# @param [Hash] opts optional parameters to this method
# @option opts [String] :search_scope where to seach for this entry, one of
# SOAP::Contacts, SOAP::ActiveDirectory, SOAP::ActiveDirectoryContacts (default),
# SOAP::ContactsActiveDirectory
# @option opts [String, FolderId] :parent_folder_id either the name of a folder or
# it's numerical ID. @see http://msdn.microsoft.com/en-us/library/aa565998.aspx
def resolve_names(name, full_contact_data = true, opts = {})
action = "#{SOAP_ACTION_PREFIX}/ResolveNames"
resp = invoke("#{NS_EWS_MESSAGES}:ResolveNames", action) do |root|
build!(root) do
root.set_attr('ReturnFullContactData',full_contact_data)
root.add("#{NS_EWS_MESSAGES}:UnresolvedEntry",name)
end
end
parse!(resp)
end
# Exposes the full membership of distribution lists.
# @see http://msdn.microsoft.com/en-us/library/aa494152.aspx ExpandDL
#
# @param [String] dist_email The e-mail address associated with the Distribution List
# @todo Fully support all of the ExpandDL operations. Today it just supports
# taking an e-mail address as an argument
def expand_dl(dist_email)
action = "#{SOAP_ACTION_PREFIX}/ExpandDL"
resp = invoke("#{NS_EWS_MESSAGES}:ExpandDL", action) do |root|
build!(root) do
mailbox!(root, {:email_address => {:text => dist_email}})
end
end
parse!(resp)
end
# Find subfolders of an identified folder
# @see http://msdn.microsoft.com/en-us/library/aa563918.aspx
#
# @param [Array] parent_folder_ids An Array of folder ids, either a
# DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @param [String] traversal Shallow/Deep/SoftDeleted
# @param [Hash] folder_shape defines the FolderShape node
# See: http://msdn.microsoft.com/en-us/library/aa494311.aspx
# @option folder_shape [String] :base_shape IdOnly/Default/AllProperties
# @option folder_shape :additional_properties
# See: http://msdn.microsoft.com/en-us/library/aa563810.aspx
# @param [Hash] opts optional parameters to this method
def find_folder(parent_folder_ids = [:root], traversal = 'Shallow', folder_shape = {:base_shape => 'Default'}, opts = {})
action = "#{SOAP_ACTION_PREFIX}/FindFolder"
resp = invoke("#{NS_EWS_MESSAGES}:FindFolder", action) do |root|
build!(root) do
restriction = opts.delete(:restriction)
root.set_attr('Traversal', traversal)
folder_shape!(root, folder_shape)
root.add("#{NS_EWS_MESSAGES}:Restriction") do |r|
add_hierarchy!(r, restriction)
end unless restriction.nil?
parent_folder_ids!(root, parent_folder_ids)
end
end
parse!(resp)
end
# Identifies items that are located in a specified folder
# @see http://msdn.microsoft.com/en-us/library/aa566107.aspx
#
# @param [Array] parent_folder_ids An Array of folder ids, either a
# DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @param [String] traversal Shallow/Deep/SoftDeleted
# @param [Hash] item_shape defines the FolderShape node
# See: http://msdn.microsoft.com/en-us/library/aa494311.aspx
# @option item_shape [String] :base_shape IdOnly/Default/AllProperties
# @option item_shape :additional_properties
# See: http://msdn.microsoft.com/en-us/library/aa563810.aspx
# @param [Hash] opts optional parameters to this method
# @option opts [Hash] :calendar_view Limit FindItem by a start and end date
# {:calendar_view => {:max_entries_returned => 2, :start => <DateTime Obj>, :end => <DateTime Obj>}}
def find_item(parent_folder_ids, traversal = 'Shallow', item_shape = {:base_shape => 'Default'}, opts = {})
action = "#{SOAP_ACTION_PREFIX}/FindItem"
resp = invoke("#{NS_EWS_MESSAGES}:FindItem", action) do |root|
build!(root) do
root.set_attr('Traversal', traversal)
item_shape!(root, item_shape)
query_strings = opts.delete(:query_string)
restriction = opts.delete(:restriction)
if(opts.has_key?(:calendar_view))
cal_view = opts[:calendar_view]
cal_view.each_pair do |k,v|
cal_view[k] = v.to_s
end
end
add_hierarchy!(root, opts, NS_EWS_MESSAGES)
#query_strings!(query_strings)
root.add("#{NS_EWS_MESSAGES}:Restriction") do |r|
add_hierarchy!(r, restriction)
end unless restriction.nil?
parent_folder_ids!(root, parent_folder_ids)
end
end
parse!(resp)
end
# Gets folders from the Exchange store
# @see http://msdn.microsoft.com/en-us/library/aa580274.aspx
#
# @param [Array] folder_ids An Array of folder ids, either a
# DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @param [Hash] folder_shape defines the FolderShape node
# See: http://msdn.microsoft.com/en-us/library/aa494311.aspx
# @option folder_shape [String] :base_shape IdOnly/Default/AllProperties
# @option folder_shape :additional_properties
# See: http://msdn.microsoft.com/en-us/library/aa563810.aspx
# @param [String,nil] act_as User to act on behalf as. This user must have been
# given delegate access to this folder or else this operation will fail.
# @param [Hash] opts optional parameters to this method
def get_folder(folder_ids, folder_shape = {:base_shape => 'Default'}, act_as = nil)
action = "#{SOAP_ACTION_PREFIX}/GetFolder"
resp = invoke("#{NS_EWS_MESSAGES}:GetFolder", action) do |root|
build!(root) do
folder_shape!(root, folder_shape)
folder_ids!(root, folder_ids, act_as)
end
end
parse!(resp)
end
def convert_id
action = "#{SOAP_ACTION_PREFIX}/ConvertId"
resp = invoke("#{NS_EWS_MESSAGES}:ConvertId", action) do |convert_id|
build_convert_id!(convert_id)
end
parse_convert_id(resp)
end
# Creates folders, calendar folders, contacts folders, tasks folders, and search folders.
# @see http://msdn.microsoft.com/en-us/library/aa563574.aspx CreateFolder
#
# @param [String,Symbol] parent_folder_id either the name of a folder or it's
# numerical ID. See: http://msdn.microsoft.com/en-us/library/aa565998.aspx
# @param [Array,String] folder_name The display name for the new folder or folders
def create_folder(parent_folder_id, folder_name)
action = "#{SOAP_ACTION_PREFIX}/CreateFolder"
resp = invoke("#{NS_EWS_MESSAGES}:CreateFolder", action) do |root|
build!(root) do
root.add("#{NS_EWS_MESSAGES}:ParentFolderId") do |pfid|
folder_id!(pfid, parent_folder_id)
end
folder_name = (folder_name.is_a?(Array)) ? folder_name : [folder_name]
root.add("#{NS_EWS_MESSAGES}:Folders") do |fids|
folder_name.each do |f|
add_hierarchy!(fids, {:folder => {:display_name => {:text => f}}})
end
end
end
end
parse!(resp)
end
# Deletes folders from a mailbox.
# @see http://msdn.microsoft.com/en-us/library/aa564767.aspx DeleteFolder
#
# @param [Array,String,Symbol] folder_id either the name of a folder or it's
# numerical ID. See: http://msdn.microsoft.com/en-us/library/aa565998.aspx
# @param [String,nil] delete_type Type of delete to do: HardDelete/SoftDelete/MoveToDeletedItems
def delete_folder(folder_id, delete_type = 'MoveToDeletedItems')
action = "#{SOAP_ACTION_PREFIX}/DeleteFolder"
resp = invoke("#{NS_EWS_MESSAGES}:DeleteFolder", action) do |root|
build!(root) do
root.set_attr('DeleteType', delete_type)
folder_id = (folder_id.is_a?(Array)) ? folder_id : [folder_id]
folder_ids!(root, folder_id)
end
end
parse!(resp)
end
def update_folder
action = "#{SOAP_ACTION_PREFIX}/UpdateFolder"
resp = invoke("#{NS_EWS_MESSAGES}:UpdateFolder", action) do |update_folder|
build_update_folder!(update_folder)
end
parse_update_folder(resp)
end
def move_folder
action = "#{SOAP_ACTION_PREFIX}/MoveFolder"
resp = invoke("#{NS_EWS_MESSAGES}:MoveFolder", action) do |move_folder|
build_move_folder!(move_folder)
end
parse_move_folder(resp)
end
def copy_folder
action = "#{SOAP_ACTION_PREFIX}/CopyFolder"
resp = invoke("#{NS_EWS_MESSAGES}:CopyFolder", action) do |copy_folder|
build_copy_folder!(copy_folder)
end
parse_copy_folder(resp)
end
# Used to subscribe client applications to either push or pull notifications.
# @see http://msdn.microsoft.com/en-us/library/aa566188.aspx Subscribe on MSDN
#
# @param [Array] folder_ids An Array of folder ids, either a
# DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @param [Array] event_types An Array of EventTypes that we should track.
# Available types are, CopiedEvent, CreatedEvent, DeletedEvent, ModifiedEvent,
# MovedEvent, NewMailEvent, FreeBusyChangedEvent
# @param [Integer] timeout The number of minutes in which the subscription
# will timeout after not receiving a get_events operation.
# @todo Decide how/if to handle the optional SubscribeToAllFolders attribute of
# the PullSubscriptionRequest element.
def subscribe(folder_ids, event_types, timeout = 10)
action = "#{SOAP_ACTION_PREFIX}/Subscribe"
resp = invoke("#{NS_EWS_MESSAGES}:Subscribe", action) do |root|
build!(root) do
pull_subscription_request!(folder_ids, event_types, timeout)
end
end
parse!(resp)
end
# Used to subscribe client applications to either push or pull notifications.
# @see http://msdn.microsoft.com/en-us/library/aa566188.aspx Subscribe on MSDN
def push_subscribe(folder_ids, event_types, url, watermark=nil, status_frequency=5)
action = "#{SOAP_ACTION_PREFIX}/Subscribe"
resp = invoke("#{NS_EWS_MESSAGES}:Subscribe", action) do |root|
build!(root) do
push_subscription_request!(folder_ids, event_types, url, watermark, status_frequency)
end
end
parse!(resp)
end
# End a pull notification subscription.
# @see http://msdn.microsoft.com/en-us/library/aa564263.aspx
#
# @param [String] subscription_id The Id of the subscription
def unsubscribe(subscription_id)
action = "#{SOAP_ACTION_PREFIX}/Unsubscribe"
resp = invoke("#{NS_EWS_MESSAGES}:Unsubscribe", action) do |root|
build!(root) do
subscription_id!(root, subscription_id)
end
end
parse!(resp)
end
# Used by pull subscription clients to request notifications from the Client Access server
# @see http://msdn.microsoft.com/en-us/library/aa566199.aspx GetEvents on MSDN
#
# @param [String] subscription_id Subscription identifier
# @param [String] watermark Event bookmark in the events queue
def get_events(subscription_id, watermark)
action = "#{SOAP_ACTION_PREFIX}/GetEvents"
resp = invoke("#{NS_EWS_MESSAGES}:GetEvents", action) do |root|
build!(root) do
subscription_id!(root, subscription_id)
watermark!(root, watermark)
end
end
parse!(resp)
end
# Defines a request to synchronize a folder hierarchy on a client
# @see http://msdn.microsoft.com/en-us/library/aa580990.aspx
def sync_folder_hierarchy
sync_state = nil
folder_id = :publicfoldersroot
action = "#{SOAP_ACTION_PREFIX}/SyncFolderHierarchy"
resp = invoke("#{NS_EWS_MESSAGES}:SyncFolderHierarchy", action) do |root|
build!(root) do
folder_shape!(root, {:base_shape => 'Default'})
root.add("#{NS_EWS_MESSAGES}:SyncFolderId") do |sfid|
folder_id!(sfid, folder_id)
end
sync_state!(root, sync_state) unless sync_state.nil?
end
end
parse!(resp)
end
# Synchronizes items between the Exchange server and the client
# @see http://msdn.microsoft.com/en-us/library/aa563967.aspx
#
# @param [String, Symbol] folder_id either a DistinguishedFolderId
# (must me a Symbol) or a FolderId (String)
# @param [String] sync_state Base-64 encoded string used to determine
# where we are in the sync process.
# @param [Integer] max_changes The amount of items to sync per call
# to SyncFolderItems
# @param [Hash] item_shape defines the ItemShape node
# See: http://msdn.microsoft.com/en-us/library/aa565261.aspx
# @option item_shape [String] :base_shape IdOnly/Default/AllProperties
# @option item_shape :additional_properties
# See: http://msdn.microsoft.com/en-us/library/aa565261.aspx
# @param [Hash] opts optional parameters to this method
def sync_folder_items(folder_id, sync_state = nil, max_changes = 256, item_shape = {:base_shape => 'Default'}, opts = {})
action = "#{SOAP_ACTION_PREFIX}/SyncFolderItems"
resp = invoke("#{NS_EWS_MESSAGES}:SyncFolderItems", action) do |root|
build!(root) do
item_shape!(root, item_shape)
root.add("#{NS_EWS_MESSAGES}:SyncFolderId") do |sfid|
folder_id!(sfid, folder_id)
end
sync_state!(root, sync_state) unless sync_state.nil?
root.add("#{NS_EWS_MESSAGES}:MaxChangesReturned", max_changes)
end
end
parse!(resp)
end
# Gets items from the Exchange store
# @see http://msdn.microsoft.com/en-us/library/aa565934.aspx
#
# @param [Array] item_ids An Array of item ids
# @param [Hash] item_shape defines the ItemShape node
# See: http://msdn.microsoft.com/en-us/library/aa565261.aspx
# @option item_shape [String] :base_shape ('Default') IdOnly/Default/AllProperties
# @option item_shape :additional_properties
# See: http://msdn.microsoft.com/en-us/library/aa563810.aspx
# @param [Hash] opts optional parameters to this method
def get_item(item_ids, item_shape = {})
action = "#{SOAP_ACTION_PREFIX}/GetItem"
item_shape[:base_shape] = 'Default' unless item_shape.has_key?(:base_shape)
resp = invoke("#{NS_EWS_MESSAGES}:GetItem", action) do |root|
build!(root) do
item_shape!(root, item_shape)
item_ids!(root, item_ids)
end
end
parse!(resp)
end
# Operation is used to create e-mail messages
# This is actually a CreateItem operation but they differ for different types
# of Exchange objects so it is named appropriately here.
# @see http://msdn.microsoft.com/en-us/library/aa566468.aspx
#
# @param [String, Symbol] folder_id The folder to save this message in. Either a
# DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @param [Hash, Array] items An array of item Hashes or a single item Hash. Hash
# This Hash will eventually be passed to add_hierarchy! in the builder so it is in that format.
# Values should be based on values found here: http://msdn.microsoft.com/en-us/library/aa494306.aspx
# @param [String] message_disposition "SaveOnly/SendOnly/SendAndSaveCopy"
# See: http://msdn.microsoft.com/en-us/library/aa565209.aspx
def create_message_item(folder_id, items, message_disposition = 'SaveOnly')
action = "#{SOAP_ACTION_PREFIX}/CreateItem"
resp = invoke("#{NS_EWS_MESSAGES}:CreateItem", action) do |node|
build!(node) do
create_item!(folder_id, items, message_disposition, send_invites=false, 'message')
end
end
parse!(resp)
end
# Operation is used to create calendar items
# @see http://msdn.microsoft.com/en-us/library/aa564690.aspx
#
# @param [String, Symbol] folder_id The folder to create this item in. Either a
# DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @param [Hash, Array] items An array of item Hashes or a single item Hash. Hash
# This Hash will eventually be passed to add_hierarchy! in the builder so it is in that format.
# Values should be based on values found here: http://msdn.microsoft.com/en-us/library/aa564765.aspx
# @param [String] send_invites "SendToNone/SendOnlyToAll/SendToAllAndSaveCopy"
def create_calendar_item(folder_id, items, send_invites = 'SendToAllAndSaveCopy')
action = "#{SOAP_ACTION_PREFIX}/CreateItem"
resp = invoke("#{NS_EWS_MESSAGES}:CreateItem", action) do |node|
build!(node) do
create_item!(folder_id, items, message_disposition=false, send_invites, 'calendar')
end
end
parse!(resp)
end
# Operation is used to create task items
# This is actually a CreateItem operation but they differ for different types
# of Exchange objects so it is named appropriately here.
# @see http://msdn.microsoft.com/en-us/library/aa563439.aspx
#
# @param [String, Symbol] folder_id The folder to save this task in. Either a
# DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @param [Hash, Array] items An array of item Hashes or a single item Hash. Hash
# values should be based on values found here: http://msdn.microsoft.com/en-us/library/aa494306.aspx
# This Hash will eventually be passed to add_hierarchy! in the builder so it is in that format.
# @param [String] message_disposition "SaveOnly/SendOnly/SendAndSaveCopy"
# See: http://msdn.microsoft.com/en-us/library/aa565209.aspx
def create_task_item(folder_id, items, message_disposition = 'SaveOnly')
action = "#{SOAP_ACTION_PREFIX}/CreateItem"
resp = invoke("#{NS_EWS_MESSAGES}:CreateItem", action) do |node|
build!(node) do
create_item!(folder_id, items, message_disposition, false, 'task')
end
end
parse!(resp)
end
# Operation is used to create contact items
# This is actually a CreateItem operation but they differ for different types
# of Exchange objects so it is named appropriately here.
# @see # http://msdn.microsoft.com/en-us/library/aa580529.aspx
#
# @param [String, Symbol] folder_id The folder to save this task in. Either a
# DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @param [Hash, Array] items An array of item Hashes or a single item Hash. Hash
# values should be based on values found here: http://msdn.microsoft.com/en-us/library/aa581315.aspx
# This Hash will eventually be passed to add_hierarchy! in the builder so it is in that format.
def create_contact_item(folder_id, items)
action = "#{SOAP_ACTION_PREFIX}/CreateItem"
resp = invoke("#{NS_EWS_MESSAGES}:CreateItem", action) do |node|
build!(node) do
create_item!(folder_id, items, nil, false, 'contact')
end
end
parse!(resp)
end
# Delete an item from a mailbox in the Exchange store
# @see http://msdn.microsoft.com/en-us/library/aa562961.aspx
# @param [Array] item_ids An Array of item ids
# @param [String] delete_type Type of deletion: "HardDelete/SoftDelete/MoveToDeletedItems"
# @param [String, nil] send_meeting_cancellations "SendToNone/SendOnlyToAll/SendToAllAndSaveCopy"
# This is only applicable to CalendarItems and should be nil otherwise, which is the default
# @param [String, nil] affected_task_occurrences "AllOccurrences/SpecifiedOccurrenceOnly"
# This is really only related to tasks and can be nil otherwise, which is the default.
def delete_item(item_ids, delete_type, send_meeting_cancellations = nil, affected_task_occurrences = nil)
action = "#{SOAP_ACTION_PREFIX}/DeleteItem"
resp = invoke("#{NS_EWS_MESSAGES}:DeleteItem", action) do |root|
build!(root) do
root.set_attr('DeleteType', delete_type)
root.set_attr('SendMeetingCancellations', send_meeting_cancellations) unless send_meeting_cancellations.nil?
root.set_attr('AffectedTaskOccurrences', affected_task_occurrences) unless affected_task_occurrences.nil?
item_ids!(root, item_ids)
end
end
parse!(resp)
end
# Used to modify the properties of an existing item in the Exchange store
# @see http://msdn.microsoft.com/en-us/library/aa581084.aspx
# @param [Array] item_ids An Array of item ids
# @param [Hash] changes a Hash of changes to be fed to auto_hierarchy!
# @param [Hash] opts various attributes to set for this update. See the Technet docs for more info
def update_item(item_ids, changes, opts = {:message_disposition => 'SaveOnly', :conflict_resolution => 'AutoResolve'})
action = "#{SOAP_ACTION_PREFIX}/UpdateItem"
resp = invoke("#{NS_EWS_MESSAGES}:UpdateItem", action) do |root|
build!(root) do
root.set_attr('MessageDisposition', opts[:message_disposition]) if opts.has_key?(:message_disposition)
root.set_attr('ConflictResolution', opts[:conflict_resolution]) if opts.has_key?(:message_disposition)
root.set_attr('SendMeetingInvitationsOrCancellations', opts[:send_meeting_invitations_or_cancellations]) if opts.has_key?(:send_meeting_invitations_or_cancellations)
item_changes!(root, item_ids, changes)
end
end
parse!(resp)
end
# Used to send e-mail messages that are located in the Exchange store.
# @see http://msdn.microsoft.com/en-us/library/aa580238.aspx
# @param [Array<Hash>] item_ids An Array of item ids. These item_ids should be a Hash of
# :id and :change_key.
# @param [Boolean] save_item Save item after sending (Think sent-items)
# @param [String, Symbol,nil] saved_item_folder The folder to save this item in. Either a
# DistinguishedFolderId (must me a Symbol) or a FolderId (String). Just leave
# it blank for the default :sentitems
def send_item(item_ids, save_item=true, saved_item_folder=nil)
action = "#{SOAP_ACTION_PREFIX}/SendItem"
resp = invoke("#{NS_EWS_MESSAGES}:SendItem", action) do |root|
build!(root) do
root.set_attr('SaveItemToFolder', save_item)
item_ids!(root,item_ids)
saved_item_folder_id!(root,saved_item_folder) unless saved_item_folder.nil?
end
end
parse!(resp)
end
# Used to move one or more items to a single destination folder.
# @see http://msdn.microsoft.com/en-us/library/aa565781.aspx
# @param [Array] item_ids An Array of item ids
# @param [String, Symbol] folder_id either a DistinguishedFolderId
# (must me a Symbol) or a FolderId (String)
def move_item(item_ids, folder_id)
action = "#{SOAP_ACTION_PREFIX}/MoveItem"
resp = invoke("#{NS_EWS_MESSAGES}:MoveItem", action) do |root|
build!(root) do
to_folder_id!(root, folder_id)
item_ids!(root, item_ids)
end
end
parse!(resp)
end
# Copies items and puts the items in a different folder
# @see http://msdn.microsoft.com/en-us/library/aa565012.aspx
# @param [Array] item_ids An Array of item ids
# @param [String, Symbol] folder_id either a DistinguishedFolderId
# (must me a Symbol) or a FolderId (String)
def copy_item(item_ids, folder_id)
action = "#{SOAP_ACTION_PREFIX}/CopyItem"
resp = invoke("#{NS_EWS_MESSAGES}:CopyItem", action) do |root|
build!(root) do
to_folder_id!(root, folder_id)
item_ids!(root, item_ids)
end
end
parse!(resp)
end
# Creates either an item or file attachment and attaches it to the specified item.
# @see http://msdn.microsoft.com/en-us/library/aa565877.aspx
# @param [String,Hash] parent_id The id of the Item. If this is a Hash
# it should contain the Id and the ChangeKey.
# @option parent_id [String] :id The item Id
# @option parent_id [String] :change_key The ChangeKey
# @param [Array<Hash>] files An Array of Base64 encoded Strings with an associated name
# hash format= :name => <name>, :content => <Base64 encoded string>
# @param [Array] items Exchange Items to attach to this Item
# @todo Need to implement attachment of Item types
def create_attachment(parent_id, files = [], items = [])
action = "#{SOAP_ACTION_PREFIX}/CreateAttachment"
resp = invoke("#{NS_EWS_MESSAGES}:CreateAttachment", action) do |root|
build!(root) do
item_id!(root, parent_id, "#{NS_EWS_MESSAGES}:ParentItemId")
attachments!(root, files, items)
end
end
parse!(resp)
end
def delete_attachment
action = "#{SOAP_ACTION_PREFIX}/DeleteAttachment"
resp = invoke("#{NS_EWS_MESSAGES}:DeleteAttachment", action) do |delete_attachment|
build_delete_attachment!(delete_attachment)
end
parse_delete_attachment(resp)
end
# Used to retrieve existing attachments on items in the Exchange store
# @see http://msdn.microsoft.com/en-us/library/aa494316.aspx
# @param [Array] attachment_ids Attachment Ids to fetch
def get_attachment(attachment_ids)
action = "#{SOAP_ACTION_PREFIX}/GetAttachment"
resp = invoke("#{NS_EWS_MESSAGES}:GetAttachment", action) do |root|
build!(root) do
attachment_shape!(root)
attachment_ids!(root, attachment_ids)
end
end
parse!(resp)
end
def create_managed_folder
action = "#{SOAP_ACTION_PREFIX}/CreateManagedFolder"
resp = invoke("#{NS_EWS_MESSAGES}:CreateManagedFolder", action) do |create_managed_folder|
build_create_managed_folder!(create_managed_folder)
end
parse_create_managed_folder(resp)
end
# Retrieves the delegate settings for a specific mailbox.
# @see http://msdn.microsoft.com/en-us/library/bb799735.aspx
#
# @param [String] owner The user that is delegating permissions
def get_delegate(owner)
action = "#{SOAP_ACTION_PREFIX}/GetDelegate"
resp = invoke("#{NS_EWS_MESSAGES}:GetDelegate", action) do |root|
root.set_attr('IncludePermissions', 'true')
build!(root) do
mailbox!(root, {:email_address => {:text => owner}})
end
end
parse!(resp)
end
# Adds one or more delegates to a principal's mailbox and sets specific access permissions.
# @see http://msdn.microsoft.com/en-us/library/bb856527.aspx
#
# @param [String] owner The user that is delegating permissions
# @param [String] delegate The user that is being given delegate permission
# @param [Hash] permissions A hash of permissions that will be delegated.
# This Hash will eventually be passed to add_hierarchy! in the builder so it is in that format.
def add_delegate(owner, delegate, permissions)
action = "#{SOAP_ACTION_PREFIX}/AddDelegate"
resp = invoke("#{NS_EWS_MESSAGES}:AddDelegate", action) do |root|
build!(root) do
add_delegate!(owner, delegate, permissions)
end
end
parse!(resp)
end
# Removes one or more delegates from a user's mailbox.
# @see http://msdn.microsoft.com/en-us/library/bb856564.aspx
#
# @param [String] owner The user that is delegating permissions
# @param [String] delegate The user that is being given delegate permission
def remove_delegate(owner, delegate)
action = "#{SOAP_ACTION_PREFIX}/RemoveDelegate"
resp = invoke("#{NS_EWS_MESSAGES}:RemoveDelegate", action) do |root|
build!(root) do
remove_delegate!(owner, delegate)
end
end
parse!(resp)
end
# Updates delegate permissions on a principal's mailbox
# @see http://msdn.microsoft.com/en-us/library/bb856529.aspx
#
# @param [String] owner The user that is delegating permissions
# @param [String] delegate The user that is being given delegate permission
# @param [Hash] permissions A hash of permissions that will be delegated.
# This Hash will eventually be passed to add_hierarchy! in the builder so it is in that format.
def update_delegate(owner, delegate, permissions)
action = "#{SOAP_ACTION_PREFIX}/UpdateDelegate"
resp = invoke("#{NS_EWS_MESSAGES}:UpdateDelegate", action) do |root|
build!(root) do
add_delegate!(owner, delegate, permissions)
end
end
parse!(resp)
end
# Provides detailed information about the availability of a set of users, rooms, and resources
# within a specified time window.
# @see http://msdn.microsoft.com/en-us/library/aa564001.aspx
def get_user_availability
action = "#{SOAP_ACTION_PREFIX}/GetUserAvailability"
resp = invoke("#{NS_EWS_MESSAGES}:GetUserAvailability", action) do |get_user_availability|
build_get_user_availability!(get_user_availability)
end
parse_get_user_availability(resp)
end
# Gets a mailbox user's Out of Office (OOF) settings and messages.
# @see http://msdn.microsoft.com/en-us/library/aa563465.aspx
def get_user_oof_settings(mailbox)
action = "#{SOAP_ACTION_PREFIX}/GetUserOofSettings"
resp = invoke("#{NS_EWS_MESSAGES}:GetUserOofSettingsRequest", action) do |root|
build!(root) do
mailbox!(root,mailbox[:mailbox],NS_EWS_TYPES)
end
end
parse!(resp)
end
# Sets a mailbox user's Out of Office (OOF) settings and message.
# @see http://msdn.microsoft.com/en-us/library/aa580294.aspx
def set_user_oof_settings(mailbox, oof_state, ext_audience, dt_start, dt_end, int_msg, ext_mg)
action = "#{SOAP_ACTION_PREFIX}/SetUserOofSettings"
resp = invoke("#{NS_EWS_MESSAGES}:SetUserOofSettings", action) do |root|
build!(root)
end
parse!(resp)
end
# Private Methods (Builders and Parsers)
private
def build!(node, opts = {}, &block)
EwsBuilder.new(node, opts, &block)
end
def parse!(response, opts = {})
return response if @@raw_soap
raise EwsError, "Can't parse an empty response. Please check your endpoint." if(response.nil?)
EwsParser.new(response).parse(opts)
end
# Override the superclasses' invoke so we can add http_options to each request
def invoke(msg, action)
raise EwsError, "EWS Endpoint not set." if uri.nil?
begin
super(msg, {:soap_action => action, :http_options => @@http_options})
rescue SocketError
raise EwsError, "Could not connect to endpoint: #{uri}"
end
end
end # class ExchangeWebService
end # module SOAP
end # EWS
end # Viewpoint
|
require 'forwardable'
module RAWS::S3::Model
module ClassMethods
include Enumerable
extend Forwardable
def_delegators :bucket,
:create_bucket,
:delete_bucket,
:owner,
:location,
:acl,
:put_object,
:put,
:copy_object,
:copy,
:get_object,
:get,
:head_object,
:head,
:delete_object,
:delete
attr_accessor :bucket_name
def bucket
RAWS::S3[bucket_name]
end
def filter(query={}, &block)
bucket.filter(query) do |contents|
block.call self.new(contents['Key'], nil)
end
end
alias :all :filter
alias :each :filter
def find(key)
self.new key
end
end
module InstanceMethods
attr_reader :key
def initialize(key)
@key, @header, @metadata = key, nil, nil
after_initialize
end
def header
@header ||= self.class.head(@key).header
end
def metadata
@metadata ||= RAWS::S3::Metadata.new header
end
def acl
self.class.acl @key
end
def delete
befor_delete
response = self.class.delete_object @key
after_delete response
end
def send(header={}, &block)
before_send
@header.merge! header
response = self.class.put_object(
@key,
@header.merge(metadata.encode)
) do |request|
request.send &block
end
after_send response
end
def receive(header={}, &block)
before_receive
after_send(
self.class.get_object(@key, header) do |request|
response = request.send
@header = response.header
@metadata.decode @header
response.receive &block
response
end
)
end
def after_initialize; end
def before_delete; end
def after_delete(response); end
def before_receive; end
def after_receive(response); end
def before_send; end
def after_send(response); end
end
def self.included(mod)
mod.class_eval do
include InstanceMethods
extend ClassMethods
end
end
end
fixed RAWS::S3::Model#find
require 'forwardable'
module RAWS::S3::Model
module ClassMethods
include Enumerable
extend Forwardable
def_delegators :bucket,
:create_bucket,
:delete_bucket,
:owner,
:location,
:acl,
:put_object,
:put,
:copy_object,
:copy,
:get_object,
:get,
:head_object,
:head,
:delete_object,
:delete
attr_accessor :bucket_name
def bucket
RAWS::S3[bucket_name]
end
def filter(query={}, &block)
bucket.filter(query) do |contents|
block.call self.new(contents['Key'])
end
end
alias :all :filter
alias :each :filter
def find(key)
begin
self.new key, head(key).header
rescue => e
if e.response.code == 404
nil
else
raise e
end
end
end
end
module InstanceMethods
attr_reader :key
def initialize(key, header=nil)
@key, @header, @metadata = key, header, nil
after_initialize
end
def header
@header ||= self.class.head(@key).header
end
def metadata
@metadata ||= RAWS::S3::Metadata.new header
end
def acl
self.class.acl @key
end
def delete
befor_delete
response = self.class.delete_object @key
after_delete response
end
def send(header={}, &block)
before_send
@header.merge! header
response = self.class.put_object(
@key,
@header.merge(metadata.encode)
) do |request|
request.send &block
end
after_send response
end
def receive(header={}, &block)
before_receive
after_send(
self.class.get_object(@key, header) do |request|
response = request.send
@header = response.header
@metadata.decode @header
response.receive &block
response
end
)
end
def after_initialize; end
def before_delete; end
def after_delete(response); end
def before_receive; end
def after_receive(response); end
def before_send; end
def after_send(response); end
end
def self.included(mod)
mod.class_eval do
include InstanceMethods
extend ClassMethods
end
end
end
|
module Sprockets
module Helpers
VERSION = '0.8.0'
end
end
Version bump
module Sprockets
module Helpers
VERSION = '0.9.0'
end
end
|
module Rbac
class Filterer
# This list is used to detemine whether RBAC, based on assigned tags, should be applied for a class in a search that is based on the class.
# Classes should be added to this list ONLY after:
# 1. It has been added to the MiqExpression::BASE_TABLES list
# 2. Tagging has been enabled in the UI
# 3. Class contains acts_as_miq_taggable
CLASSES_THAT_PARTICIPATE_IN_RBAC = %w(
AvailabilityZone
CloudTenant
CloudVolume
ConfigurationProfile
ConfiguredSystem
ConfigurationScriptBase
Container
ContainerBuild
ContainerGroup
ContainerImage
ContainerImageRegistry
ContainerNode
ContainerProject
ContainerReplicator
ContainerRoute
ContainerService
ContainerTemplate
EmsCluster
EmsFolder
ExtManagementSystem
Flavor
Host
MiqCimInstance
OrchestrationTemplate
OrchestrationStack
ResourcePool
SecurityGroup
Service
ServiceTemplate
Storage
VmOrTemplate
)
TAGGABLE_FILTER_CLASSES = CLASSES_THAT_PARTICIPATE_IN_RBAC - %w(EmsFolder)
BELONGSTO_FILTER_CLASSES = %w(
VmOrTemplate
Host
ExtManagementSystem
EmsFolder
EmsCluster
ResourcePool
Storage
)
# key: descendant::klass
# value:
# if it is a symbol/method_name:
# descendant.send(method_name) ==> klass
# if it is an array [klass_id, descendant_id]
# klass.where(klass_id => descendant.select(descendant_id))
MATCH_VIA_DESCENDANT_RELATIONSHIPS = {
"VmOrTemplate::ExtManagementSystem" => [:id, :ems_id],
"VmOrTemplate::Host" => [:id, :host_id],
"VmOrTemplate::EmsCluster" => [:id, :ems_cluster_id],
"VmOrTemplate::EmsFolder" => :parent_blue_folders,
"VmOrTemplate::ResourcePool" => :resource_pool,
"ConfiguredSystem::ExtManagementSystem" => :ext_management_system,
"ConfiguredSystem::ConfigurationProfile" => [:id, :configuration_profile_id],
}
# These classes should accept any of the relationship_mixin methods including:
# :parent_ids
# :ancestor_ids
# :child_ids
# :sibling_ids
# :descendant_ids
# ...
TENANT_ACCESS_STRATEGY = {
'CloudSnapshot' => :descendant_ids,
'CloudTenant' => :descendant_ids,
'CloudVolume' => :descendant_ids,
'ExtManagementSystem' => :ancestor_ids,
'MiqAeNamespace' => :ancestor_ids,
'MiqGroup' => :descendant_ids,
'MiqRequest' => :descendant_ids,
'MiqRequestTask' => nil, # tenant only
'MiqTemplate' => :ancestor_ids,
'Provider' => :ancestor_ids,
'ServiceTemplateCatalog' => :ancestor_ids,
'ServiceTemplate' => :ancestor_ids,
'Service' => :descendant_ids,
'Tenant' => :descendant_ids,
'User' => :descendant_ids,
'Vm' => :descendant_ids
}
include Vmdb::Logging
def self.search(*args)
new.search(*args)
end
def self.filtered(*args)
new.filtered(*args)
end
def self.filtered_object(*args)
new.filtered_object(*args)
end
def self.accessible_tenant_ids_strategy(klass)
TENANT_ACCESS_STRATEGY[klass.base_model.to_s]
end
# @param options filtering options
# @option options :targets [nil|Array<Numeric|Object>|scope] Objects to be filtered
# - an nil entry uses the optional where_clause
# - Array<Numeric> list if ids. :class is required. results are returned as ids
# - Array<Object> list of objects. results are returned as objects
# @option options :named_scope [Symbol|Array<String,Integer>] support for using named scope in search
# Example without args: :named_scope => :in_my_region
# Example with args: :named_scope => [in_region, 1]
# @option options :conditions [Hash|String|Array<String>]
# @option options :where_clause []
# @option options :sub_filter
# @option options :include_for_find [Array<Symbol>]
# @option options :filter
# @option options :user [User] (default: current_user)
# @option options :userid [String] User#userid (not user_id)
# @option options :miq_group [MiqGroup] (default: current_user.current_group)
# @option options :miq_group_id [Numeric]
# @option options :match_via_descendants [Hash]
# @option options :order [Numeric] (default: no order)
# @option options :limit [Numeric] (default: no limit)
# @option options :offset [Numeric] (default: no offset)
# @option options :apply_limit_in_sql [Boolean]
# @option options :ext_options
# @option options :skip_count [Boolean] (default: false)
# @return [Array<Array<Object>,Hash>] list of object and the associated search options
# Array<Object> list of object in the same order as input targets if possible
# @option attrs :auth_count [Numeric]
# @option attrs :user_filters
# @option attrs apply_limit_in_sql
# @option attrs target_ids_for_paging
def search(options = {})
if options.key?(:targets) && options[:targets].kind_of?(Array) && options[:targets].empty?
return [], {:auth_count => 0}
end
# => empty inputs - normal find with optional where_clause
# => list if ids - :class is required for this format.
# => list of objects
# results are returned in the same format as the targets. for empty targets, the default result format is a list of ids.
targets = options[:targets]
# Support for using named_scopes in search. Supports scopes with or without args:
# Example without args: :named_scope => :in_my_region
# Example with args: :named_scope => [in_region, 1]
scope = options[:named_scope]
klass = to_class(options[:class])
conditions = options[:conditions]
where_clause = options[:where_clause]
sub_filter = options[:sub_filter]
include_for_find = options[:include_for_find]
search_filter = options[:filter]
limit = options[:limit] || targets.try(:limit_value)
offset = options[:offset] || targets.try(:offset_value)
order = options[:order] || targets.try(:order_values)
user, miq_group, user_filters = get_user_info(options[:user],
options[:userid],
options[:miq_group],
options[:miq_group_id])
tz = user.try(:get_timezone)
attrs = {:user_filters => copy_hash(user_filters)}
ids_clause = nil
target_ids = nil
if targets.nil?
scope = apply_scope(klass, scope)
scope = apply_select(klass, scope, options[:extra_cols]) if options[:extra_cols]
elsif targets.kind_of?(Array)
if targets.first.kind_of?(Numeric)
target_ids = targets
# assume klass is passed in
else
target_ids = targets.collect(&:id)
klass = targets.first.class.base_class unless klass.respond_to?(:find)
end
scope = apply_scope(klass, scope)
scope = apply_select(klass, scope, options[:extra_cols]) if options[:extra_cols]
ids_clause = ["#{klass.table_name}.id IN (?)", target_ids] if klass.respond_to?(:table_name)
else # targets is a class_name, scope, class, or acts_as_ar_model class (VimPerformanceDaily in particular)
targets = to_class(targets).all
scope = apply_scope(targets, scope)
unless klass.respond_to?(:find)
klass = targets
klass = klass.klass if klass.respond_to?(:klass)
# working around MiqAeDomain not being in rbac_class
klass = klass.base_class if klass.respond_to?(:base_class) && rbac_class(klass).nil? && rbac_class(klass.base_class)
end
scope = apply_select(klass, scope, options[:extra_cols]) if options[:extra_cols]
end
user_filters['match_via_descendants'] = to_class(options[:match_via_descendants])
exp_sql, exp_includes, exp_attrs = search_filter.to_sql(tz) if search_filter && !klass.try(:instances_are_derived?)
attrs[:apply_limit_in_sql] = (exp_attrs.nil? || exp_attrs[:supported_by_sql]) && user_filters["belongsto"].blank?
# for belongs_to filters, scope_targets uses scope to make queries. want to remove limits for those.
# if you note, the limits are put back into scope a few lines down from here
scope = scope.except(:offset, :limit, :order)
scope = scope_targets(klass, scope, user_filters, user, miq_group)
.where(conditions).where(sub_filter).where(where_clause).where(exp_sql).where(ids_clause)
.includes(include_for_find).includes(exp_includes)
.order(order)
scope = include_references(scope, klass, include_for_find, exp_includes)
scope = scope.limit(limit).offset(offset) if attrs[:apply_limit_in_sql]
targets = scope
unless options[:skip_counts]
auth_count = attrs[:apply_limit_in_sql] && limit ? targets.except(:offset, :limit, :order).count(:all) : targets.length
end
if search_filter && targets && (!exp_attrs || !exp_attrs[:supported_by_sql])
rejects = targets.reject { |obj| matches_search_filters?(obj, search_filter, tz) }
auth_count -= rejects.length unless options[:skip_counts]
targets -= rejects
end
if limit && !attrs[:apply_limit_in_sql]
attrs[:target_ids_for_paging] = targets.collect(&:id) # Save ids of targets, since we have then all, to avoid going back to SQL for the next page
offset = offset.to_i
targets = targets[offset...(offset + limit.to_i)]
end
# Preserve sort order of incoming target_ids
if !target_ids.nil? && !order
targets = targets.sort_by { |a| target_ids.index(a.id) }
end
attrs[:auth_count] = auth_count unless options[:skip_counts]
return targets, attrs
end
def include_references(scope, klass, include_for_find, exp_includes)
ref_includes = Hash(include_for_find).merge(Hash(exp_includes))
unless polymorphic_include?(klass, ref_includes)
scope = scope.references(include_for_find).references(exp_includes)
end
scope
end
def polymorphic_include?(target_klass, includes)
includes.keys.any? do |incld|
reflection = target_klass.reflect_on_association(incld)
reflection && reflection.polymorphic?
end
end
def filtered(objects, options = {})
Rbac.search(options.reverse_merge(:targets => objects, :skip_counts => true)).first
end
def filtered_object(object, options = {})
filtered([object], options).first
end
private
##
# Determine if permissions should be applied directly via klass
# (klass directly participates in RBAC)
#
def apply_rbac_directly?(klass)
CLASSES_THAT_PARTICIPATE_IN_RBAC.include?(safe_base_class(klass).name)
end
##
# Determine if permissions should be applied via an associated parent class of klass
# If the klass is a metrics subclass, RBAC bases permissions checks on
# the associated application model. See #rbac_class method
#
def apply_rbac_through_association?(klass)
klass != VimPerformanceDaily && (klass < MetricRollup || klass < Metric)
end
def safe_base_class(klass)
klass = klass.base_class if klass.respond_to?(:base_class)
klass
end
def rbac_class(scope)
klass = scope.respond_to?(:klass) ? scope.klass : scope
return klass if apply_rbac_directly?(klass)
if apply_rbac_through_association?(klass)
# Strip "Performance" off class name, which is the associated model
# of that metric.
# e.g. HostPerformance => Host
# VmPerformance => VmOrTemplate
return klass.name[0..-12].constantize.base_class
end
nil
end
def pluck_ids(targets)
targets.pluck(:id) if targets
end
def get_self_service_objects(user, miq_group, klass)
return nil if miq_group.nil? || !miq_group.self_service? || !(klass < OwnershipMixin)
# for limited_self_service, use user's resources, not user.current_group's resources
# for reports (user = nil), still use miq_group
miq_group = nil if user && miq_group.limited_self_service?
# Get the list of objects that are owned by the user or their LDAP group
klass.user_or_group_owned(user, miq_group).except(:order)
end
def calc_filtered_ids(scope, user_filters, user, miq_group)
klass = scope.respond_to?(:klass) ? scope.klass : scope
u_filtered_ids = pluck_ids(get_self_service_objects(user, miq_group, klass))
b_filtered_ids = get_belongsto_filter_object_ids(klass, user_filters['belongsto'])
m_filtered_ids = pluck_ids(get_managed_filter_object_ids(scope, user_filters['managed']))
d_filtered_ids = pluck_ids(matches_via_descendants(rbac_class(klass), user_filters['match_via_descendants'],
:user => user, :miq_group => miq_group))
combine_filtered_ids(u_filtered_ids, b_filtered_ids, m_filtered_ids, d_filtered_ids)
end
#
# Algorithm: filter = u_filtered_ids UNION (b_filtered_ids INTERSECTION m_filtered_ids)
# filter = filter UNION d_filtered_ids if filter is not nil
#
# a nil as input for any field means it does not apply
# a nil as output means there is not filter
#
# @param u_filtered_ids [nil|Array<Integer>] self service user owned objects
# @param b_filtered_ids [nil|Array<Integer>] objects that belong to parent
# @param m_filtered_ids [nil|Array<Integer>] managed filter object ids
# @param d_filtered_ids [nil|Array<Integer>] ids from descendants
# @return nil if filters do not aply
# @return [Array<Integer>] target ids for filter
def combine_filtered_ids(u_filtered_ids, b_filtered_ids, m_filtered_ids, d_filtered_ids)
filtered_ids =
if b_filtered_ids.nil?
m_filtered_ids
elsif m_filtered_ids.nil?
b_filtered_ids
else
b_filtered_ids & m_filtered_ids
end
if u_filtered_ids.kind_of?(Array)
filtered_ids ||= []
filtered_ids += u_filtered_ids
end
if filtered_ids.kind_of?(Array)
filtered_ids += d_filtered_ids if d_filtered_ids.kind_of?(Array)
filtered_ids.uniq!
end
filtered_ids
end
# @param parent_class [Class] Class of parent (e.g. Host)
# @param klass [Class] Class of child node (e.g. Vm)
# @param scope [] scope for active records (e.g. Vm.archived)
# @param filtered_ids [nil|Array<Integer>] ids for the parent class (e.g. [1,2,3] for host)
# @return [Array<Array<Object>,Integer,Integer] targets, authorized count
def scope_by_parent_ids(parent_class, scope, filtered_ids)
if filtered_ids
if (reflection = scope.reflections[parent_class.name.underscore])
scope.where(reflection.foreign_key.to_sym => filtered_ids)
else
scope.where(:resource_type => parent_class.name, :resource_id => filtered_ids)
end
else
scope
end
end
def scope_by_ids(scope, filtered_ids)
if filtered_ids
scope.where(:id => filtered_ids)
else
scope
end
end
def get_belongsto_filter_object_ids(klass, filter)
return nil if !BELONGSTO_FILTER_CLASSES.include?(safe_base_class(klass).name) || filter.blank?
get_belongsto_matches(filter, rbac_class(klass)).collect(&:id)
end
def get_managed_filter_object_ids(scope, filter)
klass = scope.respond_to?(:klass) ? scope.klass : scope
return nil if !TAGGABLE_FILTER_CLASSES.include?(safe_base_class(klass).name) || filter.blank?
scope.find_tags_by_grouping(filter, :ns => '*').reorder(nil)
end
def scope_to_tenant(scope, user, miq_group)
klass = scope.respond_to?(:klass) ? scope.klass : scope
user_or_group = user || miq_group
tenant_id_clause = klass.tenant_id_clause(user_or_group)
tenant_id_clause ? scope.where(tenant_id_clause) : scope
end
##
# Main scoping method
#
def scope_targets(klass, scope, rbac_filters, user, miq_group)
# Results are scoped by tenant if the TenancyMixin is included in the class,
# with a few manual exceptions (User, Tenant). Note that the classes in
# TENANT_ACCESS_STRATEGY are a consolidated list of them.
if klass.respond_to?(:scope_by_tenant?) && klass.scope_by_tenant?
scope = scope_to_tenant(scope, user, miq_group)
end
if apply_rbac_directly?(klass)
filtered_ids = calc_filtered_ids(scope, rbac_filters, user, miq_group)
scope_by_ids(scope, filtered_ids)
elsif apply_rbac_through_association?(klass)
# if subclasses of MetricRollup or Metric, use the associated
# model to derive permissions from
associated_class = rbac_class(scope)
filtered_ids = calc_filtered_ids(associated_class, rbac_filters, user, miq_group)
scope_by_parent_ids(associated_class, scope, filtered_ids)
elsif klass == User && user.try!(:self_service?)
# Self service users searching for users only see themselves
scope.where(:id => user.id)
elsif klass == MiqGroup && miq_group.try!(:self_service?)
# Self Service users searching for groups only see their group
scope.where(:id => miq_group.id)
else
scope
end
end
def get_user_info(user, userid, miq_group, miq_group_id)
user, miq_group = lookup_user_group(user, userid, miq_group, miq_group_id)
[user, miq_group, lookup_user_filters(user || miq_group)]
end
def lookup_user_group(user, userid, miq_group, miq_group_id)
user ||= (userid && User.find_by_userid(userid)) || User.current_user
miq_group_id ||= miq_group.try!(:id)
return [user, user.current_group] if user && user.current_group_id.to_s == miq_group_id.to_s
if user
if miq_group_id && (detected_group = user.miq_groups.detect { |g| g.id.to_s == miq_group_id.to_s })
user.current_group = detected_group
elsif miq_group_id && user.super_admin_user?
user.current_group = miq_group || MiqGroup.find_by_id(miq_group_id)
end
else
miq_group ||= miq_group_id && MiqGroup.find_by_id(miq_group_id)
end
[user, user.try(:current_group) || miq_group]
end
# for reports, user is currently nil, so use the group filter
# the user.get_filters delegates to user.current_group anyway
def lookup_user_filters(miq_group)
filters = miq_group.try!(:get_filters).try!(:dup) || {}
filters["managed"] ||= []
filters["belongsto"] ||= []
filters
end
# @param klass [Class] base_class found in CLASSES_THAT_PARTICIPATE_IN_RBAC
# @option options :user [User]
# @option options :miq_group [MiqGroup]
def matches_via_descendants(klass, descendant_klass, options)
if descendant_klass && (method_name = lookup_method_for_descendant_class(klass, descendant_klass))
descendants = filtered(descendant_klass, options)
if method_name.kind_of?(Array)
klass_id, descendant_id = method_name
klass.where(klass_id => descendants.select(descendant_id)).distinct
else
MiqPreloader.preload(descendants, method_name)
descendants.flat_map { |object| object.send(method_name) }.grep(klass).uniq
end
end
end
def lookup_method_for_descendant_class(klass, descendant_klass)
key = "#{descendant_klass.base_class}::#{klass.base_class}"
MATCH_VIA_DESCENDANT_RELATIONSHIPS[key].tap do |method_name|
_log.warn "could not find method name for #{key}" if method_name.nil?
end
end
def to_class(klass)
klass.kind_of?(String) || klass.kind_of?(Symbol) ? klass.to_s.constantize : klass
end
def apply_scope(klass, scope)
klass = klass.all
scope_name = Array.wrap(scope).first
if scope_name.nil?
klass
elsif klass.nil? || !klass.respond_to?(scope_name)
class_name = klass.nil? ? "Object" : klass.name
raise _("Named scope '%{scope_name}' is not defined for class '%{class_name}'") % {:scope_name => scope_name,
:class_name => class_name}
else
klass.send(*scope)
end
end
def apply_select(klass, scope, extra_cols)
scope.select(scope.select_values.blank? ? klass.arel_table[Arel.star] : nil).select(extra_cols)
end
def get_belongsto_matches(blist, klass)
return get_belongsto_matches_for_host(blist) if klass == Host
return get_belongsto_matches_for_storage(blist) if klass == Storage
association_name = klass.base_model.to_s.tableize
blist.flat_map do |bfilter|
vcmeta_list = MiqFilter.belongsto2object_list(bfilter)
next [] if vcmeta_list.empty?
# typically, this is the only one we want:
vcmeta = vcmeta_list.last
if [ExtManagementSystem, Host].any? { |x| vcmeta.kind_of?(x) } && klass <= VmOrTemplate
vcmeta.send(association_name).to_a
else
vcmeta_list.grep(klass) + vcmeta.descendants.grep(klass)
end
end.uniq
end
def get_belongsto_matches_for_host(blist)
clusters = []
hosts = []
blist.each do |bfilter|
vcmeta = MiqFilter.belongsto2object(bfilter)
next unless vcmeta
subtree = vcmeta.subtree
clusters += subtree.grep(EmsCluster)
hosts += subtree.grep(Host)
end
MiqPreloader.preload_and_map(clusters, :hosts) + hosts
end
def get_belongsto_matches_for_storage(blist)
sources = blist.map do |bfilter|
MiqFilter.belongsto2object_list(bfilter).reverse.detect { |v| v.respond_to?(:storages) }
end.select(&:present?)
MiqPreloader.preload_and_map(sources, :storages)
end
def matches_search_filters?(obj, filter, tz)
filter.nil? || filter.lenient_evaluate(obj, tz)
end
end
end
Array determines list of disallowed roles for specific role
module Rbac
class Filterer
# This list is used to detemine whether RBAC, based on assigned tags, should be applied for a class in a search that is based on the class.
# Classes should be added to this list ONLY after:
# 1. It has been added to the MiqExpression::BASE_TABLES list
# 2. Tagging has been enabled in the UI
# 3. Class contains acts_as_miq_taggable
CLASSES_THAT_PARTICIPATE_IN_RBAC = %w(
AvailabilityZone
CloudTenant
CloudVolume
ConfigurationProfile
ConfiguredSystem
ConfigurationScriptBase
Container
ContainerBuild
ContainerGroup
ContainerImage
ContainerImageRegistry
ContainerNode
ContainerProject
ContainerReplicator
ContainerRoute
ContainerService
ContainerTemplate
EmsCluster
EmsFolder
ExtManagementSystem
Flavor
Host
MiqCimInstance
OrchestrationTemplate
OrchestrationStack
ResourcePool
SecurityGroup
Service
ServiceTemplate
Storage
VmOrTemplate
)
TAGGABLE_FILTER_CLASSES = CLASSES_THAT_PARTICIPATE_IN_RBAC - %w(EmsFolder)
BELONGSTO_FILTER_CLASSES = %w(
VmOrTemplate
Host
ExtManagementSystem
EmsFolder
EmsCluster
ResourcePool
Storage
)
# key: MiqUserRole#name - user's role
# value:
# array - disallowed roles for the user's role
DISALLOWED_ROLES_FOR_USER_ROLE = {
'EvmRole-tenant_administrator' => %w(EvmRole-super_administrator)
}.freeze
# key: descendant::klass
# value:
# if it is a symbol/method_name:
# descendant.send(method_name) ==> klass
# if it is an array [klass_id, descendant_id]
# klass.where(klass_id => descendant.select(descendant_id))
MATCH_VIA_DESCENDANT_RELATIONSHIPS = {
"VmOrTemplate::ExtManagementSystem" => [:id, :ems_id],
"VmOrTemplate::Host" => [:id, :host_id],
"VmOrTemplate::EmsCluster" => [:id, :ems_cluster_id],
"VmOrTemplate::EmsFolder" => :parent_blue_folders,
"VmOrTemplate::ResourcePool" => :resource_pool,
"ConfiguredSystem::ExtManagementSystem" => :ext_management_system,
"ConfiguredSystem::ConfigurationProfile" => [:id, :configuration_profile_id],
}
# These classes should accept any of the relationship_mixin methods including:
# :parent_ids
# :ancestor_ids
# :child_ids
# :sibling_ids
# :descendant_ids
# ...
TENANT_ACCESS_STRATEGY = {
'CloudSnapshot' => :descendant_ids,
'CloudTenant' => :descendant_ids,
'CloudVolume' => :descendant_ids,
'ExtManagementSystem' => :ancestor_ids,
'MiqAeNamespace' => :ancestor_ids,
'MiqGroup' => :descendant_ids,
'MiqRequest' => :descendant_ids,
'MiqRequestTask' => nil, # tenant only
'MiqTemplate' => :ancestor_ids,
'Provider' => :ancestor_ids,
'ServiceTemplateCatalog' => :ancestor_ids,
'ServiceTemplate' => :ancestor_ids,
'Service' => :descendant_ids,
'Tenant' => :descendant_ids,
'User' => :descendant_ids,
'Vm' => :descendant_ids
}
include Vmdb::Logging
def self.search(*args)
new.search(*args)
end
def self.filtered(*args)
new.filtered(*args)
end
def self.filtered_object(*args)
new.filtered_object(*args)
end
def self.accessible_tenant_ids_strategy(klass)
TENANT_ACCESS_STRATEGY[klass.base_model.to_s]
end
# @param options filtering options
# @option options :targets [nil|Array<Numeric|Object>|scope] Objects to be filtered
# - an nil entry uses the optional where_clause
# - Array<Numeric> list if ids. :class is required. results are returned as ids
# - Array<Object> list of objects. results are returned as objects
# @option options :named_scope [Symbol|Array<String,Integer>] support for using named scope in search
# Example without args: :named_scope => :in_my_region
# Example with args: :named_scope => [in_region, 1]
# @option options :conditions [Hash|String|Array<String>]
# @option options :where_clause []
# @option options :sub_filter
# @option options :include_for_find [Array<Symbol>]
# @option options :filter
# @option options :user [User] (default: current_user)
# @option options :userid [String] User#userid (not user_id)
# @option options :miq_group [MiqGroup] (default: current_user.current_group)
# @option options :miq_group_id [Numeric]
# @option options :match_via_descendants [Hash]
# @option options :order [Numeric] (default: no order)
# @option options :limit [Numeric] (default: no limit)
# @option options :offset [Numeric] (default: no offset)
# @option options :apply_limit_in_sql [Boolean]
# @option options :ext_options
# @option options :skip_count [Boolean] (default: false)
# @return [Array<Array<Object>,Hash>] list of object and the associated search options
# Array<Object> list of object in the same order as input targets if possible
# @option attrs :auth_count [Numeric]
# @option attrs :user_filters
# @option attrs apply_limit_in_sql
# @option attrs target_ids_for_paging
def search(options = {})
if options.key?(:targets) && options[:targets].kind_of?(Array) && options[:targets].empty?
return [], {:auth_count => 0}
end
# => empty inputs - normal find with optional where_clause
# => list if ids - :class is required for this format.
# => list of objects
# results are returned in the same format as the targets. for empty targets, the default result format is a list of ids.
targets = options[:targets]
# Support for using named_scopes in search. Supports scopes with or without args:
# Example without args: :named_scope => :in_my_region
# Example with args: :named_scope => [in_region, 1]
scope = options[:named_scope]
klass = to_class(options[:class])
conditions = options[:conditions]
where_clause = options[:where_clause]
sub_filter = options[:sub_filter]
include_for_find = options[:include_for_find]
search_filter = options[:filter]
limit = options[:limit] || targets.try(:limit_value)
offset = options[:offset] || targets.try(:offset_value)
order = options[:order] || targets.try(:order_values)
user, miq_group, user_filters = get_user_info(options[:user],
options[:userid],
options[:miq_group],
options[:miq_group_id])
tz = user.try(:get_timezone)
attrs = {:user_filters => copy_hash(user_filters)}
ids_clause = nil
target_ids = nil
if targets.nil?
scope = apply_scope(klass, scope)
scope = apply_select(klass, scope, options[:extra_cols]) if options[:extra_cols]
elsif targets.kind_of?(Array)
if targets.first.kind_of?(Numeric)
target_ids = targets
# assume klass is passed in
else
target_ids = targets.collect(&:id)
klass = targets.first.class.base_class unless klass.respond_to?(:find)
end
scope = apply_scope(klass, scope)
scope = apply_select(klass, scope, options[:extra_cols]) if options[:extra_cols]
ids_clause = ["#{klass.table_name}.id IN (?)", target_ids] if klass.respond_to?(:table_name)
else # targets is a class_name, scope, class, or acts_as_ar_model class (VimPerformanceDaily in particular)
targets = to_class(targets).all
scope = apply_scope(targets, scope)
unless klass.respond_to?(:find)
klass = targets
klass = klass.klass if klass.respond_to?(:klass)
# working around MiqAeDomain not being in rbac_class
klass = klass.base_class if klass.respond_to?(:base_class) && rbac_class(klass).nil? && rbac_class(klass.base_class)
end
scope = apply_select(klass, scope, options[:extra_cols]) if options[:extra_cols]
end
user_filters['match_via_descendants'] = to_class(options[:match_via_descendants])
exp_sql, exp_includes, exp_attrs = search_filter.to_sql(tz) if search_filter && !klass.try(:instances_are_derived?)
attrs[:apply_limit_in_sql] = (exp_attrs.nil? || exp_attrs[:supported_by_sql]) && user_filters["belongsto"].blank?
# for belongs_to filters, scope_targets uses scope to make queries. want to remove limits for those.
# if you note, the limits are put back into scope a few lines down from here
scope = scope.except(:offset, :limit, :order)
scope = scope_targets(klass, scope, user_filters, user, miq_group)
.where(conditions).where(sub_filter).where(where_clause).where(exp_sql).where(ids_clause)
.includes(include_for_find).includes(exp_includes)
.order(order)
scope = include_references(scope, klass, include_for_find, exp_includes)
scope = scope.limit(limit).offset(offset) if attrs[:apply_limit_in_sql]
targets = scope
unless options[:skip_counts]
auth_count = attrs[:apply_limit_in_sql] && limit ? targets.except(:offset, :limit, :order).count(:all) : targets.length
end
if search_filter && targets && (!exp_attrs || !exp_attrs[:supported_by_sql])
rejects = targets.reject { |obj| matches_search_filters?(obj, search_filter, tz) }
auth_count -= rejects.length unless options[:skip_counts]
targets -= rejects
end
if limit && !attrs[:apply_limit_in_sql]
attrs[:target_ids_for_paging] = targets.collect(&:id) # Save ids of targets, since we have then all, to avoid going back to SQL for the next page
offset = offset.to_i
targets = targets[offset...(offset + limit.to_i)]
end
# Preserve sort order of incoming target_ids
if !target_ids.nil? && !order
targets = targets.sort_by { |a| target_ids.index(a.id) }
end
attrs[:auth_count] = auth_count unless options[:skip_counts]
return targets, attrs
end
def include_references(scope, klass, include_for_find, exp_includes)
ref_includes = Hash(include_for_find).merge(Hash(exp_includes))
unless polymorphic_include?(klass, ref_includes)
scope = scope.references(include_for_find).references(exp_includes)
end
scope
end
def polymorphic_include?(target_klass, includes)
includes.keys.any? do |incld|
reflection = target_klass.reflect_on_association(incld)
reflection && reflection.polymorphic?
end
end
def filtered(objects, options = {})
Rbac.search(options.reverse_merge(:targets => objects, :skip_counts => true)).first
end
def filtered_object(object, options = {})
filtered([object], options).first
end
private
##
# Determine if permissions should be applied directly via klass
# (klass directly participates in RBAC)
#
def apply_rbac_directly?(klass)
CLASSES_THAT_PARTICIPATE_IN_RBAC.include?(safe_base_class(klass).name)
end
##
# Determine if permissions should be applied via an associated parent class of klass
# If the klass is a metrics subclass, RBAC bases permissions checks on
# the associated application model. See #rbac_class method
#
def apply_rbac_through_association?(klass)
klass != VimPerformanceDaily && (klass < MetricRollup || klass < Metric)
end
def safe_base_class(klass)
klass = klass.base_class if klass.respond_to?(:base_class)
klass
end
def rbac_class(scope)
klass = scope.respond_to?(:klass) ? scope.klass : scope
return klass if apply_rbac_directly?(klass)
if apply_rbac_through_association?(klass)
# Strip "Performance" off class name, which is the associated model
# of that metric.
# e.g. HostPerformance => Host
# VmPerformance => VmOrTemplate
return klass.name[0..-12].constantize.base_class
end
nil
end
def pluck_ids(targets)
targets.pluck(:id) if targets
end
def get_self_service_objects(user, miq_group, klass)
return nil if miq_group.nil? || !miq_group.self_service? || !(klass < OwnershipMixin)
# for limited_self_service, use user's resources, not user.current_group's resources
# for reports (user = nil), still use miq_group
miq_group = nil if user && miq_group.limited_self_service?
# Get the list of objects that are owned by the user or their LDAP group
klass.user_or_group_owned(user, miq_group).except(:order)
end
def calc_filtered_ids(scope, user_filters, user, miq_group)
klass = scope.respond_to?(:klass) ? scope.klass : scope
u_filtered_ids = pluck_ids(get_self_service_objects(user, miq_group, klass))
b_filtered_ids = get_belongsto_filter_object_ids(klass, user_filters['belongsto'])
m_filtered_ids = pluck_ids(get_managed_filter_object_ids(scope, user_filters['managed']))
d_filtered_ids = pluck_ids(matches_via_descendants(rbac_class(klass), user_filters['match_via_descendants'],
:user => user, :miq_group => miq_group))
combine_filtered_ids(u_filtered_ids, b_filtered_ids, m_filtered_ids, d_filtered_ids)
end
#
# Algorithm: filter = u_filtered_ids UNION (b_filtered_ids INTERSECTION m_filtered_ids)
# filter = filter UNION d_filtered_ids if filter is not nil
#
# a nil as input for any field means it does not apply
# a nil as output means there is not filter
#
# @param u_filtered_ids [nil|Array<Integer>] self service user owned objects
# @param b_filtered_ids [nil|Array<Integer>] objects that belong to parent
# @param m_filtered_ids [nil|Array<Integer>] managed filter object ids
# @param d_filtered_ids [nil|Array<Integer>] ids from descendants
# @return nil if filters do not aply
# @return [Array<Integer>] target ids for filter
def combine_filtered_ids(u_filtered_ids, b_filtered_ids, m_filtered_ids, d_filtered_ids)
filtered_ids =
if b_filtered_ids.nil?
m_filtered_ids
elsif m_filtered_ids.nil?
b_filtered_ids
else
b_filtered_ids & m_filtered_ids
end
if u_filtered_ids.kind_of?(Array)
filtered_ids ||= []
filtered_ids += u_filtered_ids
end
if filtered_ids.kind_of?(Array)
filtered_ids += d_filtered_ids if d_filtered_ids.kind_of?(Array)
filtered_ids.uniq!
end
filtered_ids
end
# @param parent_class [Class] Class of parent (e.g. Host)
# @param klass [Class] Class of child node (e.g. Vm)
# @param scope [] scope for active records (e.g. Vm.archived)
# @param filtered_ids [nil|Array<Integer>] ids for the parent class (e.g. [1,2,3] for host)
# @return [Array<Array<Object>,Integer,Integer] targets, authorized count
def scope_by_parent_ids(parent_class, scope, filtered_ids)
if filtered_ids
if (reflection = scope.reflections[parent_class.name.underscore])
scope.where(reflection.foreign_key.to_sym => filtered_ids)
else
scope.where(:resource_type => parent_class.name, :resource_id => filtered_ids)
end
else
scope
end
end
def scope_by_ids(scope, filtered_ids)
if filtered_ids
scope.where(:id => filtered_ids)
else
scope
end
end
def get_belongsto_filter_object_ids(klass, filter)
return nil if !BELONGSTO_FILTER_CLASSES.include?(safe_base_class(klass).name) || filter.blank?
get_belongsto_matches(filter, rbac_class(klass)).collect(&:id)
end
def get_managed_filter_object_ids(scope, filter)
klass = scope.respond_to?(:klass) ? scope.klass : scope
return nil if !TAGGABLE_FILTER_CLASSES.include?(safe_base_class(klass).name) || filter.blank?
scope.find_tags_by_grouping(filter, :ns => '*').reorder(nil)
end
def scope_to_tenant(scope, user, miq_group)
klass = scope.respond_to?(:klass) ? scope.klass : scope
user_or_group = user || miq_group
tenant_id_clause = klass.tenant_id_clause(user_or_group)
tenant_id_clause ? scope.where(tenant_id_clause) : scope
end
##
# Main scoping method
#
def scope_targets(klass, scope, rbac_filters, user, miq_group)
# Results are scoped by tenant if the TenancyMixin is included in the class,
# with a few manual exceptions (User, Tenant). Note that the classes in
# TENANT_ACCESS_STRATEGY are a consolidated list of them.
if klass.respond_to?(:scope_by_tenant?) && klass.scope_by_tenant?
scope = scope_to_tenant(scope, user, miq_group)
end
if apply_rbac_directly?(klass)
filtered_ids = calc_filtered_ids(scope, rbac_filters, user, miq_group)
scope_by_ids(scope, filtered_ids)
elsif apply_rbac_through_association?(klass)
# if subclasses of MetricRollup or Metric, use the associated
# model to derive permissions from
associated_class = rbac_class(scope)
filtered_ids = calc_filtered_ids(associated_class, rbac_filters, user, miq_group)
scope_by_parent_ids(associated_class, scope, filtered_ids)
elsif klass == User && user.try!(:self_service?)
# Self service users searching for users only see themselves
scope.where(:id => user.id)
elsif klass == MiqGroup && miq_group.try!(:self_service?)
# Self Service users searching for groups only see their group
scope.where(:id => miq_group.id)
else
scope
end
end
def get_user_info(user, userid, miq_group, miq_group_id)
user, miq_group = lookup_user_group(user, userid, miq_group, miq_group_id)
[user, miq_group, lookup_user_filters(user || miq_group)]
end
def lookup_user_group(user, userid, miq_group, miq_group_id)
user ||= (userid && User.find_by_userid(userid)) || User.current_user
miq_group_id ||= miq_group.try!(:id)
return [user, user.current_group] if user && user.current_group_id.to_s == miq_group_id.to_s
if user
if miq_group_id && (detected_group = user.miq_groups.detect { |g| g.id.to_s == miq_group_id.to_s })
user.current_group = detected_group
elsif miq_group_id && user.super_admin_user?
user.current_group = miq_group || MiqGroup.find_by_id(miq_group_id)
end
else
miq_group ||= miq_group_id && MiqGroup.find_by_id(miq_group_id)
end
[user, user.try(:current_group) || miq_group]
end
# for reports, user is currently nil, so use the group filter
# the user.get_filters delegates to user.current_group anyway
def lookup_user_filters(miq_group)
filters = miq_group.try!(:get_filters).try!(:dup) || {}
filters["managed"] ||= []
filters["belongsto"] ||= []
filters
end
# @param klass [Class] base_class found in CLASSES_THAT_PARTICIPATE_IN_RBAC
# @option options :user [User]
# @option options :miq_group [MiqGroup]
def matches_via_descendants(klass, descendant_klass, options)
if descendant_klass && (method_name = lookup_method_for_descendant_class(klass, descendant_klass))
descendants = filtered(descendant_klass, options)
if method_name.kind_of?(Array)
klass_id, descendant_id = method_name
klass.where(klass_id => descendants.select(descendant_id)).distinct
else
MiqPreloader.preload(descendants, method_name)
descendants.flat_map { |object| object.send(method_name) }.grep(klass).uniq
end
end
end
def lookup_method_for_descendant_class(klass, descendant_klass)
key = "#{descendant_klass.base_class}::#{klass.base_class}"
MATCH_VIA_DESCENDANT_RELATIONSHIPS[key].tap do |method_name|
_log.warn "could not find method name for #{key}" if method_name.nil?
end
end
def to_class(klass)
klass.kind_of?(String) || klass.kind_of?(Symbol) ? klass.to_s.constantize : klass
end
def apply_scope(klass, scope)
klass = klass.all
scope_name = Array.wrap(scope).first
if scope_name.nil?
klass
elsif klass.nil? || !klass.respond_to?(scope_name)
class_name = klass.nil? ? "Object" : klass.name
raise _("Named scope '%{scope_name}' is not defined for class '%{class_name}'") % {:scope_name => scope_name,
:class_name => class_name}
else
klass.send(*scope)
end
end
def apply_select(klass, scope, extra_cols)
scope.select(scope.select_values.blank? ? klass.arel_table[Arel.star] : nil).select(extra_cols)
end
def get_belongsto_matches(blist, klass)
return get_belongsto_matches_for_host(blist) if klass == Host
return get_belongsto_matches_for_storage(blist) if klass == Storage
association_name = klass.base_model.to_s.tableize
blist.flat_map do |bfilter|
vcmeta_list = MiqFilter.belongsto2object_list(bfilter)
next [] if vcmeta_list.empty?
# typically, this is the only one we want:
vcmeta = vcmeta_list.last
if [ExtManagementSystem, Host].any? { |x| vcmeta.kind_of?(x) } && klass <= VmOrTemplate
vcmeta.send(association_name).to_a
else
vcmeta_list.grep(klass) + vcmeta.descendants.grep(klass)
end
end.uniq
end
def get_belongsto_matches_for_host(blist)
clusters = []
hosts = []
blist.each do |bfilter|
vcmeta = MiqFilter.belongsto2object(bfilter)
next unless vcmeta
subtree = vcmeta.subtree
clusters += subtree.grep(EmsCluster)
hosts += subtree.grep(Host)
end
MiqPreloader.preload_and_map(clusters, :hosts) + hosts
end
def get_belongsto_matches_for_storage(blist)
sources = blist.map do |bfilter|
MiqFilter.belongsto2object_list(bfilter).reverse.detect { |v| v.respond_to?(:storages) }
end.select(&:present?)
MiqPreloader.preload_and_map(sources, :storages)
end
def matches_search_filters?(obj, filter, tz)
filter.nil? || filter.lenient_evaluate(obj, tz)
end
end
end
|
require 'rbbt/util/misc'
require 'rbbt/util/log'
require 'stringio'
module CMD
class CMDError < StandardError; end
module SmartIO
attr_accessor :pid, :cmd, :post, :in, :out, :err, :log
def self.tie(io, pid = nil, cmd = "", post = nil, sin = nil, out = nil, err = nil, log = true)
io.extend SmartIO
io.pid = pid
io.cmd = cmd
io.in = sin
io.out = out
io.err = err
io.post = post
io.log = log
io.class.send(:alias_method, :original_close, :close)
io.class.send(:alias_method, :original_read, :read)
io
end
def wait_and_status
if @pid
begin
Process.waitpid(@pid)
rescue
end
Log.debug "Process #{ cmd } succeded" if $? and $?.success? and log
if $? and not $?.success?
Log.debug "Raising exception" if log
exception = CMDError.new "Command [#{@pid}] #{@cmd} failed with error status #{$?.exitstatus}"
original_close
raise exception
end
end
end
def close
self.original_read unless self.eof?
wait_and_status
@post.call if @post
original_close unless self.closed?
end
def force_close
if @pid
Log.debug "Forcing close by killing '#{@pid}'" if log
Process.kill("KILL", @pid)
Process.waitpid(@pid)
end
@post.call if @post
original_close
end
def read(*args)
data = original_read(*args)
self.close if self.eof?
data
end
end
def self.process_cmd_options(options = {})
string = ""
options.each do |option, value|
case
when value.nil? || FalseClass === value
next
when TrueClass === value
string << "#{option} "
else
if option.chars.to_a.last == "="
string << "#{option}#{value} "
else
string << "#{option} #{value} "
end
end
end
string.strip
end
def self.cmd(cmd, options = {}, &block)
options = Misc.add_defaults options, :stderr => Log::DEBUG
in_content = options.delete(:in)
stderr = options.delete(:stderr)
pipe = options.delete(:pipe)
post = options.delete(:post)
log = options.delete(:log)
log = true if log.nil?
if stderr == true
stderr = Log::HIGH
end
# Process cmd_options
cmd_options = process_cmd_options options
if cmd =~ /'\{opt\}'/
cmd.sub!('\'{opt}\'', cmd_options)
else
cmd << " " << cmd_options
end
in_content = StringIO.new in_content if String === in_content
sout, serr, sin = IO.pipe, IO.pipe, IO.pipe
pid = fork {
begin
sin.last.close
sout.first.close
serr.first.close
io = in_content
while IO === io
if SmartIO === io
io.original_close unless io.closed?
io.out.close unless io.out.nil? or io.out.closed?
io.err.close unless io.err.nil? or io.err.closed?
io = io.in
else
io.close unless io.closed?
io = nil
end
end
STDIN.reopen sin.first
sin.first.close
STDERR.reopen serr.last
serr.last.close
STDOUT.reopen sout.last
sout.last.close
STDOUT.sync = STDERR.sync = true
exec(cmd)
exit(-1)
rescue Exception
Log.debug("CMDError: #{$!.message}") if log
ddd $!.backtrace if log
raise CMDError, $!.message
end
}
sin.first.close
sout.last.close
serr.last.close
sin = sin.last
sout = sout.first
serr = serr.first
Log.debug "CMD: [#{pid}] #{cmd}" if log
if in_content.respond_to?(:read)
Thread.new do
begin
loop do
break if in_content.closed?
block = in_content.read 1024
break if block.nil? or block.empty?
sin.write block
end
sin.close unless sin.closed?
in_content.close unless in_content.closed?
rescue
Process.kill "INT", pid
raise $!
end
end
else
sin.close
end
if pipe
Thread.new do
while line = serr.gets
Log.log line, stderr if Integer === stderr and log
end
serr.close
Thread.exit
end
SmartIO.tie sout, pid, cmd, post, in_content, sin, serr
sout
else
err = ""
Thread.new do
while not serr.eof?
err << serr.gets if Integer === stderr
end
serr.close
Thread.exit
end
out = StringIO.new sout.read
sout.close unless sout.closed?
SmartIO.tie out, pid, cmd, post, in_content, sin, serr
Process.waitpid pid
if not $?.success?
exception = CMDError.new "Command [#{pid}] #{cmd} failed with error status #{$?.exitstatus}.\n#{err}"
raise exception
else
Log.log err, stderr if Integer === stderr and log
end
out
end
end
end
Bug in symbols as CMD options
require 'rbbt/util/misc'
require 'rbbt/util/log'
require 'stringio'
module CMD
class CMDError < StandardError; end
module SmartIO
attr_accessor :pid, :cmd, :post, :in, :out, :err, :log
def self.tie(io, pid = nil, cmd = "", post = nil, sin = nil, out = nil, err = nil, log = true)
io.extend SmartIO
io.pid = pid
io.cmd = cmd
io.in = sin
io.out = out
io.err = err
io.post = post
io.log = log
io.class.send(:alias_method, :original_close, :close)
io.class.send(:alias_method, :original_read, :read)
io
end
def wait_and_status
if @pid
begin
Process.waitpid(@pid)
rescue
end
Log.debug "Process #{ cmd } succeded" if $? and $?.success? and log
if $? and not $?.success?
Log.debug "Raising exception" if log
exception = CMDError.new "Command [#{@pid}] #{@cmd} failed with error status #{$?.exitstatus}"
original_close
raise exception
end
end
end
def close
self.original_read unless self.eof?
wait_and_status
@post.call if @post
original_close unless self.closed?
end
def force_close
if @pid
Log.debug "Forcing close by killing '#{@pid}'" if log
Process.kill("KILL", @pid)
Process.waitpid(@pid)
end
@post.call if @post
original_close
end
def read(*args)
data = original_read(*args)
self.close if self.eof?
data
end
end
def self.process_cmd_options(options = {})
string = ""
options.each do |option, value|
case
when value.nil? || FalseClass === value
next
when TrueClass === value
string << "#{option} "
else
if option.to_s.chars.to_a.last == "="
string << "#{option}#{value} "
else
string << "#{option} #{value} "
end
end
end
string.strip
end
def self.cmd(cmd, options = {}, &block)
options = Misc.add_defaults options, :stderr => Log::DEBUG
in_content = options.delete(:in)
stderr = options.delete(:stderr)
pipe = options.delete(:pipe)
post = options.delete(:post)
log = options.delete(:log)
log = true if log.nil?
if stderr == true
stderr = Log::HIGH
end
# Process cmd_options
cmd_options = process_cmd_options options
if cmd =~ /'\{opt\}'/
cmd.sub!('\'{opt}\'', cmd_options)
else
cmd << " " << cmd_options
end
in_content = StringIO.new in_content if String === in_content
sout, serr, sin = IO.pipe, IO.pipe, IO.pipe
pid = fork {
begin
sin.last.close
sout.first.close
serr.first.close
io = in_content
while IO === io
if SmartIO === io
io.original_close unless io.closed?
io.out.close unless io.out.nil? or io.out.closed?
io.err.close unless io.err.nil? or io.err.closed?
io = io.in
else
io.close unless io.closed?
io = nil
end
end
STDIN.reopen sin.first
sin.first.close
STDERR.reopen serr.last
serr.last.close
STDOUT.reopen sout.last
sout.last.close
STDOUT.sync = STDERR.sync = true
exec(cmd)
exit(-1)
rescue Exception
Log.debug("CMDError: #{$!.message}") if log
ddd $!.backtrace if log
raise CMDError, $!.message
end
}
sin.first.close
sout.last.close
serr.last.close
sin = sin.last
sout = sout.first
serr = serr.first
Log.debug "CMD: [#{pid}] #{cmd}" if log
if in_content.respond_to?(:read)
Thread.new do
begin
loop do
break if in_content.closed?
block = in_content.read 1024
break if block.nil? or block.empty?
sin.write block
end
sin.close unless sin.closed?
in_content.close unless in_content.closed?
rescue
Process.kill "INT", pid
raise $!
end
end
else
sin.close
end
if pipe
Thread.new do
while line = serr.gets
Log.log line, stderr if Integer === stderr and log
end
serr.close
Thread.exit
end
SmartIO.tie sout, pid, cmd, post, in_content, sin, serr
sout
else
err = ""
Thread.new do
while not serr.eof?
err << serr.gets if Integer === stderr
end
serr.close
Thread.exit
end
out = StringIO.new sout.read
sout.close unless sout.closed?
SmartIO.tie out, pid, cmd, post, in_content, sin, serr
Process.waitpid pid
if not $?.success?
exception = CMDError.new "Command [#{pid}] #{cmd} failed with error status #{$?.exitstatus}.\n#{err}"
raise exception
else
Log.log err, stderr if Integer === stderr and log
end
out
end
end
end
|
require 'rbbt/workflow/definition'
require 'rbbt/workflow/dependencies'
require 'rbbt/workflow/task'
require 'rbbt/workflow/step'
require 'rbbt/workflow/accessor'
require 'rbbt/workflow/doc'
require 'rbbt/workflow/examples'
require 'rbbt/workflow/util/archive'
require 'rbbt/workflow/util/provenance'
module Workflow
class TaskNotFoundException < Exception
def initialize(workflow, task = nil)
if task
super "Task '#{ task }' not found in #{ workflow } workflow"
else
super workflow
end
end
end
#{{{ WORKFLOW MANAGEMENT
class << self
attr_accessor :workflows, :autoinstall, :workflow_dir
end
self.workflows = []
def self.autoinstall
@autoload ||= ENV["RBBT_WORKFLOW_AUTOINSTALL"] == "true"
end
def self.extended(base)
self.workflows << base
libdir = Path.caller_lib_dir
return if libdir.nil?
base.libdir = Path.setup(libdir).tap{|p| p.resource = base}
end
def self.init_remote_tasks
return if defined? @@init_remote_tasks and @@init_remote_tasks
@@init_remote_tasks = true
load_remote_tasks(Rbbt.root.etc.remote_tasks.find) if Rbbt.root.etc.remote_tasks.exists?
end
def self.require_remote_workflow(wf_name, url)
require 'rbbt/workflow/remote_workflow'
eval "Object::#{wf_name.split("+").first} = RemoteWorkflow.new '#{ url }', '#{wf_name}'"
end
def self.load_workflow_libdir(filename)
workflow_lib_dir = File.join(File.dirname(File.expand_path(filename)), 'lib')
if File.directory? workflow_lib_dir
Log.debug "Adding workflow lib directory to LOAD_PATH: #{workflow_lib_dir}"
$LOAD_PATH.unshift(workflow_lib_dir)
end
end
def self.load_workflow_file(filename)
begin
load_workflow_libdir(filename)
filename = File.expand_path(filename)
Rbbt.add_version(filename)
require filename
Log.debug{"Workflow loaded from: #{ filename }"}
return true
rescue Exception
Log.warn{"Error loading workflow: #{ filename }"}
raise $!
end
end
def self.installed_workflows
self.workflow_dir['**/workflow.rb'].glob_all.collect do |file|
File.basename(File.dirname(file))
end
end
def self.workflow_dir
@workflow_dir ||= begin
case
when (defined?(Rbbt) and Rbbt.etc.workflow_dir.exists?)
dir = Rbbt.etc.workflow_dir.read.strip
dir = File.expand_path(dir)
Path.setup(dir)
when defined?(Rbbt)
Rbbt.workflows
else
dir = File.join(ENV['HOME'], '.workflows')
Path.setup(dir)
end
end
end
def self.local_workflow_filename(wf_name)
filename = nil
if Path === wf_name
case
# Points to workflow file
when ((File.exist?(wf_name.find) and not File.directory?(wf_name.find)) or File.exist?(wf_name.find + '.rb'))
filename = wf_name.find
# Points to workflow dir
when (File.exist?(wf_name.find) and File.directory?(wf_name.find) and File.exist?(File.join(wf_name.find, 'workflow.rb')))
filename = wf_name['workflow.rb'].find
end
else
if ((File.exist?(wf_name) and not File.directory?(wf_name)) or File.exist?(wf_name + '.rb'))
filename = (wf_name =~ /\.?\//) ? wf_name : "./" << wf_name
else
filename = workflow_dir[wf_name]['workflow.rb'].find
end
end
if filename.nil? or not File.exist?(filename)
wf_name_snake = Misc.snake_case(wf_name)
return local_workflow_filename(wf_name_snake) if wf_name_snake != wf_name
end
filename
end
def self.require_local_workflow(wf_name)
filename = local_workflow_filename(wf_name)
if filename and File.exist?(filename)
load_workflow_file filename
else
return false
end
end
def self.require_workflow(wf_name, force_local=false)
Workflow.init_remote_tasks
# Already loaded
begin
workflow = Misc.string2const wf_name
Log.debug{"Workflow #{ wf_name } already loaded"}
return workflow
rescue Exception
end
# Load remotely
if not force_local and Rbbt.etc.remote_workflows.exists?
remote_workflows = Rbbt.etc.remote_workflows.yaml
if Hash === remote_workflows and remote_workflows.include?(wf_name)
url = remote_workflows[wf_name]
begin
return require_remote_workflow(wf_name, url)
ensure
Log.debug{"Workflow #{ wf_name } loaded remotely: #{ url }"}
end
end
end
if Open.remote?(wf_name) or Open.ssh?(wf_name)
url = wf_name
if Open.ssh?(wf_name)
wf_name = File.basename(url.split(":").last)
else
wf_name = File.basename(url)
end
begin
return require_remote_workflow(wf_name, url)
ensure
Log.debug{"Workflow #{ wf_name } loaded remotely: #{ url }"}
end
end
# Load locally
if wf_name =~ /::\w+$/
clean_name = wf_name.sub(/::.*/,'')
Log.info{"Looking for '#{wf_name}' in '#{clean_name}'"}
require_workflow clean_name
workflow = Misc.string2const Misc.camel_case(wf_name)
workflow.load_documentation
return workflow
end
Log.high{"Loading workflow #{wf_name}"}
first = nil
wf_name.split("+").each do |wf_name|
require_local_workflow(wf_name) or
(Workflow.autoinstall and `rbbt workflow install #{Misc.snake_case(wf_name)} || rbbt workflow install #{wf_name}` and require_local_workflow(wf_name)) or raise("Workflow not found or could not be loaded: #{ wf_name }")
workflow = begin
Misc.string2const Misc.camel_case(wf_name.split("+").first)
rescue
Workflow.workflows.last || true
end
workflow.load_documentation
first ||= workflow
end
return first
workflow
end
attr_accessor :description
attr_accessor :libdir, :workdir
attr_accessor :helpers, :tasks
attr_accessor :task_dependencies, :task_description, :last_task
attr_accessor :stream_exports, :asynchronous_exports, :synchronous_exports, :exec_exports
attr_accessor :step_cache
attr_accessor :load_step_cache
attr_accessor :remote_tasks
#{{{ ATTR DEFAULTS
def self.workdir=(path)
path = Path.setup path.dup unless Path === path
@@workdir = path
end
def self.workdir
@@workdir ||= if defined? Rbbt
Rbbt.var.jobs
else
Path.setup('var/jobs')
end
end
TAG = ENV["RBBT_INPUT_JOBNAME"] == "true" ? :inputs : :hash
DEBUG_JOB_HASH = ENV["RBBT_DEBUG_JOB_HASH"] == 'true'
def step_path(taskname, jobname, inputs, dependencies, extension = nil)
raise "Jobname makes an invalid path: #{ jobname }" if jobname.include? '..'
if inputs.length > 0 or dependencies.any?
tagged_jobname = case TAG
when :hash
clean_inputs = Annotated.purge(inputs)
clean_inputs = clean_inputs.collect{|i| Symbol === i ? i.to_s : i }
deps_str = dependencies.collect{|d| (Step === d || (defined?(RemoteStep) && RemoteStep === Step)) ? "Step: " << (d.overriden? ? d.path : d.short_path) : d }
key_obj = {:inputs => clean_inputs, :dependencies => deps_str }
key_str = Misc.obj2str(key_obj)
hash_str = Misc.digest(key_str)
Log.debug "Hash for '#{[taskname, jobname] * "/"}' #{hash_str} for #{key_str}" if DEBUG_JOB_HASH
jobname + '_' << hash_str
when :inputs
all_inputs = {}
inputs.zip(self.task_info(taskname)[:inputs]) do |i,f|
all_inputs[f] = i
end
dependencies.each do |dep|
ri = dep.recursive_inputs
ri.zip(ri.fields).each do |i,f|
all_inputs[f] = i
end
end
all_inputs.any? ? jobname + '_' << Misc.obj2str(all_inputs) : jobname
else
jobname
end
else
tagged_jobname = jobname
end
if extension and not extension.empty?
tagged_jobname = tagged_jobname + ('.' << extension.to_s)
end
workdir[taskname][tagged_jobname].find
end
def import_task(workflow, orig, new)
orig_task = workflow.tasks[orig]
new_task = orig_task.dup
options = {}
orig_task.singleton_methods.
select{|method| method.to_s[-1] != "="[0]}.each{|method|
if orig_task.respond_to?(method.to_s + "=")
options[method.to_s] = orig_task.send(method.to_s)
end
}
Task.setup(options, &new_task)
new_task.workflow = self
new_task.name = new
tasks[new] = new_task
task_dependencies[new] = workflow.task_dependencies[orig]
task_description[new] = workflow.task_description[orig]
end
def workdir=(path)
path = Path.setup path.dup unless Path === path
@workdir = path
end
def workdir
@workdir ||= begin
text = Module === self ? self.to_s : "Misc"
Workflow.workdir[text]
end
end
def libdir
@libdir = Path.setup(Path.caller_lib_dir) if @libdir.nil?
@libdir
end
def step_cache
Thread.current[:step_cache] ||= {}
end
def self.load_step_cache
Thread.current[:load_step_cache] ||= {}
end
def helpers
@helpers ||= {}
end
def tasks
@tasks ||= {}
end
def task_dependencies
@task_dependencies ||= {}
end
def task_description
@task_description ||= {}
end
def stream_exports
@stream_exports ||= []
end
def asynchronous_exports
@asynchronous_exports ||= []
end
def synchronous_exports
@synchronous_exports ||= []
end
def exec_exports
@exec_exports ||= []
end
def all_exports
@all_exports ||= asynchronous_exports + synchronous_exports + exec_exports + stream_exports
end
# {{{ JOB MANAGEMENT
DEFAULT_NAME="Default"
def self.resolve_locals(inputs)
inputs.each do |name, value|
if (String === value and value =~ /^local:(.*?):(.*)/) or
(Array === value and value.length == 1 and value.first =~ /^local:(.*?):(.*)/) or
(TSV === value and value.size == 1 and value.keys.first =~ /^local:(.*?):(.*)/)
task_name = $1
jobname = $2
value = load_id(File.join(task_name, jobname)).load
inputs[name] = value
end
end
end
def step_module
@_m ||= begin
m = Module.new
helpers.each do |name,block|
m.send(:define_method, name, &block)
end
m
end
@_m
end
def __job(taskname, jobname = nil, inputs = {})
taskname = taskname.to_sym
return remote_tasks[taskname].job(taskname, jobname, inputs) if remote_tasks and remote_tasks.include? taskname
task = tasks[taskname]
raise "Task not found: #{ taskname }" if task.nil?
inputs = IndiferentHash.setup(inputs)
not_overriden = inputs.delete :not_overriden
if not_overriden
inputs[:not_overriden] = :not_overriden_dep
end
Workflow.resolve_locals(inputs)
task_info = task_info(taskname)
task_inputs = task_info[:inputs]
#defaults = IndiferentHash.setup(task_info[:input_defaults]).merge(task.input_defaults)
all_defaults = IndiferentHash.setup(task_info[:input_defaults])
defaults = IndiferentHash.setup(task.input_defaults)
missing_inputs = []
task.required_inputs.each do |input|
missing_inputs << input if inputs[input].nil?
end if task.required_inputs
if missing_inputs.length == 1
raise ParameterException, "Input #{missing_inputs.first} is required but was not provided or is nil"
end
if missing_inputs.length > 1
raise ParameterException, "Inputs #{Misc.humanize_list(missing_inputs)} are required but were not provided or are nil"
end
# jobname => true sets the value of the input to the name of the job
if task.input_options
jobname_input = task.input_options.select{|i,o| o[:jobname]}.collect{|i,o| i }.first
else
jobname_input = nil
end
if jobname_input && jobname && inputs[jobname_input].nil?
inputs[jobname_input] = jobname
end
real_inputs = {}
has_overriden_inputs = false
inputs.each do |k,v|
#has_overriden_inputs = true if String === k and k.include? "#"
next unless (task_inputs.include?(k.to_sym) or task_inputs.include?(k.to_s))
default = all_defaults[k]
next if default == v
next if (String === default and Symbol === v and v.to_s == default)
next if (Symbol === default and String === v and v == default.to_s)
real_inputs[k.to_sym] = v
end
jobname_input_value = inputs[jobname_input] || all_defaults[jobname_input]
if jobname_input && jobname.nil? && String === jobname_input_value && ! jobname_input_value.include?('/')
jobname = jobname_input_value
end
jobname = DEFAULT_NAME if jobname.nil? or jobname.empty?
dependencies = real_dependencies(task, jobname, defaults.merge(inputs), task_dependencies[taskname] || [])
overriden_deps = dependencies.select{|d| d.overriden }
true_overriden_deps = overriden_deps.select{|d| TrueClass === d.overriden }
overriden = has_overriden_inputs || overriden_deps.any?
extension = task.extension
if extension == :dep_task
extension = nil
if dependencies.any?
dep_basename = File.basename(dependencies.last.path)
extension = dep_basename.split(".").last if dep_basename.include?('.')
end
end
if real_inputs.empty? && Workflow::TAG != :inputs && ! overriden
step_path = step_path taskname, jobname, [], [], extension
input_values = task.take_input_values(inputs)
else
input_values = task.take_input_values(inputs)
step_path = step_path taskname, jobname, input_values, dependencies, extension
end
job = get_job_step step_path, task, input_values, dependencies
job.workflow = self
job.clean_name = jobname
case not_overriden
when TrueClass
job.overriden = has_overriden_inputs || true_overriden_deps.any?
when :not_overriden_dep
job.overriden = true if has_overriden_inputs || true_overriden_deps.any?
else
job.overriden = true if has_overriden_inputs || overriden_deps.any?
end
job.real_inputs = real_inputs.keys
job
end
def _job(taskname, jobname = nil, inputs = {})
_inputs = IndiferentHash.setup(inputs.dup)
task_info = task_info(taskname)
task_inputs = task_info[:inputs]
persist_inputs = inputs.values_at(*task_inputs)
persist_inputs += inputs.values_at(*inputs.keys.select{|k| String === k && k.include?("#") }.sort)
Persist.memory("STEP", :workflow => self.to_s, :taskname => taskname, :jobname => jobname, :inputs => persist_inputs, :repo => step_cache) do
__job(taskname, jobname, inputs)
end
end
def job(taskname, jobname = nil, inputs = {})
begin
_job(taskname, jobname, inputs)
ensure
step_cache.clear
end
end
def set_step_dependencies(step)
if step.info[:dependencies]
Misc.insist do
step.dependencies = step.info[:dependencies].collect do |task, job, path|
next if job.nil?
if Open.exists?(path)
load_step(path)
else
Workflow.load_step(path)
end
end
end
end
end
#{{{ LOAD FROM FILE
def get_job_step(step_path, task = nil, input_values = nil, dependencies = nil)
step_path = step_path.call if Proc === step_path
persist = input_values.nil? ? false : true
persist = false
key = Path === step_path ? step_path.find : step_path
step = Step.new step_path, task, input_values, dependencies
set_step_dependencies(step) unless dependencies
step.extend step_module
step.task ||= task
step.inputs ||= input_values
step.dependencies = dependencies if dependencies and (step.dependencies.nil? or step.dependencies.length < dependencies.length)
step
end
def load_step(path)
task = task_for path
if task
get_job_step path, tasks[task.to_sym]
else
get_job_step path
end
end
def self.transplant(listed, real, other)
if listed.nil?
parts = real.split("/")
other_parts = other.split("/")
listed = (other_parts[0..-4] + parts[-3..-1]) * "/"
end
sl = listed.split("/", -1)
so = other.split("/", -1)
sr = real.split("/", -1)
prefix = []
while true
break if sl[0] != so[0]
cl = sl.shift
co = so.shift
prefix << cl
end
File.join(sr - sl + so)
end
def self.relocate_array(real, list)
preal = real.split(/\/+/)
prefix = preal[0..-4] * "/"
list.collect do |other|
pother = other.split(/\/+/)
end_part = pother[-3..-1] * "/"
new_path = prefix + "/" << end_part
if File.exists? new_path
new_path
else
Rbbt.var.jobs[end_part].find
end
end
end
def self.relocate(real, other)
preal = real.split(/\/+/)
pother = other.split(/\/+/)
end_part = pother[-3..-1] * "/"
new_path = preal[0..-4] * "/" << "/" << end_part
return new_path if File.exists?(new_path) || File.exists?(new_path + '.info')
Rbbt.var.jobs[end_part].find
end
def self.relocate_dependency(main, dep)
dep_path = dep.path
path = main.path
if Open.exists?(dep_path) || Open.exists?(dep_path + '.info')
dep
else
new_path = relocate(path, dep_path)
relocated = true if Open.exists?(new_path) || Open.exists?(new_path + '.info')
Workflow._load_step new_path
end
end
def self.__load_step(path)
if Open.remote?(path) || Open.ssh?(path)
require 'rbbt/workflow/remote_workflow'
return RemoteWorkflow.load_path path
end
step = Step.new path
relocated = false
step.dependencies = (step.info[:dependencies] || []).collect do |task,name,dep_path|
if Open.exists?(dep_path) || Open.exists?(dep_path + '.info') || Open.remote?(dep_path) || Open.ssh?(dep_path)
Workflow._load_step dep_path
else
new_path = relocate(path, dep_path)
relocated = true if Open.exists?(new_path) || Open.exists?(new_path + '.info')
Workflow._load_step new_path
end
end
step.relocated = relocated
step.load_inputs_from_info
step
end
def self.fast_load_step(path)
if Open.remote?(path) || Open.ssh?(path)
require 'rbbt/workflow/remote_workflow'
return RemoteWorkflow.load_path path
end
step = Step.new path
step.dependencies = nil
class << step
def dependencies
@dependencies ||= (self.info[:dependencies] || []).collect do |task,name,dep_path|
dep = if Open.exists?(dep_path) || Open.exists?(dep_path + '.info')
relocate = false
Workflow.fast_load_step dep_path
else
new_path = Workflow.relocate(path, dep_path)
relocated = true if Open.exists?(new_path) || Open.exists?(new_path + '.info')
Workflow.fast_load_step new_path
end
dep.relocated = relocated
dep
end
@dependencies
end
def inputs
self.load_inputs_from_info unless @inputs
@inputs
end
def dirty?
false
end
def updated?
true
end
end
if ! Open.exists?(step.info_file)
begin
workflow = step.path.split("/")[-3]
task_name = step.path.split("/")[-2]
workflow = Kernel.const_get workflow
step.task = workflow.tasks[task_name.to_sym]
rescue
Log.exception $!
end
end
step
end
def self._load_step(path)
Persist.memory("STEP", :path => path, :repo => load_step_cache) do
__load_step(path)
end
end
def self.load_step(path)
path = Path.setup(path.dup) unless Path === path
path = path.find
begin
_load_step(path)
ensure
load_step_cache.clear
end
end
def load_id(id)
path = if Path === workdir
workdir[id].find
else
File.join(workdir, id)
end
task = task_for path
return remote_tasks[task].load_id(id) if remote_tasks && remote_tasks.include?(task)
return Workflow.load_step path
end
def fast_load_id(id)
path = if Path === workdir
workdir[id].find
else
File.join(workdir, id)
end
task = task_for path
return remote_tasks[task].load_id(id) if remote_tasks && remote_tasks.include?(task)
return Workflow.fast_load_step path
end
def load_name(task, name)
return remote_tasks[task].load_step(path) if remote_tasks and remote_tasks.include? task
task = tasks[task.to_sym] if String === task or Symbol === task
path = step_path task.name, name, [], [], task.extension
get_job_step path, task
end
#}}} LOAD FROM FILE
def jobs(taskname, query = nil)
task_dir = File.join(File.expand_path(workdir.find), taskname.to_s)
pattern = File.join(File.expand_path(task_dir), '**/*')
job_info_files = Dir.glob(Step.info_file(pattern)).collect{|f| Misc.path_relative_to task_dir, f }
job_info_files = job_info_files.select{|f| f.index(query) == 0 } if query
job_info_files.collect{|f|
job_name = Step.job_name_for_info_file(f, tasks[taskname].extension)
}
end
#{{{ Make workflow resources local
def local_persist_setup
class << self
include LocalPersist
end
self.local_persist_dir = Rbbt.var.cache.persistence.find :lib
end
def local_workdir_setup
self.workdir = Rbbt.var.jobs.find :lib
end
def make_local
local_persist_setup
local_workdir_setup
end
def with_workdir(workdir)
saved = self.workdir
begin
self.workdir = Path.setup(File.expand_path(workdir))
yield
ensure
self.workdir = saved
end
end
def add_remote_tasks(remote_tasks)
remote_tasks.each do |remote, tasks|
tasks.each do |task|
self.remote_tasks[task.to_f] = remote
end
end
end
def self.process_remote_tasks(remote_tasks)
require 'rbbt/workflow/remote_workflow'
remote_tasks.each do |workflow, info|
wf = Workflow.require_workflow workflow
wf.remote_tasks ||= {}
IndiferentHash.setup wf.remote_tasks
info.each do |remote, tasks|
remote_wf = RemoteWorkflow.new remote, workflow
tasks.each do |task|
Log.debug "Add remote task #{task} in #{wf} using #{remote_wf.url}"
wf.remote_tasks[task.to_sym] = remote_wf
end
end
end
end
def self.load_remote_tasks(filename)
yaml_text = Open.read(filename)
remote_workflow_tasks = YAML.load(yaml_text)
Workflow.process_remote_tasks(remote_workflow_tasks)
end
end
Only use full path on the job that is actually overriden
require 'rbbt/workflow/definition'
require 'rbbt/workflow/dependencies'
require 'rbbt/workflow/task'
require 'rbbt/workflow/step'
require 'rbbt/workflow/accessor'
require 'rbbt/workflow/doc'
require 'rbbt/workflow/examples'
require 'rbbt/workflow/util/archive'
require 'rbbt/workflow/util/provenance'
module Workflow
class TaskNotFoundException < Exception
def initialize(workflow, task = nil)
if task
super "Task '#{ task }' not found in #{ workflow } workflow"
else
super workflow
end
end
end
#{{{ WORKFLOW MANAGEMENT
class << self
attr_accessor :workflows, :autoinstall, :workflow_dir
end
self.workflows = []
def self.autoinstall
@autoload ||= ENV["RBBT_WORKFLOW_AUTOINSTALL"] == "true"
end
def self.extended(base)
self.workflows << base
libdir = Path.caller_lib_dir
return if libdir.nil?
base.libdir = Path.setup(libdir).tap{|p| p.resource = base}
end
def self.init_remote_tasks
return if defined? @@init_remote_tasks and @@init_remote_tasks
@@init_remote_tasks = true
load_remote_tasks(Rbbt.root.etc.remote_tasks.find) if Rbbt.root.etc.remote_tasks.exists?
end
def self.require_remote_workflow(wf_name, url)
require 'rbbt/workflow/remote_workflow'
eval "Object::#{wf_name.split("+").first} = RemoteWorkflow.new '#{ url }', '#{wf_name}'"
end
def self.load_workflow_libdir(filename)
workflow_lib_dir = File.join(File.dirname(File.expand_path(filename)), 'lib')
if File.directory? workflow_lib_dir
Log.debug "Adding workflow lib directory to LOAD_PATH: #{workflow_lib_dir}"
$LOAD_PATH.unshift(workflow_lib_dir)
end
end
def self.load_workflow_file(filename)
begin
load_workflow_libdir(filename)
filename = File.expand_path(filename)
Rbbt.add_version(filename)
require filename
Log.debug{"Workflow loaded from: #{ filename }"}
return true
rescue Exception
Log.warn{"Error loading workflow: #{ filename }"}
raise $!
end
end
def self.installed_workflows
self.workflow_dir['**/workflow.rb'].glob_all.collect do |file|
File.basename(File.dirname(file))
end
end
def self.workflow_dir
@workflow_dir ||= begin
case
when (defined?(Rbbt) and Rbbt.etc.workflow_dir.exists?)
dir = Rbbt.etc.workflow_dir.read.strip
dir = File.expand_path(dir)
Path.setup(dir)
when defined?(Rbbt)
Rbbt.workflows
else
dir = File.join(ENV['HOME'], '.workflows')
Path.setup(dir)
end
end
end
def self.local_workflow_filename(wf_name)
filename = nil
if Path === wf_name
case
# Points to workflow file
when ((File.exist?(wf_name.find) and not File.directory?(wf_name.find)) or File.exist?(wf_name.find + '.rb'))
filename = wf_name.find
# Points to workflow dir
when (File.exist?(wf_name.find) and File.directory?(wf_name.find) and File.exist?(File.join(wf_name.find, 'workflow.rb')))
filename = wf_name['workflow.rb'].find
end
else
if ((File.exist?(wf_name) and not File.directory?(wf_name)) or File.exist?(wf_name + '.rb'))
filename = (wf_name =~ /\.?\//) ? wf_name : "./" << wf_name
else
filename = workflow_dir[wf_name]['workflow.rb'].find
end
end
if filename.nil? or not File.exist?(filename)
wf_name_snake = Misc.snake_case(wf_name)
return local_workflow_filename(wf_name_snake) if wf_name_snake != wf_name
end
filename
end
def self.require_local_workflow(wf_name)
filename = local_workflow_filename(wf_name)
if filename and File.exist?(filename)
load_workflow_file filename
else
return false
end
end
def self.require_workflow(wf_name, force_local=false)
Workflow.init_remote_tasks
# Already loaded
begin
workflow = Misc.string2const wf_name
Log.debug{"Workflow #{ wf_name } already loaded"}
return workflow
rescue Exception
end
# Load remotely
if not force_local and Rbbt.etc.remote_workflows.exists?
remote_workflows = Rbbt.etc.remote_workflows.yaml
if Hash === remote_workflows and remote_workflows.include?(wf_name)
url = remote_workflows[wf_name]
begin
return require_remote_workflow(wf_name, url)
ensure
Log.debug{"Workflow #{ wf_name } loaded remotely: #{ url }"}
end
end
end
if Open.remote?(wf_name) or Open.ssh?(wf_name)
url = wf_name
if Open.ssh?(wf_name)
wf_name = File.basename(url.split(":").last)
else
wf_name = File.basename(url)
end
begin
return require_remote_workflow(wf_name, url)
ensure
Log.debug{"Workflow #{ wf_name } loaded remotely: #{ url }"}
end
end
# Load locally
if wf_name =~ /::\w+$/
clean_name = wf_name.sub(/::.*/,'')
Log.info{"Looking for '#{wf_name}' in '#{clean_name}'"}
require_workflow clean_name
workflow = Misc.string2const Misc.camel_case(wf_name)
workflow.load_documentation
return workflow
end
Log.high{"Loading workflow #{wf_name}"}
first = nil
wf_name.split("+").each do |wf_name|
require_local_workflow(wf_name) or
(Workflow.autoinstall and `rbbt workflow install #{Misc.snake_case(wf_name)} || rbbt workflow install #{wf_name}` and require_local_workflow(wf_name)) or raise("Workflow not found or could not be loaded: #{ wf_name }")
workflow = begin
Misc.string2const Misc.camel_case(wf_name.split("+").first)
rescue
Workflow.workflows.last || true
end
workflow.load_documentation
first ||= workflow
end
return first
workflow
end
attr_accessor :description
attr_accessor :libdir, :workdir
attr_accessor :helpers, :tasks
attr_accessor :task_dependencies, :task_description, :last_task
attr_accessor :stream_exports, :asynchronous_exports, :synchronous_exports, :exec_exports
attr_accessor :step_cache
attr_accessor :load_step_cache
attr_accessor :remote_tasks
#{{{ ATTR DEFAULTS
def self.workdir=(path)
path = Path.setup path.dup unless Path === path
@@workdir = path
end
def self.workdir
@@workdir ||= if defined? Rbbt
Rbbt.var.jobs
else
Path.setup('var/jobs')
end
end
TAG = ENV["RBBT_INPUT_JOBNAME"] == "true" ? :inputs : :hash
DEBUG_JOB_HASH = ENV["RBBT_DEBUG_JOB_HASH"] == 'true'
def step_path(taskname, jobname, inputs, dependencies, extension = nil)
raise "Jobname makes an invalid path: #{ jobname }" if jobname.include? '..'
if inputs.length > 0 or dependencies.any?
tagged_jobname = case TAG
when :hash
clean_inputs = Annotated.purge(inputs)
clean_inputs = clean_inputs.collect{|i| Symbol === i ? i.to_s : i }
deps_str = dependencies.collect{|d| (Step === d || (defined?(RemoteStep) && RemoteStep === Step)) ? "Step: " << (Symbol === d.overriden ? d.path : d.short_path) : d }
key_obj = {:inputs => clean_inputs, :dependencies => deps_str }
key_str = Misc.obj2str(key_obj)
hash_str = Misc.digest(key_str)
Log.debug "Hash for '#{[taskname, jobname] * "/"}' #{hash_str} for #{key_str}" if DEBUG_JOB_HASH
jobname + '_' << hash_str
when :inputs
all_inputs = {}
inputs.zip(self.task_info(taskname)[:inputs]) do |i,f|
all_inputs[f] = i
end
dependencies.each do |dep|
ri = dep.recursive_inputs
ri.zip(ri.fields).each do |i,f|
all_inputs[f] = i
end
end
all_inputs.any? ? jobname + '_' << Misc.obj2str(all_inputs) : jobname
else
jobname
end
else
tagged_jobname = jobname
end
if extension and not extension.empty?
tagged_jobname = tagged_jobname + ('.' << extension.to_s)
end
workdir[taskname][tagged_jobname].find
end
def import_task(workflow, orig, new)
orig_task = workflow.tasks[orig]
new_task = orig_task.dup
options = {}
orig_task.singleton_methods.
select{|method| method.to_s[-1] != "="[0]}.each{|method|
if orig_task.respond_to?(method.to_s + "=")
options[method.to_s] = orig_task.send(method.to_s)
end
}
Task.setup(options, &new_task)
new_task.workflow = self
new_task.name = new
tasks[new] = new_task
task_dependencies[new] = workflow.task_dependencies[orig]
task_description[new] = workflow.task_description[orig]
end
def workdir=(path)
path = Path.setup path.dup unless Path === path
@workdir = path
end
def workdir
@workdir ||= begin
text = Module === self ? self.to_s : "Misc"
Workflow.workdir[text]
end
end
def libdir
@libdir = Path.setup(Path.caller_lib_dir) if @libdir.nil?
@libdir
end
def step_cache
Thread.current[:step_cache] ||= {}
end
def self.load_step_cache
Thread.current[:load_step_cache] ||= {}
end
def helpers
@helpers ||= {}
end
def tasks
@tasks ||= {}
end
def task_dependencies
@task_dependencies ||= {}
end
def task_description
@task_description ||= {}
end
def stream_exports
@stream_exports ||= []
end
def asynchronous_exports
@asynchronous_exports ||= []
end
def synchronous_exports
@synchronous_exports ||= []
end
def exec_exports
@exec_exports ||= []
end
def all_exports
@all_exports ||= asynchronous_exports + synchronous_exports + exec_exports + stream_exports
end
# {{{ JOB MANAGEMENT
DEFAULT_NAME="Default"
def self.resolve_locals(inputs)
inputs.each do |name, value|
if (String === value and value =~ /^local:(.*?):(.*)/) or
(Array === value and value.length == 1 and value.first =~ /^local:(.*?):(.*)/) or
(TSV === value and value.size == 1 and value.keys.first =~ /^local:(.*?):(.*)/)
task_name = $1
jobname = $2
value = load_id(File.join(task_name, jobname)).load
inputs[name] = value
end
end
end
def step_module
@_m ||= begin
m = Module.new
helpers.each do |name,block|
m.send(:define_method, name, &block)
end
m
end
@_m
end
def __job(taskname, jobname = nil, inputs = {})
taskname = taskname.to_sym
return remote_tasks[taskname].job(taskname, jobname, inputs) if remote_tasks and remote_tasks.include? taskname
task = tasks[taskname]
raise "Task not found: #{ taskname }" if task.nil?
inputs = IndiferentHash.setup(inputs)
not_overriden = inputs.delete :not_overriden
if not_overriden
inputs[:not_overriden] = :not_overriden_dep
end
Workflow.resolve_locals(inputs)
task_info = task_info(taskname)
task_inputs = task_info[:inputs]
#defaults = IndiferentHash.setup(task_info[:input_defaults]).merge(task.input_defaults)
all_defaults = IndiferentHash.setup(task_info[:input_defaults])
defaults = IndiferentHash.setup(task.input_defaults)
missing_inputs = []
task.required_inputs.each do |input|
missing_inputs << input if inputs[input].nil?
end if task.required_inputs
if missing_inputs.length == 1
raise ParameterException, "Input #{missing_inputs.first} is required but was not provided or is nil"
end
if missing_inputs.length > 1
raise ParameterException, "Inputs #{Misc.humanize_list(missing_inputs)} are required but were not provided or are nil"
end
# jobname => true sets the value of the input to the name of the job
if task.input_options
jobname_input = task.input_options.select{|i,o| o[:jobname]}.collect{|i,o| i }.first
else
jobname_input = nil
end
if jobname_input && jobname && inputs[jobname_input].nil?
inputs[jobname_input] = jobname
end
real_inputs = {}
has_overriden_inputs = false
inputs.each do |k,v|
#has_overriden_inputs = true if String === k and k.include? "#"
next unless (task_inputs.include?(k.to_sym) or task_inputs.include?(k.to_s))
default = all_defaults[k]
next if default == v
next if (String === default and Symbol === v and v.to_s == default)
next if (Symbol === default and String === v and v == default.to_s)
real_inputs[k.to_sym] = v
end
jobname_input_value = inputs[jobname_input] || all_defaults[jobname_input]
if jobname_input && jobname.nil? && String === jobname_input_value && ! jobname_input_value.include?('/')
jobname = jobname_input_value
end
jobname = DEFAULT_NAME if jobname.nil? or jobname.empty?
dependencies = real_dependencies(task, jobname, defaults.merge(inputs), task_dependencies[taskname] || [])
overriden_deps = dependencies.select{|d| d.overriden }
true_overriden_deps = overriden_deps.select{|d| TrueClass === d.overriden }
overriden = has_overriden_inputs || overriden_deps.any?
extension = task.extension
if extension == :dep_task
extension = nil
if dependencies.any?
dep_basename = File.basename(dependencies.last.path)
if dep_basename.include? "."
parts = dep_basename.split(".")
extension = [parts.pop]
while parts.last.length <= 4
extension << parts.pop
end
extension = extension.reverse * "."
end
end
end
if real_inputs.empty? && Workflow::TAG != :inputs && ! overriden
step_path = step_path taskname, jobname, [], [], extension
input_values = task.take_input_values(inputs)
else
input_values = task.take_input_values(inputs)
step_path = step_path taskname, jobname, input_values, dependencies, extension
end
job = get_job_step step_path, task, input_values, dependencies
job.workflow = self
job.clean_name = jobname
case not_overriden
when TrueClass
job.overriden = has_overriden_inputs || true_overriden_deps.any?
when :not_overriden_dep
job.overriden = true if has_overriden_inputs || true_overriden_deps.any?
else
job.overriden = true if has_overriden_inputs || overriden_deps.any?
end
job.real_inputs = real_inputs.keys
job
end
def _job(taskname, jobname = nil, inputs = {})
_inputs = IndiferentHash.setup(inputs.dup)
task_info = task_info(taskname)
task_inputs = task_info[:inputs]
persist_inputs = inputs.values_at(*task_inputs)
persist_inputs += inputs.values_at(*inputs.keys.select{|k| String === k && k.include?("#") }.sort)
Persist.memory("STEP", :workflow => self.to_s, :taskname => taskname, :jobname => jobname, :inputs => persist_inputs, :repo => step_cache) do
__job(taskname, jobname, inputs)
end
end
def job(taskname, jobname = nil, inputs = {})
begin
_job(taskname, jobname, inputs)
ensure
step_cache.clear
end
end
def set_step_dependencies(step)
if step.info[:dependencies]
Misc.insist do
step.dependencies = step.info[:dependencies].collect do |task, job, path|
next if job.nil?
if Open.exists?(path)
load_step(path)
else
Workflow.load_step(path)
end
end
end
end
end
#{{{ LOAD FROM FILE
def get_job_step(step_path, task = nil, input_values = nil, dependencies = nil)
step_path = step_path.call if Proc === step_path
persist = input_values.nil? ? false : true
persist = false
key = Path === step_path ? step_path.find : step_path
step = Step.new step_path, task, input_values, dependencies
set_step_dependencies(step) unless dependencies
step.extend step_module
step.task ||= task
step.inputs ||= input_values
step.dependencies = dependencies if dependencies and (step.dependencies.nil? or step.dependencies.length < dependencies.length)
step
end
def load_step(path)
task = task_for path
if task
get_job_step path, tasks[task.to_sym]
else
get_job_step path
end
end
def self.transplant(listed, real, other)
if listed.nil?
parts = real.split("/")
other_parts = other.split("/")
listed = (other_parts[0..-4] + parts[-3..-1]) * "/"
end
sl = listed.split("/", -1)
so = other.split("/", -1)
sr = real.split("/", -1)
prefix = []
while true
break if sl[0] != so[0]
cl = sl.shift
co = so.shift
prefix << cl
end
File.join(sr - sl + so)
end
def self.relocate_array(real, list)
preal = real.split(/\/+/)
prefix = preal[0..-4] * "/"
list.collect do |other|
pother = other.split(/\/+/)
end_part = pother[-3..-1] * "/"
new_path = prefix + "/" << end_part
if File.exists? new_path
new_path
else
Rbbt.var.jobs[end_part].find
end
end
end
def self.relocate(real, other)
preal = real.split(/\/+/)
pother = other.split(/\/+/)
end_part = pother[-3..-1] * "/"
new_path = preal[0..-4] * "/" << "/" << end_part
return new_path if File.exists?(new_path) || File.exists?(new_path + '.info')
Rbbt.var.jobs[end_part].find
end
def self.relocate_dependency(main, dep)
dep_path = dep.path
path = main.path
if Open.exists?(dep_path) || Open.exists?(dep_path + '.info')
dep
else
new_path = relocate(path, dep_path)
relocated = true if Open.exists?(new_path) || Open.exists?(new_path + '.info')
Workflow._load_step new_path
end
end
def self.__load_step(path)
if Open.remote?(path) || Open.ssh?(path)
require 'rbbt/workflow/remote_workflow'
return RemoteWorkflow.load_path path
end
step = Step.new path
relocated = false
step.dependencies = (step.info[:dependencies] || []).collect do |task,name,dep_path|
if Open.exists?(dep_path) || Open.exists?(dep_path + '.info') || Open.remote?(dep_path) || Open.ssh?(dep_path)
Workflow._load_step dep_path
else
new_path = relocate(path, dep_path)
relocated = true if Open.exists?(new_path) || Open.exists?(new_path + '.info')
Workflow._load_step new_path
end
end
step.relocated = relocated
step.load_inputs_from_info
step
end
def self.fast_load_step(path)
if Open.remote?(path) || Open.ssh?(path)
require 'rbbt/workflow/remote_workflow'
return RemoteWorkflow.load_path path
end
step = Step.new path
step.dependencies = nil
class << step
def dependencies
@dependencies ||= (self.info[:dependencies] || []).collect do |task,name,dep_path|
dep = if Open.exists?(dep_path) || Open.exists?(dep_path + '.info')
relocate = false
Workflow.fast_load_step dep_path
else
new_path = Workflow.relocate(path, dep_path)
relocated = true if Open.exists?(new_path) || Open.exists?(new_path + '.info')
Workflow.fast_load_step new_path
end
dep.relocated = relocated
dep
end
@dependencies
end
def inputs
self.load_inputs_from_info unless @inputs
@inputs
end
def dirty?
false
end
def updated?
true
end
end
if ! Open.exists?(step.info_file)
begin
workflow = step.path.split("/")[-3]
task_name = step.path.split("/")[-2]
workflow = Kernel.const_get workflow
step.task = workflow.tasks[task_name.to_sym]
rescue
Log.exception $!
end
end
step
end
def self._load_step(path)
Persist.memory("STEP", :path => path, :repo => load_step_cache) do
__load_step(path)
end
end
def self.load_step(path)
path = Path.setup(path.dup) unless Path === path
path = path.find
begin
_load_step(path)
ensure
load_step_cache.clear
end
end
def load_id(id)
path = if Path === workdir
workdir[id].find
else
File.join(workdir, id)
end
task = task_for path
return remote_tasks[task].load_id(id) if remote_tasks && remote_tasks.include?(task)
return Workflow.load_step path
end
def fast_load_id(id)
path = if Path === workdir
workdir[id].find
else
File.join(workdir, id)
end
task = task_for path
return remote_tasks[task].load_id(id) if remote_tasks && remote_tasks.include?(task)
return Workflow.fast_load_step path
end
def load_name(task, name)
return remote_tasks[task].load_step(path) if remote_tasks and remote_tasks.include? task
task = tasks[task.to_sym] if String === task or Symbol === task
path = step_path task.name, name, [], [], task.extension
get_job_step path, task
end
#}}} LOAD FROM FILE
def jobs(taskname, query = nil)
task_dir = File.join(File.expand_path(workdir.find), taskname.to_s)
pattern = File.join(File.expand_path(task_dir), '**/*')
job_info_files = Dir.glob(Step.info_file(pattern)).collect{|f| Misc.path_relative_to task_dir, f }
job_info_files = job_info_files.select{|f| f.index(query) == 0 } if query
job_info_files.collect{|f|
job_name = Step.job_name_for_info_file(f, tasks[taskname].extension)
}
end
#{{{ Make workflow resources local
def local_persist_setup
class << self
include LocalPersist
end
self.local_persist_dir = Rbbt.var.cache.persistence.find :lib
end
def local_workdir_setup
self.workdir = Rbbt.var.jobs.find :lib
end
def make_local
local_persist_setup
local_workdir_setup
end
def with_workdir(workdir)
saved = self.workdir
begin
self.workdir = Path.setup(File.expand_path(workdir))
yield
ensure
self.workdir = saved
end
end
def add_remote_tasks(remote_tasks)
remote_tasks.each do |remote, tasks|
tasks.each do |task|
self.remote_tasks[task.to_f] = remote
end
end
end
def self.process_remote_tasks(remote_tasks)
require 'rbbt/workflow/remote_workflow'
remote_tasks.each do |workflow, info|
wf = Workflow.require_workflow workflow
wf.remote_tasks ||= {}
IndiferentHash.setup wf.remote_tasks
info.each do |remote, tasks|
remote_wf = RemoteWorkflow.new remote, workflow
tasks.each do |task|
Log.debug "Add remote task #{task} in #{wf} using #{remote_wf.url}"
wf.remote_tasks[task.to_sym] = remote_wf
end
end
end
end
def self.load_remote_tasks(filename)
yaml_text = Open.read(filename)
remote_workflow_tasks = YAML.load(yaml_text)
Workflow.process_remote_tasks(remote_workflow_tasks)
end
end
|
require 'rubygems'
require 'bud'
require 'server_state'
require 'vote_counter'
module RaftProtocol
end
module Raft
include RaftProtocol
import ServerState => :st
import VoteCounter => :vc
def set_cluster(cluster)
@HOSTS = cluster
end
state do
channel :vote_request, [:@dest, :from, :term, :last_log_index, :last_log_term]
channel :vote_response, [:@dest, :from, :term, :is_granted]
channel :append_entries_request, [:@dest, :from, :term, :prev_log_index, :prev_log_term, :request_entry, :commit_index]
channel :append_entries_response, [:@dest, :from, :term, :is_success]
table :members, [:host]
table :voted_for, [:term] => [:candidate]
scratch :voted_for_in_current_term, [] => [:candidate]
scratch :voted_for_in_current_step, [] => [:candidate]
periodic :heartbeat, 0.1
end
bootstrap do
members <= @HOSTS - [[ip_port]]
st.reset_timer <= [[true]]
vc.setup <= [[@HOSTS.count]]
end
bloom :module_input do
vc.count_votes <= st.current_term {|t| [t.term]}
end
bloom :timeout do
# increment current term
st.set_term <= (st.alarm * st.current_state * st.current_term).combos do |a, s, t|
[t.term + 1] if s.state != 'leader'
end
# transition to candidate state
st.set_state <= (st.alarm * st.current_state).pairs do |t, s|
['candidate'] if s.state != 'leader'
end
# reset the timer
st.reset_timer <= (st.alarm * st.current_state).pairs do |a|
[true] if s.state != 'leader'
end
# vote for ourselves
vc.vote <= (st.alarm * st.current_state * st.current_term).combos do |a, s, t|
[t.term, ip_port, true] if s.state != 'leader'
end
voted_for <+- (st.alarm * st.current_state * st.current_term).combos do |a, s, t|
[t.term, ip_port] if s.state != 'leader'
end
end
bloom :send_vote_requests do
vote_request <~ (heartbeat * members * st.current_state * st.current_term).combos do |h, m, s, t|
[m.host, ip_port, t.term, 0, 0] if s.state == 'candidate' and not vc.voted.include?([t.term, m.host])
end
end
bloom :count_votes do
# if we discover our term is stale, step down to follower and update our term
st.set_state <= (st.current_state * vote_response * st.current_term).combos do |s, v, t|
['follower'] if s.state == 'candidate' or s.state == 'leader' and v.term > t.term
end
st.set_term <= vote_response.argmax([:term], :term) {|v| [v.term]}
# record votes if we are in the correct term
vc.vote <= (st.current_state * vote_response * st.current_term).combos do |s, v, t|
[v.term, v.from, v.is_granted] if s.state == 'candidate' and v.term == t.term
end
# if we won the election, then we become leader
st.set_state <= (vc.election_won * st.current_state * st.current_term).combos do |e, s, t|
#puts "#{ip_port} won with e.term #{e.term} and t.term #{t.term}"
['leader'] if s.state == 'candidate' and e.term == t.term
end
end
bloom :cast_votes do
# if we discover our term is stale, step down to follower and update our term
st.set_state <= (st.current_state * vote_request * st.current_term).combos do |s, v, t|
['follower'] if s.state == 'candidate' or s.state == 'leader' and v.term > t.term
end
st.set_term <= vote_request.argmax([:term], :term) {|v| [v.term]}
# TODO: if voted_for in current term is null AND the candidate's log is at least as complete as our local log, then grant our vote, reject others, and reset the election timeout
voted_for_in_current_term <= (voted_for * st.current_term).pairs do |v, t|
[v.candidate] if v.term == t.term
end
voted_for_in_current_step <= vote_request.argagg(:choose, [], :from) {|v| [v.from]}
vote_response <~ (vote_request * voted_for_in_current_step * st.current_term).combos do |r, v, t|
[r.from, ip_port, t.term, (r.from == v.candidate and not voted_for_in_current_term.exists?)]
end
st.reset_timer <= (vote_request * voted_for_in_current_step * st.current_term).combos do |r, v, t|
[true] if r.from == v.candidate and not voted_for_in_current_term.exists?
end
voted_for <+ (voted_for_in_current_step * st.current_term).pairs do |v, t|
[t.term, v.candidate] if not voted_for_in_current_term.exists?
end
end
bloom :send_heartbeats do
append_entries_request <~ (heartbeat * members * st.current_state * st.current_term).combos do |h, m, s, t|
# TODO: add legit indicies when we do logging
[m.host, ip_port, t.term, 0, 0, 0, 0] if s.state == 'leader'
end
end
bloom :normal_operation do
# revert to follower if we get an append_entries_request
st.set_state <= (st.current_state * append_entries_request * st.current_term).combos do |s, v, t|
['follower'] if (s.state == 'candidate' and v.term >= t.term) or (s.state == 'leader' and v.term > t.term)
end
# reset our timer if the term is current or our term is stale
st.reset_timer <= (append_entries_request * st.current_term).pairs do |a, t|
[true] if a.term >= t.term
end
# update term if our term is stale
st.set_term <= append_entries_request.argmax([:term], :term) {|a| [a.term]}
# TODO: step down as leader if our term is stale
# TODO: respond to append entries
# TODO: update leader if we get an append entries (and if we are leader, only if our term is stale)
end
end
minor changes
require 'rubygems'
require 'bud'
require 'server_state'
require 'vote_counter'
module RaftProtocol
end
module Raft
include RaftProtocol
import ServerState => :st
import VoteCounter => :vc
def set_cluster(cluster)
@HOSTS = cluster
end
state do
channel :vote_request, [:@dest, :from, :term, :last_log_index, :last_log_term]
channel :vote_response, [:@dest, :from, :term, :is_granted]
channel :append_entries_request, [:@dest, :from, :term, :prev_log_index, :prev_log_term, :request_entry, :commit_index]
channel :append_entries_response, [:@dest, :from, :term, :is_success]
table :members, [:host]
table :voted_for, [:term] => [:candidate]
scratch :voted_for_in_current_term, [] => [:candidate]
scratch :voted_for_in_current_step, [] => [:candidate]
periodic :heartbeat, 0.1
end
bootstrap do
members <= @HOSTS - [[ip_port]]
st.reset_timer <= [[true]]
vc.setup <= [[@HOSTS.count]]
end
bloom :module_input do
vc.count_votes <= st.current_term {|t| [t.term]}
end
bloom :timeout do
# increment current term
st.set_term <= (st.alarm * st.current_state * st.current_term).combos do |a, s, t|
[t.term + 1] if s.state != 'leader'
end
# transition to candidate state
st.set_state <= (st.alarm * st.current_state).pairs do |t, s|
['candidate'] if s.state != 'leader'
end
# reset the timer
st.reset_timer <= (st.alarm * st.current_state).pairs do |a|
[true] if s.state != 'leader'
end
# vote for ourselves
vc.vote <= (st.alarm * st.current_state * st.current_term).combos do |a, s, t|
[t.term, ip_port, true] if s.state != 'leader'
end
voted_for <+- (st.alarm * st.current_state * st.current_term).combos do |a, s, t|
[t.term, ip_port] if s.state != 'leader'
end
end
bloom :send_vote_requests do
vote_request <~ (heartbeat * members * st.current_state * st.current_term).combos do |h, m, s, t|
[m.host, ip_port, t.term, 0, 0] if s.state == 'candidate' and not vc.voted.include?([t.term, m.host])
end
end
bloom :count_votes do
# if we discover our term is stale, step down to follower and update our term
st.set_state <= (st.current_state * vote_response * st.current_term).combos do |s, v, t|
['follower'] if s.state == 'candidate' or s.state == 'leader' and v.term > t.term
end
st.set_term <= vote_response.argmax([:term], :term) {|v| [v.term]}
# record votes if we are in the correct term
vc.vote <= (st.current_state * vote_response * st.current_term).combos do |s, v, t|
[v.term, v.from, v.is_granted] if s.state == 'candidate' and v.term == t.term
end
# if we won the election, then we become leader
st.set_state <= (vc.election_won * st.current_state * st.current_term).combos do |e, s, t|
#puts "#{ip_port} won with e.term #{e.term} and t.term #{t.term}"
['leader'] if s.state == 'candidate' and e.term == t.term
end
end
bloom :cast_votes do
# if we discover our term is stale, step down to follower and update our term
st.set_state <= (st.current_state * vote_request * st.current_term).combos do |s, v, t|
['follower'] if s.state == 'candidate' or s.state == 'leader' and v.term > t.term
end
st.set_term <= vote_request.argmax([:term], :term) {|v| [v.term]}
# TODO: if voted_for in current term is null AND the candidate's log is at least as complete as our local log, then grant our vote, reject others, and reset the election timeout
# TODO: make this so that we will respond with true if we already granted a vote for this server (in case network drops packet)
voted_for_in_current_term <= (voted_for * st.current_term).pairs(:term => :term) do |v, t|
[v.candidate]
end
voted_for_in_current_step <= vote_request.argagg(:choose, [], :from) {|v| [v.from]}
vote_response <~ (vote_request * voted_for_in_current_step * st.current_term).combos do |r, v, t|
[r.from, ip_port, t.term, (r.from == v.candidate and not voted_for_in_current_term.exists?)]
end
st.reset_timer <= (vote_request * voted_for_in_current_step * st.current_term).combos do |r, v, t|
[true] if r.from == v.candidate and not voted_for_in_current_term.exists?
end
voted_for <+ (voted_for_in_current_step * st.current_term).pairs do |v, t|
[t.term, v.candidate] if not voted_for_in_current_term.exists?
end
end
bloom :send_heartbeats do
append_entries_request <~ (heartbeat * members * st.current_state * st.current_term).combos do |h, m, s, t|
# TODO: add legit indicies when we do logging
[m.host, ip_port, t.term, 0, 0, 0, 0] if s.state == 'leader'
end
end
bloom :normal_operation do
# revert to follower if we get an append_entries_request
st.set_state <= (st.current_state * append_entries_request * st.current_term).combos do |s, v, t|
['follower'] if (s.state == 'candidate' and v.term >= t.term) or (s.state == 'leader' and v.term > t.term)
end
# reset our timer if the term is current or our term is stale
st.reset_timer <= (append_entries_request * st.current_term).pairs do |a, t|
[true] if a.term >= t.term
end
# update term if our term is stale
st.set_term <= append_entries_request.argmax([:term], :term) {|a| [a.term]}
# TODO: step down as leader if our term is stale
# TODO: respond to append entries
# TODO: update leader if we get an append entries (and if we are leader, only if our term is stale)
end
end
|
class Striuct; module Containable
# @group Basic
def initialize(*values)
@db, @locks = {}, {}
replace_values(*values)
end
# see self.class.*args
delegate_class_methods(
:members, :keys, :names,
:has_member?, :member?, :has_key?, :key?,
:length, :size
)
# @return [Boolean]
def ==(other)
__compare_all__ other, :==
end
alias_method :===, :==
def eql?(other)
__compare_all__ other, :eql?
end
# @return [Integer]
def hash
@db.hash
end
# @return [String]
def inspect
"#<#{self.class} (StrictStruct)".tap do |s|
each_pair do |name, value|
suffix = (has_default?(name) && default?(name)) ? '(default)' : nil
s << " #{name}=#{value.inspect}#{suffix}"
end
s << ">"
end
end
# @return [String]
def to_s
"#<struct #{self.class}".tap do |s|
each_pair do |name, value|
s << " #{name}=#{value.inspect}"
end
s << '>'
end
end
# @param [Symbol, String, Fixnum] key
def [](key)
__subscript__(key){|name|__get__ name}
end
# @param [Symbol, String, Fixnum] key
# @param [Object] value
# @return [value]
def []=(key, value)
true_name = nil
__subscript__(key){|name|true_name = name; __set__ name, value}
rescue ConditionError
$@ = [
"#{$@[-1].sub(/[^:]+\z/){''}}in `[#{key.inspect}(#{true_name})]=': #{$!.message}",
$@[-1]
]
raise
end
alias_method :assign, :[]
# @yield [value]
# @yieldparam [Object] value - sequential under defined
# @see #each_name
# @yieldreturn [self]
# @return [Enumerator]
def each_value
return to_enum(__method__) unless block_given?
each_member{|member|yield self[member]}
end
alias_method :each, :each_value
# @yield [name, value]
# @yieldparam [Symbol] name
# @yieldparam [Object] value
# @yieldreturn [self]
# @return [Enumerator]
# @see #each_name
# @see #each_value
def each_pair
return to_enum(__method__) unless block_given?
each_name{|name|yield name, self[name]}
end
# @return [Array]
def values
each_value.to_a
end
alias_method :to_a, :values
# @param [Fixnum, Range] *keys
# @return [Array]
def values_at(*keys)
[].tap {|r|
keys.each do |key|
case key
when Fixnum
r << self[key]
when Range
key.each do |n|
raise TypeError unless n.instance_of? Fixnum
r << self[n]
end
else
raise TypeError
end
end
}
end
# @return [self]
def freeze
[@db, @locks].each(&:freeze)
super
end
# @endgroup
end; end
modify inspect strings
class Striuct; module Containable
# @group Basic
def initialize(*values)
@db, @locks = {}, {}
replace_values(*values)
end
# see self.class.*args
delegate_class_methods(
:members, :keys, :names,
:has_member?, :member?, :has_key?, :key?,
:length, :size
)
# @return [Boolean]
def ==(other)
__compare_all__ other, :==
end
alias_method :===, :==
def eql?(other)
__compare_all__ other, :eql?
end
# @return [Integer]
def hash
@db.hash
end
# @return [String]
def inspect
"#<#{self.class} (Striuct)".tap do |s|
each_pair do |name, value|
suffix = (has_default?(name) && default?(name)) ? '(default)' : nil
s << " #{name}=#{value.inspect}#{suffix}"
end
s << ">"
end
end
# @return [String]
def to_s
"#<struct #{self.class}".tap do |s|
each_pair do |name, value|
s << " #{name}=#{value.inspect}"
end
s << '>'
end
end
# @param [Symbol, String, Fixnum] key
def [](key)
__subscript__(key){|name|__get__ name}
end
# @param [Symbol, String, Fixnum] key
# @param [Object] value
# @return [value]
def []=(key, value)
true_name = nil
__subscript__(key){|name|true_name = name; __set__ name, value}
rescue ConditionError
$@ = [
"#{$@[-1].sub(/[^:]+\z/){''}}in `[#{key.inspect}(#{true_name})]=': #{$!.message}",
$@[-1]
]
raise
end
alias_method :assign, :[]
# @yield [value]
# @yieldparam [Object] value - sequential under defined
# @see #each_name
# @yieldreturn [self]
# @return [Enumerator]
def each_value
return to_enum(__method__) unless block_given?
each_member{|member|yield self[member]}
end
alias_method :each, :each_value
# @yield [name, value]
# @yieldparam [Symbol] name
# @yieldparam [Object] value
# @yieldreturn [self]
# @return [Enumerator]
# @see #each_name
# @see #each_value
def each_pair
return to_enum(__method__) unless block_given?
each_name{|name|yield name, self[name]}
end
# @return [Array]
def values
each_value.to_a
end
alias_method :to_a, :values
# @param [Fixnum, Range] *keys
# @return [Array]
def values_at(*keys)
[].tap {|r|
keys.each do |key|
case key
when Fixnum
r << self[key]
when Range
key.each do |n|
raise TypeError unless n.instance_of? Fixnum
r << self[n]
end
else
raise TypeError
end
end
}
end
# @return [self]
def freeze
[@db, @locks].each(&:freeze)
super
end
# @endgroup
end; end |
# try to detect dev env
path = File.expand_path(File.join(File.dirname(__FILE__), ".."))
if File.directory? File.join(path, ".git") then
ENV["BIXBY_HOME"] = path
require "bundler/setup"
end
require "bixby_common"
require "bixby-client"
require "bixby_agent/agent"
require "bixby_agent/version"
Bixby::Agent.setup_env()
only set home if unset
# try to detect dev env
path = File.expand_path(File.join(File.dirname(__FILE__), ".."))
if File.directory? File.join(path, ".git") then
ENV["BIXBY_HOME"] = path if not ENV["BIXBY_HOME"]
require "bundler/setup"
end
require "bixby_common"
require "bixby-client"
require "bixby_agent/agent"
require "bixby_agent/version"
Bixby::Agent.setup_env()
|
# Loads seed data out of default dir
default_path = File.join(File.dirname(__FILE__), 'default')
Rake::Task['db:load_dir'].reenable
Rake::Task['db:load_dir'].invoke(default_path)
using gems rake tasks to load seeds
# Loads seed data out of default dir
default_path = File.join(File.dirname(__FILE__), 'default')
Rake::Task['spree_travel_car:load'].reenable
Rake::Task['spree_travel_car:load'].invoke(default_path)
|
module ActiveAdmin
class ResourceController < BaseController
module Decorators
protected
def apply_decorator(resource)
decorate? ? decorator_class.new(resource) : resource
end
def apply_collection_decorator(collection)
if decorate?
collection_decorator.decorate collection, with: decorator_class
else
collection
end
end
def self.undecorate(resource)
if resource.respond_to?(:decorated?) && resource.decorated?
resource.model
else
resource
end
end
private
def decorate?
case action_name
when 'new', 'edit', 'create', 'update'
form = active_admin_config.get_page_presenter :form
form && form.options[:decorate] && decorator_class.present?
else
decorator_class.present?
end
end
def decorator_class
active_admin_config.decorator_class
end
# When using Draper, we wrap the collection draper in a new class that
# correctly delegates methods that Active Admin depends on.
def collection_decorator
if decorator_class
Wrapper.wrap decorator_class
end
end
class Wrapper
@cache = {}
def self.wrap(decorator)
collection_decorator = find_collection_decorator(decorator)
if draper_collection_decorator? collection_decorator
name = "#{collection_decorator.name} of #{decorator} + ActiveAdmin"
@cache[name] ||= wrap! collection_decorator, name
else
collection_decorator
end
end
private
def self.wrap!(parent, name)
::Class.new parent do
delegate :reorder, :page, :current_page, :total_pages, :limit_value,
:total_count, :total_pages, :offset, :to_key, :group_values,
:except, :find_each, :ransack
define_singleton_method(:name) { name }
end
end
def self.find_collection_decorator(decorator)
decorator.collection_decorator_class
end
def self.draper_collection_decorator?(decorator)
Dependency.draper? && decorator && decorator <= ::Draper::CollectionDecorator
end
end
end
end
end
Simplify draper wrapping logic to not use `collection_decorator_class`
module ActiveAdmin
class ResourceController < BaseController
module Decorators
protected
def apply_decorator(resource)
decorate? ? decorator_class.new(resource) : resource
end
def apply_collection_decorator(collection)
if decorate?
collection_decorator.decorate collection, with: decorator_class
else
collection
end
end
def self.undecorate(resource)
if resource.respond_to?(:decorated?) && resource.decorated?
resource.model
else
resource
end
end
private
def decorate?
case action_name
when 'new', 'edit', 'create', 'update'
form = active_admin_config.get_page_presenter :form
form && form.options[:decorate] && decorator_class.present?
else
decorator_class.present?
end
end
def decorator_class
active_admin_config.decorator_class
end
# When using Draper, we wrap the collection draper in a new class that
# correctly delegates methods that Active Admin depends on.
def collection_decorator
if decorator_class
Wrapper.wrap decorator_class
end
end
class Wrapper
@cache = {}
def self.wrap(decorator)
collection_decorator = find_draper_collection_decorator(decorator)
if collection_decorator
name = "#{collection_decorator.name} of #{decorator} + ActiveAdmin"
@cache[name] ||= wrap! collection_decorator, name
else
decorator
end
end
private
def self.wrap!(parent, name)
::Class.new parent do
delegate :reorder, :page, :current_page, :total_pages, :limit_value,
:total_count, :total_pages, :offset, :to_key, :group_values,
:except, :find_each, :ransack
define_singleton_method(:name) { name }
end
end
def self.find_draper_collection_decorator(decorator)
return unless Dependency.draper? && decorator && decorator <= ::Draper::Decorator
decorator.collection_decorator_class
end
end
end
end
end
|
module Recog
VERSION = "1.0.6"
end
Bump version
module Recog
VERSION = "1.0.7"
end
|
module StrongParameters
VERSION = "0.2.1"
end
bumps version for release
module StrongParameters
VERSION = "0.2.2"
end
|
module Blather
# Jabber ID or JID
#
# See [RFC 3920 Section 3 - Addressing](http://xmpp.org/rfcs/rfc3920.html#addressing)
#
# An entity is anything that can be considered a network endpoint (i.e., an
# ID on the network) and that can communicate using XMPP. All such entities
# are uniquely addressable in a form that is consistent with RFC 2396 [URI].
# For historical reasons, the address of an XMPP entity is called a Jabber
# Identifier or JID. A valid JID contains a set of ordered elements formed
# of a domain identifier, node identifier, and resource identifier.
#
# The syntax for a JID is defined below using the Augmented Backus-Naur Form
# as defined in [ABNF]. (The IPv4address and IPv6address rules are defined
# in Appendix B of [IPv6]; the allowable character sequences that conform to
# the node rule are defined by the Nodeprep profile of [STRINGPREP] as
# documented in Appendix A of this memo; the allowable character sequences
# that conform to the resource rule are defined by the Resourceprep profile
# of [STRINGPREP] as documented in Appendix B of this memo; and the
# sub-domain rule makes reference to the concept of an internationalized
# domain label as described in [IDNA].)
#
# jid = [ node "@" ] domain [ "/" resource ]
# domain = fqdn / address-literal
# fqdn = (sub-domain 1*("." sub-domain))
# sub-domain = (internationalized domain label)
# address-literal = IPv4address / IPv6address
#
# All JIDs are based on the foregoing structure. The most common use of this
# structure is to identify an instant messaging user, the server to which
# the user connects, and the user's connected resource (e.g., a specific
# client) in the form of <user@host/resource>. However, node types other
# than clients are possible; for example, a specific chat room offered by a
# multi-user chat service could be addressed as <room@service> (where "room"
# is the name of the chat room and "service" is the hostname of the
# multi-user chat service) and a specific occupant of such a room could be
# addressed as <room@service/nick> (where "nick" is the occupant's room
# nickname). Many other JID types are possible (e.g., <domain/resource>
# could be a server-side script or service).
#
# Each allowable portion of a JID (node identifier, domain identifier, and
# resource identifier) MUST NOT be more than 1023 bytes in length, resulting
# in a maximum total size (including the '@' and '/' separators) of 3071
# bytes.
class JID
include Comparable
# Validating pattern for JID string
PATTERN = /^(?:([^@]*)@)??([^@\/]*)(?:\/(.*?))?$/.freeze
attr_reader :node,
:domain,
:resource
# @private
def self.new(node, domain = nil, resource = nil)
node.is_a?(JID) ? node : super
end
# Create a new JID object
#
# @overload initialize(jid)
# Passes the jid object right back out
# @param [Blather::JID] jid a jid object
# @overload initialize(jid)
# Creates a new JID parsed out of the provided jid
# @param [String] jid a jid in the standard format
# ("node@domain/resource")
# @overload initialize(node, domain = nil, resource = nil)
# Creates a new JID
# @param [String] node the node of the JID
# @param [String, nil] domian the domain of the JID
# @param [String, nil] resource the resource of the JID
# @raise [ArgumentError] if the parts of the JID are too large (1023 bytes)
# @return [Blather::JID] a new jid object
def initialize(node, domain = nil, resource = nil)
@resource = resource
@domain = domain
@node = node
if @domain.nil? && @resource.nil?
@node, @domain, @resource = @node.to_s.scan(PATTERN).first
end
@node.downcase! if @node
@domain.downcase! if @domain
raise ArgumentError, 'Node too long' if (@node || '').length > 1023
raise ArgumentError, 'Domain too long' if (@domain || '').length > 1023
raise ArgumentError, 'Resource too long' if (@resource || '').length > 1023
end
# Turn the JID into a string
#
# * ""
# * "domain"
# * "node@domain"
# * "domain/resource"
# * "node@domain/resource"
#
# @return [String] the JID as a string
def to_s
s = @domain
s = "#{@node}@#{s}" if @node
s = "#{s}/#{@resource}" if @resource
s
end
# Returns a new JID with resource removed.
#
# @return [Blather::JID] a new JID without a resource
def stripped
dup.strip!
end
# Removes the resource (sets it to nil)
#
# @return [Blather::JID] the JID without a resource
def strip!
@resource = nil
self
end
# Compare two JIDs, helpful for sorting etc.
#
# String representations are compared, see JID#to_s
#
# @param [#to_s] other a JID to comare against
# @return [Fixnum<-1, 0, 1>]
def <=>(other)
to_s <=> other.to_s
end
alias_method :eql?, :==
# Test if JID is stripped
#
# @return [true, false]
def stripped?
@resource.nil?
end
end # JID
end # Blather
JIDs should preserve case, but compare case insensitively
module Blather
# Jabber ID or JID
#
# See [RFC 3920 Section 3 - Addressing](http://xmpp.org/rfcs/rfc3920.html#addressing)
#
# An entity is anything that can be considered a network endpoint (i.e., an
# ID on the network) and that can communicate using XMPP. All such entities
# are uniquely addressable in a form that is consistent with RFC 2396 [URI].
# For historical reasons, the address of an XMPP entity is called a Jabber
# Identifier or JID. A valid JID contains a set of ordered elements formed
# of a domain identifier, node identifier, and resource identifier.
#
# The syntax for a JID is defined below using the Augmented Backus-Naur Form
# as defined in [ABNF]. (The IPv4address and IPv6address rules are defined
# in Appendix B of [IPv6]; the allowable character sequences that conform to
# the node rule are defined by the Nodeprep profile of [STRINGPREP] as
# documented in Appendix A of this memo; the allowable character sequences
# that conform to the resource rule are defined by the Resourceprep profile
# of [STRINGPREP] as documented in Appendix B of this memo; and the
# sub-domain rule makes reference to the concept of an internationalized
# domain label as described in [IDNA].)
#
# jid = [ node "@" ] domain [ "/" resource ]
# domain = fqdn / address-literal
# fqdn = (sub-domain 1*("." sub-domain))
# sub-domain = (internationalized domain label)
# address-literal = IPv4address / IPv6address
#
# All JIDs are based on the foregoing structure. The most common use of this
# structure is to identify an instant messaging user, the server to which
# the user connects, and the user's connected resource (e.g., a specific
# client) in the form of <user@host/resource>. However, node types other
# than clients are possible; for example, a specific chat room offered by a
# multi-user chat service could be addressed as <room@service> (where "room"
# is the name of the chat room and "service" is the hostname of the
# multi-user chat service) and a specific occupant of such a room could be
# addressed as <room@service/nick> (where "nick" is the occupant's room
# nickname). Many other JID types are possible (e.g., <domain/resource>
# could be a server-side script or service).
#
# Each allowable portion of a JID (node identifier, domain identifier, and
# resource identifier) MUST NOT be more than 1023 bytes in length, resulting
# in a maximum total size (including the '@' and '/' separators) of 3071
# bytes.
class JID
include Comparable
# Validating pattern for JID string
PATTERN = /^(?:([^@]*)@)??([^@\/]*)(?:\/(.*?))?$/.freeze
attr_reader :node,
:domain,
:resource
# @private
def self.new(node, domain = nil, resource = nil)
node.is_a?(JID) ? node : super
end
# Create a new JID object
#
# @overload initialize(jid)
# Passes the jid object right back out
# @param [Blather::JID] jid a jid object
# @overload initialize(jid)
# Creates a new JID parsed out of the provided jid
# @param [String] jid a jid in the standard format
# ("node@domain/resource")
# @overload initialize(node, domain = nil, resource = nil)
# Creates a new JID
# @param [String] node the node of the JID
# @param [String, nil] domian the domain of the JID
# @param [String, nil] resource the resource of the JID
# @raise [ArgumentError] if the parts of the JID are too large (1023 bytes)
# @return [Blather::JID] a new jid object
def initialize(node, domain = nil, resource = nil)
@resource = resource
@domain = domain
@node = node
if @domain.nil? && @resource.nil?
@node, @domain, @resource = @node.to_s.scan(PATTERN).first
end
raise ArgumentError, 'Node too long' if (@node || '').length > 1023
raise ArgumentError, 'Domain too long' if (@domain || '').length > 1023
raise ArgumentError, 'Resource too long' if (@resource || '').length > 1023
end
# Turn the JID into a string
#
# * ""
# * "domain"
# * "node@domain"
# * "domain/resource"
# * "node@domain/resource"
#
# @return [String] the JID as a string
def to_s
s = @domain
s = "#{@node}@#{s}" if @node
s = "#{s}/#{@resource}" if @resource
s
end
# Returns a new JID with resource removed.
#
# @return [Blather::JID] a new JID without a resource
def stripped
dup.strip!
end
# Removes the resource (sets it to nil)
#
# @return [Blather::JID] the JID without a resource
def strip!
@resource = nil
self
end
# Compare two JIDs, helpful for sorting etc.
#
# String representations are compared, see JID#to_s
#
# @param [#to_s] other a JID to comare against
# @return [Fixnum<-1, 0, 1>]
def <=>(other)
to_s.downcase <=> other.to_s.downcase
end
alias_method :eql?, :==
# Test if JID is stripped
#
# @return [true, false]
def stripped?
@resource.nil?
end
end # JID
end # Blather
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
# rubocop:disable Style/IndentArray
mindleaps = Organization.create organization_name: 'MindLeaps'
mindleaps.chapters.create([
{ chapter_name: 'Kigali' }
])
kigali_chapter = mindleaps.chapters[0]
kigali_chapter.groups.create([
{ group_name: 'A' },
{ group_name: 'B' }
])
kigali_chapter.groups[0].students.create([
{ first_name: 'Innocent', last_name: 'Ngabo', dob: '2003-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Emmanuel', last_name: 'Ishimwe', dob: '2007-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Eric', last_name: 'Manirakize', dob: '2005-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Felix', last_name: 'Nyonkuru', dob: '2001-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Rene', last_name: 'Uwase', dob: '1999-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Patrick', last_name: 'Ishimwe', dob: '2005-11-28', estimated_dob: 'false', organization: mindleaps },
{ first_name: 'Jean', last_name: 'Musangemana', dob: '2003-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Jean de Dieu', last_name: 'Gihozo', dob: '2002-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Eugene', last_name: 'Herreimma', dob: '2002-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Musa', last_name: 'Byiringiro', dob: '2000-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Simon', last_name: 'Ndamage', dob: '2000-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Jean Paul', last_name: 'Kaysire', dob: '2002-07-15', estimated_dob: 'false', organization: mindleaps },
{ first_name: 'Andre', last_name: 'Iradukunda', dob: '2003-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Diel', last_name: 'Ndamage', dob: '2002-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Pacifique', last_name: 'Munykazi', dob: '2001-01-01', estimated_dob: 'true', organization: mindleaps }
])
kigali_chapter.groups[1].students.create([
{ first_name: 'Simon', last_name: 'Nubgazo', dob: '2001-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Moise', last_name: 'Izombigaze', dob: '2002-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Pacifique', last_name: 'Manireba', dob: '2008-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Fiston', last_name: 'Nyonkuza', dob: '2007-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Jean de Dieu', last_name: 'Umbawaze', dob: '1999-03-02', estimated_dob: 'false', organization: mindleaps },
{ first_name: 'Innocent', last_name: 'Ishimwe', dob: '1999-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Zidane', last_name: 'Musange', dob: '2003-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Jean Baptiste', last_name: 'Zabimogo', dob: '2001-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Yessin', last_name: 'Ibumina', dob: '2001-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Felix', last_name: 'Byiringira', dob: '1999-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Rene', last_name: 'Zabumazi', dob: '1999-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Eugene', last_name: 'Nyongazi', dob: '2000-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Ssali', last_name: 'Maniwarazi', dob: '2004-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Thierry', last_name: 'Isokazy', dob: '2005-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Diel', last_name: 'Munyakazi', dob: '2002-01-01', estimated_dob: 'true', organization: mindleaps }
])
subjects = Subject.create([
{ subject_name: 'Classical Dance', organization: mindleaps },
{ subject_name: 'Contemporary Dance', organization: mindleaps }
])
skills1 = Skill.create([
{ skill_name: 'Memorization', skill_description: 'Ability to memorize steps.', organization: mindleaps },
{ skill_name: 'Grit', skill_description: 'Ability to persevere.', organization: mindleaps },
{ skill_name: 'Teamwork', skill_description: 'Ability to work well with others.', organization: mindleaps },
{ skill_name: 'Language', skill_description: 'Ability to communicate in a foreign language.', organization: mindleaps },
{ skill_name: 'Creativity', skill_description: 'Ability to express in different ways.', organization: mindleaps },
{ skill_name: 'Discipline', skill_description: 'Consistency in attendance and focus..', organization: mindleaps },
{ skill_name: 'Self-Esteem', skill_description: 'Student\'s opinion of themselves.', organization: mindleaps }
])
subjects[0].skills = skills1
subjects[0].skills[0].grade_descriptors.create([
{ mark: 1, grade_description: 'Student cannot remember anything at all' },
{ mark: 2, grade_description: 'Students can remember a single combination' },
{ mark: 3, grade_description: 'Students can remember a single lengthy combination' },
{ mark: 4, grade_description: 'Students can remember two combinations' },
{ mark: 5, grade_description: 'Students can remember warmup and at least two combinations' },
{ mark: 6, grade_description: 'Students can remember warmup and at least three combinations' },
{ mark: 7, grade_description: 'Students can remember the whole routine' }
])
TRACK-4 - Seeding Mindleaps skills and descriptors
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
# rubocop:disable Style/IndentArray
# rubocop:disable Metrics/LineLength
mindleaps = Organization.create organization_name: 'MindLeaps'
mindleaps.chapters.create([
{ chapter_name: 'Kigali' }
])
kigali_chapter = mindleaps.chapters[0]
kigali_chapter.groups.create([
{ group_name: 'A' },
{ group_name: 'B' }
])
kigali_chapter.groups[0].students.create([
{ first_name: 'Innocent', last_name: 'Ngabo', dob: '2003-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Emmanuel', last_name: 'Ishimwe', dob: '2007-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Eric', last_name: 'Manirakize', dob: '2005-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Felix', last_name: 'Nyonkuru', dob: '2001-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Rene', last_name: 'Uwase', dob: '1999-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Patrick', last_name: 'Ishimwe', dob: '2005-11-28', estimated_dob: 'false', organization: mindleaps },
{ first_name: 'Jean', last_name: 'Musangemana', dob: '2003-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Jean de Dieu', last_name: 'Gihozo', dob: '2002-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Eugene', last_name: 'Herreimma', dob: '2002-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Musa', last_name: 'Byiringiro', dob: '2000-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Simon', last_name: 'Ndamage', dob: '2000-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Jean Paul', last_name: 'Kaysire', dob: '2002-07-15', estimated_dob: 'false', organization: mindleaps },
{ first_name: 'Andre', last_name: 'Iradukunda', dob: '2003-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Diel', last_name: 'Ndamage', dob: '2002-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Pacifique', last_name: 'Munykazi', dob: '2001-01-01', estimated_dob: 'true', organization: mindleaps }
])
kigali_chapter.groups[1].students.create([
{ first_name: 'Simon', last_name: 'Nubgazo', dob: '2001-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Moise', last_name: 'Izombigaze', dob: '2002-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Pacifique', last_name: 'Manireba', dob: '2008-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Fiston', last_name: 'Nyonkuza', dob: '2007-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Jean de Dieu', last_name: 'Umbawaze', dob: '1999-03-02', estimated_dob: 'false', organization: mindleaps },
{ first_name: 'Innocent', last_name: 'Ishimwe', dob: '1999-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Zidane', last_name: 'Musange', dob: '2003-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Jean Baptiste', last_name: 'Zabimogo', dob: '2001-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Yessin', last_name: 'Ibumina', dob: '2001-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Felix', last_name: 'Byiringira', dob: '1999-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Rene', last_name: 'Zabumazi', dob: '1999-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Eugene', last_name: 'Nyongazi', dob: '2000-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Ssali', last_name: 'Maniwarazi', dob: '2004-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Thierry', last_name: 'Isokazy', dob: '2005-01-01', estimated_dob: 'true', organization: mindleaps },
{ first_name: 'Diel', last_name: 'Munyakazi', dob: '2002-01-01', estimated_dob: 'true', organization: mindleaps }
])
subjects = Subject.create([
{ subject_name: 'Classical Dance', organization: mindleaps },
{ subject_name: 'Contemporary Dance', organization: mindleaps }
])
skills1 = Skill.create([
{ skill_name: 'Memorization', skill_description: 'Ability to learn and recall sequences or patterns of information.', organization: mindleaps, grade_descriptors: GradeDescriptor.create([
{ mark: 1, grade_description: 'Student cannot recall a sequence of 4 steps even after prompted at least three times' },
{ mark: 2, grade_description: 'Student can recall a sequence of 4 steps with 1 or no prompts' },
{ mark: 3, grade_description: 'Student can recall at least 2 sections of the warm up from class to class' },
{ mark: 4, grade_description: 'Student can recall entire warm up sequence, moving in time with the teacher, and can repeat diagonal steps after one prompt from the teacher' },
{ mark: 5, grade_description: 'Student can recall entire warm up sequence without teacher guidance, at least four diagonal steps, and at least 16 counts of choreography without teacher prompts' },
{ mark: 6, grade_description: 'Student can recall entire warm up, at least eight diagonal steps, all of choreography and name at least 6 muscles without teacher prompts' },
{ mark: 7, grade_description: 'Student can memorize a new sequence of choreography given in one class and do all of the above' }
]) },
{ skill_name: 'Grit', skill_description: 'Perseverance and passion for long-term goals.', organization: mindleaps, grade_descriptors: GradeDescriptor.create([
{ mark: 1, grade_description: 'Student arrives at the center but does not participate in dance class even with teacher or peer encouragement' },
{ mark: 2, grade_description: 'Student participates in less than half of the class' },
{ mark: 3, grade_description: 'Student is present but not actively trying throughout the entire class' },
{ mark: 4, grade_description: 'Student participates in warm up, recognizes change in directions, understands number repetitions, and completes at least 1/2 of diagonal or choreography sections of class' },
{ mark: 5, grade_description: 'Student participates in the entire class and noticeably demonstrates persistence when struggling' },
{ mark: 6, grade_description: 'All of the above and student asks or answers questions' },
{ mark: 7, grade_description: 'Student shows an extraordinary level of commitment by either practicing before/after class (self-initiated), asking questions that suggest a deeper analysis, or asking for more opportunities to practice' }
]) },
{ skill_name: 'Teamwork', skill_description: 'Ability to work and/or create with other students.', organization: mindleaps, grade_descriptors: GradeDescriptor.create([
{ mark: 1, grade_description: 'Student refuses to hold hands or interact with partner in a required sequence across the floor' },
{ mark: 2, grade_description: 'Student will do above, but is unable to work or communicate with his/her peer in any piece of choreography or another part of class, even when encouraged by the teacher' },
{ mark: 3, grade_description: 'Student can work together with his/her peer in 2 or 3 simple steps in diagonal (two by two) or choreography when demonstrated/encouraged by the teacher with two verbal prompts' },
{ mark: 4, grade_description: 'Student can work together with his/her peer in a section of diagonal (two by two) and complete at least four partnered/group movements in choreography' },
{ mark: 5, grade_description: 'Student can work in a group to create a short choreographic piece with teacher coaching' },
{ mark: 6, grade_description: 'Student can work in a group to create a short choreographic piece without teacher coaching' },
{ mark: 7, grade_description: 'Student can work in a group to create a piece that is presented to the rest of class' }
]) },
{ skill_name: 'Discipline', skill_description: 'Ability to obey rules and/or a code of conduct.', organization: mindleaps, grade_descriptors: GradeDescriptor.create([
{ mark: 1, grade_description: 'Student repeatedly talks back, fights, hits or argues with peers and teachers and does not stop even when asked repeatedly; student is sent out of the class for 5-10 minutes by the teacher' },
{ mark: 2, grade_description: 'Student has to be reminded at least twice by name to respect his peers and/or pay attention to the teacher' },
{ mark: 3, grade_description: 'Student has to be reminded once by name to respect his peers or pay attention to the teacher' },
{ mark: 4, grade_description: 'Student respects/pays attention to the teacher, but bothers his peers, or vice versa (with no comments/prompts by teacher)' },
{ mark: 5, grade_description: 'Student works well with others and no teacher intervention is needed' },
{ mark: 6, grade_description: 'Student actively encourages others to pay attention and improve their behavior' },
{ mark: 7, grade_description: 'Student actively becomes a role model of exceptional, respectful behavior to the others' }
]) },
{ skill_name: 'Self-Esteem', skill_description: 'Confidence in one’s own abilities.', organization: mindleaps, grade_descriptors: GradeDescriptor.create([
{ mark: 1, grade_description: 'Student cannot perform any movement isolated (by himself)' },
{ mark: 2, grade_description: 'Student can perform a sequence of 2-4 steps on his own' },
{ mark: 3, grade_description: 'Student can continue through warm up sections and repetition of diagonal steps without encouragement from the teacher' },
{ mark: 4, grade_description: 'Student can demonstrate by himself steps of the diagonal and volunteer parts of the choreography when asked by the teacher' },
{ mark: 5, grade_description: 'Student can demonstrate the warm up, diagonal steps and all of the choreography by himself with confidence and no prompts' },
{ mark: 6, grade_description: 'Student can verbally explain movement in the warm up, diagonal and choreography' },
{ mark: 7, grade_description: 'Student demonstrates confidence as a person and dancer through extending full use of body in space ' }
]) },
{ skill_name: 'Creativity & Self-Expression', skill_description: 'Use of imagination.', organization: mindleaps, grade_descriptors: GradeDescriptor.create([
{ mark: 1, grade_description: 'Student is unable to demonstrate personal creativity by making up any pose or movement of his own' },
{ mark: 2, grade_description: 'Student can only demontrate creative movement in a single step or movement with teacher\'s prompts' },
{ mark: 3, grade_description: 'Student can make up his own arms for a sequence of steps' },
{ mark: 4, grade_description: 'Student can only demonstrate creative movement in a series of steps by copying the teacher or peer\'s earlier demonstration' },
{ mark: 5, grade_description: 'Student can create his own movements that have not been taught before and differ from standard hip hop moves' },
{ mark: 6, grade_description: 'Student can create his own choreography' },
{ mark: 7, grade_description: 'Student can create his own choreography and present it' }
]) },
{ skill_name: 'Language', skill_description: 'The process to understand and communicate.', organization: mindleaps, grade_descriptors: GradeDescriptor.create([
{ mark: 1, grade_description: 'Student is unable to count in a foreign language (eg English)' },
{ mark: 2, grade_description: 'Student can count with teacher prompting, and can recall some basic words with one prompt' },
{ mark: 3, grade_description: 'Student can count without prompts and recall some words' },
{ mark: 4, grade_description: 'Student can recite positions in the warm up, at least six of the diagonal steps\' names and positions' },
{ mark: 5, grade_description: 'Student can recite positions in warm up, diagonal steps, and muscle names' },
{ mark: 6, grade_description: 'Student can recite simple phrases (minimum of 3 words)' },
{ mark: 7, grade_description: 'Student can make himself understood to ask questions or make comments' }
]) }
])
subjects[0].skills = skills1
|
#The MIT License (MIT)
#
# Copyright (c) 2012 Ido Kanner
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
require 'redis'
require_relative 'redis_session/version'
##
#
# A session module
#
module Session
##
#
# == Example:
#
# require 'redis_session'
# session = Session::SessionClient.new(:prefix => 'example', :host => '10.0.0.31')
#
# session.save('key', 'value') # save key with the value of value without expire, return true if successful
# puts session.restore('key') # will return "value"
#
# session.save('self_destruct', 'in', 10) # save the key self_destruct with the value of 'in', and will terminates in 10 seconds
# sleep 10.1
# session.restore('self_destruct') # returns empty hash
# session.restore('self_destruct', nil) # returns default value of nil
#
# session.save('boom', { :bomb => 'ball' }, 10) # saving a ruby object
# puts session.ttl('boom') # should return the seconds left to the key to live or -1
#
# session.expire('key', 60) # the key will be gone in 60 seconds
# puts session.restore('key') # prints 'value'
#
# puts 'has value' if session.value? 'key' # check if key has a value
#
# session.delete('key') # deleted it before time :)
# # it's alias to remove
#
# puts 'still here' if session.key? 'key' # do we have the key ?
#
class SessionClient
##
#
# Creates an object of SessionClient
#
# ==== Parameters
# :host:: the ip address or host name of the redis server default localhost
# :path:: the path to unix socket of redis (instead of :host)
# :port:: the port number for the host - default 6379
# :db:: the Redis database number - default 0
# :prefix:: a prefix string for storing and retriving information
# :expire:: global expiry of keys in seconds
#
def initialize(options={})
raise ArgumentError, 'options must be Hash' unless options.kind_of? Hash
options[:host] ||= 'localhost' unless options[:path]
options[:port] ||= 6379
options[:db] ||= 0
options[:prefix] ||= ''
options[:expire] ||= 0
@options = options
@redis = Redis.new(@options)
end
##
#
# Getting the prefix name
#
# returns:: The prefix string
#
def prefix
@options[:prefix]
end
##
#
# Changing the prefix string _(will not effect existing keys)_
#
# prefix:: The new prefix to be set
#
def prefix=(prefix)
@options[:prefix] = prefix
end
##
#
# Saving a key with a value
#
# key:: the name of the key to be saved
# value:: the value to save. Can be any Ruby object
# ttl:: expiry time to the key. Default nil.
#
# returns:: true if successful or false otherwise
#
# *Note*:: If expire was set and ttl is nil, then the key will have expire by the :expire option
#
def save(key, value, ttl = nil)
a_key = make_key(key)
a_data = Marshal.dump(value)
ttl ||= @options[:expire]
if ttl > 0
@redis.setex(a_key, ttl, a_data)
else
@redis.set(a_key, a_data)
end
true
rescue BaseConnectionError
raise
rescue Exception
false
end
##
#
# Restoring a key's value or providing a default value instead
#
# key:: The name of the key to restore
# default:: The value to provide if no value was given. Default empty Hash
#
# returns:: The value of the key or default value
#
def restore(key, default={})
a_key = make_key(key)
data = @redis.get(a_key)
data.nil? ? default : Marshal.load(data)
rescue BaseConnectionError
raise
rescue Exception
default
end
##
#
# Set an expire time in seconds to a key. If the key already has an expire time, it reset it to a new time.
#
# key:: The name of the key to set the expire time
# ttl:: The time in seconds to expire the key
#
# returns:: true if successful or false if not
#
def expire(key, ttl)
a_key = make_key(key)
@redis.expire(a_key, ttl)
rescue BaseConnectionError
raise
rescue Exception
false
end
##
#
# Examines how much time left to a key in seconds
#
# key:: The name of a key to check the ttl
#
# returns:: Returns the number of seconds left, or -1 if key does not exists or no ttl exists for it
#
def ttl(key)
a_key = make_key(key)
@redis.ttl(a_key)
rescue BaseConnectionError
raise
rescue Exception
-1
end
##
#
# Deleting a key from the session
#
# key:: The name of the key to be removed
#
# returns:: true if successful or false otherwise
#
def remove(key)
a_key = make_key(key)
@redis.del(a_key)
rescue BaseConnectionError
raise
rescue Exception
false
end
##
#
# Check to see if a key exists
#
# key:: The name of the key to check
#
# returns:: true if it exists or false otherwise
#
def key?(key)
a_key = make_key(key)
@redis.exists a_key
rescue BaseConnectionError
raise
rescue Exception
false
end
##
#
# Check if a key has a value
#
# key:: The name of the key to check
#
# returns:: true if exists or false otherwise
#
def value?(key)
a_key = make_key(key)
@redis.get(a_key) != nil
rescue BaseConnectionError
raise
rescue Exception
false
end
##
#
# Deleting a key from the session
#
# key:: The name of the key to be removed
#
# returns:: true if successful or false otherwise
#
alias :delete :remove
##
#
# scan for partial value in redis
# Using a block you can create your own criteria for lookup:
#
# Example:
# let's say there is a key named "foo", and the value is a hash: {:click=>true, :reading=>0}
#
# ret = session.scan_by do |x|
# next unless x.kind_of? Hash
# next unless x.key? :click
#
# x[:click] == true
# end
#
# => {"foo"=>{:click=>true, :reading=>0}}
#
# If found return a hash of key => value
# If not found, return nil
#
def scan_by(&block)
key = ''
value = ''
@redis.keys('*').each do |x|
next unless @redis.type(x) == 'string'
value = Marshal.load(@redis.get(x)) rescue next # not really a ruby object
if yield value
key = x
break
end
end
return nil if key.empty?
{ key => value }
rescue BaseConnectionError
raise
rescue Exception #=> e
# puts "exception: #{e}\n#{e.backtrace.join("\n")}"
nil
end
private
##
#
# Generate a key with a prefix string
#
# key:: The name of the key to generate
#
# returns:: the key with the prefix
#
def make_key(key)
"#{@options[:prefix]}#{key}"
end
end
end
need to qualify BaseConnectionError
#The MIT License (MIT)
#
# Copyright (c) 2012 Ido Kanner
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
require 'redis'
require_relative 'redis_session/version'
##
#
# A session module
#
module Session
##
#
# == Example:
#
# require 'redis_session'
# session = Session::SessionClient.new(:prefix => 'example', :host => '10.0.0.31')
#
# session.save('key', 'value') # save key with the value of value without expire, return true if successful
# puts session.restore('key') # will return "value"
#
# session.save('self_destruct', 'in', 10) # save the key self_destruct with the value of 'in', and will terminates in 10 seconds
# sleep 10.1
# session.restore('self_destruct') # returns empty hash
# session.restore('self_destruct', nil) # returns default value of nil
#
# session.save('boom', { :bomb => 'ball' }, 10) # saving a ruby object
# puts session.ttl('boom') # should return the seconds left to the key to live or -1
#
# session.expire('key', 60) # the key will be gone in 60 seconds
# puts session.restore('key') # prints 'value'
#
# puts 'has value' if session.value? 'key' # check if key has a value
#
# session.delete('key') # deleted it before time :)
# # it's alias to remove
#
# puts 'still here' if session.key? 'key' # do we have the key ?
#
class SessionClient
##
#
# Creates an object of SessionClient
#
# ==== Parameters
# :host:: the ip address or host name of the redis server default localhost
# :path:: the path to unix socket of redis (instead of :host)
# :port:: the port number for the host - default 6379
# :db:: the Redis database number - default 0
# :prefix:: a prefix string for storing and retriving information
# :expire:: global expiry of keys in seconds
#
def initialize(options={})
raise ArgumentError, 'options must be Hash' unless options.kind_of? Hash
options[:host] ||= 'localhost' unless options[:path]
options[:port] ||= 6379
options[:db] ||= 0
options[:prefix] ||= ''
options[:expire] ||= 0
@options = options
@redis = Redis.new(@options)
end
##
#
# Getting the prefix name
#
# returns:: The prefix string
#
def prefix
@options[:prefix]
end
##
#
# Changing the prefix string _(will not effect existing keys)_
#
# prefix:: The new prefix to be set
#
def prefix=(prefix)
@options[:prefix] = prefix
end
##
#
# Saving a key with a value
#
# key:: the name of the key to be saved
# value:: the value to save. Can be any Ruby object
# ttl:: expiry time to the key. Default nil.
#
# returns:: true if successful or false otherwise
#
# *Note*:: If expire was set and ttl is nil, then the key will have expire by the :expire option
#
def save(key, value, ttl = nil)
a_key = make_key(key)
a_data = Marshal.dump(value)
ttl ||= @options[:expire]
if ttl > 0
@redis.setex(a_key, ttl, a_data)
else
@redis.set(a_key, a_data)
end
true
rescue Redis::BaseConnectionError
raise
rescue Exception
false
end
##
#
# Restoring a key's value or providing a default value instead
#
# key:: The name of the key to restore
# default:: The value to provide if no value was given. Default empty Hash
#
# returns:: The value of the key or default value
#
def restore(key, default={})
a_key = make_key(key)
data = @redis.get(a_key)
data.nil? ? default : Marshal.load(data)
rescue Redis::BaseConnectionError
raise
rescue Exception
default
end
##
#
# Set an expire time in seconds to a key. If the key already has an expire time, it reset it to a new time.
#
# key:: The name of the key to set the expire time
# ttl:: The time in seconds to expire the key
#
# returns:: true if successful or false if not
#
def expire(key, ttl)
a_key = make_key(key)
@redis.expire(a_key, ttl)
rescue Redis::BaseConnectionError
raise
rescue Exception
false
end
##
#
# Examines how much time left to a key in seconds
#
# key:: The name of a key to check the ttl
#
# returns:: Returns the number of seconds left, or -1 if key does not exists or no ttl exists for it
#
def ttl(key)
a_key = make_key(key)
@redis.ttl(a_key)
rescue Redis::BaseConnectionError
raise
rescue Exception
-1
end
##
#
# Deleting a key from the session
#
# key:: The name of the key to be removed
#
# returns:: true if successful or false otherwise
#
def remove(key)
a_key = make_key(key)
@redis.del(a_key)
rescue Redis::BaseConnectionError
raise
rescue Exception
false
end
##
#
# Check to see if a key exists
#
# key:: The name of the key to check
#
# returns:: true if it exists or false otherwise
#
def key?(key)
a_key = make_key(key)
@redis.exists a_key
rescue Redis::BaseConnectionError
raise
rescue Exception
false
end
##
#
# Check if a key has a value
#
# key:: The name of the key to check
#
# returns:: true if exists or false otherwise
#
def value?(key)
a_key = make_key(key)
@redis.get(a_key) != nil
rescue Redis::BaseConnectionError
raise
rescue Exception
false
end
##
#
# Deleting a key from the session
#
# key:: The name of the key to be removed
#
# returns:: true if successful or false otherwise
#
alias :delete :remove
##
#
# scan for partial value in redis
# Using a block you can create your own criteria for lookup:
#
# Example:
# let's say there is a key named "foo", and the value is a hash: {:click=>true, :reading=>0}
#
# ret = session.scan_by do |x|
# next unless x.kind_of? Hash
# next unless x.key? :click
#
# x[:click] == true
# end
#
# => {"foo"=>{:click=>true, :reading=>0}}
#
# If found return a hash of key => value
# If not found, return nil
#
def scan_by(&block)
key = ''
value = ''
@redis.keys('*').each do |x|
next unless @redis.type(x) == 'string'
value = Marshal.load(@redis.get(x)) rescue next # not really a ruby object
if yield value
key = x
break
end
end
return nil if key.empty?
{ key => value }
rescue Redis::BaseConnectionError
raise
rescue Exception #=> e
# puts "exception: #{e}\n#{e.backtrace.join("\n")}"
nil
end
private
##
#
# Generate a key with a prefix string
#
# key:: The name of the key to generate
#
# returns:: the key with the prefix
#
def make_key(key)
"#{@options[:prefix]}#{key}"
end
end
end
|
require 'securerandom'
module Superintendent::Request
class Id
X_REQUEST_ID = 'HTTP_X_REQEUST_ID'.freeze
def initialize(app)
@app = app
end
def call(env)
unless env['HTTP_X_REQUEST_ID']
env.merge!('HTTP_X_REQUEST_ID' => generate_request_id)
end
@app.call(env)
end
private
def generate_request_id
"OHM#{SecureRandom.uuid.gsub!('-', '')}"
end
end
end
Use UUID for request ID
require 'securerandom'
module Superintendent::Request
class Id
X_REQUEST_ID = 'HTTP_X_REQEUST_ID'.freeze
def initialize(app)
@app = app
end
def call(env)
unless env['HTTP_X_REQUEST_ID']
env.merge!('HTTP_X_REQUEST_ID' => generate_request_id)
end
@app.call(env)
end
private
def generate_request_id
SecureRandom.uuid
end
end
end
|
# Account Types
# =============
current_assets, capital_assets, outside_capital, equity_capital, costs, earnings =
AccountType.create!([
{:name => "current_assets", :title => "Umlaufvermögen"},
{:name => "capital_assets", :title => "Anlagevermögen"},
{:name => "outside_capital", :title => "Fremdkapital"},
{:name => "equity_capital", :title => "Eigenkapital"},
{:name => "costs", :title => "Aufwand"},
{:name => "earnings", :title => "Ertrag"},
])
# Credit Invoices
Account.create!([
{:code => "2000", :title => "Kreditoren", :account_type => outside_capital},
{:code => "4000", :title => "Materialaufwand", :account_type => costs},
])
BookingTemplate.create!([
{:code => "credit_invoice:invoice", :title => "Kreditoren Rechnung", :debit_account => Account.find_by_code("2000"), :credit_account => Account.find_by_code("4000"), :amount => 1, :amount_relates_to => 'reference_amount'},
{:code => "credit_invoice:reminder", :title => "Mahnung", :debit_account => Account.find_by_code("2000"), :credit_account => Account.find_by_code("4000")},
{:code => "credit_invoice:cancel", :title => "Storno", :debit_account => Account.find_by_code("4000"), :credit_account => Account.find_by_code("2000"), :amount => 1, :amount_relates_to => 'reference_amount'},
{:code => "credit_invoice:cash_payment", :title => "Barzahlung", :debit_account => Account.find_by_code("1000"), :credit_account => Account.find_by_code("2000"), :amount => 1, :amount_relates_to => 'reference_balance'},
{:code => "credit_invoice:bank_payment", :title => "Bankzahlung", :debit_account => Account.find_by_code("1020"), :credit_account => Account.find_by_code("2000")},
])
# DebitInvoice
Account.create!([
{:code => "3900", :title => "Debitorenverlust", :account_type => costs},
])
BookingTemplate.create!([
{:code => "debit_invoice:invoice", :title => "Debitoren Rechnung", :debit_account => Account.find_by_code("3200"), :credit_account => Account.find_by_code("1100"), :amount => 1, :amount_relates_to => 'reference_amount'},
{:code => "debit_invoice:reminder", :title => "Mahnung", :debit_account => Account.find_by_code("3200"), :credit_account => Account.find_by_code("1100")},
{:code => "debit_invoice:cancel", :title => "Storno", :debit_account => Account.find_by_code("1100"), :credit_account => Account.find_by_code("3200"), :amount => 1, :amount_relates_to => 'reference_amount'},
{:code => "debit_invoice:cash_payment", :title => "Barzahlung", :debit_account => Account.find_by_code("1100"), :credit_account => Account.find_by_code("1000"), :amount => 1, :amount_relates_to => 'reference_balance'},
{:code => "debit_invoice:bank_payment", :title => "Bankzahlung", :debit_account => Account.find_by_code("1100"), :credit_account => Account.find_by_code("1020")},
])
Add Role model seeds.
# Authorization
# =============
Role.create!([
{:name => 'admin'},
{:name => 'accountant'}
])
# Account Types
# =============
current_assets, capital_assets, outside_capital, equity_capital, costs, earnings =
AccountType.create!([
{:name => "current_assets", :title => "Umlaufvermögen"},
{:name => "capital_assets", :title => "Anlagevermögen"},
{:name => "outside_capital", :title => "Fremdkapital"},
{:name => "equity_capital", :title => "Eigenkapital"},
{:name => "costs", :title => "Aufwand"},
{:name => "earnings", :title => "Ertrag"},
])
# Credit Invoices
Account.create!([
{:code => "2000", :title => "Kreditoren", :account_type => outside_capital},
{:code => "4000", :title => "Materialaufwand", :account_type => costs},
])
BookingTemplate.create!([
{:code => "credit_invoice:invoice", :title => "Kreditoren Rechnung", :debit_account => Account.find_by_code("2000"), :credit_account => Account.find_by_code("4000"), :amount => 1, :amount_relates_to => 'reference_amount'},
{:code => "credit_invoice:reminder", :title => "Mahnung", :debit_account => Account.find_by_code("2000"), :credit_account => Account.find_by_code("4000")},
{:code => "credit_invoice:cancel", :title => "Storno", :debit_account => Account.find_by_code("4000"), :credit_account => Account.find_by_code("2000"), :amount => 1, :amount_relates_to => 'reference_amount'},
{:code => "credit_invoice:cash_payment", :title => "Barzahlung", :debit_account => Account.find_by_code("1000"), :credit_account => Account.find_by_code("2000"), :amount => 1, :amount_relates_to => 'reference_balance'},
{:code => "credit_invoice:bank_payment", :title => "Bankzahlung", :debit_account => Account.find_by_code("1020"), :credit_account => Account.find_by_code("2000")},
])
# DebitInvoice
Account.create!([
{:code => "3900", :title => "Debitorenverlust", :account_type => costs},
])
BookingTemplate.create!([
{:code => "debit_invoice:invoice", :title => "Debitoren Rechnung", :debit_account => Account.find_by_code("3200"), :credit_account => Account.find_by_code("1100"), :amount => 1, :amount_relates_to => 'reference_amount'},
{:code => "debit_invoice:reminder", :title => "Mahnung", :debit_account => Account.find_by_code("3200"), :credit_account => Account.find_by_code("1100")},
{:code => "debit_invoice:cancel", :title => "Storno", :debit_account => Account.find_by_code("1100"), :credit_account => Account.find_by_code("3200"), :amount => 1, :amount_relates_to => 'reference_amount'},
{:code => "debit_invoice:cash_payment", :title => "Barzahlung", :debit_account => Account.find_by_code("1100"), :credit_account => Account.find_by_code("1000"), :amount => 1, :amount_relates_to => 'reference_balance'},
{:code => "debit_invoice:bank_payment", :title => "Bankzahlung", :debit_account => Account.find_by_code("1100"), :credit_account => Account.find_by_code("1020")},
])
|
=begin
redparse - a ruby parser written in ruby
Copyright (C) 2008 Caleb Clausen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
=end
begin
require 'rubygems'
rescue LoadError=>e
raise unless /rubygems/===e.message
#hope we don't need it
end
require 'tempfile'
require 'pp'
require "rubylexer"
require "reg"
require "redparse/float_accurate_to_s"
class RedParse
#import token classes from rubylexer
RubyLexer::constants.each{|k|
t=RubyLexer::const_get(k)
self::const_set k,t if Module===t and RubyLexer::Token>=t
}
module FlattenedIvars
EXCLUDED_IVARS=%w[@data @offset @startline @endline]
EXCLUDED_IVARS.push(*EXCLUDED_IVARS.map{|iv| iv.to_sym })
def flattened_ivars
ivars=instance_variables
ivars-=EXCLUDED_IVARS
ivars.sort!
result=ivars+ivars.map{|iv|
instance_variable_get(iv)
}
return result
end
def flattened_ivars_equal?(other)
self.class == other.class and
flattened_ivars == other.flattened_ivars
end
end
module Stackable
module Meta
#declare name to be part of the identity of current class
#variations are the allowed values for name in this class
#keep variations simple: booleans, integers, symbols and strings only
def identity_param name, *variations
name=name.to_s
list=
if (variations-[true,false,nil]).empty?
#const_get("BOOLEAN_IDENTITY_PARAMS") rescue const_set("BOOLEAN_IDENTITY_PARAMS",{})
self.boolean_identity_params
else
#const_get("IDENTITY_PARAMS") rescue const_set("IDENTITY_PARAMS",{})
self.identity_params
end
list[name]=variations
return #old way to generate examplars below
=begin
old_exemplars=self.exemplars||=[allocate]
exemplars=[]
variations.each{|var| old_exemplars.each{|exm|
exemplars<< res=exm.dup
#res.send name+"=", var
#res.send :define_method, name do var end
Symbol|String|Integer|true|false|nil===var or fail #so inspect works as a quoting
eval "def res.#{name}; #{var.inspect} end"
}}
old_exemplars.replace exemplars
=end
end
def enumerate_exemplars
@exemplars||= build_exemplars
end
def build_exemplars
exemplars=[[self]]
(boolean_identity_params.merge identity_params).each{|name,variations|
todo=[]
variations=variations.dup
variations.each{|var|
exemplars.each{|exm|
res=exm.dup
#res.send name+"=", var
#res.send :define_method, name do var end
Symbol|String|Integer|true|false|nil===var or fail #so inspect works as a quoting
#eval "def res.#{name}; #{var.inspect} end"
res.push name, var
todo<<res #unless exemplars.include? res
}
}
exemplars=todo
}
#by now, may be some exemplars with identical identities...
#those duplicate identities should be culled
# identities_seen={}
# exemplars.delete_if{|ex|
# idn=ex.identity_name
# chuck_it=identities_seen[idn]
# identities_seen[idn]=true
# chuck_it
# }
return exemplars
end
attr_writer :boolean_identity_params, :identity_params
def identity_params
return @identity_params if defined?(@identity_params) and @identity_params
@identity_params=
if superclass.respond_to? :identity_params
superclass.identity_params.dup
else
{}
end
end
def boolean_identity_params
return @boolean_identity_params if defined?(@boolean_identity_params) and @boolean_identity_params
@boolean_identity_params=
if superclass.respond_to? :boolean_identity_params
superclass.boolean_identity_params.dup
else
{}
end
end
end #of Meta
def identity_name
k=self.class
list=[k.name]
list.concat k.boolean_identity_params.map{|(bip,*)| bip if send(bip) }.compact
list.concat k.identity_params.map{|(ip,variations)|
val=send(ip)
variations.include? val or fail "identity_param #{k}##{ip} unexpected value #{val.inspect}"
[ip,val]
}.flatten
result=list.join("_")
return result
end
end
class Token
include Stackable
extend Stackable::Meta
def image; "#{inspect}" end
def to_parsetree(*options) #this shouldn't be needed anymore
o={}
[:newlines,:quirks,:ruby187].each{|opt|
o[opt]=true if options.include? opt
}
result=[parsetree(o)]
result=[] if result==[[]]
return result
end
def lvalue; nil end
def data; [self] end
def unary; false end
def rescue_parsetree(o); parsetree(o) end
def begin_parsetree(o); parsetree(o) end
#attr :line
#alias endline line
#attr_writer :startline
#def startline
# @startline||=endline
#end
end
class KeywordToken
def not_real!
@not_real=true
end
def not_real?
@not_real if defined? @not_real
end
identity_param :ident, *%w<+@ -@ unary& unary* ! ~ not defined?>+ #should be unary ops
%w<end ( ) { } [ ] alias undef in>+
%w<? : ; !~ lhs, rhs, rescue3>+ #these should be ops
%w{*= **= <<= >>= &&= ||= |= &= ^= /= %= -= += = => ... .. . ::}+ #shouldn't be here, grrr
RubyLexer::FUNCLIKE_KEYWORDLIST+
RubyLexer::VARLIKE_KEYWORDLIST+
RubyLexer::INNERBOUNDINGWORDLIST+
RubyLexer::BINOPWORDLIST+
RubyLexer::BEGINWORDLIST
#identity_param :unary, true,false,nil
#identity_param :tag, :lhs,:rhs,:param,:call,:array,:block,:nested,nil
identity_param :callsite?, nil, true, false
identity_param :not_real?, nil, true, false
identity_param :infix, nil, true
alias image ident
#KeywordToken#as/infix should be in rubylexer
alias old_as as
def as
if tag and ident[/^[,*&]$/]
tag.to_s+ident
else old_as
end
end
def infix
@infix if defined? @infix
end unless allocate.respond_to? :infix
end
class OperatorToken
identity_param :ident, *%w[+@ -@ unary& unary* lhs* ! ~ not defined? * ** + -
< << <= <=> > >= >> =~ == ===
% / & | ^ != !~ = => :: ? : , ; . .. ...
*= **= <<= >>= &&= ||= && ||
&= |= ^= %= /= -= += and or
]+RubyLexer::OPORBEGINWORDLIST+%w<; lhs, rhs, rescue3>
#identity_param :unary, true,false,nil
#identity_param :tag, :lhs,:rhs,:param,:call,:array,:block,:nested,nil
end
class NumberToken
alias to_lisp to_s
def negative; /\A-/ === ident end unless allocate.respond_to? :negative
identity_param :negative, true,false
end
class MethNameToken
alias to_lisp to_s
def has_equals; /#{LETTER_DIGIT}=$/o===ident end unless allocate.respond_to? :has_equals
identity_param :has_equals, true,false
end
class VarNameToken #none of this should be necessary now
include FlattenedIvars
alias image ident
alias == flattened_ivars_equal?
def parsetree(o)
type=case ident[0]
when ?$
case ident[1]
when ?1..?9; return [:nth_ref,ident[1..-1].to_i]
when ?&,?+,?`,?'; return [:back_ref,ident[1].chr.to_sym] #`
else :gvar
end
when ?@
if ident[1]==?@
:cvar
else
:ivar
end
when ?A..?Z; :const
else
case lvar_type
when :local; :lvar
when :block; :dvar
when :current; :dvar#_curr
else fail
end
end
return [type,ident.to_sym]
end
def varname2assigntype
case ident[0]
when ?$; :gasgn
when ?@;
if ident[1]!=?@; :iasgn
elsif in_def; :cvasgn
else :cvdecl
end
when ?A..?Z; :cdecl
else
case lvar_type
when :local; :lasgn
when :block; :dasgn
when :current; :dasgn_curr
else fail
end
end
end
def lvalue_parsetree(o)
[varname2assigntype, ident.to_sym]
end
def old_unused_lvalue #i think this is the correct way, but its overridded below
return @lvalue if defined? @lvalue
@lvalue=true
end
def all_current_lvars
lvar_type==:current ? [ident] : []
end
attr_accessor :endline,:lvalue
def dup
result=super
result.ident=@ident.dup
return result
end
public :remove_instance_variable
def unparse o=default_unparse_options; ident end
alias lhs_unparse unparse
def delete_extraneous_ivars!
huh
end
def walk
yield nil,nil,nil,self
end
end
class StringToken
attr :char unless allocate.respond_to? :char
end
class HerePlaceholderToken
attr_accessor :node
attr :string unless allocate.respond_to? :string
end
module ListInNode
def []=(*args)
val=args.pop
#inline symbols as callnodes
case val
when Symbol
val=CallNode[nil,val.to_s]
when Integer,Float
val=LiteralNode[val]
end
super( *args<<val )
end
end
class Node<Array
include Stackable
extend Stackable::Meta
include FlattenedIvars
def initialize(*data)
replace data
end
def initialize_ivars
@offset||=0
@startline||=0
@endline||=0
end
def self.create(*args)
new(*args)
end
def ==(other)
super and flattened_ivars_equal?(other)
end
def +(other)
if SequenceNode===other
SequenceNode[self,*other]
else
SequenceNode[self,other]
end
end
alias original_brackets_assign []= #needed by LiteralNode
def []=(*args)
val=args.pop
#inline symbols as callnodes
case val
when Symbol
val=CallNode[nil,val.to_s]
when Integer,Float
val=LiteralNode[val]
end
super( *args<<val )
end
def image; "(#{inspect})" end
def error? x; false end
@@data_warned=nil
def data
unless @@data_warned
warn "using obsolete Node#data from #{caller.first}"
@@data_warned=true
end
Array.new(self)
end
alias unwrap data
attr_writer :startline
def startline
@startline||=endline
end
attr_accessor :endline
attr_accessor :errors
attr_reader :offset
def self.inline_symbols data
data.map!{|datum|
Symbol===datum ?
CallNode[nil,datum.to_s,nil,nil,nil] :
datum
}
end
def self.[](*data)
options=data.pop if Hash===data.last
inline_symbols data
result=allocate
result.instance_eval{
replace data
options.each_pair{|name,val|
instance_variable_set name,val
} if options
}
result.initialize_ivars
return result
end
def inspect label=nil,indent=0,verbose=false
ivarnames=instance_variables-FlattenedIvars::EXCLUDED_IVARS
ivarnodes=[]
ivars=ivarnames.map{|ivarname|
ivar=instance_variable_get(ivarname)
if Node===ivar
ivarnodes.push [ivarname,ivar]
nil
else
ivarname[1..-1]+"="+ivar.inspect if ivar and verbose
end
}.compact.join(' ')
if verbose
pos=@startline.to_s
pos<<"..#@endline" if @endline!=@startline
pos<<"@#@offset"
end
classname=self.class.name
classname.sub!(/^(?:RedParse::)?(.*?)(?:Node)?$/){$1}
result= [' '*indent,"+",(label+': ' if label),classname,]
result+=[" pos=",pos,] if pos
result+=[" ",ivars,"\n"]
indent+=2
namelist=self.class.namelist
if namelist and !namelist.empty?
namelist.each{|name|
val=send name rescue "{{ERROR INSPECTING ATTR #{name}}}"
case val
when Node; result<< val.inspect(name,indent,verbose)
when ListInNode
result.push ' '*indent,"+#{name}:\n",*val.map{|v|
v.inspect(nil,indent+2,verbose) rescue ' '*(indent+2)+"-#{v.inspect}\n"
}
when nil;
else ivars<< " #{name}=#{val.inspect}"
end
}
else
each{|val|
case val
when Node; result<< val.inspect(nil,indent,verbose)
else result<< ' '*indent+"-#{val.inspect}\n"
end
}
end
ivarnodes.each{|(name,val)|
result<< val.inspect(name,indent)
}
return result.join
end
def evalable_inspect
ivarnames=instance_variables-["@data", :@data]
ivars=ivarnames.map{|ivarname|
val=instance_variable_get(ivarname)
if val.respond_to?(:evalable_inspect)
val=val.evalable_inspect
else
val=val.inspect
end
":"+ivarname+"=>"+val
}.join(', ')
bare="["+map{|val|
if val.respond_to?(:evalable_inspect)
val=val.evalable_inspect
else
val=val.inspect
end
}.join(", ")+"]"
bare.gsub!(/\]\Z/, ", {"+ivars+"}]") unless ivarnames.empty?
return self.class.name+bare
end
def pretty_print(q)
ivarnames=instance_variables-["@data", :@data]
ivars={}
ivarnames.each{|ivarname|
ivars[ivarname.to_sym]=instance_variable_get(ivarname)
}
q.group(1, self.class.name+'[', ']') {
displaylist= ivars.empty? ? self : dup<<ivars
q.seplist(displaylist) {|v|
q.pp v
}
# q.text ', '
# q.pp_hash ivars
}
end
def self.param_names(*names)
accessors=[]
namelist=[]
@namelist=[]
names.each{|name|
name=name.to_s
last=name[-1]
name.chomp! '!' and name << ?_
namelist << name
unless last==?_
accessors << "def #{name.chomp('_')}; self[#{@namelist.size}] end\n"
accessors << "def #{name.chomp('_')}=(newval); "+
"newval.extend ::RedParse::ListInNode if ::Array===newval and not RedParse::Node===newval;"+
"self[#{@namelist.size}]=newval "+
"end\n"
@namelist << name
end
}
init="
def initialize(#{namelist.join(', ')})
replace [#{@namelist.size==1 ?
@namelist.first :
@namelist.join(', ')
}]
end
alias init_data initialize
"
code= "class ::#{self}\n"+init+accessors.join+"\nend\n"
if defined? DEBUGGER__ or defined? Debugger
Tempfile.open("param_name_defs"){|f|
f.write code
f.flush
load f.path
}
else
eval code
end
@namelist.reject!{|name| /_\Z/===name }
end
def self.namelist
#@namelist
result=superclass.namelist||[] rescue []
result.concat @namelist if defined? @namelist
return result
end
def lhs_unparse o; unparse(o) end
def to_parsetree(*options)
o={}
[:newlines,:quirks,:ruby187].each{|opt|
o[opt]=true if options.include? opt
}
result=[parsetree(o)]
result=[] if result==[[]] || result==[nil]
return result
end
def to_parsetree_and_warnings(*options)
#for now, no warnings are ever output
return to_parsetree(*options),[]
end
def parsetree(o)
"wrong(#{inspect})"
end
def rescue_parsetree(o); parsetree(o) end
def begin_parsetree(o); parsetree(o) end
def parsetrees list,o
!list.empty? and list.map{|node| node.parsetree(o)}
end
def negate(condition,offset=nil)
if UnOpNode===condition and condition.op.ident[/^(!|not)$/]
condition.val
else
UnOpNode.new(KeywordToken.new("not",offset),condition)
end
end
#callback takes four parameters:
#parent of node currently being walked, index and subindex within
#that parent, and finally the actual node being walked.
def walk(parent=nil,index=nil,subindex=nil,&callback)
callback[ parent,index,subindex,self ] and
each_with_index{|datum,i|
case datum
when Node; datum.walk(self,i,&callback)
when Array;
datum.each_with_index{|x,j|
Node===x ? x.walk(self,i,j,&callback) : callback[self,i,j,x]
}
else callback[self,i,nil,datum]
end
}
end
def depthwalk(parent=nil,index=nil,subindex=nil,&callback)
(size-1).downto(0){|i|
datum=self[i]
case datum
when Node
datum.depthwalk(self,i,&callback)
when Array
(datum.size-1).downto(0){|j|
x=datum[j]
if Node===x
x.depthwalk(self,i,j,&callback)
else
callback[self,i,j,x]
end
}
else
callback[self, i, nil, datum]
end
}
callback[ parent,index,subindex,self ]
end
def depthwalk_nodes(parent=nil,index=nil,subindex=nil,&callback)
(size-1).downto(0){|i|
datum=self[i]
case datum
when Node
datum.depthwalk_nodes(self,i,&callback)
when Array
(datum.size-1).downto(0){|j|
x=datum[j]
if Node===x
x.depthwalk_nodes(self,i,j,&callback)
end
}
end
}
callback[ parent,index,subindex,self ]
end
def add_parent_links!
walk{|parent,i,subi,o|
o.parent=parent if Node===o
}
end
attr_accessor :parent
def xform_tree!(*xformers)
#search tree for patterns and store results of actions in session
session={}
depthwalk{|parent,i,subi,o|
xformers.each{|xformer|
if o
tempsession={}
xformer.xform!(o,tempsession)
merge_replacement_session session, tempsession
#elsif xformer===o and Reg::Transform===xformer
# new=xformer.right
# if Reg::Formula===right
# new=new.formula_value(o,session)
# end
# subi ? parent[i][subi]=new : parent[i]=new
end
}
}
session["final"]=true
#apply saved-up actions stored in session, while making a copy of tree
result=::Ron::GraphWalk::graphcopy(self,old2new={}){|cntr,o,i,ty,useit|
newo=nil
replace_value o.__id__,o,session do |val|
newo=val
useit[0]=true
end
newo
}
finallys=session["finally"] #finallys too
finallys.each{|(action,arg)| action[old2new[arg.__id__],session] } if finallys
return result
=begin was
finallys=session["finally"]
finallys.each{|(action,arg)| action[arg] } if finallys
depthwalk{|parent,i,subi,o|
next unless parent
replace_ivars_and_self o, session do |new|
subi ? parent[i][subi]=new : parent[i]=new
end
}
replace_ivars_and_self self,session do |new|
fail unless new
return new
end
return self
=end
end
def rgrep pattern
result=grep(pattern)
each{|subnode| result.concat subnode.rgrep(pattern) if subnode.respond_to? :rgrep}
return result
end
def rfind ifnone=nil, &block
result=find(proc{
find{|subnode| subnode.rfind(&block) if subnode.respond_to? :rfind}
},&block)
return result if result
return ifnone[] if ifnone
end
def rfind_all &block
result=find_all(&block)
each{|subnode| result.concat subnode.find_all(&block) if subnode.respond_to? :rfind_all}
return result
end
def replace_ivars_and_self o,session,&replace_self_action
o.instance_variables.each{|ovname|
ov=o.instance_variable_get(ovname)
replace_value ov.__id__,ov,session do |new|
o.instance_variable_set(ovname,new)
end
}
replace_value o.__id__,o,session, &replace_self_action
end
def replace_value ovid,ov,session,&replace_action
if session.has_key? ovid
new= session[ovid]
if Reg::Formula===new
new=new.formula_value(ov,session)
end
replace_action[new]
end
end
def merge_replacement_session session,tempsession
ts_has_boundvars= !tempsession.keys.grep(::Symbol).empty?
tempsession.each_pair{|k,v|
if Integer===k
if true
v=Reg::WithBoundRefValues.new(v,tempsession) if ts_has_boundvars
else
v=Ron::GraphWalk.graphcopy(v){|cntr,o,i,ty,useit|
if Reg::BoundRef===o
useit[0]=true
tempsession[o.name]||o
end
}
end
if session.has_key? k
v=v.chain_to session[k]
end
session[k]=v
elsif "finally"==k
session["finally"]=Array(session["finally"]).concat v
end
}
end
def linerange
min=9999999999999999999999999999999999999999999999999999
max=0
walk{|parent,i,subi,node|
if node.respond_to? :endline and line=node.endline
min=[min,line].min
max=[max,line].max
end
}
return min..max
end
def fixup_multiple_assignments! #dead code
result=self
walk{|parent,i,subi,node|
if CommaOpNode===node
#there should be an assignnode within this node... find it
j=nil
list=Array.new(node)
assignnode=nil
list.each_with_index{|assignnode2,jj| assignnode=assignnode2
AssignNode===assignnode and break(j=jj)
}
fail "CommaOpNode without any assignment in final parse tree" unless j
#re-hang the current node with = at the top
lhs=list[0...j]<<list[j].left
rhs=list[j+1..-1].unshift list[j].right
if lhs.size==1 and MultiAssign===lhs.first
lhs=lhs.first
else
lhs=MultiAssign.new(lhs)
end
node=AssignNode.new(lhs, assignnode.op, rhs)
#graft the new node back onto the old tree
if parent
if subi
parent[i][subi]=node
else
parent[i]=node
end
else #replacement at top level
result=node
end
#re-scan newly made node, since we tell caller not to scan our children
node.fixup_multiple_assignments!
false #skip (your old view of) my children, please
else
true
end
}
return result
end
def prohibit_fixup x
case x
when UnaryStarNode; true
# when ParenedNode; x.size>1
when CallSiteNode; x.params and !x.real_parens
else false
end
end
def fixup_rescue_assignments! #dead code
result=self
walk{|parent,i,subi,node|
#if a rescue op with a single assignment on the lhs
if RescueOpNode===node and assign=node.first and #ick
AssignNode===assign and assign.op.ident=="=" and
!(assign.multi? or
prohibit_fixup assign.right)
#re-hang the node with = at the top instead of rescue
node=AssignNode.new(assign.left, assign.op,
RescueOpNode.new(assign.right,nil,node[1][0].action)
)
#graft the new node back onto the old tree
if parent
if subi
parent[i][subi]=node
else
parent[i]=node
end
else #replacement at top level
result=node
end
#re-scan newly made node, since we tell caller not to scan our children
node.fixup_rescue_assignments!
false #skip (your old view of) my children, please
else
true
end
}
return result
end
def lvars_defined_in
result=[]
walk {|parent,i,subi,node|
case node
when MethodNode,ClassNode,ModuleNode,MetaClassNode; false
when CallSiteNode
Node===node.receiver and
result.concat node.receiver.lvars_defined_in
node.args.each{|arg|
result.concat arg.lvars_defined_in if Node===arg
} if node.args
false
when AssignNode
lvalue=node.left
lvalue.respond_to? :all_current_lvars and
result.concat lvalue.all_current_lvars
true
when ForNode
lvalue=node.for
lvalue.respond_to? :all_current_lvars and
result.concat lvalue.all_current_lvars
true
when RescueOpNode,BeginNode
rescues=node[1]
rescues.each{|resc|
name=resc.varname
name and result.push name.ident
}
true
else true
end
}
result.uniq!
return result
end
def unary; false end
def lvalue; nil end
#why not use Ron::GraphWalk.graph_copy instead here?
def deep_copy transform={},&override
handler=proc{|child|
if transform.has_key? child.__id__
transform[child.__id__]
else
case child
when Node
override&&override[child] or
child.deep_copy(transform,&override)
when Array
child.clone.map!(&handler)
when Integer,Symbol,Float,nil,false,true,Module
child
else
child.clone
end
end
}
newdata=map(&handler)
result=clone
instance_variables.each{|iv|
unless iv=="@data" or iv==:@data
val=instance_variable_get(iv)
result.instance_variable_set(iv,handler[val])
end
}
result.replace newdata
return result
end
def delete_extraneous_ivars!
walk{|parent,i,subi,node|
case node
when Node
node.remove_instance_variable :@offset rescue nil
node.remove_instance_variable :@loopword_offset rescue nil
node.remove_instance_variable :@iftok_offset rescue nil
node.remove_instance_variable :@endline rescue nil
node.remove_instance_variable :@lvalue rescue nil
if node.respond_to? :lvalue
node.lvalue or
node.remove_instance_variable :@lvalue rescue nil
end
when Token
print "#{node.inspect} in "; pp parent
fail "no tokens should be present in final parse tree (maybe except VarNameToken, ick)"
end
true
}
return self
end
def delete_linenums!
walk{|parent,i,subi,node|
case node
when Node
node.remove_instance_variable :@endline rescue nil
node.remove_instance_variable :@startline rescue nil
end
true
}
return self
end
public :remove_instance_variable
#convert to a Reg::Array expression. subnodes are also converted.
#if any matchers are present in the tree, they will be included
#directly into the enclosing Node's matcher.
#this can be a nice way to turn a (possibly deeply nested) node
#tree into a matcher.
#note: anything stored in instance variables is ignored in the
#matcher.
def +@
node2matcher=proc{|n|
case n
when Node; +n
when Array; +[*n.map(&node2matcher)]
else n
end
}
return +[*map(&node2matcher)] & self.class
end
private
#turn a list (array) of arrays into a linked list, in which each array
#has a reference to the next in turn as its last element.
def linked_list(arrays)
0.upto(arrays.size-2){|i| arrays[i]<<arrays[i+1] }
return arrays.first
end
def param_list_walk(param_list)
param_list or return
limit=param_list.size
i=0
normals=[]
lownormal=nil
handle_normals=proc{
yield '',normals,lownormal..i-1 if lownormal
lownormal=nil
normals.slice! 0..-1
}
while i<limit
case param=param_list[i]
when ArrowOpNode
handle_normals[]
low=i
i+=1 while ArrowOpNode===param_list[i]
high=i-1
yield '=>',param_list[low..high],low..high
when UnaryStarNode
handle_normals[]
yield '*',param,i
when UnOpNode&-{:op=>"&@"}
handle_normals[]
yield '&',param,i
else
lownormal=i unless lownormal
normals << param
end
i+=1
end
handle_normals[]
end
def param_list_parse(param_list,o)
output=[]
star=amp=nil
param_list_walk(param_list){|type,val,i|
case type
when ''
output.concat val.map{|param| param.rescue_parsetree(o)}
when '=>'
output.push HashLiteralNode.new(nil,val,nil).parsetree(o)
when '*'; star=val.parsetree(o)
when '&'; amp=val.parsetree(o)
end
}
return output,star,amp
end
def unparse_nl(token,o,alt=';',nl="\n")
#should really only emit newlines
#to bring line count up to startline, not endline.
linenum=
case token
when Integer; token
when nil; return alt
else token.startline rescue (return alt)
end
shy=(linenum||0)-o[:linenum]
#warn if shy<0 ???
return alt if shy<=0
o[:linenum]=linenum
return nl*shy
end
def default_unparse_options
{:linenum=>1}
end
end
class ValueNode<Node
def lvalue; nil end
#identity_param :lvalue, nil, true
end
class VarNode<ValueNode
param_names :ident
include FlattenedIvars
attr_accessor :endline,:offset
attr_reader :lvar_type,:in_def
attr_writer :lvalue
alias == flattened_ivars_equal?
def initialize(tok)
super(tok.ident)
@lvar_type=tok.lvar_type
@offset=tok.offset
@endline=@startline=tok.endline
@in_def=tok.in_def
end
# def ident; first end
# def ident=x; self[0]=x end
alias image ident
alias startline endline
alias name ident
alias name= ident=
def parsetree(o)
type=case ident[0]
when ?$
case ident[1]
when ?1..?9; return [:nth_ref,ident[1..-1].to_i]
when ?&,?+,?`,?'; return [:back_ref,ident[1].chr.to_sym] #`
else :gvar
end
when ?@
if ident[1]==?@
:cvar
else
:ivar
end
when ?A..?Z; :const
else
case lvar_type
when :local; :lvar
when :block; :dvar
when :current; :dvar#_curr
else fail
end
end
return [type,ident.to_sym]
end
def varname2assigntype
case ident[0]
when ?$; :gasgn
when ?@
if ident[1]!=?@; :iasgn
elsif in_def; :cvasgn
else :cvdecl
end
when ?A..?Z; :cdecl
else
case lvar_type
when :local; :lasgn
when :block; :dasgn
when :current; :dasgn_curr
else fail
end
end
end
def lvalue_parsetree(o)
[varname2assigntype, ident.to_sym]
end
alias to_lisp to_s
def lvalue
return @lvalue if defined? @lvalue
@lvalue=true
end
identity_param :lvalue, nil, true
def all_current_lvars
lvar_type==:current ? [ident] : []
end
def dup
result=super
result.ident=ident.dup if ident
return result
end
public :remove_instance_variable
def unparse o=default_unparse_options; ident end
alias lhs_unparse unparse
if false
def walk #is this needed?
yield nil,nil,nil,self
end
end
end
#forward decls
class RawOpNode<ValueNode
end
class OpNode<RawOpNode
end
class NotEqualNode<OpNode
end
class MatchNode<OpNode
end
class NotMatchNode<OpNode
end
class ArrowOpNode<RawOpNode
end
class RescueOpNode<RawOpNode
end
class LogicalNode<RawOpNode
end
class AndNode<LogicalNode
end
class OrNode<LogicalNode
end
class RangeNode<RawOpNode
end
class IfOpNode<RawOpNode
end
class UnlessOpNode<RawOpNode
end
class WhileOpNode<RawOpNode
end
class UntilOpNode<RawOpNode
end
OP2CLASS={
"!="=>NotEqualNode,
"!~"=>NotMatchNode,
"=~"=>MatchNode,
"if"=>IfOpNode,
"unless"=>UnlessOpNode,
"while"=>WhileOpNode,
"until"=>UntilOpNode,
".."=>RangeNode,
"..."=>RangeNode,
"=>"=>ArrowOpNode,
"&&"=>AndNode,
"||"=>OrNode,
"and"=>AndNode,
"or"=>OrNode,
"rescue"=>RescueOpNode,
"rescue3"=>RescueOpNode,
}
class RawOpNode<ValueNode
param_names(:left,:op,:right)
def initialize(left,op,right=nil)
op,right=nil,op if right.nil?
if op.respond_to? :ident
@offset=op.offset
op=op.ident
end
super(left,op,right)
end
# def initialize_copy other
# rebuild(other.left,other.op,other.right)
# end
def self.create(left,op,right)
op_s=op.ident
k=OP2CLASS[op_s]||OpNode
k.new(left,op,right)
end
def image; "(#{op})" end
def raw_unparse o
l=left.unparse(o)
l[/(~| \Z)/] and maybesp=" "
[l,op,maybesp,right.unparse(o)].to_s
end
end
class OpNode<RawOpNode
def initialize(left,op,right)
#@negative_of="="+$1 if /^!([=~])$/===op
op=op.ident if op.respond_to? :ident
super left,op,right
end
def to_lisp
"(#{op} #{left.to_lisp} #{right.to_lisp})"
end
def parsetree(o)
[:call,
left.rescue_parsetree(o),
op.to_sym,
[:array, right.rescue_parsetree(o)]
]
end
alias opnode_parsetree parsetree
def unparse o=default_unparse_options
result=l=left.unparse(o)
result+=" " if /\A(?:!|#{LCLETTER})/o===op
result+=op
result+=" " if /#{LETTER_DIGIT}\Z/o===op or / \Z/===l
result+=right.unparse(o)
end
# def unparse o=default_unparse_options; raw_unparse o end
end
class MatchNode<OpNode
param_names :left,:op_,:right
def initialize(left,op,right=nil)
op,right=nil,op unless right
replace [left,right]
end
def parsetree(o)
if StringNode===left and left.char=='/'
[:match2, left.parsetree(o), right.parsetree(o)]
elsif StringNode===right and right.char=='/'
[:match3, right.parsetree(o), left.parsetree(o)]
else
super
end
end
def op; "=~"; end
end
class NotEqualNode<OpNode
param_names :left,:op_,:right
def initialize(left,op,right=nil)
op,right=nil,op unless right
replace [left,right]
end
def parsetree(o)
result=opnode_parsetree(o)
result[2]="=#{op[1..1]}".to_sym
result=[:not, result]
return result
end
def op; "!="; end
end
class NotMatchNode<OpNode
param_names :left,:op_,:right
def initialize(left,op,right=nil)
op,right=nil,op unless right
replace [left,right]
end
def parsetree(o)
if StringNode===left and left.char=="/"
[:not, [:match2, left.parsetree(o), right.parsetree(o)]]
elsif StringNode===right and right.char=="/"
[:not, [:match3, right.parsetree(o), left.parsetree(o)]]
else
result=opnode_parsetree(o)
result[2]="=#{op[1..1]}".to_sym
result=[:not, result]
end
end
def op; "!~"; end
end
class ListOpNode<ValueNode #abstract
def initialize(val1,op,val2)
list=if self.class===val1
Array.new(val1)
else
[val1]
end
if self.class===val2
list.push( *val2 )
elsif val2
list.push val2
end
super( *list )
end
end
class CommaOpNode<ListOpNode #not to appear in final tree
def image; '(,)' end
def to_lisp
"(#{map{|x| x.to_lisp}.join(" ")})"
end
def lvalue
return @lvalue if defined? @lvalue
@lvalue=true
end
attr_writer :lvalue
identity_param :lvalue, nil, true
def extract_unbraced_hash
param_list=Array.new(self)
first=last=nil
param_list.each_with_index{|param,i|
break first=i if ArrowOpNode===param
}
(1..param_list.size).each{|i| param=param_list[-i]
break last=-i if ArrowOpNode===param
}
if first
arrowrange=first..last
arrows=param_list[arrowrange]
h=HashLiteralNode.new(nil,arrows,nil)
h.offset=arrows.first.offset
h.startline=arrows.first.startline
h.endline=arrows.last.endline
return h,arrowrange
end
end
end
class LiteralNode<ValueNode; end
class StringNode<ValueNode; end
class StringCatNode < ValueNode; end
class NopNode<ValueNode; end
class VarLikeNode<ValueNode; end #nil,false,true,__FILE__,__LINE__,self
class SequenceNode<ListOpNode
def initialize(*args)
super
@offset=self.first.offset
end
def +(other)
if SequenceNode===other
dup.push( *other )
else
dup.push other
end
end
def []=(*args)
val=args.pop
if SequenceNode===val
val=Array.new(val)
#munge args too
if args.size==1 and Integer===args.first
args<<1
end
end
super( *args<<val )
end
def image; '(;)' end
def to_lisp
"#{map{|x| x.to_lisp}.join("\n")}"
end
def to_lisp_with_parens
"(#{to_lisp})"
end
LITFIX=LiteralNode&-{:val=>Fixnum}
LITRANGE=RangeNode&-{:left=>LITFIX,:right=>LITFIX}
LITSTR=StringNode&-{:size=>1,:char=>/^[^`\[{]$/}
#LITCAT=proc{|item| item.grep(~LITSTR).empty?}
#class<<LITCAT; alias === call; end
LITCAT=StringCatNode& item_that.grep(~LITSTR).empty? #+[LITSTR.+]
LITNODE=LiteralNode|NopNode|LITSTR|LITCAT|LITRANGE|(VarLikeNode&-{:name=>/^__/})
#VarNode| #why not this too?
def parsetree(o)
data=compact
data.empty? and return
items=Array.new(data[0...-1])
if o[:quirks]
items.shift while LITNODE===items.first
else
items.reject!{|expr| LITNODE===expr }
end
items.map!{|expr| expr.rescue_parsetree(o)}.push last.parsetree(o)
# items=map{|expr| expr.parsetree(o)}
items.reject!{|expr| []==expr }
if o[:quirks]
unless BeginNode===data[0]
header=items.first
(items[0,1] = *header[1..-1]) if header and header.first==:block
end
else
(items.size-1).downto(0){|i|
header=items[i]
(items[i,1] = *header[1..-1]) if header and header.first==:block
}
end
if items.size>1
items.unshift :block
elsif items.size==1
items.first
else
items
end
end
def unparse o=default_unparse_options
return "" if empty?
unparse_nl(first,o,'')+first.unparse(o)+
self[1..-1].map{|expr|
unparse_nl(expr,o)+expr.unparse(o)
}.join
end
end
class StringCatNode < ValueNode
def initialize(*strses)
strs=strses.pop.unshift( *strses )
hd=strs.shift if HereDocNode===strs.first
strs.map!{|str| StringNode.new(str)}
strs.unshift hd if hd
super( *strs )
end
def parsetree(o)
result=map{|str| str.parsetree(o)}
sum=''
type=:str
tree=i=nil
result.each_with_index{|tree2,i2| tree,i=tree2,i2
sum+=tree[1]
tree.first==:str or break(type=:dstr)
}
[type,sum,*tree[2..-1]+result[i+1..-1].inject([]){|cat,x|
if x.first==:dstr
x.shift
x0=x[0]
if x0=='' and x.size==2
x.shift
else
x[0]=[:str,x0]
end
cat+x
elsif x.last.empty?
cat
else
cat+[x]
end
}
]
end
def unparse o=default_unparse_options
map{|ss| ss.unparse(o)}.join ' '
end
end
class ArrowOpNode
param_names(:left,:op,:right)
def initialize(*args)
super
end
#def unparse(o=default_unparse_options)
# left.unparse(o)+" => "+right.unparse(o)
#end
end
class RangeNode
param_names(:first,:op,:last)
def initialize(left,op,right=nil)
op,right="..",op unless right
op=op.ident if op.respond_to? :ident
@exclude_end=!!op[2]
@as_flow_control=false
super(left,op,right)
end
def begin; first end
def end; last end
def left; first end
def right; last end
def exclude_end?; @exclude_end end
# def self.[] *list
# result=RawOpNode[*list]
# result.extend RangeNode
# return result
# end
def self.[] *list
new(*list)
end
def parsetree(o)
first=first().parsetree(o)
last=last().parsetree(o)
if @as_flow_control
if :lit==first.first and Integer===first.last
first=[:call, [:lit, first.last], :==, [:array, [:gvar, :$.]]]
elsif :lit==first.first && Regexp===first.last or
:dregx==first.first || :dregx_once==first.first
first=[:match, first]
end
if :lit==last.first and Integer===last.last
last=[:call, [:lit, last.last], :==, [:array, [:gvar, :$.]]]
elsif :lit==last.first && Regexp===last.last or
:dregx==last.first || :dregx_once==last.first
last=[:match, last]
end
tag="flip"
else
if :lit==first.first and :lit==last.first and
Fixnum===first.last and Fixnum===last.last and
LiteralNode===first() and LiteralNode===last()
return [:lit, Range.new(first.last,last.last,@exclude_end)]
end
tag="dot"
end
count= @exclude_end ? ?3 : ?2
tag << count
[tag.to_sym, first, last]
end
def special_conditions!
@as_flow_control=true
end
def unparse(o=default_unparse_options)
result=left.unparse(o)+'..'
result+='.' if exclude_end?
result << right.unparse(o)
return result
end
end
class UnOpNode<ValueNode
param_names(:op,:val)
def self.create(op,val)
return UnaryStarNode.new(op,val) if /\*$/===op.ident
return UnaryAmpNode.new(op,val) if /&$/===op.ident
return new(op,val)
end
def initialize(op,val)
@offset||=op.offset rescue val.offset
op=op.ident if op.respond_to? :ident
/([&*])$/===op and op=$1+"@"
/^(?:!|not)$/===op and
val.respond_to? :special_conditions! and
val.special_conditions!
super(op,val)
end
def arg; val end
def arg= x; self.val=x end
alias ident op
def image; "(#{op})" end
def lvalue
# return nil unless op=="*@"
return @lvalue if defined? @lvalue
@lvalue=true
end
attr_writer :lvalue
def to_lisp
"(#{op} #{val.to_lisp})"
end
def parsetree(o)
node=self
node=node.val while UnOpNode===node and node.op=="+@"
return node.parsetree(o) if LiteralNode&-{:val=>Integer|Float|Symbol}===node
return node.parsetree(o) if StringNode&-{:char=>'/', :size=>1}===node
case op
when /^&/; [:block_arg, val.ident.to_sym]
when "!","not"; [:not, val.rescue_parsetree(o)]
when "defined?"; [:defined, val.parsetree(o)]
else
[:call, val.rescue_parsetree(o), op.to_sym]
end
end
def lvalue_parsetree(o)
parsetree(o)
end
def unparse o=default_unparse_options
op=op()
op=op.chomp "@"
result=op
result+=" " if /#{LETTER}$/o===op or /^[+-]/===op && LiteralNode===val
result+=val.unparse(o)
end
end
class UnaryAmpNode<UnOpNode
end
class UnaryStarNode<UnOpNode
def initialize(op,val=nil)
op,val="*@",op unless val
op.ident="*@" if op.respond_to? :ident
super(op,val)
end
class<<self
alias [] new
end
def parsetree(o)
[:splat, val.rescue_parsetree(o)]
end
def all_current_lvars
val.respond_to?(:all_current_lvars) ?
val.all_current_lvars : []
end
attr_accessor :after_comma
def lvalue_parsetree o
val.lvalue_parsetree(o)
end
identity_param :lvalue, nil, true
def unparse o=default_unparse_options
"*"+val.unparse(o)
end
end
class DanglingStarNode<UnaryStarNode
#param_names :op,:val
def initialize(star,var=nil)
@offset= star.offset if star.respond_to? :offset
@startline=@endline=star.startline if star.respond_to? :startline
super('*@',var||VarNode[''])
end
attr :offset
def lvars_defined_in; [] end
def parsetree(o); [:splat] end
alias lvalue_parsetree parsetree
def unparse(o=nil); "* "; end
end
class DanglingCommaNode<DanglingStarNode
def initialize
end
attr_accessor :offset
def lvalue_parsetree o
:dangle_comma
end
alias parsetree lvalue_parsetree
def unparse o=default_unparse_options; ""; end
end
class ConstantNode<ListOpNode
def initialize(*args)
@offset=args.first.offset
args.unshift nil if args.size==2
args.map!{|node|
if VarNode===node and (?A..?Z)===node.ident[0]
then node.ident
else node
end
}
super(*args)
end
def unparse(o=default_unparse_options)
if Node===first
result=dup
result[0]= first.unparse(o)#.gsub(/\s+\Z/,'')
result.join('::')
else join('::')
end
end
alias image unparse
def lvalue_parsetree(o)
[:cdecl,parsetree(o)]
end
def parsetree(o)
if !first
result=[:colon3, self[1].to_sym]
i=2
else
result=first.respond_to?(:parsetree) ?
first.parsetree(o) :
[:const,first.to_sym]
i=1
end
(i...size).inject(result){|r,j|
[:colon2, r, self[j].to_sym]
}
end
def lvalue
return @lvalue if defined? @lvalue
@lvalue=true
end
attr_writer :lvalue
identity_param :lvalue, nil, true
def inspect label=nil,indent=0,verbose=false
result=' '*indent
result+="#{label}: " if label
result+='Constant '
unless String===first or nil==first
head=first
rest=self[1..-1]
end
result+=(rest||self).map{|name| name.inspect}.join(', ')+"\n"
result+=head.inspect("head",indent+2,verbose) if head
return result
end
end
LookupNode=ConstantNode
class DoubleColonNode<ValueNode #obsolete
#dunno about this name... maybe ConstantNode?
param_names :namespace, :constant
alias left namespace
alias right constant
def initialize(val1,op,val2=nil)
val1,op,val2=nil,val1,op unless val2
val1=val1.ident if VarNode===val1 and /\A#{UCLETTER}/o===val1.ident
val2=val2.ident if VarNode===val1 and /\A#{UCLETTER}/o===val2.ident
replace [val1,val2]
end
def image; '(::)' end
def parsetree(o)
if namespace
ns= (String===namespace) ? [:const,namespace.to_sym] : namespace.parsetree(o)
[:colon2, ns, constant.to_sym]
else
[:colon3, constant.to_sym]
end
end
def lvalue_parsetree(o)
[:cdecl,parsetree(o)]
end
def lvalue
return @lvalue if defined? @lvalue
@lvalue=true
end
attr_writer :lvalue
end
class DotCallNode<ValueNode #obsolete
param_names :receiver,:dot_,:callsite
def image; '(.)' end
def to_lisp
"(#{receiver.to_lisp} #{@data.last.to_lisp[1...-1]})"
end
def parsetree(o)
cs=self[1]
cs &&= cs.parsetree(o)
cs.shift if cs.first==:vcall or cs.first==:fcall
[:call, @data.first.parsetree(o), *cs]
end
def lvalue
return @lvalue if defined? @lvalue
@lvalue=true
end
attr_writer :lvalue
end
class ParenedNode<ValueNode
param_names :body
alias val body
alias val= body=
def initialize(lparen,body,rparen)
@offset=lparen.offset
self[0]=body
end
attr_accessor :after_comma, :after_equals
def image; "(#{body.image})" end
def special_conditions!
node=body
node.special_conditions! if node.respond_to? :special_conditions!
end
def to_lisp
huh #what about rescues, else, ensure?
body.to_lisp
end
def op?; false end
def parsetree(o)
body.parsetree(o)
end
def rescue_parsetree o
body.rescue_parsetree o
# result.first==:begin and result=result.last unless o[:ruby187]
# result
end
alias begin_parsetree parsetree
def lvalue
return @lvalue if defined? @lvalue
@lvalue=true
end
attr_writer :lvalue
identity_param :lvalue, nil, true
def unparse(o=default_unparse_options)
"(#{body&&body.unparse(o)})"
end
end
module HasRescue
def parsetree_and_rescues(o)
body=body()
target=result=[] #was: [:begin, ]
#body,rescues,else_,ensure_=*self
target.push target=[:ensure, ] if ensure_ or @empty_ensure
rescues=rescues().map{|resc| resc.parsetree(o)}
if rescues.empty?
if else_
body= body ? SequenceNode.new(body,nil,else_) : else_
end
else_=nil
else
target.push newtarget=[:rescue, ]
else_=else_()
end
if body
# needbegin= (BeginNode===body and body.after_equals)
body=body.parsetree(o)
# body=[:begin, body] if needbegin and body.first!=:begin and !o[:ruby187]
(newtarget||target).push body if body
end
target.push ensure_.parsetree(o) if ensure_
target.push [:nil] if @empty_ensure
target=newtarget if newtarget
unless rescues.empty?
target.push linked_list(rescues)
end
target.push else_.parsetree(o) if else_ #and !body
result.size==0 and result=[[:nil]]
if o[:ruby187] and !rescues.empty?
result.unshift :begin
else
result=result.last
end
result
end
def unparse_and_rescues(o)
result=" "
result+= body.unparse(o) if body
result+=unparse_nl(rescues.first,o) if rescues
rescues.each{|resc| result+=resc.unparse(o) } if rescues
result+=unparse_nl(else_,o)+"else "+else_.unparse(o) if else_
result+=";else" if @empty_else
result+=unparse_nl(ensure_,o)+"ensure "+ensure_.unparse(o) if ensure_
result+=";ensure" if @empty_ensure
return result
end
end
class BeginNode<ValueNode
include HasRescue
param_names :body, :rescues, :else!, :ensure!
def initialize(*args)
@offset=args.first.offset
@empty_ensure=@empty_else=@op_rescue=nil
body,rescues,else_,ensure_=*args[1...-1]
rescues.extend ListInNode
if else_
else_=else_.val or @empty_else=true
end
if ensure_
ensure_=ensure_.val or @empty_ensure=true
end
replace [body,rescues,else_,ensure_]
end
def op?; false end
alias ensure_ ensure
alias else_ else
attr_reader :empty_ensure, :empty_else
attr_accessor :after_comma, :after_equals
identity_param :after_equals, nil, true
def image; '(begin)' end
def special_conditions!; nil end
def non_empty
rescues.size > 0 or !!ensures or body
end
identity_param :non_empty, false, true
def to_lisp
huh #what about rescues, else, ensure?
body.to_lisp
end
def parsetree(o)
result=parsetree_and_rescues(o)
if o[:ruby187] and result.first==:begin
result=result[1]
else
result=[:begin,result] unless result==[:nil]#||result.first==:begin
end
return result
end
def rescue_parsetree o
result=parsetree o
result.first==:begin and result=result.last unless o[:ruby187]
result
end
def begin_parsetree(o)
body,rescues,else_,ensure_=*self
needbegin=(rescues&&!rescues.empty?) || ensure_ || @empty_ensure
result=parsetree(o)
needbegin and result=[:begin, result] unless result.first==:begin
result
end
def lvalue
return nil
end
# attr_accessor :lvalue
def unparse(o=default_unparse_options)
result="begin "
result+=unparse_and_rescues(o)
result+=";end"
end
end
module KeywordOpNode
def unparse o=default_unparse_options
[left.unparse(o),' ',op,' ',right.unparse(o)].join
end
end
class RescueOpNode<RawOpNode
include KeywordOpNode
param_names :body, :rescues #, :else!, :ensure!
def initialize(expr,rescueword,backup)
replace [expr,[RescueNode[[],nil,backup]].extend(ListInNode)]
end
def else; nil end
def ensure; nil end
def left; body end
def right; rescues[0].action end
alias ensure_ ensure
alias else_ else
alias empty_ensure ensure
alias empty_else else
attr_accessor :after_equals
def op?; true end
def special_conditions!
nil
end
def to_lisp
huh #what about rescues
body.to_lisp
end
def parsetree(o)
body=body()
target=result=[] #was: [:begin, ]
#body,rescues,else_,ensure_=*self
rescues=rescues().map{|resc| resc.parsetree(o)}
target.push newtarget=[:rescue, ]
else_=nil
needbegin= (BeginNode===body and body.after_equals)
huh if needbegin and RescueOpNode===body #need test case for this
huh if needbegin and ParenedNode===body #need test case for this
body=body.parsetree(o)
body=[:begin, body] if needbegin and body.first!=:begin and !o[:ruby187]
newtarget.push body if body
newtarget.push linked_list(rescues)
result=result.last if result.size==1
# result=[:begin,result]
result
end
def old_rescue_parsetree o
result=parsetree o
result=result.last unless o[:ruby187]
result
end
alias begin_parsetree parsetree
alias rescue_parsetree parsetree
def lvalue
return nil
end
def unparse(o=default_unparse_options)
result= body.unparse(o)
result+=" rescue "
result+=rescues.first.action.unparse(o)
end
end
class AssignmentRhsNode < Node #not to appear in final parse tree
param_names :open_, :val, :close_
def initialize(*args)
if args.size==1; super args.first
else super args[1]
end
end
#WITHCOMMAS=UnaryStarNode|CommaOpNode|(CallSiteNode&-{:with_commas=>true})
def is_list
return !(WITHCOMMAS===val)
=begin
#this should be equivalent, why doesn't it work?
!(UnaryStarNode===val or
CommaOpNode===val or
CallSiteNode===val && val.with_commas==true)
# CallSiteNode===val && !val.real_parens && val.args.size>0
=end
end
identity_param :is_list, true, false
end
class AssignNode<ValueNode
param_names :left,:op,:right
alias lhs left
alias rhs right
def self.create(*args)
if args.size==5
if args[3].ident=="rescue3"
lhs,op,rescuee,op2,rescuer=*args
if MULTIASSIGN===lhs or !rescuee.is_list
return RescueOpNode.new(AssignNode.new(lhs,op,rescuee),nil,rescuer)
else
rhs=RescueOpNode.new(rescuee.val,op2,rescuer)
end
else
lhs,op,bogus1,rhs,bogus2=*args
end
super(lhs,op,rhs)
else super
end
end
def initialize(*args)
if args.size==5
#this branch should be dead now
if args[3].ident=="rescue3"
lhs,op,rescuee,op2,rescuer=*args
if MULTIASSIGN===lhs or rescuee.is_list?
huh
else
rhs=RescueOpNode.new(rescuee.val,op2,rescuer)
end
else
lhs,op,bogus1,rhs,bogus2=*args
end
else
lhs,op,rhs=*args
rhs=rhs.val if AssignmentRhsNode===rhs
end
case lhs
when UnaryStarNode #look for star on lhs
lhs=MultiAssign.new([lhs]) unless lhs.after_comma
when ParenedNode
if !lhs.after_comma #look for () around lhs
if CommaOpNode===lhs.first
lhs=MultiAssign.new(Array.new(lhs.first))
@lhs_parens=true
elsif UnaryStarNode===lhs.first
lhs=MultiAssign.new([lhs.first])
@lhs_parens=true
elsif ParenedNode===lhs.first
@lhs_parens=true
lhs=lhs.first
else
lhs=lhs.first
end
end
when CommaOpNode
lhs=MultiAssign.new lhs
#rhs=Array.new(rhs) if CommaOpNode===rhs
end
if CommaOpNode===rhs
rhs=Array.new(rhs)
lhs=MultiAssign.new([lhs]) unless MultiAssign===lhs
end
op=op.ident
if Array==rhs.class
rhs.extend ListInNode
end
@offset=lhs.offset
return super(lhs,op,rhs)
#punting, i hope the next layer can handle += and the like
=begin
#in theory, we should do something more sophisticated, like this:
#(but the presence of side effects in lhs will screw it up)
if op=='='
super
else
super(lhs,OpNode.new(lhs,OperatorToken.new(op.chomp('=')),rhs))
end
=end
end
def multi?
MultiAssign===left
end
def image; '(=)' end
def to_lisp
case left
when ParenedNode; huh
when BeginNode; huh
when RescueOpNode; huh
when ConstantNode; huh
when BracketsGetNode; huh
when VarNode
"(set #{left.to_lisp} (#{op.chomp('=')} #{left.to_lisp} #{right.to_lisp}))"
when CallSiteNode
if op=='='
"(#{left.receiver.to_lisp} #{left.name}= #{right.to_lisp})"
else
op_=op.chomp('=')
varname=nil
"(let #{varname=huh} #{left.receiver.to_lisp} "+
"(#{varname} #{left.name}= "+
"(#{op_} (#{varname} #{op}) #{right.to_lisp})))"
end
else huh
end
end
def all_current_lvars
left.respond_to?(:all_current_lvars) ?
left.all_current_lvars : []
end
def parsetree(o)
case left
when ParenedNode; huh
when RescueOpNode; huh
when BeginNode; huh
when ConstantNode;
left.lvalue_parsetree(o) << right.parsetree(o)
when MultiAssign;
lhs=left.lvalue_parsetree(o)
rhs= right.class==Array ? right.dup : [right]
star=rhs.pop if UnaryStarNode===rhs.last
rhs=rhs.map{|x| x.rescue_parsetree(o)}
if rhs.size==0
star or fail
rhs= star.parsetree(o)
elsif rhs.size==1 and !star and !(UnaryStarNode===left.first)
rhs.unshift :to_ary
else
rhs.unshift(:array)
if star
splat=star.val.rescue_parsetree(o)
#if splat.first==:call #I don't see how this can be right....
# splat[0]=:attrasgn
# splat[2]="#{splat[2]}=".to_sym
#end
rhs=[:argscat, rhs, splat]
end
if left.size==1 and !(UnaryStarNode===left.first) and !(NestedAssign===left.first)
rhs=[:svalue, rhs]
if CallNode===left.first
rhs=[:array, rhs]
end
end
end
if left.size==1 and BracketsGetNode===left.first and right.class==Array #hack
lhs.last<<rhs
lhs
else
lhs<< rhs
end
when CallSiteNode
op=op().chomp('=')
rcvr=left.receiver.parsetree(o)
prop=left.name.+('=').to_sym
args=right.rescue_parsetree(o)
UnaryStarNode===right and args=[:svalue, args]
if op.empty?
[:attrasgn, rcvr, prop, [:array, args] ]
else
[:op_asgn2, rcvr,prop, op.to_sym, args]
end
when BracketsGetNode
args=left.params
if op()=='='
result=left.lvalue_parsetree(o) #[:attrasgn, left[0].parsetree(o), :[]=]
result.size==3 and result.push [:array]
rhs=right.rescue_parsetree(o)
UnaryStarNode===right and rhs=[:svalue, rhs]
if args
result[-1]=[:argspush,result[-1]] if UnaryStarNode===args.last
#else result[-1]=[:zarray]
end
result.last << rhs
result
else
=begin
args&&=args.map{|x| x.parsetree(o)}.unshift(:array)
splat=args.pop if :splat==args.last.first
if splat and left.params.size==1
args=splat
elsif splat
args=[:argscat, args, splat.last]
end
=end
lhs=left.parsetree(o)
if lhs.first==:fcall
rcvr=[:self]
args=lhs[2]
else
rcvr=lhs[1]
args=lhs[3]
end
args||=[:zarray]
result=[
:op_asgn1, rcvr, args,
op().chomp('=').to_sym,
right.rescue_parsetree(o)
]
end
when VarNode
node_type=left.varname2assigntype
if /^(&&|\|\|)=$/===op()
return ["op_asgn_#{$1[0]==?& ? "and" : "or"}".to_sym,
left.parsetree(o),
[node_type, left.ident.to_sym,
right.rescue_parsetree(o)]
]
end
if op()=='='
rhs=right.rescue_parsetree(o)
UnaryStarNode===right and rhs=[:svalue, rhs]
# case left
# when VarNode;
[node_type, left.ident.to_sym, rhs]
# else [node_type, left.data[0].parsetree(o), left.data[1].data[0].ident.+('=').to_sym ,[:array, rhs]]
# end
=begin these branches shouldn't be necessary now
elsif node_type==:op_asgn2
[node_type, @data[0].data[0].parsetree(o),
@data[0].data[1].data[0].ident.+('=').to_sym,
op().ident.chomp('=').to_sym,
@data[2].parsetree(o)
]
elsif node_type==:attrasgn
[node_type]
=end
else
[node_type, left.ident.to_sym,
[:call,
left.parsetree(o),
op().chomp('=').to_sym,
[:array, right.rescue_parsetree(o)]
]
]
end
else
huh
end
end
def unparse(o=default_unparse_options)
result=lhs.lhs_unparse(o)
result="(#{result})" if defined? @lhs_parens
result+op+
(rhs.class==Array ?
rhs.map{|rv| rv.unparse o}.join(',') :
rhs.unparse(o)
)
end
end
class MultiAssignNode < ValueNode #obsolete
param_names :left,:right
#not called from parse table
def parsetree(o)
lhs=left.dup
if UnaryStarNode===lhs.last
lstar=lhs.pop
end
lhs.map!{|x|
res=x.parsetree(o)
res[0]=x.varname2assigntype if VarNode===x
res
}
lhs.unshift(:array) if lhs.size>1 or lstar
rhs=right.map{|x| x.parsetree(o)}
if rhs.size==1
if rhs.first.first==:splat
rhs=rhs.first
else
rhs.unshift :to_ary
end
else
rhs.unshift(:array)
if rhs[-1][0]==:splat
splat=rhs.pop[1]
if splat.first==:call
splat[0]=:attrasgn
splat[2]="#{splat[2]}=".to_sym
end
rhs=[:argscat, rhs, splat]
end
end
result=[:masgn, lhs, rhs]
result.insert(2,lstar.data.last.parsetree(o)) if lstar
result
end
end
class AssigneeList< ValueNode #abstract
def initialize(data)
data.each_with_index{|datum,i|
if ParenedNode===datum
first=datum.first
list=case first
when CommaOpNode; Array.new(first)
when UnaryStarNode,ParenedNode; [first]
end
data[i]=NestedAssign.new(list) if list
end
}
replace data
@offset=self.first.offset
@startline=self.first.startline
@endline=self.last.endline
end
def unparse o=default_unparse_options
map{|lval| lval.lhs_unparse o}.join(', ')
end
def old_parsetree o
lhs=data.dup
if UnaryStarNode===lhs.last
lstar=lhs.pop.val
end
lhs.map!{|x|
res=x.parsetree(o)
res[0]=x.varname2assigntype if VarNode===x
res
}
lhs.unshift(:array) if lhs.size>1 or lstar
result=[lhs]
if lstar.respond_to? :varname2assigntype
result << lstar.varname2assigntype
elsif lstar #[]=, attrib=, or A::B=
huh
else #do nothing
end
result
end
def parsetree(o)
data=self
data.empty? and return nil
# data=data.first if data.size==1 and ParenedNode===data.first and data.first.size==1
data=Array.new(data)
star=data.pop if UnaryStarNode===data.last
result=data.map{|x| x.lvalue_parsetree(o) }
=begin
{
if VarNode===x
ident=x.ident
ty=x.varname2assigntype
# ty==:lasgn and ty=:dasgn_curr
[ty, ident.to_sym]
else
x=x.parsetree(o)
if x[0]==:call
x[0]=:attrasgn
x[2]="#{x[2]}=".to_sym
end
x
end
}
=end
if result.size==0 #just star on lhs
star or fail
result=[:masgn]
result.push nil #why??? #if o[:ruby187]
result.push star.lvalue_parsetree(o)
elsif result.size==1 and !star and !(NestedAssign===data.first) #simple lhs, not multi
result=result.first
else
result=[:masgn, [:array, *result]]
result.push nil if (!star or DanglingCommaNode===star) #and o[:ruby187]
result.push star.lvalue_parsetree(o) if star and not DanglingCommaNode===star
end
result
end
def all_current_lvars
result=[]
each{|lvar|
lvar.respond_to?(:all_current_lvars) and
result.concat lvar.all_current_lvars
}
return result
end
def lvalue_parsetree(o); parsetree(o) end
end
class NestedAssign<AssigneeList
def parsetree(o)
result=super
result<<nil #why???!! #if o[:ruby187]
result
end
# def parsetree(o)
# [:masgn, *super]
# end
def unparse o=default_unparse_options
"("+super+")"
end
end
class MultiAssign<AssigneeList; end
class BlockParams<AssigneeList;
def initialize(data)
item=data.first if data.size==1
#elide 1 layer of parens if present
if ParenedNode===item
item=item.first
data=CommaOpNode===item ? Array.new(item) : [item]
@had_parens=true
end
super(data) unless data.empty?
end
def unparse o=default_unparse_options
if defined? @had_parens
"|("+super+")|"
else
"|"+super+"|"
end
end
def parsetree o
result=super
result.push nil if UnaryStarNode===self.last || size>1 #and o[:ruby187]
result
end
end
class AccessorAssignNode < ValueNode #obsolete
param_names :left,:dot_,:property,:op,:right
def to_lisp
if op.ident=='='
"(#{left.to_lisp} #{property.ident}= #{right.to_lisp})"
else
op=op().ident.chomp('=')
varname=nil
"(let #{varname=huh} #{left.to_lisp} "+
"(#{varname} #{property.ident}= "+
"(#{op} (#{varname} #{property.ident}) #{right.to_lisp})))"
end
end
def parsetree(o)
op=op().ident.chomp('=')
rcvr=left.parsetree(o)
prop=property.ident.<<(?=).to_sym
rhs=right.parsetree(o)
if op.empty?
[:attrasgn, rcvr, prop, [:array, args] ]
else
[:op_asgn2, rcvr,prop, op.to_sym, args]
end
end
end
class LogicalNode
include KeywordOpNode
def self.[](*list)
options=list.pop if Hash===list.last
result=allocate.replace list
opmap=options[:@opmap] if options and options[:@opmap]
opmap||=result.op[0,1]*(list.size-1)
result.instance_variable_set(:@opmap, opmap)
return result
end
def initialize(left,op,right)
op=op.ident if op.respond_to? :ident
@opmap=op[0,1]
case op
when "&&"; op="and"
when "||"; op="or"
end
#@reverse= op=="or"
#@op=op
replace [left,right]
(size-1).downto(0){|i|
expr=self[i]
if self.class==expr.class
self[i,1]=Array.new expr
opmap[i,0]=expr.opmap
end
}
end
attr_reader :opmap
OP_EXPAND={?o=>"or", ?a=>"and", ?&=>"&&", ?|=>"||", nil=>""}
OP_EQUIV={?o=>"or", ?a=>"and", ?&=>"and", ?|=>"or"}
def unparse o=default_unparse_options
result=''
each_with_index{|expr,i|
result.concat expr.unparse(o)
result.concat ?\s
result.concat OP_EXPAND[@opmap[i]]
result.concat ?\s
}
return result
end
def left
self[0]
end
def left= val
self[0]=val
end
def right
self[1]
end
def right= val
self[1]=val
end
def parsetree(o)
result=[].replace(self).reverse
last=result.shift.begin_parsetree(o)
first=result.pop
result=result.inject(last){|sum,x|
[op.to_sym, x.begin_parsetree(o), sum]
}
[op.to_sym, first.rescue_parsetree(o), result]
end
def special_conditions!
each{|x|
if x.respond_to? :special_conditions! and !(ParenedNode===x)
x.special_conditions!
end
}
end
end
class AndNode<LogicalNode
def reverse
false
end
def op
"and"
end
end
class OrNode<LogicalNode
def reverse
true
end
def op
"or"
end
end
class WhileOpNode
include KeywordOpNode
param_names :left, :op_, :right
def condition; right end
def consequent; left end
def initialize(val1,op,val2=nil)
op,val2=nil,op unless val2
op=op.ident if op.respond_to? :ident
@reverse=false
@loop=true
@test_first= !( BeginNode===val1 )
replace [val1,val2]
condition.special_conditions! if condition.respond_to? :special_conditions!
end
def while; condition end
def do; consequent end
alias body do
def op; "while" end
def reversed; false end
attr :test_first
def parsetree(o)
cond=condition.rescue_parsetree(o)
body=consequent.parsetree(o)
!@test_first and
body.size == 2 and
body.first == :begin and
body=body.last
if cond.first==:not
kw=:until
cond=cond.last
else
kw=:while
end
[kw, cond, body, (@test_first or body==[:nil])]
end
end
class UntilOpNode
include KeywordOpNode
param_names :left,:op_,:right
def condition; right end
def consequent; left end
def initialize(val1,op,val2=nil)
op,val2=nil,op unless val2
op=op.ident if op.respond_to? :ident
@reverse=true
@loop=true
@test_first= !( BeginNode===val1 )
replace [val1,val2]
condition.special_conditions! if condition.respond_to? :special_conditions!
end
def while; negate condition end
def do; consequent end
alias body do
def op; "until" end
def reversed; true end
def parsetree(o)
cond=condition.rescue_parsetree(o)
body=consequent.parsetree(o)
!@test_first and
body.size == 2 and
body.first == :begin and
body=body.last
if cond.first==:not
kw=:while
cond=cond.last
else
kw=:until
end
tf=@test_first||body==[:nil]
# tf||= (!consequent.body and !consequent.else and #!consequent.empty_else and
# !consequent.ensure and !consequent.empty_ensure and consequent.rescues.empty?
# ) if BeginNode===consequent
[kw, cond, body, tf]
end
end
class UnlessOpNode
include KeywordOpNode
param_names :left, :op_, :right
def condition; right end
def consequent; left end
def initialize(val1,op,val2=nil)
op,val2=nil,op unless val2
op=op.ident if op.respond_to? :ident
@reverse=true
@loop=false
replace [val1,val2]
condition.special_conditions! if condition.respond_to? :special_conditions!
end
def if; condition end
def then; nil end
def else; consequent end
def elsifs; [] end
def op; "unless" end
def parsetree(o)
cond=condition.rescue_parsetree(o)
actions=[nil, consequent.parsetree(o)]
if cond.first==:not
actions.reverse!
cond=cond.last
end
[:if, cond, *actions]
end
end
class IfOpNode
param_names :left,:op_,:right
include KeywordOpNode
def condition; right end
def consequent; left end
def initialize(left,op,right=nil)
op,right=nil,op unless right
op=op.ident if op.respond_to? :ident
@reverse=false
@loop=false
replace [left,right]
condition.special_conditions! if condition.respond_to? :special_conditions!
end
def if; condition end
def then; consequent end
def else; nil end
def elsifs; [] end
def op; "if" end
def parsetree(o)
cond=condition.rescue_parsetree(o)
actions=[consequent.parsetree(o), nil]
if cond.first==:not
actions.reverse!
cond=cond.last
end
[:if, cond, *actions]
end
end
class CallSiteNode<ValueNode
param_names :receiver, :name, :params, :blockparams, :block
alias blockargs blockparams
alias block_args blockargs
alias block_params blockparams
def initialize(method,open_paren,param_list,close_paren,block)
@not_real_parens=!open_paren || open_paren.not_real?
case param_list
when CommaOpNode
#handle inlined hash pairs in param list (if any)
# compr=Object.new
# def compr.==(other) ArrowOpNode===other end
h,arrowrange=param_list.extract_unbraced_hash
param_list=Array.new(param_list)
param_list[arrowrange]=[h] if arrowrange
when ArrowOpNode
h=HashLiteralNode.new(nil,param_list,nil)
h.startline=param_list.startline
h.endline=param_list.endline
param_list=[h]
# when KeywordOpNode
# fail "didn't expect '#{param_list.inspect}' inside actual parameter list"
when nil
else
param_list=[param_list]
end
param_list.extend ListInNode if param_list
if block
@do_end=block.do_end
blockparams=block.params
block=block.body #||[]
end
@offset=method.offset
if Token===method
method=method.ident
fail unless String===method
end
super(nil,method,param_list,blockparams,block)
#receiver, if any, is tacked on later
end
def real_parens; @not_real_parens||=nil; !@not_real_parens end
def real_parens= x; @not_real_parens=!x end
def unparse o=default_unparse_options
fail if block==false
result=[
receiver&&receiver.unparse(o)+'.',name,
real_parens ? '(' : (' ' if params),
params&¶ms.map{|param| unparse_nl(param,o,'',"\\\n")+param.unparse(o) }.join(', '),
real_parens ? ')' : nil,
block&&[
@do_end ? " do " : "{",
block_params&&block_params.unparse(o),
unparse_nl(block,o," "),
block.unparse(o),
unparse_nl(endline,o),
@do_end ? " end" : "}"
]
]
return result.join
end
def image
result="(#{receiver.image if receiver}.#{name})"
end
def with_commas
!real_parens and
args and args.size>0
end
# identity_param :with_commas, false, true
def lvalue_parsetree(o)
result=parsetree(o)
result[0]=:attrasgn
result[2]="#{result[2]}=".to_sym
result
end
def lvalue
return @lvalue if defined? @lvalue
@lvalue=true
end
attr_writer :lvalue
identity_param :lvalue, nil, true
def to_lisp
"(#{receiver.to_lisp} #{self[1..-1].map{|x| x.to_lisp}.join(' ')})"
end
alias args params
alias rcvr receiver
def set_receiver!(expr)
self[0]=expr
end
def parsetree_with_params o
args=args()||[]
if (UnOpNode===args.last and args.last.ident=="&@")
lasti=args.size-2
unamp_expr=args.last.val
else
lasti=args.size-1
end
methodname= name
methodname= methodname.chop if /^[~!]@$/===methodname
methodsym=methodname.to_sym
is_kw= RubyLexer::FUNCLIKE_KEYWORDS&~/^(BEGIN|END|raise)$/===methodname
result=
if lasti==-1
[(@not_real_parens and /[!?]$/!~methodname and !unamp_expr) ?
:vcall : :fcall, methodsym
]
elsif (UnaryStarNode===args[lasti])
if lasti.zero?
[:fcall, methodsym, args.first.rescue_parsetree(o)]
else
[:fcall, methodsym,
[:argscat,
[:array, *args[0...lasti].map{|x| x.rescue_parsetree(o) } ],
args[lasti].val.rescue_parsetree(o)
]
]
end
else
singlearg= lasti.zero?&&args.first
[:fcall, methodsym,
[:array, *args[0..lasti].map{|x| x.rescue_parsetree(o) } ]
]
end
result[0]=:vcall if block #and /\Af?call\Z/===result[0].to_s
if is_kw and !receiver
if singlearg and "super"!=methodname
result=[methodsym, singlearg.parsetree(o)]
result.push(true) if methodname=="yield" and ArrayLiteralNode===singlearg #why???!!
return result
end
breaklike= /^(break|next|return)$/===methodname
if @not_real_parens
return [:zsuper] if "super"==methodname and !args()
else
return [methodsym, [:nil]] if breaklike and args.size.zero?
end
result.shift
arg=result[1]
result[1]=[:svalue,arg] if arg and arg[0]==:splat and breaklike
end
if receiver
result.shift if result.first==:vcall or result.first==:fcall #if not kw
result=[:call, receiver.rescue_parsetree(o), *result]
end
if unamp_expr
# result[0]=:fcall if lasti.zero?
result=[:block_pass, unamp_expr.rescue_parsetree(o), result]
end
return result
end
def parsetree(o)
callsite=parsetree_with_params o
return callsite unless blockparams or block
call=name
callsite[0]=:fcall if callsite[0]==:call or callsite[0]==:vcall
unless receiver
case call
when "BEGIN"
if o[:quirks]
return []
else
callsite=[:preexe]
end
when "END"; callsite=[:postexe]
end
else
callsite[0]=:call if callsite[0]==:fcall
end
if blockparams
bparams=blockparams.dup
lastparam=bparams.last
amped=bparams.pop.val if UnOpNode===lastparam and lastparam.op=="&@"
bparams=bparams.parsetree(o)||0
if amped
bparams=[:masgn, [:array, bparams]] unless bparams==0 or bparams.first==:masgn
bparams=[:block_pass, amped.lvalue_parsetree(o), bparams]
end
else
bparams=nil
end
result=[:iter, callsite, bparams]
unless block.empty?
body=block.parsetree(o)
if curr_vars=block.lvars_defined_in
curr_vars-=blockparams.all_current_lvars if blockparams
if curr_vars.empty?
result.push body
else
curr_vars.map!{|cv| [:dasgn_curr, cv.to_sym] }
(0...curr_vars.size-1).each{|i| curr_vars[i]<<curr_vars[i+1] }
#body.first==:block ? body.shift : body=[body]
result.push((body)) #.unshift curr_vars[0]))
end
else
result.push body
end
end
result
end
def blockformals_parsetree data,o #dead code?
data.empty? and return nil
data=data.dup
star=data.pop if UnaryStarNode===data.last
result=data.map{|x| x.parsetree(o) }
=begin
{ if VarNode===x
ident=x.ident
ty=x.varname2assigntype
# ty==:lasgn and ty=:dasgn_curr
[ty, ident.to_sym]
else
x=x.parsetree(o)
if x[0]==:call
x[0]=:attrasgn
x[2]="#{x[2]}=".to_sym
end
x
end
}
=end
if result.size==0
star or fail
result=[:masgn, star.parsetree(o).last]
elsif result.size==1 and !star
result=result.first
else
result=[:masgn, [:array, *result]]
if star
old=star= star.val
star=star.parsetree(o)
if star[0]==:call
star[0]=:attrasgn
star[2]="#{star[2]}=".to_sym
end
if VarNode===old
ty=old.varname2assigntype
# ty==:lasgn and ty=:dasgn_curr
star[0]=ty
end
result.push star
end
end
result
end
end
class CallNode<CallSiteNode #normal method calls
def initialize(method,open_paren,param_list,close_paren,block)
super
end
end
class KWCallNode<CallSiteNode #keywords that look (more or less) like methods
def initialize(method,open_paren,param_list,close_paren,block)
KeywordToken===method or fail
super
end
end
class BlockFormalsNode<Node #obsolete
def initialize(goalpost1,param_list,goalpost2)
param_list or return super()
CommaOpNode===param_list and return super(*Array.new(param_list))
super(param_list)
end
def to_lisp
"(#{data.join' '})"
end
def parsetree(o)
empty? ? nil :
[:dasgn_curr,
*map{|x|
(VarNode===x) ? x.ident.to_sym : x.parsetree(o)
}
]
end
end
class BlockNode<ValueNode #not to appear in final parse tree
param_names :params,:body
def initialize(open_brace,formals,stmts,close_brace)
stmts||=SequenceNode[{:@offset => open_brace.offset, :@startline=>open_brace.startline}]
stmts=SequenceNode[stmts,{:@offset => open_brace.offset, :@startline=>open_brace.startline}] unless SequenceNode===stmts
formals&&=BlockParams.new(Array.new(formals))
@do_end=true unless open_brace.not_real?
super(formals,stmts)
end
attr_reader :do_end
def to_lisp
"(#{params.to_lisp} #{body.to_lisp})"
end
def parsetree(o) #obsolete
callsite=@data[0].parsetree(o)
call=@data[0].data[0]
callsite[0]=:fcall if call.respond_to? :ident
if call.respond_to? :ident
case call.ident
when "BEGIN"
if o[:quirks]
return []
else
callsite=[:preexe]
end
when "END"; callsite=[:postexe]
end
end
result=[:iter, callsite, @data[1].parsetree(o)]
result.push @data[2].parsetree(o) if @data[2]
result
end
end
class ProcLiteralNode<ValueNode
def initialize(params, other_locals, body)
@params, @other_locals, @body= params, other_locals, body
end
def self.create(arrow, lparen, params, rparen, do_word, body, endword)
params,other_locals=*params if SequenceNode===params
new(params,other_locals,body)
end
def unparse o=default_parse_options
huh
end
end
class NopNode<ValueNode
def initialize(*args)
@startline=@endline=1
super()
end
def unparse o=default_unparse_options
''
end
def to_lisp
"()"
end
alias image to_lisp
def to_parsetree(*options)
[]
end
end
=begin
class ObjectNode<ValueNode
def initialize
super
end
def to_lisp
"Object"
end
def parsetree(o)
:Object
end
end
=end
class CallWithBlockNode<ValueNode #obsolete
param_names :call,:block
def initialize(call,block)
KeywordCall===call and extend KeywordCall
super
end
def to_lisp
@data.first.to_lisp.chomp!(")")+" #{@data.last.to_lisp})"
end
end
class StringNode<ValueNode
def initialize(token)
if HerePlaceholderToken===token
str=token.string
@char=token.quote
else
str=token
@char=str.char
end
@modifiers=str.modifiers #if str.modifiers
super( *with_string_data(str) )
@open=token.open
@close=token.close
@offset=token.offset
@bs_handler=str.bs_handler
if /[\[{]/===@char
@parses_like=split_into_words(str)
end
return
=begin
#this should have been taken care of by with_string_data
first=shift
delete_if{|x| ''==x }
unshift(first)
#escape translation now done later on
map!{|strfrag|
if String===strfrag
str.translate_escapes strfrag
else
strfrag
end
}
=end
end
def initialize_ivars
@char||='"'
@open||='"'
@close||='"'
@bs_handler||=:dquote_esc_seq
if /[\[{]/===@char
@parses_like||=split_into_words(str)
end
end
def translate_escapes(str)
rl=RubyLexer.new("(string escape translation hack...)",'')
result=str.dup
seq=result.to_sequence
rl.instance_eval{@file=seq}
repls=[]
i=0
#ugly ugly ugly... all so I can call @bs_handler
while i<result.size and bs_at=result.index(/\\./m,i)
seq.pos=$~.end(0)-1
ch=rl.send(@bs_handler,"\\",@open[-1,1],@close)
result[bs_at...seq.pos]=ch
i=bs_at+ch.size
end
return result
end
def old_cat_initialize(*tokens) #not needed anymore?
token=tokens.shift
tokens.size==1 or fail "string node must be made from a single string token"
newdata=with_string_data(*tokens)
case token
when HereDocNode
token.list_to_append=newdata
when StringNode #do nothing
else fail "non-string token class used to construct string node"
end
replace token.data
# size%2==1 and last<<newdata.shift
if size==1 and String===first and String===newdata.first
first << newdata.shift
end
concat newdata
@implicit_match=false
end
ESCAPABLES={}
EVEN_NUM_BSLASHES=/(^|[^\\])((?:\\\\)*)/
def unparse o=default_unparse_options
o[:linenum]+=@open.count("\n")
result=[@open,unparse_interior(o),@close,@modifiers].join
o[:linenum]+=@close.count("\n")
return result
end
def escapable open=@open,close=@close
unless escapable=ESCAPABLES[open]
maybe_crunch='\\#' if %r{\A["`/\{]\Z} === @char and open[1] != ?q and open != "'" #"
#crunch (#) might need to be escaped too, depending on what @char is
escapable=ESCAPABLES[open]=
/[#{Regexp.quote open[-1,1]+close}#{maybe_crunch}]/
end
escapable
end
def unparse_interior o,open=@open,close=@close,escape=nil
escapable=escapable(open,close)
result=map{|substr|
if String===substr
#hack: this is needed for here documents only, because their
#delimiter is changing.
substr.gsub!(escape){|ch| ch[0...-1]+"\\"+ch[-1,1]} if escape
o[:linenum]+=substr.count("\n") if o[:linenum]
substr
else
['#{',substr.unparse(o),'}']
end
}
result
end
def image; '(#@char)' end
def walk(*args,&callback)
@parses_like.walk(*args,&callback) if defined? @parses_like
super
end
def depthwalk(*args,&callback)
return @parses_like.depthwalk(*args,&callback) if defined? @parses_like
super
end
def special_conditions!
@implicit_match= @char=="/"
end
attr_reader :modifiers,:char#,:data
alias type char
def with_string_data(token)
# token=tokens.first
# data=tokens.inject([]){|sum,token|
# data=elems=token.string.elems
data=elems=
case token
when StringToken; token.elems
when HerePlaceholderToken; token.string.elems
else raise "unknown string token type: #{token}:#{token.class}"
end
# sum.size%2==1 and sum.last<<elems.shift
# sum+elems
# }
# endline=@endline
1.step(data.length-1,2){|i|
tokens=data[i].ident.dup
line=data[i].linenum
#replace trailing } with EoiToken
(tokens.size-1).downto(0){|j|
tok=tokens[j]
break(tokens[j..-1]=[EoiToken.new('',nil,tokens[j].offset)]) if tok.ident=='}'
}
#remove leading {
tokens.each_with_index{|tok,j| break(tokens.delete_at j) if tok.ident=='{' }
if tokens.size==1 and VarNameToken===tokens.first
data[i]=VarNode.new tokens.first
data[i].startline=data[i].endline=token.endline
data[i].offset=tokens.first.offset
else
#parse the token list in the string inclusion
parser=Thread.current[:$RedParse_parser]
klass=parser.class
data[i]=klass.new(tokens, "(string inclusion)",1,[],:rubyversion=>parser.rubyversion,:cache_mode=>:none).parse
end
} #if data
# was_nul_header= (String===data.first and data.first.empty?) #and o[:quirks]
last=data.size-1
#remove (most) empty string fragments
last.downto(1){|frag_i|
frag=data[frag_i]
String===frag or next
next unless frag.empty?
next if frag_i==last #and o[:quirks]
next if data[frag_i-1].endline != data[frag_i+1].endline #and o[:quirks]
#prev and next inclusions on different lines
data.slice!(frag_i)
}
# data.unshift '' if was_nul_header
return data
end
def endline= endline
each{|frag|
frag.endline||=endline if frag.respond_to? :endline
}
super
end
def to_lisp
return %{"#{first}"} if size<=1 and @char=='"'
huh
end
EVEN_BSS=/(?:[^\\\s\v]|\G)(?:\\\\)*/
DQ_ESC=/(?>\\(?>[CM]-|c)?)/
DQ_EVEN=%r[
(?:
\A |
[^\\c-] |
(?>\A|[^\\])c |
(?> [^CM] | (?>\A|[^\\])[CM] )-
) #not esc
#{DQ_ESC}{2}* #an even number of esc
]omx
DQ_ODD=/#{DQ_EVEN}#{DQ_ESC}/omx
SQ_ESC=/\\/
SQ_EVEN=%r[
(?: \A | [^\\] ) #not esc
#{SQ_ESC}{2}* #an even number of esc
]omx
SQ_ODD=/#{SQ_EVEN}#{SQ_ESC}/omx
def split_into_words strtok
@offset=strtok.offset
return unless /[{\[]/===@char
result=ArrayLiteralNode[]
result << StringNode['',{:@char=>'"',:@open=>@open,:@close=>@close,:@bs_handler=>@bs_handler}]
proxy=dup
proxy[0]=proxy[0][/\A(?:\s|\v)+(.*)\Z/m,1] if /\A(?:\s|\v)/===proxy[0]
# first[/\A(?:\s|\v)+/]='' if /\A(?:\s|\v)/===first #uh-oh, changes first
proxy.each{|x|
if String===x
# x=x[/\A(?:\s|\v)+(.*)\Z/,1] if /\A[\s\v]/===x
if false
#split on ws preceded by an even # of backslashes or a non-backslash, non-ws char
#this ignores backslashed ws
#save the thing that preceded the ws, it goes back on the token preceding split
double_chunks=x.split(/( #{EVEN_BSS} | (?:[^\\\s\v]|\A|#{EVEN_BSS}\\[\s\v]) )(?:\s|\v)+/xo,-1)
chunks=[]
(0..double_chunks.size).step(2){|i|
chunks << #strtok.translate_escapes \
double_chunks[i,2].to_s #.gsub(/\\([\s\v\\])/){$1}
}
else
#split on ws, then ignore ws preceded by an odd number of esc's
#esc is \ in squote word array, \ or \c or \C- or \M- in dquote
chunks_and_ws=x.split(/([\s\v]+)/,-1)
start=chunks_and_ws.size; start-=1 if start&1==1
chunks=[]
i=start+2;
while (i-=2)>=0
ch=chunks_and_ws[i]||""
if i<chunks_and_ws.size and ch.match(@char=="[" ? /#{SQ_ODD}\Z/omx : /#{DQ_ODD}\Z/omx)
ch<< chunks_and_ws[i+1][0,1]
if chunks_and_ws[i+1].size==1
ch<< chunks.shift
end
end
chunks.unshift ch
end
end
chunk1= chunks.shift
if chunk1.empty?
#do nothing more
elsif String===result.last.last
result.last.last << chunk1
else
result.last.push chunk1
end
# result.last.last.empty? and result.last.pop
result.concat chunks.map{|chunk|
StringNode[chunk,{:@char=>'"',:@open=>@open,:@close=>@close,:@bs_handler=>@bs_handler}]
}
else
#result.last << x
unless String===result.last.last
result.push StringNode["",{:@char=>'"',:@open=>@open,:@close=>@close,:@bs_handler=>@bs_handler}]
end
result.last.push x
# result.push StringNode["",x,{:@char=>'"',:@open=>@open,:@close=>@close,:@bs_handler=>@bs_handler}]
end
}
result.shift if StringNode&-{:size=>1, :first=>''}===result.first
result.pop if StringNode&-{:size=>1, :first=>''}===result.last
return result
end
CHAROPT2NUM={
?x=>Regexp::EXTENDED,
?m=>Regexp::MULTILINE,
?i=>Regexp::IGNORECASE,
?o=>8,
}
CHARSETFLAG2NUM={
?n=>0x10,
?e=>0x20,
?s=>0x30,
?u=>0x40
}
CHAROPT2NUM.default=0
CHARSETFLAG2NUM.default=0
DOWNSHIFT_STRING_TYPE={
:dregx=>:lit,
:dregx_once=>:lit,
:dstr=>:str,
:dxstr=>:xstr,
}
def parsetree(o)
if size==1
val=translate_escapes first
type=case @char
when '"',"'"; :str
when '/'
numopts=0
charset=0
RubyLexer::CharHandler.each_char(@modifiers){|ch|
if ch==?o
type=:dregx_once
elsif numopt=CHAROPT2NUM[ch].nonzero?
numopts|=numopt
elsif set=CHARSETFLAG2NUM[ch].nonzero?
charset=set
else fail
end
}
val=Regexp.new val,numopts|charset
:lit
when '[','{'
return @parses_like.parsetree(o)
=begin
double_chunks=val.split(/([^\\]|\A)(?:\s|\v)/,-1)
chunks=[]
(0..double_chunks.size).step(2){|i|
chunks << double_chunks[i,2].to_s.gsub(/\\(\s|\v)/){$1}
}
# last=chunks
# last.last.empty? and last.pop if last and !last.empty?
words=chunks#.flatten
words.shift if words.first.empty? unless words.empty?
words.pop if words.last.empty? unless words.empty?
return [:zarray] if words.empty?
return words.map{|word| [:str,word]}.unshift(:array)
=end
when '`'; :xstr
else raise "dunno what to do with #@char<StringToken"
end
result=[type,val]
else
saw_string=false
vals=[]
each{|elem|
case elem
when String
was_esc_nl= (elem=="\\\n") #ick
elem=translate_escapes elem
if saw_string
vals.push [:str, elem] if !elem.empty? or was_esc_nl
else
saw_string=true
vals.push elem
end
when NopNode
vals.push [:evstr]
when Node #,VarNameToken
res=elem.parsetree(o)
if res.first==:str and @char != '{'
vals.push res
elsif res.first==:dstr and @char != '{'
vals.push [:str, res[1]], *res[2..-1]
else
vals.push [:evstr, res]
end
else fail "#{elem.class} not expected here"
end
}
while vals.size>1 and vals[1].first==:str
vals[0]+=vals.delete_at(1).last
end
#vals.pop if vals.last==[:str, ""]
type=case @char
when '"'; :dstr
when '/'
type=:dregx
numopts=charset=0
RubyLexer::CharHandler.each_char(@modifiers){|ch|
if ch==?o
type=:dregx_once
elsif numopt=CHAROPT2NUM[ch].nonzero?
numopts|=numopt
elsif set=CHARSETFLAG2NUM[ch].nonzero?
charset=set
end
}
regex_options= numopts|charset unless numopts|charset==0
val=/#{val}/
type
when '{'
return @parses_like.parsetree(o)
=begin
vals[0]=vals[0].sub(/\A(\s|\v)+/,'') if /\A(\s|\v)/===vals.first
merged=Array.new(vals)
result=[]
merged.each{|i|
if String===i
next if /\A(?:\s|\v)+\Z/===i
double_chunks=i.split(/([^\\]|\A)(?:\s|\v)/,-1)
chunks=[]
(0..double_chunks.size).step(2){|ii|
chunks << double_chunks[ii,2].to_s.gsub(/\\(\s|\v)/){$1}
}
words=chunks.map{|word| [:str,word]}
if !result.empty? and frag=words.shift and !frag.last.empty?
result[-1]+=frag
end
result.push( *words )
else
result.push [:str,""] if result.empty?
if i.first==:evstr and i.size>1 and i.last.first==:str
if String===result.last[-1]
result.last[-1]+=i.last.last
else
result.last[0]=:dstr
result.last.push(i.last)
end
else
result.last[0]=:dstr
result.last.push(i)
end
end
}
return result.unshift(:array)
=end
when '`'; :dxstr
else raise "dunno what to do with #@char<StringToken"
end
if vals.size==1
if :dregx==type or :dregx_once==type
lang=@modifiers.tr_s("^nesuNESU","")
lang=lang[-1,1] unless lang.empty?
lang.downcase!
regex_options=nil
vals=[Regexp_new( vals.first,numopts,lang )]
end
type=DOWNSHIFT_STRING_TYPE[type]
end
result= vals.unshift(type)
result.push regex_options if regex_options
end
result=[:match, result] if defined? @implicit_match and @implicit_match
return result
end
if //.respond_to? :encoding
LETTER2ENCODING={
?n => Encoding::ASCII,
?u => Encoding::UTF_8,
?e => Encoding::EUC_JP,
?s => Encoding::SJIS,
"" => Encoding::ASCII
}
def Regexp_new(src,opts,lang)
src.encode!(LETTER2ENCODING[lang])
Regexp.new(src,opts)
end
else
def Regexp_new(src,opts,lang)
Regexp.new(src,opts,lang)
end
end
end
class HereDocNode<StringNode
param_names :token
def initialize(token)
token.node=self
super(token)
@startline=token.string.startline
end
attr_accessor :list_to_append
# attr :token
def saw_body! #not used
replace with_string_data(token)
@char=token.quote
if @list_to_append
size%2==1 and token << @list_to_append.shift
push( *@list_to_append )
remove_instance_variable :@list_to_append
end
end
def translate_escapes x
return x if @char=="'"
super
end
#ignore instance vars in here documents when testing equality
def flattened_ivars_equal?(other)
StringNode===other
end
def unparse o=default_unparse_options
lead=unparse_nl(self,o,'',"\\\n")
inner=unparse_interior o,@char,@char,
case @char
when "'" #single-quoted here doc is a special case;
#\ and ' are not special within it
#(and therefore always escaped if converted to normal squote str)
/['\\]/
when '"'; /#{DQ_EVEN}"/
when "`"; /#{DQ_EVEN}`/
else fail
end
[lead,@char, inner, @char].join
end
end
class LiteralNode<ValueNode
param_names :val
attr_accessor :offset
def self.create(old_val)
offset=old_val.offset
val=old_val.ident
case old_val
when SymbolToken
case val[1]
when ?' #'
assert !old_val.raw.has_str_inc?
val=old_val.raw.translate_escapes(old_val.raw.elems.first).to_sym
when ?" #"
if old_val.raw.has_str_inc? or old_val.raw.elems==[""]
val=StringNode.new(old_val.raw) #ugly hack: this isn't literal
else
val=old_val.raw.translate_escapes(old_val.raw.elems.first).to_sym
end
else #val=val[1..-1].to_sym
val=old_val.raw
if StringToken===val
val=val.translate_escapes(val.elems.first)
elsif /^[!~]@$/===val
val=val.chop
end
val=val.to_sym
end
when NumberToken
case val
when /\A-?0([^.]|\Z)/; val=val.oct
when /[.e]/i; val=val.to_f
else val=val.to_i
end
end
result=LiteralNode.new(val)
result.offset=offset
result
end
def self.inline_symbols data
#don't mangle symbols when constructing node like: LiteralNode[:foo]
data
end
def []=(*args)
original_brackets_assign( *args )
end
def bare_method
Symbol===val || StringNode===val
end
identity_param :bare_method, nil, false, true
def image; "(#{':' if Symbol===val}#{val})" end
def to_lisp
return val.to_s
end
Inf="999999999999999999999999999999999.9e999999999999999999999999999999999999"
Nan="****shouldnt ever happen****"
def unparse o=default_unparse_options
val=val()
case val
when StringNode #ugly hack
":"+
val.unparse(o)
when Float
s= val.accurate_to_s
#why must it be *2? I wouldn't think any fudge factor would be necessary
case s
when /-inf/i; s="-"+Inf
when /inf/i; s= Inf
when /nan/i; s= Nan
else
fail unless [s.to_f].pack("d")==[val].pack("d")
end
s
else val.inspect
end
end
def parsetree(o)
val=val()
case val
when StringNode #ugly hack
result= val.parsetree(o)
result[0]=:dsym
return result
=begin
when String
#float or real string? or keyword?
val=
case val
when Numeric: val
when Symbol: val
when String: val
when "true": true
when "false": false
when "nil": nil
when "self": return :self
when "__FILE__": "wrong-o"
when "__LINE__": "wrong-o"
else fail "unknown token type in LiteralNode: #{val.class}"
end
=end
end
return [:lit,val]
end
end
class VarLikeNode<ValueNode #nil,false,true,__FILE__,__LINE__,self
param_names :name
def initialize(name,*more)
@offset=name.offset
if name.ident=='('
#simulate nil
replace ['nil']
@value=nil
else
replace [name.ident]
@value=name.respond_to?(:value) && name.value
end
end
alias ident name
def image; "(#{name})" end
def to_lisp
name
end
def unparse o=default_unparse_options
name
end
def parsetree(o)
if (defined? @value) and @value
type=:lit
val=@value
if name=="__FILE__"
type=:str
val="(string)" if val=="-"
end
[type,val]
else
[name.to_sym]
end
end
end
class ArrayLiteralNode<ValueNode
def initialize(lbrack,contents,rbrack)
@offset=lbrack.offset
contents or return super()
if CommaOpNode===contents
h,arrowrange=contents.extract_unbraced_hash
contents[arrowrange]=[h] if arrowrange
super( *contents )
elsif ArrowOpNode===contents
h=HashLiteralNode.new(nil,contents,nil)
h.startline=contents.startline
h.endline=contents.endline
super HashLiteralNode.new(nil,contents,nil)
else
super contents
end
end
def image; "([])" end
def unparse o=default_unparse_options
"["+map{|item| unparse_nl(item,o,'')+item.unparse(o)}.join(', ')+"]"
end
def parsetree(o)
size.zero? and return [:zarray]
normals,star,amp=param_list_parse(self,o)
result=normals.unshift :array
if star
if size==1
result=star
else
result=[:argscat, result, star.last]
end
end
result
end
end
#ArrayNode=ValueNode
class BracketsSetNode < ValueNode #obsolete
param_names :left,:assign_,:right
def parsetree(o)
[:attrasgn, left.data[0].parsetree(o), :[]=,
[:array]+Array(left.data[1]).map{|x| x.parsetree(o)}<< right.parsetree(o)
]
end
end
class BracketsModifyNode < ValueNode #obsolete
param_names :left,:assignop,:right
def initialize(left,assignop,right)
super
end
def parsetree(o)
bracketargs=@data[0].data[1]
bracketargs=bracketargs ? bracketargs.map{|x| x.parsetree(o)}.unshift(:array) : [:zarray]
[:op_asgn1, @data[0].data[0].parsetree(o), bracketargs,
data[1].ident.chomp('=').to_sym, data[2].parsetree(o)]
end
end
class IfNode < ValueNode
param_names :condition,:consequent,:elsifs,:otherwise
def initialize(iftok,condition,thentok,consequent,elsifs,else_,endtok)
@offset=iftok.offset
if else_
else_=else_.val or @empty_else=true
end
condition.special_conditions! if condition.respond_to? :special_conditions!
elsifs.extend ListInNode if elsifs
super(condition,consequent,elsifs,else_)
@reverse= iftok.ident=="unless"
if @reverse
@iftok_offset=iftok.offset
fail "elsif not allowed with unless" unless elsifs.empty?
end
end
alias if condition
alias then consequent
alias else otherwise
alias else_ else
alias if_ if
alias then_ then
attr_reader :empty_else
def unparse o=default_unparse_options
result=@reverse ? "unless " : "if "
result+="#{condition.unparse o}"
result+=unparse_nl(consequent,o)+"#{consequent.unparse(o)}" if consequent
result+=unparse_nl(elsifs.first,o)+elsifs.map{|n| n.unparse(o)}.join if elsifs
result+=unparse_nl(else_,o)+"else "+else_.unparse(o) if else_
result+=";else " if defined? @empty_else
result+=";end"
return result
end
def image; "(if)" end
def if
if @reverse
negate condition, @iftok_offset
else
condition
end
end
def then
@reverse ? otherwise : consequent
end
def else
@reverse ? consequent : otherwise
end
def to_lisp
if elsifs.empty?
"(#{@reverse ? :unless : :if} #{condition.to_lisp}\n"+
"(then #{consequent.to_lisp})\n(else #{otherwise.to_lisp}))"
else
"(cond (#{condition.to_lisp} #{consequent.to_lisp})\n"+
elsifs.map{|x| x.to_lisp}.join("\n")+
"\n(else #{otherwise.to_lisp})"+
"\n)"
end
end
def parsetree(o)
elsepart=otherwise.parsetree(o) if otherwise
elsifs.reverse_each{|elsifnode|
elsepart=elsifnode.parsetree(o) << elsepart
}
cond=condition.rescue_parsetree(o)
actions=[
consequent&&consequent.parsetree(o),
elsepart
]
if cond.first==:not
cond=cond.last
reverse=!@reverse
else
reverse=@reverse
end
actions.reverse! if reverse
result=[:if, cond, *actions]
return result
end
end
class ElseNode<Node #not to appear in final tree
param_names :elseword_,:val
alias body val
def image; "(else)" end
def to_lisp
"(else #{body.to_lisp})"
end
end
class EnsureNode<Node #not to appear in final tree
param_names :ensureword_, :val
alias body val
def image; "(ensure)" end
def parsetree(o) #obsolete?
(body=body()) ? body.parsetree(o) : [:nil]
end
end
class ElsifNode<Node
param_names(:elsifword_,:condition,:thenword_,:consequent)
def initialize(elsifword,condition,thenword,consequent)
@offset=elsifword.offset
condition.special_conditions! if condition.respond_to? :special_conditions!
super(condition,consequent)
end
alias if condition
alias elsif if
alias then consequent
def image; "(elsif)" end
def unparse o=default_unparse_options
"elsif #{condition.unparse o}#{unparse_nl(consequent,o)}#{consequent.unparse o if consequent};"
end
def to_lisp
"("+condition.to_lisp+" "+consequent.to_lisp+")"
end
def parsetree(o) #obsolete?
[:if, condition.rescue_parsetree(o), consequent&&consequent.parsetree(o), ]
end
end
class LoopNode<ValueNode
#this class should be abstract and have 2 concrete descendants for while and until
param_names :condition, :body
def initialize(loopword,condition,thenword,body,endtok)
@offset=loopword.offset
condition.special_conditions! if condition.respond_to? :special_conditions!
super(condition,body)
@reverse= loopword.ident=="until"
@loopword_offset=loopword.offset
end
alias do body
def image; "(#{loopword})" end
def unparse o=default_unparse_options
[@reverse? "until " : "while ",
condition.unparse(o), unparse_nl(body||self,o),
body&&body.unparse(o),
";end"
].join
end
def while
@reverse ? negate(condition, @loopword_offset) : condition
end
def until
@reverse ? condition : negate(condition, @loopword_offset)
end
def reversed
@reverse
end
def test_first
false
end
def to_lisp
body=body()
"(#{@reverse ? :until : :while} #{condition.to_lisp}\n#{body.to_lisp})"
end
def parsetree(o)
cond=condition.rescue_parsetree(o)
if cond.first==:not
reverse=!@reverse
cond=cond.last
else
reverse=@reverse
end
[reverse ? :until : :while, cond, body&&body.parsetree(o), true]
end
end
class CaseNode<ValueNode
param_names(:case!,:whens,:else!)
alias condition case
alias otherwise else
def initialize(caseword, condition, semi, whens, otherwise, endword)
@offset=caseword.offset
if otherwise
otherwise=otherwise.val
@empty_else=!otherwise
else
@empty_else=false
end
whens.extend ListInNode
super(condition,whens,otherwise)
end
attr_reader :empty_else
def unparse o=default_unparse_options
result="case #{condition&&condition.unparse(o)}"+
whens.map{|wh| wh.unparse o}.join
result += unparse_nl(otherwise,o)+"else "+otherwise.unparse(o) if otherwise
result += ";else;" if @empty_else
result += ";end"
return result
end
def image; "(case)" end
def to_lisp
"(case #{case_.to_lisp}\n"+
whens.map{|x| x.to_lisp}.join("\n")+"\n"+
"(else #{else_.to_lisp}"+
"\n)"
end
def parsetree(o)
result=[:case, condition&&condition.parsetree(o)]+
whens.map{|whennode| whennode.parsetree(o)}
other=otherwise&&otherwise.parsetree(o)
return [] if result==[:case, nil] and !other
if other and other[0..1]==[:case, nil] and !condition
result.concat other[2..-1]
else
result<<other
end
return result
end
end
class WhenNode<Node #not to appear in final tree?
param_names(:whenword_,:when!,:thenword_,:then!)
def initialize(whenword,when_,thenword,then_)
@offset=whenword.offset
when_=Array.new(when_) if CommaOpNode===when_
when_.extend ListInNode if when_.class==Array
super(when_,then_)
end
alias body then
alias consequent then
alias condition when
def image; "(when)" end
def unparse o=default_unparse_options
result=unparse_nl(self,o)+"when "
result+=condition.class==Array ?
condition.map{|cond| cond.unparse(o)}.join(',') :
condition.unparse(o)
result+=unparse_nl(consequent,o)+consequent.unparse(o) if consequent
result
end
def to_lisp
unless Node|Token===condition
"(when (#{condition.map{|cond| cond.to_lisp}.join(" ")}) #{
consequent&&consequent.to_lisp
})"
else
"(#{when_.to_lisp} #{then_.to_lisp})"
end
end
def parsetree(o)
conds=
if Node|Token===condition
[condition.rescue_parsetree(o)]
else
condition.map{|cond| cond.rescue_parsetree(o)}
end
if conds.last[0]==:splat
conds.last[0]=:when
conds.last.push nil
end
[:when, [:array, *conds],
consequent&&consequent.parsetree(o)
]
end
end
class ForNode<ValueNode
param_names(:forword_,:for!,:inword_,:in!,:doword_,:do!,:endword_)
def initialize(forword,for_,inword,in_,doword,do_,endword)
@offset=forword.offset
#elide 1 layer of parens if present
for_=for_.first if ParenedNode===for_
for_=CommaOpNode===for_ ? Array.new(for_) : [for_]
super(BlockParams.new(for_),in_,do_)
end
alias body do
alias enumerable in
alias iterator for
def image; "(for)" end
def unparse o=default_unparse_options
result=unparse_nl(self,o)+" for #{iterator.lhs_unparse(o)[1...-1]} in #{enumerable.unparse o}"
result+=unparse_nl(body,o)+" #{body.unparse(o)}" if body
result+=";end"
end
def parsetree(o)
=begin
case vars=@data[0]
when Node:
vars=vars.parsetree(o)
if vars.first==:call
vars[0]=:attrasgn
vars[2]="#{vars[2]}=".to_sym
end
vars
when Array:
vars=[:masgn, [:array,
*vars.map{|lval|
res=lval.parsetree(o)
res[0]=lval.varname2assigntype if VarNode===lval
res
}
]]
when VarNode
ident=vars.ident
vars=vars.parsetree(o)
(vars[0]=vars.varname2assigntype) rescue nil
else fail
end
=end
vars=self.for.lvalue_parsetree(o)
collection= self.in.begin_parsetree(o)
if ParenedNode===self.in and collection.first==:begin
assert collection.size==2
collection=collection[1]
end
result=[:for, collection, vars]
result.push self.do.parsetree(o) if self.do
result
end
end
class HashLiteralNode<ValueNode
def initialize(open,contents,close)
@offset=open.offset rescue contents.first.offset
case contents
when nil; super()
when ArrowOpNode; super(contents.first,contents.last)
when CommaOpNode,Array
if ArrowOpNode===contents.first
data=[]
contents.each{|pair|
ArrowOpNode===pair or fail
data.push pair.first,pair.last
}
else
@no_arrows=true
data=Array[*contents]
end
super(*data)
else fail
end
@no_braces=true unless open
end
attr :no_arrows
attr_accessor :no_braces
attr_writer :offset
def image; "({})" end
def unparse o=default_unparse_options
result=''
result << "{" unless defined? @no_braces and @no_braces
arrow= defined?(@no_arrows) ? " , " : " => "
(0...size).step(2){|i|
result<< unparse_nl(self[i],o,'')+
self[i].unparse(o)+arrow+
self[i+1].unparse(o)+', '
}
result.chomp! ', '
result << "}" unless defined? @no_braces and @no_braces
return result
end
def get k
case k
when Node;
k.delete_extraneous_ivars!
k.delete_linenums!
when Symbol, Numeric; k=LiteralNode[k]
when true,false,nil; k=VarLikeNode[k.inspect]
else raise ArgumentError
end
return as_h[k]
end
def as_h
return @h if defined? @h
@h={}
(0...size).step(2){|i|
k=self[i].dup
k.delete_extraneous_ivars!
k.delete_linenums!
@h[k]=self[i+1]
}
return @h
end
def parsetree(o)
map{|elem| elem.rescue_parsetree(o)}.unshift :hash
end
def error? rubyversion=1.8
return true if defined?(@no_arrows) and rubyversion>=1.9
return super
end
end
class TernaryNode<ValueNode
param_names :if!,:qm_,:then!,:colon_,:else!
alias condition if
alias consequent then
alias otherwise else
def initialize(if_,qm,then_,colon,else_)
super(if_,then_,else_)
condition.special_conditions! if condition.respond_to? :special_conditions!
@offset=self.first.offset
end
def image; "(?:)" end
def unparse o=default_unparse_options
"#{condition.unparse o} ? #{consequent.unparse o} : #{otherwise.unparse o}"
end
def elsifs; [] end
def parsetree(o)
cond=condition.rescue_parsetree(o)
cond[0]=:fcall if cond[0]==:vcall and cond[1].to_s[/[?!]$/]
[:if, cond, consequent.begin_parsetree(o), otherwise.begin_parsetree(o)]
end
end
class MethodNode<ValueNode
include HasRescue
param_names(:defword_,:receiver,:name,:maybe_eq_,:args,:semi_,:body,:rescues,:elses,:ensures,:endword_)
alias ensure_ ensures
alias else_ elses
alias ensure ensures
alias else elses
alias params args
def initialize(defword,header,maybe_eq_,semi_,
body,rescues,else_,ensure_,endword_)
@offset=defword.offset
@empty_else=@empty_ensure=nil
# if DotCallNode===header
# header=header.data[1]
# end
if CallSiteNode===header
receiver=header.receiver
args=header.args
header=header.name
end
if MethNameToken===header
header=header.ident
end
unless String===header
fail "unrecognized method header: #{header}"
end
if else_
else_=else_.val or @empty_else=true
end
if ensure_
ensure_=ensure_.val or @empty_ensure=true
end
args.extend ListInNode if args
rescues.extend ListInNode if rescues
replace [receiver,header,args,body,rescues,else_,ensure_]
end
attr_reader :empty_ensure, :empty_else
def self.namelist
%w[receiver name args body rescues elses ensures]
end
# def receiver= x
# self[0]=x
# end
#
# def body= x
# self[3]=x
# end
def ensure_= x
self[5]=x
end
def else_= x
self[6]=x
end
def image
"(def #{receiver.image.+('.') if receiver}#{name})"
end
def unparse o=default_unparse_options
result=[
"def ",receiver&&receiver.unparse(o)+'.',name,
args && '('+args.map{|arg| arg.unparse o}.join(',')+')', unparse_nl(body||self,o)
]
result<<unparse_and_rescues(o)
=begin
body&&result+=body.unparse(o)
result+=rescues.map{|resc| resc.unparse o}.to_s
result+="else #{else_.unparse o}\n" if else_
result+="else\n" if @empty_else
result+="ensure #{ensure_.unparse o}\n" if ensure_
result+="ensure\n" if @empty_ensure
=end
result<<unparse_nl(endline,o)+"end"
result.join
end
def to_lisp
"(imethod #{name} is\n#{body.to_lisp}\n)\n"
#no receiver, args, rescues, else_ or ensure_...
end
def parsetree(o)
name=name()
name=name.chop if /^[!~]@$/===name
name=name.to_sym
result=[name, target=[:scope, [:block, ]] ]
if receiver
result.unshift :defs, receiver.rescue_parsetree(o)
else
result.unshift :defn
end
goodies= (body or !rescues.empty? or elses or ensures or @empty_ensure) # or args())
if unamp=args() and unamp=unamp.last and UnOpNode===unamp and unamp.op=="&@"
receiver and goodies=true
else
unamp=false
end
if receiver and !goodies
target.delete_at 1 #omit :block
else
target=target[1]
end
target.push args=[:args,]
target.push unamp.parsetree(o) if unamp
if args()
initvals=[]
args().each{|arg|
case arg
when VarNode
args.push arg.ident.to_sym
when UnaryStarNode
args.push "*#{arg.val.ident}".to_sym
when UnOpNode
nil
when AssignNode
initvals << arg.parsetree(o)
initvals[-1][-1]=arg.right.rescue_parsetree(o) #ugly
args.push arg[0].ident.to_sym
else
fail "unsupported node type in method param list: #{arg}"
end
}
unless initvals.empty?
initvals.unshift(:block)
args << initvals
#args[-2][0]==:block_arg and target.push args.delete_at(-2)
end
end
target.push [:nil] if !goodies && !receiver
#it would be better to use parsetree_and_rescues for the rest of this method,
#just to be DRYer
target.push ensuretarget=target=[:ensure, ] if ensures or @empty_ensure
#simple dup won't work... won't copy extend'd modules
body=Marshal.load(Marshal.dump(body())) if body()
elses=elses()
if rescues.empty?
case body
when SequenceNode; body << elses;elses=nil
when nil; body=elses;elses=nil
else nil
end if elses
else
target.push target=[:rescue, ]
elses=elses()
end
if body
if BeginNode===body||RescueOpNode===body and
body.rescues.empty? and !body.ensure and !body.empty_ensure and body.body and body.body.size>1
wantblock=true
end
body=body.parsetree(o)
if body.first==:block and rescues.empty? and not ensures||@empty_ensure
if wantblock
target.push body
else
body.shift
target.concat body
end
else
#body=[:block, *body] if wantblock
target.push body
end
end
target.push linked_list(rescues.map{|rescue_| rescue_.parsetree(o) }) unless rescues.empty?
target.push elses.parsetree(o) if elses
ensuretarget.push ensures.parsetree(o) if ensures
ensuretarget.push [:nil] if @empty_ensure
return result
end
end
module BareSymbolUtils
def baresym2str(node)
case node
when MethNameToken; node.ident
when VarNode; node
when LiteralNode
case node.val
when Symbol
node.val.to_s
when StringNode; node.val
# when StringToken: StringNode.new(node.val)
else fail
end
end
end
def str_unparse(str,o)
case str
when VarNode; str.ident
when "~@"; str
when String
str.to_sym.inspect
#what if str isn't a valid method or operator name? should be quoted
when StringNode
":"+str.unparse(o)
else fail
end
end
def str2parsetree(str,o)
if String===str
str=str.chop if /^[!~]@$/===str
[:lit, str.to_sym]
else
result=str.parsetree(o)
result[0]=:dsym
result
end
end
end
class AliasNode < ValueNode
include BareSymbolUtils
param_names(:aliasword_,:to,:from)
def initialize(aliasword,to,from)
@offset=aliasword.offset
to=baresym2str(to)
from=baresym2str(from)
super(to,from)
end
def unparse o=default_unparse_options
"alias #{str_unparse to,o} #{str_unparse from,o}"
end
def image; "(alias)" end
def parsetree(o)
if VarNode===to and to.ident[0]==?$
[:valias, to.ident.to_sym, from.ident.to_sym]
else
[:alias, str2parsetree(to,o), str2parsetree(from,o)]
end
end
end
class UndefNode < ValueNode
include BareSymbolUtils
def initialize(first,middle,last=nil)
@offset=first.offset
if last
node,newsym=first,last
super(*node << baresym2str(newsym))
else
super(baresym2str(middle))
end
end
def image; "(undef)" end
def unparse o=default_unparse_options
"undef #{map{|name| str_unparse name,o}.join(', ')}"
end
def parsetree(o)
result=map{|name| [:undef, str2parsetree(name,o)] }
if result.size==1
result.first
else
result.unshift :block
end
end
end
class NamespaceNode<ValueNode
include HasRescue
def initialize(*args)
@empty_ensure=@empty_else=nil
super
end
end
class ModuleNode<NamespaceNode
param_names(:name,:body,:rescues,:else!,:ensure!)
def initialize moduleword,name,semiword,body,rescues,else_,ensure_,endword
@offset=moduleword.offset
else_=else_.val if else_
ensure_=ensure_.val if ensure_
rescues.extend ListInNode if rescues
super(name,body,rescues,else_,ensure_)
end
alias else_ else
alias ensure_ ensure
alias receiver name
def image; "(module #{name})" end
def unparse o=default_unparse_options
"module #{name.unparse o}#{unparse_nl(body||self,o)}#{unparse_and_rescues(o)}#{unparse_nl(endline,o)}end"
end
def parent; nil end
def to_lisp
result="(#{name.ident} #{body.to_lisp} "
#parent=@data[2]
#result+="is #{parent.to_lisp} " if parent
result+="\n"+body.to_lisp+")"
return result
end
def parsetree(o)
name=name()
if VarNode===name
name=name.ident.to_sym
elsif name.nil? #do nothing
# elsif o[:quirks]
# name=name.constant.ident.to_sym
else
name=name.parsetree(o)
end
result=[:module, name, scope=[:scope, ]]
scope << parsetree_and_rescues(o) if body
return result
end
end
class ClassNode<NamespaceNode
param_names(:name,:parent,:body,:rescues,:else!,:ensure!)
def initialize(classword,name,semi,body,rescues, else_, ensure_, endword)
@offset=classword.offset
if OpNode===name
name,op,parent=*name
op=="<" or fail "invalid superclass expression: #{name}"
end
else_=else_.val if else_
ensure_=ensure_.val if ensure_
rescues.extend ListInNode if rescues
super(name,parent,body,rescues,else_,ensure_)
end
alias else_ else
alias ensure_ ensure
alias receiver name
def image; "(class #{name})" end
def unparse o=default_unparse_options
result="class #{name.unparse o}"
result+=" < #{parent.unparse o}" if parent
result+=unparse_nl(body||self,o)+
unparse_and_rescues(o)+
unparse_nl(endline,o)+
"end"
return result
end
def to_lisp
result="(class #{name.to_lisp} "
result+="is #{parent.to_lisp} " if parent
result+="\n"+body.to_lisp+")"
return result
end
def parsetree(o)
name=name()
if VarNode===name
name=name.ident.to_sym
elsif name.nil? #do nothing
# elsif o[:quirks]
# name=name.constant.ident.to_sym
else
name=name.parsetree(o)
end
result=[:class, name, parent&&parent.parsetree(o), scope=[:scope,]]
scope << parsetree_and_rescues(o) if body
return result
end
end
class MetaClassNode<NamespaceNode
param_names :val, :body, :rescues,:else!,:ensure!
def initialize classword, leftleftword, val, semiword, body, rescues,else_,ensure_, endword
@offset=classword.offset
else_=else_.val if else_
ensure_=ensure_.val if ensure_
rescues.extend ListInNode if rescues
super(val,body,rescues,else_,ensure_)
end
alias expr val
alias object val
alias obj val
alias receiver val
alias receiver= val=
alias name val
alias ensure_ ensure
alias else_ else
def image; "(class<<)" end
def unparse o=default_unparse_options
"class << #{obj.unparse o}#{unparse_nl(body||self,o)}#{unparse_and_rescues(o)};end"
end
def parsetree(o)
result=[:sclass, expr.parsetree(o), scope=[:scope]]
scope << parsetree_and_rescues(o) if body
return result
end
end
class RescueHeaderNode<Node #not to appear in final tree
param_names :exceptions,:varname
def initialize(rescueword,arrowword,exceptions,thenword)
@offset=rescueword.offset
case exceptions
when nil
when VarNode
if arrowword
exvarname=exceptions
exceptions=nil
arrowword=nil
end
when ArrowOpNode
exvarname=exceptions.last
exceptions=exceptions.first
when CommaOpNode
lastexpr=exceptions.last
if ArrowOpNode===lastexpr
exceptions[-1]=lastexpr.left
exvarname=lastexpr.right
end
exceptions=Array.new(exceptions)
end
fail if arrowword
# fail unless VarNode===exvarname || exvarname.nil?
super(exceptions,exvarname)
end
def image; "(rescue=>)" end
end
class RescueNode<Node
param_names :exceptions,:varname,:action
def initialize(rescuehdr,action,semi)
@offset=rescuehdr.offset
exlist=rescuehdr.exceptions||[]
exlist=[exlist] unless exlist.class==Array
fail unless exlist.class==Array
exlist.extend ListInNode
super(exlist,rescuehdr.varname,action)
end
def unparse o=default_unparse_options
xx=exceptions.map{|exc| exc.unparse o}.join(',')
unparse_nl(self,o)+
"rescue #{xx} #{varname&&'=> '+varname.lhs_unparse(o)}#{unparse_nl(action||self,o)}#{action&&action.unparse(o)}"
end
def parsetree(o)
result=[:resbody, nil]
fail unless exceptions.class==Array
ex=#if Node===exceptions; [exceptions.rescue_parsetree(o)]
#elsif exceptions
exceptions.map{|exc| exc.rescue_parsetree(o)}
#end
if !ex or ex.empty? #do nothing
elsif ex.last.first!=:splat
result[1]= [:array, *ex]
elsif ex.size==1
result[1]= ex.first
else
result[1]= [:argscat, ex[0...-1].unshift(:array), ex.last[1]]
end
VarNode===varname and offset=varname.offset
action=if varname
SequenceNode.new(
AssignNode.new(
varname,
KeywordToken.new("=",offset),
VarNode.new(VarNameToken.new("$!",offset))
),nil,action()
)
else
action()
end
result.push action.parsetree(o) if action
result
end
def image; "(rescue)" end
end
class BracketsGetNode<ValueNode
param_names(:receiver,:lbrack_,:params,:rbrack_)
alias args params
def initialize(receiver,lbrack,params,rbrack)
case params
when CommaOpNode
h,arrowrange=params.extract_unbraced_hash
params=Array.new params
params[arrowrange]=[h] if arrowrange
when ArrowOpNode
h=HashLiteralNode.new(nil,params,nil)
h.startline=params.startline
h.endline=params.endline
params=[h]
when nil
params=nil
else
params=[params]
end
params.extend ListInNode if params
@offset=receiver.offset
super(receiver,params)
end
def name; "[]" end
def image; "(#{receiver.image}.[])" end
def unparse o=default_unparse_options
[ receiver.unparse(o).sub(/\s+\Z/,''),
'[',
params&¶ms.map{|param| param.unparse o}.join(','),
']'
].join
end
def parsetree(o)
result=parsetree_no_fcall o
o[:quirks] and VarLikeNode===receiver and receiver.name=='self' and
result[0..2]=[:fcall,:[]]
return result
end
def parsetree_no_fcall o
params=params()
output,star,amp=param_list_parse(params,o)
# receiver=receiver.parsetree(o)
result=[:call, receiver.rescue_parsetree(o), :[], output]
if params
if star and params.size==1
output.concat star
else
output.unshift :array
result[-1]=[:argscat, output, star.last] if star
end
else
result.pop
end
return result
end
def lvalue_parsetree(o)
result=parsetree_no_fcall o
result[0]=:attrasgn
result[2]=:[]=
result
end
def lvalue
return @lvalue if defined? @lvalue
@lvalue=true
end
attr_writer :lvalue
identity_param :lvalue, nil, true
end
class StartToken<Token #not to appear in final tree
def initialize; end
def image; "(START)" end
alias to_s image
end #beginning of input marker
class EoiToken
#hack hack: normally, this should never
#be called, but it may be when input is empty now.
def to_parsetree(*options)
[]
end
end
class GoalPostToken<Token #not to appear in final tree
def initialize(offset); @offset=offset end
def ident; "|" end
attr :offset
def image; "|" end
end
class GoalPostNode<Node #not to appear in final tree
def initialize(offset); @offset=offset end
def ident; "|" end
attr :offset
def image; "|" end
end
module ErrorNode
def error?(x=nil) @error end
alias msg error?
end
class MisparsedNode<ValueNode
include ErrorNode
param_names :open,:middle,:close_
alias begin open
alias what open
def image; "misparsed #{what}" end
#pass the buck to child ErrorNodes until there's no one else
def blame
middle.each{|node|
node.respond_to? :blame and return node.blame
}
return self
end
def error? x=nil
inner=middle.grep(MisparsedNode).first and return inner.error?( x )
"#@endline: misparsed #{what}: #{middle.map{|node| node&&node.image}.join(' ')}"
end
alias msg error?
end
module Nodes
::RedParse::constants.each{|k|
const=::RedParse::const_get(k)
const_set( k,const ) if Module===const and ::RedParse::Node>=const
}
end
end
=begin a (formal?) description
NodeMatcher=
Recursive(nodematcher={},
Node&-{:subnodes=>NodeList =
Recursive(nodelist={},
+[(nodematcher|nodelist|nil).*])
}
#Nodes can also have attributes which don't appear in subnodes
#this is where ordinary values (symbols, strings, numbers, true/false/nil) are kept
=end
important fix for regexp matching sequences of backslash (and friends) in strings
need to know this when splitting word array or requoting here docs
=begin
redparse - a ruby parser written in ruby
Copyright (C) 2008 Caleb Clausen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
=end
begin
require 'rubygems'
rescue LoadError=>e
raise unless /rubygems/===e.message
#hope we don't need it
end
require 'tempfile'
require 'pp'
require "rubylexer"
require "reg"
require "redparse/float_accurate_to_s"
class RedParse
#import token classes from rubylexer
RubyLexer::constants.each{|k|
t=RubyLexer::const_get(k)
self::const_set k,t if Module===t and RubyLexer::Token>=t
}
module FlattenedIvars
EXCLUDED_IVARS=%w[@data @offset @startline @endline]
EXCLUDED_IVARS.push(*EXCLUDED_IVARS.map{|iv| iv.to_sym })
def flattened_ivars
ivars=instance_variables
ivars-=EXCLUDED_IVARS
ivars.sort!
result=ivars+ivars.map{|iv|
instance_variable_get(iv)
}
return result
end
def flattened_ivars_equal?(other)
self.class == other.class and
flattened_ivars == other.flattened_ivars
end
end
module Stackable
module Meta
#declare name to be part of the identity of current class
#variations are the allowed values for name in this class
#keep variations simple: booleans, integers, symbols and strings only
def identity_param name, *variations
name=name.to_s
list=
if (variations-[true,false,nil]).empty?
#const_get("BOOLEAN_IDENTITY_PARAMS") rescue const_set("BOOLEAN_IDENTITY_PARAMS",{})
self.boolean_identity_params
else
#const_get("IDENTITY_PARAMS") rescue const_set("IDENTITY_PARAMS",{})
self.identity_params
end
list[name]=variations
return #old way to generate examplars below
=begin
old_exemplars=self.exemplars||=[allocate]
exemplars=[]
variations.each{|var| old_exemplars.each{|exm|
exemplars<< res=exm.dup
#res.send name+"=", var
#res.send :define_method, name do var end
Symbol|String|Integer|true|false|nil===var or fail #so inspect works as a quoting
eval "def res.#{name}; #{var.inspect} end"
}}
old_exemplars.replace exemplars
=end
end
def enumerate_exemplars
@exemplars||= build_exemplars
end
def build_exemplars
exemplars=[[self]]
(boolean_identity_params.merge identity_params).each{|name,variations|
todo=[]
variations=variations.dup
variations.each{|var|
exemplars.each{|exm|
res=exm.dup
#res.send name+"=", var
#res.send :define_method, name do var end
Symbol|String|Integer|true|false|nil===var or fail #so inspect works as a quoting
#eval "def res.#{name}; #{var.inspect} end"
res.push name, var
todo<<res #unless exemplars.include? res
}
}
exemplars=todo
}
#by now, may be some exemplars with identical identities...
#those duplicate identities should be culled
# identities_seen={}
# exemplars.delete_if{|ex|
# idn=ex.identity_name
# chuck_it=identities_seen[idn]
# identities_seen[idn]=true
# chuck_it
# }
return exemplars
end
attr_writer :boolean_identity_params, :identity_params
def identity_params
return @identity_params if defined?(@identity_params) and @identity_params
@identity_params=
if superclass.respond_to? :identity_params
superclass.identity_params.dup
else
{}
end
end
def boolean_identity_params
return @boolean_identity_params if defined?(@boolean_identity_params) and @boolean_identity_params
@boolean_identity_params=
if superclass.respond_to? :boolean_identity_params
superclass.boolean_identity_params.dup
else
{}
end
end
end #of Meta
def identity_name
k=self.class
list=[k.name]
list.concat k.boolean_identity_params.map{|(bip,*)| bip if send(bip) }.compact
list.concat k.identity_params.map{|(ip,variations)|
val=send(ip)
variations.include? val or fail "identity_param #{k}##{ip} unexpected value #{val.inspect}"
[ip,val]
}.flatten
result=list.join("_")
return result
end
end
class Token
include Stackable
extend Stackable::Meta
def image; "#{inspect}" end
def to_parsetree(*options) #this shouldn't be needed anymore
o={}
[:newlines,:quirks,:ruby187].each{|opt|
o[opt]=true if options.include? opt
}
result=[parsetree(o)]
result=[] if result==[[]]
return result
end
def lvalue; nil end
def data; [self] end
def unary; false end
def rescue_parsetree(o); parsetree(o) end
def begin_parsetree(o); parsetree(o) end
#attr :line
#alias endline line
#attr_writer :startline
#def startline
# @startline||=endline
#end
end
class KeywordToken
def not_real!
@not_real=true
end
def not_real?
@not_real if defined? @not_real
end
identity_param :ident, *%w<+@ -@ unary& unary* ! ~ not defined?>+ #should be unary ops
%w<end ( ) { } [ ] alias undef in>+
%w<? : ; !~ lhs, rhs, rescue3>+ #these should be ops
%w{*= **= <<= >>= &&= ||= |= &= ^= /= %= -= += = => ... .. . ::}+ #shouldn't be here, grrr
RubyLexer::FUNCLIKE_KEYWORDLIST+
RubyLexer::VARLIKE_KEYWORDLIST+
RubyLexer::INNERBOUNDINGWORDLIST+
RubyLexer::BINOPWORDLIST+
RubyLexer::BEGINWORDLIST
#identity_param :unary, true,false,nil
#identity_param :tag, :lhs,:rhs,:param,:call,:array,:block,:nested,nil
identity_param :callsite?, nil, true, false
identity_param :not_real?, nil, true, false
identity_param :infix, nil, true
alias image ident
#KeywordToken#as/infix should be in rubylexer
alias old_as as
def as
if tag and ident[/^[,*&]$/]
tag.to_s+ident
else old_as
end
end
def infix
@infix if defined? @infix
end unless allocate.respond_to? :infix
end
class OperatorToken
identity_param :ident, *%w[+@ -@ unary& unary* lhs* ! ~ not defined? * ** + -
< << <= <=> > >= >> =~ == ===
% / & | ^ != !~ = => :: ? : , ; . .. ...
*= **= <<= >>= &&= ||= && ||
&= |= ^= %= /= -= += and or
]+RubyLexer::OPORBEGINWORDLIST+%w<; lhs, rhs, rescue3>
#identity_param :unary, true,false,nil
#identity_param :tag, :lhs,:rhs,:param,:call,:array,:block,:nested,nil
end
class NumberToken
alias to_lisp to_s
def negative; /\A-/ === ident end unless allocate.respond_to? :negative
identity_param :negative, true,false
end
class MethNameToken
alias to_lisp to_s
def has_equals; /#{LETTER_DIGIT}=$/o===ident end unless allocate.respond_to? :has_equals
identity_param :has_equals, true,false
end
class VarNameToken #none of this should be necessary now
include FlattenedIvars
alias image ident
alias == flattened_ivars_equal?
def parsetree(o)
type=case ident[0]
when ?$
case ident[1]
when ?1..?9; return [:nth_ref,ident[1..-1].to_i]
when ?&,?+,?`,?'; return [:back_ref,ident[1].chr.to_sym] #`
else :gvar
end
when ?@
if ident[1]==?@
:cvar
else
:ivar
end
when ?A..?Z; :const
else
case lvar_type
when :local; :lvar
when :block; :dvar
when :current; :dvar#_curr
else fail
end
end
return [type,ident.to_sym]
end
def varname2assigntype
case ident[0]
when ?$; :gasgn
when ?@;
if ident[1]!=?@; :iasgn
elsif in_def; :cvasgn
else :cvdecl
end
when ?A..?Z; :cdecl
else
case lvar_type
when :local; :lasgn
when :block; :dasgn
when :current; :dasgn_curr
else fail
end
end
end
def lvalue_parsetree(o)
[varname2assigntype, ident.to_sym]
end
def old_unused_lvalue #i think this is the correct way, but its overridded below
return @lvalue if defined? @lvalue
@lvalue=true
end
def all_current_lvars
lvar_type==:current ? [ident] : []
end
attr_accessor :endline,:lvalue
def dup
result=super
result.ident=@ident.dup
return result
end
public :remove_instance_variable
def unparse o=default_unparse_options; ident end
alias lhs_unparse unparse
def delete_extraneous_ivars!
huh
end
def walk
yield nil,nil,nil,self
end
end
class StringToken
attr :char unless allocate.respond_to? :char
end
class HerePlaceholderToken
attr_accessor :node
attr :string unless allocate.respond_to? :string
end
module ListInNode
def []=(*args)
val=args.pop
#inline symbols as callnodes
case val
when Symbol
val=CallNode[nil,val.to_s]
when Integer,Float
val=LiteralNode[val]
end
super( *args<<val )
end
end
class Node<Array
include Stackable
extend Stackable::Meta
include FlattenedIvars
def initialize(*data)
replace data
end
def initialize_ivars
@offset||=0
@startline||=0
@endline||=0
end
def self.create(*args)
new(*args)
end
def ==(other)
super and flattened_ivars_equal?(other)
end
def +(other)
if SequenceNode===other
SequenceNode[self,*other]
else
SequenceNode[self,other]
end
end
alias original_brackets_assign []= #needed by LiteralNode
def []=(*args)
val=args.pop
#inline symbols as callnodes
case val
when Symbol
val=CallNode[nil,val.to_s]
when Integer,Float
val=LiteralNode[val]
end
super( *args<<val )
end
def image; "(#{inspect})" end
def error? x; false end
@@data_warned=nil
def data
unless @@data_warned
warn "using obsolete Node#data from #{caller.first}"
@@data_warned=true
end
Array.new(self)
end
alias unwrap data
attr_writer :startline
def startline
@startline||=endline
end
attr_accessor :endline
attr_accessor :errors
attr_reader :offset
def self.inline_symbols data
data.map!{|datum|
Symbol===datum ?
CallNode[nil,datum.to_s,nil,nil,nil] :
datum
}
end
def self.[](*data)
options=data.pop if Hash===data.last
inline_symbols data
result=allocate
result.instance_eval{
replace data
options.each_pair{|name,val|
instance_variable_set name,val
} if options
}
result.initialize_ivars
return result
end
def inspect label=nil,indent=0,verbose=false
ivarnames=instance_variables-FlattenedIvars::EXCLUDED_IVARS
ivarnodes=[]
ivars=ivarnames.map{|ivarname|
ivar=instance_variable_get(ivarname)
if Node===ivar
ivarnodes.push [ivarname,ivar]
nil
else
ivarname[1..-1]+"="+ivar.inspect if ivar and verbose
end
}.compact.join(' ')
if verbose
pos=@startline.to_s
pos<<"..#@endline" if @endline!=@startline
pos<<"@#@offset"
end
classname=self.class.name
classname.sub!(/^(?:RedParse::)?(.*?)(?:Node)?$/){$1}
result= [' '*indent,"+",(label+': ' if label),classname,]
result+=[" pos=",pos,] if pos
result+=[" ",ivars,"\n"]
indent+=2
namelist=self.class.namelist
if namelist and !namelist.empty?
namelist.each{|name|
val=send name rescue "{{ERROR INSPECTING ATTR #{name}}}"
case val
when Node; result<< val.inspect(name,indent,verbose)
when ListInNode
result.push ' '*indent,"+#{name}:\n",*val.map{|v|
v.inspect(nil,indent+2,verbose) rescue ' '*(indent+2)+"-#{v.inspect}\n"
}
when nil;
else ivars<< " #{name}=#{val.inspect}"
end
}
else
each{|val|
case val
when Node; result<< val.inspect(nil,indent,verbose)
else result<< ' '*indent+"-#{val.inspect}\n"
end
}
end
ivarnodes.each{|(name,val)|
result<< val.inspect(name,indent)
}
return result.join
end
def evalable_inspect
ivarnames=instance_variables-["@data", :@data]
ivars=ivarnames.map{|ivarname|
val=instance_variable_get(ivarname)
if val.respond_to?(:evalable_inspect)
val=val.evalable_inspect
else
val=val.inspect
end
":"+ivarname+"=>"+val
}.join(', ')
bare="["+map{|val|
if val.respond_to?(:evalable_inspect)
val=val.evalable_inspect
else
val=val.inspect
end
}.join(", ")+"]"
bare.gsub!(/\]\Z/, ", {"+ivars+"}]") unless ivarnames.empty?
return self.class.name+bare
end
def pretty_print(q)
ivarnames=instance_variables-["@data", :@data]
ivars={}
ivarnames.each{|ivarname|
ivars[ivarname.to_sym]=instance_variable_get(ivarname)
}
q.group(1, self.class.name+'[', ']') {
displaylist= ivars.empty? ? self : dup<<ivars
q.seplist(displaylist) {|v|
q.pp v
}
# q.text ', '
# q.pp_hash ivars
}
end
def self.param_names(*names)
accessors=[]
namelist=[]
@namelist=[]
names.each{|name|
name=name.to_s
last=name[-1]
name.chomp! '!' and name << ?_
namelist << name
unless last==?_
accessors << "def #{name.chomp('_')}; self[#{@namelist.size}] end\n"
accessors << "def #{name.chomp('_')}=(newval); "+
"newval.extend ::RedParse::ListInNode if ::Array===newval and not RedParse::Node===newval;"+
"self[#{@namelist.size}]=newval "+
"end\n"
@namelist << name
end
}
init="
def initialize(#{namelist.join(', ')})
replace [#{@namelist.size==1 ?
@namelist.first :
@namelist.join(', ')
}]
end
alias init_data initialize
"
code= "class ::#{self}\n"+init+accessors.join+"\nend\n"
if defined? DEBUGGER__ or defined? Debugger
Tempfile.open("param_name_defs"){|f|
f.write code
f.flush
load f.path
}
else
eval code
end
@namelist.reject!{|name| /_\Z/===name }
end
def self.namelist
#@namelist
result=superclass.namelist||[] rescue []
result.concat @namelist if defined? @namelist
return result
end
def lhs_unparse o; unparse(o) end
def to_parsetree(*options)
o={}
[:newlines,:quirks,:ruby187].each{|opt|
o[opt]=true if options.include? opt
}
result=[parsetree(o)]
result=[] if result==[[]] || result==[nil]
return result
end
def to_parsetree_and_warnings(*options)
#for now, no warnings are ever output
return to_parsetree(*options),[]
end
def parsetree(o)
"wrong(#{inspect})"
end
def rescue_parsetree(o); parsetree(o) end
def begin_parsetree(o); parsetree(o) end
def parsetrees list,o
!list.empty? and list.map{|node| node.parsetree(o)}
end
def negate(condition,offset=nil)
if UnOpNode===condition and condition.op.ident[/^(!|not)$/]
condition.val
else
UnOpNode.new(KeywordToken.new("not",offset),condition)
end
end
#callback takes four parameters:
#parent of node currently being walked, index and subindex within
#that parent, and finally the actual node being walked.
def walk(parent=nil,index=nil,subindex=nil,&callback)
callback[ parent,index,subindex,self ] and
each_with_index{|datum,i|
case datum
when Node; datum.walk(self,i,&callback)
when Array;
datum.each_with_index{|x,j|
Node===x ? x.walk(self,i,j,&callback) : callback[self,i,j,x]
}
else callback[self,i,nil,datum]
end
}
end
def depthwalk(parent=nil,index=nil,subindex=nil,&callback)
(size-1).downto(0){|i|
datum=self[i]
case datum
when Node
datum.depthwalk(self,i,&callback)
when Array
(datum.size-1).downto(0){|j|
x=datum[j]
if Node===x
x.depthwalk(self,i,j,&callback)
else
callback[self,i,j,x]
end
}
else
callback[self, i, nil, datum]
end
}
callback[ parent,index,subindex,self ]
end
def depthwalk_nodes(parent=nil,index=nil,subindex=nil,&callback)
(size-1).downto(0){|i|
datum=self[i]
case datum
when Node
datum.depthwalk_nodes(self,i,&callback)
when Array
(datum.size-1).downto(0){|j|
x=datum[j]
if Node===x
x.depthwalk_nodes(self,i,j,&callback)
end
}
end
}
callback[ parent,index,subindex,self ]
end
def add_parent_links!
walk{|parent,i,subi,o|
o.parent=parent if Node===o
}
end
attr_accessor :parent
def xform_tree!(*xformers)
#search tree for patterns and store results of actions in session
session={}
depthwalk{|parent,i,subi,o|
xformers.each{|xformer|
if o
tempsession={}
xformer.xform!(o,tempsession)
merge_replacement_session session, tempsession
#elsif xformer===o and Reg::Transform===xformer
# new=xformer.right
# if Reg::Formula===right
# new=new.formula_value(o,session)
# end
# subi ? parent[i][subi]=new : parent[i]=new
end
}
}
session["final"]=true
#apply saved-up actions stored in session, while making a copy of tree
result=::Ron::GraphWalk::graphcopy(self,old2new={}){|cntr,o,i,ty,useit|
newo=nil
replace_value o.__id__,o,session do |val|
newo=val
useit[0]=true
end
newo
}
finallys=session["finally"] #finallys too
finallys.each{|(action,arg)| action[old2new[arg.__id__],session] } if finallys
return result
=begin was
finallys=session["finally"]
finallys.each{|(action,arg)| action[arg] } if finallys
depthwalk{|parent,i,subi,o|
next unless parent
replace_ivars_and_self o, session do |new|
subi ? parent[i][subi]=new : parent[i]=new
end
}
replace_ivars_and_self self,session do |new|
fail unless new
return new
end
return self
=end
end
def rgrep pattern
result=grep(pattern)
each{|subnode| result.concat subnode.rgrep(pattern) if subnode.respond_to? :rgrep}
return result
end
def rfind ifnone=nil, &block
result=find(proc{
find{|subnode| subnode.rfind(&block) if subnode.respond_to? :rfind}
},&block)
return result if result
return ifnone[] if ifnone
end
def rfind_all &block
result=find_all(&block)
each{|subnode| result.concat subnode.find_all(&block) if subnode.respond_to? :rfind_all}
return result
end
def replace_ivars_and_self o,session,&replace_self_action
o.instance_variables.each{|ovname|
ov=o.instance_variable_get(ovname)
replace_value ov.__id__,ov,session do |new|
o.instance_variable_set(ovname,new)
end
}
replace_value o.__id__,o,session, &replace_self_action
end
def replace_value ovid,ov,session,&replace_action
if session.has_key? ovid
new= session[ovid]
if Reg::Formula===new
new=new.formula_value(ov,session)
end
replace_action[new]
end
end
def merge_replacement_session session,tempsession
ts_has_boundvars= !tempsession.keys.grep(::Symbol).empty?
tempsession.each_pair{|k,v|
if Integer===k
if true
v=Reg::WithBoundRefValues.new(v,tempsession) if ts_has_boundvars
else
v=Ron::GraphWalk.graphcopy(v){|cntr,o,i,ty,useit|
if Reg::BoundRef===o
useit[0]=true
tempsession[o.name]||o
end
}
end
if session.has_key? k
v=v.chain_to session[k]
end
session[k]=v
elsif "finally"==k
session["finally"]=Array(session["finally"]).concat v
end
}
end
def linerange
min=9999999999999999999999999999999999999999999999999999
max=0
walk{|parent,i,subi,node|
if node.respond_to? :endline and line=node.endline
min=[min,line].min
max=[max,line].max
end
}
return min..max
end
def fixup_multiple_assignments! #dead code
result=self
walk{|parent,i,subi,node|
if CommaOpNode===node
#there should be an assignnode within this node... find it
j=nil
list=Array.new(node)
assignnode=nil
list.each_with_index{|assignnode2,jj| assignnode=assignnode2
AssignNode===assignnode and break(j=jj)
}
fail "CommaOpNode without any assignment in final parse tree" unless j
#re-hang the current node with = at the top
lhs=list[0...j]<<list[j].left
rhs=list[j+1..-1].unshift list[j].right
if lhs.size==1 and MultiAssign===lhs.first
lhs=lhs.first
else
lhs=MultiAssign.new(lhs)
end
node=AssignNode.new(lhs, assignnode.op, rhs)
#graft the new node back onto the old tree
if parent
if subi
parent[i][subi]=node
else
parent[i]=node
end
else #replacement at top level
result=node
end
#re-scan newly made node, since we tell caller not to scan our children
node.fixup_multiple_assignments!
false #skip (your old view of) my children, please
else
true
end
}
return result
end
def prohibit_fixup x
case x
when UnaryStarNode; true
# when ParenedNode; x.size>1
when CallSiteNode; x.params and !x.real_parens
else false
end
end
def fixup_rescue_assignments! #dead code
result=self
walk{|parent,i,subi,node|
#if a rescue op with a single assignment on the lhs
if RescueOpNode===node and assign=node.first and #ick
AssignNode===assign and assign.op.ident=="=" and
!(assign.multi? or
prohibit_fixup assign.right)
#re-hang the node with = at the top instead of rescue
node=AssignNode.new(assign.left, assign.op,
RescueOpNode.new(assign.right,nil,node[1][0].action)
)
#graft the new node back onto the old tree
if parent
if subi
parent[i][subi]=node
else
parent[i]=node
end
else #replacement at top level
result=node
end
#re-scan newly made node, since we tell caller not to scan our children
node.fixup_rescue_assignments!
false #skip (your old view of) my children, please
else
true
end
}
return result
end
def lvars_defined_in
result=[]
walk {|parent,i,subi,node|
case node
when MethodNode,ClassNode,ModuleNode,MetaClassNode; false
when CallSiteNode
Node===node.receiver and
result.concat node.receiver.lvars_defined_in
node.args.each{|arg|
result.concat arg.lvars_defined_in if Node===arg
} if node.args
false
when AssignNode
lvalue=node.left
lvalue.respond_to? :all_current_lvars and
result.concat lvalue.all_current_lvars
true
when ForNode
lvalue=node.for
lvalue.respond_to? :all_current_lvars and
result.concat lvalue.all_current_lvars
true
when RescueOpNode,BeginNode
rescues=node[1]
rescues.each{|resc|
name=resc.varname
name and result.push name.ident
}
true
else true
end
}
result.uniq!
return result
end
def unary; false end
def lvalue; nil end
#why not use Ron::GraphWalk.graph_copy instead here?
def deep_copy transform={},&override
handler=proc{|child|
if transform.has_key? child.__id__
transform[child.__id__]
else
case child
when Node
override&&override[child] or
child.deep_copy(transform,&override)
when Array
child.clone.map!(&handler)
when Integer,Symbol,Float,nil,false,true,Module
child
else
child.clone
end
end
}
newdata=map(&handler)
result=clone
instance_variables.each{|iv|
unless iv=="@data" or iv==:@data
val=instance_variable_get(iv)
result.instance_variable_set(iv,handler[val])
end
}
result.replace newdata
return result
end
def delete_extraneous_ivars!
walk{|parent,i,subi,node|
case node
when Node
node.remove_instance_variable :@offset rescue nil
node.remove_instance_variable :@loopword_offset rescue nil
node.remove_instance_variable :@iftok_offset rescue nil
node.remove_instance_variable :@endline rescue nil
node.remove_instance_variable :@lvalue rescue nil
if node.respond_to? :lvalue
node.lvalue or
node.remove_instance_variable :@lvalue rescue nil
end
when Token
print "#{node.inspect} in "; pp parent
fail "no tokens should be present in final parse tree (maybe except VarNameToken, ick)"
end
true
}
return self
end
def delete_linenums!
walk{|parent,i,subi,node|
case node
when Node
node.remove_instance_variable :@endline rescue nil
node.remove_instance_variable :@startline rescue nil
end
true
}
return self
end
public :remove_instance_variable
#convert to a Reg::Array expression. subnodes are also converted.
#if any matchers are present in the tree, they will be included
#directly into the enclosing Node's matcher.
#this can be a nice way to turn a (possibly deeply nested) node
#tree into a matcher.
#note: anything stored in instance variables is ignored in the
#matcher.
def +@
node2matcher=proc{|n|
case n
when Node; +n
when Array; +[*n.map(&node2matcher)]
else n
end
}
return +[*map(&node2matcher)] & self.class
end
private
#turn a list (array) of arrays into a linked list, in which each array
#has a reference to the next in turn as its last element.
def linked_list(arrays)
0.upto(arrays.size-2){|i| arrays[i]<<arrays[i+1] }
return arrays.first
end
def param_list_walk(param_list)
param_list or return
limit=param_list.size
i=0
normals=[]
lownormal=nil
handle_normals=proc{
yield '',normals,lownormal..i-1 if lownormal
lownormal=nil
normals.slice! 0..-1
}
while i<limit
case param=param_list[i]
when ArrowOpNode
handle_normals[]
low=i
i+=1 while ArrowOpNode===param_list[i]
high=i-1
yield '=>',param_list[low..high],low..high
when UnaryStarNode
handle_normals[]
yield '*',param,i
when UnOpNode&-{:op=>"&@"}
handle_normals[]
yield '&',param,i
else
lownormal=i unless lownormal
normals << param
end
i+=1
end
handle_normals[]
end
def param_list_parse(param_list,o)
output=[]
star=amp=nil
param_list_walk(param_list){|type,val,i|
case type
when ''
output.concat val.map{|param| param.rescue_parsetree(o)}
when '=>'
output.push HashLiteralNode.new(nil,val,nil).parsetree(o)
when '*'; star=val.parsetree(o)
when '&'; amp=val.parsetree(o)
end
}
return output,star,amp
end
def unparse_nl(token,o,alt=';',nl="\n")
#should really only emit newlines
#to bring line count up to startline, not endline.
linenum=
case token
when Integer; token
when nil; return alt
else token.startline rescue (return alt)
end
shy=(linenum||0)-o[:linenum]
#warn if shy<0 ???
return alt if shy<=0
o[:linenum]=linenum
return nl*shy
end
def default_unparse_options
{:linenum=>1}
end
end
class ValueNode<Node
def lvalue; nil end
#identity_param :lvalue, nil, true
end
class VarNode<ValueNode
param_names :ident
include FlattenedIvars
attr_accessor :endline,:offset
attr_reader :lvar_type,:in_def
attr_writer :lvalue
alias == flattened_ivars_equal?
def initialize(tok)
super(tok.ident)
@lvar_type=tok.lvar_type
@offset=tok.offset
@endline=@startline=tok.endline
@in_def=tok.in_def
end
# def ident; first end
# def ident=x; self[0]=x end
alias image ident
alias startline endline
alias name ident
alias name= ident=
def parsetree(o)
type=case ident[0]
when ?$
case ident[1]
when ?1..?9; return [:nth_ref,ident[1..-1].to_i]
when ?&,?+,?`,?'; return [:back_ref,ident[1].chr.to_sym] #`
else :gvar
end
when ?@
if ident[1]==?@
:cvar
else
:ivar
end
when ?A..?Z; :const
else
case lvar_type
when :local; :lvar
when :block; :dvar
when :current; :dvar#_curr
else fail
end
end
return [type,ident.to_sym]
end
def varname2assigntype
case ident[0]
when ?$; :gasgn
when ?@
if ident[1]!=?@; :iasgn
elsif in_def; :cvasgn
else :cvdecl
end
when ?A..?Z; :cdecl
else
case lvar_type
when :local; :lasgn
when :block; :dasgn
when :current; :dasgn_curr
else fail
end
end
end
def lvalue_parsetree(o)
[varname2assigntype, ident.to_sym]
end
alias to_lisp to_s
def lvalue
return @lvalue if defined? @lvalue
@lvalue=true
end
identity_param :lvalue, nil, true
def all_current_lvars
lvar_type==:current ? [ident] : []
end
def dup
result=super
result.ident=ident.dup if ident
return result
end
public :remove_instance_variable
def unparse o=default_unparse_options; ident end
alias lhs_unparse unparse
if false
def walk #is this needed?
yield nil,nil,nil,self
end
end
end
#forward decls
class RawOpNode<ValueNode
end
class OpNode<RawOpNode
end
class NotEqualNode<OpNode
end
class MatchNode<OpNode
end
class NotMatchNode<OpNode
end
class ArrowOpNode<RawOpNode
end
class RescueOpNode<RawOpNode
end
class LogicalNode<RawOpNode
end
class AndNode<LogicalNode
end
class OrNode<LogicalNode
end
class RangeNode<RawOpNode
end
class IfOpNode<RawOpNode
end
class UnlessOpNode<RawOpNode
end
class WhileOpNode<RawOpNode
end
class UntilOpNode<RawOpNode
end
OP2CLASS={
"!="=>NotEqualNode,
"!~"=>NotMatchNode,
"=~"=>MatchNode,
"if"=>IfOpNode,
"unless"=>UnlessOpNode,
"while"=>WhileOpNode,
"until"=>UntilOpNode,
".."=>RangeNode,
"..."=>RangeNode,
"=>"=>ArrowOpNode,
"&&"=>AndNode,
"||"=>OrNode,
"and"=>AndNode,
"or"=>OrNode,
"rescue"=>RescueOpNode,
"rescue3"=>RescueOpNode,
}
class RawOpNode<ValueNode
param_names(:left,:op,:right)
def initialize(left,op,right=nil)
op,right=nil,op if right.nil?
if op.respond_to? :ident
@offset=op.offset
op=op.ident
end
super(left,op,right)
end
# def initialize_copy other
# rebuild(other.left,other.op,other.right)
# end
def self.create(left,op,right)
op_s=op.ident
k=OP2CLASS[op_s]||OpNode
k.new(left,op,right)
end
def image; "(#{op})" end
def raw_unparse o
l=left.unparse(o)
l[/(~| \Z)/] and maybesp=" "
[l,op,maybesp,right.unparse(o)].to_s
end
end
class OpNode<RawOpNode
def initialize(left,op,right)
#@negative_of="="+$1 if /^!([=~])$/===op
op=op.ident if op.respond_to? :ident
super left,op,right
end
def to_lisp
"(#{op} #{left.to_lisp} #{right.to_lisp})"
end
def parsetree(o)
[:call,
left.rescue_parsetree(o),
op.to_sym,
[:array, right.rescue_parsetree(o)]
]
end
alias opnode_parsetree parsetree
def unparse o=default_unparse_options
result=l=left.unparse(o)
result+=" " if /\A(?:!|#{LCLETTER})/o===op
result+=op
result+=" " if /#{LETTER_DIGIT}\Z/o===op or / \Z/===l
result+=right.unparse(o)
end
# def unparse o=default_unparse_options; raw_unparse o end
end
class MatchNode<OpNode
param_names :left,:op_,:right
def initialize(left,op,right=nil)
op,right=nil,op unless right
replace [left,right]
end
def parsetree(o)
if StringNode===left and left.char=='/'
[:match2, left.parsetree(o), right.parsetree(o)]
elsif StringNode===right and right.char=='/'
[:match3, right.parsetree(o), left.parsetree(o)]
else
super
end
end
def op; "=~"; end
end
class NotEqualNode<OpNode
param_names :left,:op_,:right
def initialize(left,op,right=nil)
op,right=nil,op unless right
replace [left,right]
end
def parsetree(o)
result=opnode_parsetree(o)
result[2]="=#{op[1..1]}".to_sym
result=[:not, result]
return result
end
def op; "!="; end
end
class NotMatchNode<OpNode
param_names :left,:op_,:right
def initialize(left,op,right=nil)
op,right=nil,op unless right
replace [left,right]
end
def parsetree(o)
if StringNode===left and left.char=="/"
[:not, [:match2, left.parsetree(o), right.parsetree(o)]]
elsif StringNode===right and right.char=="/"
[:not, [:match3, right.parsetree(o), left.parsetree(o)]]
else
result=opnode_parsetree(o)
result[2]="=#{op[1..1]}".to_sym
result=[:not, result]
end
end
def op; "!~"; end
end
class ListOpNode<ValueNode #abstract
def initialize(val1,op,val2)
list=if self.class===val1
Array.new(val1)
else
[val1]
end
if self.class===val2
list.push( *val2 )
elsif val2
list.push val2
end
super( *list )
end
end
class CommaOpNode<ListOpNode #not to appear in final tree
def image; '(,)' end
def to_lisp
"(#{map{|x| x.to_lisp}.join(" ")})"
end
def lvalue
return @lvalue if defined? @lvalue
@lvalue=true
end
attr_writer :lvalue
identity_param :lvalue, nil, true
def extract_unbraced_hash
param_list=Array.new(self)
first=last=nil
param_list.each_with_index{|param,i|
break first=i if ArrowOpNode===param
}
(1..param_list.size).each{|i| param=param_list[-i]
break last=-i if ArrowOpNode===param
}
if first
arrowrange=first..last
arrows=param_list[arrowrange]
h=HashLiteralNode.new(nil,arrows,nil)
h.offset=arrows.first.offset
h.startline=arrows.first.startline
h.endline=arrows.last.endline
return h,arrowrange
end
end
end
class LiteralNode<ValueNode; end
class StringNode<ValueNode; end
class StringCatNode < ValueNode; end
class NopNode<ValueNode; end
class VarLikeNode<ValueNode; end #nil,false,true,__FILE__,__LINE__,self
class SequenceNode<ListOpNode
def initialize(*args)
super
@offset=self.first.offset
end
def +(other)
if SequenceNode===other
dup.push( *other )
else
dup.push other
end
end
def []=(*args)
val=args.pop
if SequenceNode===val
val=Array.new(val)
#munge args too
if args.size==1 and Integer===args.first
args<<1
end
end
super( *args<<val )
end
def image; '(;)' end
def to_lisp
"#{map{|x| x.to_lisp}.join("\n")}"
end
def to_lisp_with_parens
"(#{to_lisp})"
end
LITFIX=LiteralNode&-{:val=>Fixnum}
LITRANGE=RangeNode&-{:left=>LITFIX,:right=>LITFIX}
LITSTR=StringNode&-{:size=>1,:char=>/^[^`\[{]$/}
#LITCAT=proc{|item| item.grep(~LITSTR).empty?}
#class<<LITCAT; alias === call; end
LITCAT=StringCatNode& item_that.grep(~LITSTR).empty? #+[LITSTR.+]
LITNODE=LiteralNode|NopNode|LITSTR|LITCAT|LITRANGE|(VarLikeNode&-{:name=>/^__/})
#VarNode| #why not this too?
def parsetree(o)
data=compact
data.empty? and return
items=Array.new(data[0...-1])
if o[:quirks]
items.shift while LITNODE===items.first
else
items.reject!{|expr| LITNODE===expr }
end
items.map!{|expr| expr.rescue_parsetree(o)}.push last.parsetree(o)
# items=map{|expr| expr.parsetree(o)}
items.reject!{|expr| []==expr }
if o[:quirks]
unless BeginNode===data[0]
header=items.first
(items[0,1] = *header[1..-1]) if header and header.first==:block
end
else
(items.size-1).downto(0){|i|
header=items[i]
(items[i,1] = *header[1..-1]) if header and header.first==:block
}
end
if items.size>1
items.unshift :block
elsif items.size==1
items.first
else
items
end
end
def unparse o=default_unparse_options
return "" if empty?
unparse_nl(first,o,'')+first.unparse(o)+
self[1..-1].map{|expr|
unparse_nl(expr,o)+expr.unparse(o)
}.join
end
end
class StringCatNode < ValueNode
def initialize(*strses)
strs=strses.pop.unshift( *strses )
hd=strs.shift if HereDocNode===strs.first
strs.map!{|str| StringNode.new(str)}
strs.unshift hd if hd
super( *strs )
end
def parsetree(o)
result=map{|str| str.parsetree(o)}
sum=''
type=:str
tree=i=nil
result.each_with_index{|tree2,i2| tree,i=tree2,i2
sum+=tree[1]
tree.first==:str or break(type=:dstr)
}
[type,sum,*tree[2..-1]+result[i+1..-1].inject([]){|cat,x|
if x.first==:dstr
x.shift
x0=x[0]
if x0=='' and x.size==2
x.shift
else
x[0]=[:str,x0]
end
cat+x
elsif x.last.empty?
cat
else
cat+[x]
end
}
]
end
def unparse o=default_unparse_options
map{|ss| ss.unparse(o)}.join ' '
end
end
class ArrowOpNode
param_names(:left,:op,:right)
def initialize(*args)
super
end
#def unparse(o=default_unparse_options)
# left.unparse(o)+" => "+right.unparse(o)
#end
end
class RangeNode
param_names(:first,:op,:last)
def initialize(left,op,right=nil)
op,right="..",op unless right
op=op.ident if op.respond_to? :ident
@exclude_end=!!op[2]
@as_flow_control=false
super(left,op,right)
end
def begin; first end
def end; last end
def left; first end
def right; last end
def exclude_end?; @exclude_end end
# def self.[] *list
# result=RawOpNode[*list]
# result.extend RangeNode
# return result
# end
def self.[] *list
new(*list)
end
def parsetree(o)
first=first().parsetree(o)
last=last().parsetree(o)
if @as_flow_control
if :lit==first.first and Integer===first.last
first=[:call, [:lit, first.last], :==, [:array, [:gvar, :$.]]]
elsif :lit==first.first && Regexp===first.last or
:dregx==first.first || :dregx_once==first.first
first=[:match, first]
end
if :lit==last.first and Integer===last.last
last=[:call, [:lit, last.last], :==, [:array, [:gvar, :$.]]]
elsif :lit==last.first && Regexp===last.last or
:dregx==last.first || :dregx_once==last.first
last=[:match, last]
end
tag="flip"
else
if :lit==first.first and :lit==last.first and
Fixnum===first.last and Fixnum===last.last and
LiteralNode===first() and LiteralNode===last()
return [:lit, Range.new(first.last,last.last,@exclude_end)]
end
tag="dot"
end
count= @exclude_end ? ?3 : ?2
tag << count
[tag.to_sym, first, last]
end
def special_conditions!
@as_flow_control=true
end
def unparse(o=default_unparse_options)
result=left.unparse(o)+'..'
result+='.' if exclude_end?
result << right.unparse(o)
return result
end
end
class UnOpNode<ValueNode
param_names(:op,:val)
def self.create(op,val)
return UnaryStarNode.new(op,val) if /\*$/===op.ident
return UnaryAmpNode.new(op,val) if /&$/===op.ident
return new(op,val)
end
def initialize(op,val)
@offset||=op.offset rescue val.offset
op=op.ident if op.respond_to? :ident
/([&*])$/===op and op=$1+"@"
/^(?:!|not)$/===op and
val.respond_to? :special_conditions! and
val.special_conditions!
super(op,val)
end
def arg; val end
def arg= x; self.val=x end
alias ident op
def image; "(#{op})" end
def lvalue
# return nil unless op=="*@"
return @lvalue if defined? @lvalue
@lvalue=true
end
attr_writer :lvalue
def to_lisp
"(#{op} #{val.to_lisp})"
end
def parsetree(o)
node=self
node=node.val while UnOpNode===node and node.op=="+@"
return node.parsetree(o) if LiteralNode&-{:val=>Integer|Float|Symbol}===node
return node.parsetree(o) if StringNode&-{:char=>'/', :size=>1}===node
case op
when /^&/; [:block_arg, val.ident.to_sym]
when "!","not"; [:not, val.rescue_parsetree(o)]
when "defined?"; [:defined, val.parsetree(o)]
else
[:call, val.rescue_parsetree(o), op.to_sym]
end
end
def lvalue_parsetree(o)
parsetree(o)
end
def unparse o=default_unparse_options
op=op()
op=op.chomp "@"
result=op
result+=" " if /#{LETTER}$/o===op or /^[+-]/===op && LiteralNode===val
result+=val.unparse(o)
end
end
class UnaryAmpNode<UnOpNode
end
class UnaryStarNode<UnOpNode
def initialize(op,val=nil)
op,val="*@",op unless val
op.ident="*@" if op.respond_to? :ident
super(op,val)
end
class<<self
alias [] new
end
def parsetree(o)
[:splat, val.rescue_parsetree(o)]
end
def all_current_lvars
val.respond_to?(:all_current_lvars) ?
val.all_current_lvars : []
end
attr_accessor :after_comma
def lvalue_parsetree o
val.lvalue_parsetree(o)
end
identity_param :lvalue, nil, true
def unparse o=default_unparse_options
"*"+val.unparse(o)
end
end
class DanglingStarNode<UnaryStarNode
#param_names :op,:val
def initialize(star,var=nil)
@offset= star.offset if star.respond_to? :offset
@startline=@endline=star.startline if star.respond_to? :startline
super('*@',var||VarNode[''])
end
attr :offset
def lvars_defined_in; [] end
def parsetree(o); [:splat] end
alias lvalue_parsetree parsetree
def unparse(o=nil); "* "; end
end
class DanglingCommaNode<DanglingStarNode
def initialize
end
attr_accessor :offset
def lvalue_parsetree o
:dangle_comma
end
alias parsetree lvalue_parsetree
def unparse o=default_unparse_options; ""; end
end
class ConstantNode<ListOpNode
def initialize(*args)
@offset=args.first.offset
args.unshift nil if args.size==2
args.map!{|node|
if VarNode===node and (?A..?Z)===node.ident[0]
then node.ident
else node
end
}
super(*args)
end
def unparse(o=default_unparse_options)
if Node===first
result=dup
result[0]= first.unparse(o)#.gsub(/\s+\Z/,'')
result.join('::')
else join('::')
end
end
alias image unparse
def lvalue_parsetree(o)
[:cdecl,parsetree(o)]
end
def parsetree(o)
if !first
result=[:colon3, self[1].to_sym]
i=2
else
result=first.respond_to?(:parsetree) ?
first.parsetree(o) :
[:const,first.to_sym]
i=1
end
(i...size).inject(result){|r,j|
[:colon2, r, self[j].to_sym]
}
end
def lvalue
return @lvalue if defined? @lvalue
@lvalue=true
end
attr_writer :lvalue
identity_param :lvalue, nil, true
def inspect label=nil,indent=0,verbose=false
result=' '*indent
result+="#{label}: " if label
result+='Constant '
unless String===first or nil==first
head=first
rest=self[1..-1]
end
result+=(rest||self).map{|name| name.inspect}.join(', ')+"\n"
result+=head.inspect("head",indent+2,verbose) if head
return result
end
end
LookupNode=ConstantNode
class DoubleColonNode<ValueNode #obsolete
#dunno about this name... maybe ConstantNode?
param_names :namespace, :constant
alias left namespace
alias right constant
def initialize(val1,op,val2=nil)
val1,op,val2=nil,val1,op unless val2
val1=val1.ident if VarNode===val1 and /\A#{UCLETTER}/o===val1.ident
val2=val2.ident if VarNode===val1 and /\A#{UCLETTER}/o===val2.ident
replace [val1,val2]
end
def image; '(::)' end
def parsetree(o)
if namespace
ns= (String===namespace) ? [:const,namespace.to_sym] : namespace.parsetree(o)
[:colon2, ns, constant.to_sym]
else
[:colon3, constant.to_sym]
end
end
def lvalue_parsetree(o)
[:cdecl,parsetree(o)]
end
def lvalue
return @lvalue if defined? @lvalue
@lvalue=true
end
attr_writer :lvalue
end
class DotCallNode<ValueNode #obsolete
param_names :receiver,:dot_,:callsite
def image; '(.)' end
def to_lisp
"(#{receiver.to_lisp} #{@data.last.to_lisp[1...-1]})"
end
def parsetree(o)
cs=self[1]
cs &&= cs.parsetree(o)
cs.shift if cs.first==:vcall or cs.first==:fcall
[:call, @data.first.parsetree(o), *cs]
end
def lvalue
return @lvalue if defined? @lvalue
@lvalue=true
end
attr_writer :lvalue
end
class ParenedNode<ValueNode
param_names :body
alias val body
alias val= body=
def initialize(lparen,body,rparen)
@offset=lparen.offset
self[0]=body
end
attr_accessor :after_comma, :after_equals
def image; "(#{body.image})" end
def special_conditions!
node=body
node.special_conditions! if node.respond_to? :special_conditions!
end
def to_lisp
huh #what about rescues, else, ensure?
body.to_lisp
end
def op?; false end
def parsetree(o)
body.parsetree(o)
end
def rescue_parsetree o
body.rescue_parsetree o
# result.first==:begin and result=result.last unless o[:ruby187]
# result
end
alias begin_parsetree parsetree
def lvalue
return @lvalue if defined? @lvalue
@lvalue=true
end
attr_writer :lvalue
identity_param :lvalue, nil, true
def unparse(o=default_unparse_options)
"(#{body&&body.unparse(o)})"
end
end
module HasRescue
def parsetree_and_rescues(o)
body=body()
target=result=[] #was: [:begin, ]
#body,rescues,else_,ensure_=*self
target.push target=[:ensure, ] if ensure_ or @empty_ensure
rescues=rescues().map{|resc| resc.parsetree(o)}
if rescues.empty?
if else_
body= body ? SequenceNode.new(body,nil,else_) : else_
end
else_=nil
else
target.push newtarget=[:rescue, ]
else_=else_()
end
if body
# needbegin= (BeginNode===body and body.after_equals)
body=body.parsetree(o)
# body=[:begin, body] if needbegin and body.first!=:begin and !o[:ruby187]
(newtarget||target).push body if body
end
target.push ensure_.parsetree(o) if ensure_
target.push [:nil] if @empty_ensure
target=newtarget if newtarget
unless rescues.empty?
target.push linked_list(rescues)
end
target.push else_.parsetree(o) if else_ #and !body
result.size==0 and result=[[:nil]]
if o[:ruby187] and !rescues.empty?
result.unshift :begin
else
result=result.last
end
result
end
def unparse_and_rescues(o)
result=" "
result+= body.unparse(o) if body
result+=unparse_nl(rescues.first,o) if rescues
rescues.each{|resc| result+=resc.unparse(o) } if rescues
result+=unparse_nl(else_,o)+"else "+else_.unparse(o) if else_
result+=";else" if @empty_else
result+=unparse_nl(ensure_,o)+"ensure "+ensure_.unparse(o) if ensure_
result+=";ensure" if @empty_ensure
return result
end
end
class BeginNode<ValueNode
include HasRescue
param_names :body, :rescues, :else!, :ensure!
def initialize(*args)
@offset=args.first.offset
@empty_ensure=@empty_else=@op_rescue=nil
body,rescues,else_,ensure_=*args[1...-1]
rescues.extend ListInNode
if else_
else_=else_.val or @empty_else=true
end
if ensure_
ensure_=ensure_.val or @empty_ensure=true
end
replace [body,rescues,else_,ensure_]
end
def op?; false end
alias ensure_ ensure
alias else_ else
attr_reader :empty_ensure, :empty_else
attr_accessor :after_comma, :after_equals
identity_param :after_equals, nil, true
def image; '(begin)' end
def special_conditions!; nil end
def non_empty
rescues.size > 0 or !!ensures or body
end
identity_param :non_empty, false, true
def to_lisp
huh #what about rescues, else, ensure?
body.to_lisp
end
def parsetree(o)
result=parsetree_and_rescues(o)
if o[:ruby187] and result.first==:begin
result=result[1]
else
result=[:begin,result] unless result==[:nil]#||result.first==:begin
end
return result
end
def rescue_parsetree o
result=parsetree o
result.first==:begin and result=result.last unless o[:ruby187]
result
end
def begin_parsetree(o)
body,rescues,else_,ensure_=*self
needbegin=(rescues&&!rescues.empty?) || ensure_ || @empty_ensure
result=parsetree(o)
needbegin and result=[:begin, result] unless result.first==:begin
result
end
def lvalue
return nil
end
# attr_accessor :lvalue
def unparse(o=default_unparse_options)
result="begin "
result+=unparse_and_rescues(o)
result+=";end"
end
end
module KeywordOpNode
def unparse o=default_unparse_options
[left.unparse(o),' ',op,' ',right.unparse(o)].join
end
end
class RescueOpNode<RawOpNode
include KeywordOpNode
param_names :body, :rescues #, :else!, :ensure!
def initialize(expr,rescueword,backup)
replace [expr,[RescueNode[[],nil,backup]].extend(ListInNode)]
end
def else; nil end
def ensure; nil end
def left; body end
def right; rescues[0].action end
alias ensure_ ensure
alias else_ else
alias empty_ensure ensure
alias empty_else else
attr_accessor :after_equals
def op?; true end
def special_conditions!
nil
end
def to_lisp
huh #what about rescues
body.to_lisp
end
def parsetree(o)
body=body()
target=result=[] #was: [:begin, ]
#body,rescues,else_,ensure_=*self
rescues=rescues().map{|resc| resc.parsetree(o)}
target.push newtarget=[:rescue, ]
else_=nil
needbegin= (BeginNode===body and body.after_equals)
huh if needbegin and RescueOpNode===body #need test case for this
huh if needbegin and ParenedNode===body #need test case for this
body=body.parsetree(o)
body=[:begin, body] if needbegin and body.first!=:begin and !o[:ruby187]
newtarget.push body if body
newtarget.push linked_list(rescues)
result=result.last if result.size==1
# result=[:begin,result]
result
end
def old_rescue_parsetree o
result=parsetree o
result=result.last unless o[:ruby187]
result
end
alias begin_parsetree parsetree
alias rescue_parsetree parsetree
def lvalue
return nil
end
def unparse(o=default_unparse_options)
result= body.unparse(o)
result+=" rescue "
result+=rescues.first.action.unparse(o)
end
end
class AssignmentRhsNode < Node #not to appear in final parse tree
param_names :open_, :val, :close_
def initialize(*args)
if args.size==1; super args.first
else super args[1]
end
end
#WITHCOMMAS=UnaryStarNode|CommaOpNode|(CallSiteNode&-{:with_commas=>true})
def is_list
return !(WITHCOMMAS===val)
=begin
#this should be equivalent, why doesn't it work?
!(UnaryStarNode===val or
CommaOpNode===val or
CallSiteNode===val && val.with_commas==true)
# CallSiteNode===val && !val.real_parens && val.args.size>0
=end
end
identity_param :is_list, true, false
end
class AssignNode<ValueNode
param_names :left,:op,:right
alias lhs left
alias rhs right
def self.create(*args)
if args.size==5
if args[3].ident=="rescue3"
lhs,op,rescuee,op2,rescuer=*args
if MULTIASSIGN===lhs or !rescuee.is_list
return RescueOpNode.new(AssignNode.new(lhs,op,rescuee),nil,rescuer)
else
rhs=RescueOpNode.new(rescuee.val,op2,rescuer)
end
else
lhs,op,bogus1,rhs,bogus2=*args
end
super(lhs,op,rhs)
else super
end
end
def initialize(*args)
if args.size==5
#this branch should be dead now
if args[3].ident=="rescue3"
lhs,op,rescuee,op2,rescuer=*args
if MULTIASSIGN===lhs or rescuee.is_list?
huh
else
rhs=RescueOpNode.new(rescuee.val,op2,rescuer)
end
else
lhs,op,bogus1,rhs,bogus2=*args
end
else
lhs,op,rhs=*args
rhs=rhs.val if AssignmentRhsNode===rhs
end
case lhs
when UnaryStarNode #look for star on lhs
lhs=MultiAssign.new([lhs]) unless lhs.after_comma
when ParenedNode
if !lhs.after_comma #look for () around lhs
if CommaOpNode===lhs.first
lhs=MultiAssign.new(Array.new(lhs.first))
@lhs_parens=true
elsif UnaryStarNode===lhs.first
lhs=MultiAssign.new([lhs.first])
@lhs_parens=true
elsif ParenedNode===lhs.first
@lhs_parens=true
lhs=lhs.first
else
lhs=lhs.first
end
end
when CommaOpNode
lhs=MultiAssign.new lhs
#rhs=Array.new(rhs) if CommaOpNode===rhs
end
if CommaOpNode===rhs
rhs=Array.new(rhs)
lhs=MultiAssign.new([lhs]) unless MultiAssign===lhs
end
op=op.ident
if Array==rhs.class
rhs.extend ListInNode
end
@offset=lhs.offset
return super(lhs,op,rhs)
#punting, i hope the next layer can handle += and the like
=begin
#in theory, we should do something more sophisticated, like this:
#(but the presence of side effects in lhs will screw it up)
if op=='='
super
else
super(lhs,OpNode.new(lhs,OperatorToken.new(op.chomp('=')),rhs))
end
=end
end
def multi?
MultiAssign===left
end
def image; '(=)' end
def to_lisp
case left
when ParenedNode; huh
when BeginNode; huh
when RescueOpNode; huh
when ConstantNode; huh
when BracketsGetNode; huh
when VarNode
"(set #{left.to_lisp} (#{op.chomp('=')} #{left.to_lisp} #{right.to_lisp}))"
when CallSiteNode
if op=='='
"(#{left.receiver.to_lisp} #{left.name}= #{right.to_lisp})"
else
op_=op.chomp('=')
varname=nil
"(let #{varname=huh} #{left.receiver.to_lisp} "+
"(#{varname} #{left.name}= "+
"(#{op_} (#{varname} #{op}) #{right.to_lisp})))"
end
else huh
end
end
def all_current_lvars
left.respond_to?(:all_current_lvars) ?
left.all_current_lvars : []
end
def parsetree(o)
case left
when ParenedNode; huh
when RescueOpNode; huh
when BeginNode; huh
when ConstantNode;
left.lvalue_parsetree(o) << right.parsetree(o)
when MultiAssign;
lhs=left.lvalue_parsetree(o)
rhs= right.class==Array ? right.dup : [right]
star=rhs.pop if UnaryStarNode===rhs.last
rhs=rhs.map{|x| x.rescue_parsetree(o)}
if rhs.size==0
star or fail
rhs= star.parsetree(o)
elsif rhs.size==1 and !star and !(UnaryStarNode===left.first)
rhs.unshift :to_ary
else
rhs.unshift(:array)
if star
splat=star.val.rescue_parsetree(o)
#if splat.first==:call #I don't see how this can be right....
# splat[0]=:attrasgn
# splat[2]="#{splat[2]}=".to_sym
#end
rhs=[:argscat, rhs, splat]
end
if left.size==1 and !(UnaryStarNode===left.first) and !(NestedAssign===left.first)
rhs=[:svalue, rhs]
if CallNode===left.first
rhs=[:array, rhs]
end
end
end
if left.size==1 and BracketsGetNode===left.first and right.class==Array #hack
lhs.last<<rhs
lhs
else
lhs<< rhs
end
when CallSiteNode
op=op().chomp('=')
rcvr=left.receiver.parsetree(o)
prop=left.name.+('=').to_sym
args=right.rescue_parsetree(o)
UnaryStarNode===right and args=[:svalue, args]
if op.empty?
[:attrasgn, rcvr, prop, [:array, args] ]
else
[:op_asgn2, rcvr,prop, op.to_sym, args]
end
when BracketsGetNode
args=left.params
if op()=='='
result=left.lvalue_parsetree(o) #[:attrasgn, left[0].parsetree(o), :[]=]
result.size==3 and result.push [:array]
rhs=right.rescue_parsetree(o)
UnaryStarNode===right and rhs=[:svalue, rhs]
if args
result[-1]=[:argspush,result[-1]] if UnaryStarNode===args.last
#else result[-1]=[:zarray]
end
result.last << rhs
result
else
=begin
args&&=args.map{|x| x.parsetree(o)}.unshift(:array)
splat=args.pop if :splat==args.last.first
if splat and left.params.size==1
args=splat
elsif splat
args=[:argscat, args, splat.last]
end
=end
lhs=left.parsetree(o)
if lhs.first==:fcall
rcvr=[:self]
args=lhs[2]
else
rcvr=lhs[1]
args=lhs[3]
end
args||=[:zarray]
result=[
:op_asgn1, rcvr, args,
op().chomp('=').to_sym,
right.rescue_parsetree(o)
]
end
when VarNode
node_type=left.varname2assigntype
if /^(&&|\|\|)=$/===op()
return ["op_asgn_#{$1[0]==?& ? "and" : "or"}".to_sym,
left.parsetree(o),
[node_type, left.ident.to_sym,
right.rescue_parsetree(o)]
]
end
if op()=='='
rhs=right.rescue_parsetree(o)
UnaryStarNode===right and rhs=[:svalue, rhs]
# case left
# when VarNode;
[node_type, left.ident.to_sym, rhs]
# else [node_type, left.data[0].parsetree(o), left.data[1].data[0].ident.+('=').to_sym ,[:array, rhs]]
# end
=begin these branches shouldn't be necessary now
elsif node_type==:op_asgn2
[node_type, @data[0].data[0].parsetree(o),
@data[0].data[1].data[0].ident.+('=').to_sym,
op().ident.chomp('=').to_sym,
@data[2].parsetree(o)
]
elsif node_type==:attrasgn
[node_type]
=end
else
[node_type, left.ident.to_sym,
[:call,
left.parsetree(o),
op().chomp('=').to_sym,
[:array, right.rescue_parsetree(o)]
]
]
end
else
huh
end
end
def unparse(o=default_unparse_options)
result=lhs.lhs_unparse(o)
result="(#{result})" if defined? @lhs_parens
result+op+
(rhs.class==Array ?
rhs.map{|rv| rv.unparse o}.join(',') :
rhs.unparse(o)
)
end
end
class MultiAssignNode < ValueNode #obsolete
param_names :left,:right
#not called from parse table
def parsetree(o)
lhs=left.dup
if UnaryStarNode===lhs.last
lstar=lhs.pop
end
lhs.map!{|x|
res=x.parsetree(o)
res[0]=x.varname2assigntype if VarNode===x
res
}
lhs.unshift(:array) if lhs.size>1 or lstar
rhs=right.map{|x| x.parsetree(o)}
if rhs.size==1
if rhs.first.first==:splat
rhs=rhs.first
else
rhs.unshift :to_ary
end
else
rhs.unshift(:array)
if rhs[-1][0]==:splat
splat=rhs.pop[1]
if splat.first==:call
splat[0]=:attrasgn
splat[2]="#{splat[2]}=".to_sym
end
rhs=[:argscat, rhs, splat]
end
end
result=[:masgn, lhs, rhs]
result.insert(2,lstar.data.last.parsetree(o)) if lstar
result
end
end
class AssigneeList< ValueNode #abstract
def initialize(data)
data.each_with_index{|datum,i|
if ParenedNode===datum
first=datum.first
list=case first
when CommaOpNode; Array.new(first)
when UnaryStarNode,ParenedNode; [first]
end
data[i]=NestedAssign.new(list) if list
end
}
replace data
@offset=self.first.offset
@startline=self.first.startline
@endline=self.last.endline
end
def unparse o=default_unparse_options
map{|lval| lval.lhs_unparse o}.join(', ')
end
def old_parsetree o
lhs=data.dup
if UnaryStarNode===lhs.last
lstar=lhs.pop.val
end
lhs.map!{|x|
res=x.parsetree(o)
res[0]=x.varname2assigntype if VarNode===x
res
}
lhs.unshift(:array) if lhs.size>1 or lstar
result=[lhs]
if lstar.respond_to? :varname2assigntype
result << lstar.varname2assigntype
elsif lstar #[]=, attrib=, or A::B=
huh
else #do nothing
end
result
end
def parsetree(o)
data=self
data.empty? and return nil
# data=data.first if data.size==1 and ParenedNode===data.first and data.first.size==1
data=Array.new(data)
star=data.pop if UnaryStarNode===data.last
result=data.map{|x| x.lvalue_parsetree(o) }
=begin
{
if VarNode===x
ident=x.ident
ty=x.varname2assigntype
# ty==:lasgn and ty=:dasgn_curr
[ty, ident.to_sym]
else
x=x.parsetree(o)
if x[0]==:call
x[0]=:attrasgn
x[2]="#{x[2]}=".to_sym
end
x
end
}
=end
if result.size==0 #just star on lhs
star or fail
result=[:masgn]
result.push nil #why??? #if o[:ruby187]
result.push star.lvalue_parsetree(o)
elsif result.size==1 and !star and !(NestedAssign===data.first) #simple lhs, not multi
result=result.first
else
result=[:masgn, [:array, *result]]
result.push nil if (!star or DanglingCommaNode===star) #and o[:ruby187]
result.push star.lvalue_parsetree(o) if star and not DanglingCommaNode===star
end
result
end
def all_current_lvars
result=[]
each{|lvar|
lvar.respond_to?(:all_current_lvars) and
result.concat lvar.all_current_lvars
}
return result
end
def lvalue_parsetree(o); parsetree(o) end
end
class NestedAssign<AssigneeList
def parsetree(o)
result=super
result<<nil #why???!! #if o[:ruby187]
result
end
# def parsetree(o)
# [:masgn, *super]
# end
def unparse o=default_unparse_options
"("+super+")"
end
end
class MultiAssign<AssigneeList; end
class BlockParams<AssigneeList;
def initialize(data)
item=data.first if data.size==1
#elide 1 layer of parens if present
if ParenedNode===item
item=item.first
data=CommaOpNode===item ? Array.new(item) : [item]
@had_parens=true
end
super(data) unless data.empty?
end
def unparse o=default_unparse_options
if defined? @had_parens
"|("+super+")|"
else
"|"+super+"|"
end
end
def parsetree o
result=super
result.push nil if UnaryStarNode===self.last || size>1 #and o[:ruby187]
result
end
end
class AccessorAssignNode < ValueNode #obsolete
param_names :left,:dot_,:property,:op,:right
def to_lisp
if op.ident=='='
"(#{left.to_lisp} #{property.ident}= #{right.to_lisp})"
else
op=op().ident.chomp('=')
varname=nil
"(let #{varname=huh} #{left.to_lisp} "+
"(#{varname} #{property.ident}= "+
"(#{op} (#{varname} #{property.ident}) #{right.to_lisp})))"
end
end
def parsetree(o)
op=op().ident.chomp('=')
rcvr=left.parsetree(o)
prop=property.ident.<<(?=).to_sym
rhs=right.parsetree(o)
if op.empty?
[:attrasgn, rcvr, prop, [:array, args] ]
else
[:op_asgn2, rcvr,prop, op.to_sym, args]
end
end
end
class LogicalNode
include KeywordOpNode
def self.[](*list)
options=list.pop if Hash===list.last
result=allocate.replace list
opmap=options[:@opmap] if options and options[:@opmap]
opmap||=result.op[0,1]*(list.size-1)
result.instance_variable_set(:@opmap, opmap)
return result
end
def initialize(left,op,right)
op=op.ident if op.respond_to? :ident
@opmap=op[0,1]
case op
when "&&"; op="and"
when "||"; op="or"
end
#@reverse= op=="or"
#@op=op
replace [left,right]
(size-1).downto(0){|i|
expr=self[i]
if self.class==expr.class
self[i,1]=Array.new expr
opmap[i,0]=expr.opmap
end
}
end
attr_reader :opmap
OP_EXPAND={?o=>"or", ?a=>"and", ?&=>"&&", ?|=>"||", nil=>""}
OP_EQUIV={?o=>"or", ?a=>"and", ?&=>"and", ?|=>"or"}
def unparse o=default_unparse_options
result=''
each_with_index{|expr,i|
result.concat expr.unparse(o)
result.concat ?\s
result.concat OP_EXPAND[@opmap[i]]
result.concat ?\s
}
return result
end
def left
self[0]
end
def left= val
self[0]=val
end
def right
self[1]
end
def right= val
self[1]=val
end
def parsetree(o)
result=[].replace(self).reverse
last=result.shift.begin_parsetree(o)
first=result.pop
result=result.inject(last){|sum,x|
[op.to_sym, x.begin_parsetree(o), sum]
}
[op.to_sym, first.rescue_parsetree(o), result]
end
def special_conditions!
each{|x|
if x.respond_to? :special_conditions! and !(ParenedNode===x)
x.special_conditions!
end
}
end
end
class AndNode<LogicalNode
def reverse
false
end
def op
"and"
end
end
class OrNode<LogicalNode
def reverse
true
end
def op
"or"
end
end
class WhileOpNode
include KeywordOpNode
param_names :left, :op_, :right
def condition; right end
def consequent; left end
def initialize(val1,op,val2=nil)
op,val2=nil,op unless val2
op=op.ident if op.respond_to? :ident
@reverse=false
@loop=true
@test_first= !( BeginNode===val1 )
replace [val1,val2]
condition.special_conditions! if condition.respond_to? :special_conditions!
end
def while; condition end
def do; consequent end
alias body do
def op; "while" end
def reversed; false end
attr :test_first
def parsetree(o)
cond=condition.rescue_parsetree(o)
body=consequent.parsetree(o)
!@test_first and
body.size == 2 and
body.first == :begin and
body=body.last
if cond.first==:not
kw=:until
cond=cond.last
else
kw=:while
end
[kw, cond, body, (@test_first or body==[:nil])]
end
end
class UntilOpNode
include KeywordOpNode
param_names :left,:op_,:right
def condition; right end
def consequent; left end
def initialize(val1,op,val2=nil)
op,val2=nil,op unless val2
op=op.ident if op.respond_to? :ident
@reverse=true
@loop=true
@test_first= !( BeginNode===val1 )
replace [val1,val2]
condition.special_conditions! if condition.respond_to? :special_conditions!
end
def while; negate condition end
def do; consequent end
alias body do
def op; "until" end
def reversed; true end
def parsetree(o)
cond=condition.rescue_parsetree(o)
body=consequent.parsetree(o)
!@test_first and
body.size == 2 and
body.first == :begin and
body=body.last
if cond.first==:not
kw=:while
cond=cond.last
else
kw=:until
end
tf=@test_first||body==[:nil]
# tf||= (!consequent.body and !consequent.else and #!consequent.empty_else and
# !consequent.ensure and !consequent.empty_ensure and consequent.rescues.empty?
# ) if BeginNode===consequent
[kw, cond, body, tf]
end
end
class UnlessOpNode
include KeywordOpNode
param_names :left, :op_, :right
def condition; right end
def consequent; left end
def initialize(val1,op,val2=nil)
op,val2=nil,op unless val2
op=op.ident if op.respond_to? :ident
@reverse=true
@loop=false
replace [val1,val2]
condition.special_conditions! if condition.respond_to? :special_conditions!
end
def if; condition end
def then; nil end
def else; consequent end
def elsifs; [] end
def op; "unless" end
def parsetree(o)
cond=condition.rescue_parsetree(o)
actions=[nil, consequent.parsetree(o)]
if cond.first==:not
actions.reverse!
cond=cond.last
end
[:if, cond, *actions]
end
end
class IfOpNode
param_names :left,:op_,:right
include KeywordOpNode
def condition; right end
def consequent; left end
def initialize(left,op,right=nil)
op,right=nil,op unless right
op=op.ident if op.respond_to? :ident
@reverse=false
@loop=false
replace [left,right]
condition.special_conditions! if condition.respond_to? :special_conditions!
end
def if; condition end
def then; consequent end
def else; nil end
def elsifs; [] end
def op; "if" end
def parsetree(o)
cond=condition.rescue_parsetree(o)
actions=[consequent.parsetree(o), nil]
if cond.first==:not
actions.reverse!
cond=cond.last
end
[:if, cond, *actions]
end
end
class CallSiteNode<ValueNode
param_names :receiver, :name, :params, :blockparams, :block
alias blockargs blockparams
alias block_args blockargs
alias block_params blockparams
def initialize(method,open_paren,param_list,close_paren,block)
@not_real_parens=!open_paren || open_paren.not_real?
case param_list
when CommaOpNode
#handle inlined hash pairs in param list (if any)
# compr=Object.new
# def compr.==(other) ArrowOpNode===other end
h,arrowrange=param_list.extract_unbraced_hash
param_list=Array.new(param_list)
param_list[arrowrange]=[h] if arrowrange
when ArrowOpNode
h=HashLiteralNode.new(nil,param_list,nil)
h.startline=param_list.startline
h.endline=param_list.endline
param_list=[h]
# when KeywordOpNode
# fail "didn't expect '#{param_list.inspect}' inside actual parameter list"
when nil
else
param_list=[param_list]
end
param_list.extend ListInNode if param_list
if block
@do_end=block.do_end
blockparams=block.params
block=block.body #||[]
end
@offset=method.offset
if Token===method
method=method.ident
fail unless String===method
end
super(nil,method,param_list,blockparams,block)
#receiver, if any, is tacked on later
end
def real_parens; @not_real_parens||=nil; !@not_real_parens end
def real_parens= x; @not_real_parens=!x end
def unparse o=default_unparse_options
fail if block==false
result=[
receiver&&receiver.unparse(o)+'.',name,
real_parens ? '(' : (' ' if params),
params&¶ms.map{|param| unparse_nl(param,o,'',"\\\n")+param.unparse(o) }.join(', '),
real_parens ? ')' : nil,
block&&[
@do_end ? " do " : "{",
block_params&&block_params.unparse(o),
unparse_nl(block,o," "),
block.unparse(o),
unparse_nl(endline,o),
@do_end ? " end" : "}"
]
]
return result.join
end
def image
result="(#{receiver.image if receiver}.#{name})"
end
def with_commas
!real_parens and
args and args.size>0
end
# identity_param :with_commas, false, true
def lvalue_parsetree(o)
result=parsetree(o)
result[0]=:attrasgn
result[2]="#{result[2]}=".to_sym
result
end
def lvalue
return @lvalue if defined? @lvalue
@lvalue=true
end
attr_writer :lvalue
identity_param :lvalue, nil, true
def to_lisp
"(#{receiver.to_lisp} #{self[1..-1].map{|x| x.to_lisp}.join(' ')})"
end
alias args params
alias rcvr receiver
def set_receiver!(expr)
self[0]=expr
end
def parsetree_with_params o
args=args()||[]
if (UnOpNode===args.last and args.last.ident=="&@")
lasti=args.size-2
unamp_expr=args.last.val
else
lasti=args.size-1
end
methodname= name
methodname= methodname.chop if /^[~!]@$/===methodname
methodsym=methodname.to_sym
is_kw= RubyLexer::FUNCLIKE_KEYWORDS&~/^(BEGIN|END|raise)$/===methodname
result=
if lasti==-1
[(@not_real_parens and /[!?]$/!~methodname and !unamp_expr) ?
:vcall : :fcall, methodsym
]
elsif (UnaryStarNode===args[lasti])
if lasti.zero?
[:fcall, methodsym, args.first.rescue_parsetree(o)]
else
[:fcall, methodsym,
[:argscat,
[:array, *args[0...lasti].map{|x| x.rescue_parsetree(o) } ],
args[lasti].val.rescue_parsetree(o)
]
]
end
else
singlearg= lasti.zero?&&args.first
[:fcall, methodsym,
[:array, *args[0..lasti].map{|x| x.rescue_parsetree(o) } ]
]
end
result[0]=:vcall if block #and /\Af?call\Z/===result[0].to_s
if is_kw and !receiver
if singlearg and "super"!=methodname
result=[methodsym, singlearg.parsetree(o)]
result.push(true) if methodname=="yield" and ArrayLiteralNode===singlearg #why???!!
return result
end
breaklike= /^(break|next|return)$/===methodname
if @not_real_parens
return [:zsuper] if "super"==methodname and !args()
else
return [methodsym, [:nil]] if breaklike and args.size.zero?
end
result.shift
arg=result[1]
result[1]=[:svalue,arg] if arg and arg[0]==:splat and breaklike
end
if receiver
result.shift if result.first==:vcall or result.first==:fcall #if not kw
result=[:call, receiver.rescue_parsetree(o), *result]
end
if unamp_expr
# result[0]=:fcall if lasti.zero?
result=[:block_pass, unamp_expr.rescue_parsetree(o), result]
end
return result
end
def parsetree(o)
callsite=parsetree_with_params o
return callsite unless blockparams or block
call=name
callsite[0]=:fcall if callsite[0]==:call or callsite[0]==:vcall
unless receiver
case call
when "BEGIN"
if o[:quirks]
return []
else
callsite=[:preexe]
end
when "END"; callsite=[:postexe]
end
else
callsite[0]=:call if callsite[0]==:fcall
end
if blockparams
bparams=blockparams.dup
lastparam=bparams.last
amped=bparams.pop.val if UnOpNode===lastparam and lastparam.op=="&@"
bparams=bparams.parsetree(o)||0
if amped
bparams=[:masgn, [:array, bparams]] unless bparams==0 or bparams.first==:masgn
bparams=[:block_pass, amped.lvalue_parsetree(o), bparams]
end
else
bparams=nil
end
result=[:iter, callsite, bparams]
unless block.empty?
body=block.parsetree(o)
if curr_vars=block.lvars_defined_in
curr_vars-=blockparams.all_current_lvars if blockparams
if curr_vars.empty?
result.push body
else
curr_vars.map!{|cv| [:dasgn_curr, cv.to_sym] }
(0...curr_vars.size-1).each{|i| curr_vars[i]<<curr_vars[i+1] }
#body.first==:block ? body.shift : body=[body]
result.push((body)) #.unshift curr_vars[0]))
end
else
result.push body
end
end
result
end
def blockformals_parsetree data,o #dead code?
data.empty? and return nil
data=data.dup
star=data.pop if UnaryStarNode===data.last
result=data.map{|x| x.parsetree(o) }
=begin
{ if VarNode===x
ident=x.ident
ty=x.varname2assigntype
# ty==:lasgn and ty=:dasgn_curr
[ty, ident.to_sym]
else
x=x.parsetree(o)
if x[0]==:call
x[0]=:attrasgn
x[2]="#{x[2]}=".to_sym
end
x
end
}
=end
if result.size==0
star or fail
result=[:masgn, star.parsetree(o).last]
elsif result.size==1 and !star
result=result.first
else
result=[:masgn, [:array, *result]]
if star
old=star= star.val
star=star.parsetree(o)
if star[0]==:call
star[0]=:attrasgn
star[2]="#{star[2]}=".to_sym
end
if VarNode===old
ty=old.varname2assigntype
# ty==:lasgn and ty=:dasgn_curr
star[0]=ty
end
result.push star
end
end
result
end
end
class CallNode<CallSiteNode #normal method calls
def initialize(method,open_paren,param_list,close_paren,block)
super
end
end
class KWCallNode<CallSiteNode #keywords that look (more or less) like methods
def initialize(method,open_paren,param_list,close_paren,block)
KeywordToken===method or fail
super
end
end
class BlockFormalsNode<Node #obsolete
def initialize(goalpost1,param_list,goalpost2)
param_list or return super()
CommaOpNode===param_list and return super(*Array.new(param_list))
super(param_list)
end
def to_lisp
"(#{data.join' '})"
end
def parsetree(o)
empty? ? nil :
[:dasgn_curr,
*map{|x|
(VarNode===x) ? x.ident.to_sym : x.parsetree(o)
}
]
end
end
class BlockNode<ValueNode #not to appear in final parse tree
param_names :params,:body
def initialize(open_brace,formals,stmts,close_brace)
stmts||=SequenceNode[{:@offset => open_brace.offset, :@startline=>open_brace.startline}]
stmts=SequenceNode[stmts,{:@offset => open_brace.offset, :@startline=>open_brace.startline}] unless SequenceNode===stmts
formals&&=BlockParams.new(Array.new(formals))
@do_end=true unless open_brace.not_real?
super(formals,stmts)
end
attr_reader :do_end
def to_lisp
"(#{params.to_lisp} #{body.to_lisp})"
end
def parsetree(o) #obsolete
callsite=@data[0].parsetree(o)
call=@data[0].data[0]
callsite[0]=:fcall if call.respond_to? :ident
if call.respond_to? :ident
case call.ident
when "BEGIN"
if o[:quirks]
return []
else
callsite=[:preexe]
end
when "END"; callsite=[:postexe]
end
end
result=[:iter, callsite, @data[1].parsetree(o)]
result.push @data[2].parsetree(o) if @data[2]
result
end
end
class ProcLiteralNode<ValueNode
def initialize(params, other_locals, body)
@params, @other_locals, @body= params, other_locals, body
end
def self.create(arrow, lparen, params, rparen, do_word, body, endword)
params,other_locals=*params if SequenceNode===params
new(params,other_locals,body)
end
def unparse o=default_parse_options
huh
end
end
class NopNode<ValueNode
def initialize(*args)
@startline=@endline=1
super()
end
def unparse o=default_unparse_options
''
end
def to_lisp
"()"
end
alias image to_lisp
def to_parsetree(*options)
[]
end
end
=begin
class ObjectNode<ValueNode
def initialize
super
end
def to_lisp
"Object"
end
def parsetree(o)
:Object
end
end
=end
class CallWithBlockNode<ValueNode #obsolete
param_names :call,:block
def initialize(call,block)
KeywordCall===call and extend KeywordCall
super
end
def to_lisp
@data.first.to_lisp.chomp!(")")+" #{@data.last.to_lisp})"
end
end
class StringNode<ValueNode
def initialize(token)
if HerePlaceholderToken===token
str=token.string
@char=token.quote
else
str=token
@char=str.char
end
@modifiers=str.modifiers #if str.modifiers
super( *with_string_data(str) )
@open=token.open
@close=token.close
@offset=token.offset
@bs_handler=str.bs_handler
if /[\[{]/===@char
@parses_like=split_into_words(str)
end
return
=begin
#this should have been taken care of by with_string_data
first=shift
delete_if{|x| ''==x }
unshift(first)
#escape translation now done later on
map!{|strfrag|
if String===strfrag
str.translate_escapes strfrag
else
strfrag
end
}
=end
end
def initialize_ivars
@char||='"'
@open||='"'
@close||='"'
@bs_handler||=:dquote_esc_seq
if /[\[{]/===@char
@parses_like||=split_into_words(str)
end
end
def translate_escapes(str)
rl=RubyLexer.new("(string escape translation hack...)",'')
result=str.dup
seq=result.to_sequence
rl.instance_eval{@file=seq}
repls=[]
i=0
#ugly ugly ugly... all so I can call @bs_handler
while i<result.size and bs_at=result.index(/\\./m,i)
seq.pos=$~.end(0)-1
ch=rl.send(@bs_handler,"\\",@open[-1,1],@close)
result[bs_at...seq.pos]=ch
i=bs_at+ch.size
end
return result
end
def old_cat_initialize(*tokens) #not needed anymore?
token=tokens.shift
tokens.size==1 or fail "string node must be made from a single string token"
newdata=with_string_data(*tokens)
case token
when HereDocNode
token.list_to_append=newdata
when StringNode #do nothing
else fail "non-string token class used to construct string node"
end
replace token.data
# size%2==1 and last<<newdata.shift
if size==1 and String===first and String===newdata.first
first << newdata.shift
end
concat newdata
@implicit_match=false
end
ESCAPABLES={}
EVEN_NUM_BSLASHES=/(^|[^\\])((?:\\\\)*)/
def unparse o=default_unparse_options
o[:linenum]+=@open.count("\n")
result=[@open,unparse_interior(o),@close,@modifiers].join
o[:linenum]+=@close.count("\n")
return result
end
def escapable open=@open,close=@close
unless escapable=ESCAPABLES[open]
maybe_crunch='\\#' if %r{\A["`/\{]\Z} === @char and open[1] != ?q and open != "'" #"
#crunch (#) might need to be escaped too, depending on what @char is
escapable=ESCAPABLES[open]=
/[#{Regexp.quote open[-1,1]+close}#{maybe_crunch}]/
end
escapable
end
def unparse_interior o,open=@open,close=@close,escape=nil
escapable=escapable(open,close)
result=map{|substr|
if String===substr
#hack: this is needed for here documents only, because their
#delimiter is changing.
substr.gsub!(escape){|ch| ch[0...-1]+"\\"+ch[-1,1]} if escape
o[:linenum]+=substr.count("\n") if o[:linenum]
substr
else
['#{',substr.unparse(o),'}']
end
}
result
end
def image; '(#@char)' end
def walk(*args,&callback)
@parses_like.walk(*args,&callback) if defined? @parses_like
super
end
def depthwalk(*args,&callback)
return @parses_like.depthwalk(*args,&callback) if defined? @parses_like
super
end
def special_conditions!
@implicit_match= @char=="/"
end
attr_reader :modifiers,:char#,:data
alias type char
def with_string_data(token)
# token=tokens.first
# data=tokens.inject([]){|sum,token|
# data=elems=token.string.elems
data=elems=
case token
when StringToken; token.elems
when HerePlaceholderToken; token.string.elems
else raise "unknown string token type: #{token}:#{token.class}"
end
# sum.size%2==1 and sum.last<<elems.shift
# sum+elems
# }
# endline=@endline
1.step(data.length-1,2){|i|
tokens=data[i].ident.dup
line=data[i].linenum
#replace trailing } with EoiToken
(tokens.size-1).downto(0){|j|
tok=tokens[j]
break(tokens[j..-1]=[EoiToken.new('',nil,tokens[j].offset)]) if tok.ident=='}'
}
#remove leading {
tokens.each_with_index{|tok,j| break(tokens.delete_at j) if tok.ident=='{' }
if tokens.size==1 and VarNameToken===tokens.first
data[i]=VarNode.new tokens.first
data[i].startline=data[i].endline=token.endline
data[i].offset=tokens.first.offset
else
#parse the token list in the string inclusion
parser=Thread.current[:$RedParse_parser]
klass=parser.class
data[i]=klass.new(tokens, "(string inclusion)",1,[],:rubyversion=>parser.rubyversion,:cache_mode=>:none).parse
end
} #if data
# was_nul_header= (String===data.first and data.first.empty?) #and o[:quirks]
last=data.size-1
#remove (most) empty string fragments
last.downto(1){|frag_i|
frag=data[frag_i]
String===frag or next
next unless frag.empty?
next if frag_i==last #and o[:quirks]
next if data[frag_i-1].endline != data[frag_i+1].endline #and o[:quirks]
#prev and next inclusions on different lines
data.slice!(frag_i)
}
# data.unshift '' if was_nul_header
return data
end
def endline= endline
each{|frag|
frag.endline||=endline if frag.respond_to? :endline
}
super
end
def to_lisp
return %{"#{first}"} if size<=1 and @char=='"'
huh
end
EVEN_BSS=/(?:[^\\\s\v]|\G)(?:\\\\)*/
DQ_ESC=/(?>\\(?>[CM]-|c)?)/
DQ_EVEN=%r[
(?:
\G |
[^\\c-] |
(?>\G|[^\\])c |
(?> [^CM] | (?>\G|[^\\])[CM] )-
) #not esc
#{DQ_ESC}{2}* #an even number of esc
]omx
DQ_ODD=/#{DQ_EVEN}#{DQ_ESC}/omx
SQ_ESC=/\\/
SQ_EVEN=%r[
(?: \G | [^\\] ) #not esc
#{SQ_ESC}{2}* #an even number of esc
]omx
SQ_ODD=/#{SQ_EVEN}#{SQ_ESC}/omx
def split_into_words strtok
@offset=strtok.offset
return unless /[{\[]/===@char
result=ArrayLiteralNode[]
result << StringNode['',{:@char=>'"',:@open=>@open,:@close=>@close,:@bs_handler=>@bs_handler}]
proxy=dup
proxy[0]=proxy[0][/\A(?:\s|\v)+(.*)\Z/m,1] if /\A(?:\s|\v)/===proxy[0]
# first[/\A(?:\s|\v)+/]='' if /\A(?:\s|\v)/===first #uh-oh, changes first
proxy.each{|x|
if String===x
# x=x[/\A(?:\s|\v)+(.*)\Z/,1] if /\A[\s\v]/===x
if false
#split on ws preceded by an even # of backslashes or a non-backslash, non-ws char
#this ignores backslashed ws
#save the thing that preceded the ws, it goes back on the token preceding split
double_chunks=x.split(/( #{EVEN_BSS} | (?:[^\\\s\v]|\A|#{EVEN_BSS}\\[\s\v]) )(?:\s|\v)+/xo,-1)
chunks=[]
(0..double_chunks.size).step(2){|i|
chunks << #strtok.translate_escapes \
double_chunks[i,2].to_s #.gsub(/\\([\s\v\\])/){$1}
}
else
#split on ws, then ignore ws preceded by an odd number of esc's
#esc is \ in squote word array, \ or \c or \C- or \M- in dquote
chunks_and_ws=x.split(/([\s\v]+)/,-1)
start=chunks_and_ws.size; start-=1 if start&1==1
chunks=[]
i=start+2;
while (i-=2)>=0
ch=chunks_and_ws[i]||""
if i<chunks_and_ws.size and ch.match(@char=="[" ? /#{SQ_ODD}\Z/omx : /#{DQ_ODD}\Z/omx)
ch<< chunks_and_ws[i+1][0,1]
if chunks_and_ws[i+1].size==1
ch<< chunks.shift
end
end
chunks.unshift ch
end
end
chunk1= chunks.shift
if chunk1.empty?
#do nothing more
elsif String===result.last.last
result.last.last << chunk1
else
result.last.push chunk1
end
# result.last.last.empty? and result.last.pop
result.concat chunks.map{|chunk|
StringNode[chunk,{:@char=>'"',:@open=>@open,:@close=>@close,:@bs_handler=>@bs_handler}]
}
else
#result.last << x
unless String===result.last.last
result.push StringNode["",{:@char=>'"',:@open=>@open,:@close=>@close,:@bs_handler=>@bs_handler}]
end
result.last.push x
# result.push StringNode["",x,{:@char=>'"',:@open=>@open,:@close=>@close,:@bs_handler=>@bs_handler}]
end
}
result.shift if StringNode&-{:size=>1, :first=>''}===result.first
result.pop if StringNode&-{:size=>1, :first=>''}===result.last
return result
end
CHAROPT2NUM={
?x=>Regexp::EXTENDED,
?m=>Regexp::MULTILINE,
?i=>Regexp::IGNORECASE,
?o=>8,
}
CHARSETFLAG2NUM={
?n=>0x10,
?e=>0x20,
?s=>0x30,
?u=>0x40
}
CHAROPT2NUM.default=0
CHARSETFLAG2NUM.default=0
DOWNSHIFT_STRING_TYPE={
:dregx=>:lit,
:dregx_once=>:lit,
:dstr=>:str,
:dxstr=>:xstr,
}
def parsetree(o)
if size==1
val=translate_escapes first
type=case @char
when '"',"'"; :str
when '/'
numopts=0
charset=0
RubyLexer::CharHandler.each_char(@modifiers){|ch|
if ch==?o
type=:dregx_once
elsif numopt=CHAROPT2NUM[ch].nonzero?
numopts|=numopt
elsif set=CHARSETFLAG2NUM[ch].nonzero?
charset=set
else fail
end
}
val=Regexp.new val,numopts|charset
:lit
when '[','{'
return @parses_like.parsetree(o)
=begin
double_chunks=val.split(/([^\\]|\A)(?:\s|\v)/,-1)
chunks=[]
(0..double_chunks.size).step(2){|i|
chunks << double_chunks[i,2].to_s.gsub(/\\(\s|\v)/){$1}
}
# last=chunks
# last.last.empty? and last.pop if last and !last.empty?
words=chunks#.flatten
words.shift if words.first.empty? unless words.empty?
words.pop if words.last.empty? unless words.empty?
return [:zarray] if words.empty?
return words.map{|word| [:str,word]}.unshift(:array)
=end
when '`'; :xstr
else raise "dunno what to do with #@char<StringToken"
end
result=[type,val]
else
saw_string=false
vals=[]
each{|elem|
case elem
when String
was_esc_nl= (elem=="\\\n") #ick
elem=translate_escapes elem
if saw_string
vals.push [:str, elem] if !elem.empty? or was_esc_nl
else
saw_string=true
vals.push elem
end
when NopNode
vals.push [:evstr]
when Node #,VarNameToken
res=elem.parsetree(o)
if res.first==:str and @char != '{'
vals.push res
elsif res.first==:dstr and @char != '{'
vals.push [:str, res[1]], *res[2..-1]
else
vals.push [:evstr, res]
end
else fail "#{elem.class} not expected here"
end
}
while vals.size>1 and vals[1].first==:str
vals[0]+=vals.delete_at(1).last
end
#vals.pop if vals.last==[:str, ""]
type=case @char
when '"'; :dstr
when '/'
type=:dregx
numopts=charset=0
RubyLexer::CharHandler.each_char(@modifiers){|ch|
if ch==?o
type=:dregx_once
elsif numopt=CHAROPT2NUM[ch].nonzero?
numopts|=numopt
elsif set=CHARSETFLAG2NUM[ch].nonzero?
charset=set
end
}
regex_options= numopts|charset unless numopts|charset==0
val=/#{val}/
type
when '{'
return @parses_like.parsetree(o)
=begin
vals[0]=vals[0].sub(/\A(\s|\v)+/,'') if /\A(\s|\v)/===vals.first
merged=Array.new(vals)
result=[]
merged.each{|i|
if String===i
next if /\A(?:\s|\v)+\Z/===i
double_chunks=i.split(/([^\\]|\A)(?:\s|\v)/,-1)
chunks=[]
(0..double_chunks.size).step(2){|ii|
chunks << double_chunks[ii,2].to_s.gsub(/\\(\s|\v)/){$1}
}
words=chunks.map{|word| [:str,word]}
if !result.empty? and frag=words.shift and !frag.last.empty?
result[-1]+=frag
end
result.push( *words )
else
result.push [:str,""] if result.empty?
if i.first==:evstr and i.size>1 and i.last.first==:str
if String===result.last[-1]
result.last[-1]+=i.last.last
else
result.last[0]=:dstr
result.last.push(i.last)
end
else
result.last[0]=:dstr
result.last.push(i)
end
end
}
return result.unshift(:array)
=end
when '`'; :dxstr
else raise "dunno what to do with #@char<StringToken"
end
if vals.size==1
if :dregx==type or :dregx_once==type
lang=@modifiers.tr_s("^nesuNESU","")
lang=lang[-1,1] unless lang.empty?
lang.downcase!
regex_options=nil
vals=[Regexp_new( vals.first,numopts,lang )]
end
type=DOWNSHIFT_STRING_TYPE[type]
end
result= vals.unshift(type)
result.push regex_options if regex_options
end
result=[:match, result] if defined? @implicit_match and @implicit_match
return result
end
if //.respond_to? :encoding
LETTER2ENCODING={
?n => Encoding::ASCII,
?u => Encoding::UTF_8,
?e => Encoding::EUC_JP,
?s => Encoding::SJIS,
"" => Encoding::ASCII
}
def Regexp_new(src,opts,lang)
src.encode!(LETTER2ENCODING[lang])
Regexp.new(src,opts)
end
else
def Regexp_new(src,opts,lang)
Regexp.new(src,opts,lang)
end
end
end
class HereDocNode<StringNode
param_names :token
def initialize(token)
token.node=self
super(token)
@startline=token.string.startline
end
attr_accessor :list_to_append
# attr :token
def saw_body! #not used
replace with_string_data(token)
@char=token.quote
if @list_to_append
size%2==1 and token << @list_to_append.shift
push( *@list_to_append )
remove_instance_variable :@list_to_append
end
end
def translate_escapes x
return x if @char=="'"
super
end
#ignore instance vars in here documents when testing equality
def flattened_ivars_equal?(other)
StringNode===other
end
def unparse o=default_unparse_options
lead=unparse_nl(self,o,'',"\\\n")
inner=unparse_interior o,@char,@char,
case @char
when "'" #single-quoted here doc is a special case;
#\ and ' are not special within it
#(and therefore always escaped if converted to normal squote str)
/['\\]/
when '"'; /#{DQ_EVEN}"/
when "`"; /#{DQ_EVEN}`/
else fail
end
[lead,@char, inner, @char].join
end
end
class LiteralNode<ValueNode
param_names :val
attr_accessor :offset
def self.create(old_val)
offset=old_val.offset
val=old_val.ident
case old_val
when SymbolToken
case val[1]
when ?' #'
assert !old_val.raw.has_str_inc?
val=old_val.raw.translate_escapes(old_val.raw.elems.first).to_sym
when ?" #"
if old_val.raw.has_str_inc? or old_val.raw.elems==[""]
val=StringNode.new(old_val.raw) #ugly hack: this isn't literal
else
val=old_val.raw.translate_escapes(old_val.raw.elems.first).to_sym
end
else #val=val[1..-1].to_sym
val=old_val.raw
if StringToken===val
val=val.translate_escapes(val.elems.first)
elsif /^[!~]@$/===val
val=val.chop
end
val=val.to_sym
end
when NumberToken
case val
when /\A-?0([^.]|\Z)/; val=val.oct
when /[.e]/i; val=val.to_f
else val=val.to_i
end
end
result=LiteralNode.new(val)
result.offset=offset
result
end
def self.inline_symbols data
#don't mangle symbols when constructing node like: LiteralNode[:foo]
data
end
def []=(*args)
original_brackets_assign( *args )
end
def bare_method
Symbol===val || StringNode===val
end
identity_param :bare_method, nil, false, true
def image; "(#{':' if Symbol===val}#{val})" end
def to_lisp
return val.to_s
end
Inf="999999999999999999999999999999999.9e999999999999999999999999999999999999"
Nan="****shouldnt ever happen****"
def unparse o=default_unparse_options
val=val()
case val
when StringNode #ugly hack
":"+
val.unparse(o)
when Float
s= val.accurate_to_s
#why must it be *2? I wouldn't think any fudge factor would be necessary
case s
when /-inf/i; s="-"+Inf
when /inf/i; s= Inf
when /nan/i; s= Nan
else
fail unless [s.to_f].pack("d")==[val].pack("d")
end
s
else val.inspect
end
end
def parsetree(o)
val=val()
case val
when StringNode #ugly hack
result= val.parsetree(o)
result[0]=:dsym
return result
=begin
when String
#float or real string? or keyword?
val=
case val
when Numeric: val
when Symbol: val
when String: val
when "true": true
when "false": false
when "nil": nil
when "self": return :self
when "__FILE__": "wrong-o"
when "__LINE__": "wrong-o"
else fail "unknown token type in LiteralNode: #{val.class}"
end
=end
end
return [:lit,val]
end
end
class VarLikeNode<ValueNode #nil,false,true,__FILE__,__LINE__,self
param_names :name
def initialize(name,*more)
@offset=name.offset
if name.ident=='('
#simulate nil
replace ['nil']
@value=nil
else
replace [name.ident]
@value=name.respond_to?(:value) && name.value
end
end
alias ident name
def image; "(#{name})" end
def to_lisp
name
end
def unparse o=default_unparse_options
name
end
def parsetree(o)
if (defined? @value) and @value
type=:lit
val=@value
if name=="__FILE__"
type=:str
val="(string)" if val=="-"
end
[type,val]
else
[name.to_sym]
end
end
end
class ArrayLiteralNode<ValueNode
def initialize(lbrack,contents,rbrack)
@offset=lbrack.offset
contents or return super()
if CommaOpNode===contents
h,arrowrange=contents.extract_unbraced_hash
contents[arrowrange]=[h] if arrowrange
super( *contents )
elsif ArrowOpNode===contents
h=HashLiteralNode.new(nil,contents,nil)
h.startline=contents.startline
h.endline=contents.endline
super HashLiteralNode.new(nil,contents,nil)
else
super contents
end
end
def image; "([])" end
def unparse o=default_unparse_options
"["+map{|item| unparse_nl(item,o,'')+item.unparse(o)}.join(', ')+"]"
end
def parsetree(o)
size.zero? and return [:zarray]
normals,star,amp=param_list_parse(self,o)
result=normals.unshift :array
if star
if size==1
result=star
else
result=[:argscat, result, star.last]
end
end
result
end
end
#ArrayNode=ValueNode
class BracketsSetNode < ValueNode #obsolete
param_names :left,:assign_,:right
def parsetree(o)
[:attrasgn, left.data[0].parsetree(o), :[]=,
[:array]+Array(left.data[1]).map{|x| x.parsetree(o)}<< right.parsetree(o)
]
end
end
class BracketsModifyNode < ValueNode #obsolete
param_names :left,:assignop,:right
def initialize(left,assignop,right)
super
end
def parsetree(o)
bracketargs=@data[0].data[1]
bracketargs=bracketargs ? bracketargs.map{|x| x.parsetree(o)}.unshift(:array) : [:zarray]
[:op_asgn1, @data[0].data[0].parsetree(o), bracketargs,
data[1].ident.chomp('=').to_sym, data[2].parsetree(o)]
end
end
class IfNode < ValueNode
param_names :condition,:consequent,:elsifs,:otherwise
def initialize(iftok,condition,thentok,consequent,elsifs,else_,endtok)
@offset=iftok.offset
if else_
else_=else_.val or @empty_else=true
end
condition.special_conditions! if condition.respond_to? :special_conditions!
elsifs.extend ListInNode if elsifs
super(condition,consequent,elsifs,else_)
@reverse= iftok.ident=="unless"
if @reverse
@iftok_offset=iftok.offset
fail "elsif not allowed with unless" unless elsifs.empty?
end
end
alias if condition
alias then consequent
alias else otherwise
alias else_ else
alias if_ if
alias then_ then
attr_reader :empty_else
def unparse o=default_unparse_options
result=@reverse ? "unless " : "if "
result+="#{condition.unparse o}"
result+=unparse_nl(consequent,o)+"#{consequent.unparse(o)}" if consequent
result+=unparse_nl(elsifs.first,o)+elsifs.map{|n| n.unparse(o)}.join if elsifs
result+=unparse_nl(else_,o)+"else "+else_.unparse(o) if else_
result+=";else " if defined? @empty_else
result+=";end"
return result
end
def image; "(if)" end
def if
if @reverse
negate condition, @iftok_offset
else
condition
end
end
def then
@reverse ? otherwise : consequent
end
def else
@reverse ? consequent : otherwise
end
def to_lisp
if elsifs.empty?
"(#{@reverse ? :unless : :if} #{condition.to_lisp}\n"+
"(then #{consequent.to_lisp})\n(else #{otherwise.to_lisp}))"
else
"(cond (#{condition.to_lisp} #{consequent.to_lisp})\n"+
elsifs.map{|x| x.to_lisp}.join("\n")+
"\n(else #{otherwise.to_lisp})"+
"\n)"
end
end
def parsetree(o)
elsepart=otherwise.parsetree(o) if otherwise
elsifs.reverse_each{|elsifnode|
elsepart=elsifnode.parsetree(o) << elsepart
}
cond=condition.rescue_parsetree(o)
actions=[
consequent&&consequent.parsetree(o),
elsepart
]
if cond.first==:not
cond=cond.last
reverse=!@reverse
else
reverse=@reverse
end
actions.reverse! if reverse
result=[:if, cond, *actions]
return result
end
end
class ElseNode<Node #not to appear in final tree
param_names :elseword_,:val
alias body val
def image; "(else)" end
def to_lisp
"(else #{body.to_lisp})"
end
end
class EnsureNode<Node #not to appear in final tree
param_names :ensureword_, :val
alias body val
def image; "(ensure)" end
def parsetree(o) #obsolete?
(body=body()) ? body.parsetree(o) : [:nil]
end
end
class ElsifNode<Node
param_names(:elsifword_,:condition,:thenword_,:consequent)
def initialize(elsifword,condition,thenword,consequent)
@offset=elsifword.offset
condition.special_conditions! if condition.respond_to? :special_conditions!
super(condition,consequent)
end
alias if condition
alias elsif if
alias then consequent
def image; "(elsif)" end
def unparse o=default_unparse_options
"elsif #{condition.unparse o}#{unparse_nl(consequent,o)}#{consequent.unparse o if consequent};"
end
def to_lisp
"("+condition.to_lisp+" "+consequent.to_lisp+")"
end
def parsetree(o) #obsolete?
[:if, condition.rescue_parsetree(o), consequent&&consequent.parsetree(o), ]
end
end
class LoopNode<ValueNode
#this class should be abstract and have 2 concrete descendants for while and until
param_names :condition, :body
def initialize(loopword,condition,thenword,body,endtok)
@offset=loopword.offset
condition.special_conditions! if condition.respond_to? :special_conditions!
super(condition,body)
@reverse= loopword.ident=="until"
@loopword_offset=loopword.offset
end
alias do body
def image; "(#{loopword})" end
def unparse o=default_unparse_options
[@reverse? "until " : "while ",
condition.unparse(o), unparse_nl(body||self,o),
body&&body.unparse(o),
";end"
].join
end
def while
@reverse ? negate(condition, @loopword_offset) : condition
end
def until
@reverse ? condition : negate(condition, @loopword_offset)
end
def reversed
@reverse
end
def test_first
false
end
def to_lisp
body=body()
"(#{@reverse ? :until : :while} #{condition.to_lisp}\n#{body.to_lisp})"
end
def parsetree(o)
cond=condition.rescue_parsetree(o)
if cond.first==:not
reverse=!@reverse
cond=cond.last
else
reverse=@reverse
end
[reverse ? :until : :while, cond, body&&body.parsetree(o), true]
end
end
class CaseNode<ValueNode
param_names(:case!,:whens,:else!)
alias condition case
alias otherwise else
def initialize(caseword, condition, semi, whens, otherwise, endword)
@offset=caseword.offset
if otherwise
otherwise=otherwise.val
@empty_else=!otherwise
else
@empty_else=false
end
whens.extend ListInNode
super(condition,whens,otherwise)
end
attr_reader :empty_else
def unparse o=default_unparse_options
result="case #{condition&&condition.unparse(o)}"+
whens.map{|wh| wh.unparse o}.join
result += unparse_nl(otherwise,o)+"else "+otherwise.unparse(o) if otherwise
result += ";else;" if @empty_else
result += ";end"
return result
end
def image; "(case)" end
def to_lisp
"(case #{case_.to_lisp}\n"+
whens.map{|x| x.to_lisp}.join("\n")+"\n"+
"(else #{else_.to_lisp}"+
"\n)"
end
def parsetree(o)
result=[:case, condition&&condition.parsetree(o)]+
whens.map{|whennode| whennode.parsetree(o)}
other=otherwise&&otherwise.parsetree(o)
return [] if result==[:case, nil] and !other
if other and other[0..1]==[:case, nil] and !condition
result.concat other[2..-1]
else
result<<other
end
return result
end
end
class WhenNode<Node #not to appear in final tree?
param_names(:whenword_,:when!,:thenword_,:then!)
def initialize(whenword,when_,thenword,then_)
@offset=whenword.offset
when_=Array.new(when_) if CommaOpNode===when_
when_.extend ListInNode if when_.class==Array
super(when_,then_)
end
alias body then
alias consequent then
alias condition when
def image; "(when)" end
def unparse o=default_unparse_options
result=unparse_nl(self,o)+"when "
result+=condition.class==Array ?
condition.map{|cond| cond.unparse(o)}.join(',') :
condition.unparse(o)
result+=unparse_nl(consequent,o)+consequent.unparse(o) if consequent
result
end
def to_lisp
unless Node|Token===condition
"(when (#{condition.map{|cond| cond.to_lisp}.join(" ")}) #{
consequent&&consequent.to_lisp
})"
else
"(#{when_.to_lisp} #{then_.to_lisp})"
end
end
def parsetree(o)
conds=
if Node|Token===condition
[condition.rescue_parsetree(o)]
else
condition.map{|cond| cond.rescue_parsetree(o)}
end
if conds.last[0]==:splat
conds.last[0]=:when
conds.last.push nil
end
[:when, [:array, *conds],
consequent&&consequent.parsetree(o)
]
end
end
class ForNode<ValueNode
param_names(:forword_,:for!,:inword_,:in!,:doword_,:do!,:endword_)
def initialize(forword,for_,inword,in_,doword,do_,endword)
@offset=forword.offset
#elide 1 layer of parens if present
for_=for_.first if ParenedNode===for_
for_=CommaOpNode===for_ ? Array.new(for_) : [for_]
super(BlockParams.new(for_),in_,do_)
end
alias body do
alias enumerable in
alias iterator for
def image; "(for)" end
def unparse o=default_unparse_options
result=unparse_nl(self,o)+" for #{iterator.lhs_unparse(o)[1...-1]} in #{enumerable.unparse o}"
result+=unparse_nl(body,o)+" #{body.unparse(o)}" if body
result+=";end"
end
def parsetree(o)
=begin
case vars=@data[0]
when Node:
vars=vars.parsetree(o)
if vars.first==:call
vars[0]=:attrasgn
vars[2]="#{vars[2]}=".to_sym
end
vars
when Array:
vars=[:masgn, [:array,
*vars.map{|lval|
res=lval.parsetree(o)
res[0]=lval.varname2assigntype if VarNode===lval
res
}
]]
when VarNode
ident=vars.ident
vars=vars.parsetree(o)
(vars[0]=vars.varname2assigntype) rescue nil
else fail
end
=end
vars=self.for.lvalue_parsetree(o)
collection= self.in.begin_parsetree(o)
if ParenedNode===self.in and collection.first==:begin
assert collection.size==2
collection=collection[1]
end
result=[:for, collection, vars]
result.push self.do.parsetree(o) if self.do
result
end
end
class HashLiteralNode<ValueNode
def initialize(open,contents,close)
@offset=open.offset rescue contents.first.offset
case contents
when nil; super()
when ArrowOpNode; super(contents.first,contents.last)
when CommaOpNode,Array
if ArrowOpNode===contents.first
data=[]
contents.each{|pair|
ArrowOpNode===pair or fail
data.push pair.first,pair.last
}
else
@no_arrows=true
data=Array[*contents]
end
super(*data)
else fail
end
@no_braces=true unless open
end
attr :no_arrows
attr_accessor :no_braces
attr_writer :offset
def image; "({})" end
def unparse o=default_unparse_options
result=''
result << "{" unless defined? @no_braces and @no_braces
arrow= defined?(@no_arrows) ? " , " : " => "
(0...size).step(2){|i|
result<< unparse_nl(self[i],o,'')+
self[i].unparse(o)+arrow+
self[i+1].unparse(o)+', '
}
result.chomp! ', '
result << "}" unless defined? @no_braces and @no_braces
return result
end
def get k
case k
when Node;
k.delete_extraneous_ivars!
k.delete_linenums!
when Symbol, Numeric; k=LiteralNode[k]
when true,false,nil; k=VarLikeNode[k.inspect]
else raise ArgumentError
end
return as_h[k]
end
def as_h
return @h if defined? @h
@h={}
(0...size).step(2){|i|
k=self[i].dup
k.delete_extraneous_ivars!
k.delete_linenums!
@h[k]=self[i+1]
}
return @h
end
def parsetree(o)
map{|elem| elem.rescue_parsetree(o)}.unshift :hash
end
def error? rubyversion=1.8
return true if defined?(@no_arrows) and rubyversion>=1.9
return super
end
end
class TernaryNode<ValueNode
param_names :if!,:qm_,:then!,:colon_,:else!
alias condition if
alias consequent then
alias otherwise else
def initialize(if_,qm,then_,colon,else_)
super(if_,then_,else_)
condition.special_conditions! if condition.respond_to? :special_conditions!
@offset=self.first.offset
end
def image; "(?:)" end
def unparse o=default_unparse_options
"#{condition.unparse o} ? #{consequent.unparse o} : #{otherwise.unparse o}"
end
def elsifs; [] end
def parsetree(o)
cond=condition.rescue_parsetree(o)
cond[0]=:fcall if cond[0]==:vcall and cond[1].to_s[/[?!]$/]
[:if, cond, consequent.begin_parsetree(o), otherwise.begin_parsetree(o)]
end
end
class MethodNode<ValueNode
include HasRescue
param_names(:defword_,:receiver,:name,:maybe_eq_,:args,:semi_,:body,:rescues,:elses,:ensures,:endword_)
alias ensure_ ensures
alias else_ elses
alias ensure ensures
alias else elses
alias params args
def initialize(defword,header,maybe_eq_,semi_,
body,rescues,else_,ensure_,endword_)
@offset=defword.offset
@empty_else=@empty_ensure=nil
# if DotCallNode===header
# header=header.data[1]
# end
if CallSiteNode===header
receiver=header.receiver
args=header.args
header=header.name
end
if MethNameToken===header
header=header.ident
end
unless String===header
fail "unrecognized method header: #{header}"
end
if else_
else_=else_.val or @empty_else=true
end
if ensure_
ensure_=ensure_.val or @empty_ensure=true
end
args.extend ListInNode if args
rescues.extend ListInNode if rescues
replace [receiver,header,args,body,rescues,else_,ensure_]
end
attr_reader :empty_ensure, :empty_else
def self.namelist
%w[receiver name args body rescues elses ensures]
end
# def receiver= x
# self[0]=x
# end
#
# def body= x
# self[3]=x
# end
def ensure_= x
self[5]=x
end
def else_= x
self[6]=x
end
def image
"(def #{receiver.image.+('.') if receiver}#{name})"
end
def unparse o=default_unparse_options
result=[
"def ",receiver&&receiver.unparse(o)+'.',name,
args && '('+args.map{|arg| arg.unparse o}.join(',')+')', unparse_nl(body||self,o)
]
result<<unparse_and_rescues(o)
=begin
body&&result+=body.unparse(o)
result+=rescues.map{|resc| resc.unparse o}.to_s
result+="else #{else_.unparse o}\n" if else_
result+="else\n" if @empty_else
result+="ensure #{ensure_.unparse o}\n" if ensure_
result+="ensure\n" if @empty_ensure
=end
result<<unparse_nl(endline,o)+"end"
result.join
end
def to_lisp
"(imethod #{name} is\n#{body.to_lisp}\n)\n"
#no receiver, args, rescues, else_ or ensure_...
end
def parsetree(o)
name=name()
name=name.chop if /^[!~]@$/===name
name=name.to_sym
result=[name, target=[:scope, [:block, ]] ]
if receiver
result.unshift :defs, receiver.rescue_parsetree(o)
else
result.unshift :defn
end
goodies= (body or !rescues.empty? or elses or ensures or @empty_ensure) # or args())
if unamp=args() and unamp=unamp.last and UnOpNode===unamp and unamp.op=="&@"
receiver and goodies=true
else
unamp=false
end
if receiver and !goodies
target.delete_at 1 #omit :block
else
target=target[1]
end
target.push args=[:args,]
target.push unamp.parsetree(o) if unamp
if args()
initvals=[]
args().each{|arg|
case arg
when VarNode
args.push arg.ident.to_sym
when UnaryStarNode
args.push "*#{arg.val.ident}".to_sym
when UnOpNode
nil
when AssignNode
initvals << arg.parsetree(o)
initvals[-1][-1]=arg.right.rescue_parsetree(o) #ugly
args.push arg[0].ident.to_sym
else
fail "unsupported node type in method param list: #{arg}"
end
}
unless initvals.empty?
initvals.unshift(:block)
args << initvals
#args[-2][0]==:block_arg and target.push args.delete_at(-2)
end
end
target.push [:nil] if !goodies && !receiver
#it would be better to use parsetree_and_rescues for the rest of this method,
#just to be DRYer
target.push ensuretarget=target=[:ensure, ] if ensures or @empty_ensure
#simple dup won't work... won't copy extend'd modules
body=Marshal.load(Marshal.dump(body())) if body()
elses=elses()
if rescues.empty?
case body
when SequenceNode; body << elses;elses=nil
when nil; body=elses;elses=nil
else nil
end if elses
else
target.push target=[:rescue, ]
elses=elses()
end
if body
if BeginNode===body||RescueOpNode===body and
body.rescues.empty? and !body.ensure and !body.empty_ensure and body.body and body.body.size>1
wantblock=true
end
body=body.parsetree(o)
if body.first==:block and rescues.empty? and not ensures||@empty_ensure
if wantblock
target.push body
else
body.shift
target.concat body
end
else
#body=[:block, *body] if wantblock
target.push body
end
end
target.push linked_list(rescues.map{|rescue_| rescue_.parsetree(o) }) unless rescues.empty?
target.push elses.parsetree(o) if elses
ensuretarget.push ensures.parsetree(o) if ensures
ensuretarget.push [:nil] if @empty_ensure
return result
end
end
module BareSymbolUtils
def baresym2str(node)
case node
when MethNameToken; node.ident
when VarNode; node
when LiteralNode
case node.val
when Symbol
node.val.to_s
when StringNode; node.val
# when StringToken: StringNode.new(node.val)
else fail
end
end
end
def str_unparse(str,o)
case str
when VarNode; str.ident
when "~@"; str
when String
str.to_sym.inspect
#what if str isn't a valid method or operator name? should be quoted
when StringNode
":"+str.unparse(o)
else fail
end
end
def str2parsetree(str,o)
if String===str
str=str.chop if /^[!~]@$/===str
[:lit, str.to_sym]
else
result=str.parsetree(o)
result[0]=:dsym
result
end
end
end
class AliasNode < ValueNode
include BareSymbolUtils
param_names(:aliasword_,:to,:from)
def initialize(aliasword,to,from)
@offset=aliasword.offset
to=baresym2str(to)
from=baresym2str(from)
super(to,from)
end
def unparse o=default_unparse_options
"alias #{str_unparse to,o} #{str_unparse from,o}"
end
def image; "(alias)" end
def parsetree(o)
if VarNode===to and to.ident[0]==?$
[:valias, to.ident.to_sym, from.ident.to_sym]
else
[:alias, str2parsetree(to,o), str2parsetree(from,o)]
end
end
end
class UndefNode < ValueNode
include BareSymbolUtils
def initialize(first,middle,last=nil)
@offset=first.offset
if last
node,newsym=first,last
super(*node << baresym2str(newsym))
else
super(baresym2str(middle))
end
end
def image; "(undef)" end
def unparse o=default_unparse_options
"undef #{map{|name| str_unparse name,o}.join(', ')}"
end
def parsetree(o)
result=map{|name| [:undef, str2parsetree(name,o)] }
if result.size==1
result.first
else
result.unshift :block
end
end
end
class NamespaceNode<ValueNode
include HasRescue
def initialize(*args)
@empty_ensure=@empty_else=nil
super
end
end
class ModuleNode<NamespaceNode
param_names(:name,:body,:rescues,:else!,:ensure!)
def initialize moduleword,name,semiword,body,rescues,else_,ensure_,endword
@offset=moduleword.offset
else_=else_.val if else_
ensure_=ensure_.val if ensure_
rescues.extend ListInNode if rescues
super(name,body,rescues,else_,ensure_)
end
alias else_ else
alias ensure_ ensure
alias receiver name
def image; "(module #{name})" end
def unparse o=default_unparse_options
"module #{name.unparse o}#{unparse_nl(body||self,o)}#{unparse_and_rescues(o)}#{unparse_nl(endline,o)}end"
end
def parent; nil end
def to_lisp
result="(#{name.ident} #{body.to_lisp} "
#parent=@data[2]
#result+="is #{parent.to_lisp} " if parent
result+="\n"+body.to_lisp+")"
return result
end
def parsetree(o)
name=name()
if VarNode===name
name=name.ident.to_sym
elsif name.nil? #do nothing
# elsif o[:quirks]
# name=name.constant.ident.to_sym
else
name=name.parsetree(o)
end
result=[:module, name, scope=[:scope, ]]
scope << parsetree_and_rescues(o) if body
return result
end
end
class ClassNode<NamespaceNode
param_names(:name,:parent,:body,:rescues,:else!,:ensure!)
def initialize(classword,name,semi,body,rescues, else_, ensure_, endword)
@offset=classword.offset
if OpNode===name
name,op,parent=*name
op=="<" or fail "invalid superclass expression: #{name}"
end
else_=else_.val if else_
ensure_=ensure_.val if ensure_
rescues.extend ListInNode if rescues
super(name,parent,body,rescues,else_,ensure_)
end
alias else_ else
alias ensure_ ensure
alias receiver name
def image; "(class #{name})" end
def unparse o=default_unparse_options
result="class #{name.unparse o}"
result+=" < #{parent.unparse o}" if parent
result+=unparse_nl(body||self,o)+
unparse_and_rescues(o)+
unparse_nl(endline,o)+
"end"
return result
end
def to_lisp
result="(class #{name.to_lisp} "
result+="is #{parent.to_lisp} " if parent
result+="\n"+body.to_lisp+")"
return result
end
def parsetree(o)
name=name()
if VarNode===name
name=name.ident.to_sym
elsif name.nil? #do nothing
# elsif o[:quirks]
# name=name.constant.ident.to_sym
else
name=name.parsetree(o)
end
result=[:class, name, parent&&parent.parsetree(o), scope=[:scope,]]
scope << parsetree_and_rescues(o) if body
return result
end
end
class MetaClassNode<NamespaceNode
param_names :val, :body, :rescues,:else!,:ensure!
def initialize classword, leftleftword, val, semiword, body, rescues,else_,ensure_, endword
@offset=classword.offset
else_=else_.val if else_
ensure_=ensure_.val if ensure_
rescues.extend ListInNode if rescues
super(val,body,rescues,else_,ensure_)
end
alias expr val
alias object val
alias obj val
alias receiver val
alias receiver= val=
alias name val
alias ensure_ ensure
alias else_ else
def image; "(class<<)" end
def unparse o=default_unparse_options
"class << #{obj.unparse o}#{unparse_nl(body||self,o)}#{unparse_and_rescues(o)};end"
end
def parsetree(o)
result=[:sclass, expr.parsetree(o), scope=[:scope]]
scope << parsetree_and_rescues(o) if body
return result
end
end
class RescueHeaderNode<Node #not to appear in final tree
param_names :exceptions,:varname
def initialize(rescueword,arrowword,exceptions,thenword)
@offset=rescueword.offset
case exceptions
when nil
when VarNode
if arrowword
exvarname=exceptions
exceptions=nil
arrowword=nil
end
when ArrowOpNode
exvarname=exceptions.last
exceptions=exceptions.first
when CommaOpNode
lastexpr=exceptions.last
if ArrowOpNode===lastexpr
exceptions[-1]=lastexpr.left
exvarname=lastexpr.right
end
exceptions=Array.new(exceptions)
end
fail if arrowword
# fail unless VarNode===exvarname || exvarname.nil?
super(exceptions,exvarname)
end
def image; "(rescue=>)" end
end
class RescueNode<Node
param_names :exceptions,:varname,:action
def initialize(rescuehdr,action,semi)
@offset=rescuehdr.offset
exlist=rescuehdr.exceptions||[]
exlist=[exlist] unless exlist.class==Array
fail unless exlist.class==Array
exlist.extend ListInNode
super(exlist,rescuehdr.varname,action)
end
def unparse o=default_unparse_options
xx=exceptions.map{|exc| exc.unparse o}.join(',')
unparse_nl(self,o)+
"rescue #{xx} #{varname&&'=> '+varname.lhs_unparse(o)}#{unparse_nl(action||self,o)}#{action&&action.unparse(o)}"
end
def parsetree(o)
result=[:resbody, nil]
fail unless exceptions.class==Array
ex=#if Node===exceptions; [exceptions.rescue_parsetree(o)]
#elsif exceptions
exceptions.map{|exc| exc.rescue_parsetree(o)}
#end
if !ex or ex.empty? #do nothing
elsif ex.last.first!=:splat
result[1]= [:array, *ex]
elsif ex.size==1
result[1]= ex.first
else
result[1]= [:argscat, ex[0...-1].unshift(:array), ex.last[1]]
end
VarNode===varname and offset=varname.offset
action=if varname
SequenceNode.new(
AssignNode.new(
varname,
KeywordToken.new("=",offset),
VarNode.new(VarNameToken.new("$!",offset))
),nil,action()
)
else
action()
end
result.push action.parsetree(o) if action
result
end
def image; "(rescue)" end
end
class BracketsGetNode<ValueNode
param_names(:receiver,:lbrack_,:params,:rbrack_)
alias args params
def initialize(receiver,lbrack,params,rbrack)
case params
when CommaOpNode
h,arrowrange=params.extract_unbraced_hash
params=Array.new params
params[arrowrange]=[h] if arrowrange
when ArrowOpNode
h=HashLiteralNode.new(nil,params,nil)
h.startline=params.startline
h.endline=params.endline
params=[h]
when nil
params=nil
else
params=[params]
end
params.extend ListInNode if params
@offset=receiver.offset
super(receiver,params)
end
def name; "[]" end
def image; "(#{receiver.image}.[])" end
def unparse o=default_unparse_options
[ receiver.unparse(o).sub(/\s+\Z/,''),
'[',
params&¶ms.map{|param| param.unparse o}.join(','),
']'
].join
end
def parsetree(o)
result=parsetree_no_fcall o
o[:quirks] and VarLikeNode===receiver and receiver.name=='self' and
result[0..2]=[:fcall,:[]]
return result
end
def parsetree_no_fcall o
params=params()
output,star,amp=param_list_parse(params,o)
# receiver=receiver.parsetree(o)
result=[:call, receiver.rescue_parsetree(o), :[], output]
if params
if star and params.size==1
output.concat star
else
output.unshift :array
result[-1]=[:argscat, output, star.last] if star
end
else
result.pop
end
return result
end
def lvalue_parsetree(o)
result=parsetree_no_fcall o
result[0]=:attrasgn
result[2]=:[]=
result
end
def lvalue
return @lvalue if defined? @lvalue
@lvalue=true
end
attr_writer :lvalue
identity_param :lvalue, nil, true
end
class StartToken<Token #not to appear in final tree
def initialize; end
def image; "(START)" end
alias to_s image
end #beginning of input marker
class EoiToken
#hack hack: normally, this should never
#be called, but it may be when input is empty now.
def to_parsetree(*options)
[]
end
end
class GoalPostToken<Token #not to appear in final tree
def initialize(offset); @offset=offset end
def ident; "|" end
attr :offset
def image; "|" end
end
class GoalPostNode<Node #not to appear in final tree
def initialize(offset); @offset=offset end
def ident; "|" end
attr :offset
def image; "|" end
end
module ErrorNode
def error?(x=nil) @error end
alias msg error?
end
class MisparsedNode<ValueNode
include ErrorNode
param_names :open,:middle,:close_
alias begin open
alias what open
def image; "misparsed #{what}" end
#pass the buck to child ErrorNodes until there's no one else
def blame
middle.each{|node|
node.respond_to? :blame and return node.blame
}
return self
end
def error? x=nil
inner=middle.grep(MisparsedNode).first and return inner.error?( x )
"#@endline: misparsed #{what}: #{middle.map{|node| node&&node.image}.join(' ')}"
end
alias msg error?
end
module Nodes
::RedParse::constants.each{|k|
const=::RedParse::const_get(k)
const_set( k,const ) if Module===const and ::RedParse::Node>=const
}
end
end
=begin a (formal?) description
NodeMatcher=
Recursive(nodematcher={},
Node&-{:subnodes=>NodeList =
Recursive(nodelist={},
+[(nodematcher|nodelist|nil).*])
}
#Nodes can also have attributes which don't appear in subnodes
#this is where ordinary values (symbols, strings, numbers, true/false/nil) are kept
=end
|
module Breadcrumbs
def self.included receiver
receiver.extend ClassMethods
end
module ClassMethods
def add_breadcrumb name, url, *args
options = args.extract_options!
before_filter options do |controller|
url = controller.send(url) if url.class == Symbol
controller.send(:add_breadcrumb, name, url)
end
end
def add_breadcrumb_for_resource instance_variable, name_method, *args
options = args.extract_options!
before_filter options do |controller|
resource = controller.send(:instance_variable_get, "@#{instance_variable}")
controller_path = controller.send(:controller_path)
name = resource.send(name_method)
url = '/'+controller_path+"/"+resource.id.to_s
controller.send(:add_breadcrumb, name, url)
end
end
def add_breadcrumb_for_actions *args
options = args.extract_options!
before_filter options do |controller|
current_action = controller.send(:params)['action']
controller.send(:add_breadcrumb, current_action, '')
end
end
end
def add_breadcrumb name, url = ''
@breadcrumbs ||= []
url = eval(url) if url =~ /_path|_url|@/
@breadcrumbs << [name, url]
end
end
changed some variable names
module Breadcrumbs
def self.included receiver
receiver.extend ClassMethods
end
module ClassMethods
def add_breadcrumb name, url, *args
options = args.extract_options!
before_filter options do |controller|
url = controller.send(url) if url.class == Symbol
controller.send(:add_breadcrumb, name, url)
end
end
def add_breadcrumb_for_resource resource, title, *args
options = args.extract_options!
before_filter options do |controller|
resource = controller.send(:instance_variable_get, "@#{resource}")
controller_path = controller.send(:controller_path)
name = resource.send(title)
url = '/'+controller_path+"/"+resource.id.to_s
controller.send(:add_breadcrumb, name, url)
end
end
def add_breadcrumb_for_actions *args
options = args.extract_options!
before_filter options do |controller|
current_action = controller.send(:params)['action']
controller.send(:add_breadcrumb, current_action, '')
end
end
end
def add_breadcrumb name, url = ''
@breadcrumbs ||= []
url = eval(url) if url =~ /_path|_url|@/
@breadcrumbs << [name, url]
end
end
|
require 'timeout'
module Symbiont
module Element
def element(name, *identifier)
build(name, *identifier) do
define_method(name.to_s) do |*options|
find_first(*identifier, *options)
end
end
end
def elements(name, *identifier)
build(name, *identifier) do
define_method(name.to_s) do |*options|
find_all(*identifier, *options)
end
end
end
def region(name, *identifier, &block)
region_class, region_args = extract_region_details(identifier, &block)
build(name, *region_args) do
define_method(name) do
region_class.new(self, find_first(*region_args))
end
end
end
def regions(name, *identifier, &block)
region_class, region_args = extract_region_details(identifier, &block)
build(name, *region_args) do
define_method(name) do
puts "REGION ARGS: #{region_args}"
find_all(*region_args).map do |element|
puts "ELEMENT: #{element}"
region_class.new(self, element)
end
end
end
end
private
def build(name, *identifier)
add_to_mapped_elements(name)
yield
add_element_methods(name, *identifier)
end
def add_to_mapped_elements(name)
@mapped_elements ||= []
@mapped_elements << name.to_s
end
def add_element_methods(name, *identifier)
create_existence_check(name, *identifier)
create_nonexistence_check(name, *identifier)
create_wait_check(name, *identifier)
create_visible_check(name, *identifier)
create_invisible_check(name, *identifier)
end
def create_element_method(_name, *_identifier)
yield
end
def create_existence_check(name, *identifier)
method_name = "has_#{name}?"
create_element_method(method_name, *identifier) do
define_method(method_name) do |*args|
wait_time = Symbiont.use_implicit_waits ? Capybara.default_max_wait_time : 0
Capybara.using_wait_time(wait_time) do
element_exists?(*identifier, *args)
end
end
end
end
def create_nonexistence_check(name, *identifier)
method_name = "has_no_#{name}?"
create_element_method(method_name, *identifier) do
define_method(method_name) do |*args|
wait_time = Symbiont.use_implicit_waits ? Capybara.default_max_wait_time : 0
Capybara.using_wait_time(wait_time) do
element_does_not_exist?(*identifier, *args)
end
end
end
end
def create_wait_check(name, *identifier)
method_name = "wait_for_#{name}"
create_element_method(method_name, *identifier) do
define_method(method_name) do |timeout = nil, *args|
timeout = timeout.nil? ? Capybara.default_max_wait_time : timeout
Capybara.using_wait_time(timeout) do
element_exists?(*identifier, *args)
end
end
end
end
def create_visible_check(name, *identifier)
method_name = "wait_until_#{name}_visible"
create_element_method(method_name, *identifier) do
define_method(method_name) do |timeout = Capybara.default_max_wait_time, *args|
Timeout.timeout(timeout, Symbiont::Errors::ElementVisibleTimeout) do
Capybara.using_wait_time(0) do
sleep(0.05) until element_exists?(*identifier, *args, visible: true)
end
end
end
end
end
def create_invisible_check(name, *identifier)
method_name = "wait_until_#{name}_invisible"
create_element_method(name, *identifier) do
define_method(method_name) do |timeout = Capybara.default_max_wait_time, *args|
Timeout.timeout(timeout, Symbiont::Errors::ElementNonVisibleTimeout) do
Capybara.using_wait_time(0) do
sleep(0.05) while element_exists?(*identifier, *args, visible: true)
end
end
end
end
end
def extract_region_details(identifier, &block)
if identifier.first.is_a?(Class)
region_class = identifier.shift
elsif block_given?
region_class = Class.new(Symbiont::Region, &block)
else
fail(ArgumentError, 'Provide a region class either as a block or as the second argument.')
end
[region_class, identifier]
end
end
end
Add ability to support query options in regions.
require 'timeout'
module Symbiont
module Element
def element(name, *identifier)
build(name, *identifier) do
define_method(name.to_s) do |*options|
find_first(*identifier, *options)
end
end
end
def elements(name, *identifier)
build(name, *identifier) do
define_method(name.to_s) do |*options|
find_all(*identifier, *options)
end
end
end
def region(name, *identifier, &block)
region_class, region_args = extract_region_details(identifier, &block)
build(name, *region_args) do
define_method(name) do |*options|
region_class.new(self, find_first(*region_args, *options))
end
end
end
def regions(name, *identifier, &block)
region_class, region_args = extract_region_details(identifier, &block)
build(name, *region_args) do
define_method(name) do |*options|
find_all(*region_args, *options).map do |element|
region_class.new(self, element)
end
end
end
end
private
def build(name, *identifier)
add_to_mapped_elements(name)
yield
add_element_methods(name, *identifier)
end
def add_to_mapped_elements(name)
@mapped_elements ||= []
@mapped_elements << name.to_s
end
def add_element_methods(name, *identifier)
create_existence_check(name, *identifier)
create_nonexistence_check(name, *identifier)
create_wait_check(name, *identifier)
create_visible_check(name, *identifier)
create_invisible_check(name, *identifier)
end
def create_element_method(_name, *_identifier)
yield
end
def create_existence_check(name, *identifier)
method_name = "has_#{name}?"
create_element_method(method_name, *identifier) do
define_method(method_name) do |*args|
wait_time = Symbiont.use_implicit_waits ? Capybara.default_max_wait_time : 0
Capybara.using_wait_time(wait_time) do
element_exists?(*identifier, *args)
end
end
end
end
def create_nonexistence_check(name, *identifier)
method_name = "has_no_#{name}?"
create_element_method(method_name, *identifier) do
define_method(method_name) do |*args|
wait_time = Symbiont.use_implicit_waits ? Capybara.default_max_wait_time : 0
Capybara.using_wait_time(wait_time) do
element_does_not_exist?(*identifier, *args)
end
end
end
end
def create_wait_check(name, *identifier)
method_name = "wait_for_#{name}"
create_element_method(method_name, *identifier) do
define_method(method_name) do |timeout = nil, *args|
timeout = timeout.nil? ? Capybara.default_max_wait_time : timeout
Capybara.using_wait_time(timeout) do
element_exists?(*identifier, *args)
end
end
end
end
def create_visible_check(name, *identifier)
method_name = "wait_until_#{name}_visible"
create_element_method(method_name, *identifier) do
define_method(method_name) do |timeout = Capybara.default_max_wait_time, *args|
Timeout.timeout(timeout, Symbiont::Errors::ElementVisibleTimeout) do
Capybara.using_wait_time(0) do
sleep(0.05) until element_exists?(*identifier, *args, visible: true)
end
end
end
end
end
def create_invisible_check(name, *identifier)
method_name = "wait_until_#{name}_invisible"
create_element_method(name, *identifier) do
define_method(method_name) do |timeout = Capybara.default_max_wait_time, *args|
Timeout.timeout(timeout, Symbiont::Errors::ElementNonVisibleTimeout) do
Capybara.using_wait_time(0) do
sleep(0.05) while element_exists?(*identifier, *args, visible: true)
end
end
end
end
end
def extract_region_details(identifier, &block)
if identifier.first.is_a?(Class)
region_class = identifier.shift
elsif block_given?
region_class = Class.new(Symbiont::Region, &block)
else
fail(ArgumentError, 'Provide a region class either as a block or as the second argument.')
end
[region_class, identifier]
end
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
Add seed data.
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
member1 = Member.create(id: 1, name: 'Member1')
member2 = Member.create(id: 2, name: 'Member2')
Message.create(content: 'message1 for member1', member: member1)
Message.create(content: 'message2 for member1', member: member1)
Message.create(content: 'message3 for member1', member: member1)
Message.create(content: 'message4 for member1', member: member1)
Message.create(content: 'message5 for member1', member: member1)
Message.create(content: 'message6 for member1', member: member1)
Message.create(content: 'message7 for member1', member: member1)
Message.create(content: 'message8 for member1', member: member1)
Message.create(content: 'message1 for member2', member: member2)
Message.create(content: 'message2 for member2', member: member2)
Message.create(content: 'message3 for member2', member: member2)
Message.create(content: 'message4 for member2', member: member2)
Message.create(content: 'message5 for member2', member: member2)
|
require "refile/memory/version"
module Refile
module Memory
class Backend
attr_reader :directory
def initialize(max_size: nil, hasher: Refile::RandomHasher.new)
@hasher = hasher
@max_size = max_size
@store = {}
end
def upload(uploadable)
Refile.verify_uploadable(uploadable, @max_size)
id = @hasher.hash(uploadable)
@store[id] = uploadable.read
Refile::File.new(self, id)
end
def get(id)
Refile::File.new(self, id)
end
def delete(id)
@store.delete(id)
end
def open(id)
StringIO.new(@store[id])
end
def read(id)
@store[id]
end
def size(id)
@store[id].bytesize if exists?(id)
end
def exists?(id)
@store.has_key?(id)
end
def clear!(confirm = nil)
raise ArgumentError, "are you sure? this will remove all files in the backend, call as `clear!(:confirm)` if you're sure you want to do this" unless confirm == :confirm
@store = {}
end
end
end
end
Make sure we require refile
require "refile"
require "refile/memory/version"
module Refile
module Memory
class Backend
attr_reader :directory
def initialize(max_size: nil, hasher: Refile::RandomHasher.new)
@hasher = hasher
@max_size = max_size
@store = {}
end
def upload(uploadable)
Refile.verify_uploadable(uploadable, @max_size)
id = @hasher.hash(uploadable)
@store[id] = uploadable.read
Refile::File.new(self, id)
end
def get(id)
Refile::File.new(self, id)
end
def delete(id)
@store.delete(id)
end
def open(id)
StringIO.new(@store[id])
end
def read(id)
@store[id]
end
def size(id)
@store[id].bytesize if exists?(id)
end
def exists?(id)
@store.has_key?(id)
end
def clear!(confirm = nil)
raise ArgumentError, "are you sure? this will remove all files in the backend, call as `clear!(:confirm)` if you're sure you want to do this" unless confirm == :confirm
@store = {}
end
end
end
end
|
fail "Users exist" if User.count > 0
admin = User.create!(
name: ENV['ADMIN_NAME'],
email: ENV['ADMIN_EMAIL'],
username: "admin",
password: ENV['ADMIN_PASSWORD'],
password_confirmation: ENV['ADMIN_PASSWORD'],
admin: true
)
admin.confirm!
puts "Admin Created: #{admin.email}"
Assume present of env vars
fail "Users exist" if User.count > 0
admin = User.create!(
name: ENV.fetch('ADMIN_NAME'),
email: ENV.fetch('ADMIN_EMAIL'),
username: "admin",
password: ENV.fetch('ADMIN_PASSWORD'),
password_confirmation: ENV.fetch('ADMIN_PASSWORD'),
admin: true
)
admin.confirm!
puts "Admin Created: #{admin.email}"
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
coms = [
{title_en: 'Student Division Board', title_sv: 'Styrelse', name: 'styrIT', url: 'http://styrit.chalmers.it', email: 'styrit@chalmers.it' },
{title_en: 'Student Educational Committee', title_sv: 'Studienämnd', name: 'snIT', url: 'http://snit.chalmers.it', email: 'snit@chalmers.it' },
{title_en: 'Sexmästeri', title_sv: 'Sexmästeri', name: 'sexIT', url: 'http://sexit.chalmers.it', email: 'sexit@chalmers.it' },
{title_en: 'PR & Rustmästeri', title_sv: 'PR & Rustmästeri', name: 'P.R.I.T.', url: 'http://prit.chalmers.it', email: 'prit@chalmers.it' },
{title_en: 'Student Reception Committee', title_sv: 'Mottagningskommitté', name: 'NollKIT', url: 'http://nollk.it', email: 'nollkit@chalmers.it' },
{title_en: 'Business Relations Committee', title_sv: 'Arbetsmarknad', name: 'ArmIT', url: 'http://armit.se', email: 'armit@chalmers.it' },
{title_en: 'Digital systems', title_sv: 'Digitala system', name: 'digIT', url: 'http://digit.chalmers.it', email: 'digit@chalmers.it' },
{title_en: 'Standard Bearers', title_sv: 'Fanbärare', name: 'FanbärerIT', url: 'http://fanbärerit.chalmers.it', email: 'fanbärerit@chalmers.it' },
{title_en: 'Physical Activities', title_sv: 'Fysiska aktiviteter', name: 'frITid', url: 'http://fritid.chalmers.it', email: 'fritid@chalmers.it' },
{title_en: 'Digital games', title_sv: 'Digitala spel', name: '8-bIT', url: 'http://8bit.chalmers.it', email: '8bit@chalmers.it' },
{title_en: 'Analog games', title_sv: 'Analoga spel', name: 'DrawIT', url: 'http://drawit.chalmers.it', email: 'drawit@chalmers.it' },
{title_en: 'Photo Committee', title_sv: 'Foto', name: 'FlashIT', url: 'http://flashit.chalmers.it', email: 'flashit@chalmers.it' },
{title_en: 'Chugging Committee', title_sv: 'Häfv och odygd', name: 'HookIT', url: 'http://hookit.chalmers.it', email: 'hookit@chalmers.it' },
{title_en: 'Auditors', title_sv: 'Sektionens revisorer', name: 'Revisorer', url: 'http://revisorer.chalmers.it', email: 'revisorer@chalmers.it' },
{title_en: 'Nomination Committee', title_sv: 'Valberedning', name: 'Valberedningen', url: 'http://valberedningen.chalmers.it', email: 'valberedningen@chalmers.it' }
]
Committee.delete_all
coms.each do |c|
desc = "Lorem ipsum osv"
c.merge!(slug: c[:name].gsub('.', '').parameterize, description_en: desc, description_sv: desc )
Committee.create!(c)
end
periods = [
{ name: 'Period 1'},
{ name: 'Period 2'},
{ name: 'Period 3'},
{ name: 'Period 4'}
]
periods.each do |p|
Period.create!(p)
end
main_menu = Menu.create(name: 'main')
[
{ controller: "pages", action: "index", title: "section", preferred_order: 0 },
{ controller: "posts", action: "index", title: "news", preferred_order: 1 },
{ controller: "courses", action: "index", title: "courses", preferred_order: 2 },
{ controller: "redirect", action: "findit", title: "services", preferred_order: 3 },
{ controller: "contact", action: "index", title: "contact", preferred_order: 4 }
].each do |link|
MenuLink.create(link.merge(menu: main_menu))
end
unless Page.where(slug: "student-division").exists?
page = Page.create(title_sv: "Sektionen", body_sv: "Lorem ipsum osv", title_en: "Student Division", body_en: "Lorem ipsum etc", slug: "student-division", parent_id: nil)
frontpage = Frontpage.create(page_id: page.id)
end
add company page to header
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
coms = [
{title_en: 'Student Division Board', title_sv: 'Styrelse', name: 'styrIT', url: 'http://styrit.chalmers.it', email: 'styrit@chalmers.it' },
{title_en: 'Student Educational Committee', title_sv: 'Studienämnd', name: 'snIT', url: 'http://snit.chalmers.it', email: 'snit@chalmers.it' },
{title_en: 'Sexmästeri', title_sv: 'Sexmästeri', name: 'sexIT', url: 'http://sexit.chalmers.it', email: 'sexit@chalmers.it' },
{title_en: 'PR & Rustmästeri', title_sv: 'PR & Rustmästeri', name: 'P.R.I.T.', url: 'http://prit.chalmers.it', email: 'prit@chalmers.it' },
{title_en: 'Student Reception Committee', title_sv: 'Mottagningskommitté', name: 'NollKIT', url: 'http://nollk.it', email: 'nollkit@chalmers.it' },
{title_en: 'Business Relations Committee', title_sv: 'Arbetsmarknad', name: 'ArmIT', url: 'http://armit.se', email: 'armit@chalmers.it' },
{title_en: 'Digital systems', title_sv: 'Digitala system', name: 'digIT', url: 'http://digit.chalmers.it', email: 'digit@chalmers.it' },
{title_en: 'Standard Bearers', title_sv: 'Fanbärare', name: 'FanbärerIT', url: 'http://fanbärerit.chalmers.it', email: 'fanbärerit@chalmers.it' },
{title_en: 'Physical Activities', title_sv: 'Fysiska aktiviteter', name: 'frITid', url: 'http://fritid.chalmers.it', email: 'fritid@chalmers.it' },
{title_en: 'Digital games', title_sv: 'Digitala spel', name: '8-bIT', url: 'http://8bit.chalmers.it', email: '8bit@chalmers.it' },
{title_en: 'Analog games', title_sv: 'Analoga spel', name: 'DrawIT', url: 'http://drawit.chalmers.it', email: 'drawit@chalmers.it' },
{title_en: 'Photo Committee', title_sv: 'Foto', name: 'FlashIT', url: 'http://flashit.chalmers.it', email: 'flashit@chalmers.it' },
{title_en: 'Chugging Committee', title_sv: 'Häfv och odygd', name: 'HookIT', url: 'http://hookit.chalmers.it', email: 'hookit@chalmers.it' },
{title_en: 'Auditors', title_sv: 'Sektionens revisorer', name: 'Revisorer', url: 'http://revisorer.chalmers.it', email: 'revisorer@chalmers.it' },
{title_en: 'Nomination Committee', title_sv: 'Valberedning', name: 'Valberedningen', url: 'http://valberedningen.chalmers.it', email: 'valberedningen@chalmers.it' }
]
Committee.delete_all
coms.each do |c|
desc = "Lorem ipsum osv"
c.merge!(slug: c[:name].gsub('.', '').parameterize, description_en: desc, description_sv: desc )
Committee.create!(c)
end
periods = [
{ name: 'Period 1'},
{ name: 'Period 2'},
{ name: 'Period 3'},
{ name: 'Period 4'}
]
periods.each do |p|
Period.create!(p)
end
main_menu = Menu.create(name: 'main')
[
{ controller: "pages", action: "index", title: "section", preferred_order: 0 },
{ controller: "posts", action: "index", title: "news", preferred_order: 1 },
{ controller: "courses", action: "index", title: "courses", preferred_order: 2 },
{ controller: "redirect", action: "findit", title: "services", preferred_order: 3 },
{ controller: "contact", action: "index", title: "contact", preferred_order: 4 },
{ controller: "pages", action: "show", title: "companies", preferred_order: 5, params: {id: "companies"}}
].each do |link|
MenuLink.create(link.merge(menu: main_menu))
end
unless Page.where(slug: "student-division").exists?
page = Page.create(title_sv: "Sektionen", body_sv: "Lorem ipsum osv", title_en: "Student Division", body_en: "Lorem ipsum etc", slug: "student-division", parent_id: nil)
frontpage = Frontpage.create(page_id: page.id)
end
unless Page.where(slug: "companies").exists?
page = Page.create(title_sv: "Företag", body_sv: "Lorem ipsum osv", title_en: "Companies", body_en: "Lorem ipsum etc", slug: "companies", parent_id: nil)
end
|
require 'representable/definition'
require 'representable/deprecations'
# Representable can be used in two ways.
#
# == On class level
#
# To try out Representable you might include the format module into the represented class directly and then
# define the properties.
#
# class Hero < ActiveRecord::Base
# include Representable::JSON
# property :name
#
# This will give you to_/from_json for each instance. However, this approach limits your class to one representation.
#
# == On module level
#
# Modules give you much more flexibility since you can mix them into objects at runtime, roughly following the DCI
# pattern.
#
# module HeroRepresenter
# include Representable::JSON
# property :name
# end
#
# hero.extend(HeroRepresenter).to_json
module Representable
attr_writer :representable_attrs
def self.included(base)
base.class_eval do
include Deprecations
extend ClassMethods
extend ClassMethods::Declarations
extend ClassMethods::Accessors
def self.included(base)
base.representable_attrs.push(*representable_attrs.clone) # "inherit".
end
# Copies the representable_attrs to the extended object.
def self.extended(object)
object.representable_attrs=(representable_attrs)
end
end
end
# Reads values from +doc+ and sets properties accordingly.
def update_properties_from(doc, options, format)
representable_bindings_for(format).each do |bin|
next if skip_property?(bin, options)
uncompile_fragment(bin, doc)
end
self
end
private
# Compiles the document going through all properties.
def create_representation_with(doc, options, format)
representable_bindings_for(format).each do |bin|
next if skip_property?(bin, options)
compile_fragment(bin, doc)
end
doc
end
# Checks and returns if the property should be included.
def skip_property?(binding, options)
return true if skip_excluded_property?(binding, options) # no need for further evaluation when :exclude'ed
skip_conditional_property?(binding)
end
def skip_excluded_property?(binding, options)
return unless props = options[:exclude] || options[:include]
res = props.include?(binding.definition.name.to_sym)
options[:include] ? !res : res
end
def skip_conditional_property?(binding)
return unless condition = binding.definition.options[:if]
not instance_exec(&condition)
end
# Retrieve value and write fragment to the doc.
def compile_fragment(bin, doc)
value = send(bin.definition.getter)
# centralize the nil check here, on purpose. i do that in favor of Definition#default_for.
value = bin.definition.default if bin.definition.skipable_nil_value?(value)
write_fragment_for(bin, value, doc) unless bin.definition.skipable_nil_value?(value)
end
# Parse value from doc and update the model property.
def uncompile_fragment(bin, doc)
value = read_fragment_for(bin, doc)
value = bin.definition.default if bin.definition.skipable_nil_value?(value)
send(bin.definition.setter, value)
end
def write_fragment_for(bin, value, doc) # DISCUSS: move to Binding?
bin.write(doc, value)
end
def read_fragment_for(bin, doc) # DISCUSS: move to Binding?
bin.read(doc)
end
def representable_attrs
@representable_attrs ||= self.class.representable_attrs # DISCUSS: copy, or better not?
end
def representable_bindings_for(format)
representable_attrs.map {|attr| format.binding_for_definition(attr) }
end
# Returns the wrapper for the representation. Mostly used in XML.
def representation_wrap
representable_attrs.wrap_for(self.class.name)
end
module ClassMethods # :nodoc:
# Create and yield object and options. Called in .from_json and friends.
def create_represented(document, *args)
new.tap do |represented|
yield represented, *args if block_given?
end
end
module Declarations
def definition_class
Definition
end
# Declares a represented document node, which is usually a XML tag or a JSON key.
#
# Examples:
#
# property :name
# property :name, :from => :title
# property :name, :class => Name
# property :name, :default => "Mike"
# property :name, :include_nil => true
def property(name, options={})
representable_attrs << definition_class.new(name, options)
end
# Declares a represented document node collection.
#
# Examples:
#
# collection :products
# collection :products, :from => :item
# collection :products, :class => Product
def collection(name, options={})
options[:collection] = true
property(name, options)
end
def hash(name=nil, options={})
return super() unless name # allow Object.hash.
options[:hash] = true
property(name, options)
end
end
module Accessors
def representable_attrs
@representable_attrs ||= Config.new
end
def representation_wrap=(name)
representable_attrs.wrap = name
end
end
end
class Config < Array
attr_accessor :wrap
# Computes the wrap string or returns false.
def wrap_for(name)
return unless wrap
return infer_name_for(name) if wrap === true
wrap
end
def clone
self.class.new(collect { |d| d.clone })
end
private
def infer_name_for(name)
name.to_s.split('::').last.
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
downcase
end
end
end
using Defintion#default_for now. this distributes knowledge of nil values to Definition and Representable, which might make things a bit less obvious. let's see.
require 'representable/definition'
require 'representable/deprecations'
# Representable can be used in two ways.
#
# == On class level
#
# To try out Representable you might include the format module into the represented class directly and then
# define the properties.
#
# class Hero < ActiveRecord::Base
# include Representable::JSON
# property :name
#
# This will give you to_/from_json for each instance. However, this approach limits your class to one representation.
#
# == On module level
#
# Modules give you much more flexibility since you can mix them into objects at runtime, roughly following the DCI
# pattern.
#
# module HeroRepresenter
# include Representable::JSON
# property :name
# end
#
# hero.extend(HeroRepresenter).to_json
module Representable
attr_writer :representable_attrs
def self.included(base)
base.class_eval do
include Deprecations
extend ClassMethods
extend ClassMethods::Declarations
extend ClassMethods::Accessors
def self.included(base)
base.representable_attrs.push(*representable_attrs.clone) # "inherit".
end
# Copies the representable_attrs to the extended object.
def self.extended(object)
object.representable_attrs=(representable_attrs)
end
end
end
# Reads values from +doc+ and sets properties accordingly.
def update_properties_from(doc, options, format)
representable_bindings_for(format).each do |bin|
next if skip_property?(bin, options)
uncompile_fragment(bin, doc)
end
self
end
private
# Compiles the document going through all properties.
def create_representation_with(doc, options, format)
representable_bindings_for(format).each do |bin|
next if skip_property?(bin, options)
compile_fragment(bin, doc)
end
doc
end
# Checks and returns if the property should be included.
def skip_property?(binding, options)
return true if skip_excluded_property?(binding, options) # no need for further evaluation when :exclude'ed
skip_conditional_property?(binding)
end
def skip_excluded_property?(binding, options)
return unless props = options[:exclude] || options[:include]
res = props.include?(binding.definition.name.to_sym)
options[:include] ? !res : res
end
def skip_conditional_property?(binding)
return unless condition = binding.definition.options[:if]
not instance_exec(&condition)
end
# Retrieve value and write fragment to the doc.
def compile_fragment(bin, doc)
value = send(bin.definition.getter)
value = bin.definition.default_for(value)
write_fragment_for(bin, value, doc)
end
# Parse value from doc and update the model property.
def uncompile_fragment(bin, doc)
value = read_fragment_for(bin, doc)
value = bin.definition.default_for(value)
send(bin.definition.setter, value)
end
def write_fragment_for(bin, value, doc) # DISCUSS: move to Binding?
return if bin.definition.skipable_nil_value?(value)
bin.write(doc, value)
end
def read_fragment_for(bin, doc) # DISCUSS: move to Binding?
bin.read(doc)
end
def representable_attrs
@representable_attrs ||= self.class.representable_attrs # DISCUSS: copy, or better not?
end
def representable_bindings_for(format)
representable_attrs.map {|attr| format.binding_for_definition(attr) }
end
# Returns the wrapper for the representation. Mostly used in XML.
def representation_wrap
representable_attrs.wrap_for(self.class.name)
end
module ClassMethods # :nodoc:
# Create and yield object and options. Called in .from_json and friends.
def create_represented(document, *args)
new.tap do |represented|
yield represented, *args if block_given?
end
end
module Declarations
def definition_class
Definition
end
# Declares a represented document node, which is usually a XML tag or a JSON key.
#
# Examples:
#
# property :name
# property :name, :from => :title
# property :name, :class => Name
# property :name, :default => "Mike"
# property :name, :include_nil => true
def property(name, options={})
representable_attrs << definition_class.new(name, options)
end
# Declares a represented document node collection.
#
# Examples:
#
# collection :products
# collection :products, :from => :item
# collection :products, :class => Product
def collection(name, options={})
options[:collection] = true
property(name, options)
end
def hash(name=nil, options={})
return super() unless name # allow Object.hash.
options[:hash] = true
property(name, options)
end
end
module Accessors
def representable_attrs
@representable_attrs ||= Config.new
end
def representation_wrap=(name)
representable_attrs.wrap = name
end
end
end
class Config < Array
attr_accessor :wrap
# Computes the wrap string or returns false.
def wrap_for(name)
return unless wrap
return infer_name_for(name) if wrap === true
wrap
end
def clone
self.class.new(collect { |d| d.clone })
end
private
def infer_name_for(name)
name.to_s.split('::').last.
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
downcase
end
end
end
|
# coding: utf-8
puts 'Seeding the database...'
[
{ pt: 'Porto Alegre', en: 'Porto Alegre' },
{ pt: 'Rio de Janeiro', en: 'Rio de Janeiro' },
{ pt: 'São Paulo', en: 'São Paulo' },
{ pt: 'Floripa', en: 'Floripa' }
].each do |name|
category = Category.find_or_initialize_by_name_pt name[:pt]
category.update_attributes({
name_en: name[:en]
})
end
[
'confirm_backer','payment_slip','project_success','backer_project_successful',
'backer_project_unsuccessful','project_received', 'project_received_channel', 'updates','project_unsuccessful',
'project_visible','processing_payment','new_draft_project', 'new_draft_channel', 'project_rejected',
'pending_backer_project_unsuccessful', 'project_owner_backer_confirmed', 'adm_project_deadline',
'project_in_wainting_funds', 'credits_warning', 'backer_confirmed_after_project_was_closed',
'backer_canceled_after_confirmed', 'new_user_registration'
].each do |name|
NotificationType.find_or_create_by_name name
end
{
company_name: 'Mútuo',
host: 'mutuo.cc',
base_url: "http://mutuo.cc",
blog_url: "http://blog.mutuo.cc",
email_contact: 'contato@mutuo.cc',
email_payments: 'financeiro@mutuo.cc',
email_projects: 'projetos@mutuo.cc',
email_system: 'system@mutuo.cc',
email_no_reply: 'no-reply@mutuo.cc',
facebook_url: "http://facebook.com/mutuo.cc",
facebook_app_id: '1405409603010977',
twitter_url: 'https://twitter.com/mutuo_cc',
twitter_username: "mutuo_cc",
mailchimp_url: "",
catarse_fee: '0.15',
support_forum: 'http://suporte.mutuo.cc/',
base_domain: 'mutuo.cc',
uservoice_secret_gadget: 'change_this',
uservoice_key: 'uservoice_key',
project_finish_time: '02:59:59',
mandrill_username: 'enzozuccolotto@gmail.com',
mandrill_api_key: 'PhwKttWY1EFr1r8jfYI8Eg'
}.each do |name, value|
conf = Configuration.find_or_initialize_by_name name
conf.update_attributes({
value: value
})
end
# Channel.find_or_create_by_name!(
# name: "Channel name",
# permalink: "sample-permalink",
# description: "Lorem Ipsum"
# )
OauthProvider.find_or_create_by_name!(
name: 'facebook',
key: '1405409603010977',
secret: '72712d7f5780efbac72e28add09b1ec0',
path: 'facebook'
)
puts
puts '============================================='
puts ' Showing all Authentication Providers'
puts '---------------------------------------------'
OauthProvider.all.each do |conf|
a = conf.attributes
puts " name #{a['name']}"
puts " key: #{a['key']}"
puts " secret: #{a['secret']}"
puts " path: #{a['path']}"
puts
end
puts
puts '============================================='
puts ' Showing all entries in Configuration Table...'
puts '---------------------------------------------'
Configuration.all.each do |conf|
a = conf.attributes
puts " #{a['name']}: #{a['value']}"
end
puts '---------------------------------------------'
puts 'Done!'
updating seeds
# coding: utf-8
puts 'Seeding the database...'
[
{ pt: 'Porto Alegre', en: 'Porto Alegre' },
{ pt: 'Rio de Janeiro', en: 'Rio de Janeiro' },
{ pt: 'São Paulo', en: 'São Paulo' },
{ pt: 'Floripa', en: 'Floripa' }
].each do |name|
category = Category.find_or_initialize_by_name_pt name[:pt]
category.update_attributes({
name_en: name[:en]
})
end
[
'confirm_backer','payment_slip','project_success','backer_project_successful',
'backer_project_unsuccessful','project_received', 'project_received_channel', 'updates','project_unsuccessful',
'project_visible','processing_payment','new_draft_project', 'new_draft_channel', 'project_rejected',
'pending_backer_project_unsuccessful', 'project_owner_backer_confirmed', 'adm_project_deadline',
'project_in_wainting_funds', 'credits_warning', 'backer_confirmed_after_project_was_closed',
'backer_canceled_after_confirmed', 'new_user_registration'
].each do |name|
NotificationType.find_or_create_by_name name
end
{
company_name: 'Mútuo',
host: 'mutuo.cc',
base_url: "http://mutuo.cc",
blog_url: "http://mutuo.cc/blog",
email_contact: 'contato@mutuo.cc',
email_payments: 'financeiro@mutuo.cc',
email_projects: 'projetos@mutuo.cc',
email_system: 'system@mutuo.cc',
email_no_reply: 'no-reply@mutuo.cc',
facebook_url: "http://facebook.com/mutuo.cc",
facebook_app_id: '1405409603010977',
twitter_url: 'https://twitter.com/mutuo_cc',
twitter_username: "mutuo_cc",
mailchimp_url: "",
catarse_fee: '0.15',
support_forum: 'http://suporte.mutuo.cc/',
base_domain: 'mutuo.cc',
uservoice_secret_gadget: 'change_this',
uservoice_key: 'uservoice_key',
project_finish_time: '02:59:59',
mandrill_username: 'enzozuccolotto@gmail.com',
mandrill_api_key: 'PhwKttWY1EFr1r8jfYI8Eg'
}.each do |name, value|
conf = Configuration.find_or_initialize_by_name name
conf.update_attributes({
value: value
})
end
# Channel.find_or_create_by_name!(
# name: "Channel name",
# permalink: "sample-permalink",
# description: "Lorem Ipsum"
# )
OauthProvider.find_or_create_by_name!(
name: 'facebook',
key: '1405409603010977',
secret: '72712d7f5780efbac72e28add09b1ec0',
path: 'facebook'
)
puts
puts '============================================='
puts ' Showing all Authentication Providers'
puts '---------------------------------------------'
OauthProvider.all.each do |conf|
a = conf.attributes
puts " name #{a['name']}"
puts " key: #{a['key']}"
puts " secret: #{a['secret']}"
puts " path: #{a['path']}"
puts
end
puts
puts '============================================='
puts ' Showing all entries in Configuration Table...'
puts '---------------------------------------------'
Configuration.all.each do |conf|
a = conf.attributes
puts " #{a['name']}: #{a['value']}"
end
puts '---------------------------------------------'
puts 'Done!'
|
# Default Super admin
Admin.create(first_name: "Admin", last_name: "Katalyst", email: "admin@katalyst.com.au",
role: "Super", password: "katalyst", password_confirmation: "katalyst")
Admin.create(first_name: "Rahul", last_name: "Trikha", email: "rahul@katalyst.com.au",
role: "Admin", password: "katalyst", password_confirmation: "katalyst")
Admin.create(first_name: "Jason", last_name: "Sidoryn", email: "jason@katalyst.com.au",
role: "Admin", password: "katalyst", password_confirmation: "katalyst")
# RootNavItem.create!(title: "Home", url: "/", key: "home")
header = FolderNavItem.create!(title: "Header Navigation", parent: RootNavItem.root, key: "header_navigation")
footer = FolderNavItem.create!(title: "Footer Navigation", parent: RootNavItem.root, key: "footer_navigation")
# Few Header Pages
about_us_page = Page.create!(title: "About Us").to_navigator!(parent_id: header.id)
contact_us_page = Page.create!(title: "Contact Us").to_navigator!(parent_id: header.id)
# Few Aliases
AliasNavItem.create!(title: "About Us", alias_id: about_us_page.id, parent: footer)
AliasNavItem.create!(title: "Contact Us", alias_id: contact_us_page.id, parent: footer)
# One Footer Pages
privacy_policy_page = Page.create!(title: "Privacy Policy").to_navigator!(parent_id: footer.id)
# Settings
Translation.create!(label: "Site Title", key: "site.title", value: "Site Title", field_type: "string")
Translation.create!(label: "Site Meta Description", key: "site.meta_description", value: "Meta Description", field_type: "text")
Translation.create!(label: "Site Meta Keywords", key: "site.meta_keywords", value: "Meta Keywords", field_type: "text")
Translation.create!(label: "Google Analytics", key: "site.google_analytics", value: "Google Analytics code", field_type: "text")
Changed google analytics default value to script
# Default Super admin
Admin.create(first_name: "Admin", last_name: "Katalyst", email: "admin@katalyst.com.au",
role: "Super", password: "katalyst", password_confirmation: "katalyst")
Admin.create(first_name: "Rahul", last_name: "Trikha", email: "rahul@katalyst.com.au",
role: "Admin", password: "katalyst", password_confirmation: "katalyst")
Admin.create(first_name: "Jason", last_name: "Sidoryn", email: "jason@katalyst.com.au",
role: "Admin", password: "katalyst", password_confirmation: "katalyst")
# RootNavItem.create!(title: "Home", url: "/", key: "home")
header = FolderNavItem.create!(title: "Header Navigation", parent: RootNavItem.root, key: "header_navigation")
footer = FolderNavItem.create!(title: "Footer Navigation", parent: RootNavItem.root, key: "footer_navigation")
# Few Header Pages
about_us_page = Page.create!(title: "About Us").to_navigator!(parent_id: header.id)
contact_us_page = Page.create!(title: "Contact Us").to_navigator!(parent_id: header.id)
# Few Aliases
AliasNavItem.create!(title: "About Us", alias_id: about_us_page.id, parent: footer)
AliasNavItem.create!(title: "Contact Us", alias_id: contact_us_page.id, parent: footer)
# One Footer Pages
privacy_policy_page = Page.create!(title: "Privacy Policy").to_navigator!(parent_id: footer.id)
# Settings
Translation.create!(label: "Site Title", key: "site.title", value: "Site Title", field_type: "string")
Translation.create!(label: "Site Meta Description", key: "site.meta_description", value: "Meta Description", field_type: "text")
Translation.create!(label: "Site Meta Keywords", key: "site.meta_keywords", value: "Meta Keywords", field_type: "text")
Translation.create!(label: "Google Analytics", key: "site.google_analytics", value: "<script></script>", field_type: "text")
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
#!/bin/env ruby
# encoding: utf-8
# Central requirements
CustomRequirement.create(
name: 'Physical Exam',
description: 'Checkup by a doctor',
uri: 'http://www.health.ri.gov/forms/school/Physical.pdf',
req_type: :url,
authority_level: :central
)
# West Warwick School District
west_warick_district = District.create(
name: 'West Warwick Public Schools',
mailing_street_address_1: "10 Harris Ave",
mailing_city: 'West Warwick',
mailing_state: 'RI',
mailing_zip_code: '02984',
phone: '4018211180',
active: true
)
WelcomeMessage.create(
message: "<p>Welcome to West Warwick Public Schools!</p><p>Please register!</p>",
language: 'en',
district: west_warick_district
)
CustomRequirement.create(
name: 'Release Authorization',
description: 'Permission to release records',
req_type: :file,
district: west_warick_district,
authority_level: :district
)
greenbush_elementary_school = School.create(
name: 'Greenbush Elementary School',
mailing_street_address_1: '127 Greenbush Road',
mailing_city: 'West Warwick',
mailing_state: 'RI',
mailing_zip_code: '02893',
phone: '4018228454',
active: true,
district: west_warick_district
)
john_f_horgan_elementary_school = School.create(
name: 'John F Horgan Elementary School',
mailing_street_address_1: '124 Providence St',
mailing_city: 'West Warwick',
mailing_state: 'RI',
mailing_zip_code: '02893',
phone: '4018028450',
active: true,
district: west_warick_district
)
wakefield_hills_elementary_school = School.create(
name: 'Wakefield Hills Elementary School',
mailing_street_address_1: '',
mailing_city: 'West Warwick',
mailing_state: 'RI',
mailing_zip_code: '02893',
phone: '4018228452',
active: true,
district: west_warick_district
)
john_f_deering_middle_school = School.create(
name: 'John F. Deering Middle School',
mailing_street_address_1: '2 Webster Knight Drive',
mailing_city: 'West Warwick',
mailing_state: 'RI',
mailing_zip_code: '02893',
phone: '4018228445',
active: true,
district: west_warick_district
)
west_warwick_high_school = School.create(
name: '',
mailing_street_address_1: '1 Webster Knight Dr',
mailing_city: 'West Warwick',
mailing_state: 'RI',
mailing_zip_code: '02893',
phone: '4018216596',
active: true,
district: west_warick_district
)
Admin.create(
name: 'Jim Monti',
district: west_warick_district,
active: true
)
Admin.create(
name: 'Toni Mouat',
district: west_warick_district,
active: true
)
guardian_complete_west_warwick_student = Student.create(
first_name: 'Jimmy',
middle_name: 'Michael',
last_name: 'Miller',
birthday: '2008-01-01',
first_language: 'english',
second_language: 'spanish',
school_start_date: '2014-09-01',
iep: true,
p504: true,
bus_required: true,
birth_certificate_verified: false,
residency_verified: false,
lunch_provided: true,
home_street_address_1: '60 Coit Ave',
home_street_address_2: 'Apt 4',
home_city: 'West Warwick',
home_state: 'RI',
home_zip_code: '02893',
mailing_street_address_1: 'P.O. Box 14',
mailing_street_address_2: 'Lockbox 18',
mailing_city: 'West Warwick',
mailing_state: 'RI',
mailing_zip_code: '02893',
school: greenbush_elementary_school,
gender: :male,
birth_city: 'West Warwick',
birth_state: 'RI',
birth_country: 'USA',
is_hispanic: false,
alt_home_street_address_1: '71 Coit Ave',
alt_home_street_address_2: 'Backdoor',
alt_home_city: 'West Warwick',
alt_home_state: 'RI',
alt_home_zip_code: '02893',
nickname: 'Jimbo',
guardian_complete_time: '2013-06-18',
estimated_graduation_year: 2027,
active: true,
grade: :kindergarten
)
StudentRace.create(
student: guardian_complete_west_warwick_student,
race: :white,
active: true
)
StudentRace.create(
student: guardian_complete_west_warwick_student,
race: :black,
active: true
)
guardian_complete_west_warwick_guardian = Guardian.create(
first_name: 'Linda',
middle_name: 'Belinda',
last_name: 'Miller',
mailing_street_address_1: 'P.O. Box 14',
mailing_street_address_2: 'Lockbox 18',
mailing_city: 'West Warwick',
mailing_state: 'RI',
mailing_zip_code: '02893',
cell_phone: '4011234567',
alt_phone: '4018901234',
alt_phone_type: :work,
email: 'linda@codeisland.org',
receive_emails: true,
receive_sms: true,
receive_postal_mail: true,
receive_grade_notices: true,
receive_conduct_notices: true,
restricted: false,
student: guardian_complete_west_warwick_student,
active: true,
relationship: 'mother'
)
ContactPerson.create(
relationship: 'uncle',
language: 'en',
mailing_street_address_1: '95 Factory St',
mailing_street_address_2: 'Back door',
mailing_city: 'West Warwick',
mailing_state: 'RI',
mailing_zip_code: '02893',
phone: '4019876543',
can_pickup_child: true,
guardian: guardian_complete_west_warwick_guardian,
active: true,
first_name: 'Terry',
last_name: 'Mooler',
email: 'terry@codeisland.org'
)
ContactPerson.create(
relationship: 'aunt',
language: 'en',
mailing_street_address_1: '95 Factory St',
mailing_street_address_2: 'Back door',
mailing_city: 'West Warwick',
mailing_state: 'RI',
mailing_zip_code: '02893',
phone: '4019876543',
can_pickup_child: false,
guardian: guardian_complete_west_warwick_guardian,
active: true,
first_name: 'Rita',
last_name: 'Mooler',
email: 'rita@codeisland.org'
)
Fixed spelling of Warwick
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
#!/bin/env ruby
# encoding: utf-8
# Central requirements
CustomRequirement.create(
name: 'Physical Exam',
description: 'Checkup by a doctor',
uri: 'http://www.health.ri.gov/forms/school/Physical.pdf',
req_type: :url,
authority_level: :central
)
# West Warwick School District
west_warwick_district = District.create(
name: 'West Warwick Public Schools',
mailing_street_address_1: "10 Harris Ave",
mailing_city: 'West Warwick',
mailing_state: 'RI',
mailing_zip_code: '02984',
phone: '4018211180',
active: true
)
WelcomeMessage.create(
message: "<p>Welcome to West Warwick Public Schools!</p><p>Please register!</p>",
language: 'en',
district: west_warwick_district
)
CustomRequirement.create(
name: 'Release Authorization',
description: 'Permission to release records',
req_type: :file,
district: west_warwick_district,
authority_level: :district
)
greenbush_elementary_school = School.create(
name: 'Greenbush Elementary School',
mailing_street_address_1: '127 Greenbush Road',
mailing_city: 'West Warwick',
mailing_state: 'RI',
mailing_zip_code: '02893',
phone: '4018228454',
active: true,
district: west_warwick_district
)
john_f_horgan_elementary_school = School.create(
name: 'John F Horgan Elementary School',
mailing_street_address_1: '124 Providence St',
mailing_city: 'West Warwick',
mailing_state: 'RI',
mailing_zip_code: '02893',
phone: '4018028450',
active: true,
district: west_warwick_district
)
wakefield_hills_elementary_school = School.create(
name: 'Wakefield Hills Elementary School',
mailing_street_address_1: '',
mailing_city: 'West Warwick',
mailing_state: 'RI',
mailing_zip_code: '02893',
phone: '4018228452',
active: true,
district: west_warwick_district
)
john_f_deering_middle_school = School.create(
name: 'John F. Deering Middle School',
mailing_street_address_1: '2 Webster Knight Drive',
mailing_city: 'West Warwick',
mailing_state: 'RI',
mailing_zip_code: '02893',
phone: '4018228445',
active: true,
district: west_warwick_district
)
west_warwick_high_school = School.create(
name: '',
mailing_street_address_1: '1 Webster Knight Dr',
mailing_city: 'West Warwick',
mailing_state: 'RI',
mailing_zip_code: '02893',
phone: '4018216596',
active: true,
district: west_warwick_district
)
Admin.create(
name: 'Jim Monti',
district: west_warwick_district,
active: true
)
Admin.create(
name: 'Toni Mouat',
district: west_warwick_district,
active: true
)
guardian_complete_west_warwick_student = Student.create(
first_name: 'Jimmy',
middle_name: 'Michael',
last_name: 'Miller',
birthday: '2008-01-01',
first_language: 'english',
second_language: 'spanish',
school_start_date: '2014-09-01',
iep: true,
p504: true,
bus_required: true,
birth_certificate_verified: false,
residency_verified: false,
lunch_provided: true,
home_street_address_1: '60 Coit Ave',
home_street_address_2: 'Apt 4',
home_city: 'West Warwick',
home_state: 'RI',
home_zip_code: '02893',
mailing_street_address_1: 'P.O. Box 14',
mailing_street_address_2: 'Lockbox 18',
mailing_city: 'West Warwick',
mailing_state: 'RI',
mailing_zip_code: '02893',
school: greenbush_elementary_school,
gender: :male,
birth_city: 'West Warwick',
birth_state: 'RI',
birth_country: 'USA',
is_hispanic: false,
alt_home_street_address_1: '71 Coit Ave',
alt_home_street_address_2: 'Backdoor',
alt_home_city: 'West Warwick',
alt_home_state: 'RI',
alt_home_zip_code: '02893',
nickname: 'Jimbo',
guardian_complete_time: '2013-06-18',
estimated_graduation_year: 2027,
active: true,
grade: :kindergarten
)
StudentRace.create(
student: guardian_complete_west_warwick_student,
race: :white,
active: true
)
StudentRace.create(
student: guardian_complete_west_warwick_student,
race: :black,
active: true
)
guardian_complete_west_warwick_guardian = Guardian.create(
first_name: 'Linda',
middle_name: 'Belinda',
last_name: 'Miller',
mailing_street_address_1: 'P.O. Box 14',
mailing_street_address_2: 'Lockbox 18',
mailing_city: 'West Warwick',
mailing_state: 'RI',
mailing_zip_code: '02893',
cell_phone: '4011234567',
alt_phone: '4018901234',
alt_phone_type: :work,
email: 'linda@codeisland.org',
receive_emails: true,
receive_sms: true,
receive_postal_mail: true,
receive_grade_notices: true,
receive_conduct_notices: true,
restricted: false,
student: guardian_complete_west_warwick_student,
active: true,
relationship: 'mother'
)
ContactPerson.create(
relationship: 'uncle',
language: 'en',
mailing_street_address_1: '95 Factory St',
mailing_street_address_2: 'Back door',
mailing_city: 'West Warwick',
mailing_state: 'RI',
mailing_zip_code: '02893',
phone: '4019876543',
can_pickup_child: true,
guardian: guardian_complete_west_warwick_guardian,
active: true,
first_name: 'Terry',
last_name: 'Mooler',
email: 'terry@codeisland.org'
)
ContactPerson.create(
relationship: 'aunt',
language: 'en',
mailing_street_address_1: '95 Factory St',
mailing_street_address_2: 'Back door',
mailing_city: 'West Warwick',
mailing_state: 'RI',
mailing_zip_code: '02893',
phone: '4019876543',
can_pickup_child: false,
guardian: guardian_complete_west_warwick_guardian,
active: true,
first_name: 'Rita',
last_name: 'Mooler',
email: 'rita@codeisland.org'
) |
require 'resolv'
def name
"dns_srv_brute"
end
def pretty_name
"DNS SRV Brute"
end
# Returns a string which describes what this task does
def description
"Simple DNS Service Record Bruteforce"
end
# Returns an array of valid types for this task
def allowed_types
[Entities::Domain]
end
## Returns an array of valid options and their description/type for this task
def allowed_options
[]
end
def setup(entity, options={})
super(entity, options)
@resolver = Dnsruby::DNS.new # uses system default
self
end
# Default method, subclasses must override this
def run
super
if @options['srv_list']
subdomain_list = @options['srv_list']
else
# Add a builtin domain list
srv_list = [
'_gc._tcp', '_kerberos._tcp', '_kerberos._udp', '_ldap._tcp',
'_test._tcp', '_sips._tcp', '_sip._udp', '_sip._tcp', '_aix._tcp',
'_aix._tcp', '_finger._tcp', '_ftp._tcp', '_http._tcp', '_nntp._tcp',
'_telnet._tcp', '_whois._tcp', '_h323cs._tcp', '_h323cs._udp',
'_h323be._tcp', '_h323be._udp', '_h323ls._tcp',
'_h323ls._udp', '_sipinternal._tcp', '_sipinternaltls._tcp',
'_sip._tls', '_sipfederationtls._tcp', '_jabber._tcp',
'_xmpp-server._tcp', '_xmpp-client._tcp', '_imap.tcp',
'_certificates._tcp', '_crls._tcp', '_pgpkeys._tcp',
'_pgprevokations._tcp', '_cmp._tcp', '_svcp._tcp', '_crl._tcp',
'_ocsp._tcp', '_PKIXREP._tcp', '_smtp._tcp', '_hkp._tcp',
'_hkps._tcp', '_jabber._udp','_xmpp-server._udp', '_xmpp-client._udp',
'_jabber-client._tcp', '_jabber-client._udp','_kerberos.tcp.dc._msdcs',
'_ldap._tcp.ForestDNSZones', '_ldap._tcp.dc._msdcs', '_ldap._tcp.pdc._msdcs',
'_ldap._tcp.gc._msdcs','_kerberos._tcp.dc._msdcs','_kpasswd._tcp','_kpasswd._udp'
]
end
@task_logger.log_good "Using srv list: #{srv_list}"
srv_list.each do |srv|
begin
# Calculate the domain name
domain = "#{srv}.#{@entity.name}"
# Try to resolve
@resolver.getresources(domain, "SRV").collect do |rec|
# split up the record
resolved_address = rec.target
port = rec.port
weight = rec.weight
priority = rec.priority
@task_logger.log_good "Resolved Address #{resolved_address} for #{domain}" if resolved_address
# If we resolved, create the right entities
if resolved_address
@task_logger.log_good "Creating domain and host entities..."
# Create a domain
d = create_entity(Entities::Domain, {:name => domain })
# Create a host to store the ip address
h = create_entity(Entities::Host, {:name => resolved_address})
h.domains << d
h.save
# Create a service, and also associate that with our host.
create_entity(Entities::NetSvc, {:proto => "tcp", :port_num => port, :host => h})
end
end
rescue Exception => e
@task_logger.log_error "Hit exception: #{e}"
end
end
end
save more information about the netsvc
require 'resolv'
def name
"dns_srv_brute"
end
def pretty_name
"DNS SRV Brute"
end
# Returns a string which describes what this task does
def description
"Simple DNS Service Record Bruteforce"
end
# Returns an array of valid types for this task
def allowed_types
[Entities::Domain]
end
## Returns an array of valid options and their description/type for this task
def allowed_options
[]
end
def setup(entity, options={})
super(entity, options)
@resolver = Dnsruby::DNS.new # uses system default
self
end
# Default method, subclasses must override this
def run
super
if @options['srv_list']
subdomain_list = @options['srv_list']
else
# Add a builtin domain list
srv_list = [
'_gc._tcp', '_kerberos._tcp', '_kerberos._udp', '_ldap._tcp',
'_test._tcp', '_sips._tcp', '_sip._udp', '_sip._tcp', '_aix._tcp',
'_aix._tcp', '_finger._tcp', '_ftp._tcp', '_http._tcp', '_nntp._tcp',
'_telnet._tcp', '_whois._tcp', '_h323cs._tcp', '_h323cs._udp',
'_h323be._tcp', '_h323be._udp', '_h323ls._tcp',
'_h323ls._udp', '_sipinternal._tcp', '_sipinternaltls._tcp',
'_sip._tls', '_sipfederationtls._tcp', '_jabber._tcp',
'_xmpp-server._tcp', '_xmpp-client._tcp', '_imap.tcp',
'_certificates._tcp', '_crls._tcp', '_pgpkeys._tcp',
'_pgprevokations._tcp', '_cmp._tcp', '_svcp._tcp', '_crl._tcp',
'_ocsp._tcp', '_PKIXREP._tcp', '_smtp._tcp', '_hkp._tcp',
'_hkps._tcp', '_jabber._udp','_xmpp-server._udp', '_xmpp-client._udp',
'_jabber-client._tcp', '_jabber-client._udp','_kerberos.tcp.dc._msdcs',
'_ldap._tcp.ForestDNSZones', '_ldap._tcp.dc._msdcs', '_ldap._tcp.pdc._msdcs',
'_ldap._tcp.gc._msdcs','_kerberos._tcp.dc._msdcs','_kpasswd._tcp','_kpasswd._udp'
]
end
@task_logger.log_good "Using srv list: #{srv_list}"
srv_list.each do |srv|
begin
# Calculate the domain name
domain = "#{srv}.#{@entity.name}"
# Try to resolve
@resolver.getresources(domain, "SRV").collect do |rec|
# split up the record
resolved_address = rec.target
port = rec.port
weight = rec.weight
priority = rec.priority
@task_logger.log_good "Resolved Address #{resolved_address} for #{domain}" if resolved_address
# If we resolved, create the right entities
if resolved_address
@task_logger.log_good "Creating domain and host entities..."
# Create a domain
d = create_entity(Entities::Domain, {:name => domain })
# Create a host to store the ip address
h = create_entity(Entities::Host, {:name => resolved_address})
h.domains << d
h.save
# Create a service, and also associate that with our host.
create_entity(Entities::NetSvc, {
:proto => "tcp",
:port_num => port,
:name => "#{h.name}:#{port}/tcp",
:host_id => h.id
})
end
end
rescue Exception => e
@task_logger.log_error "Hit exception: #{e}"
end
end
end
|
require 'securerandom'
puts "Seeding database"
puts "-------------------------------"
# Create an initial Admin User
admin_username = ENV['ERRBIT_ADMIN_USER'] || "errbit"
def admin_email
return 'admin@example.com' if heroku_pr_review_app?
ENV['ERRBIT_ADMIN_EMAIL'] || "errbit@#{Errbit::Config.host}"
end
def admin_pass
return 'demo-admin' if heroku_pr_review_app?
@admin_pass ||= ENV['ERRBIT_ADMIN_PASSWORD'] || SecureRandom.urlsafe_base64(12)[0, 12]
end
def heroku_pr_review_app?
app_name = ENV.fetch("HEROKU_APP_NAME", "")
app_name.include?("errbit-deploy-pr-")
end
puts "Creating an initial admin user:"
puts "-- username: #{admin_username}" if Errbit::Config.user_has_username
puts "-- email: #{admin_email}"
puts "-- password: #{admin_pass}"
puts ""
puts "Be sure to note down these credentials now!"
user = User.find_or_initialize_by(email: admin_email)
user.name = 'Errbit Admin'
user.password = admin_pass
user.password_confirmation = admin_pass
user.username = admin_username if Errbit::Config.user_has_username
user.admin = true
user.save!
Seeds: emit unique message when running on PR environment
require 'securerandom'
puts "Seeding database"
puts "-------------------------------"
# Create an initial Admin User
admin_username = ENV['ERRBIT_ADMIN_USER'] || "errbit"
def admin_email
return 'admin@example.com' if heroku_pr_review_app?
ENV['ERRBIT_ADMIN_EMAIL'] || "errbit@#{Errbit::Config.host}"
end
def admin_pass
return 'demo-admin' if heroku_pr_review_app?
@admin_pass ||= ENV['ERRBIT_ADMIN_PASSWORD'] || SecureRandom.urlsafe_base64(12)[0, 12]
end
def heroku_pr_review_app?
app_name = ENV.fetch("HEROKU_APP_NAME", "")
app_name.include?("errbit-deploy-pr-")
end
puts "Creating an initial admin user:"
puts "-- username: #{admin_username}" if Errbit::Config.user_has_username
puts "-- email: #{admin_email}"
puts "-- password: #{admin_pass}"
puts ""
puts "Be sure to note down these credentials now!"
puts "\nNOTE: DEMO instance, not for production use!" if heroku_pr_review_app?
user = User.find_or_initialize_by(email: admin_email)
user.name = 'Errbit Admin'
user.password = admin_pass
user.password_confirmation = admin_pass
user.username = admin_username if Errbit::Config.user_has_username
user.admin = true
user.save!
|
add backup task to write db contents to csv
require 'fileutils'
require 'csv'
namespace :taproot do
namespace :db do
desc 'Backup database to ruby hashes'
task :to_csv => :environment do
backup_dir = Rails.root.join('db','backups','csv')
FileUtils.mkdir_p(backup_dir)
ActiveRecord::Base.connection.tables.each do |table|
begin
model = table.classify.constantize
CSV.open("#{backup_dir}/#{model.table_name}.csv", "wb") do |csv|
csv << model.column_names
model.all.each do |item|
csv << item.attributes.values
end
end
rescue
end
end
end
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
wine_biz_data = [
{name: 'Charles Smith Wine Jet City', location: '1136 S Albro Pl, Seattle, WA 98108', theme: 0},
{name: 'Elsom Cellars', location: '2960 4th Ave S, Seattle, WA 98134', theme: 0},
{name: 'Stomani Cellars', location: '1403 Dexter Ave N, Seattle, WA 98109', theme: 0},
{name: 'Hand Of God Wines', location: '308 9th Ave N, Seattle, WA 98109', theme: 0},
{name: 'The Tasting Room', location: 'Pike Place Market, 1924 Post Alley, Seattle, WA 98101', theme: 0},
{name: '21 Acres', location: '13701 NE 171st Street, Woodinville, WA 98072', theme: 0},
{name: 'Adams Bench Winery', location: '14360 160th Pl NE, Woodinville, WA 98072', theme: 0},
{name: 'Alexandria Nicole Cellars', location: '14810 NE 145th St, Woodinville, WA 98072', theme: 0},
{name: 'áMaurice Cellars', location: '14463 Woodinville-Redmond Rd NE, Woodinville, WA 98072', theme: 0},
{name: 'áMaurice Cellars', location: '14463 Woodinville-Redmond Rd NE, Woodinville, WA 98072', theme: 0},
{name: 'Domanico Cellars', location: '825 NW 49th St, Seattle, WA 98107', theme: 0},
{name: 'Laurelhurst Cellars Winery', location: '5608 7th Ave S, Seattle, WA 98108', theme: 0},
{name: 'Viscon Cellars', location: '5910 California Ave SW, Seattle, WA 98136', theme: 0},
{name: 'J Bookwalter Tasting Studio', location: '14810 NE 145th St, Woodinville, WA 98072', theme: 0},
{name: 'Rolling Bay Winery', location: '10334 Beach Crest, Bainbridge Island, WA 98110', theme: 0},
{name: 'Fletcher Bay Winery', location: '9415 Coppertop Loop NE, Bainbridge Island, WA 98110', theme: 0},
{name: 'Eleven Winery', location: '287 Winslow Way E, Bainbridge Island, WA 98110', theme: 0},
{name: 'Island Vintners', location: '450 Winslow Way E, Bainbridge Island, WA 98110', theme: 0},
{name: 'Aspenwood Cellars Winery', location: '18642 142nd Ave NE, Woodinville, WA 98072', theme: 0},
{name: 'Waving Tree Winery', location: '11901 124th AVE NE, Kirkland, WA 98034', theme: 0},
{name: 'Matthews Winery', location: '16116 140th Pl NE, Woodinville, WA 98072', theme: 0},
{name: 'Eye of the Needle Winery', location: '19501 144th Ave NE, Woodinville, WA 98072', theme: 0},
{name: 'Northwest Cellars', location: '11909 124th Ave NE, Kirkland, WA 98034', theme: 0},
{name: 'Eagle Harbor Wine Company', location: '278 Winslow Way E, Bainbridge Island, WA 98110', theme: 0},
{name: 'Patterson Cellars', location: '14505 148th Ave NE, Woodinville, WA 98072', theme: 0},
{name: 'Perennial Vintners', location: '8840 NE Lovgreen Rd, Bainbridge Island, WA 98110', theme: 0},
{name: 'Mark Ryan Winery', location: '14475 Woodinville-redmond Rd NE, Woodinville, WA 98072', theme: 0},
{name: 'Kestrel Cellar and Tasting Room', location: '19501 144th Ave NE, Woodinville, WA 98072', theme: 0},
{name: 'Martedi Winery', location: '16110 Woodinville-Redmond Rd NE, Woodinville, WA 98072', theme: 0},
{name: 'Darby Winery', location: '14450 Woodinville Redmond Rd NE, Woodinville, WA 98072', theme: 0},
{name: 'Sparkman Cellars', location: '19501 144 Ave. NE, Woodinville, WA 98072', theme: 0},
{name: 'Palouse Winery', location: '12431 Vashon Hwy SW, Vashon, WA 98070', theme: 0},
{name: 'Arista Wine Cellars', location: '320 5th Ave S, Edmonds, WA 98020', theme: 0},
{name: 'Red Sky Winery', location: '19495 144th Ave NE, Woodinville, WA 98072', theme: 0},
{name: 'Efeste', location: '19730 144th Ave NE, Woodinville, WA 98072', theme: 0},
{name: 'Vashon Winery', location: '10317 SW 156th St, Vashon, WA 98070', theme: 0},
{name: 'Finn Hill Winery', location: '8218 NE 115th Way, Kirkland, WA 98034', theme: 0},
{name: 'Almquist Family Vintners', location: '198 Nickerson St, Seattle, WA 98109', theme: 0},
{name: 'Barrique', location: '1762 Airport Way S, Seattle, WA 98134', theme: 0},
{name: 'Bartholomew Winery', location: '3100 Airport Way S, Seattle, WA 98134', theme: 0},
{name: 'Cloudlift Cellars', location: '312 S Lucile St, Seattle, WA 98108', theme: 0},
{name: 'Eight Bells Winery', location: '6213-B Roosevelt Way NE, Seattle, WA 98115', theme: 0},
{name: 'Falling Rain Cellars', location: '825 NW 49th Street, Seattle, WA 98107', theme: 0},
{name: 'Kerloo Cellars', location: '3911 1st Ave South, Seattle, WA 98134', theme: 0},
{name: 'Nota Bene Cellars', location: '9320 15th Ave S Unit CC, Seattle, WA 98108', theme: 0},
{name: 'O·S Winery', location: '5319 4th Avenue South, Seattle, WA 98108', theme: 0},
{name: 'Riley Sexton Vintners', location: '1403 Dexter Avenue North', theme: 0},
{name: 'Robert Ramsay Cellars', location: '1629 Queen Anne Ave N 102, Seattle, WA 98109', theme: 0},
{name: 'Structure Cellars', location: '3849 1st Ave So suite D , Seattle, WA 98134 ', theme: 0},
{name: 'The Estates Wine Room', location: '307 Occidental Ave S, Seattle, WA 98104', theme: 0},
{name: 'Two Brothers Winery', location: '3902 California Ave SW, Seattle, WA 98116', theme: 0},
{name: 'Ward Johnson Winery', location: '1445 Elliott Ave W, Seattle, WA 98119', theme: 0},
{name: 'Welcome Road Winery', location: '4415 SW Stevens St, Seattle, WA 98116', theme: 0},
{name: 'Capri Cellars', location: '88 Front St S, Issaquah, WA 98027', theme: 0},
{name: 'Fivash Cellars', location: '602 234th Ave SE, Sammamish, WA 98074', theme: 0},
{name: 'Piccola Cellars', location: '112 W 2nd St, North Bend, WA 98045', theme: 0}
]
coffee_biz_data = [
{name: 'Slate Coffee Roasters', location: '602 2nd Ave, Seattle, WA 98104', theme: 3},
{name: 'Elm Coffee Roasters', location: '240 2nd Ave S #103, Seattle, WA, 98104', theme: 3},
{name: 'Victrola Coffee Roasters', location: '310 E Pike St, Seattle, WA, 98122', theme: 3},
{name: 'Lighthouse Roasters', location: '400 N 43rd St, Seattle, WA, 98103', theme: 3},
{name: 'Caffe Lusso Coffee Roasters', location: '17725 NE 65th St A150, Redmond, WA 98052', theme: 3},
{name: 'Caffe Luca Coffee Roasters', location: '885 Industry Dr, Seattle, WA 98188', theme: 3},
{name: 'Middle Fork Roasters', location: '420 S 96th St #6, Seattle, WA 98108', theme: 3},
{name: 'Storyville Coffee Roasting Studio Coffee Shop & Tasting Room', location: '9459 Coppertop Loop NE, Bainbridge Island, WA 98110', theme: 3},
{name: 'Fonte Coffee Roaster', location: '5501 6th Ave S, Seattle, WA 98108', theme: 3},
{name: 'Zoka Coffee Roasters and Tea Company', location: '129 Central Way, Kirkland, WA 98033', theme: 3},
{name: 'Bluebeard Coffee Roasters', location: '2201 6th Ave, Tacoma, WA 98403', theme: 3},
{name: 'Black Swan Coffee Roasting', location: '8510 Cedarhome Dr, Stanwood, WA 98292', theme: 3},
{name: 'Camano Island Coffee Roasters', location: '848 N Sunrise Blvd, Camano Island, WA 98282', theme: 3},
{name: 'RainShadow Coffee Roasting Company', location: '157 W Cedar St, Sequim, WA 98382', theme: 3},
{name: 'Honeymoon Bay Coffee Roasters', location: '1100 SW Bowmer St A101, Oak Harbor, WA 98277', theme: 3},
{name: 'Red Door Coffee Roasters', location: '7425 Hardeson Rd, Everett, WA 98203', theme: 3},
{name: 'Majestic Mountain Coffee Roasters', location: '11229 NE State Hwy 104, Kingston, WA 98346', theme: 3},
{name: 'Broadcast Coffee Roasters', location: '1918 E Yesler Way, Seattle, WA 98122', theme: 3},
{name: 'Stumptown Coffee Roasters', location: '1115 12th Ave, Seattle, WA 98122', theme: 3},
{name: 'Seven Coffee Roasters Market & Cafe', location: '2007 NE Ravenna Blvd, Seattle, WA 98105', theme: 3},
{name: 'Zoka Coffee Roaster & Tea Company', location: '2200 N 56th St, Seattle, WA 98103', theme: 3},
{name: 'True North Coffee Roasters', location: '1406 NW 53rd St, Seattle, WA 98107', theme: 3},
{name: 'Ventoux Roasters and Hart Coffee', location: '3404 NE 55th St, Seattle, WA 98105', theme: 3},
{name: 'Seattle Coffee Works', location: '107 Pike St, Seattle, WA 98101', theme: 3},
{name: 'QED Coffee', location: '1418 31st Ave S, Seattle, WA 98144', theme: 3},
{name: 'Fonté Cafe & Wine Bar', location: '1321 1st Ave, Seattle, WA 98101', theme: 3},
{name: 'Caffe Vita', location: '5028 Wilson Ave S, Seattle, WA 98118', theme: 3},
{name: 'Tin Umbrella Coffee', location: '5600 Rainier Ave S, Seattle, WA 98118', theme: 3}
]
beer_biz_data = [
{name: 'Holy Mountain Brewing Company', location: '1421 Elliott Ave W, Seattle, WA 98119', theme: 1},
{name: 'Standard Brewing', location: '2504 S Jackson St, Seattle, WA 98144', theme: 1},
{name: 'Schooner Exact Brewing Company', location: '3901 1st Avenue South, Seattle, WA 98134', theme: 1},
{name: 'Two Beers Brewing Co.', location: '4700 Ohio Ave S, Seattle, WA 98134', theme: 1},
{name: 'Reuben\'s Brews', location: '5010 14th Ave NW, Seattle, WA 98107', theme: 1},
{name: 'Stoup Brewing', location: '1108 NW 52nd St, Seattle, WA 98107', theme: 1},
{name: 'Outlander Brewery and Pub', location: '225 N 36th St, Seattle, WA 98103', theme: 1},
{name: 'Big Time Brewery & Alehouse', location: '4133 University Way NE, Seattle, WA 98105', theme: 1},
{name: 'Naked City Brewery & Taphouse', location: '8564 Greenwood Ave N, Seattle, WA 98103', theme: 1},
{name: 'Snoqualmie Brewery and Taproom', location: '8032 Falls Ave SE, Snoqualmie, WA 98065', theme: 1},
{name: 'Airways Brewing Company - Brewery & Tap Room', location: '8611 S 212th St, Kent, WA 98031', theme: 1},
{name: 'Elliott Bay Brewhouse & Pub', location: '255 SW 152nd St, Burien, WA 98166', theme: 1},
{name: 'Sound Brewery Tasting Room', location: '19815 Viking Ave NW, Poulsbo, WA 98370', theme: 1},
{name: 'Port Townsend Brewing Co', location: '330 10th St, Port Townsend, WA 98368', theme: 1},
{name: 'Diamond Knot Brewery & Alehouse', location: '621 Front St, Mukilteo, WA 98275', theme: 1},
{name: 'Black Raven Brewing Company', location: '14679 NE 95th St, Redmond, WA 98052', theme: 1},
{name: 'Elliott Bay Brewery', location: '12537 Lake City Way NE, Seattle, WA 98125', theme: 1},
{name: 'Hi-Fi Brewing', location: '14950 NE 95th St, Redmond, WA 98052', theme: 1},
{name: 'Bushnell Craft Brewing Company', location: '8461 164th Ave NE, Redmond, WA 98052', theme: 1},
{name: 'Mac & Jack\'s Brewery', location: '17825 NE 65th St, Redmond, WA 98052', theme: 1},
{name: 'Chainline Brewing Company', location: '503 6th St S, Kirkland, WA 98033', theme: 1},
{name: 'Bellevue Brewing Company', location: '1820 130th Ave NE #2, Bellevue, WA 98005', theme: 1},
{name: 'Geaux Brewing', location: '12031 Northup Way #203, Bellevue, WA 98005', theme: 1},
{name: 'Resonate Brewery + Pizzeria', location: '5606 119th Ave SE, Bellevue, WA 98006', theme: 1},
{name: 'Four Generals Brewing', location: '229 Wells Ave S, Renton, WA 98057', theme: 1},
{name: 'Herbert B. Friendly Brewing', location: '527 Wells Ave S, Renton, WA 98057', theme: 1},
{name: 'Odin Brewing Company', location: '402 Baker Blvd, Tukwila, WA 98188', theme: 1},
{name: 'Big Al Brewing', location: '9832 14th Ave SW, Seattle, WA 98106', theme: 1},
{name: 'Tin Dog Brewing', location: '309 S Cloverdale St Suite A2, Seattle, WA 98108', theme: 1},
{name: 'Lowercase Brewing - Brewery', location: '8103 8th Ave S, Seattle, WA 98108', theme: 1},
{name: 'Counterbalance Brewing Company', location: '503B S Michigan St, Seattle, WA 98108', theme: 1},
{name: 'Elliott Bay Brewery & Pub', location: '4720 California Ave SW, Seattle, WA 98116', theme: 1},
{name: 'Machine House Brewery', location: '5840 Airport Way S #121, Seattle, WA 98108', theme: 1},
{name: 'Spinnaker Bay Brewing', location: '5718 Rainier Ave S, Seattle, WA 98118', theme: 1},
{name: 'Flying Lion Brewing', location: '5041 Rainier Ave S, Seattle, WA 98118', theme: 1},
{name: 'Georgetown Brewing Co', location: '5200 Denver Ave S, Seattle, WA 98108', theme: 1},
{name: 'Optimism Brewing Company', location: '1158 Broadway, Seattle, WA 98122', theme: 1},
{name: 'Outer Planet Craft Brewing', location: '1812 12th Ave #100, Seattle, WA 98122', theme: 1},
{name: 'Cloudburst Brewing', location: '2116 Western Ave, Seattle, WA 98121', theme: 1},
{name: 'Old Stove Brewing', location: '1525 1st Ave #16, Seattle, WA 98101', theme: 1},
{name: 'Rock Bottom Restaurant & Brewery', location: 'Rainier Square, 1333 5th Ave, Seattle, WA 98101', theme: 1},
{name: 'McMenamins Six Arms', location: '300 E Pike St, Seattle, WA 98122', theme: 1},
{name: 'Urban Family Brewing Co.', location: '4441 26th Ave W, Seattle, WA 98199', theme: 1},
{name: 'Fremont Brewing Company', location: '1050 N 34th St, Seattle, WA 98103', theme: 1},
{name: 'Outlander Brewery and Pub', location: '225 N 36th St, Seattle, WA 98103', theme: 1},
{name: 'Hale\'s Ales Brewery & Pub', location: '4301 Leary Way NW, Seattle, WA 98107', theme: 1},
{name: 'Rooftop Brewing Company', location: '1220 W Nickerson St, Seattle, WA 98119', theme: 1},
{name: 'Peddler Brewing Company', location: '1514 NW Leary Way, Seattle, WA 98107', theme: 1},
{name: 'NW Peaks Brewery', location: '4818 17th Ave NW, Seattle, WA 98107', theme: 1},
{name: 'Bad Jimmy\'s Brewing Co.', location: 'B, 4358 Leary Way NW, Seattle, WA 98107', theme: 1},
{name: 'Populuxe Brewing', location: '826B NW 49th St, Seattle, WA 98107', theme: 1},
{name: 'Reuben\'s Brews', location: '5010 14th Ave NW, Seattle, WA 98107', theme: 1},
{name: 'Cedar River Brewing Company', location: '7410 Greenwood Ave N #B, Seattle, WA 98103', theme: 1},
{name: 'Flying Bike Cooperative Brewery', location: '8570 Greenwood Ave N, Seattle, WA 98103', theme: 1},
{name: 'Ravenna Brewing Co', location: '5408 26th Ave NE, Seattle, WA 98105', theme: 1},
{name: 'Floating Bridge Brewing', location: '722 NE 45th St, Seattle, WA 98105', theme: 1},
{name: 'Hellbent Brewing Company', location: '13035 Lake City Way NE, Seattle, WA 98125', theme: 1},
{name: 'Lantern Brewing', location: '938 N 95th St, Seattle, WA 98103', theme: 1},
{name: '192 Brewing Company', location: '7324 NE 175th St, Kenmore, WA 98028', theme: 1},
{name: 'Sumerian Brewing Company', location: '15510 Woodinville-Redmond Rd NE E110, Woodinville, WA 98072', theme: 1},
{name: 'Redhook Brewery Woodinville', location: '14300 NE 145th St, Woodinville, WA 98072', theme: 1},
{name: 'Dirty Bucket Brewing Co.', location: '19151 144th Ave NE, Woodinville, WA 98072', theme: 1},
{name: 'Fish Brewing', location: '14701 148th Ave NE, Woodinville, WA 98072', theme: 1},
{name: 'Triplehorn Brewing Co', location: '19510 144th Ave NE #6, Woodinville, WA 98072', theme: 1},
{name: 'Diamond Knot Brewpub @ MLT', location: '5602 232nd St SW, Mountlake Terrace, WA 98043', theme: 1},
{name: 'American Brewing Company Inc.', location: '180 W Dayton St, Edmonds, WA 98020', theme: 1},
{name: 'Big E Ales', location: '5030 208th St SW, Lynnwood, WA 98036', theme: 1},
{name: 'Salish Sea Brewing Co.', location: '518 Dayton St #104, Edmonds, WA 98020', theme: 1}
]
distillery_biz_data = [
{name: 'Westland Distillery', location: '2931 1st Avenue South Seattle, WA 98134', theme: 2},
{name: '2Bar Spirits', location: '2960 4th Ave S #106 Seattle, WA 98134', theme: 2},
{name: '3 Howls Distillery', location: '426 S Massachusetts St Seattle, WA 98134', theme: 2},
{name: 'Letterpress Distilling', location: '85 S Atlantic St #110 Seattle, WA 98134', theme: 2},
{name: 'Copperworks Tasting Room & Distillery', location: '1250 Alaskan Way Seattle, WA 98101', theme: 2},
{name: 'OOLA Distillery', location: '1314 E Union St Seattle, WA 98122', theme: 2},
{name: 'Sun Liquor Distillery', location: '514 E Pike St Seattle, WA 98122', theme: 2},
{name: 'Batch 206', location: '1417 Elliott Ave W Seattle, WA 98119', theme: 2},
{name: 'Sound Spirits', location: '1630 15th Ave W Seattle, WA 98119', theme: 2},
{name: 'Old Ballard Liquor Co.', location: '4421 Shilshole Ave NW Seattle, WA 98107', theme: 2},
{name: 'Captive Spirits', location: '1518 NW 52nd St Seattle, WA 98107', theme: 2},
{name: 'Woodinville Whiskey Co.', location: '16110 Woodinville Redmond Rd NE Woodinville, WA 98072', theme: 2},
{name: 'J.P. Trodden', location: '18646 142nd Ave NE Woodinville, WA 98072', theme: 2},
{name: 'Pacific Distillery', location: '18808 142nd Ave NE #4B Woodinville, WA 98072', theme: 2},
{name: 'Wildwood Spirits & Co.', location: '19116 Beardslee Blvd Ste 102 Bothell, WA 98011', theme: 2},
{name: 'Parliament Distillery', location: '14209 29th St E, Sumner, WA 98390', theme: 2},
{name: 'Scratch Distillery', location: '190 Sunset Ave, Edmonds, WA 98020', theme: 2},
{name: 'The Barrel Thief', location: '3417 Evanston Ave N #102, Seattle, WA 98103', theme: 2},
{name: 'Bad Dog Distillery', location: '19109 63rd Ave NE Suite 1A, Arlington, WA 98223', theme: 2},
{name: 'BelleWood Distilling', location: '6140 Guide Meridian #3, Lynden, WA 98264', theme: 2},
{name: 'Blackfish Spirits Distillery', location: '420 37th St NW, Auburn, WA 98001', theme: 2},
{name: 'Black Heron Spirits', location: '8011 Keene Rd, West Richland, WA 99353', theme: 2},
{name: 'BroVo Spirits', location: '18808 142nd Ave NE, Woodinville, WA 98072', theme: 2},
{name: 'Cadée Distillery', location: '8912 WA-525, Clinton, WA 98236', theme: 2},
{name: 'Chambers Bay Distillery', location: '2013 70th Ave W, University Place, WA 98466', theme: 2},
{name: 'Chuckanut Bay Distillery', location: ' 1115 Railroad Avenue, Bellingham, WA 98225', theme: 2},
{name: 'Four Leaf Spirits', location: '12280 NE Woodinville Dr, Woodinville, WA 98072', theme: 2},
{name: 'Fremont Mischief', location: '132 N Canal St, Seattle, WA 98103', theme: 2},
{name: 'Heritage Distilling Company ', location: '3207 57th St Ct NW, Gig Harbor, WA 98335', theme: 2},
{name: 'Salish Sea Organic Liqueurs', location: '2641 Willamette Dr NE Ste D Lacey, WA 98516', theme: 2},
{name: 'Sandstone Distillery', location: '842 Wright Rd SE, Tenino, WA 98589', theme: 2},
{name: 'Seattle Distilling', location: '19429 Vashon Hwy SW, Vashon, WA 98070', theme: 2},
{name: 'Sidetrack Distillery', location: 'Lazy River Farm 27010 78th Ave S Kent, WA 98032', theme: 2},
{name: 'Skip Rock Distillers', location: '104 Ave C, Snohomish, WA 98290', theme: 2},
{name: 'Temple Distilling Company', location: '19231 36th Ave W, Lynnwood, WA 98036', theme: 2},
{name: 'Valley Shine Distillery', location: '320 S 1st St, Mt Vernon, WA 98273', theme: 2},
{name: 'Whidbey Island Distillery', location: '3466 Craw Rd, Langley, WA 98260', theme: 2},
{name: 'Whiskey Gap Distillery', location: '213 W Main Ave, Ritzville, WA 99169', theme: 2},
{name: 'Wildwood Spirits Co.', location: '19116 Beardslee Blvd #102, Bothell, WA 98011', theme: 2},
{name: 'Wishkah River Distillery', location: '2210 Port Industrial Rd, Aberdeen, WA 98520', theme: 2},
{name: 'Schnapsleiche Spirits', location: '19151 144th Ave NE Woodinville, WA 98072', theme: 2},
{name: 'SoDo Spirits Distillery', location: '2228 Occidental Ave S Seattle, WA 98134', theme: 2},
{name: 'Bainbridge Organic Distillers', location: '9727 Coppertop Loop NE Bainbridge Island, WA 98110', theme: 2},
{name: 'Tucker Distillery', location: '5451 NW Newbery Hill Rd Silverdale, WA 98383', theme: 2},
{name: 'Headframe Spirits', location: '21 S Montana St, Butte, MT 59701', theme: 2},
{name: 'Spiritopia Liqueurs', location: '720 NE Granger Ave, Corvallis, OR 97330', theme: 2},
{name: 'Martin Ryan Distilling Co', location: '2304 NW Savier St, Portland, OR 97210', theme: 2}
]
distillery_biz_data.each do |business_data|
business = Business.new(business_data)
business.retrieve_google_place_id
business.save
end
beer_biz_data.each do |business_data|
business = Business.new(business_data)
business.retrieve_google_place_id
business.save
end
coffee_biz_data.each do |business_data|
business = Business.new(business_data)
business.retrieve_google_place_id
business.save
end
wine_biz_data.each do |business_data|
business = Business.new(business_data)
business.retrieve_google_place_id
business.save
end
Add google_place_id to wineries in seed file.
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
distillery_biz_data = [
{name: 'Westland Distillery', location: '2931 1st Avenue South Seattle, WA 98134', theme: 2},
{name: '2Bar Spirits', location: '2960 4th Ave S #106 Seattle, WA 98134', theme: 2},
{name: '3 Howls Distillery', location: '426 S Massachusetts St Seattle, WA 98134', theme: 2},
{name: 'Letterpress Distilling', location: '85 S Atlantic St #110 Seattle, WA 98134', theme: 2},
{name: 'Copperworks Tasting Room & Distillery', location: '1250 Alaskan Way Seattle, WA 98101', theme: 2},
{name: 'OOLA Distillery', location: '1314 E Union St Seattle, WA 98122', theme: 2},
{name: 'Sun Liquor Distillery', location: '514 E Pike St Seattle, WA 98122', theme: 2},
{name: 'Batch 206', location: '1417 Elliott Ave W Seattle, WA 98119', theme: 2},
{name: 'Sound Spirits', location: '1630 15th Ave W Seattle, WA 98119', theme: 2},
{name: 'Old Ballard Liquor Co.', location: '4421 Shilshole Ave NW Seattle, WA 98107', theme: 2},
{name: 'Captive Spirits', location: '1518 NW 52nd St Seattle, WA 98107', theme: 2},
{name: 'Woodinville Whiskey Co.', location: '16110 Woodinville Redmond Rd NE Woodinville, WA 98072', theme: 2},
{name: 'J.P. Trodden', location: '18646 142nd Ave NE Woodinville, WA 98072', theme: 2},
{name: 'Pacific Distillery', location: '18808 142nd Ave NE #4B Woodinville, WA 98072', theme: 2},
{name: 'Wildwood Spirits & Co.', location: '19116 Beardslee Blvd Ste 102 Bothell, WA 98011', theme: 2},
{name: 'Parliament Distillery', location: '14209 29th St E, Sumner, WA 98390', theme: 2},
{name: 'Scratch Distillery', location: '190 Sunset Ave, Edmonds, WA 98020', theme: 2},
{name: 'The Barrel Thief', location: '3417 Evanston Ave N #102, Seattle, WA 98103', theme: 2},
{name: 'Bad Dog Distillery', location: '19109 63rd Ave NE Suite 1A, Arlington, WA 98223', theme: 2},
{name: 'BelleWood Distilling', location: '6140 Guide Meridian #3, Lynden, WA 98264', theme: 2},
{name: 'Blackfish Spirits Distillery', location: '420 37th St NW, Auburn, WA 98001', theme: 2},
{name: 'Black Heron Spirits', location: '8011 Keene Rd, West Richland, WA 99353', theme: 2},
{name: 'BroVo Spirits', location: '18808 142nd Ave NE, Woodinville, WA 98072', theme: 2},
{name: 'Cadée Distillery', location: '8912 WA-525, Clinton, WA 98236', theme: 2},
{name: 'Chambers Bay Distillery', location: '2013 70th Ave W, University Place, WA 98466', theme: 2},
{name: 'Chuckanut Bay Distillery', location: ' 1115 Railroad Avenue, Bellingham, WA 98225', theme: 2},
{name: 'Four Leaf Spirits', location: '12280 NE Woodinville Dr, Woodinville, WA 98072', theme: 2},
{name: 'Fremont Mischief', location: '132 N Canal St, Seattle, WA 98103', theme: 2},
{name: 'Heritage Distilling Company ', location: '3207 57th St Ct NW, Gig Harbor, WA 98335', theme: 2},
{name: 'Salish Sea Organic Liqueurs', location: '2641 Willamette Dr NE Ste D Lacey, WA 98516', theme: 2},
{name: 'Sandstone Distillery', location: '842 Wright Rd SE, Tenino, WA 98589', theme: 2},
{name: 'Seattle Distilling', location: '19429 Vashon Hwy SW, Vashon, WA 98070', theme: 2},
{name: 'Sidetrack Distillery', location: 'Lazy River Farm 27010 78th Ave S Kent, WA 98032', theme: 2},
{name: 'Skip Rock Distillers', location: '104 Ave C, Snohomish, WA 98290', theme: 2},
{name: 'Temple Distilling Company', location: '19231 36th Ave W, Lynnwood, WA 98036', theme: 2},
{name: 'Valley Shine Distillery', location: '320 S 1st St, Mt Vernon, WA 98273', theme: 2},
{name: 'Whidbey Island Distillery', location: '3466 Craw Rd, Langley, WA 98260', theme: 2},
{name: 'Whiskey Gap Distillery', location: '213 W Main Ave, Ritzville, WA 99169', theme: 2},
{name: 'Wildwood Spirits Co.', location: '19116 Beardslee Blvd #102, Bothell, WA 98011', theme: 2},
{name: 'Wishkah River Distillery', location: '2210 Port Industrial Rd, Aberdeen, WA 98520', theme: 2},
{name: 'Schnapsleiche Spirits', location: '19151 144th Ave NE Woodinville, WA 98072', theme: 2},
{name: 'SoDo Spirits Distillery', location: '2228 Occidental Ave S Seattle, WA 98134', theme: 2},
{name: 'Bainbridge Organic Distillers', location: '9727 Coppertop Loop NE Bainbridge Island, WA 98110', theme: 2},
{name: 'Tucker Distillery', location: '5451 NW Newbery Hill Rd Silverdale, WA 98383', theme: 2},
{name: 'Headframe Spirits', location: '21 S Montana St, Butte, MT 59701', theme: 2},
{name: 'Spiritopia Liqueurs', location: '720 NE Granger Ave, Corvallis, OR 97330', theme: 2},
{name: 'Martin Ryan Distilling Co', location: '2304 NW Savier St, Portland, OR 97210', theme: 2}
]
beer_biz_data = [
{name: 'Holy Mountain Brewing Company', location: '1421 Elliott Ave W, Seattle, WA 98119', theme: 1},
{name: 'Standard Brewing', location: '2504 S Jackson St, Seattle, WA 98144', theme: 1},
{name: 'Schooner Exact Brewing Company', location: '3901 1st Avenue South, Seattle, WA 98134', theme: 1},
{name: 'Two Beers Brewing Co.', location: '4700 Ohio Ave S, Seattle, WA 98134', theme: 1},
{name: 'Reuben\'s Brews', location: '5010 14th Ave NW, Seattle, WA 98107', theme: 1},
{name: 'Stoup Brewing', location: '1108 NW 52nd St, Seattle, WA 98107', theme: 1},
{name: 'Outlander Brewery and Pub', location: '225 N 36th St, Seattle, WA 98103', theme: 1},
{name: 'Big Time Brewery & Alehouse', location: '4133 University Way NE, Seattle, WA 98105', theme: 1},
{name: 'Naked City Brewery & Taphouse', location: '8564 Greenwood Ave N, Seattle, WA 98103', theme: 1},
{name: 'Snoqualmie Brewery and Taproom', location: '8032 Falls Ave SE, Snoqualmie, WA 98065', theme: 1},
{name: 'Airways Brewing Company - Brewery & Tap Room', location: '8611 S 212th St, Kent, WA 98031', theme: 1},
{name: 'Elliott Bay Brewhouse & Pub', location: '255 SW 152nd St, Burien, WA 98166', theme: 1},
{name: 'Sound Brewery Tasting Room', location: '19815 Viking Ave NW, Poulsbo, WA 98370', theme: 1},
{name: 'Port Townsend Brewing Co', location: '330 10th St, Port Townsend, WA 98368', theme: 1},
{name: 'Diamond Knot Brewery & Alehouse', location: '621 Front St, Mukilteo, WA 98275', theme: 1},
{name: 'Black Raven Brewing Company', location: '14679 NE 95th St, Redmond, WA 98052', theme: 1},
{name: 'Elliott Bay Brewery', location: '12537 Lake City Way NE, Seattle, WA 98125', theme: 1},
{name: 'Hi-Fi Brewing', location: '14950 NE 95th St, Redmond, WA 98052', theme: 1},
{name: 'Bushnell Craft Brewing Company', location: '8461 164th Ave NE, Redmond, WA 98052', theme: 1},
{name: 'Mac & Jack\'s Brewery', location: '17825 NE 65th St, Redmond, WA 98052', theme: 1},
{name: 'Chainline Brewing Company', location: '503 6th St S, Kirkland, WA 98033', theme: 1},
{name: 'Bellevue Brewing Company', location: '1820 130th Ave NE #2, Bellevue, WA 98005', theme: 1},
{name: 'Geaux Brewing', location: '12031 Northup Way #203, Bellevue, WA 98005', theme: 1},
{name: 'Resonate Brewery + Pizzeria', location: '5606 119th Ave SE, Bellevue, WA 98006', theme: 1},
{name: 'Four Generals Brewing', location: '229 Wells Ave S, Renton, WA 98057', theme: 1},
{name: 'Herbert B. Friendly Brewing', location: '527 Wells Ave S, Renton, WA 98057', theme: 1},
{name: 'Odin Brewing Company', location: '402 Baker Blvd, Tukwila, WA 98188', theme: 1},
{name: 'Big Al Brewing', location: '9832 14th Ave SW, Seattle, WA 98106', theme: 1},
{name: 'Tin Dog Brewing', location: '309 S Cloverdale St Suite A2, Seattle, WA 98108', theme: 1},
{name: 'Lowercase Brewing - Brewery', location: '8103 8th Ave S, Seattle, WA 98108', theme: 1},
{name: 'Counterbalance Brewing Company', location: '503B S Michigan St, Seattle, WA 98108', theme: 1},
{name: 'Elliott Bay Brewery & Pub', location: '4720 California Ave SW, Seattle, WA 98116', theme: 1},
{name: 'Machine House Brewery', location: '5840 Airport Way S #121, Seattle, WA 98108', theme: 1},
{name: 'Spinnaker Bay Brewing', location: '5718 Rainier Ave S, Seattle, WA 98118', theme: 1},
{name: 'Flying Lion Brewing', location: '5041 Rainier Ave S, Seattle, WA 98118', theme: 1},
{name: 'Georgetown Brewing Co', location: '5200 Denver Ave S, Seattle, WA 98108', theme: 1},
{name: 'Optimism Brewing Company', location: '1158 Broadway, Seattle, WA 98122', theme: 1},
{name: 'Outer Planet Craft Brewing', location: '1812 12th Ave #100, Seattle, WA 98122', theme: 1},
{name: 'Cloudburst Brewing', location: '2116 Western Ave, Seattle, WA 98121', theme: 1},
{name: 'Old Stove Brewing', location: '1525 1st Ave #16, Seattle, WA 98101', theme: 1},
{name: 'Rock Bottom Restaurant & Brewery', location: 'Rainier Square, 1333 5th Ave, Seattle, WA 98101', theme: 1},
{name: 'McMenamins Six Arms', location: '300 E Pike St, Seattle, WA 98122', theme: 1},
{name: 'Urban Family Brewing Co.', location: '4441 26th Ave W, Seattle, WA 98199', theme: 1},
{name: 'Fremont Brewing Company', location: '1050 N 34th St, Seattle, WA 98103', theme: 1},
{name: 'Outlander Brewery and Pub', location: '225 N 36th St, Seattle, WA 98103', theme: 1},
{name: 'Hale\'s Ales Brewery & Pub', location: '4301 Leary Way NW, Seattle, WA 98107', theme: 1},
{name: 'Rooftop Brewing Company', location: '1220 W Nickerson St, Seattle, WA 98119', theme: 1},
{name: 'Peddler Brewing Company', location: '1514 NW Leary Way, Seattle, WA 98107', theme: 1},
{name: 'NW Peaks Brewery', location: '4818 17th Ave NW, Seattle, WA 98107', theme: 1},
{name: 'Bad Jimmy\'s Brewing Co.', location: 'B, 4358 Leary Way NW, Seattle, WA 98107', theme: 1},
{name: 'Populuxe Brewing', location: '826B NW 49th St, Seattle, WA 98107', theme: 1},
{name: 'Reuben\'s Brews', location: '5010 14th Ave NW, Seattle, WA 98107', theme: 1},
{name: 'Cedar River Brewing Company', location: '7410 Greenwood Ave N #B, Seattle, WA 98103', theme: 1},
{name: 'Flying Bike Cooperative Brewery', location: '8570 Greenwood Ave N, Seattle, WA 98103', theme: 1},
# #########
{name: 'Ravenna Brewing Co', location: '5408 26th Ave NE, Seattle, WA 98105', theme: 1},
{name: 'Floating Bridge Brewing', location: '722 NE 45th St, Seattle, WA 98105', theme: 1},
{name: 'Hellbent Brewing Company', location: '13035 Lake City Way NE, Seattle, WA 98125', theme: 1},
{name: 'Lantern Brewing', location: '938 N 95th St, Seattle, WA 98103', theme: 1},
{name: '192 Brewing Company', location: '7324 NE 175th St, Kenmore, WA 98028', theme: 1},
{name: 'Sumerian Brewing Company', location: '15510 Woodinville-Redmond Rd NE E110, Woodinville, WA 98072', theme: 1},
{name: 'Redhook Brewery Woodinville', location: '14300 NE 145th St, Woodinville, WA 98072', theme: 1},
{name: 'Dirty Bucket Brewing Co.', location: '19151 144th Ave NE, Woodinville, WA 98072', theme: 1},
{name: 'Fish Brewing', location: '14701 148th Ave NE, Woodinville, WA 98072', theme: 1},
{name: 'Triplehorn Brewing Co', location: '19510 144th Ave NE #6, Woodinville, WA 98072', theme: 1},
{name: 'Diamond Knot Brewpub @ MLT', location: '5602 232nd St SW, Mountlake Terrace, WA 98043', theme: 1},
{name: 'American Brewing Company Inc.', location: '180 W Dayton St, Edmonds, WA 98020', theme: 1},
{name: 'Big E Ales', location: '5030 208th St SW, Lynnwood, WA 98036', theme: 1},
{name: 'Salish Sea Brewing Co.', location: '518 Dayton St #104, Edmonds, WA 98020', theme: 1}
]
coffee_biz_data = [
{name: 'Slate Coffee Roasters', location: '602 2nd Ave, Seattle, WA 98104', theme: 3},
{name: 'Elm Coffee Roasters', location: '240 2nd Ave S #103, Seattle, WA, 98104', theme: 3},
{name: 'Victrola Coffee Roasters', location: '310 E Pike St, Seattle, WA, 98122', theme: 3},
{name: 'Lighthouse Roasters', location: '400 N 43rd St, Seattle, WA, 98103', theme: 3},
{name: 'Caffe Lusso Coffee Roasters', location: '17725 NE 65th St A150, Redmond, WA 98052', theme: 3},
{name: 'Caffe Luca Coffee Roasters', location: '885 Industry Dr, Seattle, WA 98188', theme: 3},
{name: 'Middle Fork Roasters', location: '420 S 96th St #6, Seattle, WA 98108', theme: 3},
{name: 'Storyville Coffee Roasting Studio Coffee Shop & Tasting Room', location: '9459 Coppertop Loop NE, Bainbridge Island, WA 98110', theme: 3},
{name: 'Fonte Coffee Roaster', location: '5501 6th Ave S, Seattle, WA 98108', theme: 3},
{name: 'Zoka Coffee Roasters and Tea Company', location: '129 Central Way, Kirkland, WA 98033', theme: 3},
{name: 'Bluebeard Coffee Roasters', location: '2201 6th Ave, Tacoma, WA 98403', theme: 3},
{name: 'Black Swan Coffee Roasting', location: '8510 Cedarhome Dr, Stanwood, WA 98292', theme: 3},
{name: 'Camano Island Coffee Roasters', location: '848 N Sunrise Blvd, Camano Island, WA 98282', theme: 3},
{name: 'RainShadow Coffee Roasting Company', location: '157 W Cedar St, Sequim, WA 98382', theme: 3},
{name: 'Honeymoon Bay Coffee Roasters', location: '1100 SW Bowmer St A101, Oak Harbor, WA 98277', theme: 3},
{name: 'Red Door Coffee Roasters', location: '7425 Hardeson Rd, Everett, WA 98203', theme: 3},
{name: 'Majestic Mountain Coffee Roasters', location: '11229 NE State Hwy 104, Kingston, WA 98346', theme: 3},
{name: 'Broadcast Coffee Roasters', location: '1918 E Yesler Way, Seattle, WA 98122', theme: 3},
{name: 'Stumptown Coffee Roasters', location: '1115 12th Ave, Seattle, WA 98122', theme: 3},
{name: 'Seven Coffee Roasters Market & Cafe', location: '2007 NE Ravenna Blvd, Seattle, WA 98105', theme: 3},
{name: 'Zoka Coffee Roaster & Tea Company', location: '2200 N 56th St, Seattle, WA 98103', theme: 3},
{name: 'True North Coffee Roasters', location: '1406 NW 53rd St, Seattle, WA 98107', theme: 3},
{name: 'Ventoux Roasters and Hart Coffee', location: '3404 NE 55th St, Seattle, WA 98105', theme: 3},
{name: 'Seattle Coffee Works', location: '107 Pike St, Seattle, WA 98101', theme: 3},
{name: 'QED Coffee', location: '1418 31st Ave S, Seattle, WA 98144', theme: 3},
{name: 'Fonté Cafe & Wine Bar', location: '1321 1st Ave, Seattle, WA 98101', theme: 3},
{name: 'Caffe Vita', location: '5028 Wilson Ave S, Seattle, WA 98118', theme: 3},
{name: 'Tin Umbrella Coffee', location: '5600 Rainier Ave S, Seattle, WA 98118', theme: 3}
]
wine_biz_data = [
{name: 'Charles Smith Wine Jet City', location: '1136 S Albro Pl, Seattle, WA 98108', theme: 0, google_place_id: 'ChIJVym2i-xBkFQRX1O30QaiGIM'},
{name: 'Elsom Cellars', location: '2960 4th Ave S, Seattle, WA 98134', average_rating: 5.0, theme: 0, google_place_id: 'ChIJb8KVi8kNkFQR_e7zWgSAneM'},
{name: 'Stomani Cellars', location: '1403 Dexter Ave N, Seattle, WA 98109', average_rating: 2.0, theme: 0, google_place_id:'ChIJ4xKG6T0VkFQR-sIc8E4f_dQ'},
{name: 'Hand Of God Wines', location: '308 9th Ave N, Seattle, WA 98109', average_rating: 4.0, theme: 0, google_place_id: 'ChIJrceiwjcVkFQRgLvQSohGx7o'},
{name: 'The Tasting Room', location: 'Pike Place Market, 1924 Post Alley, Seattle, WA 98101', average_rating: 3.0, theme: 0, google_place_id: 'ChIJQVHlzbJqkFQR3KSsOoYgmr4'},
{name: '21 Acres', location: '13701 NE 171st Street, Woodinville, WA 98072', average_rating: 5.0, theme: 0, google_place_id: 'ChIJ34iHbywMkFQR0H2syINxKt8'},
{name: 'Adams Bench Winery', location: '14360 160th Pl NE, Woodinville, WA 98072', average_rating: 3.0, theme: 0, google_place_id: 'ChIJQyPIAlEMkFQRvzrV1hVs7LE'},
{name: 'Alexandria Nicole Cellars', location: '14810 NE 145th St, Woodinville, WA 98072', average_rating: 4.0, theme: 0, google_place_id: 'ChIJicuRUrMNkFQRMDo0eD9XM1w'},
{name: 'áMaurice Cellars', location: '14463 Woodinville-Redmond Rd NE, Woodinville, WA 98072', average_rating: 2.0, theme: 0, google_place_id: 'ChIJh_NZtYYSkFQRKVXSoEwzRCk'},
{name: 'Laurelhurst Cellars Winery', location: '5608 7th Ave S, Seattle, WA 98108', theme: 0, google_place_id: 'ChIJa_hkM8BBkFQR0hRYEcdzLRA'},
{name: 'Viscon Cellars', location: '5910 California Ave SW, Seattle, WA 98136', theme: 0, google_place_id: 'ChIJTWum_RxBkFQRR1PrcLQfdok'},
{name: 'J Bookwalter Tasting Studio', location: '14810 NE 145th St, Woodinville, WA 98072', theme: 0, google_place_id: 'ChIJU9O3MlAMkFQRx7gm0DLgcn4'},
{name: 'Rolling Bay Winery', location: '10334 Beach Crest, Bainbridge Island, WA 98110', theme: 0, google_place_id: 'ChIJJ2QHwzE8kFQRiIzbeC3eFxY'},
{name: 'Fletcher Bay Winery', location: '9415 Coppertop Loop NE, Bainbridge Island, WA 98110', theme: 0, google_place_id: 'ChIJpzYKZyI8kFQRhGGlnMu4lrk'},
{name: 'Eleven Winery', location: '287 Winslow Way E, Bainbridge Island, WA 98110', theme: 0, google_place_id: 'ChIJQ38_arc-kFQRV6RHlZ_N1eI'},
{name: 'Island Vintners', location: '450 Winslow Way E, Bainbridge Island, WA 98110', theme: 0, google_place_id: 'ChIJ4Unf2bk-kFQREAw2KJPUW7Q'},
{name: 'Aspenwood Cellars Winery', location: '18642 142nd Ave NE, Woodinville, WA 98072', theme: 0, google_place_id: 'ChIJT8htJJwOkFQRxRtnkFpEPY4'},
{name: 'Waving Tree Winery', location: '11901 124th AVE NE, Kirkland, WA 98034', theme: 0, google_place_id: 'ChIJk9ongX8NkFQRBGUnuyk4yD4'},
{name: 'Matthews Winery', location: '16116 140th Pl NE, Woodinville, WA 98072', theme: 0, google_place_id: 'ChIJQ_1q9jMMkFQRuH1vrYJZTpI'},
{name: 'Eye of the Needle Winery', location: '19501 144th Ave NE, Woodinville, WA 98072', theme: 0, google_place_id: 'ChIJv2XfnqIOkFQRtEL1yxk5xdk'},
{name: 'Northwest Cellars', location: '11909 124th Ave NE, Kirkland, WA 98034', theme: 0, google_place_id: 'ChIJ2-N2gH8NkFQRRrcIuMtQt_I'},
{name: 'Eagle Harbor Wine Company', location: '278 Winslow Way E, Bainbridge Island, WA 98110', theme: 0, google_place_id: 'ChIJx1hwarc-kFQRwsrcUAOFVEY'},
{name: 'Patterson Cellars', location: '14505 148th Ave NE, Woodinville, WA 98072', theme: 0, google_place_id: 'ChIJvRvgnqIOkFQR_DD-FUKD-Ug'},
{name: 'Perennial Vintners', location: '8840 NE Lovgreen Rd, Bainbridge Island, WA 98110', theme: 0, google_place_id: 'ChIJrUIVMlI8kFQRzUC3AK7UAtU'},
{name: 'Mark Ryan Winery', location: '14475 Woodinville-redmond Rd NE, Woodinville, WA 98072', theme: 0, google_place_id: 'ChIJObYJHJgOkFQRAPPNexih3zY'},
{name: 'Martedi Winery', location: '16110 Woodinville-Redmond Rd NE, Woodinville, WA 98072', theme: 0, google_place_id: 'ChIJhR08f9INkFQRY0ZvozKCTkk'},
{name: 'Darby Winery', location: '14450 Woodinville Redmond Rd NE, Woodinville, WA 98072', theme: 0, google_place_id: 'ChIJFTzqMLMNkFQRHPuP_t8ZIyg'},
{name: 'Sparkman Cellars', location: '19501 144 Ave. NE, Woodinville, WA 98072', theme: 0, google_place_id: 'ChIJvRvgnqIOkFQRn_n95nhP7P8'},
{name: 'Palouse Winery', location: '12431 Vashon Hwy SW, Vashon, WA 98070', theme: 0, google_place_id: 'ChIJv56L2HFGkFQRLutDnEVX5oM'},
{name: 'Arista Wine Cellars', location: '320 5th Ave S, Edmonds, WA 98020', theme: 0, google_place_id: 'ChIJY6uJB_oakFQRqJfD0fic-38'},
{name: 'Efeste', location: '19730 144th Ave NE, Woodinville, WA 98072', theme: 0, google_place_id: 'ChIJhcUW07wOkFQRxbqvJK16Ckg'},
{name: 'Vashon Winery', location: '10317 SW 156th St, Vashon, WA 98070', theme: 0, google_place_id: 'ChIJXRsQcPJFkFQR6RpJJePkuyE'},
{name: 'Finn Hill Winery', location: '8218 NE 115th Way, Kirkland, WA 98034', theme: 0, google_place_id: 'ChIJDXHLB0USkFQRJ4bNFkIwW_8'},
{name: 'Almquist Family Vintners', location: '198 Nickerson St, Seattle, WA 98109', theme: 0, google_place_id: 'ChIJmbwqTwYVkFQROKjnZ0HRZk8'},
{name: 'Barrique', location: '1762 Airport Way S, Seattle, WA 98134', theme: 0, google_place_id: 'ChIJTcHABJtqkFQRV13PMztNl8g'},
{name: 'Bartholomew Winery', location: '3100 Airport Way S, Seattle, WA 98134', theme: 0, google_place_id: 'ChIJg8_PzIFqkFQRWpIerh8Xgu8'},
{name: 'Cloudlift Cellars', location: '312 S Lucile St, Seattle, WA 98108', theme: 0, google_place_id: 'ChIJIQyGqMBBkFQRSERQywlWvcA'},
{name: 'Eight Bells Winery', location: '6213-B Roosevelt Way NE, Seattle, WA 98115', theme: 0, google_place_id: 'ChIJz0ocfm8UkFQRR6e_meDMDvE'},
{name: 'Falling Rain Cellars', location: '825 NW 49th Street, Seattle, WA 98107', theme: 0, google_place_id: 'ChIJH9cYpLYVkFQRRcfc1JXQMrs'},
{name: 'Kerloo Cellars', location: '3911 1st Ave South, Seattle, WA 98134', theme: 0, google_place_id: 'ChIJn9yTHc1BkFQRHR6BePQfBBs'},
{name: 'Nota Bene Cellars', location: '9320 15th Ave S Unit CC, Seattle, WA 98108', theme: 0, google_place_id: 'ChIJJxirmDFCkFQRZz7Mo9zkyZc'},
{name: 'O·S Winery', location: '5319 4th Avenue South, Seattle, WA 98108', theme: 0, google_place_id: 'ChIJd81w1DFCkFQRfvWywekjcOw'},
{name: 'Robert Ramsay Cellars', location: '1629 Queen Anne Ave N 102, Seattle, WA 98109', theme: 0, google_place_id: 'ChIJT3FvSxMVkFQRtcxKKRVeR70'},
{name: 'Structure Cellars', location: '3849 1st Ave So suite D , Seattle, WA 98134', theme: 0, google_place_id: 'ChIJr4Yd2cxBkFQRZ3fgNqX11Ho'},
{name: 'The Estates Wine Room', location: '307 Occidental Ave S, Seattle, WA 98104', theme: 0, google_place_id: 'ChIJoz8d16RqkFQRjlWaQ7mhmsA'},
{name: 'Two Brothers Winery', location: '3902 California Ave SW, Seattle, WA 98116', theme: 0, google_place_id: 'ChIJM-wktFhAkFQRr1iFrgoZk-s'},
{name: 'Ward Johnson Winery', location: '1445 Elliott Ave W, Seattle, WA 98119', theme: 0, google_place_id: 'ChIJldswcmUVkFQRTaUuCxpHRb8'},
{name: 'Welcome Road Winery', location: '4415 SW Stevens St, Seattle, WA 98116', theme: 0, google_place_id: 'ChIJZYUT1WBAkFQRv44xhmc8xUw'},
{name: 'Capri Cellars', location: '88 Front St S, Issaquah, WA 98027', theme: 0, google_place_id: 'ChIJidvxLYBlkFQR5vaX0vtNPek'},
{name: 'Fivash Cellars', location: '602 234th Ave SE, Sammamish, WA 98074', theme: 0, google_place_id: 'ChIJXUJ_5OtxkFQRWya_GEvO8r8'},
{name: 'Piccola Cellars', location: '112 W 2nd St, North Bend, WA 98045', theme: 0, google_place_id: 'ChIJ1-YDRCN8kFQRnIW6Ey1Etm4'}
]
distillery_biz_data.each do |business_data|
Business.find_or_create_by(business_data)
end
beer_biz_data.each do |business_data|
Business.find_or_create_by(business_data)
end
coffee_biz_data.each do |business_data|
Business.find_or_create_by(business_data)
end
wine_biz_data.each do |business_data|
Business.find_or_create_by(business_data)
end
|
require 'open-uri'
module Fog
module Compute
class Octocloud
class Real
protected
def import_file(target, src, opts = {})
case File.extname(src)
when '.box'
import_box(target, src, opts)
when '.ova'
import_ova(target, src, opts)
else
raise "Can't import non .box or .ova"
end
end
# Imports a box (a tarball from vagrant or tenderloin)
#
# @param [Pathname] target destination directory of the box contents
# @param [Pathname, String] path box source file (can be URL or file)
# @param [Hash] opts extra options
# @option opts [Boolean] :show_progress display progress when importing a remote box
#
def import_box(target, path, opts = {})
if path.to_s =~ /^http/
show_progress = opts.is_a?(Hash) ? opts[:show_progress] == true : false
downloaded_file = download_file path.to_s, show_progress
input = Archive::Tar::Minitar::Input.new(downloaded_file)
else
# need to coerce path to a string, so open-uri can figure what it is
input = Archive::Tar::Minitar::Input.new(open(path.to_s))
end
input.each do |entry|
input.extract_entry(target, entry)
end
# DO WE CONVERT??
if !Dir[target.join('*.vmx')].empty?
# We can do nothing - it's already good for vmware
elsif !Dir[target.join('Vagrantfile')].empty?
# Need to import from Vagrant. Convert the ovf to vmx using OVFtool, then write a base tenderfile
convert_box_ovf(target)
else
raise "Invalid box - No vmx or Vagrantfile"
end
end
# Imports an OVA
#
# @param [Pathname] target destination directory of the box contents
# @param [Pathname, String] src OVA source file (can be URL or file)
# @param [Hash] opts extra options
# @option opts [Boolean] :show_progress display progress when importing a remote box
#
def import_ova(target, src, opts = {})
# First, dump the contents in to a tempfile.
tmpfile = Tempfile.new(['ova-import', '.ova'])
if src =~ /^http/
show_progress = opts.is_a?(Hash) ? opts[:show_progress] == true : false
downloaded = download_file(src, show_progress)
FileUtils.mv downloaded.path, tmpfile.path
else
tmpfile.write(open(src).read)
end
tmpfile_path = Pathname.new(tmpfile)
convert_ova(tmpfile_path, target)
end
def convert_ova(ova, target)
vmx = target.join('vmwarebox.vmx')
OVFTool.convert(ova.to_s, vmx)
# OVFTool.convert creates ~/.octocloud/boxes/<cubename>.vmwarevm
# We want to rename it to <cubename> removing the .vmwarevm
# directory suffix
File.rename(target.cleanpath.to_s + ".vmwarevm", target)
end
def convert_box_ovf(path)
ovf = path.join('box.ovf')
vmx = path.join('vmwarebox.vmx')
OVFTool.convert(ovf.to_s, vmx.to_s, :lax => true)
# things work a little different under linux ovftool. So handle appropriately
if Pathname.new(path.to_s + ".vmwarevm").exist?
# This was a mac ovftool conversion
FileUtils.rm_rf(path)
FileUtils.mv(path.to_s + ".vmwarevm", path)
else
# Delete items we didn't create
remove = path.entries.delete_if {|f| f.to_s =~ /vmwarebox/ || f.to_s == '.' || f.to_s == '..'}
remove.each {|f| path.join(f).delete }
end
end
# Download remote file from URL and optionally print progress.
#
# If the progressbar gem is installed it will be automatically used
# to display the download progress, gracefully degrading to a simple
# progress animation otherwise.
#
# @param [String] url file URL
# @param [Boolean] show_progress display progress when true
#
def download_file(url, show_progress = false)
if show_progress
pbar = nil
begin
require 'progressbar'
rescue LoadError => e
Fog::Logger.warning "progressbar rubygem not found. Install it for fancier progress."
pbar = :noop
end
open(
url,
:content_length_proc => lambda { |total|
if pbar != :noop
if total && 0 < total
pbar = ProgressBar.new("Downloading", total)
pbar.file_transfer_mode
end
end
},
:progress_proc => lambda { |read_size|
if pbar != :noop
pbar.set read_size if pbar
else
print "\rDownloading... #{"%.2f" % (read_size/1024.0**2)} MB"
end
}
)
else
open(url)
end
end
end
end
end
end
Fix OVA imports on Linux
require 'open-uri'
module Fog
module Compute
class Octocloud
class Real
protected
def import_file(target, src, opts = {})
case File.extname(src)
when '.box'
import_box(target, src, opts)
when '.ova'
import_ova(target, src, opts)
else
raise "Can't import non .box or .ova"
end
end
# Imports a box (a tarball from vagrant or tenderloin)
#
# @param [Pathname] target destination directory of the box contents
# @param [Pathname, String] path box source file (can be URL or file)
# @param [Hash] opts extra options
# @option opts [Boolean] :show_progress display progress when importing a remote box
#
def import_box(target, path, opts = {})
if path.to_s =~ /^http/
show_progress = opts.is_a?(Hash) ? opts[:show_progress] == true : false
downloaded_file = download_file path.to_s, show_progress
input = Archive::Tar::Minitar::Input.new(downloaded_file)
else
# need to coerce path to a string, so open-uri can figure what it is
input = Archive::Tar::Minitar::Input.new(open(path.to_s))
end
input.each do |entry|
input.extract_entry(target, entry)
end
# DO WE CONVERT??
if !Dir[target.join('*.vmx')].empty?
# We can do nothing - it's already good for vmware
elsif !Dir[target.join('Vagrantfile')].empty?
# Need to import from Vagrant. Convert the ovf to vmx using OVFtool, then write a base tenderfile
convert_box_ovf(target)
else
raise "Invalid box - No vmx or Vagrantfile"
end
end
# Imports an OVA
#
# @param [Pathname] target destination directory of the box contents
# @param [Pathname, String] src OVA source file (can be URL or file)
# @param [Hash] opts extra options
# @option opts [Boolean] :show_progress display progress when importing a remote box
#
def import_ova(target, src, opts = {})
# First, dump the contents in to a tempfile.
tmpfile = Tempfile.new(['ova-import', '.ova'])
if src =~ /^http/
show_progress = opts.is_a?(Hash) ? opts[:show_progress] == true : false
downloaded = download_file(src, show_progress)
FileUtils.mv downloaded.path, tmpfile.path
else
tmpfile.write(open(src).read)
end
tmpfile_path = Pathname.new(tmpfile)
convert_ova(tmpfile_path, target)
end
def convert_ova(ova, target)
vmx = target.join('vmwarebox.vmx')
OVFTool.convert(ova.to_s, vmx)
# OVFTool.convert creates ~/.octocloud/boxes/<cubename>.vmwarevm
# We want to rename it to <cubename> removing the .vmwarevm
# directory suffix.
#
# Except on linux hosts with Workstation/Player
unless RUBY_PLATFORM =~ /linux/
File.rename(target.cleanpath.to_s + ".vmwarevm", target)
end
end
def convert_box_ovf(path)
ovf = path.join('box.ovf')
vmx = path.join('vmwarebox.vmx')
OVFTool.convert(ovf.to_s, vmx.to_s, :lax => true)
# things work a little different under linux ovftool. So handle appropriately
if Pathname.new(path.to_s + ".vmwarevm").exist?
# This was a mac ovftool conversion
FileUtils.rm_rf(path)
FileUtils.mv(path.to_s + ".vmwarevm", path)
else
# Delete items we didn't create
remove = path.entries.delete_if {|f| f.to_s =~ /vmwarebox/ || f.to_s == '.' || f.to_s == '..'}
remove.each {|f| path.join(f).delete }
end
end
# Download remote file from URL and optionally print progress.
#
# If the progressbar gem is installed it will be automatically used
# to display the download progress, gracefully degrading to a simple
# progress animation otherwise.
#
# @param [String] url file URL
# @param [Boolean] show_progress display progress when true
#
def download_file(url, show_progress = false)
if show_progress
pbar = nil
begin
require 'progressbar'
rescue LoadError => e
Fog::Logger.warning "progressbar rubygem not found. Install it for fancier progress."
pbar = :noop
end
open(
url,
:content_length_proc => lambda { |total|
if pbar != :noop
if total && 0 < total
pbar = ProgressBar.new("Downloading", total)
pbar.file_transfer_mode
end
end
},
:progress_proc => lambda { |read_size|
if pbar != :noop
pbar.set read_size if pbar
else
print "\rDownloading... #{"%.2f" % (read_size/1024.0**2)} MB"
end
}
)
else
open(url)
end
end
end
end
end
end
|
module RgGen
MAJOR = 0
MINOR = 3
TEENY = 1
VERSION = "#{MAJOR}.#{MINOR}.#{TEENY}".freeze
end
バージョンを0.3.2に更新
module RgGen
MAJOR = 0
MINOR = 3
TEENY = 2
VERSION = "#{MAJOR}.#{MINOR}.#{TEENY}".freeze
end
|
module TentD
module Model
module PostBuilder
extend self
CreateFailure = Post::CreateFailure
def build_attributes(env, options = {})
data = env['data']
current_user = env['current_user']
type, base_type = Type.find_or_create(data['type'])
unless type
raise CreateFailure.new("Invalid type: #{data['type'].inspect}")
end
received_at_timestamp = (options[:import] && data['received_at']) ? data['received_at'] : TentD::Utils.timestamp
published_at_timestamp = (data['published_at'] || received_at_timestamp).to_i
if data['version']
version_published_at_timestamp = data['version']['published_at'] || published_at_timestamp
version_received_at_timestamp = (options[:import] && data['version']['received_at']) ? data['version']['received_at'] : received_at_timestamp
else
version_published_at_timestamp = published_at_timestamp
version_received_at_timestamp = received_at_timestamp
end
attrs = {
:user_id => current_user.id,
:type => type.type,
:type_id => type.id,
:type_base_id => base_type.id,
:version_published_at => version_published_at_timestamp,
:version_received_at => version_received_at_timestamp,
:published_at => published_at_timestamp,
:received_at => received_at_timestamp,
:content => data['content'],
}
if options[:import]
attrs.merge!(
:entity_id => Entity.first_or_create(data['entity']).id,
:entity => data['entity']
)
elsif options[:entity]
attrs.merge!(
:entity_id => options[:entity_id] || Entity.first_or_create(options[:entity]).id,
:entity => options[:entity]
)
else
attrs.merge!(
:entity_id => current_user.entity_id,
:entity => current_user.entity,
)
end
if options[:public_id]
attrs[:public_id] = options[:public_id]
end
if data['version'] && Array === data['version']['parents']
attrs[:version_parents] = data['version']['parents']
attrs[:version_parents].each_with_index do |item, index|
unless item['version']
raise CreateFailure.new("/version/parents/#{index}/version is required")
end
unless item['post']
if options[:public_id]
item['post'] = attrs[:public_id]
else
raise CreateFailure.new("/version/parents/#{index}/post is required")
end
end
end
elsif options[:version]
unless options[:notification]
raise CreateFailure.new("Parent version not specified")
end
end
if TentType.new(attrs[:type]).base == %(https://tent.io/types/meta)
# meta post is always public
attrs[:public] = true
else
if Hash === data['permissions']
if data['permissions']['public'] == true
attrs[:public] = true
else
attrs[:public] = false
if Array === data['permissions']['entities']
attrs[:permissions_entities] = data['permissions']['entities']
end
end
else
attrs[:public] = true
end
end
if Array === data['mentions'] && data['mentions'].any?
attrs[:mentions] = data['mentions'].map do |m|
m['entity'] = attrs[:entity] unless m.has_key?('entity')
m
end
end
if Array === data['refs'] && data['refs'].any?
attrs[:refs] = data['refs'].map do |ref|
ref['entity'] = attrs[:entity] unless ref.has_key?('entity')
ref
end
end
if options[:notification]
attrs[:attachments] = data['attachments'] if Array === data['attachments']
else
if Array === data['attachments']
data['attachments'] = data['attachments'].inject([]) do |memo, attachment|
next memo unless attachment.has_key?('digest')
if attachment['model'] = Attachment.where(:digest => attachment['digest']).first
memo << attachment
end
memo
end
attrs[:attachments] = data['attachments'].map do |attachment|
{
:digest => attachment['digest'],
:size => attachment['model'].size,
:name => attachment['name'],
:category => attachment['category'],
:content_type => attachment['content_type']
}
end
end
if Array === env['attachments']
attrs[:attachments] = env['attachments'].inject(attrs[:attachments] || Array.new) do |memo, attachment|
memo << {
:digest => TentD::Utils.hex_digest(attachment[:tempfile]),
:size => attachment[:tempfile].size,
:name => attachment[:name],
:category => attachment[:category],
:content_type => attachment[:content_type]
}
memo
end
end
end
attrs
end
def create_delete_post(post, options = {})
ref = { 'entity' => post.entity, 'post' => post.public_id }
ref['version'] = post.version if options[:version]
create_from_env(
'current_user' => post.user,
'data' => {
'type' => 'https://tent.io/types/delete/v0#',
'refs' => [ ref ]
}
)
end
def delete_from_notification(env, post)
post_conditions = post.refs.to_a.inject({}) do |memo, ref|
next memo unless !ref['entity'] || ref['entity'] == post.entity
memo[ref['post']] ||= []
memo[ref['post']] << ref['version'] if ref['version']
memo
end.inject([]) do |memo, (public_id, versions)|
memo << if versions.any?
{ :public_id => public_id, :version => versions }
else
{ :public_id => public_id }
end
memo
end
q = Post.where(:user_id => env['current_user'].id, :entity_id => post.entity_id)
q = q.where(Sequel.|(*post_conditions))
q.all.to_a.each do |post|
delete_opts = { :create_delete_post => false }
delete_opts[:version] = !!post_conditions.find { |c| c[:public_id] == post.public_id }[:version]
post.destroy(delete_opts)
end
end
def create_from_env(env, options = {})
attrs = build_attributes(env, options)
if TentType.new(env['data']['type']).base == %(https://tent.io/types/subscription)
if options[:notification]
subscription = Subscription.create_from_notification(env['current_user'], attrs, env['current_auth.resource'])
post = subscription.post
else
subscription = Subscription.find_or_create(attrs)
post = subscription.post
if subscription.deliver == false
# this will happen as part of the relaitonship init job
options[:deliver_notification] = false
end
end
elsif options[:import] &&
(
TentType.new(attrs[:type]).base == %(https://tent.io/types/relationship) ||
(TentType.new(attrs[:type]).base == %(https://tent.io/types/credentials) &&
attrs[:mentions].any? { |m|
TentType.new(m['type']).base == %(https://tent.io/types/relationship)
})
)
# is a relationship post or credentials mentioning one
import_results = RelationshipImporter.import(env['current_user'], attrs)
post = import_results.post
else
post = Post.create(attrs)
end
case TentType.new(post.type).base
when %(https://tent.io/types/app)
App.update_or_create_from_post(post, :create_credentials => !options[:import])
when %(https://tent.io/types/app-auth)
if options[:import] && (m = post.mentions.find { |m| TentType.new(m['type']).base == %(https://tent.io/types/app) })
App.update_app_auth(post, m['post'])
end
when %(https://tent.io/types/credentials)
if options[:import]
if m = post.mentions.find { |m| TentType.new(m['type']).base == %(https://tent.io/types/app) }
App.update_credentials(post, m['post'])
elsif m = post.mentions.find { |m| TentType.new(m['type']).base == %(https://tent.io/types/app-auth) }
App.update_app_auth_credentials(post, m['post'])
end
end
end
if options[:notification] && TentType.new(post.type).base == %(https://tent.io/types/delete)
delete_from_notification(env, post)
end
if TentType.new(post.type).base == %(https://tent.io/types/meta)
env['current_user'].update_meta_post_id(post)
Relationship.update_meta_post_ids(post)
end
if Array === env['data']['mentions']
post.create_mentions(env['data']['mentions'])
end
unless options[:notification]
if Array === env['data']['attachments']
env['data']['attachments'].each do |attachment|
PostsAttachment.create(
:attachment_id => attachment['model'].id,
:content_type => attachment['content_type'],
:post_id => post.id
)
end
end
if Array === env['attachments']
post.create_attachments(env['attachments'])
end
end
if Array === attrs[:version_parents]
post.create_version_parents(attrs[:version_parents])
end
if !options[:notification] && !options[:import] && options[:deliver_notification] != false
post.queue_delivery
end
post
end
def create_attachments(post, attachments)
attachments.each_with_index do |attachment, index|
data = attachment[:tempfile].read
attachment[:tempfile].rewind
PostsAttachment.create(
:attachment_id => Attachment.find_or_create(
TentD::Utils::Hash.slice(post.attachments[index], 'digest', 'size').merge(:data => data)
).id,
:post_id => post.id,
:content_type => attachment[:content_type]
)
end
end
def create_mentions(post, mentions)
mentions.map do |mention|
mention_attrs = {
:user_id => post.user_id,
:post_id => post.id
}
if mention['entity']
mention_attrs[:entity_id] = Entity.first_or_create(mention['entity']).id
mention_attrs[:entity] = mention['entity']
else
mention_attrs[:entity_id] = post.entity_id
mention_attrs[:entity] = post.entity
end
if mention['type']
mention_attrs[:type_id] = Type.find_or_create_full(mention['type']).id
mention_attrs[:type] = mention['type']
end
mention_attrs[:post] = mention['post'] if mention.has_key?('post')
mention_attrs[:public] = mention['public'] if mention.has_key?('public')
Mention.create(mention_attrs)
end
end
def create_version_parents(post, version_parents)
version_parents.each do |item|
item['post'] ||= post.public_id
_parent = Post.where(:user_id => post.user_id, :public_id => item['post'], :version => item['version']).first
Parent.create(
:post_id => post.id,
:parent_post_id => _parent ? _parent.id : nil,
:version => item['version'],
:post => item['post']
)
end
end
end
end
end
Return 400 when attachments specified for new post/version that are unknown to server
module TentD
module Model
module PostBuilder
extend self
CreateFailure = Post::CreateFailure
def build_attributes(env, options = {})
data = env['data']
current_user = env['current_user']
type, base_type = Type.find_or_create(data['type'])
unless type
raise CreateFailure.new("Invalid type: #{data['type'].inspect}")
end
received_at_timestamp = (options[:import] && data['received_at']) ? data['received_at'] : TentD::Utils.timestamp
published_at_timestamp = (data['published_at'] || received_at_timestamp).to_i
if data['version']
version_published_at_timestamp = data['version']['published_at'] || published_at_timestamp
version_received_at_timestamp = (options[:import] && data['version']['received_at']) ? data['version']['received_at'] : received_at_timestamp
else
version_published_at_timestamp = published_at_timestamp
version_received_at_timestamp = received_at_timestamp
end
attrs = {
:user_id => current_user.id,
:type => type.type,
:type_id => type.id,
:type_base_id => base_type.id,
:version_published_at => version_published_at_timestamp,
:version_received_at => version_received_at_timestamp,
:published_at => published_at_timestamp,
:received_at => received_at_timestamp,
:content => data['content'],
}
if options[:import]
attrs.merge!(
:entity_id => Entity.first_or_create(data['entity']).id,
:entity => data['entity']
)
elsif options[:entity]
attrs.merge!(
:entity_id => options[:entity_id] || Entity.first_or_create(options[:entity]).id,
:entity => options[:entity]
)
else
attrs.merge!(
:entity_id => current_user.entity_id,
:entity => current_user.entity,
)
end
if options[:public_id]
attrs[:public_id] = options[:public_id]
end
if data['version'] && Array === data['version']['parents']
attrs[:version_parents] = data['version']['parents']
attrs[:version_parents].each_with_index do |item, index|
unless item['version']
raise CreateFailure.new("/version/parents/#{index}/version is required")
end
unless item['post']
if options[:public_id]
item['post'] = attrs[:public_id]
else
raise CreateFailure.new("/version/parents/#{index}/post is required")
end
end
end
elsif options[:version]
unless options[:notification]
raise CreateFailure.new("Parent version not specified")
end
end
if TentType.new(attrs[:type]).base == %(https://tent.io/types/meta)
# meta post is always public
attrs[:public] = true
else
if Hash === data['permissions']
if data['permissions']['public'] == true
attrs[:public] = true
else
attrs[:public] = false
if Array === data['permissions']['entities']
attrs[:permissions_entities] = data['permissions']['entities']
end
end
else
attrs[:public] = true
end
end
if Array === data['mentions'] && data['mentions'].any?
attrs[:mentions] = data['mentions'].map do |m|
m['entity'] = attrs[:entity] unless m.has_key?('entity')
m
end
end
if Array === data['refs'] && data['refs'].any?
attrs[:refs] = data['refs'].map do |ref|
ref['entity'] = attrs[:entity] unless ref.has_key?('entity')
ref
end
end
if options[:notification]
attrs[:attachments] = data['attachments'] if Array === data['attachments']
else
if Array === data['attachments']
data['attachments'] = data['attachments'].inject([]) do |memo, attachment|
raise CreateFailure.new("Unknown attachment: #{Yajl::Encoder.encode(attachment)}") unless attachment.has_key?('digest')
if model = Attachment.where(:digest => attachment['digest']).first
attachment['model'] = model
memo << attachment
else
raise CreateFailure.new("Unknown attachment: #{Yajl::Encoder.encode(attachment)}")
end
memo
end
attrs[:attachments] = data['attachments'].map do |attachment|
{
:digest => attachment['digest'],
:size => attachment['model'].size,
:name => attachment['name'],
:category => attachment['category'],
:content_type => attachment['content_type']
}
end
end
if Array === env['attachments']
attrs[:attachments] = env['attachments'].inject(attrs[:attachments] || Array.new) do |memo, attachment|
memo << {
:digest => TentD::Utils.hex_digest(attachment[:tempfile]),
:size => attachment[:tempfile].size,
:name => attachment[:name],
:category => attachment[:category],
:content_type => attachment[:content_type]
}
memo
end
end
end
attrs
end
def create_delete_post(post, options = {})
ref = { 'entity' => post.entity, 'post' => post.public_id }
ref['version'] = post.version if options[:version]
create_from_env(
'current_user' => post.user,
'data' => {
'type' => 'https://tent.io/types/delete/v0#',
'refs' => [ ref ]
}
)
end
def delete_from_notification(env, post)
post_conditions = post.refs.to_a.inject({}) do |memo, ref|
next memo unless !ref['entity'] || ref['entity'] == post.entity
memo[ref['post']] ||= []
memo[ref['post']] << ref['version'] if ref['version']
memo
end.inject([]) do |memo, (public_id, versions)|
memo << if versions.any?
{ :public_id => public_id, :version => versions }
else
{ :public_id => public_id }
end
memo
end
q = Post.where(:user_id => env['current_user'].id, :entity_id => post.entity_id)
q = q.where(Sequel.|(*post_conditions))
q.all.to_a.each do |post|
delete_opts = { :create_delete_post => false }
delete_opts[:version] = !!post_conditions.find { |c| c[:public_id] == post.public_id }[:version]
post.destroy(delete_opts)
end
end
def create_from_env(env, options = {})
attrs = build_attributes(env, options)
if TentType.new(env['data']['type']).base == %(https://tent.io/types/subscription)
if options[:notification]
subscription = Subscription.create_from_notification(env['current_user'], attrs, env['current_auth.resource'])
post = subscription.post
else
subscription = Subscription.find_or_create(attrs)
post = subscription.post
if subscription.deliver == false
# this will happen as part of the relaitonship init job
options[:deliver_notification] = false
end
end
elsif options[:import] &&
(
TentType.new(attrs[:type]).base == %(https://tent.io/types/relationship) ||
(TentType.new(attrs[:type]).base == %(https://tent.io/types/credentials) &&
attrs[:mentions].any? { |m|
TentType.new(m['type']).base == %(https://tent.io/types/relationship)
})
)
# is a relationship post or credentials mentioning one
import_results = RelationshipImporter.import(env['current_user'], attrs)
post = import_results.post
else
post = Post.create(attrs)
end
case TentType.new(post.type).base
when %(https://tent.io/types/app)
App.update_or_create_from_post(post, :create_credentials => !options[:import])
when %(https://tent.io/types/app-auth)
if options[:import] && (m = post.mentions.find { |m| TentType.new(m['type']).base == %(https://tent.io/types/app) })
App.update_app_auth(post, m['post'])
end
when %(https://tent.io/types/credentials)
if options[:import]
if m = post.mentions.find { |m| TentType.new(m['type']).base == %(https://tent.io/types/app) }
App.update_credentials(post, m['post'])
elsif m = post.mentions.find { |m| TentType.new(m['type']).base == %(https://tent.io/types/app-auth) }
App.update_app_auth_credentials(post, m['post'])
end
end
end
if options[:notification] && TentType.new(post.type).base == %(https://tent.io/types/delete)
delete_from_notification(env, post)
end
if TentType.new(post.type).base == %(https://tent.io/types/meta)
env['current_user'].update_meta_post_id(post)
Relationship.update_meta_post_ids(post)
end
if Array === env['data']['mentions']
post.create_mentions(env['data']['mentions'])
end
unless options[:notification]
if Array === env['data']['attachments']
env['data']['attachments'].each do |attachment|
PostsAttachment.create(
:attachment_id => attachment['model'].id,
:content_type => attachment['content_type'],
:post_id => post.id
)
end
end
if Array === env['attachments']
post.create_attachments(env['attachments'])
end
end
if Array === attrs[:version_parents]
post.create_version_parents(attrs[:version_parents])
end
if !options[:notification] && !options[:import] && options[:deliver_notification] != false
post.queue_delivery
end
post
end
def create_attachments(post, attachments)
attachments.each_with_index do |attachment, index|
data = attachment[:tempfile].read
attachment[:tempfile].rewind
PostsAttachment.create(
:attachment_id => Attachment.find_or_create(
TentD::Utils::Hash.slice(post.attachments[index], 'digest', 'size').merge(:data => data)
).id,
:post_id => post.id,
:content_type => attachment[:content_type]
)
end
end
def create_mentions(post, mentions)
mentions.map do |mention|
mention_attrs = {
:user_id => post.user_id,
:post_id => post.id
}
if mention['entity']
mention_attrs[:entity_id] = Entity.first_or_create(mention['entity']).id
mention_attrs[:entity] = mention['entity']
else
mention_attrs[:entity_id] = post.entity_id
mention_attrs[:entity] = post.entity
end
if mention['type']
mention_attrs[:type_id] = Type.find_or_create_full(mention['type']).id
mention_attrs[:type] = mention['type']
end
mention_attrs[:post] = mention['post'] if mention.has_key?('post')
mention_attrs[:public] = mention['public'] if mention.has_key?('public')
Mention.create(mention_attrs)
end
end
def create_version_parents(post, version_parents)
version_parents.each do |item|
item['post'] ||= post.public_id
_parent = Post.where(:user_id => post.user_id, :public_id => item['post'], :version => item['version']).first
Parent.create(
:post_id => post.id,
:parent_post_id => _parent ? _parent.id : nil,
:version => item['version'],
:post => item['post']
)
end
end
end
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
## User
User.create!({
nom: 'Doe',
prenom: 'John',
telephone: ENV["Default_SMS_Number"],
email: 'admin@example.com',
password: 'password',
password_confirmation: 'password',
confirmed_at: DateTime.now
})
user = User.find_by(email: 'admin@example.com')
user.add_role :entrepreneur
user.add_role :restaurateur
user.add_role :livreur
user.add_role :client
## Restaurants
Restaurant.create!([{
nom: "Noma",
adresse: "200 Rue Beaubien Est, Montréal, QC H2S 1R4"
}, {
nom: "Eleven Madison Park",
adresse: "New York, USA"
}, {
nom: "Bouillon Bilk",
adresse: "1595 Boul Saint-Laurent, Montréal, Québec H2X 2S9, Canada"
}])
## Menus et Plats
Menu.create!([{
nom: "Spéciaux",
restaurant_id: 3,
plats_attributes: [{
nom: "McDouble Xtrem Plus",
description: "S.O.",
prix: "6.0",
}, {
nom: "Bob Burger",
description: "S.O.",
prix: "5.0",
}],
}, {
nom: "Le menu festin",
restaurant_id: 2,
plats_attributes: [{
nom: "McDouble Xtrem Plus",
description: "S.O.",
prix: "3.75",
}, {
nom: "Sushi",
description: "S.O.",
prix: "8.25",
}],
}])
## Adresses
[
"1100 rue Notre-Dame Ouest, Montréal, QC H3C 1K3",
"1111 rue Notre-Dame Ouest, Montréal, QC H3C 6M8",
"1909 Avenue des Canadiens-de-Montréal, Montréal, QC H4B 5G0",
"845 Rue Sherbrooke O, Montréal, QC H3A 0G4",
"4777 Avenue Pierre-de Coubertin, Montréal, QC H1V 1B3"
].each do |address|
Adresse.create!(value: address, user_id: 1)
end
## Commandes
Commande.create!([{
date_de_livraison: 1.hour.from_now,
restaurant_id: 1,
adresse_id: 1,
ligne_commandes_attributes: [{qte: 70, plat_id: 1}],
user_id: 1
}, {
date_de_livraison: 3.hour.from_now,
restaurant_id: 2,
adresse_id: 1,
ligne_commandes_attributes: [{qte: 2, plat_id: 1}, {qte: 1, plat_id: 2}],
user_id: 1
}, {
date_de_livraison: 4.days.from_now,
restaurant_id: 3,
adresse_id: 1,
ligne_commandes_attributes: [{qte: 3, plat_id: 1}, {qte: 5, plat_id: 2}, {qte: 8, plat_id: 3}, {qte: 14, plat_id: 4}],
user_id: 1,
etat: Commande.etats[:prete]
}])
MOD : update seed
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
## User
User.create!({
nom: 'Doe',
prenom: 'John',
telephone: ENV["Default_SMS_Number"],
email: 'admin@example.com',
password: 'password',
password_confirmation: 'password',
confirmed_at: DateTime.now
})
user = User.find_by(email: 'admin@example.com')
[:entrepreneur, :restaurateur, :livreur, :client].each do |role|
n = User.new({
nom: role.capitalize,
prenom: 'LOGTI',
telephone: ENV["Default_SMS_Number"],
email: "#{role.to_s}@example.com",
password: 'password',
password_confirmation: 'password',
confirmed_at: DateTime.now
})
n.add_role role
n.save!
user.add_role role
end
## Restaurants
Restaurant.create!([{
nom: "Noma",
adresse: "200 Rue Beaubien Est, Montréal, QC H2S 1R4"
}, {
nom: "Europea",
adresse: "1227 Rue de la Montagne, Montréal, QC H3G 1Z2"
}, {
nom: "Bouillon Bilk",
adresse: "1595 Boul Saint-Laurent, Montréal, Québec H2X 2S9, Canada"
}, {
nom: "Evy ting Wong![TEST]",
adresse: "8335 Boul Langelier, Montréal, QC H1P 2B8"
}])
## Menus et Plats
Menu.create!([{
nom: "Spéciaux",
restaurant_id: 1,
plats_attributes: [{
nom: "McDouble Xtrem Plus",
description: "S.O.",
prix: "6.0"
}, {
nom: "Bob Burger",
description: "S.O.",
prix: "5.0"
}],
}, {
nom: "Soir",
restaurant_id: 3,
plats_attributes: [{
nom: "Hamachi",
description: "S.O.",
prix: "16.25"
}, {
nom: "Assortiment de fromages québécois",
description: "S.O.",
prix: "20.0"
}],
}, {
nom: "Menu dégustation signature",
restaurant_id: 2,
plats_attributes: [{
nom: "Risotto",
description: "Risotto crémeux mascarpone et burrata. Poêlée de champignons et asperges de saison. Mousseline de petits pois et vrilles.
Oeuf en coquille de béarnaise et crumble",
prix: "23.50"
}, {
nom: "Calamar",
description: "Calamar citronné et structuré en tagliatelles. OEuf de caille poché, croutons d’encre de seiche au beurre à l’ail",
prix: "23.50"
}, {
nom: "Cerf",
description: "Tartare de cerf boucané sous cloche. Pommes allumettes et croutons au wasabi. Réduction de carminé du Québec
et vieux cheddar. Émulsion de moutarde",
prix: "25.50"
}, {
nom: "Fruits de Mer",
description: "Calamar citronné et structuré en tagliatelles. OEuf de caille poché, croutons d’encre de seiche au beurre à l’ail",
prix: "26.50"
}],
}])
menu = { nom: "BIG @$$ Menu", restaurant_id: 4, plats_attributes: [] }
5000.times do |index|
nom = ('a'..'z').to_a.sample(10).join
description = ('a'..'z').to_a.sample(30).join
prix = (rand(100)+rand).round 2
menu[:plats_attributes] << { nom: nom, description: description, prix: prix }
end
## Adresses
[
"1100 rue Notre-Dame Ouest, Montréal, QC H3C 1K3",
"1111 rue Notre-Dame Ouest, Montréal, QC H3C 6M8",
"1909 Avenue des Canadiens-de-Montréal, Montréal, QC H4B 5G0",
"845 Rue Sherbrooke O, Montréal, QC H3A 0G4"
].each do |address|
Adresse.create!(value: address, user_id: 1)
end
User.all.each do |user|
Adresse.create! value: "4777 Avenue Pierre-de Coubertin, Montréal, QC H1V 1B3", user_id: user
end
## Commandes
ENV['SKIP_SMS'] = 'true'
Commande.create!([{
date_de_livraison: 1.hour.from_now,
restaurant_id: 1,
adresse_id: 1,
ligne_commandes_attributes: [{qte: 70, plat_id: 1}],
user_id: 1,
etat: Commande.etats[:paye]
}, {
date_de_livraison: 3.hour.from_now,
restaurant_id: 2,
adresse_id: 1,
ligne_commandes_attributes: [{qte: 2, plat_id: 5}, {qte: 1, plat_id: 6}],
user_id: 1,
etat: Commande.etats[:paye]
}, {
date_de_livraison: 4.days.from_now,
restaurant_id: 3,
adresse_id: 1,
ligne_commandes_attributes: [{qte: 3, plat_id: 3}, {qte: 5, plat_id: 4}],
user_id: 1,
etat: Commande.etats[:prete]
}])
|
require File.dirname(__FILE__) + "/cli"
require File.dirname(__FILE__) + "/helpers/get_callable"
require File.dirname(__FILE__) + "/helpers/logging"
require "shellwords"
module Roger
class Release
include Roger::Helpers::Logging
attr_reader :config, :project
attr_reader :finalizers, :stack
class << self
include Roger::Helpers::GetCallable
def default_stack
[]
end
def default_finalizers
[[self.get_callable(:dir, Roger::Release::Finalizers.map), {}]]
end
end
# @option config [Symbol] :scm The SCM to use (default = :git)
# @option config [String, Pathname] :target_path The path/directory to put the release into
# @option config [String, Pathname]:build_path Temporary path used to build the release
# @option config [Boolean] :cleanup_build Wether or not to remove the build_path after we're done (default = true)
# @option config [Array,String, nil] :cp CP command to use; Array will be escaped with Shellwords. Pass nil to get native Ruby CP. (default = ["cp", "-RL"])
# @option config [Boolean] :blank Keeps the release clean, don't automatically add any processors or finalizers (default = false)
def initialize(project, config = {})
defaults = {
:scm => :git,
:source_path => Pathname.new(Dir.pwd) + "html",
:target_path => Pathname.new(Dir.pwd) + "releases",
:build_path => Pathname.new(Dir.pwd) + "build",
:cp => ["cp", "-RL"],
:blank => false,
:cleanup_build => true
}
@config = {}.update(defaults).update(config)
@project = project
@stack = []
@finalizers = []
end
# Accessor for target_path
# The target_path is the path where the finalizers will put the release
#
# @return Pathname the target_path
def target_path
Pathname.new(self.config[:target_path])
end
# Accessor for build_path
# The build_path is a temporary directory where the release will be built
#
# @return Pathname the build_path
def build_path
Pathname.new(self.config[:build_path])
end
# Accessor for source_path
# The source path is the root of the mockup
#
# @return Pathanem the source_path
def source_path
Pathname.new(self.config[:source_path])
end
# Get the current SCM object
def scm(force = false)
return @_scm if @_scm && !force
case self.config[:scm]
when :git
@_scm = Release::Scm::Git.new(:path => self.source_path)
else
raise "Unknown SCM #{options[:scm].inspect}"
end
end
# Inject variables into files with an optional filter
#
# @examples
# release.inject({"VERSION" => release.version, "DATE" => release.date}, :into => %w{_doc/toc.html})
# release.inject({"CHANGELOG" => {:file => "", :filter => BlueCloth}}, :into => %w{_doc/changelog.html})
def inject(variables, options)
@stack << Injector.new(variables, options)
end
# Use a certain pre-processor
#
# @examples
# release.use :sprockets, sprockets_config
def use(processor, options = {})
@stack << [self.class.get_callable(processor, Roger::Release::Processors.map), options]
end
# Write out the whole release into a directory, zip file or anything you can imagine
# #finalize can be called multiple times, it just will run all of them.
#
# The default finalizer is :dir
#
# @param [Symbol, Proc] Finalizer to use
#
# @examples
# release.finalize :zip
def finalize(finalizer, options = {})
@finalizers << [self.class.get_callable(finalizer, Roger::Release::Finalizers.map), options]
end
# Files to clean up in the build directory just before finalization happens
#
# @param [String] Pattern to glob within build directory
#
# @examples
# release.cleanup "**/.DS_Store"
def cleanup(pattern)
@stack << Cleaner.new(pattern)
end
# Generates a banner if a block is given, or returns the currently set banner.
# It automatically takes care of adding comment marks around the banner.
#
# The default banner looks like this:
#
# =======================
# = Version : v1.0.0 =
# = Date : 2012-06-20 =
# =======================
#
#
# @option options [:css,:js,:html,false] :comment Wether or not to comment the output and in what style. (default=js)
def banner(options = {}, &block)
options = {
:comment => :js
}.update(options)
if block_given?
@_banner = yield.to_s
elsif !@_banner
banner = []
banner << "Version : #{self.scm.version}"
banner << "Date : #{self.scm.date.strftime("%Y-%m-%d")}"
size = banner.inject(0){|mem,b| b.size > mem ? b.size : mem }
banner.map!{|b| "= #{b.ljust(size)} =" }
div = "=" * banner.first.size
banner.unshift(div)
banner << div
@_banner = banner.join("\n")
end
if options[:comment]
self.comment(@_banner, :style => options[:comment])
else
@_banner
end
end
# Extract the mockup, this will happen anyway, and will always happen first
# This method gives you a way to pass options to the extractor.
#
# @param Hash options Options hash passed to extractor
#
# @deprecated Don't use the extractor anymore, use release.use(:mockup, options) processor
def extract(options = {})
self.warn(self, "Don't use the extractor anymore, use release.use(:mockup, options) and release.use(:url_relativizer, options) processors")
@extractor_options = options
end
# Actually perform the release
def run!
project.mode = :release
# Validate paths
validate_paths!
# Extract mockup
copy_source_path_to_build_path!
validate_stack!
# Run stack
run_stack!
# Run finalizers
run_finalizers!
# Cleanup
cleanup! if self.config[:cleanup_build]
ensure
project.mode = nil
end
# @param [Array] globs an array of file path globs that will be globbed against the build_path
# @param [Array] excludes an array of regexps that will be excluded from the result
def get_files(globs, excludes = [])
files = globs.map{|g| Dir.glob(self.build_path + g) }.flatten
if excludes.any?
files.reject{|c| excludes.detect{|e| e.match(c) } }
else
files
end
end
protected
# ==============
# = The runway =
# ==============
# Checks if build path exists (and cleans it up)
# Checks if target path exists (if not, creates it)
def validate_paths!
if self.build_path.exist?
log self, "Cleaning up previous build \"#{self.build_path}\""
rm_rf(self.build_path)
end
if !self.target_path.exist?
log self, "Creating target path \"#{self.target_path}\""
mkdir self.target_path
end
end
# Checks if deprecated extractor options have been set
# Checks if the mockup will be runned
# If config[:blank] is true it will automatically add UrlRelativizer or Mockup processor
def validate_stack!
return if config[:blank]
mockup_options = {}
relativizer_options = {}
run_relativizer = true
if @extractor_options
mockup_options = {:env => @extractor_options[:env]}
relativizer_options = {:url_attributes => @extractor_options[:url_attributes]}
run_relativizer = @extractor_options[:url_relativize]
end
unless @stack.find{|(processor, options)| processor.class == Roger::Release::Processors::Mockup }
@stack.unshift([Roger::Release::Processors::Mockup.new, mockup_options])
end
unless @stack.find{|(processor, options)| processor.class == Roger::Release::Processors::UrlRelativizer }
@stack.push([Roger::Release::Processors::UrlRelativizer.new, relativizer_options])
end
end
def copy_source_path_to_build_path!
mkdir(self.build_path)
if self.config[:cp]
command = [self.config[:cp]].flatten
system(Shellwords.join(command + ["#{self.source_path}/", self.build_path]))
else
cp_r(self.source_path.children, self.build_path)
end
end
def run_stack!
@stack = self.class.default_stack.dup if @stack.empty?
# call all objects in @stack
@stack.each do |task|
if (task.kind_of?(Array))
task[0].call(self, task[1])
else
task.call(self)
end
end
end
# Will run all finalizers, if no finalizers are set it will take the
# default finalizers.
#
# If config[:blank] is true, it will not use the default finalizers
def run_finalizers!
@finalizers = self.class.default_finalizers.dup if @finalizers.empty? && !config[:blank]
# call all objects in @finalizes
@finalizers.each do |finalizer|
finalizer[0].call(self, finalizer[1])
end
end
def cleanup!
log(self, "Cleaning up build path #{self.build_path}")
rm_rf(self.build_path)
end
# @param [String] string The string to comment
#
# @option options [:html, :css, :js] :style The comment style to use (default=:js, which is the same as :css)
# @option options [Boolean] :per_line Comment per line or make one block? (default=true)
def comment(string, options = {})
options = {
:style => :css,
:per_line => true
}.update(options)
commenters = {
:html => Proc.new{|s| "<!-- #{s} -->" },
:css => Proc.new{|s| "/*! #{s} */" },
:js => Proc.new{|s| "/*! #{s} */" }
}
commenter = commenters[options[:style]] || commenters[:js]
if options[:per_line]
string = string.split(/\r?\n/)
string.map{|s| commenter.call(s) }.join("\n")
else
commenter.call(s)
end
end
end
end
require File.dirname(__FILE__) + "/extractor"
require File.dirname(__FILE__) + "/release/scm"
require File.dirname(__FILE__) + "/release/injector"
require File.dirname(__FILE__) + "/release/cleaner"
require File.dirname(__FILE__) + "/release/finalizers"
require File.dirname(__FILE__) + "/release/processors"
When building releases take project path instead of current path
require File.dirname(__FILE__) + "/cli"
require File.dirname(__FILE__) + "/helpers/get_callable"
require File.dirname(__FILE__) + "/helpers/logging"
require "shellwords"
module Roger
class Release
include Roger::Helpers::Logging
attr_reader :config, :project
attr_reader :finalizers, :stack
class << self
include Roger::Helpers::GetCallable
def default_stack
[]
end
def default_finalizers
[[self.get_callable(:dir, Roger::Release::Finalizers.map), {}]]
end
end
# @option config [Symbol] :scm The SCM to use (default = :git)
# @option config [String, Pathname] :target_path The path/directory to put the release into
# @option config [String, Pathname]:build_path Temporary path used to build the release
# @option config [Boolean] :cleanup_build Wether or not to remove the build_path after we're done (default = true)
# @option config [Array,String, nil] :cp CP command to use; Array will be escaped with Shellwords. Pass nil to get native Ruby CP. (default = ["cp", "-RL"])
# @option config [Boolean] :blank Keeps the release clean, don't automatically add any processors or finalizers (default = false)
def initialize(project, config = {})
defaults = {
:scm => :git,
:source_path => project.path + "html",
:target_path => project.path + "releases",
:build_path => project.path + "build",
:cp => ["cp", "-RL"],
:blank => false,
:cleanup_build => true
}
@config = {}.update(defaults).update(config)
@project = project
@stack = []
@finalizers = []
end
# Accessor for target_path
# The target_path is the path where the finalizers will put the release
#
# @return Pathname the target_path
def target_path
Pathname.new(self.config[:target_path])
end
# Accessor for build_path
# The build_path is a temporary directory where the release will be built
#
# @return Pathname the build_path
def build_path
Pathname.new(self.config[:build_path])
end
# Accessor for source_path
# The source path is the root of the mockup
#
# @return Pathanem the source_path
def source_path
Pathname.new(self.config[:source_path])
end
# Get the current SCM object
def scm(force = false)
return @_scm if @_scm && !force
case self.config[:scm]
when :git
@_scm = Release::Scm::Git.new(:path => self.source_path)
else
raise "Unknown SCM #{options[:scm].inspect}"
end
end
# Inject variables into files with an optional filter
#
# @examples
# release.inject({"VERSION" => release.version, "DATE" => release.date}, :into => %w{_doc/toc.html})
# release.inject({"CHANGELOG" => {:file => "", :filter => BlueCloth}}, :into => %w{_doc/changelog.html})
def inject(variables, options)
@stack << Injector.new(variables, options)
end
# Use a certain pre-processor
#
# @examples
# release.use :sprockets, sprockets_config
def use(processor, options = {})
@stack << [self.class.get_callable(processor, Roger::Release::Processors.map), options]
end
# Write out the whole release into a directory, zip file or anything you can imagine
# #finalize can be called multiple times, it just will run all of them.
#
# The default finalizer is :dir
#
# @param [Symbol, Proc] Finalizer to use
#
# @examples
# release.finalize :zip
def finalize(finalizer, options = {})
@finalizers << [self.class.get_callable(finalizer, Roger::Release::Finalizers.map), options]
end
# Files to clean up in the build directory just before finalization happens
#
# @param [String] Pattern to glob within build directory
#
# @examples
# release.cleanup "**/.DS_Store"
def cleanup(pattern)
@stack << Cleaner.new(pattern)
end
# Generates a banner if a block is given, or returns the currently set banner.
# It automatically takes care of adding comment marks around the banner.
#
# The default banner looks like this:
#
# =======================
# = Version : v1.0.0 =
# = Date : 2012-06-20 =
# =======================
#
#
# @option options [:css,:js,:html,false] :comment Wether or not to comment the output and in what style. (default=js)
def banner(options = {}, &block)
options = {
:comment => :js
}.update(options)
if block_given?
@_banner = yield.to_s
elsif !@_banner
banner = []
banner << "Version : #{self.scm.version}"
banner << "Date : #{self.scm.date.strftime("%Y-%m-%d")}"
size = banner.inject(0){|mem,b| b.size > mem ? b.size : mem }
banner.map!{|b| "= #{b.ljust(size)} =" }
div = "=" * banner.first.size
banner.unshift(div)
banner << div
@_banner = banner.join("\n")
end
if options[:comment]
self.comment(@_banner, :style => options[:comment])
else
@_banner
end
end
# Extract the mockup, this will happen anyway, and will always happen first
# This method gives you a way to pass options to the extractor.
#
# @param Hash options Options hash passed to extractor
#
# @deprecated Don't use the extractor anymore, use release.use(:mockup, options) processor
def extract(options = {})
self.warn(self, "Don't use the extractor anymore, use release.use(:mockup, options) and release.use(:url_relativizer, options) processors")
@extractor_options = options
end
# Actually perform the release
def run!
project.mode = :release
# Validate paths
validate_paths!
# Extract mockup
copy_source_path_to_build_path!
validate_stack!
# Run stack
run_stack!
# Run finalizers
run_finalizers!
# Cleanup
cleanup! if self.config[:cleanup_build]
ensure
project.mode = nil
end
# @param [Array] globs an array of file path globs that will be globbed against the build_path
# @param [Array] excludes an array of regexps that will be excluded from the result
def get_files(globs, excludes = [])
files = globs.map{|g| Dir.glob(self.build_path + g) }.flatten
if excludes.any?
files.reject{|c| excludes.detect{|e| e.match(c) } }
else
files
end
end
protected
# ==============
# = The runway =
# ==============
# Checks if build path exists (and cleans it up)
# Checks if target path exists (if not, creates it)
def validate_paths!
if self.build_path.exist?
log self, "Cleaning up previous build \"#{self.build_path}\""
rm_rf(self.build_path)
end
if !self.target_path.exist?
log self, "Creating target path \"#{self.target_path}\""
mkdir self.target_path
end
end
# Checks if deprecated extractor options have been set
# Checks if the mockup will be runned
# If config[:blank] is true it will automatically add UrlRelativizer or Mockup processor
def validate_stack!
return if config[:blank]
mockup_options = {}
relativizer_options = {}
run_relativizer = true
if @extractor_options
mockup_options = {:env => @extractor_options[:env]}
relativizer_options = {:url_attributes => @extractor_options[:url_attributes]}
run_relativizer = @extractor_options[:url_relativize]
end
unless @stack.find{|(processor, options)| processor.class == Roger::Release::Processors::Mockup }
@stack.unshift([Roger::Release::Processors::Mockup.new, mockup_options])
end
unless @stack.find{|(processor, options)| processor.class == Roger::Release::Processors::UrlRelativizer }
@stack.push([Roger::Release::Processors::UrlRelativizer.new, relativizer_options])
end
end
def copy_source_path_to_build_path!
mkdir(self.build_path)
if self.config[:cp]
command = [self.config[:cp]].flatten
system(Shellwords.join(command + ["#{self.source_path}/", self.build_path]))
else
cp_r(self.source_path.children, self.build_path)
end
end
def run_stack!
@stack = self.class.default_stack.dup if @stack.empty?
# call all objects in @stack
@stack.each do |task|
if (task.kind_of?(Array))
task[0].call(self, task[1])
else
task.call(self)
end
end
end
# Will run all finalizers, if no finalizers are set it will take the
# default finalizers.
#
# If config[:blank] is true, it will not use the default finalizers
def run_finalizers!
@finalizers = self.class.default_finalizers.dup if @finalizers.empty? && !config[:blank]
# call all objects in @finalizes
@finalizers.each do |finalizer|
finalizer[0].call(self, finalizer[1])
end
end
def cleanup!
log(self, "Cleaning up build path #{self.build_path}")
rm_rf(self.build_path)
end
# @param [String] string The string to comment
#
# @option options [:html, :css, :js] :style The comment style to use (default=:js, which is the same as :css)
# @option options [Boolean] :per_line Comment per line or make one block? (default=true)
def comment(string, options = {})
options = {
:style => :css,
:per_line => true
}.update(options)
commenters = {
:html => Proc.new{|s| "<!-- #{s} -->" },
:css => Proc.new{|s| "/*! #{s} */" },
:js => Proc.new{|s| "/*! #{s} */" }
}
commenter = commenters[options[:style]] || commenters[:js]
if options[:per_line]
string = string.split(/\r?\n/)
string.map{|s| commenter.call(s) }.join("\n")
else
commenter.call(s)
end
end
end
end
require File.dirname(__FILE__) + "/extractor"
require File.dirname(__FILE__) + "/release/scm"
require File.dirname(__FILE__) + "/release/injector"
require File.dirname(__FILE__) + "/release/cleaner"
require File.dirname(__FILE__) + "/release/finalizers"
require File.dirname(__FILE__) + "/release/processors"
|
# frozen_string_literal: true
Doorkeeper.configure do
# Change the ORM that doorkeeper will use (needs plugins)
orm :active_record
# This block will be called to check whether the resource owner is authenticated or not.
resource_owner_authenticator do
raise "Please configure doorkeeper resource_owner_authenticator block located in #{__FILE__}"
# Put your resource owner authentication logic here.
# Example implementation:
# User.find_by_id(session[:user_id]) || redirect_to(new_user_session_url)
end
# If you didn't skip applications controller from Doorkeeper routes in your application routes.rb
# file then you need to declare this block in order to restrict access to the web interface for
# adding oauth authorized applications. In other case it will return 403 Forbidden response
# every time somebody will try to access the admin web interface.
#
# admin_authenticator do
# # Put your admin authentication logic here.
# # Example implementation:
#
# if current_user
# head :forbidden unless current_user.admin?
# else
# redirect_to sign_in_url
# end
# end
# If you are planning to use Doorkeeper in Rails 5 API-only application, then you might
# want to use API mode that will skip all the views management and change the way how
# Doorkeeper responds to a requests.
#
# api_only
# Enforce token request content type to application/x-www-form-urlencoded.
# It is not enabled by default to not break prior versions of the gem.
#
# enforce_content_type
# Authorization Code expiration time (default 10 minutes).
#
# authorization_code_expires_in 10.minutes
# Access token expiration time (default 2 hours).
# If you want to disable expiration, set this to nil.
#
# access_token_expires_in 2.hours
# Assign custom TTL for access tokens. Will be used instead of access_token_expires_in
# option if defined. In case the block returns `nil` value Doorkeeper fallbacks to
# `access_token_expires_in` configuration option value. If you really need to issue a
# non-expiring access token (which is not recommended) then you need to return
# Float::INFINITY from this block.
#
# `context` has the following properties available:
#
# `client` - the OAuth client application (see Doorkeeper::OAuth::Client)
# `grant_type` - the grant type of the request (see Doorkeeper::OAuth)
# `scopes` - the requested scopes (see Doorkeeper::OAuth::Scopes)
#
# custom_access_token_expires_in do |context|
# context.client.application.additional_settings.implicit_oauth_expiration
# end
# Use a custom class for generating the access token.
# See https://doorkeeper.gitbook.io/guides/configuration/other-configurations#custom-access-token-generator
#
# access_token_generator '::Doorkeeper::JWT'
# The controller Doorkeeper::ApplicationController inherits from.
# Defaults to ActionController::Base.
# See https://doorkeeper.gitbook.io/guides/configuration/other-configurations#custom-base-controller
#
# base_controller 'ApplicationController'
# Reuse access token for the same resource owner within an application (disabled by default).
#
# This option protects your application from creating new tokens before old valid one becomes
# expired so your database doesn't bloat. Keep in mind that when this option is `on` Doorkeeper
# doesn't updates existing token expiration time, it will create a new token instead.
# Rationale: https://github.com/doorkeeper-gem/doorkeeper/issues/383
#
# You can not enable this option together with +hash_token_secrets+.
#
# reuse_access_token
# Set a limit for token_reuse if using reuse_access_token option
#
# This option limits token_reusability to some extent.
# If not set then access_token will be reused unless it expires.
# Rationale: https://github.com/doorkeeper-gem/doorkeeper/issues/1189
#
# This option should be a percentage(i.e. (0,100])
#
# token_reuse_limit 100
# Hash access and refresh tokens before persisting them.
# This will disable the possibility to use +reuse_access_token+
# since plain values can no longer be retrieved.
#
# Note: If you are already a user of doorkeeper and have existing tokens
# in your installation, they will be invalid without enabling the additional
# setting `fallback_to_plain_secrets` below.
#
# hash_token_secrets
# By default, token secrets will be hashed using the
# +Doorkeeper::Hashing::SHA256+ strategy.
#
# If you wish to use another hashing implementation, you can override
# this strategy as follows:
#
# hash_token_secrets using: '::Doorkeeper::Hashing::MyCustomHashImpl'
#
# Keep in mind that changing the hashing function will invalidate all existing
# secrets, if there are any.
# Hash application secrets before persisting them.
#
# hash_application_secrets
#
# By default, applications will be hashed
# with the +Doorkeeper::SecretStoring::SHA256+ strategy.
#
# If you wish to use bcrypt for application secret hashing, uncomment
# this line instead:
#
# hash_application_secrets using: '::Doorkeeper::SecretStoring::BCrypt'
# When the above option is enabled,
# and a hashed token or secret is not found,
# you can allow to fall back to another strategy.
# For users upgrading doorkeeper and wishing to enable hashing,
# you will probably want to enable the fallback to plain tokens.
#
# This will ensure that old access tokens and secrets
# will remain valid even if the hashing above is enabled.
#
# fallback_to_plain_secrets
# Issue access tokens with refresh token (disabled by default), you may also
# pass a block which accepts `context` to customize when to give a refresh
# token or not. Similar to `custom_access_token_expires_in`, `context` has
# the properties:
#
# `client` - the OAuth client application (see Doorkeeper::OAuth::Client)
# `grant_type` - the grant type of the request (see Doorkeeper::OAuth)
# `scopes` - the requested scopes (see Doorkeeper::OAuth::Scopes)
#
# use_refresh_token
# Provide support for an owner to be assigned to each registered application (disabled by default)
# Optional parameter confirmation: true (default false) if you want to enforce ownership of
# a registered application
# NOTE: you must also run the rails g doorkeeper:application_owner generator
# to provide the necessary support
#
# enable_application_owner confirmation: false
# Define access token scopes for your provider
# For more information go to
# https://doorkeeper.gitbook.io/guides/ruby-on-rails/scopes
#
# default_scopes :public
# optional_scopes :write, :update
# Define scopes_by_grant_type to restrict only certain scopes for grant_type
# By default, all the scopes will be available for all the grant types.
#
# Keys to this hash should be the name of grant_type and
# values should be the array of scopes for that grant type.
# Note: scopes should be from configured_scopes(i.e. default or optional)
#
# scopes_by_grant_type password: [:write], client_credentials: [:update]
# Forbids creating/updating applications with arbitrary scopes that are
# not in configuration, i.e. `default_scopes` or `optional_scopes`.
# (disabled by default)
#
# enforce_configured_scopes
# Change the way client credentials are retrieved from the request object.
# By default it retrieves first from the `HTTP_AUTHORIZATION` header, then
# falls back to the `:client_id` and `:client_secret` params from the `params` object.
# Check out https://github.com/doorkeeper-gem/doorkeeper/wiki/Changing-how-clients-are-authenticated
# for more information on customization
#
# client_credentials :from_basic, :from_params
# Change the way access token is authenticated from the request object.
# By default it retrieves first from the `HTTP_AUTHORIZATION` header, then
# falls back to the `:access_token` or `:bearer_token` params from the `params` object.
# Check out https://github.com/doorkeeper-gem/doorkeeper/wiki/Changing-how-clients-are-authenticated
# for more information on customization
#
# access_token_methods :from_bearer_authorization, :from_access_token_param, :from_bearer_param
# Forces the usage of the HTTPS protocol in non-native redirect uris (enabled
# by default in non-development environments). OAuth2 delegates security in
# communication to the HTTPS protocol so it is wise to keep this enabled.
#
# Callable objects such as proc, lambda, block or any object that responds to
# #call can be used in order to allow conditional checks (to allow non-SSL
# redirects to localhost for example).
#
# force_ssl_in_redirect_uri !Rails.env.development?
#
# force_ssl_in_redirect_uri { |uri| uri.host != 'localhost' }
# Specify what redirect URI's you want to block during Application creation.
# Any redirect URI is whitelisted by default.
#
# You can use this option in order to forbid URI's with 'javascript' scheme
# for example.
#
# forbid_redirect_uri { |uri| uri.scheme.to_s.downcase == 'javascript' }
# Allows to set blank redirect URIs for Applications in case Doorkeeper configured
# to use URI-less OAuth grant flows like Client Credentials or Resource Owner
# Password Credentials. The option is on by default and checks configured grant
# types, but you **need** to manually drop `NOT NULL` constraint from `redirect_uri`
# column for `oauth_applications` database table.
#
# You can completely disable this feature with:
#
# allow_blank_redirect_uri false
#
# Or you can define your custom check:
#
# allow_blank_redirect_uri do |grant_flows, client|
# client.superapp?
# end
# Specify how authorization errors should be handled.
# By default, doorkeeper renders json errors when access token
# is invalid, expired, revoked or has invalid scopes.
#
# If you want to render error response yourself (i.e. rescue exceptions),
# set handle_auth_errors to `:raise` and rescue Doorkeeper::Errors::InvalidToken
# or following specific errors:
#
# Doorkeeper::Errors::TokenForbidden, Doorkeeper::Errors::TokenExpired,
# Doorkeeper::Errors::TokenRevoked, Doorkeeper::Errors::TokenUnknown
#
# handle_auth_errors :raise
# Customize token introspection response.
# Allows to add your own fields to default one that are required by the OAuth spec
# for the introspection response. It could be `sub`, `aud` and so on.
# This configuration option can be a proc, lambda or any Ruby object responds
# to `.call` method and result of it's invocation must be a Hash.
#
# custom_introspection_response do |token, context|
# {
# "sub": "Z5O3upPC88QrAjx00dis",
# "aud": "https://protected.example.net/resource",
# "username": User.find(token.resource_owner_id).username
# }
# end
#
# or
#
# custom_introspection_response CustomIntrospectionResponder
# Specify what grant flows are enabled in array of Strings. The valid
# strings and the flows they enable are:
#
# "authorization_code" => Authorization Code Grant Flow
# "implicit" => Implicit Grant Flow
# "password" => Resource Owner Password Credentials Grant Flow
# "client_credentials" => Client Credentials Grant Flow
#
# If not specified, Doorkeeper enables authorization_code and
# client_credentials.
#
# implicit and password grant flows have risks that you should understand
# before enabling:
# http://tools.ietf.org/html/rfc6819#section-4.4.2
# http://tools.ietf.org/html/rfc6819#section-4.4.3
#
# grant_flows %w[authorization_code client_credentials]
# Hook into the strategies' request & response life-cycle in case your
# application needs advanced customization or logging:
#
# before_successful_strategy_response do |request|
# puts "BEFORE HOOK FIRED! #{request}"
# end
#
# after_successful_strategy_response do |request, response|
# puts "AFTER HOOK FIRED! #{request}, #{response}"
# end
# Hook into Authorization flow in order to implement Single Sign Out
# or add any other functionality.
#
# before_successful_authorization do |controller|
# Rails.logger.info(controller.request.params.inspect)
# end
#
# after_successful_authorization do |controller|
# controller.session[:logout_urls] <<
# Doorkeeper::Application
# .find_by(controller.request.params.slice(:redirect_uri))
# .logout_uri
# end
# Under some circumstances you might want to have applications auto-approved,
# so that the user skips the authorization step.
# For example if dealing with a trusted application.
#
# skip_authorization do |resource_owner, client|
# client.superapp? or resource_owner.admin?
# end
# Configure custom constraints for the Token Introspection request.
# By default this configuration option allows to introspect a token by another
# token of the same application, OR to introspect the token that belongs to
# authorized client (from authenticated client) OR when token doesn't
# belong to any client (public token). Otherwise requester has no access to the
# introspection and it will return response as stated in the RFC.
#
# Block arguments:
#
# @param token [Doorkeeper::AccessToken]
# token to be introspected
#
# @param authorized_client [Doorkeeper::Application]
# authorized client (if request is authorized using Basic auth with
# Client Credentials for example)
#
# @param authorized_token [Doorkeeper::AccessToken]
# Bearer token used to authorize the request
#
# In case the block returns `nil` or `false` introspection responses with 401 status code
# when using authorized token to introspect, or you'll get 200 with { "active": false } body
# when using authorized client to introspect as stated in the
# RFC 7662 section 2.2. Introspection Response.
#
# Using with caution:
# Keep in mind that these three parameters pass to block can be nil as following case:
# `authorized_client` is nil if and only if `authorized_token` is present, and vice versa.
# `token` will be nil if and only if `authorized_token` is present.
# So remember to use `&` or check if it is present before calling method on
# them to make sure you doesn't get NoMethodError exception.
#
# You can define your custom check:
#
# allow_token_introspection do |token, authorized_client, authorized_token|
# if authorized_token
# # customize: require `introspection` scope
# authorized_token.application == token&.application ||
# authorized_token.scopes.include?("introspection")
# elsif token.application
# # `protected_resource` is a new database boolean column, for example
# authorized_client == token.application || authorized_client.protected_resource?
# else
# # public token (when token.application is nil, token doesn't belong to any application)
# true
# end
# end
#
# Or you can completely disable any token introspection:
#
# allow_token_introspection false
#
# If you need to block the request at all, then configure your routes.rb or web-server
# like nginx to forbid the request.
# WWW-Authenticate Realm (default "Doorkeeper").
#
# realm "Doorkeeper"
end
Use `find_by` instead of `find_by_id` in initializer template
`find_by_id` style is deprecated.
# frozen_string_literal: true
Doorkeeper.configure do
# Change the ORM that doorkeeper will use (needs plugins)
orm :active_record
# This block will be called to check whether the resource owner is authenticated or not.
resource_owner_authenticator do
raise "Please configure doorkeeper resource_owner_authenticator block located in #{__FILE__}"
# Put your resource owner authentication logic here.
# Example implementation:
# User.find_by(id: session[:user_id]) || redirect_to(new_user_session_url)
end
# If you didn't skip applications controller from Doorkeeper routes in your application routes.rb
# file then you need to declare this block in order to restrict access to the web interface for
# adding oauth authorized applications. In other case it will return 403 Forbidden response
# every time somebody will try to access the admin web interface.
#
# admin_authenticator do
# # Put your admin authentication logic here.
# # Example implementation:
#
# if current_user
# head :forbidden unless current_user.admin?
# else
# redirect_to sign_in_url
# end
# end
# If you are planning to use Doorkeeper in Rails 5 API-only application, then you might
# want to use API mode that will skip all the views management and change the way how
# Doorkeeper responds to a requests.
#
# api_only
# Enforce token request content type to application/x-www-form-urlencoded.
# It is not enabled by default to not break prior versions of the gem.
#
# enforce_content_type
# Authorization Code expiration time (default 10 minutes).
#
# authorization_code_expires_in 10.minutes
# Access token expiration time (default 2 hours).
# If you want to disable expiration, set this to nil.
#
# access_token_expires_in 2.hours
# Assign custom TTL for access tokens. Will be used instead of access_token_expires_in
# option if defined. In case the block returns `nil` value Doorkeeper fallbacks to
# `access_token_expires_in` configuration option value. If you really need to issue a
# non-expiring access token (which is not recommended) then you need to return
# Float::INFINITY from this block.
#
# `context` has the following properties available:
#
# `client` - the OAuth client application (see Doorkeeper::OAuth::Client)
# `grant_type` - the grant type of the request (see Doorkeeper::OAuth)
# `scopes` - the requested scopes (see Doorkeeper::OAuth::Scopes)
#
# custom_access_token_expires_in do |context|
# context.client.application.additional_settings.implicit_oauth_expiration
# end
# Use a custom class for generating the access token.
# See https://doorkeeper.gitbook.io/guides/configuration/other-configurations#custom-access-token-generator
#
# access_token_generator '::Doorkeeper::JWT'
# The controller Doorkeeper::ApplicationController inherits from.
# Defaults to ActionController::Base.
# See https://doorkeeper.gitbook.io/guides/configuration/other-configurations#custom-base-controller
#
# base_controller 'ApplicationController'
# Reuse access token for the same resource owner within an application (disabled by default).
#
# This option protects your application from creating new tokens before old valid one becomes
# expired so your database doesn't bloat. Keep in mind that when this option is `on` Doorkeeper
# doesn't updates existing token expiration time, it will create a new token instead.
# Rationale: https://github.com/doorkeeper-gem/doorkeeper/issues/383
#
# You can not enable this option together with +hash_token_secrets+.
#
# reuse_access_token
# Set a limit for token_reuse if using reuse_access_token option
#
# This option limits token_reusability to some extent.
# If not set then access_token will be reused unless it expires.
# Rationale: https://github.com/doorkeeper-gem/doorkeeper/issues/1189
#
# This option should be a percentage(i.e. (0,100])
#
# token_reuse_limit 100
# Hash access and refresh tokens before persisting them.
# This will disable the possibility to use +reuse_access_token+
# since plain values can no longer be retrieved.
#
# Note: If you are already a user of doorkeeper and have existing tokens
# in your installation, they will be invalid without enabling the additional
# setting `fallback_to_plain_secrets` below.
#
# hash_token_secrets
# By default, token secrets will be hashed using the
# +Doorkeeper::Hashing::SHA256+ strategy.
#
# If you wish to use another hashing implementation, you can override
# this strategy as follows:
#
# hash_token_secrets using: '::Doorkeeper::Hashing::MyCustomHashImpl'
#
# Keep in mind that changing the hashing function will invalidate all existing
# secrets, if there are any.
# Hash application secrets before persisting them.
#
# hash_application_secrets
#
# By default, applications will be hashed
# with the +Doorkeeper::SecretStoring::SHA256+ strategy.
#
# If you wish to use bcrypt for application secret hashing, uncomment
# this line instead:
#
# hash_application_secrets using: '::Doorkeeper::SecretStoring::BCrypt'
# When the above option is enabled,
# and a hashed token or secret is not found,
# you can allow to fall back to another strategy.
# For users upgrading doorkeeper and wishing to enable hashing,
# you will probably want to enable the fallback to plain tokens.
#
# This will ensure that old access tokens and secrets
# will remain valid even if the hashing above is enabled.
#
# fallback_to_plain_secrets
# Issue access tokens with refresh token (disabled by default), you may also
# pass a block which accepts `context` to customize when to give a refresh
# token or not. Similar to `custom_access_token_expires_in`, `context` has
# the properties:
#
# `client` - the OAuth client application (see Doorkeeper::OAuth::Client)
# `grant_type` - the grant type of the request (see Doorkeeper::OAuth)
# `scopes` - the requested scopes (see Doorkeeper::OAuth::Scopes)
#
# use_refresh_token
# Provide support for an owner to be assigned to each registered application (disabled by default)
# Optional parameter confirmation: true (default false) if you want to enforce ownership of
# a registered application
# NOTE: you must also run the rails g doorkeeper:application_owner generator
# to provide the necessary support
#
# enable_application_owner confirmation: false
# Define access token scopes for your provider
# For more information go to
# https://doorkeeper.gitbook.io/guides/ruby-on-rails/scopes
#
# default_scopes :public
# optional_scopes :write, :update
# Define scopes_by_grant_type to restrict only certain scopes for grant_type
# By default, all the scopes will be available for all the grant types.
#
# Keys to this hash should be the name of grant_type and
# values should be the array of scopes for that grant type.
# Note: scopes should be from configured_scopes(i.e. default or optional)
#
# scopes_by_grant_type password: [:write], client_credentials: [:update]
# Forbids creating/updating applications with arbitrary scopes that are
# not in configuration, i.e. `default_scopes` or `optional_scopes`.
# (disabled by default)
#
# enforce_configured_scopes
# Change the way client credentials are retrieved from the request object.
# By default it retrieves first from the `HTTP_AUTHORIZATION` header, then
# falls back to the `:client_id` and `:client_secret` params from the `params` object.
# Check out https://github.com/doorkeeper-gem/doorkeeper/wiki/Changing-how-clients-are-authenticated
# for more information on customization
#
# client_credentials :from_basic, :from_params
# Change the way access token is authenticated from the request object.
# By default it retrieves first from the `HTTP_AUTHORIZATION` header, then
# falls back to the `:access_token` or `:bearer_token` params from the `params` object.
# Check out https://github.com/doorkeeper-gem/doorkeeper/wiki/Changing-how-clients-are-authenticated
# for more information on customization
#
# access_token_methods :from_bearer_authorization, :from_access_token_param, :from_bearer_param
# Forces the usage of the HTTPS protocol in non-native redirect uris (enabled
# by default in non-development environments). OAuth2 delegates security in
# communication to the HTTPS protocol so it is wise to keep this enabled.
#
# Callable objects such as proc, lambda, block or any object that responds to
# #call can be used in order to allow conditional checks (to allow non-SSL
# redirects to localhost for example).
#
# force_ssl_in_redirect_uri !Rails.env.development?
#
# force_ssl_in_redirect_uri { |uri| uri.host != 'localhost' }
# Specify what redirect URI's you want to block during Application creation.
# Any redirect URI is whitelisted by default.
#
# You can use this option in order to forbid URI's with 'javascript' scheme
# for example.
#
# forbid_redirect_uri { |uri| uri.scheme.to_s.downcase == 'javascript' }
# Allows to set blank redirect URIs for Applications in case Doorkeeper configured
# to use URI-less OAuth grant flows like Client Credentials or Resource Owner
# Password Credentials. The option is on by default and checks configured grant
# types, but you **need** to manually drop `NOT NULL` constraint from `redirect_uri`
# column for `oauth_applications` database table.
#
# You can completely disable this feature with:
#
# allow_blank_redirect_uri false
#
# Or you can define your custom check:
#
# allow_blank_redirect_uri do |grant_flows, client|
# client.superapp?
# end
# Specify how authorization errors should be handled.
# By default, doorkeeper renders json errors when access token
# is invalid, expired, revoked or has invalid scopes.
#
# If you want to render error response yourself (i.e. rescue exceptions),
# set handle_auth_errors to `:raise` and rescue Doorkeeper::Errors::InvalidToken
# or following specific errors:
#
# Doorkeeper::Errors::TokenForbidden, Doorkeeper::Errors::TokenExpired,
# Doorkeeper::Errors::TokenRevoked, Doorkeeper::Errors::TokenUnknown
#
# handle_auth_errors :raise
# Customize token introspection response.
# Allows to add your own fields to default one that are required by the OAuth spec
# for the introspection response. It could be `sub`, `aud` and so on.
# This configuration option can be a proc, lambda or any Ruby object responds
# to `.call` method and result of it's invocation must be a Hash.
#
# custom_introspection_response do |token, context|
# {
# "sub": "Z5O3upPC88QrAjx00dis",
# "aud": "https://protected.example.net/resource",
# "username": User.find(token.resource_owner_id).username
# }
# end
#
# or
#
# custom_introspection_response CustomIntrospectionResponder
# Specify what grant flows are enabled in array of Strings. The valid
# strings and the flows they enable are:
#
# "authorization_code" => Authorization Code Grant Flow
# "implicit" => Implicit Grant Flow
# "password" => Resource Owner Password Credentials Grant Flow
# "client_credentials" => Client Credentials Grant Flow
#
# If not specified, Doorkeeper enables authorization_code and
# client_credentials.
#
# implicit and password grant flows have risks that you should understand
# before enabling:
# http://tools.ietf.org/html/rfc6819#section-4.4.2
# http://tools.ietf.org/html/rfc6819#section-4.4.3
#
# grant_flows %w[authorization_code client_credentials]
# Hook into the strategies' request & response life-cycle in case your
# application needs advanced customization or logging:
#
# before_successful_strategy_response do |request|
# puts "BEFORE HOOK FIRED! #{request}"
# end
#
# after_successful_strategy_response do |request, response|
# puts "AFTER HOOK FIRED! #{request}, #{response}"
# end
# Hook into Authorization flow in order to implement Single Sign Out
# or add any other functionality.
#
# before_successful_authorization do |controller|
# Rails.logger.info(controller.request.params.inspect)
# end
#
# after_successful_authorization do |controller|
# controller.session[:logout_urls] <<
# Doorkeeper::Application
# .find_by(controller.request.params.slice(:redirect_uri))
# .logout_uri
# end
# Under some circumstances you might want to have applications auto-approved,
# so that the user skips the authorization step.
# For example if dealing with a trusted application.
#
# skip_authorization do |resource_owner, client|
# client.superapp? or resource_owner.admin?
# end
# Configure custom constraints for the Token Introspection request.
# By default this configuration option allows to introspect a token by another
# token of the same application, OR to introspect the token that belongs to
# authorized client (from authenticated client) OR when token doesn't
# belong to any client (public token). Otherwise requester has no access to the
# introspection and it will return response as stated in the RFC.
#
# Block arguments:
#
# @param token [Doorkeeper::AccessToken]
# token to be introspected
#
# @param authorized_client [Doorkeeper::Application]
# authorized client (if request is authorized using Basic auth with
# Client Credentials for example)
#
# @param authorized_token [Doorkeeper::AccessToken]
# Bearer token used to authorize the request
#
# In case the block returns `nil` or `false` introspection responses with 401 status code
# when using authorized token to introspect, or you'll get 200 with { "active": false } body
# when using authorized client to introspect as stated in the
# RFC 7662 section 2.2. Introspection Response.
#
# Using with caution:
# Keep in mind that these three parameters pass to block can be nil as following case:
# `authorized_client` is nil if and only if `authorized_token` is present, and vice versa.
# `token` will be nil if and only if `authorized_token` is present.
# So remember to use `&` or check if it is present before calling method on
# them to make sure you doesn't get NoMethodError exception.
#
# You can define your custom check:
#
# allow_token_introspection do |token, authorized_client, authorized_token|
# if authorized_token
# # customize: require `introspection` scope
# authorized_token.application == token&.application ||
# authorized_token.scopes.include?("introspection")
# elsif token.application
# # `protected_resource` is a new database boolean column, for example
# authorized_client == token.application || authorized_client.protected_resource?
# else
# # public token (when token.application is nil, token doesn't belong to any application)
# true
# end
# end
#
# Or you can completely disable any token introspection:
#
# allow_token_introspection false
#
# If you need to block the request at all, then configure your routes.rb or web-server
# like nginx to forbid the request.
# WWW-Authenticate Realm (default "Doorkeeper").
#
# realm "Doorkeeper"
end
|
# frozen_string_literal: true
# Copyright 2016 New Context Services, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'terraform/apply_command'
require 'terraform/destructive_plan_command'
require 'terraform/get_command'
require 'terraform/output_command'
require 'terraform/plan_command'
require 'terraform/show_command'
require 'terraform/validate_command'
require 'terraform/version_command'
module Terraform
# A factory to create commands
class CommandFactory
def apply_command
::Terraform::ApplyCommand.new target: config[:plan] do |options|
options.color = config[:color]
options.input = false
options.parallelism = config[:parallelism]
options.state = config[:state]
end
end
def destructive_plan_command
::Terraform::DestructivePlanCommand
.new target: config[:directory] do |options|
configure_plan options: options
options.destroy = true
options.state = config[:state]
end
end
def get_command
::Terraform::GetCommand.new target: config[:directory] do |options|
options.update = true
end
end
def output_command(target:, version:)
version
.if_json_not_supported { return base_output_command target: target }
json_output_command target: target
end
def plan_command
::Terraform::PlanCommand.new target: config[:directory] do |options|
configure_plan options: options
end
end
def show_command
::Terraform::ShowCommand.new target: config[:state] do |options|
options.color = config[:color]
end
end
def validate_command
::Terraform::ValidateCommand.new target: config[:directory]
end
def version_command
::Terraform::VersionCommand.new
end
private
attr_accessor :config
def base_output_command(target:, &block)
block ||= proc {}
::Terraform::OutputCommand.new target: target do |options|
options.color = config[:color]
options.state = config[:state]
block.call options
end
end
def configure_plan(options:)
options.color = config[:color]
options.input = false
options.out = config[:plan]
options.parallelism = config[:parallelism]
options.state = config[:state]
options.var = config[:variables]
options.var_file = config[:variable_files]
end
def initialize(config:)
self.config = config
end
def json_output_command(target:)
base_output_command(target: target) { |options| options.json = true }
end
end
end
Remove redundant state option for destroys.
# frozen_string_literal: true
# Copyright 2016 New Context Services, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'terraform/apply_command'
require 'terraform/destructive_plan_command'
require 'terraform/get_command'
require 'terraform/output_command'
require 'terraform/plan_command'
require 'terraform/show_command'
require 'terraform/validate_command'
require 'terraform/version_command'
module Terraform
# A factory to create commands
class CommandFactory
def apply_command
::Terraform::ApplyCommand.new target: config[:plan] do |options|
options.color = config[:color]
options.input = false
options.parallelism = config[:parallelism]
options.state = config[:state]
end
end
def destructive_plan_command
::Terraform::DestructivePlanCommand
.new target: config[:directory] do |options|
configure_plan options: options
options.destroy = true
end
end
def get_command
::Terraform::GetCommand.new target: config[:directory] do |options|
options.update = true
end
end
def output_command(target:, version:)
version
.if_json_not_supported { return base_output_command target: target }
json_output_command target: target
end
def plan_command
::Terraform::PlanCommand.new target: config[:directory] do |options|
configure_plan options: options
end
end
def show_command
::Terraform::ShowCommand.new target: config[:state] do |options|
options.color = config[:color]
end
end
def validate_command
::Terraform::ValidateCommand.new target: config[:directory]
end
def version_command
::Terraform::VersionCommand.new
end
private
attr_accessor :config
def base_output_command(target:, &block)
block ||= proc {}
::Terraform::OutputCommand.new target: target do |options|
options.color = config[:color]
options.state = config[:state]
block.call options
end
end
def configure_plan(options:)
options.color = config[:color]
options.input = false
options.out = config[:plan]
options.parallelism = config[:parallelism]
options.state = config[:state]
options.var = config[:variables]
options.var_file = config[:variable_files]
end
def initialize(config:)
self.config = config
end
def json_output_command(target:)
base_output_command(target: target) { |options| options.json = true }
end
end
end
|
20.times do |n|
email = Faker::Internet.unique.safe_email
password = "password"
password_confirmation = "password"
user = User.create!(email: email,
password: password,
password_confirmation: password)
restaurant_name = Faker::Company.name
content = Faker::Lorem.paragraph(3, true, 3)
cuisine_name = ["Chinese", "Mexican", "Steak", "Pizza", "American", "Italian"].sample
review_cuisine = Cuisine.find_or_create_by :name => cuisine_name
date_visited = Faker::Date.backward(125)
rating = ["Excellent", "Good", "Average", "Poor"].sample
Review.create!(user: user,
:cuisines => [review_cuisine],
restaurant_name: restaurant_name,
content: content,
date_visited: date_visited,
rating: rating)
end
10.times do |n|
email = Faker::Internet.unique.safe_email
password = "password"
password_confirmation = "password"
user = User.create!(email: email,
password: password,
password_confirmation: password)
restaurant_name = ["McDonalds", "Burger King", "Wendy's", "Jack In The Box", "Subway", "Arby's"].sample
content = Faker::Lorem.paragraph(3, true, 3)
cuisine_name = ["Burgers", "Sandwiches", "Fast Food"].sample
review_cuisine = Cuisine.find_or_create_by :name => cuisine_name
date_visited = Faker::Date.backward(90)
rating = ["Excellent", "Good", "Average", "Poor"].sample
3.times do |n|
Review.create!(user: user,
:cuisines => [review_cuisine],
restaurant_name: restaurant_name,
content: content,
date_visited: date_visited,
rating: rating)
end
end
Added new Faker date to re-seed db
20.times do |n|
email = Faker::Internet.unique.safe_email
password = "password"
password_confirmation = "password"
user = User.create!(email: email,
password: password,
password_confirmation: password)
restaurant_name = Faker::Company.name
content = Faker::Lorem.paragraph(3, true, 3)
cuisine_name = ["Chinese", "Mexican", "Steak", "Pizza", "American", "Italian"].sample
review_cuisine = Cuisine.find_or_create_by :name => cuisine_name
date_visited = Faker::Date.backward(125)
rating = ["Excellent", "Good", "Average", "Poor"].sample
Review.create!(user: user,
:cuisines => [review_cuisine],
restaurant_name: restaurant_name,
content: content,
date_visited: date_visited,
rating: rating)
end
10.times do |n|
email = Faker::Internet.unique.safe_email
password = "password"
password_confirmation = "password"
user = User.create!(email: email,
password: password,
password_confirmation: password)
3.times do |n|
restaurant_name = ["McDonalds", "Burger King", "Wendy's", "Jack In The Box", "Subway", "Arby's"].sample
content = Faker::Lorem.paragraph(3, true, 3)
cuisine_name = ["Burgers", "Sandwiches", "Fast Food"].sample
review_cuisine = Cuisine.find_or_create_by :name => cuisine_name
date_visited = Faker::Date.backward(90)
rating = ["Excellent", "Good", "Average", "Poor"].sample
Review.create!(user: user,
:cuisines => [review_cuisine],
restaurant_name: restaurant_name,
content: content,
date_visited: date_visited,
rating: rating)
end
end
|
require sprintf('%s/../../%s', File.dirname(File.expand_path(__FILE__)), 'path_helper')
require 'rouster/deltas'
class Rouster
def dir(dir, use_cache=false)
self.deltas[:files] = Hash.new if self.deltas[:files].nil?
if use_cache and ! self.deltas[:files][dir].nil?
self.deltas[:files][dir]
end
begin
raw = self.run(sprintf('ls -ld %s', dir))
rescue Rouster::RemoteExecutionError
raw = self.get_output()
end
if raw.match(/No such file or directory/)
res = nil
elsif raw.match(/Permission denied/)
@log.info(sprintf('is_dir?(%s) output[%s], try with sudo', dir, raw)) unless self.uses_sudo?
res = nil
else
res = parse_ls_string(raw)
end
if use_cache
self.deltas[:files][dir] = res
end
res
end
def file(file, use_cache=false)
self.deltas[:files] = Hash.new if self.deltas[:files].nil?
if use_cache and ! self.deltas[:files][file].nil?
self.deltas[:files][file]
end
begin
raw = self.run(sprintf('ls -l %s', file))
rescue Rouster::RemoteExecutionError
raw = self.get_output()
end
if raw.match(/No such file or directory/)
@log.info(sprintf('is_file?(%s) output[%s], try with sudo', file, res)) unless self.uses_sudo?
res = nil
elsif raw.match(/Permission denied/)
res = nil
else
res = parse_ls_string(raw)
end
if use_cache
self.deltas[:files][file] = res
end
res
end
def is_dir?(dir)
res = self.dir(dir)
res.class.eql?(Hash) ? res[:directory?] : false
end
def is_executable?(filename, level='u')
res = file(filename)
if res
array = res[:executable?]
case level
when 'u', 'U', 'user'
array[0]
when 'g', 'G', 'group'
array[1]
when 'o', 'O', 'other'
array[2]
else
raise InternalError.new(sprintf('unknown level[%s]'))
end
else
false
end
end
def is_file?(file)
res = self.file(file)
res.class.eql?(Hash) ? res[:file?] : false
end
def is_group?(group)
groups = self.get_groups()
groups.has_key?(group)
end
def is_in_file?(file, regex, scp=false)
res = nil
if scp
# download the file to a temporary directory
# not implementing as part of MVP
end
begin
command = sprintf("grep -c '%s' %s", regex, file)
res = self.run(command)
rescue Rouster::RemoteExecutionError
false
end
if res.nil?.false? and res.grep(/^0/)
false
else
true
end
end
def is_in_path?(filename)
begin
self.run(sprintf('which %s', filename))
rescue Rouster::RemoteExecutionError
false
end
true
end
def is_package?(package, use_cache=true)
packages = self.get_packages(use_cache)
packages.has_key?(package)
end
def is_readable?(filename, level='u')
res = file(filename)
if res
array = res[:readable?]
case level
when 'u', 'U', 'user'
array[0]
when 'g', 'G', 'group'
array[1]
when 'o', 'O', 'other'
array[2]
else
raise InternalError.new(sprintf('unknown level[%s]'))
end
else
false
end
end
def is_service?(service, use_cache=true)
services = self.get_services(use_cache)
services.has_key?(service)
end
def is_service_running?(service, use_cache=true)
services = self.get_services(use_cache)
if services.has_key?(service)
services[service].eql?('running').true?
else
false
end
end
def is_user?(user, use_cache=true)
users = self.get_users(use_cache)
users.has_key?(user)
end
def is_user_in_group?(user, group, use_cache=true)
users = self.get_users(use_cache)
groups = self.get_groups(use_cache)
users.has_key?(user) and groups.has_key?(group) and groups[group][:users].member?(user)
end
def is_writeable?(filename, level='u')
res = file(filename)
if res
array = res[:writeable?]
case level
when 'u', 'U', 'user'
array[0]
when 'g', 'G', 'group'
array[1]
when 'o', 'O', 'other'
array[2]
else
raise InternalError.new(sprintf('unknown level[%s]'))
end
else
false
end
end
# non-test, helper methods
def parse_ls_string(string)
# ht avaghti
res = Hash.new()
tokens = string.split(/\s+/)
# eww - do better here
modes = [ tokens[0][1..3], tokens[0][4..6], tokens[0][7..9] ]
mode = 0
# can't use modes.size here (or could, but would have to -1)
for i in 0..2 do
value = 0
element = modes[i]
for j in 0..2 do
chr = element[j].chr
case chr
when 'r'
value += 4
when 'w'
value += 2
when 'x', 't'
# is 't' really right here? copying Salesforce::Vagrant
value += 1
when '-'
# noop
else
raise InternalError.new(sprintf('unexpected character[%s]', chr))
end
end
mode = sprintf('%s%s', mode, value)
end
res[:mode] = mode
res[:owner] = tokens[2]
res[:group] = tokens[3]
res[:size] = tokens[4]
res[:directory?] = tokens[0][0].chr.eql?('d')
res[:file?] = ! res[:directory?]
res[:executable?] = [ tokens[0][3].chr.eql?('x'), tokens[0][6].chr.eql?('x'), tokens[0][9].chr.eql?('x') || tokens[0][9].chr.eql?('t') ]
res[:writeable?] = [ tokens[0][2].chr.eql?('w'), tokens[0][5].chr.eql?('w'), tokens[0][8].chr.eql?('w') ]
res[:readable?] = [ tokens[0][1].chr.eql?('r'), tokens[0][4].chr.eql?('r'), tokens[0][7].chr.eql?('r') ]
res
end
end
adding is_process_running?(name)
require sprintf('%s/../../%s', File.dirname(File.expand_path(__FILE__)), 'path_helper')
require 'rouster/deltas'
class Rouster
def dir(dir, use_cache=false)
self.deltas[:files] = Hash.new if self.deltas[:files].nil?
if use_cache and ! self.deltas[:files][dir].nil?
self.deltas[:files][dir]
end
begin
raw = self.run(sprintf('ls -ld %s', dir))
rescue Rouster::RemoteExecutionError
raw = self.get_output()
end
if raw.match(/No such file or directory/)
res = nil
elsif raw.match(/Permission denied/)
@log.info(sprintf('is_dir?(%s) output[%s], try with sudo', dir, raw)) unless self.uses_sudo?
res = nil
else
res = parse_ls_string(raw)
end
if use_cache
self.deltas[:files][dir] = res
end
res
end
def file(file, use_cache=false)
self.deltas[:files] = Hash.new if self.deltas[:files].nil?
if use_cache and ! self.deltas[:files][file].nil?
self.deltas[:files][file]
end
begin
raw = self.run(sprintf('ls -l %s', file))
rescue Rouster::RemoteExecutionError
raw = self.get_output()
end
if raw.match(/No such file or directory/)
@log.info(sprintf('is_file?(%s) output[%s], try with sudo', file, res)) unless self.uses_sudo?
res = nil
elsif raw.match(/Permission denied/)
res = nil
else
res = parse_ls_string(raw)
end
if use_cache
self.deltas[:files][file] = res
end
res
end
def is_dir?(dir)
res = self.dir(dir)
res.class.eql?(Hash) ? res[:directory?] : false
end
def is_executable?(filename, level='u')
res = file(filename)
if res
array = res[:executable?]
case level
when 'u', 'U', 'user'
array[0]
when 'g', 'G', 'group'
array[1]
when 'o', 'O', 'other'
array[2]
else
raise InternalError.new(sprintf('unknown level[%s]'))
end
else
false
end
end
def is_file?(file)
res = self.file(file)
res.class.eql?(Hash) ? res[:file?] : false
end
def is_group?(group)
groups = self.get_groups()
groups.has_key?(group)
end
def is_in_file?(file, regex, scp=false)
res = nil
if scp
# download the file to a temporary directory
# not implementing as part of MVP
end
begin
command = sprintf("grep -c '%s' %s", regex, file)
res = self.run(command)
rescue Rouster::RemoteExecutionError
false
end
if res.nil?.false? and res.grep(/^0/)
false
else
true
end
end
def is_in_path?(filename)
begin
self.run(sprintf('which %s', filename))
rescue Rouster::RemoteExecutionError
false
end
true
end
def is_package?(package, use_cache=true)
packages = self.get_packages(use_cache)
packages.has_key?(package)
end
def is_process_running?(name)
# TODO support other flavors - this will work on RHEL and OSX
res = self.run(sprintf('ps ax | grep -c %s', name))
res.chomp!.to_i
res > 1
end
def is_readable?(filename, level='u')
res = file(filename)
if res
array = res[:readable?]
case level
when 'u', 'U', 'user'
array[0]
when 'g', 'G', 'group'
array[1]
when 'o', 'O', 'other'
array[2]
else
raise InternalError.new(sprintf('unknown level[%s]'))
end
else
false
end
end
def is_service?(service, use_cache=true)
services = self.get_services(use_cache)
services.has_key?(service)
end
def is_service_running?(service, use_cache=true)
services = self.get_services(use_cache)
if services.has_key?(service)
services[service].eql?('running').true?
else
false
end
end
def is_user?(user, use_cache=true)
users = self.get_users(use_cache)
users.has_key?(user)
end
def is_user_in_group?(user, group, use_cache=true)
users = self.get_users(use_cache)
groups = self.get_groups(use_cache)
users.has_key?(user) and groups.has_key?(group) and groups[group][:users].member?(user)
end
def is_writeable?(filename, level='u')
res = file(filename)
if res
array = res[:writeable?]
case level
when 'u', 'U', 'user'
array[0]
when 'g', 'G', 'group'
array[1]
when 'o', 'O', 'other'
array[2]
else
raise InternalError.new(sprintf('unknown level[%s]'))
end
else
false
end
end
# non-test, helper methods
def parse_ls_string(string)
# ht avaghti
res = Hash.new()
tokens = string.split(/\s+/)
# eww - do better here
modes = [ tokens[0][1..3], tokens[0][4..6], tokens[0][7..9] ]
mode = 0
# can't use modes.size here (or could, but would have to -1)
for i in 0..2 do
value = 0
element = modes[i]
for j in 0..2 do
chr = element[j].chr
case chr
when 'r'
value += 4
when 'w'
value += 2
when 'x', 't'
# is 't' really right here? copying Salesforce::Vagrant
value += 1
when '-'
# noop
else
raise InternalError.new(sprintf('unexpected character[%s]', chr))
end
end
mode = sprintf('%s%s', mode, value)
end
res[:mode] = mode
res[:owner] = tokens[2]
res[:group] = tokens[3]
res[:size] = tokens[4]
res[:directory?] = tokens[0][0].chr.eql?('d')
res[:file?] = ! res[:directory?]
res[:executable?] = [ tokens[0][3].chr.eql?('x'), tokens[0][6].chr.eql?('x'), tokens[0][9].chr.eql?('x') || tokens[0][9].chr.eql?('t') ]
res[:writeable?] = [ tokens[0][2].chr.eql?('w'), tokens[0][5].chr.eql?('w'), tokens[0][8].chr.eql?('w') ]
res[:readable?] = [ tokens[0][1].chr.eql?('r'), tokens[0][4].chr.eql?('r'), tokens[0][7].chr.eql?('r') ]
res
end
end
|
require "capital_git/version"
require 'logger'
module CapitalGit
def self.logger
@logger ||= Logger.new(STDOUT)
@logger
end
def self.logger=(logger)
@logger = logger
end
def self.env_name
return Rails.env if defined?(Rails) && Rails.respond_to?(:env)
return Sinatra::Base.environment.to_s if defined?(Sinatra)
ENV["RACK_ENV"] || ENV["CAPITAL_GIT_ENV"] || raise("No environment defined")
end
def self.base_keypath
return Rails.root if defined?(Rails) && Rails.respond_to?(:root)
return Sinatra::Base.root.to_s if defined?(Sinatra)
ENV["CAPITAL_GIT_KEYPATH"] || File.dirname(__FILE__)
end
@@repositories = {}
@@databases = {}
# handle repositories and servers
# defined in a config file
def self.load! path_to_config, environment = nil
environment = self.env_name if environment.nil?
puts environment
puts File.read(path_to_config)
@@config = YAML::load(File.read(path_to_config))[environment]
self.load_config! @@config
end
def self.load_config! config
self.cleanup!
@@repositories = {}
@@databases = {}
config.each do |config_section|
database = CapitalGit::Database.new
if config_section['local_path']
database.local_path = config_section['local_path']
end
if config_section['credentials']
database.credentials = config_section['credentials']
end
if config_section['committer']
database.committer = config_section['committer']
end
if config_section.has_key? "name"
@@repositories[config_section['name']] = database.connect(config_section['url'])
elsif config_section.has_key? "server"
if config_section['server']
database.server = config_section['server']
end
@@databases[config_section['server']] = database
end
end
end
def self.repository name
@@repositories[name]
end
# TODO: weird that database options here don't apply to
# already initialized databases
def self.connect url, options={}, database_options={}
@@repositories.each do |name, repo|
if url == repo.url
return repo
end
end
@@databases.each do |servername, database|
if url[0,servername.length] == servername
return database.connect(url, options)
end
end
self.logger.warn("Attempting to connect to a repository that's not defined in configuration.")
database = CapitalGit::Database.new(database_options)
database.connect(url, options)
end
# purge local clones
def self.cleanup!
@@databases.each do |server_name, d|
d.cleanup
end
@@repositories.each do |repo_name, r|
r.database.cleanup
end
end
end
require 'capital_git/database'
require 'capital_git/local_repository'
Remove puts
require "capital_git/version"
require 'logger'
module CapitalGit
def self.logger
@logger ||= Logger.new(STDOUT)
@logger
end
def self.logger=(logger)
@logger = logger
end
def self.env_name
return Rails.env if defined?(Rails) && Rails.respond_to?(:env)
return Sinatra::Base.environment.to_s if defined?(Sinatra)
ENV["RACK_ENV"] || ENV["CAPITAL_GIT_ENV"] || raise("No environment defined")
end
def self.base_keypath
return Rails.root if defined?(Rails) && Rails.respond_to?(:root)
return Sinatra::Base.root.to_s if defined?(Sinatra)
ENV["CAPITAL_GIT_KEYPATH"] || File.dirname(__FILE__)
end
@@repositories = {}
@@databases = {}
# handle repositories and servers
# defined in a config file
def self.load! path_to_config, environment = nil
environment = self.env_name if environment.nil?
@@config = YAML::load(File.read(path_to_config))[environment]
self.load_config! @@config
end
def self.load_config! config
self.cleanup!
@@repositories = {}
@@databases = {}
config.each do |config_section|
database = CapitalGit::Database.new
if config_section['local_path']
database.local_path = config_section['local_path']
end
if config_section['credentials']
database.credentials = config_section['credentials']
end
if config_section['committer']
database.committer = config_section['committer']
end
if config_section.has_key? "name"
@@repositories[config_section['name']] = database.connect(config_section['url'])
elsif config_section.has_key? "server"
if config_section['server']
database.server = config_section['server']
end
@@databases[config_section['server']] = database
end
end
end
def self.repository name
@@repositories[name]
end
# TODO: weird that database options here don't apply to
# already initialized databases
def self.connect url, options={}, database_options={}
@@repositories.each do |name, repo|
if url == repo.url
return repo
end
end
@@databases.each do |servername, database|
if url[0,servername.length] == servername
return database.connect(url, options)
end
end
self.logger.warn("Attempting to connect to a repository that's not defined in configuration.")
database = CapitalGit::Database.new(database_options)
database.connect(url, options)
end
# purge local clones
def self.cleanup!
@@databases.each do |server_name, d|
d.cleanup
end
@@repositories.each do |repo_name, r|
r.database.cleanup
end
end
end
require 'capital_git/database'
require 'capital_git/local_repository'
|
require_relative 'miq_ae_service/miq_ae_service_model_legacy'
require_relative 'miq_ae_service/miq_ae_service_object_common'
require_relative 'miq_ae_service/miq_ae_service_vmdb'
module MiqAeMethodService
class Deprecation < Vmdb::Deprecation
def self.default_log
$miq_ae_logger
end
end
class MiqAeServiceFront
include DRbUndumped
def find(id)
MiqAeService.find(id)
end
end
class MiqAeService
include Vmdb::Logging
include DRbUndumped
include MiqAeMethodService::MiqAeServiceModelLegacy
include MiqAeMethodService::MiqAeServiceVmdb
@@id_hash = {}
@@current = []
def self.current
@@current.last
end
def self.find(id)
@@id_hash[id.to_i]
end
def self.add(obj)
@@id_hash[obj.object_id] = obj
@@current << obj
end
def self.destroy(obj)
@@id_hash.delete(obj.object_id)
@@current.delete(obj)
end
def initialize(ws)
@drb_server_references = []
@inputs = {}
@workspace = ws
@preamble_lines = 0
@body = []
@persist_state_hash = ws.persist_state_hash
self.class.add(self)
end
def destroy
self.class.destroy(self)
end
def body=(data)
@body_raw = data
@body = begin
lines = []
@body_raw.each_line { |l| lines << l.rstrip }
lines
end
end
def body
@body_raw
end
def preamble
@preamble_raw
end
def preamble=(data)
@preamble_raw = data
@preamble = begin
lines = []
@preamble_raw.each_line { |l| lines << l.rstrip }
lines
end
@preamble_lines = @preamble.length
end
def method_body(options = {})
if options[:line_numbers]
line_number = 0
@body.collect do |line|
line_number += 1
"#{format "%03d" % line_number}: #{line}"
end
else
@body
end
end
def backtrace(callers)
return callers unless callers.respond_to?(:collect)
callers.collect do |c|
file, line, context = c.split(':')
if file == "-"
line_adjusted_for_preamble = line.to_i - @preamble_lines
file = @body[line_adjusted_for_preamble - 1].to_s.strip
"<code: #{file}>:#{line_adjusted_for_preamble}:#{context}"
else
c
end
end
end
def disconnect_sql
ActiveRecord::Base.connection_pool.release_connection
end
attr_writer :inputs
attr_reader :inputs
####################################################
def log(level, msg)
$miq_ae_logger.send(level, "<AEMethod #{current_method}> #{msg}")
end
def set_state_var(name, value)
@persist_state_hash[name] = value
end
def state_var_exist?(name)
@persist_state_hash.key?(name)
end
def get_state_var(name)
@persist_state_hash[name]
end
def prepend_namespace=(ns)
@workspace.prepend_namespace=(ns)
end
def instantiate(uri)
obj = @workspace.instantiate(uri, @workspace.ae_user, @workspace.current_object)
return nil if obj.nil?
MiqAeServiceObject.new(obj, self)
rescue => e
return nil
end
def object(path = nil)
obj = @workspace.get_obj_from_path(path)
return nil if obj.nil?
MiqAeServiceObject.new(obj, self)
end
def hash_to_query(hash)
MiqAeEngine::MiqAeUri.hash2query(hash)
end
def query_to_hash(query)
MiqAeEngine::MiqAeUri.query2hash(query)
end
def current_namespace
@workspace.current_namespace
end
def current_class
@workspace.current_class
end
def current_instance
@workspace.current_instance
end
def current_message
@workspace.current_message
end
def current_object
@current_object ||= MiqAeServiceObject.new(@workspace.current_object, self)
end
def current_method
@workspace.current_method
end
def current
current_object
end
def root
@root_object ||= object("/")
end
def parent
@parent_object ||= object("..")
end
def objects(aobj)
aobj.collect do |obj|
obj = MiqAeServiceObject.new(obj, self) unless obj.kind_of?(MiqAeServiceObject)
obj
end
end
def datastore
end
def ldap
end
def execute(m, *args)
MiqAeServiceMethods.send(m, *args)
rescue NoMethodError => err
raise MiqAeException::MethodNotFound, err.message
end
def instance_exists?(path)
_log.info "<< path=#{path.inspect}"
__find_instance_from_path(path) ? true : false
end
def instance_create(path, values_hash = {})
_log.info "<< path=#{path.inspect}, values_hash=#{values_hash.inspect}"
return false unless editable_instance?(path)
ns, klass, instance = MiqAeEngine::MiqAePath.split(path)
$log.info("Instance Create for ns: #{ns} class #{klass} instance: #{instance}")
aec = MiqAeClass.find_by_namespace_and_name(ns, klass)
return false if aec.nil?
aei = aec.ae_instances.detect { |i| instance.casecmp(i.name) == 0 }
return false unless aei.nil?
aei = MiqAeInstance.create(:name => instance, :class_id => aec.id)
values_hash.each { |key, value| aei.set_field_value(key, value) }
true
end
def instance_get_display_name(path)
_log.info "<< path=#{path.inspect}"
aei = __find_instance_from_path(path)
aei ? aei.display_name : nil
end
def instance_set_display_name(path, display_name)
_log.info "<< path=#{path.inspect}, display_name=#{display_name.inspect}"
aei = __find_instance_from_path(path)
return false if aei.nil?
aei.update_attributes(:display_name => display_name)
true
end
def instance_update(path, values_hash)
_log.info "<< path=#{path.inspect}, values_hash=#{values_hash.inspect}"
return false unless editable_instance?(path)
aei = __find_instance_from_path(path)
return false if aei.nil?
values_hash.each { |key, value| aei.set_field_value(key, value) }
true
end
def instance_find(path, options = {})
_log.info "<< path=#{path.inspect}"
result = {}
ns, klass, instance = MiqAeEngine::MiqAePath.split(path)
aec = MiqAeClass.find_by_namespace_and_name(ns, klass)
unless aec.nil?
instance.gsub!(".", '\.')
instance.gsub!("*", ".*")
instance.gsub!("?", ".{1}")
instance_re = Regexp.new("^#{instance}$", Regexp::IGNORECASE)
aec.ae_instances.select { |i| instance_re =~ i.name }.each do |aei|
iname = if options[:path]
aei.fqname
else
aei.name
end
result[iname] = aei.field_attributes
end
end
result
end
def instance_get(path)
_log.info "<< path=#{path.inspect}"
aei = __find_instance_from_path(path)
return nil if aei.nil?
aei.field_attributes
end
def instance_delete(path)
_log.info "<< path=#{path.inspect}"
return false unless editable_instance?(path)
aei = __find_instance_from_path(path)
return false if aei.nil?
aei.destroy
true
end
def __find_instance_from_path(path)
dom, ns, klass, instance = MiqAeEngine::MiqAePath.get_domain_ns_klass_inst(path)
return false unless visible_domain?(dom)
aec = MiqAeClass.find_by_namespace_and_name("#{dom}/#{ns}", klass)
return nil if aec.nil?
aec.ae_instances.detect { |i| instance.casecmp(i.name) == 0 }
end
private
def editable_instance?(path)
dom, = MiqAeEngine::MiqAePath.get_domain_ns_klass_inst(path)
return false unless owned_domain?(dom)
domain = MiqAeDomain.find_by_fqname(dom, false)
return false unless domain
$log.warn "path=#{path.inspect} : is not editable" unless domain.editable?
domain.editable?
end
def owned_domain?(dom)
domains = @workspace.ae_user.current_tenant.ae_domains.collect(&:name).map(&:upcase)
return true if domains.include?(dom.upcase)
$log.warn "domain=#{dom} : is not editable"
false
end
def visible_domain?(dom)
domains = @workspace.ae_user.current_tenant.visible_domains.collect(&:name).map(&:upcase)
return true if domains.include?(dom.upcase)
$log.warn "domain=#{dom} : is not viewable"
false
end
end
class MiqAeServiceObject
include MiqAeMethodService::MiqAeServiceObjectCommon
include DRbUndumped
def initialize(obj, svc)
raise "object cannot be nil" if obj.nil?
@object = obj
@service = svc
end
def children(name = nil)
objs = @object.children(name)
return nil if objs.nil?
objs = @service.objects([objs].flatten)
objs.length == 1 ? objs.first : objs
end
def to_s
name
end
def inspect
hex_id = (object_id << 1).to_s(16).rjust(14, '0')
"#<#{self.class.name}:0x#{hex_id} name: #{name.inspect}>"
end
end
end
Fixed Rubocop warnings
(transferred from ManageIQ/manageiq@bc08fc7d1bd32478c0be1f222eee8a5069bac9de)
require_relative 'miq_ae_service/miq_ae_service_model_legacy'
require_relative 'miq_ae_service/miq_ae_service_object_common'
require_relative 'miq_ae_service/miq_ae_service_vmdb'
module MiqAeMethodService
class Deprecation < Vmdb::Deprecation
def self.default_log
$miq_ae_logger
end
end
class MiqAeServiceFront
include DRbUndumped
def find(id)
MiqAeService.find(id)
end
end
class MiqAeService
include Vmdb::Logging
include DRbUndumped
include MiqAeMethodService::MiqAeServiceModelLegacy
include MiqAeMethodService::MiqAeServiceVmdb
@@id_hash = {}
@@current = []
def self.current
@@current.last
end
def self.find(id)
@@id_hash[id.to_i]
end
def self.add(obj)
@@id_hash[obj.object_id] = obj
@@current << obj
end
def self.destroy(obj)
@@id_hash.delete(obj.object_id)
@@current.delete(obj)
end
def initialize(ws)
@drb_server_references = []
@inputs = {}
@workspace = ws
@preamble_lines = 0
@body = []
@persist_state_hash = ws.persist_state_hash
self.class.add(self)
end
def destroy
self.class.destroy(self)
end
def body=(data)
@body_raw = data
@body = begin
lines = []
@body_raw.each_line { |l| lines << l.rstrip }
lines
end
end
def body
@body_raw
end
def preamble
@preamble_raw
end
def preamble=(data)
@preamble_raw = data
@preamble = begin
lines = []
@preamble_raw.each_line { |l| lines << l.rstrip }
lines
end
@preamble_lines = @preamble.length
end
def method_body(options = {})
if options[:line_numbers]
line_number = 0
@body.collect do |line|
line_number += 1
"#{format "%03d" % line_number}: #{line}"
end
else
@body
end
end
def backtrace(callers)
return callers unless callers.respond_to?(:collect)
callers.collect do |c|
file, line, context = c.split(':')
if file == "-"
line_adjusted_for_preamble = line.to_i - @preamble_lines
file = @body[line_adjusted_for_preamble - 1].to_s.strip
"<code: #{file}>:#{line_adjusted_for_preamble}:#{context}"
else
c
end
end
end
def disconnect_sql
ActiveRecord::Base.connection_pool.release_connection
end
attr_writer :inputs
attr_reader :inputs
####################################################
def log(level, msg)
$miq_ae_logger.send(level, "<AEMethod #{current_method}> #{msg}")
end
def set_state_var(name, value)
@persist_state_hash[name] = value
end
def state_var_exist?(name)
@persist_state_hash.key?(name)
end
def get_state_var(name)
@persist_state_hash[name]
end
def prepend_namespace=(ns)
@workspace.prepend_namespace = ns
end
def instantiate(uri)
obj = @workspace.instantiate(uri, @workspace.ae_user, @workspace.current_object)
return nil if obj.nil?
MiqAeServiceObject.new(obj, self)
rescue => e
return nil
end
def object(path = nil)
obj = @workspace.get_obj_from_path(path)
return nil if obj.nil?
MiqAeServiceObject.new(obj, self)
end
def hash_to_query(hash)
MiqAeEngine::MiqAeUri.hash2query(hash)
end
def query_to_hash(query)
MiqAeEngine::MiqAeUri.query2hash(query)
end
def current_namespace
@workspace.current_namespace
end
def current_class
@workspace.current_class
end
def current_instance
@workspace.current_instance
end
def current_message
@workspace.current_message
end
def current_object
@current_object ||= MiqAeServiceObject.new(@workspace.current_object, self)
end
def current_method
@workspace.current_method
end
def current
current_object
end
def root
@root_object ||= object("/")
end
def parent
@parent_object ||= object("..")
end
def objects(aobj)
aobj.collect do |obj|
obj = MiqAeServiceObject.new(obj, self) unless obj.kind_of?(MiqAeServiceObject)
obj
end
end
def datastore
end
def ldap
end
def execute(m, *args)
MiqAeServiceMethods.send(m, *args)
rescue NoMethodError => err
raise MiqAeException::MethodNotFound, err.message
end
def instance_exists?(path)
_log.info "<< path=#{path.inspect}"
__find_instance_from_path(path) ? true : false
end
def instance_create(path, values_hash = {})
_log.info "<< path=#{path.inspect}, values_hash=#{values_hash.inspect}"
return false unless editable_instance?(path)
ns, klass, instance = MiqAeEngine::MiqAePath.split(path)
$log.info("Instance Create for ns: #{ns} class #{klass} instance: #{instance}")
aec = MiqAeClass.find_by_namespace_and_name(ns, klass)
return false if aec.nil?
aei = aec.ae_instances.detect { |i| instance.casecmp(i.name) == 0 }
return false unless aei.nil?
aei = MiqAeInstance.create(:name => instance, :class_id => aec.id)
values_hash.each { |key, value| aei.set_field_value(key, value) }
true
end
def instance_get_display_name(path)
_log.info "<< path=#{path.inspect}"
aei = __find_instance_from_path(path)
aei ? aei.display_name : nil
end
def instance_set_display_name(path, display_name)
_log.info "<< path=#{path.inspect}, display_name=#{display_name.inspect}"
aei = __find_instance_from_path(path)
return false if aei.nil?
aei.update_attributes(:display_name => display_name)
true
end
def instance_update(path, values_hash)
_log.info "<< path=#{path.inspect}, values_hash=#{values_hash.inspect}"
return false unless editable_instance?(path)
aei = __find_instance_from_path(path)
return false if aei.nil?
values_hash.each { |key, value| aei.set_field_value(key, value) }
true
end
def instance_find(path, options = {})
_log.info "<< path=#{path.inspect}"
result = {}
ns, klass, instance = MiqAeEngine::MiqAePath.split(path)
aec = MiqAeClass.find_by_namespace_and_name(ns, klass)
unless aec.nil?
instance.gsub!(".", '\.')
instance.gsub!("*", ".*")
instance.gsub!("?", ".{1}")
instance_re = Regexp.new("^#{instance}$", Regexp::IGNORECASE)
aec.ae_instances.select { |i| instance_re =~ i.name }.each do |aei|
iname = if options[:path]
aei.fqname
else
aei.name
end
result[iname] = aei.field_attributes
end
end
result
end
def instance_get(path)
_log.info "<< path=#{path.inspect}"
aei = __find_instance_from_path(path)
return nil if aei.nil?
aei.field_attributes
end
def instance_delete(path)
_log.info "<< path=#{path.inspect}"
return false unless editable_instance?(path)
aei = __find_instance_from_path(path)
return false if aei.nil?
aei.destroy
true
end
def __find_instance_from_path(path)
dom, ns, klass, instance = MiqAeEngine::MiqAePath.get_domain_ns_klass_inst(path)
return false unless visible_domain?(dom)
aec = MiqAeClass.find_by_namespace_and_name("#{dom}/#{ns}", klass)
return nil if aec.nil?
aec.ae_instances.detect { |i| instance.casecmp(i.name) == 0 }
end
private
def editable_instance?(path)
dom, = MiqAeEngine::MiqAePath.get_domain_ns_klass_inst(path)
return false unless owned_domain?(dom)
domain = MiqAeDomain.find_by_fqname(dom, false)
return false unless domain
$log.warn "path=#{path.inspect} : is not editable" unless domain.editable?
domain.editable?
end
def owned_domain?(dom)
domains = @workspace.ae_user.current_tenant.ae_domains.collect(&:name).map(&:upcase)
return true if domains.include?(dom.upcase)
$log.warn "domain=#{dom} : is not editable"
false
end
def visible_domain?(dom)
domains = @workspace.ae_user.current_tenant.visible_domains.collect(&:name).map(&:upcase)
return true if domains.include?(dom.upcase)
$log.warn "domain=#{dom} : is not viewable"
false
end
end
class MiqAeServiceObject
include MiqAeMethodService::MiqAeServiceObjectCommon
include DRbUndumped
def initialize(obj, svc)
raise "object cannot be nil" if obj.nil?
@object = obj
@service = svc
end
def children(name = nil)
objs = @object.children(name)
return nil if objs.nil?
objs = @service.objects([objs].flatten)
objs.length == 1 ? objs.first : objs
end
def to_s
name
end
def inspect
hex_id = (object_id << 1).to_s(16).rjust(14, '0')
"#<#{self.class.name}:0x#{hex_id} name: #{name.inspect}>"
end
end
end
|
class RouterBridge
attr_accessor :router, :logger
def initialize options = {}
logger = options[:logger] || NullLogger.instance
self.router = options[:router] || Router::Client.new :logger => logger
self.logger = logger
end
def run
transport = Messenger.transport
marples = Marples::Client.new transport: transport, logger: logger
marples.when 'publisher', '*', 'broadcast' do |publication|
register_publication publication
end
marples.join
end
def register_publication publication
register_route(
:application_id => 'publisher',
:incoming_path => "/#{publication[:slug]}",
:route_type => :full
)
register_route(
:application_id => 'publisher',
:incoming_path => "/#{publication[:slug]}.json",
:route_type => :full
)
register_route(
:application_id => 'publisher',
:incoming_path => "/#{publication[:slug]}.xml",
:route_type => :full
)
end
def register_route route
logger.debug "Registering route #{route.inspect}"
router.routes.update(route)
logger.info "Registered #{route.inspect}"
end
end
Skipped brackets
class RouterBridge
attr_accessor :router, :logger
def initialize options = {}
logger = options[:logger] || NullLogger.instance
self.router = options[:router] || Router::Client.new(:logger => logger)
self.logger = logger
end
def run
transport = Messenger.transport
marples = Marples::Client.new transport: transport, logger: logger
marples.when 'publisher', '*', 'broadcast' do |publication|
register_publication publication
end
marples.join
end
def register_publication publication
register_route(
:application_id => 'publisher',
:incoming_path => "/#{publication[:slug]}",
:route_type => :full
)
register_route(
:application_id => 'publisher',
:incoming_path => "/#{publication[:slug]}.json",
:route_type => :full
)
register_route(
:application_id => 'publisher',
:incoming_path => "/#{publication[:slug]}.xml",
:route_type => :full
)
end
def register_route route
logger.debug "Registering route #{route.inspect}"
router.routes.update(route)
logger.info "Registered #{route.inspect}"
end
end
|
# coding: utf-8
module Cha
VERSION = '0.0.1'
end
Version up to 1.0.0
# coding: utf-8
module Cha
VERSION = '1.0.0'
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
Professor.create(name: "admin", email: "admin@admin.com", password: "password", is_approved: true, is_admin: true)
Professor.create(name: "Matt Baker", email: "matt@madzcintiztz.com", password: "password")
Student.create(name: "Duke", email: "duke@duke.com", password: "password")
10.times do
Professor.create!(email: Faker::Internet.email,
name: Faker::Name.name,
password: "password",
is_approved: true)
end
Professor.all.each do |professor|
professor.projects.create!(professor_id: professor.id,
title: Faker::Hipster.sentence,
hypothesis: Faker::Lorem.sentence,
summary: Faker::Lorem.paragraph(4),
time_budget: rand(100..700),
status: "active")
end
10.times do
Student.create!(email: Faker::Internet.email,
name: Faker::Name.name,
password: "password")
end
Student.all.each do |student|
rand(1..4).times do
student.records.create!(student_id: student.id,
project_id: rand(1..10),
hours_worked: rand(10..50),
observations: Faker::Lorem.paragraph(2, true))
end
end
longer summaries
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
Professor.create(name: "admin", email: "admin@admin.com", password: "password", is_approved: true, is_admin: true)
Professor.create(name: "Matt Baker", email: "matt@madzcintiztz.com", password: "password")
Student.create(name: "Duke", email: "duke@duke.com", password: "password")
10.times do
Professor.create!(email: Faker::Internet.email,
name: Faker::Name.name,
password: "password",
is_approved: true)
end
Professor.all.each do |professor|
professor.projects.create!(professor_id: professor.id,
title: Faker::Hipster.sentence,
hypothesis: Faker::Lorem.sentence,
summary: Faker::Lorem.paragraph(20),
time_budget: rand(100..700),
status: "active")
end
10.times do
Student.create!(email: Faker::Internet.email,
name: Faker::Name.name,
password: "password")
end
Student.all.each do |student|
rand(1..4).times do
student.records.create!(student_id: student.id,
project_id: rand(1..10),
hours_worked: rand(10..50),
observations: Faker::Lorem.paragraph(2, true))
end
end
|
# frozen_string_literal: true
module Textbringer
module Commands
define_command(:describe_bindings) do
help = Buffer.find_or_new("*Help*", undo_limit: 0)
help.read_only_edit do
s = format("%-16s%s\n", "Key", "Binding")
s << format("%-16s%s\n", "---", "-------")
s << "\n"
bindings = {}
[
GLOBAL_MAP,
Buffer.current.keymap,
Controller.current.overriding_map
].each do |map|
map&.each do |key_sequence, command|
bindings[key_sequence] = command
end
end
bindings.each do |key_sequence, command|
s << format("%-16s%s\n",
Keymap.key_sequence_string(key_sequence),
command)
end
help.insert(s)
help.beginning_of_buffer
switch_to_buffer(help)
end
end
end
end
Add space.
# frozen_string_literal: true
module Textbringer
module Commands
define_command(:describe_bindings) do
help = Buffer.find_or_new("*Help*", undo_limit: 0)
help.read_only_edit do
s = format("%-16s %s\n", "Key", "Binding")
s << format("%-16s %s\n", "---", "-------")
s << "\n"
bindings = {}
[
GLOBAL_MAP,
Buffer.current.keymap,
Controller.current.overriding_map
].each do |map|
map&.each do |key_sequence, command|
bindings[key_sequence] = command
end
end
bindings.each do |key_sequence, command|
s << format("%-16s %s\n",
Keymap.key_sequence_string(key_sequence),
command)
end
help.insert(s)
help.beginning_of_buffer
switch_to_buffer(help)
end
end
end
end
|
require 'pact/consumer/mock_service/mock_service_administration_endpoint'
module Pact
module Consumer
class VerificationGet < MockServiceAdministrationEndpoint
include RackRequestHelper
attr_accessor :interaction_list, :log_description
def initialize name, logger, interaction_list, log_description
super name, logger
@interaction_list = interaction_list
@log_description = log_description
end
def request_path
'/verify'
end
def request_method
'GET'
end
def respond env
if interaction_list.all_matched?
logger.info "Verifying - interactions matched for example \"#{example_description(env)}\""
[200, {'Content-Type' => 'text/plain'}, ['Interactions matched']]
else
error_message = FailureMessage.new(interaction_list).to_s
logger.warn "Verifying - actual interactions do not match expected interactions for example \"#{example_description(env)}\". \n#{error_message}"
logger.warn error_message
[500, {'Content-Type' => 'text/plain'}, ["Actual interactions do not match expected interactions for mock #{name}.\n\n#{error_message}See #{log_description} for details."]]
end
end
def example_description env
params_hash(env)['example_description']
end
class FailureMessage
def initialize interaction_list
@interaction_list = interaction_list
end
def to_s
missing_interactions_summaries = interaction_list.missing_interactions_summaries
interaction_mismatches_summaries = interaction_list.interaction_mismatches_summaries
unexpected_requests_summaries = interaction_list.unexpected_requests_summaries
error_message = ""
if missing_interactions_summaries.any?
error_message << "Missing requests:\n\t#{missing_interactions_summaries.join("\n ")}\n\n"
end
if interaction_mismatches_summaries.any?
error_message << "Incorrect requests:\n\t#{interaction_mismatches_summaries.join("\n ")}\n\n"
end
if unexpected_requests_summaries.any?
error_message << "Unexpected requests:\n\t#{unexpected_requests_summaries.join("\n ")}\n\n"
end
error_message
end
private
attr_reader :interaction_list
end
end
end
end
DRYed up FailureMessage
require 'pact/consumer/mock_service/mock_service_administration_endpoint'
module Pact
module Consumer
class VerificationGet < MockServiceAdministrationEndpoint
include RackRequestHelper
attr_accessor :interaction_list, :log_description
def initialize name, logger, interaction_list, log_description
super name, logger
@interaction_list = interaction_list
@log_description = log_description
end
def request_path
'/verify'
end
def request_method
'GET'
end
def respond env
if interaction_list.all_matched?
logger.info "Verifying - interactions matched for example \"#{example_description(env)}\""
[200, {'Content-Type' => 'text/plain'}, ['Interactions matched']]
else
error_message = FailureMessage.new(interaction_list).to_s
logger.warn "Verifying - actual interactions do not match expected interactions for example \"#{example_description(env)}\". \n#{error_message}"
logger.warn error_message
[500, {'Content-Type' => 'text/plain'}, ["Actual interactions do not match expected interactions for mock #{name}.\n\n#{error_message}See #{log_description} for details."]]
end
end
def example_description env
params_hash(env)['example_description']
end
class FailureMessage
def initialize interaction_list
@interaction_list = interaction_list
end
def to_s
titles_and_summaries.collect do | title, summaries |
"#{title}:\n\t#{summaries.join("\n ")}\n\n" if summaries.any?
end.compact.join
end
private
attr_reader :interaction_list
def titles_and_summaries
{
"Missing requests" => interaction_list.missing_interactions_summaries,
"Incorrect requests" => interaction_list.interaction_mismatches_summaries,
"Unexpected requests" => interaction_list.unexpected_requests_summaries,
}
end
end
end
end
end
|
#encoding: utf-8
# determine if we are using postgres or mysql
is_mysql = (ActiveRecord::Base.configurations[Rails.env]['adapter'] == 'mysql2')
is_sqlite = (ActiveRecord::Base.configurations[Rails.env]['adapter'] == 'sqlite3')
puts "======= Processing TransAM Transit Lookup Tables ======="
#------------------------------------------------------------------------------
#
# Customized Lookup Tables
#
# These are the specific to TransAM Transit
#
#------------------------------------------------------------------------------
asset_types = [
{:active => 1, :name => 'Revenue Vehicles', :description => 'Revenue rolling stock', :class_name => 'Vehicle', :map_icon_name => "redIcon", :display_icon_name => "fa fa-bus"},
{:active => 1, :name => 'Stations/Stops/Terminals', :description => 'Stations/Stops/Terminals', :class_name => 'TransitFacility', :map_icon_name => "greenIcon", :display_icon_name => "fa fa-building-o"},
{:active => 1, :name => 'Support Facilities', :description => 'Support Facilities', :class_name => 'SupportFacility', :map_icon_name => "blueIcon", :display_icon_name => "fa fa-building"},
{:active => 1, :name => 'Support Vehicles', :description => 'Support Vehicles', :class_name => 'SupportVehicle', :map_icon_name => "blueIcon", :display_icon_name => "fa fa-car"},
{:active => 1, :name => 'Maintenance Equipment', :description => 'Maintenance Equipment', :class_name => 'Equipment', :map_icon_name => "blueIcon", :display_icon_name => "fa fa-wrench"},
{:active => 1, :name => 'Facility Equipment', :description => 'Facility Equipment', :class_name => 'Equipment', :map_icon_name => "blueIcon", :display_icon_name => "fa fa-lightbulb-o"},
{:active => 1, :name => 'IT Equipment', :description => 'IT Equipment', :class_name => 'Equipment', :map_icon_name => "blueIcon", :display_icon_name => "fa fa-laptop"},
{:active => 1, :name => 'Office Equipment', :description => 'Office Equipment', :class_name => 'Equipment', :map_icon_name => "blueIcon", :display_icon_name => "fa fa-inbox"},
{:active => 1, :name => 'Communications Equipment', :description => 'Communications Equipment', :class_name => 'Equipment', :map_icon_name => "blueIcon", :display_icon_name => "fa fa-phone"},
{:active => 1, :name => 'Signals/Signs', :description => 'Signals and Signs', :class_name => 'Equipment', :map_icon_name => "blueIcon", :display_icon_name => "fa fa-h-square"}
]
asset_subtypes = [
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus Std 40 FT', :description => 'Bus Std 40 FT'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus Std 35 FT', :description => 'Bus Std 35 FT'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus 30 FT', :description => 'Bus 30 FT'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus < 30 FT', :description => 'Bus < 30 FT'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus School', :description => 'Bus School'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus Articulated', :description => 'Bus Articulated'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus Commuter/Suburban',:description => 'Bus Commuter/Suburban'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus Intercity', :description => 'Bus Intercity'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus Trolley Std', :description => 'Bus Trolley Std'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus Trolley Articulated',:description => 'Bus Trolley Articulated'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus Double Deck', :description => 'Bus Double Deck'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus Dual Mode', :description => 'Bus Dual Mode'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Van', :description => 'Van'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Sedan/Station Wagon', :description => 'Sedan/Station Wagon'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Ferry Boat', :description => 'Ferry Boat'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Stations/Stops/Terminals', :name => 'Bus Shelter', :description => 'Bus Shelter'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Stations/Stops/Terminals', :name => 'Bus Station', :description => 'Bus Station'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Stations/Stops/Terminals', :name => 'Ferry Dock', :description => 'Ferry Dock'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Stations/Stops/Terminals', :name => 'Intermodal Terminal', :description => 'Intermodal Terminal'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Stations/Stops/Terminals', :name => 'Park and Ride Lot', :description => 'Park and Ride Lot'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Stations/Stops/Terminals', :name => 'Parking Garage', :description => 'Parking Garage'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Stations/Stops/Terminals', :name => 'Parking Lot', :description => 'Parking Lot'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Stations/Stops/Terminals', :name => 'Other Transit Facility',:description => 'Other Transit Facility'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Facilities', :name => 'Administration Building', :description => 'Administration Building'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Facilities', :name => 'Bus Maintenance Facility', :description => 'Bus Maintenance Facility'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Facilities', :name => 'Bus Parking Facility', :description => 'Bus Parking Facility'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Facilities', :name => 'Bus Turnaround Facility', :description => 'Bus Turnaround Facility'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Facilities', :name => 'Storage Yard', :description => 'Storage Yard'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Facilities', :name => 'Other Support Facility', :description => 'Other Support Facility'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Vehicles', :name => 'Van', :description => 'Van'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Vehicles', :name => 'Tow Truck', :description => 'Tow Truck'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Vehicles', :name => 'Sedan/Station Wagon', :description => 'Sedan/Station Wagon'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Vehicles', :name => 'Pickup/Utility Truck', :description => 'Pickup/Utility Truck'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Vehicles', :name => 'Sports Utility Vehicle', :description => 'Sports Utility Vehicle'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Vehicles', :name => 'Other Support Vehicle', :description => 'Other Support Vehicle'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Maintenance Equipment', :name => 'Bus Maintenance Equipment', :description => 'Bus Maintenance Equipment'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Maintenance Equipment', :name => 'Other Maintenance Equipment', :description => 'Other Maintenance Equipment'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Facility Equipment', :name => 'Mechanical Equipment', :description => 'Mechanical Equipment'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Facility Equipment', :name => 'Electrical Equipment', :description => 'Electrical Equipment'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Facility Equipment', :name => 'Structural Equipment', :description => 'Structural Equipment'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Facility Equipment', :name => 'Other Facilities Equipment', :description => 'Other Facilities Equipment'},
{:active => 1, :belongs_to => 'asset_type', :type => 'IT Equipment', :name => 'Hardware', :description => 'Hardware'},
{:active => 1, :belongs_to => 'asset_type', :type => 'IT Equipment', :name => 'Software', :description => 'Hardware'},
{:active => 1, :belongs_to => 'asset_type', :type => 'IT Equipment', :name => 'Networks', :description => 'Hardware'},
{:active => 1, :belongs_to => 'asset_type', :type => 'IT Equipment', :name => 'Storage', :description => 'Storage'},
{:active => 1, :belongs_to => 'asset_type', :type => 'IT Equipment', :name => 'Other IT Equipment', :description => 'Hardware'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Office Equipment', :name => 'Furniture', :description => 'Office Furniture'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Office Equipment', :name => 'Supplies', :description => 'Office Supplies'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Office Equipment', :name => 'Other Office Equipment', :description => 'Other Office Equipment'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Communications Equipment', :name => 'Vehicle Location Systems', :description => 'Vehicle Location Systems'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Communications Equipment', :name => 'Radios', :description => 'Radios'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Communications Equipment', :name => 'Surveillance & Security', :description => 'Surveillance & Security'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Communications Equipment', :name => 'Fare Collection Systems', :description => 'Fare Collection Systems'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Communications Equipment', :name => 'Other Communications Equipment', :description => 'Other Communication Equipment'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Signals/Signs', :name => 'Route Signage', :description => 'Route Signage'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Signals/Signs', :name => 'Other Signage Equipment', :description => 'Other Signage Equipment'}
]
fuel_types = [
{:active => 1, :name => 'Biodiesel', :code => 'BD', :description => 'Biodiesel.'},
{:active => 1, :name => 'Bunker Fuel', :code => 'BF', :description => 'Bunker Fuel.'},
{:active => 1, :name => 'Compressed Natural Gas', :code => 'CNG', :description => 'Compressed Natutral Gas.'},
{:active => 1, :name => 'Diesel Fuel', :code => 'DF', :description => 'Diesel Fuel.'},
{:active => 1, :name => 'Dual Fuel', :code => 'DU', :description => 'Dual Fuel.'},
{:active => 1, :name => 'Electric Battery', :code => 'EB', :description => 'Electric Battery.'},
{:active => 1, :name => 'Electric Propulsion', :code => 'EP', :description => 'Electric Propulsion.'},
{:active => 1, :name => 'Ethanol', :code => 'ET', :description => 'Ethanol.'},
{:active => 1, :name => 'Gasoline', :code => 'GA', :description => 'Gasoline.'},
{:active => 1, :name => 'Hybrid Diesel', :code => 'HD', :description => 'Hybrid Diesel.'},
{:active => 1, :name => 'Hybrid Gasoline', :code => 'HG', :description => 'Hybrid Gasoline.'},
{:active => 1, :name => 'Hydrogen', :code => 'HY', :description => 'Hydrogen.'},
{:active => 1, :name => 'Kerosene', :code => 'KE', :description => 'Kerosene.'},
{:active => 1, :name => 'Liquefied Natural Gas', :code => 'LN', :description => 'Liquefied Natural Gas.'},
{:active => 1, :name => 'Liquefied Petroleum Gas', :code => 'LP', :description => 'Liquefied Petroleum Gas.'},
{:active => 1, :name => 'Methanol', :code => 'MT', :description => 'Methanol.'},
{:active => 1, :name => 'Other', :code => 'OR', :description => 'Other.'},
{:active => 1, :name => 'Unknown', :code => 'XX', :description => 'No Fuel type specified.'}
]
vehicle_features = [
{:active => 1, :name => 'AVL System', :code => 'AS', :description => 'Automatic Vehicle Location System.'},
{:active => 1, :name => 'Lift Equipped', :code => 'LE', :description => 'Lift Equipped.'},
{:active => 1, :name => 'Electronic Ramp', :code => 'ER', :description => 'Electronic Ramp.'},
{:active => 1, :name => 'Video Cameras', :code => 'VC', :description => 'Video Cameras.'},
{:active => 1, :name => 'Fare Box (Standard)', :code => 'FBS', :description => 'Fare Box (Standard).'},
{:active => 1, :name => 'Fare Box (Electronic)',:code => 'FBE', :description => 'Fare Box (Electronic).'},
{:active => 1, :name => 'Radio Equipped', :code => 'RE', :description => 'Radio Equipped.'},
{:active => 1, :name => 'Bike Rack', :code => 'BR', :description => 'Bike Rack.'},
{:active => 1, :name => 'Scheduling Software', :code => 'SS', :description => 'Scheduling Software.'},
{:active => 1, :name => 'WIFI', :code => 'WI', :description => 'WIFI.'}
]
vehicle_usage_codes = [
{:active => 1, :name => 'Revenue Vehicle', :code => 'R', :description => 'Revenue Vehicle.'},
{:active => 1, :name => 'Support Vehicle', :code => 'S', :description => 'Support Vehicle.'},
{:active => 1, :name => 'Van Pool', :code => 'V', :description => 'Van Pool.'},
{:active => 1, :name => 'Paratransit', :code => 'P', :description => 'Paratransit.'},
{:active => 1, :name => 'Spare Inventory', :code => 'I', :description => 'Spare Inventory.'},
{:active => 1, :name => 'Unknown', :code => 'X', :description => 'No vehicle usage specified.'}
]
vehicle_rebuild_types = [
{:active => 1, :name => 'Mid-Life Powertrain', :description => 'Mid-Life Powertrain'},
{:active => 1, :name => 'Mid-Life Overhaul', :description => 'Mid-Life Overhaul'},
{:active => 1, :name => 'Life-Extending Overhaul', :description => 'Life-Extending Overhaul'},
]
fta_mode_types = [
# Rural Reporting Modes
{:active => 1, :name => 'Unknown', :code => 'XX', :description => 'No FTA mode type specified.'},
{:active => 1, :name => 'Bus', :code => 'MB', :description => 'Bus.'},
{:active => 1, :name => 'Commuter Bus', :code => 'CB', :description => 'Commuter bus.'},
{:active => 1, :name => 'Demand Response', :code => 'DR', :description => 'Demand Response.'},
{:active => 1, :name => 'Ferry Boat', :code => 'FB', :description => 'Ferryboat.'},
{:active => 1, :name => 'Taxi', :code => 'TX', :description => 'Taxi.'},
{:active => 1, :name => 'Vanpool', :code => 'VP', :description => 'Vanpool.'},
{:active => 1, :name => 'Aerial Tramway', :code => 'TR', :description => 'Aerial Tramway.'},
{:active => 1, :name => 'Bus Rapid Transit', :code => 'RB', :description => 'Bus rapid transit.'},
{:active => 1, :name => 'Other', :code => 'OR', :description => 'Other.'}
# Urban Reporting Modes
#{:active => 1, :name => 'Jitney', :code => 'JT', :description => 'Jitney.'},
#{:active => 1, :name => 'Publico', :code => 'PB', :description => 'Publico.'},
#{:active => 1, :name => 'Trolley Bus', :code => 'TB', :description => 'Trolleybus.'},
#{:active => 1, :name => 'Alaska Railroad', :code => 'AR', :description => 'Alaska Railroad.'},
#{:active => 1, :name => 'Monorail/Automated Guideway Transit', :code => 'MG', :description => 'Monorail/Automated guideway transit.'},
#{:active => 1, :name => 'Cable Car', :code => 'CC', :description => 'Cable car.'},
#{:active => 1, :name => 'Commuter Rail', :code => 'CR', :description => 'Commuter rail.'},
#{:active => 1, :name => 'Heavy Rail', :code => 'HR', :description => 'Heavy rail.'},
#{:active => 1, :name => 'Inclined Plane', :code => 'IP', :description => 'Inclined plane.'},
#{:active => 1, :name => 'Light Rail', :code => 'LR', :description => 'Light rail.'},
#{:active => 1, :name => 'Street Car', :code => 'SR', :description => 'Streetcar.'},
#{:active => 1, :name => 'Hybrid Rail', :code => 'HR', :description => 'Hybrid rail.'}
]
fta_bus_mode_types = [
# Rural Reporting Modes
{:active => 1, :name => 'Deviated Fixed Route', :code => 'DFR', :description => 'Deviated Fixed Route'},
{:active => 1, :name => 'Fixed Route', :code => 'FR', :description => 'Fixed route'},
{:active => 1, :name => 'Both', :code => 'B', :description => 'Both deviated and fixed routes.'},
]
fta_service_types = [
{:active => 1, :name => 'Directly Operated', :code => 'DO', :description => 'Directly Operated.'},
{:active => 1, :name => 'Purchased Transportation', :code => 'PT', :description => 'Purchased Transportation.'},
{:active => 1, :name => 'Unknown', :code => 'XX', :description => 'FTA Service type not specified.'}
]
fta_facility_types = [
# Facility Types for Support Facilities
{:active => 1, :name => 'Maintenance Facility (Service and Inspection)', :description => 'Maintenance Facility (Service and Inspection).'},
{:active => 1, :name => 'Heavy Maintenance and Overhaul (Backshop)', :description => 'Heavy Maintenance and Overhaul (Backshop).'},
{:active => 1, :name => 'General Purpose Maintenance Facility/Depot', :description => 'General Purpose Maintenance Facility/Depot.'},
{:active => 1, :name => 'Vehicle Washing Facility', :description => 'Vehicle Washing Facility.'},
{:active => 1, :name => 'Vehicle Blow-Down Facility', :description => 'Vehicle Blow-Down Facility.'},
{:active => 1, :name => 'Vehicle Fueling Facility', :description => 'Vehicle Fueling Facility.'},
{:active => 1, :name => 'Vehicle Testing Facility', :description => 'Vehicle Testing Facility.'},
{:active => 1, :name => 'Administrative Office/Sales Office', :description => 'Administrative Office/Sales Office.'},
{:active => 1, :name => 'Revenue Collection Facility', :description => 'Revenue Collection Facility.'},
{:active => 1, :name => 'Other Support Facility', :description => 'Other Support Facility.'},
# Facility Types for Transit Facilities
{:active => 1, :name => 'Bus Transfer Station', :description => 'Bus Transfer Station.'},
{:active => 1, :name => 'Elevated Fixed Guideway Station', :description => 'Elevated Fixed Guideway Station.'},
{:active => 1, :name => 'At-Grade Fixed Guideway Station', :description => 'At-Grade Fixed Guideway Station.'},
{:active => 1, :name => 'Underground Fixed Guideway Station', :description => 'Underground Fixed Guideway Station.'},
{:active => 1, :name => 'Simple At-Grade Platform Station', :description => 'Simple At-Grade Platform Station.'},
{:active => 1, :name => 'Surface Parking Lot', :description => 'Surface Parking Lot.'},
{:active => 1, :name => 'Parking Structure', :description => 'Parking Structure.'},
{:active => 1, :name => 'Other Transit Facility', :description => 'Other Transit Facility.'}
]
fta_agency_types = [
{:active => 1, :name => 'Public Agency (Not DOT or Tribal)', :description => 'Public Agency (Not DOT or Tribal).'},
{:active => 1, :name => 'Public Agency (State DOT)', :description => 'Public Agency (State DOT).'},
{:active => 1, :name => 'Public Agency (Tribal)', :description => 'Public Agency (Tribal).'},
{:active => 1, :name => 'Private (Not for profit)', :description => 'Private (Not for profit).'}
]
fta_service_area_types = [
{:active => 1, :name => 'County/Independent city', :description => 'County / Independent city.'},
{:active => 1, :name => 'Multi-county/Independent city', :description => 'Multi-county / Independent city.'},
{:active => 1, :name => 'Multi-state', :description => 'Multi-state.'},
{:active => 1, :name => 'Municipality', :description => 'Municipality.'},
{:active => 1, :name => 'Reservation', :description => 'Reservation.'},
{:active => 1, :name => 'Other', :description => 'Other.'}
]
fta_funding_types = [
{:active => 1, :name => 'Urbanized Area Formula Program', :code => 'UA', :description => 'UA -Urbanized Area Formula Program.'},
{:active => 1, :name => 'Other Federal funds', :code => 'OF', :description => 'OF-Other Federal funds.'},
{:active => 1, :name => 'Non-Federal public funds', :code => 'NFPA', :description => 'NFPA-Non-Federal public funds.'},
{:active => 1, :name => 'Non-Federal private funds', :code => 'NFPE', :description => 'NFPE-Non-Federal private funds.'},
{:active => 1, :name => 'Unknown', :code => 'XX', :description => 'FTA funding type not specified.'}
]
fta_ownership_types = [
# Rural Reporting Ownership Types
{:active => 1, :name => 'Owned by Service Provider', :code => 'OSP', :description => 'Owned by Service Provider.'},
{:active => 1, :name => 'Owned by Public Agency for Service Provider', :code => 'OPA', :description => 'Owned by Public Agency for Service Provider.'},
{:active => 1, :name => 'Leased by Service Provider', :code => 'LSP', :description => 'Leased by Service Provider.'},
{:active => 1, :name => 'Leased by Public Agency for Service Provider', :code => 'LPA', :description => 'Leased by Public Agency for Service Provider.'},
{:active => 1, :name => 'Other', :code => 'OR', :description => 'Other.'},
{:active => 1, :name => 'Unknown', :code => 'XX', :description => 'FTA ownership type not specified.'}
]
fta_vehicle_types = [
# Rural Reporting Types
{:active => 1, :name => 'Automobile', :code => 'AO', :description => 'Automobile.'},
{:active => 1, :name => 'Bus', :code => 'BU', :description => 'Bus.'},
{:active => 1, :name => 'Cutaway', :code => 'CU', :description => 'Cutaway.'},
{:active => 1, :name => 'Ferry Boat', :code => 'FB', :description => 'Ferryboat.'},
{:active => 1, :name => 'Mini Van', :code => 'MV', :description => 'Minivan.'},
{:active => 1, :name => 'Over-The-Road Bus', :code => 'BR', :description => 'Over-The-Road Bus.'},
{:active => 1, :name => 'School Bus', :code => 'SB', :description => 'School Bus.'},
{:active => 1, :name => 'Sports Utility Vehicle', :code => 'SV', :description => 'Sports Utility Vehicle.'},
{:active => 1, :name => 'Van', :code => 'VN', :description => 'Van.'},
{:active => 1, :name => 'Articulated Bus', :code => 'AB', :description => 'Articulated Bus.'},
{:active => 1, :name => 'Double Decker Bus', :code => 'DB', :description => 'Double Decker Bus.'},
{:active => 1, :name => 'Aerial Tramway', :code => 'TR', :description => 'Aerial Tramway.'},
{:active => 1, :name => 'Other', :code => 'OR', :description => 'Other.'},
# Urban Reporting Types
{:active => 1, :name => 'Automated Guideway Vehicle', :code => 'AG', :description => 'Automated Guideway Vehicle.'},
{:active => 1, :name => 'Cable Car', :code => 'CC', :description => 'Cable Car.'},
{:active => 1, :name => 'Heavy Rail Passenger Car', :code => 'HR', :description => 'Heavy Rail Passenger Car.'},
{:active => 1, :name => 'Inclined Plane Vehicle', :code => 'IP', :description => 'Inclined Plane Vehicle.'},
{:active => 1, :name => 'Light Rail Vehicle', :code => 'LR', :description => 'Light Rail Vehicle.'},
{:active => 1, :name => 'Monorail/Automated Guideway', :code => 'MO', :description => 'Monorail/Automated Guideway.'},
{:active => 1, :name => 'Commuter Rail Locomotive', :code => 'RL', :description => 'Commuter Rail Locomotive.'},
{:active => 1, :name => 'Commuter Rail Passenger Coach', :code => 'RP', :description => 'Commuter Rail Passenger Coach.'},
{:active => 1, :name => 'Commuter Rail Self-Propelled Passenger Car', :code => 'RS', :description => 'Commuter Rail Self-Propelled Passenger Car.'},
{:active => 1, :name => 'Trolley Bus', :code => 'TB', :description => 'Trolley Bus.'},
{:active => 1, :name => 'Taxicab Sedan', :code => 'TS', :description => 'Taxicab Sedan.'},
{:active => 1, :name => 'Taxicab Van', :code => 'TV', :description => 'Taxicab Van.'},
{:active => 1, :name => 'Taxicab Station Wagon', :code => 'TW', :description => 'Taxicab Station Wagon.'},
{:active => 1, :name => 'Vintage Trolley/Streetcar',:code => 'VT', :description => 'Vintage Trolley/Streetcar.'},
{:active => 1, :name => 'Unknown', :code => 'XX', :description => 'Vehicle type not specified.'}
]
facility_capacity_types = [
{:active => 1, :name => 'N/A', :description => 'Not applicable.'},
{:active => 1, :name => 'Less than 200 vehicles', :description => 'Less than 200 vehicles.'},
{:active => 1, :name => 'Between 200 and 300 vehicles', :description => 'Between 200 and 300 vehicles.'},
{:active => 1, :name => 'Over 300 vehicles', :description => 'Over 300 vehicles.'}
]
facility_features = [
{:active => 1, :name => 'Moving walkways', :code => 'MW', :description => 'Moving walkways.'},
{:active => 1, :name => 'Ticketing', :code => 'TK', :description => 'Ticketing.'},
{:active => 1, :name => 'Information kiosks', :code => 'IK', :description => 'Information kiosks.'},
{:active => 1, :name => 'Restrooms', :code => 'RR', :description => 'Restrooms.'},
{:active => 1, :name => 'Concessions', :code => 'CS', :description => 'Concessions.'},
{:active => 1, :name => 'Telephones', :code => 'TP', :description => 'Telephones.'},
{:active => 1, :name => 'ATM', :code => 'AT', :description => 'ATM.'},
{:active => 1, :name => 'WIFI', :code => 'WI', :description => 'WIFI.'}
]
leed_certification_types = [
{:active => 1, :name => 'Not Certified', :description => 'Not Certified'},
{:active => 1, :name => 'Certified', :description => 'Certified'},
{:active => 1, :name => 'Silver', :description => 'Silver'},
{:active => 1, :name => 'Gold', :description => 'Gold'},
{:active => 1, :name => 'Platinum', :description => 'Platinum'},
]
district_types = [
{:active => 1, :name => 'State', :description => 'State.'},
{:active => 1, :name => 'District', :description => 'Engineering District.'},
{:active => 1, :name => 'MSA', :description => 'Metropolitan Statistical Area.'},
{:active => 1, :name => 'County', :description => 'County.'},
{:active => 1, :name => 'City', :description => 'City.'},
{:active => 1, :name => 'Borough', :description => 'Borough.'},
{:active => 1, :name => 'MPO/RPO', :description => 'MPO or RPO planning area.'},
{:active => 1, :name => 'Postal Code', :description => 'ZIP Code or Postal Area.'}
]
file_content_types = [
{:active => 1, :name => 'Inventory Updates', :class_name => 'TransitInventoryUpdatesFileHandler', :builder_name => "TransitInventoryUpdatesTemplateBuilder", :description => 'Worksheet records updated condition, status, and mileage for existing inventory.'},
{:active => 1, :name => 'Maintenance Updates', :class_name => 'MaintenanceUpdatesFileHandler',:builder_name => "MaintenanceUpdatesTemplateBuilder", :description => 'Worksheet records latest maintenance updates for assets'},
{:active => 1, :name => 'Disposition Updates', :class_name => 'DispositionUpdatesFileHandler', :builder_name => "TransitDispositionUpdatesTemplateBuilder", :description => 'Worksheet contains final disposition updates for existing inventory.'},
{:active => 1, :name => 'New Inventory', :class_name => 'TransitNewInventoryFileHandler', :builder_name => "TransitNewInventoryTemplateBuilder", :description => 'Worksheet records updated condition, status, and mileage for existing inventory.'}
]
maintenance_types = [
{:active => 1, :name => "Oil Change/Filter/Lube", :description => "Oil Change/Filter/Lube"},
{:active => 1, :name => "Standard PM Inspection", :description => "Standard PM Inspection"}
]
service_provider_types = [
{:active => 1, :name => 'Urban', :code => 'URB', :description => 'Operates in an urban area.'},
{:active => 1, :name => 'Rural', :code => 'RUR', :description => 'Operates in a rural area.'},
{:active => 1, :name => 'Shared Ride', :code => 'SHR', :description => 'Provides shared ride services.'},
{:active => 1, :name => 'Intercity Bus', :code => 'ICB', :description => 'Provides intercity bus services.'},
{:active => 1, :name => 'Intercity Rail', :code => 'ICR', :description => 'Provides intercity rail services.'}
]
vehicle_storage_method_types = [
{:active => 1, :name => 'Indoors', :code => 'I', :description => 'Vehicle is always stored indoors.'},
{:active => 1, :name => 'Outdoors', :code => 'O', :description => 'Vehicle is always stored outdoors.'},
{:active => 1, :name => 'Indoor/Outdoor', :code => 'B', :description => 'Vehicle is stored both indoors and outdoors.'},
{:active => 1, :name => 'Unknown',:code => 'X', :description => 'Vehicle storage method not supplied.'}
]
maintenance_provider_types = [
{:active => 1, :name => 'Self Maintained', :code => 'SM', :description => 'Self Maintained.'},
{:active => 1, :name => 'County', :code => 'CO', :description => 'County.'},
{:active => 1, :name => 'Public Agency', :code => 'PA', :description => 'Public Agency.'},
{:active => 1, :name => 'Private Entity', :code => 'PE', :description => 'Private Entity.'},
{:active => 1, :name => 'Unknown', :code => 'XX', :description => 'Maintenance provider not supplied.'}
]
organization_types = [
{:active => 1, :name => 'Grantor', :class_name => "Grantor", :display_icon_name => "fa fa-usd", :map_icon_name => "redIcon", :description => 'Organizations who manage funding grants.', :roles => 'guest,manager'},
{:active => 1, :name => 'Transit Operator', :class_name => "TransitOperator", :display_icon_name => "fa fa-bus", :map_icon_name => "greenIcon", :description => 'Transit Operator.', :roles => 'guest,user,transit_manager'},
{:active => 1, :name => 'Planning Partner', :class_name => "PlanningPartner", :display_icon_name => "fa fa-group", :map_icon_name => "purpleIcon", :description => 'Organizations who need visibility into grantee assets for planning purposes.', :roles => 'guest'}
]
governing_body_types = [
{:active => 1, :name => 'Corporate Board of Directors', :description => 'Corporate Board of Directors'},
{:active => 1, :name => 'Authority Board', :description => 'Board of Directors'},
{:active => 1, :name => 'County', :description => 'County'},
{:active => 1, :name => 'City', :description => 'City'},
{:active => 1, :name => 'Other', :description => 'Other Governing Body'}
]
replace_tables = %w{ asset_types fuel_types vehicle_features vehicle_usage_codes vehicle_rebuild_types fta_mode_types fta_bus_mode_types fta_agency_types fta_service_area_types
fta_service_types fta_funding_types fta_ownership_types fta_vehicle_types facility_capacity_types
facility_features leed_certification_types district_types maintenance_provider_types file_content_types service_provider_types organization_types maintenance_types
vehicle_storage_method_types fta_facility_types governing_body_types
}
replace_tables.each do |table_name|
puts " Loading #{table_name}"
if is_mysql
ActiveRecord::Base.connection.execute("TRUNCATE TABLE #{table_name};")
elsif is_sqlite
ActiveRecord::Base.connection.execute("DELETE FROM #{table_name};")
else
ActiveRecord::Base.connection.execute("TRUNCATE #{table_name} RESTART IDENTITY;")
end
data = eval(table_name)
klass = table_name.classify.constantize
data.each do |row|
x = klass.new(row)
x.save!
end
end
table_name = 'asset_subtypes'
puts " Loading #{table_name}"
if is_mysql
ActiveRecord::Base.connection.execute("TRUNCATE TABLE #{table_name};")
elsif is_sqlite
ActiveRecord::Base.connection.execute("DELETE FROM #{table_name};")
else
ActiveRecord::Base.connection.execute("TRUNCATE #{table_name} RESTART IDENTITY;")
end
data = eval(table_name)
data.each do |row|
x = AssetSubtype.new(row.except(:belongs_to, :type))
x.asset_type = AssetType.where(:name => row[:type]).first
x.save!
end
require_relative File.join("seeds", 'team_ali_code_seeds') # TEAM ALI Codes are seeded from a separate file
# See if we need to load the rail/locomotive seed data
if Rails.application.config.transam_transit_rail == true
require_relative File.join("seeds", 'rail.seeds') # Rail assets are seeded from a separate file
end
# These tables are merged with core tables
roles = [
{:privilege => false, :name => 'transit_manager', :weight => 5},
{:privilege => true, :name => 'director_transit_operations'},
{:privilege => true, :name => 'ntd_contact'}
]
asset_event_types = [
{:active => 1, :name => 'Mileage', :display_icon_name => "fa fa-road", :description => 'Mileage Update', :class_name => 'MileageUpdateEvent', :job_name => 'AssetMileageUpdateJob'},
{:active => 1, :name => 'Operations metrics', :display_icon_name => "fa fa-calculator", :description => 'Operations Update',:class_name => 'OperationsUpdateEvent', :job_name => 'AssetOperationsUpdateJob'},
{:active => 1, :name => 'Facility operations metrics', :display_icon_name => "fa fa-calculator", :description => 'Facility Operations Update',:class_name => 'FacilityOperationsUpdateEvent', :job_name => 'AssetFacilityOperationsUpdateJob'},
{:active => 1, :name => 'Vehicle use metrics', :display_icon_name => "fa fa-line-chart", :description => 'Vehicle Usage Update', :class_name => 'VehicleUsageUpdateEvent', :job_name => 'AssetVehicleUsageUpdateJob'},
{:active => 1, :name => 'Storage method', :display_icon_name => "fa fa-star-half-o", :description => 'Storage Method', :class_name => 'StorageMethodUpdateEvent', :job_name => 'AssetStorageMethodUpdateJob'},
{:active => 1, :name => 'Usage codes', :display_icon_name => "fa fa-star-half-o", :description => 'Usage Codes', :class_name => 'UsageCodesUpdateEvent', :job_name => 'AssetUsageCodesUpdateJob'},
{:active => 1, :name => 'Maintenance provider type', :display_icon_name => "fa fa-cog", :description => 'Maintenance Provider', :class_name => 'MaintenanceProviderUpdateEvent', :job_name => 'AssetMaintenanceProviderUpdateJob'}
]
condition_estimation_types = [
{:active => 1, :name => 'TERM', :class_name => 'TermEstimationCalculator', :description => 'Asset condition is estimated using FTA TERM approximations.'}
]
report_types = [
{:active => 1, :name => 'Planning Report', :display_icon_name => "fa fa-line-chart", :description => 'Planning Report.'},
]
service_life_calculation_types = [
{:active => 1, :name => 'Age and Mileage', :class_name => 'ServiceLifeAgeAndMileage', :description => 'Calculate the replacement year based on the age or mileage conditions both being met.'},
{:active => 1, :name => 'Age or Mileage', :class_name => 'ServiceLifeAgeOrMileage', :description => 'Calculate the replacement year based on either the age of the asset or mileage conditions being met.'},
{:active => 1, :name => 'Age and Mileage and Condition', :class_name => 'ServiceLifeAgeAndMileageAndCondition', :description => 'Calculate the replacement year based on all of the age and condition and mileage conditions being met.'},
{:active => 1, :name => 'Age or Mileage or Condition', :class_name => 'ServiceLifeAgeOrMileageOrCondition', :description => 'Calculate the replacement year based on any of the age and condition and mileage conditions being met.'},
{:active => 1, :name => 'Condition and Mileage', :class_name => 'ServiceLifeConditionAndMileage', :description => 'Calculate the replacement year based on both the asset and mileage conditions both being met.'},
{:active => 1, :name => 'Condition or Mileage', :class_name => 'ServiceLifeConditionOrMileage', :description => 'Calculate the replacement year based on either of the asset and mileage conditions being met.'}
]
merge_tables = %w{ roles asset_event_types condition_estimation_types service_life_calculation_types report_types }
merge_tables.each do |table_name|
puts " Merging #{table_name}"
data = eval(table_name)
klass = table_name.classify.constantize
data.each do |row|
x = klass.new(row)
x.save!
end
end
puts " Merging asset_subsystems"
asset_subsystems = [
{:name => "Transmission", :code => "TR", :asset_type => "Vehicle"},
{:name => "Engine", :code => "EN", :asset_type => "Vehicle"},
{:name => "Trucks", :code => "TR", :asset_type => "RailCar"},
{:name => "Trucks", :code => "TR", :asset_type => "Locomotive"}
]
asset_subsystems.each do |s|
subsystem = AssetSubsystem.new(:name => s[:name], :description => s[:name], :active => true, :code => s[:code])
asset_type = AssetType.find_by(name: s[:asset_type])
subsystem.asset_type = asset_type
subsystem.save
end
puts "======= Processing TransAM Transit Reports ======="
reports = [
{:active => 1, :belongs_to => 'report_type', :type => "Inventory Report",
:name => 'Useful Life Consumed Report',
:class_name => "ServiceLifeConsumedReport",
:view_name => "generic_chart",
:show_in_nav => 1,
:show_in_dashboard => 0,
:roles => 'guest,user',
:description => 'Displays a summary of the amount of useful life that has been consumed as a percentage of all assets.',
:chart_type => 'column',
:chart_options => "{is3D : true, isStacked: true, fontSize: 10, hAxis: {title: 'Percent of expected useful life consumed'}, vAxis: {title: 'Share of all assets'}}"},
{:active => 1, :belongs_to => 'report_type', :type => "Inventory Report",
:name => 'Asset Condition Report',
:class_name => "AssetConditionReport",
:view_name => "generic_chart",
:show_in_nav => 1,
:show_in_dashboard => 0,
:roles => 'guest,user',
:description => 'Displays asset counts by condition.',
:chart_type => 'pie',
:chart_options => '{is3D : true}'},
{:active => 1, :belongs_to => 'report_type', :type => "Inventory Report",
:name => 'Asset Subtype Report',
:class_name => "AssetSubtypeReport",
:view_name => "generic_chart",
:show_in_nav => 1,
:show_in_dashboard => 0,
:roles => 'guest,user',
:description => 'Displays asset counts by subtypes.',
:chart_type => 'pie',
:chart_options => '{is3D : true}'},
{:active => 1, :belongs_to => 'report_type', :type => "Inventory Report",
:name => 'Asset Age Report',
:class_name => "AssetAgeReport",
:view_name => "generic_chart",
:show_in_nav => 1,
:show_in_dashboard => 0,
:roles => 'guest,user',
:description => 'Displays asset counts by age.',
:chart_type => 'column',
:chart_options => "{is3D : true, isStacked : true, hAxis: {title: 'Age (years)'}, vAxis: {title: 'Count'}}"},
{:active => 1, :belongs_to => 'report_type', :type => "Capital Needs Report",
:name => 'Backlog Report',
:class_name => "BacklogReport",
:view_name => "generic_report",
:show_in_nav => 1,
:show_in_dashboard => 0,
:roles => 'guest,user',
:description => 'Determines backlog needs.'},
{:active => 1, :belongs_to => 'report_type', :type => "Inventory Report",
:name => 'Asset Type by Org Report',
:class_name => "CustomSqlReport",
:view_name => "generic_report_table",
:show_in_nav => 0,
:show_in_dashboard => 0,
:roles => 'guest,user',
:description => 'Displays a summary of asset types by agency.',
:custom_sql => "SELECT c.short_name AS 'Org', b.name AS 'Type', COUNT(*) AS 'Count' FROM assets a LEFT JOIN asset_subtypes b ON a.asset_subtype_id = b.id LEFT JOIN organizations c ON a.organization_id = c.id GROUP BY a.organization_id, a.asset_subtype_id ORDER BY c.short_name, b.name"},
{:active => 1, :belongs_to => 'report_type', :type => "Planning Report",
:name => 'Vehicle Replacement Report',
:class_name => "VehicleReplacementReport",
:view_name => "vehicle_replacement_report",
:show_in_nav => 1,
:show_in_dashboard => 0,
:roles => 'guest,user',
:description => 'Reports the list of vehicles scheduled to be replaced.'},
{:active => 1, :belongs_to => 'report_type', :type => "Planning Report",
:name => 'State of Good Repair Report',
:class_name => "StateOfGoodRepairReport",
:view_name => "state_of_good_repair_report",
:show_in_nav => 1,
:show_in_dashboard => 0,
:roles => 'guest,user',
:description => 'Reports an agency\'s current State of Good Repair.'},
{:active => 1, :belongs_to => 'report_type', :type => "Planning Report",
:name => 'Disposition Report',
:class_name => "AssetDispositionReport",
:view_name => "asset_disposition_report",
:show_in_nav => 1,
:show_in_dashboard => 0,
:roles => 'guest,user',
:description => 'Reports Vehicles which have been disposed.'}
]
table_name = 'reports'
puts " Merging #{table_name}"
data = eval(table_name)
data.each do |row|
puts "Creating Report #{row[:name]}"
x = Report.new(row.except(:belongs_to, :type))
x.report_type = ReportType.find_by(:name => row[:type])
x.save!
end
[#145286823] I've added the UZA district type the the transit seed data and updated the districts.txt file that should be loaded for the BPT district list. I also removed a duplicate instance of MPO/RPO Altoona from that list.
#encoding: utf-8
# determine if we are using postgres or mysql
is_mysql = (ActiveRecord::Base.configurations[Rails.env]['adapter'] == 'mysql2')
is_sqlite = (ActiveRecord::Base.configurations[Rails.env]['adapter'] == 'sqlite3')
puts "======= Processing TransAM Transit Lookup Tables ======="
#------------------------------------------------------------------------------
#
# Customized Lookup Tables
#
# These are the specific to TransAM Transit
#
#------------------------------------------------------------------------------
asset_types = [
{:active => 1, :name => 'Revenue Vehicles', :description => 'Revenue rolling stock', :class_name => 'Vehicle', :map_icon_name => "redIcon", :display_icon_name => "fa fa-bus"},
{:active => 1, :name => 'Stations/Stops/Terminals', :description => 'Stations/Stops/Terminals', :class_name => 'TransitFacility', :map_icon_name => "greenIcon", :display_icon_name => "fa fa-building-o"},
{:active => 1, :name => 'Support Facilities', :description => 'Support Facilities', :class_name => 'SupportFacility', :map_icon_name => "blueIcon", :display_icon_name => "fa fa-building"},
{:active => 1, :name => 'Support Vehicles', :description => 'Support Vehicles', :class_name => 'SupportVehicle', :map_icon_name => "blueIcon", :display_icon_name => "fa fa-car"},
{:active => 1, :name => 'Maintenance Equipment', :description => 'Maintenance Equipment', :class_name => 'Equipment', :map_icon_name => "blueIcon", :display_icon_name => "fa fa-wrench"},
{:active => 1, :name => 'Facility Equipment', :description => 'Facility Equipment', :class_name => 'Equipment', :map_icon_name => "blueIcon", :display_icon_name => "fa fa-lightbulb-o"},
{:active => 1, :name => 'IT Equipment', :description => 'IT Equipment', :class_name => 'Equipment', :map_icon_name => "blueIcon", :display_icon_name => "fa fa-laptop"},
{:active => 1, :name => 'Office Equipment', :description => 'Office Equipment', :class_name => 'Equipment', :map_icon_name => "blueIcon", :display_icon_name => "fa fa-inbox"},
{:active => 1, :name => 'Communications Equipment', :description => 'Communications Equipment', :class_name => 'Equipment', :map_icon_name => "blueIcon", :display_icon_name => "fa fa-phone"},
{:active => 1, :name => 'Signals/Signs', :description => 'Signals and Signs', :class_name => 'Equipment', :map_icon_name => "blueIcon", :display_icon_name => "fa fa-h-square"}
]
asset_subtypes = [
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus Std 40 FT', :description => 'Bus Std 40 FT'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus Std 35 FT', :description => 'Bus Std 35 FT'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus 30 FT', :description => 'Bus 30 FT'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus < 30 FT', :description => 'Bus < 30 FT'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus School', :description => 'Bus School'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus Articulated', :description => 'Bus Articulated'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus Commuter/Suburban',:description => 'Bus Commuter/Suburban'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus Intercity', :description => 'Bus Intercity'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus Trolley Std', :description => 'Bus Trolley Std'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus Trolley Articulated',:description => 'Bus Trolley Articulated'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus Double Deck', :description => 'Bus Double Deck'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Bus Dual Mode', :description => 'Bus Dual Mode'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Van', :description => 'Van'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Sedan/Station Wagon', :description => 'Sedan/Station Wagon'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Revenue Vehicles', :name => 'Ferry Boat', :description => 'Ferry Boat'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Stations/Stops/Terminals', :name => 'Bus Shelter', :description => 'Bus Shelter'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Stations/Stops/Terminals', :name => 'Bus Station', :description => 'Bus Station'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Stations/Stops/Terminals', :name => 'Ferry Dock', :description => 'Ferry Dock'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Stations/Stops/Terminals', :name => 'Intermodal Terminal', :description => 'Intermodal Terminal'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Stations/Stops/Terminals', :name => 'Park and Ride Lot', :description => 'Park and Ride Lot'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Stations/Stops/Terminals', :name => 'Parking Garage', :description => 'Parking Garage'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Stations/Stops/Terminals', :name => 'Parking Lot', :description => 'Parking Lot'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Stations/Stops/Terminals', :name => 'Other Transit Facility',:description => 'Other Transit Facility'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Facilities', :name => 'Administration Building', :description => 'Administration Building'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Facilities', :name => 'Bus Maintenance Facility', :description => 'Bus Maintenance Facility'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Facilities', :name => 'Bus Parking Facility', :description => 'Bus Parking Facility'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Facilities', :name => 'Bus Turnaround Facility', :description => 'Bus Turnaround Facility'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Facilities', :name => 'Storage Yard', :description => 'Storage Yard'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Facilities', :name => 'Other Support Facility', :description => 'Other Support Facility'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Vehicles', :name => 'Van', :description => 'Van'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Vehicles', :name => 'Tow Truck', :description => 'Tow Truck'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Vehicles', :name => 'Sedan/Station Wagon', :description => 'Sedan/Station Wagon'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Vehicles', :name => 'Pickup/Utility Truck', :description => 'Pickup/Utility Truck'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Vehicles', :name => 'Sports Utility Vehicle', :description => 'Sports Utility Vehicle'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Support Vehicles', :name => 'Other Support Vehicle', :description => 'Other Support Vehicle'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Maintenance Equipment', :name => 'Bus Maintenance Equipment', :description => 'Bus Maintenance Equipment'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Maintenance Equipment', :name => 'Other Maintenance Equipment', :description => 'Other Maintenance Equipment'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Facility Equipment', :name => 'Mechanical Equipment', :description => 'Mechanical Equipment'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Facility Equipment', :name => 'Electrical Equipment', :description => 'Electrical Equipment'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Facility Equipment', :name => 'Structural Equipment', :description => 'Structural Equipment'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Facility Equipment', :name => 'Other Facilities Equipment', :description => 'Other Facilities Equipment'},
{:active => 1, :belongs_to => 'asset_type', :type => 'IT Equipment', :name => 'Hardware', :description => 'Hardware'},
{:active => 1, :belongs_to => 'asset_type', :type => 'IT Equipment', :name => 'Software', :description => 'Hardware'},
{:active => 1, :belongs_to => 'asset_type', :type => 'IT Equipment', :name => 'Networks', :description => 'Hardware'},
{:active => 1, :belongs_to => 'asset_type', :type => 'IT Equipment', :name => 'Storage', :description => 'Storage'},
{:active => 1, :belongs_to => 'asset_type', :type => 'IT Equipment', :name => 'Other IT Equipment', :description => 'Hardware'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Office Equipment', :name => 'Furniture', :description => 'Office Furniture'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Office Equipment', :name => 'Supplies', :description => 'Office Supplies'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Office Equipment', :name => 'Other Office Equipment', :description => 'Other Office Equipment'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Communications Equipment', :name => 'Vehicle Location Systems', :description => 'Vehicle Location Systems'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Communications Equipment', :name => 'Radios', :description => 'Radios'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Communications Equipment', :name => 'Surveillance & Security', :description => 'Surveillance & Security'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Communications Equipment', :name => 'Fare Collection Systems', :description => 'Fare Collection Systems'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Communications Equipment', :name => 'Other Communications Equipment', :description => 'Other Communication Equipment'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Signals/Signs', :name => 'Route Signage', :description => 'Route Signage'},
{:active => 1, :belongs_to => 'asset_type', :type => 'Signals/Signs', :name => 'Other Signage Equipment', :description => 'Other Signage Equipment'}
]
fuel_types = [
{:active => 1, :name => 'Biodiesel', :code => 'BD', :description => 'Biodiesel.'},
{:active => 1, :name => 'Bunker Fuel', :code => 'BF', :description => 'Bunker Fuel.'},
{:active => 1, :name => 'Compressed Natural Gas', :code => 'CNG', :description => 'Compressed Natutral Gas.'},
{:active => 1, :name => 'Diesel Fuel', :code => 'DF', :description => 'Diesel Fuel.'},
{:active => 1, :name => 'Dual Fuel', :code => 'DU', :description => 'Dual Fuel.'},
{:active => 1, :name => 'Electric Battery', :code => 'EB', :description => 'Electric Battery.'},
{:active => 1, :name => 'Electric Propulsion', :code => 'EP', :description => 'Electric Propulsion.'},
{:active => 1, :name => 'Ethanol', :code => 'ET', :description => 'Ethanol.'},
{:active => 1, :name => 'Gasoline', :code => 'GA', :description => 'Gasoline.'},
{:active => 1, :name => 'Hybrid Diesel', :code => 'HD', :description => 'Hybrid Diesel.'},
{:active => 1, :name => 'Hybrid Gasoline', :code => 'HG', :description => 'Hybrid Gasoline.'},
{:active => 1, :name => 'Hydrogen', :code => 'HY', :description => 'Hydrogen.'},
{:active => 1, :name => 'Kerosene', :code => 'KE', :description => 'Kerosene.'},
{:active => 1, :name => 'Liquefied Natural Gas', :code => 'LN', :description => 'Liquefied Natural Gas.'},
{:active => 1, :name => 'Liquefied Petroleum Gas', :code => 'LP', :description => 'Liquefied Petroleum Gas.'},
{:active => 1, :name => 'Methanol', :code => 'MT', :description => 'Methanol.'},
{:active => 1, :name => 'Other', :code => 'OR', :description => 'Other.'},
{:active => 1, :name => 'Unknown', :code => 'XX', :description => 'No Fuel type specified.'}
]
vehicle_features = [
{:active => 1, :name => 'AVL System', :code => 'AS', :description => 'Automatic Vehicle Location System.'},
{:active => 1, :name => 'Lift Equipped', :code => 'LE', :description => 'Lift Equipped.'},
{:active => 1, :name => 'Electronic Ramp', :code => 'ER', :description => 'Electronic Ramp.'},
{:active => 1, :name => 'Video Cameras', :code => 'VC', :description => 'Video Cameras.'},
{:active => 1, :name => 'Fare Box (Standard)', :code => 'FBS', :description => 'Fare Box (Standard).'},
{:active => 1, :name => 'Fare Box (Electronic)',:code => 'FBE', :description => 'Fare Box (Electronic).'},
{:active => 1, :name => 'Radio Equipped', :code => 'RE', :description => 'Radio Equipped.'},
{:active => 1, :name => 'Bike Rack', :code => 'BR', :description => 'Bike Rack.'},
{:active => 1, :name => 'Scheduling Software', :code => 'SS', :description => 'Scheduling Software.'},
{:active => 1, :name => 'WIFI', :code => 'WI', :description => 'WIFI.'}
]
vehicle_usage_codes = [
{:active => 1, :name => 'Revenue Vehicle', :code => 'R', :description => 'Revenue Vehicle.'},
{:active => 1, :name => 'Support Vehicle', :code => 'S', :description => 'Support Vehicle.'},
{:active => 1, :name => 'Van Pool', :code => 'V', :description => 'Van Pool.'},
{:active => 1, :name => 'Paratransit', :code => 'P', :description => 'Paratransit.'},
{:active => 1, :name => 'Spare Inventory', :code => 'I', :description => 'Spare Inventory.'},
{:active => 1, :name => 'Unknown', :code => 'X', :description => 'No vehicle usage specified.'}
]
vehicle_rebuild_types = [
{:active => 1, :name => 'Mid-Life Powertrain', :description => 'Mid-Life Powertrain'},
{:active => 1, :name => 'Mid-Life Overhaul', :description => 'Mid-Life Overhaul'},
{:active => 1, :name => 'Life-Extending Overhaul', :description => 'Life-Extending Overhaul'},
]
fta_mode_types = [
# Rural Reporting Modes
{:active => 1, :name => 'Unknown', :code => 'XX', :description => 'No FTA mode type specified.'},
{:active => 1, :name => 'Bus', :code => 'MB', :description => 'Bus.'},
{:active => 1, :name => 'Commuter Bus', :code => 'CB', :description => 'Commuter bus.'},
{:active => 1, :name => 'Demand Response', :code => 'DR', :description => 'Demand Response.'},
{:active => 1, :name => 'Ferry Boat', :code => 'FB', :description => 'Ferryboat.'},
{:active => 1, :name => 'Taxi', :code => 'TX', :description => 'Taxi.'},
{:active => 1, :name => 'Vanpool', :code => 'VP', :description => 'Vanpool.'},
{:active => 1, :name => 'Aerial Tramway', :code => 'TR', :description => 'Aerial Tramway.'},
{:active => 1, :name => 'Bus Rapid Transit', :code => 'RB', :description => 'Bus rapid transit.'},
{:active => 1, :name => 'Other', :code => 'OR', :description => 'Other.'}
# Urban Reporting Modes
#{:active => 1, :name => 'Jitney', :code => 'JT', :description => 'Jitney.'},
#{:active => 1, :name => 'Publico', :code => 'PB', :description => 'Publico.'},
#{:active => 1, :name => 'Trolley Bus', :code => 'TB', :description => 'Trolleybus.'},
#{:active => 1, :name => 'Alaska Railroad', :code => 'AR', :description => 'Alaska Railroad.'},
#{:active => 1, :name => 'Monorail/Automated Guideway Transit', :code => 'MG', :description => 'Monorail/Automated guideway transit.'},
#{:active => 1, :name => 'Cable Car', :code => 'CC', :description => 'Cable car.'},
#{:active => 1, :name => 'Commuter Rail', :code => 'CR', :description => 'Commuter rail.'},
#{:active => 1, :name => 'Heavy Rail', :code => 'HR', :description => 'Heavy rail.'},
#{:active => 1, :name => 'Inclined Plane', :code => 'IP', :description => 'Inclined plane.'},
#{:active => 1, :name => 'Light Rail', :code => 'LR', :description => 'Light rail.'},
#{:active => 1, :name => 'Street Car', :code => 'SR', :description => 'Streetcar.'},
#{:active => 1, :name => 'Hybrid Rail', :code => 'HR', :description => 'Hybrid rail.'}
]
fta_bus_mode_types = [
# Rural Reporting Modes
{:active => 1, :name => 'Deviated Fixed Route', :code => 'DFR', :description => 'Deviated Fixed Route'},
{:active => 1, :name => 'Fixed Route', :code => 'FR', :description => 'Fixed route'},
{:active => 1, :name => 'Both', :code => 'B', :description => 'Both deviated and fixed routes.'},
]
fta_service_types = [
{:active => 1, :name => 'Directly Operated', :code => 'DO', :description => 'Directly Operated.'},
{:active => 1, :name => 'Purchased Transportation', :code => 'PT', :description => 'Purchased Transportation.'},
{:active => 1, :name => 'Unknown', :code => 'XX', :description => 'FTA Service type not specified.'}
]
fta_facility_types = [
# Facility Types for Support Facilities
{:active => 1, :name => 'Maintenance Facility (Service and Inspection)', :description => 'Maintenance Facility (Service and Inspection).'},
{:active => 1, :name => 'Heavy Maintenance and Overhaul (Backshop)', :description => 'Heavy Maintenance and Overhaul (Backshop).'},
{:active => 1, :name => 'General Purpose Maintenance Facility/Depot', :description => 'General Purpose Maintenance Facility/Depot.'},
{:active => 1, :name => 'Vehicle Washing Facility', :description => 'Vehicle Washing Facility.'},
{:active => 1, :name => 'Vehicle Blow-Down Facility', :description => 'Vehicle Blow-Down Facility.'},
{:active => 1, :name => 'Vehicle Fueling Facility', :description => 'Vehicle Fueling Facility.'},
{:active => 1, :name => 'Vehicle Testing Facility', :description => 'Vehicle Testing Facility.'},
{:active => 1, :name => 'Administrative Office/Sales Office', :description => 'Administrative Office/Sales Office.'},
{:active => 1, :name => 'Revenue Collection Facility', :description => 'Revenue Collection Facility.'},
{:active => 1, :name => 'Other Support Facility', :description => 'Other Support Facility.'},
# Facility Types for Transit Facilities
{:active => 1, :name => 'Bus Transfer Station', :description => 'Bus Transfer Station.'},
{:active => 1, :name => 'Elevated Fixed Guideway Station', :description => 'Elevated Fixed Guideway Station.'},
{:active => 1, :name => 'At-Grade Fixed Guideway Station', :description => 'At-Grade Fixed Guideway Station.'},
{:active => 1, :name => 'Underground Fixed Guideway Station', :description => 'Underground Fixed Guideway Station.'},
{:active => 1, :name => 'Simple At-Grade Platform Station', :description => 'Simple At-Grade Platform Station.'},
{:active => 1, :name => 'Surface Parking Lot', :description => 'Surface Parking Lot.'},
{:active => 1, :name => 'Parking Structure', :description => 'Parking Structure.'},
{:active => 1, :name => 'Other Transit Facility', :description => 'Other Transit Facility.'}
]
fta_agency_types = [
{:active => 1, :name => 'Public Agency (Not DOT or Tribal)', :description => 'Public Agency (Not DOT or Tribal).'},
{:active => 1, :name => 'Public Agency (State DOT)', :description => 'Public Agency (State DOT).'},
{:active => 1, :name => 'Public Agency (Tribal)', :description => 'Public Agency (Tribal).'},
{:active => 1, :name => 'Private (Not for profit)', :description => 'Private (Not for profit).'}
]
fta_service_area_types = [
{:active => 1, :name => 'County/Independent city', :description => 'County / Independent city.'},
{:active => 1, :name => 'Multi-county/Independent city', :description => 'Multi-county / Independent city.'},
{:active => 1, :name => 'Multi-state', :description => 'Multi-state.'},
{:active => 1, :name => 'Municipality', :description => 'Municipality.'},
{:active => 1, :name => 'Reservation', :description => 'Reservation.'},
{:active => 1, :name => 'Other', :description => 'Other.'}
]
fta_funding_types = [
{:active => 1, :name => 'Urbanized Area Formula Program', :code => 'UA', :description => 'UA -Urbanized Area Formula Program.'},
{:active => 1, :name => 'Other Federal funds', :code => 'OF', :description => 'OF-Other Federal funds.'},
{:active => 1, :name => 'Non-Federal public funds', :code => 'NFPA', :description => 'NFPA-Non-Federal public funds.'},
{:active => 1, :name => 'Non-Federal private funds', :code => 'NFPE', :description => 'NFPE-Non-Federal private funds.'},
{:active => 1, :name => 'Unknown', :code => 'XX', :description => 'FTA funding type not specified.'}
]
fta_ownership_types = [
# Rural Reporting Ownership Types
{:active => 1, :name => 'Owned by Service Provider', :code => 'OSP', :description => 'Owned by Service Provider.'},
{:active => 1, :name => 'Owned by Public Agency for Service Provider', :code => 'OPA', :description => 'Owned by Public Agency for Service Provider.'},
{:active => 1, :name => 'Leased by Service Provider', :code => 'LSP', :description => 'Leased by Service Provider.'},
{:active => 1, :name => 'Leased by Public Agency for Service Provider', :code => 'LPA', :description => 'Leased by Public Agency for Service Provider.'},
{:active => 1, :name => 'Other', :code => 'OR', :description => 'Other.'},
{:active => 1, :name => 'Unknown', :code => 'XX', :description => 'FTA ownership type not specified.'}
]
fta_vehicle_types = [
# Rural Reporting Types
{:active => 1, :name => 'Automobile', :code => 'AO', :description => 'Automobile.'},
{:active => 1, :name => 'Bus', :code => 'BU', :description => 'Bus.'},
{:active => 1, :name => 'Cutaway', :code => 'CU', :description => 'Cutaway.'},
{:active => 1, :name => 'Ferry Boat', :code => 'FB', :description => 'Ferryboat.'},
{:active => 1, :name => 'Mini Van', :code => 'MV', :description => 'Minivan.'},
{:active => 1, :name => 'Over-The-Road Bus', :code => 'BR', :description => 'Over-The-Road Bus.'},
{:active => 1, :name => 'School Bus', :code => 'SB', :description => 'School Bus.'},
{:active => 1, :name => 'Sports Utility Vehicle', :code => 'SV', :description => 'Sports Utility Vehicle.'},
{:active => 1, :name => 'Van', :code => 'VN', :description => 'Van.'},
{:active => 1, :name => 'Articulated Bus', :code => 'AB', :description => 'Articulated Bus.'},
{:active => 1, :name => 'Double Decker Bus', :code => 'DB', :description => 'Double Decker Bus.'},
{:active => 1, :name => 'Aerial Tramway', :code => 'TR', :description => 'Aerial Tramway.'},
{:active => 1, :name => 'Other', :code => 'OR', :description => 'Other.'},
# Urban Reporting Types
{:active => 1, :name => 'Automated Guideway Vehicle', :code => 'AG', :description => 'Automated Guideway Vehicle.'},
{:active => 1, :name => 'Cable Car', :code => 'CC', :description => 'Cable Car.'},
{:active => 1, :name => 'Heavy Rail Passenger Car', :code => 'HR', :description => 'Heavy Rail Passenger Car.'},
{:active => 1, :name => 'Inclined Plane Vehicle', :code => 'IP', :description => 'Inclined Plane Vehicle.'},
{:active => 1, :name => 'Light Rail Vehicle', :code => 'LR', :description => 'Light Rail Vehicle.'},
{:active => 1, :name => 'Monorail/Automated Guideway', :code => 'MO', :description => 'Monorail/Automated Guideway.'},
{:active => 1, :name => 'Commuter Rail Locomotive', :code => 'RL', :description => 'Commuter Rail Locomotive.'},
{:active => 1, :name => 'Commuter Rail Passenger Coach', :code => 'RP', :description => 'Commuter Rail Passenger Coach.'},
{:active => 1, :name => 'Commuter Rail Self-Propelled Passenger Car', :code => 'RS', :description => 'Commuter Rail Self-Propelled Passenger Car.'},
{:active => 1, :name => 'Trolley Bus', :code => 'TB', :description => 'Trolley Bus.'},
{:active => 1, :name => 'Taxicab Sedan', :code => 'TS', :description => 'Taxicab Sedan.'},
{:active => 1, :name => 'Taxicab Van', :code => 'TV', :description => 'Taxicab Van.'},
{:active => 1, :name => 'Taxicab Station Wagon', :code => 'TW', :description => 'Taxicab Station Wagon.'},
{:active => 1, :name => 'Vintage Trolley/Streetcar',:code => 'VT', :description => 'Vintage Trolley/Streetcar.'},
{:active => 1, :name => 'Unknown', :code => 'XX', :description => 'Vehicle type not specified.'}
]
facility_capacity_types = [
{:active => 1, :name => 'N/A', :description => 'Not applicable.'},
{:active => 1, :name => 'Less than 200 vehicles', :description => 'Less than 200 vehicles.'},
{:active => 1, :name => 'Between 200 and 300 vehicles', :description => 'Between 200 and 300 vehicles.'},
{:active => 1, :name => 'Over 300 vehicles', :description => 'Over 300 vehicles.'}
]
facility_features = [
{:active => 1, :name => 'Moving walkways', :code => 'MW', :description => 'Moving walkways.'},
{:active => 1, :name => 'Ticketing', :code => 'TK', :description => 'Ticketing.'},
{:active => 1, :name => 'Information kiosks', :code => 'IK', :description => 'Information kiosks.'},
{:active => 1, :name => 'Restrooms', :code => 'RR', :description => 'Restrooms.'},
{:active => 1, :name => 'Concessions', :code => 'CS', :description => 'Concessions.'},
{:active => 1, :name => 'Telephones', :code => 'TP', :description => 'Telephones.'},
{:active => 1, :name => 'ATM', :code => 'AT', :description => 'ATM.'},
{:active => 1, :name => 'WIFI', :code => 'WI', :description => 'WIFI.'}
]
leed_certification_types = [
{:active => 1, :name => 'Not Certified', :description => 'Not Certified'},
{:active => 1, :name => 'Certified', :description => 'Certified'},
{:active => 1, :name => 'Silver', :description => 'Silver'},
{:active => 1, :name => 'Gold', :description => 'Gold'},
{:active => 1, :name => 'Platinum', :description => 'Platinum'},
]
district_types = [
{:active => 1, :name => 'State', :description => 'State.'},
{:active => 1, :name => 'District', :description => 'Engineering District.'},
{:active => 1, :name => 'MSA', :description => 'Metropolitan Statistical Area.'},
{:active => 1, :name => 'County', :description => 'County.'},
{:active => 1, :name => 'City', :description => 'City.'},
{:active => 1, :name => 'Borough', :description => 'Borough.'},
{:active => 1, :name => 'MPO/RPO', :description => 'MPO or RPO planning area.'},
{:active => 1, :name => 'Postal Code', :description => 'ZIP Code or Postal Area.'},
{:active => 1, :name => 'UZA', :description => 'Urbanized Area.'}
]
file_content_types = [
{:active => 1, :name => 'Inventory Updates', :class_name => 'TransitInventoryUpdatesFileHandler', :builder_name => "TransitInventoryUpdatesTemplateBuilder", :description => 'Worksheet records updated condition, status, and mileage for existing inventory.'},
{:active => 1, :name => 'Maintenance Updates', :class_name => 'MaintenanceUpdatesFileHandler',:builder_name => "MaintenanceUpdatesTemplateBuilder", :description => 'Worksheet records latest maintenance updates for assets'},
{:active => 1, :name => 'Disposition Updates', :class_name => 'DispositionUpdatesFileHandler', :builder_name => "TransitDispositionUpdatesTemplateBuilder", :description => 'Worksheet contains final disposition updates for existing inventory.'},
{:active => 1, :name => 'New Inventory', :class_name => 'TransitNewInventoryFileHandler', :builder_name => "TransitNewInventoryTemplateBuilder", :description => 'Worksheet records updated condition, status, and mileage for existing inventory.'}
]
maintenance_types = [
{:active => 1, :name => "Oil Change/Filter/Lube", :description => "Oil Change/Filter/Lube"},
{:active => 1, :name => "Standard PM Inspection", :description => "Standard PM Inspection"}
]
service_provider_types = [
{:active => 1, :name => 'Urban', :code => 'URB', :description => 'Operates in an urban area.'},
{:active => 1, :name => 'Rural', :code => 'RUR', :description => 'Operates in a rural area.'},
{:active => 1, :name => 'Shared Ride', :code => 'SHR', :description => 'Provides shared ride services.'},
{:active => 1, :name => 'Intercity Bus', :code => 'ICB', :description => 'Provides intercity bus services.'},
{:active => 1, :name => 'Intercity Rail', :code => 'ICR', :description => 'Provides intercity rail services.'}
]
vehicle_storage_method_types = [
{:active => 1, :name => 'Indoors', :code => 'I', :description => 'Vehicle is always stored indoors.'},
{:active => 1, :name => 'Outdoors', :code => 'O', :description => 'Vehicle is always stored outdoors.'},
{:active => 1, :name => 'Indoor/Outdoor', :code => 'B', :description => 'Vehicle is stored both indoors and outdoors.'},
{:active => 1, :name => 'Unknown',:code => 'X', :description => 'Vehicle storage method not supplied.'}
]
maintenance_provider_types = [
{:active => 1, :name => 'Self Maintained', :code => 'SM', :description => 'Self Maintained.'},
{:active => 1, :name => 'County', :code => 'CO', :description => 'County.'},
{:active => 1, :name => 'Public Agency', :code => 'PA', :description => 'Public Agency.'},
{:active => 1, :name => 'Private Entity', :code => 'PE', :description => 'Private Entity.'},
{:active => 1, :name => 'Unknown', :code => 'XX', :description => 'Maintenance provider not supplied.'}
]
organization_types = [
{:active => 1, :name => 'Grantor', :class_name => "Grantor", :display_icon_name => "fa fa-usd", :map_icon_name => "redIcon", :description => 'Organizations who manage funding grants.', :roles => 'guest,manager'},
{:active => 1, :name => 'Transit Operator', :class_name => "TransitOperator", :display_icon_name => "fa fa-bus", :map_icon_name => "greenIcon", :description => 'Transit Operator.', :roles => 'guest,user,transit_manager'},
{:active => 1, :name => 'Planning Partner', :class_name => "PlanningPartner", :display_icon_name => "fa fa-group", :map_icon_name => "purpleIcon", :description => 'Organizations who need visibility into grantee assets for planning purposes.', :roles => 'guest'}
]
governing_body_types = [
{:active => 1, :name => 'Corporate Board of Directors', :description => 'Corporate Board of Directors'},
{:active => 1, :name => 'Authority Board', :description => 'Board of Directors'},
{:active => 1, :name => 'County', :description => 'County'},
{:active => 1, :name => 'City', :description => 'City'},
{:active => 1, :name => 'Other', :description => 'Other Governing Body'}
]
replace_tables = %w{ asset_types fuel_types vehicle_features vehicle_usage_codes vehicle_rebuild_types fta_mode_types fta_bus_mode_types fta_agency_types fta_service_area_types
fta_service_types fta_funding_types fta_ownership_types fta_vehicle_types facility_capacity_types
facility_features leed_certification_types district_types maintenance_provider_types file_content_types service_provider_types organization_types maintenance_types
vehicle_storage_method_types fta_facility_types governing_body_types
}
replace_tables.each do |table_name|
puts " Loading #{table_name}"
if is_mysql
ActiveRecord::Base.connection.execute("TRUNCATE TABLE #{table_name};")
elsif is_sqlite
ActiveRecord::Base.connection.execute("DELETE FROM #{table_name};")
else
ActiveRecord::Base.connection.execute("TRUNCATE #{table_name} RESTART IDENTITY;")
end
data = eval(table_name)
klass = table_name.classify.constantize
data.each do |row|
x = klass.new(row)
x.save!
end
end
table_name = 'asset_subtypes'
puts " Loading #{table_name}"
if is_mysql
ActiveRecord::Base.connection.execute("TRUNCATE TABLE #{table_name};")
elsif is_sqlite
ActiveRecord::Base.connection.execute("DELETE FROM #{table_name};")
else
ActiveRecord::Base.connection.execute("TRUNCATE #{table_name} RESTART IDENTITY;")
end
data = eval(table_name)
data.each do |row|
x = AssetSubtype.new(row.except(:belongs_to, :type))
x.asset_type = AssetType.where(:name => row[:type]).first
x.save!
end
require_relative File.join("seeds", 'team_ali_code_seeds') # TEAM ALI Codes are seeded from a separate file
# See if we need to load the rail/locomotive seed data
if Rails.application.config.transam_transit_rail == true
require_relative File.join("seeds", 'rail.seeds') # Rail assets are seeded from a separate file
end
# These tables are merged with core tables
roles = [
{:privilege => false, :name => 'transit_manager', :weight => 5},
{:privilege => true, :name => 'director_transit_operations'},
{:privilege => true, :name => 'ntd_contact'}
]
asset_event_types = [
{:active => 1, :name => 'Mileage', :display_icon_name => "fa fa-road", :description => 'Mileage Update', :class_name => 'MileageUpdateEvent', :job_name => 'AssetMileageUpdateJob'},
{:active => 1, :name => 'Operations metrics', :display_icon_name => "fa fa-calculator", :description => 'Operations Update',:class_name => 'OperationsUpdateEvent', :job_name => 'AssetOperationsUpdateJob'},
{:active => 1, :name => 'Facility operations metrics', :display_icon_name => "fa fa-calculator", :description => 'Facility Operations Update',:class_name => 'FacilityOperationsUpdateEvent', :job_name => 'AssetFacilityOperationsUpdateJob'},
{:active => 1, :name => 'Vehicle use metrics', :display_icon_name => "fa fa-line-chart", :description => 'Vehicle Usage Update', :class_name => 'VehicleUsageUpdateEvent', :job_name => 'AssetVehicleUsageUpdateJob'},
{:active => 1, :name => 'Storage method', :display_icon_name => "fa fa-star-half-o", :description => 'Storage Method', :class_name => 'StorageMethodUpdateEvent', :job_name => 'AssetStorageMethodUpdateJob'},
{:active => 1, :name => 'Usage codes', :display_icon_name => "fa fa-star-half-o", :description => 'Usage Codes', :class_name => 'UsageCodesUpdateEvent', :job_name => 'AssetUsageCodesUpdateJob'},
{:active => 1, :name => 'Maintenance provider type', :display_icon_name => "fa fa-cog", :description => 'Maintenance Provider', :class_name => 'MaintenanceProviderUpdateEvent', :job_name => 'AssetMaintenanceProviderUpdateJob'}
]
condition_estimation_types = [
{:active => 1, :name => 'TERM', :class_name => 'TermEstimationCalculator', :description => 'Asset condition is estimated using FTA TERM approximations.'}
]
report_types = [
{:active => 1, :name => 'Planning Report', :display_icon_name => "fa fa-line-chart", :description => 'Planning Report.'},
]
service_life_calculation_types = [
{:active => 1, :name => 'Age and Mileage', :class_name => 'ServiceLifeAgeAndMileage', :description => 'Calculate the replacement year based on the age or mileage conditions both being met.'},
{:active => 1, :name => 'Age or Mileage', :class_name => 'ServiceLifeAgeOrMileage', :description => 'Calculate the replacement year based on either the age of the asset or mileage conditions being met.'},
{:active => 1, :name => 'Age and Mileage and Condition', :class_name => 'ServiceLifeAgeAndMileageAndCondition', :description => 'Calculate the replacement year based on all of the age and condition and mileage conditions being met.'},
{:active => 1, :name => 'Age or Mileage or Condition', :class_name => 'ServiceLifeAgeOrMileageOrCondition', :description => 'Calculate the replacement year based on any of the age and condition and mileage conditions being met.'},
{:active => 1, :name => 'Condition and Mileage', :class_name => 'ServiceLifeConditionAndMileage', :description => 'Calculate the replacement year based on both the asset and mileage conditions both being met.'},
{:active => 1, :name => 'Condition or Mileage', :class_name => 'ServiceLifeConditionOrMileage', :description => 'Calculate the replacement year based on either of the asset and mileage conditions being met.'}
]
merge_tables = %w{ roles asset_event_types condition_estimation_types service_life_calculation_types report_types }
merge_tables.each do |table_name|
puts " Merging #{table_name}"
data = eval(table_name)
klass = table_name.classify.constantize
data.each do |row|
x = klass.new(row)
x.save!
end
end
puts " Merging asset_subsystems"
asset_subsystems = [
{:name => "Transmission", :code => "TR", :asset_type => "Vehicle"},
{:name => "Engine", :code => "EN", :asset_type => "Vehicle"},
{:name => "Trucks", :code => "TR", :asset_type => "RailCar"},
{:name => "Trucks", :code => "TR", :asset_type => "Locomotive"}
]
asset_subsystems.each do |s|
subsystem = AssetSubsystem.new(:name => s[:name], :description => s[:name], :active => true, :code => s[:code])
asset_type = AssetType.find_by(name: s[:asset_type])
subsystem.asset_type = asset_type
subsystem.save
end
puts "======= Processing TransAM Transit Reports ======="
reports = [
{:active => 1, :belongs_to => 'report_type', :type => "Inventory Report",
:name => 'Useful Life Consumed Report',
:class_name => "ServiceLifeConsumedReport",
:view_name => "generic_chart",
:show_in_nav => 1,
:show_in_dashboard => 0,
:roles => 'guest,user',
:description => 'Displays a summary of the amount of useful life that has been consumed as a percentage of all assets.',
:chart_type => 'column',
:chart_options => "{is3D : true, isStacked: true, fontSize: 10, hAxis: {title: 'Percent of expected useful life consumed'}, vAxis: {title: 'Share of all assets'}}"},
{:active => 1, :belongs_to => 'report_type', :type => "Inventory Report",
:name => 'Asset Condition Report',
:class_name => "AssetConditionReport",
:view_name => "generic_chart",
:show_in_nav => 1,
:show_in_dashboard => 0,
:roles => 'guest,user',
:description => 'Displays asset counts by condition.',
:chart_type => 'pie',
:chart_options => '{is3D : true}'},
{:active => 1, :belongs_to => 'report_type', :type => "Inventory Report",
:name => 'Asset Subtype Report',
:class_name => "AssetSubtypeReport",
:view_name => "generic_chart",
:show_in_nav => 1,
:show_in_dashboard => 0,
:roles => 'guest,user',
:description => 'Displays asset counts by subtypes.',
:chart_type => 'pie',
:chart_options => '{is3D : true}'},
{:active => 1, :belongs_to => 'report_type', :type => "Inventory Report",
:name => 'Asset Age Report',
:class_name => "AssetAgeReport",
:view_name => "generic_chart",
:show_in_nav => 1,
:show_in_dashboard => 0,
:roles => 'guest,user',
:description => 'Displays asset counts by age.',
:chart_type => 'column',
:chart_options => "{is3D : true, isStacked : true, hAxis: {title: 'Age (years)'}, vAxis: {title: 'Count'}}"},
{:active => 1, :belongs_to => 'report_type', :type => "Capital Needs Report",
:name => 'Backlog Report',
:class_name => "BacklogReport",
:view_name => "generic_report",
:show_in_nav => 1,
:show_in_dashboard => 0,
:roles => 'guest,user',
:description => 'Determines backlog needs.'},
{:active => 1, :belongs_to => 'report_type', :type => "Inventory Report",
:name => 'Asset Type by Org Report',
:class_name => "CustomSqlReport",
:view_name => "generic_report_table",
:show_in_nav => 0,
:show_in_dashboard => 0,
:roles => 'guest,user',
:description => 'Displays a summary of asset types by agency.',
:custom_sql => "SELECT c.short_name AS 'Org', b.name AS 'Type', COUNT(*) AS 'Count' FROM assets a LEFT JOIN asset_subtypes b ON a.asset_subtype_id = b.id LEFT JOIN organizations c ON a.organization_id = c.id GROUP BY a.organization_id, a.asset_subtype_id ORDER BY c.short_name, b.name"},
{:active => 1, :belongs_to => 'report_type', :type => "Planning Report",
:name => 'Vehicle Replacement Report',
:class_name => "VehicleReplacementReport",
:view_name => "vehicle_replacement_report",
:show_in_nav => 1,
:show_in_dashboard => 0,
:roles => 'guest,user',
:description => 'Reports the list of vehicles scheduled to be replaced.'},
{:active => 1, :belongs_to => 'report_type', :type => "Planning Report",
:name => 'State of Good Repair Report',
:class_name => "StateOfGoodRepairReport",
:view_name => "state_of_good_repair_report",
:show_in_nav => 1,
:show_in_dashboard => 0,
:roles => 'guest,user',
:description => 'Reports an agency\'s current State of Good Repair.'},
{:active => 1, :belongs_to => 'report_type', :type => "Planning Report",
:name => 'Disposition Report',
:class_name => "AssetDispositionReport",
:view_name => "asset_disposition_report",
:show_in_nav => 1,
:show_in_dashboard => 0,
:roles => 'guest,user',
:description => 'Reports Vehicles which have been disposed.'}
]
table_name = 'reports'
puts " Merging #{table_name}"
data = eval(table_name)
data.each do |row|
puts "Creating Report #{row[:name]}"
x = Report.new(row.except(:belongs_to, :type))
x.report_type = ReportType.find_by(:name => row[:type])
x.save!
end
|
require 'tic_tac_toe/human'
require 'tic_tac_toe/game'
module TicTacToe
class ConsoleShell
attr_reader :game
def self.new_shell(console)
game = TicTacToe::Game.new_game(TicTacToe::Board.empty_board)
player = TicTacToe::Human.new
TicTacToe::ConsoleShell.new(console, game, player)
end
def initialize(console, game, player)
@console, @game, @player = console, game, player
player.set_shell(self)
end
def main_loop
show_welcome_message
loop do
game.set_players(*choose_players)
game_loop
break unless play_again?
game.reset
end
end
def game_loop
while not game.finished?
do_turn
end
display_winner(game.who_won?)
end
def do_turn
show_move_message
show_board(game.board)
moved = false
current_player = game.players[game.current_mark]
while not moved
begin
game.move(index: current_player.get_move(game.board))
moved = true
rescue ArgumentError
show_illegal_move_message
end
end
end
def prompt_move
@console.print "Enter your move [0-8]: "
@console.flush
@console.gets.chomp
end
def prompt_player(mark)
@console.print "Who should play #{mark}'s ([h]uman, [r]andom or [a]i)? "
@console.flush
@console.gets.chomp
end
def yn_to_bool(input)
case input.downcase
when "y", "yes"
true
when "n", "no"
false
end
end
def play_again?
@console.print "Would you like to play again? "
@console.flush
yn_to_bool(@console.gets.chomp)
end
def try_again
@console.puts "Please try again."
end
def show_move_error_message
@console.puts "Sorry, I didn't understand your move."
try_again
end
def show_invalid_move_message
@console.puts "That is not a valid move choice."
try_again
end
def show_illegal_move_message
@console.puts "That move has already been played."
try_again
end
def show_move_message
@console.puts "\nIt is the #{game.current_mark}'s move."
end
def show_board(board)
@console.puts board
@console.puts
end
def show_welcome_message
@console.puts "Welcome to Tic Tac Toe!"
end
def display_winner(winner_mark)
show_board(game.board)
if winner_mark
@console.puts "The #{winner_mark}'s win!"
else
@console.puts "It was a draw."
end
end
def get_human
@player
end
def get_player(mark, other_mark)
loop do
case prompt_player(mark)
when "h", "human"
return @player
when "r", "random"
return TicTacToe::AI::Random.new(Random.new)
when "a", "ai"
return TicTacToe::AI::Minimax.new(mark, other_mark)
end
end
end
def choose_players
[get_player(TicTacToe::Game::X,
TicTacToe::Game::O),
get_player(TicTacToe::Game::O,
TicTacToe::Game::X)]
end
end
end
Move IO methods to the bottom
require 'tic_tac_toe/human'
require 'tic_tac_toe/game'
module TicTacToe
class ConsoleShell
attr_reader :game
def self.new_shell(console)
game = TicTacToe::Game.new_game(TicTacToe::Board.empty_board)
player = TicTacToe::Human.new
TicTacToe::ConsoleShell.new(console, game, player)
end
def initialize(console, game, player)
@console, @game, @player = console, game, player
player.set_shell(self)
end
def main_loop
show_welcome_message
loop do
game.set_players(*choose_players)
game_loop
break unless play_again?
game.reset
end
end
def game_loop
while not game.finished?
do_turn
end
display_winner(game.who_won?)
end
def do_turn
show_move_message
show_board(game.board)
moved = false
current_player = game.players[game.current_mark]
while not moved
begin
game.move(index: current_player.get_move(game.board))
moved = true
rescue ArgumentError
show_illegal_move_message
end
end
end
def get_human
@player
end
def get_player(mark, other_mark)
loop do
case prompt_player(mark)
when "h", "human"
return @player
when "r", "random"
return TicTacToe::AI::Random.new(Random.new)
when "a", "ai"
return TicTacToe::AI::Minimax.new(mark, other_mark)
end
end
end
def choose_players
[get_player(TicTacToe::Game::X,
TicTacToe::Game::O),
get_player(TicTacToe::Game::O,
TicTacToe::Game::X)]
end
########################################
## I/O Methods
########################################
def prompt_move
@console.print "Enter your move [0-8]: "
@console.flush
@console.gets.chomp
end
def prompt_player(mark)
@console.print "Who should play #{mark}'s ([h]uman, [r]andom or [a]i)? "
@console.flush
@console.gets.chomp
end
def yn_to_bool(input)
case input.downcase
when "y", "yes"
true
when "n", "no"
false
end
end
def play_again?
@console.print "Would you like to play again? "
@console.flush
yn_to_bool(@console.gets.chomp)
end
def try_again
@console.puts "Please try again."
end
def show_move_error_message
@console.puts "Sorry, I didn't understand your move."
try_again
end
def show_invalid_move_message
@console.puts "That is not a valid move choice."
try_again
end
def show_illegal_move_message
@console.puts "That move has already been played."
try_again
end
def show_move_message
@console.puts "\nIt is the #{game.current_mark}'s move."
end
def show_board(board)
@console.puts board
@console.puts
end
def show_welcome_message
@console.puts "Welcome to Tic Tac Toe!"
end
def display_winner(winner_mark)
show_board(game.board)
if winner_mark
@console.puts "The #{winner_mark}'s win!"
else
@console.puts "It was a draw."
end
end
end
end
|
begin
require 'freebox_api'
require 'inifile'
rescue
Puppet.warning "You need freebox_api gem to manage Freebox OS with this provider."
end
Puppet::Type.type(:freebox_dhcp_lease).provide(:bindings) do
def self.app_token
ini = IniFile.load('/etc/puppet/freebox.conf')
section = ini['mafreebox.free.fr']
section['app_token']
end
def self.instances
FreeboxApi::Resources::DhcpLease.instances('fr.freebox.puppet', self.app_token).collect do |dhcp_lease|
# initialize @property_hash
new(
:name => dhcp_lease.id,
:ensure => :present,
:mac => dhcp_lease.mac,
:comment => dhcp_lease.comment,
:hostname => dhcp_lease.hostname,
:ip => dhcp_lease.ip
)
end
end
def self.prefetch(resources)
dhcp_leases = instances
resources.keys.each do |name|
if provider = dhcp_leases.find{ |dhcp_lease| dhcp_lease.name == name }
resources[name].provider = provider
end
end
end
def exists?
@property_hash[:ensure] == :present
end
def create
# TODO
end
def destroy
# TODO
end
def initialize(value={})
super(value)
@property_flush = {}
end
def mac
@property_hash[:mac]
end
def mac=(value)
@property_flush[:mac] = value
end
def comment
@property_hash[:comment]
end
def comment=(value)
@property_flush[:comment] = value
end
def hostname
@property_hash[:hostname]
end
def hostname=(value)
@property_flush[:hostname] = value
end
def ip
@property_hash[:ip]
end
def ip=(value)
@property_flush[:ip] = value
end
def flush
# TODO
end
end
Use new freebox_api version
begin
require 'freebox_api'
require 'inifile'
rescue
Puppet.warning "You need freebox_api gem to manage Freebox OS with this provider."
end
Puppet::Type.type(:freebox_dhcp_lease).provide(:bindings) do
def self.app_token
ini = IniFile.load('/etc/puppet/freebox.conf')
section = ini['mafreebox.free.fr']
section['app_token']
end
def self.instances
FreeboxApi.app_id = 'fr.freebox.puppet'
FreeboxApi.app_token = self.app_token
FreeboxApi::Resources::DhcpLease.instances.collect do |dhcp_lease|
# initialize @property_hash
new(
:name => dhcp_lease['id'],
:ensure => :present,
:mac => dhcp_lease['mac'],
:comment => dhcp_lease['comment'],
:hostname => dhcp_lease['hostname'],
:ip => dhcp_lease['ip']
)
end
end
def self.prefetch(resources)
dhcp_leases = instances
resources.keys.each do |name|
if provider = dhcp_leases.find{ |dhcp_lease| dhcp_lease.name == name }
resources[name].provider = provider
end
end
end
def exists?
@property_hash[:ensure] == :present
end
def create
myHash = {}
if @property_flush
(myHash[:id] = resource[:name]) if @property_flush[:name]
(myHash[:mac] = resource[:mac]) if @property_flush[:mac]
(myHash[:comment] = resource[:comment]) if @property_flush[:comment]
(myHash[:hostname] = resource[:hostname]) if @property_flush[:hostname]
(myHash[:ip] = resource[:ip]) if @property_flush[:ip]
unless myHash.empty?
FreeboxApi::Resources::DhcpLease.create(myHash)
end
end
@property_hash = resource.to_hash
end
def destroy
FreeboxApi::Resources::DhcpLease.destroy(resource[:name])
end
def initialize(value={})
super(value)
@property_flush = {}
end
def mac
@property_hash[:mac]
end
def mac=(value)
@property_flush[:mac] = value
end
def comment
@property_hash[:comment]
end
def comment=(value)
@property_flush[:comment] = value
end
def hostname
@property_hash[:hostname]
end
def hostname=(value)
@property_flush[:hostname] = value
end
def ip
@property_hash[:ip]
end
def ip=(value)
@property_flush[:ip] = value
end
def flush
myHash = {}
if @property_flush
(myHash[:mac] = resource[:mac]) if @property_flush[:mac]
(myHash[:comment] = resource[:comment]) if @property_flush[:comment]
(myHash[:hostname] = resource[:hostname]) if @property_flush[:hostname]
(myHash[:ip] = resource[:ip]) if @property_flush[:ip]
unless myHash.empty?
FreeboxApi::Resources::DhcpLease.update(myHash)
end
end
@property_hash = resource.to_hash
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.