CombinedText
stringlengths
4
3.42M
module SvnCommandHelper # version VERSION = "0.5.0" end Bump to 0.6.0 module SvnCommandHelper # version VERSION = "0.6.0" end
module Tablebuilder class Column attr_accessor :column, :header, :content, :context def render_header if @header.nil? @context.t(".#{@column}") else call_or_output(@header) end end def render_content(object) if @content.nil? object.send @column else call_or_output(@content, object) end end private def call_or_output(target, *opts) if target.respond_to? :call @context.capture(*opts) do |object| result = target.call(*opts) @context.concat result if @context.output_buffer.empty? end else target.to_s end end end class TableBuilder include ActionView::Helpers::TagHelper attr_accessor :output_buffer def initialize(model_list, context, options) @model_list = model_list @context = context @options = options @columns = [] end def column(column, options = {}, &block) col = Column.new col.context = @context col.column = column col.content = block || options[:content] col.header = options[:header] @columns << col end def render_table content_tag :table do render_thead + render_tbody end end private def render_thead content_tag :tr do @columns.map do |column| content_tag :th do column.render_header end end.join.html_safe end end def render_tbody content_tag :tbody do @model_list.map do |object| content_tag :tr do @columns.map do |column| content_tag :td, column.render_content(object) end.join.html_safe end end.join.html_safe end end end end Add odd and even classes to table row tags module Tablebuilder class Column attr_accessor :column, :header, :content, :context def render_header if @header.nil? @context.t(".#{@column}") else call_or_output(@header) end end def render_content(object) if @content.nil? object.send @column else call_or_output(@content, object) end end private def call_or_output(target, *opts) if target.respond_to? :call @context.capture(*opts) do |object| result = target.call(*opts) @context.concat result if @context.output_buffer.empty? end else target.to_s end end end class TableBuilder include ActionView::Helpers::TagHelper attr_accessor :output_buffer def initialize(model_list, context, options) @model_list = model_list @context = context @options = options @columns = [] end def column(column, options = {}, &block) col = Column.new col.context = @context col.column = column col.content = block || options[:content] col.header = options[:header] @columns << col end def render_table content_tag :table do render_thead + render_tbody end end private def render_thead content_tag :tr do @columns.map do |column| content_tag :th do column.render_header end end.join.html_safe end end def render_tbody content_tag :tbody do @model_list.map do |object| content_tag :tr, :class => @context.cycle("odd", "even", :name => "_tablebuilder_row") do @columns.map do |column| content_tag :td, column.render_content(object) end.join.html_safe end end.join.html_safe end end end end
#!/usr/bin/env ruby require 'optparse' require_relative "../../lib/tachiban/policy_generator/policy_generator.rb" options = {} optparse = OptionParser.new do |opts| opts.banner = "\nHanami authorization policy generator Usage: tachiban -n myapp -p user Flags: \n" opts.on("-n", "--app_name APP", "Specify the application name for the policy") do |app_name| options[:app_name] = app_name end opts.on("-p", "--policy POLICY", "Specify the policy name") do |policy| options[:policy] = policy end opts.on("-h", "--help", "Displays help") do puts opts exit end end begin optparse.parse! puts "Add flag -h or --help to see usage instructions." if options.empty? mandatory = [:app_name, :policy] missing = mandatory.select{ |arg| options[arg].nil? } unless missing.empty? raise OptionParser::MissingArgument.new(missing.join(', ')) end rescue OptionParser::InvalidOption, OptionParser::MissingArgument puts $!.to_s puts optparse exit end puts "Performing task with options: #{options.inspect}" generate_policy("#{options[:app_name]}", "#{options[:policy]}") if options[:policy] gemspec modification #!/usr/bin/env ruby require 'optparse' require_relative "../lib/tachiban/policy_generator/policy_generator.rb" options = {} optparse = OptionParser.new do |opts| opts.banner = "\nHanami authorization policy generator Usage: tachiban -n myapp -p user Flags: \n" opts.on("-n", "--app_name APP", "Specify the application name for the policy") do |app_name| options[:app_name] = app_name end opts.on("-p", "--policy POLICY", "Specify the policy name") do |policy| options[:policy] = policy end opts.on("-h", "--help", "Displays help") do puts opts exit end end begin optparse.parse! puts "Add flag -h or --help to see usage instructions." if options.empty? mandatory = [:app_name, :policy] missing = mandatory.select{ |arg| options[arg].nil? } unless missing.empty? raise OptionParser::MissingArgument.new(missing.join(', ')) end rescue OptionParser::InvalidOption, OptionParser::MissingArgument puts $!.to_s puts optparse exit end puts "Performing task with options: #{options.inspect}" generate_policy("#{options[:app_name]}", "#{options[:policy]}") if options[:policy]
namespace :avalon do namespace :ualbertalib do desc "Given a set of MediaObject IDs, in a file, one-per-line, update visibility to 'restricted'" task :visibility_restricted => :environment do options = {:commit => false} option_parser = OptionParser.new do |opts| opts.banner = "Usage: rake avalon:ualbertalib:visibility_restricted [options]" opts.on("-c", "--commit", "Commit change; override default dry-run") { options[:commit] = true } opts.on("-m ARG", "--media_objects", "File containing list of MediaObject IDs, one per line") { |filename| options[:filename] = filename } opts.on("-h", "--help") do puts opts exit end end # return `ARGV` with the intended arguments args = option_parser.order!(ARGV) {} option_parser.parse!(args) if options[:commit] puts "Committing changes" else puts "Executing a 'dry-run' (no changes commited); use '-c' to save the change." end if options[:filename].nil? puts "Manditory argument: -m filename" puts option_parser.help exit 1 elsif !File.exist?(options[:filename]) puts "Filename not found: #{options[:filename]}" exit 1 end mediaobject_ids = File.read(options[:filename]).split count = 0 count_success = 0 mediaobject_ids.each do |id| begin count += 1 obj = MediaObject.find(id) old_visibility = obj.visibility obj.visibility = 'restricted' if obj.valid? obj.save! if options[:commit] # default to dry-run unless commit specified puts "[success] old:[#{old_visibility}] new:[#{obj.visibility}] id:[#{obj.id}]" count_success += 1 else puts "[fail] old:[#{old_visibility}] new:[#{obj.visibility}] id:[#{obj.id}]" raise StandardError, "validation failure on id: #{id}, visibility change not saved" end rescue StandardError => e puts "Error: %s - %s - %s" % [id, e.class.name, e.message] end end puts "Number processed: [#{count}]; success: [#{count_success}]" if count == 0 puts "You must specify an set of MediaObject IDs." puts option_parser.help exit 1 end end desc "Return a list of collections: id's and labels" task :list_collections => :environment do Admin::Collection.all.to_a.collect.each do |collection| puts "[%s] %s" % [collection.id, collection.name] end end desc "Given a single collection ID, return a list of collection members" task :list_collection_members => :environment do options = {} option_parser = OptionParser.new do |opts| opts.on("-c=ARG", "--collection_id=ARG", "collection id") { |id| options[:id] = id } end args = option_parser.order!(ARGV) {} option_parser.parse!(args) if options[:id].nil? puts "Manditory argument: -c id" puts option_parser.help exit 1 end obj = ActiveFedora::Base.find(options[:id]) if (obj.is_a?(Admin::Collection)) obj.media_objects.to_a.collect.each do |m| puts "%s" % [m.id] end; else puts "ERROR: not a Collection obj: [%s]" % [options[:id]] end end desc "Given a set of IDs, in a file, one-per-line, export contents" task :export_contents => :environment do options = {} option_parser = OptionParser.new do |opts| opts.on("-m=ARG", "--objects=ARG", "File containing list of object IDs, one per line") { |filename| options[:filename] = filename } opts.on("-d=ARG", "--derivatives=ARG", "Base directory of the derivatives") { |stream_base_dir| options[:stream_base_dir] = stream_base_dir } opts.on("-b=ARG", "--dest_base=ARG", "Output directory") { |dest_base_dir| options[:dest_base_dir] = dest_base_dir } opts.on("-s=ARG", "--delay=ARG", "Delay between exports") { |delay| options[:delay] = delay ? delay.to_i : 0 } opts.on("-h", "--help") do puts opts exit end end args = option_parser.order!(ARGV) {} option_parser.parse!(args) if options[:filename].nil? puts "Manditory argument: -m filename" puts option_parser.help exit 1 elsif !File.exist?(options[:filename]) puts "Filename not found: #{options[:filename]}" exit 1 end ids = File.read(options[:filename]).split count = 0 count_success = 0 ids.each do |id| begin count += 1 obj = ActiveFedora::Base.find(id) if (obj.is_a?(MediaObject)) ualberta_export_mediaObject(obj, options) elsif (obj.is_a?(Admin::Collection)) ualberta_export_collectionObject(obj, options) end count_success += 1 sleep(options[:delay]) if (options[:delay]) rescue StandardError => e puts "ERROR: %s - %s - %s" % [id, e.class.name, e.message] puts e.backtrace end end puts "Number processed: [#{count}]; success: [#{count_success}]" if count == 0 puts "You must specify an set of MediaObject IDs." puts option_parser.help exit 1 end end def ualberta_export_collectionObject( obj, options ) base_dir = File.join(options[:dest_base_dir], obj.id) FileUtils.mkdir_p(base_dir) File.open("#{base_dir}/collection_object.json", 'w') { |file| file.write(obj.as_json.to_json(:except => :captions)) } end def ualberta_export_mediaObject( obj, options ) base_dir = File.join(options[:dest_base_dir], obj.collection_id, "MediaObjects", obj.id) FileUtils.mkdir_p(base_dir) File.open("#{base_dir}/media_object.json", 'w') { |file| file.write(obj.as_json.to_json(:except => :captions)) } File.open("#{base_dir}/mods.xml", 'w:BINARY') { |file| file.write(obj.descMetadata.content) } obj.ordered_master_files.to_a.collect.each do |mf| ualberta_export_masterFile(mf, base_dir, options) end end def ualberta_export_masterFile ( mf, base_dir, options ) mf_base_dir = File.join(base_dir, "media_files", mf.id) FileUtils.mkdir_p(mf_base_dir) File.open("#{mf_base_dir}/media_file.json", 'w') { |file| file.write(mf.to_json) } File.open("#{mf_base_dir}/structural_metadata.xml", 'w') { |file| file.write(mf.structuralMetadata.content) } original_base_dir = File.join(mf_base_dir, "original_media_file") if File.file?(mf.file_location) FileUtils.mkdir_p(original_base_dir) FileUtils.cp(mf.file_location, "#{original_base_dir}/") else # mf.file_location may be outdated (i.e., moved outside Avalon) # search for file in other directories # log: if media doesn't exist or has been moved glob = Dir.glob("#{ENV['SETTINGS__DROPBOX__PATH']}/**/#{File.basename(mf.file_location)}") puts "ERROR: [%s] media file not found: [%s] for Object [%s]" % [mf.id, mf.file_location, mf.media_object_id] if glob.empty? # assumption: every media file should have a unique name otherwise this fails and fails by reporting 2+ items # log: if multiple files of the same name found but don't change execution path as there could be a legitemate reason puts "ERROR: [%s] stored media file path outdated: multiple media files found with name [%s]" % [mf.id, File.basename(mf.file_location) ] if glob.count > 1 glob.each do |file| FileUtils.mkdir_p(original_base_dir) FileUtils.cp(file, "#{original_base_dir}/") puts "INFO: [%s] stored media file path outdated [%s] -- using alternaive [%s]" % [mf.id, mf.file_location, file] end end mf.derivatives.to_a.collect.each do |derivative| derivative_base_dir = File.join(mf_base_dir,"derivatives","#{derivative.quality}_#{derivative.id}") FileUtils.mkdir_p(derivative_base_dir) File.open("#{derivative_base_dir}/derivative.json", 'w') { |file| file.write(derivative.to_json) } # locate the derivative file and export # derivative files are stored on the streaming server; UAL mounts this filesystem on the app server as well # parse streaming server path to translate into a valid app server path # start with the derivativeFile path and parse the last two subdirectories along with the filename if (File.exists?(tmp_path = File.join(options[:stream_base_dir], derivative.derivativeFile.split(File::SEPARATOR)[4..-1]))) FileUtils.cp(tmp_path, derivative_base_dir) end end if mf.captions.has_content? caption_base_dir = File.join(mf_base_dir, "captions") FileUtils.mkdir_p(caption_base_dir) File.open("#{caption_base_dir}/#{mf.captions.original_name}", 'w:BINARY') { |file| file.write(mf.captions.content) } end if mf.poster.has_content? poster_base_dir = File.join(mf_base_dir,"poster") FileUtils.mkdir_p(poster_base_dir) File.open("#{poster_base_dir}/#{mf.poster.original_name}", 'w:BINARY') { |file| file.write(mf.poster.content) } end if mf.thumbnail.has_content? thumbnail_base_dir = File.join(mf_base_dir,"thumbnail") FileUtils.mkdir_p(thumbnail_base_dir) File.open("#{thumbnail_base_dir}/#{mf.thumbnail.original_name}", 'w:BINARY') { |file| file.write(mf.thumbnail.content) } end end end end Apply suggestions from code review Co-authored-by: Tricia Jenkins <d580280e50b7302c03ddd30b2da59831536473c9@gmail.com> namespace :avalon do namespace :ualbertalib do desc "Given a set of MediaObject IDs, in a file, one-per-line, update visibility to 'restricted'" task :visibility_restricted => :environment do options = {:commit => false} option_parser = OptionParser.new do |opts| opts.banner = "Usage: rake avalon:ualbertalib:visibility_restricted [options]" opts.on("-c", "--commit", "Commit change; override default dry-run") { options[:commit] = true } opts.on("-m ARG", "--media_objects", "File containing list of MediaObject IDs, one per line") { |filename| options[:filename] = filename } opts.on("-h", "--help") do puts opts exit end end # return `ARGV` with the intended arguments args = option_parser.order!(ARGV) {} option_parser.parse!(args) if options[:commit] puts "Committing changes" else puts "Executing a 'dry-run' (no changes commited); use '-c' to save the change." end if options[:filename].nil? puts "Manditory argument: -m filename" puts option_parser.help exit 1 elsif !File.exist?(options[:filename]) puts "Filename not found: #{options[:filename]}" exit 1 end mediaobject_ids = File.read(options[:filename]).split count = 0 count_success = 0 mediaobject_ids.each do |id| begin count += 1 obj = MediaObject.find(id) old_visibility = obj.visibility obj.visibility = 'restricted' if obj.valid? obj.save! if options[:commit] # default to dry-run unless commit specified puts "[success] old:[#{old_visibility}] new:[#{obj.visibility}] id:[#{obj.id}]" count_success += 1 else puts "[fail] old:[#{old_visibility}] new:[#{obj.visibility}] id:[#{obj.id}]" raise StandardError, "validation failure on id: #{id}, visibility change not saved" end rescue StandardError => e puts "Error: %s - %s - %s" % [id, e.class.name, e.message] end end puts "Number processed: [#{count}]; success: [#{count_success}]" if count == 0 puts "You must specify an set of MediaObject IDs." puts option_parser.help exit 1 end end desc "Return a list of collections: id's and labels" task :list_collections => :environment do Admin::Collection.all.to_a.collect.each do |collection| puts "[%s] %s" % [collection.id, collection.name] end end desc "Given a single collection ID, return a list of collection members" task :list_collection_members => :environment do options = {} option_parser = OptionParser.new do |opts| opts.on("-c=ARG", "--collection_id=ARG", "collection id") { |id| options[:id] = id } end args = option_parser.order!(ARGV) {} option_parser.parse!(args) if options[:id].nil? puts "Manditory argument: -c id" puts option_parser.help exit 1 end obj = Admin::Collection.find(options[:id]) obj.media_objects.each do |m| puts m.id end rescue ActiveRecord::RecordNotFound puts "ERROR: not a Collection obj: #{options[:id]}" end desc "Given a set of IDs, in a file, one-per-line, export contents" task :export_contents => :environment do options = {} option_parser = OptionParser.new do |opts| opts.on("-m=ARG", "--objects=ARG", "File containing list of object IDs, one per line") { |filename| options[:filename] = filename } opts.on("-d=ARG", "--derivatives=ARG", "Base directory of the derivatives") { |stream_base_dir| options[:stream_base_dir] = stream_base_dir } opts.on("-b=ARG", "--dest_base=ARG", "Output directory") { |dest_base_dir| options[:dest_base_dir] = dest_base_dir } opts.on("-s=ARG", "--delay=ARG", "Delay between exports") { |delay| options[:delay] = delay ? delay.to_i : 0 } opts.on("-h", "--help") do puts opts exit end end args = option_parser.order!(ARGV) {} option_parser.parse!(args) if options[:filename].nil? puts "Manditory argument: -m filename" puts option_parser.help exit 1 elsif !File.exist?(options[:filename]) puts "Filename not found: #{options[:filename]}" exit 1 end ids = File.read(options[:filename]).split count = 0 count_success = 0 ids.each do |id| begin count += 1 obj = ActiveFedora::Base.find(id) if (obj.is_a?(MediaObject)) ualberta_export_mediaObject(obj, options) elsif (obj.is_a?(Admin::Collection)) ualberta_export_collectionObject(obj, options) end count_success += 1 sleep(options[:delay]) if (options[:delay]) rescue StandardError => e puts "ERROR: %s - %s - %s" % [id, e.class.name, e.message] puts e.backtrace end end puts "Number processed: [#{ids.count}]; success: [#{count_success}]" if count == 0 puts "You must specify an set of MediaObject IDs." puts option_parser.help exit 1 end end def ualberta_export_collectionObject( obj, options ) base_dir = File.join(options[:dest_base_dir], obj.id) FileUtils.mkdir_p(base_dir) File.open("#{base_dir}/collection_object.json", 'w') { |file| file.write(obj.as_json.to_json(:except => :captions)) } end def ualberta_export_mediaObject( obj, options ) base_dir = File.join(options[:dest_base_dir], obj.collection_id, "MediaObjects", obj.id) FileUtils.mkdir_p(base_dir) File.open("#{base_dir}/media_object.json", 'w') { |file| file.write(obj.as_json.to_json(:except => :captions)) } File.open("#{base_dir}/mods.xml", 'w:BINARY') { |file| file.write(obj.descMetadata.content) } obj.ordered_master_files.to_a.collect.each do |mf| ualberta_export_masterFile(mf, base_dir, options) end end def ualberta_export_masterFile ( mf, base_dir, options ) mf_base_dir = File.join(base_dir, "media_files", mf.id) FileUtils.mkdir_p(mf_base_dir) File.open("#{mf_base_dir}/media_file.json", 'w') { |file| file.write(mf.to_json) } File.open("#{mf_base_dir}/structural_metadata.xml", 'w') { |file| file.write(mf.structuralMetadata.content) } original_base_dir = File.join(mf_base_dir, "original_media_file") if File.file?(mf.file_location) FileUtils.mkdir_p(original_base_dir) FileUtils.cp(mf.file_location, "#{original_base_dir}/") else # mf.file_location may be outdated (i.e., moved outside Avalon) # search for file in other directories # log: if media doesn't exist or has been moved glob = Dir.glob("#{ENV['SETTINGS__DROPBOX__PATH']}/**/#{File.basename(mf.file_location)}") puts "ERROR: [%s] media file not found: [%s] for Object [%s]" % [mf.id, mf.file_location, mf.media_object_id] if glob.empty? # assumption: every media file should have a unique name otherwise this fails and fails by reporting 2+ items # log: if multiple files of the same name found but don't change execution path as there could be a legitemate reason puts "ERROR: [%s] stored media file path outdated: multiple media files found with name [%s]" % [mf.id, File.basename(mf.file_location) ] if glob.count > 1 glob.each do |file| FileUtils.mkdir_p(original_base_dir) FileUtils.cp(file, "#{original_base_dir}/") puts "INFO: [%s] stored media file path outdated [%s] -- using alternative [%s]" % [mf.id, mf.file_location, file] end end mf.derivatives.to_a.collect.each do |derivative| derivative_base_dir = File.join(mf_base_dir,"derivatives","#{derivative.quality}_#{derivative.id}") FileUtils.mkdir_p(derivative_base_dir) File.open("#{derivative_base_dir}/derivative.json", 'w') { |file| file.write(derivative.to_json) } # locate the derivative file and export # derivative files are stored on the streaming server; UAL mounts this filesystem on the app server as well # parse streaming server path to translate into a valid app server path # start with the derivativeFile path and parse the last two subdirectories along with the filename if (File.exists?(tmp_path = File.join(options[:stream_base_dir], derivative.derivativeFile.split(File::SEPARATOR)[4..-1]))) FileUtils.cp(tmp_path, derivative_base_dir) end end if mf.captions.has_content? caption_base_dir = File.join(mf_base_dir, "captions") FileUtils.mkdir_p(caption_base_dir) File.open("#{caption_base_dir}/#{mf.captions.original_name}", 'w:BINARY') { |file| file.write(mf.captions.content) } end if mf.poster.has_content? poster_base_dir = File.join(mf_base_dir,"poster") FileUtils.mkdir_p(poster_base_dir) File.open("#{poster_base_dir}/#{mf.poster.original_name}", 'w:BINARY') { |file| file.write(mf.poster.content) } end if mf.thumbnail.has_content? thumbnail_base_dir = File.join(mf_base_dir,"thumbnail") FileUtils.mkdir_p(thumbnail_base_dir) File.open("#{thumbnail_base_dir}/#{mf.thumbnail.original_name}", 'w:BINARY') { |file| file.write(mf.thumbnail.content) } end end end end
module Jossh VERSION = "0.0.3" end version bump module Jossh VERSION = "0.1.0" end
require 'test/reporters/abstract' module Test::Reporters # Simple Dot-Progress Reporter class Dotprogress < Abstract def pass(unit) print "." $stdout.flush end def fail(unit, exception) print "F".ansi(:red) $stdout.flush end def error(unit, exception) print "E".ansi(:red, :bold) $stdout.flush end def todo(unit, exception) print "P".ansi(:yellow) $stdout.flush end def omit(unit, exception) print "O".ansi(:cyan) $stdout.flush end def end_suite(suite) puts; puts puts timestamp puts if runner.verbose? unless record[:omit].empty? puts "OMISSIONS:\n\n" record[:omit].each do |test, exception| puts " #{test}".ansi(:bold) puts " #{exception}" puts " #{file_and_line(exception)}" #puts code(exception) puts end end end unless record[:todo].empty? puts "PENDING:\n\n" record[:todo].each do |test, exception| puts " #{test}".ansi(:bold) puts " #{exception}" puts " #{file_and_line(exception)}" puts code(exception) puts end end unless record[:fail].empty? puts "FAILURES:\n\n" record[:fail].each do |test_unit, exception| puts " #{test_unit}".ansi(:bold) puts " #{exception}" puts " #{file_and_line(exception)}" puts code(exception) puts end end unless record[:error].empty? puts "ERRORS:\n\n" record[:error].each do |test_unit, exception| puts " #{test_unit}".ansi(:bold) puts " #{exception}" puts " #{file_and_line(exception)}" puts code(exception) puts end end puts tally end end end Do not print test descripting if empty string. require 'test/reporters/abstract' module Test::Reporters # Simple Dot-Progress Reporter class Dotprogress < Abstract def pass(unit) print "." $stdout.flush end def fail(unit, exception) print "F".ansi(:red) $stdout.flush end def error(unit, exception) print "E".ansi(:red, :bold) $stdout.flush end def todo(unit, exception) print "P".ansi(:yellow) $stdout.flush end def omit(unit, exception) print "O".ansi(:cyan) $stdout.flush end def end_suite(suite) puts; puts puts timestamp puts if runner.verbose? unless record[:omit].empty? puts "OMISSIONS:\n\n" record[:omit].each do |test, exception| puts " #{test}".ansi(:bold) puts " #{exception}" puts " #{file_and_line(exception)}" #puts code(exception) puts end end end unless record[:todo].empty? puts "PENDING:\n\n" record[:todo].each do |test, exception| puts " #{test}".ansi(:bold) unless test.to_s.empty? puts " #{exception}" puts " #{file_and_line(exception)}" puts code(exception) puts end end unless record[:fail].empty? puts "FAILURES:\n\n" record[:fail].each do |test_unit, exception| puts " #{test_unit}".ansi(:bold) puts " #{exception}" puts " #{file_and_line(exception)}" puts code(exception) puts end end unless record[:error].empty? puts "ERRORS:\n\n" record[:error].each do |test_unit, exception| puts " #{test_unit}".ansi(:bold) puts " #{exception}" puts " #{file_and_line(exception)}" puts code(exception) puts end end puts tally end end end
require 'serverspec' require 'net/ssh' include SpecInfra::Helper::Ssh RSpec.configure do |c| c.before :all do host = ENV['DOCKER_HOST'] if c.host != host c.ssh.close if c.ssh c.host = host options = Net::SSH::Config.for(c.host) options[:key_data] = [ENV['DOCKER_SSH_KEY']] options[:user] = 'root' options[:port] = ENV['DOCKER_SSH_PORT'] || 22 puts options.inspect c.ssh = Net::SSH.start(c.host, options[:user], options) end end end Removed erroneous debug require 'serverspec' require 'net/ssh' include SpecInfra::Helper::Ssh RSpec.configure do |c| c.before :all do host = ENV['DOCKER_HOST'] if c.host != host c.ssh.close if c.ssh c.host = host options = Net::SSH::Config.for(c.host) options[:key_data] = [ENV['DOCKER_SSH_KEY']] options[:user] = 'root' options[:port] = ENV['DOCKER_SSH_PORT'] || 22 c.ssh = Net::SSH.start(c.host, options[:user], options) end end end
module Traits module Controller module Resource module ClassMethods def self.extended(reciever) reciever.before_filter "find_#{reciever.controller_name.singularize}" end def singular_name controller_name.singularize end end module InstanceMethods def self.included(receiver) receiver.send(:define_method, "find_#{receiver.singular_name}") do instance_variable_set("@#{singular_name}", resource_class.find(params[:id])) if params[:id] end end def singular_name controller_name.singularize end def resource_class singular_name.classify.constantize end def response_with_options(resource) serialize_options = resource_class.constants.include?("SerializeOptions") ? resource_class::SerializeOptions : {} respond_with resource, serialize_options end end def self.included(receiver) receiver.extend ClassMethods receiver.send :include, InstanceMethods end end end end override resource module Traits module Controller module Resource module ClassMethods def self.extended(reciever) reciever.before_filter "find_#{reciever.controller_name.singularize}" end def singular_name controller_name.singularize end end module InstanceMethods def self.included(receiver) receiver.send(:define_method, "find_#{receiver.singular_name}") do instance_variable_set("@#{singular_name}", resource_class.find(params[:id])) if params[:id] end end def singular_name controller_name.singularize end def resource_class singular_name.classify.constantize end def response_with_options(resource) serialize_options = {} begin serialize_options = resource_class.const_get(:SerializeOptions) rescue end respond_with resource, serialize_options end end def self.included(receiver) receiver.extend ClassMethods receiver.send :include, InstanceMethods end end end end
module TransamAccounting VERSION = "0.1.59" end Bump version module TransamAccounting VERSION = "0.1.60" end
module JSTP class Dispatch < Hash include Discoverer::Writer include Discoverer::Reader def initialize *args unless args.empty? if args.length == 1 if args.first.is_a? Hash from.hash args.first elsif args.first.is_a? String from.string args.first elsif args.first.is_a? Symbol self.method = args.first end else from.array args end end self["protocol"] = ["JSTP", "0.1"] unless self.has_key? "protocol" self["timestamp"] = Time.now.to_i end def to_s to.string end def method self["method"] end def method= the_method self["method"] = the_method.to_s.upcase end def resource self["resource"] end def resource= the_resource if the_resource.is_a? Array self["resource"] = the_resource elsif the_resource.is_a? String self["resource"] = the_resource.split "/" end end def protocol self["protocol"] end def protocol= the_protocol if the_protocol.is_a? Array self["protocol"] = the_protocol elsif the_protocol.is_a? String self["protocol"] = the_protocol.split "/" end end def timestamp self["timestamp"] end def timestamp= the_timestamp if the_timestamp.is_a? Integer self["timestamp"] = the_timestamp elsif the_timestamp.is_a? Time self["timestamp"] = the_timestamp.to_i end end def referer self["referer"] end def referer= the_referer if the_referer.is_a? Array self["referer"] = the_referer elsif the_referer.is_a? String self["referer"] = the_referer.split "/" end end def token self["token"] end def token= the_token if the_token.is_a? Array self["token"] = the_token elsif the_token.is_a? String self["token"] = the_token.split "/" end end def body self["body"] end def body= the_body self["body"] = the_body end end end Minor correction module JSTP class Dispatch < Hash include Discoverer::Writer include Discoverer::Reader def initialize *args unless args.empty? if args.length == 1 if args.first.is_a? Hash from.hash args.first elsif args.first.is_a? String from.string args.first elsif args.first.is_a? Symbol self.method = args.first end else from.array args end end self["protocol"] = ["JSTP", "0.1"] unless self.has_key? "protocol" self["timestamp"] = Time.now.to_i end def to_s to.string end def method self["method"] end def method= the_method self["method"] = the_method.to_s.upcase end def resource self["resource"] end def resource= the_resource if the_resource.is_a? Array self["resource"] = the_resource elsif the_resource.is_a? String self["resource"] = the_resource.split "/" end end def protocol self["protocol"] end def protocol= the_protocol if the_protocol.is_a? Array self["protocol"] = the_protocol elsif the_protocol.is_a? String self["protocol"] = the_protocol.split "/" end end def timestamp self["timestamp"] end def timestamp= the_timestamp if the_timestamp.is_a? Integer self["timestamp"] = the_timestamp elsif the_timestamp.is_a? Time self["timestamp"] = the_timestamp.to_i end end def referer self["referer"] end def referer= the_referer if the_referer.is_a? Array self["referer"] = the_referer elsif the_referer.is_a? String self["referer"] = the_referer.split "/" end end def token self["token"] end def token= the_token if the_token.is_a? Array self["token"] = the_token elsif the_token.is_a? String self["token"] = the_token.split "/" end end def body self["body"] end def body= the_body self["body"] = the_body end def gateway self["gateway"] end def gateway= the_gateway self["gateway"] = the_gateway end end end
require 'rake/clean' require 'k4compiler' require 'k4slide/expand_compiler_options' module K4slide module Tasks def self.install(&block) instance = K4slideTasks.new instance.install(&block) end class K4slideTasks include Rake::DSL def initialize @compiler = nil end def install(&block) @compiler = ::K4compiler.setup(&block) @config = @compiler.config namespace :k4s do namespace :compile do desc 'Compile JavaScript source with Closure Library.' task :closure => get_closure_sources() desc 'Compile SASS sources' task :sass => get_sass_source() desc 'Compile Markdown sources' task :markdown do puts "Compile Markdown" end desc 'Compile sources.' task :all => ['k4s:compile:closure', 'k4s:compile:sass', 'k4s:compile:markdown'] end namespace :example do task :md2s => (['k4s:example:compile'] + example_markdown_targets()) task :compile => ['k4s:compile:all'] end end end # @return [FileList] def get_closure_sources target_files = [] source_dir = @config.closure.target_dir compiled_dir = @config.closure.compiled_dir depends_files = [] @config.closure.load_paths << source_dir @config.closure.load_paths.each do |load_path| depends_files += FileList[File.join(load_path, '**/*.js')].flatten if load_path end ns_suffix = @config.closure.namespace_suffix || 'App' filelist = FileList[File.join(source_dir, '*.js')] filelist.each do |source_path| source_basename = File.basename(source_path) target_path = File.join(compiled_dir, source_basename) same_name_dir = source_path.gsub(/\.js$/, '') depends = depends_files.dup depends.unshift(FileList[File.join(same_name_dir, '**/*.js')].flatten) depends.unshift(source_path) depends = depends.flatten file(target_path => depends) do |t, args| basename = File.basename(t.name).gsub(/\.js$/, '') namespace = "#{basename}.#{ns_suffix}" js_source = @compiler.closure.compile(namespace) File.open(target_path, 'w') do |io| io.write(js_source) end end target_files << target_path end return target_files end # @return [FileList] def get_sass_source() target_files = [] source_dir = @config.scss.target_dir compiled_dir = @config.scss.compiled_dir ext = @config.scss.ext || 'scss' @config.scss.load_paths << source_dir depends_files = [] @config.scss.load_paths.each do |load_path| depends_files += FileList[File.join(load_path, "**/*.#{ext}")].flatten if load_path end filelist = FileList[File.join(source_dir, "*.#{ext}")] filelist.each do |source_path| source_basename = File.basename(source_path) next if source_basename =~ /^_/ source_basename = source_basename.gsub(/#{ext}$/, 'css') target_path = File.join(compiled_dir, source_basename) depends = depends_files.dup depends.unshift(source_path) file(target_path => depends) do |t, args| puts t.name src = File.read(source_path) css_source = @compiler.scss.compile(src) File.open(target_path, 'w') do |io| io.write(css_source) end end target_files << target_path end return target_files end # Compiling example markdown file def example_markdown_targets() target_files = [] example_dir = File.join(K4_ROOT, 'example') ext = 'md' filelist = FileList[File.join(example_dir, "*.#{ext}")] puts filelist filelist.each do |source_path| source_basename = File.basename(source_path) next if source_basename =~ /^_/ source_basename = source_basename.gsub(/#{ext}$/, 'html') target_path = File.join(example_dir, source_basename) # DEV File.delete(target_path) if File.exists?(target_path) file(target_path) do |t, args| puts t.name src = File.read(source_path) compiler_ = MarkdownCompiler.new(@compiler) html_source = compiler_.to_slide(src) File.open(target_path, 'w') do |io| io.write(html_source) end end target_files << target_path end return target_files end end end end Delete File.delete require 'rake/clean' require 'k4compiler' require 'k4slide/expand_compiler_options' module K4slide module Tasks def self.install(&block) instance = K4slideTasks.new instance.install(&block) end class K4slideTasks include Rake::DSL def initialize @compiler = nil end def install(&block) @compiler = ::K4compiler.setup(&block) @config = @compiler.config namespace :k4s do namespace :compile do desc 'Compile JavaScript source with Closure Library.' task :closure => get_closure_sources() desc 'Compile SASS sources' task :sass => get_sass_source() desc 'Compile Markdown sources' task :markdown do puts "Compile Markdown" end desc 'Compile sources.' task :all => ['k4s:compile:closure', 'k4s:compile:sass', 'k4s:compile:markdown'] end namespace :example do task :md2s => (['k4s:example:compile'] + example_markdown_targets()) task :compile => ['k4s:compile:all'] end end end # @return [FileList] def get_closure_sources target_files = [] source_dir = @config.closure.target_dir compiled_dir = @config.closure.compiled_dir depends_files = [] @config.closure.load_paths << source_dir @config.closure.load_paths.each do |load_path| depends_files += FileList[File.join(load_path, '**/*.js')].flatten if load_path end ns_suffix = @config.closure.namespace_suffix || 'App' filelist = FileList[File.join(source_dir, '*.js')] filelist.each do |source_path| source_basename = File.basename(source_path) target_path = File.join(compiled_dir, source_basename) same_name_dir = source_path.gsub(/\.js$/, '') depends = depends_files.dup depends.unshift(FileList[File.join(same_name_dir, '**/*.js')].flatten) depends.unshift(source_path) depends = depends.flatten file(target_path => depends) do |t, args| basename = File.basename(t.name).gsub(/\.js$/, '') namespace = "#{basename}.#{ns_suffix}" js_source = @compiler.closure.compile(namespace) File.open(target_path, 'w') do |io| io.write(js_source) end end target_files << target_path end return target_files end # @return [FileList] def get_sass_source() target_files = [] source_dir = @config.scss.target_dir compiled_dir = @config.scss.compiled_dir ext = @config.scss.ext || 'scss' @config.scss.load_paths << source_dir depends_files = [] @config.scss.load_paths.each do |load_path| depends_files += FileList[File.join(load_path, "**/*.#{ext}")].flatten if load_path end filelist = FileList[File.join(source_dir, "*.#{ext}")] filelist.each do |source_path| source_basename = File.basename(source_path) next if source_basename =~ /^_/ source_basename = source_basename.gsub(/#{ext}$/, 'css') target_path = File.join(compiled_dir, source_basename) depends = depends_files.dup depends.unshift(source_path) file(target_path => depends) do |t, args| puts t.name src = File.read(source_path) css_source = @compiler.scss.compile(src) File.open(target_path, 'w') do |io| io.write(css_source) end end target_files << target_path end return target_files end # Compiling example markdown file def example_markdown_targets() target_files = [] example_dir = File.join(K4_ROOT, 'example') ext = 'md' filelist = FileList[File.join(example_dir, "*.#{ext}")] puts filelist filelist.each do |source_path| source_basename = File.basename(source_path) next if source_basename =~ /^_/ source_basename = source_basename.gsub(/#{ext}$/, 'html') target_path = File.join(example_dir, source_basename) file(target_path) do |t, args| puts t.name src = File.read(source_path) compiler_ = MarkdownCompiler.new(@compiler) html_source = compiler_.to_slide(src) File.open(target_path, 'w') do |io| io.write(html_source) end end target_files << target_path end return target_files end end end end
module Travis class Build module Job class Test class Perl < Test class Config < Hashr define :perl => '5.14' end def setup super shell.execute "perlbrew use #{config.perl}" announce_versions end def cpanm_modules_location "~/perl5/perlbrew/perls/#{config.perl}/cpanm" end def install "cpanm -vv --installdeps --notest ." end def announce_versions shell.execute("perl --version") shell.execute("cpanm --version") end def script if uses_module_build? run_tests_with_mb elsif uses_eumm? run_tests_with_eumm else run_default end end protected def uses_module_build? @uses_module_build ||= shell.file_exists?('Build.PL') end def uses_eumm? @uses_eumm ||= shell.file_exists?('Makefile.PL') end def run_tests_with_mb "perl Build.PL && ./Build test" end def run_tests_with_eumm "perl Makefile.PL && make test" end def run_default "make test" end end end end end end -vv is too verbose, -q has similar output to gem see http://travis-ci.org/#!/leedo/noembed/jobs/756283 for an example of the current output. Takes a good 30s to load, and is impossible to watch live output without crashing. module Travis class Build module Job class Test class Perl < Test class Config < Hashr define :perl => '5.14' end def setup super shell.execute "perlbrew use #{config.perl}" announce_versions end def cpanm_modules_location "~/perl5/perlbrew/perls/#{config.perl}/cpanm" end def install "cpanm --quiet --installdeps --notest ." end def announce_versions shell.execute("perl --version") shell.execute("cpanm --version") end def script if uses_module_build? run_tests_with_mb elsif uses_eumm? run_tests_with_eumm else run_default end end protected def uses_module_build? @uses_module_build ||= shell.file_exists?('Build.PL') end def uses_eumm? @uses_eumm ||= shell.file_exists?('Makefile.PL') end def run_tests_with_mb "perl Build.PL && ./Build test" end def run_tests_with_eumm "perl Makefile.PL && make test" end def run_default "make test" end end end end end end
class Karasuba class Todo attr_accessor :element, :title, :following_siblings, :stopping_sibling, :text_sibblings, :stopped_by_link, :options def initialize(element, title = '', following_siblings = [], text_sibblings = [], options = {}) @element = element @title = title @following_siblings = following_siblings @stopping_sibling = nil @stopping_link = nil @stopped_by_link = false @text_sibblings = text_sibblings @options = options end def update_title(string) @title = string self.text_sibblings.each(&:remove) clean_links el = title_element(string) self.element.next = el reset parse title end def checked=(bool) self.element["checked"] = (!!bool).to_s end def checked self.element["checked"] == "true" end alias :checked? :checked def links(href = nil) regex = Regexp.new(href) if href self.following_siblings.inject([]) do |ary, s| match = if href s.name == 'a' && regex.match(s['href']) else s.name == 'a' end next ary unless match ary << Link.new(s, s['href'], s.text) end end def remove_links(href = nil) links(href).each { |link| link.element.remove } reset parse links(href) end def clean_links(href = nil) regex = Regexp.new(href) if href links(href).map do |link| match = if href regex.match(links.href) else true end next unless match if link.element.xpath('.//text()').empty? link.element.remove end end.compact reset parse links(href) end def linked?(href = nil) !links(href).empty? end def stopped_by_link? @stopped_by_link end def stopping_link return nil unless stopped_by_link? Link.new(stopping_sibling, stopping_sibling['href'], stopping_sibling.text) end def append_link(href, text = '', options = {}) appender = LinkAppender.new(append_link_point) appender.append_link(href, text, options) reset parse self end private def reset @title = '' @following_siblings = [] @stopping_sibling = nil @text_sibblings = [] @stopping_link = nil @stopped_by_link = false end def parse Parser.new(self, options).parse end def append_link_point self.text_sibblings.reverse.find { |s| !s.blank? } || self.element end def title_element(string) Nokogiri::XML::Text.new(string, self.element.document) end end end Fix links typo class Karasuba class Todo attr_accessor :element, :title, :following_siblings, :stopping_sibling, :text_sibblings, :stopped_by_link, :options def initialize(element, title = '', following_siblings = [], text_sibblings = [], options = {}) @element = element @title = title @following_siblings = following_siblings @stopping_sibling = nil @stopping_link = nil @stopped_by_link = false @text_sibblings = text_sibblings @options = options end def update_title(string) @title = string self.text_sibblings.each(&:remove) clean_links el = title_element(string) self.element.next = el reset parse title end def checked=(bool) self.element["checked"] = (!!bool).to_s end def checked self.element["checked"] == "true" end alias :checked? :checked def links(href = nil) regex = Regexp.new(href) if href self.following_siblings.inject([]) do |ary, s| match = if href s.name == 'a' && regex.match(s['href']) else s.name == 'a' end next ary unless match ary << Link.new(s, s['href'], s.text) end end def remove_links(href = nil) links(href).each { |link| link.element.remove } reset parse links(href) end def clean_links(href = nil) regex = Regexp.new(href) if href links(href).map do |link| match = if href regex.match(link.href) else true end next unless match if link.element.xpath('.//text()').empty? link.element.remove end end.compact reset parse links(href) end def linked?(href = nil) !links(href).empty? end def stopped_by_link? @stopped_by_link end def stopping_link return nil unless stopped_by_link? Link.new(stopping_sibling, stopping_sibling['href'], stopping_sibling.text) end def append_link(href, text = '', options = {}) appender = LinkAppender.new(append_link_point) appender.append_link(href, text, options) reset parse self end private def reset @title = '' @following_siblings = [] @stopping_sibling = nil @text_sibblings = [] @stopping_link = nil @stopped_by_link = false end def parse Parser.new(self, options).parse end def append_link_point self.text_sibblings.reverse.find { |s| !s.blank? } || self.element end def title_element(string) Nokogiri::XML::Text.new(string, self.element.document) end end end
class Katte VERSION = "0.0.1" end update version. class Katte VERSION = "0.0.1.1" end
# Copyright (C) 2015 Twitter, Inc. module TwitterAds module ReachEstimate class << self # Get a reach estimate for the specified line item details. # # @example # TwitterAds::ReachEstimate.fetch( # account, # 'PROMOTED_TWEETS', # 'WEBSITE_CLICKS', # 2153688540, # similar_to_followers_of_user: 2153688540, # gender: 2 # ) # # @param client [Client] The Client object instance. # @param account [Account] The Ads Account instance for this request. # @param product_type [String] The product type being targeted. # @param objective [String] The objective being targeted. # @param user_id [Long] The ID of the user whose content will be promoted. # @param opts [Hash] A Hash of extended options. # # @option opts [String] :bid_type The bidding mechanism. # @option opts [Long] :bid_amount_local_micro Bid amount in local currency micros. # @option opts [String] :currency ISO-4217 Currency code for bid amount. # @option opts [String] :followers_of_users Comma-separated user IDs. # @option opts [String] :similar_to_followers_of_users Comma-separated user IDs. # @option opts [String] :locations Comma-separated location IDs. # @option opts [String] :interests Comma-seaprated interest IDs. # @option opts [String] :gender Gender identifier. # @option opts [String] :platforms Comma-separated platform IDs. # @option opts [String] :tailored_audiences Comma-separated tailored audience IDs. # @option opts [String] :tailored_audiences_expanded Comma-separated tailoerd audience IDs. # @option opts [String] :languages Comma-separated language IDs. # @option opts [String] :platform_versions Comma-separated platform version IDs. # @option opts [String] :devices Comma-separated device IDs. # @option opts [String] :behaviors Comma-separated behavior IDs. # @option opts [String] :behaviors_expanded Comma-separated behaviors IDs. # @option opts [String] :campaign engagement Campaign ID for Tweet Engager Retargeting. # @option opts [String] :user_engagement Promoted User ID for Tweet Engager Retargeting. # @option opts [String] :engagement_type engagement type for Tweet Engager Retargeting. # # @return [Hash] A hash containing count and infinite_bid_count. # # @since 0.2.0 # @see https://dev.twitter.com/ads/reference/get/accounts/%3Aaccount_id/reach_estimate def fetch(account, product_type, objective, user_id, opts = {}) resource = "/0/accounts/#{account.id}/reach_estimate" params = { product_type: product_type, objective: objective, user_id: user_id } response = TwitterAds::Request.new( account.client, :get, resource, params: params.merge(opts)).perform response.body[:data] end end end end [minor] cleanup of reach estimate logic # Copyright (C) 2015 Twitter, Inc. module TwitterAds module ReachEstimate class << self # Get a reach estimate for the specified line item details. # # @example # TwitterAds::ReachEstimate.fetch( # account, # 'PROMOTED_TWEETS', # 'WEBSITE_CLICKS', # 2153688540, # similar_to_followers_of_user: 2153688540, # gender: 2 # ) # # @param client [Client] The Client object instance. # @param account [Account] The Ads Account instance for this request. # @param product_type [String] The product type being targeted. # @param objective [String] The objective being targeted. # @param user_id [Long] The ID of the user whose content will be promoted. # @param opts [Hash] A Hash of extended options. # # @option opts [String] :bid_type The bidding mechanism. # @option opts [Long] :bid_amount_local_micro Bid amount in local currency micros. # @option opts [String] :currency ISO-4217 Currency code for bid amount. # @option opts [String] :followers_of_users Comma-separated user IDs. # @option opts [String] :similar_to_followers_of_users Comma-separated user IDs. # @option opts [String] :locations Comma-separated location IDs. # @option opts [String] :interests Comma-seaprated interest IDs. # @option opts [String] :gender Gender identifier. # @option opts [String] :platforms Comma-separated platform IDs. # @option opts [String] :tailored_audiences Comma-separated tailored audience IDs. # @option opts [String] :tailored_audiences_expanded Comma-separated tailoerd audience IDs. # @option opts [String] :languages Comma-separated language IDs. # @option opts [String] :platform_versions Comma-separated platform version IDs. # @option opts [String] :devices Comma-separated device IDs. # @option opts [String] :behaviors Comma-separated behavior IDs. # @option opts [String] :behaviors_expanded Comma-separated behaviors IDs. # @option opts [String] :campaign engagement Campaign ID for Tweet Engager Retargeting. # @option opts [String] :user_engagement Promoted User ID for Tweet Engager Retargeting. # @option opts [String] :engagement_type engagement type for Tweet Engager Retargeting. # # @return [Hash] A hash containing count and infinite_bid_count. # # @since 0.2.0 # @see https://dev.twitter.com/ads/reference/get/accounts/%3Aaccount_id/reach_estimate def fetch(account, product_type, objective, user_id, opts = {}) resource = "/0/accounts/#{account.id}/reach_estimate" params = { product_type: product_type, objective: objective, user_id: user_id }.merge!(opts) response = TwitterAds::Request.new(account.client, :get, resource, params: params).perform response.body[:data] end end end end
module Kitno VERSION = "0.1.0" end Bump to 0.1.2 module Kitno VERSION = '0.1.2' end
module Ddb module Userstamp module MigrationHelper def self.included(base) # :nodoc: base.send(:include, InstanceMethods) end module InstanceMethods def userstamps(options = {}) # add backwards compatibility support options = {include_deleted_by: options} if (options === true || options === false) append_id_suffix = options[:include_id] ? '_id' : '' column(Ddb::Userstamp.compatibility_mode ? "created_by#{append_id_suffix}".to_sym : :creator_id, :integer) column(Ddb::Userstamp.compatibility_mode ? "updated_by#{append_id_suffix}".to_sym : :updater_id, :integer) column(Ddb::Userstamp.compatibility_mode ? "deleted_by#{append_id_suffix}".to_sym : :deleter_id, :integer) if options[:include_deleted_by] end end end end end ActiveRecord::ConnectionAdapters::Table.send(:include, Ddb::Userstamp::MigrationHelper) Revert "Convert arguements to hash and add Suffix" This reverts commit 7aa98aa747887703a8a144e1819a7282ea69e02b. module Ddb module Userstamp module MigrationHelper def self.included(base) # :nodoc: base.send(:include, InstanceMethods) end module InstanceMethods def userstamps(include_deleted_by = false) column(Ddb::Userstamp.compatibility_mode ? :created_by : :creator_id, :integer) column(Ddb::Userstamp.compatibility_mode ? :updated_by : :updater_id, :integer) column(Ddb::Userstamp.compatibility_mode ? :deleted_by : :deleter_id, :integer) if include_deleted_by end end end end end ActiveRecord::ConnectionAdapters::Table.send(:include, Ddb::Userstamp::MigrationHelper)
# coding: utf-8 require 'binlog' require 'logger' module Kodama class Client LOG_LEVEL = { :fatal => Logger::FATAL, :error => Logger::ERROR, :warn => Logger::WARN, :info => Logger::INFO, :debug => Logger::DEBUG, } class << self def start(options = {}, &block) client = self.new(mysql_url(options)) block.call(client) client.start end def mysql_url(options = {}) password = options[:password] ? ":#{options[:password]}" : nil port = options[:port] ? ":#{options[:port]}" : nil "mysql://#{options[:username]}#{password}@#{options[:host]}#{port}" end end def initialize(url) @url = url @binlog_info = BinlogInfo.new @sent_binlog_info = BinlogInfo.new @retry_info = RetryInfo.new(:limit => 100, :wait => 3) @callbacks = {} @logger = Logger.new(STDOUT) @safe_to_stop = true self.log_level = :info end def on_query_event(&block); @callbacks[:on_query_event] = block; end def on_rotate_event(&block); @callbacks[:on_rotate_event] = block; end def on_int_var_event(&block); @callbacks[:on_int_var_event] = block; end def on_user_var_event(&block); @callbacks[:on_user_var_event] = block; end def on_format_event(&block); @callbacks[:on_format_event] = block; end def on_xid(&block); @callbacks[:on_xid] = block; end def on_table_map_event(&block); @callbacks[:on_table_map_event] = block; end def on_row_event(&block); @callbacks[:on_row_event] = block; end def on_incident_event(&block); @callbacks[:on_incident_event] = block; end def on_unimplemented_event(&block); @callbacks[:on_unimplemented_event] = block; end def binlog_position_file=(filename) @position_file = position_file(filename) @binlog_info.load!(@position_file) end def sent_binlog_position_file=(filename) @sent_position_file = position_file(filename) @sent_binlog_info.load!(@sent_position_file) end def connection_retry_wait=(wait) @retry_info.wait = wait end def connection_retry_limit=(limit) @retry_info.limit = limit end def log_level=(level) @logger.level = LOG_LEVEL[level] end def gracefully_stop_on(*signals) signals.each do |signal| Signal.trap(signal) do if safe_to_stop? exit(0) else stop_request end end end end def binlog_client(url) Binlog::Client.new(url) end def position_file(filename) PositionFile.new(filename) end def connection_retry_count @retry_info.count end def safe_to_stop? !!@safe_to_stop end def stop_request @stop_requested = true end def start @retry_info.count_reset begin client = binlog_client(@url) raise Binlog::Error, 'MySQL server has gone away' unless client.connect if @binlog_info.valid? client.set_position(@binlog_info.filename, @binlog_info.position) end while event = client.wait_for_next_event unsafe do process_event(event) end break if stop_requested? end rescue Binlog::Error => e @logger.debug e if client.closed? && @retry_info.retryable? sleep @retry_info.wait @retry_info.count_up retry end raise e end end private def unsafe @safe_to_stop = false yield @safe_to_stop = true end def stop_requested? @stop_requested end def process_event(event) # If the position in binlog file is behind the sent position, # keep updating only binlog info in most of cases processable = @binlog_info.should_process?(@sent_binlog_info) # Keep current binlog position temporary cur_binlog_file = @binlog_info.filename cur_binlog_pos = @binlog_info.position case event when Binlog::QueryEvent if processable callback :on_query_event, event # Save current event's position as sent (@sent_binlog_info) @sent_binlog_info.save_with(cur_binlog_file, cur_binlog_pos) end # Save next event's position as checkpoint (@binlog_info) @binlog_info.save_with(cur_binlog_file, event.next_position) when Binlog::RotateEvent # Even if the event is already sent, call callback # because app might need binlog info when resuming. callback :on_rotate_event, event # Update binlog_info with rotation @binlog_info.save_with(event.binlog_file, event.binlog_pos) when Binlog::IntVarEvent if processable callback :on_int_var_event, event end when Binlog::UserVarEvent if processable callback :on_user_var_event, event end when Binlog::FormatEvent if processable callback :on_format_event, event end when Binlog::Xid if processable callback :on_xid, event end when Binlog::TableMapEvent if processable callback :on_table_map_event, event end # Save current event's position as checkpoint @binlog_info.save_with(cur_binlog_file, cur_binlog_pos) when Binlog::RowEvent if processable callback :on_row_event, event # Save current event's position as sent @sent_binlog_info.save_with(cur_binlog_file, cur_binlog_pos) end when Binlog::IncidentEvent if processable callback :on_incident_event, event end when Binlog::UnimplementedEvent if processable callback :on_unimplemented_event, event end else @logger.error "Not Implemented: #{event.event_type}" end # Set the next event position for the next iteration set_next_event_position(@binlog_info, event) end def callback(name, *args) if @callbacks[name] instance_exec *args, &@callbacks[name] else @logger.debug "Unhandled: #{name}" end end # Set the next event position for the next iteration # Compare positions to avoid decreasing the position unintentionally # because next_position of Binlog::FormatEvent is always 0 def set_next_event_position(binlog_info, event) if !event.kind_of?(Binlog::RotateEvent) && binlog_info.position.to_i < event.next_position.to_i binlog_info.position = event.next_position end end class BinlogInfo attr_accessor :filename, :position, :position_file def initialize(filename = nil, position = nil, position_file = nil) @filename = filename @position = position @position_file = position_file end def valid? @filename && @position end def save_with(filename, position) @filename = filename if filename @position = position if position save end def save(position_file = nil) @position_file = position_file if position_file @position_file.update(@filename, @position) if @position_file end def load!(position_file = nil) @position_file = position_file if position_file @filename, @position = @position_file.read end def should_process?(sent_binlog_info) if self.valid? && sent_binlog_info && sent_binlog_info.valid? # Compare binlog filename and position # # Event should be sent only when the event position is bigger than # the sent position # # ex) # binlog_info sent_binlog_info result # ----------------------------------------------------------- # mysql-bin.000004 00001 mysql-bin.000003 00001 true # mysql-bin.000004 00030 mysql-bin.000004 00001 true # mysql-bin.000004 00030 mysql-bin.000004 00030 false # mysql-bin.000004 00030 mysql-bin.000004 00050 false # mysql-bin.000004 00030 mysql-bin.000005 00001 false @filename > sent_binlog_info.filename || (@filename == sent_binlog_info.filename && @position.to_i > sent_binlog_info.position.to_i) else true end end end class RetryInfo attr_accessor :count, :limit, :wait def initialize(options = {}) @wait = options[:wait] || 3 @limit = options[:limit] || 100 @count = 0 end def retryable? @count < @limit end def count_up @count += 1 end def count_reset @count = 0 end end class PositionFile def initialize(filename) @file = open(filename, File::RDWR|File::CREAT) @file.sync = true end def update(filename, position) @file.pos = 0 @file.write "#{filename}\t#{position}" @file.truncate @file.pos end def read @file.pos = 0 if line = @file.gets filename, position = line.split("\t") [filename, position.to_i] end end end end end Support ssl_ca= api # coding: utf-8 require 'binlog' require 'logger' module Kodama class Client LOG_LEVEL = { :fatal => Logger::FATAL, :error => Logger::ERROR, :warn => Logger::WARN, :info => Logger::INFO, :debug => Logger::DEBUG, } class << self def start(options = {}, &block) client = self.new(mysql_url(options)) block.call(client) client.start end def mysql_url(options = {}) password = options[:password] ? ":#{options[:password]}" : nil port = options[:port] ? ":#{options[:port]}" : nil "mysql://#{options[:username]}#{password}@#{options[:host]}#{port}" end end def initialize(url) @url = url @binlog_info = BinlogInfo.new @sent_binlog_info = BinlogInfo.new @retry_info = RetryInfo.new(:limit => 100, :wait => 3) @callbacks = {} @logger = Logger.new(STDOUT) @safe_to_stop = true self.log_level = :info end def on_query_event(&block); @callbacks[:on_query_event] = block; end def on_rotate_event(&block); @callbacks[:on_rotate_event] = block; end def on_int_var_event(&block); @callbacks[:on_int_var_event] = block; end def on_user_var_event(&block); @callbacks[:on_user_var_event] = block; end def on_format_event(&block); @callbacks[:on_format_event] = block; end def on_xid(&block); @callbacks[:on_xid] = block; end def on_table_map_event(&block); @callbacks[:on_table_map_event] = block; end def on_row_event(&block); @callbacks[:on_row_event] = block; end def on_incident_event(&block); @callbacks[:on_incident_event] = block; end def on_unimplemented_event(&block); @callbacks[:on_unimplemented_event] = block; end def binlog_position_file=(filename) @position_file = position_file(filename) @binlog_info.load!(@position_file) end def sent_binlog_position_file=(filename) @sent_position_file = position_file(filename) @sent_binlog_info.load!(@sent_position_file) end def ssl_ca=(filename) raise Errno::ENOENT, "ssl ca file (#{filename})" unless File.exists?(filename) raise "ssl ca is empty (#{filename})" if IO.read(filename).empty? @ssl_ca = filename end def connection_retry_wait=(wait) @retry_info.wait = wait end def connection_retry_limit=(limit) @retry_info.limit = limit end def log_level=(level) @logger.level = LOG_LEVEL[level] end def gracefully_stop_on(*signals) signals.each do |signal| Signal.trap(signal) do if safe_to_stop? exit(0) else stop_request end end end end def binlog_client(url) Binlog::Client.new(url) end def position_file(filename) PositionFile.new(filename) end def connection_retry_count @retry_info.count end def safe_to_stop? !!@safe_to_stop end def stop_request @stop_requested = true end def start @retry_info.count_reset begin client = binlog_client(@url) if @ssl_ca && client.respond_to?(:set_ssl_ca) client.set_ssl_ca(@ssl_ca) end raise Binlog::Error, 'MySQL server has gone away' unless client.connect if @binlog_info.valid? client.set_position(@binlog_info.filename, @binlog_info.position) end while event = client.wait_for_next_event unsafe do process_event(event) end break if stop_requested? end rescue Binlog::Error => e @logger.debug e if client.closed? && @retry_info.retryable? sleep @retry_info.wait @retry_info.count_up retry end raise e end end private def unsafe @safe_to_stop = false yield @safe_to_stop = true end def stop_requested? @stop_requested end def process_event(event) # If the position in binlog file is behind the sent position, # keep updating only binlog info in most of cases processable = @binlog_info.should_process?(@sent_binlog_info) # Keep current binlog position temporary cur_binlog_file = @binlog_info.filename cur_binlog_pos = @binlog_info.position case event when Binlog::QueryEvent if processable callback :on_query_event, event # Save current event's position as sent (@sent_binlog_info) @sent_binlog_info.save_with(cur_binlog_file, cur_binlog_pos) end # Save next event's position as checkpoint (@binlog_info) @binlog_info.save_with(cur_binlog_file, event.next_position) when Binlog::RotateEvent # Even if the event is already sent, call callback # because app might need binlog info when resuming. callback :on_rotate_event, event # Update binlog_info with rotation @binlog_info.save_with(event.binlog_file, event.binlog_pos) when Binlog::IntVarEvent if processable callback :on_int_var_event, event end when Binlog::UserVarEvent if processable callback :on_user_var_event, event end when Binlog::FormatEvent if processable callback :on_format_event, event end when Binlog::Xid if processable callback :on_xid, event end when Binlog::TableMapEvent if processable callback :on_table_map_event, event end # Save current event's position as checkpoint @binlog_info.save_with(cur_binlog_file, cur_binlog_pos) when Binlog::RowEvent if processable callback :on_row_event, event # Save current event's position as sent @sent_binlog_info.save_with(cur_binlog_file, cur_binlog_pos) end when Binlog::IncidentEvent if processable callback :on_incident_event, event end when Binlog::UnimplementedEvent if processable callback :on_unimplemented_event, event end else @logger.error "Not Implemented: #{event.event_type}" end # Set the next event position for the next iteration set_next_event_position(@binlog_info, event) end def callback(name, *args) if @callbacks[name] instance_exec *args, &@callbacks[name] else @logger.debug "Unhandled: #{name}" end end # Set the next event position for the next iteration # Compare positions to avoid decreasing the position unintentionally # because next_position of Binlog::FormatEvent is always 0 def set_next_event_position(binlog_info, event) if !event.kind_of?(Binlog::RotateEvent) && binlog_info.position.to_i < event.next_position.to_i binlog_info.position = event.next_position end end class BinlogInfo attr_accessor :filename, :position, :position_file def initialize(filename = nil, position = nil, position_file = nil) @filename = filename @position = position @position_file = position_file end def valid? @filename && @position end def save_with(filename, position) @filename = filename if filename @position = position if position save end def save(position_file = nil) @position_file = position_file if position_file @position_file.update(@filename, @position) if @position_file end def load!(position_file = nil) @position_file = position_file if position_file @filename, @position = @position_file.read end def should_process?(sent_binlog_info) if self.valid? && sent_binlog_info && sent_binlog_info.valid? # Compare binlog filename and position # # Event should be sent only when the event position is bigger than # the sent position # # ex) # binlog_info sent_binlog_info result # ----------------------------------------------------------- # mysql-bin.000004 00001 mysql-bin.000003 00001 true # mysql-bin.000004 00030 mysql-bin.000004 00001 true # mysql-bin.000004 00030 mysql-bin.000004 00030 false # mysql-bin.000004 00030 mysql-bin.000004 00050 false # mysql-bin.000004 00030 mysql-bin.000005 00001 false @filename > sent_binlog_info.filename || (@filename == sent_binlog_info.filename && @position.to_i > sent_binlog_info.position.to_i) else true end end end class RetryInfo attr_accessor :count, :limit, :wait def initialize(options = {}) @wait = options[:wait] || 3 @limit = options[:limit] || 100 @count = 0 end def retryable? @count < @limit end def count_up @count += 1 end def count_reset @count = 0 end end class PositionFile def initialize(filename) @file = open(filename, File::RDWR|File::CREAT) @file.sync = true end def update(filename, position) @file.pos = 0 @file.write "#{filename}\t#{position}" @file.truncate @file.pos end def read @file.pos = 0 if line = @file.gets filename, position = line.split("\t") [filename, position.to_i] end end end end end
require 'vcr/util/version_checker' require 'vcr/request_handler' require 'typhoeus' VCR::VersionChecker.new('Typhoeus', Typhoeus::VERSION, '0.3.2', '0.3').check_version! module VCR class LibraryHooks module Typhoeus module Helpers def vcr_request_from(request) VCR::Request.new \ request.method, request.url, request.body, request.headers end def vcr_response_from(response) VCR::Response.new \ VCR::ResponseStatus.new(response.code, response.status_message), response.headers_hash, response.body, response.http_version end end class RequestHandler < ::VCR::RequestHandler include Helpers attr_reader :request def initialize(request) @request = request end private def on_connection_not_allowed invoke_after_request_hook(nil) super end def vcr_request @vcr_request ||= vcr_request_from(request) end def on_stubbed_request ::Typhoeus::Response.new \ :http_version => stubbed_response.http_version, :code => stubbed_response.status.code, :status_message => stubbed_response.status.message, :headers_hash => stubbed_response_headers, :body => stubbed_response.body end def stubbed_response_headers @stubbed_response_headers ||= {}.tap do |hash| stubbed_response.headers.each do |key, values| hash[key] = values.size == 1 ? values.first : values end if stubbed_response.headers end end end extend Helpers ::Typhoeus::Hydra.after_request_before_on_complete do |request| unless VCR.library_hooks.disabled?(:typhoeus) vcr_request, vcr_response = vcr_request_from(request), vcr_response_from(request.response) unless request.response.mock? http_interaction = VCR::HTTPInteraction.new(vcr_request, vcr_response) VCR.record_http_interaction(http_interaction) end VCR.configuration.invoke_hook(:after_http_request, vcr_request, vcr_response) end end ::Typhoeus::Hydra.register_stub_finder do |request| VCR::LibraryHooks::Typhoeus::RequestHandler.new(request).handle end end end end class << Typhoeus::Hydra # ensure HTTP requests are always allowed; VCR takes care of disallowing # them at the appropriate times in its hook def allow_net_connect_with_vcr?(*args) VCR.turned_on? ? true : allow_net_connect_without_vcr? end alias allow_net_connect_without_vcr? allow_net_connect? alias allow_net_connect? allow_net_connect_with_vcr? end unless Typhoeus::Hydra.respond_to?(:allow_net_connect_with_vcr?) VCR.configuration.after_library_hooks_loaded do # ensure WebMock's Typhoeus adapter does not conflict with us here # (i.e. to double record requests or whatever). if defined?(WebMock::HttpLibAdapters::TyphoeusAdapter) WebMock::HttpLibAdapters::TyphoeusAdapter.disable! end end Change our Typhoeus::Hydra monkey patch to be more compatible with yard. It got confused by the fact that we were opening the Typhoeus::Hydra singleton class before declaring the class (since we get it by requiring it); spelling it out this way avoids this warning: [warn]: Load Order / Name Resolution Problem on Typhoeus::Hydra: [warn]: - [warn]: Something is trying to call child on object Typhoeus::Hydra before it has been recognized. [warn]: This error usually means that you need to modify the order in which you parse files [warn]: so that Typhoeus::Hydra is parsed before methods or other objects attempt to access it. [warn]: - [warn]: YARD will recover from this error and continue to parse but you *may* have problems [warn]: with your generated documentation. You should probably fix this. [warn]: - [error]: Unhandled exception in YARD::Handlers::Ruby::AliasHandler: [error]: in `lib/vcr/library_hooks/typhoeus.rb`:94: 94: alias allow_net_connect_without_vcr? allow_net_connect? require 'vcr/util/version_checker' require 'vcr/request_handler' require 'typhoeus' VCR::VersionChecker.new('Typhoeus', Typhoeus::VERSION, '0.3.2', '0.3').check_version! module VCR class LibraryHooks module Typhoeus module Helpers def vcr_request_from(request) VCR::Request.new \ request.method, request.url, request.body, request.headers end def vcr_response_from(response) VCR::Response.new \ VCR::ResponseStatus.new(response.code, response.status_message), response.headers_hash, response.body, response.http_version end end class RequestHandler < ::VCR::RequestHandler include Helpers attr_reader :request def initialize(request) @request = request end private def on_connection_not_allowed invoke_after_request_hook(nil) super end def vcr_request @vcr_request ||= vcr_request_from(request) end def on_stubbed_request ::Typhoeus::Response.new \ :http_version => stubbed_response.http_version, :code => stubbed_response.status.code, :status_message => stubbed_response.status.message, :headers_hash => stubbed_response_headers, :body => stubbed_response.body end def stubbed_response_headers @stubbed_response_headers ||= {}.tap do |hash| stubbed_response.headers.each do |key, values| hash[key] = values.size == 1 ? values.first : values end if stubbed_response.headers end end end extend Helpers ::Typhoeus::Hydra.after_request_before_on_complete do |request| unless VCR.library_hooks.disabled?(:typhoeus) vcr_request, vcr_response = vcr_request_from(request), vcr_response_from(request.response) unless request.response.mock? http_interaction = VCR::HTTPInteraction.new(vcr_request, vcr_response) VCR.record_http_interaction(http_interaction) end VCR.configuration.invoke_hook(:after_http_request, vcr_request, vcr_response) end end ::Typhoeus::Hydra.register_stub_finder do |request| VCR::LibraryHooks::Typhoeus::RequestHandler.new(request).handle end end end end module Typhoeus class << Hydra # ensure HTTP requests are always allowed; VCR takes care of disallowing # them at the appropriate times in its hook def allow_net_connect_with_vcr?(*args) VCR.turned_on? ? true : allow_net_connect_without_vcr? end alias allow_net_connect_without_vcr? allow_net_connect? alias allow_net_connect? allow_net_connect_with_vcr? end unless Hydra.respond_to?(:allow_net_connect_with_vcr?) end VCR.configuration.after_library_hooks_loaded do # ensure WebMock's Typhoeus adapter does not conflict with us here # (i.e. to double record requests or whatever). if defined?(WebMock::HttpLibAdapters::TyphoeusAdapter) WebMock::HttpLibAdapters::TyphoeusAdapter.disable! end end
module Layer class Message < Resource include Operations::Find def conversation Conversation.from_response(attributes['conversation'], client) end def sent_at Time.parse(attributes['sent_at']) end def read! client.post("#{url}/receipts", { type: 'read' }) end def delivered! client.post("#{url}/receipts", { type: 'delivery' }) end end end Use the receipts url attribute if available module Layer class Message < Resource include Operations::Find def conversation Conversation.from_response(attributes['conversation'], client) end def sent_at Time.parse(attributes['sent_at']) end def read! client.post(receipts_url, { type: 'read' }) end def delivered! client.post(receipts_url, { type: 'delivery' }) end def receipts_url attributes['receipts_url'] || "#{url}/receipts" end end end
module YARD module Parser class StatementList < Array include RubyToken # The following list of tokens will require a block to be opened # if used at the beginning of a statement. OPEN_BLOCK_TOKENS = [TkCLASS, TkDEF, TkMODULE, TkUNTIL, TkIF, TkUNLESS, TkWHILE, TkFOR, TkCASE] COLON_TOKENS = [TkUNTIL, TkIF, TkUNLESS, TkWHILE, TkCASE, TkWHEN] ## # Creates a new statement list # # @param [TokenList, String] content the tokens to create the list from def initialize(content) if content.is_a? TokenList @tokens = content.dup elsif content.is_a? String @tokens = TokenList.new(content) else raise ArgumentError, "Invalid content for StatementList: #{content.inspect}:#{content.class}" end parse_statements end private def parse_statements while stmt = next_statement do self << stmt end end # MUST REFACTOR THIS CODE # WARNING WARNING WARNING WARNING # MUST REFACTOR THIS CODE | # OR CHILDREN WILL DIE V # WARNING WARNING WARNING WARNING # THIS IS MEANT TO BE UGLY. def next_statement @statement, @block, @comments = TokenList.new, nil, nil @stmt_number, @level = 0, 0 @new_statement, @open_block = true, false @last_tk, @last_ns_tk, @before_last_tk = nil, nil, nil @open_parens = 0 while tk = @tokens.shift break if process_token(tk) #break if @new_statement && @level == 0 @before_last_tk = @last_tk @last_tk = tk # Save last token @last_ns_tk = tk unless [TkSPACE, TkNL, TkEND_OF_SCRIPT].include? tk.class end # Return the code block with starting token and initial comments # If there is no code in the block, return nil @comments = @comments.compact if @comments if @block || !@statement.empty? Statement.new(@statement, @block, @comments) else nil end end ## # Processes a single token, modifying instance variables accordingly # # @param [RubyToken::Token] tk the token to process # @return [Boolean] whether or not the statement has been ended by +tk+ def process_token(tk) #p tk.class # !!!!!!!!!!!!!!!!!!!! REMOVED TkfLPAREN, TkfLBRACK @open_parens += 1 if [TkLPAREN, TkLBRACK].include? tk.class @open_parens -= 1 if [TkRPAREN, TkRBRACK].include? tk.class #if @open_parens < 0 || @level < 0 # STDERR.puts @block.to_s + " TOKEN #{tk.inspect}" # exit #end # Get the initial comments if @statement.empty? # Two new-lines in a row will destroy any comment blocks if [TkCOMMENT].include?(tk.class) && @last_tk.class == TkNL && (@before_last_tk && (@before_last_tk.class == TkNL || @before_last_tk.class == TkSPACE)) @comments = nil elsif tk.class == TkCOMMENT # Remove the "#" and up to 1 space before the text # Since, of course, the convention is to have "# text" # and not "#text", which I deem ugly (you heard it here first) @comments ||= [] @comments << tk.text.gsub(/^#+\s{0,1}/, '') @comments.pop if @comments.size == 1 && @comments.first =~ /^\s*$/ end end # Ignore any initial comments or whitespace unless @statement.empty? && @stmt_number == 0 && [TkSPACE, TkNL, TkCOMMENT].include?(tk.class) # Decrease if end or '}' is seen @level -= 1 if [TkEND, TkRBRACE].include?(tk.class) # Increase level if we have a 'do' or block opening if [TkLBRACE, TkDO, TkBEGIN].include?(tk.class) #p "#{tk.line_no} #{@level} #{tk} \t#{tk.text} #{tk.lex_state}" @stmt_number += 1 @new_statement = true @level += 1 end # If the level is greater than 0, add the code to the block text # otherwise it's part of the statement text if @stmt_number > 0 #puts "Block of #{@statement}" #puts "#{@stmt_number} #{tk.line_no} #{@level} #{@open_parens} #{tk.class.class_name} \t#{tk.text.inspect} #{tk.lex_state} #{@open_block.inspect}" @block ||= TokenList.new @block << tk elsif @stmt_number == 0 && tk.class != TkNL && tk.class != TkSEMICOLON && tk.class != TkCOMMENT @statement << tk end #puts "#{tk.line_no} #{@level} #{@open_parens} #{tk.class.class_name} \t#{tk.text.inspect} #{tk.lex_state} #{@open_block.inspect}" # Vouch to open a block when this statement would otherwise end @open_block = [@level, tk.class] if (@new_statement || (@last_tk && @last_tk.lex_state == EXPR_BEG)) && OPEN_BLOCK_TOKENS.include?(tk.class) # Check if this token creates a new statement or not #puts "#{@open_parens} open brackets for: #{@statement.to_s}" if @open_parens == 0 && ((@last_tk && [TkSEMICOLON, TkNL, TkEND_OF_SCRIPT].include?(tk.class)) || (@open_block && @open_block.last == TkDEF && tk.class == TkRPAREN)) # Make sure we don't have any running expressions # This includes things like # # class < # Foo # # if a || # b if (@last_tk && [EXPR_END, EXPR_ARG].include?(@last_tk.lex_state)) || (@open_block && [TkNL, TkSEMICOLON].include?(tk.class) && @last_ns_tk.class != @open_block.last) @stmt_number += 1 @new_statement = true #p "NEW STATEMENT #{@block.to_s}" # The statement started with a if/while/begin, so we must go to the next level now if @open_block && @open_block.first == @level if tk.class == TkNL && @block.nil? @block = TokenList.new @block << tk end @open_block = false @level += 1 end end elsif tk.class != TkSPACE @new_statement = false end # Else keyword is kind of weird if tk.is_a? TkELSE @new_statement = true @stmt_number += 1 @open_block = false end # We're done if we've ended a statement and we're at level 0 return true if @new_statement && @level == 0 #raise "Unexpected end" if @level < 0 end end end end end Parser::StatementList: Factor out initial-comment processing. module YARD module Parser class StatementList < Array include RubyToken # The following list of tokens will require a block to be opened # if used at the beginning of a statement. OPEN_BLOCK_TOKENS = [TkCLASS, TkDEF, TkMODULE, TkUNTIL, TkIF, TkUNLESS, TkWHILE, TkFOR, TkCASE] COLON_TOKENS = [TkUNTIL, TkIF, TkUNLESS, TkWHILE, TkCASE, TkWHEN] ## # Creates a new statement list # # @param [TokenList, String] content the tokens to create the list from def initialize(content) if content.is_a? TokenList @tokens = content.dup elsif content.is_a? String @tokens = TokenList.new(content) else raise ArgumentError, "Invalid content for StatementList: #{content.inspect}:#{content.class}" end parse_statements end private def parse_statements while stmt = next_statement do self << stmt end end # MUST REFACTOR THIS CODE # WARNING WARNING WARNING WARNING # MUST REFACTOR THIS CODE | # OR CHILDREN WILL DIE V # WARNING WARNING WARNING WARNING # THIS IS MEANT TO BE UGLY. def next_statement @statement, @block, @comments = TokenList.new, nil, nil @stmt_number, @level = 0, 0 @new_statement, @open_block = true, false @last_tk, @last_ns_tk, @before_last_tk = nil, nil, nil @open_parens = 0 while tk = @tokens.shift break if process_token(tk) #break if @new_statement && @level == 0 @before_last_tk = @last_tk @last_tk = tk # Save last token @last_ns_tk = tk unless [TkSPACE, TkNL, TkEND_OF_SCRIPT].include? tk.class end # Return the code block with starting token and initial comments # If there is no code in the block, return nil @comments = @comments.compact if @comments if @block || !@statement.empty? Statement.new(@statement, @block, @comments) else nil end end ## # Processes a single token, modifying instance variables accordingly # # @param [RubyToken::Token] tk the token to process # @return [Boolean] whether or not the statement has been ended by +tk+ def process_token(tk) #p tk.class # !!!!!!!!!!!!!!!!!!!! REMOVED TkfLPAREN, TkfLBRACK @open_parens += 1 if [TkLPAREN, TkLBRACK].include? tk.class @open_parens -= 1 if [TkRPAREN, TkRBRACK].include? tk.class #if @open_parens < 0 || @level < 0 # STDERR.puts @block.to_s + " TOKEN #{tk.inspect}" # exit #end return if process_initial_comment(tk) # Ignore any initial comments or whitespace unless @statement.empty? && @stmt_number == 0 && [TkSPACE, TkNL, TkCOMMENT].include?(tk.class) # Decrease if end or '}' is seen @level -= 1 if [TkEND, TkRBRACE].include?(tk.class) # Increase level if we have a 'do' or block opening if [TkLBRACE, TkDO, TkBEGIN].include?(tk.class) #p "#{tk.line_no} #{@level} #{tk} \t#{tk.text} #{tk.lex_state}" @stmt_number += 1 @new_statement = true @level += 1 end # If the level is greater than 0, add the code to the block text # otherwise it's part of the statement text if @stmt_number > 0 #puts "Block of #{@statement}" #puts "#{@stmt_number} #{tk.line_no} #{@level} #{@open_parens} #{tk.class.class_name} \t#{tk.text.inspect} #{tk.lex_state} #{@open_block.inspect}" @block ||= TokenList.new @block << tk elsif @stmt_number == 0 && tk.class != TkNL && tk.class != TkSEMICOLON && tk.class != TkCOMMENT @statement << tk end #puts "#{tk.line_no} #{@level} #{@open_parens} #{tk.class.class_name} \t#{tk.text.inspect} #{tk.lex_state} #{@open_block.inspect}" # Vouch to open a block when this statement would otherwise end @open_block = [@level, tk.class] if (@new_statement || (@last_tk && @last_tk.lex_state == EXPR_BEG)) && OPEN_BLOCK_TOKENS.include?(tk.class) # Check if this token creates a new statement or not #puts "#{@open_parens} open brackets for: #{@statement.to_s}" if @open_parens == 0 && ((@last_tk && [TkSEMICOLON, TkNL, TkEND_OF_SCRIPT].include?(tk.class)) || (@open_block && @open_block.last == TkDEF && tk.class == TkRPAREN)) # Make sure we don't have any running expressions # This includes things like # # class < # Foo # # if a || # b if (@last_tk && [EXPR_END, EXPR_ARG].include?(@last_tk.lex_state)) || (@open_block && [TkNL, TkSEMICOLON].include?(tk.class) && @last_ns_tk.class != @open_block.last) @stmt_number += 1 @new_statement = true #p "NEW STATEMENT #{@block.to_s}" # The statement started with a if/while/begin, so we must go to the next level now if @open_block && @open_block.first == @level if tk.class == TkNL && @block.nil? @block = TokenList.new @block << tk end @open_block = false @level += 1 end end elsif tk.class != TkSPACE @new_statement = false end # Else keyword is kind of weird if tk.is_a? TkELSE @new_statement = true @stmt_number += 1 @open_block = false end # We're done if we've ended a statement and we're at level 0 return true if @new_statement && @level == 0 #raise "Unexpected end" if @level < 0 end end ## # Processes a comment token that comes before a statement # # @param [RubyToken::Token] tk the token to process # @return [Boolean] whether or not +tk+ was processed as an initial comment def process_initial_comment(tk) return unless @statement.empty? && tk.class == TkCOMMENT # Two new-lines in a row will destroy any comment blocks if @last_tk.class == TkNL && @before_last_tk && (@before_last_tk.class == TkNL || @before_last_tk.class == TkSPACE) @comments = nil return end # Remove the "#" and up to 1 space before the text # Since, of course, the convention is to have "# text" # and not "#text", which I deem ugly (you heard it here first) @comments ||= [] @comments << tk.text.gsub(/^#+\s{0,1}/, '') @comments.pop if @comments.size == 1 && @comments.first =~ /^\s*$/ true end end end end
require 'pathname' require 'multi_json' require 'jshintrb' module ZendeskAppsTools class Package attr_reader :root def initialize(dir) @root = Pathname.new(File.expand_path(dir)) end def files @files ||= Dir[ root.join('**/**') ].each_with_object([]) do |f, files| relative_file_name = f.sub(/#{root}\/?/, '') next unless File.file?(f) next if relative_file_name =~ /^tmp\// files << AppFile.new(self, relative_file_name) end end def template_files @template_files ||= files.select { |f| f =~ /^templates\/.*\.hdbs$/ } end def translation_files @translation_files ||= files.select { |f| f =~ /^translations\// } end def validate Validations::Manifest.call(self) + Validations::Source.call(self) + Validations::Templates.call(self) + Validations::Translations.call(self) end end end Package: move file initialization into #initialize require 'pathname' require 'multi_json' require 'jshintrb' module ZendeskAppsTools class Package attr_reader :root, :files, :template_files, :translation_files def initialize(dir) @root = Pathname.new(File.expand_path(dir)) @files = non_tmp_files @template_files = files.select { |f| f =~ /^templates\/.*\.hdbs$/ } @translation_files = files.select { |f| f =~ /^translations\// } end def validate Validations::Manifest.call(self) + Validations::Source.call(self) + Validations::Templates.call(self) + Validations::Translations.call(self) end private def non_tmp_files Dir[ root.join('**/**') ].each_with_object([]) do |f, files| relative_file_name = f.sub(/#{root}\/?/, '') next unless File.file?(f) next if relative_file_name =~ /^tmp\// files << AppFile.new(self, relative_file_name) end end end end
module Lightning # Runs bin/* commands, handling setup and execution. module Cli @usage = {} extend self # Used by bin/* to run commands def run_command(command, args) @command = command.to_s if %w{-h --help}.include?(args[0]) print_command_help else send("#{command}_command", args) end rescue StandardError, SyntaxError $stderr.puts "Error: "+ $!.message end # Executes a command with given arguments def run(argv=ARGV) if (command = argv.shift) && (actual_command = commands.sort.find {|e| e[/^#{command}/] }) run_command(actual_command, argv) elsif %w{-v --version}.include?(command) puts VERSION else puts "Command '#{command}' not found.","\n" if command && !%w{-h --help}.include?(command) print_help end end # Array of valid commands def commands @usage.keys end private def print_help puts "lightning COMMAND [arguments]", "" puts "Available commands:" print_command_table puts "", "For more information on a command use:" puts " lightning COMMAND -h", "" puts "Options: " puts " -h, --help Show this help and exit" puts " -v, --version Print current version and exit" end def print_command_table offset = commands.map {|e| e.size }.max + 2 offset += 1 unless offset % 2 == 0 @usage.sort.each do |command, (usage, desc)| puts " #{command}" << ' ' * (offset - command.size) << desc end end def print_command_help usage_array = Array(@usage[@command]) usage_array[0] = "Usage: lightning #{@command} #{usage_array[0]}" puts usage_array end def usage(command, *args) @usage[command] = args end end end tweak command help module Lightning # Runs bin/* commands, handling setup and execution. module Cli @usage = {} extend self # Used by bin/* to run commands def run_command(command, args) @command = command.to_s if %w{-h --help}.include?(args[0]) print_command_help else send("#{command}_command", args) end rescue StandardError, SyntaxError $stderr.puts "Error: "+ $!.message end # Executes a command with given arguments def run(argv=ARGV) if (command = argv.shift) && (actual_command = commands.sort.find {|e| e[/^#{command}/] }) run_command(actual_command, argv) elsif %w{-v --version}.include?(command) puts VERSION else puts "Command '#{command}' not found.","\n" if command && !%w{-h --help}.include?(command) print_help end end # Array of valid commands def commands @usage.keys end private def print_help puts "lightning COMMAND [arguments]", "" puts "Available commands:" print_command_table puts "", "For more information on a command use:" puts " lightning COMMAND -h", "" puts "Options: " puts " -h, --help Show this help and exit" puts " -v, --version Print current version and exit" end def print_command_table offset = commands.map {|e| e.size }.max + 2 offset += 1 unless offset % 2 == 0 @usage.sort.each do |command, (usage, desc)| puts " #{command}" << ' ' * (offset - command.size) << desc end end def print_command_help usage_array = Array(@usage[@command]) usage_array[0] = "Usage: lightning #{@command} #{usage_array[0]}" usage_array.insert(1, '') puts usage_array end def usage(command, *args) @usage[command] = args end end end
class ListingTitle MAX_TITLE_LENGTH = 70 UPCASE = Proc.new do |str| str.upcase end TITLECASE = Proc.new do |str| str.titlecase end DOWNCASE = Proc.new do |str| str.downcase end TRANSFORMS = [UPCASE, TITLECASE, DOWNCASE] ADJECTIVES = ["Great", "Beautiful", "Nice", "Awesome", "Flashy", "Amazing", "Charming", "Cute", "Wonderful", "Gorgeous", "Superb", "Excellent", "Good", "Slick", "Divine", "Majestic", "Enjoyable", "Stunning", "Fabulous", "Very Nice", ] ADVERTISING_STRINGS = [ "Must see!", "Too good to be true!", "Look here!", "Look no further!", "Your search is over!", "Unique!", "Rare find!", "Ready To View!", "Ready To Show!", "Check It Out!", "Ready To Move In!", "Only now!", "Dont wait!", "Chance of a lifetime!", "Pure Joy!", "Wow!", "Don't Miss Out!", "Great Chance!", "Great Opportunity!", "Cant Believe Its Still Available!", "Now Or Never!", "What An Opportunity!", "Looking For A Deal?", ] TIME_LIMITS = [ "Hurry Wont Last!", "Limited Offer!", "Now Or Never!", "Limited Opportunity!", "Dont Wait!", "Limited Time Only!", ] AMENITIES = [ /Pool/i, /Gym/i, /Hot Tub/i, /Tennis/i, /Basketball/i, /Large Yard/i, /Parking/i, /Garage/i, /Exercise Room/i, /Tiled/i, /Terrace/i, /Terrace/i, /Sauna/i, /Patio/i, /Winter Garden/i, /Barbeque/i, /Vaulted Ceiling/i, /Furnished/i, /Sun Deck/i, /Walk-In Closet/i, /Walk-In Closets/i, /Art Decor/i, ] #TODO #ame9: [Material] Floors #ame11: [Material] Kitchen #ame22: New [Kitchen, etc.] #ame25: Large [dining, living, etc.] Room #ame26: [Ocean, Waterway, etc.] View PERKS = [ /Close To Beach/i, /Gated Community/i, /Live Security/i, /Close To Preserve/i, /Golf Course Close/i, /Near University/i, /Close[ \-]?By Shops/i, /Close To Public Transportation/i, /Close To Everything/i, /In Quiet Area/i, ] AGES = [/modern/i, /remodelled/i, /refurbished/i, /rustic style/i, /renovated/i, ] BR = ["br","bed","bd"] TEMPLATES = [ "[<til>] <rai> <adj> <bdr> [<age>] <top> In [<are>, ]<loc>[, Features <ame>][,<per>]", "<rai> [<age>] <adj> <top> with <bdr>[, <ame>][, <per>] In [<are>, ]<loc>, [<til>]", "<adj> <top>, <bdr>[, <ame>] In [<are>, ]<loc>[, <per>], <rai>, [<age>][<til>]", "<adj> [<age> ] <bdr> <top> in [<are>, ]<loc>[, <per>,] [<til>, ]<rai> [, Features <ame>]", "This [, <age>]<adj> <top> In [<are>, ]<loc>, [Features <ame>][, <per>] <bdr>s[, <til>], <rai>", ] def self.generate(listing) bdr = (listing.infos["ad_bedrooms"] == "0" or listing.infos["ad_bedrooms"].nil?) ? "" : "#{listing.infos["ad_bedrooms"]}#{BR.sample}" loc = (listing.infos["ad_location"] or "") top = (listing.infos["ad_type"] or "") adj = ADJECTIVES.sample amenities_array = [] for potential_amenity in AMENITIES match = potential_amenity.match(listing.infos["ad_amenities"]) or potential_amenity.match(listing.infos["ad_description"]) if match amenities_array << match[0] end end ame = (amenities_array.sample or "") til = TIME_LIMITS.sample ages_array = [] for potential_age in AGES match = potential_age.match(listing.infos["ad_description"]) if match ages_array << match[0] end end age = (ages_array.sample or "") perks_array = [] for potential_perk in PERKS match = potential_perk.match(listing.infos["ad_description"]) if match perks_array << match[0] end end per = (perks_array.sample or "") rai = ADVERTISING_STRINGS.sample # BEGIN TEMPLATE GENERATION templates_list = TEMPLATES title = nil while title.nil? and !templates_list.empty? template = templates_list.sample prospect = String.new(template) prospect.gsub!(/<bdr>/, bdr) prospect.gsub!(/<loc>/, loc) prospect.gsub!(/<top>/, top) prospect.gsub!(/<adj>/, adj) prospect.gsub!(/<ame>/, ame) prospect.gsub!(/<til>/, til) prospect.gsub!(/<age>/, age) prospect.gsub!(/<per>/, per) prospect.gsub!(/<rai>/, rai) prospect.gsub!(/ */, ' ') # Remove double spaces puts bdr base_title = prospect.gsub(/ *\[[^\[\]]*\] */, ' ') if base_title.length > 70 templates_list -= [template] next end optional_match_list = [] for optional_match in prospect.scan(/\[[^\[\]]*\]/) optional_match_list << optional_match[1..-2] end optional_match_list.shuffle for match in optional_match_list if (base_title.size + match.size) <= 70 base_title = prospect.gsub(/\[#{match}\]/, match).gsub(/ *\[[^\[\]]*\] */, ' ').gsub(/^ */, '').gsub(/ *$/, '') end end title = prospect.gsub(/ *\[[^\[\]]*\] */, ' ').gsub(/^ */, '').gsub(/ *$/, '') end return title end end Improvements to title generator class ListingTitle MAX_TITLE_LENGTH = 70 UPCASE = Proc.new do |str| str.upcase end TITLECASE = Proc.new do |str| str.titlecase end DOWNCASE = Proc.new do |str| str.downcase end TRANSFORMS = [UPCASE, TITLECASE, DOWNCASE] ADJECTIVES = ["Great", "Beautiful", "Nice", "Awesome", "Flashy", "Amazing", "Charming", "Cute", "Wonderful", "Gorgeous", "Superb", "Excellent", "Good", "Slick", "Divine", "Majestic", "Enjoyable", "Stunning", "Fabulous", "Very Nice", ] ADVERTISING_STRINGS = [ "Must see!", "Too good to be true!", "Look here!", "Look no further!", "Your search is over!", "Unique!", "Rare find!", "Ready To View!", "Ready To Show!", "Check It Out!", "Ready To Move In!", "Only now!", "Dont wait!", "Chance of a lifetime!", "Pure Joy!", "Wow!", "Don't Miss Out!", "Great Chance!", "Great Opportunity!", "Cant Believe Its Still Available!", "Now Or Never!", "What An Opportunity!", "Looking For A Deal?", ] TIME_LIMITS = [ "Hurry Wont Last!", "Limited Offer!", "Now Or Never!", "Limited Opportunity!", "Dont Wait!", "Limited Time Only!", ] AMENITIES = [ /Pool/i, /Gym/i, /Hot Tub/i, /Tennis/i, /Basketball/i, /Large Yard/i, /Parking/i, /Garage/i, /Exercise Room/i, /Tiled/i, /Terrace/i, /Terrace/i, /Sauna/i, /Patio/i, /Winter Garden/i, /Barbeque/i, /Vaulted Ceiling/i, /Furnished/i, /Sun Deck/i, /Walk-In Closet/i, /Walk-In Closets/i, /Art Decor/i, ] #TODO #ame9: [Material] Floors #ame11: [Material] Kitchen #ame22: New [Kitchen, etc.] #ame25: Large [dining, living, etc.] Room #ame26: [Ocean, Waterway, etc.] View PERKS = [ /Close To Beach/i, /Gated Community/i, /Live Security/i, /Close To Preserve/i, /Golf Course Close/i, /Near University/i, /Close[ \-]?By Shops/i, /Close To Public Transportation/i, /Close To Everything/i, /In Quiet Area/i, ] AGES = [/modern/i, /remodelled/i, /refurbished/i, /rustic style/i, /renovated/i, ] BR = ["br","bed","bd"] TEMPLATES = [ "[<til>] <rai> <adj> <bdr> [<age>] <top> In <loc>[, Features <ame>][,<per>]", "<rai> [<age>] <adj> <top> with <bdr>[, <ame>][, <per>] In <loc>, [<til>]", "<adj> <top>, <bdr>[, <ame>] In <loc>[, <per>], <rai>, [<age>][<til>]", "<adj> [<age> ] <bdr> <top> in <loc>[, <per>,] [<til>, ]<rai> [, Features <ame>]", "This [, <age>]<adj> <top> In <loc>, [Features <ame>][, <per>] <bdr>s[, <til>], <rai>", ] def self.generate(listing) bdr = (listing.infos["ad_bedrooms"] == "0" or listing.infos["ad_bedrooms"].nil?) ? "" : "#{listing.infos["ad_bedrooms"]}#{BR.sample}" loc = (listing.infos["ad_location"] or "") top = ( listing.infos["ad_type"] or ("house" if (listing.infos["ad_description"] =~ /house/i)) or ((listing.customer.craigslist_type == "apa" ? "apt" : "condo") if (listing.infos["ad_complex"] or (listing.infos["ad_address"] =~ /(#|apt|suite|unit)/i) or (listing.infos["ad_description"] =~ /(apartment|condo)/i))) or "") adj = ADJECTIVES.sample amenities_array = [] for potential_amenity in AMENITIES match = potential_amenity.match(listing.infos["ad_amenities"]) or potential_amenity.match(listing.infos["ad_description"]) if match amenities_array << match[0] end end ame = (amenities_array.sample or "") til = TIME_LIMITS.sample ages_array = [] for potential_age in AGES match = potential_age.match(listing.infos["ad_description"]) if match ages_array << match[0] end end age = (ages_array.sample or "") perks_array = [] for potential_perk in PERKS match = potential_perk.match(listing.infos["ad_description"]) if match perks_array << match[0] end end per = (perks_array.sample or "") rai = ADVERTISING_STRINGS.sample # BEGIN TEMPLATE GENERATION templates_list = TEMPLATES title = nil while title.nil? and !templates_list.empty? template = templates_list.sample prospect = String.new(template) prospect.gsub!(/<bdr>/, bdr) prospect.gsub!(/<loc>/, loc) prospect.gsub!(/<top>/, top) prospect.gsub!(/<adj>/, adj) prospect.gsub!(/<ame>/, ame) prospect.gsub!(/<til>/, til) prospect.gsub!(/<age>/, age) prospect.gsub!(/<per>/, per) prospect.gsub!(/<rai>/, rai) prospect.gsub!(/ */, ' ') # Remove double spaces puts bdr base_title = prospect.gsub(/ *\[[^\[\]]*\] */, ' ') if base_title.length > 70 templates_list -= [template] next end optional_match_list = [] for optional_match in prospect.scan(/\[[^\[\]]*\]/) optional_match_list << optional_match[1..-2] end optional_match_list.shuffle for match in optional_match_list if (base_title.size + match.size) <= 70 base_title = prospect.gsub(/\[#{match}\]/, match).gsub(/ *\[[^\[\]]*\] */, ' ').gsub(/^ */, '').gsub(/ *$/, '') prospect = prospect.gsub(/\[#{match}\]/, match) end end title = prospect.gsub(/ *\[[^\[\]]*\] */, ' ').gsub(/^ */, '').gsub(/ *$/, '').gsub(/[ ,]*,/, ',') end return title end end
class ActionView::LogSubscriber # In order to be more friendly to Splunk, which we use for log analysis, # we override a few logging methods. There are not overriden if enable_splunk_logging is set to false in config/application.yml def render_template(event) count = event.payload[:count] || 1 hash = {:event => :render, :template => from_rails_root(event.payload[:identifier]), :total_ms => event.duration, :count => count, :ms => event.duration / count} hash.merge(:layout => event.payload[:layout]) if event.payload[:layout] Rails.logger.info(hash) end alias :render_partial :render_template alias :render_collection :render_template end module ActionDispatch class ShowExceptions private # This override logs in a format Splunk can more easily understand. # @see ActionView::LogSubscriber#render_template def log_error(exception) return unless logger ActiveSupport::Deprecation.silence do message = "event=error error_class=#{exception.class} error_message='#{exception.message}' " message << "gc_ms=#{GC.time/1000} gc_collections=#{GC.collections} gc_bytes=#{GC.growth} " if GC.respond_to?(:enable_stats) message << "orig_error_message='#{exception.original_exception.message}'" if exception.respond_to?(:original_exception) message << "annotated_source='#{exception.annoted_source_code.to_s}' " if exception.respond_to?(:annoted_source_code) message << "app_backtrace='#{application_trace(exception).join(";")}'" logger.fatal("\n\n#{message}\n\n") end end end end class ActionController::LogSubscriber require "#{File.dirname(__FILE__)}/active_record_instantiation_logs.rb" include Oink::InstanceTypeCounter def start_processing(event) #noop end # This override logs in a format Splunk can more easily understand. # @see ActionView::LogSubscriber#render_template def process_action(event) payload = event.payload additions = ActionController::Base.log_process_action(payload) params = payload[:params].except(*INTERNAL_PARAMS) log_hash = {:event => :request_completed, :status => payload[:status], :controller => payload[:controller], :action => payload[:action], :format => payload[:formats].first.to_s.upcase, :ms => ("%.0f" % event.duration).to_i, :params => params.inspect} log_hash.merge!({ :gc_ms => GC.time/1000, :gc_collections => GC.collections, :gc_bytes=> GC.growth}) if GC.respond_to?(:enable_stats) log_hash.merge!({:view_ms => payload[:view_runtime], :db_ms => payload[:db_runtime]}) unless additions.blank? log_hash.merge!(report_hash!) Rails.logger.info(log_hash) end end module Rails module Rack class Logger # This override logs in a format Splunk can more easily understand. # @see ActionView::LogSubscriber#render_template def before_dispatch(env) request = ActionDispatch::Request.new(env) path = request.fullpath Rails.logger.info("event=request_started verb=#{env["REQUEST_METHOD"]} path=#{path} ip=#{request.ip} ") end end end end module ActiveRecord class LogSubscriber # This override logs in a format Splunk can more easily understand. # @see ActionView::LogSubscriber#render_template def sql(event) self.class.runtime += event.duration return unless logger.info? payload = event.payload sql = payload[:sql].squeeze(' ') binds = nil unless (payload[:binds] || []).empty? binds = " " + payload[:binds].map { |col,v| [col.name, v] }.inspect end log_string = "event=sql name='#{payload[:name]}' ms=#{event.duration} query='#{sql}'" cleaned_trace = Rails.backtrace_cleaner.clean(caller) log_string << "backtrace_hash=#{cleaned_trace.hash} binds='#{binds}' application_backtrace='#{cleaned_trace[0..2].inspect}'" info log_string end end end Delete the sql logging, the backtrace cleaner was out of control class ActionView::LogSubscriber # In order to be more friendly to Splunk, which we use for log analysis, # we override a few logging methods. There are not overriden if enable_splunk_logging is set to false in config/application.yml def render_template(event) count = event.payload[:count] || 1 hash = {:event => :render, :template => from_rails_root(event.payload[:identifier]), :total_ms => event.duration, :count => count, :ms => event.duration / count} hash.merge(:layout => event.payload[:layout]) if event.payload[:layout] Rails.logger.info(hash) end alias :render_partial :render_template alias :render_collection :render_template end module ActionDispatch class ShowExceptions private # This override logs in a format Splunk can more easily understand. # @see ActionView::LogSubscriber#render_template def log_error(exception) return unless logger ActiveSupport::Deprecation.silence do message = "event=error error_class=#{exception.class} error_message='#{exception.message}' " message << "gc_ms=#{GC.time/1000} gc_collections=#{GC.collections} gc_bytes=#{GC.growth} " if GC.respond_to?(:enable_stats) message << "orig_error_message='#{exception.original_exception.message}'" if exception.respond_to?(:original_exception) message << "annotated_source='#{exception.annoted_source_code.to_s}' " if exception.respond_to?(:annoted_source_code) message << "app_backtrace='#{application_trace(exception).join(";")}'" logger.fatal("\n\n#{message}\n\n") end end end end class ActionController::LogSubscriber require "#{File.dirname(__FILE__)}/active_record_instantiation_logs.rb" include Oink::InstanceTypeCounter def start_processing(event) #noop end # This override logs in a format Splunk can more easily understand. # @see ActionView::LogSubscriber#render_template def process_action(event) payload = event.payload additions = ActionController::Base.log_process_action(payload) params = payload[:params].except(*INTERNAL_PARAMS) log_hash = {:event => :request_completed, :status => payload[:status], :controller => payload[:controller], :action => payload[:action], :format => payload[:formats].first.to_s.upcase, :ms => ("%.0f" % event.duration).to_i, :params => params.inspect} log_hash.merge!({ :gc_ms => GC.time/1000, :gc_collections => GC.collections, :gc_bytes=> GC.growth}) if GC.respond_to?(:enable_stats) log_hash.merge!({:view_ms => payload[:view_runtime], :db_ms => payload[:db_runtime]}) unless additions.blank? log_hash.merge!(report_hash!) Rails.logger.info(log_hash) end end module Rails module Rack class Logger # This override logs in a format Splunk can more easily understand. # @see ActionView::LogSubscriber#render_template def before_dispatch(env) request = ActionDispatch::Request.new(env) path = request.fullpath Rails.logger.info("event=request_started verb=#{env["REQUEST_METHOD"]} path=#{path} ip=#{request.ip} ") end end end end
require 'drb' require File.expand_path("../message_formatter", __FILE__) require 'yaml' require 'mail' require 'net/imap' require 'time' require 'logger' class String def col(width) self[0,width].ljust(width) end end class GmailServer MailboxAliases = { 'sent' => '[Gmail]/Sent Mail', 'all' => '[Gmail]/All Mail', 'starred' => '[Gmail]/Starred', 'important' => '[Gmail]/Important', 'drafts' => '[Gmail]/Drafts', 'spam' => '[Gmail]/Spam', 'trash' => '[Gmail]/Trash' } attr_accessor :drb_uri def initialize(config) @username, @password = config['login'], config['password'] @drb_uri = config['drb_uri'] @mailbox = nil @logger = Logger.new(STDERR) @logger.level = Logger::DEBUG end def open @imap = Net::IMAP.new('imap.gmail.com', 993, true, nil, false) @imap.login(@username, @password) end def close log "closing connection" @imap.close rescue Net::IMAP::BadResponseError @imap.disconnect end def select_mailbox(mailbox) if MailboxAliases[mailbox] mailbox = MailboxAliases[mailbox] end if mailbox == @mailbox return end log "selecting mailbox #{mailbox.inspect}" reconnect_if_necessary do @imap.select(mailbox) end @mailbox = mailbox @all_uids = [] @bad_uids = [] return "OK" end def revive_connection log "reviving connection" open log "reselecting mailbox #@mailbox" @imap.select(@mailbox) end def list_mailboxes @mailboxes ||= (@imap.list("[Gmail]/", "%") + @imap.list("", "%")). select {|struct| struct.attr.none? {|a| a == :Noselect} }. map {|struct| struct.name}. map {|name| MailboxAliases.invert[name] || name} @mailboxes.delete("INBOX") @mailboxes.unshift("INBOX") @mailboxes.join("\n") end def fetch_headers(uid_set) if uid_set.is_a?(String) uid_set = uid_set.split(",").map(&:to_i) end log "fetch headers for #{uid_set.inspect}" if uid_set.empty? return "" end results = reconnect_if_necessary do @imap.uid_fetch(uid_set, ["FLAGS", "ENVELOPE"]) end log "extracting headers" lines = results.map do |res| format_header(res) end log "returning result" return lines.join("\n") end def format_header(fetch_data) uid = fetch_data.attr["UID"] envelope = fetch_data.attr["ENVELOPE"] flags = fetch_data.attr["FLAGS"] address_struct = (@mailbox == '[Gmail]/Sent Mail' ? envelope.to.first : envelope.from.first) # TODO use this data if address_struct.name log "address name: #{address_struct.name}" end address = [address_struct.mailbox, address_struct.host].join('@') date = Time.parse(envelope.date).localtime.strftime "%D %I:%M%P" rescue envelope.date.to_s flags = format_flags(flags) "#{uid} #{(date || '').ljust(16)} #{address[0,30].ljust(30)} #{(envelope.subject || '').encode('utf-8')[0,70].ljust(70)} #{flags.col(30)}" end FLAGMAP = {:Flagged => '[*]'} # flags is an array like [:Flagged, :Seen] def format_flags(flags) flags = flags.map {|flag| FLAGMAP[flag] || flag} if flags.delete(:Seen).nil? flags << '[+]' # unread end flags.join('') end def search(limit, *query) limit = 25 if limit.to_s !~ /^\d+$/ query = ['ALL'] if query.empty? @query = query.join(' ') log "uid_search #@query #{limit}" @all_uids = reconnect_if_necessary do @imap.uid_search(@query) end uids = @all_uids[-([limit.to_i, @all_uids.size].min)..-1] || [] res = fetch_headers(uids) add_more_message_line(res, uids) end def update reconnect_if_necessary do # this is just to prime the IMAP connection # It's necessary for some reason. fetch_headers(@all_uids[-1]) end uids = reconnect_if_necessary { @imap.uid_search(@query) } new_uids = uids - @all_uids log "UPDATE: NEW UIDS: #{new_uids.inspect}" if !new_uids.empty? res = fetch_headers(new_uids) @all_uids = uids res end end # gets 100 messages prior to uid def more_messages(uid, limit=100) uid = uid.to_i x = [(@all_uids.index(uid) - limit), 0].max y = [@all_uids.index(uid) - 1, 0].max uids = @all_uids[x..y] res = fetch_headers(uids) add_more_message_line(res, uids) end def add_more_message_line(res, uids) return res if uids.empty? start_index = @all_uids.index(uids[0]) if start_index > 0 remaining = start_index res = "> Load #{[100, remaining].min} more messages. #{remaining} remaining.\n" + res end res end def lookup(uid, raw=false) log "fetching #{uid.inspect}" res = reconnect_if_necessary do @imap.uid_fetch(uid.to_i, ["FLAGS", "RFC822"])[0].attr["RFC822"] end if raw return res end mail = Mail.new(res) formatter = MessageFormatter.new(mail) part = formatter.find_text_part out = formatter.process_body message = <<-END #{format_headers(formatter.extract_headers)} #{formatter.list_parts} -- body -- #{out} END end def flag(uid_set, action, flg) uid_set = uid_set.split(",").map(&:to_i) # #<struct Net::IMAP::FetchData seqno=17423, attr={"FLAGS"=>[:Seen, "Flagged"], "UID"=>83113}> log "flag #{uid_set} #{flg} #{action}" if flg == 'Deleted' # for delete, do in a separate thread because deletions are slow Thread.new do @imap.uid_copy(uid_set, "[Gmail]/Trash") res = @imap.uid_store(uid_set, action, [flg.to_sym]) end elsif flg == '[Gmail]/Spam' @imap.uid_copy(uid_set, "[Gmail]/Spam") res = @imap.uid_store(uid_set, action, [:Deleted]) "#{uid} deleted" else log "Flagging" res = @imap.uid_store(uid_set, action, [flg.to_sym]) # log res.inspect fetch_headers(uid_set) end end # TODO copy to a different mailbox # TODO mark spam def message_template headers = {'from' => @username, 'to' => 'dhchoi@gmail.com', 'subject' => "test #{rand(90)}" } format_headers(headers) + "\n\n" end def format_headers(hash) lines = [] hash.each_pair do |key, value| if value.is_a?(Array) value = value.join(", ") end lines << "#{key}: #{value}" end lines.join("\n") end def reply_template(uid) res = @imap.uid_fetch(uid.to_i, ["FLAGS", "RFC822"])[0].attr["RFC822"] mail = Mail.new(res) formatter = MessageFormatter.new(mail) headers = formatter.extract_headers reply_to = headers['reply_to'] || headers['from'] sender = headers['from'] subject = headers['subject'] if subject !~ /Re: / subject = "Re: #{subject}" end # orig message info e.g. # On Wed, Dec 1, 2010 at 3:30 PM, Matt MacDonald (JIRA) <do-not-reply@prx.org> wrote: # quoting # quote header date = headers['date'] quote_header = "On #{date}, #{sender} wrote:\n" # TODO fix the character encoding, making sure it is valid UTF8 and encoded as such body = quote_header + formatter.process_body.gsub(/^(?=>)/, ">").gsub(/^(?!>)/, "> ") reply_headers = { 'from' => @username, 'to' => reply_to, 'cc' => headers['cc'], 'subject' => headers['subject'] } format_headers(reply_headers) + "\n\n" + body end def deliver(text) # parse the text. The headers are yaml. The rest is text body. require 'net/smtp' require 'smtp_tls' require 'mail' mail = Mail.new raw_headers, body = *text.split(/\n\n/, 2) headers = {} raw_headers.split("\n").each do |line| key, value = *line.split(':', 2) headers[key] = value end log "headers: #{headers.inspect}" log "delivering: #{headers.inspect}" mail.from = headers['from'] || @username mail.to = headers['to'] #.split(/,\s+/) mail.cc = headers['cc'] #&& headers['cc'].split(/,\s+/) mail.bcc = headers['bcc'] #&& headers['cc'].split(/,\s+/) mail.subject = headers['subject'] mail.delivery_method(*smtp_settings) mail.from ||= @username mail.body = body mail.deliver! "SENT" end def smtp_settings [:smtp, {:address => "smtp.gmail.com", :port => 587, :domain => 'gmail.com', :user_name => @username, :password => @password, :authentication => 'plain', :enable_starttls_auto => true}] end def log(string) @logger.debug string end def handle_error(error) log error end def reconnect_if_necessary(timeout = 60, &block) # if this times out, we know the connection is stale while the user is trying to update Timeout::timeout(timeout) do block.call end rescue IOError, Errno::EADDRNOTAVAIL, Timeout::Error log "error: #{$!}" log "attempting to reconnect" log(revive_connection) # try just once block.call end def self.start config = YAML::load(File.read(File.expand_path("../../config/gmail.yml", __FILE__))) $gmail = GmailServer.new config $gmail.open end def self.daemon self.start puts DRb.start_service($gmail.drb_uri, $gmail) uri = DRb.uri puts "starting gmail service at #{uri}" uri DRb.thread.join end end trap("INT") { require 'timeout' puts "closing connection" begin Timeout::timeout(5) do $gmail.close end rescue Timeout::Error put "close connection attempt timed out" end exit } if __FILE__ == $0 puts "starting gmail server" GmailServer.daemon end fix reply template to show better date format require 'drb' require File.expand_path("../message_formatter", __FILE__) require 'yaml' require 'mail' require 'net/imap' require 'time' require 'logger' class String def col(width) self[0,width].ljust(width) end end class GmailServer MailboxAliases = { 'sent' => '[Gmail]/Sent Mail', 'all' => '[Gmail]/All Mail', 'starred' => '[Gmail]/Starred', 'important' => '[Gmail]/Important', 'drafts' => '[Gmail]/Drafts', 'spam' => '[Gmail]/Spam', 'trash' => '[Gmail]/Trash' } attr_accessor :drb_uri def initialize(config) @username, @password = config['login'], config['password'] @drb_uri = config['drb_uri'] @mailbox = nil @logger = Logger.new(STDERR) @logger.level = Logger::DEBUG end def open @imap = Net::IMAP.new('imap.gmail.com', 993, true, nil, false) @imap.login(@username, @password) end def close log "closing connection" @imap.close rescue Net::IMAP::BadResponseError @imap.disconnect end def select_mailbox(mailbox) if MailboxAliases[mailbox] mailbox = MailboxAliases[mailbox] end if mailbox == @mailbox return end log "selecting mailbox #{mailbox.inspect}" reconnect_if_necessary do @imap.select(mailbox) end @mailbox = mailbox @all_uids = [] @bad_uids = [] return "OK" end def revive_connection log "reviving connection" open log "reselecting mailbox #@mailbox" @imap.select(@mailbox) end def list_mailboxes @mailboxes ||= (@imap.list("[Gmail]/", "%") + @imap.list("", "%")). select {|struct| struct.attr.none? {|a| a == :Noselect} }. map {|struct| struct.name}. map {|name| MailboxAliases.invert[name] || name} @mailboxes.delete("INBOX") @mailboxes.unshift("INBOX") @mailboxes.join("\n") end def fetch_headers(uid_set) if uid_set.is_a?(String) uid_set = uid_set.split(",").map(&:to_i) end log "fetch headers for #{uid_set.inspect}" if uid_set.empty? return "" end results = reconnect_if_necessary do @imap.uid_fetch(uid_set, ["FLAGS", "ENVELOPE"]) end log "extracting headers" lines = results.map do |res| format_header(res) end log "returning result" return lines.join("\n") end def format_header(fetch_data) uid = fetch_data.attr["UID"] envelope = fetch_data.attr["ENVELOPE"] flags = fetch_data.attr["FLAGS"] address_struct = (@mailbox == '[Gmail]/Sent Mail' ? envelope.to.first : envelope.from.first) # TODO use this data if address_struct.name log "address name: #{address_struct.name}" end address = [address_struct.mailbox, address_struct.host].join('@') date = Time.parse(envelope.date).localtime.strftime "%D %I:%M%P" rescue envelope.date.to_s flags = format_flags(flags) "#{uid} #{(date || '').ljust(16)} #{address[0,30].ljust(30)} #{(envelope.subject || '').encode('utf-8')[0,70].ljust(70)} #{flags.col(30)}" end FLAGMAP = {:Flagged => '[*]'} # flags is an array like [:Flagged, :Seen] def format_flags(flags) flags = flags.map {|flag| FLAGMAP[flag] || flag} if flags.delete(:Seen).nil? flags << '[+]' # unread end flags.join('') end def search(limit, *query) limit = 25 if limit.to_s !~ /^\d+$/ query = ['ALL'] if query.empty? @query = query.join(' ') log "uid_search #@query #{limit}" @all_uids = reconnect_if_necessary do @imap.uid_search(@query) end uids = @all_uids[-([limit.to_i, @all_uids.size].min)..-1] || [] res = fetch_headers(uids) add_more_message_line(res, uids) end def update reconnect_if_necessary do # this is just to prime the IMAP connection # It's necessary for some reason. fetch_headers(@all_uids[-1]) end uids = reconnect_if_necessary { @imap.uid_search(@query) } new_uids = uids - @all_uids log "UPDATE: NEW UIDS: #{new_uids.inspect}" if !new_uids.empty? res = fetch_headers(new_uids) @all_uids = uids res end end # gets 100 messages prior to uid def more_messages(uid, limit=100) uid = uid.to_i x = [(@all_uids.index(uid) - limit), 0].max y = [@all_uids.index(uid) - 1, 0].max uids = @all_uids[x..y] res = fetch_headers(uids) add_more_message_line(res, uids) end def add_more_message_line(res, uids) return res if uids.empty? start_index = @all_uids.index(uids[0]) if start_index > 0 remaining = start_index res = "> Load #{[100, remaining].min} more messages. #{remaining} remaining.\n" + res end res end def lookup(uid, raw=false) log "fetching #{uid.inspect}" res = reconnect_if_necessary do @imap.uid_fetch(uid.to_i, ["FLAGS", "RFC822"])[0].attr["RFC822"] end if raw return res end mail = Mail.new(res) formatter = MessageFormatter.new(mail) part = formatter.find_text_part out = formatter.process_body message = <<-END #{format_headers(formatter.extract_headers)} #{formatter.list_parts} -- body -- #{out} END end def flag(uid_set, action, flg) uid_set = uid_set.split(",").map(&:to_i) # #<struct Net::IMAP::FetchData seqno=17423, attr={"FLAGS"=>[:Seen, "Flagged"], "UID"=>83113}> log "flag #{uid_set} #{flg} #{action}" if flg == 'Deleted' # for delete, do in a separate thread because deletions are slow Thread.new do @imap.uid_copy(uid_set, "[Gmail]/Trash") res = @imap.uid_store(uid_set, action, [flg.to_sym]) end elsif flg == '[Gmail]/Spam' @imap.uid_copy(uid_set, "[Gmail]/Spam") res = @imap.uid_store(uid_set, action, [:Deleted]) "#{uid} deleted" else log "Flagging" res = @imap.uid_store(uid_set, action, [flg.to_sym]) # log res.inspect fetch_headers(uid_set) end end # TODO copy to a different mailbox # TODO mark spam def message_template headers = {'from' => @username, 'to' => 'dhchoi@gmail.com', 'subject' => "test #{rand(90)}" } format_headers(headers) + "\n\n" end def format_headers(hash) lines = [] hash.each_pair do |key, value| if value.is_a?(Array) value = value.join(", ") end lines << "#{key}: #{value}" end lines.join("\n") end def reply_template(uid) res = @imap.uid_fetch(uid.to_i, ["FLAGS", "RFC822"])[0].attr["RFC822"] mail = Mail.new(res) formatter = MessageFormatter.new(mail) headers = formatter.extract_headers reply_to = headers['reply_to'] || headers['from'] sender = headers['from'] subject = headers['subject'] if subject !~ /Re: / subject = "Re: #{subject}" end # orig message info e.g. # On Wed, Dec 1, 2010 at 3:30 PM, Matt MacDonald (JIRA) <do-not-reply@prx.org> wrote: # quoting # quote header #date = Time.parse(headers['date'].to_s) date = headers['date'] quote_header = "On #{date.strftime('%a, %b %d, %Y at %I:%M %p')}, #{sender} wrote:\n\n" # TODO fix the character encoding, making sure it is valid UTF8 and encoded as such body = quote_header + formatter.process_body.gsub(/^(?=>)/, ">").gsub(/^(?!>)/, "> ") reply_headers = { 'from' => @username, 'to' => reply_to, 'cc' => headers['cc'], 'subject' => headers['subject'] } format_headers(reply_headers) + "\n\n" + body end def deliver(text) # parse the text. The headers are yaml. The rest is text body. require 'net/smtp' require 'smtp_tls' require 'mail' mail = Mail.new raw_headers, body = *text.split(/\n\n/, 2) headers = {} raw_headers.split("\n").each do |line| key, value = *line.split(':', 2) headers[key] = value end log "headers: #{headers.inspect}" log "delivering: #{headers.inspect}" mail.from = headers['from'] || @username mail.to = headers['to'] #.split(/,\s+/) mail.cc = headers['cc'] #&& headers['cc'].split(/,\s+/) mail.bcc = headers['bcc'] #&& headers['cc'].split(/,\s+/) mail.subject = headers['subject'] mail.delivery_method(*smtp_settings) mail.from ||= @username mail.body = body mail.deliver! "SENT" end def smtp_settings [:smtp, {:address => "smtp.gmail.com", :port => 587, :domain => 'gmail.com', :user_name => @username, :password => @password, :authentication => 'plain', :enable_starttls_auto => true}] end def log(string) @logger.debug string end def handle_error(error) log error end def reconnect_if_necessary(timeout = 60, &block) # if this times out, we know the connection is stale while the user is trying to update Timeout::timeout(timeout) do block.call end rescue IOError, Errno::EADDRNOTAVAIL, Timeout::Error log "error: #{$!}" log "attempting to reconnect" log(revive_connection) # try just once block.call end def self.start config = YAML::load(File.read(File.expand_path("../../config/gmail.yml", __FILE__))) $gmail = GmailServer.new config $gmail.open end def self.daemon self.start puts DRb.start_service($gmail.drb_uri, $gmail) uri = DRb.uri puts "starting gmail service at #{uri}" uri DRb.thread.join end end trap("INT") { require 'timeout' puts "closing connection" begin Timeout::timeout(5) do $gmail.close end rescue Timeout::Error put "close connection attempt timed out" end exit } if __FILE__ == $0 puts "starting gmail server" GmailServer.daemon end
require 'base64' module Compass::Magick # A Canvas class that inherits ChunkyPNG::Canvas to represent the image as # a matrix of pixels. # # The canvas is constructed from a given width and height on a transparent # background. The list of commands is executed in order and the resulting # image is returned as a Base64 encoded PNG-24 Data URI. # # @see http://rdoc.info/gems/chunky_png/0.12.0/ChunkyPNG/Canvas # @example # # Canvas.new(320, 240).to_data_uri class Canvas < ChunkyPNG::Canvas include Utils # Initializes a new Canvas instance. # # @overload initialize(canvas, *commands) # @param [Canvas] canvas Copy image from another Canvas object. # @param [Array<Command>] commands The list of commands to execute on # new Canvas instance. # @overload initialize(data, *commands) # @param [Sass::Script::String] data A Base64 encoded Data URL # containing the image. # @param [Array<Command>] commands The list of commands to execute on # the Canvas instance. # @overload initialize(url, *commands) # @param [Sass::Script::String] url The URL to the image, relative to # the stylesheet. # @param [Array<Command>] commands The list of commands to execute on # the Canvas instance. # @overload initialize(path, *commands) # @param [Sass::Script::String] path The path to the image, relative to # the configured <tt>images_dir</tt>. # @param [Array<Command>] commands The list of commands to execute on # the Canvas instance. # @overload initialize(width, height, *commands) # @param [Sass::Script::Number] width The width of the new transparent # Canvas. # @param [Sass::Script::Number] height The height of the new transparent # Canvas. # @param [Array<Command>] commands The list of commands to execute on the # Canvas instance. def initialize(*commands) from_any(commands) commands.each_with_index { |command, index| assert_type "command[#{index}]", command, Command } commands.each { |command| command.block.call(self) } end # Sets the options hash for this node. # # @param [{Symbol => Object}] options The options hash. def options=(options) @options = options end # Serializes the Canvas as a Base64 encoded PNG-24 Data URI. # # @return [String] A Base64 encoded PNG-24 Data URI for the generated # image. def to_data_uri data = Base64.encode64(to_blob).gsub("\n", '') "url('data:image/png;base64,#{data}')" end alias :to_s :to_data_uri private def from_any(args) source = args.shift if source.kind_of?(Canvas) @width = source.width @height = source.height @pixels = source.pixels.dup elsif source.kind_of?(Sass::Script::Number) @width = source.value @height = args.shift.value @pixels = Array.new(@width * @height, ChunkyPNG::Color::TRANSPARENT) elsif source.kind_of?(Sass::Script::String) if source.value.include?('url(') if source.value.include?('base64,') encoded = source.value.match(/base64,([a-zA-Z0-9+\/=]+)/)[1] blob = Base64.decode64(encoded) canvas = ChunkyPNG::Canvas.from_blob(blob) else filename = source.value.gsub(/^url\(['"]?|["']?\)$/, '') path = File.join(Compass.configuration.css_path, filename.split('?').shift()) canvas = ChunkyPNG::Canvas.from_file(path) end else path = File.join(Compass.configuration.images_path, source.value.split('?').shift()) canvas = ChunkyPNG::Canvas.from_file(path) end @width = canvas.width @height = canvas.height @pixels = canvas.pixels else raise NotSupported.new("Canvas.new(..) expected argument of type " + "Compass::Magick::Canvas, Sass::Script::Number or Sass::Script::String " + "got #{source.class}(#{source.inspect}) instead") end end end end Allow commands to return a different Canvas instace which overrides the attributes of the original. require 'base64' module Compass::Magick # A Canvas class that inherits ChunkyPNG::Canvas to represent the image as # a matrix of pixels. # # The canvas is constructed from a given width and height on a transparent # background. The list of commands is executed in order and the resulting # image is returned as a Base64 encoded PNG-24 Data URI. # # @see http://rdoc.info/gems/chunky_png/0.12.0/ChunkyPNG/Canvas # @example # # Canvas.new(320, 240).to_data_uri class Canvas < ChunkyPNG::Canvas include Utils # Initializes a new Canvas instance. # # @overload initialize(canvas, *commands) # @param [Canvas] canvas Copy image from another Canvas object. # @param [Array<Command>] commands The list of commands to execute on # new Canvas instance. # @overload initialize(data, *commands) # @param [Sass::Script::String] data A Base64 encoded Data URL # containing the image. # @param [Array<Command>] commands The list of commands to execute on # the Canvas instance. # @overload initialize(url, *commands) # @param [Sass::Script::String] url The URL to the image, relative to # the stylesheet. # @param [Array<Command>] commands The list of commands to execute on # the Canvas instance. # @overload initialize(path, *commands) # @param [Sass::Script::String] path The path to the image, relative to # the configured <tt>images_dir</tt>. # @param [Array<Command>] commands The list of commands to execute on # the Canvas instance. # @overload initialize(width, height, *commands) # @param [Sass::Script::Number] width The width of the new transparent # Canvas. # @param [Sass::Script::Number] height The height of the new transparent # Canvas. # @param [Array<Command>] commands The list of commands to execute on the # Canvas instance. def initialize(*commands) from_any(commands) commands.each_with_index { |command, index| assert_type "command[#{index}]", command, Command } commands.each do |command| result = command.block.call(self) inherit result, false if result.kind_of?(ChunkyPNG::Canvas) unless result == self end end # Sets the options hash for this node. # # @param [{Symbol => Object}] options The options hash. def options=(options) @options = options end # Serializes the Canvas as a Base64 encoded PNG-24 Data URI. # # @return [String] A Base64 encoded PNG-24 Data URI for the generated # image. def to_data_uri data = Base64.encode64(to_blob).gsub("\n", '') "url('data:image/png;base64,#{data}')" end alias :to_s :to_data_uri private def inherit(canvas, copy = true) @width = canvas.width @height = canvas.height @pixels = (copy ? canvas.pixels.dup : canvas.pixels) self end def from_any(args) source = args.shift if source.kind_of?(Canvas) inherit source elsif source.kind_of?(Sass::Script::Number) inherit ChunkyPNG::Canvas.new(source.value, args.shift.value), false elsif source.kind_of?(Sass::Script::String) if source.value.include?('url(') if source.value.include?('base64,') encoded = source.value.match(/base64,([a-zA-Z0-9+\/=]+)/)[1] blob = Base64.decode64(encoded) canvas = ChunkyPNG::Canvas.from_blob(blob) else filename = source.value.gsub(/^url\(['"]?|["']?\)$/, '') path = File.join(Compass.configuration.css_path, filename.split('?').shift()) canvas = ChunkyPNG::Canvas.from_file(path) end else path = File.join(Compass.configuration.images_path, source.value.split('?').shift()) canvas = ChunkyPNG::Canvas.from_file(path) end inherit canvas, false else raise NotSupported.new("Canvas.new(..) expected argument of type " + "Compass::Magick::Canvas, Sass::Script::Number or Sass::Script::String " + "got #{source.class}(#{source.inspect}) instead") end end end end
class Matrix def initialize(matrix_a = nil, matrix_b = nil) @matrix_a = matrix_a @matrix_b = matrix_b @rows = @matrix_a.count @cols = @matrix_a[0].count end def gaussian_elimination matrix_a = @matrix_a.clone for k in (0 .. @rows - 1) for i in (k + 1 .. @rows - 1) times = matrix_a[i][k] / matrix_a[k][k].to_f for j in (k .. @cols - 1) matrix_a[i][j] = matrix_a[i][j] - times * matrix_a[k][j].to_f end end end matrix_a end end add the processing of @matrix_b class Matrix def initialize(matrix_a = nil, matrix_b = nil) @matrix_a = matrix_a @matrix_b = matrix_b @rows = @matrix_a.count @cols = @matrix_a[0].count @matrix_b.map!{|row| [row]} if !@matrix_b[0].is_a?(Array) && @rows > 1 end def gaussian_elimination matrix_a = @matrix_a.clone rescue nil matrix_b = @matrix_b.clone rescue nil for k in (0 .. @rows - 1) for i in (k + 1 .. @rows - 1) times = matrix_a[i][k] / matrix_a[k][k].to_f for j in (k .. @cols - 1) matrix_a[i][j] = matrix_a[i][j] - times * matrix_a[k][j].to_f matrix_b[i][j] = matrix_b[i][j] - times * matrix_b[k][j].to_f if j < matrix_b[i].count end end end [matrix_a, matrix_b] end end
require "dropbox_sdk" require "memot/evernote" require "memot/markdown" module Memot REVISION_FILENAME = ".memot.revision.yml" class DropboxCli def initialize(access_token, evernote) @client = DropboxClient.new(access_token) @evernote = evernote end def parse_dir_tree(path, notebook, recursive = false) latest_revision = get_revision(path) refreshed_latest_revision = latest_revision @client.metadata(path)["contents"].each do |cont| cont_path = cont["path"] if cont["is_dir"] # if recursive # child_rev = parse_dir_tree(cont_path, recursive) # latest_revision = child_rev if child_rev > latest_revision # end else if (cont["revision"] > latest_revision) && (%w{.md .markdown}.include? File.extname(cont_path).downcase) save_to_evernote(cont_path, notebook) refreshed_latest_revision = cont["revision"] if cont["revision"] > refreshed_latest_revision end end end set_revision(path, refreshed_latest_revision) if refreshed_latest_revision > latest_revision end def self.auth(app_key, app_secret) flow = DropboxOAuth2FlowNoRedirect.new(app_key, app_seccret) puts "Access to this URL: #{flow.start}" print "PIN code: " code = gets.strip access_token, user_id = flow.finish(code) end private def save_to_evernote(path, notebook) body = Memot::Markdown.parse_markdown(get_file_body(path)) title = File.basename(path) if (note_guid = @evernote.get_note_guid(title, notebook)) == "" @evernote.create_note(title, body, notebook) puts "Created: #{notebook}/#{title}" else @evernote.update_note(title, body, notebook, note_guid) puts "Updated: #{notebook}/#{title}" end end def revision_path(dir) # Only text-type extensions are allowed. ".memot.revision" is not allowed. File.expand_path(REVISION_FILENAME, dir) end def get_revision(dir) if file_exists?(dir, REVISION_FILENAME) get_file_body(revision_path(dir)).strip.to_i else set_revision(dir, 0) 0 end end def set_revision(dir, revision) @client.put_file(revision_path(dir), revision, true) end def get_file_body(path) @client.get_file(path) rescue DropboxError => e $stderr.puts e.message exit 1 end def file_exists?(dir, name) @client.search(dir, name).length > 0 end def save_file(path, filepath) body = get_file_body(path) open(filepath, "w+") { |f| f.puts body } unless filepath == "" end end end Rename variable require "dropbox_sdk" require "memot/evernote" require "memot/markdown" module Memot REVISION_FILENAME = ".memot.revision.yml" class DropboxCli def initialize(access_token, evernote) @client = DropboxClient.new(access_token) @evernote = evernote end def parse_dir_tree(path, notebook, recursive = false) latest_revision = get_revision(path) updated_revision_revision = latest_revision @client.metadata(path)["contents"].each do |cont| cont_path = cont["path"] if cont["is_dir"] # if recursive # child_rev = parse_dir_tree(cont_path, recursive) # latest_revision = child_rev if child_rev > latest_revision # end else if (cont["revision"] > latest_revision) && (%w{.md .markdown}.include? File.extname(cont_path).downcase) save_to_evernote(cont_path, notebook) updated_revision_revision = cont["revision"] if cont["revision"] > updated_revision_revision end end end set_revision(path, updated_revision_revision) if updated_revision_revision > latest_revision end def self.auth(app_key, app_secret) flow = DropboxOAuth2FlowNoRedirect.new(app_key, app_seccret) puts "Access to this URL: #{flow.start}" print "PIN code: " code = gets.strip access_token, user_id = flow.finish(code) end private def save_to_evernote(path, notebook) body = Memot::Markdown.parse_markdown(get_file_body(path)) title = File.basename(path) if (note_guid = @evernote.get_note_guid(title, notebook)) == "" @evernote.create_note(title, body, notebook) puts "Created: #{notebook}/#{title}" else @evernote.update_note(title, body, notebook, note_guid) puts "Updated: #{notebook}/#{title}" end end def revision_path(dir) # Only text-type extensions are allowed. ".memot.revision" is not allowed. File.expand_path(REVISION_FILENAME, dir) end def get_revision(dir) if file_exists?(dir, REVISION_FILENAME) get_file_body(revision_path(dir)).strip.to_i else set_revision(dir, 0) 0 end end def set_revision(dir, revision) @client.put_file(revision_path(dir), revision, true) end def get_file_body(path) @client.get_file(path) rescue DropboxError => e $stderr.puts e.message exit 1 end def file_exists?(dir, name) @client.search(dir, name).length > 0 end def save_file(path, filepath) body = get_file_body(path) open(filepath, "w+") { |f| f.puts body } unless filepath == "" end end end
module Metaa VERSION = "0.0.13" end Bumped version to 0.1.0 module Metaa VERSION = "0.1.0" end
module Metar module VERSION #:nodoc: MAJOR = 0 MINOR = 9 TINY = 13 STRING = [ MAJOR, MINOR, TINY ].join( '.' ) end end Version bump for release module Metar module VERSION #:nodoc: MAJOR = 0 MINOR = 9 TINY = 14 STRING = [ MAJOR, MINOR, TINY ].join( '.' ) end end
module Metro VERSION = "0.0.2" end Version 0.0.3 module Metro VERSION = "0.0.3" end
# Generate Dot Code from ruby objects # Include the Dot module, # provide child_nodes() in nodes, optionally parent_nodes(), sibling_nodes() # provide dot_label() # optionally provide dot_record() which # returns [record_object, position ] module MFactor def dot_escape(str) # str.to_s.gsub(/[-+.><*=]/,{ str.to_s.gsub(/[><|]/,{ # '+' => 'plus', # '-' => 'minus', # '.' => 'dot', '>' => '\>', '<' => '\<', '|' => '\|', # '*' => 'times', # '=' => 'equalp', }) end module_function :dot_escape def assert_is_node(n) raise "not a GraphNode: #{n}" unless n.is_a? GraphNode end module_function :assert_is_node module GraphNode require 'set' require 'ostruct' @@unique='1' attr_accessor :record # def add_child(*clist) # puts "maybe add child to #{node_name}..." # @child_nodes ||= [] # clist.each do |c| # MFactor::assert_is_node(c) # unless @child_nodes.member? c # puts "yes" # @child_nodes.push c # c.add_parent self # end # end # end # def add_parent(*clist) # puts "maybe add parent to #{node_name}..." # @parent_nodes ||= [] # clist.each do |c| # MFactor::assert_is_node(c) # unless @parent_nodes.member? c # puts "yes" # @parent_nodes.push c # c.add_child self # end # end # end # def add_sibling(*clist) # puts "sibling to #{node_name}" # @sibling_nodes ||= [] # clist.each do |c| # MFactor::assert_is_node(c) # unless @sibling_nodes.member? c # @sibling_nodes.push c # c.add_sibling self # end # end # end # overwrite equality test def ==(x) self.equal? x end def is_record? is_a? DotRecord end def gensym(s="G") (s.to_s+@@unique.succ!).to_sym end module_function :gensym def node_name @name||=gensym(self.class.to_s.split("::").last) # @name||=gensym("node") @name end # traverse from 1 node, collect all reachable nodes # def collect_nodes(nodes=[],transitions=Set.new) # return nodes,transitions if nodes.member?(self) # @child_nodes ||= [] # @parent_nodes ||= [] # @sibling_nodes ||= [] # self.record ||= nil # nodes.push self # puts "collected #{node_name}" # if is_record? # puts "collect port" # get_port_nodes.map do |n| # n.collect_nodes(nodes,transitions) # end # end # if self.record # puts "node in record" # self.record.collect_nodes(nodes,transitions) # end # @child_nodes.each do |n| # puts "collect child" # transitions.add [self,n] # n.collect_nodes(nodes,transitions) # end # @parent_nodes.each do |n| # puts "collect parent" # transitions.add [n,self] # n.collect_nodes(nodes,transitions) # end # @sibling_nodes.each do |n| # puts "collect sibling" # n.collect_nodes(nodes,transitions) # end # return nodes,transitions # end end module DotRecord attr_accessor :handle_port def props @port_nodes ||= [] end def add_port(c,handle_port_p=false) props if handle_port_p # puts "found handle" self.handle_port=c end # puts "port to #{node_name}" MFactor::assert_is_node(c) unless @port_nodes.member? c @port_nodes.push c raise "node already in record #{c.record.node_name}" if c.record c.record = self end end # if explicitely set, take that, otherwise rely on instance having implemented port_nodes def get_port_nodes props if @port_nodes.empty? # puts "ports lazy" pnodes = self.port_nodes() pnodes.each do |n| add_port n end end @port_nodes end def node_name @name||=gensym(self.class.to_s.split("::").last) @name end # generate dot code for one record def dot_code(io) # puts "drawing record" props portinfos = get_port_nodes.map do |n| OpenStruct.new(name: n.node_name, label: MFactor::dot_escape(n.dot_label)) end io << node_name << " [label=\"{{" io << portinfos.map do |p| "<#{p.name}> #{p.label}" end.join(" | ") io << "}}\"]\n" end end # control flow and data flow, enough information to generate some code (after de-SSA-ing) class CDFG attr_accessor :inputs attr_accessor :outputs attr_accessor :start attr_accessor :end def initialize @nodes=[] @control_edges=[] @data_edges=[] @inputs=[] @outputs=[] @start,@end=nil end # this needs only to be used when there is a node without a transition in the graph def add_node(n) @nodes.push n unless @nodes.include? n end def add_control_edge(s,d) add_transition s,d label=nil # Check if we come from choice node. If yes, label the correspondig edges if s.class == ChoiceNode if s.else_edge raise "choice node has more than one outgoing edge" elsif s.then_edge s.else_edge = true label="else" else s.then_edge = true label="then" end end @control_edges.push [s,d,label] end def add_data_edge(s,d) add_transition s,d @data_edges.push [s,d] end # generate graph from this node on, reachability determined by self def dot(io) # puts "drawing" io << <<END digraph test_definition { graph [ rankdir=TB ] node [shape=record,fontname=helvetica] edge [fontname=helvetica, arrowsize=0.5] END # nodes,transitions = collect_nodes # transitions.to_a.flatten.to_set.each do |n| @nodes.each do |n| next if n.record # if we are a port, skip, record handles drawing if n.is_record? # if we are a record, call specialized function n.dot_code(io) else label_sym = (n.class == JoinNode ? :xlabel : :label) attrs={label_sym => '"'+n.dot_label+'"'} if n.respond_to? :dot_node_shape attrs[:shape]='"'+n.dot_node_shape+'"' end attr_string=attrs.map do |k,v| "#{k.to_s}=#{v}" end.join(", ") io.puts "#{n.node_name} [#{attr_string}]" end end @control_edges.each do |s,d,label| attrs={color:"red",fontcolor:"red"} attrs[:label] = '"'+label+'"' if label draw_transition(s,d,io,attrs) end @data_edges.each do |s,d| draw_transition(s,d,io,{color: "green"}) end io.puts "}" self end # return all nodes that are followers of a given node (TODO: check performance) def data_successors node @data_edges.find_all{ |s,d| s == node }.map{ |s,d| d} end private def draw_transition(s,d,io,attrs={}) sname = s.node_name.to_s dname = d.node_name.to_s if s.is_record? && s.handle_port # puts "using handle" sname = sname+':'+s.handle_port.node_name.to_s end if d.is_record? && d.handle_port # puts "using handle" dname = dname+':'+d.handle_port.node_name.to_s end if s.record sname = s.record.node_name.to_s+':'+sname end if d.record dname = d.record.node_name.to_s+':'+dname end attr_string = if attrs ' ['+attrs.map {|k,v| "#{k.to_s}=#{v}"}.join(", ")+']' else "" end io.puts "#{sname} -> #{dname}#{attr_string}" end # register nodes if necessary def add_transition(source,dest) add_node source add_node dest if source.record add_node source.record end if dest.record add_node dest.record end end end end add `data_predecessor` to CDFG finds the node that supplys the data for a given node # Generate Dot Code from ruby objects # Include the Dot module, # provide child_nodes() in nodes, optionally parent_nodes(), sibling_nodes() # provide dot_label() # optionally provide dot_record() which # returns [record_object, position ] module MFactor def dot_escape(str) # str.to_s.gsub(/[-+.><*=]/,{ str.to_s.gsub(/[><|]/,{ # '+' => 'plus', # '-' => 'minus', # '.' => 'dot', '>' => '\>', '<' => '\<', '|' => '\|', # '*' => 'times', # '=' => 'equalp', }) end module_function :dot_escape def assert_is_node(n) raise "not a GraphNode: #{n}" unless n.is_a? GraphNode end module_function :assert_is_node module GraphNode require 'set' require 'ostruct' @@unique='1' attr_accessor :record # def add_child(*clist) # puts "maybe add child to #{node_name}..." # @child_nodes ||= [] # clist.each do |c| # MFactor::assert_is_node(c) # unless @child_nodes.member? c # puts "yes" # @child_nodes.push c # c.add_parent self # end # end # end # def add_parent(*clist) # puts "maybe add parent to #{node_name}..." # @parent_nodes ||= [] # clist.each do |c| # MFactor::assert_is_node(c) # unless @parent_nodes.member? c # puts "yes" # @parent_nodes.push c # c.add_child self # end # end # end # def add_sibling(*clist) # puts "sibling to #{node_name}" # @sibling_nodes ||= [] # clist.each do |c| # MFactor::assert_is_node(c) # unless @sibling_nodes.member? c # @sibling_nodes.push c # c.add_sibling self # end # end # end # overwrite equality test def ==(x) self.equal? x end def is_record? is_a? DotRecord end def gensym(s="G") (s.to_s+@@unique.succ!).to_sym end module_function :gensym def node_name @name||=gensym(self.class.to_s.split("::").last) # @name||=gensym("node") @name end # traverse from 1 node, collect all reachable nodes # def collect_nodes(nodes=[],transitions=Set.new) # return nodes,transitions if nodes.member?(self) # @child_nodes ||= [] # @parent_nodes ||= [] # @sibling_nodes ||= [] # self.record ||= nil # nodes.push self # puts "collected #{node_name}" # if is_record? # puts "collect port" # get_port_nodes.map do |n| # n.collect_nodes(nodes,transitions) # end # end # if self.record # puts "node in record" # self.record.collect_nodes(nodes,transitions) # end # @child_nodes.each do |n| # puts "collect child" # transitions.add [self,n] # n.collect_nodes(nodes,transitions) # end # @parent_nodes.each do |n| # puts "collect parent" # transitions.add [n,self] # n.collect_nodes(nodes,transitions) # end # @sibling_nodes.each do |n| # puts "collect sibling" # n.collect_nodes(nodes,transitions) # end # return nodes,transitions # end end module DotRecord attr_accessor :handle_port def props @port_nodes ||= [] end def add_port(c,handle_port_p=false) props if handle_port_p # puts "found handle" self.handle_port=c end # puts "port to #{node_name}" MFactor::assert_is_node(c) unless @port_nodes.member? c @port_nodes.push c raise "node already in record #{c.record.node_name}" if c.record c.record = self end end # if explicitely set, take that, otherwise rely on instance having implemented port_nodes def get_port_nodes props if @port_nodes.empty? # puts "ports lazy" pnodes = self.port_nodes() pnodes.each do |n| add_port n end end @port_nodes end def node_name @name||=gensym(self.class.to_s.split("::").last) @name end # generate dot code for one record def dot_code(io) # puts "drawing record" props portinfos = get_port_nodes.map do |n| OpenStruct.new(name: n.node_name, label: MFactor::dot_escape(n.dot_label)) end io << node_name << " [label=\"{{" io << portinfos.map do |p| "<#{p.name}> #{p.label}" end.join(" | ") io << "}}\"]\n" end end # control flow and data flow, enough information to generate some code (after de-SSA-ing) class CDFG attr_accessor :inputs attr_accessor :outputs attr_accessor :start attr_accessor :end def initialize @nodes=[] @control_edges=[] @data_edges=[] @inputs=[] @outputs=[] @start,@end=nil end # this needs only to be used when there is a node without a transition in the graph def add_node(n) @nodes.push n unless @nodes.include? n end def add_control_edge(s,d) add_transition s,d label=nil # Check if we come from choice node. If yes, label the correspondig edges if s.class == ChoiceNode if s.else_edge raise "choice node has more than one outgoing edge" elsif s.then_edge s.else_edge = true label="else" else s.then_edge = true label="then" end end @control_edges.push [s,d,label] end def add_data_edge(s,d) add_transition s,d @data_edges.push [s,d] end # generate graph from this node on, reachability determined by self def dot(io) # puts "drawing" io << <<END digraph test_definition { graph [ rankdir=TB ] node [shape=record,fontname=helvetica] edge [fontname=helvetica, arrowsize=0.5] END # nodes,transitions = collect_nodes # transitions.to_a.flatten.to_set.each do |n| @nodes.each do |n| next if n.record # if we are a port, skip, record handles drawing if n.is_record? # if we are a record, call specialized function n.dot_code(io) else label_sym = (n.class == JoinNode ? :xlabel : :label) attrs={label_sym => '"'+n.dot_label+'"'} if n.respond_to? :dot_node_shape attrs[:shape]='"'+n.dot_node_shape+'"' end attr_string=attrs.map do |k,v| "#{k.to_s}=#{v}" end.join(", ") io.puts "#{n.node_name} [#{attr_string}]" end end @control_edges.each do |s,d,label| attrs={color:"red",fontcolor:"red"} attrs[:label] = '"'+label+'"' if label draw_transition(s,d,io,attrs) end @data_edges.each do |s,d| draw_transition(s,d,io,{color: "green"}) end io.puts "}" self end # return all nodes that are followers of a given node (TODO: check performance) def data_successors node @data_edges.find_all{ |s,d| s == node }.map{ |s,d| d} end def data_predecessor node edge=@data_edges.find{ |s,d| d == node } if edge edge[0] else nil end end private def draw_transition(s,d,io,attrs={}) sname = s.node_name.to_s dname = d.node_name.to_s if s.is_record? && s.handle_port # puts "using handle" sname = sname+':'+s.handle_port.node_name.to_s end if d.is_record? && d.handle_port # puts "using handle" dname = dname+':'+d.handle_port.node_name.to_s end if s.record sname = s.record.node_name.to_s+':'+sname end if d.record dname = d.record.node_name.to_s+':'+dname end attr_string = if attrs ' ['+attrs.map {|k,v| "#{k.to_s}=#{v}"}.join(", ")+']' else "" end io.puts "#{sname} -> #{dname}#{attr_string}" end # register nodes if necessary def add_transition(source,dest) add_node source add_node dest if source.record add_node source.record end if dest.record add_node dest.record end end end end
module Minil module Version MAJOR, MINOR, TEENY, PATCH = 0, 15, 0, nil STRING = [MAJOR, MINOR, TEENY, PATCH].compact.join('.') end VERSION = Version::STRING end Updated to 0.16.0 module Minil module Version MAJOR, MINOR, TEENY, PATCH = 0, 17, 0, nil STRING = [MAJOR, MINOR, TEENY, PATCH].compact.join('.') end VERSION = Version::STRING end
# Add a callback - to be executed before each request in development, # and at startup in production - to patch existing app classes. # Doing so in init/environment.rb wouldn't work in development, since # classes are reloaded, but initialization is not run each time. # See http://stackoverflow.com/questions/7072758/plugin-not-reloading-in-development-mode # Rails.configuration.to_prepare do PublicBody.class_eval do def jurisdiction if has_tag?('ACT_state') :act elsif has_tag?('NSW_state') || has_tag?('NSW_council') :nsw elsif has_tag?('NT_state') || has_tag?('NT_council') :nt elsif has_tag?('QLD_state') || has_tag?('QLD_council') :qld elsif has_tag?('SA_state') || has_tag?('SA_council') :sa elsif has_tag?('TAS_state') || has_tag?('TAS_council') :tas elsif has_tag?('VIC_state') || has_tag?('VIC_council') :vic elsif has_tag?('WA_state') || has_tag?('WA_council') :wa elsif has_tag?('federal') :federal end end end InfoRequest.class_eval do def australian_law_used if public_body.jurisdiction == :nsw "gipa" elsif public_body.jurisdiction == :qld || public_body.jurisdiction == :tas "rti" else "foi" end end def law_used_full if australian_law_used == "gipa" _("Government Information (Public Access)") elsif australian_law_used == "rti" _("Right to Information") elsif australian_law_used == 'foi' _("Freedom of Information") elsif australian_law_used == 'eir' _("Environmental Information Regulations") else raise "Unknown law used '" + australian_law_used + "'" end end def law_used_short if australian_law_used == "gipa" _("GIPA") elsif australian_law_used == "rti" _("RTI") elsif australian_law_used == 'foi' _("FOI") elsif australian_law_used == 'eir' _("EIR") else raise "Unknown law used '" + australian_law_used + "'" end end # Unused method def law_used_act if australian_law_used == "gipa" _("Government Information (Public Access) Act") elsif australian_law_used == "rti" _("Right to Information Act") elsif australian_law_used == 'foi' _("Freedom of Information Act") elsif australian_law_used == 'eir' _("Environmental Information Regulations") else raise "Unknown law used '" + australian_law_used + "'" end end # Unused method def law_used_with_a if australian_law_used == "gipa" _("A Government Information (Public Access) request") elsif australian_law_used == "rti" _("A Right to Information request") elsif australian_law_used == 'foi' _("A Freedom of Information request") elsif australian_law_used == 'eir' _("An Environmental Information Regulations request") else raise "Unknown law used '" + australian_law_used + "'" end end end end Remove EIR since it's not a law used in Australia # Add a callback - to be executed before each request in development, # and at startup in production - to patch existing app classes. # Doing so in init/environment.rb wouldn't work in development, since # classes are reloaded, but initialization is not run each time. # See http://stackoverflow.com/questions/7072758/plugin-not-reloading-in-development-mode # Rails.configuration.to_prepare do PublicBody.class_eval do def jurisdiction if has_tag?('ACT_state') :act elsif has_tag?('NSW_state') || has_tag?('NSW_council') :nsw elsif has_tag?('NT_state') || has_tag?('NT_council') :nt elsif has_tag?('QLD_state') || has_tag?('QLD_council') :qld elsif has_tag?('SA_state') || has_tag?('SA_council') :sa elsif has_tag?('TAS_state') || has_tag?('TAS_council') :tas elsif has_tag?('VIC_state') || has_tag?('VIC_council') :vic elsif has_tag?('WA_state') || has_tag?('WA_council') :wa elsif has_tag?('federal') :federal end end end InfoRequest.class_eval do def australian_law_used if public_body.jurisdiction == :nsw "gipa" elsif public_body.jurisdiction == :qld || public_body.jurisdiction == :tas "rti" else "foi" end end def law_used_full if australian_law_used == "gipa" _("Government Information (Public Access)") elsif australian_law_used == "rti" _("Right to Information") elsif australian_law_used == 'foi' _("Freedom of Information") else raise "Unknown law used '" + australian_law_used + "'" end end def law_used_short if australian_law_used == "gipa" _("GIPA") elsif australian_law_used == "rti" _("RTI") elsif australian_law_used == 'foi' _("FOI") else raise "Unknown law used '" + australian_law_used + "'" end end # Unused method def law_used_act if australian_law_used == "gipa" _("Government Information (Public Access) Act") elsif australian_law_used == "rti" _("Right to Information Act") elsif australian_law_used == 'foi' _("Freedom of Information Act") else raise "Unknown law used '" + australian_law_used + "'" end end # Unused method def law_used_with_a if australian_law_used == "gipa" _("A Government Information (Public Access) request") elsif australian_law_used == "rti" _("A Right to Information request") elsif australian_law_used == 'foi' _("A Freedom of Information request") else raise "Unknown law used '" + australian_law_used + "'" end end end end
# Copyright (C) 2014-2016 MongoDB, 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. module Mongo # The current version of the driver. # # @since 2.0.0 VERSION = '2.4.0'.freeze end Update version to 2.4.0.rc0 # Copyright (C) 2014-2016 MongoDB, 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. module Mongo # The current version of the driver. # # @since 2.0.0 VERSION = '2.4.0.rc0'.freeze end
module Lotion extend self def require(path) if resolve(path) puts " Warning Please add `app.require \"#{path}\"` within Lotion.setup".yellow else raise LoadError, "cannot load such file -- #{path}" end end def warn(*args) message = begin if args.size == 1 args.first else object, method, caller = *args "Called #{object}.#{method} from #{resolve caller[0]}" end end puts " Warning #{message}".yellow end private def resolve(path) if path.match /^\// path else path = path.gsub(/\.rb.*$/, "") + ".rb" LOAD_PATHS.each do |load_path| if File.exists?(absolute_path = "#{load_path}/#{path}") return absolute_path end end nil end end end Improved Lotion.require and Lotion.resolve module Lotion extend self def require(path) return if required.include? path required << path if absolute_path = resolve(path) unless (IGNORED_REQUIRES + REQUIRED).include?(absolute_path) puts " Warning Add the following with Lotion.setup block: app.require \"#{path}\"".yellow end else raise LoadError, "cannot load such file -- #{path}" end end def warn(*args) message = begin if args.size == 1 args.first else object, method, caller = *args "Called #{object}.#{method} from #{resolve caller[0]}" end end puts " Warning #{message}".yellow end private def required @required ||= [] end def resolve(path) if path.match /^\// path else path = path.gsub(/\.rb.*$/, "") + ".rb" (GEM_PATHS + LOAD_PATHS).each do |load_path| if File.exists?(absolute_path = "#{load_path}/#{path}") return absolute_path end end nil end end end
require 'mountain_view/version' require 'mountain_view/configuration' require 'mountain_view/presenter' require 'mountain_view/component' require 'mountain_view/stub' module MountainView def self.configuration @configuration ||= Configuration.new end def self.configure yield(configuration) end end require 'mountain_view/engine' if defined?(Rails) Add Frozen String Literal magic comment for mountain_view.rb # frozen_string_literal: true require 'mountain_view/version' require 'mountain_view/configuration' require 'mountain_view/presenter' require 'mountain_view/component' require 'mountain_view/stub' module MountainView def self.configuration @configuration ||= Configuration.new end def self.configure yield(configuration) end end require 'mountain_view/engine' if defined?(Rails)
class NbaStats::CLI def call puts "Welcome to the NBA Stats CLI Gem" start end def start puts "Input one of the team names below to load their roster." puts "Input exit to leave this program." puts "Here's the list of current teams" make_teams if NbaStats::Team.all.empty? rows = [["Eastern Conference", "Western Conference"]] west_teams = NbaStats::Team.western_names east_teams = NbaStats::Team.eastern_names i = 0 while i < 15 rows << [east_teams[i], west_teams[i]] i += 1 end team_table = Terminal::Table.new rows: rows puts team_table input = "" while input != "exit" puts "Input a team name to see their roster: " input = gets.strip if (NbaStats::Team.team_names.include? input) display_roster(input) puts "Input a player name to see their individual stats: " input = gets.strip while (NbaStats::Player.player_names.include? input) display_player_stats(input) puts "Input another player name from this team to see their stats." puts "Or input change teams to see another team's roster." input = gets.strip if input == "change teams" || input == "change team" start end end break end end end def make_teams teams_array = NbaStats::Scraper.get_teams NbaStats::Team.create_from_collection(teams_array) end def display_roster(requested_team) team = NbaStats::Team.all.detect {|team| team.name == requested_team} team.add_players if team.players.empty? puts team.name + " roster:" rows = [["Number", "Name", "Position", "Height", "Experience"]] team.players.each do |player| rows << [player.number, player.name, player.position, player.height, player.experience] end roster_table = Terminal::Table.new rows: rows puts roster_table end def display_player_stats(requested_player) player = NbaStats::Player.all.detect {|player| player.name == requested_player} player.add_player_stats rows = [["Points/Game", "Assists/Game", "Rebounds/Game", "Blocks/Game", "Steals/Game", "FG%", "3P%", "FT%", "Minutes/Game",]] rows << [player.points_pg, player.assists_pg, player.rebounds_pg, player.blocks_pg, player.steals_pg, player.fg_percentage, player.three_percentage, player.ft_percentage, player.minutes_pg] puts "Here are #{player.name}'s 2015-16 stats: " stats_table = Terminal::Table.new rows: rows puts stats_table end end Refactoring CLI class NbaStats::CLI def call puts "Welcome to the NBA Stats CLI Gem" start end def start puts "Input one of the team names below to load their roster." puts "Input exit to leave this program." puts "Here's the list of current teams" display_teams input = "" while input != "exit" puts "Input a team name to see their roster: " input = gets.strip if (NbaStats::Team.team_names.include? input) display_roster(input) puts "Input a player name to see their individual stats: " input = gets.strip while (NbaStats::Player.player_names.include? input) display_player_stats(input) puts "Input another player name from this team to see their stats." puts "Or input change teams to see another team's roster." input = gets.strip if input == "change teams" || input == "change team" start end end break end end end def make_teams teams_array = NbaStats::Scraper.get_teams NbaStats::Team.create_from_collection(teams_array) end def display_teams make_teams if NbaStats::Team.all.empty? rows = [["Eastern Conference", "Western Conference"]] west_teams = NbaStats::Team.western_names east_teams = NbaStats::Team.eastern_names i = 0 while i < 15 rows << [east_teams[i], west_teams[i]] i += 1 end puts Terminal::Table.new rows: rows end def display_roster(requested_team) team = NbaStats::Team.all.detect {|team| team.name == requested_team} team.add_players if team.players.empty? puts team.name + " roster:" rows = [["Number", "Name", "Position", "Height", "Experience"]] team.players.each do |player| rows << [player.number, player.name, player.position, player.height, player.experience] end puts Terminal::Table.new rows: rows end def display_player_stats(requested_player) player = NbaStats::Player.all.detect {|player| player.name == requested_player} player.add_player_stats rows = [["Points/Game", "Assists/Game", "Rebounds/Game", "Blocks/Game", "Steals/Game", "FG%", "3P%", "FT%", "Minutes/Game",]] rows << [player.points_pg, player.assists_pg, player.rebounds_pg, player.blocks_pg, player.steals_pg, player.fg_percentage, player.three_percentage, player.ft_percentage, player.minutes_pg] puts "Here are #{player.name}'s 2015-16 stats: " puts Terminal::Table.new rows: rows end end
require 'active_support/notifications' require 'rails/railtie' module Neo4j class Railtie < ::Rails::Railtie config.neo4j = ActiveSupport::OrderedOptions.new # Add ActiveModel translations to the I18n load_path initializer 'i18n' do config.i18n.load_path += Dir[File.join(File.dirname(__FILE__), '..', '..', '..', 'config', 'locales', '*.{rb,yml}')] end rake_tasks do load 'neo4j/tasks/neo4j_server.rake' load 'neo4j/tasks/migration.rake' end class << self def java_platform? RUBY_PLATFORM =~ /java/ end def setup_default_session(cfg) cfg.session_type ||= :server_db cfg.session_path ||= 'http://localhost:7474' cfg.session_options ||= {} cfg.sessions ||= [] unless (uri = URI(cfg.session_path)).user.blank? cfg.session_options.reverse_merge!(basic_auth: {username: uri.user, password: uri.password}) cfg.session_path = cfg.session_path.gsub("#{uri.user}:#{uri.password}@", '') end return if !cfg.sessions.empty? cfg.sessions << {type: cfg.session_type, path: cfg.session_path, options: cfg.session_options} end def start_embedded_session(session) # See https://github.com/jruby/jruby/wiki/UnlimitedStrengthCrypto security_class = java.lang.Class.for_name('javax.crypto.JceSecurity') restricted_field = security_class.get_declared_field('isRestricted') restricted_field.accessible = true restricted_field.set nil, false session.start end def open_neo4j_session(options) type, name, default, path = options.values_at(:type, :name, :default, :path) if !java_platform? && type == :embedded_db fail "Tried to start embedded Neo4j db without using JRuby (got #{RUBY_PLATFORM}), please run `rvm jruby`" end session = if options.key?(:name) Neo4j::Session.open_named(type, name, default, path) else Neo4j::Session.open(type, path, options[:options]) end start_embedded_session(session) if type == :embedded_db end end # Starting Neo after :load_config_initializers allows apps to # register migrations in config/initializers initializer 'neo4j.start', after: :load_config_initializers do |app| cfg = app.config.neo4j # Set Rails specific defaults Neo4j::Railtie.setup_default_session(cfg) cfg.sessions.each do |session_opts| Neo4j::Railtie.open_neo4j_session(session_opts) end Neo4j::Config.configuration.merge!(cfg.to_hash) clear = "\e[0m" yellow = "\e[33m" cyan = "\e[36m" ActiveSupport::Notifications.subscribe('neo4j.cypher_query') do |_, start, finish, _id, payload| ms = (finish - start) * 1000 Rails.logger.info " #{cyan}#{payload[:context]}#{clear} #{yellow}#{ms.round}ms#{clear} #{payload[:cypher]}" + (payload[:params].size > 0 ? ' | ' + payload[:params].inspect : '') end end end end Use array deconstruction to make variables require 'active_support/notifications' require 'rails/railtie' module Neo4j class Railtie < ::Rails::Railtie config.neo4j = ActiveSupport::OrderedOptions.new # Add ActiveModel translations to the I18n load_path initializer 'i18n' do config.i18n.load_path += Dir[File.join(File.dirname(__FILE__), '..', '..', '..', 'config', 'locales', '*.{rb,yml}')] end rake_tasks do load 'neo4j/tasks/neo4j_server.rake' load 'neo4j/tasks/migration.rake' end class << self def java_platform? RUBY_PLATFORM =~ /java/ end def setup_default_session(cfg) cfg.session_type ||= :server_db cfg.session_path ||= 'http://localhost:7474' cfg.session_options ||= {} cfg.sessions ||= [] unless (uri = URI(cfg.session_path)).user.blank? cfg.session_options.reverse_merge!(basic_auth: {username: uri.user, password: uri.password}) cfg.session_path = cfg.session_path.gsub("#{uri.user}:#{uri.password}@", '') end return if !cfg.sessions.empty? cfg.sessions << {type: cfg.session_type, path: cfg.session_path, options: cfg.session_options} end def start_embedded_session(session) # See https://github.com/jruby/jruby/wiki/UnlimitedStrengthCrypto security_class = java.lang.Class.for_name('javax.crypto.JceSecurity') restricted_field = security_class.get_declared_field('isRestricted') restricted_field.accessible = true restricted_field.set nil, false session.start end def open_neo4j_session(options) type, name, default, path = options.values_at(:type, :name, :default, :path) if !java_platform? && type == :embedded_db fail "Tried to start embedded Neo4j db without using JRuby (got #{RUBY_PLATFORM}), please run `rvm jruby`" end session = if options.key?(:name) Neo4j::Session.open_named(type, name, default, path) else Neo4j::Session.open(type, path, options[:options]) end start_embedded_session(session) if type == :embedded_db end end # Starting Neo after :load_config_initializers allows apps to # register migrations in config/initializers initializer 'neo4j.start', after: :load_config_initializers do |app| cfg = app.config.neo4j # Set Rails specific defaults Neo4j::Railtie.setup_default_session(cfg) cfg.sessions.each do |session_opts| Neo4j::Railtie.open_neo4j_session(session_opts) end Neo4j::Config.configuration.merge!(cfg.to_hash) clear, yellow, cyan = %W(\e[0m \e[33m \e[36m) ActiveSupport::Notifications.subscribe('neo4j.cypher_query') do |_, start, finish, _id, payload| ms = (finish - start) * 1000 Rails.logger.info " #{cyan}#{payload[:context]}#{clear} #{yellow}#{ms.round}ms#{clear} #{payload[:cypher]}" + (payload[:params].size > 0 ? ' | ' + payload[:params].inspect : '') end end end end
require 'active_support/inflector' require 'thor' require 'thor/group' class NetzkeConfig < Thor::Group include Thor::Actions # group used when displaying thor tasks with: thor list or thor -T # group :netzke # Define arguments argument :location, :type => :string, :default => '~/netzke/modules', :desc => 'location where netzke modules are stored' # argument :my_arg_name, :type (:string, :hash, :array, :numeric), :default, :required, :optional, :desc, :banner class_option :extjs, :type => :string, :default => nil, :desc => 'location of ExtJS 3.x.x library' class_option :account, :type => :string, :default => 'skozlov', :desc => 'Github account to get Netzke plugins from' class_option :force_all, :type => :boolean, :default => false, :desc => 'Force force of all files, including existing modules and links' class_option :force_links, :type => :boolean, :default => true, :desc => 'Force force of symbolic links' class_option :ext_version, :type => :string, :default => '3.2.1', :desc => 'ExtJS version to download' class_option :download, :type => :boolean, :default => false, :desc => 'Download ExtJS if not found in specified extjs location' GITHUB = 'http://github.com' def main exit(-1) if !valid_context? configure_modules configure_extjs if options[:extjs] end protected def valid_context? if netzke_app? && rails3_app? true else say "Must be run from a Netzke rails3 application root directory", :red false end end def configure_modules create_module_container_dir inside "#{location}" do ["netzke-core", "netzke-basepack"].each do |module_name| get_module module_name config_netzke_plugin module_name end end end def create_module_container_dir if File.directory?(location) run "rm -rf #{location}" if options[:force_all] end empty_directory "#{location}" if !File.directory?(location) end def get_module module_name run "rm -rf #{module_name}" if options[:force_all] if File.directory? module_name update_module module_name else create_module module_name end end def update_module module_name inside module_name do run "git checkout rails3" run "git rebase origin/rails3" run "git pull" end end def create_module module_name # create dir for module by cloning run "git clone #{netzke_github}/#{module_name}.git #{module_name}" inside module_name do run "git checkout rails3" end end def config_netzke_plugin module_name inside 'vendor/plugins' do module_src = local_module_src(module_name) run "rm -f #{module_name}" if options[:force_links] run "ln -s #{module_src} #{module_name}" end end def configure_extjs extjs_dir = options[:extjs] if !File.directory? extjs_dir say "No directory for extjs found at #{extjs_dir}", :red extjs_dir = download_extjs if options[:download] end return if !File.directory(extjs_dir) inside extjs_dir do if !File.exist? 'ext-all.js' say "Directory #{extjs_dir} does not appear to contain a valid ExtJS library. File 'ext-all.js' missing.", :red return end end inside 'public' do run "rm -f extjs" if options[:force_links] run "ln -s #{extjs_dir} extjs" end end private def download_extjs extjs_dir = options[:extjs] run "mkdir -p #{extjs_dir}" run %Q{ cd #{extjs_dir} && curl -s -o extjs.zip "http://www.extjs.com/deploy/ext-#{ext_version}.zip" && unzip -q extjs.zip && rm extjs.zip } File.join(extjs_dir, extjs) end def netzke_github "#{GITHUB}/#{options[:account]}" end def netzke_app? File.directory? 'lib/netzke' end def rails3_app? File.exist? 'Gemfile' end def local_module_src module_name "#{options[:location]}/#{module_name}" end end added branch option for modules require 'active_support/inflector' require 'thor' require 'thor/group' class NetzkeConfig < Thor::Group include Thor::Actions # group used when displaying thor tasks with: thor list or thor -T # group :netzke # Define arguments argument :location, :type => :string, :default => '~/netzke/modules', :desc => 'location where netzke modules are stored' # argument :my_arg_name, :type (:string, :hash, :array, :numeric), :default, :required, :optional, :desc, :banner class_option :extjs, :type => :string, :default => nil, :desc => 'location of ExtJS 3.x.x library' class_option :branch, :type => :string, :default => 'rails3', :desc => 'Branch to use for netzke modules' class_option :account, :type => :string, :default => 'skozlov', :desc => 'Github account to get Netzke plugins from' class_option :force_all, :type => :boolean, :default => false, :desc => 'Force force of all files, including existing modules and links' class_option :force_links, :type => :boolean, :default => true, :desc => 'Force force of symbolic links' class_option :ext_version, :type => :string, :default => '3.2.1', :desc => 'ExtJS version to download' class_option :download, :type => :boolean, :default => false, :desc => 'Download ExtJS if not found in specified extjs location' GITHUB = 'http://github.com' def main exit(-1) if !valid_context? configure_modules configure_extjs if options[:extjs] end protected def valid_context? if netzke_app? && rails3_app? true else say "Must be run from a Netzke rails3 application root directory", :red false end end def configure_modules create_module_container_dir inside "#{location}" do ["netzke-core", "netzke-basepack"].each do |module_name| get_module module_name config_netzke_plugin module_name end end end def create_module_container_dir if File.directory?(location) run "rm -rf #{location}" if options[:force_all] end empty_directory "#{location}" if !File.directory?(location) end def get_module module_name run "rm -rf #{module_name}" if options[:force_all] if File.directory? module_name update_module module_name else create_module module_name end end def update_module module_name inside module_name do run "git checkout #{branch}" run "git rebase origin/#{branch}" run "git pull" end end def create_module module_name # create dir for module by cloning run "git clone #{netzke_github}/#{module_name}.git #{module_name}" inside module_name do run "git checkout #{branch}" end end def config_netzke_plugin module_name inside 'vendor/plugins' do module_src = local_module_src(module_name) run "rm -f #{module_name}" if options[:force_links] run "ln -s #{module_src} #{module_name}" end end def configure_extjs extjs_dir = options[:extjs] if !File.directory? extjs_dir say "No directory for extjs found at #{extjs_dir}", :red extjs_dir = download_extjs if options[:download] end return if !File.directory(extjs_dir) inside extjs_dir do if !File.exist? 'ext-all.js' say "Directory #{extjs_dir} does not appear to contain a valid ExtJS library. File 'ext-all.js' missing.", :red return end end inside 'public' do run "rm -f extjs" if options[:force_links] run "ln -s #{extjs_dir} extjs" end end private def download_extjs extjs_dir = options[:extjs] run "mkdir -p #{extjs_dir}" run %Q{ cd #{extjs_dir} && curl -s -o extjs.zip "http://www.extjs.com/deploy/ext-#{ext_version}.zip" && unzip -q extjs.zip && rm extjs.zip } File.join(extjs_dir, extjs) end def netzke_github "#{GITHUB}/#{options[:account]}" end def netzke_app? File.directory? 'lib/netzke' end def rails3_app? File.exist? 'Gemfile' end def local_module_src module_name "#{options[:location]}/#{module_name}" end end
module FwtPushNotificationServer module Notifier class Base def begin_transaction(message, payload = nil) @device_tokens = [] @message = message @payload = payload end def add_device_token(device_token) @device_tokens << device_token if device_token.is_valid end def commit_transaction notify_once(@message, @device_tokens.uniq, @payload) end def notify_once(message, device_tokens, payload = nil) return if device_tokens.empty? if FwtPushNotificationServer.delivery_method == :test n = FwtPushNotificationServer::Notification.new n.message = message n.device_tokens = device_tokens FwtPushNotificationServer.deliveries << n else send_notify_once(message, device_tokens, payload) end end end end end Simplify notifier/base module FwtPushNotificationServer module Notifier class Base def notify_once(message, device_tokens = [], payload = nil) send_notify_once(message, device_tokens, payload) end end end end
module NRSER VERSION = "0.0.30.dev" module Version # @return [Gem::Version] # Parse of {NRSER::VERSION}. # def self.gem_version Gem::Version.new VERSION end # .gem_version # The `Gem::Version` "release" for {NRSER::VERSION} - everything before # any `-<alpha-numeric>` prerelease part (like `-dev`). # # @see https://ruby-doc.org/stdlib-2.4.1/libdoc/rubygems/rdoc/Gem/Version.html#method-i-release # # @example # # NRSER::VERSION # # => '0.0.21.dev' # # NRSER::Version.release # # => #<Gem::Version "0.0.21"> # # @return [Gem::Version] # def self.release gem_version.release end # .release # Get a URL to a place in the current version's docs on ruby-docs.org. # # @param [String] rel_path # Relative path. # # @return [String] # The RubyDocs URL. # def self.doc_url rel_path File.join( "http://www.rubydoc.info/gems/nrser", NRSER::Version.release.to_s, rel_path ) end # .doc_url end end bump to v0.0.30 module NRSER VERSION = "0.0.30" module Version # @return [Gem::Version] # Parse of {NRSER::VERSION}. # def self.gem_version Gem::Version.new VERSION end # .gem_version # The `Gem::Version` "release" for {NRSER::VERSION} - everything before # any `-<alpha-numeric>` prerelease part (like `-dev`). # # @see https://ruby-doc.org/stdlib-2.4.1/libdoc/rubygems/rdoc/Gem/Version.html#method-i-release # # @example # # NRSER::VERSION # # => '0.0.21.dev' # # NRSER::Version.release # # => #<Gem::Version "0.0.21"> # # @return [Gem::Version] # def self.release gem_version.release end # .release # Get a URL to a place in the current version's docs on ruby-docs.org. # # @param [String] rel_path # Relative path. # # @return [String] # The RubyDocs URL. # def self.doc_url rel_path File.join( "http://www.rubydoc.info/gems/nrser", NRSER::Version.release.to_s, rel_path ) end # .doc_url end end
class NycToday::CLI @@set_no = 0 @@type_choice = 0 def call puts welcome NycToday::Scraper.scrape_events list_event_types end def welcome system "clear" <<~HEREDOC Welcome to NYC Today-- your guide to today's events in and around New York City! Please wait a few seconds while I gather today's events. For best results, maximize the terminal. HEREDOC end def list_event_types system "clear" puts "\nHere are today's event categories:\n\n" type_entry puts menu_bottom choose_type list_events end def menu_bottom <<~HEREDOC ------------------------------------------------------------- * Enter a number for the type of event you would like to see. * Type 'exit' to leave the program. HEREDOC end def type_entry NycToday::Event.event_types.each.with_index(1) do |event_type, i| puts "#{i.to_s.rjust(2," ")} | #{event_type}" end end def choose_type input = gets.strip if input.to_i > 0 && input.to_i <= NycToday::Event.event_types.count @@type_choice = input.to_i-1 elsif input.downcase == "exit" goodbye else system "clear" puts "I'm sorry, that is not an option. Please choose a number from the menu." sleep 1 system "clear" list_event_types end end def list_events system "clear" page_count category if @@set_no+1 <= page_count puts "\nHere's page #{@@set_no+1}/#{page_count} of today's #{category} events ordered by time:\n\n" event_entry else end_of_list end selection end def page_count NycToday::Event.event_sets(@@type_choice).count end def category NycToday::Event.event_types[@@type_choice] end def event_entry NycToday::Event.event_sets(@@type_choice)[@@set_no].each.with_index(1) do |event, i| puts "#{i.to_s.rjust(3," ")} | #{event.name}" puts " | #{event.time} at #{event.venue}\n\n" end end def error puts "I'm sorry, I didn't understand what you typed. Please try again." sleep 1 system "clear" end def selection puts more_events input = gets.strip.downcase if input == "" or input == " " @@set_no += 1 list_events elsif input.to_i > 0 event = NycToday::Event.sets[@@set_no][input.to_i-1] NycToday::Scraper.scrape_event_page(event) unless event.event_info != nil more_info(event) elsif input == "menu" reset_menu elsif input == "back" if @@set_no >= 1 @@set_no -= 1 list_events else reset_menu end puts elsif input == "exit" goodbye else system "clear" error sleep 2 list_events end end def more_events <<~HEREDOC ------------------------------------------------------------------- * Enter the number of any event you'd like to know more about" * Press Enter for more events * Type 'menu' to return to the main menu, or type 'back' or 'exit' HEREDOC end def more_info(event) if event.event_info != nil || event.price != nil system "clear" puts "\n--------------------------------------------------------------------------------\n\n" puts "Ticket info: #{event.price}\n\n" unless event.price == nil puts wrap(event.event_info, 80) unless event.event_info == nil else system "clear" puts "\nI'm sorry, there is no additional information about this event." end return_to_menu end def wrap(text, width=80) paragraphs = text.split("\n") wrapped = paragraphs.collect do |para| para.gsub(/(.{1,#{width}})(\s+|\Z)/, "\\1\n") end wrapped end def return_to_menu puts event_info_bottom input = gets.strip.downcase if input == "exit" goodbye else system "clear" list_events end end def event_info_bottom <<~HEREDOC -------------------------------------------------------------------------------- * Press Enter to return to the list of events * Type 'exit' to leave the program HEREDOC end def end_of_list puts "\nYou've reached the end of the #{category} events list. Would you like to see it again? (Y/n)" input = gets.strip.downcase if input == "y" || input == "yes" @@set_no = 0 list_events elsif input == "n" || input == "no" puts "\nReturning to main menu..." sleep 1.25 reset_menu else error end_of_list end end def reset_menu system "clear" NycToday::Event.reset_sets @@set_no = 0 @@type_choice = 0 list_event_types end def goodbye system "clear" puts "\nGood-bye! Come back tomorrow for a new list of events." sleep 1.25 system "clear" exit end end Tiny proofreading fix class NycToday::CLI @@set_no = 0 @@type_choice = 0 def call puts welcome NycToday::Scraper.scrape_events list_event_types end def welcome system "clear" <<~HEREDOC Welcome to NYC Today-- your guide to today's events in and around New York City! Please wait a few seconds while I gather today's events. For best results, maximize the terminal. HEREDOC end def list_event_types system "clear" puts "\nHere are today's event categories:\n\n" type_entry puts menu_bottom choose_type list_events end def menu_bottom <<~HEREDOC ------------------------------------------------------------- * Enter a number for the type of event you would like to see. * Type 'exit' to leave the program. HEREDOC end def type_entry NycToday::Event.event_types.each.with_index(1) do |event_type, i| puts "#{i.to_s.rjust(2," ")} | #{event_type}" end end def choose_type input = gets.strip if input.to_i > 0 && input.to_i <= NycToday::Event.event_types.count @@type_choice = input.to_i-1 elsif input.downcase == "exit" goodbye else system "clear" puts "I'm sorry, that is not an option. Please choose a number from the menu." sleep 1 system "clear" list_event_types end end def list_events system "clear" page_count category if @@set_no+1 <= page_count puts "\nHere's page #{@@set_no+1}/#{page_count} of today's #{category} events ordered by time:\n\n" event_entry else end_of_list end selection end def page_count NycToday::Event.event_sets(@@type_choice).count end def category NycToday::Event.event_types[@@type_choice] end def event_entry NycToday::Event.event_sets(@@type_choice)[@@set_no].each.with_index(1) do |event, i| puts "#{i.to_s.rjust(3," ")} | #{event.name}" puts " | #{event.time} at #{event.venue}\n\n" end end def error puts "I'm sorry, I didn't understand what you typed. Please try again." sleep 1 system "clear" end def selection puts more_events input = gets.strip.downcase if input == "" or input == " " @@set_no += 1 list_events elsif input.to_i > 0 event = NycToday::Event.sets[@@set_no][input.to_i-1] NycToday::Scraper.scrape_event_page(event) unless event.event_info != nil more_info(event) elsif input == "menu" reset_menu elsif input == "back" if @@set_no >= 1 @@set_no -= 1 list_events else reset_menu end puts elsif input == "exit" goodbye else system "clear" error sleep 2 list_events end end def more_events <<~HEREDOC ------------------------------------------------------------------- * Enter the number of any event you'd like to know more about * Press Enter for more events * Type 'menu' to return to the main menu, or type 'back' or 'exit' HEREDOC end def more_info(event) if event.event_info != nil || event.price != nil system "clear" puts "\n--------------------------------------------------------------------------------\n\n" puts "Ticket info: #{event.price}\n\n" unless event.price == nil puts wrap(event.event_info, 80) unless event.event_info == nil else system "clear" puts "\nI'm sorry, there is no additional information about this event." end return_to_menu end def wrap(text, width=80) paragraphs = text.split("\n") wrapped = paragraphs.collect do |para| para.gsub(/(.{1,#{width}})(\s+|\Z)/, "\\1\n") end wrapped end def return_to_menu puts event_info_bottom input = gets.strip.downcase if input == "exit" goodbye else system "clear" list_events end end def event_info_bottom <<~HEREDOC -------------------------------------------------------------------------------- * Press Enter to return to the list of events * Type 'exit' to leave the program HEREDOC end def end_of_list puts "\nYou've reached the end of the #{category} events list. Would you like to see it again? (Y/n)" input = gets.strip.downcase if input == "y" || input == "yes" @@set_no = 0 list_events elsif input == "n" || input == "no" puts "\nReturning to main menu..." sleep 1.25 reset_menu else error end_of_list end end def reset_menu system "clear" NycToday::Event.reset_sets @@set_no = 0 @@type_choice = 0 list_event_types end def goodbye system "clear" puts "\nGood-bye! Come back tomorrow for a new list of events." sleep 1.25 system "clear" exit end end
require 'nydp/cond' require 'nydp/function_invocation' require 'nydp/interpreted_function' require 'nydp/literal' module Nydp class Compiler extend Helper def self.compile expression, bindings compile_expr expression, bindings rescue StandardError => e raise Nydp::Error.new "failed to compile expression:\n#{expression.inspect}" end def self.compile_expr expression, bindings if expression.is_a? Nydp::Symbol SymbolLookup.build expression, bindings elsif literal? expression Literal.build expression, bindings elsif expression.is_a? Nydp::Pair compile_pair expression, bindings end end def self.maybe_cons a, b Nydp::NIL.is?(a) ? b : cons(a, b) end def self.compile_each expr, bindings if Nydp::NIL.is?(expr) expr elsif pair?(expr) maybe_cons compile(expr.car, bindings), compile_each(expr.cdr, bindings) else compile(expr, bindings) end end def self.compile_pair expression, bindings key = expression.car if sym?(key, :cond) Cond.build expression.cdr, bindings elsif sym?(key, :quote) Literal.build expression.cadr, bindings elsif sym?(key, :assign) Assignment.build expression.cdr, bindings elsif sym?(key, :fn) InterpretedFunction.build expression.cadr, expression.cddr, bindings else FunctionInvocation.build expression, bindings end end end end compiler: todo require 'nydp/cond' require 'nydp/function_invocation' require 'nydp/interpreted_function' require 'nydp/literal' module Nydp class Compiler extend Helper def self.compile expression, bindings compile_expr expression, bindings rescue StandardError => e raise Nydp::Error.new "failed to compile expression:\n#{expression.inspect}" end def self.compile_expr expression, bindings if expression.is_a? Nydp::Symbol SymbolLookup.build expression, bindings elsif literal? expression Literal.build expression, bindings elsif expression.is_a? Nydp::Pair compile_pair expression, bindings end end def self.maybe_cons a, b Nydp::NIL.is?(a) ? b : cons(a, b) end def self.compile_each expr, bindings if Nydp::NIL.is?(expr) expr elsif pair?(expr) maybe_cons compile(expr.car, bindings), compile_each(expr.cdr, bindings) else compile(expr, bindings) end end def self.compile_pair expression, bindings key = expression.car if sym?(key, :cond) Cond.build expression.cdr, bindings # todo: replace with function? (cond x (fn () iftrue) (fn () iffalse)) -->> performance issues, creating two closures for every cond invocation elsif sym?(key, :quote) Literal.build expression.cadr, bindings elsif sym?(key, :assign) Assignment.build expression.cdr, bindings elsif sym?(key, :fn) InterpretedFunction.build expression.cadr, expression.cddr, bindings else FunctionInvocation.build expression, bindings end end end end
# This file is part of the opengl-aux project. # <https://github.com/nilium/opengl-aux> # # ----------------------------------------------------------------------------- # # gl.rb # Basic GL functions and typedefs for snow-data. require 'opengl-core' require 'snow-data' # Extensions to the opengl-core Gl module. module GL # Define snow-data typedefs for OpenGL Snow::CStruct.alias_type(:gl_short, :short) Snow::CStruct.alias_type(:gl_ushort, :unsigned_short) Snow::CStruct.alias_type(:gl_half, :unsigned_short) Snow::CStruct.alias_type(:gl_enum, :unsigned_int) Snow::CStruct.alias_type(:gl_uint, :unsigned_int) Snow::CStruct.alias_type(:gl_int, :int) Snow::CStruct.alias_type(:gl_fixed, :int) Snow::CStruct.alias_type(:gl_uint64, :uint64_t) Snow::CStruct.alias_type(:gl_int64, :int64_t) Snow::CStruct.alias_type(:gl_sizei, :int) Snow::CStruct.alias_type(:gl_float, :float) Snow::CStruct.alias_type(:gl_clampf, :float) Snow::CStruct.alias_type(:gl_double, :double) Snow::CStruct.alias_type(:gl_clampd, :double) GLObject = Snow::CStruct.new { gl_uint :name } def check_gl_error(msg = nil) error = glGetError if error != GL_ERROR_NONE end end class << self # @api private attr_accessor :__box_types__ # @api private # # Temporarily allocates the given type, yields it to a block, and releases # the allocated memory. Uses alloca if available. Any additional arguments # to this function are forwarded to the type's allocator. # def __temp_alloc__(type, *args, &block) result = nil if type.respond_to?(:alloca) result = type.alloca(*args, &block) else type.new(*args) do |p| begin result = yield[p] ensure p.free! end end end result end # @api private # # Returns a boxed type for the given typename. All boxed types contain a # single member, 'name', which is of the boxed type. Boxed types are created # on demand and cached. # def __boxed_type__(typename, &block) box_types = (__box_types__ ||= Hash.new do |hash, type| hash[type] = Snow::CStruct.new { __send__(type, :name) } end) box_types[typename] end # @api private # # Wraps a previously-defined native glGen* function that returns the given # type of object. The glGen function returns one or more GL object names. # If returning a single name, the return type is Fixnum, otherwise it's an # array of Fixnums. # def __define_gl_gen_object_method__(name, type) self.module_exec(name, :"#{name}__", GL.__boxed_type__(type)) do |func_name, raw_name, box_type| define_method(func_name, -> (count) do return nil if count <= 0 if count == 1 GL.__temp_alloc__(box_type) do |p| send(raw_name, count, p.address) p.name end else GL.__temp_alloc__(box_type::Array, count) do |p| send(raw_name, count, p.address) Array.new(count) { |i| p[i].name } end end end) # define_method end # module_exec end # __define_gl_get_method__ # @api private # # Similar to __define_gl_gen_object_method__, except for deletion. Takes # four possible types of objects to delete: a GLObject or an array of # GLObjects, a Fixnum, or an array of Fixnums. Any other types will raise # an error, and any type contained by an Array that is not implicitly # convertible to a Fixnum will also raise an error. # def __define_gl_delete_object_method__(name, type) self.module_exec(name, :"#{name}__") do |func_name, raw_name| define_method(func_name, -> (objects) do case objects when GLObject send(raw_name, 1, objects.address) when GLObject::Array send(raw_name, objects.length, objects.address) when Fixnum GL.__temp_alloc__(GLObject) do |p| p.name = objects send(raw_name, 1, p.address) end when Array # Assumes an array of fixnums GL.__temp_alloc__(GLObject::Array, objects.length) do |p| objects.each_with_index { |e, i| p[i].name = e } send(raw_name, p.length, p.address) end else raise ArgumentError, "Invalid object passed to #{name} for deletion: #{objects.inspect}" end self end) # define_method end # module_exec end # __define_gl_get_method__ # @api private # # Defines a glGet* method that returns a single value of the given type. # def __define_gl_get_method__(name, type) self.module_exec(name, :"#{name}v__", GL.__boxed_type__(type)) do |func_name, raw_name, box_type| define_method(func_name, -> (pname) do GL.__temp_alloc__(box_type) do |p| send(raw_name, pname, p.address) p.name end end) # define_method end # module_exec end # __define_gl_get_method__ end # singleton_class # @!method self.glGenTextures(count) # Returns an array of generated texture names. __define_gl_gen_object_method__ :glGenTextures, :gl_uint # @!method self.glDeleteTextures(count, objects) __define_gl_delete_object_method__ :glDeleteTextures, :gl_uint # @!method self.glGenVertexArrays(count) # Returns an array of generated vertex array object names. __define_gl_gen_object_method__ :glGenVertexArrays, :gl_uint # @!method self.glDeleteVertexArrays(count, objects) __define_gl_delete_object_method__ :glDeleteVertexArrays, :gl_uint # @!method self.glGenBuffers(count) # Returns an array of generated buffer object names. __define_gl_gen_object_method__ :glGenBuffers, :gl_uint # @!method self.glDeleteBuffers(count, objects) __define_gl_delete_object_method__ :glDeleteBuffers, :gl_uint # @!method self.glGenQueries(count) # Returns an array of generated query object names. __define_gl_gen_object_method__ :glGenQueries, :gl_uint # @!method self.glDeleteQueries(count, objects) __define_gl_delete_object_method__ :glDeleteQueries, :gl_uint # @!method self.glGenSamplers(count) # Returns an array of generated sampler object names. __define_gl_gen_object_method__ :glGenSamplers, :gl_uint # @!method self.glDeleteSamplers(count, objects) __define_gl_delete_object_method__ :glDeleteSamplers, :gl_uint # @!method self.glGenFramebuffers(count) # Returns an array of generated framebuffer object names. __define_gl_gen_object_method__ :glGenFramebuffers, :gl_uint # @!method self.glDeleteFramebuffers(count, objects) __define_gl_delete_object_method__ :glDeleteFramebuffers, :gl_uint # @!method self.glGenRenderbuffers(count) # Returns an array of generated renderbuffer object names. __define_gl_gen_object_method__ :glGenRenderbuffers, :gl_uint # @!method self.glDeleteRenderbuffers(count, objects) __define_gl_delete_object_method__ :glDeleteRenderbuffers, :gl_uint # @!method self.glGenRenderbuffersProgramPipelines(count) # Returns an array of generated program pipeline object names. __define_gl_gen_object_method__ :glGenProgramPipelines, :gl_uint # @!method self.glDeleteRenderbuffersProgramPipelines(count, objects) __define_gl_delete_object_method__ :glDeleteProgramPipelines, :gl_uint # @!method self.glGenRenderbuffersTrasnformFeedbacks(count) # Returns an array of generated transform feedback objects __define_gl_gen_object_method__ :glGenTransformFeedbacks, :gl_uint # @!method self.glDeleteRenderbuffersTrasnformFeedbacks(count, objects) __define_gl_delete_object_method__ :glDeleteTransformFeedbacks, :gl_uint __define_gl_get_method__ :glGetInteger, :gl_int __define_gl_get_method__ :glGetInteger64, :gl_int64 __define_gl_get_method__ :glGetFloat, :float __define_gl_get_method__ :glGetDouble, :double # @return [Boolean] Returns the boolean value of the given parameter name. def glGetBoolean(pname) GL.__temp_alloc__(GL.__boxed_type__(:gl_boolean)) do |p| p.name = 0 glGetBooleanv(pname, p.address) p.name != GL::GL_FALSE end end # @return [String] Returns the string value of the given parameter name. def glGetString(name) glGetString__(name).to_s end # @return [String] Returns the string value of a parameter name at a given index. def glGetStringi(name, index) glGetStringi__(name, index).to_s end # Assumes sources is a def glShaderSource(shader, sources) ary_len = (source_array = sources.kind_of?(Array)) ? sources.length : 1 lengths = GL.__boxed_type__(:gl_sizei)[ary_len] pointers = GL.__boxed_type__(:intptr_t)[ary_len] begin assign_block = -> (src, index) do lengths[index].name = src.bytesize pointers[index].name = Fiddle::Pointer[src].to_i end if source_array sources.each_with_index(&assign_block) else assign_block[sources, 0] end glShaderSource__(shader, ary_len, pointers.address, lengths.address) ensure lengths.free! pointers.free! end self end # Returns the version or release number. Calls glGetString. def gl_version glGetString(GL_VERSION) end # Returns the implementation vendor. Calls glGetString. def gl_vendor glGetString(GL_VENDOR) end # Returns the renderer. Calls glGetString. def gl_renderer glGetString(GL_RENDERER) end # Returns the shading language version. Calls glGetString. def gl_shading_language_version glGetString(GL_SHADING_LANGUAGE_VERSION) end # Gets an array of GL extensions. This calls glGetIntegerv and glGetStringi, # so be aware that you should probably cache the results. def gl_extensions Array.new(glGetInteger(GL_NUM_EXTENSIONS)) do |index| glGetStringi(GL_EXTENSIONS, index) end end def glGetShader(shader, pname) GL.__temp_alloc__(GL.__boxed_type__(:gl_int)) do |p| glGetShaderiv__(shader, pname, p.address) p.name end end def glGetShaderInfoLog(shader) length = glGetShader(shader, GL_INFO_LOG_LENGTH) return '' if length == 0 output = ' ' * length glGetShaderInfoLog__(shader, output.bytesize, 0, output) output end def glGetShaderSource(shader) length = glGetShader(shader, GL_SHADER_SOURCE_LENGTH) return '' if length == 0 output = ' ' * length glGetShaderInfoLog__(shader, output.bytesize, 0, output) output end def glGetProgram(program, pname) GL.__temp_alloc__(GL.__boxed_type__(:gl_int)) do |p| glGetProgramiv__(program, pname, p.address) p.name end end def glGetProgramInfoLog(program) length = glGetProgram(program, GL_INFO_LOG_LENGTH) return '' if length == 0 output = ' ' * length glGetProgramInfoLog__(program, output.bytesize, 0, output) output end GLProgramBinary = Struct.new(:format, :data) def glGetProgramBinary(program) binary_length = glGetProgram(program, GL_PROGRAM_BINARY_LENGTH) return nil if binary_length <= 0 GL.__temp_alloc__(GL.__boxed_type__(:gl_enum)) do |format_buffer; binary_buffer| binary_buffer = ' ' * binary_length glGetProgramBinary( program, binary_buffer.bytesize, 0, format_buffer.address, binary_buffer.address ) GLProgramBinary[format_buffer.name, binary_buffer] end end extend self end # GL Rename check_gl_error to assert_no_gl_error, finish it. # This file is part of the opengl-aux project. # <https://github.com/nilium/opengl-aux> # # ----------------------------------------------------------------------------- # # gl.rb # Basic GL functions and typedefs for snow-data. require 'opengl-core' require 'snow-data' require 'opengl-aux/error' # Extensions to the opengl-core Gl module. module GL # Define snow-data typedefs for OpenGL Snow::CStruct.alias_type(:gl_short, :short) Snow::CStruct.alias_type(:gl_ushort, :unsigned_short) Snow::CStruct.alias_type(:gl_half, :unsigned_short) Snow::CStruct.alias_type(:gl_enum, :unsigned_int) Snow::CStruct.alias_type(:gl_uint, :unsigned_int) Snow::CStruct.alias_type(:gl_int, :int) Snow::CStruct.alias_type(:gl_fixed, :int) Snow::CStruct.alias_type(:gl_uint64, :uint64_t) Snow::CStruct.alias_type(:gl_int64, :int64_t) Snow::CStruct.alias_type(:gl_sizei, :int) Snow::CStruct.alias_type(:gl_float, :float) Snow::CStruct.alias_type(:gl_clampf, :float) Snow::CStruct.alias_type(:gl_double, :double) Snow::CStruct.alias_type(:gl_clampd, :double) GLObject = Snow::CStruct.new { gl_uint :name } def assert_no_gl_error(msg = nil) error = glGetError if error != GL_NO_ERROR raise GLStateError.new(error), msg end end class << self # @api private attr_accessor :__box_types__ # @api private # # Temporarily allocates the given type, yields it to a block, and releases # the allocated memory. Uses alloca if available. Any additional arguments # to this function are forwarded to the type's allocator. # def __temp_alloc__(type, *args, &block) result = nil if type.respond_to?(:alloca) result = type.alloca(*args, &block) else type.new(*args) do |p| begin result = yield[p] ensure p.free! end end end result end # @api private # # Returns a boxed type for the given typename. All boxed types contain a # single member, 'name', which is of the boxed type. Boxed types are created # on demand and cached. # def __boxed_type__(typename, &block) box_types = (__box_types__ ||= Hash.new do |hash, type| hash[type] = Snow::CStruct.new { __send__(type, :name) } end) box_types[typename] end # @api private # # Wraps a previously-defined native glGen* function that returns the given # type of object. The glGen function returns one or more GL object names. # If returning a single name, the return type is Fixnum, otherwise it's an # array of Fixnums. # def __define_gl_gen_object_method__(name, type) self.module_exec(name, :"#{name}__", GL.__boxed_type__(type)) do |func_name, raw_name, box_type| define_method(func_name, -> (count) do return nil if count <= 0 if count == 1 GL.__temp_alloc__(box_type) do |p| send(raw_name, count, p.address) p.name end else GL.__temp_alloc__(box_type::Array, count) do |p| send(raw_name, count, p.address) Array.new(count) { |i| p[i].name } end end end) # define_method end # module_exec end # __define_gl_get_method__ # @api private # # Similar to __define_gl_gen_object_method__, except for deletion. Takes # four possible types of objects to delete: a GLObject or an array of # GLObjects, a Fixnum, or an array of Fixnums. Any other types will raise # an error, and any type contained by an Array that is not implicitly # convertible to a Fixnum will also raise an error. # def __define_gl_delete_object_method__(name, type) self.module_exec(name, :"#{name}__") do |func_name, raw_name| define_method(func_name, -> (objects) do case objects when GLObject send(raw_name, 1, objects.address) when GLObject::Array send(raw_name, objects.length, objects.address) when Fixnum GL.__temp_alloc__(GLObject) do |p| p.name = objects send(raw_name, 1, p.address) end when Array # Assumes an array of fixnums GL.__temp_alloc__(GLObject::Array, objects.length) do |p| objects.each_with_index { |e, i| p[i].name = e } send(raw_name, p.length, p.address) end else raise ArgumentError, "Invalid object passed to #{name} for deletion: #{objects.inspect}" end self end) # define_method end # module_exec end # __define_gl_get_method__ # @api private # # Defines a glGet* method that returns a single value of the given type. # def __define_gl_get_method__(name, type) self.module_exec(name, :"#{name}v__", GL.__boxed_type__(type)) do |func_name, raw_name, box_type| define_method(func_name, -> (pname) do GL.__temp_alloc__(box_type) do |p| send(raw_name, pname, p.address) p.name end end) # define_method end # module_exec end # __define_gl_get_method__ end # singleton_class # @!method self.glGenTextures(count) # Returns an array of generated texture names. __define_gl_gen_object_method__ :glGenTextures, :gl_uint # @!method self.glDeleteTextures(count, objects) __define_gl_delete_object_method__ :glDeleteTextures, :gl_uint # @!method self.glGenVertexArrays(count) # Returns an array of generated vertex array object names. __define_gl_gen_object_method__ :glGenVertexArrays, :gl_uint # @!method self.glDeleteVertexArrays(count, objects) __define_gl_delete_object_method__ :glDeleteVertexArrays, :gl_uint # @!method self.glGenBuffers(count) # Returns an array of generated buffer object names. __define_gl_gen_object_method__ :glGenBuffers, :gl_uint # @!method self.glDeleteBuffers(count, objects) __define_gl_delete_object_method__ :glDeleteBuffers, :gl_uint # @!method self.glGenQueries(count) # Returns an array of generated query object names. __define_gl_gen_object_method__ :glGenQueries, :gl_uint # @!method self.glDeleteQueries(count, objects) __define_gl_delete_object_method__ :glDeleteQueries, :gl_uint # @!method self.glGenSamplers(count) # Returns an array of generated sampler object names. __define_gl_gen_object_method__ :glGenSamplers, :gl_uint # @!method self.glDeleteSamplers(count, objects) __define_gl_delete_object_method__ :glDeleteSamplers, :gl_uint # @!method self.glGenFramebuffers(count) # Returns an array of generated framebuffer object names. __define_gl_gen_object_method__ :glGenFramebuffers, :gl_uint # @!method self.glDeleteFramebuffers(count, objects) __define_gl_delete_object_method__ :glDeleteFramebuffers, :gl_uint # @!method self.glGenRenderbuffers(count) # Returns an array of generated renderbuffer object names. __define_gl_gen_object_method__ :glGenRenderbuffers, :gl_uint # @!method self.glDeleteRenderbuffers(count, objects) __define_gl_delete_object_method__ :glDeleteRenderbuffers, :gl_uint # @!method self.glGenRenderbuffersProgramPipelines(count) # Returns an array of generated program pipeline object names. __define_gl_gen_object_method__ :glGenProgramPipelines, :gl_uint # @!method self.glDeleteRenderbuffersProgramPipelines(count, objects) __define_gl_delete_object_method__ :glDeleteProgramPipelines, :gl_uint # @!method self.glGenRenderbuffersTrasnformFeedbacks(count) # Returns an array of generated transform feedback objects __define_gl_gen_object_method__ :glGenTransformFeedbacks, :gl_uint # @!method self.glDeleteRenderbuffersTrasnformFeedbacks(count, objects) __define_gl_delete_object_method__ :glDeleteTransformFeedbacks, :gl_uint __define_gl_get_method__ :glGetInteger, :gl_int __define_gl_get_method__ :glGetInteger64, :gl_int64 __define_gl_get_method__ :glGetFloat, :float __define_gl_get_method__ :glGetDouble, :double # @return [Boolean] Returns the boolean value of the given parameter name. def glGetBoolean(pname) GL.__temp_alloc__(GL.__boxed_type__(:gl_boolean)) do |p| p.name = 0 glGetBooleanv(pname, p.address) p.name != GL::GL_FALSE end end # @return [String] Returns the string value of the given parameter name. def glGetString(name) glGetString__(name).to_s end # @return [String] Returns the string value of a parameter name at a given index. def glGetStringi(name, index) glGetStringi__(name, index).to_s end # Assumes sources is a def glShaderSource(shader, sources) ary_len = (source_array = sources.kind_of?(Array)) ? sources.length : 1 lengths = GL.__boxed_type__(:gl_sizei)[ary_len] pointers = GL.__boxed_type__(:intptr_t)[ary_len] begin assign_block = -> (src, index) do lengths[index].name = src.bytesize pointers[index].name = Fiddle::Pointer[src].to_i end if source_array sources.each_with_index(&assign_block) else assign_block[sources, 0] end glShaderSource__(shader, ary_len, pointers.address, lengths.address) ensure lengths.free! pointers.free! end self end # Returns the version or release number. Calls glGetString. def gl_version glGetString(GL_VERSION) end # Returns the implementation vendor. Calls glGetString. def gl_vendor glGetString(GL_VENDOR) end # Returns the renderer. Calls glGetString. def gl_renderer glGetString(GL_RENDERER) end # Returns the shading language version. Calls glGetString. def gl_shading_language_version glGetString(GL_SHADING_LANGUAGE_VERSION) end # Gets an array of GL extensions. This calls glGetIntegerv and glGetStringi, # so be aware that you should probably cache the results. def gl_extensions Array.new(glGetInteger(GL_NUM_EXTENSIONS)) do |index| glGetStringi(GL_EXTENSIONS, index) end end def glGetShader(shader, pname) GL.__temp_alloc__(GL.__boxed_type__(:gl_int)) do |p| glGetShaderiv__(shader, pname, p.address) p.name end end def glGetShaderInfoLog(shader) length = glGetShader(shader, GL_INFO_LOG_LENGTH) return '' if length == 0 output = ' ' * length glGetShaderInfoLog__(shader, output.bytesize, 0, output) output end def glGetShaderSource(shader) length = glGetShader(shader, GL_SHADER_SOURCE_LENGTH) return '' if length == 0 output = ' ' * length glGetShaderInfoLog__(shader, output.bytesize, 0, output) output end def glGetProgram(program, pname) GL.__temp_alloc__(GL.__boxed_type__(:gl_int)) do |p| glGetProgramiv__(program, pname, p.address) p.name end end def glGetProgramInfoLog(program) length = glGetProgram(program, GL_INFO_LOG_LENGTH) return '' if length == 0 output = ' ' * length glGetProgramInfoLog__(program, output.bytesize, 0, output) output end GLProgramBinary = Struct.new(:format, :data) def glGetProgramBinary(program) binary_length = glGetProgram(program, GL_PROGRAM_BINARY_LENGTH) return nil if binary_length <= 0 GL.__temp_alloc__(GL.__boxed_type__(:gl_enum)) do |format_buffer; binary_buffer| binary_buffer = ' ' * binary_length glGetProgramBinary( program, binary_buffer.bytesize, 0, format_buffer.address, binary_buffer.address ) GLProgramBinary[format_buffer.name, binary_buffer] end end extend self end # GL
module OverSIP module Utils # It ensures that two identical byte secuences are matched regardless # they have different encoding. # For example in Ruby the following returns false: # "iñaki".force_encoding(::Encoding::BINARY) == "iñaki" def self.string_compare string1, string2 string1.force_encoding(::Encoding::BINARY) == string2.force_encoding(::Encoding::BINARY) end # This avoid "invalid byte sequence in UTF-8" when the directly doing: # string =~ /EXPRESSION/ # and string has invalid UTF-8 bytes secuence. # NOTE: expression argument must be a Regexp expression (with / symbols at the # begining and at the end). def self.regexp_compare string, expression return false unless string && string.valid_encoding? string.force_encoding(::Encoding::BINARY) =~ expression end end end Improvements in OverSIP::Utils module methods. module OverSIP module Utils # It ensures that two identical byte secuences are matched regardless # they have different encoding. # For example in Ruby the following returns false: # "iñaki".force_encoding(::Encoding::BINARY) == "iñaki" def self.string_compare string1, string2 string1.to_s.force_encoding(::Encoding::BINARY) == string2.to_s.force_encoding(::Encoding::BINARY) end # This avoid "invalid byte sequence in UTF-8" when the directly doing: # string =~ /EXPRESSION/ # and string has invalid UTF-8 bytes secuence. # NOTE: expression argument must be a Regexp expression (with / symbols at the # begining and at the end). def self.regexp_compare string, expression string = string.to_s return false unless string.valid_encoding? string.force_encoding(::Encoding::BINARY) =~ expression end end end
module Pacer VERSION = "2.0.14" # Clients may optionally define the following constants in the Pacer namespace: # - LOAD_JARS : set to false to manage jar loading in the client. Be sure to load the jars defined in JARFILES. # - LOCKJAR_LOCK_OPTS : set some options to be passed to LockJar.lock (ie. :lockfile, :download_artifacts, :local_repo) unless const_defined? :START_TIME START_TIME = Time.now end end [skip ci] New development cycle with version 2.0.15.pre module Pacer VERSION = "2.0.15.pre" # Clients may optionally define the following constants in the Pacer namespace: # - LOAD_JARS : set to false to manage jar loading in the client. Be sure to load the jars defined in JARFILES. # - LOCKJAR_LOCK_OPTS : set some options to be passed to LockJar.lock (ie. :lockfile, :download_artifacts, :local_repo) unless const_defined? :START_TIME START_TIME = Time.now end end
module Paysafe class Error < StandardError # Raised on a 4xx HTTP status code ClientError = Class.new(self) # Raised on the HTTP status code 400 BadRequest = Class.new(ClientError) # Raised on the HTTP status code 401 Unauthorized = Class.new(ClientError) # Raised on the HTTP status code 402 RequestDeclined = Class.new(ClientError) # Raised on the HTTP status code 403 Forbidden = Class.new(ClientError) # Raised on the HTTP status code 404 NotFound = Class.new(ClientError) # Raised on the HTTP status code 406 NotAcceptable = Class.new(ClientError) # Raised on the HTTP status code 409 Conflict = Class.new(ClientError) # Raised on the HTTP status code 415 UnsupportedMediaType = Class.new(ClientError) # Raised on the HTTP status code 422 UnprocessableEntity = Class.new(ClientError) # Raised on the HTTP status code 429 TooManyRequests = Class.new(ClientError) # Raised on a 5xx HTTP status code ServerError = Class.new(self) # Raised on the HTTP status code 500 InternalServerError = Class.new(ServerError) # Raised on the HTTP status code 502 BadGateway = Class.new(ServerError) # Raised on the HTTP status code 503 ServiceUnavailable = Class.new(ServerError) # Raised on the HTTP status code 504 GatewayTimeout = Class.new(ServerError) ERRORS = { 400 => Paysafe::Error::BadRequest, 401 => Paysafe::Error::Unauthorized, 402 => Paysafe::Error::RequestDeclined, 403 => Paysafe::Error::Forbidden, 404 => Paysafe::Error::NotFound, 406 => Paysafe::Error::NotAcceptable, 409 => Paysafe::Error::Conflict, 415 => Paysafe::Error::UnsupportedMediaType, 422 => Paysafe::Error::UnprocessableEntity, 429 => Paysafe::Error::TooManyRequests, 500 => Paysafe::Error::InternalServerError, 502 => Paysafe::Error::BadGateway, 503 => Paysafe::Error::ServiceUnavailable, 504 => Paysafe::Error::GatewayTimeout, } class << self # Create a new error from an HTTP response # # @param body [String] # @param status [Integer] # @return [Paysafe::Error] def from_response(body, status) klass = ERRORS[status] || Paysafe::Error message, error_code = parse_error(body) klass.new(message: message, code: error_code, response: body) end private def parse_error(body) if body.is_a?(Hash) [ body.dig(:error, :message), body.dig(:error, :code) ] else [ '', nil ] end end end # The Paysafe API Error Code # # @return [String] attr_reader :code # The JSON HTTP response in Hash form # # @return [Hash] attr_reader :response # Initializes a new Error object # # @param message [Exception, String] # @param code [String] # @param response [Hash] # @return [Paysafe::Error] def initialize(message: '', code: nil, response: {}) super(message) @code = code @response = response end end end Move super call to the end module Paysafe class Error < StandardError # Raised on a 4xx HTTP status code ClientError = Class.new(self) # Raised on the HTTP status code 400 BadRequest = Class.new(ClientError) # Raised on the HTTP status code 401 Unauthorized = Class.new(ClientError) # Raised on the HTTP status code 402 RequestDeclined = Class.new(ClientError) # Raised on the HTTP status code 403 Forbidden = Class.new(ClientError) # Raised on the HTTP status code 404 NotFound = Class.new(ClientError) # Raised on the HTTP status code 406 NotAcceptable = Class.new(ClientError) # Raised on the HTTP status code 409 Conflict = Class.new(ClientError) # Raised on the HTTP status code 415 UnsupportedMediaType = Class.new(ClientError) # Raised on the HTTP status code 422 UnprocessableEntity = Class.new(ClientError) # Raised on the HTTP status code 429 TooManyRequests = Class.new(ClientError) # Raised on a 5xx HTTP status code ServerError = Class.new(self) # Raised on the HTTP status code 500 InternalServerError = Class.new(ServerError) # Raised on the HTTP status code 502 BadGateway = Class.new(ServerError) # Raised on the HTTP status code 503 ServiceUnavailable = Class.new(ServerError) # Raised on the HTTP status code 504 GatewayTimeout = Class.new(ServerError) ERRORS = { 400 => Paysafe::Error::BadRequest, 401 => Paysafe::Error::Unauthorized, 402 => Paysafe::Error::RequestDeclined, 403 => Paysafe::Error::Forbidden, 404 => Paysafe::Error::NotFound, 406 => Paysafe::Error::NotAcceptable, 409 => Paysafe::Error::Conflict, 415 => Paysafe::Error::UnsupportedMediaType, 422 => Paysafe::Error::UnprocessableEntity, 429 => Paysafe::Error::TooManyRequests, 500 => Paysafe::Error::InternalServerError, 502 => Paysafe::Error::BadGateway, 503 => Paysafe::Error::ServiceUnavailable, 504 => Paysafe::Error::GatewayTimeout, } class << self # Create a new error from an HTTP response # # @param body [String] # @param status [Integer] # @return [Paysafe::Error] def from_response(body, status) klass = ERRORS[status] || Paysafe::Error message, error_code = parse_error(body) klass.new(message: message, code: error_code, response: body) end private def parse_error(body) if body.is_a?(Hash) [ body.dig(:error, :message), body.dig(:error, :code) ] else [ '', nil ] end end end # The Paysafe API Error Code # # @return [String] attr_reader :code # The JSON HTTP response in Hash form # # @return [Hash] attr_reader :response # Initializes a new Error object # # @param message [Exception, String] # @param code [String] # @param response [Hash] # @return [Paysafe::Error] def initialize(message: '', code: nil, response: {}) @code = code @response = response super(message) end end end
# encoding: utf-8 require 'active_support/testing/assertions' require 'active_support/testing/deprecation' require 'active_support/core_ext/kernel/reporting' require 'active_support/deprecation' require 'rails/backtrace_cleaner' require 'peck_on_rails/assertions' require 'peck_on_rails/backtrace_cleaning' require 'peck_on_rails/controller' require 'peck_on_rails/helper' require 'peck_on_rails/model' class Peck class Rails def self.dev_null @dev_null ||= File.open('/dev/null', 'w') end def self.silence stdout, stderr = $stdout, $stderr $stdout, $stderr = dev_null, dev_null begin yield ensure $stdout, $stderr = stdout, stderr end end def self.subject(context) context.description.find { |a| a.is_a?(Module) } end def self.context_type_for_description(context, subject) context.description.find do |subject| subject.is_a?(Symbol) end end HELPER_RE = /Helper$/ def self.context_type_for_subject(context, subject) if subject.nil? :plain elsif defined?(ActionController) && subject < ActionController::Base :controller elsif defined?(ActiveRecord) && subject < ActiveRecord::Base :model elsif subject.name =~ HELPER_RE :helper else :plain end end def self.context_type(context, subject) context_type = context_type_for_description(context, subject) || context_type_for_subject(context, subject) Peck.log("Using `#{context_type}' as context type for `#{subject.respond_to?(:name) ? subject.name : subject}'") context_type end def self.init if defined?(ActiveRecord) Peck.log("Migrate database if necessary") ActiveRecord::Migration.load_schema_if_pending! end Peck.log("Setting up Peck::Rails") proc do |context| subject = Peck::Rails.subject(context) context_type = Peck::Rails.context_type(context, subject) [ Peck::Rails::Helper, Peck::Rails::Model, Peck::Rails::Controller ].each do |klass| klass.send(:init, context, context_type, subject) end context.before do if respond_to?(:setup_fixtures) begin setup_fixtures rescue ActiveRecord::ConnectionNotEstablished end end end context.after do if respond_to?(:teardown_fixtures) begin teardown_fixtures rescue ActiveRecord::ConnectionNotEstablished end end end end end end end class Peck class Notifiers class Base include Peck::Rails::BacktraceCleaning end end end Peck::Context.once(&Peck::Rails.init) Don't shadow unused argument in context_type_for_description. # encoding: utf-8 require 'active_support/testing/assertions' require 'active_support/testing/deprecation' require 'active_support/core_ext/kernel/reporting' require 'active_support/deprecation' require 'rails/backtrace_cleaner' require 'peck_on_rails/assertions' require 'peck_on_rails/backtrace_cleaning' require 'peck_on_rails/controller' require 'peck_on_rails/helper' require 'peck_on_rails/model' class Peck class Rails def self.dev_null @dev_null ||= File.open('/dev/null', 'w') end def self.silence stdout, stderr = $stdout, $stderr $stdout, $stderr = dev_null, dev_null begin yield ensure $stdout, $stderr = stdout, stderr end end def self.subject(context) context.description.find { |a| a.is_a?(Module) } end def self.context_type_for_description(context, _) context.description.find do |subject| subject.is_a?(Symbol) end end HELPER_RE = /Helper$/ def self.context_type_for_subject(context, subject) if subject.nil? :plain elsif defined?(ActionController) && subject < ActionController::Base :controller elsif defined?(ActiveRecord) && subject < ActiveRecord::Base :model elsif subject.name =~ HELPER_RE :helper else :plain end end def self.context_type(context, subject) context_type = context_type_for_description(context, subject) || context_type_for_subject(context, subject) Peck.log("Using `#{context_type}' as context type for `#{subject.respond_to?(:name) ? subject.name : subject}'") context_type end def self.init if defined?(ActiveRecord) Peck.log("Migrate database if necessary") ActiveRecord::Migration.load_schema_if_pending! end Peck.log("Setting up Peck::Rails") proc do |context| subject = Peck::Rails.subject(context) context_type = Peck::Rails.context_type(context, subject) [ Peck::Rails::Helper, Peck::Rails::Model, Peck::Rails::Controller ].each do |klass| klass.send(:init, context, context_type, subject) end context.before do if respond_to?(:setup_fixtures) begin setup_fixtures rescue ActiveRecord::ConnectionNotEstablished end end end context.after do if respond_to?(:teardown_fixtures) begin teardown_fixtures rescue ActiveRecord::ConnectionNotEstablished end end end end end end end class Peck class Notifiers class Base include Peck::Rails::BacktraceCleaning end end end Peck::Context.once(&Peck::Rails.init)
Pod::Spec.new do |s| s.name = "Sqwiggle" s.version = "0.1.3" s.summary = "Objective-C Wrapper for Sqwiggle API" s.homepage = "https://www.sqwiggle.com" s.license = 'MIT' s.author = { "Cameron Webb" => "cameron@sqwiggle.com" } s.source = { :git => "https://github.com/sqwiggle/sqwiggle-ios-sdk.git", :tag => s.version.to_s } s.ios.deployment_target = '6.0' s.requires_arc = true s.public_header_files = "iOSSDK/*.h" s.source_files = "iOSSDK/*.{h,m}" s.dependency 'AFNetworking', "~> 2.0.3" s.dependency "ObjectiveSugar", '~> 0.9' end Add prefix header imports Pod::Spec.new do |s| s.name = "Sqwiggle" s.version = "0.1.3" s.summary = "Objective-C Wrapper for Sqwiggle API" s.homepage = "https://www.sqwiggle.com" s.license = 'MIT' s.author = { "Cameron Webb" => "cameron@sqwiggle.com" } s.source = { :git => "https://github.com/sqwiggle/sqwiggle-ios-sdk.git", :tag => s.version.to_s } s.ios.deployment_target = '6.0' s.requires_arc = true s.public_header_files = "iOSSDK/*.h" s.source_files = "iOSSDK/*.{h,m}" s.dependency 'AFNetworking', "~> 2.0.3" s.dependency "ObjectiveSugar", '~> 0.9' s.prefix_header_contents = '#import <ObjectiveSugar/ObjectiveSugar.h>', '#import <AFNetworking/AFNetworking.h>' end
module Pinas VERSION = "0.2.0" end bump version module Pinas VERSION = "0.2.1" end
Pod::Spec.new do |s| s.name = "StompKit" s.version = "0.1.21" s.summary = "STOMP Objective-C Client for iOS." s.homepage = "https://github.com/mobile-web-messaging/StompKit" s.license = 'Apache License, Version 2.0' s.author = "Jeff Mesnil" s.source = { :git => 'https://github.com/mobile-web-messaging/StompKit.git', :tag => "#{s.version}" } s.ios.deployment_target = '5.0' s.osx.deployment_target = '10.7' s.source_files = 'StompKit/*.{h,m}' s.public_header_files = 'StompKit/StompKit.h' s.requires_arc = true s.dependency 'CocoaAsyncSocket', '7.4.1' end pointing cocoaasync in debug-mode Pod::Spec.new do |s| s.name = "StompKit" s.version = "0.1.22" s.summary = "STOMP Objective-C Client for iOS." s.homepage = "https://github.com/mobile-web-messaging/StompKit" s.license = 'Apache License, Version 2.0' s.author = "Jeff Mesnil" s.source = { :git => 'https://github.com/mobile-web-messaging/StompKit.git', :tag => "#{s.version}" } s.ios.deployment_target = '5.0' s.osx.deployment_target = '10.7' s.source_files = 'StompKit/*.{h,m}' s.public_header_files = 'StompKit/StompKit.h' s.requires_arc = true s.dependency 'CocoaAsyncSocket', '7.4.1', :git => "git@github.com:buffpojken/CocoaAsyncSocket.git" end
module PivoFlow class Cli def initialize *args if args.length.zero? puts "You forgot method name" exit 1 end parse_argv(*args) end def stories PivoFlow::Pivotal.new.show_stories end def start story_id PivoFlow::Pivotal.new.pick_up_story(story_id) end def finish story_id=nil file_story_path = File.join(Dir.pwd, "/tmp/.pivotal_story_id") if File.exists? file_story_path story_id = File.open(file_story_path).read.strip end PivoFlow::Pivotal.new.finish_story(story_id) end def clear file_story_path = File.join(Dir.pwd, "/tmp/.pivotal_story_id") if File.exists? file_story_path FileUtils.remove_file(file_story_path) end puts "Current pivotal story id cleared." end def reconfig PivoFlow::Base.new.reconfig end private def valid_method? method_name self.methods.include? method_name.to_sym end def parse_argv(*args) command = args.first.split.first args = args.slice(1..-1) unless valid_method?(command) puts "Ups, no such method..." exit 1 end send(command, *args) exit 0 end end end don't show stacktrace on exit + version module PivoFlow class Cli def initialize *args if args.length.zero? puts "You forgot method name" exit 1 end Signal.trap(2) { puts "\nkkthxbye!" exit(0) } parse_argv(*args) end def stories PivoFlow::Pivotal.new.show_stories end def start story_id PivoFlow::Pivotal.new.pick_up_story(story_id) end def finish story_id=nil file_story_path = File.join(Dir.pwd, "/tmp/.pivotal_story_id") if File.exists? file_story_path story_id = File.open(file_story_path).read.strip end PivoFlow::Pivotal.new.finish_story(story_id) end def clear file_story_path = File.join(Dir.pwd, "/tmp/.pivotal_story_id") if File.exists? file_story_path FileUtils.remove_file(file_story_path) end puts "Current pivotal story id cleared." end def reconfig PivoFlow::Base.new.reconfig end def version puts PivoFlow::VERSION end private def valid_method? method_name self.methods.include? method_name.to_sym end def parse_argv(*args) command = args.first.split.first args = args.slice(1..-1) unless valid_method?(command) puts "Ups, no such method..." exit 1 end send(command, *args) exit 0 end end end
require 'open-uri' require 'json' require 'fuzzy_match' module Cinch module Plugins class Melon include Cinch::Plugin match /(melon)$/ match /(melon) (.+)/, method: :with_num match /(melon trend)$/, method: :trend match /(melon trend) (.+)/, method: :trend_num match /(help melon)$/, method: :help def execute(m) with_num(m, '.', 'melon', '1') end def with_num(m, prefix, melon, entry) return if entry.include? 'trend' return m.reply '1-100 only bru' if entry.to_i > 100 return m.reply '1-100 only bru' if entry == '0' return m.reply 'invalid num bru' if entry.to_i < 0 link = open("http://www.melon.com/chart/index.htm.json").read result = JSON.parse(link) if !/\A\d+\z/.match(entry) all_songs = Hash.new all_titles = Array.new result['songList'].each do |song| all_titles << song['songName'].downcase all_songs[song['curRank']] = song['songName'].downcase end match = FuzzyMatch.new(all_titles).find(entry.downcase) match_rank = all_songs.key(match).to_i rank = result['songList'][match_rank - 1]['curRank'] artist = result['songList'][match_rank - 1]['artistNameBasket'] title = result['songList'][match_rank - 1]['songName'] return m.reply "Melon Rank #{rank}: #{artist} - #{title}" else rank = result['songList'][entry.to_i - 1]['curRank'] artist = result['songList'][entry.to_i - 1]['artistNameBasket'] title = result['songList'][entry.to_i - 1]['songName'] return m.reply "Melon Rank #{rank}: #{artist} - #{title}" end m.reply 'no results in top 100 bru' end def trend(m) trend_num(m, '.', 'melon trend', 1) end def trend_num(m, prefix, melon_trend, num) return m.reply '1-10 only bru' if num.to_i > 10 return m.reply 'invalid num bru' if num.to_i < 1 link = open("http://www.melon.com/search/trend/index.htm.json").read result = JSON.parse(link) rank = result['keywordRealList'][num.to_i - 1]['ranking'] keyword = result['keywordRealList'][num.to_i - 1]['keyword'] m.reply "Melon Trending #{rank}: #{keyword}" end def help(m) m.reply 'returns current song at specified melon rank.' m.reply '.melon trend [num] to return keyword(s) at specified melon trending search rank' end end end end Refactor for DRYness require 'open-uri' require 'json' require 'fuzzy_match' module Cinch module Plugins class Melon include Cinch::Plugin match /(melon)$/ match /(melon) (.+)/, method: :with_num match /(melon trend)$/, method: :trend match /(melon trend) (.+)/, method: :trend_num match /(help melon)$/, method: :help def execute(m) with_num(m, '.', 'melon', '1') end def with_num(m, prefix, melon, entry) return if entry.include? 'trend' return m.reply '1-100 only bru' if entry.to_i > 100 return m.reply '1-100 only bru' if entry == '0' return m.reply 'invalid num bru' if entry.to_i < 0 link = open("http://www.melon.com/chart/index.htm.json").read result = JSON.parse(link) if !/\A\d+\z/.match(entry) # if entry is not a number with_entry(m, result, entry) else rank = result['songList'][entry.to_i - 1]['curRank'] artist = result['songList'][entry.to_i - 1]['artistNameBasket'] title = result['songList'][entry.to_i - 1]['songName'] return m.reply "Melon Rank #{rank}: #{artist} - #{title}" end end def with_entry(m, result, entry) all_songs = Hash.new all_titles = Array.new result['songList'].each do |song| all_titles << song['songName'].downcase all_songs[song['curRank']] = song['songName'].downcase end match = FuzzyMatch.new(all_titles).find(entry.downcase) match_rank = all_songs.key(match).to_i rank = result['songList'][match_rank - 1]['curRank'] artist = result['songList'][match_rank - 1]['artistNameBasket'] title = result['songList'][match_rank - 1]['songName'] m.reply "Melon Rank #{rank}: #{artist} - #{title}" end def trend(m) trend_num(m, '.', 'melon trend', 1) end def trend_num(m, prefix, melon_trend, num) return m.reply '1-10 only bru' if num.to_i > 10 return m.reply 'invalid num bru' if num.to_i < 1 link = open("http://www.melon.com/search/trend/index.htm.json").read result = JSON.parse(link) rank = result['keywordRealList'][num.to_i - 1]['ranking'] keyword = result['keywordRealList'][num.to_i - 1]['keyword'] m.reply "Melon Trending #{rank}: #{keyword}" end def help(m) m.reply 'returns current song at specified melon rank.' m.reply '.melon trend [num] to return keyword(s) at specified melon trending search rank' end end end end
Pod::Spec.new do |s| s.name = "SwiftDDP" s.version = "0.2.0" s.summary = "A DDP Client for communicating with Meteor servers, written in Swift. Supports OAuth login with Facebook, Google, Twitter & Github." s.description = <<-DESC "A DDP Client for communicating with DDP Servers (Meteor JS), written in Swift" DESC s.homepage = "https://github.com/siegesmund/SwiftDDP" s.license = 'MIT' s.author = { "Peter Siegesmund" => "peter.siegesmund@icloud.com" } s.source = { :git => "https://github.com/siegesmund/SwiftDDP.git", :tag => s.version.to_s } s.social_media_url = 'https://twitter.com/psiegesmund' s.requires_arc = true s.platform = :ios, '8.1' s.source_files = 'SwiftDDP/**/*.swift' s.dependency 'CryptoSwift' s.dependency 'SwiftWebSocket' s.dependency 'XCGLogger' end updated podspec Pod::Spec.new do |s| s.name = "SwiftDDP" s.version = "0.2.1" s.summary = "A DDP Client for communicating with Meteor servers, written in Swift. Supports OAuth login with Facebook, Google, Twitter & Github." s.description = <<-DESC "A DDP Client for communicating with DDP Servers (Meteor JS), written in Swift" DESC s.homepage = "https://github.com/siegesmund/SwiftDDP" s.license = 'MIT' s.author = { "Peter Siegesmund" => "peter.siegesmund@icloud.com" } s.source = { :git => "https://github.com/siegesmund/SwiftDDP.git", :tag => s.version.to_s } s.social_media_url = 'https://twitter.com/psiegesmund' s.requires_arc = true s.platform = :ios, '8.1' s.source_files = 'SwiftDDP/**/*.swift' s.dependency 'CryptoSwift' s.dependency 'SwiftWebSocket' s.dependency 'XCGLogger' end
Pod::Spec.new do |s| s.version = "3.0.4" s.name = "SwiftyVK" s.summary = "Easy and powerful way to interact with VK API for iOS and macOS" s.homepage = "https://github.com/SwiftyVK/SwiftyVK" s.authors = { "Alexey Kudryavtsev" => "westor@me.com" } s.license = { :type => 'MIT', :file => 'LICENSE.txt'} s.requires_arc = true s.osx.deployment_target = "10.10" s.ios.deployment_target = "8.0" s.source = { :git => "https://github.com/SwiftyVK/SwiftyVK.git" , :tag => s.version.to_s } s.source_files = "Library/Sources/**/*.*" s.ios.source_files = "Library/UI/iOS" s.osx.source_files = "Library/UI/macOS" s.ios.resources = "Library/Resources/Bundles/SwiftyVK_resources_iOS.bundle" s.osx.resources = "Library/Resources/Bundles/SwiftyVK_resources_macOS.bundle" end [CocoaPods] Bump patch version Pod::Spec.new do |s| s.version = "3.0.5" s.name = "SwiftyVK" s.summary = "Easy and powerful way to interact with VK API for iOS and macOS" s.homepage = "https://github.com/SwiftyVK/SwiftyVK" s.authors = { "Alexey Kudryavtsev" => "westor@me.com" } s.license = { :type => 'MIT', :file => 'LICENSE.txt'} s.requires_arc = true s.osx.deployment_target = "10.10" s.ios.deployment_target = "8.0" s.source = { :git => "https://github.com/SwiftyVK/SwiftyVK.git" , :tag => s.version.to_s } s.source_files = "Library/Sources/**/*.*" s.ios.source_files = "Library/UI/iOS" s.osx.source_files = "Library/UI/macOS" s.ios.resources = "Library/Resources/Bundles/SwiftyVK_resources_iOS.bundle" s.osx.resources = "Library/Resources/Bundles/SwiftyVK_resources_macOS.bundle" end
class Controls PARAMS_REQUIRED = [:window] BUTTONS = { up: Gosu::KbUp, down: Gosu::KbDown, left: Gosu::KbLeft, right: Gosu::KbRight } def initialize(params) Params.check_params(params, PARAMS_REQUIRED) @window = params[:window] @buttons_pressed = [] end def press_button(button) BUTTONS.each do |key, value| if button == value @buttons_pressed = key end end end end Fix erroneous assignment of @buttons_pressed class Controls PARAMS_REQUIRED = [:window] BUTTONS = { up: Gosu::KbUp, down: Gosu::KbDown, left: Gosu::KbLeft, right: Gosu::KbRight } def initialize(params) Params.check_params(params, PARAMS_REQUIRED) @window = params[:window] @buttons_pressed = [] end def press_button(button) BUTTONS.each do |key, value| if button == value @buttons_pressed.push(key) end end end end
module PQSDK VERSION = '2.1.7'.freeze end new v module PQSDK VERSION = '2.1.8'.freeze end
class Matriz include Enumerable include Comparable attr_reader :_fil, :_col, :_Matriz def initialize() end #------------------------------------------------------------------- def convert(array) @_fil = array.length @_col = array[0].length matriz_retorno = nil totalElementos = @_fil * @_col if (ContarCeros(array) % totalElementos) < 0.6 matriz_retorno = Matriz_Densa.new(@_fil, @_col) matriz_retorno.copy!(array) else matriz_retorno = Matriz_Dispersa.new(@_fil, @_col) matriz_retorno.copy!(array) end matriz_retorno end #------------------------------------------------------------------- private def ContarCeros(array) nCeros = 0 for i in (0...@_fil) for j in (0...@_col) if (array[i][j] == 0) nCeros+=1 end end end nCeros end #------------------------------------------------------------------- end ######################################################################## class Matriz_Densa < Matriz def initialize(fil, col) @_fil, @_col = fil, col @_Matriz = Array.new(@_fil){Array.new()} #for i in (0...@_fil) # @_Matriz[i] = Array.new() #end end #------------------------------------------------------------------- def read() for i in (0...@_fil) for j in (0...@_col) print "get element [#{i}][#{j}]: " value = gets @_Matriz[i][j] = value.to_i end end end #------------------------------------------------------------------- def to_s() cad = "" for i in (0...@_fil) for j in (0...@_col) cad << "#{@_Matriz[i][j]} " end cad << "\n" end cad end #------------------------------------------------------------------- def copy!(other) @_fil = other.length @_col = other[0].length for i in (0...other.length) #arr = other[i] for j in (0...other[i].length) @_Matriz[i][j] = other[i][j] end #for j end #for i end #------------------------------------------------------------------- def +(other) sum = Matriz_Densa.new(@_fil, @_col) 0.upto(@_fil-1) { |i| 0.upto(@_col-1) { |j| sum._Matriz[i][j] = (@_Matriz[i][j] + other._Matriz[i][j]) } } sum end #------------------------------------------------------------------- def sum(other) sum = Matriz_Densa.new(@_fil, @_col) for i in (0...@_fil) for j in (0...@_col) sum._Matriz[i][j] = (@_Matriz[i][j] + other._Matriz[i][j]) end end sum end #------------------------------------------------------------------- def *(other) mult = Matriz_Densa.new(@_fil, @_col) 0.upto(@_fil-1) { |i| 0.upto(@_col-1) { |j| aux = 0 0.upto(other._fil-1) { |k| aux += (@_Matriz[i][k] * other._Matriz[k][j]) } mult._Matriz[i][j] = aux } } mult end #------------------------------------------------------------------- def prod(other) mult = Matriz_Densa.new(@_fil, @_col) for i in (0...@_fil) for j in (0...other._col) aux = 0 for k in (0...other._fil) aux += (@_Matriz[i][k] * other._Matriz[k][j]) end #for mult._Matriz[i][j] = aux end #for j end #for i mult end #------------------------------------------------------------------- def max() max = @_Matriz[0][0] 0.upto(@_fil-1) { |i| 0.upto(@_col-1) { |j| if (@_Matriz[i][j] >= max) max = @_Matriz[i][j] end } } max end #------------------------------------------------------------------- def min() min = @_Matriz[0][0] 0.upto(@_fil-1) { |i| 0.upto(@_col-1) { |j| if (@_Matriz[i][j] <= min) min = @_Matriz[i][j] end } } min end #------------------------------------------------------------------- def ==(other) raise TypeError, "Solo se pueden comparar matrices" unless other.is_a?Matriz_Densa raise RangeError, "Las filas deben ser iguales" unless @_fil == other._fil raise RangeError, "Las columnas deben ser iguales" unless @_col == other._col iguales = true for i in (0...@_fil) for j in (0...@_col) if (@_Matriz[i][j] != other._Matriz[i][j]) iguales = false end #if end #for j end #for i iguales end #------------------------------------------------------------------- def to_mdisp() #conversion a Matriz_Dispersa mat_disp = Matriz_Dispersa.new(@_fil, @_col) mat_disp.copy!(@_Matriz) mat_disp end #------------------------------------------------------------------- def coerce(other) #other.class = Matriz_Dispersa [self, other.to_mdensa] end #------------------------------------------------------------------- def each() for i in (0...@_fil) for j in (0...@_col) yield @_Matriz[i][j] end end end #------------------------------------------------------------------- def <=>(other) max <=> other.max end def encontrar 0.upto(@_fil-1) { |i| 0.upto(@_col-1) { |j| if (yield @_Matriz[i][j]) return [i, j] end } } end end ######################################################################## class Matriz_Dispersa < Matriz def initialize(fil, col) @_fil, @_col = fil, col @_Matriz = Hash.new() end #------------------------------------------------------------------- def read() continue = true while (continue == true) print "intro row:" fil = gets print "intro column:" col = gets print "intro value:" value = gets @_Matriz["#{fil.to_i},#{col.to_i}"] = value.to_i print "Continue read? true(1) or false(0): " otro_mas = gets if (otro_mas.to_i != 1) continue = false end end end #------------------------------------------------------------------- def to_s() cad = "" for i in (0...@_fil) for j in (0...@_col) if (@_Matriz.include?("#{i},#{j}")) value = @_Matriz["#{i},#{j}"] cad << "#{value} " else cad << "0 " end end cad << "\n" end cad end #------------------------------------------------------------------- def copy!(other) @_fil = other.length @_col = other[0].length for i in (0...other.length) for j in (0...other[i].length) if (other[i][j] != 0) @_Matriz["#{i},#{j}"] = other[i][j].to_i end end #for j end #for i end #------------------------------------------------------------------- def +(other) end #------------------------------------------------------------------- def +(other) sum = Matriz_Dispersa.new(@_fil, @_col) 0.upto(@_fil-1) { |i| 0.upto(@_col-1) { |j| valueA = 0 if (@_Matriz.include?("#{i},#{j}")) valueA = @_Matriz["#{i},#{j}"] end valueB = 0 if (other._Matriz.include?("#{i},#{j}")) valueB = other._Matriz["#{i},#{j}"] end sum._Matriz["#{i},#{j}"] = (valueA + valueB) } } sum end #------------------------------------------------------------------- def sum(other) sum = Matriz_Dispersa.new(@_fil, @_col) for i in (0...@_fil) for j in (0...@_col) valueA = 0 if (@_Matriz.include?("#{i},#{j}")) valueA = @_Matriz["#{i},#{j}"] end valueB = 0 if (other._Matriz.include?("#{i},#{j}")) valueB = other._Matriz["#{i},#{j}"] end sum._Matriz["#{i},#{j}"] = (valueA + valueB) end end sum end #------------------------------------------------------------------- def *(other) mult = Matriz_Dispersa.new(@_fil, @_col) 0.upto(@_fil-1) { |i| 0.upto(@_col-1) { |j| aux = 0 0.upto(other._fil-1) { |k| valueA, valueB = 0, 0 if (@_Matriz.include?("#{i},#{j}")) and (other._Matriz.include?("#{i},#{j}")) aux += (@_Matriz["#{i},#{j}"] * other._Matriz["#{i},#{j}"]) else aux += 0 end } mult._Matriz["#{i},#{j}"] = aux } } mult end #------------------------------------------------------------------- def prod(other) mult = Matriz_Dispersa.new(@_fil, @_col) for i in (0...@_fil) for j in (0...other._col) aux = 0 for k in (0...other._fil) valueA, valueB = 0, 0 if (@_Matriz.include?("#{i},#{j}")) and (other._Matriz.include?("#{i},#{j}")) aux += (@_Matriz["#{i},#{j}"] * other._Matriz["#{i},#{j}"]) else aux += 0 end end #for mult._Matriz["#{i},#{j}"] = aux end #for j end #for i mult end #------------------------------------------------------------------- def max() if (@_Matriz.include?("0,0")) #max = al primer elemento del hash max = @_Matriz["0,0"] else max = 0 end for i in (0...@_fil) for j in (0...@_col) if ((@_Matriz.include?("#{i},#{j}")) && (@_Matriz["#{i},#{j}"] >= max)) max = @_Matriz["#{i},#{j}"] end #if end #for j end #for i max end #------------------------------------------------------------------- def min() if (@_Matriz.include?("0,0")) #min = al primer elemento del hash min = @_Matriz["0,0"] else min = 0 end for i in (0...@_fil) for j in (0...@_col) if (@_Matriz.include?("#{i},#{j}")) if (@_Matriz["#{i},#{j}"] <= min) min = @_Matriz["#{i},#{j}"] end else #Si el minimo no tiene en cuenta el 0 quitar el else min = 0 end #if end #for j end #for i max end #------------------------------------------------------------------- def ==(other) raise TypeError, "Solo se pueden comparar matrices" unless other.is_a?Matriz_Dispersa raise RangeError, "Las filas deben ser iguales" unless @_fil == other._fil raise RangeError, "Las columnas deben ser iguales" unless @_col == other._col iguales = true if (@_Matriz != other._Matriz) iguales = false end iguales end #------------------------------------------------------------------- def to_mdensa() #conversion a matriz mat_densa = Matriz_Densa.new(@_fil, @_col) array = Array.new() for i in (0...@_fil) aux = Array.new() for j in (0...@_col) if (@_Matriz.include?("#{i},#{j}")) aux << @_Matriz["#{i},#{j}"] else aux << 0 end #if end #for j array << aux end #for i mat_densa.copy!(array) mat_densa end #------------------------------------------------------------------- def coerce(other) #other.class = Matriz_Densa [self, other.to_mdisp] end #------------------------------------------------------------------- def each() for i in (0...@_fil) for j in (0...@_col) if (@_Matriz.include?("#{i},#{j}")) yield @_Matriz["#{i},#{j}"] end end end end #------------------------------------------------------------------- def <=>(other) max <=> other.max end end ######################################################################## Puesto return nil en encontrar class Matriz include Enumerable include Comparable attr_reader :_fil, :_col, :_Matriz def initialize() end #------------------------------------------------------------------- def convert(array) @_fil = array.length @_col = array[0].length matriz_retorno = nil totalElementos = @_fil * @_col if (ContarCeros(array) % totalElementos) < 0.6 matriz_retorno = Matriz_Densa.new(@_fil, @_col) matriz_retorno.copy!(array) else matriz_retorno = Matriz_Dispersa.new(@_fil, @_col) matriz_retorno.copy!(array) end matriz_retorno end #------------------------------------------------------------------- private def ContarCeros(array) nCeros = 0 for i in (0...@_fil) for j in (0...@_col) if (array[i][j] == 0) nCeros+=1 end end end nCeros end #------------------------------------------------------------------- end ######################################################################## class Matriz_Densa < Matriz def initialize(fil, col) @_fil, @_col = fil, col @_Matriz = Array.new(@_fil){Array.new()} #for i in (0...@_fil) # @_Matriz[i] = Array.new() #end end #------------------------------------------------------------------- def read() for i in (0...@_fil) for j in (0...@_col) print "get element [#{i}][#{j}]: " value = gets @_Matriz[i][j] = value.to_i end end end #------------------------------------------------------------------- def to_s() cad = "" for i in (0...@_fil) for j in (0...@_col) cad << "#{@_Matriz[i][j]} " end cad << "\n" end cad end #------------------------------------------------------------------- def copy!(other) @_fil = other.length @_col = other[0].length for i in (0...other.length) #arr = other[i] for j in (0...other[i].length) @_Matriz[i][j] = other[i][j] end #for j end #for i end #------------------------------------------------------------------- def +(other) sum = Matriz_Densa.new(@_fil, @_col) 0.upto(@_fil-1) { |i| 0.upto(@_col-1) { |j| sum._Matriz[i][j] = (@_Matriz[i][j] + other._Matriz[i][j]) } } sum end #------------------------------------------------------------------- def sum(other) sum = Matriz_Densa.new(@_fil, @_col) for i in (0...@_fil) for j in (0...@_col) sum._Matriz[i][j] = (@_Matriz[i][j] + other._Matriz[i][j]) end end sum end #------------------------------------------------------------------- def *(other) mult = Matriz_Densa.new(@_fil, @_col) 0.upto(@_fil-1) { |i| 0.upto(@_col-1) { |j| aux = 0 0.upto(other._fil-1) { |k| aux += (@_Matriz[i][k] * other._Matriz[k][j]) } mult._Matriz[i][j] = aux } } mult end #------------------------------------------------------------------- def prod(other) mult = Matriz_Densa.new(@_fil, @_col) for i in (0...@_fil) for j in (0...other._col) aux = 0 for k in (0...other._fil) aux += (@_Matriz[i][k] * other._Matriz[k][j]) end #for mult._Matriz[i][j] = aux end #for j end #for i mult end #------------------------------------------------------------------- def max() max = @_Matriz[0][0] 0.upto(@_fil-1) { |i| 0.upto(@_col-1) { |j| if (@_Matriz[i][j] >= max) max = @_Matriz[i][j] end } } max end #------------------------------------------------------------------- def min() min = @_Matriz[0][0] 0.upto(@_fil-1) { |i| 0.upto(@_col-1) { |j| if (@_Matriz[i][j] <= min) min = @_Matriz[i][j] end } } min end #------------------------------------------------------------------- def ==(other) raise TypeError, "Solo se pueden comparar matrices" unless other.is_a?Matriz_Densa raise RangeError, "Las filas deben ser iguales" unless @_fil == other._fil raise RangeError, "Las columnas deben ser iguales" unless @_col == other._col iguales = true for i in (0...@_fil) for j in (0...@_col) if (@_Matriz[i][j] != other._Matriz[i][j]) iguales = false end #if end #for j end #for i iguales end #------------------------------------------------------------------- def to_mdisp() #conversion a Matriz_Dispersa mat_disp = Matriz_Dispersa.new(@_fil, @_col) mat_disp.copy!(@_Matriz) mat_disp end #------------------------------------------------------------------- def coerce(other) #other.class = Matriz_Dispersa [self, other.to_mdensa] end #------------------------------------------------------------------- def each() for i in (0...@_fil) for j in (0...@_col) yield @_Matriz[i][j] end end end #------------------------------------------------------------------- def <=>(other) max <=> other.max end def encontrar 0.upto(@_fil-1) { |i| 0.upto(@_col-1) { |j| if (yield @_Matriz[i][j]) return [i, j] end } } return nil end end ######################################################################## class Matriz_Dispersa < Matriz def initialize(fil, col) @_fil, @_col = fil, col @_Matriz = Hash.new() end #------------------------------------------------------------------- def read() continue = true while (continue == true) print "intro row:" fil = gets print "intro column:" col = gets print "intro value:" value = gets @_Matriz["#{fil.to_i},#{col.to_i}"] = value.to_i print "Continue read? true(1) or false(0): " otro_mas = gets if (otro_mas.to_i != 1) continue = false end end end #------------------------------------------------------------------- def to_s() cad = "" for i in (0...@_fil) for j in (0...@_col) if (@_Matriz.include?("#{i},#{j}")) value = @_Matriz["#{i},#{j}"] cad << "#{value} " else cad << "0 " end end cad << "\n" end cad end #------------------------------------------------------------------- def copy!(other) @_fil = other.length @_col = other[0].length for i in (0...other.length) for j in (0...other[i].length) if (other[i][j] != 0) @_Matriz["#{i},#{j}"] = other[i][j].to_i end end #for j end #for i end #------------------------------------------------------------------- def +(other) end #------------------------------------------------------------------- def +(other) sum = Matriz_Dispersa.new(@_fil, @_col) 0.upto(@_fil-1) { |i| 0.upto(@_col-1) { |j| valueA = 0 if (@_Matriz.include?("#{i},#{j}")) valueA = @_Matriz["#{i},#{j}"] end valueB = 0 if (other._Matriz.include?("#{i},#{j}")) valueB = other._Matriz["#{i},#{j}"] end sum._Matriz["#{i},#{j}"] = (valueA + valueB) } } sum end #------------------------------------------------------------------- def sum(other) sum = Matriz_Dispersa.new(@_fil, @_col) for i in (0...@_fil) for j in (0...@_col) valueA = 0 if (@_Matriz.include?("#{i},#{j}")) valueA = @_Matriz["#{i},#{j}"] end valueB = 0 if (other._Matriz.include?("#{i},#{j}")) valueB = other._Matriz["#{i},#{j}"] end sum._Matriz["#{i},#{j}"] = (valueA + valueB) end end sum end #------------------------------------------------------------------- def *(other) mult = Matriz_Dispersa.new(@_fil, @_col) 0.upto(@_fil-1) { |i| 0.upto(@_col-1) { |j| aux = 0 0.upto(other._fil-1) { |k| valueA, valueB = 0, 0 if (@_Matriz.include?("#{i},#{j}")) and (other._Matriz.include?("#{i},#{j}")) aux += (@_Matriz["#{i},#{j}"] * other._Matriz["#{i},#{j}"]) else aux += 0 end } mult._Matriz["#{i},#{j}"] = aux } } mult end #------------------------------------------------------------------- def prod(other) mult = Matriz_Dispersa.new(@_fil, @_col) for i in (0...@_fil) for j in (0...other._col) aux = 0 for k in (0...other._fil) valueA, valueB = 0, 0 if (@_Matriz.include?("#{i},#{j}")) and (other._Matriz.include?("#{i},#{j}")) aux += (@_Matriz["#{i},#{j}"] * other._Matriz["#{i},#{j}"]) else aux += 0 end end #for mult._Matriz["#{i},#{j}"] = aux end #for j end #for i mult end #------------------------------------------------------------------- def max() if (@_Matriz.include?("0,0")) #max = al primer elemento del hash max = @_Matriz["0,0"] else max = 0 end for i in (0...@_fil) for j in (0...@_col) if ((@_Matriz.include?("#{i},#{j}")) && (@_Matriz["#{i},#{j}"] >= max)) max = @_Matriz["#{i},#{j}"] end #if end #for j end #for i max end #------------------------------------------------------------------- def min() if (@_Matriz.include?("0,0")) #min = al primer elemento del hash min = @_Matriz["0,0"] else min = 0 end for i in (0...@_fil) for j in (0...@_col) if (@_Matriz.include?("#{i},#{j}")) if (@_Matriz["#{i},#{j}"] <= min) min = @_Matriz["#{i},#{j}"] end else #Si el minimo no tiene en cuenta el 0 quitar el else min = 0 end #if end #for j end #for i max end #------------------------------------------------------------------- def ==(other) raise TypeError, "Solo se pueden comparar matrices" unless other.is_a?Matriz_Dispersa raise RangeError, "Las filas deben ser iguales" unless @_fil == other._fil raise RangeError, "Las columnas deben ser iguales" unless @_col == other._col iguales = true if (@_Matriz != other._Matriz) iguales = false end iguales end #------------------------------------------------------------------- def to_mdensa() #conversion a matriz mat_densa = Matriz_Densa.new(@_fil, @_col) array = Array.new() for i in (0...@_fil) aux = Array.new() for j in (0...@_col) if (@_Matriz.include?("#{i},#{j}")) aux << @_Matriz["#{i},#{j}"] else aux << 0 end #if end #for j array << aux end #for i mat_densa.copy!(array) mat_densa end #------------------------------------------------------------------- def coerce(other) #other.class = Matriz_Densa [self, other.to_mdisp] end #------------------------------------------------------------------- def each() for i in (0...@_fil) for j in (0...@_col) if (@_Matriz.include?("#{i},#{j}")) yield @_Matriz["#{i},#{j}"] end end end end #------------------------------------------------------------------- def <=>(other) max <=> other.max end end ########################################################################
require "protest" require "test/unit/assertions" require "action_controller/test_case" require "webrat" module Protest module Rails # Wrap all tests in a database transaction. # # TODO: make this optional somehow (yet enabled by default) so users of # other ORMs don't run into problems. module TransactionalTests def run(*args, &block) ActiveRecord::Base.connection.transaction do super(*args, &block) raise ActiveRecord::Rollback end end end # You should inherit from this TestCase in order to get rails' helpers # loaded into Protest. These include all the assertions bundled with rails # and your tests being wrapped in a transaction. class TestCase < ::Protest::TestCase include ::Test::Unit::Assertions include ActiveSupport::Testing::Assertions include TransactionalTests end class RequestTest < TestCase #:nodoc: %w(response selector tag dom routing model).each do |kind| include ActionController::Assertions.const_get("#{kind.camelize}Assertions") end end # Make your integration tests inherit from this class, which bundles the # integration runner included with rails, and webrat's test methods. You # should use webrat for integration tests. Really. class IntegrationTest < RequestTest include ActionController::Integration::Runner include Webrat::Methods end end # The preferred way to declare a context (top level) is to use # +Protest.describe+ or +Protest.context+, which will ensure you're using # rails adapter with the helpers you need. def self.context(description, &block) Rails::TestCase.context(description, &block) end # Use +Protest.story+ to declare an integration test for your rails app. Note # that the files should still be called 'test/integration/foo_test.rb' if you # want the 'test:integration' rake task to pick them up. def self.story(description, &block) Rails::IntegrationTest.story(description, &block) end class << self alias_method :describe, :context end end Rails: Don't include Webwrat::Methods if webrat isn't available require "protest" require "test/unit/assertions" require "action_controller/test_case" begin require "webrat" rescue LoadError $no_webrat = true end module Protest module Rails # Wrap all tests in a database transaction. # # TODO: make this optional somehow (yet enabled by default) so users of # other ORMs don't run into problems. module TransactionalTests def run(*args, &block) ActiveRecord::Base.connection.transaction do super(*args, &block) raise ActiveRecord::Rollback end end end # You should inherit from this TestCase in order to get rails' helpers # loaded into Protest. These include all the assertions bundled with rails # and your tests being wrapped in a transaction. class TestCase < ::Protest::TestCase include ::Test::Unit::Assertions include ActiveSupport::Testing::Assertions include TransactionalTests end class RequestTest < TestCase #:nodoc: %w(response selector tag dom routing model).each do |kind| include ActionController::Assertions.const_get("#{kind.camelize}Assertions") end end # Make your integration tests inherit from this class, which bundles the # integration runner included with rails, and webrat's test methods. You # should use webrat for integration tests. Really. class IntegrationTest < RequestTest include ActionController::Integration::Runner include Webrat::Methods unless $no_webrat end end # The preferred way to declare a context (top level) is to use # +Protest.describe+ or +Protest.context+, which will ensure you're using # rails adapter with the helpers you need. def self.context(description, &block) Rails::TestCase.context(description, &block) end # Use +Protest.story+ to declare an integration test for your rails app. Note # that the files should still be called 'test/integration/foo_test.rb' if you # want the 'test:integration' rake task to pick them up. def self.story(description, &block) Rails::IntegrationTest.story(description, &block) end class << self alias_method :describe, :context end end
require 'cgi' require 'net/http' require 'uri' require 'medline' # 1. get 5000 PMIDs for a given search # 2. select PMIDs not in Article # 3. fetch articles in step 2 in MEDLINE format # 4. repeat 1-3 until all articles are received class PubmedImport < Struct.new(:bibliome_id, :webenv, :retstart) RETMAX = 1000 ONE_YEAR_IN_SECONDS = 365 * 24 * 60 * 60 FIVE_YEARS_IN_SECONDS = 5 * ONE_YEAR_IN_SECONDS TEN_YEARS_IN_SECONDS = 10 * ONE_YEAR_IN_SECONDS def perform bibliome = Bibliome.find(bibliome_id) bibliome.started_at ||= Time.now # timestamp only once! bibliome.save! article_ids = bibliome.article_ids medline = Medvane::Eutils.efetch(webenv, retstart, RETMAX, "medline") unless medline.size > 0 # webenv expired webenv, count = Medvane::Eutils.esearch(bibliome.query) medline = Medvane::Eutils.efetch(webenv, retstart, RETMAX, "medline") if count > bibliome.total_articles bibliome.total_articles = count bibliome.save! end end medline.each do |m| unless article_ids.include?(m.pmid.to_i) # do this way rather than medline.reject!{...}.each to save memory # http://www.nlm.nih.gov/bsd/mms/medlineelements.html a = Article.find_or_initialize_by_id(m.pmid) periods = periods(m.pubdate) journal = Journal.find_or_create_by_abbr_and_title(m.ta, m.jt) subjects = m.major_descriptors.map {|d| Subject.find_by_term(d)} ancestors = subjects.map {|s| s.ancestors}.flatten.uniq.reject! {|s| subjects.include?(s)} pubtypes = m.pt.map {|p| Pubtype.find_by_term(p)} authors = m.authors.map {|u| Author.find_or_create_by_last_name_and_fore_name_and_initials_and_suffix(u['last_name'], u['fore_name'], u['initials'], u['suffix'])} genes = [] # article if a.new_record? a.journal = journal a.pubdate = m.pubdate a.title = m.ti a.affiliation = m.ad a.source = m.source a.save! subjects.each do |s| a.subjects<<(s) end pubtypes.each do |p| a.pubtypes<<(p) end last_position = authors.size authors.each_index do |i| position = i + 1 authors[i].authorships.create!( :article => a, :position => position, :last_position => last_position ) end a.save! end # bibliome_journals periods.each do |year| bj = BibliomeJournal.find_or_initialize_by_bibliome_id_and_year_and_journal_id(bibliome.id, year, journal.id) bj.increment!(:articles_count) authors.each_index do |i| author = authors[i] position = position_name(i + 1, authors.size) #bibliome.author_journals aj = AuthorJournal.find_or_initialize_by_bibliome_id_and_author_id_and_journal_id_and_year(bibliome.id, author.id, journal.id, year) aj.increment(position) aj.increment(:total) aj.save! #bibliome.coauthorships authors.select {|c| c.id != author.id}.each do |coauthor| ca = Coauthorship.find_or_initialize_by_bibliome_id_and_author_id_and_coauthor_id_and_year(bibliome.id, author.id, coauthor.id, year) ca.increment(position) ca.increment(:total) ca.save! end #bibliome.author_subjects subjects.each do |subject| as = AuthorSubject.find_or_initialize_by_bibliome_id_and_author_id_and_subject_id_and_year(bibliome.id, author.id, subject.id, year) ["_direct", "_total"].each do |stype| as.increment(position + stype) as.increment("total" + stype) as.save! end end ## author_subject descendant ancestors.try(:each) do |subject| as = AuthorSubject.find_or_initialize_by_bibliome_id_and_author_id_and_subject_id_and_year(bibliome.id, author.id, subject.id, year) ["_descendant", "_total"].each do |stype| as.increment(position + stype) as.increment("total" + stype) as.save! end end #bibliome.author_pubtypes pubtypes.each do |pubtype| ap = AuthorPubtype.find_or_initialize_by_bibliome_id_and_author_id_and_pubtype_id_and_year(bibliome.id, author.id, pubtype.id, year) ap.increment(position) ap.increment(:total) ap.save! end # bibliome_authors ## TODO: distinguish first/last/middle/total x one/five/ten/all ba = BibliomeAuthor.find_or_initialize_by_bibliome_id_and_year_and_author_id(bibliome.id, year, author.id) ba.increment!(:articles_count) end #bibliome.journal_pubtypes pubtypes.each do |pubtype| jp = JournalPubtype.find_or_initialize_by_bibliome_id_and_journal_id_and_pubtype_id_and_year(bibliome.id, journal.id, pubtype.id, year) jp.increment!(:total) # bibliome_pubtypes bp = BibliomePubtype.find_or_initialize_by_bibliome_id_and_year_and_pubtype_id(bibliome.id, year, pubtype.id) bp.increment!(:articles_count) end #bibliome.journal_subject subjects.each do |subject| js = JournalSubject.find_or_initialize_by_bibliome_id_and_journal_id_and_subject_id_and_year(bibliome.id, journal.id, subject.id, year) js.increment(:direct) js.increment(:total) js.save! #bibliome.cosubjects subjects.reject {|s| s.id == subject.id}.each do |cosubject| cs = Cosubjectship.find_or_initialize_by_bibliome_id_and_subject_id_and_cosubject_id_and_year(bibliome.id, subject.id, cosubject.id, year) cs.increment(:direct) cs.increment(:total) cs.save! end #cosubjectst descendant subjects.reject {|s| s.id == subject.id}.map {|s| s.ancestors}.flatten.uniq.reject! {|s| subjects.include?(s) || (subject.id == s.id)}.try(:each) do |cosubject| cs = Cosubjectship.find_or_initialize_by_bibliome_id_and_subject_id_and_cosubject_id_and_year(bibliome.id, subject.id, cosubject.id, year) cs.increment(:descendant) cs.increment(:total) cs.save! end # bibliome_subjects # TODO: update schema to distinguish direct/descendant bs = BibliomeSubject.find_or_initialize_by_bibliome_id_and_year_and_subject_id(bibliome.id, year, subject.id) bs.increment!(:articles_count) end ## journal_subject descendant ancestors.try(:each) do |subject| js = JournalSubject.find_or_initialize_by_bibliome_id_and_journal_id_and_subject_id_and_year(bibliome.id, journal.id, subject.id, m.year) js.increment(:descendant) js.increment(:total) js.save! # bibliome_subjects descendants # TODO: update schema to distinguish direct/descendant ## one, five, ten end end BibliomeArticle.find_or_create_by_bibliome_id_and_article_id_and_pubdate(bibliome.id, a.id, a.pubdate) bibliome.save! end end ["all", "one", "five", "ten"].each do |period| ["journals", "authors", "subjects", "pubtypes"].each do |obj| #TODO: genes col = "#{period}_#{obj}_count" val = bibliome.send(obj).period(period).count bibliome.update_attribute(col, val) end end bibliome.articles_count = BibliomeArticle.count('id', :conditions => {:bibliome_id => bibliome.id}) if bibliome.articles_count == bibliome.total_articles bibliome.built = true bibliome.built_at = Time.now bibliome.delete_at = 2.weeks.from_now bibliome.save! end end def position_name(position, last_position) if position == 1 return "first" elsif position > 1 && position == last_position return "last" else return "middle" end end def periods(pubdate) article_age = (Time.now.to_time - pubdate.to_time).round article_age = 0 if article_age < 0 periods = [pubdate[0, 4], "all"] periods.push("one") if article_age <= ONE_YEAR_IN_SECONDS periods.push("five") if article_age <= FIVE_YEARS_IN_SECONDS periods.push("ten") if article_age <= TEN_YEARS_IN_SECONDS return periods end end process 500 articles per job require 'cgi' require 'net/http' require 'uri' require 'medline' # 1. get 5000 PMIDs for a given search # 2. select PMIDs not in Article # 3. fetch articles in step 2 in MEDLINE format # 4. repeat 1-3 until all articles are received class PubmedImport < Struct.new(:bibliome_id, :webenv, :retstart) RETMAX = 500 ONE_YEAR_IN_SECONDS = 365 * 24 * 60 * 60 FIVE_YEARS_IN_SECONDS = 5 * ONE_YEAR_IN_SECONDS TEN_YEARS_IN_SECONDS = 10 * ONE_YEAR_IN_SECONDS def perform bibliome = Bibliome.find(bibliome_id) bibliome.started_at ||= Time.now # timestamp only once! bibliome.save! article_ids = bibliome.article_ids medline = Medvane::Eutils.efetch(webenv, retstart, RETMAX, "medline") unless medline.size > 0 # webenv expired webenv, count = Medvane::Eutils.esearch(bibliome.query) medline = Medvane::Eutils.efetch(webenv, retstart, RETMAX, "medline") if count > bibliome.total_articles bibliome.total_articles = count bibliome.save! end end medline.each do |m| unless article_ids.include?(m.pmid.to_i) # do this way rather than medline.reject!{...}.each to save memory # http://www.nlm.nih.gov/bsd/mms/medlineelements.html a = Article.find_or_initialize_by_id(m.pmid) periods = periods(m.pubdate) journal = Journal.find_or_create_by_abbr_and_title(m.ta, m.jt) subjects = m.major_descriptors.map {|d| Subject.find_by_term(d)} ancestors = subjects.map {|s| s.ancestors}.flatten.uniq.reject! {|s| subjects.include?(s)} pubtypes = m.pt.map {|p| Pubtype.find_by_term(p)} authors = m.authors.map {|u| Author.find_or_create_by_last_name_and_fore_name_and_initials_and_suffix(u['last_name'], u['fore_name'], u['initials'], u['suffix'])} genes = [] # article if a.new_record? a.journal = journal a.pubdate = m.pubdate a.title = m.ti a.affiliation = m.ad a.source = m.source a.save! subjects.each do |s| a.subjects<<(s) end pubtypes.each do |p| a.pubtypes<<(p) end last_position = authors.size authors.each_index do |i| position = i + 1 authors[i].authorships.create!( :article => a, :position => position, :last_position => last_position ) end a.save! end # bibliome_journals periods.each do |year| bj = BibliomeJournal.find_or_initialize_by_bibliome_id_and_year_and_journal_id(bibliome.id, year, journal.id) bj.increment!(:articles_count) authors.each_index do |i| author = authors[i] position = position_name(i + 1, authors.size) #bibliome.author_journals aj = AuthorJournal.find_or_initialize_by_bibliome_id_and_author_id_and_journal_id_and_year(bibliome.id, author.id, journal.id, year) aj.increment(position) aj.increment(:total) aj.save! #bibliome.coauthorships authors.select {|c| c.id != author.id}.each do |coauthor| ca = Coauthorship.find_or_initialize_by_bibliome_id_and_author_id_and_coauthor_id_and_year(bibliome.id, author.id, coauthor.id, year) ca.increment(position) ca.increment(:total) ca.save! end #bibliome.author_subjects subjects.each do |subject| as = AuthorSubject.find_or_initialize_by_bibliome_id_and_author_id_and_subject_id_and_year(bibliome.id, author.id, subject.id, year) ["_direct", "_total"].each do |stype| as.increment(position + stype) as.increment("total" + stype) as.save! end end ## author_subject descendant ancestors.try(:each) do |subject| as = AuthorSubject.find_or_initialize_by_bibliome_id_and_author_id_and_subject_id_and_year(bibliome.id, author.id, subject.id, year) ["_descendant", "_total"].each do |stype| as.increment(position + stype) as.increment("total" + stype) as.save! end end #bibliome.author_pubtypes pubtypes.each do |pubtype| ap = AuthorPubtype.find_or_initialize_by_bibliome_id_and_author_id_and_pubtype_id_and_year(bibliome.id, author.id, pubtype.id, year) ap.increment(position) ap.increment(:total) ap.save! end # bibliome_authors ## TODO: distinguish first/last/middle/total x one/five/ten/all ba = BibliomeAuthor.find_or_initialize_by_bibliome_id_and_year_and_author_id(bibliome.id, year, author.id) ba.increment!(:articles_count) end #bibliome.journal_pubtypes pubtypes.each do |pubtype| jp = JournalPubtype.find_or_initialize_by_bibliome_id_and_journal_id_and_pubtype_id_and_year(bibliome.id, journal.id, pubtype.id, year) jp.increment!(:total) # bibliome_pubtypes bp = BibliomePubtype.find_or_initialize_by_bibliome_id_and_year_and_pubtype_id(bibliome.id, year, pubtype.id) bp.increment!(:articles_count) end #bibliome.journal_subject subjects.each do |subject| js = JournalSubject.find_or_initialize_by_bibliome_id_and_journal_id_and_subject_id_and_year(bibliome.id, journal.id, subject.id, year) js.increment(:direct) js.increment(:total) js.save! #bibliome.cosubjects subjects.reject {|s| s.id == subject.id}.each do |cosubject| cs = Cosubjectship.find_or_initialize_by_bibliome_id_and_subject_id_and_cosubject_id_and_year(bibliome.id, subject.id, cosubject.id, year) cs.increment(:direct) cs.increment(:total) cs.save! end #cosubjectst descendant subjects.reject {|s| s.id == subject.id}.map {|s| s.ancestors}.flatten.uniq.reject! {|s| subjects.include?(s) || (subject.id == s.id)}.try(:each) do |cosubject| cs = Cosubjectship.find_or_initialize_by_bibliome_id_and_subject_id_and_cosubject_id_and_year(bibliome.id, subject.id, cosubject.id, year) cs.increment(:descendant) cs.increment(:total) cs.save! end # bibliome_subjects # TODO: update schema to distinguish direct/descendant bs = BibliomeSubject.find_or_initialize_by_bibliome_id_and_year_and_subject_id(bibliome.id, year, subject.id) bs.increment!(:articles_count) end ## journal_subject descendant ancestors.try(:each) do |subject| js = JournalSubject.find_or_initialize_by_bibliome_id_and_journal_id_and_subject_id_and_year(bibliome.id, journal.id, subject.id, m.year) js.increment(:descendant) js.increment(:total) js.save! # bibliome_subjects descendants # TODO: update schema to distinguish direct/descendant ## one, five, ten end end BibliomeArticle.find_or_create_by_bibliome_id_and_article_id_and_pubdate(bibliome.id, a.id, a.pubdate) bibliome.save! end end ["all", "one", "five", "ten"].each do |period| ["journals", "authors", "subjects", "pubtypes"].each do |obj| #TODO: genes col = "#{period}_#{obj}_count" val = bibliome.send(obj).period(period).count bibliome.update_attribute(col, val) end end bibliome.articles_count = BibliomeArticle.count('id', :conditions => {:bibliome_id => bibliome.id}) if bibliome.articles_count == bibliome.total_articles bibliome.built = true bibliome.built_at = Time.now bibliome.delete_at = 2.weeks.from_now bibliome.save! end end def position_name(position, last_position) if position == 1 return "first" elsif position > 1 && position == last_position return "last" else return "middle" end end def periods(pubdate) article_age = (Time.now.to_time - pubdate.to_time).round article_age = 0 if article_age < 0 periods = [pubdate[0, 4], "all"] periods.push("one") if article_age <= ONE_YEAR_IN_SECONDS periods.push("five") if article_age <= FIVE_YEARS_IN_SECONDS periods.push("ten") if article_age <= TEN_YEARS_IN_SECONDS return periods end end
require 'signature' module Pusher class Client attr_accessor :scheme, :host, :port, :app_id, :key, :secret attr_reader :http_proxy, :proxy attr_writer :connect_timeout, :send_timeout, :receive_timeout, :keep_alive_timeout ## CONFIGURATION ## def initialize(options = {}) options = { :scheme => 'http', :host => 'api.pusherapp.com', :port => 80, }.merge(options) @scheme, @host, @port, @app_id, @key, @secret = options.values_at( :scheme, :host, :port, :app_id, :key, :secret ) @http_proxy = nil self.http_proxy = options[:http_proxy] if options[:http_proxy] # Default timeouts @connect_timeout = 5 @send_timeout = 5 @receive_timeout = 5 @keep_alive_timeout = 30 end # @private Returns the authentication token for the client def authentication_token Signature::Token.new(@key, @secret) end # @private Builds a url for this app, optionally appending a path def url(path = nil) URI::Generic.build({ :scheme => @scheme, :host => @host, :port => @port, :path => "/apps/#{@app_id}#{path}" }) end # Configure Pusher connection by providing a url rather than specifying # scheme, key, secret, and app_id separately. # # @example # Pusher.url = http://KEY:SECRET@api.pusherapp.com/apps/APP_ID # def url=(url) uri = URI.parse(url) @scheme = uri.scheme @app_id = uri.path.split('/').last @key = uri.user @secret = uri.password @host = uri.host @port = uri.port end def http_proxy=(http_proxy) @http_proxy = http_proxy uri = URI.parse(http_proxy) @proxy = { :scheme => uri.scheme, :host => uri.host, :port => uri.port, :user => uri.user, :password => uri.password } @http_proxy end # Configure whether Pusher API calls should be made over SSL # (default false) # # @example # Pusher.encrypted = true # def encrypted=(boolean) @scheme = boolean ? 'https' : 'http' # Configure port if it hasn't already been configured @port = boolean ? 443 : 80 end def encrypted? @scheme == 'https' end # Convenience method to set all timeouts to the same value (in seconds). # For more control, use the individual writers. def timeout=(value) @connect_timeout, @send_timeout, @receive_timeout = value, value, value end ## INTERACE WITH THE API ## def resource(path) Resource.new(self, path) end # GET arbitrary REST API resource using a synchronous http client. # All request signing is handled automatically. # # @example # begin # Pusher.get('/channels', filter_by_prefix: 'private-') # rescue Pusher::Error => e # # Handle error # end # # @param path [String] Path excluding /apps/APP_ID # @param params [Hash] API params (see http://pusher.com/docs/rest_api) # # @return [Hash] See Pusher API docs # # @raise [Pusher::Error] Unsuccessful response - see the error message # @raise [Pusher::HTTPError] Error raised inside http client. The original error is wrapped in error.original_error # def get(path, params = {}) Resource.new(self, path).get(params) end # GET arbitrary REST API resource using an asynchronous http client. # All request signing is handled automatically. # # When the eventmachine reactor is running, the em-http-request gem is used; # otherwise an async request is made using httpclient. See README for # details and examples. # # @param path [String] Path excluding /apps/APP_ID # @param params [Hash] API params (see http://pusher.com/docs/rest_api) # # @return Either an EM::DefaultDeferrable or a HTTPClient::Connection # def get_async(path, params = {}) Resource.new(self, path).get_async(params) end # POST arbitrary REST API resource using a synchronous http client. # Works identially to get method, but posts params as JSON in post body. def post(path, params = {}) Resource.new(self, path).post(params) end # POST arbitrary REST API resource using an asynchronous http client. # Works identially to get_async method, but posts params as JSON in post # body. def post_async(path, params = {}) Resource.new(self, path).post_async(params) end ## HELPER METHODS ## # Convenience method for creating a new WebHook instance for validating # and extracting info from a received WebHook # # @param request [Rack::Request] Either a Rack::Request or a Hash containing :key, :signature, :body, and optionally :content_type. # def webhook(request) WebHook.new(request, self) end # Return a convenience channel object by name. No API request is made. # # @example # Pusher['my-channel'] # @return [Channel] # @raise [ConfigurationError] unless key, secret and app_id have been # configured. Channel names should be less than 200 characters, and # should not contain anything other than letters, numbers, or the # characters "_\-=@,.;" def channel(channel_name) raise ConfigurationError, 'Missing client configuration: please check that key, secret and app_id are configured.' unless configured? Channel.new(url, channel_name, self) end alias :[] :channel # Request a list of occupied channels from the API # # GET /apps/[id]/channels # # @param params [Hash] Hash of parameters for the API - see REST API docs # # @return [Hash] See Pusher API docs # # @raise [Pusher::Error] Unsuccessful response - see the error message # @raise [Pusher::HTTPError] Error raised inside http client. The original error is wrapped in error.original_error # def channels(params = {}) get('/channels', params) end # Request info for a specific channel # # GET /apps/[id]/channels/[channel_name] # # @param channel_name [String] Channel name (max 200 characters) # @param params [Hash] Hash of parameters for the API - see REST API docs # # @return [Hash] See Pusher API docs # # @raise [Pusher::Error] Unsuccessful response - see the error message # @raise [Pusher::HTTPError] Error raised inside http client. The original error is wrapped in error.original_error # def channel_info(channel_name, params = {}) get("/channels/#{channel_name}", params) end # Trigger an event on one or more channels # # POST /apps/[app_id]/events # # @param channels [String or Array] 1-10 channel names # @param event_name [String] # @param data [Object] Event data to be triggered in javascript. # Objects other than strings will be converted to JSON # @param params [Hash] Additional parameters to send to api, e.g socket_id # # @return [Hash] See Pusher API docs # # @raise [Pusher::Error] Unsuccessful response - see the error message # @raise [Pusher::HTTPError] Error raised inside http client. The original error is wrapped in error.original_error # def trigger(channels, event_name, data, params = {}) post('/events', trigger_params(channels, event_name, data, params)) end # Trigger an event on one or more channels asynchronously. # For parameters see #trigger # def trigger_async(channels, event_name, data, params = {}) post_async('/events', trigger_params(channels, event_name, data, params)) end # @private Construct a net/http http client def sync_http_client @client ||= begin require 'httpclient' HTTPClient.new(@http_proxy).tap do |c| c.connect_timeout = @connect_timeout c.send_timeout = @send_timeout c.receive_timeout = @receive_timeout c.keep_alive_timeout = @keep_alive_timeout end end end # @private Construct an em-http-request http client def em_http_client(uri) begin unless defined?(EventMachine) && EventMachine.reactor_running? raise Error, "In order to use async calling you must be running inside an eventmachine loop" end require 'em-http' unless defined?(EventMachine::HttpRequest) connection_opts = { :connect_timeout => @connect_timeout, :inactivity_timeout => @receive_timeout, } if defined?(@proxy) proxy_opts = { :host => @proxy[:host], :port => @proxy[:port] } if @proxy[:user] proxy_opts[:authorization] = [@proxy[:user], @proxy[:password]] end connection_opts[:proxy] = proxy_opts end EventMachine::HttpRequest.new(uri, connection_opts) end end private def trigger_params(channels, event_name, data, params) channels = Array(channels).map(&:to_s) raise Pusher::Error, "Too many channels '#{[channels].flatten.join(?,)}'" if channels.length > 10 encoded_data = case data when String data else begin MultiJson.encode(data) rescue MultiJson::DecodeError => e Pusher.logger.error("Could not convert #{data.inspect} into JSON") raise e end end return params.merge({ :name => event_name, :channels => channels, :data => encoded_data, }) end def configured? host && scheme && key && secret && app_id end end end Just include the number of channels which was too many require 'signature' module Pusher class Client attr_accessor :scheme, :host, :port, :app_id, :key, :secret attr_reader :http_proxy, :proxy attr_writer :connect_timeout, :send_timeout, :receive_timeout, :keep_alive_timeout ## CONFIGURATION ## def initialize(options = {}) options = { :scheme => 'http', :host => 'api.pusherapp.com', :port => 80, }.merge(options) @scheme, @host, @port, @app_id, @key, @secret = options.values_at( :scheme, :host, :port, :app_id, :key, :secret ) @http_proxy = nil self.http_proxy = options[:http_proxy] if options[:http_proxy] # Default timeouts @connect_timeout = 5 @send_timeout = 5 @receive_timeout = 5 @keep_alive_timeout = 30 end # @private Returns the authentication token for the client def authentication_token Signature::Token.new(@key, @secret) end # @private Builds a url for this app, optionally appending a path def url(path = nil) URI::Generic.build({ :scheme => @scheme, :host => @host, :port => @port, :path => "/apps/#{@app_id}#{path}" }) end # Configure Pusher connection by providing a url rather than specifying # scheme, key, secret, and app_id separately. # # @example # Pusher.url = http://KEY:SECRET@api.pusherapp.com/apps/APP_ID # def url=(url) uri = URI.parse(url) @scheme = uri.scheme @app_id = uri.path.split('/').last @key = uri.user @secret = uri.password @host = uri.host @port = uri.port end def http_proxy=(http_proxy) @http_proxy = http_proxy uri = URI.parse(http_proxy) @proxy = { :scheme => uri.scheme, :host => uri.host, :port => uri.port, :user => uri.user, :password => uri.password } @http_proxy end # Configure whether Pusher API calls should be made over SSL # (default false) # # @example # Pusher.encrypted = true # def encrypted=(boolean) @scheme = boolean ? 'https' : 'http' # Configure port if it hasn't already been configured @port = boolean ? 443 : 80 end def encrypted? @scheme == 'https' end # Convenience method to set all timeouts to the same value (in seconds). # For more control, use the individual writers. def timeout=(value) @connect_timeout, @send_timeout, @receive_timeout = value, value, value end ## INTERACE WITH THE API ## def resource(path) Resource.new(self, path) end # GET arbitrary REST API resource using a synchronous http client. # All request signing is handled automatically. # # @example # begin # Pusher.get('/channels', filter_by_prefix: 'private-') # rescue Pusher::Error => e # # Handle error # end # # @param path [String] Path excluding /apps/APP_ID # @param params [Hash] API params (see http://pusher.com/docs/rest_api) # # @return [Hash] See Pusher API docs # # @raise [Pusher::Error] Unsuccessful response - see the error message # @raise [Pusher::HTTPError] Error raised inside http client. The original error is wrapped in error.original_error # def get(path, params = {}) Resource.new(self, path).get(params) end # GET arbitrary REST API resource using an asynchronous http client. # All request signing is handled automatically. # # When the eventmachine reactor is running, the em-http-request gem is used; # otherwise an async request is made using httpclient. See README for # details and examples. # # @param path [String] Path excluding /apps/APP_ID # @param params [Hash] API params (see http://pusher.com/docs/rest_api) # # @return Either an EM::DefaultDeferrable or a HTTPClient::Connection # def get_async(path, params = {}) Resource.new(self, path).get_async(params) end # POST arbitrary REST API resource using a synchronous http client. # Works identially to get method, but posts params as JSON in post body. def post(path, params = {}) Resource.new(self, path).post(params) end # POST arbitrary REST API resource using an asynchronous http client. # Works identially to get_async method, but posts params as JSON in post # body. def post_async(path, params = {}) Resource.new(self, path).post_async(params) end ## HELPER METHODS ## # Convenience method for creating a new WebHook instance for validating # and extracting info from a received WebHook # # @param request [Rack::Request] Either a Rack::Request or a Hash containing :key, :signature, :body, and optionally :content_type. # def webhook(request) WebHook.new(request, self) end # Return a convenience channel object by name. No API request is made. # # @example # Pusher['my-channel'] # @return [Channel] # @raise [ConfigurationError] unless key, secret and app_id have been # configured. Channel names should be less than 200 characters, and # should not contain anything other than letters, numbers, or the # characters "_\-=@,.;" def channel(channel_name) raise ConfigurationError, 'Missing client configuration: please check that key, secret and app_id are configured.' unless configured? Channel.new(url, channel_name, self) end alias :[] :channel # Request a list of occupied channels from the API # # GET /apps/[id]/channels # # @param params [Hash] Hash of parameters for the API - see REST API docs # # @return [Hash] See Pusher API docs # # @raise [Pusher::Error] Unsuccessful response - see the error message # @raise [Pusher::HTTPError] Error raised inside http client. The original error is wrapped in error.original_error # def channels(params = {}) get('/channels', params) end # Request info for a specific channel # # GET /apps/[id]/channels/[channel_name] # # @param channel_name [String] Channel name (max 200 characters) # @param params [Hash] Hash of parameters for the API - see REST API docs # # @return [Hash] See Pusher API docs # # @raise [Pusher::Error] Unsuccessful response - see the error message # @raise [Pusher::HTTPError] Error raised inside http client. The original error is wrapped in error.original_error # def channel_info(channel_name, params = {}) get("/channels/#{channel_name}", params) end # Trigger an event on one or more channels # # POST /apps/[app_id]/events # # @param channels [String or Array] 1-10 channel names # @param event_name [String] # @param data [Object] Event data to be triggered in javascript. # Objects other than strings will be converted to JSON # @param params [Hash] Additional parameters to send to api, e.g socket_id # # @return [Hash] See Pusher API docs # # @raise [Pusher::Error] Unsuccessful response - see the error message # @raise [Pusher::HTTPError] Error raised inside http client. The original error is wrapped in error.original_error # def trigger(channels, event_name, data, params = {}) post('/events', trigger_params(channels, event_name, data, params)) end # Trigger an event on one or more channels asynchronously. # For parameters see #trigger # def trigger_async(channels, event_name, data, params = {}) post_async('/events', trigger_params(channels, event_name, data, params)) end # @private Construct a net/http http client def sync_http_client @client ||= begin require 'httpclient' HTTPClient.new(@http_proxy).tap do |c| c.connect_timeout = @connect_timeout c.send_timeout = @send_timeout c.receive_timeout = @receive_timeout c.keep_alive_timeout = @keep_alive_timeout end end end # @private Construct an em-http-request http client def em_http_client(uri) begin unless defined?(EventMachine) && EventMachine.reactor_running? raise Error, "In order to use async calling you must be running inside an eventmachine loop" end require 'em-http' unless defined?(EventMachine::HttpRequest) connection_opts = { :connect_timeout => @connect_timeout, :inactivity_timeout => @receive_timeout, } if defined?(@proxy) proxy_opts = { :host => @proxy[:host], :port => @proxy[:port] } if @proxy[:user] proxy_opts[:authorization] = [@proxy[:user], @proxy[:password]] end connection_opts[:proxy] = proxy_opts end EventMachine::HttpRequest.new(uri, connection_opts) end end private def trigger_params(channels, event_name, data, params) channels = Array(channels).map(&:to_s) raise Pusher::Error, "Too many channels (#{channels.length}), max 10" if channels.length > 10 encoded_data = case data when String data else begin MultiJson.encode(data) rescue MultiJson::DecodeError => e Pusher.logger.error("Could not convert #{data.inspect} into JSON") raise e end end return params.merge({ :name => event_name, :channels => channels, :data => encoded_data, }) end def configured? host && scheme && key && secret && app_id end end end
module Pwwka VERSION = '0.17.0' end bump version module Pwwka VERSION = '0.18.0' end
Pod::Spec.new do |s| s.name = "TCUTools" s.version = "1.1.0" s.summary = "Helper classes for various needs coded on Objective-C, iOS." s.homepage = "https://github.com/toreuyar/TCUTools" s.license = { :type => 'MIT' } s.author = { "Töre Çağrı Uyar" => "mail@toreuyar.net" } s.source = { :git => 'https://github.com/toreuyar/TCUTools.git', :tag => s.version.to_s, :submodules => true } s.platform = :ios, '7.0' s.requires_arc = true s.source_files = 'Pod/Classes/**/*' s.resource_bundles = { 'TCUTools' => ['Pod/Assets/*.png'] } s.frameworks = 'UIKit', 'Foundation' s.xcconfig = { 'OTHER_LDFLAGS' => '-lObjC' } end Updated podspec for version `1.1.1`. Pod::Spec.new do |s| s.name = "TCUTools" s.version = "1.1.1" s.summary = "Helper classes for various needs coded on Objective-C, iOS." s.homepage = "https://github.com/toreuyar/TCUTools" s.license = { :type => 'MIT' } s.author = { "Töre Çağrı Uyar" => "mail@toreuyar.net" } s.source = { :git => 'https://github.com/toreuyar/TCUTools.git', :tag => s.version.to_s, :submodules => true } s.platform = :ios, '7.0' s.requires_arc = true s.source_files = 'Pod/Classes/**/*' s.resource_bundles = { 'TCUTools' => ['Pod/Assets/*.png'] } s.frameworks = 'UIKit', 'Foundation' s.xcconfig = { 'OTHER_LDFLAGS' => '-lObjC' } end
module Pxpay # The request object to send to Payment Express class Request require 'pxpay/error' require 'rest_client' require 'nokogiri' require 'builder' attr_accessor :post # Create a new instance of Pxpay::Request # Pxpay::Request.new( id, amount, options = {} ) # Current available options are: # :currency_input, currency for transaction, default is NZD, can be any of Pxpay::Base.currency_types # :reference, a reference field, default is the id. # :email_address, email address of user, default is nil. # :token_billing, boolean value, set to true to enable token billing. # :billing_id, optional billing_id field only used if token_billing is set to true. # :txn_type, can be set to :auth for Auth transaction, defaults to Purchase # :url_success, Success URL, can optionally be set globally via Pxpay::Base.url_success= # :url_failure, Failure URL, can optionally be set globally via Pxpay::Base.url_failure= def initialize( id , price, options = {} ) @post = build_xml( id, price, options ) end # Get the redirect URL from Payment Express def url response = ::RestClient.post("https://sec2.paymentexpress.com/pxpay/pxaccess.aspx", post ) response_text = ::Nokogiri::XML(response) if response_text.at_css("Request").attributes["valid"].value == "1" url = response_text.at_css("URI").inner_html else if Pxpay::Base.pxpay_user_id && Pxpay::Base.pxpay_key raise Pxpay::Error, response_text.at_css("Request").inner_html else raise Pxpay::MissingKey, "Your Pxpay config is not set up properly, run rails generate pxpay:install" end end return URI::extract(url).first.gsub("&amp;", "&") end private # Internal method to build the xml to send to Payment Express def build_xml( id, price, options ) xml = ::Builder::XmlMarkup.new xml.GenerateRequest do xml.PxPayUserId ::Pxpay::Base.pxpay_user_id xml.PxPayKey ::Pxpay::Base.pxpay_key xml.AmountInput sprintf("%.2f", price) xml.TxnId id xml.TxnType options[:txn_type] ? options[:txn_type].to_s.capitalize : "Purchase" xml.CurrencyInput options[:currency_input] || "NZD" xml.MerchantReference options[:reference] || id.to_s xml.UrlSuccess options[:url_success] || ::Pxpay::Base.url_success xml.UrlFail options[:url_failure] || ::Pxpay::Base.url_failure xml.EmailAddress options[:email_address] if options[:email_address] xml.TxnData1 options[:txn_data1] if options[:txn_data1] xml.TxnData2 options[:txn_data2] if options[:txn_data2] xml.TxnData3 options[:txn_data3] if options[:txn_data3] xml.TxnData4 options[:txn_data4] if options[:txn_data4] xml.Opt options[:opt] if options[:opt] xml.EnableAddBillCard 1 if options[:token_billing] xml.BillingId options[:billing_id] if options[:token_billing] end end end end Added documentation for the new options module Pxpay # The request object to send to Payment Express class Request require 'pxpay/error' require 'rest_client' require 'nokogiri' require 'builder' attr_accessor :post # Create a new instance of Pxpay::Request # Pxpay::Request.new( id, amount, options = {} ) # Current available options are: # :currency_input, currency for transaction, default is NZD, can be any of Pxpay::Base.currency_types # :reference, a reference field, default is the id. # :email_address, email address of user, optional. # :token_billing, boolean value, set to true to enable token billing. # :billing_id, optional billing_id field only used if token_billing is set to true. # :txn_type, can be set to :auth for Auth transaction, defaults to Purchase # :url_success, Success URL, can optionally be set globally via Pxpay::Base.url_success= # :url_failure, Failure URL, can optionally be set globally via Pxpay::Base.url_failure= # :txn_data1, Optional data # :txn_data2, Optional data # :txn_data3, Optional data # :txn_data4, Optional data # :opt, Optional data def initialize( id , price, options = {} ) @post = build_xml( id, price, options ) end # Get the redirect URL from Payment Express def url response = ::RestClient.post("https://sec2.paymentexpress.com/pxpay/pxaccess.aspx", post ) response_text = ::Nokogiri::XML(response) if response_text.at_css("Request").attributes["valid"].value == "1" url = response_text.at_css("URI").inner_html else if Pxpay::Base.pxpay_user_id && Pxpay::Base.pxpay_key raise Pxpay::Error, response_text.at_css("Request").inner_html else raise Pxpay::MissingKey, "Your Pxpay config is not set up properly, run rails generate pxpay:install" end end return URI::extract(url).first.gsub("&amp;", "&") end private # Internal method to build the xml to send to Payment Express def build_xml( id, price, options ) xml = ::Builder::XmlMarkup.new xml.GenerateRequest do xml.PxPayUserId ::Pxpay::Base.pxpay_user_id xml.PxPayKey ::Pxpay::Base.pxpay_key xml.AmountInput sprintf("%.2f", price) xml.TxnId id xml.TxnType options[:txn_type] ? options[:txn_type].to_s.capitalize : "Purchase" xml.CurrencyInput options[:currency_input] || "NZD" xml.MerchantReference options[:reference] || id.to_s xml.UrlSuccess options[:url_success] || ::Pxpay::Base.url_success xml.UrlFail options[:url_failure] || ::Pxpay::Base.url_failure xml.EmailAddress options[:email_address] if options[:email_address] xml.TxnData1 options[:txn_data1] if options[:txn_data1] xml.TxnData2 options[:txn_data2] if options[:txn_data2] xml.TxnData3 options[:txn_data3] if options[:txn_data3] xml.TxnData4 options[:txn_data4] if options[:txn_data4] xml.Opt options[:opt] if options[:opt] xml.EnableAddBillCard 1 if options[:token_billing] xml.BillingId options[:billing_id] if options[:token_billing] end end end end
require 'qdisk/exceptions' require 'set' require 'fileutils' require 'pathname' require 'timeout' module QDisk extend self def unmount(options) options[:only] = true unless options.fetch(:multi, false) candidates = mandatory_target_query(options) candidates.each do | disk | disk.partitions.each do |part| if part.mounted? QDisk.unmount_partition(part, options) end end if options.fetch(:detach, false) QDisk.detach_disk(disk, options) end end end def cp(args, options) raise InvalidParameter.new('--multi', 'cp') if options.fetch(:multi, false) if args.length < 1 raise MissingRequiredArgument, 'copy source' end if args.length < 2 raise MissingRequiredArgument, 'destination' end destination = args.pop options[:only] = true candidates = mandatory_target_query(options) disk = candidates.first puts "disk => #{disk.device_name}" if options[:verbose] part = disk.partitions.find do |p| p.mounted? end raise NotFound, 'partition' if part.nil? puts "partition => #{part.device_name}" if options[:verbose] path = part.get('mount paths') raise NotFound, 'partition' unless path args = args.first if args.length == 1 FileUtils.cp(args, Pathname(path) + destination, :verbose => options[:verbose], :noop => options[:no_act]) end def run(args, options = {}) p args if $DEBUG puts args.join(' ') if options.fetch(:verbose, false) return [nil, nil] if options.fetch(:no_act, false) IO.popen(args) do |f| pid = f.pid _, status = Process.wait2(pid) [status, f.read] end end def unmount_partition(partition, options = {}) cmd = %w{udisks --unmount} << partition.device_name status, output = QDisk.run(cmd, :verbose => options[:verbose], :no_act => options[:no_act]) if status.nil? and output.nil? true # no_act elsif status.exited? and status.exitstatus == 0 true elsif output =~ /Unmount failed: Device is not mounted/ true else raise UnmountFailed.new(partition, output) end end def detach_disk(disk, options = {}) cmd = %w{udisks --detach} << disk.device_name status, output = QDisk.run(cmd, :verbose => options[:verbose], :no_act => options[:no_act]) if status.nil? and output.nil? true # no_act elsif status.exited? and status.exitstatus == 0 raise DetachFailed.new(disk, output) if (output and output =~ /^Detach failed: /) true else raise DetachFailed.new(disk, output) end end def wait(args, options) if options[:query].nil? or options[:query].empty? raise MissingRequiredArgument, '--query' end work = lambda do found = nil while true info = QDisk::Info.new found = QDisk.find_partitions(info, {:query => options[:query] }) break if found and !found.empty? sleep(0.2) end found end if options[:timeout] Timeout.timeout(options[:timeout]) {|x| work.call} else work.call end rescue Timeout::Error return false end end Add query variant of wait require 'qdisk/exceptions' require 'set' require 'fileutils' require 'pathname' require 'timeout' module QDisk extend self def unmount(options) options[:only] = true unless options.fetch(:multi, false) candidates = mandatory_target_query(options) candidates.each do | disk | disk.partitions.each do |part| if part.mounted? QDisk.unmount_partition(part, options) end end if options.fetch(:detach, false) QDisk.detach_disk(disk, options) end end end def cp(args, options) raise InvalidParameter.new('--multi', 'cp') if options.fetch(:multi, false) if args.length < 1 raise MissingRequiredArgument, 'copy source' end if args.length < 2 raise MissingRequiredArgument, 'destination' end destination = args.pop options[:only] = true candidates = mandatory_target_query(options) disk = candidates.first puts "disk => #{disk.device_name}" if options[:verbose] part = disk.partitions.find do |p| p.mounted? end raise NotFound, 'partition' if part.nil? puts "partition => #{part.device_name}" if options[:verbose] path = part.get('mount paths') raise NotFound, 'partition' unless path args = args.first if args.length == 1 FileUtils.cp(args, Pathname(path) + destination, :verbose => options[:verbose], :noop => options[:no_act]) end def run(args, options = {}) p args if $DEBUG puts args.join(' ') if options.fetch(:verbose, false) return [nil, nil] if options.fetch(:no_act, false) IO.popen(args) do |f| pid = f.pid _, status = Process.wait2(pid) [status, f.read] end end def unmount_partition(partition, options = {}) cmd = %w{udisks --unmount} << partition.device_name status, output = QDisk.run(cmd, :verbose => options[:verbose], :no_act => options[:no_act]) if status.nil? and output.nil? true # no_act elsif status.exited? and status.exitstatus == 0 true elsif output =~ /Unmount failed: Device is not mounted/ true else raise UnmountFailed.new(partition, output) end end def detach_disk(disk, options = {}) cmd = %w{udisks --detach} << disk.device_name status, output = QDisk.run(cmd, :verbose => options[:verbose], :no_act => options[:no_act]) if status.nil? and output.nil? true # no_act elsif status.exited? and status.exitstatus == 0 raise DetachFailed.new(disk, output) if (output and output =~ /^Detach failed: /) true else raise DetachFailed.new(disk, output) end end def query(args, options) raise InvalidParameter.new('--multi', 'timeout') unless options.fetch(:timeout, nil).nil? query_(args, options, false) end def wait(args, options) query_(args, options, true) end private def query_(args, options, wait) if options[:query].nil? or options[:query].empty? raise MissingRequiredArgument, '--query' end work = lambda do found = nil while true info = QDisk::Info.new found = QDisk.find_partitions(info, {:query => options[:query] }) break if !wait break if found and !found.empty? sleep(0.2) end found end if options[:timeout] Timeout.timeout(options[:timeout]) {|x| work.call} else work.call end rescue Timeout::Error return false end end
module Raemon class Master < Struct.new(:timeout, :worker_processes, :worker_klass, :detach, :logger, :pid_file, :master_pid) #attr_reader :worker_pids # The basic max request size we'll try to read. CHUNK_SIZE=(16 * 1024) # This hash maps PIDs to Workers WORKERS = {} # We use SELF_PIPE differently in the master and worker processes: # # * The master process never closes or reinitializes this once # initialized. Signal handlers in the master process will write to # it to wake up the master from IO.select in exactly the same manner # djb describes in http://cr.yp.to/docs/selfpipe.html # # * The workers immediately close the pipe they inherit from the # master and replace it with a new pipe after forking. This new # pipe is also used to wakeup from IO.select from inside (worker) # signal handlers. However, workers *close* the pipe descriptors in # the signal handlers to raise EBADF in IO.select instead of writing # like we do in the master. We cannot easily use the reader set for # IO.select because LISTENERS is already that set, and it's extra # work (and cycles) to distinguish the pipe FD from the reader set # once IO.select returns. So we're lazy and just close the pipe when # a (rare) signal arrives in the worker and reinitialize the pipe later. SELF_PIPE = [] # signal queue used for self-piping SIG_QUEUE = [] def self.startup(num_workers, worker_klass, opts={}) master = new(opts) master.startup(num_workers, worker_klass) end def self.shutdown(pid_file) pid = File.open(pid_file, 'r') {|f| f.gets }.to_i Process.kill('TERM', pid) if pid > 0 #File.unlink(pid_file) rescue Errno::ESRCH end def initialize(opts={}) self.detach = opts[:detach] || false self.logger = opts[:logger] || Logger.new(STDOUT) self.pid_file = opts[:pid_file] self.timeout = 60 # @worker_pids = [] daemonize if detach end def startup(num_workers, worker_klass) self.worker_processes = num_workers self.worker_klass = worker_klass logger.info "=> starting Raemon::Master with #{worker_processes} worker(s)" # Check if the worker implements our protocol if !worker_klass.include?(Raemon::Worker) logger.error "** invalid Raemon worker" exit end self.master_pid = $$ # Spawn workers maintain_worker_count reap_all_workers self end # monitors children and receives signals forever # (or until a termination signal is sent). This handles signals # one-at-a-time time and we'll happily drop signals in case somebody # is signalling us too often. def join # this pipe is used to wake us up from select(2) in #join when signals # are trapped. See trap_deferred init_self_pipe! respawn = true last_check = Time.now QUEUE_SIGS.each { |sig| trap_deferred(sig) } trap(:CHLD) { |sig_nr| awaken_master } proc_name 'master' logger.info "=> master process ready" # test_exec.rb relies on this message begin loop do reap_all_workers case SIG_QUEUE.shift when nil # avoid murdering workers after our master process (or the # machine) comes out of suspend/hibernation if (last_check + timeout) >= (last_check = Time.now) murder_lazy_workers end maintain_worker_count if respawn master_sleep when :QUIT # graceful shutdown break when :TERM, :INT # immediate shutdown stop(false) break when :WINCH if Process.ppid == 1 || Process.getpgrp != $$ respawn = false logger.info "gracefully stopping all workers" kill_each_worker(:QUIT) else logger.info "SIGWINCH ignored because we're not daemonized" end end end rescue Errno::EINTR retry rescue => e logger.error "Unhandled master loop exception #{e.inspect}." logger.error e.backtrace.join("\n") retry end stop # gracefully shutdown all workers on our way out logger.info "master complete" unlink_pid_safe(pid_file) if pid_file end # Terminates all workers, but does not exit master process def stop(graceful = true) #self.listeners = [] timeout = 30 limit = Time.now + timeout until WORKERS.empty? || Time.now > limit kill_each_worker(graceful ? :QUIT : :TERM) sleep(0.1) reap_all_workers end kill_each_worker(:KILL) end def daemonize exit if Process.fork Process.setsid Dir.chdir '/' File.umask 0000 STDIN.reopen '/dev/null' STDOUT.reopen '/dev/null', 'a' STDERR.reopen '/dev/null', 'a' File.open(pid_file, 'w') { |f| f.puts(Process.pid) } if pid_file end private # list of signals we care about and trap in master. QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP, :TTIN, :TTOU ] # defer a signal for later processing in #join (master process) def trap_deferred(signal) trap(signal) do |sig_nr| if SIG_QUEUE.size < 5 SIG_QUEUE << signal awaken_master else logger.error "ignoring SIG#{signal}, queue=#{SIG_QUEUE.inspect}" end end end # wait for a signal hander to wake us up and then consume the pipe # Wake up every second anyways to run murder_lazy_workers def master_sleep begin ready = IO.select([SELF_PIPE.first], nil, nil, 1) or return ready.first && ready.first.first or return loop { SELF_PIPE.first.read_nonblock(CHUNK_SIZE) } rescue Errno::EAGAIN, Errno::EINTR end end def awaken_master begin SELF_PIPE.last.write_nonblock('.') # wakeup master process from select rescue Errno::EAGAIN, Errno::EINTR # pipe is full, master should wake up anyways retry end end # reaps all unreaped workers def reap_all_workers begin loop do wpid, status = Process.waitpid2(-1, Process::WNOHANG) wpid or break worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil logger.info "=> reaped #{status.inspect} " \ "worker=#{worker.nr rescue 'unknown'}" end rescue Errno::ECHILD end end # forcibly terminate all workers that haven't checked in in timeout # seconds. The timeout is implemented using an unlinked File # shared between the parent process and each worker. The worker # runs File#chmod to modify the ctime of the File. If the ctime # is stale for >timeout seconds, then we'll kill the corresponding # worker. def murder_lazy_workers WORKERS.dup.each_pair do |wpid, worker| stat = worker.tmp.stat # skip workers that disable fchmod or have never fchmod-ed stat.mode == 0100600 and next (diff = (Time.now - stat.ctime)) <= timeout and next logger.error "=> worker=#{worker.nr} PID:#{wpid} timeout " \ "(#{diff}s > #{timeout}s), killing" kill_worker(:KILL, wpid) # take no prisoners for timeout violations end end def spawn_missing_workers (0...worker_processes).each do |worker_nr| WORKERS.values.include?(worker_nr) and next worker = worker_klass.new(self, worker_nr, Raemon::Util.tmpio) #before_fork.call(self, worker) WORKERS[fork { worker_loop(worker) }] = worker end end def maintain_worker_count (off = WORKERS.size - worker_processes) == 0 and return off < 0 and return spawn_missing_workers WORKERS.dup.each_pair { |wpid,w| w.nr >= worker_processes and kill_worker(:QUIT, wpid) rescue nil } end # gets rid of stuff the worker has no business keeping track of # to free some resources and drops all sig handlers. def init_worker_process(worker) QUEUE_SIGS.each { |sig| trap(sig, nil) } trap(:CHLD, 'DEFAULT') SIG_QUEUE.clear proc_name "worker[#{worker.nr}]" init_self_pipe! WORKERS.values.each { |other| other.tmp.close rescue nil } WORKERS.clear #LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) } worker.tmp.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) #after_fork.call(self, worker) # can drop perms self.timeout /= 2.0 # halve it for select() end # runs inside each forked worker, this sits around and waits # for connections and doesn't die until the parent dies (or is # given a INT, QUIT, or TERM signal) def worker_loop(worker) ppid = master_pid init_worker_process(worker) alive = worker.tmp # tmp is our lifeline to the master process #ready = LISTENERS # closing anything we IO.select on will raise EBADF trap(:QUIT) { alive = nil } [:TERM, :INT].each { |sig| trap(sig) { worker.shutdown } } # instant shutdown logger.info "=> worker=#{worker.nr} ready" m = 0 begin # we're a goner in timeout seconds anyways if alive.chmod # breaks, so don't trap the exception. Using fchmod() since # futimes() is not available in base Ruby and I very strongly # prefer temporary files to be unlinked for security, # performance and reliability reasons, so utime is out. No-op # changes with chmod doesn't update ctime on all filesystems; so # we change our counter each and every time (after process_client # and before IO.select). alive.chmod(m = 0 == m ? 1 : 0) worker.execute ppid == Process.ppid or return alive.chmod(m = 0 == m ? 1 : 0) begin # timeout used so we can detect parent death: ret = IO.select(SELF_PIPE, nil, nil, timeout) or redo ready = ret.first # rescue Errno::EINTR rescue Errno::EBADF return end rescue => e if alive logger.error "Unhandled listen loop exception #{e.inspect}." logger.error e.backtrace.join("\n") end end while alive end # delivers a signal to a worker and fails gracefully if the worker # is no longer running. def kill_worker(signal, wpid) begin Process.kill(signal, wpid) rescue Errno::ESRCH worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil end end # delivers a signal to each worker def kill_each_worker(signal) WORKERS.keys.each { |wpid| kill_worker(signal, wpid) } end # unlinks a PID file at given +path+ if it contains the current PID # still potentially racy without locking the directory (which is # non-portable and may interact badly with other programs), but the # window for hitting the race condition is small def unlink_pid_safe(path) (File.read(path).to_i == $$ and File.unlink(path)) rescue nil end def proc_name(tag) $0 = "raemon #{worker_klass.name} #{tag}" end def init_self_pipe! SELF_PIPE.each { |io| io.close rescue nil } SELF_PIPE.replace(IO.pipe) SELF_PIPE.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) } end end end remove IO.select from worker loop due to this may not be suited for our case module Raemon class Master < Struct.new(:timeout, :worker_processes, :worker_klass, :detach, :logger, :pid_file, :master_pid) #attr_reader :worker_pids # The basic max request size we'll try to read. CHUNK_SIZE=(16 * 1024) # This hash maps PIDs to Workers WORKERS = {} # We use SELF_PIPE differently in the master and worker processes: # # * The master process never closes or reinitializes this once # initialized. Signal handlers in the master process will write to # it to wake up the master from IO.select in exactly the same manner # djb describes in http://cr.yp.to/docs/selfpipe.html # # * The workers immediately close the pipe they inherit from the # master and replace it with a new pipe after forking. This new # pipe is also used to wakeup from IO.select from inside (worker) # signal handlers. However, workers *close* the pipe descriptors in # the signal handlers to raise EBADF in IO.select instead of writing # like we do in the master. We cannot easily use the reader set for # IO.select because LISTENERS is already that set, and it's extra # work (and cycles) to distinguish the pipe FD from the reader set # once IO.select returns. So we're lazy and just close the pipe when # a (rare) signal arrives in the worker and reinitialize the pipe later. SELF_PIPE = [] # signal queue used for self-piping SIG_QUEUE = [] def self.startup(num_workers, worker_klass, opts={}) master = new(opts) master.startup(num_workers, worker_klass) end def self.shutdown(pid_file) pid = File.open(pid_file, 'r') {|f| f.gets }.to_i Process.kill('TERM', pid) if pid > 0 #File.unlink(pid_file) rescue Errno::ESRCH end def initialize(opts={}) self.detach = opts[:detach] || false self.logger = opts[:logger] || Logger.new(STDOUT) self.pid_file = opts[:pid_file] self.timeout = opts[:timeout] || 60 # 1 min # @worker_pids = [] daemonize if detach end def startup(num_workers, worker_klass) self.worker_processes = num_workers self.worker_klass = worker_klass logger.info "=> starting Raemon::Master with #{worker_processes} worker(s)" # Check if the worker implements our protocol if !worker_klass.include?(Raemon::Worker) logger.error "** invalid Raemon worker" exit end self.master_pid = $$ # Spawn workers maintain_worker_count reap_all_workers self end # monitors children and receives signals forever # (or until a termination signal is sent). This handles signals # one-at-a-time time and we'll happily drop signals in case somebody # is signalling us too often. def join # this pipe is used to wake us up from select(2) in #join when signals # are trapped. See trap_deferred init_self_pipe! respawn = true last_check = Time.now QUEUE_SIGS.each { |sig| trap_deferred(sig) } trap(:CHLD) { |sig_nr| awaken_master } proc_name 'master' logger.info "=> master process ready" # test_exec.rb relies on this message begin loop do reap_all_workers case SIG_QUEUE.shift when nil # avoid murdering workers after our master process (or the # machine) comes out of suspend/hibernation if (last_check + timeout) >= (last_check = Time.now) murder_lazy_workers end maintain_worker_count if respawn master_sleep when :QUIT # graceful shutdown break when :TERM, :INT # immediate shutdown stop(false) break when :WINCH if Process.ppid == 1 || Process.getpgrp != $$ respawn = false logger.info "gracefully stopping all workers" kill_each_worker(:QUIT) else logger.info "SIGWINCH ignored because we're not daemonized" end end end rescue Errno::EINTR retry rescue => e logger.error "Unhandled master loop exception #{e.inspect}." logger.error e.backtrace.join("\n") retry end stop # gracefully shutdown all workers on our way out logger.info "master complete" unlink_pid_safe(pid_file) if pid_file end # Terminates all workers, but does not exit master process def stop(graceful = true) #self.listeners = [] timeout = 30 limit = Time.now + timeout until WORKERS.empty? || Time.now > limit kill_each_worker(graceful ? :QUIT : :TERM) sleep(0.1) reap_all_workers end kill_each_worker(:KILL) end def daemonize exit if Process.fork Process.setsid Dir.chdir '/' File.umask 0000 STDIN.reopen '/dev/null' STDOUT.reopen '/dev/null', 'a' STDERR.reopen '/dev/null', 'a' File.open(pid_file, 'w') { |f| f.puts(Process.pid) } if pid_file end private # list of signals we care about and trap in master. QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP, :TTIN, :TTOU ] # defer a signal for later processing in #join (master process) def trap_deferred(signal) trap(signal) do |sig_nr| if SIG_QUEUE.size < 5 SIG_QUEUE << signal awaken_master else logger.error "ignoring SIG#{signal}, queue=#{SIG_QUEUE.inspect}" end end end # wait for a signal hander to wake us up and then consume the pipe # Wake up every second anyways to run murder_lazy_workers def master_sleep begin ready = IO.select([SELF_PIPE.first], nil, nil, 1) or return ready.first && ready.first.first or return loop { SELF_PIPE.first.read_nonblock(CHUNK_SIZE) } rescue Errno::EAGAIN, Errno::EINTR end end def awaken_master begin SELF_PIPE.last.write_nonblock('.') # wakeup master process from select rescue Errno::EAGAIN, Errno::EINTR # pipe is full, master should wake up anyways retry end end # reaps all unreaped workers def reap_all_workers begin loop do wpid, status = Process.waitpid2(-1, Process::WNOHANG) wpid or break worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil logger.info "=> reaped #{status.inspect} " \ "worker=#{worker.nr rescue 'unknown'}" end rescue Errno::ECHILD end end # forcibly terminate all workers that haven't checked in in timeout # seconds. The timeout is implemented using an unlinked File # shared between the parent process and each worker. The worker # runs File#chmod to modify the ctime of the File. If the ctime # is stale for >timeout seconds, then we'll kill the corresponding # worker. def murder_lazy_workers WORKERS.dup.each_pair do |wpid, worker| stat = worker.tmp.stat # skip workers that disable fchmod or have never fchmod-ed stat.mode == 0100600 and next (diff = (Time.now - stat.ctime)) <= timeout and next logger.error "=> worker=#{worker.nr} PID:#{wpid} timeout " \ "(#{diff}s > #{timeout}s), killing" kill_worker(:KILL, wpid) # take no prisoners for timeout violations end end def spawn_missing_workers (0...worker_processes).each do |worker_nr| WORKERS.values.include?(worker_nr) and next worker = worker_klass.new(self, worker_nr, Raemon::Util.tmpio) #before_fork.call(self, worker) WORKERS[fork { worker_loop(worker) }] = worker end end def maintain_worker_count (off = WORKERS.size - worker_processes) == 0 and return off < 0 and return spawn_missing_workers WORKERS.dup.each_pair { |wpid,w| w.nr >= worker_processes and kill_worker(:QUIT, wpid) rescue nil } end # gets rid of stuff the worker has no business keeping track of # to free some resources and drops all sig handlers. def init_worker_process(worker) QUEUE_SIGS.each { |sig| trap(sig, nil) } trap(:CHLD, 'DEFAULT') SIG_QUEUE.clear proc_name "worker[#{worker.nr}]" init_self_pipe! WORKERS.values.each { |other| other.tmp.close rescue nil } WORKERS.clear #LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) } worker.tmp.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) #after_fork.call(self, worker) # can drop perms self.timeout /= 2.0 # halve it for select() end # runs inside each forked worker, this sits around and waits # for connections and doesn't die until the parent dies (or is # given a INT, QUIT, or TERM signal) def worker_loop(worker) ppid = master_pid init_worker_process(worker) alive = worker.tmp # tmp is our lifeline to the master process #ready = LISTENERS # closing anything we IO.select on will raise EBADF trap(:QUIT) { alive = nil } [:TERM, :INT].each { |sig| trap(sig) { worker.shutdown } } # instant shutdown logger.info "=> worker=#{worker.nr} ready" m = 0 begin # we're a goner in timeout seconds anyways if alive.chmod # breaks, so don't trap the exception. Using fchmod() since # futimes() is not available in base Ruby and I very strongly # prefer temporary files to be unlinked for security, # performance and reliability reasons, so utime is out. No-op # changes with chmod doesn't update ctime on all filesystems; so # we change our counter each and every time (after process_client # and before IO.select). alive.chmod(m = 0 == m ? 1 : 0) worker.execute ppid == Process.ppid or return alive.chmod(m = 0 == m ? 1 : 0) rescue => e if alive logger.error "Unhandled listen loop exception #{e.inspect}." logger.error e.backtrace.join("\n") end end while alive end # delivers a signal to a worker and fails gracefully if the worker # is no longer running. def kill_worker(signal, wpid) begin Process.kill(signal, wpid) rescue Errno::ESRCH worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil end end # delivers a signal to each worker def kill_each_worker(signal) WORKERS.keys.each { |wpid| kill_worker(signal, wpid) } end # unlinks a PID file at given +path+ if it contains the current PID # still potentially racy without locking the directory (which is # non-portable and may interact badly with other programs), but the # window for hitting the race condition is small def unlink_pid_safe(path) (File.read(path).to_i == $$ and File.unlink(path)) rescue nil end def proc_name(tag) $0 = "raemon #{worker_klass.name} #{tag}" end def init_self_pipe! SELF_PIPE.each { |io| io.close rescue nil } SELF_PIPE.replace(IO.pipe) SELF_PIPE.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) } end end end
# encoding: utf-8 module Rails module Mongoid extend self # Create indexes for each model given the provided globs and the class is # not embedded. # # @example Create all the indexes. # Rails::Mongoid.create_indexes # # @return [ Array<Class> ] The indexed models. # # @since 2.1.0 def create_indexes ::Mongoid.models.each do |model| next if model.index_options.empty? unless model.embedded? model.create_indexes logger.info("MONGOID: Created indexes on #{model}:") model.index_options.each_pair do |index, options| logger.info("MONGOID: Index: #{index}, Options: #{options}") end model else logger.info("MONGOID: Index ignored on: #{model}, please define in the root model.") nil end end.compact end # Remove indexes for each model given the provided globs and the class is # not embedded. # # @example Remove all the indexes. # Rails::Mongoid.create_indexes # # @return [ Array<Class> ] The un-indexed models. # def remove_indexes ::Mongoid.models.each do |model| next if model.embedded? indexes = model.collection.indexes.map{ |doc| doc["name"] } indexes.delete_one("_id_") model.remove_indexes logger.info("MONGOID: Removing indexes on: #{model} for: #{indexes.join(', ')}.") model end.compact end # Use the application configuration to get every model and require it, so # that indexing and inheritance work in both development and production # with the same results. # # @example Load all the application models. # Rails::Mongoid.load_models(app) # # @param [ Application ] app The rails application. def load_models(app) app.config.paths["app/models"].each do |path| preload = ::Mongoid.preload_models if preload.resizable? files = preload.map { |model| "#{path}/#{model}.rb" } else files = Dir.glob("#{path}/**/*.rb") end files.sort.each do |file| load_model(file.gsub("#{path}/" , "").gsub(".rb", "")) end end end # Conditionally calls `Rails::Mongoid.load_models(app)` if the # `::Mongoid.preload_models` is `true`. # # @param [ Application ] app The rails application. def preload_models(app) load_models(app) if ::Mongoid.preload_models end private # I don't want to mock out kernel for unit testing purposes, so added this # method as a convenience. # # @example Load the model. # Mongoid.load_model("/mongoid/behaviour") # # @param [ String ] file The base filename. # # @since 2.0.0.rc.3 def load_model(file) begin require_dependency(file) rescue Exception => e Logger.new($stdout).warn(e.message) end end # Given the provided file name, determine the model and return the class. # # @example Determine the model from the file. # Rails::Mongoid.determine_model("app/models/person.rb") # # @param [ String ] file The filename. # # @return [ Class ] The model. # # @since 2.1.0 def determine_model(file, logger) return nil unless file =~ /app\/models\/(.*).rb$/ return nil unless logger model_path = $1.split('/') begin parts = model_path.map { |path| path.camelize } name = parts.join("::") klass = name.constantize rescue NameError, LoadError logger.info("MONGOID: Attempted to constantize #{name}, trying without namespacing.") klass = parts.last.constantize rescue nil end klass if klass && klass.ancestors.include?(::Mongoid::Document) end def logger @logger ||= Logger.new($stdout) end end end fixing small doc typo # encoding: utf-8 module Rails module Mongoid extend self # Create indexes for each model given the provided globs and the class is # not embedded. # # @example Create all the indexes. # Rails::Mongoid.create_indexes # # @return [ Array<Class> ] The indexed models. # # @since 2.1.0 def create_indexes ::Mongoid.models.each do |model| next if model.index_options.empty? unless model.embedded? model.create_indexes logger.info("MONGOID: Created indexes on #{model}:") model.index_options.each_pair do |index, options| logger.info("MONGOID: Index: #{index}, Options: #{options}") end model else logger.info("MONGOID: Index ignored on: #{model}, please define in the root model.") nil end end.compact end # Remove indexes for each model given the provided globs and the class is # not embedded. # # @example Remove all the indexes. # Rails::Mongoid.remove_indexes # # @return [ Array<Class> ] The un-indexed models. # def remove_indexes ::Mongoid.models.each do |model| next if model.embedded? indexes = model.collection.indexes.map{ |doc| doc["name"] } indexes.delete_one("_id_") model.remove_indexes logger.info("MONGOID: Removing indexes on: #{model} for: #{indexes.join(', ')}.") model end.compact end # Use the application configuration to get every model and require it, so # that indexing and inheritance work in both development and production # with the same results. # # @example Load all the application models. # Rails::Mongoid.load_models(app) # # @param [ Application ] app The rails application. def load_models(app) app.config.paths["app/models"].each do |path| preload = ::Mongoid.preload_models if preload.resizable? files = preload.map { |model| "#{path}/#{model}.rb" } else files = Dir.glob("#{path}/**/*.rb") end files.sort.each do |file| load_model(file.gsub("#{path}/" , "").gsub(".rb", "")) end end end # Conditionally calls `Rails::Mongoid.load_models(app)` if the # `::Mongoid.preload_models` is `true`. # # @param [ Application ] app The rails application. def preload_models(app) load_models(app) if ::Mongoid.preload_models end private # I don't want to mock out kernel for unit testing purposes, so added this # method as a convenience. # # @example Load the model. # Mongoid.load_model("/mongoid/behaviour") # # @param [ String ] file The base filename. # # @since 2.0.0.rc.3 def load_model(file) begin require_dependency(file) rescue Exception => e Logger.new($stdout).warn(e.message) end end # Given the provided file name, determine the model and return the class. # # @example Determine the model from the file. # Rails::Mongoid.determine_model("app/models/person.rb") # # @param [ String ] file The filename. # # @return [ Class ] The model. # # @since 2.1.0 def determine_model(file, logger) return nil unless file =~ /app\/models\/(.*).rb$/ return nil unless logger model_path = $1.split('/') begin parts = model_path.map { |path| path.camelize } name = parts.join("::") klass = name.constantize rescue NameError, LoadError logger.info("MONGOID: Attempted to constantize #{name}, trying without namespacing.") klass = parts.last.constantize rescue nil end klass if klass && klass.ancestors.include?(::Mongoid::Document) end def logger @logger ||= Logger.new($stdout) end end end
require_dependency 'open311' module RailsOpen311 CONFIG_PATH = "#{Rails.root}/config/open311.yml" CACHE_KEY = 'open311_services' def self.load_config YAML.load_file(CONFIG_PATH) end def self.load_all_services! api_wrapper = self.api_wrapper services = api_wrapper.services_with_attrs Rails.cache.write CACHE_KEY, services end def self.all_services Rails.cache.read(CACHE_KEY) || load_all_services! end def self.filtered_services api_config = load_config grouped_services = Hash[all_services.map { |s| [s.code, s] }] return api_config['services'].map { |sc| grouped_services[sc] } end def self.api_wrapper api_config = load_config url = api_config['url'] jurisdiction_id = api_config['jurisdiction_id'] api_key = api_config['apikey'] wrapper = Open311::ApiWrapper.from_url(url, api_key, jurisdiction_id) wrapper.logger = Rails.logger wrapper end end Allow to embed erb in open311.yml require_dependency 'open311' module RailsOpen311 CONFIG_PATH = "#{Rails.root}/config/open311.yml" CACHE_KEY = 'open311_services' def self.load_config YAML.load(ERB.new(IO.read(CONFIG_PATH)).result) end def self.load_all_services! api_wrapper = self.api_wrapper services = api_wrapper.services_with_attrs Rails.cache.write CACHE_KEY, services end def self.all_services Rails.cache.read(CACHE_KEY) || load_all_services! end def self.filtered_services api_config = load_config grouped_services = Hash[all_services.map { |s| [s.code, s] }] return api_config['services'].map { |sc| grouped_services[sc] } end def self.api_wrapper api_config = load_config url = api_config['url'] jurisdiction_id = api_config['jurisdiction_id'] api_key = api_config['apikey'] wrapper = Open311::ApiWrapper.from_url(url, api_key, jurisdiction_id) wrapper.logger = Rails.logger wrapper end end
class RailsDebugBar def self.filter(controller) content_type = controller.response.content_type return unless content_type =~ /html/ body = controller.response.body insertpoint = (body =~ /<\/body>/) if insertpoint.nil? insertpoint = -1 end bar = "DEBUG" controller.response.body = body.insert(insertpoint, bar) end end fancied up, rails_version display class RailsDebugBar def self.filter(controller) content_type = controller.response.content_type return unless content_type =~ /html/ body = controller.response.body insertpoint = (body =~ /<\/body>/) if insertpoint.nil? insertpoint = -1 end parts = ["DEBUG", rails_version ] controller.response.body = body.insert(insertpoint, decorate_parts(parts)) end def self.rails_version "Rails: "+Rails::VERSION::STRING end def self.decorate_parts(parts) css_for_insertion = <<-EOF <style> ul#rails_debug_bar { list-style-type: none; margin-bottom: 0; margin-top: 1em; padding-left: 0 } ul#rails_debug_bar li { display: inline; padding: 0.2em; border: 1px solid black; background-color: #fda; color: black; } </style> EOF parts_for_insertion = parts.map{|s| "<li>#{s}</li>"} html_for_insertion = "<ul id=\"rails_debug_bar\">#{parts_for_insertion}</ul>" return css_for_insertion + html_for_insertion end end
require 'rbbt/util/resource' require 'rbbt/util/misc' require 'rbbt/util/open' require 'rbbt/util/tc_hash' require 'rbbt/util/tmpfile' require 'rbbt/util/log' require 'rbbt/util/persistence' require 'digest' require 'fileutils' require 'rbbt/util/tsv/parse' require 'rbbt/util/tsv/accessor' require 'rbbt/util/tsv/manipulate' require 'rbbt/util/tsv/index' require 'rbbt/util/tsv/attach' require 'rbbt/util/tsv/resource' class TSV ESCAPES = { "\n" => "[[NL]]", "\t" => "[[TAB]]", } def self.escape(text) ESCAPES.each do |char,replacement| text = text.gsub(char, replacement) end text end def self.unescape(text) ESCAPES.each do |char,replacement| text = text.gsub(replacement, char) end text end def self.headers(file, options = {}) ## Remove options from filename if String === file and file =~/(.*?)#(.*)/ and File.exists? $1 options = Misc.add_defaults options, Misc.string2hash($2) file = $1 end fields = case when Open.can_open?(file) Open.open(file, :grep => options[:grep]) do |f| TSV.parse_header(f, options[:sep], options[:header_hash]).values_at(0, 1).flatten end when File === file file = Open.grep(file, options[:grep]) if options[:grep] TSV.parse_header(file, options[:sep], options[:header_hash]).values_at(0, 1).flatten else raise "File #{file.inspect} not found" end if fields.compact.empty? nil else fields end end def initialize(file = {}, type = nil, options = {}) # Process Options if Hash === type options = type type = nil end ## Remove options from filename if String === file and file =~/(.*?)#(.*)/ and File.exists? $1 options = Misc.add_defaults options, Misc.string2hash($2) file = $1 end options = Misc.add_defaults options, :persistence => false, :type => type, :in_situ_persistence => true # Extract Filename file, extra = file if Array === file and file.length == 2 and Hash === file.last @filename = Misc.process_options options, :filename @filename ||= case when Resource::Path === file file when (String === file and File.exists? file) File.expand_path file when String === file file when File === file File.expand_path file.path when TSV === file File.expand_path file.filename when (Persistence::TSV === file and file.filename) File.expand_path file.filename else file.class.to_s end # Process With Persistence # Use filename to identify the persistence # Several inputs supported # Filename or File: Parsed # Hash: Encapsulated, empty info # TSV: Duplicate case when block_given? @data, extra = Persistence.persist(file, :TSV, :tsv_extra, options.merge(:force_array => true)) do |file, options, filename| yield file, options, filename end extra.each do |key, values| self.send("#{ key }=".to_sym, values) if self.respond_to? "#{ key }=".to_sym end if not extra.nil? else case when Array === file @data = Hash[file.collect{|v| [v,[]] }] @data.key_field = key_field if key_field @data.fields = fields if fields when Hash === file @data = file @data.key_field = key_field if key_field @data.fields = fields if fields when TSV === file @data = file.data @data.key_field = key_field if key_field @data.fields = fields if fields when Persistence::TSV === file @data = file %w(case_insensitive namespace identifiers datadir fields key_field type filename cast).each do |key| if @data.respond_to?(key.to_sym) and self.respond_to?("#{key}=".to_sym) self.send "#{key}=".to_sym, @data.send(key.to_sym) end end else in_situ_persistence = Misc.process_options(options, :in_situ_persistence) @data, extra = Persistence.persist(file, :TSV, :tsv_extra, options) do |file, options, filename, persistence_file| data, extra = nil if in_situ_persistence and persistence_file options.merge! :persistence_data => Persistence::TSV.get(persistence_file, true, :double) end begin case ## Parse source when Resource::Path === file #(String === file and file.respond_to? :open) data, extra = TSV.parse(file.open(:grep => options[:grep]) , options) extra[:namespace] ||= file.namespace extra[:datadir] ||= file.datadir when StringIO === file data, extra = TSV.parse(file, options) when Open.can_open?(file) Open.open(file, :grep => options[:grep]) do |f| data, extra = TSV.parse(f, options) end when File === file path = file.path file = Open.grep(file, options[:grep]) if options[:grep] data, extra = TSV.parse(file, options) when IO === file file = Open.grep(file, options[:grep]) if options[:grep] data, extra = TSV.parse(file, options) when block_given? data else raise "Unknown input in TSV.new #{file.inspect}" end extra[:filename] = filename rescue Exception FileUtils.rm persistence_file if persistence_file and File.exists?(persistence_file) raise $! end if Persistence::TSV === data %w(case_insensitive namespace identifiers datadir fields key_field type filename cast).each do |key| if extra.include? key.to_sym if data.respond_to? "#{key}=".to_sym data.send("#{key}=".to_sym, extra[key.to_sym]) end end end data.read end [data, extra] end end end if not extra.nil? %w(case_insensitive namespace identifiers datadir fields key_field type filename cast).each do |key| if extra.include? key.to_sym self.send("#{key}=".to_sym, extra[key.to_sym]) #if @data.respond_to? "#{key}=".to_sym # @data.send("#{key}=".to_sym, extra[key.to_sym]) #end end end end end def write @data.write if @data.respond_to? :write end def read @data.read if @data.respond_to? :read end def write? @data.write? if @data.respond_to? :write end end Fixed setting fields and key_field in Array, Hash and TSV input require 'rbbt/util/resource' require 'rbbt/util/misc' require 'rbbt/util/open' require 'rbbt/util/tc_hash' require 'rbbt/util/tmpfile' require 'rbbt/util/log' require 'rbbt/util/persistence' require 'digest' require 'fileutils' require 'rbbt/util/tsv/parse' require 'rbbt/util/tsv/accessor' require 'rbbt/util/tsv/manipulate' require 'rbbt/util/tsv/index' require 'rbbt/util/tsv/attach' require 'rbbt/util/tsv/resource' class TSV ESCAPES = { "\n" => "[[NL]]", "\t" => "[[TAB]]", } def self.escape(text) ESCAPES.each do |char,replacement| text = text.gsub(char, replacement) end text end def self.unescape(text) ESCAPES.each do |char,replacement| text = text.gsub(replacement, char) end text end def self.headers(file, options = {}) ## Remove options from filename if String === file and file =~/(.*?)#(.*)/ and File.exists? $1 options = Misc.add_defaults options, Misc.string2hash($2) file = $1 end fields = case when Open.can_open?(file) Open.open(file, :grep => options[:grep]) do |f| TSV.parse_header(f, options[:sep], options[:header_hash]).values_at(0, 1).flatten end when File === file file = Open.grep(file, options[:grep]) if options[:grep] TSV.parse_header(file, options[:sep], options[:header_hash]).values_at(0, 1).flatten else raise "File #{file.inspect} not found" end if fields.compact.empty? nil else fields end end def initialize(file = {}, type = nil, options = {}) # Process Options if Hash === type options = type type = nil end ## Remove options from filename if String === file and file =~/(.*?)#(.*)/ and File.exists? $1 options = Misc.add_defaults options, Misc.string2hash($2) file = $1 end options = Misc.add_defaults options, :persistence => false, :type => type, :in_situ_persistence => true # Extract Filename file, extra = file if Array === file and file.length == 2 and Hash === file.last @filename = Misc.process_options options, :filename @filename ||= case when Resource::Path === file file when (String === file and File.exists? file) File.expand_path file when String === file file when File === file File.expand_path file.path when TSV === file File.expand_path file.filename when (Persistence::TSV === file and file.filename) File.expand_path file.filename else file.class.to_s end # Process With Persistence # Use filename to identify the persistence # Several inputs supported # Filename or File: Parsed # Hash: Encapsulated, empty info # TSV: Duplicate case when block_given? @data, extra = Persistence.persist(file, :TSV, :tsv_extra, options.merge(:force_array => true)) do |file, options, filename| yield file, options, filename end extra.each do |key, values| self.send("#{ key }=".to_sym, values) if self.respond_to? "#{ key }=".to_sym end if not extra.nil? else case when Array === file @data = Hash[file.collect{|v| [v,[]] }] self.key_field = options[:key_field] self.fields = options[:fields] when Hash === file @data = file self.key_field = options[:key_field] self.fields = options[:fields] when TSV === file @data = file.data self.key_field = file.key_field || options[:key_field] self.fields = file.fields || options[:key_field] when Persistence::TSV === file @data = file %w(case_insensitive namespace identifiers datadir fields key_field type filename cast).each do |key| if @data.respond_to?(key.to_sym) and self.respond_to?("#{key}=".to_sym) self.send "#{key}=".to_sym, @data.send(key.to_sym) end end else in_situ_persistence = Misc.process_options(options, :in_situ_persistence) @data, extra = Persistence.persist(file, :TSV, :tsv_extra, options) do |file, options, filename, persistence_file| data, extra = nil if in_situ_persistence and persistence_file options.merge! :persistence_data => Persistence::TSV.get(persistence_file, true, :double) end begin case ## Parse source when Resource::Path === file #(String === file and file.respond_to? :open) data, extra = TSV.parse(file.open(:grep => options[:grep]) , options) extra[:namespace] ||= file.namespace extra[:datadir] ||= file.datadir when StringIO === file data, extra = TSV.parse(file, options) when Open.can_open?(file) Open.open(file, :grep => options[:grep]) do |f| data, extra = TSV.parse(f, options) end when File === file path = file.path file = Open.grep(file, options[:grep]) if options[:grep] data, extra = TSV.parse(file, options) when IO === file file = Open.grep(file, options[:grep]) if options[:grep] data, extra = TSV.parse(file, options) when block_given? data else raise "Unknown input in TSV.new #{file.inspect}" end extra[:filename] = filename rescue Exception FileUtils.rm persistence_file if persistence_file and File.exists?(persistence_file) raise $! end if Persistence::TSV === data %w(case_insensitive namespace identifiers datadir fields key_field type filename cast).each do |key| if extra.include? key.to_sym if data.respond_to? "#{key}=".to_sym data.send("#{key}=".to_sym, extra[key.to_sym]) end end end data.read end [data, extra] end end end if not extra.nil? %w(case_insensitive namespace identifiers datadir fields key_field type filename cast).each do |key| if extra.include? key.to_sym self.send("#{key}=".to_sym, extra[key.to_sym]) #if @data.respond_to? "#{key}=".to_sym # @data.send("#{key}=".to_sym, extra[key.to_sym]) #end end end end end def write @data.write if @data.respond_to? :write end def read @data.read if @data.respond_to? :read end def write? @data.write? if @data.respond_to? :write end end
Capistrano::Configuration.instance(:must_exist).load do namespace :rails do namespace :config do desc "Copies all files in cookbook/rails to shared config" task :default, :roles => :app do run "mkdir -p #{shared_path}/config" Dir[File.expand_path('../templates/rails/*', File.dirname(__FILE__))].each do |f| upload_from_erb "#{shared_path}/config/#{File.basename(f, '.erb')}", binding, :folder => 'rails' end end desc "Copies yml files in the shared config folder into our app config" task :to_app, :roles => :app do run "cp -Rf #{shared_path}/config/* #{release_path}/config" end desc "Set up app with app_helpers" task :app_helpers do run "cd #{release_path} && script/plugin install git://github.com/winton/app_helpers.git" run "cd #{release_path} && rake RAILS_ENV=production db=false app_helpers" run "cd #{release_path} && rake RAILS_ENV=production plugins:update" end desc "Configure asset_packager" task :asset_packager do run "source ~/.bash_profile && cd #{release_path} && rake RAILS_ENV=production asset:packager:build_all" end desc "Configure attachment_fu" task :attachment_fu, :roles => :app do run_each [ "mkdir -p #{shared_path}/media", "ln -sf #{shared_path}/media #{release_path}/public/media" ] sudo_each [ "mkdir -p #{release_path}/tmp/attachment_fu", "chown -R #{user} #{release_path}/tmp/attachment_fu" ] end namespace :thinking_sphinx do desc "Configures thinking_sphinx" task :default, :roles => :app do sudo "cd #{release_path} && rake RAILS_ENV=production ts:config" end desc "Stop thinking_sphinx" task :stop, :roles => :app do sudo "cd #{release_path} && rake RAILS_ENV=production ts:stop" end desc "Start thinking_sphinx" task :start, :roles => :app do sudo "cd #{release_path} && rake RAILS_ENV=production ts:start" end desc "Restart thinking_sphinx" task :restart, :roles => :app do rails.config.thinking_sphinx.stop rails.config.thinking_sphinx.start end end namespace :ultrasphinx do desc "Configures ultrasphinx" task :default, :roles => :app do sudo "cd #{release_path} && rake RAILS_ENV=production ultrasphinx:configure" end desc "Stop ultrasphinx" task :stop, :roles => :app do sudo "cd #{release_path} && rake RAILS_ENV=production ultrasphinx:daemon:stop" end desc "Start ultrasphinx" task :start, :roles => :app do sudo "cd #{release_path} && rake RAILS_ENV=production ultrasphinx:daemon:start" end desc "Restart ultrasphinx" task :restart, :roles => :app do rails.config.ultrasphinx.stop rails.config.ultrasphinx.start end end end desc "Intialize Git submodules" task :setup_git, :roles => :app do run "cd #{release_path}; git submodule init; git submodule update" end end end Updating app_helpers config call Capistrano::Configuration.instance(:must_exist).load do namespace :rails do namespace :config do desc "Copies all files in cookbook/rails to shared config" task :default, :roles => :app do run "mkdir -p #{shared_path}/config" Dir[File.expand_path('../templates/rails/*', File.dirname(__FILE__))].each do |f| upload_from_erb "#{shared_path}/config/#{File.basename(f, '.erb')}", binding, :folder => 'rails' end end desc "Copies yml files in the shared config folder into our app config" task :to_app, :roles => :app do run "cp -Rf #{shared_path}/config/* #{release_path}/config" end desc "Set up app with app_helpers" task :app_helpers do run "cd #{release_path} && script/plugin install git://github.com/winton/app_helpers.git" run "cd #{release_path} && rake RAILS_ENV=production db=false app_helpers" run "cd #{release_path} && rake RAILS_ENV=production plugins:install" end desc "Configure asset_packager" task :asset_packager do run "source ~/.bash_profile && cd #{release_path} && rake RAILS_ENV=production asset:packager:build_all" end desc "Configure attachment_fu" task :attachment_fu, :roles => :app do run_each [ "mkdir -p #{shared_path}/media", "ln -sf #{shared_path}/media #{release_path}/public/media" ] sudo_each [ "mkdir -p #{release_path}/tmp/attachment_fu", "chown -R #{user} #{release_path}/tmp/attachment_fu" ] end namespace :thinking_sphinx do desc "Configures thinking_sphinx" task :default, :roles => :app do sudo "cd #{release_path} && rake RAILS_ENV=production ts:config" end desc "Stop thinking_sphinx" task :stop, :roles => :app do sudo "cd #{release_path} && rake RAILS_ENV=production ts:stop" end desc "Start thinking_sphinx" task :start, :roles => :app do sudo "cd #{release_path} && rake RAILS_ENV=production ts:start" end desc "Restart thinking_sphinx" task :restart, :roles => :app do rails.config.thinking_sphinx.stop rails.config.thinking_sphinx.start end end namespace :ultrasphinx do desc "Configures ultrasphinx" task :default, :roles => :app do sudo "cd #{release_path} && rake RAILS_ENV=production ultrasphinx:configure" end desc "Stop ultrasphinx" task :stop, :roles => :app do sudo "cd #{release_path} && rake RAILS_ENV=production ultrasphinx:daemon:stop" end desc "Start ultrasphinx" task :start, :roles => :app do sudo "cd #{release_path} && rake RAILS_ENV=production ultrasphinx:daemon:start" end desc "Restart ultrasphinx" task :restart, :roles => :app do rails.config.ultrasphinx.stop rails.config.ultrasphinx.start end end end desc "Intialize Git submodules" task :setup_git, :roles => :app do run "cd #{release_path}; git submodule init; git submodule update" end end end
module Recog VERSION = '1.0.9' end Bump version to 1.0.10, correcting Tektronix printer SNMP fingerprint module Recog VERSION = '1.0.10' end
module Recog VERSION = "1.0.5" end Bump to 1.0.6, correcting Boa fingerprinting module Recog VERSION = "1.0.6" end
module RedBlack class Tree def left_rotate end def right_rotate end def insert end def insert_fixup end def delete end def delete_fixup end def delete end def search end def predecessor end def successor end def minimum end def maximum end def inorder_tree_walk end end end Implement first inorder tree walk method module RedBlack class Tree def left_rotate end def right_rotate end def insert end def insert_fixup end def delete end def delete_fixup end def delete end def search end def predecessor end def successor end def minimum end def maximum end def inorder_tree_walk(node) if node != nil inorder_tree_walk(node.left) puts node.key inorder_tree_walk(node.right) end end end end
module Redde VERSION = "0.0.7" end Bumped version module Redde VERSION = "0.0.8" end
module Redde VERSION = "0.0.3" end Bumped version module Redde VERSION = "0.0.4" end
=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" 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 def flattened_ivars ivars=instance_variables ivars-=%w[@data @offset @startline @endline] 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 instance_methods.include? "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 instance_methods.include? "negative" identity_param :negative, true,false end class MethNameToken alias to_lisp to_s def has_equals; /#{LETTER_DIGIT}=$/o===ident end unless instance_methods.include? "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 lvalue 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 end class HerePlaceholderToken attr_accessor :node attr :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 if true def inspect label=nil,indent=0 ivarnames=instance_variables-%w[@data @offset @startline @endline] 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 end }.compact.join(' ') pos=@startline.to_s pos<<"..#@endline" if @endline!=@startline pos<<"@#@offset" classname=self.class.name classname.sub!(/^(?:RedParse::)?(.*?)(?:Node)?$/){$1} result= [' '*indent,"+",(label+': ' if label),classname," pos=",pos," ",ivars,"\n"] indent+=2 namelist=self.class.namelist if namelist and !namelist.empty? namelist.each{|name| val=send name case val when Node; result<< val.inspect(name,indent) when ListInNode result.push ' '*indent,"#{name}:\n",*val.map{|v| v.inspect(nil,indent+2) 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) else result<< ' '*indent+"-#{val.inspect}\n" end } end ivarnodes.each{|(name,val)| result<< val.inspect(name,indent) } return result.join end else def inspect ivarnames=instance_variables-["@data"] ivars=ivarnames.map{|ivarname| ":"+ivarname+"=>"+instance_variable_get(ivarname).inspect }.join(', ') bare=super bare.gsub!(/\]\Z/, ", {"+ivars+"}]") unless ivarnames.empty? return self.class.name+bare end end def pretty_print(q) ivarnames=instance_variables-["@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.to_s+"\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) 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 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{|assignnode,jj| 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_module=nil result=clone instance_variables.each{|iv| unless iv=="@data" val=instance_variable_get(iv) result.instance_variable_set(iv,handler[val]) result_module=val if iv=="@module" #hacky end } result.replace newdata result.extend result_module if result_module 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= Integer===token ? token : token.startline rescue (return alt) shy=(linenum||0)-o[:linenum] 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 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 module ArrowOpNode; end module RangeNode; end module LogicalNode; end module WhileOpNode; end module UntilOpNode; end module IfOpNode; end module UnlessOpNode; end module OpNode; end module NotEqualNode; end module MatchNode; end module NotMatchNode; end OP2MIXIN={ "=>"=>ArrowOpNode, ".."=>RangeNode, "..."=>RangeNode, "&&"=>LogicalNode, "||"=>LogicalNode, "and"=>LogicalNode, "or"=>LogicalNode, "while"=>WhileOpNode, "until"=>UntilOpNode, "if"=>IfOpNode, "unless"=>UnlessOpNode, "!="=>NotEqualNode, "!~"=>NotMatchNode, "=~"=>MatchNode, } class RawOpNode<ValueNode param_names(:left,:op,:right) def initialize(left,op,right) @offset=op.offset op=op.ident super(left,op,right) Array((OP2MIXIN[op]||OpNode)).each{|mod| extend(mod) mod.instance_method(:initialize).bind(self).call(left,op,right) } end def self.[](*args) result=super @module and extend @module return result 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 module OpNode def self.[] *list result=RawOpNode[*list] result.extend OpNode return result end def initialize(left,op,right) #@negative_of="="+$1 if /^!([=~])$/===op @module=OpNode 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 module MatchNode include OpNode def initialize(left,op,right) @module=MatchNode end def self.[] *list result=RawOpNode[*list] result.extend MatchNode return result 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 module NotEqualNode include OpNode def initialize(left,op,right) @module=NotEqualNode end def self.[] *list result=RawOpNode[*list] result.extend NotEqualNode return result 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 module NotMatchNode include OpNode def initialize(left,op,right) @module=NotMatchNode end def self.[] *list result=RawOpNode[*list] result.extend NotMatchNode return result 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 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| # p expr unparse_nl(expr,o)+expr.unparse(o) }.to_s 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{|tree,i| 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<ValueNode # param_names(:left,:arrow_,:right) # end module ArrowOpNode def initialize(*args) @module=ArrowOpNode end def unparse(o=default_unparse_options) left.unparse(o)+" => "+right.unparse(o) end end # class RangeNode<ValueNode module RangeNode # param_names(:first,:op_,:last) def initialize(left,op_,right) @exclude_end=!!op_[2] @module=RangeNode @as_flow_control=false # super(left,right) end def begin; left end def end; right end def first; left end def last; right end def exclude_end?; @exclude_end end def self.[] *list result=RawOpNode[*list] result.extend RangeNode return result 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 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 initialize(op,val) @offset=op.offset op=op.ident /([&*])$/===op and op=$1+"@" /^(?:!|not)$/===op and val.respond_to? :special_conditions! and val.special_conditions! super(op,val) 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 UnaryStarNode<UnOpNode def initialize(op,val) op.ident="*@" super(op,val) 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) @offset= star.offset replace ['*@',var=VarNode.new(VarNameToken.new('',offset))] var.startline=var.endline=star.startline 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 result=' '*indent result+="#{label}: " if label result+='Constant ' result+=map{|name| name.inspect}.join(', ')+"\n" 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 =begin class OldParenedNode<ValueNode param_names :body, :rescues, :else!, :ensure! def initialize(*args) @empty_ensure=@op_rescue=nil replace( if args.size==3 #() if (KeywordToken===args.first and args.first.ident=='(') [args[1]] else expr,rescueword,backup=*args @op_rescue=true [expr,[RescueNode[[],nil,backup]],nil,nil] end else body,rescues,else_,ensure_=*args[1...-1] if else_ else_=else_.val or @empty_else=true end if ensure_ ensure_=ensure_.val or @empty_ensure=true end [body,rescues,else_,ensure_] end ) end alias ensure_ ensure alias else_ else attr_reader :empty_ensure, :empty_else attr_accessor :after_comma, :after_equals def op?; @op_rescue; end def image; '(begin)' end def special_conditions! if size==1 node=body node.special_conditions! if node.respond_to? :special_conditions! end end def to_lisp huh #what about rescues, else, ensure? body.to_lisp end def parsetree(o) if size==1 body.parsetree(o) else 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? else_ and body=SequenceNode.new(body,nil,else_) 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]] result=result.last #if @op_rescue result=[:begin,result] unless o[:ruby187]||op?||result==[:nil]#||result.first==:begin result end 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 unless size==1 # case first # when CommaOpNode,UnaryStarNode: #do nothing # when ParenedNode: return first.lvalue # else return nil # end return @lvalue if defined? @lvalue @lvalue=true end attr_writer :lvalue def unparse(o=default_unparse_options) if size==1 "("+(body&&body.unparse(o))+")" else result="begin " body&&result+= body.unparse(o) result+=unparse_nl(rescues.first,o) rescues.each{|resc| result+=resc.unparse(o) } result+=unparse_nl(ensure_,o)+"ensure "+ensure_.unparse(o) if ensure_ result+=unparse_nl(else_,o)+"else "+else_.unparse(o) if else_ result+=";end" end end end =end class ParenedNode<ValueNode param_names :body #, :rescues, :else!, :ensure! 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]] result=result.last #if @op_rescue result end def unparse_and_rescues(o) result=" " result+= body.unparse(o) if body result+=unparse_nl(rescues.first,o) rescues.each{|resc| result+=resc.unparse(o) } 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) result=[:begin,result] unless o[:ruby187]||result==[:nil]#||result.first==:begin 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 class RescueOpNode<ValueNode # include OpNode 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.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 initialize(*args) if args.size==5 if args[3].ident=="rescue3" lhs,op,rescuee,op2,rescuer=*args rhs=RescueOpNode.new(rescuee.val,op2,rescuer) 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)) elsif UnaryStarNode===lhs.first lhs=MultiAssign.new([lhs.first]) else lhs=lhs.first end @lhs_parens=true 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 module KeywordOpNode def unparse o=default_unparse_options [left.unparse(o),' ',op,' ',right.unparse(o)].to_s end end module LogicalNode include KeywordOpNode def self.[] *list result=RawOpNode[*list] result.extend LogicalNode return result end def initialize(left,op,right) @opmap=op[0,1] case op when "&&"; op="and" when "||"; op="or" end #@reverse= op=="or" #@op=op @module=LogicalNode replace [left,right] (size-1).downto(0){|i| expr=self[i] if LogicalNode===expr and expr.op==op 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 reverse /\A[o|]/===@opmap end def op OP_EQUIV[@opmap[0]] end 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 module WhileOpNode include KeywordOpNode def condition; right end def consequent; left end def initialize(val1,op,val2) self[1]=op @reverse=false @module=WhileOpNode @loop=true @test_first= !( BeginNode===val1 ) condition.special_conditions! if condition.respond_to? :special_conditions! end def while; condition end def do; consequent end def self.[] *list result=RawOpNode[*list] result.extend WhileOpNode return result 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=:until cond=cond.last else kw=:while end [kw, cond, body, (@test_first or body==[:nil])] end end module UntilOpNode include KeywordOpNode def condition; right end def consequent; left end def initialize(val1,op,val2) self[1]=op @reverse=true @loop=true @test_first= !( BeginNode===val1 ) @module=UntilOpNode condition.special_conditions! if condition.respond_to? :special_conditions! end def while; negate condition end def do; consequent end def self.[] *list result=RawOpNode[*list] result.extend UntilOpNode return result 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 module UnlessOpNode include KeywordOpNode def condition; right end def consequent; left end def initialize(val1,op,val2) self[1]=op @reverse=true @loop=false @module=UnlessOpNode 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 self.[] *list result=RawOpNode[*list] result.extend UnlessOpNode return result 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 module IfOpNode include KeywordOpNode def condition; right end def consequent; left end def initialize(left,op,right) self[1]=op @reverse=false @loop=false @module=IfOpNode 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 self.[] *list result=RawOpNode[*list] result.extend IfOpNode return result 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 param_list=Array.new(param_list) 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 param_list[arrowrange]=[h] end 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 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&&params.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.to_s 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 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}] 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 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].to_s 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 @modifiers.each_byte{|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 @modifiers.each_byte{|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 vals=[/#{vals[0]}/] if :dregx==type or :dregx_once==type 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 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 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].to_s end end class LiteralNode<ValueNode param_names :val attr_accessor :offset def initialize(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 if StringToken===old_val.raw val=old_val.raw.translate_escapes(old_val.raw.elems.first).to_sym else val=old_val.raw.to_sym end 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 super(val) 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= "%#{Float::DIG+1}.#{Float::DIG+1}f"%val 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=false 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 super( *contents ) 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)}.to_s 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};" 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" ].to_s end def while @reverse ? negate(condition, @loopword_offset) : condition end def until @reverse ? condition : negate(condition, @loopword_offset) 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 or @empty_else=true 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}.to_s result += unparse_nl(otherwise,o)+"else "+otherwise.unparse(o) if otherwise 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) end @no_braces=!open end attr :no_arrows attr_writer :offset def image; "({})" end def unparse o=default_unparse_options result='' result << "{" unless @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 @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.to_s 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().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 then [: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 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 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 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_) def initialize(receiver,lbrack,params,rbrack) params=case params when CommaOpNode; Array.new params when nil else [params] end params.extend ListInNode if params @offset=receiver.offset super(receiver,params) end def image; "(#{receiver.image}.[])" end def unparse o=default_unparse_options [ receiver.unparse(o).sub(/\s+\Z/,''), '[', params&&params.map{|param| param.unparse o}.join(','), ']' ].to_s 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 node_modules=%w[ArrowOpNode RangeNode LogicalNode WhileOpNode UntilOpNode IfOpNode UnlessOpNode OpNode NotEqualNode MatchNode NotMatchNode] ::RedParse::constants.each{|k| const=::RedParse::const_get(k) const_set( k,const ) if Module===const and (::RedParse::Node>=const || node_modules.include?( k )) } 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 VarNode#ident is now kept in a slot, not an ivar =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" 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 def flattened_ivars ivars=instance_variables ivars-=%w[@data @offset @startline @endline] 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 instance_methods.include? "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 instance_methods.include? "negative" identity_param :negative, true,false end class MethNameToken alias to_lisp to_s def has_equals; /#{LETTER_DIGIT}=$/o===ident end unless instance_methods.include? "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 lvalue 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 end class HerePlaceholderToken attr_accessor :node attr :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 if true def inspect label=nil,indent=0 ivarnames=instance_variables-%w[@data @offset @startline @endline] 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 end }.compact.join(' ') pos=@startline.to_s pos<<"..#@endline" if @endline!=@startline pos<<"@#@offset" classname=self.class.name classname.sub!(/^(?:RedParse::)?(.*?)(?:Node)?$/){$1} result= [' '*indent,"+",(label+': ' if label),classname," pos=",pos," ",ivars,"\n"] indent+=2 namelist=self.class.namelist if namelist and !namelist.empty? namelist.each{|name| val=send name case val when Node; result<< val.inspect(name,indent) when ListInNode result.push ' '*indent,"#{name}:\n",*val.map{|v| v.inspect(nil,indent+2) 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) else result<< ' '*indent+"-#{val.inspect}\n" end } end ivarnodes.each{|(name,val)| result<< val.inspect(name,indent) } return result.join end else def inspect ivarnames=instance_variables-["@data"] ivars=ivarnames.map{|ivarname| ":"+ivarname+"=>"+instance_variable_get(ivarname).inspect }.join(', ') bare=super bare.gsub!(/\]\Z/, ", {"+ivars+"}]") unless ivarnames.empty? return self.class.name+bare end end def pretty_print(q) ivarnames=instance_variables-["@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.to_s+"\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) 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 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{|assignnode,jj| 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_module=nil result=clone instance_variables.each{|iv| unless iv=="@data" val=instance_variable_get(iv) result.instance_variable_set(iv,handler[val]) result_module=val if iv=="@module" #hacky end } result.replace newdata result.extend result_module if result_module 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= Integer===token ? token : token.startline rescue (return alt) shy=(linenum||0)-o[:linenum] 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 module ArrowOpNode; end module RangeNode; end module LogicalNode; end module WhileOpNode; end module UntilOpNode; end module IfOpNode; end module UnlessOpNode; end module OpNode; end module NotEqualNode; end module MatchNode; end module NotMatchNode; end OP2MIXIN={ "=>"=>ArrowOpNode, ".."=>RangeNode, "..."=>RangeNode, "&&"=>LogicalNode, "||"=>LogicalNode, "and"=>LogicalNode, "or"=>LogicalNode, "while"=>WhileOpNode, "until"=>UntilOpNode, "if"=>IfOpNode, "unless"=>UnlessOpNode, "!="=>NotEqualNode, "!~"=>NotMatchNode, "=~"=>MatchNode, } class RawOpNode<ValueNode param_names(:left,:op,:right) def initialize(left,op,right) @offset=op.offset op=op.ident super(left,op,right) Array((OP2MIXIN[op]||OpNode)).each{|mod| extend(mod) mod.instance_method(:initialize).bind(self).call(left,op,right) } end def self.[](*args) result=super @module and extend @module return result 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 module OpNode def self.[] *list result=RawOpNode[*list] result.extend OpNode return result end def initialize(left,op,right) #@negative_of="="+$1 if /^!([=~])$/===op @module=OpNode 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 module MatchNode include OpNode def initialize(left,op,right) @module=MatchNode end def self.[] *list result=RawOpNode[*list] result.extend MatchNode return result 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 module NotEqualNode include OpNode def initialize(left,op,right) @module=NotEqualNode end def self.[] *list result=RawOpNode[*list] result.extend NotEqualNode return result 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 module NotMatchNode include OpNode def initialize(left,op,right) @module=NotMatchNode end def self.[] *list result=RawOpNode[*list] result.extend NotMatchNode return result 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 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| # p expr unparse_nl(expr,o)+expr.unparse(o) }.to_s 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{|tree,i| 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<ValueNode # param_names(:left,:arrow_,:right) # end module ArrowOpNode def initialize(*args) @module=ArrowOpNode end def unparse(o=default_unparse_options) left.unparse(o)+" => "+right.unparse(o) end end # class RangeNode<ValueNode module RangeNode # param_names(:first,:op_,:last) def initialize(left,op_,right) @exclude_end=!!op_[2] @module=RangeNode @as_flow_control=false # super(left,right) end def begin; left end def end; right end def first; left end def last; right end def exclude_end?; @exclude_end end def self.[] *list result=RawOpNode[*list] result.extend RangeNode return result 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 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 initialize(op,val) @offset=op.offset op=op.ident /([&*])$/===op and op=$1+"@" /^(?:!|not)$/===op and val.respond_to? :special_conditions! and val.special_conditions! super(op,val) 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 UnaryStarNode<UnOpNode def initialize(op,val) op.ident="*@" super(op,val) 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) @offset= star.offset replace ['*@',var=VarNode.new(VarNameToken.new('',offset))] var.startline=var.endline=star.startline 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 result=' '*indent result+="#{label}: " if label result+='Constant ' result+=map{|name| name.inspect}.join(', ')+"\n" 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 =begin class OldParenedNode<ValueNode param_names :body, :rescues, :else!, :ensure! def initialize(*args) @empty_ensure=@op_rescue=nil replace( if args.size==3 #() if (KeywordToken===args.first and args.first.ident=='(') [args[1]] else expr,rescueword,backup=*args @op_rescue=true [expr,[RescueNode[[],nil,backup]],nil,nil] end else body,rescues,else_,ensure_=*args[1...-1] if else_ else_=else_.val or @empty_else=true end if ensure_ ensure_=ensure_.val or @empty_ensure=true end [body,rescues,else_,ensure_] end ) end alias ensure_ ensure alias else_ else attr_reader :empty_ensure, :empty_else attr_accessor :after_comma, :after_equals def op?; @op_rescue; end def image; '(begin)' end def special_conditions! if size==1 node=body node.special_conditions! if node.respond_to? :special_conditions! end end def to_lisp huh #what about rescues, else, ensure? body.to_lisp end def parsetree(o) if size==1 body.parsetree(o) else 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? else_ and body=SequenceNode.new(body,nil,else_) 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]] result=result.last #if @op_rescue result=[:begin,result] unless o[:ruby187]||op?||result==[:nil]#||result.first==:begin result end 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 unless size==1 # case first # when CommaOpNode,UnaryStarNode: #do nothing # when ParenedNode: return first.lvalue # else return nil # end return @lvalue if defined? @lvalue @lvalue=true end attr_writer :lvalue def unparse(o=default_unparse_options) if size==1 "("+(body&&body.unparse(o))+")" else result="begin " body&&result+= body.unparse(o) result+=unparse_nl(rescues.first,o) rescues.each{|resc| result+=resc.unparse(o) } result+=unparse_nl(ensure_,o)+"ensure "+ensure_.unparse(o) if ensure_ result+=unparse_nl(else_,o)+"else "+else_.unparse(o) if else_ result+=";end" end end end =end class ParenedNode<ValueNode param_names :body #, :rescues, :else!, :ensure! 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]] result=result.last #if @op_rescue result end def unparse_and_rescues(o) result=" " result+= body.unparse(o) if body result+=unparse_nl(rescues.first,o) rescues.each{|resc| result+=resc.unparse(o) } 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) result=[:begin,result] unless o[:ruby187]||result==[:nil]#||result.first==:begin 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 class RescueOpNode<ValueNode # include OpNode 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.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 initialize(*args) if args.size==5 if args[3].ident=="rescue3" lhs,op,rescuee,op2,rescuer=*args rhs=RescueOpNode.new(rescuee.val,op2,rescuer) 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)) elsif UnaryStarNode===lhs.first lhs=MultiAssign.new([lhs.first]) else lhs=lhs.first end @lhs_parens=true 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 module KeywordOpNode def unparse o=default_unparse_options [left.unparse(o),' ',op,' ',right.unparse(o)].to_s end end module LogicalNode include KeywordOpNode def self.[] *list result=RawOpNode[*list] result.extend LogicalNode return result end def initialize(left,op,right) @opmap=op[0,1] case op when "&&"; op="and" when "||"; op="or" end #@reverse= op=="or" #@op=op @module=LogicalNode replace [left,right] (size-1).downto(0){|i| expr=self[i] if LogicalNode===expr and expr.op==op 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 reverse /\A[o|]/===@opmap end def op OP_EQUIV[@opmap[0]] end 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 module WhileOpNode include KeywordOpNode def condition; right end def consequent; left end def initialize(val1,op,val2) self[1]=op @reverse=false @module=WhileOpNode @loop=true @test_first= !( BeginNode===val1 ) condition.special_conditions! if condition.respond_to? :special_conditions! end def while; condition end def do; consequent end def self.[] *list result=RawOpNode[*list] result.extend WhileOpNode return result 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=:until cond=cond.last else kw=:while end [kw, cond, body, (@test_first or body==[:nil])] end end module UntilOpNode include KeywordOpNode def condition; right end def consequent; left end def initialize(val1,op,val2) self[1]=op @reverse=true @loop=true @test_first= !( BeginNode===val1 ) @module=UntilOpNode condition.special_conditions! if condition.respond_to? :special_conditions! end def while; negate condition end def do; consequent end def self.[] *list result=RawOpNode[*list] result.extend UntilOpNode return result 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 module UnlessOpNode include KeywordOpNode def condition; right end def consequent; left end def initialize(val1,op,val2) self[1]=op @reverse=true @loop=false @module=UnlessOpNode 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 self.[] *list result=RawOpNode[*list] result.extend UnlessOpNode return result 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 module IfOpNode include KeywordOpNode def condition; right end def consequent; left end def initialize(left,op,right) self[1]=op @reverse=false @loop=false @module=IfOpNode 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 self.[] *list result=RawOpNode[*list] result.extend IfOpNode return result 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 param_list=Array.new(param_list) 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 param_list[arrowrange]=[h] end 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 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&&params.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.to_s 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 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}] 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 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].to_s 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 @modifiers.each_byte{|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 @modifiers.each_byte{|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 vals=[/#{vals[0]}/] if :dregx==type or :dregx_once==type 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 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 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].to_s end end class LiteralNode<ValueNode param_names :val attr_accessor :offset def initialize(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 if StringToken===old_val.raw val=old_val.raw.translate_escapes(old_val.raw.elems.first).to_sym else val=old_val.raw.to_sym end 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 super(val) 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= "%#{Float::DIG+1}.#{Float::DIG+1}f"%val 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=false 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 super( *contents ) 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)}.to_s 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};" 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" ].to_s end def while @reverse ? negate(condition, @loopword_offset) : condition end def until @reverse ? condition : negate(condition, @loopword_offset) 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 or @empty_else=true 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}.to_s result += unparse_nl(otherwise,o)+"else "+otherwise.unparse(o) if otherwise 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) end @no_braces=!open end attr :no_arrows attr_writer :offset def image; "({})" end def unparse o=default_unparse_options result='' result << "{" unless @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 @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.to_s 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().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 then [: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 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 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 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_) def initialize(receiver,lbrack,params,rbrack) params=case params when CommaOpNode; Array.new params when nil else [params] end params.extend ListInNode if params @offset=receiver.offset super(receiver,params) end def image; "(#{receiver.image}.[])" end def unparse o=default_unparse_options [ receiver.unparse(o).sub(/\s+\Z/,''), '[', params&&params.map{|param| param.unparse o}.join(','), ']' ].to_s 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 node_modules=%w[ArrowOpNode RangeNode LogicalNode WhileOpNode UntilOpNode IfOpNode UnlessOpNode OpNode NotEqualNode MatchNode NotMatchNode] ::RedParse::constants.each{|k| const=::RedParse::const_get(k) const_set( k,const ) if Module===const and (::RedParse::Node>=const || node_modules.include?( k )) } 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
# -*- encoding : utf-8 -*- require 'net/http' require 'net/https' require 'yajl' module RegApi2 # Networking Error class NetError < Exception end # API Contract Error class ContractError < Exception end # API Error class ApiError < Exception # @!attribute [r] Localized error description. attr_reader :description def initialize code, description super code @description = description end end class << self # @!attribute [rw] username # @return [String] User name. attr_accessor :username # @!attribute [rw] password # @return [String] Password. attr_accessor :password # @!attribute [rw] io_encoding # @return [String] IO encoding ('utf-8' by default). attr_accessor :io_encoding # @!attribute [rw] lang # @return [String] Language ('en' by default). attr_accessor :lang # Default IO encoding DEFAULT_IO_ENCODING = 'utf-8' # Default lang. DEFAULT_LANG = 'en' # Default API contract DEFAULT_CONTRACT = RegApi2::Contract::Default # REG.API base URI API_URI = URI.parse("https://api.reg.ru/api/regru2") # Creates or gets HTTPS handler. # @return [Net::HTTP] HTTPS handler. def http @http ||= begin http = Net::HTTP.new( API_URI.host, API_URI.port ) http.use_ssl = true http end end # Do actual call to REG.API using POST/JSON convention. # @param [Symbol] category # @param [Symbol] name # @param [Hash] defopts # @param [Hash] opts # @return [Hash] Result answer field. # @raise [NetError] # @raise [ApiError] def make_action category, name, defopts, opts = {} req = Net::HTTP::Post.new( category.nil? ? "#{API_URI.path}/#{name}" : "#{API_URI.path}/#{category}/#{name}" ) # HACK: REG.API doesn't know about utf-8. io_encoding = 'utf8' if !io_encoding || io_encoding == DEFAULT_IO_ENCODING form = { 'username' => username, 'password' => password, 'io_encoding' => io_encoding, 'lang' => lang || DEFAULT_LANG, 'output_format' => 'json', 'input_format' => 'json', 'show_input_params' => 0, 'input_data' => Yajl::Encoder.encode(opts) } req.set_form_data(form) res = http.request(req) raise NetError.new(res.body) unless res.code == '200' json = Yajl::Parser.parse(res.body) raise ApiError.new(json['error_code'], json['error_text']) if json['result'] == 'error' (defopts[:contract] || DEFAULT_CONTRACT).new(defopts).handle_result(json) end end end Dont forget about error_params for ApiError. # -*- encoding : utf-8 -*- require 'net/http' require 'net/https' require 'yajl' module RegApi2 # Networking Error class NetError < Exception end # API Contract Error class ContractError < Exception end # API Error class ApiError < Exception # @!attribute [r] Localized error description. attr_reader :description, :params def initialize code, description, params super code @description = description @params = params end end class << self # @!attribute [rw] username # @return [String] User name. attr_accessor :username # @!attribute [rw] password # @return [String] Password. attr_accessor :password # @!attribute [rw] io_encoding # @return [String] IO encoding ('utf-8' by default). attr_accessor :io_encoding # @!attribute [rw] lang # @return [String] Language ('en' by default). attr_accessor :lang # Default IO encoding DEFAULT_IO_ENCODING = 'utf-8' # Default lang. DEFAULT_LANG = 'en' # Default API contract DEFAULT_CONTRACT = RegApi2::Contract::Default # REG.API base URI API_URI = URI.parse("https://api.reg.ru/api/regru2") # Creates or gets HTTPS handler. # @return [Net::HTTP] HTTPS handler. def http @http ||= begin http = Net::HTTP.new( API_URI.host, API_URI.port ) http.use_ssl = true http end end # Do actual call to REG.API using POST/JSON convention. # @param [Symbol] category # @param [Symbol] name # @param [Hash] defopts # @param [Hash] opts # @return [Hash] Result answer field. # @raise [NetError] # @raise [ApiError] def make_action category, name, defopts, opts = {} req = Net::HTTP::Post.new( category.nil? ? "#{API_URI.path}/#{name}" : "#{API_URI.path}/#{category}/#{name}" ) # HACK: REG.API doesn't know about utf-8. io_encoding = 'utf8' if !io_encoding || io_encoding == DEFAULT_IO_ENCODING form = { 'username' => username, 'password' => password, 'io_encoding' => io_encoding, 'lang' => lang || DEFAULT_LANG, 'output_format' => 'json', 'input_format' => 'json', 'show_input_params' => 0, 'input_data' => Yajl::Encoder.encode(opts) } req.set_form_data(form) res = http.request(req) raise NetError.new(res.body) unless res.code == '200' json = Yajl::Parser.parse(res.body) raise ApiError.new(json['error_code'], json['error_text'], json['error_params']) if json['result'] == 'error' (defopts[:contract] || DEFAULT_CONTRACT).new(defopts).handle_result(json) end end end
module RegXing class Regex # Class Methods # ------------- class << self def matchers { /(?<!\\)\./ => random_letter, /\\d/ => random_number, /\\w/ => random_letter, /\\W/ => random_non_word_character, /\\D/ => random_letter, /\\h/ => random_hexdigit_character, /\\H/ => random_non_hexdigit_character, /\\s/ => " ", /\\S/ => random_letter } end def count_indicators [ /(?<!\\)\*/, /(?<!\\)\+/, /(?<!\\)\?/, /\{\d*\,?\d*\}/ ] end def anchors [ /^\^/, /\$$/ ] end def process_count_indicator(indicator) if indicator.match count_indicators.last minimum = indicator.match(/(?<=\{)\d+/) ? indicator.match(/(?<=\{)\d+/)[0].to_i : 1 return minimum else return 1 end end private def random_letter ("a".."z").to_a.sample end alias_method :random_lowercase_letter, :random_letter def random_uppercase_letter ("A".."Z").to_a.sample end def random_number (0..9).to_a.sample.to_s end def random_non_word_character non_word_characters.sample end def random_hexdigit_character [(0..9).to_a.map(&:to_s), ("A".."F").to_a, ("a".."f").to_a].flatten.sample end def random_non_hexdigit_character ("h".."z").to_a.sample end def non_word_characters [ "!", "@", "#", "%", "&", "*", "(", ")", "-", "{", "}", "[", "]", "\\", "'", "\"", ":", ";", ",", ".", "?", "/" ] end end # Instance Methods # ---------------- attr_reader :expression def initialize(exp) @expression = exp end def to_s expression.inspect[1..-2] end def extract_groupings to_s.split(/[\(\)\[\]]/).reject {|str| str == "" } end def is_anchor(char) RegXing::Regex.anchors.any? {|exp| char.match(exp) } end def is_indicator(first, second=nil) RegXing::Regex.count_indicators.any? {|exp| second && second.match(exp) } end def split arr = to_s.scan(/\\\?|[^\\]?\?|\\\.|[^\\]?\.|\\\+|[^\\]?\+|\\\*|[^\\]?\*|\\[a-zA-Z]|(?<!\\)[a-zA-Z]|\{\d*\,?\d*\}|\[\[\:.{5,6}\:\]\]|./).flatten arr.each_with_index do |item, index| if is_indicator(item, arr[index + 1]) arr[index] = [ item, RegXing::Regex.process_count_indicator(arr.delete_at(index + 1)) ] elsif is_anchor(item) arr[index] = nil else arr[index] = [item, 1] end end arr.compact end end end Extract return_matches method module RegXing class Regex # Class Methods # ------------- class << self def matchers { /(?<!\\)\./ => random_letter, /\\d/ => random_number, /\\w/ => random_letter, /\\W/ => random_non_word_character, /\\D/ => random_letter, /\\h/ => random_hexdigit_character, /\\H/ => random_non_hexdigit_character, /\\s/ => " ", /\\S/ => random_letter } end def count_indicators [ /(?<!\\)\*/, /(?<!\\)\+/, /(?<!\\)\?/, /\{\d*\,?\d*\}/ ] end def anchors [ /^\^/, /\$$/ ] end def process_count_indicator(indicator) if indicator.match count_indicators.last minimum = indicator.match(/(?<=\{)\d+/) ? indicator.match(/(?<=\{)\d+/)[0].to_i : 1 return minimum else return 1 end end private def random_letter ("a".."z").to_a.sample end alias_method :random_lowercase_letter, :random_letter def random_uppercase_letter ("A".."Z").to_a.sample end def random_number (0..9).to_a.sample.to_s end def random_non_word_character non_word_characters.sample end def random_hexdigit_character [(0..9).to_a.map(&:to_s), ("A".."F").to_a, ("a".."f").to_a].flatten.sample end def random_non_hexdigit_character ("h".."z").to_a.sample end def non_word_characters [ "!", "@", "#", "%", "&", "*", "(", ")", "-", "{", "}", "[", "]", "\\", "'", "\"", ":", ";", ",", ".", "?", "/" ] end end # Instance Methods # ---------------- attr_reader :expression def initialize(exp) @expression = exp end def to_s expression.inspect[1..-2] end def extract_groupings to_s.split(/[\(\)\[\]]/).reject {|str| str == "" } end def is_anchor(char) RegXing::Regex.anchors.any? {|exp| char.match(exp) } end def return_matches(string) string.scan(/\\\?|[^\\]?\?|\\\.|[^\\]?\.|\\\+|[^\\]?\+|\\\*|[^\\]?\*|\\[a-zA-Z]|(?<!\\)[a-zA-Z]|\{\d*\,?\d*\}|\[\[\:.{5,6}\:\]\]|./).flatten end def is_indicator(first, second=nil) RegXing::Regex.count_indicators.any? {|exp| second && second.match(exp) } end def split arr = return_matches(to_s) arr.each_with_index do |item, index| if is_indicator(item, arr[index + 1]) arr[index] = [ item, RegXing::Regex.process_count_indicator(arr.delete_at(index + 1)) ] elsif is_anchor(item) arr[index] = nil else arr[index] = [item, 1] end end arr.compact end end end
require 'thread' require "renoir/cluster_info" require "renoir/connection_adapters" require "renoir/crc16" module Renoir class Client REDIS_CLUSTER_HASH_SLOTS = 16_384 DEFAULT_OPTIONS = { cluster_nodes: [ ["127.0.0.1", 6379] ], max_redirection: 10, max_connection_error: 5, connect_retry_random_factor: 0.1, connect_retry_interval: 0.001, # 1 ms connection_adapter: :redis, }.freeze def initialize(options) @connections = {} @cluster_info = ClusterInfo.new @refresh_slots = true options = options.map { |k, v| [k.to_sym, v] }.to_h @options = DEFAULT_OPTIONS.merge(options) @logger = @options[:logger] @adapter_class = ConnectionAdapters.const_get(@options[:connection_adapter].to_s.capitalize) cluster_nodes = @options.delete(:cluster_nodes) fail "the cluster_nodes option must contain at least one node" if cluster_nodes.empty? cluster_nodes.each do |node| host, port = case node when Array node when Hash [node[:host], node[:port]] when String node.split(":") else fail "invalid entry in cluster_nodes option: #{node}" end port ||= 6379 @cluster_info.add_node(host, port.to_i) end @connections_mutex = Mutex.new end def call(*command, &block) keys = @adapter_class.get_keys_from_command(command) slots = keys.map { |key| key_slot(key) }.uniq fail "No way to dispatch this command to Redis Cluster." if slots.size != 1 slot = slots.first refresh_slots if @refresh_slots call_with_redirection(slot, command, &block) end def close while entry = @connections.shift entry[1].close end end def each_node return enum_for(:each_node) unless block_given? @cluster_info.nodes.each do |node| fetch_connection(node).with_raw_connection do |conn| yield conn end end end def method_missing(command, *args, &block) call(command, *args, &block) end private def key_slot(key) s = key.index("{") if s e = key.index("}", s + 1) if e && e != s + 1 key = key[s + 1..e - 1] end end CRC16.crc16(key) % REDIS_CLUSTER_HASH_SLOTS end def call_with_redirection(slot, command, &block) nodes = @cluster_info.nodes.dup node = @cluster_info.slot_node(slot) || nodes.sample redirect_count = 0 connect_error_count = 0 connect_retry_count = 0 asking = false loop do nodes.delete(node) conn = fetch_connection(node) reply = conn.call(command, asking, &block) case reply when ConnectionAdapters::Reply::RedirectionError asking = reply.ask node = @cluster_info.add_node(reply.ip, reply.port) @refresh_slots ||= !asking redirect_count += 1 raise RedirectionError, "Too many redirections" if @options[:max_redirection] < redirect_count when ConnectionAdapters::Reply::ConnectionError connect_error_count += 1 raise reply.cause if @options[:max_connection_error] < connect_error_count if nodes.empty? connect_retry_count += 1 sleep(sleep_interval(connect_retry_count)) else asking = false node = nodes.sample end else return reply end end end def refresh_slots slots = nil @cluster_info.nodes.each do |node| conn = fetch_connection(node) reply = conn.call(["cluster", "slots"]) case reply when ConnectionAdapters::Reply::RedirectionError fail "never reach here" when ConnectionAdapters::Reply::ConnectionError if @logger @logger.warn("CLUSTER SLOTS command failed: node_name=#{node[:name]}, message=#{reply.cause}") end else slots = reply break end end return unless slots @refresh_slots = false @cluster_info = ClusterInfo.new.tap do |cluster_info| cluster_info.load_slots(slots) end (@connections.keys - @cluster_info.node_names).each do |key| conn = @connections.delete(key) conn.close if conn end end def fetch_connection(node) name = node[:name] if conn = @connections[name] conn else @connections_mutex.synchronize do @connections[name] ||= @adapter_class.new(node[:host], node[:port], @options) end end end def sleep_interval(retry_count) factor = 1 + 2 * (rand - 0.5) * @options[:connect_retry_random_factor] factor * @options[:connect_retry_interval] * 2**(retry_count - 1) end end end Prevent simultaneous slot refreshing require 'thread' require "renoir/cluster_info" require "renoir/connection_adapters" require "renoir/crc16" module Renoir class Client REDIS_CLUSTER_HASH_SLOTS = 16_384 DEFAULT_OPTIONS = { cluster_nodes: [ ["127.0.0.1", 6379] ], max_redirection: 10, max_connection_error: 5, connect_retry_random_factor: 0.1, connect_retry_interval: 0.001, # 1 ms connection_adapter: :redis, }.freeze def initialize(options) @connections = {} @cluster_info = ClusterInfo.new @refresh_slots = true options = options.map { |k, v| [k.to_sym, v] }.to_h @options = DEFAULT_OPTIONS.merge(options) @logger = @options[:logger] @adapter_class = ConnectionAdapters.const_get(@options[:connection_adapter].to_s.capitalize) cluster_nodes = @options.delete(:cluster_nodes) fail "the cluster_nodes option must contain at least one node" if cluster_nodes.empty? cluster_nodes.each do |node| host, port = case node when Array node when Hash [node[:host], node[:port]] when String node.split(":") else fail "invalid entry in cluster_nodes option: #{node}" end port ||= 6379 @cluster_info.add_node(host, port.to_i) end @connections_mutex = Mutex.new @refresh_slots_mutex = Mutex.new end def call(*command, &block) keys = @adapter_class.get_keys_from_command(command) slots = keys.map { |key| key_slot(key) }.uniq fail "No way to dispatch this command to Redis Cluster." if slots.size != 1 slot = slots.first refresh = @refresh_slots_mutex.synchronize do refresh = @refresh_slots @refresh_slots = false refresh end refresh_slots if refresh call_with_redirection(slot, command, &block) end def close while entry = @connections.shift entry[1].close end end def each_node return enum_for(:each_node) unless block_given? @cluster_info.nodes.each do |node| fetch_connection(node).with_raw_connection do |conn| yield conn end end end def method_missing(command, *args, &block) call(command, *args, &block) end private def key_slot(key) s = key.index("{") if s e = key.index("}", s + 1) if e && e != s + 1 key = key[s + 1..e - 1] end end CRC16.crc16(key) % REDIS_CLUSTER_HASH_SLOTS end def call_with_redirection(slot, command, &block) nodes = @cluster_info.nodes.dup node = @cluster_info.slot_node(slot) || nodes.sample redirect_count = 0 connect_error_count = 0 connect_retry_count = 0 asking = false loop do nodes.delete(node) conn = fetch_connection(node) reply = conn.call(command, asking, &block) case reply when ConnectionAdapters::Reply::RedirectionError asking = reply.ask node = @cluster_info.add_node(reply.ip, reply.port) @refresh_slots ||= !asking redirect_count += 1 raise RedirectionError, "Too many redirections" if @options[:max_redirection] < redirect_count when ConnectionAdapters::Reply::ConnectionError connect_error_count += 1 raise reply.cause if @options[:max_connection_error] < connect_error_count if nodes.empty? connect_retry_count += 1 sleep(sleep_interval(connect_retry_count)) else asking = false node = nodes.sample end else return reply end end end def refresh_slots slots = nil @cluster_info.nodes.each do |node| conn = fetch_connection(node) reply = conn.call(["cluster", "slots"]) case reply when ConnectionAdapters::Reply::RedirectionError fail "never reach here" when ConnectionAdapters::Reply::ConnectionError if @logger @logger.warn("CLUSTER SLOTS command failed: node_name=#{node[:name]}, message=#{reply.cause}") end else slots = reply break end end return unless slots @cluster_info = ClusterInfo.new.tap do |cluster_info| cluster_info.load_slots(slots) end (@connections.keys - @cluster_info.node_names).each do |key| conn = @connections.delete(key) conn.close if conn end end def fetch_connection(node) name = node[:name] if conn = @connections[name] conn else @connections_mutex.synchronize do @connections[name] ||= @adapter_class.new(node[:host], node[:port], @options) end end end def sleep_interval(retry_count) factor = 1 + 2 * (rand - 0.5) * @options[:connect_retry_random_factor] factor * @options[:connect_retry_interval] * 2**(retry_count - 1) end end end
module Rlyeh VERSION = "0.0.2" end Version bump to 0.0.3 module Rlyeh VERSION = "0.0.3" end
module Rubbr class Options class << self include Rubbr::Cli def defaults root_dir = Dir.pwd source_dir = 'src' @defaults ||= { :root_dir => root_dir, :source_dir => source_dir, :build_dir => 'tmp', :distribution_dir => 'dist', :template_file => 'template.erb', :base_file => 'base', :vendor_dir => source_dir + '/vendor', :graphics_dir => source_dir + '/graphics', :spell_dir => source_dir, :spell_file => 'dictionary.ispell', :distribution_name => distribution_name(root_dir), :verbose => false, :format => :dvi, :engine => :latex } end # Fetching options from a config file if present and merges it # with the defaults. def setup preference_file = "#{defaults[:root_dir]}/config.yml" preferences = {} if File.exists? preference_file require 'yaml' File.open(preference_file) { |file| preferences = YAML.load(file) } end base_file_variations(absolute_paths(defaults.merge(preferences))) end private def distribution_name(root) name = File.basename(root) name << ".#{user_name}" if stats = Rubbr::Scm.stats(root) name << ".r#{stats[:revision].gsub(':', '_')}" end name end def user_name `whoami`.strip end def absolute_paths(options) relatives = %w(source_dir build_dir distribution_dir template_file vendor_dir graphics_dir spell_dir) relatives.each do |key| options[key.to_sym] = File.join(options[:root_dir], options[key.to_sym]) end options end def base_file_variations(options) options[:base_latex_file] = options[:base_file] + '.tex' options[:base_bibtex_file] = options[:base_file] + '.aux' options[:base_dvi_file] = options[:base_file] + '.dvi' options[:base_ps_file] = options[:base_file] + '.ps' options[:base_pdf_file] = options[:base_file] + '.pdf' options end end end end Template not used anymore. module Rubbr class Options class << self include Rubbr::Cli def defaults root_dir = Dir.pwd source_dir = 'src' @defaults ||= { :root_dir => root_dir, :source_dir => source_dir, :build_dir => 'tmp', :distribution_dir => 'dist', :base_file => 'base', :vendor_dir => source_dir + '/vendor', :graphics_dir => source_dir + '/graphics', :spell_dir => source_dir, :spell_file => 'dictionary.ispell', :distribution_name => distribution_name(root_dir), :verbose => false, :format => :dvi, :engine => :latex } end # Fetching options from a config file if present and merges it # with the defaults. def setup preference_file = "#{defaults[:root_dir]}/config.yml" preferences = {} if File.exists? preference_file require 'yaml' File.open(preference_file) { |file| preferences = YAML.load(file) } end base_file_variations(absolute_paths(defaults.merge(preferences))) end private def distribution_name(root) name = File.basename(root) name << ".#{user_name}" if stats = Rubbr::Scm.stats(root) name << ".r#{stats[:revision].gsub(':', '_')}" end name end def user_name `whoami`.strip end def absolute_paths(options) relatives = %w(source_dir build_dir distribution_dir vendor_dir graphics_dir spell_dir) relatives.each do |key| options[key.to_sym] = File.join(options[:root_dir], options[key.to_sym]) end options end def base_file_variations(options) options[:base_latex_file] = options[:base_file] + '.tex' options[:base_bibtex_file] = options[:base_file] + '.aux' options[:base_dvi_file] = options[:base_file] + '.dvi' options[:base_ps_file] = options[:base_file] + '.ps' options[:base_pdf_file] = options[:base_file] + '.pdf' options end end end end
require 'ruby-asterisk/version' require 'ruby-asterisk/request' require 'ruby-asterisk/response' require 'net/telnet' module RubyAsterisk ## # # Ruby-asterisk main classes # class AMI attr_accessor :host, :port, :connected def initialize(host, port) self.host = host.to_s self.port = port.to_i self.connected = false @session = nil end def connect begin @session = Net::Telnet::new('Host' => self.host, 'Port' => self.port, 'Timeout' => 10) self.connected = true rescue Exception => ex false end end def disconnect begin @session.close if self.connected self.connected = false true rescue Exception => ex puts ex false end end def login(username, password) self.connect unless self.connected execute 'Login', {'Username' => username, 'Secret' => password, 'Event' => 'On'} end def command(command) execute 'Command', {'Command' => command} end def core_show_channels execute 'CoreShowChannels' end def meet_me_list execute 'MeetMeList' end def parked_calls execute 'ParkedCalls' end def extension_state(exten, context, action_id = nil) execute 'ExtensionState', {'Exten' => exten, 'Context' => context, 'ActionID' => action_id} end def skinny_devices execute 'SKINNYdevices' end def skinny_lines execute 'SKINNYlines' end def status(channel = nil, action_id = nil) execute 'Status', {'Channel' => channel, 'ActionID' => action_id} end def originate(caller, context, callee, priority, variable = nil) execute 'Originate', {'Channel' => caller, 'Context' => context, 'Exten' => callee, 'Priority' => priority, 'Callerid' => caller, 'Timeout' => '30000', 'Variable' => variable } end def channels execute 'Command', { 'Command' => 'show channels' } end def redirect(caller,context,callee,priority,variable=nil) execute 'Redirect', {'Channel' => caller, 'Context' => context, 'Exten' => callee, 'Priority' => priority, 'Callerid' => caller, 'Timeout' => '30000', 'Variable' => variable} end def queues execute 'Queues', {} end def queue_add(queue, exten, penalty = 2, paused = false, member_name = '') execute 'QueueAdd', {'Queue' => queue, 'Interface' => exten, 'Penalty' => penalty, 'Paused' => paused, 'MemberName' => member_name} end def queue_pause(exten, paused) execute 'QueuePause', {'Interface' => exten, 'Paused' => paused} end def queue_remove(queue, exten) execute 'QueueRemove', {'Queue' => queue, 'Interface' => exten} end def queue_status execute 'QueueStatus' end def queue_summary(queue) execute 'QueueSummary', {'Queue' => queue} end def mailbox_status(exten, context='default') execute 'MailboxStatus', {'Mailbox' => "#{exten}@#{context}"} end def mailbox_count(exten, context='default') execute 'MailboxCount', {'Mailbox' => "#{exten}@#{context}"} end def queue_pause(interface,paused,queue,reason='none') execute 'QueuePause', {'Interface' => interface, 'Paused' => paused, 'Queue' => queue, 'Reason' => reason} end def ping execute 'Ping' end def event_mask(event_mask='off') execute 'Events', {'EventMask' => event_mask} end def sip_peers execute 'SIPpeers' end private def execute(command, options = {}) request = Request.new(command, options) request.commands.each do |command| @session.write(command) end @session.waitfor('Match' => /ActionID: #{request.action_id}.*?\n\n/m) do |data| request.response_data << data end Response.new(command, request.response_data) end end end Added originate_app require 'ruby-asterisk/version' require 'ruby-asterisk/request' require 'ruby-asterisk/response' require 'net/telnet' module RubyAsterisk ## # # Ruby-asterisk main classes # class AMI attr_accessor :host, :port, :connected def initialize(host, port) self.host = host.to_s self.port = port.to_i self.connected = false @session = nil end def connect begin @session = Net::Telnet::new('Host' => self.host, 'Port' => self.port, 'Timeout' => 10) self.connected = true rescue Exception => ex false end end def disconnect begin @session.close if self.connected self.connected = false true rescue Exception => ex puts ex false end end def login(username, password) self.connect unless self.connected execute 'Login', {'Username' => username, 'Secret' => password, 'Event' => 'On'} end def command(command) execute 'Command', {'Command' => command} end def core_show_channels execute 'CoreShowChannels' end def meet_me_list execute 'MeetMeList' end def parked_calls execute 'ParkedCalls' end def extension_state(exten, context, action_id = nil) execute 'ExtensionState', {'Exten' => exten, 'Context' => context, 'ActionID' => action_id} end def skinny_devices execute 'SKINNYdevices' end def skinny_lines execute 'SKINNYlines' end def status(channel = nil, action_id = nil) execute 'Status', {'Channel' => channel, 'ActionID' => action_id} end def originate(caller, context, callee, priority, variable = nil) execute 'Originate', {'Channel' => caller, 'Context' => context, 'Exten' => callee, 'Priority' => priority, 'Callerid' => caller, 'Timeout' => '30000', 'Variable' => variable } end def originate_app(caller, app, data, async) execute 'Originate', {'Channel' => caller, 'Application' => app, 'Data' => data, 'Timeout' => '30000', 'Async' => async } end def channels execute 'Command', { 'Command' => 'show channels' } end def redirect(caller,context,callee,priority,variable=nil) execute 'Redirect', {'Channel' => caller, 'Context' => context, 'Exten' => callee, 'Priority' => priority, 'Callerid' => caller, 'Timeout' => '30000', 'Variable' => variable} end def queues execute 'Queues', {} end def queue_add(queue, exten, penalty = 2, paused = false, member_name = '') execute 'QueueAdd', {'Queue' => queue, 'Interface' => exten, 'Penalty' => penalty, 'Paused' => paused, 'MemberName' => member_name} end def queue_pause(exten, paused) execute 'QueuePause', {'Interface' => exten, 'Paused' => paused} end def queue_remove(queue, exten) execute 'QueueRemove', {'Queue' => queue, 'Interface' => exten} end def queue_status execute 'QueueStatus' end def queue_summary(queue) execute 'QueueSummary', {'Queue' => queue} end def mailbox_status(exten, context='default') execute 'MailboxStatus', {'Mailbox' => "#{exten}@#{context}"} end def mailbox_count(exten, context='default') execute 'MailboxCount', {'Mailbox' => "#{exten}@#{context}"} end def queue_pause(interface,paused,queue,reason='none') execute 'QueuePause', {'Interface' => interface, 'Paused' => paused, 'Queue' => queue, 'Reason' => reason} end def ping execute 'Ping' end def event_mask(event_mask='off') execute 'Events', {'EventMask' => event_mask} end def sip_peers execute 'SIPpeers' end private def execute(command, options = {}) request = Request.new(command, options) request.commands.each do |command| @session.write(command) end @session.waitfor('Match' => /ActionID: #{request.action_id}.*?\n\n/m) do |data| request.response_data << data end Response.new(command, request.response_data) end end end
require 'ruby-sml/helpers' module SML module OBIS def resolve(obis) if SML::OBIS::Lookup[obis].nil? return SML::Helpers::hex_to_s(obis) else return SML::OBIS::Lookup[obis] end end Lookup = {} Lookup["\x81\x81\xc7\x82\x01\xff"] = "Device Properties Root" Lookup["\x81\x81\xc7\x82\x02\xff"] = "Device Class" Lookup["\x81\x81\xc7\x82\x03\xff"] = "Manufacturer" Lookup["\x81\x81\xc7\x82\x05\xff"] = "Public Key" Lookup["\x01\x00\x00\x00\x09\xff"] = "Device ID" Lookup["\x01\x00\x00\x02\x00\xff"] = "Firmware Version" Lookup["\x01\x00\x00\x02\x02\xff"] = "Control Program Nr" Lookup["\x81\x81\xc7\x89\xe1\xff"] = "Event log" Lookup["\x81\x81\xc7\x89\xe2\xff"] = "Event ID" Lookup["\x81\x81\xc7\x8c\x01\xff"] = "INFO interface active" Lookup["\x81\x81\xc7\x8c\x02\xff"] = "EDL40 mode" Lookup["\x81\x81\xc7\x8c\x03\xff"] = "Delete old usage values" Lookup["\x81\x81\xc7\x8c\x04\xff"] = "Display old usage values" Lookup["\x81\x81\xc7\x8c\x06\xff"] = "Display Text on INFO display" Lookup["\x81\x81\xc7\x8c\x07\xff"] = "Displayed Tariff Registers Bitmask" Lookup["\x81\x81\xc7\x8c\x08\xff"] = "Advanced Manufacturer Dataset on MSB" Lookup["\x81\x81\xc7\x8c\x09\xff"] = "History Delete via Blinken- Interface enabled" Lookup["\x81\x81\xc7\x8c\x0a\xff"] = "Display PIN Protected enabled" Lookup["\x81\x81\xc7\x8c\x0b\xff"] = "Display PIN Code" Lookup["\x81\x81\xc7\x8c\x0c\xff"] = "Number of Manipulation Attempts" Lookup["\x81\x81\xc7\x8c\x0d\xff"] = "Automatic PIN Protected after Timeout enabled" Lookup["\x01\x00\x01\x08\x00\xff"] = "Current Value - Overall Register" Lookup["\x01\x00\x01\x08\x01\xff"] = "Current Value - Register Tariff 1" Lookup["\x01\x00\x01\x08\x02\xff"] = "Current Value - Register Tariff 2" Lookup["\x01\x00\x01\x11\x00\xff"] = "Last signed overall Register Value" Lookup["\x01\x00\x0f\x07\x00\xff"] = "Current Meter Reading" Lookup["\x01\x00\x01\x08\x00\x60"] = "Usage History - last Day" Lookup["\x01\x00\x01\x08\x00\x61"] = "Usage History - last 7 Days" Lookup["\x01\x00\x01\x08\x00\x62"] = "Usage History - last 30 Days" Lookup["\x01\x00\x01\x08\x00\x63"] = "Usage History - last 365 Days" Lookup["\x01\x00\x00\x09\x0b\x00"] = "Current Time" Lookup["\x01\x00\x00\x09\x0b\x01"] = "Former Time" Lookup["\x00\x00\x60\x0e\x00\xff"] = "Selected Tariff" end end added a whole lot of OBIS numbers from MUC specs require 'ruby-sml/helpers' module SML module OBIS def resolve(obis) if SML::OBIS::Lookup[obis].nil? return SML::Helpers::hex_to_s(obis) else return SML::OBIS::Lookup[obis] end end Lookup = {} Lookup["\x81\x81\xc7\x82\x01\xff"] = "Device Properties Root" Lookup["\x81\x81\xc7\x82\x02\xff"] = "Device Class" Lookup["\x81\x81\xc7\x82\x03\xff"] = "Manufacturer" Lookup["\x81\x81\xc7\x82\x05\xff"] = "Public Key" Lookup["\x01\x00\x00\x00\x09\xff"] = "Device ID" Lookup["\x01\x00\x00\x02\x00\xff"] = "Firmware Version" Lookup["\x01\x00\x00\x02\x02\xff"] = "Control Program Nr" Lookup["\x81\x81\xc7\x89\xe1\xff"] = "Event Log" Lookup["\x81\x81\xc7\x89\xe2\xff"] = "Event ID" Lookup["\x81\x81\xc7\x8c\x01\xff"] = "INFO interface active" Lookup["\x81\x81\xc7\x8c\x02\xff"] = "EDL40 mode" Lookup["\x81\x81\xc7\x8c\x03\xff"] = "Delete old usage values" Lookup["\x81\x81\xc7\x8c\x04\xff"] = "Display old usage values" Lookup["\x81\x81\xc7\x8c\x06\xff"] = "Display Text on INFO display" Lookup["\x81\x81\xc7\x8c\x07\xff"] = "Displayed Tariff Registers Bitmask" Lookup["\x81\x81\xc7\x8c\x08\xff"] = "Advanced Manufacturer Dataset on MSB" Lookup["\x81\x81\xc7\x8c\x09\xff"] = "History Delete via Blinken- Interface enabled" Lookup["\x81\x81\xc7\x8c\x0a\xff"] = "Display PIN Protected enabled" Lookup["\x81\x81\xc7\x8c\x0b\xff"] = "Display PIN Code" Lookup["\x81\x81\xc7\x8c\x0c\xff"] = "Number of Manipulation Attempts" Lookup["\x81\x81\xc7\x8c\x0d\xff"] = "Automatic PIN Protected after Timeout enabled" Lookup["\x01\x00\x01\x08\x00\xff"] = "Current Value - Overall Register" Lookup["\x01\x00\x01\x08\x01\xff"] = "Current Value - Register Tariff 1" Lookup["\x01\x00\x01\x08\x02\xff"] = "Current Value - Register Tariff 2" Lookup["\x01\x00\x01\x11\x00\xff"] = "Last signed overall Register Value" Lookup["\x01\x00\x0f\x07\x00\xff"] = "Current Meter Reading" Lookup["\x01\x00\x01\x08\x00\x60"] = "Usage History - last Day" Lookup["\x01\x00\x01\x08\x00\x61"] = "Usage History - last 7 Days" Lookup["\x01\x00\x01\x08\x00\x62"] = "Usage History - last 30 Days" Lookup["\x01\x00\x01\x08\x00\x63"] = "Usage History - last 365 Days" Lookup["\x01\x00\x00\x09\x0b\x00"] = "Current Time" Lookup["\x01\x00\x00\x09\x0b\x01"] = "Former Time" Lookup["\x00\x00\x60\x08\x00\xff"] = "Seconds counter" Lookup["\x81\x00\x00\x09\x0b\x01"] = "Timezone Offset" Lookup["\x00\x00\x60\x0e\x00\xff"] = "Selected Tariff" Lookup["\x81\x81\x27\x32\x07\x01"] = "Log Entry Period" Lookup["\x81\x00\x60\x05\x00\x00"] = "Status word" Lookup["\x81\x01\x00\x00\x01\x00"] = "Interface name" Lookup["\x81\x03\x00\x00\x01\x00"] = "Interface name" Lookup["\x81\x81\x81\x60\xff\xff"] = "Rights and Roles Root" Lookup["\x81\x81\x81\x60\x01\xff"] = "Role" Lookup["\x81\x81\x81\x60\x02\xff"] = "Role" Lookup["\x81\x81\x81\x60\x03\xff"] = "Role" Lookup["\x81\x81\x81\x60\x04\xff"] = "Role" Lookup["\x81\x81\x81\x60\x05\xff"] = "Role" Lookup["\x81\x81\x81\x60\x06\xff"] = "Role" Lookup["\x81\x81\x81\x60\x07\xff"] = "Role" Lookup["\x81\x81\x81\x60\x08\xff"] = "Role" Lookup["\x81\x81\x81\x60\x01\x01"] = "Access Right" # actualle all of \x81\x81\x81\x60\x0[1-8]\x[01-fe] Lookup["\x81\x81\x81\x61\xff\xff"] = "Username" Lookup["\x81\x81\x81\x62\xff\xff"] = "Password" Lookup["\x81\x81\x81\x63\xff\xff"] = "Public Key for User Access" Lookup["\x81\x81\x81\x64\x01\x01"] = "ACL for Server ID" # actually all ending with \x01 to \xfe Lookup["\x81\x02\x00\x07\x00\xff"] = "Enduser Interface Root" Lookup["\x81\x02\x00\x07\x01\xff"] = "Enduser IP Acquisition Method" Lookup["\x81\x02\x17\x07\x00\x01"] = "Enduser manually assigned IP Address" Lookup["\x81\x02\x17\x07\x01\x01"] = "Enduser manually assigned Network Mask" Lookup["\x81\x02\x00\x07\x02\xff"] = "Enduser DHCP Server active" Lookup["\x81\x02\x00\x07\x02\x01"] = "Enduser DHCP Local Netmask" Lookup["\x81\x02\x00\x07\x02\x02"] = "Enduser DHCP Default Gateway" Lookup["\x81\x02\x00\x07\x02\x03"] = "Enduser DHCP DNS Server" Lookup["\x81\x02\x00\x07\x02\x04"] = "Enduser DHCP IP Pool Start" Lookup["\x81\x02\x00\x07\x02\x05"] = "Enduser DHCP IP Pool End" Lookup["\x81\x02\x00\x07\x10\xff"] = "Enduser Interface Status Root" Lookup["\x81\x02\x17\x07\x00\x00"] = "Enduser Current IP Address" Lookup["\x81\x04\x00\x06\x00\xff"] = "WAN Interface Status Root" Lookup["\x81\x04\x00\x00\x01\x00"] = "WAN Interface Name" Lookup["\x81\x04\x00\x02\x00\x00"] = "WAN Interface Firmware Version" Lookup["\x81\x04\x00\x07\x00\xff"] = "WAN Interface Parameter Root" Lookup["\x81\x04\x27\x32\x03\x01"] = "WAN Interface automatic Reboot" Lookup["\x81\x42\x64\x3c\x01\x01"] = "WAN Interface Max. Inter Message Timeout" Lookup["\x81\x42\x64\x3c\x01\x02"] = "WAN Interface Max. Timeout from Close-Request to Open-Response" Lookup["\x81\x04\x02\x07\x00\xff"] = "GSM Parameter Root" Lookup["\x81\x04\x00\x32\x01\x01"] = "GSM SIM PIN" Lookup["\x81\x04\x00\x32\x04\x01"] = "GSM Provider Selection Method" Lookup["\x81\x04\x00\x32\x08\x01"] = "GSM Bearer Service Type" Lookup["\x81\x04\x00\x32\x09\x01"] = "GSM Quality of Service" Lookup["\x81\x04\x27\x32\x01\x01"] = "GSM Max. Connection Length" Lookup["\x81\x04\x27\x32\x02\x01"] = "GSM Connection Idle Time" Lookup["\x81\x04\x31\x32\x01\x01"] = "GSM Number of Rings until Call pickup" Lookup["\x81\x49\x0d\x06\x00\xff"] = "IPT Status Root" Lookup["\x81\x49\x17\x07\x00\x00"] = "IPT Current Master Target IP Address" Lookup["\x81\x49\x1a\x07\x00\x00"] = "IPT Current Master Target Port" Lookup["\x81\x49\x19\x07\x00\x00"] = "IPT Current Master Source Port" Lookup["\x81\x49\x0d\x07\x00\xff"] = "IPT Parameter Root" Lookup["\x81\x49\x0d\x07\x00\x01"] = "IPT Primary Master Root" Lookup["\x81\x49\x17\x07\x00\x01"] = "IPT Primary Master Target IP Address" Lookup["\x81\x49\x1a\x07\x00\x01"] = "IPT Primary Master Target Port" Lookup["\x81\x49\x19\x07\x00\x01"] = "IPT Primary Master Source Port" Lookup["\x81\x49\x63\x3c\x01\x01"] = "IPT Primary Master Username" Lookup["\x81\x49\x63\x3c\x02\x01"] = "IPT Primary Master Password" Lookup["\x81\x49\x0d\x07\x00\x02"] = "IPT Secondary Master Root" Lookup["\x81\x49\x17\x07\x00\x02"] = "IPT Secondary Master Target IP Address" Lookup["\x81\x49\x1a\x07\x00\x02"] = "IPT Secondary Master Target Port" Lookup["\x81\x49\x19\x07\x00\x02"] = "IPT Secondary Master Source Port" Lookup["\x81\x49\x63\x3c\x01\x02"] = "IPT Secondary Master Username" Lookup["\x81\x49\x63\x3c\x02\x02"] = "IPT Secondary Master Password" Lookup["\x81\x48\x27\x32\x06\x01"] = "IPT Connection Retry Timeout" Lookup["\x81\x48\x31\x32\x02\x01"] = "IPT Max. Connection Retries" Lookup["\x81\x04\x00\x33\x01\xff"] = "AT-Hayes-Strings Root" Lookup["\x81\x04\x00\x33\x01\x01"] = "AT-Hayes-String after Modem Power-On, before PIN-Entry" Lookup["\x81\x04\x00\x33\x02\x01"] = "AT-Hayes-String after PIN-Entry" Lookup["\x81\x04\x00\x33\x03\x01"] = "AT-Hayes-String GPRS Initialization" end end
module Rubyc VERSION = "0.0.14" end bumping version module Rubyc VERSION = "0.0.14.alpha" end
# # Rubygame -- Ruby bindings to SDL to facilitate game creation # Copyright (C) 2004 John 'jacius' Croisant # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #Table of Contents: # #Rubygame.rect_from_object # #class Rect # GENERAL: # initialize # to_s # to_a, to_ary # [] # ATTRIBUTES: # x, y, w, h [<- accessors] # width, height, size # left, top, right, bottom # center, centerx, centery # topleft, topright # bottomleft, bottomright # midleft, midtop, midright, midbottom # METHODS: # clamp, clamp! # clip, clip! # collide_hash, collide_hash_all # collide_array, collide_array_all # collide_point? # collide_rect? # contain? # inflate, inflate! # move, move! # normalize, normalize! # union, union! # union_all, union_all! module Rubygame def rect_from_object(object,recurse=0) case(rect.class) when Rect return self.dup when Array if rect.length >= 4 return Rect.new(object) else raise ArgumentError( "Array does not have enough indexes to be made"+ "into a Rect (%d for 4)."%rect.length ) end else begin if recurse < 1 return Rubygame.rect_from_object(rect.rect,recurse+1) else raise TypeError("Object must be a Rect or Array [x,y,w,h], or have an attribute called 'rect'. Got %s instance."%rect.class) end rescue NoMethodError # if no rect.rect raise TypeError("Object must be a Rect or Array [x,y,w,h], or have an attribute called 'rect'. Got %s instance."%rect.class) end end # case end # def class Rect # All rect values must be integers def initialize(*argv) case argv.length when 1 if argv[0].kind_of? Rect; @x,@y,@w,@h = argv[0].to_a; elsif argv[0].kind_of? Array; @x,@y,@w,@h = argv[0]; elsif argv[0].respond_to? :rect; @x,@y,@w,@h=argv[0].rect.to_a; end when 2 @x,@y = argv[0] @w,@h = argv[1] when 4 @x,@y,@w,@h = argv end return self end def to_s; "Rect(%s,%s,%s,%s)"%[@x,@y,@w,@h]; end alias inspect to_s def to_a; [@x,@y,@w,@h]; end #alias to_ary to_a # causes problems with puts def [](i); self.to_a[i]; end def []=(i,value) case(i) when 0; @x = value when 1; @y = value when 2; @w = value when 3; @h = value return i end end def ==(other) other.to_a == self.to_a end ######################### #### RECT ATTRIBUTES #### ######################### attr_accessor :x, :y, :w, :h #Width -- expanded text of "w" alias width w alias width= w= #Height -- expanded text of "h" alias height h alias height= h= #Size def size; [@w, @h]; end def size=(size); @w, @h = size; return size; end #Left alias left x alias left= x= alias l left alias l= left= #Top alias top y alias top= y= alias t top alias t= top= #Right def right; @x+@w; end def right=(r); @x = r - @w; return r; end alias r right alias r= right= #Bottom def bottom; @y+@h; end def bottom=(b); @y = b - @h; return b; end alias b bottom alias b= bottom= #Center def center; [@x+@w/2, @y+@h/2]; end def center=(center) @x, @y = center[0]-@w/2, center[1]-@h/2 return center end alias c center alias c= center= #Centerx def centerx; @x+@w/2; end def centerx=(x); @x = x-@w/2; return x; end alias cx centerx alias cx= centerx= #Centery def centery; @y+@h/2; end def centery=(y); @y = y-@h/2; return y; end alias cy centery alias cy= centery= #TopLeft def topleft; [@x,@y]; end def topleft=(topleft) @x, @y = *topleft return topleft end alias tl topleft alias tl= topleft= #TopRight def topright; [@x+@w, @y]; end def topright=(topright) @x, @y = topright[0]-@w, topright[1] return topright end alias tr topright alias tr= topright= #BottomLeft def bottomleft; [@x, @y+@h]; end def bottomleft=(bottomleft) @x, @y = bottomleft[0], bottomleft[1]-@h return bottomleft end alias bl bottomleft alias bl= bottomleft= #BottomRight def bottomright; [@x+@w, @y+@h]; end def bottomright=(bottomright) @x, @y = bottomright[0]-@w, bottomright[1]-@h return bottomright end alias br bottomright alias br= bottomright= #MidLeft def midleft; [@x, @y+@h/2]; end def midleft=(midleft) @x, @y = midleft[0], midleft[1]-@h/2 return midleft end alias ml midleft alias ml= midleft= #MidTop def midtop; [@x+@w/2, @y]; end def midtop=(top) @x, @y = midleft[0]-@w/2, midleft[1] return midtop end alias mt midtop alias mt= midtop= #MidRight def midright; [@x+@w, @y+@h/2]; end def midright=(midleft) @x, @y = midleft[0]-@w, midleft[1]-@h/2 return midright end alias mr midright alias mr= midright= #MidBottom def midbottom; [@x+@w/2, @y+@h]; end def midbottom=(midbottom) @x, @y = midbottom[0]-@w/2, midbottom[1]-@h return midbottom end alias mb midbottom alias mb= midbottom= ######################### ##### RECT METHODS ##### ######################### def clamp(rect) self.dup.clamp!(rect) end def clamp!(rect) nself = self.normalize rect = rect_from_object(rect) #If self is inside given, there is no need to move self if not rect.contains(nself) #If self is too wide: if nself.w >= rect.w @x = rect.centerx - nself.w/2 #Else self is not too wide else #If self is to the left of arg if nself.x < rect.x @x = rect.x #If self is to the right of arg elsif nself.right > rect.right @x = rect.right - nself.w #Otherwise, leave x alone end end #If self is too tall: if nself.h >= rect.h @y = rect.centery - nself.h/2 #Else self is not too tall else #If self is above arg if nself.y < rect.y @y = rect.y #If self below arg elsif nself.bottom > rect.bottom @y = rect.bottom - nself.h #Otherwise, leave y alone end end end # if not rect.contains(self) return self end def clip(rect) self.dup.clip!(rect) end def clip!(rect) nself = self.normalize rect = rect_from_object(rect).normalize if self.collide_rect(rect) @x = min(nself.right, rect.right) - nself.x @h = min(nself.bottom, rect.bottom) - nself.y @x = max(nself.x, rect.x) @y = max(nself.y, rect.y) #if they do not intersect at all: else @x, @y = nself.topleft @w, @h = 0, 0 end return self end def collide_hash(hash_rects) hash_rects.each { |key,value| if value.colliderect(self); return [key,value]; end } return nil end def collide_hash_all(hash_rects) collection = [] hash_rects.each { |key,value| if value.colliderect(self); collection += [key,value]; end } return collection end def collide_array(array_rects) for i in 0..(array_rects.length) if array_rects[i].colliderect(self) return i end end return nil end def collide_array_all(array_rects) indexes = [] for i in 0..(array_rects.length) if array_rects[i].colliderect(self) indexes += [i] end end return indexes end def collide_point?(x,y=nil) begin if not y; x, y = x[0], x[1]; end rescue NoMethodError raise ArgumentError("You must pass either 2 Numerics or 1 Array.") end nself = self.normalize return ((nself.left..nself.right).include? x and (nself.top..nself.bottom).include? y) end def collide_rect?(rect) nself = self.normalize rect = rect_from_object(rect).normalize coll_horz = ((rect.left)..(rect.right)).include?(nself.left) or\ ((nself.left)..(nself.right)).include?(rect.left) coll_vert = ((rect.top)..(rect.bottom)).include?(nself.top) or\ ((nself.top)..(nself.bottom)).include?(rect.top) return (coll_horz and coll_vert) end def contain?(rect) nself = self.normalize rect = rect_from_object(rect).normalize return (nself.left <= rect.left and rect.right <= nself.right and nself.top <= rect.top and rect.bottom <= nself.bottom) end def inflate(x,y=nil) self.dup.inflate(x,y) end def inflate!(x,y=nil) begin if not y; x, y = x[0], x[1]; end rescue NoMethodError # x has no [] raise ArgumentError("You must pass either 2 Numerics or 1 Array.") end @x, @y = (@x - x/2), (@y - y/2) #if we just did x/2 or y/2 again, we would inflate it 1 pixel too #few if x or y is an odd number, due to rounding. @w, @h = (@w + (x-x/2)), (@w + (y-y/2)) return self end def move(x,y=nil) self.dup.move!(x,y) end def move!(x,y=nil) begin if not y; x, y = x[0], x[1]; end rescue NoMethodError # x has no [] raise ArgumentError("You must pass either 2 Numerics or 1 Array.") end @x+=x; @y+=y return self end def normalize self.dup.normalize() end def normalize! if @w < 0 @x, @w = @x+@w, -@w end if @h < 0 @y, @h = @y+@h, -@h end return self end def union(rect) self.dup.union!(rect) end def union!(rect) nself = self.normalize rect = rect_from_object(rect).normalize @x = min(nself.x, rect.x) @y = min(nself.y, rect.y) @w = max(nself.w, rect.w) @h = max(nself.h, rect.h) return self end def union_all(array_rects) self.dup.union_all!(array_rects) end def union_all!(array_rects) nself = self.normalize left = nself.left top = nself.top right = nself.right bottom = nself.bottom array_rects.each do |r| rect = rect_from_object(r).normalize left = min(left,rect.left) top = min(top,rect.top) right = min(right,rect.right) bottom = min(bottom,rect.bottom) end @x, @y = left, top @w, @h = right - left, bottom-top return self end end # class Rect end # module Rubygame - Fix Rect#[]=. return statement should be outside of case statement, should return value instead of index to be consistent with Array. - Add RDoc-style documentary comments. #-- # Rubygame -- Ruby bindings to SDL to facilitate game creation # Copyright (C) 2004 John 'jacius' Croisant # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #++ #Table of Contents: # #Rubygame.rect_from_object # #class Rect # GENERAL: # initialize # to_s # to_a, to_ary # [] # ATTRIBUTES: # x, y, w, h [<- accessors] # width, height, size # left, top, right, bottom # center, centerx, centery # topleft, topright # bottomleft, bottomright # midleft, midtop, midright, midbottom # METHODS: # clamp, clamp! # clip, clip! # collide_hash, collide_hash_all # collide_array, collide_array_all # collide_point? # collide_rect? # contain? # inflate, inflate! # move, move! # normalize, normalize! # union, union! # union_all, union_all! module Rubygame # Extract or generate a Rect from the given object, if possible, using the # following process: # # 1. If it's a Rect already, return a duplicate Rect. # 2. Elsif it's an Array with at least 4 values, make a Rect from it. # 3. Elsif it has a rect attribute, repeat this process on that attribute. # 4. Otherwise, raise TypeError. # def rect_from_object(object,recurse=0) case(rect.class) when Rect return self.dup when Array if rect.length >= 4 return Rect.new(object) else raise ArgumentError("Array does not have enough indices to be made into a Rect (%d for 4)."%rect.length ) end else begin if recurse < 1 return rect_from_object(rect.rect, recurse+1) else raise TypeError("Object must be a Rect or Array [x,y,w,h], or have an attribute called 'rect'. (Got %s instance)."%rect.class) end rescue NoMethodError # if no rect.rect raise TypeError("Object must be a Rect or Array [x,y,w,h], or have an attribute called 'rect'. (Got %s instance.)"%rect.class) end end # case end #-- # Maybe Rect should be based on Array? Haven't we been through this before? # Or was that with Sprite::Group... #++ # A Rect is a representation of a rectangle, with four core attributes # (x offset, y offset, width, and height) and a variety of functions # for manipulating and accessing these attributes. # # Like all coordinates in Rubygame (and its base library, SDL), x and y # offsets are measured from the top-left corner of the screen, with larger y # offsets being lower. Thus, specifying the x and y offsets of the Rect is # equivalent to setting the location of its top-left corner. # # In Rubygame, Rects are used for collision detection and describing # the area of a Surface to operate on. class Rect # Create a new Rect, attempting to extract its own information from # the given arguments. The arguments must fall into one of these cases: # # - 4 integers, +(x, y, w, h)+. # - 1 Array containing 4 integers, +([x, y, w, h])+. # - 2 Arrays containing 2 integers each, +([x,y], [w,h])+. # - 1 valid Rect object. # - 1 object with a +rect+ attribute (such as a Sprite) which is valid # Rect object. # # All rect core attributes (x,y,w,h) must be integers. # def initialize(*argv) case argv.length when 1 if argv[0].kind_of? Rect; @x,@y,@w,@h = argv[0].to_a; elsif argv[0].kind_of? Array; @x,@y,@w,@h = argv[0]; elsif argv[0].respond_to? :rect; @x,@y,@w,@h=argv[0].rect.to_a; end when 2 @x,@y = argv[0] @w,@h = argv[1] when 4 @x,@y,@w,@h = argv end return self end # Print the Rect in the form "+Rect(x,y,w,h)+" def to_s; "Rect(%s,%s,%s,%s)"%[@x,@y,@w,@h]; end alias inspect to_s # Return an Array of the form +[x,y,w,h]+ def to_a; [@x,@y,@w,@h]; end # Return the value of the Rect at the index as if it were an Array of the # form [x,y,w,h]. def [](i); self.to_a[i]; end # Set the value of the Rect at the index as if it were an Array of the form # [x,y,w,h]. def []=(i,value) case(i) when 0; @x = value when 1; @y = value when 2; @w = value when 3; @h = value end return value end # Convert the Rect and the other object to an Array (using #to_a) and # test equality. def ==(other) other.to_a == self.to_a end ############################ ##### RECT ATTRIBUTES ##### ############################ # Core attributes (x offset, y offset, width, height) attr_accessor :x, :y, :w, :h alias width w alias width= w=; alias height h alias height= h=; # Return the width and height of the Rect. def size; [@w, @h]; end # Set the width and height of the Rect. def size=(size); @w, @h = size; return size; end alias left x alias left= x=; alias l x alias l= x=; alias top y alias top= y=; alias t y alias t= y=; # Return the x coordinate of the right side of the Rect. def right; @x+@w; end # Set the x coordinate of the right side of the Rect by translating the # Rect (adjusting the x offset). def right=(r); @x = r - @w; return r; end alias r right alias r= right=; # Return the y coordinate of the bottom side of the Rect. def bottom; @y+@h; end # Set the y coordinate of the bottom side of the Rect by translating the # Rect (adjusting the y offset). def bottom=(b); @y = b - @h; return b; end alias b bottom alias b= bottom=; # Return the x and y coordinates of the center of the Rect. def center; [@x+@w/2, @y+@h/2]; end # Set the x and y coordinates of the center of the Rect by translating the # Rect (adjusting the x and y offsets). def center=(center) @x, @y = center[0]-@w/2, center[1]-@h/2 return center end alias c center alias c= center=; # Return the x coordinate of the center of the Rect def centerx; @x+@w/2; end # Set the x coordinate of the center of the Rect by translating the # Rect (adjusting the x offset). def centerx=(x); @x = x-@w/2; return x; end alias cx centerx alias cx= centerx=; # Return the y coordinate of the center of the Rect def centery; @y+@h/2; end # Set the y coordinate of the center of the Rect by translating the # Rect (adjusting the y offset). def centery=(y); @y = y-@h/2; return y; end alias cy centery alias cy= centery=; # Return the x and y coordinates of the top-left corner of the Rect def topleft; [@x,@y]; end # Set the x and y coordinates of the top-left corner of the Rect by # translating the Rect (adjusting the x and y offsets). def topleft=(topleft) @x, @y = *topleft return topleft end alias tl topleft alias tl= topleft=; # Return the x and y coordinates of the top-right corner of the Rect def topright; [@x+@w, @y]; end # Set the x and y coordinates of the top-right corner of the Rect by # translating the Rect (adjusting the x and y offsets). def topright=(topright) @x, @y = topright[0]-@w, topright[1] return topright end alias tr topright alias tr= topright=; # Return the x and y coordinates of the bottom-left corner of the Rect def bottomleft; [@x, @y+@h]; end # Set the x and y coordinates of the bottom-left corner of the Rect by # translating the Rect (adjusting the x and y offsets). def bottomleft=(bottomleft) @x, @y = bottomleft[0], bottomleft[1]-@h return bottomleft end alias bl bottomleft alias bl= bottomleft=; # Return the x and y coordinates of the bottom-right corner of the Rect def bottomright; [@x+@w, @y+@h]; end # Set the x and y coordinates of the bottom-right corner of the Rect by # translating the Rect (adjusting the x and y offsets). def bottomright=(bottomright) @x, @y = bottomright[0]-@w, bottomright[1]-@h return bottomright end alias br bottomright alias br= bottomright=; # Return the x and y coordinates of the midpoint on the left side of the # Rect. def midleft; [@x, @y+@h/2]; end # Set the x and y coordinates of the midpoint on the left side of the Rect # by translating the Rect (adjusting the x and y offsets). def midleft=(midleft) @x, @y = midleft[0], midleft[1]-@h/2 return midleft end alias ml midleft alias ml= midleft=; # Return the x and y coordinates of the midpoint on the left side of the # Rect. def midtop; [@x+@w/2, @y]; end # Set the x and y coordinates of the midpoint on the top side of the Rect # by translating the Rect (adjusting the x and y offsets). def midtop=(top) @x, @y = midleft[0]-@w/2, midleft[1] return midtop end alias mt midtop alias mt= midtop=; # Return the x and y coordinates of the midpoint on the left side of the # Rect. def midright; [@x+@w, @y+@h/2]; end # Set the x and y coordinates of the midpoint on the right side of the Rect # by translating the Rect (adjusting the x and y offsets). def midright=(midleft) @x, @y = midleft[0]-@w, midleft[1]-@h/2 return midright end alias mr midright alias mr= midright=; # Return the x and y coordinates of the midpoint on the left side of the # Rect. def midbottom; [@x+@w/2, @y+@h]; end # Set the x and y coordinates of the midpoint on the bottom side of the # Rect by translating the Rect (adjusting the x and y offsets). def midbottom=(midbottom) @x, @y = midbottom[0]-@w/2, midbottom[1]-@h return midbottom end alias mb midbottom alias mb= midbottom=; ######################### ##### RECT METHODS ##### ######################### # As #clamp!, but the original caller is not changed. def clamp(rect) self.dup.clamp!(rect) end # Translate the calling Rect to be entirely inside the given Rect. If the # caller is too large along either axis to fit in the given rect, it is # centered with respect to the given rect, along that axis. def clamp!(rect) nself = self.normalize rect = rect_from_object(rect) #If self is inside given, there is no need to move self if not rect.contains(nself) #If self is too wide: if nself.w >= rect.w @x = rect.centerx - nself.w/2 #Else self is not too wide else #If self is to the left of arg if nself.x < rect.x @x = rect.x #If self is to the right of arg elsif nself.right > rect.right @x = rect.right - nself.w #Otherwise, leave x alone end end #If self is too tall: if nself.h >= rect.h @y = rect.centery - nself.h/2 #Else self is not too tall else #If self is above arg if nself.y < rect.y @y = rect.y #If self below arg elsif nself.bottom > rect.bottom @y = rect.bottom - nself.h #Otherwise, leave y alone end end end # if not rect.contains(self) return self end # As #clip!, but the original caller is not changed. def clip(rect) self.dup.clip!(rect) end # Crop the calling Rect to be entirely inside the given Rect. If the caller # does not intersect the given Rect at all, its width and height are set # to zero, but its x and y offsets are not changed. # # As a side effect, the Rect is normalized. def clip!(rect) nself = self.normalize rect = rect_from_object(rect).normalize if self.collide_rect(rect) @x = min(nself.right, rect.right) - nself.x @h = min(nself.bottom, rect.bottom) - nself.y @x = max(nself.x, rect.x) @y = max(nself.y, rect.y) #if they do not intersect at all: else @x, @y = nself.topleft @w, @h = 0, 0 end return self end # Iterate through all key/value pairs in the given hash table, and return # the first pair whose value is a Rect that collides with the caller. # # Because a hash table is unordered, you should not expect any particular # Rect to be returned first, if more than one collides with the caller. def collide_hash(hash_rects) hash_rects.each { |key,value| if value.colliderect(self); return [key,value]; end } return nil end # Iterate through all key/value pairs in the given hash table, and return # an Array of every pair whose value is a Rect that collides with the # caller. # # Because a hash table is unordered, you should not expect the returned # pairs to be in any particular order. def collide_hash_all(hash_rects) collection = [] hash_rects.each { |key,value| if value.colliderect(self); collection += [key,value]; end } return collection end # Iterate through all elements in the given Array, and return # the *index* of the first element which is a Rect that collides with the # caller. def collide_array(array_rects) for i in 0..(array_rects.length) if array_rects[i].colliderect(self) return i end end return nil end # Iterate through all elements in the given Array, and return # an Array containing the *indices* of every element that is a Rect that # collides with the caller. def collide_array_all(array_rects) indexes = [] for i in 0..(array_rects.length) if array_rects[i].colliderect(self) indexes += [i] end end return indexes end # True if the point is inside (including on the border) of the caller. # The point can be given as either an Array or separate coordinates. def collide_point?(x,y=nil) begin if not y; x, y = x[0], x[1]; end rescue NoMethodError raise ArgumentError("You must pass either 2 Numerics or 1 Array.") end nself = self.normalize return ((nself.left..nself.right).include? x and (nself.top..nself.bottom).include? y) end # True if the caller and the given Rect overlap at all. def collide_rect?(rect) nself = self.normalize rect = Rubygame.rect_from_object(rect).normalize coll_horz = ((rect.left)..(rect.right)).include?(nself.left) or\ ((nself.left)..(nself.right)).include?(rect.left) coll_vert = ((rect.top)..(rect.bottom)).include?(nself.top) or\ ((nself.top)..(nself.bottom)).include?(rect.top) return (coll_horz and coll_vert) end # True if the given Rect is totally within the caller. Borders may touch. def contain?(rect) nself = self.normalize rect = rect_from_object(rect).normalize return (nself.left <= rect.left and rect.right <= nself.right and nself.top <= rect.top and rect.bottom <= nself.bottom) end # As #inflate!, but the original caller is not changed. def inflate(x,y=nil) self.dup.inflate!(x,y) end # Increase the Rect's size is the x and y directions, while keeping the # same center point. For best results, expand by an even number. # X and y inflation can be given as an Array or as separate values. def inflate!(x,y=nil) begin if not y; x, y = x[0], x[1]; end rescue NoMethodError # x has no [] raise ArgumentError("You must pass either 2 Numerics or 1 Array.") end @x, @y = (@x - x/2), (@y - y/2) #if we just did x/2 or y/2 again, we would inflate it 1 pixel too #few if x or y is an odd number, due to rounding. @w, @h = (@w + (x-x/2)), (@h + (y-y/2)) return self end # As #move!, but the original caller is not changed. def move(x,y=nil) self.dup.move!(x,y) end # Translate the Rect by the given amounts in the x and y directions. # Positive values are rightward for x and downward for y. # X and y movement can be given as an Array or as separate values. def move!(x,y=nil) begin if not y; x, y = x[0], x[1]; end rescue NoMethodError # x has no [] raise ArgumentError("You must pass either 2 Numerics or 1 Array.") end @x+=x; @y+=y return self end # As #normalize!, but the original caller is not changed. def normalize self.dup.normalize!() end # Fix Rects that have negative width or height, without changing the area # it represents. Has no effect on Rects with non-negative width and height. # Some Rect methods will automatically normalize the Rect. def normalize! if @w < 0 @x, @w = @x+@w, -@w end if @h < 0 @y, @h = @y+@h, -@h end return self end # As #union!, but the original caller is not changed. def union(rect) self.dup.union!(rect) end # Expand the caller to also cover the given Rect. The Rect is still a # rectangle,so it may also cover areas that neither of the original Rects # did, for example areas between the two Rects. def union!(rect) nself = self.normalize rect = rect_from_object(rect).normalize @x = min(nself.x, rect.x) @y = min(nself.y, rect.y) @w = max(nself.w, rect.w) @h = max(nself.h, rect.h) return self end # As #union_all!, but the original caller is not changed. def union_all(array_rects) self.dup.union_all!(array_rects) end # Expand the caller to cover all of the given Rects. See also #union! def union_all!(array_rects) nself = self.normalize left = nself.left top = nself.top right = nself.right bottom = nself.bottom array_rects.each do |r| rect = rect_from_object(r).normalize left = min(left,rect.left) top = min(top,rect.top) right = min(right,rect.right) bottom = min(bottom,rect.bottom) end @x, @y = left, top @w, @h = right - left, bottom-top return self end end # class Rect end # module Rubygame
module Rudy # = Rudy::Huxtable # # Huxtable gives access to instances for config, global, and logger to any # class that includes it. # # class Rudy::Hello # include Rudy::Huxtable # # def print_config # p @@config.defaults # {:nocolor => true, ...} # p @@global.verbose # => 1 # p @@logger.class # => StringIO # end # # end # module Huxtable extend self @@config = Rudy::Config.new @@global = Rudy::Global.new @@logger = StringIO.new # BUG: memory-leak for long-running apps def self.config; @@config; end def self.global; @@global; end def self.logger; @@logger; end def self.update_config(path=nil) @@config.verbose = (@@global.verbose >= 3) # -vvv # nil and bad paths sent to look_and_load are ignored @@config.look_and_load(path || @@global.config) @@global.apply_config(@@config) end def self.update_global(ghash); @@global.update(ghash); end def self.update_logger(logger); @@logger = logger; end def self.reset_config; @@config = Rudy::Config.new; end def self.reset_global; @@global = Rudy::Global.new; end def self.create_domain @sdb = Rudy::AWS::SDB.new(@@global.accesskey, @@global.secretkey, @@global.region) @sdb.create_domain Rudy::DOMAIN end def self.domain_exists? @sdb = Rudy::AWS::SDB.new(@@global.accesskey, @@global.secretkey, @@global.region) (@sdb.list_domains || []).member? Rudy::DOMAIN end def self.domain Rudy::DOMAIN end # Puts +msg+ to +@@logger+ def self.li(*msg); msg.each { |m| @@logger.puts m } if !@@global.quiet; end # Puts +msg+ to +@@logger+ if +Rudy.debug?+ returns true def self.ld(*msg); msg.each { |m| @@logger.puts "D: #{m}" } if Rudy.debug?; end # Puts +msg+ to +@@logger+ with "ERROR: " prepended def self.le(*msg); msg.each { |m| @@logger.puts " #{m}" }; end def li(*msg); Rudy::Huxtable.li *msg; end def ld(*msg); Rudy::Huxtable.ld *msg; end def le(*msg); Rudy::Huxtable.le *msg; end def config_dirname raise "No config paths defined" unless @@config.is_a?(Rudy::Config) && @@config.paths.is_a?(Array) base_dir = File.dirname @@config.paths.first raise "Config directory doesn't exist #{base_dir}" unless File.exists?(base_dir) base_dir end # Returns the name of the current keypair for the given user. # If there's a private key path in the config this will return # the basename (it's assumed the Amazon Keypair has the same # name as the file). Otherwise this returns the Rudy style # name: <tt>key-ZONE-ENV-ROLE-USER</tt>. Or if this the user is # root: <tt>key-ZONE-ENV-ROLE</tt> def user_keypairname(user=nil) user ||= current_machine_user path = defined_keypairpath user if path Huxtable.keypair_path_to_name(path) else n = (user.to_s == 'root') ? '' : "-#{user}" "key-%s-%s%s" % [@@global.zone, current_machine_group, n] end end def root_keypairname user_keypairname :root end def current_user_keypairname user_keypairname current_machine_user end def user_keypairpath(name=nil) name ||= current_machine_user path = defined_keypairpath name # If we can't find a user defined key, we'll # check the config path for a generated one. if path raise "Private key file not found (#{path})" unless File.exists?(path) path = File.expand_path(path) else ssh_key_dir = @@config.defaults.keydir || Rudy::SSH_KEY_DIR path = File.join(ssh_key_dir, user_keypairname(name)) end path end def root_keypairpath user_keypairpath :root end def current_user_keypairpath user_keypairpath current_machine_user end def defined_keypairpath(name=nil) name ||= current_machine_user raise Rudy::Error, "No user provided" unless name ## NOTE: I think it is more appropriate to return nil here ## than raise errors. This stuff should be checked already ##raise NoConfig unless @@config ##raise NoMachinesConfig unless @@config.machines ##raise NoGlobal unless @@global return unless @@global && @@config && @@config.machines zon, env, rol = @@global.zone, @@global.environment, @@global.role path = @@global.identity path ||= @@config.machines.find_deferred(zon, env, rol, [:users, name, :keypair]) path ||= @@config.machines.find_deferred(env, rol, [:users, name, :keypair]) path ||= @@config.machines.find_deferred(rol, [:users, name, :keypair]) path ||= @@config.machines.find_deferred(@@global.region, [:users, name, :keypair]) path end def current_machine_group [@@global.environment, @@global.role].join(Rudy::DELIM) end def current_group_name "grp-#{@@global.zone}-#{current_machine_group}" end def current_machine_count fetch_machine_param(:positions) || 1 end def current_machine_hostname # NOTE: There is an issue with Caesars that a keyword that has been # defined as forced_array (or forced_hash, etc...) is like that for # all subclasses of Caesars. There is a conflict between "hostname" # in the machines config and routines config. The routines config # parses hostname with forced_array because it's a shell command # in Rye::Cmd. Machines config expects just a symbol. The issue # is with Caesars so this is a workaround to return a symbol. hn = fetch_machine_param(:hostname) || :rudy hn = hn.flatten.compact.first if hn.is_a?(Array) hn end def current_machine_image fetch_machine_param(:ami) end def current_machine_os fetch_machine_param(:os) || 'linux' end def current_machine_size fetch_machine_param(:size) || 'm1.small' end def current_machine_address(position='01') raise NoConfig unless @@config raise NoMachinesConfig unless @@config.machines raise "Position cannot be nil" if position.nil? addresses = [fetch_machine_param(:addresses)].flatten.compact addresses[position.to_i-1] end # TODO: fix machine_group to include zone def current_machine_name [@@global.zone, current_machine_group, @@global.position].join(Rudy::DELIM) end def current_machine_user @@global.user || fetch_machine_param(:user) || @@config.defaults.user || Rudy.sysinfo.user end def current_machine_bucket @@global.bucket || fetch_machine_param(:bucket) || nil end def self.keypair_path_to_name(kp) return nil unless kp name = File.basename kp #name.gsub(/key-/, '') # We keep the key- now end # Looks for ENV-ROLE configuration in machines. There must be # at least one definition in the config for this to return true # That's how Rudy knows the current group is defined. def known_machine_group? raise NoConfig unless @@config return true if default_machine_group? raise NoMachinesConfig unless @@config.machines return false if !@@config && !@@global zon, env, rol = @@global.zone, @@global.environment, @@global.role conf = @@config.machines.find_deferred(@@global.region, zon, [env, rol]) conf ||= @@config.machines.find_deferred(zon, [env, rol]) !conf.nil? end private # We grab the appropriate routines config and check the paths # against those defined for the matching machine group. # Disks that appear in a routine but not in a machine will be # removed and a warning printed. Otherwise, the routines config # is merged on top of the machine config and that's what we return. # # This means that all the disk info is returned so we know what # size they are and stuff. # Return a hash: # # :after: # - :root: !ruby/object:Proc {} # - :rudy: !ruby/object:Proc {} # :disks: # :create: # /rudy/example1: # :device: /dev/sdr # :size: 2 # /rudy/example2: # :device: /dev/sdm # :size: 1 # # NOTE: dashes in +action+ are converted to underscores. We do this # because routine names are defined by method names and valid # method names don't use dashes. This way, we can use a dash on the # command-line which looks nicer (underscore still works of course). def fetch_routine_config(action) raise "No action specified" unless action raise NoConfig unless @@config raise NoRoutinesConfig unless @@config.routines raise NoGlobal unless @@global action = action.to_s.tr('-', '_') zon, env, rol = @@global.zone, @@global.environment, @@global.role disk_defs = fetch_machine_param(:disks) || {} # We want to find only one routines config with the name +action+. # This is unlike the routines config where it's okay to merge via # precedence. routine = @@config.routines.find_deferred(@@global.environment, @@global.role, action) routine ||= @@config.routines.find_deferred([@@global.environment, @@global.role], action) routine ||= @@config.routines.find_deferred(@@global.role, action) return nil unless routine return routine unless routine.has_key?(:disks) routine.disks.each_pair do |raction,disks| unless disks.kind_of?(Hash) li "#{raction} is not defined. Check your #{action} routines config.".color(:red) next end disks.each_pair do |path, props| unless disk_defs.has_key?(path) li "#{path} is not defined. Check your #{action} machines config.".color(:red) routine.disks[raction].delete(path) next end routine.disks[raction][path] = disk_defs[path].merge(props) end end routine end # Is +action+ a valid routine for the current machine group? def valid_routine?(action) !fetch_routine_config(action).nil? end def fetch_machine_param(parameter) raise "No parameter specified" unless parameter raise NoConfig unless @@config return if !@@config.machines && default_machine_group? raise NoMachinesConfig if !@@config.machines raise NoGlobal unless @@global top_level = @@config.machines.find(parameter) mc = fetch_machine_config || {} mc[parameter] || top_level || nil end # Returns true if this is the default machine environment and role def default_machine_group? default_env = @@config.defaults.environment || Rudy::DEFAULT_ENVIRONMENT default_rol = @@config.defaults.role || Rudy::DEFAULT_ROLE @@global.environment == default_env && @@global.role == default_rol end def fetch_machine_config raise NoConfig unless @@config raise NoMachinesConfig unless @@config.machines raise NoGlobal unless @@global zon, env, rol = @@global.zone, @@global.environment, @@global.role hashes = [] # This is fucked! hashes << @@config.machines.find(env, rol) hashes << @@config.machines.find(zon, env, rol) hashes << @@config.machines.find(zon, [env, rol]) hashes << @@config.machines.find(zon, env) hashes << @@config.machines.find(env) hashes << @@config.machines.find(zon) hashes << @@config.machines.find(rol) hashes << @@config.machines.find(@@global.region) compilation = {} hashes.reverse.each do |conf| compilation.merge! conf if conf end compilation = nil if compilation.empty? compilation end # Returns the appropriate config block from the machines config. # Also adds the following unless otherwise specified: # :region, :zone, :environment, :role, :position def fetch_script_config sconf = fetch_machine_param :config sconf ||= {} extras = { :region => @@global.region, :zone => @@global.zone, :environment => @@global.environment, :role => @@global.role, :position => @@global.position } sconf.merge! extras sconf end end end ADDED: Allow colons in place of dashes module Rudy # = Rudy::Huxtable # # Huxtable gives access to instances for config, global, and logger to any # class that includes it. # # class Rudy::Hello # include Rudy::Huxtable # # def print_config # p @@config.defaults # {:nocolor => true, ...} # p @@global.verbose # => 1 # p @@logger.class # => StringIO # end # # end # module Huxtable extend self @@config = Rudy::Config.new @@global = Rudy::Global.new @@logger = StringIO.new # BUG: memory-leak for long-running apps def self.config; @@config; end def self.global; @@global; end def self.logger; @@logger; end def self.update_config(path=nil) @@config.verbose = (@@global.verbose >= 3) # -vvv # nil and bad paths sent to look_and_load are ignored @@config.look_and_load(path || @@global.config) @@global.apply_config(@@config) end def self.update_global(ghash); @@global.update(ghash); end def self.update_logger(logger); @@logger = logger; end def self.reset_config; @@config = Rudy::Config.new; end def self.reset_global; @@global = Rudy::Global.new; end def self.create_domain @sdb = Rudy::AWS::SDB.new(@@global.accesskey, @@global.secretkey, @@global.region) @sdb.create_domain Rudy::DOMAIN end def self.domain_exists? @sdb = Rudy::AWS::SDB.new(@@global.accesskey, @@global.secretkey, @@global.region) (@sdb.list_domains || []).member? Rudy::DOMAIN end def self.domain Rudy::DOMAIN end # Puts +msg+ to +@@logger+ def self.li(*msg); msg.each { |m| @@logger.puts m } if !@@global.quiet; end # Puts +msg+ to +@@logger+ if +Rudy.debug?+ returns true def self.ld(*msg); msg.each { |m| @@logger.puts "D: #{m}" } if Rudy.debug?; end # Puts +msg+ to +@@logger+ with "ERROR: " prepended def self.le(*msg); msg.each { |m| @@logger.puts " #{m}" }; end def li(*msg); Rudy::Huxtable.li *msg; end def ld(*msg); Rudy::Huxtable.ld *msg; end def le(*msg); Rudy::Huxtable.le *msg; end def config_dirname raise "No config paths defined" unless @@config.is_a?(Rudy::Config) && @@config.paths.is_a?(Array) base_dir = File.dirname @@config.paths.first raise "Config directory doesn't exist #{base_dir}" unless File.exists?(base_dir) base_dir end # Returns the name of the current keypair for the given user. # If there's a private key path in the config this will return # the basename (it's assumed the Amazon Keypair has the same # name as the file). Otherwise this returns the Rudy style # name: <tt>key-ZONE-ENV-ROLE-USER</tt>. Or if this the user is # root: <tt>key-ZONE-ENV-ROLE</tt> def user_keypairname(user=nil) user ||= current_machine_user path = defined_keypairpath user if path Huxtable.keypair_path_to_name(path) else n = (user.to_s == 'root') ? '' : "-#{user}" "key-%s-%s%s" % [@@global.zone, current_machine_group, n] end end def root_keypairname user_keypairname :root end def current_user_keypairname user_keypairname current_machine_user end def user_keypairpath(name=nil) name ||= current_machine_user path = defined_keypairpath name # If we can't find a user defined key, we'll # check the config path for a generated one. if path raise "Private key file not found (#{path})" unless File.exists?(path) path = File.expand_path(path) else ssh_key_dir = @@config.defaults.keydir || Rudy::SSH_KEY_DIR path = File.join(ssh_key_dir, user_keypairname(name)) end path end def root_keypairpath user_keypairpath :root end def current_user_keypairpath user_keypairpath current_machine_user end def defined_keypairpath(name=nil) name ||= current_machine_user raise Rudy::Error, "No user provided" unless name ## NOTE: I think it is more appropriate to return nil here ## than raise errors. This stuff should be checked already ##raise NoConfig unless @@config ##raise NoMachinesConfig unless @@config.machines ##raise NoGlobal unless @@global return unless @@global && @@config && @@config.machines zon, env, rol = @@global.zone, @@global.environment, @@global.role path = @@global.identity path ||= @@config.machines.find_deferred(zon, env, rol, [:users, name, :keypair]) path ||= @@config.machines.find_deferred(env, rol, [:users, name, :keypair]) path ||= @@config.machines.find_deferred(rol, [:users, name, :keypair]) path ||= @@config.machines.find_deferred(@@global.region, [:users, name, :keypair]) path end def current_machine_group [@@global.environment, @@global.role].join(Rudy::DELIM) end def current_group_name "grp-#{@@global.zone}-#{current_machine_group}" end def current_machine_count fetch_machine_param(:positions) || 1 end def current_machine_hostname # NOTE: There is an issue with Caesars that a keyword that has been # defined as forced_array (or forced_hash, etc...) is like that for # all subclasses of Caesars. There is a conflict between "hostname" # in the machines config and routines config. The routines config # parses hostname with forced_array because it's a shell command # in Rye::Cmd. Machines config expects just a symbol. The issue # is with Caesars so this is a workaround to return a symbol. hn = fetch_machine_param(:hostname) || :rudy hn = hn.flatten.compact.first if hn.is_a?(Array) hn end def current_machine_image fetch_machine_param(:ami) end def current_machine_os fetch_machine_param(:os) || 'linux' end def current_machine_size fetch_machine_param(:size) || 'm1.small' end def current_machine_address(position='01') raise NoConfig unless @@config raise NoMachinesConfig unless @@config.machines raise "Position cannot be nil" if position.nil? addresses = [fetch_machine_param(:addresses)].flatten.compact addresses[position.to_i-1] end # TODO: fix machine_group to include zone def current_machine_name [@@global.zone, current_machine_group, @@global.position].join(Rudy::DELIM) end def current_machine_user @@global.user || fetch_machine_param(:user) || @@config.defaults.user || Rudy.sysinfo.user end def current_machine_bucket @@global.bucket || fetch_machine_param(:bucket) || nil end def self.keypair_path_to_name(kp) return nil unless kp name = File.basename kp #name.gsub(/key-/, '') # We keep the key- now end # Looks for ENV-ROLE configuration in machines. There must be # at least one definition in the config for this to return true # That's how Rudy knows the current group is defined. def known_machine_group? raise NoConfig unless @@config return true if default_machine_group? raise NoMachinesConfig unless @@config.machines return false if !@@config && !@@global zon, env, rol = @@global.zone, @@global.environment, @@global.role conf = @@config.machines.find_deferred(@@global.region, zon, [env, rol]) conf ||= @@config.machines.find_deferred(zon, [env, rol]) !conf.nil? end private # We grab the appropriate routines config and check the paths # against those defined for the matching machine group. # Disks that appear in a routine but not in a machine will be # removed and a warning printed. Otherwise, the routines config # is merged on top of the machine config and that's what we return. # # This means that all the disk info is returned so we know what # size they are and stuff. # Return a hash: # # :after: # - :root: !ruby/object:Proc {} # - :rudy: !ruby/object:Proc {} # :disks: # :create: # /rudy/example1: # :device: /dev/sdr # :size: 2 # /rudy/example2: # :device: /dev/sdm # :size: 1 # # NOTE: dashes in +action+ are converted to underscores. We do this # because routine names are defined by method names and valid # method names don't use dashes. This way, we can use a dash on the # command-line which looks nicer (underscore still works of course). def fetch_routine_config(action) raise "No action specified" unless action raise NoConfig unless @@config raise NoRoutinesConfig unless @@config.routines raise NoGlobal unless @@global action = action.to_s.tr('-:', '_') zon, env, rol = @@global.zone, @@global.environment, @@global.role disk_defs = fetch_machine_param(:disks) || {} # We want to find only one routines config with the name +action+. # This is unlike the routines config where it's okay to merge via # precedence. routine = @@config.routines.find_deferred(@@global.environment, @@global.role, action) routine ||= @@config.routines.find_deferred([@@global.environment, @@global.role], action) routine ||= @@config.routines.find_deferred(@@global.role, action) return nil unless routine return routine unless routine.has_key?(:disks) routine.disks.each_pair do |raction,disks| unless disks.kind_of?(Hash) li "#{raction} is not defined. Check your #{action} routines config.".color(:red) next end disks.each_pair do |path, props| unless disk_defs.has_key?(path) li "#{path} is not defined. Check your #{action} machines config.".color(:red) routine.disks[raction].delete(path) next end routine.disks[raction][path] = disk_defs[path].merge(props) end end routine end # Is +action+ a valid routine for the current machine group? def valid_routine?(action) !fetch_routine_config(action).nil? end def fetch_machine_param(parameter) raise "No parameter specified" unless parameter raise NoConfig unless @@config return if !@@config.machines && default_machine_group? raise NoMachinesConfig if !@@config.machines raise NoGlobal unless @@global top_level = @@config.machines.find(parameter) mc = fetch_machine_config || {} mc[parameter] || top_level || nil end # Returns true if this is the default machine environment and role def default_machine_group? default_env = @@config.defaults.environment || Rudy::DEFAULT_ENVIRONMENT default_rol = @@config.defaults.role || Rudy::DEFAULT_ROLE @@global.environment == default_env && @@global.role == default_rol end def fetch_machine_config raise NoConfig unless @@config raise NoMachinesConfig unless @@config.machines raise NoGlobal unless @@global zon, env, rol = @@global.zone, @@global.environment, @@global.role hashes = [] # This is fucked! hashes << @@config.machines.find(env, rol) hashes << @@config.machines.find(zon, env, rol) hashes << @@config.machines.find(zon, [env, rol]) hashes << @@config.machines.find(zon, env) hashes << @@config.machines.find(env) hashes << @@config.machines.find(zon) hashes << @@config.machines.find(rol) hashes << @@config.machines.find(@@global.region) compilation = {} hashes.reverse.each do |conf| compilation.merge! conf if conf end compilation = nil if compilation.empty? compilation end # Returns the appropriate config block from the machines config. # Also adds the following unless otherwise specified: # :region, :zone, :environment, :role, :position def fetch_script_config sconf = fetch_machine_param :config sconf ||= {} extras = { :region => @@global.region, :zone => @@global.zone, :environment => @@global.environment, :role => @@global.role, :position => @@global.position } sconf.merge! extras sconf end end end
# encoding: utf-8 require 'fileutils' require 'yajl' require 'haml' require 'i18n' require 'sinatra/base' require 'file/tail' require 'runit-man/helpers' require 'runit-man/version' if RUBY_VERSION >= '1.9' Encoding.default_external = "utf-8" Encoding.default_internal = "utf-8" end class RunitMan::App < Sinatra::Base MIN_TAIL = 100 MAX_TAIL = 10000 GEM_FOLDER = File.expand_path(File.join('..', '..'), File.dirname(__FILE__)).freeze CONTENT_TYPES = { :html => 'text/html', :txt => 'text/plain', :css => 'text/css', :js => 'application/x-javascript', :json => 'application/json' }.freeze DEFAULT_LOGGER = 'svlogd'.freeze DEFAULT_ALL_SERVICES_DIR = '/etc/sv'.freeze DEFAULT_ACTIVE_SERVICES_DIR = '/etc/service'.freeze set :environment, :production set :root, GEM_FOLDER enable :logging, :dump_errors, :static disable :raise_errors helpers do include Helpers def readonly? @read_write_mode == :readonly end def sendfile? !!File.instance_methods.detect { |m| "#{m}" == 'trysendfile' } end end def self.i18n_location File.join(GEM_FOLDER, 'i18n') end def self.setup_i18n_files files = [] Dir.glob("#{i18n_location}/*.yml") do |full_path| next unless File.file?(full_path) files << full_path end I18n.load_path = files I18n.reload! nil end configure do RunitMan::App.setup_i18n_files haml_options = { :ugly => true } haml_options[:encoding] = 'utf-8' if defined?(Encoding) set :haml, haml_options end before do case RunitMan::App.runit_logger when RunitMan::App::DEFAULT_LOGGER; ServiceInfo.klass = ServiceInfo::Svlogd else ServiceInfo.klass = ServiceInfo::Logger end @read_write_mode = RunitMan::App.read_write_mode @scripts = [] base_content_type = CONTENT_TYPES.keys.detect do |t| request.env['REQUEST_URI'] =~ /\.#{Regexp.escape(t.to_s)}$/ end || :html content_type CONTENT_TYPES[base_content_type], :charset => 'utf-8' headers({ 'X-Powered-By' => 'runit-man', 'X-Version' => RunitMan::VERSION }) parse_language(request.env['HTTP_ACCEPT_LANGUAGE']) end def setup_i18n(locales) locales.each do |locale| if I18n.available_locales.include?(locale) I18n.locale = locale break end end end def parse_language(header) weighted_locales = [] if header header.split(',').each do |s| if s =~ /^(.+)\;q\=(\d(?:\.\d)?)$/ weighted_locales << { :locale => $1.to_sym, :weight => $2.to_f } else weighted_locales << { :locale => s.to_sym, :weight => 1.0 } end end end weighted_locales << { :locale => :en, :weight => 0.0 } if weighted_locales.length >= 2 weighted_locales.sort! do |a, b| b[:weight] <=> a[:weight] end end locales = weighted_locales.map { |wl| wl[:locale] } setup_i18n(locales) end get '/' do @scripts = %w[ jquery-1.7.2.min runit-man ] @title = host_name haml :index end get '/info' do @server = env['SERVER_SOFTWARE'] @large_files = !!(@server =~ /rainbows/i) @rack_version = Rack.release @sendfile = sendfile? && @large_files haml :info end get '/services' do partial :services end get '/services.json' do Yajl::Encoder.encode(service_infos) end def log_of_service_n(filepath, count, no) text = '' if File.readable?(filepath) File::Tail::Logfile.open(filepath, :backward => count, :return_if_eof => true) do |log| log.tail do |line| text += line end end end { :location => filepath, :text => text, :id => no } end def log_of_service(name, count, no) count = count.to_i count = MIN_TAIL if count < MIN_TAIL count = MAX_TAIL if count > MAX_TAIL srv = ServiceInfo.klass[name] return nil if srv.nil? || !srv.logged? logs = [] if no.nil? srv.log_file_locations.each_with_index do |filepath, no| logs << log_of_service_n(filepath, count, no) end else filepath = srv.log_file_locations[no] return nil if filepath.nil? logs << log_of_service_n(filepath, count, no) end { :name => name, :count => count, :logs => logs } end def data_of_file_view(request) if !request.GET.has_key?('file') return nil end file_path = request.GET['file'] return nil unless all_files_to_view.include?(file_path) text = IO.read(file_path) { :name => file_path, :text => text } end get %r[\A/([^/]+)/log(?:/(\d+))?/?\z] do |name, count| data = log_of_service(name, count, nil) return not_found if data.nil? @title = t('runit.services.log.title', :name => name, :host => host_name, :count => count) haml :log, :locals => data end get %r[\A/([^/]+)/log(?:/(\d+))?/(\d+)\.txt\z] do |name, d1, d2| if d2 count, no = d1, d2 else count, no = nil, d1 end no = no.to_i data = log_of_service(name, count, no) return not_found if data.nil? data[:logs][no][:text] end get %r[\A/([^/]+)/log\-downloads/?\z] do |name| srv = ServiceInfo.klass[name] return not_found if srv.nil? || !srv.logged? haml :log_downloads, :locals => { :name => name, :files => srv.all_log_file_locations } end get %r[\A/([^/]+)/log\-download/(.+)\z] do |name, file_name| srv = ServiceInfo.klass[name] return not_found if srv.nil? || !srv.logged? f = srv.all_log_file_locations.detect { |f| f[:name] == file_name } return not_found unless f send_file(f[:path], :type => 'text/plain', :disposition => 'attachment', :filename => f[:label], :last_modified => f[:modified].httpdate) end get '/view' do data = data_of_file_view(request) return not_found if data.nil? @title = t('runit.view_file.title', :file => data[:name], :host => host_name) content_type CONTENT_TYPES[:html], :charset => 'utf-8' haml :view_file, :locals => data end get '/view.txt' do data = data_of_file_view(request) return not_found if data.nil? content_type CONTENT_TYPES[:txt], :charset => 'utf-8' data[:text] end def log_action(name, text) env = request.env log "#{addr} - - [#{Time.now}] \"Do #{text} on #{name}\"" end def log_denied_action(name, text) env = request.env log "#{addr} - - [#{Time.now}] \"Receive #{text} for #{name}. Denied.\"" end post '/:name/signal/:signal' do |name, signal| unless readonly? service = ServiceInfo.klass[name] return not_found if service.nil? service.send_signal(signal) log_action(name, "send signal \"#{signal}\"") else log_denied_action(name, "signal \"#{signal}\"") end '' end post '/:name/:action' do |name, action| unless readonly? service = ServiceInfo.klass[name] action = "#{action}!".to_sym return not_found if service.nil? || !service.respond_to?(action) service.send(action) log_action(name, action) else log_denied_action(name, action) end '' end class << self def exec_rackup(command) ENV['RUNIT_ALL_SERVICES_DIR'] = RunitMan::App.all_services_directory ENV['RUNIT_ACTIVE_SERVICES_DIR'] = RunitMan::App.active_services_directory ENV['RUNIT_LOGGER'] = RunitMan::App.runit_logger ENV['RUNIT_MAN_VIEW_FILES'] = RunitMan::App.files_to_view.join(',') ENV['RUNIT_MAN_CREDENTIALS'] = RunitMan::App.allowed_users.keys.map { |user| "#{user}:#{RunitMan.allowed_users[user]}" }.join(',') ENV['RUNIT_MAN_READWRITE_MODE'] = RunitMan::App.read_write_mode.to_s Dir.chdir(File.dirname(__FILE__)) exec(command) end def register_as_runit_service all_r_dir = File.join(RunitMan::App.all_services_directory, 'runit-man') active_r_dir = File.join(RunitMan::App.active_services_directory, 'runit-man') my_dir = File.join(GEM_FOLDER, 'sv') log_dir = File.join(all_r_dir, 'log') if File.symlink?(all_r_dir) File.unlink(all_r_dir) end unless File.directory?(all_r_dir) FileUtils.mkdir_p(log_dir) create_log_run_script(all_r_dir) end create_run_script(all_r_dir) unless File.symlink?(active_r_dir) File.symlink(all_r_dir, active_r_dir) end end def enable_view_of(file_location) files_to_view << File.expand_path(file_location, '/') end def add_user(name, password) allowed_users[name] = password end def files_to_view @files_to_view ||= [] end def allowed_users @allowed_users ||= {} end def prepare_to_run unless allowed_users.empty? use Rack::Auth::Basic, 'runit-man' do |username, password| allowed_users.include?(username) && allowed_users[username] == password end end end private def create_run_script(dir) require 'erb' script_name = File.join(dir, 'run') template_name = File.join(GEM_FOLDER, 'sv', 'run.erb') all_services_directory = RunitMan::App.all_services_directory active_services_directory = RunitMan::App.active_services_directory port = RunitMan::App.port bind = RunitMan::App.bind server = RunitMan::App.server files_to_view = RunitMan::App.files_to_view logger = RunitMan::App.runit_logger auth = RunitMan::App.allowed_users rackup_command_line = RunitMan::App.rackup_command_line read_write_mode = RunitMan::App.read_write_mode.to_s File.open(script_name, 'w') do |script_source| script_source.print ERB.new(IO.read(template_name)).result(binding()) end File.chmod(0755, script_name) end def create_log_run_script(dir) require 'erb' script_name = File.join(dir, 'log', 'run') template_name = File.join(GEM_FOLDER, 'sv', 'log', 'run.erb') logger = RunitMan::App.runit_logger File.open(script_name, 'w') do |script_source| script_source.print ERB.new(IO.read(template_name)).result(binding()) end File.chmod(0755, script_name) end end end Fix credentials setup for --rackup option. closes #6. # encoding: utf-8 require 'fileutils' require 'yajl' require 'haml' require 'i18n' require 'sinatra/base' require 'file/tail' require 'runit-man/helpers' require 'runit-man/version' if RUBY_VERSION >= '1.9' Encoding.default_external = "utf-8" Encoding.default_internal = "utf-8" end class RunitMan::App < Sinatra::Base MIN_TAIL = 100 MAX_TAIL = 10000 GEM_FOLDER = File.expand_path(File.join('..', '..'), File.dirname(__FILE__)).freeze CONTENT_TYPES = { :html => 'text/html', :txt => 'text/plain', :css => 'text/css', :js => 'application/x-javascript', :json => 'application/json' }.freeze DEFAULT_LOGGER = 'svlogd'.freeze DEFAULT_ALL_SERVICES_DIR = '/etc/sv'.freeze DEFAULT_ACTIVE_SERVICES_DIR = '/etc/service'.freeze set :environment, :production set :root, GEM_FOLDER enable :logging, :dump_errors, :static disable :raise_errors helpers do include Helpers def readonly? @read_write_mode == :readonly end def sendfile? !!File.instance_methods.detect { |m| "#{m}" == 'trysendfile' } end end def self.i18n_location File.join(GEM_FOLDER, 'i18n') end def self.setup_i18n_files files = [] Dir.glob("#{i18n_location}/*.yml") do |full_path| next unless File.file?(full_path) files << full_path end I18n.load_path = files I18n.reload! nil end configure do RunitMan::App.setup_i18n_files haml_options = { :ugly => true } haml_options[:encoding] = 'utf-8' if defined?(Encoding) set :haml, haml_options end before do case RunitMan::App.runit_logger when RunitMan::App::DEFAULT_LOGGER; ServiceInfo.klass = ServiceInfo::Svlogd else ServiceInfo.klass = ServiceInfo::Logger end @read_write_mode = RunitMan::App.read_write_mode @scripts = [] base_content_type = CONTENT_TYPES.keys.detect do |t| request.env['REQUEST_URI'] =~ /\.#{Regexp.escape(t.to_s)}$/ end || :html content_type CONTENT_TYPES[base_content_type], :charset => 'utf-8' headers({ 'X-Powered-By' => 'runit-man', 'X-Version' => RunitMan::VERSION }) parse_language(request.env['HTTP_ACCEPT_LANGUAGE']) end def setup_i18n(locales) locales.each do |locale| if I18n.available_locales.include?(locale) I18n.locale = locale break end end end def parse_language(header) weighted_locales = [] if header header.split(',').each do |s| if s =~ /^(.+)\;q\=(\d(?:\.\d)?)$/ weighted_locales << { :locale => $1.to_sym, :weight => $2.to_f } else weighted_locales << { :locale => s.to_sym, :weight => 1.0 } end end end weighted_locales << { :locale => :en, :weight => 0.0 } if weighted_locales.length >= 2 weighted_locales.sort! do |a, b| b[:weight] <=> a[:weight] end end locales = weighted_locales.map { |wl| wl[:locale] } setup_i18n(locales) end get '/' do @scripts = %w[ jquery-1.7.2.min runit-man ] @title = host_name haml :index end get '/info' do @server = env['SERVER_SOFTWARE'] @large_files = !!(@server =~ /rainbows/i) @rack_version = Rack.release @sendfile = sendfile? && @large_files haml :info end get '/services' do partial :services end get '/services.json' do Yajl::Encoder.encode(service_infos) end def log_of_service_n(filepath, count, no) text = '' if File.readable?(filepath) File::Tail::Logfile.open(filepath, :backward => count, :return_if_eof => true) do |log| log.tail do |line| text += line end end end { :location => filepath, :text => text, :id => no } end def log_of_service(name, count, no) count = count.to_i count = MIN_TAIL if count < MIN_TAIL count = MAX_TAIL if count > MAX_TAIL srv = ServiceInfo.klass[name] return nil if srv.nil? || !srv.logged? logs = [] if no.nil? srv.log_file_locations.each_with_index do |filepath, no| logs << log_of_service_n(filepath, count, no) end else filepath = srv.log_file_locations[no] return nil if filepath.nil? logs << log_of_service_n(filepath, count, no) end { :name => name, :count => count, :logs => logs } end def data_of_file_view(request) if !request.GET.has_key?('file') return nil end file_path = request.GET['file'] return nil unless all_files_to_view.include?(file_path) text = IO.read(file_path) { :name => file_path, :text => text } end get %r[\A/([^/]+)/log(?:/(\d+))?/?\z] do |name, count| data = log_of_service(name, count, nil) return not_found if data.nil? @title = t('runit.services.log.title', :name => name, :host => host_name, :count => count) haml :log, :locals => data end get %r[\A/([^/]+)/log(?:/(\d+))?/(\d+)\.txt\z] do |name, d1, d2| if d2 count, no = d1, d2 else count, no = nil, d1 end no = no.to_i data = log_of_service(name, count, no) return not_found if data.nil? data[:logs][no][:text] end get %r[\A/([^/]+)/log\-downloads/?\z] do |name| srv = ServiceInfo.klass[name] return not_found if srv.nil? || !srv.logged? haml :log_downloads, :locals => { :name => name, :files => srv.all_log_file_locations } end get %r[\A/([^/]+)/log\-download/(.+)\z] do |name, file_name| srv = ServiceInfo.klass[name] return not_found if srv.nil? || !srv.logged? f = srv.all_log_file_locations.detect { |f| f[:name] == file_name } return not_found unless f send_file(f[:path], :type => 'text/plain', :disposition => 'attachment', :filename => f[:label], :last_modified => f[:modified].httpdate) end get '/view' do data = data_of_file_view(request) return not_found if data.nil? @title = t('runit.view_file.title', :file => data[:name], :host => host_name) content_type CONTENT_TYPES[:html], :charset => 'utf-8' haml :view_file, :locals => data end get '/view.txt' do data = data_of_file_view(request) return not_found if data.nil? content_type CONTENT_TYPES[:txt], :charset => 'utf-8' data[:text] end def log_action(name, text) env = request.env log "#{addr} - - [#{Time.now}] \"Do #{text} on #{name}\"" end def log_denied_action(name, text) env = request.env log "#{addr} - - [#{Time.now}] \"Receive #{text} for #{name}. Denied.\"" end post '/:name/signal/:signal' do |name, signal| unless readonly? service = ServiceInfo.klass[name] return not_found if service.nil? service.send_signal(signal) log_action(name, "send signal \"#{signal}\"") else log_denied_action(name, "signal \"#{signal}\"") end '' end post '/:name/:action' do |name, action| unless readonly? service = ServiceInfo.klass[name] action = "#{action}!".to_sym return not_found if service.nil? || !service.respond_to?(action) service.send(action) log_action(name, action) else log_denied_action(name, action) end '' end class << self def exec_rackup(command) ENV['RUNIT_ALL_SERVICES_DIR'] = RunitMan::App.all_services_directory ENV['RUNIT_ACTIVE_SERVICES_DIR'] = RunitMan::App.active_services_directory ENV['RUNIT_LOGGER'] = RunitMan::App.runit_logger ENV['RUNIT_MAN_VIEW_FILES'] = RunitMan::App.files_to_view.join(',') ENV['RUNIT_MAN_CREDENTIALS'] = RunitMan::App.allowed_users.keys.map { |user| "#{user}:#{RunitMan::App.allowed_users[user]}" }.join(',') ENV['RUNIT_MAN_READWRITE_MODE'] = RunitMan::App.read_write_mode.to_s Dir.chdir(File.dirname(__FILE__)) exec(command) end def register_as_runit_service all_r_dir = File.join(RunitMan::App.all_services_directory, 'runit-man') active_r_dir = File.join(RunitMan::App.active_services_directory, 'runit-man') my_dir = File.join(GEM_FOLDER, 'sv') log_dir = File.join(all_r_dir, 'log') if File.symlink?(all_r_dir) File.unlink(all_r_dir) end unless File.directory?(all_r_dir) FileUtils.mkdir_p(log_dir) create_log_run_script(all_r_dir) end create_run_script(all_r_dir) unless File.symlink?(active_r_dir) File.symlink(all_r_dir, active_r_dir) end end def enable_view_of(file_location) files_to_view << File.expand_path(file_location, '/') end def add_user(name, password) allowed_users[name] = password end def files_to_view @files_to_view ||= [] end def allowed_users @allowed_users ||= {} end def prepare_to_run unless allowed_users.empty? use Rack::Auth::Basic, 'runit-man' do |username, password| allowed_users.include?(username) && allowed_users[username] == password end end end private def create_run_script(dir) require 'erb' script_name = File.join(dir, 'run') template_name = File.join(GEM_FOLDER, 'sv', 'run.erb') all_services_directory = RunitMan::App.all_services_directory active_services_directory = RunitMan::App.active_services_directory port = RunitMan::App.port bind = RunitMan::App.bind server = RunitMan::App.server files_to_view = RunitMan::App.files_to_view logger = RunitMan::App.runit_logger auth = RunitMan::App.allowed_users rackup_command_line = RunitMan::App.rackup_command_line read_write_mode = RunitMan::App.read_write_mode.to_s File.open(script_name, 'w') do |script_source| script_source.print ERB.new(IO.read(template_name)).result(binding()) end File.chmod(0755, script_name) end def create_log_run_script(dir) require 'erb' script_name = File.join(dir, 'log', 'run') template_name = File.join(GEM_FOLDER, 'sv', 'log', 'run.erb') logger = RunitMan::App.runit_logger File.open(script_name, 'w') do |script_source| script_source.print ERB.new(IO.read(template_name)).result(binding()) end File.chmod(0755, script_name) end end end
# encoding: UTF-8 require 'logger' require 'pty' require 'expect' module Sambal class Client attr_reader :connected def initialize(options={}) begin options = {domain: 'WORKGROUP', host: '127.0.0.1', share: '', user: 'guest', password: '--no-pass', port: 445, timeout: 10}.merge(options) @timeout = options[:timeout].to_i @o, @i, @pid = PTY.spawn("smbclient \"//#{options[:host]}/#{options[:share]}\" '#{options[:password]}' -W \"#{options[:domain]}\" -U \"#{options[:user]}\" -p #{options[:port]}") #@o.set_encoding('UTF-8:UTF-8') ## don't know didn't work, we only have this problem when the files are named using non-english characters #@i.set_encoding('UTF-8:UTF-8') res = @o.expect(/(.*\n)?smb:.*\\>/, @timeout)[0] rescue nil @connected = case res when nil $stderr.puts "Failed to connect" false when /^put/ res['putting'].nil? ? false : true else if res['NT_STATUS'] false elsif res['timed out'] || res['Server stopped'] false else true end end unless @connected close if @pid exit(1) end rescue Exception => e raise RuntimeError.exception("Unknown Process Failed!! (#{$!.to_s}): #{e.message.inspect}\n"+e.backtrace.join("\n")) end end def logger @logger ||= Logger.new(STDOUT) end def logger=(l) @logger = l end def file_context(path) if (path_parts = path.split('/')).length>1 file = path_parts.pop subdirs = path_parts.length dir = path_parts.join('/') cd dir else file = path end begin yield(file) ensure unless subdirs.nil? subdirs.times { cd '..' } end end end def ls(qualifier = '*') parse_files(ask_wrapped('ls', qualifier)) end def cd(dir) response = ask("cd \"#{dir}\"") if response.split("\r\n").join('') =~ /NT_STATUS_OBJECT_NAME_NOT_FOUND/ Response.new(response, false) else Response.new(response, true) end end def get(file, output) begin file_context(file) do |file| response = ask_wrapped 'get', [file, output] if response =~ /^getting\sfile.*$/ Response.new(response, true) else Response.new(response, false) end end rescue InternalError => e Response.new(e.message, false) end end def put(file, destination) response = ask_wrapped 'put', [file, destination] if response =~ /^putting\sfile.*$/ Response.new(response, true) else Response.new(response, false) end rescue InternalError => e Response.new(e.message, false) end def put_content(content, destination) t = Tempfile.new("upload-smb-content-#{destination}") File.open(t.path, 'w') do |f| f << content end response = ask_wrapped 'put', [t.path, destination] if response =~ /^putting\sfile.*$/ Response.new(response, true) else Response.new(response, false) end rescue InternalError => e Response.new(e.message, false) ensure t.close end def mkdir(directory) return Response.new('directory name is empty', false) if directory.strip.empty? response = ask_wrapped('mkdir', directory) if response =~ /NT_STATUS_OBJECT_NAME_(INVALID|COLLISION)/ Response.new(response, false) else Response.new(response, true) end end def rmdir(dir) response = cd dir return response if response.failure? begin ls.each do |name, meta| if meta[:type]==:file response = del name elsif meta[:type]==:directory && !(name =~ /^\.+$/) response = rmdir(name) end raise InternalError.new response.message if response && response.failure? end cd '..' response = ask_wrapped 'rmdir', dir next_line = response.split("\n")[1] if next_line =~ /^smb:.*\\>/ Response.new(response, true) else Response.new(response, false) end rescue InternalError => e Response.new(e.message, false) end end def del(file) begin file_context(file) do |file| response = ask_wrapped 'del', file next_line = response.split("\n")[1] if next_line =~ /^smb:.*\\>/ Response.new(response, true) #elsif next_line =~ /^NT_STATUS_NO_SUCH_FILE.*$/ # Response.new(response, false) #elsif next_line =~ /^NT_STATUS_ACCESS_DENIED.*$/ # Response.new(response, false) else Response.new(response, false) end end rescue InternalError => e Response.new(e.message, false) end #end #if (path_parts = file.split('/')).length>1 # file = path_parts.pop # subdirs = path_parts.length # dir = path_parts.join('/') # cd dir #end # response = ask "del #{file}" # next_line = response.split("\n")[1] # if next_line =~ /^smb:.*\\>/ # Response.new(response, true) # #elsif next_line =~ /^NT_STATUS_NO_SUCH_FILE.*$/ # # Response.new(response, false) # #elsif next_line =~ /^NT_STATUS_ACCESS_DENIED.*$/ # # Response.new(response, false) # else # Response.new(response, false) # end #rescue InternalError => e # Response.new(e.message, false) #ensure # unless subdirs.nil? # subdirs.times { cd '..' } # end end def close @i.close @o.close Process.wait(@pid) @connected = false end def ask(cmd) @i.printf("#{cmd}\n") response = @o.expect(/^smb:.*\\>/,@timeout)[0] rescue nil if response.nil? $stderr.puts "Failed to do #{cmd}" raise Exception.new, "Failed to do #{cmd}" else response end end def ask_wrapped(cmd,filenames) ask wrap_filenames(cmd,filenames) end def wrap_filenames(cmd,filenames) filenames = [filenames] unless filenames.kind_of?(Array) filenames.map!{ |filename| "\"#{filename}\"" } [cmd,filenames].flatten.join(' ') end def parse_files(str) files = {} str.each_line do |line| if line =~ /\s+([\w\.\d\-\_\?\!\s]+)\s+([DAH]?)\s+(\d+)\s+(.+)$/ lsplit = line.split(/\s{2,}/) #$stderr.puts "lsplit: #{lsplit}" lsplit.shift ## remove first empty string name = lsplit.shift#$1 if lsplit.first =~ /^[A-Za-z]+$/ type = lsplit.shift else type = "" end size = lsplit.shift#$3 date = lsplit.join(' ')#$4 name.gsub!(/\s+$/,'') files[name] = if type =~/^D.*$/ {type: :directory, size: size, modified: (Time.parse(date) rescue "!!#{date}")} else {type: :file, size: size , modified: (Time.parse(date) rescue "!!#{date}")} end end end files end end end fix working with long(then more 80 charters) path of folders/files PTY terminal has restriction of columns length (default = 80 charters) by each command row. So after row has more than 80 characters terminal switch to new line (set special symbols) and method 'getc' in IO.expect method can not read these "special symbols' from terminal # encoding: UTF-8 require 'logger' require 'pty' require 'expect' module Sambal class Client attr_reader :connected def initialize(options={}) begin options = {domain: 'WORKGROUP', host: '127.0.0.1', share: '', user: 'guest', password: '--no-pass', port: 445, timeout: 10, columns: 80}.merge(options) @timeout = options[:timeout].to_i @o, @i, @pid = PTY.spawn("COLUMNS=#{options[:columns]} smbclient \"//#{options[:host]}/#{options[:share]}\" '#{options[:password]}' -W \"#{options[:domain]}\" -U \"#{options[:user]}\" -p #{options[:port]}") res = @o.expect(/(.*\n)?smb:.*\\>/, @timeout)[0] rescue nil @connected = case res when nil $stderr.puts "Failed to connect" false when /^put/ res['putting'].nil? ? false : true else if res['NT_STATUS'] false elsif res['timed out'] || res['Server stopped'] false else true end end unless @connected close if @pid exit(1) end rescue Exception => e raise RuntimeError.exception("Unknown Process Failed!! (#{$!.to_s}): #{e.message.inspect}\n"+e.backtrace.join("\n")) end end def logger @logger ||= Logger.new(STDOUT) end def logger=(l) @logger = l end def file_context(path) if (path_parts = path.split('/')).length>1 file = path_parts.pop subdirs = path_parts.length dir = path_parts.join('/') cd dir else file = path end begin yield(file) ensure unless subdirs.nil? subdirs.times { cd '..' } end end end def ls(qualifier = '*') parse_files(ask_wrapped('ls', qualifier)) end def cd(dir) response = ask("cd \"#{dir}\"") if response.split("\r\n").join('') =~ /NT_STATUS_OBJECT_NAME_NOT_FOUND/ Response.new(response, false) else Response.new(response, true) end end def get(file, output) begin file_context(file) do |file| response = ask_wrapped 'get', [file, output] if response =~ /^getting\sfile.*$/ Response.new(response, true) else Response.new(response, false) end end rescue InternalError => e Response.new(e.message, false) end end def put(file, destination) response = ask_wrapped 'put', [file, destination] if response =~ /^putting\sfile.*$/ Response.new(response, true) else Response.new(response, false) end rescue InternalError => e Response.new(e.message, false) end def put_content(content, destination) t = Tempfile.new("upload-smb-content-#{destination}") File.open(t.path, 'w') do |f| f << content end response = ask_wrapped 'put', [t.path, destination] if response =~ /^putting\sfile.*$/ Response.new(response, true) else Response.new(response, false) end rescue InternalError => e Response.new(e.message, false) ensure t.close end def mkdir(directory) return Response.new('directory name is empty', false) if directory.strip.empty? response = ask_wrapped('mkdir', directory) if response =~ /NT_STATUS_OBJECT_NAME_(INVALID|COLLISION)/ Response.new(response, false) else Response.new(response, true) end end def rmdir(dir) response = cd dir return response if response.failure? begin ls.each do |name, meta| if meta[:type]==:file response = del name elsif meta[:type]==:directory && !(name =~ /^\.+$/) response = rmdir(name) end raise InternalError.new response.message if response && response.failure? end cd '..' response = ask_wrapped 'rmdir', dir next_line = response.split("\n")[1] if next_line =~ /^smb:.*\\>/ Response.new(response, true) else Response.new(response, false) end rescue InternalError => e Response.new(e.message, false) end end def del(file) begin file_context(file) do |file| response = ask_wrapped 'del', file next_line = response.split("\n")[1] if next_line =~ /^smb:.*\\>/ Response.new(response, true) #elsif next_line =~ /^NT_STATUS_NO_SUCH_FILE.*$/ # Response.new(response, false) #elsif next_line =~ /^NT_STATUS_ACCESS_DENIED.*$/ # Response.new(response, false) else Response.new(response, false) end end rescue InternalError => e Response.new(e.message, false) end #end #if (path_parts = file.split('/')).length>1 # file = path_parts.pop # subdirs = path_parts.length # dir = path_parts.join('/') # cd dir #end # response = ask "del #{file}" # next_line = response.split("\n")[1] # if next_line =~ /^smb:.*\\>/ # Response.new(response, true) # #elsif next_line =~ /^NT_STATUS_NO_SUCH_FILE.*$/ # # Response.new(response, false) # #elsif next_line =~ /^NT_STATUS_ACCESS_DENIED.*$/ # # Response.new(response, false) # else # Response.new(response, false) # end #rescue InternalError => e # Response.new(e.message, false) #ensure # unless subdirs.nil? # subdirs.times { cd '..' } # end end def close @i.close @o.close Process.wait(@pid) @connected = false end def ask(cmd) @i.printf("#{cmd}\n") response = @o.expect(/^smb:.*\\>/,@timeout)[0] rescue nil if response.nil? $stderr.puts "Failed to do #{cmd}" raise Exception.new, "Failed to do #{cmd}" else response end end def ask_wrapped(cmd,filenames) ask wrap_filenames(cmd,filenames) end def wrap_filenames(cmd,filenames) filenames = [filenames] unless filenames.kind_of?(Array) filenames.map!{ |filename| "\"#{filename}\"" } [cmd,filenames].flatten.join(' ') end def parse_files(str) files = {} str.each_line do |line| if line =~ /\s+([\w\.\d\-\_\?\!\s]+)\s+([DAH]?)\s+(\d+)\s+(.+)$/ lsplit = line.split(/\s{2,}/) #$stderr.puts "lsplit: #{lsplit}" lsplit.shift ## remove first empty string name = lsplit.shift#$1 if lsplit.first =~ /^[A-Za-z]+$/ type = lsplit.shift else type = "" end size = lsplit.shift#$3 date = lsplit.join(' ')#$4 name.gsub!(/\s+$/,'') files[name] = if type =~/^D.*$/ {type: :directory, size: size, modified: (Time.parse(date) rescue "!!#{date}")} else {type: :file, size: size , modified: (Time.parse(date) rescue "!!#{date}")} end end end files end end end
class Scash VERSION = "0.2.3" end Bump version class Scash VERSION = "0.2.4" end
require 'cgi' require 'nokogiri' require 'base64' require 'namae' require 'ostruct' require_relative 'helpers' class SearchResult include Sinatra::Search include Sinatra::Session attr_accessor :date, :year, :month, :day, :title, :publication, :authors, :volume, :issue, :first_page, :last_page, :type, :subtype, :doi, :score, :normal_score, :citations, :hashed, :related, :alternate, :version, :rights_uri, :subject, :description, :creative_commons, :contributor, :contributor_type, :contributors_with_type, :grant_info, :related_identifiers, :combined_related attr_reader :hashed, :doi, :title_escaped, :xml # Merge a mongo DOI record with solr highlight information. def initialize(solr_doc, solr_result, citations, user_state, related_identifiers) @doi = solr_doc.fetch('doi') @type = solr_doc.fetch('resourceTypeGeneral', nil) @subtype = solr_doc.fetch('resourceType', nil) @doc = solr_doc @score = solr_doc.fetch('score', nil).to_i @normal_score = (@score / solr_result.fetch('response', {}).fetch('maxScore', 1) * 100).to_i @citations = citations @hashed = solr_doc.fetch('mongo_id', nil) @user_claimed = user_state.fetch(:claimed, false) @in_user_profile = user_state.fetch(:in_profile, false) @highlights = solr_result.fetch('highlighting', {}) @publication = find_value('publisher') @title = solr_doc.fetch('title', [""]).first.strip description = solr_doc.fetch('description', []).first @description = description.to_s.truncate_words(100).gsub(/\\n\\n/, "<br/>") @date = solr_doc.fetch('date', []).last @year = find_value('publicationYear') @month = solr_doc['month'] ? MONTH_SHORT_NAMES[solr_doc['month'] - 1] : (@date && @date.size > 6 ? MONTH_SHORT_NAMES[@date[5..6].to_i - 1] : nil) @day = solr_doc['day'] || @date && @date.size > 9 ? @date[8..9].to_i : nil # @volume = find_value('hl_volume') # @issue = find_value('hl_issue') # @authors = find_value('creator') # @first_page = find_value('hl_first_page') # @last_page = find_value('hl_last_page') @rights_uri = Array(solr_doc.fetch('rightsURI', nil)) @related = solr_doc.fetch('relatedIdentifier', nil) @related_identifiers = related_identifiers @alternate = solr_doc.fetch('alternateIdentifier', nil) @version = solr_doc.fetch('version', nil) @contributor = Array(solr_doc.fetch('contributor', [])) @contributor_type = Array(solr_doc.fetch('contributorType', [])) xml = Base64.decode64(solr_doc.fetch('xml', "PGhzaD48L2hzaD4=\n")).force_encoding('UTF-8') @xml = Hash.from_xml(xml).fetch("resource", {}) @authors = @xml.fetch("creators", {}).fetch("creator", []) @authors = [@authors] if @authors.is_a?(Hash) # Insert/update record in MongoDB # Hack Alert (possibly) MongoData.coll('dois').update({ doi: @doi }, { doi: @doi, title: @title, type: @type, subtype: @subtype, publication: @publication, contributor: @authors, published: { year: @year, month: @month, day: @day } }, { upsert: true }) end def title_escaped title.gsub("'", %q(\\\')) if title.present? end def open_access? @doc['oa_status'] == 'Open Access' end def creative_commons if rights_uri.find { |uri| /licenses\/by-nc-nd\// =~ uri } 'by-nc-nd' elsif rights_uri.find { |uri| /licenses\/by-nc-sa\// =~ uri } 'by-nc-sa' elsif rights_uri.find { |uri| /licenses\/by-nc\// =~ uri } 'by-nc' elsif rights_uri.find { |uri| /licenses\/by-sa\// =~ uri } 'by-sa' elsif rights_uri.find { |uri| /licenses\/by\// =~ uri } 'by' elsif rights_uri.find { |uri| /publicdomain\/zero/ =~ uri } 'zero' else nil end end def contributors_with_type contributor_type.zip(contributor).map { |c| {c[0] => c[1] }} end def contributors_by_type(type) contributors_with_type.map do |hsh| hsh.select { |key, value| key == type } end end def grant_info contributors_by_type("Funder").map { |c| c["Funder"] }.compact.uniq end def related Array(@related).map do |item| { relation: item.split(':', 3)[0], id: item.split(':', 3)[1], text: item.split(':', 3)[2], source: "Datacite" } end.select { |item| item[:text].present? && item[:id] =~ /(DOI|URL)/ } end def combined_related (related + related_identifiers).group_by { |item| item[:relation] } end def alternate Array(@alternate).map do |item| { id: item.split(':', 2)[0], text: item.split(':', 2)[1] } end.select { |item| item[:id] !~ /citation/ } end def authors Array(@authors).map do |author| creator_name = author.fetch("creatorName", nil) names = Namae.parse(creator_name) name = names.first || OpenStruct.new(family: nil, given: nil, literal: creator_name) credit_name = name.family ? [name.given, name.family].join(" ") : name.literal { "family" => name.family, "given" => name.given, "credit-name" => credit_name, "id" => author.fetch("nameIdentifier", nil) } end end def authors_as_string authors[0..19].map do |author| author["id"].present? ? "<a href=\"/?q=#{author["id"]}\">#{author["credit-name"]}</a>" : author["credit-name"] end.join(", ") end def parse_author(name) # revert order if single words, separated by comma name = name.split(',') if name.all? { |i| i.split(' ').size > 1 } name.join(', ') else name.reverse.join(' ') end end def user_claimed? @user_claimed end def in_user_profile? @in_user_profile end def coins_atitle @title || '' end def coins_title @doc['hl_publication'] end def coins_year @year end def coins_volume @doc['hl_volume'] end def coins_issue @doc['hl_issue'] end def coins_spage @doc['hl_first_page'] end def coins_lpage @doc['hl_last_page'] end def coins_authors if @authors authors_as_string else '' end end def coins_au_first @doc['first_author_given'] end def coins_au_last @doc['first_author_surname'] end def coins props = { 'ctx_ver' => 'Z39.88-2004', 'rft_id' => "info:doi/#{@doi}", 'rfr_id' => 'info:sid/datacite.org:search', 'rft.atitle' => coins_atitle, 'rft.jtitle' => coins_title, 'rft.date' => coins_year, 'rft.volume' => coins_volume, 'rft.issue' => coins_issue, 'rft.spage' => coins_spage, 'rft.epage' => coins_lpage, 'rft.aufirst' => coins_au_first, 'rft.aulast' => coins_au_last } case @type when 'journal_article' props['rft_val_fmt'] = 'info:ofi/fmt:kev:mtx:journal' props['rft.genre'] = 'article' when 'conference_paper' props['rft_val_fmt'] = 'info:ofi/fmt:kev:mtx:journal' props['rft.genre'] = 'proceeding' when 'Dataset' props['rft_val_fmt'] = 'info:ofi/fmt:kev:mtx:dc' props['rft.genre'] = 'dataset' when 'Collection' props['rft_val_fmt'] = 'info:ofi/fmt:kev:mtx:dc' props['rft.genre'] = 'collection' when 'Text' props['rft_val_fmt'] = 'info:ofi/fmt:kev:mtx:dc' props['rft.genre'] = 'text' when 'Software' props['rft_val_fmt'] = 'info:ofi/fmt:kev:mtx:dc' props['rft.genre'] = 'software' else props['rft_val_fmt'] = 'info:ofi/fmt:kev:mtx:dc' props['rft.genre'] = 'unknown' end title_parts = [] props.reject { |_, value| value.nil? }.each_pair do |key, value| title_parts << "#{key}=#{CGI.escape(value.to_s)}" end title = title_parts.join('&') coins_authors.split(',').each { |author| title += "&rft.au=#{CGI.escape(author.strip)}" } if coins_authors CGI.escapeHTML title end def coins_span "<span class=\"Z3988\" title=\"#{coins}\"><!-- coins --></span>" end # Mimic SIGG citation format. def citation a = [] a << CGI.escapeHTML(coins_authors) unless coins_authors.empty? a << CGI.escapeHTML(coins_year.to_s) unless coins_year.nil? a << "'#{CGI.escapeHTML(coins_atitle)}'" unless coins_atitle.nil? a << "<i>#{CGI.escapeHTML(coins_title)}</i>" unless coins_title.nil? a << "vol. #{CGI.escapeHTML(coins_volume)}" unless coins_volume.nil? a << "no. #{CGI.escapeHTML(coins_issue)}" unless coins_issue.nil? if !coins_spage.nil? && !coins_lpage.nil? a << "pp. #{CGI.escapeHTML(coins_spage)}-#{CGI.escapeHTML(coins_lpage)}" elsif !coins_spage.nil? a << "p. #{CGI.escapeHTML(coins_spage)}" end a.join ', ' end def has_path?(hash, path) path_found = true path.each do |node| if hash.key?(node) && !hash[node].nil? hash = hash[node] else path_found = false break end end path_found end def find_value(key) if has_path? @highlights, [@doi, key] @highlights[@doi][key].first else @doc[key] end end end properly handle organization. #42 require 'cgi' require 'nokogiri' require 'base64' require 'namae' require 'ostruct' require_relative 'helpers' class SearchResult include Sinatra::Search include Sinatra::Session attr_accessor :date, :year, :month, :day, :title, :publication, :authors, :volume, :issue, :first_page, :last_page, :type, :subtype, :doi, :score, :normal_score, :citations, :hashed, :related, :alternate, :version, :rights_uri, :subject, :description, :creative_commons, :contributor, :contributor_type, :contributors_with_type, :grant_info, :related_identifiers, :combined_related attr_reader :hashed, :doi, :title_escaped, :xml # Merge a mongo DOI record with solr highlight information. def initialize(solr_doc, solr_result, citations, user_state, related_identifiers) @doi = solr_doc.fetch('doi') @type = solr_doc.fetch('resourceTypeGeneral', nil) @subtype = solr_doc.fetch('resourceType', nil) @doc = solr_doc @score = solr_doc.fetch('score', nil).to_i @normal_score = (@score / solr_result.fetch('response', {}).fetch('maxScore', 1) * 100).to_i @citations = citations @hashed = solr_doc.fetch('mongo_id', nil) @user_claimed = user_state.fetch(:claimed, false) @in_user_profile = user_state.fetch(:in_profile, false) @highlights = solr_result.fetch('highlighting', {}) @publication = find_value('publisher') @title = solr_doc.fetch('title', [""]).first.strip description = solr_doc.fetch('description', []).first @description = description.to_s.truncate_words(100).gsub(/\\n\\n/, "<br/>") @date = solr_doc.fetch('date', []).last @year = find_value('publicationYear') @month = solr_doc['month'] ? MONTH_SHORT_NAMES[solr_doc['month'] - 1] : (@date && @date.size > 6 ? MONTH_SHORT_NAMES[@date[5..6].to_i - 1] : nil) @day = solr_doc['day'] || @date && @date.size > 9 ? @date[8..9].to_i : nil # @volume = find_value('hl_volume') # @issue = find_value('hl_issue') # @authors = find_value('creator') # @first_page = find_value('hl_first_page') # @last_page = find_value('hl_last_page') @rights_uri = Array(solr_doc.fetch('rightsURI', nil)) @related = solr_doc.fetch('relatedIdentifier', nil) @related_identifiers = related_identifiers @alternate = solr_doc.fetch('alternateIdentifier', nil) @version = solr_doc.fetch('version', nil) @contributor = Array(solr_doc.fetch('contributor', [])) @contributor_type = Array(solr_doc.fetch('contributorType', [])) xml = Base64.decode64(solr_doc.fetch('xml', "PGhzaD48L2hzaD4=\n")).force_encoding('UTF-8') @xml = Hash.from_xml(xml).fetch("resource", {}) @authors = @xml.fetch("creators", {}).fetch("creator", []) @authors = [@authors] if @authors.is_a?(Hash) # Insert/update record in MongoDB # Hack Alert (possibly) MongoData.coll('dois').update({ doi: @doi }, { doi: @doi, title: @title, type: @type, subtype: @subtype, publication: @publication, contributor: @authors, published: { year: @year, month: @month, day: @day } }, { upsert: true }) end def title_escaped title.gsub("'", %q(\\\')) if title.present? end def open_access? @doc['oa_status'] == 'Open Access' end def creative_commons if rights_uri.find { |uri| /licenses\/by-nc-nd\// =~ uri } 'by-nc-nd' elsif rights_uri.find { |uri| /licenses\/by-nc-sa\// =~ uri } 'by-nc-sa' elsif rights_uri.find { |uri| /licenses\/by-nc\// =~ uri } 'by-nc' elsif rights_uri.find { |uri| /licenses\/by-sa\// =~ uri } 'by-sa' elsif rights_uri.find { |uri| /licenses\/by\// =~ uri } 'by' elsif rights_uri.find { |uri| /publicdomain\/zero/ =~ uri } 'zero' else nil end end def contributors_with_type contributor_type.zip(contributor).map { |c| {c[0] => c[1] }} end def contributors_by_type(type) contributors_with_type.map do |hsh| hsh.select { |key, value| key == type } end end def grant_info contributors_by_type("Funder").map { |c| c["Funder"] }.compact.uniq end def related Array(@related).map do |item| { relation: item.split(':', 3)[0], id: item.split(':', 3)[1], text: item.split(':', 3)[2], source: "Datacite" } end.select { |item| item[:text].present? && item[:id] =~ /(DOI|URL)/ } end def combined_related (related + related_identifiers).group_by { |item| item[:relation] } end def alternate Array(@alternate).map do |item| { id: item.split(':', 2)[0], text: item.split(':', 2)[1] } end.select { |item| item[:id] !~ /citation/ } end def authors Array(@authors).map do |author| creator_name = author.fetch("creatorName", nil) names = Namae.parse(creator_name) name = names.first || OpenStruct.new(family: nil, given: nil, literal: creator_name) credit_name = name.given ? [name.given, name.family].join(" ") : name.literal { "family" => name.family, "given" => name.given, "credit-name" => credit_name, "id" => author.fetch("nameIdentifier", nil) } end end def authors_as_string authors[0..19].map do |author| author["id"].present? ? "<a href=\"/?q=#{author["id"]}\">#{author["credit-name"]}</a>" : author["credit-name"] end.join(", ") end def parse_author(name) # revert order if single words, separated by comma name = name.split(',') if name.all? { |i| i.split(' ').size > 1 } name.join(', ') else name.reverse.join(' ') end end def user_claimed? @user_claimed end def in_user_profile? @in_user_profile end def coins_atitle @title || '' end def coins_title @doc['hl_publication'] end def coins_year @year end def coins_volume @doc['hl_volume'] end def coins_issue @doc['hl_issue'] end def coins_spage @doc['hl_first_page'] end def coins_lpage @doc['hl_last_page'] end def coins_authors if @authors authors_as_string else '' end end def coins_au_first @doc['first_author_given'] end def coins_au_last @doc['first_author_surname'] end def coins props = { 'ctx_ver' => 'Z39.88-2004', 'rft_id' => "info:doi/#{@doi}", 'rfr_id' => 'info:sid/datacite.org:search', 'rft.atitle' => coins_atitle, 'rft.jtitle' => coins_title, 'rft.date' => coins_year, 'rft.volume' => coins_volume, 'rft.issue' => coins_issue, 'rft.spage' => coins_spage, 'rft.epage' => coins_lpage, 'rft.aufirst' => coins_au_first, 'rft.aulast' => coins_au_last } case @type when 'journal_article' props['rft_val_fmt'] = 'info:ofi/fmt:kev:mtx:journal' props['rft.genre'] = 'article' when 'conference_paper' props['rft_val_fmt'] = 'info:ofi/fmt:kev:mtx:journal' props['rft.genre'] = 'proceeding' when 'Dataset' props['rft_val_fmt'] = 'info:ofi/fmt:kev:mtx:dc' props['rft.genre'] = 'dataset' when 'Collection' props['rft_val_fmt'] = 'info:ofi/fmt:kev:mtx:dc' props['rft.genre'] = 'collection' when 'Text' props['rft_val_fmt'] = 'info:ofi/fmt:kev:mtx:dc' props['rft.genre'] = 'text' when 'Software' props['rft_val_fmt'] = 'info:ofi/fmt:kev:mtx:dc' props['rft.genre'] = 'software' else props['rft_val_fmt'] = 'info:ofi/fmt:kev:mtx:dc' props['rft.genre'] = 'unknown' end title_parts = [] props.reject { |_, value| value.nil? }.each_pair do |key, value| title_parts << "#{key}=#{CGI.escape(value.to_s)}" end title = title_parts.join('&') coins_authors.split(',').each { |author| title += "&rft.au=#{CGI.escape(author.strip)}" } if coins_authors CGI.escapeHTML title end def coins_span "<span class=\"Z3988\" title=\"#{coins}\"><!-- coins --></span>" end # Mimic SIGG citation format. def citation a = [] a << CGI.escapeHTML(coins_authors) unless coins_authors.empty? a << CGI.escapeHTML(coins_year.to_s) unless coins_year.nil? a << "'#{CGI.escapeHTML(coins_atitle)}'" unless coins_atitle.nil? a << "<i>#{CGI.escapeHTML(coins_title)}</i>" unless coins_title.nil? a << "vol. #{CGI.escapeHTML(coins_volume)}" unless coins_volume.nil? a << "no. #{CGI.escapeHTML(coins_issue)}" unless coins_issue.nil? if !coins_spage.nil? && !coins_lpage.nil? a << "pp. #{CGI.escapeHTML(coins_spage)}-#{CGI.escapeHTML(coins_lpage)}" elsif !coins_spage.nil? a << "p. #{CGI.escapeHTML(coins_spage)}" end a.join ', ' end def has_path?(hash, path) path_found = true path.each do |node| if hash.key?(node) && !hash[node].nil? hash = hash[node] else path_found = false break end end path_found end def find_value(key) if has_path? @highlights, [@doi, key] @highlights[@doi][key].first else @doc[key] end end end
require_relative 'sendgrid/exceptions' require_relative 'sendgrid/mail' require_relative 'sendgrid/version' require 'rest-client' module SendGrid class Client attr_reader :api_user, :api_key, :host, :endpoint def initialize(params) @api_user = params.fetch(:api_user) @api_key = params.fetch(:api_key) @host = params.fetch(:host, 'https://api.sendgrid.com') @endpoint = params.fetch(:endpoint, '/api/mail.send.json') @conn = params.fetch(:conn, create_conn) @user_agent = params.fetch(:user_agent, 'sendgrid/' + SendGrid::VERSION + ';ruby') end def send(mail) payload = mail.to_h.merge({api_user: @api_user, api_key: @api_key}) @conn[@endpoint].post(payload, {user_agent: @user_agent}) do |response, request, result| case response.code.to_s when /2\d\d/ response when /4\d\d|5\d\d/ raise SendGrid::Exception.new(response) else # TODO: What will reach this? "DEFAULT #{response.code} #{response}" end end end private def create_conn @conn = RestClient::Resource.new(@host) end end end Add block option to client require_relative 'sendgrid/exceptions' require_relative 'sendgrid/mail' require_relative 'sendgrid/version' require 'rest-client' module SendGrid class Client attr_accessor :api_user, :api_key, :host, :endpoint def initialize(params = {}) @api_user = params.fetch(:api_user, nil) @api_key = params.fetch(:api_key, nil) @host = params.fetch(:host, 'https://api.sendgrid.com') @endpoint = params.fetch(:endpoint, '/api/mail.send.json') @conn = params.fetch(:conn, create_conn) @user_agent = params.fetch(:user_agent, 'sendgrid/' + SendGrid::VERSION + ';ruby') yield self if block_given? raise SendGrid::Exception.new('api_user and api_key are required') unless @api_user && @api_key end def send(mail) payload = mail.to_h.merge({api_user: @api_user, api_key: @api_key}) @conn[@endpoint].post(payload, {user_agent: @user_agent}) do |response, request, result| case response.code.to_s when /2\d\d/ response when /4\d\d|5\d\d/ raise SendGrid::Exception.new(response) else # TODO: What will reach this? "DEFAULT #{response.code} #{response}" end end end private def create_conn @conn = RestClient::Resource.new(@host) end end end
require 'rubygems' require 'nokogiri' require 'net/http' require 'net/https' require 'builder' require 'uri' class ServiceProxy VERSION = '0.0.1' attr_accessor :endpoint, :service_methods, :soap_actions, :service_uri, :http, :uri, :debug, :wsdl, :target_namespace def initialize(endpoint) self.endpoint = endpoint self.setup end protected def setup self.soap_actions = {} self.service_methods = [] setup_http get_wsdl parse_wsdl setup_namespace end private def setup_http self.uri = URI.parse(self.endpoint) raise ArgumentError, "Endpoint URI must be valid" unless self.uri.scheme self.http = Net::HTTP.new(self.uri.host, self.uri.port) self.http.use_ssl = true if self.uri.scheme == 'https' self.http.set_debug_output(STDOUT) if self.debug end def get_wsdl response = self.http.get("#{self.uri.path}?#{self.uri.query}") self.wsdl = Nokogiri.XML(response.body) end def parse_wsdl method_list = [] self.wsdl.xpath('//*[name()="soap:operation"]').each do |operation| operation_name = operation.parent.get_attribute('name') method_list << operation_name self.soap_actions[operation_name] = operation.get_attribute('soapAction') end raise RuntimeError, "Could not parse WSDL" if method_list.empty? self.service_methods = method_list.sort end def setup_namespace self.target_namespace = self.wsdl.namespaces['xmlns:tns'] end def call_service(options) method = options[:method] headers = { 'content-type' => 'text/xml; charset=utf-8', 'SOAPAction' => self.soap_actions[method] } body = build_envelope(method, options) response = self.http.request_post(self.uri.path, body, headers) parse_response(method, response) end def build_envelope(method, options) builder = underscore("build_#{method}") self.respond_to?(builder) ? self.send(builder, options).target! : soap_envelope(options).target! end def parse_response(method, response) parser = underscore("parse_#{method}") self.respond_to?(parser) ? self.send(parser, response) : raise(NoMethodError, "You must define the parse method: #{parser}") end def soap_envelope(options, &block) xsd = 'http://www.w3.org/2001/XMLSchema' env = 'http://schemas.xmlsoap.org/soap/envelope/' xsi = 'http://www.w3.org/2001/XMLSchema-instance' xml = Builder::XmlMarkup.new xml.env(:Envelope, 'xmlns:xsd' => xsd, 'xmlns:env' => env, 'xmlns:xsi' => xsi) do xml.env(:Body) do xml.n1(options[:method].to_sym, "xmlns:n1" => self.target_namespace) do yield xml if block_given? end end end xml end def method_missing(method, *args) options = args.pop || {} super unless self.service_methods.include?(method.to_s) call_service(options.update(:method => method.to_s)) end def underscore(camel_cased_word) camel_cased_word.to_s.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). downcase end end Reformatting long line require 'rubygems' require 'nokogiri' require 'net/http' require 'net/https' require 'builder' require 'uri' class ServiceProxy VERSION = '0.0.1' attr_accessor :endpoint, :service_methods, :soap_actions, :service_uri, :http, :uri, :debug, :wsdl, :target_namespace def initialize(endpoint) self.endpoint = endpoint self.setup end protected def setup self.soap_actions = {} self.service_methods = [] setup_http get_wsdl parse_wsdl setup_namespace end private def setup_http self.uri = URI.parse(self.endpoint) raise ArgumentError, "Endpoint URI must be valid" unless self.uri.scheme self.http = Net::HTTP.new(self.uri.host, self.uri.port) self.http.use_ssl = true if self.uri.scheme == 'https' self.http.set_debug_output(STDOUT) if self.debug end def get_wsdl response = self.http.get("#{self.uri.path}?#{self.uri.query}") self.wsdl = Nokogiri.XML(response.body) end def parse_wsdl method_list = [] self.wsdl.xpath('//*[name()="soap:operation"]').each do |operation| operation_name = operation.parent.get_attribute('name') method_list << operation_name self.soap_actions[operation_name] = operation.get_attribute('soapAction') end raise RuntimeError, "Could not parse WSDL" if method_list.empty? self.service_methods = method_list.sort end def setup_namespace self.target_namespace = self.wsdl.namespaces['xmlns:tns'] end def call_service(options) method = options[:method] headers = { 'content-type' => 'text/xml; charset=utf-8', 'SOAPAction' => self.soap_actions[method] } body = build_envelope(method, options) response = self.http.request_post(self.uri.path, body, headers) parse_response(method, response) end def build_envelope(method, options) builder = underscore("build_#{method}") self.respond_to?(builder) ? self.send(builder, options).target! : soap_envelope(options).target! end def parse_response(method, response) parser = underscore("parse_#{method}") self.respond_to?(parser) ? self.send(parser, response) : raise(NoMethodError, "You must define the parse method: #{parser}") end def soap_envelope(options, &block) xsd = 'http://www.w3.org/2001/XMLSchema' env = 'http://schemas.xmlsoap.org/soap/envelope/' xsi = 'http://www.w3.org/2001/XMLSchema-instance' xml = Builder::XmlMarkup.new xml.env(:Envelope, 'xmlns:xsd' => xsd, 'xmlns:env' => env, 'xmlns:xsi' => xsi) do xml.env(:Body) do xml.n1(options[:method].to_sym, "xmlns:n1" => self.target_namespace) do yield xml if block_given? end end end xml end def method_missing(method, *args) options = args.pop || {} super unless self.service_methods.include?(method.to_s) call_service(options.update(:method => method.to_s)) end def underscore(camel_cased_word) camel_cased_word.to_s.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). downcase end end
require 'yaml' require 'signed_config/crypto' require 'signed_config/errors' require 'signed_config/reader' require 'signed_config/writer' module SignedConfig VERSION = "0.0.1" end Incrementing version number for trivial reason. require 'yaml' require 'signed_config/crypto' require 'signed_config/errors' require 'signed_config/reader' require 'signed_config/writer' module SignedConfig VERSION = "0.0.2" end
module Simplefb require 'net/http' require 'json' class Error < StandardError; end class << self attr_accessor :app_id, :app_secret attr_writer :logger end def self.logger return @logger ||= BasicLogger.new end def self.app_access_token "#{@app_id}|#{@app_secret}" end def self.query_endpoint(endpoint, access_token, options={}) logger.info "Querying endpoint: #{endpoint}" options[:access_token]=access_token perform_request("https://graph.facebook.com/#{endpoint}", options) end def self.debug_token(access_token) logger.info "Debugging token" raise Error, "No Access Token Given" unless access_token response=perform_request("https://graph.facebook.com/debug_token", :input_token=>access_token, :access_token=>app_access_token) # Check that this access token belongs to our app raise Error if response['data']['app_id'] != @app_id # Parse Unix times for easier reading # From Documentation: issued_at field is not returned for short-lived access tokens (https://developers.facebook.com/docs/facebook-login/access-tokens) %w(issued_at expires_at).each {|field| response['data'][field]=Time.at(response['data'][field]) if response['data'].has_key?(field)} response end def self.get_access_token(code, redirect_uri) raise Error, "No code given" unless code logger.info "*** Getting access token" access_token_response = perform_request("https://graph.facebook.com/oauth/access_token", :client_id=>@app_id, :redirect_uri=>redirect_uri, :client_secret=>@app_secret, :code=>code) cracked_access_token_response=access_token_response.body.scan(/(\w+)=(\w+)+/) cracked_access_token_response_hash=cracked_access_token_response.reduce({}) { |hash, curr| hash[curr[0]]=curr[1];hash } access_token=cracked_access_token_response_hash['access_token'] return access_token end def self.get_login_prompt_url(redirect_uri, permissions: [:public_profile, :email, :user_friends]) raise Error, 'No app ID provided' unless @app_id url="https://www.facebook.com/dialog/oauth?client_id=#{@app_id}&scope=#{permissions.join(',')}&redirect_uri=#{redirect_uri}" return url end # The token is actually sent back to the client as part of the URL Fragment. Therefore, it is not visible by the server def self.get_token_login_prompt_url(redirect_uri) raise Error, 'No app ID provided' unless @app_id url="https://www.facebook.com/dialog/oauth?client_id=#{@app_id}&scope=public_profile,email,user_friends&response_type=token&redirect_uri=#{redirect_uri}" return url end private def self.debug_response(response) logger.debug "#{response.code}" logger.debug response.body response.each do |header, value| logger.debug "#{header}, #{value}" end end def self.perform_request(uristring, options={}) response=nil if options.length>0 query=options.map {|k,v| "#{k}=#{v}"}.join('&') uristring+="?#{query}" end uri=URI(URI.escape(uristring)) logger.debug "URI: #{uri}" Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http| req = Net::HTTP::Get.new(uri) # req.add_field('Accept', 'application/json') response = http.request(req) # Net::HTTPResponse object end raise Error unless response debug_response(response) raise Error, "Failed status code #{response.code} #{response.body}" unless response.code =~ /2\d+/ if response['Content-Type'] =~ /^application\/json/ # Facebook likes to return 'application/json; charset=UTF-8' if no 'Accept:' is given logger.info "Returning a hash" return JSON.parse(response.body) else return response end end end -Adding login urls for mobile web and facebook app module Simplefb require 'net/http' require 'json' class Error < StandardError; end class << self attr_accessor :app_id, :app_secret attr_writer :logger end def self.logger return @logger ||= BasicLogger.new end def self.app_access_token "#{@app_id}|#{@app_secret}" end def self.query_endpoint(endpoint, access_token, options={}) logger.info "Querying endpoint: #{endpoint}" options[:access_token]=access_token perform_request("https://graph.facebook.com/#{endpoint}", options) end def self.debug_token(access_token) logger.info "Debugging token" raise Error, "No Access Token Given" unless access_token response=perform_request("https://graph.facebook.com/debug_token", :input_token=>access_token, :access_token=>app_access_token) # Check that this access token belongs to our app raise Error if response['data']['app_id'] != @app_id # Parse Unix times for easier reading # From Documentation: issued_at field is not returned for short-lived access tokens (https://developers.facebook.com/docs/facebook-login/access-tokens) %w(issued_at expires_at).each {|field| response['data'][field]=Time.at(response['data'][field]) if response['data'].has_key?(field)} response end def self.get_access_token(code, redirect_uri) raise Error, "No code given" unless code logger.info "*** Getting access token" access_token_response = perform_request("https://graph.facebook.com/oauth/access_token", :client_id=>@app_id, :redirect_uri=>redirect_uri, :client_secret=>@app_secret, :code=>code) cracked_access_token_response=access_token_response.body.scan(/(\w+)=(\w+)+/) cracked_access_token_response_hash=cracked_access_token_response.reduce({}) { |hash, curr| hash[curr[0]]=curr[1];hash } access_token=cracked_access_token_response_hash['access_token'] return access_token end def self.get_login_prompt_url(redirect_uri, permissions: [:public_profile, :email, :user_friends]) raise Error, 'No app ID provided' unless @app_id url="https://www.facebook.com/dialog/oauth?client_id=#{@app_id}&scope=#{permissions.join(',')}&redirect_uri=#{redirect_uri}" return url end # The token is actually sent back to the client as part of the URL Fragment. Therefore, it is not visible by the server def self.get_token_login_prompt_url(redirect_uri, permissions: [:public_profile, :email, :user_friends]) raise Error, 'No app ID provided' unless @app_id url="https://www.facebook.com/dialog/oauth?client_id=#{@app_id}&scope=#{permissions.join(',')}&response_type=token&redirect_uri=#{redirect_uri}" return url end # Facebook will redirect to the right scheme regardless, so no redirect_uri will be required def self.get_app_login_prompt_url(permissions: [:public_profile, :email, :user_friends]) raise Error, 'No app ID provided' unless @app_id "fbauth://authorize?client_id=#{@app_id}&scope=#{permissions.join(',')}&response_type=code" end def self.get_mobile_web_login_prompt_url(permissions: [:public_profile, :email, :user_friends]) raise Error, 'No app ID provided' unless @app_id "https://www.facebook.com/dialog/oauth?client_id=#{@app_id}&scope=#{permissions.join(',')}&response_type=token&redirect_uri=fb#{@app_id}://authorize" end private def self.debug_response(response) logger.debug "#{response.code}" logger.debug response.body response.each do |header, value| logger.debug "#{header}, #{value}" end end def self.perform_request(uristring, options={}) response=nil if options.length>0 query=options.map {|k,v| "#{k}=#{v}"}.join('&') uristring+="?#{query}" end uri=URI(URI.escape(uristring)) logger.debug "URI: #{uri}" Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http| req = Net::HTTP::Get.new(uri) # req.add_field('Accept', 'application/json') response = http.request(req) # Net::HTTPResponse object end raise Error unless response debug_response(response) raise Error, "Failed status code #{response.code} #{response.body}" unless response.code =~ /2\d+/ if response['Content-Type'] =~ /^application\/json/ # Facebook likes to return 'application/json; charset=UTF-8' if no 'Accept:' is given logger.info "Returning a hash" return JSON.parse(response.body) else return response end end end
# encoding: utf-8 require 'slim/optimizer' module Slim module Compiler include Optimizer AUTOCLOSED = %w{meta img link br hr input area param col base} CONTROL_WORDS = %w{if unless do} ELSE_CONTROL_WORDS = %w{else elsif} REGEX_LINE_PARSER = /^(\s*)(!?`?\|?-?=?\w*)((?:\s*(?:\w|-)*="[^=]+")+|(\s*[#.]\S+))?(.*)/ REGEX_LINE_CONTAINS_OUTPUT_CODE = /^=(.*)/ REGEX_METHOD_HAS_NO_PARENTHESES = /^\w+\s/ REGEX_CODE_BLOCK_DETECTED = / do ?.*$/ REGEX_CODE_CONTROL_WORD_DETECTED = /(?:( )|(\())(#{CONTROL_WORDS * '|'})\b ?(.*)$/ REGEX_CODE_ELSE_CONTROL_WORD_DETECTED = /^#{ELSE_CONTROL_WORDS * '\b|'}\b/ REGEX_FIND_HTML_ATTR_ID = /#([^.\s]+)/ REGEX_FIND_HTML_ATTR_CLASSES = /\.([^#\s]+)/ def compile @_buffer = ["_buf = [];"] @in_text = false text_indent = last_indent = -1; enders = [] @template.each_line do |line| line.chomp!; line.rstrip! if line.length == 0 @_buffer << "_buf << \"<br/>\";" if @in_text next end line =~ REGEX_LINE_PARSER indent = $1.to_s.length if @in_text && indent > text_indent spaces = indent - text_indent @_buffer << "_buf << \"#{(' '*(spaces - 1)) + line.lstrip}\";" next end marker = $2 attrs = $3 shortcut_attrs = $4 string = $5 # prepends "div" to the shortcut form of attrs if no marker is given if shortcut_attrs && marker.empty? marker = "div" end line_type = case marker when '`', '|' then :text when '-' then :control_code when '=' then :output_code when '!' then :declaration else :markup end if line_type != :text @in_text = false text_indent = -1 end if attrs attrs = normalize_attributes(attrs) if shortcut_attrs attrs.gsub!('"', '\"') end if string string.strip! string = nil if string.empty? end unless indent > last_indent begin break if enders.empty? continue_closing = true ender, ender_indent = enders.pop unless ender_indent < indent || ender == 'end;' && line_type == :control_code && ender_indent == indent && string =~ REGEX_CODE_ELSE_CONTROL_WORD_DETECTED @_buffer << ender else enders << [ender, ender_indent] continue_closing = false end end while continue_closing == true end last_indent = indent case line_type when :markup if AUTOCLOSED.include?(marker) @_buffer << "_buf << \"<#{marker}#{attrs || ''}/>\";" else enders << ["_buf << \"</#{marker}>\";", indent] @_buffer << "_buf << \"<#{marker}#{attrs || ''}>\";" end if string string.lstrip! if string =~ REGEX_LINE_CONTAINS_OUTPUT_CODE @_buffer << "_buf << #{parenthesesify_method($1.strip)};" else @_buffer << "_buf << \"#{string}\";" end end when :text @in_text = true text_indent = indent @_buffer << "_buf << \"#{string}\";" if string.to_s.length > 0 when :control_code enders << ['end;', indent] unless enders.detect{|e| e[0] == 'end;' && e[1] == indent} @_buffer << "#{string};" when :output_code enders << ['end;', indent] if string =~ REGEX_CODE_BLOCK_DETECTED @_buffer << "_buf << #{parenthesesify_method(string)};" when :declaration @_buffer << "_buf << \"<!#{string}>\";" else raise NotImplementedError.new("Don't know how to parse line: #{line}") end end # template iterator enders.reverse_each do |t| @_buffer << t[0].to_s end @_buffer << "_buf.join;" @compiled = @_buffer.join optimize return nil end private # adds a pair of parentheses to the method def parenthesesify_method(string) if string =~ /^=(.*)/ # used == string = $1.strip noescape = true end string << ' ' if string =~ /^\s*\w+\S?$/ if string =~ REGEX_METHOD_HAS_NO_PARENTHESES string.sub!(' ', '(') && string.sub!(REGEX_CODE_CONTROL_WORD_DETECTED, '\2) \3 \4') || string << ')' end unless string =~ REGEX_CODE_BLOCK_DETECTED || noescape string.sub!(/^(\w+\(.*\))(.*)/,'Slim.escape_html(\1) \2') end return string.strip end # converts 'p#hello.world' to 'p id="hello" class="world"' def normalize_attributes(string) string.sub!(REGEX_FIND_HTML_ATTR_ID, ' id="\1"') string.sub!(REGEX_FIND_HTML_ATTR_CLASSES, ' class="\1"') string.gsub!('.', ' ') string end end end Removed unneeded regex capture. # encoding: utf-8 require 'slim/optimizer' module Slim module Compiler include Optimizer AUTOCLOSED = %w{meta img link br hr input area param col base} CONTROL_WORDS = %w{if unless do} ELSE_CONTROL_WORDS = %w{else elsif} REGEX_LINE_PARSER = /^(\s*)(!?`?\|?-?=?\w*)((?:\s*(?:\w|-)*="[^=]+")+|(\s*[#.]\S+))?(.*)/ REGEX_LINE_CONTAINS_OUTPUT_CODE = /^=(.*)/ REGEX_METHOD_HAS_NO_PARENTHESES = /^\w+\s/ REGEX_CODE_BLOCK_DETECTED = / do ?.*$/ REGEX_CODE_CONTROL_WORD_DETECTED = /(?:( )|(\())(#{CONTROL_WORDS * '|'})\b ?(.*)$/ REGEX_CODE_ELSE_CONTROL_WORD_DETECTED = /^#{ELSE_CONTROL_WORDS * '\b|'}\b/ REGEX_FIND_HTML_ATTR_ID = /#([^.\s]+)/ REGEX_FIND_HTML_ATTR_CLASSES = /\.([^#\s]+)/ def compile @_buffer = ["_buf = [];"] @in_text = false text_indent = last_indent = -1; enders = [] @template.each_line do |line| line.chomp!; line.rstrip! if line.length == 0 @_buffer << "_buf << \"<br/>\";" if @in_text next end line =~ REGEX_LINE_PARSER indent = $1.to_s.length if @in_text && indent > text_indent spaces = indent - text_indent @_buffer << "_buf << \"#{(' '*(spaces - 1)) + line.lstrip}\";" next end marker = $2 attrs = $3 shortcut_attrs = $4 string = $5 # prepends "div" to the shortcut form of attrs if no marker is given if shortcut_attrs && marker.empty? marker = "div" end line_type = case marker when '`', '|' then :text when '-' then :control_code when '=' then :output_code when '!' then :declaration else :markup end if line_type != :text @in_text = false text_indent = -1 end if attrs attrs = normalize_attributes(attrs) if shortcut_attrs attrs.gsub!('"', '\"') end if string string.strip! string = nil if string.empty? end unless indent > last_indent begin break if enders.empty? continue_closing = true ender, ender_indent = enders.pop unless ender_indent < indent || ender == 'end;' && line_type == :control_code && ender_indent == indent && string =~ REGEX_CODE_ELSE_CONTROL_WORD_DETECTED @_buffer << ender else enders << [ender, ender_indent] continue_closing = false end end while continue_closing == true end last_indent = indent case line_type when :markup if AUTOCLOSED.include?(marker) @_buffer << "_buf << \"<#{marker}#{attrs || ''}/>\";" else enders << ["_buf << \"</#{marker}>\";", indent] @_buffer << "_buf << \"<#{marker}#{attrs || ''}>\";" end if string string.lstrip! if string =~ REGEX_LINE_CONTAINS_OUTPUT_CODE @_buffer << "_buf << #{parenthesesify_method($1.strip)};" else @_buffer << "_buf << \"#{string}\";" end end when :text @in_text = true text_indent = indent @_buffer << "_buf << \"#{string}\";" if string.to_s.length > 0 when :control_code enders << ['end;', indent] unless enders.detect{|e| e[0] == 'end;' && e[1] == indent} @_buffer << "#{string};" when :output_code enders << ['end;', indent] if string =~ REGEX_CODE_BLOCK_DETECTED @_buffer << "_buf << #{parenthesesify_method(string)};" when :declaration @_buffer << "_buf << \"<!#{string}>\";" else raise NotImplementedError.new("Don't know how to parse line: #{line}") end end # template iterator enders.reverse_each do |t| @_buffer << t[0].to_s end @_buffer << "_buf.join;" @compiled = @_buffer.join optimize return nil end private # adds a pair of parentheses to the method def parenthesesify_method(string) if string =~ /^=(.*)/ # used == string = $1.strip noescape = true end string << ' ' if string =~ /^\s*\w+\S?$/ if string =~ REGEX_METHOD_HAS_NO_PARENTHESES string.sub!(' ', '(') && string.sub!(REGEX_CODE_CONTROL_WORD_DETECTED, '\2) \3 \4') || string << ')' end unless string =~ REGEX_CODE_BLOCK_DETECTED || noescape string.sub!(/^(\w+\(.*\)).*/, 'Slim.escape_html(\1) \2') end return string.strip end # converts 'p#hello.world' to 'p id="hello" class="world"' def normalize_attributes(string) string.sub!(REGEX_FIND_HTML_ATTR_ID, ' id="\1"') string.sub!(REGEX_FIND_HTML_ATTR_CLASSES, ' class="\1"') string.gsub!('.', ' ') string end end end
# encoding: utf-8 require 'slim/optimizer' module Slim module Compiler include Optimizer AUTOCLOSED = %w{meta img link br hr input area param col base} CONTROL_WORDS = %w{if unless do} ELSE_CONTROL_WORDS = %w{else elsif} REGEX_LINE_PARSER = /^(\s*)(!?`?\|?-?=?\w*)((?:\s*(?:\w|-)*="[^=]+")+|(\s*[#.]\S+))?(.*)/ REGEX_LINE_CONTAINS_OUTPUT_CODE = /^=(.*)/ REGEX_LINE_CONTAINS_ONLY_HTML_TAG = /^\s*\w+\S?$/ REGEX_LINE_CONTAINS_METHOD_DETECTED = /^(\w+\(.*\))(.*)/ REGEX_METHOD_HAS_NO_PARENTHESES = /^\w+\s/ REGEX_CODE_BLOCK_DETECTED = / do ?.*$/ REGEX_CODE_CONTROL_WORD_DETECTED = /(?:\s|(\())(#{CONTROL_WORDS * '|'})\b\s?(.*)$/ REGEX_CODE_ELSE_CONTROL_WORD_DETECTED = /^#{ELSE_CONTROL_WORDS * '\b|'}\b/ REGEX_FIND_HTML_ATTR_ID = /#([^.\s]+)/ REGEX_FIND_HTML_ATTR_CLASSES = /\.([^#\s]+)/ def compile @_buffer = ['_buf = [];'] in_text = false text_indent = last_indent = -1; enders = [] @template.each_line do |line| line.chomp!; line.rstrip! if line.length == 0 @_buffer << '_buf << "<br/>";' if in_text next end line =~ REGEX_LINE_PARSER indent = $1.to_s.length if in_text && indent > text_indent spaces = indent - text_indent @_buffer << "_buf << \"#{(' '*(spaces - 1)) + line.lstrip}\";" next end marker = $2 attrs = $3 shortcut_attrs = $4 string = $5.strip # prepends "div" to the shortcut form of attrs if no marker is given marker = 'div' if shortcut_attrs && marker.empty? line_type = case marker when '`', '|' then :text when '-' then :control_code when '=' then :output_code when '!' then :declaration else :markup end unless line_type == :text in_text = false text_indent = -1 end if attrs normalize_attributes!(attrs) if shortcut_attrs attrs.gsub!('"', '\"') end unless indent > last_indent begin break if enders.empty? continue_closing = true ender, ender_indent = enders.pop unless ender_indent < indent || ender == 'end;' && line_type == :control_code && ender_indent == indent && string =~ REGEX_CODE_ELSE_CONTROL_WORD_DETECTED @_buffer << ender else enders << [ender, ender_indent] continue_closing = false end end while continue_closing == true end last_indent = indent case line_type when :markup if AUTOCLOSED.include?(marker) @_buffer << "_buf << \"<#{marker}#{attrs || ''}/>\";" else enders << ["_buf << \"</#{marker}>\";", indent] @_buffer << "_buf << \"<#{marker}#{attrs || ''}>\";" end unless string.empty? string.lstrip! if string =~ REGEX_LINE_CONTAINS_OUTPUT_CODE @_buffer << "_buf << #{parse_string($1.strip)};" else @_buffer << "_buf << \"#{string}\";" end end when :text in_text = true text_indent = indent @_buffer << "_buf << \"#{string}\";" if string.to_s.length > 0 when :control_code enders << ['end;', indent] unless enders.detect{|e| e[0] == 'end;' && e[1] == indent} @_buffer << "#{string};" when :output_code enders << ['end;', indent] if string =~ REGEX_CODE_BLOCK_DETECTED @_buffer << "_buf << #{parse_string(string)};" when :declaration @_buffer << "_buf << \"<!#{string}>\";" else raise NotImplementedError.new("Don't know how to parse line: #{line}") end end # template iterator enders.reverse_each do |t| @_buffer << t[0] end @_buffer << "_buf.join;" @compiled = @_buffer.join @optimized = optimize! end private def parse_string(string) string = string_skip_escape = $1.strip if string =~ REGEX_LINE_CONTAINS_OUTPUT_CODE string << ' ' if string =~ REGEX_LINE_CONTAINS_ONLY_HTML_TAG parenthesesify_method!(string) if string =~ REGEX_METHOD_HAS_NO_PARENTHESES wraps_with_slim_escape!(string) unless string =~ REGEX_CODE_BLOCK_DETECTED || string_skip_escape string.strip end # adds a pair of parentheses to the method def parenthesesify_method!(string) string.sub!(' ', '(') && string.sub!(REGEX_CODE_CONTROL_WORD_DETECTED, '\1) \2 \3') || string << ')' end # escapes the string def wraps_with_slim_escape!(string) string.sub!(REGEX_LINE_CONTAINS_METHOD_DETECTED, 'Slim.escape_html(\1) \2') end # converts 'p#hello.world' to 'p id="hello" class="world"' def normalize_attributes!(string) string.sub!(REGEX_FIND_HTML_ATTR_ID, ' id="\1"') string.sub!(REGEX_FIND_HTML_ATTR_CLASSES, ' class="\1"') string.gsub!('.', ' ') end end end Better example documentation for normalize_attributes!. # encoding: utf-8 require 'slim/optimizer' module Slim module Compiler include Optimizer AUTOCLOSED = %w{meta img link br hr input area param col base} CONTROL_WORDS = %w{if unless do} ELSE_CONTROL_WORDS = %w{else elsif} REGEX_LINE_PARSER = /^(\s*)(!?`?\|?-?=?\w*)((?:\s*(?:\w|-)*="[^=]+")+|(\s*[#.]\S+))?(.*)/ REGEX_LINE_CONTAINS_OUTPUT_CODE = /^=(.*)/ REGEX_LINE_CONTAINS_ONLY_HTML_TAG = /^\s*\w+\S?$/ REGEX_LINE_CONTAINS_METHOD_DETECTED = /^(\w+\(.*\))(.*)/ REGEX_METHOD_HAS_NO_PARENTHESES = /^\w+\s/ REGEX_CODE_BLOCK_DETECTED = / do ?.*$/ REGEX_CODE_CONTROL_WORD_DETECTED = /(?:\s|(\())(#{CONTROL_WORDS * '|'})\b\s?(.*)$/ REGEX_CODE_ELSE_CONTROL_WORD_DETECTED = /^#{ELSE_CONTROL_WORDS * '\b|'}\b/ REGEX_FIND_HTML_ATTR_ID = /#([^.\s]+)/ REGEX_FIND_HTML_ATTR_CLASSES = /\.([^#\s]+)/ def compile @_buffer = ['_buf = [];'] in_text = false text_indent = last_indent = -1; enders = [] @template.each_line do |line| line.chomp!; line.rstrip! if line.length == 0 @_buffer << '_buf << "<br/>";' if in_text next end line =~ REGEX_LINE_PARSER indent = $1.to_s.length if in_text && indent > text_indent spaces = indent - text_indent @_buffer << "_buf << \"#{(' '*(spaces - 1)) + line.lstrip}\";" next end marker = $2 attrs = $3 shortcut_attrs = $4 string = $5.strip # prepends "div" to the shortcut form of attrs if no marker is given marker = 'div' if shortcut_attrs && marker.empty? line_type = case marker when '`', '|' then :text when '-' then :control_code when '=' then :output_code when '!' then :declaration else :markup end unless line_type == :text in_text = false text_indent = -1 end if attrs normalize_attributes!(attrs) if shortcut_attrs attrs.gsub!('"', '\"') end unless indent > last_indent begin break if enders.empty? continue_closing = true ender, ender_indent = enders.pop unless ender_indent < indent || ender == 'end;' && line_type == :control_code && ender_indent == indent && string =~ REGEX_CODE_ELSE_CONTROL_WORD_DETECTED @_buffer << ender else enders << [ender, ender_indent] continue_closing = false end end while continue_closing == true end last_indent = indent case line_type when :markup if AUTOCLOSED.include?(marker) @_buffer << "_buf << \"<#{marker}#{attrs || ''}/>\";" else enders << ["_buf << \"</#{marker}>\";", indent] @_buffer << "_buf << \"<#{marker}#{attrs || ''}>\";" end unless string.empty? string.lstrip! if string =~ REGEX_LINE_CONTAINS_OUTPUT_CODE @_buffer << "_buf << #{parse_string($1.strip)};" else @_buffer << "_buf << \"#{string}\";" end end when :text in_text = true text_indent = indent @_buffer << "_buf << \"#{string}\";" if string.to_s.length > 0 when :control_code enders << ['end;', indent] unless enders.detect{|e| e[0] == 'end;' && e[1] == indent} @_buffer << "#{string};" when :output_code enders << ['end;', indent] if string =~ REGEX_CODE_BLOCK_DETECTED @_buffer << "_buf << #{parse_string(string)};" when :declaration @_buffer << "_buf << \"<!#{string}>\";" else raise NotImplementedError.new("Don't know how to parse line: #{line}") end end # template iterator enders.reverse_each do |t| @_buffer << t[0] end @_buffer << "_buf.join;" @compiled = @_buffer.join @optimized = optimize! end private def parse_string(string) string = string_skip_escape = $1.strip if string =~ REGEX_LINE_CONTAINS_OUTPUT_CODE string << ' ' if string =~ REGEX_LINE_CONTAINS_ONLY_HTML_TAG parenthesesify_method!(string) if string =~ REGEX_METHOD_HAS_NO_PARENTHESES wraps_with_slim_escape!(string) unless string =~ REGEX_CODE_BLOCK_DETECTED || string_skip_escape string.strip end # adds a pair of parentheses to the method def parenthesesify_method!(string) string.sub!(' ', '(') && string.sub!(REGEX_CODE_CONTROL_WORD_DETECTED, '\1) \2 \3') || string << ')' end # escapes the string def wraps_with_slim_escape!(string) string.sub!(REGEX_LINE_CONTAINS_METHOD_DETECTED, 'Slim.escape_html(\1) \2') end # converts 'p#hello.world.mate' to 'p id="hello" class="world mate"' def normalize_attributes!(string) string.sub!(REGEX_FIND_HTML_ATTR_ID, ' id="\1"') string.sub!(REGEX_FIND_HTML_ATTR_CLASSES, ' class="\1"') string.gsub!('.', ' ') end end end
# encoding: utf-8 require 'slim/optimizer' module Slim module Compiler include Optimizer AUTOCLOSED = %w{meta img link br hr input area param col base} CONTROL_WORDS = %w{if unless do} ELSE_CONTROL_WORDS = %w{else elsif} REGEX_LINE_PARSER = /^(\s*)(!?`?\|?-?=?\w*)((?:\s*(?:\w|-)*="[^=]+")+|(\s*[#.]\S+))?(.*)/ REGEX_LINE_CONTAINS_OUTPUT_CODE = /^=(.*)/ REGEX_METHOD_HAS_NO_PARENTHESES = /^\w+\s/ REGEX_CODE_BLOCK_DETECTED = / do ?.*$/ REGEX_CODE_CONTROL_WORD_DETECTED = /(?:\s|(\())(#{CONTROL_WORDS * '|'})\b\s?(.*)$/ REGEX_CODE_ELSE_CONTROL_WORD_DETECTED = /^#{ELSE_CONTROL_WORDS * '\b|'}\b/ REGEX_FIND_HTML_ATTR_ID = /#([^.\s]+)/ REGEX_FIND_HTML_ATTR_CLASSES = /\.([^#\s]+)/ def compile @_buffer = ["_buf = [];"] @in_text = false text_indent = last_indent = -1; enders = [] @template.each_line do |line| line.chomp!; line.rstrip! if line.length == 0 @_buffer << "_buf << \"<br/>\";" if @in_text next end line =~ REGEX_LINE_PARSER indent = $1.to_s.length if @in_text && indent > text_indent spaces = indent - text_indent @_buffer << "_buf << \"#{(' '*(spaces - 1)) + line.lstrip}\";" next end marker = $2 attrs = $3 shortcut_attrs = $4 string = $5 # prepends "div" to the shortcut form of attrs if no marker is given if shortcut_attrs && marker.empty? marker = "div" end line_type = case marker when '`', '|' then :text when '-' then :control_code when '=' then :output_code when '!' then :declaration else :markup end if line_type != :text @in_text = false text_indent = -1 end if attrs attrs = normalize_attributes(attrs) if shortcut_attrs attrs.gsub!('"', '\"') end if string string.strip! string = nil if string.empty? end unless indent > last_indent begin break if enders.empty? continue_closing = true ender, ender_indent = enders.pop unless ender_indent < indent || ender == 'end;' && line_type == :control_code && ender_indent == indent && string =~ REGEX_CODE_ELSE_CONTROL_WORD_DETECTED @_buffer << ender else enders << [ender, ender_indent] continue_closing = false end end while continue_closing == true end last_indent = indent case line_type when :markup if AUTOCLOSED.include?(marker) @_buffer << "_buf << \"<#{marker}#{attrs || ''}/>\";" else enders << ["_buf << \"</#{marker}>\";", indent] @_buffer << "_buf << \"<#{marker}#{attrs || ''}>\";" end if string string.lstrip! if string =~ REGEX_LINE_CONTAINS_OUTPUT_CODE @_buffer << "_buf << #{parenthesesify_method($1.strip)};" else @_buffer << "_buf << \"#{string}\";" end end when :text @in_text = true text_indent = indent @_buffer << "_buf << \"#{string}\";" if string.to_s.length > 0 when :control_code enders << ['end;', indent] unless enders.detect{|e| e[0] == 'end;' && e[1] == indent} @_buffer << "#{string};" when :output_code enders << ['end;', indent] if string =~ REGEX_CODE_BLOCK_DETECTED @_buffer << "_buf << #{parenthesesify_method(string)};" when :declaration @_buffer << "_buf << \"<!#{string}>\";" else raise NotImplementedError.new("Don't know how to parse line: #{line}") end end # template iterator enders.reverse_each do |t| @_buffer << t[0].to_s end @_buffer << "_buf.join;" @compiled = @_buffer.join optimize return nil end private # adds a pair of parentheses to the method def parenthesesify_method(string) if string =~ /^=(.*)/ # used == string = $1.strip noescape = true end string << ' ' if string =~ /^\s*\w+\S?$/ if string =~ REGEX_METHOD_HAS_NO_PARENTHESES string.sub!(' ', '(') && string.sub!(REGEX_CODE_CONTROL_WORD_DETECTED, '\1) \2 \3') || string << ')' end unless string =~ REGEX_CODE_BLOCK_DETECTED || noescape string.sub!(/^(\w+\(.*\)).*/, 'Slim.escape_html(\1) \2') end return string.strip end # converts 'p#hello.world' to 'p id="hello" class="world"' def normalize_attributes(string) string.sub!(REGEX_FIND_HTML_ATTR_ID, ' id="\1"') string.sub!(REGEX_FIND_HTML_ATTR_CLASSES, ' class="\1"') string.gsub!('.', ' ') string end end end Refactored the code a bit. # encoding: utf-8 require 'slim/optimizer' module Slim module Compiler include Optimizer AUTOCLOSED = %w{meta img link br hr input area param col base} CONTROL_WORDS = %w{if unless do} ELSE_CONTROL_WORDS = %w{else elsif} REGEX_LINE_PARSER = /^(\s*)(!?`?\|?-?=?\w*)((?:\s*(?:\w|-)*="[^=]+")+|(\s*[#.]\S+))?(.*)/ REGEX_LINE_CONTAINS_OUTPUT_CODE = /^=(.*)/ REGEX_LINE_CONTAINS_ONLY_HTML_TAG = /^\s*\w+\S?$/ REGEX_LINE_CONTAINS_METHOD_DETECTED = /^(\w+\(.*\))(.*)/ REGEX_METHOD_HAS_NO_PARENTHESES = /^\w+\s/ REGEX_CODE_BLOCK_DETECTED = / do ?.*$/ REGEX_CODE_CONTROL_WORD_DETECTED = /(?:\s|(\())(#{CONTROL_WORDS * '|'})\b\s?(.*)$/ REGEX_CODE_ELSE_CONTROL_WORD_DETECTED = /^#{ELSE_CONTROL_WORDS * '\b|'}\b/ REGEX_FIND_HTML_ATTR_ID = /#([^.\s]+)/ REGEX_FIND_HTML_ATTR_CLASSES = /\.([^#\s]+)/ def compile @_buffer = ["_buf = [];"] @in_text = false text_indent = last_indent = -1; enders = [] @template.each_line do |line| line.chomp!; line.rstrip! noescape = false if line.length == 0 @_buffer << "_buf << \"<br/>\";" if @in_text next end line =~ REGEX_LINE_PARSER indent = $1.to_s.length if @in_text && indent > text_indent spaces = indent - text_indent @_buffer << "_buf << \"#{(' '*(spaces - 1)) + line.lstrip}\";" next end marker = $2 attrs = $3 shortcut_attrs = $4 string = $5 # prepends "div" to the shortcut form of attrs if no marker is given if shortcut_attrs && marker.empty? marker = "div" end line_type = case marker when '`', '|' then :text when '-' then :control_code when '=' then :output_code when '!' then :declaration else :markup end if line_type != :text @in_text = false text_indent = -1 end if attrs attrs = normalize_attributes(attrs) if shortcut_attrs attrs.gsub!('"', '\"') end if string string.strip! string = nil if string.empty? end unless indent > last_indent begin break if enders.empty? continue_closing = true ender, ender_indent = enders.pop unless ender_indent < indent || ender == 'end;' && line_type == :control_code && ender_indent == indent && string =~ REGEX_CODE_ELSE_CONTROL_WORD_DETECTED @_buffer << ender else enders << [ender, ender_indent] continue_closing = false end end while continue_closing == true end last_indent = indent case line_type when :markup if AUTOCLOSED.include?(marker) @_buffer << "_buf << \"<#{marker}#{attrs || ''}/>\";" else enders << ["_buf << \"</#{marker}>\";", indent] @_buffer << "_buf << \"<#{marker}#{attrs || ''}>\";" end if string string.lstrip! if string =~ REGEX_LINE_CONTAINS_OUTPUT_CODE @_buffer << "_buf << #{parse_string($1.strip)};" else @_buffer << "_buf << \"#{string}\";" end end when :text @in_text = true text_indent = indent @_buffer << "_buf << \"#{string}\";" if string.to_s.length > 0 when :control_code enders << ['end;', indent] unless enders.detect{|e| e[0] == 'end;' && e[1] == indent} @_buffer << "#{string};" when :output_code enders << ['end;', indent] if string =~ REGEX_CODE_BLOCK_DETECTED @_buffer << "_buf << #{parse_string(string)};" when :declaration @_buffer << "_buf << \"<!#{string}>\";" else raise NotImplementedError.new("Don't know how to parse line: #{line}") end end # template iterator enders.reverse_each do |t| @_buffer << t[0].to_s end @_buffer << "_buf.join;" @compiled = @_buffer.join optimize return nil end private def parse_string(string) string = string_skip_escape = $1.strip if string =~ REGEX_LINE_CONTAINS_OUTPUT_CODE string << ' ' if string =~ REGEX_LINE_CONTAINS_ONLY_HTML_TAG parenthesesify_method!(string) if string =~ REGEX_METHOD_HAS_NO_PARENTHESES wraps_with_slim_escape!(string) unless string =~ REGEX_CODE_BLOCK_DETECTED || string_skip_escape string.strip end # adds a pair of parentheses to the method def parenthesesify_method!(string) string.sub!(' ', '(') && string.sub!(REGEX_CODE_CONTROL_WORD_DETECTED, '\1) \2 \3') || string << ')' end # escapes the string def wraps_with_slim_escape!(string) string.sub!(REGEX_LINE_CONTAINS_METHOD_DETECTED, 'Slim.escape_html(\1) \2') end # converts 'p#hello.world' to 'p id="hello" class="world"' def normalize_attributes(string) string.sub!(REGEX_FIND_HTML_ATTR_ID, ' id="\1"') string.sub!(REGEX_FIND_HTML_ATTR_CLASSES, ' class="\1"') string.gsub!('.', ' ') string end end end