repository_name
stringlengths
7
56
func_path_in_repository
stringlengths
10
101
func_name
stringlengths
12
78
language
stringclasses
1 value
func_code_string
stringlengths
74
11.9k
func_documentation_string
stringlengths
3
8.03k
split_name
stringclasses
1 value
func_code_url
stringlengths
98
213
enclosing_scope
stringlengths
42
98.2k
wied03/opal-factory_girl
opal/opal/active_support/inflector/methods.rb
ActiveSupport.Inflector.titleize
ruby
def titleize(word) # negative lookbehind doesn't work in Firefox / Safari # humanize(underscore(word)).gsub(/\b(?<!['’`])[a-z]/) { |match| match.capitalize } humanized = humanize(underscore(word)) humanized.reverse.gsub(/[a-z](?!['’`])\b/) { |match| match.capitalize }.reverse end
Capitalizes all the words and replaces some characters in the string to create a nicer looking title. +titleize+ is meant for creating pretty output. It is not used in the Rails internals. +titleize+ is also aliased as +titlecase+. titleize('man from the boondocks') # => "Man From The Boondocks" titleize('x-men: the last stand') # => "X Men: The Last Stand" titleize('TheManWithoutAPast') # => "The Man Without A Past" titleize('raiders_of_the_lost_ark') # => "Raiders Of The Lost Ark"
train
https://github.com/wied03/opal-factory_girl/blob/697114a8c63f4cba38b84d27d1f7b823c8d0bb38/opal/opal/active_support/inflector/methods.rb#L160-L165
module Inflector extend self # Returns the plural form of the word in the string. # # If passed an optional +locale+ parameter, the word will be # pluralized using rules defined for that language. By default, # this parameter is set to <tt>:en</tt>. # # pluralize('post') # => "posts" # pluralize('octopus') # => "octopi" # pluralize('sheep') # => "sheep" # pluralize('words') # => "words" # pluralize('CamelOctopus') # => "CamelOctopi" # pluralize('ley', :es) # => "leyes" def pluralize(word, locale = :en) apply_inflections(word, inflections(locale).plurals) end # The reverse of #pluralize, returns the singular form of a word in a # string. # # If passed an optional +locale+ parameter, the word will be # singularized using rules defined for that language. By default, # this parameter is set to <tt>:en</tt>. # # singularize('posts') # => "post" # singularize('octopi') # => "octopus" # singularize('sheep') # => "sheep" # singularize('word') # => "word" # singularize('CamelOctopi') # => "CamelOctopus" # singularize('leyes', :es) # => "ley" def singularize(word, locale = :en) apply_inflections(word, inflections(locale).singulars) end # Converts strings to UpperCamelCase. # If the +uppercase_first_letter+ parameter is set to false, then produces # lowerCamelCase. # # Also converts '/' to '::' which is useful for converting # paths to namespaces. # # camelize('active_model') # => "ActiveModel" # camelize('active_model', false) # => "activeModel" # camelize('active_model/errors') # => "ActiveModel::Errors" # camelize('active_model/errors', false) # => "activeModel::Errors" # # As a rule of thumb you can think of +camelize+ as the inverse of # #underscore, though there are cases where that does not hold: # # camelize(underscore('SSLError')) # => "SslError" def camelize(term, uppercase_first_letter = true) string = term.to_s if uppercase_first_letter string = string.sub(/^[a-z\d]*/) { |match| inflections.acronyms[match] || match.capitalize } else string = string.sub(/^(?:#{inflections.acronym_regex}(?=\b|[A-Z_])|\w)/) { |match| match.downcase } end string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" } string.gsub!('/'.freeze, '::'.freeze) string end # Makes an underscored, lowercase form from the expression in the string. # # Changes '::' to '/' to convert namespaces to paths. # # underscore('ActiveModel') # => "active_model" # underscore('ActiveModel::Errors') # => "active_model/errors" # # As a rule of thumb you can think of +underscore+ as the inverse of # #camelize, though there are cases where that does not hold: # # camelize(underscore('SSLError')) # => "SslError" def underscore(camel_cased_word) return camel_cased_word unless camel_cased_word =~ /[A-Z-]|::/ word = camel_cased_word.to_s.gsub('::'.freeze, '/'.freeze) word.gsub!(/(?:(?<=([A-Za-z\d]))|\b)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1 && '_'.freeze }#{$2.downcase}" } word.gsub!(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2'.freeze) word.gsub!(/([a-z\d])([A-Z])/, '\1_\2'.freeze) word.tr!("-".freeze, "_".freeze) word.downcase! word end # Tweaks an attribute name for display to end users. # # Specifically, performs these transformations: # # * Applies human inflection rules to the argument. # * Deletes leading underscores, if any. # * Removes a "_id" suffix if present. # * Replaces underscores with spaces, if any. # * Downcases all words except acronyms. # * Capitalizes the first word. # # The capitalization of the first word can be turned off by setting the # +:capitalize+ option to false (default is true). # # humanize('employee_salary') # => "Employee salary" # humanize('author_id') # => "Author" # humanize('author_id', capitalize: false) # => "author" # humanize('_id') # => "Id" # # If "SSL" was defined to be an acronym: # # humanize('ssl_error') # => "SSL error" # def humanize(lower_case_and_underscored_word, options = {}) result = lower_case_and_underscored_word.to_s.dup # no humans attr exists on inflections, need to port that over # opal - string mutation inflections.humans.each { |(rule, replacement)| break if (result = result.sub(rule, replacement)) } # opal - \A and \z not supported #result = result.sub(/\A_+/, ''.freeze) result = result.sub(/^_+/, ''.freeze) #result = result.sub(/_id\z/, ''.freeze) result = result.sub(/_id$/, ''.freeze) result = result.tr('_'.freeze, ' '.freeze) result = result.gsub(/([a-z\d]*)/i) do |match| "#{inflections.acronyms[match] || match.downcase}" end if options.fetch(:capitalize, true) #result = result.sub(/\A\w/) { |match| match.upcase } result = result.sub(/^\w/) { |match| match.upcase } end result end # Capitalizes all the words and replaces some characters in the string to # create a nicer looking title. +titleize+ is meant for creating pretty # output. It is not used in the Rails internals. # # +titleize+ is also aliased as +titlecase+. # # titleize('man from the boondocks') # => "Man From The Boondocks" # titleize('x-men: the last stand') # => "X Men: The Last Stand" # titleize('TheManWithoutAPast') # => "The Man Without A Past" # titleize('raiders_of_the_lost_ark') # => "Raiders Of The Lost Ark" # Creates the name of a table like Rails does for models to table names. # This method uses the #pluralize method on the last word in the string. # # tableize('RawScaledScorer') # => "raw_scaled_scorers" # tableize('ham_and_egg') # => "ham_and_eggs" # tableize('fancyCategory') # => "fancy_categories" def tableize(class_name) pluralize(underscore(class_name)) end # Creates a class name from a plural table name like Rails does for table # names to models. Note that this returns a string and not a Class (To # convert to an actual class follow +classify+ with #constantize). # # classify('ham_and_eggs') # => "HamAndEgg" # classify('posts') # => "Post" # # Singular names are not handled correctly: # # classify('calculus') # => "Calculu" def classify(table_name) # strip out any leading schema name camelize(singularize(table_name.to_s.sub(/.*\./, ''.freeze))) end # Replaces underscores with dashes in the string. # # dasherize('puni_puni') # => "puni-puni" def dasherize(underscored_word) underscored_word.tr('_'.freeze, '-'.freeze) end # Removes the module part from the expression in the string. # # demodulize('ActiveRecord::CoreExtensions::String::Inflections') # => "Inflections" # demodulize('Inflections') # => "Inflections" # demodulize('::Inflections') # => "Inflections" # demodulize('') # => "" # # See also #deconstantize. def demodulize(path) path = path.to_s if i = path.rindex('::') path[(i+2)..-1] else path end end # Removes the rightmost segment from the constant expression in the string. # # deconstantize('Net::HTTP') # => "Net" # deconstantize('::Net::HTTP') # => "::Net" # deconstantize('String') # => "" # deconstantize('::String') # => "" # deconstantize('') # => "" # # See also #demodulize. def deconstantize(path) path.to_s[0, path.rindex('::') || 0] # implementation based on the one in facets' Module#spacename end # Creates a foreign key name from a class name. # +separate_class_name_and_id_with_underscore+ sets whether # the method should put '_' between the name and 'id'. # # foreign_key('Message') # => "message_id" # foreign_key('Message', false) # => "messageid" # foreign_key('Admin::Post') # => "post_id" def foreign_key(class_name, separate_class_name_and_id_with_underscore = true) underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id") end # Tries to find a constant with the name specified in the argument string. # # 'Module'.constantize # => Module # 'Foo::Bar'.constantize # => Foo::Bar # # The name is assumed to be the one of a top-level constant, no matter # whether it starts with "::" or not. No lexical context is taken into # account: # # C = 'outside' # module M # C = 'inside' # C # => 'inside' # 'C'.constantize # => 'outside', same as ::C # end # # NameError is raised when the name is not in CamelCase or the constant is # unknown. def constantize(camel_cased_word) names = camel_cased_word.split('::'.freeze) # Trigger a built-in NameError exception including the ill-formed constant in the message. Object.const_get(camel_cased_word) if names.empty? # Remove the first blank element in case of '::ClassName' notation. names.shift if names.size > 1 && names.first.empty? names.inject(Object) do |constant, name| if constant == Object constant.const_get(name) else candidate = constant.const_get(name) next candidate if constant.const_defined?(name, false) next candidate unless Object.const_defined?(name) # Go down the ancestors to check if it is owned directly. The check # stops when we reach Object or the end of ancestors tree. constant = constant.ancestors.inject do |const, ancestor| break const if ancestor == Object break ancestor if ancestor.const_defined?(name, false) const end # owner is in Object, so raise constant.const_get(name, false) end end end # Tries to find a constant with the name specified in the argument string. # # safe_constantize('Module') # => Module # safe_constantize('Foo::Bar') # => Foo::Bar # # The name is assumed to be the one of a top-level constant, no matter # whether it starts with "::" or not. No lexical context is taken into # account: # # C = 'outside' # module M # C = 'inside' # C # => 'inside' # safe_constantize('C') # => 'outside', same as ::C # end # # +nil+ is returned when the name is not in CamelCase or the constant (or # part of it) is unknown. # # safe_constantize('blargle') # => nil # safe_constantize('UnknownModule') # => nil # safe_constantize('UnknownModule::Foo::Bar') # => nil def safe_constantize(camel_cased_word) constantize(camel_cased_word) rescue NameError => e raise if e.name && !(camel_cased_word.to_s.split("::").include?(e.name.to_s) || e.name.to_s == camel_cased_word.to_s) rescue ArgumentError => e raise unless e.message =~ /not missing constant #{const_regexp(camel_cased_word)}\!$/ end # Returns the suffix that should be added to a number to denote the position # in an ordered sequence such as 1st, 2nd, 3rd, 4th. # # ordinal(1) # => "st" # ordinal(2) # => "nd" # ordinal(1002) # => "nd" # ordinal(1003) # => "rd" # ordinal(-11) # => "th" # ordinal(-1021) # => "st" def ordinal(number) abs_number = number.to_i.abs if (11..13).include?(abs_number % 100) "th" else case abs_number % 10 when 1; "st" when 2; "nd" when 3; "rd" else "th" end end end # Turns a number into an ordinal string used to denote the position in an # ordered sequence such as 1st, 2nd, 3rd, 4th. # # ordinalize(1) # => "1st" # ordinalize(2) # => "2nd" # ordinalize(1002) # => "1002nd" # ordinalize(1003) # => "1003rd" # ordinalize(-11) # => "-11th" # ordinalize(-1021) # => "-1021st" def ordinalize(number) "#{number}#{ordinal(number)}" end private # Mounts a regular expression, returned as a string to ease interpolation, # that will match part by part the given constant. # # const_regexp("Foo::Bar::Baz") # => "Foo(::Bar(::Baz)?)?" # const_regexp("::") # => "::" def const_regexp(camel_cased_word) #:nodoc: parts = camel_cased_word.split("::".freeze) return Regexp.escape(camel_cased_word) if parts.blank? last = parts.pop parts.reverse.inject(last) do |acc, part| part.empty? ? acc : "#{part}(::#{acc})?" end end # Applies inflection rules for +singularize+ and +pluralize+. # # apply_inflections('post', inflections.plurals) # => "posts" # apply_inflections('posts', inflections.singulars) # => "post" def apply_inflections(word, rules) result = word.to_s.dup if word.empty? || inflections.uncountables.uncountable?(result) result else rules.each { |(rule, replacement)| break if result.sub!(rule, replacement) } result end end end
bitbucket-rest-api/bitbucket
lib/bitbucket_rest_api/teams.rb
BitBucket.Teams.followers
ruby
def followers(team_name) response = get_request("/2.0/teams/#{team_name.to_s}/followers") return response["values"] unless block_given? response["values"].each { |el| yield el } end
List followers of the provided team = Examples bitbucket = BitBucket.new :oauth_token => '...', :oauth_secret => '...' bitbucket.teams.followers(:team_name_here) bitbucket.teams.followers(:team_name_here) { |follower| ... }
train
https://github.com/bitbucket-rest-api/bitbucket/blob/e03b6935104d59b3d9a922474c3dc210a5ef76d2/lib/bitbucket_rest_api/teams.rb#L54-L58
class Teams < API extend AutoloadHelper def initialize(options = { }) super(options) end # List teams for the authenticated user where the user has the provided role # Roles are :admin, :contributor, :member # # = Examples # bitbucket = BitBucket.new :oauth_token => '...', :oauth_secret => '...' # bitbucket.teams.list(:admin) # bitbucket.teams.list('member') # bitbucket.teams.list(:contributor) { |team| ... } def list(user_role) response = get_request("/2.0/teams/?role=#{user_role.to_s}") return response["values"] unless block_given? response["values"].each { |el| yield el } end alias :all :list # Return the profile for the provided team # # = Example # bitbucket = BitBucket.new :oauth_token => '...', :oauth_secret => '...' # bitbucket.teams.profile(:team_name_here) def profile(team_name) get_request("/2.0/teams/#{team_name.to_s}") end # List members of the provided team # # = Examples # bitbucket = BitBucket.new :oauth_token => '...', :oauth_secret => '...' # bitbucket.teams.members(:team_name_here) # bitbucket.teams.members(:team_name_here) { |member| ... } def members(team_name) response = get_request("/2.0/teams/#{team_name.to_s}/members") return response["values"] unless block_given? response["values"].each { |el| yield el } end # List followers of the provided team # # = Examples # bitbucket = BitBucket.new :oauth_token => '...', :oauth_secret => '...' # bitbucket.teams.followers(:team_name_here) # bitbucket.teams.followers(:team_name_here) { |follower| ... } # List accounts following the provided team # # = Examples # bitbucket = BitBucket.new :oauth_token => '...', :oauth_secret => '...' # bitbucket.teams.following(:team_name_here) # bitbucket.teams.following(:team_name_here) { |followee| ... } def following(team_name) response = get_request("/2.0/teams/#{team_name.to_s}/following") return response["values"] unless block_given? response["values"].each { |el| yield el } end # List repos for provided team # Private repos will only be returned if the user is authorized to view them # # = Examples # bitbucket = BitBucket.new :oauth_token => '...', :oauth_secret => '...' # bitbucket.teams.repos(:team_name_here) # bitbucket.teams.repos(:team_name_here) { |repo| ... } def repos(team_name) response = get_request("/2.0/repositories/#{team_name.to_s}") return response["values"] unless block_given? response["values"].each { |el| yield el } end alias :repositories :repos end # Team
senchalabs/jsduck
lib/jsduck/news.rb
JsDuck.News.filter_new_members
ruby
def filter_new_members(cls) members = cls.all_local_members.find_all do |m| visible?(m) && (m[:new] || new_params?(m)) end members = discard_accessors(members) members.sort! {|a, b| a[:name] <=> b[:name] } end
Returns all members of a class that have been marked as new, or have parameters marked as new.
train
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/news.rb#L68-L74
class News # Creates News object from relations data when --import option # specified. def self.create(relations, doc_formatter, opts) if opts.import.length > 0 News.new(relations, doc_formatter) else Util::NullObject.new(:to_html => "") end end # Generates list of new classes & members in this version. def initialize(relations, doc_formatter) @doc_formatter = doc_formatter @columns = Columns.new(:members) @new_items = filter_new_items(relations) end # Returns the HTML def to_html(style="") return [ "<div id='news-content' style='#{style}'>", "<div class='section'>", "<h1>New in this version</h1>", render_news(@new_items), "<div style='clear:both'></div>", "</div>", "</div>", ].flatten.join("\n") end private def filter_new_items(relations) classes = [] new_items = [] relations.each do |cls| if !cls[:private] if cls[:new] classes << cls else members = filter_new_members(cls) if members.length > 0 new_items << {:name => cls[:name], :members => members} end end end end new_items.sort! {|a, b| a[:name] <=> b[:name] } # Place the new classes section at the beginning if classes.length > 0 new_items.unshift({:name => "New classes", :members => classes}) end new_items end # Returns all members of a class that have been marked as new, or # have parameters marked as new. def visible?(member) !member[:private] && !member[:hide] end def new_params?(member) Array(member[:params]).any? {|p| p[:new] } end def discard_accessors(members) accessors = {} members.find_all {|m| m[:accessor] }.each do |cfg| accessors["set" + upcase_first(cfg[:name])] = true accessors["get" + upcase_first(cfg[:name])] = true accessors[cfg[:name].downcase + "change"] = true if cfg[:evented] end members.reject {|m| accessors[m[:name]] } end def upcase_first(str) str[0,1].upcase + str[1..-1] end def render_news(new_items) if new_items.length > 0 render_columns(new_items) else "<h3>Nothing new.</h3>" end end def render_columns(new_items) align = ["left-column", "middle-column", "right-column"] i = -1 return @columns.split(new_items, 3).map do |col| i += 1 [ "<div class='#{align[i]}'>", render_col(col), "</div>", ] end end def render_col(col) return col.map do |item| [ "<h3>#{item[:name]}</h3>", "<ul class='links'>", item[:members].map {|m| "<li>" + link(m) + "</li>" }, "</ul>", ] end end def link(m) if m[:tagname] == :class @doc_formatter.link(m[:name], nil, m[:name]) else @doc_formatter.link(m[:owner], m[:name], m[:name], m[:tagname], m[:static]) + params_note(m) end end def params_note(m) if !m[:new] && new_params?(m) " <small>+parameters</small>" else "" end end end
rossf7/elasticrawl
lib/elasticrawl/config.rb
Elasticrawl.Config.load_config
ruby
def load_config(config_file) if dir_exists? begin config_file = File.join(config_dir, "#{config_file}.yml") config = YAML::load(File.open(config_file)) rescue StandardError => e raise FileAccessError, e.message end else raise ConfigDirMissingError, 'Config dir missing. Run init command' end end
Loads a YAML configuration file.
train
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/config.rb#L57-L69
class Config CONFIG_DIR = '.elasticrawl' DATABASE_FILE = 'elasticrawl.sqlite3' TEMPLATES_DIR = '../../templates' TEMPLATE_FILES = ['aws.yml', 'cluster.yml', 'jobs.yml'] attr_reader :access_key_id attr_reader :secret_access_key # Sets the AWS access credentials needed for the S3 and EMR API calls. def initialize(access_key_id = nil, secret_access_key = nil) # Credentials have been provided to the init command. @access_key_id = access_key_id @secret_access_key = secret_access_key # If credentials are not set then check if they are available in aws.yml. if dir_exists? config = load_config('aws') key = config['access_key_id'] secret = config['secret_access_key'] @access_key_id ||= key unless key == 'ACCESS_KEY_ID' @secret_access_key ||= secret unless secret == 'SECRET_ACCESS_KEY' end # If credentials are still not set then check AWS environment variables. @access_key_id ||= ENV['AWS_ACCESS_KEY_ID'] @secret_access_key ||= ENV['AWS_SECRET_ACCESS_KEY'] # Set AWS credentials for use when accessing the S3 API. AWS.config(:access_key_id => @access_key_id, :secret_access_key => @secret_access_key) end # Returns the location of the config directory. def config_dir File.join(Dir.home, CONFIG_DIR) end # Checks if the configuration directory exists. def dir_exists? Dir.exists?(config_dir) end # Loads a YAML configuration file. # Loads the sqlite database. If no database exists it will be created # and the database migrations will be run. def load_database if dir_exists? config = { 'adapter' => 'sqlite3', 'database' => File.join(config_dir, DATABASE_FILE), 'pool' => 5, 'timeout' => 5000 } begin ActiveRecord::Base.establish_connection(config) ActiveRecord::Migrator.migrate(File.join(File.dirname(__FILE__), \ '../../db/migrate'), ENV['VERSION'] ? ENV['VERSION'].to_i : nil ) rescue StandardError => e raise DatabaseAccessError, e.message end else raise ConfigDirMissingError, 'Config dir missing. Run init command' end end # Checks if a S3 bucket name is in use. def bucket_exists?(bucket_name) begin s3 = AWS::S3.new s3.buckets[bucket_name].exists? rescue AWS::S3::Errors::SignatureDoesNotMatch => e raise AWSCredentialsInvalidError, 'AWS access credentials are invalid' rescue AWS::Errors::Base => s3e raise S3AccessError.new(s3e.http_response), s3e.message end end # Creates the S3 bucket and config directory. Deploys the config templates # and creates the sqlite database. def create(bucket_name) create_bucket(bucket_name) deploy_templates(bucket_name) load_database status_message(bucket_name, 'created') end # Deletes the S3 bucket and config directory. def delete bucket_name = load_config('jobs')['s3_bucket_name'] delete_bucket(bucket_name) delete_config_dir status_message(bucket_name, 'deleted') end # Displayed by destroy command to confirm deletion. def delete_warning bucket_name = load_config('jobs')['s3_bucket_name'] message = ['WARNING:'] message << "Bucket s3://#{bucket_name} and its data will be deleted" message << "Config dir #{config_dir} will be deleted" message.join("\n") end # Displayed by init command. def access_key_prompt prompt = "Enter AWS Access Key ID:" prompt += " [#{@access_key_id}]" if @access_key_id.present? prompt end # Displayed by init command. def secret_key_prompt prompt = "Enter AWS Secret Access Key:" prompt += " [#{@secret_access_key}]" if @secret_access_key.present? prompt end private # Creates a bucket using the S3 API. def create_bucket(bucket_name) begin s3 = AWS::S3.new s3.buckets.create(bucket_name) rescue AWS::Errors::Base => s3e raise S3AccessError.new(s3e.http_response), s3e.message end end # Deletes a bucket and its contents using the S3 API. def delete_bucket(bucket_name) begin s3 = AWS::S3.new bucket = s3.buckets[bucket_name] bucket.delete! rescue AWS::Errors::Base => s3e raise S3AccessError.new(s3e.http_response), s3e.message end end # Creates config directory and copies config templates into it. # Saves S3 bucket name to jobs.yml and AWS credentials to aws.yml. def deploy_templates(bucket_name) begin Dir.mkdir(config_dir, 0755) if dir_exists? == false TEMPLATE_FILES.each do |template_file| FileUtils.cp(File.join(File.dirname(__FILE__), TEMPLATES_DIR, template_file), File.join(config_dir, template_file)) end save_config('jobs', { 'BUCKET_NAME' => bucket_name }) save_aws_config rescue StandardError => e raise FileAccessError, e.message end end # Saves AWS access credentials to aws.yml unless they are configured as # environment variables. def save_aws_config env_key = ENV['AWS_ACCESS_KEY_ID'] env_secret = ENV['AWS_SECRET_ACCESS_KEY'] creds = {} creds['ACCESS_KEY_ID'] = @access_key_id unless @access_key_id == env_key creds['SECRET_ACCESS_KEY'] = @secret_access_key \ unless @secret_access_key == env_secret save_config('aws', creds) end # Saves config values by overwriting placeholder values in template. def save_config(template, params) config_file = File.join(config_dir, "#{template}.yml") config = File.read(config_file) params.map { |key, value| config = config.gsub(key, value) } File.open(config_file, 'w') { |file| file.write(config) } end # Deletes the config directory including its contents. def delete_config_dir begin FileUtils.rm_r(config_dir) if dir_exists? rescue StandardError => e raise FileAccessError, e.message end end # Notifies user of results of init or destroy commands. def status_message(bucket_name, state) message = ['', "Bucket s3://#{bucket_name} #{state}"] message << "Config dir #{config_dir} #{state}" state = 'complete' if state == 'created' message << "Config #{state}" message.join("\n") end end
tarcieri/cool.io
lib/cool.io/meta.rb
Coolio.Meta.watcher_delegate
ruby
def watcher_delegate(proxy_var) %w{attach attached? detach enable disable}.each do |method| module_eval <<-EOD def #{method}(*args) if defined? #{proxy_var} and #{proxy_var} #{proxy_var}.#{method}(*args) return self end super end EOD end end
Use an alternate watcher with the attach/detach/enable/disable methods if it is presently assigned. This is useful if you are waiting for an event to occur before the current watcher can be used in earnest, such as making an outgoing TCP connection.
train
https://github.com/tarcieri/cool.io/blob/0fd3fd1d8e8d81e24f79f809979367abc3f52b92/lib/cool.io/meta.rb#L13-L26
module Meta # Use an alternate watcher with the attach/detach/enable/disable methods # if it is presently assigned. This is useful if you are waiting for # an event to occur before the current watcher can be used in earnest, # such as making an outgoing TCP connection. # Define callbacks whose behavior can be changed on-the-fly per instance. # This is done by giving a block to the callback method, which is captured # as a proc and stored for later. If the method is called without a block, # the stored block is executed if present, otherwise it's a noop. def event_callback(*methods) methods.each do |method| module_eval <<-EOD remove_method "#{method}" def #{method}(*args, &block) if block @#{method}_callback = block return end if defined? @#{method}_callback and @#{method}_callback @#{method}_callback.call(*args) end end EOD end end end
dennisreimann/masq
app/controllers/masq/server_controller.rb
Masq.ServerController.decide
ruby
def decide @site = current_account.sites.find_or_initialize_by_url(checkid_request.trust_root) @site.persona = current_account.personas.find(params[:persona_id] || :first) if sreg_request || ax_store_request || ax_fetch_request end
Displays the decision page on that the user can confirm the request and choose which data should be transfered to the relying party.
train
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/controllers/masq/server_controller.rb#L64-L67
class ServerController < BaseController # CSRF-protection must be skipped, because incoming # OpenID requests lack an authenticity token skip_before_filter :verify_authenticity_token # Error handling rescue_from OpenID::Server::ProtocolError, :with => :render_openid_error # Actions other than index require a logged in user before_filter :login_required, :except => [:index, :cancel, :seatbelt_config, :seatbelt_login_state] before_filter :ensure_valid_checkid_request, :except => [:index, :cancel, :seatbelt_config, :seatbelt_login_state] after_filter :clear_checkid_request, :only => [:cancel, :complete] # These methods are used to display information about the request to the user helper_method :sreg_request, :ax_fetch_request, :ax_store_request # This is the server endpoint which handles all incoming OpenID requests. # Associate and CheckAuth requests are answered directly - functionality # therefor is provided by the ruby-openid gem. Handling of CheckId requests # dependents on the users login state (see handle_checkid_request). # Yadis requests return information about this endpoint. def index clear_checkid_request respond_to do |format| format.html do if openid_request.is_a?(OpenID::Server::CheckIDRequest) handle_checkid_request elsif openid_request handle_non_checkid_request else render :text => t(:this_is_openid_not_a_human_ressource) end end format.xrds end end # This action decides how to process the current request and serves as # dispatcher and re-entry in case the request could not be processed # directly (for instance if the user had to log in first). # When the user has already trusted the relying party, the request will # be answered based on the users release policy. If the request is immediate # (relying party wants no user interaction, used e.g. for ajax requests) # the request can only be answered if no further information (like simple # registration data) is requested. Otherwise the user will be redirected # to the decision page. def proceed identity = identifier(current_account) if @site = current_account.sites.find_by_url(checkid_request.trust_root) resp = checkid_request.answer(true, nil, identity) resp = add_sreg(resp, @site.sreg_properties) if sreg_request resp = add_ax(resp, @site.ax_properties) if ax_fetch_request resp = add_pape(resp, auth_policies, auth_level, auth_time) render_response(resp) elsif checkid_request.immediate && (sreg_request || ax_store_request || ax_fetch_request) render_response(checkid_request.answer(false)) elsif checkid_request.immediate render_response(checkid_request.answer(true, nil, identity)) else redirect_to decide_path end end # Displays the decision page on that the user can confirm the request and # choose which data should be transfered to the relying party. # This action is called by submitting the decision form, the information entered by # the user is used to answer the request. If the user decides to always trust the # relying party, a new site according to the release policies the will be created. def complete if params[:cancel] cancel else resp = checkid_request.answer(true, nil, identifier(current_account)) if params[:always] @site = current_account.sites.find_or_create_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url]) @site.update_attributes(params[:site]) elsif sreg_request || ax_fetch_request @site = current_account.sites.find_or_initialize_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url]) @site.attributes = params[:site] elsif ax_store_request @site = current_account.sites.find_or_initialize_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url]) not_supported, not_accepted, accepted = [], [], [] ax_store_request.data.each do |type_uri, values| if property = Persona.attribute_name_for_type_uri(type_uri) store_attribute = params[:site][:ax_store][property.to_sym] if store_attribute && !store_attribute[:value].blank? @site.persona.update_attribute(property, values.first) accepted << type_uri else not_accepted << type_uri end else not_supported << type_uri end end ax_store_response = (accepted.count > 0) ? OpenID::AX::StoreResponse.new : OpenID::AX::StoreResponse.new(false, "None of the attributes were accepted.") resp.add_extension(ax_store_response) end resp = add_pape(resp, auth_policies, auth_level, auth_time) resp = add_sreg(resp, @site.sreg_properties) if sreg_request && @site.sreg_properties resp = add_ax(resp, @site.ax_properties) if ax_fetch_request && @site.ax_properties render_response(resp) end end # Cancels the current OpenID request def cancel redirect_to checkid_request.cancel_url end protected # Decides how to process an incoming checkid request. If the user is # already logged in he will be forwarded to the proceed action. If # the user is not logged in and the request is immediate, the request # cannot be answered successfully. In case the user is not logged in, # the request will be stored and the user is asked to log in. def handle_checkid_request if allow_verification? save_checkid_request redirect_to proceed_path elsif openid_request.immediate render_response(openid_request.answer(false)) else reset_session request = save_checkid_request session[:return_to] = proceed_path redirect_to( request.from_trusted_domain? ? login_path : safe_login_path ) end end # Stores the current OpenID request. # Returns the OpenIdRequest def save_checkid_request clear_checkid_request request = OpenIdRequest.create!(:parameters => openid_params) session[:request_token] = request.token request end # Deletes the old request when a new one comes in. def clear_checkid_request unless session[:request_token].blank? OpenIdRequest.destroy_all :token => session[:request_token] session[:request_token] = nil end end # Use this as before_filter for every CheckID request based action. # Loads the current openid request and cancels if none can be found. # The user has to log in, if he has not verified his ownership of # the identifier, yet. def ensure_valid_checkid_request self.openid_request = checkid_request if !openid_request.is_a?(OpenID::Server::CheckIDRequest) redirect_to root_path, :alert => t(:identity_verification_request_invalid) elsif !allow_verification? flash[:notice] = logged_in? && !pape_requirements_met?(auth_time) ? t(:service_provider_requires_reauthentication_last_login_too_long_ago) : t(:login_to_verify_identity) session[:return_to] = proceed_path redirect_to login_path end end # The user must be logged in, he must be the owner of the claimed identifier # and the PAPE requirements must be met if applicable. def allow_verification? logged_in? && correct_identifier? && pape_requirements_met?(auth_time) end # Is the user allowed to verify the claimed identifier? The user # must be logged in, so that we know his identifier or the identifier # has to be selected by the server (id_select). def correct_identifier? (openid_request.identity == identifier(current_account) || openid_request.id_select) end # Clears the stored request and answers def render_response(resp) clear_checkid_request render_openid_response(resp) end # Transforms the parameters from the form to valid AX response values def transform_ax_data(parameters) data = {} parameters.each_pair do |key, details| if details['value'] data["type.#{key}"] = details['type'] data["value.#{key}"] = details['value'] end end data end # Renders the exception message as text output def render_openid_error(exception) error = case exception when OpenID::Server::MalformedTrustRoot then "Malformed trust root '#{exception.to_s}'" else exception.to_s end render :text => h("Invalid OpenID request: #{error}"), :status => 500 end private # The NIST Assurance Level, see: # http://openid.net/specs/openid-provider-authentication-policy-extension-1_0-01.html#anchor12 def auth_level if Masq::Engine.config.masq['use_ssl'] current_account.last_authenticated_with_yubikey? ? 3 : 2 else 0 end end def auth_time current_account.last_authenticated_at end def auth_policies current_account.last_authenticated_with_yubikey? ? [OpenID::PAPE::AUTH_MULTI_FACTOR, OpenID::PAPE::AUTH_PHISHING_RESISTANT] : [] end end
arvicco/win_gui
old_code/lib/win_gui/def_api.rb
WinGui.DefApi.def_api
ruby
def def_api(function, params, returns, options={}, &define_block) name, aliases = generate_names(function, options) boolean = options[:boolean] zeronil = options[:zeronil] proto = params.respond_to?(:join) ? params.join : params # Convert params into prototype string api = Win32::API.new(function, proto.upcase, returns.upcase, options[:dll] || DEFAULT_DLL) define_method(function) {|*args| api.call(*args)} # define CamelCase method wrapper for api call define_method(name) do |*args, &runtime_block| # define snake_case method with enhanced api return api if args == [:api] return define_block[api, *args, &runtime_block] if define_block WinGui.enforce_count(args, proto) result = api.call(*args) result = runtime_block[result] if runtime_block return result != 0 if boolean # Boolean function returns true/false instead of nonzero/zero return nil if zeronil && result == 0 # Zeronil function returns nil instead of zero result end aliases.each {|ali| alias_method ali, name } # define aliases end
Defines new method wrappers for Windows API function call: - Defines method with original (CamelCase) API function name and original signature (matches MSDN description) - Defines method with snake_case name (converted from CamelCase function name) with enhanced API signature When the defined wrapper method is called, it checks the argument count, executes underlying API function call and (optionally) transforms the result before returning it. If block is attached to method invocation, raw result is yielded to this block before final transformations - Defines aliases for enhanced method with more Rubyesque names for getters, setters and tests: GetWindowText -> window_test, SetWindowText -> window_text=, IsZoomed -> zoomed? You may modify default behavior of defined method by providing optional &define_block to def_api. If you do so, instead of directly calling API function, defined method just yields callable api object, arguments and (optional) runtime block to your &define_block and returns result coming out of it. So, &define_block should define all the behavior of defined method. You can use define_block to: - Change original signature of API function, provide argument defaults, check argument types - Pack arguments into strings for [in] or [in/out] parameters that expect a pointer - Allocate string buffers for pointers required by API functions [out] parameters - Unpack [out] and [in/out] parameters returned as pointers - Explicitly return results of API call that are returned in [out] and [in/out] parameters - Convert attached runtime blocks into callback functions and stuff them into [in] callback parameters Accepts following options: :dll:: Use this dll instead of default 'user32' :rename:: Use this name instead of standard (conventional) function name :alias(es):: Provides additional alias(es) for defined method :boolean:: Forces method to return true/false instead of nonzero/zero :zeronil:: Forces method to return nil if function result is zero
train
https://github.com/arvicco/win_gui/blob/a3a4c18db2391144fcb535e4be2f0fb47e9dcec7/old_code/lib/win_gui/def_api.rb#L36-L56
module DefApi # DLL to use with API decarations by default ('user32') DEFAULT_DLL = 'user32' ## # Defines new method wrappers for Windows API function call: # - Defines method with original (CamelCase) API function name and original signature (matches MSDN description) # - Defines method with snake_case name (converted from CamelCase function name) with enhanced API signature # When the defined wrapper method is called, it checks the argument count, executes underlying API # function call and (optionally) transforms the result before returning it. If block is attached to # method invocation, raw result is yielded to this block before final transformations # - Defines aliases for enhanced method with more Rubyesque names for getters, setters and tests: # GetWindowText -> window_test, SetWindowText -> window_text=, IsZoomed -> zoomed? # # You may modify default behavior of defined method by providing optional &define_block to def_api. # If you do so, instead of directly calling API function, defined method just yields callable api # object, arguments and (optional) runtime block to your &define_block and returns result coming out of it. # So, &define_block should define all the behavior of defined method. You can use define_block to: # - Change original signature of API function, provide argument defaults, check argument types # - Pack arguments into strings for [in] or [in/out] parameters that expect a pointer # - Allocate string buffers for pointers required by API functions [out] parameters # - Unpack [out] and [in/out] parameters returned as pointers # - Explicitly return results of API call that are returned in [out] and [in/out] parameters # - Convert attached runtime blocks into callback functions and stuff them into [in] callback parameters # # Accepts following options: # :dll:: Use this dll instead of default 'user32' # :rename:: Use this name instead of standard (conventional) function name # :alias(es):: Provides additional alias(es) for defined method # :boolean:: Forces method to return true/false instead of nonzero/zero # :zeronil:: Forces method to return nil if function result is zero # # Generates name and aliases for defined method based on function name, # sets boolean flag for test functions (Is...) # def generate_names(function, options) aliases = ([options[:alias]] + [options[:aliases]]).flatten.compact name = options[:rename] || function.snake_case case name when /^is_/ aliases << name.sub(/^is_/, '') + '?' options[:boolean] = true when /^set_/ aliases << name.sub(/^set_/, '')+ '=' when /^get_/ aliases << name.sub(/^get_/, '') end [name, aliases] end # Ensures that args count is equal to params count plus diff # def enforce_count(args, params, diff = 0) num_args = args.size num_params = params == 'V' ? 0 : params.size + diff if num_args != num_params raise ArgumentError, "wrong number of parameters: expected #{num_params}, got #{num_args}" end end # Converts block into API::Callback object that can be used as API callback argument # def callback(params, returns, &block) Win32::API::Callback.new(params, returns, &block) end private # Helper methods: # # Returns FFI string buffer - used to supply string pointer reference to API functions # # # def buffer(size = 1024, char = "\x00") # FFI.MemoryPointer.from_string(char * size) # end # Returns array of given args if none of them is zero, # if any arg is zero, returns array of nils # def nonzero_array(*args) args.any?{|arg| arg == 0 } ? args.map{||nil} : args end # Procedure that returns (possibly encoded) string as a result of api function call # or nil if zero characters was returned by api call # def return_string( encode = nil ) lambda do |api, *args| WinGui.enforce_count( args, api.prototype, -2) args += [string = buffer, string.length] num_chars = api.call(*args) return nil if num_chars == 0 string = string.force_encoding('utf-16LE').encode(encode) if encode string.rstrip end end # Procedure that calls api function expecting a callback. If runtime block is given # it is converted into actual callback, otherwise procedure returns an array of all # handles pushed into callback by api enumeration # def return_enum lambda do |api, *args, &block| WinGui.enforce_count( args, api.prototype, -1) handles = [] cb = if block callback('LP', 'I', &block) else callback('LP', 'I') do |handle, message| handles << handle true end end args[api.prototype.find_index('K'), 0] = cb # Insert callback into appropriate place of args Array api.call *args handles end end # Procedure that calls (DdeInitialize) function expecting a DdeCallback. Runtime block is converted # into Dde callback and registered with DdeInitialize. Returns DDE init status and DDE instance id. # # TODO: Pushed into this module since RubyMine (wrongly) reports error on lambda args # def return_id_status lambda do |api, id=0, cmd, &block| raise ArgumentError, 'No callback block' unless block callback = callback 'IIPPPPPP', 'L', &block status = api.call(id = [id].pack('L'), callback, cmd, 0) id = status == 0 ? id.unpack('L').first : nil [id, status] end end end
sup-heliotrope/sup
lib/sup/index.rb
Redwood.Index.parse_query
ruby
def parse_query s query = {} subs = HookManager.run("custom-search", :subs => s) || s begin subs = SearchManager.expand subs rescue SearchManager::ExpansionError => e raise ParseError, e.message end subs = subs.gsub(/\b(to|from):(\S+)\b/) do field, value = $1, $2 email_field, name_field = %w(email name).map { |x| "#{field}_#{x}" } if(p = ContactManager.contact_for(value)) "#{email_field}:#{p.email}" elsif value == "me" '(' + AccountManager.user_emails.map { |e| "#{email_field}:#{e}" }.join(' OR ') + ')' else "(#{email_field}:#{value} OR #{name_field}:#{value})" end end ## gmail style "is" operator subs = subs.gsub(/\b(is|has):(\S+)\b/) do field, label = $1, $2 case label when "read" "-label:unread" when "spam" query[:load_spam] = true "label:spam" when "deleted" query[:load_deleted] = true "label:deleted" else "label:#{$2}" end end ## labels are stored lower-case in the index subs = subs.gsub(/\blabel:(\S+)\b/) do label = $1 "label:#{label.downcase}" end ## if we see a label:deleted or a label:spam term anywhere in the query ## string, we set the extra load_spam or load_deleted options to true. ## bizarre? well, because the query allows arbitrary parenthesized boolean ## expressions, without fully parsing the query, we can't tell whether ## the user is explicitly directing us to search spam messages or not. ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to ## search spam messages or not? ## ## so, we rely on the fact that turning these extra options ON turns OFF ## the adding of "-label:deleted" or "-label:spam" terms at the very ## final stage of query processing. if the user wants to search spam ## messages, not adding that is the right thing; if he doesn't want to ## search spam messages, then not adding it won't have any effect. query[:load_spam] = true if subs =~ /\blabel:spam\b/ query[:load_deleted] = true if subs =~ /\blabel:deleted\b/ query[:load_killed] = true if subs =~ /\blabel:killed\b/ ## gmail style attachments "filename" and "filetype" searches subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do field, name = $1, ($3 || $4) case field when "filename" debug "filename: translated #{field}:#{name} to attachment:\"#{name.downcase}\"" "attachment:\"#{name.downcase}\"" when "filetype" debug "filetype: translated #{field}:#{name} to attachment_extension:#{name.downcase}" "attachment_extension:#{name.downcase}" end end lastdate = 2<<32 - 1 firstdate = 0 subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do field, datestr = $1, ($3 || $4) realdate = Chronic.parse datestr, :guess => false, :context => :past if realdate case field when "after" debug "chronic: translated #{field}:#{datestr} to #{realdate.end}" "date:#{realdate.end.to_i}..#{lastdate}" when "before" debug "chronic: translated #{field}:#{datestr} to #{realdate.begin}" "date:#{firstdate}..#{realdate.end.to_i}" else debug "chronic: translated #{field}:#{datestr} to #{realdate}" "date:#{realdate.begin.to_i}..#{realdate.end.to_i}" end else raise ParseError, "can't understand date #{datestr.inspect}" end end ## limit:42 restrict the search to 42 results subs = subs.gsub(/\blimit:(\S+)\b/) do lim = $1 if lim =~ /^\d+$/ query[:limit] = lim.to_i '' else raise ParseError, "non-numeric limit #{lim.inspect}" end end debug "translated query: #{subs.inspect}" qp = Xapian::QueryParser.new qp.database = @xapian qp.stemmer = Xapian::Stem.new($config[:stem_language]) qp.stemming_strategy = Xapian::QueryParser::STEM_SOME qp.default_op = Xapian::Query::OP_AND valuerangeprocessor = Xapian::NumberValueRangeProcessor.new(DATE_VALUENO, 'date:', true) qp.add_valuerangeprocessor(valuerangeprocessor) NORMAL_PREFIX.each { |k,info| info[:prefix].each { |v| qp.add_prefix k, v } } BOOLEAN_PREFIX.each { |k,info| info[:prefix].each { |v| qp.add_boolean_prefix k, v, info[:exclusive] } } begin xapian_query = qp.parse_query(subs, Xapian::QueryParser::FLAG_PHRASE | Xapian::QueryParser::FLAG_BOOLEAN | Xapian::QueryParser::FLAG_LOVEHATE | Xapian::QueryParser::FLAG_WILDCARD) rescue RuntimeError => e raise ParseError, "xapian query parser error: #{e}" end debug "parsed xapian query: #{Util::Query.describe(xapian_query, subs)}" if xapian_query.nil? or xapian_query.empty? raise ParseError, "couldn't parse \"#{s}\" as xapian query " \ "(special characters aren't indexed)" end query[:qobj] = xapian_query query[:text] = s query end
parse a query string from the user. returns a query object that can be passed to any index method with a 'query' argument. raises a ParseError if something went wrong.
train
https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/index.rb#L405-L548
class Index include InteractiveLock INDEX_VERSION = '4' ## dates are converted to integers for xapian, and are used for document ids, ## so we must ensure they're reasonably valid. this typically only affect ## spam. MIN_DATE = Time.at 0 MAX_DATE = Time.at(2**31-1) HookManager.register "custom-search", <<EOS Executes before a string search is applied to the index, returning a new search string. Variables: subs: The string being searched. EOS class LockError < StandardError def initialize h @h = h end def method_missing m; @h[m.to_s] end end include Redwood::Singleton def initialize dir=BASE_DIR @dir = dir FileUtils.mkdir_p @dir @lock = Lockfile.new lockfile, :retries => 0, :max_age => nil @sync_worker = nil @sync_queue = Queue.new @index_mutex = Monitor.new end def lockfile; File.join @dir, "lock" end def lock debug "locking #{lockfile}..." begin @lock.lock rescue Lockfile::MaxTriesLockError raise LockError, @lock.lockinfo_on_disk end end def start_lock_update_thread @lock_update_thread = Redwood::reporting_thread("lock update") do while true sleep 30 @lock.touch_yourself end end end def stop_lock_update_thread @lock_update_thread.kill if @lock_update_thread @lock_update_thread = nil end def unlock if @lock && @lock.locked? debug "unlocking #{lockfile}..." @lock.unlock end end def load failsafe=false SourceManager.load_sources load_index failsafe end def save debug "saving index and sources..." FileUtils.mkdir_p @dir unless File.exist? @dir SourceManager.save_sources save_index end def get_xapian @xapian end def load_index failsafe=false path = File.join(@dir, 'xapian') if File.exist? path @xapian = Xapian::WritableDatabase.new(path, Xapian::DB_OPEN) db_version = @xapian.get_metadata 'version' db_version = '0' if db_version.empty? if false info "Upgrading index format #{db_version} to #{INDEX_VERSION}" @xapian.set_metadata 'version', INDEX_VERSION elsif db_version != INDEX_VERSION fail "This Sup version expects a v#{INDEX_VERSION} index, but you have an existing v#{db_version} index. Please run sup-dump to save your labels, move #{path} out of the way, and run sup-sync --restore." end else @xapian = Xapian::WritableDatabase.new(path, Xapian::DB_CREATE) @xapian.set_metadata 'version', INDEX_VERSION @xapian.set_metadata 'rescue-version', '0' end @enquire = Xapian::Enquire.new @xapian @enquire.weighting_scheme = Xapian::BoolWeight.new @enquire.docid_order = Xapian::Enquire::ASCENDING end def add_message m; sync_message m, true end def update_message m; sync_message m, true end def update_message_state m; sync_message m[0], false, m[1] end def save_index info "Flushing Xapian updates to disk. This may take a while..." @xapian.flush end def contains_id? id synchronize { find_docid(id) && true } end def contains? m; contains_id? m.id end def size synchronize { @xapian.doccount } end def empty?; size == 0 end ## Yields a message-id and message-building lambda for each ## message that matches the given query, in descending date order. ## You should probably not call this on a block that doesn't break ## rather quickly because the results can be very large. def each_id_by_date query={} each_id(query) { |id| yield id, lambda { build_message id } } end ## Return the number of matches for query in the index def num_results_for query={} xapian_query = build_xapian_query query matchset = run_query xapian_query, 0, 0, 100 matchset.matches_estimated end ## check if a message is part of a killed thread ## (warning: duplicates code below) ## NOTE: We can be more efficient if we assume every ## killed message that hasn't been initially added ## to the indexi s this way def message_joining_killed? m return false unless doc = find_doc(m.id) queue = doc.value(THREAD_VALUENO).split(',') seen_threads = Set.new seen_messages = Set.new [m.id] while not queue.empty? thread_id = queue.pop next if seen_threads.member? thread_id return true if thread_killed?(thread_id) seen_threads << thread_id docs = term_docids(mkterm(:thread, thread_id)).map { |x| @xapian.document x } docs.each do |doc| msgid = doc.value MSGID_VALUENO next if seen_messages.member? msgid seen_messages << msgid queue.concat doc.value(THREAD_VALUENO).split(',') end end false end ## yield all messages in the thread containing 'm' by repeatedly ## querying the index. yields pairs of message ids and ## message-building lambdas, so that building an unwanted message ## can be skipped in the block if desired. ## ## only two options, :limit and :skip_killed. if :skip_killed is ## true, stops loading any thread if a message with a :killed flag ## is found. def each_message_in_thread_for m, opts={} # TODO thread by subject return unless doc = find_doc(m.id) queue = doc.value(THREAD_VALUENO).split(',') msgids = [m.id] seen_threads = Set.new seen_messages = Set.new [m.id] while not queue.empty? thread_id = queue.pop next if seen_threads.member? thread_id return false if opts[:skip_killed] && thread_killed?(thread_id) seen_threads << thread_id docs = term_docids(mkterm(:thread, thread_id)).map { |x| @xapian.document x } docs.each do |doc| msgid = doc.value MSGID_VALUENO next if seen_messages.member? msgid msgids << msgid seen_messages << msgid queue.concat doc.value(THREAD_VALUENO).split(',') end end msgids.each { |id| yield id, lambda { build_message id } } true end ## Load message with the given message-id from the index def build_message id entry = synchronize { get_entry id } return unless entry locations = entry[:locations].map do |source_id,source_info| source = SourceManager[source_id] raise "invalid source #{source_id}" unless source Location.new source, source_info end m = Message.new :locations => locations, :labels => entry[:labels], :snippet => entry[:snippet] # Try to find person from contacts before falling back to # generating it from the address. mk_person = lambda { |x| Person.from_name_and_email(*x.reverse!) } entry[:from] = mk_person[entry[:from]] entry[:to].map!(&mk_person) entry[:cc].map!(&mk_person) entry[:bcc].map!(&mk_person) m.load_from_index! entry m end ## Delete message with the given message-id from the index def delete id synchronize { @xapian.delete_document mkterm(:msgid, id) } end ## Given an array of email addresses, return an array of Person objects that ## have sent mail to or received mail from any of the given addresses. def load_contacts email_addresses, opts={} contacts = Set.new num = opts[:num] || 20 each_id_by_date :participants => email_addresses do |id,b| break if contacts.size >= num m = b.call ([m.from]+m.to+m.cc+m.bcc).compact.each { |p| contacts << [p.name, p.email] } end contacts.to_a.compact[0...num].map { |n,e| Person.from_name_and_email n, e } end ## Yield each message-id matching query EACH_ID_PAGE = 100 def each_id query={}, ignore_neg_terms = true offset = 0 page = EACH_ID_PAGE xapian_query = build_xapian_query query, ignore_neg_terms while true ids = run_query_ids xapian_query, offset, (offset+page) ids.each { |id| yield id } break if ids.size < page offset += page end end ## Yield each message matching query ## The ignore_neg_terms parameter is used to display result even if ## it contains "forbidden" labels such as :deleted, it is used in ## Poll#poll_from when we need to get the location of a message that ## may contain these labels def each_message query={}, ignore_neg_terms = true, &b each_id query, ignore_neg_terms do |id| yield build_message(id) end end # Search messages. Returns an Enumerator. def find_messages query_expr enum_for :each_message, parse_query(query_expr) end # wrap all future changes inside a transaction so they're done atomically def begin_transaction synchronize { @xapian.begin_transaction } end # complete the transaction and write all previous changes to disk def commit_transaction synchronize { @xapian.commit_transaction } end # abort the transaction and revert all changes made since begin_transaction def cancel_transaction synchronize { @xapian.cancel_transaction } end ## xapian-compact takes too long, so this is a no-op ## until we think of something better def optimize end ## Return the id source of the source the message with the given message-id ## was synced from def source_for_id id synchronize { get_entry(id)[:source_id] } end ## Yields each term in the index that starts with prefix def each_prefixed_term prefix term = @xapian._dangerous_allterms_begin prefix lastTerm = @xapian._dangerous_allterms_end prefix until term.equals lastTerm yield term.term term.next end nil end ## Yields (in lexicographical order) the source infos of all locations from ## the given source with the given source_info prefix def each_source_info source_id, prefix='', &b p = mkterm :location, source_id, prefix each_prefixed_term p do |x| yield prefix + x[p.length..-1] end end class ParseError < StandardError; end # Stemmed NORMAL_PREFIX = { 'subject' => {:prefix => 'S', :exclusive => false}, 'body' => {:prefix => 'B', :exclusive => false}, 'from_name' => {:prefix => 'FN', :exclusive => false}, 'to_name' => {:prefix => 'TN', :exclusive => false}, 'name' => {:prefix => %w(FN TN), :exclusive => false}, 'attachment' => {:prefix => 'A', :exclusive => false}, 'email_text' => {:prefix => 'E', :exclusive => false}, '' => {:prefix => %w(S B FN TN A E), :exclusive => false}, } # Unstemmed BOOLEAN_PREFIX = { 'type' => {:prefix => 'K', :exclusive => true}, 'from_email' => {:prefix => 'FE', :exclusive => false}, 'to_email' => {:prefix => 'TE', :exclusive => false}, 'email' => {:prefix => %w(FE TE), :exclusive => false}, 'date' => {:prefix => 'D', :exclusive => true}, 'label' => {:prefix => 'L', :exclusive => false}, 'source_id' => {:prefix => 'I', :exclusive => true}, 'attachment_extension' => {:prefix => 'O', :exclusive => false}, 'msgid' => {:prefix => 'Q', :exclusive => true}, 'id' => {:prefix => 'Q', :exclusive => true}, 'thread' => {:prefix => 'H', :exclusive => false}, 'ref' => {:prefix => 'R', :exclusive => false}, 'location' => {:prefix => 'J', :exclusive => false}, } PREFIX = NORMAL_PREFIX.merge BOOLEAN_PREFIX COMPL_OPERATORS = %w[AND OR NOT] COMPL_PREFIXES = ( %w[ from to is has label filename filetypem before on in during after limit ] + NORMAL_PREFIX.keys + BOOLEAN_PREFIX.keys ).map{|p|"#{p}:"} + COMPL_OPERATORS ## parse a query string from the user. returns a query object ## that can be passed to any index method with a 'query' ## argument. ## ## raises a ParseError if something went wrong. def save_message m, sync_back = true if @sync_worker @sync_queue << [m, sync_back] else update_message_state [m, sync_back] end m.clear_dirty end def save_thread t, sync_back = true t.each_dirty_message do |m| save_message m, sync_back end end def start_sync_worker @sync_worker = Redwood::reporting_thread('index sync') { run_sync_worker } end def stop_sync_worker return unless worker = @sync_worker @sync_worker = nil @sync_queue << :die worker.join end def run_sync_worker while m = @sync_queue.deq return if m == :die update_message_state m # Necessary to keep Xapian calls from lagging the UI too much. sleep 0.03 end end private MSGID_VALUENO = 0 THREAD_VALUENO = 1 DATE_VALUENO = 2 MAX_TERM_LENGTH = 245 # Xapian can very efficiently sort in ascending docid order. Sup always wants # to sort by descending date, so this method maps between them. In order to # handle multiple messages per second, we use a logistic curve centered # around MIDDLE_DATE so that the slope (docid/s) is greatest in this time # period. A docid collision is not an error - the code will pick the next # smallest unused one. DOCID_SCALE = 2.0**32 TIME_SCALE = 2.0**27 MIDDLE_DATE = Time.gm(2011) def assign_docid m, truncated_date t = (truncated_date.to_i - MIDDLE_DATE.to_i).to_f docid = (DOCID_SCALE - DOCID_SCALE/(Math::E**(-(t/TIME_SCALE)) + 1)).to_i while docid > 0 and docid_exists? docid docid -= 1 end docid > 0 ? docid : nil end # XXX is there a better way? def docid_exists? docid begin @xapian.doclength docid true rescue RuntimeError #Xapian::DocNotFoundError raise unless $!.message =~ /DocNotFoundError/ false end end def term_docids term @xapian.postlist(term).map { |x| x.docid } end def find_docid id docids = term_docids(mkterm(:msgid,id)) fail unless docids.size <= 1 docids.first end def find_doc id return unless docid = find_docid(id) @xapian.document docid end def get_id docid return unless doc = @xapian.document(docid) doc.value MSGID_VALUENO end def get_entry id return unless doc = find_doc(id) doc.entry end def thread_killed? thread_id not run_query(Q.new(Q::OP_AND, mkterm(:thread, thread_id), mkterm(:label, :Killed)), 0, 1).empty? end def synchronize &b @index_mutex.synchronize &b end def run_query xapian_query, offset, limit, checkatleast=0 synchronize do @enquire.query = xapian_query @enquire.mset(offset, limit-offset, checkatleast) end end def run_query_ids xapian_query, offset, limit matchset = run_query xapian_query, offset, limit matchset.matches.map { |r| r.document.value MSGID_VALUENO } end Q = Xapian::Query def build_xapian_query opts, ignore_neg_terms = true labels = ([opts[:label]] + (opts[:labels] || [])).compact neglabels = [:spam, :deleted, :killed].reject { |l| (labels.include? l) || opts.member?("load_#{l}".intern) } pos_terms, neg_terms = [], [] pos_terms << mkterm(:type, 'mail') pos_terms.concat(labels.map { |l| mkterm(:label,l) }) pos_terms << opts[:qobj] if opts[:qobj] pos_terms << mkterm(:source_id, opts[:source_id]) if opts[:source_id] pos_terms << mkterm(:location, *opts[:location]) if opts[:location] if opts[:participants] participant_terms = opts[:participants].map { |p| [:from,:to].map { |d| mkterm(:email, d, (Redwood::Person === p) ? p.email : p) } }.flatten pos_terms << Q.new(Q::OP_OR, participant_terms) end neg_terms.concat(neglabels.map { |l| mkterm(:label,l) }) if ignore_neg_terms pos_query = Q.new(Q::OP_AND, pos_terms) neg_query = Q.new(Q::OP_OR, neg_terms) if neg_query.empty? pos_query else Q.new(Q::OP_AND_NOT, [pos_query, neg_query]) end end def sync_message m, overwrite, sync_back = true ## TODO: we should not save the message if the sync_back failed ## since it would overwrite the location field m.sync_back if sync_back doc = synchronize { find_doc(m.id) } existed = doc != nil doc ||= Xapian::Document.new do_index_static = overwrite || !existed old_entry = !do_index_static && doc.entry snippet = do_index_static ? m.snippet : old_entry[:snippet] entry = { :message_id => m.id, :locations => m.locations.map { |x| [x.source.id, x.info] }, :date => truncate_date(m.date), :snippet => snippet, :labels => m.labels.to_a, :from => [m.from.email, m.from.name], :to => m.to.map { |p| [p.email, p.name] }, :cc => m.cc.map { |p| [p.email, p.name] }, :bcc => m.bcc.map { |p| [p.email, p.name] }, :subject => m.subj, :refs => m.refs.to_a, :replytos => m.replytos.to_a, } if do_index_static doc.clear_terms doc.clear_values index_message_static m, doc, entry end index_message_locations doc, entry, old_entry index_message_threading doc, entry, old_entry index_message_labels doc, entry[:labels], (do_index_static ? [] : old_entry[:labels]) doc.entry = entry synchronize do unless docid = existed ? doc.docid : assign_docid(m, truncate_date(m.date)) # Could be triggered by spam warn "docid underflow, dropping #{m.id.inspect}" return end @xapian.replace_document docid, doc end m.labels.each { |l| LabelManager << l } true end ## Index content that can't be changed by the user def index_message_static m, doc, entry # Person names are indexed with several prefixes person_termer = lambda do |d| lambda do |p| doc.index_text p.name, PREFIX["#{d}_name"][:prefix] if p.name doc.index_text p.email, PREFIX['email_text'][:prefix] doc.add_term mkterm(:email, d, p.email) end end person_termer[:from][m.from] if m.from (m.to+m.cc+m.bcc).each(&(person_termer[:to])) # Full text search content subject_text = m.indexable_subject body_text = m.indexable_body doc.index_text subject_text, PREFIX['subject'][:prefix] doc.index_text body_text, PREFIX['body'][:prefix] m.attachments.each { |a| doc.index_text a, PREFIX['attachment'][:prefix] } # Miscellaneous terms doc.add_term mkterm(:date, m.date) if m.date doc.add_term mkterm(:type, 'mail') doc.add_term mkterm(:msgid, m.id) m.attachments.each do |a| a =~ /\.(\w+)$/ or next doc.add_term mkterm(:attachment_extension, $1) end # Date value for range queries date_value = begin Xapian.sortable_serialise m.date.to_i rescue TypeError Xapian.sortable_serialise 0 end doc.add_value MSGID_VALUENO, m.id doc.add_value DATE_VALUENO, date_value end def index_message_locations doc, entry, old_entry old_entry[:locations].map { |x| x[0] }.uniq.each { |x| doc.remove_term mkterm(:source_id, x) } if old_entry entry[:locations].map { |x| x[0] }.uniq.each { |x| doc.add_term mkterm(:source_id, x) } old_entry[:locations].each { |x| (doc.remove_term mkterm(:location, *x) rescue nil) } if old_entry entry[:locations].each { |x| doc.add_term mkterm(:location, *x) } end def index_message_labels doc, new_labels, old_labels return if new_labels == old_labels added = new_labels.to_a - old_labels.to_a removed = old_labels.to_a - new_labels.to_a added.each { |t| doc.add_term mkterm(:label,t) } removed.each { |t| doc.remove_term mkterm(:label,t) } end ## Assign a set of thread ids to the document. This is a hybrid of the runtime ## search done by the Ferret index and the index-time union done by previous ## versions of the Xapian index. We first find the thread ids of all messages ## with a reference to or from us. If that set is empty, we use our own ## message id. Otherwise, we use all the thread ids we previously found. In ## the common case there's only one member in that set, but if we're the ## missing link between multiple previously unrelated threads we can have ## more. XapianIndex#each_message_in_thread_for follows the thread ids when ## searching so the user sees a single unified thread. def index_message_threading doc, entry, old_entry return if old_entry && (entry[:refs] == old_entry[:refs]) && (entry[:replytos] == old_entry[:replytos]) children = term_docids(mkterm(:ref, entry[:message_id])).map { |docid| @xapian.document docid } parent_ids = entry[:refs] + entry[:replytos] parents = parent_ids.map { |id| find_doc id }.compact thread_members = SavingHash.new { [] } (children + parents).each do |doc2| thread_ids = doc2.value(THREAD_VALUENO).split ',' thread_ids.each { |thread_id| thread_members[thread_id] << doc2 } end thread_ids = thread_members.empty? ? [entry[:message_id]] : thread_members.keys thread_ids.each { |thread_id| doc.add_term mkterm(:thread, thread_id) } parent_ids.each { |ref| doc.add_term mkterm(:ref, ref) } doc.add_value THREAD_VALUENO, (thread_ids * ',') end def truncate_date date if date < MIN_DATE debug "warning: adjusting too-low date #{date} for indexing" MIN_DATE elsif date > MAX_DATE debug "warning: adjusting too-high date #{date} for indexing" MAX_DATE else date end end # Construct a Xapian term def mkterm type, *args case type when :label PREFIX['label'][:prefix] + args[0].to_s.downcase when :type PREFIX['type'][:prefix] + args[0].to_s.downcase when :date PREFIX['date'][:prefix] + args[0].getutc.strftime("%Y%m%d%H%M%S") when :email case args[0] when :from then PREFIX['from_email'][:prefix] when :to then PREFIX['to_email'][:prefix] else raise "Invalid email term type #{args[0]}" end + args[1].to_s.downcase when :source_id PREFIX['source_id'][:prefix] + args[0].to_s.downcase when :location PREFIX['location'][:prefix] + [args[0]].pack('n') + args[1].to_s when :attachment_extension PREFIX['attachment_extension'][:prefix] + args[0].to_s.downcase when :msgid, :ref, :thread PREFIX[type.to_s][:prefix] + args[0][0...(MAX_TERM_LENGTH-1)] else raise "Invalid term type #{type}" end end end
rmagick/rmagick
lib/rmagick_internal.rb
Magick.ImageList.method_missing
ruby
def method_missing(meth_id, *args, &block) if @scene @images[@scene].send(meth_id, *args, &block) else super end rescue NoMethodError Kernel.raise NoMethodError, "undefined method `#{meth_id.id2name}' for #{self.class}" rescue Exception $ERROR_POSITION.delete_if { |s| /:in `send'$/.match(s) || /:in `method_missing'$/.match(s) } Kernel.raise end
The ImageList class supports the Magick::Image class methods by simply sending the method to the current image. If the method isn't explicitly supported, send it to the current image in the array. If there are no images, send it up the line. Catch a NameError and emit a useful message.
train
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L1603-L1614
class ImageList include Comparable include Enumerable attr_reader :scene private def get_current @images[@scene].__id__ rescue StandardError nil end protected def is_an_image(obj) Kernel.raise ArgumentError, "Magick::Image required (#{obj.class} given)" unless obj.is_a? Magick::Image true end # Ensure array is always an array of Magick::Image objects def is_an_image_array(ary) Kernel.raise ArgumentError, "Magick::ImageList or array of Magick::Images required (#{ary.class} given)" unless ary.respond_to? :each ary.each { |obj| is_an_image obj } true end # Find old current image, update scene number # current is the id of the old current image. def set_current(current) if length.zero? self.scene = nil return # Don't bother looking for current image elsif scene.nil? || scene >= length self.scene = length - 1 return elsif !current.nil? # Find last instance of "current" in the list. # If "current" isn't in the list, set current to last image. self.scene = length - 1 each_with_index do |f, i| self.scene = i if f.__id__ == current end return end self.scene = length - 1 end public # Allow scene to be set to nil def scene=(n) if n.nil? Kernel.raise IndexError, 'scene number out of bounds' unless @images.length.zero? @scene = nil return @scene elsif @images.length.zero? Kernel.raise IndexError, 'scene number out of bounds' end n = Integer(n) Kernel.raise IndexError, 'scene number out of bounds' if n < 0 || n > length - 1 @scene = n @scene end # All the binary operators work the same way. # 'other' should be either an ImageList or an Array %w[& + - |].each do |op| module_eval <<-END_BINOPS def #{op}(other) ilist = self.class.new begin a = other #{op} @images rescue TypeError Kernel.raise ArgumentError, "Magick::ImageList expected, got " + other.class.to_s end current = get_current() a.each do |image| is_an_image image ilist << image end ilist.set_current current return ilist end END_BINOPS end def *(other) Kernel.raise ArgumentError, "Integer required (#{other.class} given)" unless other.is_a? Integer current = get_current ilist = self.class.new (@images * other).each { |image| ilist << image } ilist.set_current current ilist end def <<(obj) is_an_image obj @images << obj @scene = @images.length - 1 self end # Compare ImageLists # Compare each image in turn until the result of a comparison # is not 0. If all comparisons return 0, then # return if A.scene != B.scene # return A.length <=> B.length def <=>(other) Kernel.raise TypeError, "#{self.class} required (#{other.class} given)" unless other.is_a? self.class size = [length, other.length].min size.times do |x| r = self[x] <=> other[x] return r unless r.zero? end return 0 if @scene.nil? && other.scene.nil? Kernel.raise TypeError, "cannot convert nil into #{other.scene.class}" if @scene.nil? && !other.scene.nil? Kernel.raise TypeError, "cannot convert nil into #{scene.class}" if !@scene.nil? && other.scene.nil? r = scene <=> other.scene return r unless r.zero? length <=> other.length end def [](*args) a = @images[*args] if a.respond_to?(:each) ilist = self.class.new a.each { |image| ilist << image } a = ilist end a end def []=(*args) obj = @images.[]=(*args) if obj && obj.respond_to?(:each) is_an_image_array(obj) set_current obj.last.__id__ elsif obj is_an_image(obj) set_current obj.__id__ else set_current nil end obj end %i[at each each_index empty? fetch first hash include? index length rindex sort!].each do |mth| module_eval <<-END_SIMPLE_DELEGATES def #{mth}(*args, &block) @images.#{mth}(*args, &block) end END_SIMPLE_DELEGATES end alias size length # Array#nitems is not available in 1.9 if Array.instance_methods.include?('nitems') def nitems @images.nitems end end def clear @scene = nil @images.clear end def clone ditto = dup ditto.freeze if frozen? ditto end # override Enumerable#collect def collect(&block) current = get_current a = @images.collect(&block) ilist = self.class.new a.each { |image| ilist << image } ilist.set_current current ilist end def collect!(&block) @images.collect!(&block) is_an_image_array @images self end # Make a deep copy def copy ditto = self.class.new @images.each { |f| ditto << f.copy } ditto.scene = @scene ditto.taint if tainted? ditto end # Return the current image def cur_image Kernel.raise IndexError, 'no images in this list' unless @scene @images[@scene] end # ImageList#map took over the "map" name. Use alternatives. alias __map__ collect alias map! collect! alias __map__! collect! # ImageMagic used affinity in 6.4.3, switch to remap in 6.4.4. alias affinity remap def compact current = get_current ilist = self.class.new a = @images.compact a.each { |image| ilist << image } ilist.set_current current ilist end def compact! current = get_current a = @images.compact! # returns nil if no changes were made set_current current a.nil? ? nil : self end def concat(other) is_an_image_array other other.each { |image| @images << image } @scene = length - 1 self end # Set same delay for all images def delay=(d) raise ArgumentError, 'delay must be greater than or equal to 0' if Integer(d) < 0 @images.each { |f| f.delay = Integer(d) } end def delete(obj, &block) is_an_image obj current = get_current a = @images.delete(obj, &block) set_current current a end def delete_at(ndx) current = get_current a = @images.delete_at(ndx) set_current current a end def delete_if(&block) current = get_current @images.delete_if(&block) set_current current self end def dup ditto = self.class.new @images.each { |img| ditto << img } ditto.scene = @scene ditto.taint if tainted? ditto end def eql?(other) is_an_image_array other eql = other.eql?(@images) begin # "other" is another ImageList eql &&= @scene == other.scene rescue NoMethodError # "other" is a plain Array end eql end def fill(*args, &block) is_an_image args[0] unless block_given? current = get_current @images.fill(*args, &block) is_an_image_array self set_current current self end # Override Enumerable's find_all def find_all(&block) current = get_current a = @images.find_all(&block) ilist = self.class.new a.each { |image| ilist << image } ilist.set_current current ilist end alias select find_all def from_blob(*blobs, &block) Kernel.raise ArgumentError, 'no blobs given' if blobs.length.zero? blobs.each do |b| Magick::Image.from_blob(b, &block).each { |n| @images << n } end @scene = length - 1 self end # Initialize new instances def initialize(*filenames, &block) @images = [] @scene = nil filenames.each do |f| Magick::Image.read(f, &block).each { |n| @images << n } end if length > 0 @scene = length - 1 # last image in array end self end def insert(index, *args) args.each { |image| is_an_image image } current = get_current @images.insert(index, *args) set_current current self end # Call inspect for all the images def inspect img = [] @images.each { |image| img << image.inspect } img = '[' + img.join(",\n") + "]\nscene=#{@scene}" end # Set the number of iterations of an animated GIF def iterations=(n) n = Integer(n) Kernel.raise ArgumentError, 'iterations must be between 0 and 65535' if n < 0 || n > 65_535 @images.each { |f| f.iterations = n } self end def last(*args) if args.length.zero? a = @images.last else a = @images.last(*args) ilist = self.class.new a.each { |img| ilist << img } @scene = a.length - 1 a = ilist end a end # Custom marshal/unmarshal for Ruby 1.8. def marshal_dump ary = [@scene] @images.each { |i| ary << Marshal.dump(i) } ary end def marshal_load(ary) @scene = ary.shift @images = [] ary.each { |a| @images << Marshal.load(a) } end # The ImageList class supports the Magick::Image class methods by simply sending # the method to the current image. If the method isn't explicitly supported, # send it to the current image in the array. If there are no images, send # it up the line. Catch a NameError and emit a useful message. # Create a new image and add it to the end def new_image(cols, rows, *fill, &info_blk) self << Magick::Image.new(cols, rows, *fill, &info_blk) end def partition(&block) a = @images.partition(&block) t = self.class.new a[0].each { |img| t << img } t.set_current nil f = self.class.new a[1].each { |img| f << img } f.set_current nil [t, f] end # Ping files and concatenate the new images def ping(*files, &block) Kernel.raise ArgumentError, 'no files given' if files.length.zero? files.each do |f| Magick::Image.ping(f, &block).each { |n| @images << n } end @scene = length - 1 self end def pop current = get_current a = @images.pop # can return nil set_current current a end def push(*objs) objs.each do |image| is_an_image image @images << image end @scene = length - 1 self end # Read files and concatenate the new images def read(*files, &block) Kernel.raise ArgumentError, 'no files given' if files.length.zero? files.each do |f| Magick::Image.read(f, &block).each { |n| @images << n } end @scene = length - 1 self end # override Enumerable's reject def reject(&block) current = get_current ilist = self.class.new a = @images.reject(&block) a.each { |image| ilist << image } ilist.set_current current ilist end def reject!(&block) current = get_current a = @images.reject!(&block) @images = a unless a.nil? set_current current a.nil? ? nil : self end def replace(other) is_an_image_array other current = get_current @images.clear other.each { |image| @images << image } @scene = length.zero? ? nil : 0 set_current current self end # Ensure respond_to? answers correctly when we are delegating to Image alias __respond_to__? respond_to? def respond_to?(meth_id, priv = false) return true if __respond_to__?(meth_id, priv) if @scene @images[@scene].respond_to?(meth_id, priv) else super end end def reverse current = get_current a = self.class.new @images.reverse_each { |image| a << image } a.set_current current a end def reverse! current = get_current @images.reverse! set_current current self end def reverse_each @images.reverse_each { |image| yield(image) } self end def shift current = get_current a = @images.shift set_current current a end def slice(*args) slice = @images.slice(*args) if slice ilist = self.class.new if slice.respond_to?(:each) slice.each { |image| ilist << image } else ilist << slice end else ilist = nil end ilist end def slice!(*args) current = get_current a = @images.slice!(*args) set_current current a end def ticks_per_second=(t) Kernel.raise ArgumentError, 'ticks_per_second must be greater than or equal to 0' if Integer(t) < 0 @images.each { |f| f.ticks_per_second = Integer(t) } end def to_a a = [] @images.each { |image| a << image } a end def uniq current = get_current a = self.class.new @images.uniq.each { |image| a << image } a.set_current current a end def uniq!(*_args) current = get_current a = @images.uniq! set_current current a.nil? ? nil : self end # @scene -> new object def unshift(obj) is_an_image obj @images.unshift(obj) @scene = 0 self end def values_at(*args) a = @images.values_at(*args) a = self.class.new @images.values_at(*args).each { |image| a << image } a.scene = a.length - 1 a end alias indexes values_at alias indices values_at end # Magick::ImageList
documentcloud/jammit
lib/jammit/helper.rb
Jammit.Helper.tags_with_options
ruby
def tags_with_options(packages, options) packages.dup.map {|package| yield package }.flatten.map {|package| stylesheet_link_tag package, options }.join("\n") end
Generate the stylesheet tags for a batch of packages, with options, by yielding each package to a block.
train
https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/helper.rb#L76-L82
module Helper DATA_URI_START = "<!--[if (!IE)|(gte IE 8)]><!-->" unless defined?(DATA_URI_START) DATA_URI_END = "<!--<![endif]-->" unless defined?(DATA_URI_END) MHTML_START = "<!--[if lte IE 7]>" unless defined?(MHTML_START) MHTML_END = "<![endif]-->" unless defined?(MHTML_END) # If embed_assets is turned on, writes out links to the Data-URI and MHTML # versions of the stylesheet package, otherwise the package is regular # compressed CSS, and in development the stylesheet URLs are passed verbatim. def include_stylesheets(*packages) options = packages.extract_options! return html_safe(individual_stylesheets(packages, options)) unless should_package? disabled = (options.delete(:embed_assets) == false) || (options.delete(:embed_images) == false) return html_safe(packaged_stylesheets(packages, options)) if disabled || !Jammit.embed_assets return html_safe(embedded_image_stylesheets(packages, options)) end # Writes out the URL to the bundled and compressed javascript package, # except in development, where it references the individual scripts. def include_javascripts(*packages) options = packages.extract_options! options.merge!(:extname=>false) html_safe packages.map {|pack| should_package? ? Jammit.asset_url(pack, :js) : Jammit.packager.individual_urls(pack.to_sym, :js) }.flatten.map {|pack| "<script src=\"#{pack}\"></script>" }.join("\n") end # Writes out the URL to the concatenated and compiled JST file -- we always # have to pre-process it, even in development. def include_templates(*packages) raise DeprecationError, "Jammit 0.5+ no longer supports separate packages for templates.\nYou can include your JST alongside your JS, and use include_javascripts." end private def should_package? Jammit.package_assets && !(Jammit.allow_debugging && params[:debug_assets]) end def html_safe(string) string.respond_to?(:html_safe) ? string.html_safe : string end # HTML tags, in order, for all of the individual stylesheets. def individual_stylesheets(packages, options) tags_with_options(packages, options) {|p| Jammit.packager.individual_urls(p.to_sym, :css) } end # HTML tags for the stylesheet packages. def packaged_stylesheets(packages, options) tags_with_options(packages, options) {|p| Jammit.asset_url(p, :css) } end # HTML tags for the 'datauri', and 'mhtml' versions of the packaged # stylesheets, using conditional comments to load the correct variant. def embedded_image_stylesheets(packages, options) datauri_tags = tags_with_options(packages, options) {|p| Jammit.asset_url(p, :css, :datauri) } ie_tags = Jammit.mhtml_enabled ? tags_with_options(packages, options) {|p| Jammit.asset_url(p, :css, :mhtml) } : packaged_stylesheets(packages, options) [DATA_URI_START, datauri_tags, DATA_URI_END, MHTML_START, ie_tags, MHTML_END].join("\n") end # Generate the stylesheet tags for a batch of packages, with options, by # yielding each package to a block. end
quixoten/queue_to_the_future
lib/queue_to_the_future/job.rb
QueueToTheFuture.Job.method_missing
ruby
def method_missing(*args, &block) Thread.pass until defined?(@result) case @result when Exception def self.method_missing(*args, &block); raise @result; end else def self.method_missing(*args, &block); @result.send(*args, &block); end end self.method_missing(*args, &block) end
Allows the job to behave as the return value of the block. Accessing any method on the job will cause code to block until the job is completed.
train
https://github.com/quixoten/queue_to_the_future/blob/dd8260fa165ee42b95e6d76bc665fdf68339dfd6/lib/queue_to_the_future/job.rb#L34-L45
class Job instance_methods.each { |meth| undef_method(meth) unless %w(__send__ __id__ object_id inspect).include?(meth.to_s) } # Creates a job and schedules it by calling {Coordinator#schedule}. # # @param [List] *args The list of arguments to pass to the given block # @param [Proc] &block The block to be executed def initialize(*args, &block) @args = args @block = block Coordinator.schedule(self) end # Execute the job. # # This is called by the worker the job gets assigned to. # @return [nil] def __execute__ @result = @block[*@args] rescue Exception => e @result = e ensure # Prevent multiple executions def self.__execute__; nil; end end # Allows the job to behave as the return value of the block. # # Accessing any method on the job will cause code to block # until the job is completed. end
simplymadeapps/simple_scheduler
lib/simple_scheduler/task.rb
SimpleScheduler.Task.future_run_times
ruby
def future_run_times future_run_times = existing_run_times.dup last_run_time = future_run_times.last || at - frequency last_run_time = last_run_time.in_time_zone(time_zone) # Ensure there are at least two future jobs scheduled and that the queue ahead time is filled while future_run_times.length < 2 || minutes_queued_ahead(last_run_time) < queue_ahead last_run_time = frequency.from_now(last_run_time) # The hour may not match because of a shift caused by DST in previous run times, # so we need to ensure that the hour matches the specified hour if given. last_run_time = last_run_time.change(hour: at.hour, min: at.min) if at.hour? future_run_times << last_run_time end future_run_times end
Returns an array Time objects for future run times based on the current time and the given minutes to look ahead. @return [Array<Time>] rubocop:disable Metrics/AbcSize
train
https://github.com/simplymadeapps/simple_scheduler/blob/4d186042507c1397ee79a5e8fe929cc14008c026/lib/simple_scheduler/task.rb#L67-L82
class Task attr_reader :job_class, :params DEFAULT_QUEUE_AHEAD_MINUTES = 360 # Initializes a task by parsing the params so the task can be queued in the future. # @param params [Hash] # @option params [String] :class The class of the Active Job or Sidekiq Worker # @option params [String] :every How frequently the job will be performed # @option params [String] :at The starting time for the interval # @option params [String] :expires_after The interval used to determine how late the job is allowed to run # @option params [Integer] :queue_ahead The number of minutes that jobs should be queued in the future # @option params [String] :task_name The name of the task as defined in the YAML config # @option params [String] :tz The time zone to use when parsing the `at` option def initialize(params) validate_params!(params) @params = params end # The task's first run time as a Time-like object. # @return [SimpleScheduler::At] def at @at ||= At.new(@params[:at], time_zone) end # The time between the scheduled and actual run time that should cause the job not to run. # @return [String] def expires_after @params[:expires_after] end # Returns an array of existing jobs matching the job class of the task. # @return [Array<Sidekiq::SortedEntry>] def existing_jobs @existing_jobs ||= SimpleScheduler::Task.scheduled_set.select do |job| next unless job.display_class == "SimpleScheduler::FutureJob" task_params = job.display_args[0].symbolize_keys task_params[:class] == job_class_name && task_params[:name] == name end.to_a end # Returns an array of existing future run times that have already been scheduled. # @return [Array<Time>] def existing_run_times @existing_run_times ||= existing_jobs.map(&:at) end # How often the job will be run. # @return [ActiveSupport::Duration] def frequency @frequency ||= parse_frequency(@params[:every]) end # Returns an array Time objects for future run times based on # the current time and the given minutes to look ahead. # @return [Array<Time>] # rubocop:disable Metrics/AbcSize # rubocop:enable Metrics/AbcSize # The class name of the job or worker. # @return [String] def job_class_name @params[:class] end # The name of the task as defined in the YAML config. # @return [String] def name @params[:name] end # The number of minutes that jobs should be queued in the future. # @return [Integer] def queue_ahead @queue_ahead ||= @params[:queue_ahead] || DEFAULT_QUEUE_AHEAD_MINUTES end # The time zone to use when parsing the `at` option. # @return [ActiveSupport::TimeZone] def time_zone @time_zone ||= params[:tz] ? ActiveSupport::TimeZone.new(params[:tz]) : Time.zone end # Loads the scheduled jobs from Sidekiq once to avoid loading from # Redis for each task when looking up existing scheduled jobs. # @return [Sidekiq::ScheduledSet] def self.scheduled_set @scheduled_set ||= Sidekiq::ScheduledSet.new end private def minutes_queued_ahead(last_run_time) (last_run_time - Time.now) / 60 end def parse_frequency(every_string) split_duration = every_string.split(".") frequency = split_duration[0].to_i frequency_units = split_duration[1] frequency.send(frequency_units) end def validate_params!(params) raise ArgumentError, "Missing param `class` specifying the class of the job to run." unless params.key?(:class) raise ArgumentError, "Missing param `every` specifying how often the job should run." unless params.key?(:every) @job_class = params[:class].constantize params[:name] ||= params[:class] end end
SamSaffron/message_bus
lib/message_bus/http_client.rb
MessageBus.HTTPClient.start
ruby
def start @mutex.synchronize do return if started? @status = STARTED thread = Thread.new do begin while started? unless @channels.empty? poll @stats.success += 1 @stats.failed = 0 end sleep interval end rescue StandardError => e @stats.failed += 1 warn("#{e.class} #{e.message}: #{e.backtrace.join("\n")}") sleep interval retry ensure stop end end thread.abort_on_exception = true end self end
@param base_url [String] Base URL of the message_bus server to connect to @param enable_long_polling [Boolean] Enable long polling @param enable_chunked_encoding [Boolean] Enable chunk encoding @param min_poll_interval [Float, Integer] Min poll interval when long polling in seconds @param max_poll_interval [Float, Integer] Max poll interval when long polling in seconds. When requests fail, the client will backoff and this is the upper limit. @param background_callback_interval [Float, Integer] Interval to poll when when polling in seconds. @param headers [Hash] extra HTTP headers to be set on the polling requests. @return [Object] Instance of MessageBus::HTTPClient Starts a background thread that polls the message bus endpoint for the given base_url. Intervals for long polling can be configured via min_poll_interval and max_poll_interval. Intervals for polling can be configured via background_callback_interval. @return [Object] Instance of MessageBus::HTTPClient
train
https://github.com/SamSaffron/message_bus/blob/90fba639eb5d332ca8e87fd35f1d603a5743076d/lib/message_bus/http_client.rb#L96-L127
class HTTPClient class InvalidChannel < StandardError; end class MissingBlock < StandardError; end attr_reader :channels, :stats attr_accessor :enable_long_polling, :status, :enable_chunked_encoding, :min_poll_interval, :max_poll_interval, :background_callback_interval CHUNK_SEPARATOR = "\r\n|\r\n".freeze private_constant :CHUNK_SEPARATOR STATUS_CHANNEL = "/__status".freeze private_constant :STATUS_CHANNEL STOPPED = 0 STARTED = 1 Stats = Struct.new(:failed, :success) private_constant :Stats # @param base_url [String] Base URL of the message_bus server to connect to # @param enable_long_polling [Boolean] Enable long polling # @param enable_chunked_encoding [Boolean] Enable chunk encoding # @param min_poll_interval [Float, Integer] Min poll interval when long polling in seconds # @param max_poll_interval [Float, Integer] Max poll interval when long polling in seconds. # When requests fail, the client will backoff and this is the upper limit. # @param background_callback_interval [Float, Integer] Interval to poll when # when polling in seconds. # @param headers [Hash] extra HTTP headers to be set on the polling requests. # # @return [Object] Instance of MessageBus::HTTPClient def initialize(base_url, enable_long_polling: true, enable_chunked_encoding: true, min_poll_interval: 0.1, max_poll_interval: 180, background_callback_interval: 60, headers: {}) @uri = URI(base_url) @enable_long_polling = enable_long_polling @enable_chunked_encoding = enable_chunked_encoding @min_poll_interval = min_poll_interval @max_poll_interval = max_poll_interval @background_callback_interval = background_callback_interval @headers = headers @client_id = SecureRandom.hex @channels = {} @status = STOPPED @mutex = Mutex.new @stats = Stats.new(0, 0) end # Starts a background thread that polls the message bus endpoint # for the given base_url. # # Intervals for long polling can be configured via min_poll_interval and # max_poll_interval. # # Intervals for polling can be configured via background_callback_interval. # # @return [Object] Instance of MessageBus::HTTPClient # Stops the client from polling the message bus endpoint. # # @return [Integer] the current status of the client def stop @status = STOPPED end # Subscribes to a channel which executes the given callback when a message # is published to the channel # # @example Subscribing to a channel for message # client = MessageBus::HTTPClient.new('http://some.test.com') # # client.subscribe("/test") do |payload, _message_id, _global_id| # puts payload # end # # A last_message_id may be provided. # * -1 will subscribe to all new messages # * -2 will recieve last message + all new messages # * -3 will recieve last 2 message + all new messages # # @example Subscribing to a channel with `last_message_id` # client.subscribe("/test", last_message_id: -2) do |payload| # puts payload # end # # @param channel [String] channel to listen for messages on # @param last_message_id [Integer] last message id to start polling on. # # @yield [data, message_id, global_id] # callback to be executed whenever a message is received # # @yieldparam data [Hash] data payload of the message received on the channel # @yieldparam message_id [Integer] id of the message in the channel # @yieldparam global_id [Integer] id of the message in the global backlog # @yieldreturn [void] # # @return [Integer] the current status of the client def subscribe(channel, last_message_id: nil, &callback) raise InvalidChannel unless channel.to_s.start_with?("/") raise MissingBlock unless block_given? last_message_id = -1 if last_message_id && !last_message_id.is_a?(Integer) @channels[channel] ||= Channel.new channel = @channels[channel] channel.last_message_id = last_message_id if last_message_id channel.callbacks.push(callback) start if stopped? end # unsubscribes from a channel # # @example Unsubscribing from a channel # client = MessageBus::HTTPClient.new('http://some.test.com') # callback = -> { |payload| puts payload } # client.subscribe("/test", &callback) # client.unsubscribe("/test") # # If a callback is given, only the specific callback will be unsubscribed. # # @example Unsubscribing a callback from a channel # client.unsubscribe("/test", &callback) # # When the client does not have any channels left, it will stop polling and # waits until a new subscription is started. # # @param channel [String] channel to unsubscribe # @yield [data, global_id, message_id] specific callback to unsubscribe # # @return [Integer] the current status of the client def unsubscribe(channel, &callback) if callback @channels[channel].callbacks.delete(callback) remove_channel(channel) if @channels[channel].callbacks.empty? else remove_channel(channel) end stop if @channels.empty? @status end private def stopped? @status == STOPPED end def started? @status == STARTED end def remove_channel(channel) @channels.delete(channel) end def interval if @enable_long_polling if (failed_count = @stats.failed) > 2 (@min_poll_interval * 2**failed_count).clamp( @min_poll_interval, @max_poll_interval ) else @min_poll_interval end else @background_callback_interval end end def poll http = Net::HTTP.new(@uri.host, @uri.port) http.use_ssl = true if @uri.scheme == 'https' request = Net::HTTP::Post.new(request_path, headers) request.body = poll_payload if @enable_long_polling buffer = '' http.request(request) do |response| response.read_body do |chunk| unless chunk.empty? buffer << chunk process_buffer(buffer) end end end else response = http.request(request) notify_channels(JSON.parse(response.body)) end end def is_chunked? !headers["Dont-Chunk"] end def process_buffer(buffer) index = buffer.index(CHUNK_SEPARATOR) if is_chunked? return unless index messages = buffer[0..(index - 1)] buffer.slice!("#{messages}#{CHUNK_SEPARATOR}") else messages = buffer[0..-1] buffer.slice!(messages) end notify_channels(JSON.parse(messages)) end def notify_channels(messages) messages.each do |message| current_channel = message['channel'] if current_channel == STATUS_CHANNEL message["data"].each do |channel_name, last_message_id| if (channel = @channels[channel_name]) channel.last_message_id = last_message_id end end else @channels.each do |channel_name, channel| next unless channel_name == current_channel channel.last_message_id = message['message_id'] channel.callbacks.each do |callback| callback.call( message['data'], channel.last_message_id, message['global_id'] ) end end end end end def poll_payload payload = {} @channels.each do |channel_name, channel| payload[channel_name] = channel.last_message_id end payload.to_json end def request_path "/message-bus/#{@client_id}/poll" end def headers headers = {} headers['Content-Type'] = 'application/json' headers['X-Silence-logger'] = 'true' if !@enable_long_polling || !@enable_chunked_encoding headers['Dont-Chunk'] = 'true' end headers.merge!(@headers) end end
bitbucket-rest-api/bitbucket
lib/bitbucket_rest_api/issues/components.rb
BitBucket.Issues::Components.get
ruby
def get(user_name, repo_name, component_id, params={}) _update_user_repo_params(user_name, repo_name) _validate_user_repo_params(user, repo) unless user? && repo? _validate_presence_of component_id normalize! params get_request("/1.0/repositories/#{user}/#{repo.downcase}/issues/components/#{component_id}", params) end
Get a single component = Examples bitbucket = BitBucket.new bitbucket.issues.components.find 'user-name', 'repo-name', 'component-id'
train
https://github.com/bitbucket-rest-api/bitbucket/blob/e03b6935104d59b3d9a922474c3dc210a5ef76d2/lib/bitbucket_rest_api/issues/components.rb#L36-L43
class Issues::Components < API VALID_COMPONENT_INPUTS = %w[ name ].freeze # Creates new Issues::Components API def initialize(options = {}) super(options) end # List all components for a repository # # = Examples # bitbucket = BitBucket.new :user => 'user-name', :repo => 'repo-name' # bitbucket.issues.components.list # bitbucket.issues.components.list { |component| ... } # def list(user_name, repo_name, params={}) _update_user_repo_params(user_name, repo_name) _validate_user_repo_params(user, repo) unless user? && repo? normalize! params response = get_request("/1.0/repositories/#{user}/#{repo.downcase}/issues/components", params) return response unless block_given? response.each { |el| yield el } end alias :all :list # Get a single component # # = Examples # bitbucket = BitBucket.new # bitbucket.issues.components.find 'user-name', 'repo-name', 'component-id' # alias :find :get # Create a component # # = Inputs # <tt>:name</tt> - Required string # # = Examples # bitbucket = BitBucket.new :user => 'user-name', :repo => 'repo-name' # bitbucket.issues.components.create :name => 'API' # def create(user_name, repo_name, params={}) _update_user_repo_params(user_name, repo_name) _validate_user_repo_params(user, repo) unless user? && repo? normalize! params filter! VALID_COMPONENT_INPUTS, params assert_required_keys(VALID_COMPONENT_INPUTS, params) post_request("/1.0/repositories/#{user}/#{repo.downcase}/issues/components", params) end # Update a component # # = Inputs # <tt>:name</tt> - Required string # # = Examples # @bitbucket = BitBucket.new # @bitbucket.issues.components.update 'user-name', 'repo-name', 'component-id', # :name => 'API' # def update(user_name, repo_name, component_id, params={}) _update_user_repo_params(user_name, repo_name) _validate_user_repo_params(user, repo) unless user? && repo? _validate_presence_of component_id normalize! params filter! VALID_COMPONENT_INPUTS, params assert_required_keys(VALID_COMPONENT_INPUTS, params) put_request("/1.0/repositories/#{user}/#{repo.downcase}/issues/components/#{component_id}", params) end alias :edit :update # Delete a component # # = Examples # bitbucket = BitBucket.new # bitbucket.issues.components.delete 'user-name', 'repo-name', 'component-id' # def delete(user_name, repo_name, component_id, params={}) _update_user_repo_params(user_name, repo_name) _validate_user_repo_params(user, repo) unless user? && repo? _validate_presence_of component_id normalize! params delete_request("/1.0/repositories/#{user}/#{repo.downcase}/issues/components/#{component_id}", params) end end # Issues::Components
cookpad/rrrspec
rrrspec-client/lib/rrrspec/redis_models.rb
RRRSpec.Task.add_trial
ruby
def add_trial(trial) RRRSpec.redis.rpush(RRRSpec.make_key(key, 'trial'), trial.key) end
Public: Add a trial of the task.
train
https://github.com/cookpad/rrrspec/blob/a5bde2b062ce68b1e32b8caddf194389c2ce28b0/rrrspec-client/lib/rrrspec/redis_models.rb#L640-L643
class Task attr_reader :key def initialize(task_key) @key = task_key end def self.create(taskset, estimate_sec, spec_file) task_key = RRRSpec.make_key(taskset.key, 'task', spec_file) RRRSpec.redis.hmset( task_key, 'taskset', taskset.key, 'estimate_sec', estimate_sec, 'spec_file', spec_file ) return new(task_key) end def ==(other) @key == other.key end # ========================================================================== # Property # Public: Estimate time to finishe the task. # # Returns seconds or nil if there is no estimation def estimate_sec v = RRRSpec.redis.hget(key, 'estimate_sec') v.present? ? v.to_i : nil end # Public: Spec file to run. # # Returns a path to the spec def spec_file RRRSpec.redis.hget(key, 'spec_file') end # Public: Included taskset # # Returns a Taskset def taskset Taskset.new(RRRSpec.redis.hget(key, 'taskset')) end # ========================================================================== # Trial # Public: Returns the trials of the task. # The return value should be sorted in the order added. # # Returns an array of the Trials def trials RRRSpec.redis.lrange(RRRSpec.make_key(key, 'trial'), 0, -1).map do |key| Trial.new(key) end end # Public: Add a trial of the task. # ========================================================================== # Status # Public: Current status # # Returns either nil, "running", "passed", "pending" or "failed" def status RRRSpec.redis.hget(key, 'status') end # Public: Update the status. It should be one of: # [nil, "running", "passed", "pending", "failed"] def update_status(status) if status.present? RRRSpec.redis.hset(key, 'status', status) else RRRSpec.redis.hdel(key, 'status') end end # ========================================================================== # Serialize def to_h h = RRRSpec.redis.hgetall(key) h['key'] = key h['trials'] = trials.map { |trial| { 'key' => trial.key } } h['taskset'] = { 'key' => h['taskset'] } RRRSpec.convert_if_present(h, 'estimate_sec') { |v| v.to_i } h end def to_json(options=nil) to_h.to_json(options) end # ========================================================================== # Persistence def expire(sec) trials.each { |trial| trial.expire(sec) } RRRSpec.redis.expire(key, sec) RRRSpec.redis.expire(RRRSpec.make_key(key, 'trial'), sec) end end
ImpressCMS/vagrant-impressbox
lib/vagrant-impressbox/provisioner.rb
Impressbox.Provisioner.xaml_config
ruby
def xaml_config require_relative File.join('objects', 'config_file') file = detect_file(config.file) @machine.ui.info "\t" + I18n.t('config.loaded_from_file', file: file) Impressbox::Objects::ConfigFile.new file end
Loads xaml config @return [::Impressbox::Objects::ConfigFile]
train
https://github.com/ImpressCMS/vagrant-impressbox/blob/78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2/lib/vagrant-impressbox/provisioner.rb#L81-L86
class Provisioner < Vagrant.plugin('2', :provisioner) # Stores loaded ConfigFile instance # #@return [::Impressbox::Objects::ConfigFile,nil] @@__loaded_config = nil # Object with loaded config from file # #@return [::Impressbox::Objects::ConfigFile,nil] def self.loaded_config @@__loaded_config end # Cleanup operations def cleanup end # Do configuration operations # #@param root_config [Object] Current Vagrantfile configuration instance def configure(root_config) @@__loaded_config = xaml_config run_primaty_configuration root_config end # Do provision tasks def provision mass_loader('provision').each do |configurator| next unless configurator.can_be_configured?(@machine, @@__loaded_config) @machine.ui.info configurator.description if configurator.description configurator.configure @machine, @@__loaded_config end end private # Runs primary configuration # #@param root_config [Object] Root Vagrant config def run_primaty_configuration(root_config) old_root = root_config.dup old_loaded = @@__loaded_config.dup mass_loader('primary').each do |configurator| next unless configurator.can_be_configured?(old_root, old_loaded) @machine.ui.info configurator.description if configurator.description configurator.configure root_config, old_loaded end end # Gets preconfigured MassFileLoader instance # #@param type [String] Files type # #@return [::Impressbox::Objects::MassFileLoader] def mass_loader(type) namespace = 'Impressbox::Configurators::' + ucfirst(type) path = File.join('..', 'configurators', type) Impressbox::Objects::MassFileLoader.new namespace, path end # Makes first latter of tsuplied world in uppercase # #@param str [String] String to do what needed to do # #@return [String] def ucfirst(str) str[0] = str[0, 1].upcase str end # Loads xaml config # #@return [::Impressbox::Objects::ConfigFile] # Try to detect config.yaml file # #@param file [String] Tries file and if not returns default file # #@return [String] def detect_file(file) return file if File.exist?(file) 'config.yaml' end end
grpc/grpc
src/ruby/lib/grpc/generic/client_stub.rb
GRPC.ClientStub.request_response
ruby
def request_response(method, req, marshal, unmarshal, deadline: nil, return_op: false, parent: nil, credentials: nil, metadata: {}) c = new_active_call(method, marshal, unmarshal, deadline: deadline, parent: parent, credentials: credentials) interception_context = @interceptors.build_context intercept_args = { method: method, request: req, call: c.interceptable, metadata: metadata } if return_op # return the operation view of the active_call; define #execute as a # new method for this instance that invokes #request_response. c.merge_metadata_to_send(metadata) op = c.operation op.define_singleton_method(:execute) do interception_context.intercept!(:request_response, intercept_args) do c.request_response(req, metadata: metadata) end end op else interception_context.intercept!(:request_response, intercept_args) do c.request_response(req, metadata: metadata) end end end
Creates a new ClientStub. Minimally, a stub is created with the just the host of the gRPC service it wishes to access, e.g., my_stub = ClientStub.new(example.host.com:50505, :this_channel_is_insecure) If a channel_override argument is passed, it will be used as the underlying channel. Otherwise, the channel_args argument will be used to construct a new underlying channel. There are some specific keyword args that are not used to configure the channel: - :channel_override when present, this must be a pre-created GRPC::Core::Channel. If it's present the host and arbitrary keyword arg areignored, and the RPC connection uses this channel. - :timeout when present, this is the default timeout used for calls @param host [String] the host the stub connects to @param creds [Core::ChannelCredentials|Symbol] the channel credentials, or :this_channel_is_insecure, which explicitly indicates that the client should be created with an insecure connection. Note: this argument is ignored if the channel_override argument is provided. @param channel_override [Core::Channel] a pre-created channel @param timeout [Number] the default timeout to use in requests @param propagate_mask [Number] A bitwise combination of flags in GRPC::Core::PropagateMasks. Indicates how data should be propagated from parent server calls to child client calls if this client is being used within a gRPC server. @param channel_args [Hash] the channel arguments. Note: this argument is ignored if the channel_override argument is provided. @param interceptors [Array<GRPC::ClientInterceptor>] An array of GRPC::ClientInterceptor objects that will be used for intercepting calls before they are executed Interceptors are an EXPERIMENTAL API. request_response sends a request to a GRPC server, and returns the response. == Flow Control == This is a blocking call. * it does not return until a response is received. * the requests is sent only when GRPC core's flow control allows it to be sent. == Errors == An RuntimeError is raised if * the server responds with a non-OK status * the deadline is exceeded == Return Value == If return_op is false, the call returns the response If return_op is true, the call returns an Operation, calling execute on the Operation returns the response. @param method [String] the RPC method to call on the GRPC server @param req [Object] the request sent to the server @param marshal [Function] f(obj)->string that marshals requests @param unmarshal [Function] f(string)->obj that unmarshals responses @param deadline [Time] (optional) the time the request should complete @param return_op [true|false] return an Operation if true @param parent [Core::Call] a prior call whose reserved metadata will be propagated by this one. @param credentials [Core::CallCredentials] credentials to use when making the call @param metadata [Hash] metadata to be sent to the server @return [Object] the response received from the server
train
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/client_stub.rb#L148-L181
class ClientStub include Core::StatusCodes include Core::TimeConsts # Default timeout is infinity. DEFAULT_TIMEOUT = INFINITE_FUTURE # setup_channel is used by #initialize to constuct a channel from its # arguments. def self.setup_channel(alt_chan, host, creds, channel_args = {}) unless alt_chan.nil? fail(TypeError, '!Channel') unless alt_chan.is_a?(Core::Channel) return alt_chan end if channel_args['grpc.primary_user_agent'].nil? channel_args['grpc.primary_user_agent'] = '' else channel_args['grpc.primary_user_agent'] += ' ' end channel_args['grpc.primary_user_agent'] += "grpc-ruby/#{VERSION}" unless creds.is_a?(Core::ChannelCredentials) || creds.is_a?(Symbol) fail(TypeError, '!ChannelCredentials or Symbol') end Core::Channel.new(host, channel_args, creds) end # Allows users of the stub to modify the propagate mask. # # This is an advanced feature for use when making calls to another gRPC # server whilst running in the handler of an existing one. attr_writer :propagate_mask # Creates a new ClientStub. # # Minimally, a stub is created with the just the host of the gRPC service # it wishes to access, e.g., # # my_stub = ClientStub.new(example.host.com:50505, # :this_channel_is_insecure) # # If a channel_override argument is passed, it will be used as the # underlying channel. Otherwise, the channel_args argument will be used # to construct a new underlying channel. # # There are some specific keyword args that are not used to configure the # channel: # # - :channel_override # when present, this must be a pre-created GRPC::Core::Channel. If it's # present the host and arbitrary keyword arg areignored, and the RPC # connection uses this channel. # # - :timeout # when present, this is the default timeout used for calls # # @param host [String] the host the stub connects to # @param creds [Core::ChannelCredentials|Symbol] the channel credentials, or # :this_channel_is_insecure, which explicitly indicates that the client # should be created with an insecure connection. Note: this argument is # ignored if the channel_override argument is provided. # @param channel_override [Core::Channel] a pre-created channel # @param timeout [Number] the default timeout to use in requests # @param propagate_mask [Number] A bitwise combination of flags in # GRPC::Core::PropagateMasks. Indicates how data should be propagated # from parent server calls to child client calls if this client is being # used within a gRPC server. # @param channel_args [Hash] the channel arguments. Note: this argument is # ignored if the channel_override argument is provided. # @param interceptors [Array<GRPC::ClientInterceptor>] An array of # GRPC::ClientInterceptor objects that will be used for # intercepting calls before they are executed # Interceptors are an EXPERIMENTAL API. def initialize(host, creds, channel_override: nil, timeout: nil, propagate_mask: nil, channel_args: {}, interceptors: []) @ch = ClientStub.setup_channel(channel_override, host, creds, channel_args) alt_host = channel_args[Core::Channel::SSL_TARGET] @host = alt_host.nil? ? host : alt_host @propagate_mask = propagate_mask @timeout = timeout.nil? ? DEFAULT_TIMEOUT : timeout @interceptors = InterceptorRegistry.new(interceptors) end # request_response sends a request to a GRPC server, and returns the # response. # # == Flow Control == # This is a blocking call. # # * it does not return until a response is received. # # * the requests is sent only when GRPC core's flow control allows it to # be sent. # # == Errors == # An RuntimeError is raised if # # * the server responds with a non-OK status # # * the deadline is exceeded # # == Return Value == # # If return_op is false, the call returns the response # # If return_op is true, the call returns an Operation, calling execute # on the Operation returns the response. # # @param method [String] the RPC method to call on the GRPC server # @param req [Object] the request sent to the server # @param marshal [Function] f(obj)->string that marshals requests # @param unmarshal [Function] f(string)->obj that unmarshals responses # @param deadline [Time] (optional) the time the request should complete # @param return_op [true|false] return an Operation if true # @param parent [Core::Call] a prior call whose reserved metadata # will be propagated by this one. # @param credentials [Core::CallCredentials] credentials to use when making # the call # @param metadata [Hash] metadata to be sent to the server # @return [Object] the response received from the server # client_streamer sends a stream of requests to a GRPC server, and # returns a single response. # # requests provides an 'iterable' of Requests. I.e. it follows Ruby's # #each enumeration protocol. In the simplest case, requests will be an # array of marshallable objects; in typical case it will be an Enumerable # that allows dynamic construction of the marshallable objects. # # == Flow Control == # This is a blocking call. # # * it does not return until a response is received. # # * each requests is sent only when GRPC core's flow control allows it to # be sent. # # == Errors == # An RuntimeError is raised if # # * the server responds with a non-OK status # # * the deadline is exceeded # # == Return Value == # # If return_op is false, the call consumes the requests and returns # the response. # # If return_op is true, the call returns the response. # # @param method [String] the RPC method to call on the GRPC server # @param requests [Object] an Enumerable of requests to send # @param marshal [Function] f(obj)->string that marshals requests # @param unmarshal [Function] f(string)->obj that unmarshals responses # @param deadline [Time] (optional) the time the request should complete # @param return_op [true|false] return an Operation if true # @param parent [Core::Call] a prior call whose reserved metadata # will be propagated by this one. # @param credentials [Core::CallCredentials] credentials to use when making # the call # @param metadata [Hash] metadata to be sent to the server # @return [Object|Operation] the response received from the server def client_streamer(method, requests, marshal, unmarshal, deadline: nil, return_op: false, parent: nil, credentials: nil, metadata: {}) c = new_active_call(method, marshal, unmarshal, deadline: deadline, parent: parent, credentials: credentials) interception_context = @interceptors.build_context intercept_args = { method: method, requests: requests, call: c.interceptable, metadata: metadata } if return_op # return the operation view of the active_call; define #execute as a # new method for this instance that invokes #client_streamer. c.merge_metadata_to_send(metadata) op = c.operation op.define_singleton_method(:execute) do interception_context.intercept!(:client_streamer, intercept_args) do c.client_streamer(requests) end end op else interception_context.intercept!(:client_streamer, intercept_args) do c.client_streamer(requests, metadata: metadata) end end end # server_streamer sends one request to the GRPC server, which yields a # stream of responses. # # responses provides an enumerator over the streamed responses, i.e. it # follows Ruby's #each iteration protocol. The enumerator blocks while # waiting for each response, stops when the server signals that no # further responses will be supplied. If the implicit block is provided, # it is executed with each response as the argument and no result is # returned. # # == Flow Control == # This is a blocking call. # # * the request is sent only when GRPC core's flow control allows it to # be sent. # # * the request will not complete until the server sends the final # response followed by a status message. # # == Errors == # An RuntimeError is raised if # # * the server responds with a non-OK status when any response is # * retrieved # # * the deadline is exceeded # # == Return Value == # # if the return_op is false, the return value is an Enumerator of the # results, unless a block is provided, in which case the block is # executed with each response. # # if return_op is true, the function returns an Operation whose #execute # method runs server streamer call. Again, Operation#execute either # calls the given block with each response or returns an Enumerator of the # responses. # # == Keyword Args == # # Unspecified keyword arguments are treated as metadata to be sent to the # server. # # @param method [String] the RPC method to call on the GRPC server # @param req [Object] the request sent to the server # @param marshal [Function] f(obj)->string that marshals requests # @param unmarshal [Function] f(string)->obj that unmarshals responses # @param deadline [Time] (optional) the time the request should complete # @param return_op [true|false]return an Operation if true # @param parent [Core::Call] a prior call whose reserved metadata # will be propagated by this one. # @param credentials [Core::CallCredentials] credentials to use when making # the call # @param metadata [Hash] metadata to be sent to the server # @param blk [Block] when provided, is executed for each response # @return [Enumerator|Operation|nil] as discussed above def server_streamer(method, req, marshal, unmarshal, deadline: nil, return_op: false, parent: nil, credentials: nil, metadata: {}, &blk) c = new_active_call(method, marshal, unmarshal, deadline: deadline, parent: parent, credentials: credentials) interception_context = @interceptors.build_context intercept_args = { method: method, request: req, call: c.interceptable, metadata: metadata } if return_op # return the operation view of the active_call; define #execute # as a new method for this instance that invokes #server_streamer c.merge_metadata_to_send(metadata) op = c.operation op.define_singleton_method(:execute) do interception_context.intercept!(:server_streamer, intercept_args) do c.server_streamer(req, &blk) end end op else interception_context.intercept!(:server_streamer, intercept_args) do c.server_streamer(req, metadata: metadata, &blk) end end end # bidi_streamer sends a stream of requests to the GRPC server, and yields # a stream of responses. # # This method takes an Enumerable of requests, and returns and enumerable # of responses. # # == requests == # # requests provides an 'iterable' of Requests. I.e. it follows Ruby's # #each enumeration protocol. In the simplest case, requests will be an # array of marshallable objects; in typical case it will be an # Enumerable that allows dynamic construction of the marshallable # objects. # # == responses == # # This is an enumerator of responses. I.e, its #next method blocks # waiting for the next response. Also, if at any point the block needs # to consume all the remaining responses, this can be done using #each or # #collect. Calling #each or #collect should only be done if # the_call#writes_done has been called, otherwise the block will loop # forever. # # == Flow Control == # This is a blocking call. # # * the call completes when the next call to provided block returns # false # # * the execution block parameters are two objects for sending and # receiving responses, each of which blocks waiting for flow control. # E.g, calles to bidi_call#remote_send will wait until flow control # allows another write before returning; and obviously calls to # responses#next block until the next response is available. # # == Termination == # # As well as sending and receiving messages, the block passed to the # function is also responsible for: # # * calling bidi_call#writes_done to indicate no further reqs will be # sent. # # * returning false if once the bidi stream is functionally completed. # # Note that response#next will indicate that there are no further # responses by throwing StopIteration, but can only happen either # if bidi_call#writes_done is called. # # To properly terminate the RPC, the responses should be completely iterated # through; one way to do this is to loop on responses#next until no further # responses are available. # # == Errors == # An RuntimeError is raised if # # * the server responds with a non-OK status when any response is # * retrieved # # * the deadline is exceeded # # # == Return Value == # # if the return_op is false, the return value is an Enumerator of the # results, unless a block is provided, in which case the block is # executed with each response. # # if return_op is true, the function returns an Operation whose #execute # method runs the Bidi call. Again, Operation#execute either calls a # given block with each response or returns an Enumerator of the # responses. # # @param method [String] the RPC method to call on the GRPC server # @param requests [Object] an Enumerable of requests to send # @param marshal [Function] f(obj)->string that marshals requests # @param unmarshal [Function] f(string)->obj that unmarshals responses # @param deadline [Time] (optional) the time the request should complete # @param return_op [true|false] return an Operation if true # @param parent [Core::Call] a prior call whose reserved metadata # will be propagated by this one. # @param credentials [Core::CallCredentials] credentials to use when making # the call # @param metadata [Hash] metadata to be sent to the server # @param blk [Block] when provided, is executed for each response # @return [Enumerator|nil|Operation] as discussed above def bidi_streamer(method, requests, marshal, unmarshal, deadline: nil, return_op: false, parent: nil, credentials: nil, metadata: {}, &blk) c = new_active_call(method, marshal, unmarshal, deadline: deadline, parent: parent, credentials: credentials) interception_context = @interceptors.build_context intercept_args = { method: method, requests: requests, call: c.interceptable, metadata: metadata } if return_op # return the operation view of the active_call; define #execute # as a new method for this instance that invokes #bidi_streamer c.merge_metadata_to_send(metadata) op = c.operation op.define_singleton_method(:execute) do interception_context.intercept!(:bidi_streamer, intercept_args) do c.bidi_streamer(requests, &blk) end end op else interception_context.intercept!(:bidi_streamer, intercept_args) do c.bidi_streamer(requests, metadata: metadata, &blk) end end end private # Creates a new active stub # # @param method [string] the method being called. # @param marshal [Function] f(obj)->string that marshals requests # @param unmarshal [Function] f(string)->obj that unmarshals responses # @param parent [Grpc::Call] a parent call, available when calls are # made from server # @param credentials [Core::CallCredentials] credentials to use when making # the call def new_active_call(method, marshal, unmarshal, deadline: nil, parent: nil, credentials: nil) deadline = from_relative_time(@timeout) if deadline.nil? # Provide each new client call with its own completion queue call = @ch.create_call(parent, # parent call @propagate_mask, # propagation options method, nil, # host use nil, deadline) call.set_credentials! credentials unless credentials.nil? ActiveCall.new(call, marshal, unmarshal, deadline, started: false) end end
CocoaPods/Xcodeproj
lib/xcodeproj/workspace.rb
Xcodeproj.Workspace.save_as
ruby
def save_as(path) FileUtils.mkdir_p(path) File.open(File.join(path, 'contents.xcworkspacedata'), 'w') do |out| out << to_s end end
Saves the workspace at the given `xcworkspace` path. @param [String] path the path where to save the project. @return [void]
train
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/workspace.rb#L179-L184
class Workspace # @return [REXML::Document] the parsed XML model for the workspace contents attr_reader :document # @return [Hash<String => String>] a mapping from scheme name to project full path # containing the scheme attr_reader :schemes # @return [Array<FileReference>] the paths of the projects contained in the # workspace. # def file_references return [] unless @document @document.get_elements('/Workspace//FileRef').map do |node| FileReference.from_node(node) end end # @return [Array<GroupReference>] the groups contained in the workspace # def group_references return [] unless @document @document.get_elements('/Workspace//Group').map do |node| GroupReference.from_node(node) end end # @param [REXML::Document] document @see document # @param [Array<FileReference>] file_references additional projects to add # # @note The document parameter is passed to the << operator if it is not a # valid REXML::Document. It is optional, but may also be passed as nil # def initialize(document, *file_references) @schemes = {} if document.nil? @document = REXML::Document.new(root_xml('')) elsif document.is_a?(REXML::Document) @document = document else @document = REXML::Document.new(root_xml('')) self << document end file_references.each { |ref| self << ref } end #-------------------------------------------------------------------------# # Returns a workspace generated by reading the contents of the given path. # # @param [String] path # the path of the `xcworkspace` file. # # @return [Workspace] the generated workspace. # def self.new_from_xcworkspace(path) from_s(File.read(File.join(path, 'contents.xcworkspacedata')), File.expand_path(path)) rescue Errno::ENOENT new(nil) end #-------------------------------------------------------------------------# # Returns a workspace generated by reading the contents of the given # XML representation. # # @param [String] xml # the XML representation of the workspace. # # @return [Workspace] the generated workspace. # def self.from_s(xml, workspace_path = '') document = REXML::Document.new(xml) instance = new(document) instance.load_schemes(workspace_path) instance end # Adds a new path to the list of the of projects contained in the # workspace. # @param [String, Xcodeproj::Workspace::FileReference] path_or_reference # A string or Xcode::Workspace::FileReference containing a path to an Xcode project # # @raise [ArgumentError] Raised if the input is neither a String nor a FileReference # # @return [void] # def <<(path_or_reference) return unless @document && @document.respond_to?(:root) case path_or_reference when String project_file_reference = Xcodeproj::Workspace::FileReference.new(path_or_reference) when Xcodeproj::Workspace::FileReference project_file_reference = path_or_reference projpath = nil else raise ArgumentError, "Input to the << operator must be a file path or FileReference, got #{path_or_reference.inspect}" end @document.root.add_element(project_file_reference.to_node) load_schemes_from_project File.expand_path(projpath || project_file_reference.path) end #-------------------------------------------------------------------------# # Adds a new group container to the workspace # workspace. # # @param [String] name The name of the group # # @yield [Xcodeproj::Workspace::GroupReference, REXML::Element] # Yields the GroupReference and underlying XML element for mutation # # @return [Xcodeproj::Workspace::GroupReference] The added group reference # def add_group(name) return nil unless @document group = Xcodeproj::Workspace::GroupReference.new(name) elem = @document.root.add_element(group.to_node) yield group, elem if block_given? group end # Checks if the workspace contains the project with the given file # reference. # # @param [FileReference] file_reference # The file_reference to the project. # # @return [Boolean] whether the project is contained in the workspace. # def include?(file_reference) file_references.include?(file_reference) end # @return [String] the XML representation of the workspace. # def to_s contents = '' stack = [] @document.root.each_recursive do |elem| until stack.empty? last = stack.last break if last == elem.parent contents += xcworkspace_element_end_xml(stack.length, last) stack.pop end stack << elem contents += xcworkspace_element_start_xml(stack.length, elem) end until stack.empty? contents += xcworkspace_element_end_xml(stack.length, stack.last) stack.pop end root_xml(contents) end # Saves the workspace at the given `xcworkspace` path. # # @param [String] path # the path where to save the project. # # @return [void] # #-------------------------------------------------------------------------# # Load all schemes from all projects in workspace or in the workspace container itself # # @param [String] workspace_dir_path # path of workspaces dir # # @return [void] # def load_schemes(workspace_dir_path) # Normalizes path to directory of workspace needed for file_reference.absolute_path workspaces_dir = workspace_dir_path if File.extname(workspace_dir_path) == '.xcworkspace' workspaces_dir = File.expand_path('..', workspaces_dir) end file_references.each do |file_reference| project_full_path = file_reference.absolute_path(workspaces_dir) load_schemes_from_project(project_full_path) end # Load schemes that are in the workspace container. workspace_abs_path = File.absolute_path(workspace_dir_path) Dir[File.join(workspace_dir_path, 'xcshareddata', 'xcschemes', '*.xcscheme')].each do |scheme| scheme_name = File.basename(scheme, '.xcscheme') @schemes[scheme_name] = workspace_abs_path end end private # Load all schemes from project # # @param [String] project_full_path # project full path # # @return [void] # def load_schemes_from_project(project_full_path) schemes = Xcodeproj::Project.schemes project_full_path schemes.each do |scheme_name| @schemes[scheme_name] = project_full_path end end # @return [String] The template of the workspace XML as formated by Xcode. # # @param [String] contents The XML contents of the workspace. # def root_xml(contents) <<-DOC <?xml version="1.0" encoding="UTF-8"?> <Workspace version = "1.0"> #{contents.rstrip} </Workspace> DOC end # # @param [Integer] depth The depth of the element in the tree # @param [REXML::Document::Element] elem The XML element to format. # # @return [String] The Xcode-specific XML formatting of an element start # def xcworkspace_element_start_xml(depth, elem) attributes = case elem.name when 'Group' %w(location name) when 'FileRef' %w(location) end contents = "<#{elem.name}" indent = ' ' * depth attributes.each { |name| contents += "\n #{name} = \"#{elem.attribute(name)}\"" } contents.split("\n").map { |line| "#{indent}#{line}" }.join("\n") + ">\n" end # # @param [Integer] depth The depth of the element in the tree # @param [REXML::Document::Element] elem The XML element to format. # # @return [String] The Xcode-specific XML formatting of an element end # def xcworkspace_element_end_xml(depth, elem) "#{' ' * depth}</#{elem.name}>\n" end #-------------------------------------------------------------------------# end
puppetlabs/beaker-aws
lib/beaker/hypervisor/aws_sdk.rb
Beaker.AwsSdk.create_group
ruby
def create_group(region_or_vpc, ports, sg_cidr_ips = ['0.0.0.0/0']) name = group_id(ports) @logger.notify("aws-sdk: Creating group #{name} for ports #{ports.to_s}") @logger.notify("aws-sdk: Creating group #{name} with CIDR IPs #{sg_cidr_ips.to_s}") cl = region_or_vpc.is_a?(String) ? client(region_or_vpc) : client params = { :description => "Custom Beaker security group for #{ports.to_a}", :group_name => name, } params[:vpc_id] = region_or_vpc.vpc_id if region_or_vpc.is_a?(Aws::EC2::Types::Vpc) group = cl.create_security_group(params) unless ports.is_a? Set ports = Set.new(ports) end sg_cidr_ips.each do |cidr_ip| ports.each do |port| add_ingress_rule(cl, group, cidr_ip, port, port) end end group end
Create a new security group Accepts a region or VPC for group creation. @param region_or_vpc [Aws::EC2::Region, Aws::EC2::VPC] the AWS region or vpc control object @param ports [Array<Number>] an array of port numbers @param sg_cidr_ips [Array<String>] CIDRs used for outbound security group rule @return [Aws::EC2::SecurityGroup] created security group @api private
train
https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L1068-L1094
class AwsSdk < Beaker::Hypervisor ZOMBIE = 3 #anything older than 3 hours is considered a zombie PING_SECURITY_GROUP_NAME = 'beaker-ping' attr_reader :default_region # Initialize AwsSdk hypervisor driver # # @param [Array<Beaker::Host>] hosts Array of Beaker::Host objects # @param [Hash<String, String>] options Options hash def initialize(hosts, options) @hosts = hosts @options = options @logger = options[:logger] @default_region = ENV['AWS_REGION'] || 'us-west-2' # Get AWS credentials creds = options[:use_fog_credentials] ? load_credentials() : nil config = { :credentials => creds, :logger => Logger.new($stdout), :log_level => :debug, :log_formatter => Aws::Log::Formatter.colored, :retry_limit => 12, :region => ENV['AWS_REGION'] || 'us-west-2' }.delete_if{ |k,v| v.nil? } Aws.config.update(config) @client = {} @client.default_proc = proc do |hash, key| hash[key] = Aws::EC2::Client.new(:region => key) end test_split_install() end def client(region = default_region) @client[region] end # Provision all hosts on EC2 using the Aws::EC2 API # # @return [void] def provision start_time = Time.now # Perform the main launch work launch_all_nodes() # Add metadata tags to each instance # tagging early as some nodes take longer # to initialize and terminate before it has # a chance to provision add_tags() # adding the correct security groups to the # network interface, as during the `launch_all_nodes()` # step they never get assigned, although they get created modify_network_interface() wait_for_status_netdev() # Grab the ip addresses and dns from EC2 for each instance to use for ssh populate_dns() #enable root if user is not root enable_root_on_hosts() # Set the hostname for each box set_hostnames() # Configure /etc/hosts on each host configure_hosts() @logger.notify("aws-sdk: Provisioning complete in #{Time.now - start_time} seconds") nil #void end def regions @regions ||= client.describe_regions.regions.map(&:region_name) end # Kill all instances. # # @param instances [Enumerable<Aws::EC2::Types::Instance>] # @return [void] def kill_instances(instances) running_instances = instances.compact.select do |instance| instance_by_id(instance.instance_id).state.name == 'running' end instance_ids = running_instances.map(&:instance_id) return nil if instance_ids.empty? @logger.notify("aws-sdk: killing EC2 instance(s) #{instance_ids.join(', ')}") client.terminate_instances(:instance_ids => instance_ids) nil end # Cleanup all earlier provisioned hosts on EC2 using the Aws::EC2 library # # It goes without saying, but a #cleanup does nothing without a #provision # method call first. # # @return [void] def cleanup # Provisioning should have set the host 'instance' values. kill_instances(@hosts.map{ |h| h['instance'] }.select{ |x| !x.nil? }) delete_key_pair_all_regions() nil end # Print instances to the logger. Instances will be from all regions # associated with provided key name and limited by regex compared to # instance status. Defaults to running instances. # # @param [String] key The key_name to match for # @param [Regex] status The regular expression to match against the instance's status def log_instances(key = key_name, status = /running/) instances = [] regions.each do |region| @logger.debug "Reviewing: #{region}" client(region).describe_instances.reservations.each do |reservation| reservation.instances.each do |instance| if (instance.key_name =~ /#{key}/) and (instance.state.name =~ status) instances << instance end end end end output = "" instances.each do |instance| dns_name = instance.public_dns_name || instance.private_dns_name output << "#{instance.instance_id} keyname: #{instance.key_name}, dns name: #{dns_name}, private ip: #{instance.private_ip_address}, ip: #{instance.public_ip_address}, launch time #{instance.launch_time}, status: #{instance.state.name}\n" end @logger.notify("aws-sdk: List instances (keyname: #{key})") @logger.notify("#{output}") end # Provided an id return an instance object. # Instance object will respond to methods described here: {http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/EC2/Instance.html AWS Instance Object}. # @param [String] id The id of the instance to return # @return [Aws::EC2::Types::Instance] An Aws::EC2 instance object def instance_by_id(id) client.describe_instances(:instance_ids => [id]).reservations.first.instances.first end # Return all instances currently on ec2. # @see AwsSdk#instance_by_id # @return [Array<Aws::Ec2::Types::Instance>] An array of Aws::EC2 instance objects def instances client.describe_instances.reservations.map(&:instances).flatten end # Provided an id return a VPC object. # VPC object will respond to methods described here: {http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/EC2/VPC.html AWS VPC Object}. # @param [String] id The id of the VPC to return # @return [Aws::EC2::Types::Vpc] An Aws::EC2 vpc object def vpc_by_id(id) client.describe_vpcs(:vpc_ids => [id]).vpcs.first end # Return all VPCs currently on ec2. # @see AwsSdk#vpc_by_id # @return [Array<Aws::EC2::Types::Vpc>] An array of Aws::EC2 vpc objects def vpcs client.describe_vpcs.vpcs end # Provided an id return a security group object # Security object will respond to methods described here: {http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/EC2/SecurityGroup.html AWS SecurityGroup Object}. # @param [String] id The id of the security group to return # @return [Aws::EC2::Types::SecurityGroup] An Aws::EC2 security group object def security_group_by_id(id) client.describe_security_groups(:group_ids => [id]).security_groups.first end # Return all security groups currently on ec2. # @see AwsSdk#security_goup_by_id # @return [Array<Aws::EC2::Types::SecurityGroup>] An array of Aws::EC2 security group objects def security_groups client.describe_security_groups.security_groups end # Shutdown and destroy ec2 instances idenfitied by key that have been alive # longer than ZOMBIE hours. # # @param [Integer] max_age The age in hours that a machine needs to be older than to be considered a zombie # @param [String] key The key_name to match for def kill_zombies(max_age = ZOMBIE, key = key_name) @logger.notify("aws-sdk: Kill Zombies! (keyname: #{key}, age: #{max_age} hrs)") instances_to_kill = [] time_now = Time.now.getgm #ec2 uses GM time #examine all available regions regions.each do |region| @logger.debug "Reviewing: #{region}" client(region).describe_instances.reservations.each do |reservation| reservation.instances.each do |instance| if (instance.key_name =~ /#{key}/) @logger.debug "Examining #{instance.instance_id} (keyname: #{instance.key_name}, launch time: #{instance.launch_time}, state: #{instance.state.name})" if ((time_now - instance.launch_time) > max_age*60*60) and instance.state.name !~ /terminated/ @logger.debug "Kill! #{instance.instance_id}: #{instance.key_name} (Current status: #{instance.state.name})" instances_to_kill << instance end end end end end kill_instances(instances_to_kill) delete_key_pair_all_regions(key_name_prefix) @logger.notify "#{key}: Killed #{instances_to_kill.length} instance(s)" end # Destroy any volumes marked 'available', INCLUDING THOSE YOU DON'T OWN! Use with care. def kill_zombie_volumes # Occasionaly, tearing down ec2 instances leaves orphaned EBS volumes behind -- these stack up quickly. # This simply looks for EBS volumes that are not in use @logger.notify("aws-sdk: Kill Zombie Volumes!") volume_count = 0 regions.each do |region| @logger.debug "Reviewing: #{region}" available_volumes = client(region).describe_volumes( :filters => [ { :name => 'status', :values => ['available'], } ] ).volumes available_volumes.each do |volume| begin client(region).delete_volume(:volume_id => volume.id) volume_count += 1 rescue Aws::EC2::Errors::InvalidVolume::NotFound => e @logger.debug "Failed to remove volume: #{volume.id} #{e}" end end end @logger.notify "Freed #{volume_count} volume(s)" end # Create an EC2 instance for host, tag it, and return it. # # @return [void] # @api private def create_instance(host, ami_spec, subnet_id) amitype = host['vmname'] || host['platform'] amisize = host['amisize'] || 'm1.small' vpc_id = host['vpc_id'] || @options['vpc_id'] || nil host['sg_cidr_ips'] = host['sg_cidr_ips'] || '0.0.0.0/0'; sg_cidr_ips = host['sg_cidr_ips'].split(',') assoc_pub_ip_addr = host['associate_public_ip_address'] if vpc_id && !subnet_id raise RuntimeError, "A subnet_id must be provided with a vpc_id" end if assoc_pub_ip_addr && !subnet_id raise RuntimeError, "A subnet_id must be provided when configuring assoc_pub_ip_addr" end # Use snapshot provided for this host image_type = host['snapshot'] raise RuntimeError, "No snapshot/image_type provided for EC2 provisioning" unless image_type ami = ami_spec[amitype] ami_region = ami[:region] # Main region object for ec2 operations region = ami_region # If we haven't defined a vpc_id then we use the default vpc for the provided region unless vpc_id @logger.notify("aws-sdk: filtering available vpcs in region by 'isDefault'") default_vpcs = client(region).describe_vpcs(:filters => [{:name => 'isDefault', :values => ['true']}]) vpc_id = if default_vpcs.vpcs.empty? nil else default_vpcs.vpcs.first.vpc_id end end # Grab the vpc object based upon provided id vpc = vpc_id ? client(region).describe_vpcs(:vpc_ids => [vpc_id]).vpcs.first : nil # Grab image object image_id = ami[:image][image_type.to_sym] @logger.notify("aws-sdk: Checking image #{image_id} exists and getting its root device") image = client(region).describe_images(:image_ids => [image_id]).images.first raise RuntimeError, "Image not found: #{image_id}" if image.nil? @logger.notify("Image Storage Type: #{image.root_device_type}") # Transform the images block_device_mappings output into a format # ready for a create. block_device_mappings = [] if image.root_device_type == :ebs orig_bdm = image.block_device_mappings @logger.notify("aws-sdk: Image block_device_mappings: #{orig_bdm}") orig_bdm.each do |block_device| block_device_mappings << { :device_name => block_device.device_name, :ebs => { # Change the default size of the root volume. :volume_size => host['volume_size'] || block_device.ebs.volume_size, # This is required to override the images default for # delete_on_termination, forcing all volumes to be deleted once the # instance is terminated. :delete_on_termination => true, } } end end security_group = ensure_group(vpc || region, Beaker::EC2Helper.amiports(host), sg_cidr_ips) #check if ping is enabled ping_security_group = ensure_ping_group(vpc || region, sg_cidr_ips) msg = "aws-sdk: launching %p on %p using %p/%p%s" % [host.name, amitype, amisize, image_type, subnet_id ? ("in %p" % subnet_id) : ''] @logger.notify(msg) config = { :max_count => 1, :min_count => 1, :image_id => image_id, :monitoring => { :enabled => true, }, :key_name => ensure_key_pair(region).key_pairs.first.key_name, :instance_type => amisize, :disable_api_termination => false, :instance_initiated_shutdown_behavior => "terminate", } if assoc_pub_ip_addr # this never gets created, so they end up with # default security group which only allows for # ssh access from outside world which # doesn't work well with remote devices etc. config[:network_interfaces] = [{ :subnet_id => subnet_id, :groups => [security_group.group_id, ping_security_group.group_id], :device_index => 0, :associate_public_ip_address => assoc_pub_ip_addr, }] else config[:subnet_id] = subnet_id end config[:block_device_mappings] = block_device_mappings if image.root_device_type == :ebs reservation = client(region).run_instances(config) reservation.instances.first end # For each host, create an EC2 instance in one of the specified # subnets and push it onto instances_created. Each subnet will be # tried at most once for each host, and more than one subnet may # be tried if capacity constraints are encountered. Each Hash in # instances_created will contain an :instance and :host value. # # @param hosts [Enumerable<Host>] # @param subnets [Enumerable<String>] # @param ami_spec [Hash] # @param instances_created Enumerable<Hash{Symbol=>EC2::Instance,Host}> # @return [void] # @api private def launch_nodes_on_some_subnet(hosts, subnets, ami_spec, instances_created) # Shuffle the subnets so we don't always hit the same one # first, and cycle though the subnets independently of the # host, so we stick with one that's working. Try each subnet # once per-host. if subnets.nil? or subnets.empty? return end subnet_i = 0 shuffnets = subnets.shuffle hosts.each do |host| instance = nil shuffnets.length.times do begin subnet_id = shuffnets[subnet_i] instance = create_instance(host, ami_spec, subnet_id) instances_created.push({:instance => instance, :host => host}) break rescue Aws::EC2::Errors::InsufficientInstanceCapacity @logger.notify("aws-sdk: hit #{subnet_id} capacity limit; moving on") subnet_i = (subnet_i + 1) % shuffnets.length end end if instance.nil? raise RuntimeError, "unable to launch host in any requested subnet" end end end # Create EC2 instances for all hosts, tag them, and wait until # they're running. When a host provides a subnet_id, create the # instance in that subnet, otherwise prefer a CONFIG subnet_id. # If neither are set but there is a CONFIG subnet_ids list, # attempt to create the host in each specified subnet, which might # fail due to capacity constraints, for example. Specifying both # a CONFIG subnet_id and subnet_ids will provoke an error. # # @return [void] # @api private def launch_all_nodes @logger.notify("aws-sdk: launch all hosts in configuration") ami_spec = YAML.load_file(@options[:ec2_yaml])["AMI"] global_subnet_id = @options['subnet_id'] global_subnets = @options['subnet_ids'] if global_subnet_id and global_subnets raise RuntimeError, 'Config specifies both subnet_id and subnet_ids' end no_subnet_hosts = [] specific_subnet_hosts = [] some_subnet_hosts = [] @hosts.each do |host| if global_subnet_id or host['subnet_id'] specific_subnet_hosts.push(host) elsif global_subnets some_subnet_hosts.push(host) else no_subnet_hosts.push(host) end end instances = [] # Each element is {:instance => i, :host => h} begin @logger.notify("aws-sdk: launch instances not particular about subnet") launch_nodes_on_some_subnet(some_subnet_hosts, global_subnets, ami_spec, instances) @logger.notify("aws-sdk: launch instances requiring a specific subnet") specific_subnet_hosts.each do |host| subnet_id = host['subnet_id'] || global_subnet_id instance = create_instance(host, ami_spec, subnet_id) instances.push({:instance => instance, :host => host}) end @logger.notify("aws-sdk: launch instances requiring no subnet") no_subnet_hosts.each do |host| instance = create_instance(host, ami_spec, nil) instances.push({:instance => instance, :host => host}) end wait_for_status(:running, instances) rescue Exception => ex @logger.notify("aws-sdk: exception #{ex.class}: #{ex}") kill_instances(instances.map{|x| x[:instance]}) raise ex end # At this point, all instances should be running since wait # either returns on success or throws an exception. if instances.empty? raise RuntimeError, "Didn't manage to launch any EC2 instances" end # Assign the now known running instances to their hosts. instances.each {|x| x[:host]['instance'] = x[:instance]} nil end # Wait until all instances reach the desired state. Each Hash in # instances must contain an :instance and :host value. # # @param state_name [String] EC2 state to wait for, 'running', 'stopped', etc. # @param instances Enumerable<Hash{Symbol=>EC2::Instance,Host}> # @param block [Proc] more complex checks can be made by passing a # block in. This overrides the status parameter. # EC2::Instance objects from the hosts will be # yielded to the passed block # @return [void] # @api private # FIXME: rename to #wait_for_state def wait_for_status(state_name, instances, &block) # Wait for each node to reach status :running @logger.notify("aws-sdk: Waiting for all hosts to be #{state_name}") instances.each do |x| name = x[:host] ? x[:host].name : x[:name] instance = x[:instance] @logger.notify("aws-sdk: Wait for node #{name} to be #{state_name}") # Here we keep waiting for the machine state to reach 'running' with an # exponential backoff for each poll. # TODO: should probably be a in a shared method somewhere for tries in 1..10 refreshed_instance = instance_by_id(instance.instance_id) if refreshed_instance.nil? @logger.debug("Instance #{name} not yet available (#{e})") else if block_given? test_result = yield refreshed_instance else test_result = refreshed_instance.state.name.to_s == state_name.to_s end if test_result x[:instance] = refreshed_instance # Always sleep, so the next command won't cause a throttle backoff_sleep(tries) break elsif tries == 10 raise "Instance never reached state #{state_name}" end end backoff_sleep(tries) end end end # Handles special checks needed for netdev platforms. # # @note if any host is an netdev one, these checks will happen once across all # of the hosts, and then we'll exit # # @return [void] # @api private def wait_for_status_netdev() @hosts.each do |host| if host['platform'] =~ /f5-|netscaler/ wait_for_status(:running, @hosts) wait_for_status(nil, @hosts) do |instance| instance_status_collection = client.describe_instance_status({:instance_ids => [instance.instance_id]}) first_instance = instance_status_collection.first[:instance_statuses].first first_instance[:instance_status][:status] == "ok" if first_instance end break end end end # Add metadata tags to all instances # # @return [void] # @api private def add_tags @hosts.each do |host| instance = host['instance'] # Define tags for the instance @logger.notify("aws-sdk: Add tags for #{host.name}") tags = [ { :key => 'jenkins_build_url', :value => @options[:jenkins_build_url], }, { :key => 'Name', :value => host.name, }, { :key => 'department', :value => @options[:department], }, { :key => 'project', :value => @options[:project], }, { :key => 'created_by', :value => @options[:created_by], }, ] host[:host_tags].each do |name, val| tags << { :key => name.to_s, :value => val } end client.create_tags( :resources => [instance.instance_id], :tags => tags.reject { |r| r[:value].nil? }, ) end nil end # Add correct security groups to hosts network_interface # as during the create_instance stage it is too early in process # to configure # # @return [void] # @api private def modify_network_interface @hosts.each do |host| instance = host['instance'] host['sg_cidr_ips'] = host['sg_cidr_ips'] || '0.0.0.0/0'; sg_cidr_ips = host['sg_cidr_ips'].split(',') # Define tags for the instance @logger.notify("aws-sdk: Update network_interface for #{host.name}") security_group = ensure_group(instance[:network_interfaces].first, Beaker::EC2Helper.amiports(host), sg_cidr_ips) ping_security_group = ensure_ping_group(instance[:network_interfaces].first, sg_cidr_ips) client.modify_network_interface_attribute( :network_interface_id => "#{instance[:network_interfaces].first[:network_interface_id]}", :groups => [security_group.group_id, ping_security_group.group_id], ) end nil end # Populate the hosts IP address from the EC2 dns_name # # @return [void] # @api private def populate_dns # Obtain the IP addresses and dns_name for each host @hosts.each do |host| @logger.notify("aws-sdk: Populate DNS for #{host.name}") instance = host['instance'] host['ip'] = instance.public_ip_address || instance.private_ip_address host['private_ip'] = instance.private_ip_address host['dns_name'] = instance.public_dns_name || instance.private_dns_name @logger.notify("aws-sdk: name: #{host.name} ip: #{host['ip']} private_ip: #{host['private_ip']} dns_name: #{host['dns_name']}") end nil end # Return a valid /etc/hosts line for a given host # # @param [Beaker::Host] host Beaker::Host object for generating /etc/hosts entry # @param [Symbol] interface Symbol identifies which ip should be used for host # @return [String] formatted hosts entry for host # @api private def etc_hosts_entry(host, interface = :ip) name = host.name domain = get_domain_name(host) ip = host[interface.to_s] "#{ip}\t#{name} #{name}.#{domain} #{host['dns_name']}\n" end # Configure /etc/hosts for each node # # @note f5 hosts are skipped since this isn't a valid step there # # @return [void] # @api private def configure_hosts non_netdev_windows_hosts = @hosts.select{ |h| !(h['platform'] =~ /f5-|netscaler|windows/) } non_netdev_windows_hosts.each do |host| host_entries = non_netdev_windows_hosts.map do |h| h == host ? etc_hosts_entry(h, :private_ip) : etc_hosts_entry(h) end host_entries.unshift "127.0.0.1\tlocalhost localhost.localdomain\n" set_etc_hosts(host, host_entries.join('')) end nil end # Enables root for instances with custom username like ubuntu-amis # # @return [void] # @api private def enable_root_on_hosts @hosts.each do |host| if host['disable_root_ssh'] == true @logger.notify("aws-sdk: Not enabling root for instance as disable_root_ssh is set to 'true'.") else @logger.notify("aws-sdk: Enabling root ssh") enable_root(host) end end end # Enables root access for a host when username is not root # # @return [void] # @api private def enable_root(host) if host['user'] != 'root' if host['platform'] =~ /f5-/ enable_root_f5(host) elsif host['platform'] =~ /netscaler/ enable_root_netscaler(host) else copy_ssh_to_root(host, @options) enable_root_login(host, @options) host['user'] = 'root' end host.close end end # Enables root access for a host on an f5 platform # @note This method does not support other platforms # # @return nil # @api private def enable_root_f5(host) for tries in 1..10 begin #This command is problematic as the F5 is not always done loading if host.exec(Command.new("modify sys db systemauth.disablerootlogin value false"), :acceptable_exit_codes => [0,1]).exit_code == 0 \ and host.exec(Command.new("modify sys global-settings gui-setup disabled"), :acceptable_exit_codes => [0,1]).exit_code == 0 \ and host.exec(Command.new("save sys config"), :acceptable_exit_codes => [0,1]).exit_code == 0 backoff_sleep(tries) break elsif tries == 10 raise "Instance was unable to be configured" end rescue Beaker::Host::CommandFailure => e @logger.debug("Instance not yet configured (#{e})") end backoff_sleep(tries) end host['user'] = 'admin' sha256 = Digest::SHA256.new password = sha256.hexdigest((1..50).map{(rand(86)+40).chr}.join.gsub(/\\/,'\&\&')) + 'password!' # disabling password policy to account for the enforcement level set # and the generated password is sometimes too `01070366:3: Bad password (admin): BAD PASSWORD: \ # it is too simplistic/systematic` host.exec(Command.new('modify auth password-policy policy-enforcement disabled')) host.exec(Command.new("modify auth user admin password #{password}")) @logger.notify("f5: Configured admin password to be #{password}") host.close host['ssh'] = {:password => password} end # Enables root access for a host on an netscaler platform # @note This method does not support other platforms # # @return nil # @api private def enable_root_netscaler(host) host['ssh'] = {:password => host['instance'].instance_id} @logger.notify("netscaler: nsroot password is #{host['instance'].instance_id}") end # Set the :vmhostname for each host object to be the dns_name, which is accessible # publicly. Then configure each ec2 machine to that dns_name, so that when facter # is installed the facts for hostname and domain match the dns_name. # # if :use_beaker_hostnames: is true, set the :vmhostname and hostname of each ec2 # machine to the host[:name] from the beaker hosts file. # # @return [@hosts] # @api private def set_hostnames if @options[:use_beaker_hostnames] @hosts.each do |host| host[:vmhostname] = host.name if host['platform'] =~ /el-7/ # on el-7 hosts, the hostname command doesn't "stick" randomly host.exec(Command.new("hostnamectl set-hostname #{host.name}")) elsif host['platform'] =~ /windows/ @logger.notify('aws-sdk: Change hostname on windows is not supported.') else next if host['platform'] =~ /f5-|netscaler/ host.exec(Command.new("hostname #{host.name}")) if host['vmname'] =~ /^amazon/ # Amazon Linux requires this to preserve host name changes across reboots. # http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-hostname.html # Also note that without an elastic ip set, while this will # preserve the hostname across a full shutdown/startup of the vm # (as opposed to a reboot) -- the ip address will have changed. host.exec(Command.new("sed -ie '/^HOSTNAME/ s/=.*/=#{host.name}/' /etc/sysconfig/network")) end end end else @hosts.each do |host| host[:vmhostname] = host[:dns_name] if host['platform'] =~ /el-7/ # on el-7 hosts, the hostname command doesn't "stick" randomly host.exec(Command.new("hostnamectl set-hostname #{host.hostname}")) elsif host['platform'] =~ /windows/ @logger.notify('aws-sdk: Change hostname on windows is not supported.') else next if host['platform'] =~ /ft-|netscaler/ host.exec(Command.new("hostname #{host.hostname}")) if host['vmname'] =~ /^amazon/ # See note above host.exec(Command.new("sed -ie '/^HOSTNAME/ s/=.*/=#{host.hostname}/' /etc/sysconfig/network")) end end end end end # Calculates and waits a back-off period based on the number of tries # # Logs each backupoff time and retry value to the console. # # @param tries [Number] number of tries to calculate back-off period # @return [void] # @api private def backoff_sleep(tries) # Exponential with some randomization sleep_time = 2 ** tries @logger.notify("aws-sdk: Sleeping #{sleep_time} seconds for attempt #{tries}.") sleep sleep_time nil end # Retrieve the public key locally from the executing users ~/.ssh directory # # @return [String] contents of public key # @api private def public_key keys = Array(@options[:ssh][:keys]) keys << '~/.ssh/id_rsa' keys << '~/.ssh/id_dsa' key_file = keys.find do |key| key_pub = key + '.pub' File.exist?(File.expand_path(key_pub)) && File.exist?(File.expand_path(key)) end if key_file @logger.debug("Using public key: #{key_file}") else raise RuntimeError, "Expected to find a public key, but couldn't in #{keys}" end File.read(File.expand_path(key_file + '.pub')) end # Generate a key prefix for key pair names # # @note This is the part of the key that will stay static between Beaker # runs on the same host. # # @return [String] Beaker key pair name based on sanitized hostname def key_name_prefix safe_hostname = Socket.gethostname.gsub('.', '-') "Beaker-#{local_user}-#{safe_hostname}" end # Generate a reusable key name from the local hosts hostname # # @return [String] safe key name for current host # @api private def key_name "#{key_name_prefix}-#{@options[:aws_keyname_modifier]}-#{@options[:timestamp].strftime("%F_%H_%M_%S_%N")}" end # Returns the local user running this tool # # @return [String] username of local user # @api private def local_user ENV['USER'] end # Creates the KeyPair for this test run # # @param region [Aws::EC2::Region] region to create the key pair in # @return [Aws::EC2::KeyPair] created key_pair # @api private def ensure_key_pair(region) pair_name = key_name() delete_key_pair(region, pair_name) create_new_key_pair(region, pair_name) end # Deletes key pairs from all regions # # @param [String] keypair_name_filter if given, will get all keypairs that match # a simple {::String#start_with?} filter. If no filter is given, the basic key # name returned by {#key_name} will be used. # # @return nil # @api private def delete_key_pair_all_regions(keypair_name_filter=nil) region_keypairs_hash = my_key_pairs(keypair_name_filter) region_keypairs_hash.each_pair do |region, keypair_name_array| keypair_name_array.each do |keypair_name| delete_key_pair(region, keypair_name) end end end # Gets the Beaker user's keypairs by region # # @param [String] name_filter if given, will get all keypairs that match # a simple {::String#start_with?} filter. If no filter is given, the basic key # name returned by {#key_name} will be used. # # @return [Hash{String=>Array[String]}] a hash of region name to # an array of the keypair names that match for the filter # @api private def my_key_pairs(name_filter=nil) keypairs_by_region = {} key_name_filter = name_filter ? "#{name_filter}-*" : key_name regions.each do |region| keypairs_by_region[region] = client(region).describe_key_pairs( :filters => [{ :name => 'key-name', :values => [key_name_filter] }] ).key_pairs.map(&:key_name) end keypairs_by_region end # Deletes a given key pair # # @param [Aws::EC2::Region] region the region the key belongs to # @param [String] pair_name the name of the key to be deleted # # @api private def delete_key_pair(region, pair_name) kp = client(region).describe_key_pairs(:key_names => [pair_name]).key_pairs.first unless kp.nil? @logger.debug("aws-sdk: delete key pair in region: #{region}") client(region).delete_key_pair(:key_name => pair_name) end rescue Aws::EC2::Errors::InvalidKeyPairNotFound nil end # Create a new key pair for a given Beaker run # # @param [Aws::EC2::Region] region the region the key pair will be imported into # @param [String] pair_name the name of the key to be created # # @return [Aws::EC2::KeyPair] key pair created # @raise [RuntimeError] raised if AWS keypair not created def create_new_key_pair(region, pair_name) @logger.debug("aws-sdk: importing new key pair: #{pair_name}") client(region).import_key_pair(:key_name => pair_name, :public_key_material => public_key) begin client(region).wait_until(:key_pair_exists, { :key_names => [pair_name] }, :max_attempts => 5, :delay => 2) rescue Aws::Waiters::Errors::WaiterFailed raise RuntimeError, "AWS key pair #{pair_name} can not be queried, even after import" end end # Return a reproducable security group identifier based on input ports # # @param ports [Array<Number>] array of port numbers # @return [String] group identifier # @api private def group_id(ports) if ports.nil? or ports.empty? raise ArgumentError, "Ports list cannot be nil or empty" end unless ports.is_a? Set ports = Set.new(ports) end # Lolwut, #hash is inconsistent between ruby processes "Beaker-#{Zlib.crc32(ports.inspect)}" end # Return an existing group, or create new one # # Accepts a VPC as input for checking & creation. # # @param vpc [Aws::EC2::VPC] the AWS vpc control object # @param sg_cidr_ips [Array<String>] CIDRs used for outbound security group rule # @return [Aws::EC2::SecurityGroup] created security group # @api private def ensure_ping_group(vpc, sg_cidr_ips = ['0.0.0.0/0']) @logger.notify("aws-sdk: Ensure security group exists that enables ping, create if not") group = client.describe_security_groups( :filters => [ { :name => 'group-name', :values => [PING_SECURITY_GROUP_NAME] }, { :name => 'vpc-id', :values => [vpc.vpc_id] }, ] ).security_groups.first if group.nil? group = create_ping_group(vpc, sg_cidr_ips) end group end # Return an existing group, or create new one # # Accepts a VPC as input for checking & creation. # # @param vpc [Aws::EC2::VPC] the AWS vpc control object # @param ports [Array<Number>] an array of port numbers # @param sg_cidr_ips [Array<String>] CIDRs used for outbound security group rule # @return [Aws::EC2::SecurityGroup] created security group # @api private def ensure_group(vpc, ports, sg_cidr_ips = ['0.0.0.0/0']) @logger.notify("aws-sdk: Ensure security group exists for ports #{ports.to_s}, create if not") name = group_id(ports) group = client.describe_security_groups( :filters => [ { :name => 'group-name', :values => [name] }, { :name => 'vpc-id', :values => [vpc.vpc_id] }, ] ).security_groups.first if group.nil? group = create_group(vpc, ports, sg_cidr_ips) end group end # Create a new ping enabled security group # # Accepts a region or VPC for group creation. # # @param region_or_vpc [Aws::EC2::Region, Aws::EC2::VPC] the AWS region or vpc control object # @param sg_cidr_ips [Array<String>] CIDRs used for outbound security group rule # @return [Aws::EC2::SecurityGroup] created security group # @api private def create_ping_group(region_or_vpc, sg_cidr_ips = ['0.0.0.0/0']) @logger.notify("aws-sdk: Creating group #{PING_SECURITY_GROUP_NAME}") cl = region_or_vpc.is_a?(String) ? client(region_or_vpc) : client params = { :description => 'Custom Beaker security group to enable ping', :group_name => PING_SECURITY_GROUP_NAME, } params[:vpc_id] = region_or_vpc.vpc_id if region_or_vpc.is_a?(Aws::EC2::Types::Vpc) group = cl.create_security_group(params) sg_cidr_ips.each do |cidr_ip| add_ingress_rule( cl, group, cidr_ip, '8', # 8 == ICMPv4 ECHO request '-1', # -1 == All ICMP codes 'icmp', ) end group end # Create a new security group # # Accepts a region or VPC for group creation. # # @param region_or_vpc [Aws::EC2::Region, Aws::EC2::VPC] the AWS region or vpc control object # @param ports [Array<Number>] an array of port numbers # @param sg_cidr_ips [Array<String>] CIDRs used for outbound security group rule # @return [Aws::EC2::SecurityGroup] created security group # @api private # Authorizes connections from certain CIDR to a range of ports # # @param cl [Aws::EC2::Client] # @param sg_group [Aws::EC2::SecurityGroup] the AWS security group # @param cidr_ip [String] CIDR used for outbound security group rule # @param from_port [String] Starting Port number in the range # @param to_port [String] Ending Port number in the range # @return [void] # @api private def add_ingress_rule(cl, sg_group, cidr_ip, from_port, to_port, protocol = 'tcp') cl.authorize_security_group_ingress( :cidr_ip => cidr_ip, :ip_protocol => protocol, :from_port => from_port, :to_port => to_port, :group_id => sg_group.group_id, ) end # Return a hash containing AWS credentials # # @return [Hash<Symbol, String>] AWS credentials # @api private def load_credentials return load_env_credentials if load_env_credentials.set? load_fog_credentials(@options[:dot_fog]) end # Return AWS credentials loaded from environment variables # # @param prefix [String] environment variable prefix # @return [Aws::Credentials] ec2 credentials # @api private def load_env_credentials(prefix='AWS') Aws::Credentials.new( ENV["#{prefix}_ACCESS_KEY_ID"], ENV["#{prefix}_SECRET_ACCESS_KEY"], ENV["#{prefix}_SESSION_TOKEN"] ) end # Return a hash containing the fog credentials for EC2 # # @param dot_fog [String] dot fog path # @return [Aws::Credentials] ec2 credentials # @api private def load_fog_credentials(dot_fog = '.fog') default = get_fog_credentials(dot_fog) raise "You must specify an aws_access_key_id in your .fog file (#{dot_fog}) for ec2 instances!" unless default[:aws_access_key_id] raise "You must specify an aws_secret_access_key in your .fog file (#{dot_fog}) for ec2 instances!" unless default[:aws_secret_access_key] Aws::Credentials.new( default[:aws_access_key_id], default[:aws_secret_access_key], default[:aws_session_token] ) end # Adds port 8143 to host[:additional_ports] # if master, database and dashboard are not on same instance def test_split_install @hosts.each do |host| mono_roles = ['master', 'database', 'dashboard'] roles_intersection = host[:roles] & mono_roles if roles_intersection.size != 3 && roles_intersection.any? host[:additional_ports] ? host[:additional_ports].push(8143) : host[:additional_ports] = [8143] end end end end
phatworx/rails_paginate
lib/rails_paginate/renderers/base.rb
RailsPaginate::Renderers.Base.link_to_page
ruby
def link_to_page(page, key, link_options = {}) css_class = "#{link_options[:class]} #{page == current_page ? 'current' : ''}" if key.nil? content_tag :span, "..", :class => "spacer" elsif page.nil? content_tag :span, t(key), :class => "#{css_class} unavailable" else link_to t(key, :page => page), url_for_page(page), :class => css_class, :alt => view.strip_tags(t(key, :page => page)), :remote => options[:remote], :method => options[:method] end end
link to page with i18n support
train
https://github.com/phatworx/rails_paginate/blob/ae8cbc12030853b236dc2cbf6ede8700fb835771/lib/rails_paginate/renderers/base.rb#L30-L39
class Base attr_reader :view, :collection, :options, :pager # setup rails_paginate collection def initialize(view, collection, pager, options = {}) raise ArgumentError, "first argument must be a RailsPaginate::Collection" unless collection.is_a? RailsPaginate::Collection raise ArgumentError, "second argument must be a Hash" unless options.is_a? Hash raise ArgumentError, "third argument must be an instance of RailsPaginate::Pagers::Base" unless pager.is_a? RailsPaginate::Pagers::Base @options = options @collection = collection @view = view @pager = pager end # build url def url_for_page(page) view.url_for(view.default_url_options.merge({page_param.to_sym => page}).merge(options[:params] || {})) end # abstrack renderer def render raise StandardError, "render is not implemented" end protected # link to page with i18n support # def page_param options[:page_param] || RailsPaginate.page_param end # helper def current_page collection.current_page end # map to view helper def content_tag(*args, &block) view.content_tag(*args, &block) end # map to view helper def link_to(*args, &block) view.link_to(*args, &block) end # map to view helper def t(*args) view.t(*args) end end
cookpad/rrrspec
rrrspec-client/lib/rrrspec/redis_models.rb
RRRSpec.WorkerLog.to_h
ruby
def to_h h = RRRSpec.redis.hgetall(key) h['key'] = key h['log'] = log h['worker'] = { 'key' => h['worker'] } h['taskset'] = { 'key' => h['taskset'] } RRRSpec.convert_if_present(h, 'started_at') { |v| Time.zone.parse(v) } RRRSpec.convert_if_present(h, 'rsync_finished_at') { |v| Time.zone.parse(v) } RRRSpec.convert_if_present(h, 'setup_finished_at') { |v| Time.zone.parse(v) } RRRSpec.convert_if_present(h, 'finished_at') { |v| Time.zone.parse(v) } h end
========================================================================== Serialize
train
https://github.com/cookpad/rrrspec/blob/a5bde2b062ce68b1e32b8caddf194389c2ce28b0/rrrspec-client/lib/rrrspec/redis_models.rb#L553-L564
class WorkerLog attr_reader :key def initialize(worker_log_key) @key = worker_log_key end # Public: Create a new worker_log. # This method will call Taskset#add_worker_log def self.create(worker, taskset) worker_log_key = RRRSpec.make_key(taskset.key, worker.key) RRRSpec.redis.hmset( worker_log_key, 'worker', worker.key, 'taskset', taskset.key, 'started_at', Time.zone.now.to_s, ) worker_log = new(worker_log_key) taskset.add_worker_log(worker_log) return worker_log end # ========================================================================== # Property # Public: Returns the started_at def started_at v = RRRSpec.redis.hget(key, 'started_at') v.present? ? Time.zone.parse(v) : nil end # ========================================================================== # Status # Public: Returns the rsync_finished_at def rsync_finished_at v = RRRSpec.redis.hget(key, 'rsync_finished_at') v.present? ? Time.zone.parse(v) : nil end # Public: Set rsync_finished_at time def set_rsync_finished_time RRRSpec.redis.hset(key, 'rsync_finished_at', Time.zone.now.to_s) end # Public: Returns the setup_finished_at def setup_finished_at v = RRRSpec.redis.hget(key, 'setup_finished_at') v.present? ? Time.zone.parse(v) : nil end # Public: Set setup_finished_at time def set_setup_finished_time RRRSpec.redis.hset(key, 'setup_finished_at', Time.zone.now.to_s) end # Public: Returns the finished_at def finished_at v = RRRSpec.redis.hget(key, 'finished_at') v.present? ? Time.zone.parse(v) : nil end # Public: Set finished_at time if it is empty def set_finished_time RRRSpec.redis.hsetnx(key, 'finished_at', Time.zone.now.to_s) end # Public: Logs happend in worker def log RRRSpec.redis.get(RRRSpec.make_key(key, 'log')) || "" end # Public: Append a line to the log def append_log(string) RRRSpec.redis.append(RRRSpec.make_key(key, 'log'), string) end # ========================================================================== # Serialize def to_json(options=nil) to_h.to_json(options) end # ========================================================================== # Persistence def expire(sec) RRRSpec.redis.expire(key, sec) RRRSpec.redis.expire(RRRSpec.make_key(key, 'log'), sec) end end
PeterCamilleri/pause_output
lib/pause_output/output_pager.rb
PauseOutput.OutputPager.write_str
ruby
def write_str(str) loop do len = str.length if @chars + len < chars_per_line $pause_output_out.write(str) @chars += len return else tipping_point = chars_per_line - @chars $pause_output_out.write(str[0, tipping_point]) count_lines str = (str[tipping_point..-1]) end end end
Write out a simple string with no embedded new-lines.
train
https://github.com/PeterCamilleri/pause_output/blob/60bcf8e0f386543aba7f3274714d877168f7cf28/lib/pause_output/output_pager.rb#L34-L50
class OutputPager # Set up the initial values. def initialize(options={}) @options = options @lines = 0 @chars = 0 end # Write out a general string with page pauses. def write(str) while !str.empty? pre,mid,str = str.partition("\n") write_str(pre) unless pre.empty? writeln unless mid.empty? end end # Write out an object as a string. def <<(obj) write(obj.to_s) end private # Write out a simple string with no embedded new-lines. # Write out a new-line. def writeln $pause_output_out.write("\n") count_lines end # A new line is out, count it! def count_lines @chars = 0 @lines += 1 if @lines >= (lines_per_page - 1) case pause.downcase when " " @lines -= 1 when "q" @lines = 0 raise PauseOutputStop else @lines = 0 end end end # Pause waiting for the user. def pause msg = pause_message $pause_output_out.write(msg) MiniTerm.raw do |term| result = term.get_raw_char term.flush result end ensure $pause_output_out.write("\r" + " " * msg.length + "\r") end # How many lines fit on a page? def lines_per_page result = @options[:page_height].to_i result = MiniTerm.height if result < 2 result end # How many characters fit on a line? def chars_per_line result = @options[:page_width].to_i result = MiniTerm.width if result < 20 result end # Get the text of the pause message. def pause_message @options.key?(:page_msg) ? @options[:page_msg] : "Press enter, space or q:" end end
oleganza/btcruby
lib/btcruby/open_assets/asset_transaction_builder.rb
BTC.AssetTransactionBuilder.validate_bitcoin_change_address!
ruby
def validate_bitcoin_change_address! addr = self.bitcoin_change_address raise ArgumentError, "Missing bitcoin_change_address" if !addr raise ArgumentError, "bitcoin_change_address must be an instance of BTC::Address" if !addr.is_a?(Address) raise ArgumentError, "bitcoin_change_address must not be an instance of BTC::AssetAddress" if addr.is_a?(AssetAddress) end
Validation Methods
train
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/open_assets/asset_transaction_builder.rb#L379-L384
class AssetTransactionBuilder # Network to validate provided addresses against. # Default value is `Network.default`. attr_accessor :network # Must be a subclass of a BTC::BitcoinPaymentAddress attr_accessor :bitcoin_change_address # Must be a subclass of a BTC::AssetAddress attr_accessor :asset_change_address # Enumerable yielding BTC::TransactionOutput instances with valid `transaction_hash` and `index` properties. # If not specified, `bitcoin_unspent_outputs_provider` is used if possible. attr_accessor :bitcoin_unspent_outputs # Enumerable yielding BTC::AssetTransactionOutput instances with valid `transaction_hash` and `index` properties. attr_accessor :asset_unspent_outputs # Provider of the pure bitcoin unspent outputs adopting TransactionBuilder::Provider. # If not specified, `bitcoin_unspent_outputs` must be provided. attr_accessor :bitcoin_provider # Provider of the pure bitcoin unspent outputs adopting AssetTransactionBuilder::Provider. # If not specified, `asset_unspent_outputs` must be provided. attr_accessor :asset_provider # TransactionBuilder::Signer for all the inputs (bitcoins and assets). # If not provided, inputs will be left unsigned and `result.unsigned_input_indexes` will contain indexes of these inputs. attr_accessor :signer # Miner's fee per kilobyte (1000 bytes). # Default is Transaction::DEFAULT_FEE_RATE attr_accessor :fee_rate # Metadata to embed in the marker output. Default is nil (empty string). attr_accessor :metadata def initialize end def asset_unspent_outputs=(unspents) self.asset_provider = Provider.new{|atxbuilder| unspents } end # Adds an issuance of some assets. # If `script` is specified, it is used to create an intermediate base transaction. # If `output` is specified, it must be a valid spendable output with `transaction_id` and `index`. # It can be regular TransactionOutput or verified AssetTransactionOutput. # `amount` must be > 0 - number of units to be issued def issue_asset(source_script: nil, source_output: nil, amount: nil, script: nil, address: nil) raise ArgumentError, "Either `source_script` or `source_output` must be specified" if !source_script && !source_output raise ArgumentError, "Both `source_script` and `source_output` cannot be specified" if source_script && source_output raise ArgumentError, "Either `script` or `address` must be specified" if !script && !address raise ArgumentError, "Both `script` and `address` cannot be specified" if script && address raise ArgumentError, "Amount must be greater than zero" if !amount || amount <= 0 if source_output && (!source_output.index || !source_output.transaction_hash) raise ArgumentError, "If `source_output` is specified, it must have valid `transaction_hash` and `index` attributes" end script ||= AssetAddress.parse(address).script # Ensure source output is a verified asset output. if source_output if source_output.is_a?(AssetTransactionOutput) raise ArgumentError, "Must be verified asset output to spend" if !source_output.verified? else source_output = AssetTransactionOutput.new(transaction_output: source_output, verified: true) end end # Set either the script or output only once. # All the remaining issuances must use the same script or output. if !self.issuing_asset_script && !self.issuing_asset_output self.issuing_asset_script = source_script self.issuing_asset_output = source_output else if self.issuing_asset_script != source_script || self.issuing_asset_output != source_output raise ArgumentError, "Can't issue more assets from a different source script or source output" end end self.issued_assets << {amount: amount, script: script} end # Adds a transfer output. # May override per-builder unspents/provider/change address to allow multi-user swaps. def transfer_asset(asset_id: nil, amount: nil, script: nil, address: nil, provider: nil, unspent_outputs: nil, change_address: nil) raise ArgumentError, "AssetID must be provided" if !asset_id raise ArgumentError, "Either `script` or `address` must be specified" if !script && !address raise ArgumentError, "Both `script` and `address` cannot be specified" if script && address raise ArgumentError, "Amount must be greater than zero" if !amount || amount <= 0 provider = Provider.new{|atxbuilder| unspent_outputs } if unspent_outputs change_address = AssetAddress.parse(change_address) if change_address asset_id = AssetID.parse(asset_id) script ||= AssetAddress.parse(address).script self.transferred_assets << {asset_id: asset_id, amount: amount, script: script, provider: provider, change_address: change_address} end # Adds a normal payment output. Typically used for transfer def send_bitcoin(output: nil, amount: nil, script: nil, address: nil) if !output raise ArgumentError, "Either `script` or `address` must be specified" if !script && !address raise ArgumentError, "Amount must be specified (>= 0)" if (!amount || amount < 0) script ||= address.public_address.script if address output = TransactionOutput.new(value: amount, script: script) end self.bitcoin_outputs << output end def bitcoin_change_address=(addr) @bitcoin_change_address = BitcoinPaymentAddress.parse(addr) end def asset_change_address=(addr) @asset_change_address = AssetAddress.parse(addr) end def build validate_bitcoin_change_address! validate_asset_change_address! result = Result.new # We don't count assets_cost because outputs of these txs # will be consumed in the next transaction. Only add the fees. if self.issuing_asset_script issuing_tx, unsigned_input_indexes = make_transaction_for_issues result.fee = issuing_tx.fee result.transactions << issuing_tx result.unsigned_input_indexes << unsigned_input_indexes self.issuing_asset_output = AssetTransactionOutput.new(transaction_output: issuing_tx.outputs.first, verified: true) end # Prepare the target transaction txbuilder = make_transaction_builder if result.transactions.size > 0 txbuilder.parent_transactions = [result.transactions.last] end txbuilder.prepended_unspent_outputs ||= [] txbuilder.outputs = [] # Add issuance input and outputs first. consumed_asset_outputs = [] # used in inputs issue_outputs = [] transfer_outputs = [] if self.issued_assets.size > 0 txbuilder.prepended_unspent_outputs << self.issuing_asset_output.transaction_output self.issued_assets.each do |issue| atxo = make_asset_transaction_output(asset_id: issuing_asset_id, amount: issue[:amount], script: issue[:script]) issue_outputs << atxo end end # Move all transfers of the asset ID used on the issuing output to the top of the list. asset_id_on_the_issuing_input = self.issuing_asset_output ? self.issuing_asset_output.asset_id : nil if asset_id_on_the_issuing_input aid = asset_id_on_the_issuing_input.to_s self.transferred_assets = self.transferred_assets.sort do |a,b| # move the asset id used in the issue input to the top if a[:asset_id].to_s == aid -1 elsif b[:asset_id] == aid 1 else 0 # keep the order end end end consumed_outpoints = {} # "txid:index" => true self.transferred_assets.each do |transfer| # |aid,transfers| asset_id = transfer[:asset_id] transfers = [transfer] amount_required = 0 amount_provided = 0 if asset_id_on_the_issuing_input.to_s == asset_id.to_s amount_provided = self.issuing_asset_output.value end atxo = make_asset_transaction_output(asset_id: transfer[:asset_id], amount: transfer[:amount], script: transfer[:script]) amount_required += atxo.value transfer_outputs << atxo # Fill in enough unspent assets for this asset_id. # Use per-transfer provider if it's specified. Otherwise use global provider. provider = transfer[:provider] || self.asset_provider unspents = provider.asset_unspent_outputs(asset_id: asset_id, amount: amount_required).dup while amount_provided < amount_required autxo = unspents.shift if !autxo raise InsufficientFundsError, "Not enough outputs for asset #{asset_id.to_s} (#{amount_provided} available < #{amount_required} required)" end if !consumed_outpoints[oid = autxo.transaction_output.outpoint_id] # Only apply outputs with matching asset ids. if autxo.asset_id == asset_id raise ArgumentError, "Must be verified asset outputs to spend" if !autxo.verified? consumed_outpoints[oid] = true amount_provided += autxo.value consumed_asset_outputs << autxo txbuilder.prepended_unspent_outputs << autxo.transaction_output end end end # If the difference is > 0, add a change output change = amount_provided - amount_required if change > 0 # Use per-transfer change address if it's specified. Otherwise use global change address. change_addr = transfer[:change_address] || self.asset_change_address atxo = make_asset_transaction_output(asset_id: asset_id, amount: change, script: change_addr.script) transfer_outputs << atxo end end # each transfer # If we have an asset on the issuance input and it is never used in any transfer, # then we need to create a change output just for it. if asset_id_on_the_issuing_input && self.issuing_asset_output.value > 0 if !self.transferred_assets.map{|dict| dict[:asset_id].to_s }.uniq.include?(asset_id_on_the_issuing_input.to_s) atxo = make_asset_transaction_output(asset_id: self.issuing_asset_output.asset_id, amount: self.issuing_asset_output.value, script: self.asset_change_address.script) transfer_outputs << atxo end end all_asset_outputs = (issue_outputs + transfer_outputs) result.assets_cost = all_asset_outputs.inject(0){|sum, atxo| sum + atxo.transaction_output.value } marker = AssetMarker.new(quantities: all_asset_outputs.map{|atxo| atxo.value }, metadata: self.metadata) # Now, add underlying issues, marker and transfer outputs issue_outputs.each do |atxo| txbuilder.outputs << atxo.transaction_output end txbuilder.outputs << marker.output transfer_outputs.each do |atxo| txbuilder.outputs << atxo.transaction_output end txresult = txbuilder.build tx = txresult.transaction atx = AssetTransaction.new(transaction: tx) BTC::Invariant(atx.outputs.size == all_asset_outputs.size + 1 + (txresult.change_amount > 0 ? 1 : 0), "Must have all asset outputs (with marker output and optional change output)"); if txresult.change_amount > 0 plain_change_output = atx.outputs.last BTC::Invariant(!plain_change_output.verified?, "Must have plain change output not verified"); BTC::Invariant(!plain_change_output.asset_id, "Must have plain change output not have asset id"); BTC::Invariant(!plain_change_output.value, "Must have plain change output not have asset amount"); plain_change_output.verified = true # to match the rest of outputs. end # Provide color info for each input consumed_asset_outputs.each_with_index do |atxo, i| atx.inputs[i].asset_id = atxo.asset_id atx.inputs[i].value = atxo.value atx.inputs[i].verified = true end atx.inputs[consumed_asset_outputs.size..-1].each do |input| input.asset_id = nil input.value = nil input.verified = true end # Provide color info for each output issue_outputs.each_with_index do |aout1, i| aout = atx.outputs[i] aout.asset_id = aout1.asset_id aout.value = aout1.value aout.verified = true end atx.outputs[issue_outputs.size].verified = true # make marker verified offset = 1 + issue_outputs.size # +1 for marker transfer_outputs.each_with_index do |aout1, i| aout = atx.outputs[i + offset] aout.asset_id = aout1.asset_id aout.value = aout1.value aout.verified = true end offset = 1 + issue_outputs.size + transfer_outputs.size # +1 for marker atx.outputs[offset..-1].each do |aout| aout.asset_id = nil aout.value = nil aout.verified = true end if txresult.change_amount == 0 atx.outputs.each do |aout| if !aout.marker? BTC::Invariant(aout.verified?, "Must be verified"); BTC::Invariant(!!aout.asset_id, "Must have asset id"); BTC::Invariant(aout.value && aout.value > 0, "Must have some asset amount"); end end end result.unsigned_input_indexes << txresult.unsigned_input_indexes result.transactions << tx result.asset_transaction = atx result end # Helpers def issuing_asset_id @issuing_asset_id ||= AssetID.new(script: @issuing_asset_script || @issuing_asset_output.transaction_output.script) end def make_asset_transaction_output(asset_id: nil, amount: nil, script: nil) txout = make_output_for_asset_script(script) AssetTransactionOutput.new(transaction_output: txout, asset_id: asset_id, value: amount, verified: true) end def make_transaction_for_issues raise "Sanity check" if !self.issuing_asset_script txbuilder = make_transaction_builder txbuilder.outputs = [ make_output_for_asset_script(self.issuing_asset_script) ] result = txbuilder.build [result.transaction, result.unsigned_input_indexes] end def make_output_for_asset_script(script) txout = BTC::TransactionOutput.new(value: MAX_MONEY, script: script) txout.value = txout.dust_limit raise RuntimeError, "Sanity check: txout value must not be zero" if txout.value <= 0 txout end def make_transaction_builder txbuilder = TransactionBuilder.new txbuilder.change_address = self.bitcoin_change_address txbuilder.signer = self.signer txbuilder.provider = self.internal_bitcoin_provider txbuilder.unspent_outputs = self.bitcoin_unspent_outputs txbuilder.fee_rate = self.fee_rate txbuilder end def internal_bitcoin_provider @internal_bitcoin_provider ||= (self.bitcoin_provider || TransactionBuilder::Provider.new{|txb| []}) end # Validation Methods def validate_asset_change_address! self.transferred_assets.each do |dict| addr = dict[:change_address] || self.asset_change_address raise ArgumentError, "Missing asset_change_address" if !addr raise ArgumentError, "asset_change_address must be an instance of BTC::AssetAddress" if !addr.is_a?(AssetAddress) end end protected attr_accessor :issuing_asset_script attr_accessor :issuing_asset_output attr_accessor :issued_assets attr_accessor :transferred_assets attr_accessor :bitcoin_outputs def issued_assets @issued_assets ||= [] end def transferred_assets @transferred_assets ||= [] end def bitcoin_outputs @bitcoin_outputs ||= [] end end
metanorma/isodoc
lib/isodoc/function/i18n.rb
IsoDoc::Function.I18n.eref_localities1_zh
ruby
def eref_localities1_zh(target, type, from, to) ret = ", 第#{from.text}" if from ret += "&ndash;#{to}" if to loc = (@locality[type] || type.sub(/^locality:/, "").capitalize ) ret += " #{loc}" ret end
TODO: move to localization file
train
https://github.com/metanorma/isodoc/blob/b8b51a28f9aecb7ce3ec1028317e94d0d623036a/lib/isodoc/function/i18n.rb#L79-L85
module I18n def load_yaml(lang, script) if @i18nyaml then YAML.load_file(@i18nyaml) elsif lang == "en" YAML.load_file(File.join(File.dirname(__FILE__), "../../isodoc-yaml/i18n-en.yaml")) elsif lang == "fr" YAML.load_file(File.join(File.dirname(__FILE__), "../../isodoc-yaml/i18n-fr.yaml")) elsif lang == "zh" && script == "Hans" YAML.load_file(File.join(File.dirname(__FILE__), "../../isodoc-yaml/i18n-zh-Hans.yaml")) else YAML.load_file(File.join(File.dirname(__FILE__), "../../isodoc-yaml/i18n-en.yaml")) end end def i18n_init(lang, script) @lang = lang @script = script y = load_yaml(lang, script) @term_def_boilerplate = y["term_def_boilerplate"] @scope_lbl = y["scope"] @symbols_lbl = y["symbols"] @table_of_contents_lbl = y["table_of_contents"] @introduction_lbl = y["introduction"] @foreword_lbl = y["foreword"] @abstract_lbl = y["abstract"] @termsdef_lbl = y["termsdef"] @termsdefsymbols_lbl = y["termsdefsymbols"] @normref_lbl = y["normref"] @bibliography_lbl = y["bibliography"] @clause_lbl = y["clause"] @annex_lbl = y["annex"] @appendix_lbl = y["appendix"] @no_terms_boilerplate = y["no_terms_boilerplate"] @internal_terms_boilerplate = y["internal_terms_boilerplate"] @norm_with_refs_pref = y["norm_with_refs_pref"] @norm_empty_pref = y["norm_empty_pref"] @external_terms_boilerplate = y["external_terms_boilerplate"] @internal_external_terms_boilerplate = y["internal_external_terms_boilerplate"] @note_lbl = y["note"] @note_xref_lbl = y["note_xref"] @termnote_lbl = y["termnote"] @figure_lbl = y["figure"] @list_lbl = y["list"] @formula_lbl = y["formula"] @table_lbl = y["table"] @key_lbl = y["key"] @example_lbl = y["example"] @example_xref_lbl = y["example_xref"] @where_lbl = y["where"] @wholeoftext_lbl = y["wholeoftext"] @draft_lbl = y["draft_label"] @inform_annex_lbl = y["inform_annex"] @norm_annex_lbl = y["norm_annex"] @modified_lbl = y["modified"] @deprecated_lbl = y["deprecated"] @source_lbl = y["source"] @and_lbl = y["and"] @all_parts_lbl = y["all_parts"] @permission_lbl = y["permission"] @recommendation_lbl = y["recommendation"] @requirement_lbl = y["requirement"] @locality = y["locality"] @admonition = y["admonition"] @labels = y @labels["language"] = @lang @labels["script"] = @script end # TODO: move to localization file # TODO: move to localization file def eref_localities1(target, type, from, to, lang = "en") return l10n(eref_localities1_zh(target, type, from, to)) if lang == "zh" ret = "," loc = @locality[type] || type.sub(/^locality:/, "").capitalize ret += " #{loc}" ret += " #{from.text}" if from ret += "&ndash;#{to.text}" if to l10n(ret) end # TODO: move to localization file # function localising spaces and punctuation. # Not clear if period needs to be localised for zh def l10n(x, lang = @lang, script = @script) if lang == "zh" && script == "Hans" x.gsub(/ /, "").gsub(/:/, ":").gsub(/,/, "、"). gsub(/\(/, "(").gsub(/\)/, ")"). gsub(/\[/, "【").gsub(/\]/, "】"). gsub(/<b>/, "").gsub("</b>", "") else x end end module_function :l10n end
ynab/ynab-sdk-ruby
lib/ynab/models/account.rb
YNAB.Account.valid?
ruby
def valid? return false if @id.nil? return false if @name.nil? return false if @type.nil? type_validator = EnumAttributeValidator.new('String', ['checking', 'savings', 'cash', 'creditCard', 'lineOfCredit', 'otherAsset', 'otherLiability', 'payPal', 'merchantAccount', 'investmentAccount', 'mortgage']) return false unless type_validator.valid?(@type) return false if @on_budget.nil? return false if @closed.nil? return false if @note.nil? return false if @balance.nil? return false if @cleared_balance.nil? return false if @uncleared_balance.nil? return false if @transfer_payee_id.nil? return false if @deleted.nil? true end
Check to see if the all the properties in the model are valid @return true if the model is valid
train
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/models/account.rb#L209-L224
class Account attr_accessor :id attr_accessor :name # The type of account. Note: payPal, merchantAccount, investmentAccount, and mortgage types have been deprecated and will be removed in the future. attr_accessor :type # Whether this account is on budget or not attr_accessor :on_budget # Whether this account is closed or not attr_accessor :closed attr_accessor :note # The current balance of the account in milliunits format attr_accessor :balance # The current cleared balance of the account in milliunits format attr_accessor :cleared_balance # The current uncleared balance of the account in milliunits format attr_accessor :uncleared_balance # The payee id which should be used when transferring to this account attr_accessor :transfer_payee_id # Whether or not the account has been deleted. Deleted accounts will only be included in delta requests. attr_accessor :deleted class EnumAttributeValidator attr_reader :datatype attr_reader :allowable_values def initialize(datatype, allowable_values) @allowable_values = allowable_values.map do |value| case datatype.to_s when /Integer/i value.to_i when /Float/i value.to_f else value end end end def valid?(value) !value || allowable_values.include?(value) end end # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'id' => :'id', :'name' => :'name', :'type' => :'type', :'on_budget' => :'on_budget', :'closed' => :'closed', :'note' => :'note', :'balance' => :'balance', :'cleared_balance' => :'cleared_balance', :'uncleared_balance' => :'uncleared_balance', :'transfer_payee_id' => :'transfer_payee_id', :'deleted' => :'deleted' } end # Attribute type mapping. def self.swagger_types { :'id' => :'String', :'name' => :'String', :'type' => :'String', :'on_budget' => :'BOOLEAN', :'closed' => :'BOOLEAN', :'note' => :'String', :'balance' => :'Integer', :'cleared_balance' => :'Integer', :'uncleared_balance' => :'Integer', :'transfer_payee_id' => :'String', :'deleted' => :'BOOLEAN' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } if attributes.has_key?(:'id') self.id = attributes[:'id'] end if attributes.has_key?(:'name') self.name = attributes[:'name'] end if attributes.has_key?(:'type') self.type = attributes[:'type'] end if attributes.has_key?(:'on_budget') self.on_budget = attributes[:'on_budget'] end if attributes.has_key?(:'closed') self.closed = attributes[:'closed'] end if attributes.has_key?(:'note') self.note = attributes[:'note'] end if attributes.has_key?(:'balance') self.balance = attributes[:'balance'] end if attributes.has_key?(:'cleared_balance') self.cleared_balance = attributes[:'cleared_balance'] end if attributes.has_key?(:'uncleared_balance') self.uncleared_balance = attributes[:'uncleared_balance'] end if attributes.has_key?(:'transfer_payee_id') self.transfer_payee_id = attributes[:'transfer_payee_id'] end if attributes.has_key?(:'deleted') self.deleted = attributes[:'deleted'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new if @id.nil? invalid_properties.push('invalid value for "id", id cannot be nil.') end if @name.nil? invalid_properties.push('invalid value for "name", name cannot be nil.') end if @type.nil? invalid_properties.push('invalid value for "type", type cannot be nil.') end if @on_budget.nil? invalid_properties.push('invalid value for "on_budget", on_budget cannot be nil.') end if @closed.nil? invalid_properties.push('invalid value for "closed", closed cannot be nil.') end if @note.nil? invalid_properties.push('invalid value for "note", note cannot be nil.') end if @balance.nil? invalid_properties.push('invalid value for "balance", balance cannot be nil.') end if @cleared_balance.nil? invalid_properties.push('invalid value for "cleared_balance", cleared_balance cannot be nil.') end if @uncleared_balance.nil? invalid_properties.push('invalid value for "uncleared_balance", uncleared_balance cannot be nil.') end if @transfer_payee_id.nil? invalid_properties.push('invalid value for "transfer_payee_id", transfer_payee_id cannot be nil.') end if @deleted.nil? invalid_properties.push('invalid value for "deleted", deleted cannot be nil.') end invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid # Custom attribute writer method checking allowed values (enum). # @param [Object] type Object to be assigned def type=(type) validator = EnumAttributeValidator.new('String', ['checking', 'savings', 'cash', 'creditCard', 'lineOfCredit', 'otherAsset', 'otherLiability', 'payPal', 'merchantAccount', 'investmentAccount', 'mortgage']) unless validator.valid?(type) fail ArgumentError, 'invalid value for "type", must be one of #{validator.allowable_values}.' end @type = type end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && id == o.id && name == o.name && type == o.type && on_budget == o.on_budget && closed == o.closed && note == o.note && balance == o.balance && cleared_balance == o.cleared_balance && uncleared_balance == o.uncleared_balance && transfer_payee_id == o.transfer_payee_id && deleted == o.deleted end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [id, name, type, on_budget, closed, note, balance, cleared_balance, uncleared_balance, transfer_payee_id, deleted].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BOOLEAN if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model temp_model = YNAB.const_get(type).new temp_model.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.draw_total_items
ruby
def draw_total_items header_r.draw_total_items count: items.size, size: items.inject(0) {|sum, i| sum += i.size} end
Update the header information concerning total files and directories in the current directory.
train
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L616-L618
class Controller include Rfd::Commands attr_reader :header_l, :header_r, :main, :command_line, :items, :displayed_items, :current_row, :current_page, :current_dir, :current_zip # :nodoc: def initialize @main = MainWindow.new @header_l = HeaderLeftWindow.new @header_r = HeaderRightWindow.new @command_line = CommandLineWindow.new @debug = DebugWindow.new if ENV['DEBUG'] @direction, @dir_history, @last_command, @times, @yanked_items = nil, [], nil, nil, nil end # The main loop. def run loop do begin number_pressed = false ret = case (c = Curses.getch) when 10, 13 # enter, return enter when 27 # ESC q when ' ' # space space when 127 # DEL del when Curses::KEY_DOWN j when Curses::KEY_UP k when Curses::KEY_LEFT h when Curses::KEY_RIGHT l when Curses::KEY_CTRL_A..Curses::KEY_CTRL_Z chr = ((c - 1 + 65) ^ 0b0100000).chr public_send "ctrl_#{chr}" if respond_to?("ctrl_#{chr}") when ?0..?9 public_send c number_pressed = true when ?!..?~ if respond_to? c public_send c else debug "key: #{c}" if ENV['DEBUG'] end when Curses::KEY_MOUSE if (mouse_event = Curses.getmouse) case mouse_event.bstate when Curses::BUTTON1_CLICKED click y: mouse_event.y, x: mouse_event.x when Curses::BUTTON1_DOUBLE_CLICKED double_click y: mouse_event.y, x: mouse_event.x end end else debug "key: #{c}" if ENV['DEBUG'] end Curses.doupdate if ret @times = nil unless number_pressed rescue StopIteration raise rescue => e command_line.show_error e.to_s raise if ENV['DEBUG'] end end ensure Curses.close_screen end # Change the number of columns in the main window. def spawn_panes(num) main.number_of_panes = num @current_row = @current_page = 0 end # Number of times to repeat the next command. def times (@times || 1).to_i end # The file or directory on which the cursor is on. def current_item items[current_row] end # * marked files and directories. def marked_items items.select(&:marked?) end # Marked files and directories or Array(the current file or directory). # # . and .. will not be included. def selected_items ((m = marked_items).any? ? m : Array(current_item)).reject {|i| %w(. ..).include? i.name} end # Move the cursor to specified row. # # The main window and the headers will be updated reflecting the displayed files and directories. # The row number can be out of range of the current page. def move_cursor(row = nil) if row if (prev_item = items[current_row]) main.draw_item prev_item end page = row / max_items switch_page page if page != current_page main.activate_pane row / maxy @current_row = row else @current_row = 0 end item = items[current_row] main.draw_item item, current: true main.display current_page header_l.draw_current_file_info item @current_row end # Change the current directory. def cd(dir = '~', pushd: true) dir = load_item path: expand_path(dir) unless dir.is_a? Item unless dir.zip? Dir.chdir dir @current_zip = nil else @current_zip = dir end @dir_history << current_dir if current_dir && pushd @current_dir, @current_page, @current_row = dir, 0, nil main.activate_pane 0 ls @current_dir end # cd to the previous directory. def popd cd @dir_history.pop, pushd: false if @dir_history.any? end # Fetch files from current directory. # Then update each windows reflecting the newest information. def ls fetch_items_from_filesystem_or_zip sort_items_according_to_current_direction @current_page ||= 0 draw_items move_cursor (current_row ? [current_row, items.size - 1].min : nil) draw_marked_items draw_total_items true end # Sort the whole files and directories in the current directory, then refresh the screen. # # ==== Parameters # * +direction+ - Sort order in a String. # nil : order by name # r : reverse order by name # s, S : order by file size # sr, Sr: reverse order by file size # t : order by mtime # tr : reverse order by mtime # c : order by ctime # cr : reverse order by ctime # u : order by atime # ur : reverse order by atime # e : order by extname # er : reverse order by extname def sort(direction = nil) @direction, @current_page = direction, 0 sort_items_according_to_current_direction switch_page 0 move_cursor 0 end # Change the file permission of the selected files and directories. # # ==== Parameters # * +mode+ - Unix chmod string (e.g. +w, g-r, 755, 0644) def chmod(mode = nil) return unless mode begin Integer mode mode = Integer mode.size == 3 ? "0#{mode}" : mode rescue ArgumentError end FileUtils.chmod mode, selected_items.map(&:path) ls end # Change the file owner of the selected files and directories. # # ==== Parameters # * +user_and_group+ - user name and group name separated by : (e.g. alice, nobody:nobody, :admin) def chown(user_and_group) return unless user_and_group user, group = user_and_group.split(':').map {|s| s == '' ? nil : s} FileUtils.chown user, group, selected_items.map(&:path) ls end # Fetch files from current directory or current .zip file. def fetch_items_from_filesystem_or_zip unless in_zip? @items = Dir.foreach(current_dir).map {|fn| load_item dir: current_dir, name: fn }.to_a.partition {|i| %w(. ..).include? i.name}.flatten else @items = [load_item(dir: current_dir, name: '.', stat: File.stat(current_dir)), load_item(dir: current_dir, name: '..', stat: File.stat(File.dirname(current_dir)))] zf = Zip::File.new current_dir zf.each {|entry| next if entry.name_is_directory? stat = zf.file.stat entry.name @items << load_item(dir: current_dir, name: entry.name, stat: stat) } end end # Focus at the first file or directory of which name starts with the given String. def find(str) index = items.index {|i| i.index > current_row && i.name.start_with?(str)} || items.index {|i| i.name.start_with? str} move_cursor index if index end # Focus at the last file or directory of which name starts with the given String. def find_reverse(str) index = items.reverse.index {|i| i.index < current_row && i.name.start_with?(str)} || items.reverse.index {|i| i.name.start_with? str} move_cursor items.size - index - 1 if index end # Height of the currently active pane. def maxy main.maxy end # Number of files or directories that the current main window can show in a page. def max_items main.max_items end # Update the main window with the loaded files and directories. Also update the header. def draw_items main.newpad items @displayed_items = items[current_page * max_items, max_items] main.display current_page header_l.draw_path_and_page_number path: current_dir.path, current: current_page + 1, total: total_pages end # Sort the loaded files and directories in already given sort order. def sort_items_according_to_current_direction case @direction when nil @items = items.shift(2) + items.partition(&:directory?).flat_map(&:sort) when 'r' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort.reverse} when 'S', 's' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by {|i| -i.size}} when 'Sr', 'sr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:size)} when 't' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.mtime <=> x.mtime}} when 'tr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:mtime)} when 'c' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.ctime <=> x.ctime}} when 'cr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:ctime)} when 'u' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.atime <=> x.atime}} when 'ur' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:atime)} when 'e' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.extname <=> x.extname}} when 'er' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:extname)} end items.each.with_index {|item, index| item.index = index} end # Search files and directories from the current directory, and update the screen. # # * +pattern+ - Search pattern against file names in Ruby Regexp string. # # === Example # # a : Search files that contains the letter "a" in their file name # .*\.pdf$ : Search PDF files def grep(pattern = '.*') regexp = Regexp.new(pattern) fetch_items_from_filesystem_or_zip @items = items.shift(2) + items.select {|i| i.name =~ regexp} sort_items_according_to_current_direction draw_items draw_total_items switch_page 0 move_cursor 0 end # Copy selected files and directories to the destination. def cp(dest) unless in_zip? src = (m = marked_items).any? ? m.map(&:path) : current_item FileUtils.cp_r src, expand_path(dest) else raise 'cping multiple items in .zip is not supported.' if selected_items.size > 1 Zip::File.open(current_zip) do |zip| entry = zip.find_entry(selected_items.first.name).dup entry.name, entry.name_length = dest, dest.size zip.instance_variable_get(:@entry_set) << entry end end ls end # Move selected files and directories to the destination. def mv(dest) unless in_zip? src = (m = marked_items).any? ? m.map(&:path) : current_item FileUtils.mv src, expand_path(dest) else raise 'mving multiple items in .zip is not supported.' if selected_items.size > 1 rename "#{selected_items.first.name}/#{dest}" end ls end # Rename selected files and directories. # # ==== Parameters # * +pattern+ - new filename, or a shash separated Regexp like string def rename(pattern) from, to = pattern.sub(/^\//, '').sub(/\/$/, '').split '/' if to.nil? from, to = current_item.name, from else from = Regexp.new from end unless in_zip? selected_items.each do |item| name = item.name.gsub from, to FileUtils.mv item, current_dir.join(name) if item.name != name end else Zip::File.open(current_zip) do |zip| selected_items.each do |item| name = item.name.gsub from, to zip.rename item.name, name end end end ls end # Soft delete selected files and directories. # # If the OS is not OSX, performs the same as `delete` command. def trash unless in_zip? if osx? FileUtils.mv selected_items.map(&:path), File.expand_path('~/.Trash/') else #TODO support other OS FileUtils.rm_rf selected_items.map(&:path) end else return unless ask %Q[Trashing zip entries is not supported. Actually the files will be deleted. Are you sure want to proceed? (y/n)] delete end @current_row -= selected_items.count {|i| i.index <= current_row} ls end # Delete selected files and directories. def delete unless in_zip? FileUtils.rm_rf selected_items.map(&:path) else Zip::File.open(current_zip) do |zip| zip.select {|e| selected_items.map(&:name).include? e.to_s}.each do |entry| if entry.name_is_directory? zip.dir.delete entry.to_s else zip.file.delete entry.to_s end end end end @current_row -= selected_items.count {|i| i.index <= current_row} ls end # Create a new directory. def mkdir(dir) unless in_zip? FileUtils.mkdir_p current_dir.join(dir) else Zip::File.open(current_zip) do |zip| zip.dir.mkdir dir end end ls end # Create a new empty file. def touch(filename) unless in_zip? FileUtils.touch current_dir.join(filename) else Zip::File.open(current_zip) do |zip| # zip.file.open(filename, 'w') {|_f| } #HAXX this code creates an unneeded temporary file zip.instance_variable_get(:@entry_set) << Zip::Entry.new(current_zip, filename) end end ls end # Create a symlink to the current file or directory. def symlink(name) FileUtils.ln_s current_item, name ls end # Yank selected file / directory names. def yank @yanked_items = selected_items end # Paste yanked files / directories here. def paste if @yanked_items if current_item.directory? FileUtils.cp_r @yanked_items.map(&:path), current_item else @yanked_items.each do |item| if items.include? item i = 1 while i += 1 new_item = load_item dir: current_dir, name: "#{item.basename}_#{i}#{item.extname}", stat: item.stat break unless File.exist? new_item.path end FileUtils.cp_r item, new_item else FileUtils.cp_r item, current_dir end end end ls end end # Copy selected files and directories' path into clipboard on OSX. def clipboard IO.popen('pbcopy', 'w') {|f| f << selected_items.map(&:path).join(' ')} if osx? end # Archive selected files and directories into a .zip file. def zip(zipfile_name) return unless zipfile_name zipfile_name += '.zip' unless zipfile_name.end_with? '.zip' Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile| selected_items.each do |item| next if item.symlink? if item.directory? Dir[item.join('**/**')].each do |file| zipfile.add file.sub("#{current_dir}/", ''), file end else zipfile.add item.name, item end end end ls end # Unarchive .zip and .tar.gz files within selected files and directories into current_directory. def unarchive unless in_zip? zips, gzs = selected_items.partition(&:zip?).tap {|z, others| break [z, *others.partition(&:gz?)]} zips.each do |item| FileUtils.mkdir_p current_dir.join(item.basename) Zip::File.open(item) do |zip| zip.each do |entry| FileUtils.mkdir_p File.join(item.basename, File.dirname(entry.to_s)) zip.extract(entry, File.join(item.basename, entry.to_s)) { true } end end end gzs.each do |item| Zlib::GzipReader.open(item) do |gz| Gem::Package::TarReader.new(gz) do |tar| dest_dir = current_dir.join (gz.orig_name || item.basename).sub(/\.tar$/, '') tar.each do |entry| dest = nil if entry.full_name == '././@LongLink' dest = File.join dest_dir, entry.read.strip next end dest ||= File.join dest_dir, entry.full_name if entry.directory? FileUtils.mkdir_p dest, :mode => entry.header.mode elsif entry.file? FileUtils.mkdir_p dest_dir File.open(dest, 'wb') {|f| f.print entry.read} FileUtils.chmod entry.header.mode, dest elsif entry.header.typeflag == '2' # symlink File.symlink entry.header.linkname, dest end unless Dir.exist? dest_dir FileUtils.mkdir_p dest_dir File.open(File.join(dest_dir, gz.orig_name || item.basename), 'wb') {|f| f.print gz.read} end end end end end else Zip::File.open(current_zip) do |zip| zip.select {|e| selected_items.map(&:name).include? e.to_s}.each do |entry| FileUtils.mkdir_p File.join(current_zip.dir, current_zip.basename, File.dirname(entry.to_s)) zip.extract(entry, File.join(current_zip.dir, current_zip.basename, entry.to_s)) { true } end end end ls end # Current page is the first page? def first_page? current_page == 0 end # Do we have more pages? def last_page? current_page == total_pages - 1 end # Number of pages in the current directory. def total_pages (items.size - 1) / max_items + 1 end # Move to the given page number. # # ==== Parameters # * +page+ - Target page number def switch_page(page) main.display (@current_page = page) @displayed_items = items[current_page * max_items, max_items] header_l.draw_path_and_page_number path: current_dir.path, current: current_page + 1, total: total_pages end # Update the header information concerning currently marked files or directories. def draw_marked_items items = marked_items header_r.draw_marked_items count: items.size, size: items.inject(0) {|sum, i| sum += i.size} end # Update the header information concerning total files and directories in the current directory. # Swktch on / off marking on the current file or directory. def toggle_mark main.toggle_mark current_item end # Get a char as a String from user input. def get_char c = Curses.getch c if (0..255) === c.ord end def clear_command_line command_line.writeln 0, "" command_line.clear command_line.noutrefresh end # Accept user input, and directly execute it as a Ruby method call to the controller. # # ==== Parameters # * +preset_command+ - A command that would be displayed at the command line before user input. def process_command_line(preset_command: nil) prompt = preset_command ? ":#{preset_command} " : ':' command_line.set_prompt prompt cmd, *args = command_line.get_command(prompt: prompt).split(' ') if cmd && !cmd.empty? && respond_to?(cmd) ret = self.public_send cmd, *args clear_command_line ret end rescue Interrupt clear_command_line end # Accept user input, and directly execute it in an external shell. def process_shell_command command_line.set_prompt ':!' cmd = command_line.get_command(prompt: ':!')[1..-1] execute_external_command pause: true do system cmd end rescue Interrupt ensure command_line.clear command_line.noutrefresh end # Let the user answer y or n. # # ==== Parameters # * +prompt+ - Prompt message def ask(prompt = '(y/n)') command_line.set_prompt prompt command_line.refresh while (c = Curses.getch) next unless [?N, ?Y, ?n, ?y, 3, 27] .include? c # N, Y, n, y, ^c, esc command_line.clear command_line.noutrefresh break (c == 'y') || (c == 'Y') end end # Open current file or directory with the editor. def edit execute_external_command do editor = ENV['EDITOR'] || 'vim' unless in_zip? system %Q[#{editor} "#{current_item.path}"] else begin tmpdir, tmpfile_name = nil Zip::File.open(current_zip) do |zip| tmpdir = Dir.mktmpdir FileUtils.mkdir_p File.join(tmpdir, File.dirname(current_item.name)) tmpfile_name = File.join(tmpdir, current_item.name) File.open(tmpfile_name, 'w') {|f| f.puts zip.file.read(current_item.name)} system %Q[#{editor} "#{tmpfile_name}"] zip.add(current_item.name, tmpfile_name) { true } end ls ensure FileUtils.remove_entry_secure tmpdir if tmpdir end end end end # Open current file or directory with the viewer. def view pager = ENV['PAGER'] || 'less' execute_external_command do unless in_zip? system %Q[#{pager} "#{current_item.path}"] else begin tmpdir, tmpfile_name = nil Zip::File.open(current_zip) do |zip| tmpdir = Dir.mktmpdir FileUtils.mkdir_p File.join(tmpdir, File.dirname(current_item.name)) tmpfile_name = File.join(tmpdir, current_item.name) File.open(tmpfile_name, 'w') {|f| f.puts zip.file.read(current_item.name)} end system %Q[#{pager} "#{tmpfile_name}"] ensure FileUtils.remove_entry_secure tmpdir if tmpdir end end end end def move_cursor_by_click(y: nil, x: nil) if (idx = main.pane_index_at(y: y, x: x)) row = current_page * max_items + main.maxy * idx + y - main.begy move_cursor row if (row >= 0) && (row < items.size) end end private def execute_external_command(pause: false) Curses.def_prog_mode Curses.close_screen yield ensure Curses.reset_prog_mode Curses.getch if pause #NOTE needs to draw borders and ls again here since the stdlib Curses.refresh fails to retrieve the previous screen Rfd::Window.draw_borders Curses.refresh ls end def expand_path(path) File.expand_path path.start_with?('/', '~') ? path : current_dir ? current_dir.join(path) : path end def load_item(path: nil, dir: nil, name: nil, stat: nil) Item.new dir: dir || File.dirname(path), name: name || File.basename(path), stat: stat, window_width: main.width end def osx? @_osx ||= RbConfig::CONFIG['host_os'] =~ /darwin/ end def in_zip? @current_zip end def debug(str) @debug.debug str end end
moneta-rb/moneta
lib/moneta/builder.rb
Moneta.Builder.build
ruby
def build adapter = @proxies.first if Array === adapter klass, options, block = adapter adapter = new_proxy(klass, options, &block) check_arity(klass, adapter, 1) end @proxies[1..-1].inject([adapter]) do |result, proxy| klass, options, block = proxy proxy = new_proxy(klass, result.last, options, &block) check_arity(klass, proxy, 2) result << proxy end end
@yieldparam Builder dsl code block Build proxy stack @return [Object] Generated Moneta proxy stack @api public
train
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/builder.rb#L16-L29
class Builder # @yieldparam Builder dsl code block def initialize(&block) raise ArgumentError, 'No block given' unless block_given? @proxies = [] instance_eval(&block) end # Build proxy stack # # @return [Object] Generated Moneta proxy stack # @api public # Add proxy to stack # # @param [Symbol/Class] proxy Name of proxy class or proxy class # @param [Hash] options Options hash # @api public def use(proxy, options = {}, &block) proxy = Moneta.const_get(proxy) if Symbol === proxy raise ArgumentError, 'You must give a Class or a Symbol' unless Class === proxy @proxies.unshift [proxy, options, block] nil end # Add adapter to stack # # @param [Symbol/Class/Moneta store] adapter Name of adapter class, adapter class or Moneta store # @param [Hash] options Options hash # @api public def adapter(adapter, options = {}, &block) case adapter when Symbol use(Adapters.const_get(adapter), options, &block) when Class use(adapter, options, &block) else raise ArgumentError, 'Adapter must be a Moneta store' unless adapter.respond_to?(:load) && adapter.respond_to?(:store) raise ArgumentError, 'No options allowed' unless options.empty? @proxies.unshift adapter nil end end protected def new_proxy(klass, *args, &block) klass.new(*args, &block) rescue ArgumentError check_arity(klass, klass.allocate, args.size) raise end def check_arity(klass, proxy, expected) args = proxy.method(:initialize).arity.abs raise(ArgumentError, %{#{klass.name}#new accepts wrong number of arguments (#{args} accepted, #{expected} expected) Please check your Moneta builder block: * Proxies must be used before the adapter * Only one adapter is allowed * The adapter must be used last }) if args != expected end end
dagrz/nba_stats
lib/nba_stats/stats/team_year_by_year_stats.rb
NbaStats.TeamYearByYearStats.team_year_by_year_stats
ruby
def team_year_by_year_stats( team_id, season, per_mode=NbaStats::Constants::PER_MODE_TOTALS, season_type=NbaStats::Constants::SEASON_TYPE_REGULAR, league_id=NbaStats::Constants::LEAGUE_ID_NBA ) NbaStats::Resources::TeamYearByYearStats.new( get(TEAM_YEAR_BY_YEAR_STATS_PATH, { :LeagueID => league_id, :PerMode => per_mode, :SeasonType => season_type, :TeamID => team_id, :Season => season }) ) end
Calls the teamyearbyyearstats API and returns a TeamYearByYearStats resource. @param team_id [Integer] @param season [String] @param per_mode [String] @param season_type [String] @param league_id [String] @return [NbaStats::Resources::TeamYearByYearStats]
train
https://github.com/dagrz/nba_stats/blob/d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa/lib/nba_stats/stats/team_year_by_year_stats.rb#L18-L34
module TeamYearByYearStats # The path of the teamyearbyyearstats API TEAM_YEAR_BY_YEAR_STATS_PATH = '/stats/teamyearbyyearstats' # Calls the teamyearbyyearstats API and returns a TeamYearByYearStats resource. # # @param team_id [Integer] # @param season [String] # @param per_mode [String] # @param season_type [String] # @param league_id [String] # @return [NbaStats::Resources::TeamYearByYearStats] end # TeamYearByYearStats
sunspot/sunspot
sunspot/lib/sunspot/schema.rb
Sunspot.Schema.variant_combinations
ruby
def variant_combinations combinations = [] 0.upto(2 ** FIELD_VARIANTS.length - 1) do |b| combinations << combination = [] FIELD_VARIANTS.each_with_index do |variant, i| combination << variant if b & 1<<i > 0 end end combinations end
All of the possible combinations of variants
train
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/schema.rb#L108-L117
class Schema #:nodoc:all FieldType = Struct.new(:name, :class_name, :suffix) FieldVariant = Struct.new(:attribute, :suffix) DEFAULT_TOKENIZER = 'solr.StandardTokenizerFactory' DEFAULT_FILTERS = %w(solr.StandardFilterFactory solr.LowerCaseFilterFactory) FIELD_TYPES = [ FieldType.new('boolean', 'Bool', 'b'), FieldType.new('sfloat', 'SortableFloat', 'f'), FieldType.new('date', 'Date', 'd'), FieldType.new('sint', 'SortableInt', 'i'), FieldType.new('string', 'Str', 's'), FieldType.new('sdouble', 'SortableDouble', 'e'), FieldType.new('slong', 'SortableLong', 'l'), FieldType.new('tint', 'TrieInteger', 'it'), FieldType.new('tfloat', 'TrieFloat', 'ft'), FieldType.new('tdate', 'TrieInt', 'dt'), FieldType.new('daterange', 'DateRange', 'dr') ] FIELD_VARIANTS = [ FieldVariant.new('multiValued', 'm'), FieldVariant.new('stored', 's') ] attr_reader :tokenizer, :filters def initialize @tokenizer = DEFAULT_TOKENIZER @filters = DEFAULT_FILTERS.dup end # # Attribute field types defined in the schema # def types FIELD_TYPES end # # DynamicField instances representing all the available types and variants # def dynamic_fields fields = [] variant_combinations.each do |field_variants| FIELD_TYPES.each do |type| fields << DynamicField.new(type, field_variants) end end fields end # # Which tokenizer to use for text fields # def tokenizer=(tokenizer) @tokenizer = if tokenizer =~ /\./ tokenizer else "solr.#{tokenizer}TokenizerFactory" end end # # Add a filter for text field tokenization # def add_filter(filter) @filters << if filter =~ /\./ filter else "solr.#{filter}FilterFactory" end end # # Return an XML representation of this schema using the ERB template # def to_xml template_path = File.join(File.dirname(__FILE__), '..', '..', 'templates', 'schema.xml.erb') template_text = File.read(template_path) erb = if RUBY_VERSION >= '2.6' ERB.new(template_text, trim_mode: '-') else ERB.new(template_text, nil, '-') end erb.result(binding) end private # # All of the possible combinations of variants # # # Represents a dynamic field (in the Solr schema sense, not the Sunspot # sense). # class DynamicField def initialize(type, field_variants) @type, @field_variants = type, field_variants end # # Name of the field in the schema # def name variant_suffixes = @field_variants.map { |variant| variant.suffix }.join "*_#{@type.suffix}#{variant_suffixes}" end # # Name of the type as defined in the schema # def type @type.name end # # Implement magic methods to ask if a field is of a particular variant. # Returns "true" if the field is of that variant and "false" otherwise. # def method_missing(name, *args, &block) if name.to_s =~ /\?$/ && args.empty? if @field_variants.any? { |variant| "#{variant.attribute}?" == name.to_s } 'true' else 'false' end else super(name.to_sym, *args, &block) end end end end
jdigger/git-process
lib/git-process/git_lib.rb
GitProc.GitLib.workdir=
ruby
def workdir=(dir) workdir = GitLib.find_workdir(dir) if workdir.nil? @workdir = dir logger.info { "Initializing new repository at #{dir}" } return command(:init) else @workdir = workdir logger.debug { "Opening existing repository at #{dir}" } end end
Sets the working directory to use for the (non-bare) repository. If the directory is *not* part of an existing repository, a new repository is created. (i.e., "git init") @param [Dir] dir the working directory @return [void]
train
https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_lib.rb#L98-L108
class GitLib # @param [Dir] dir the work dir # @param [Hash] logging_opts see {log_level} def initialize(dir, logging_opts) self.log_level = GitLib.log_level(logging_opts) self.workdir = dir end # @return [GitLogger] the logger to use def logger if @logger.nil? @logger = GitLogger.new(log_level) end return @logger end # # Decodes the [Hash] to determine what logging level to use # # @option opts [Fixnum] :log_level the log level from {Logger} # @option opts :quiet {Logger::ERROR} # @option opts :verbose {Logger::DEBUG} # # @return [Fixnum] the log level from Logger; defaults to {Logger::INFO} # def self.log_level(opts) if opts[:log_level] return opts[:log_level] elsif opts[:quiet] return Logger::ERROR elsif opts[:verbose] return Logger::DEBUG else return Logger::INFO end end # @return [Fixnum] the logging level to use; defaults to {Logger::WARN} def log_level @log_level || Logger::WARN end # @param [Fixnum] lvl the logging level to use. See {Logger} # @return [void] def log_level=(lvl) @log_level = lvl end # @return [Dir] the working directory def workdir @workdir end # # Sets the working directory to use for the (non-bare) repository. # # If the directory is *not* part of an existing repository, a new repository is created. (i.e., "git init") # # @param [Dir] dir the working directory # @return [void] def self.find_workdir(dir) if dir == File::SEPARATOR return nil elsif File.directory?(File.join(dir, '.git')) return dir else return find_workdir(File.expand_path("#{dir}#{File::SEPARATOR}..")) end end # @return [void] def fetch_remote_changes(remote_name = nil) if remote.exists? fetch(remote_name || remote.name) else logger.debug 'Can not fetch latest changes because there is no remote defined' end end # # Executes a rebase, but translates any {GitExecuteError} to a {RebaseError} # # @param (see #rebase) # @option (see #rebase) # @raise [RebaseError] if there is a problem executing the rebase def proc_rebase(base, opts = {}) begin return rebase(base, opts) rescue GitExecuteError => rebase_error raise RebaseError.new(rebase_error.message, self) end end # # Executes a merge, but translates any {GitExecuteError} to a {MergeError} # # @param (see #merge) # @option (see #merge) # @raise [MergeError] if there is a problem executing the merge def proc_merge(base, opts = {}) begin return merge(base, opts) rescue GitExecuteError => merge_error raise MergeError.new(merge_error.message, self) end end # @return [String, nil] the previous remote sha ONLY IF it is not the same as the new remote sha; otherwise nil def previous_remote_sha(current_branch, remote_branch) return nil unless has_a_remote? return nil unless remote_branches.include?(remote_branch) control_file_sha = read_sync_control_file(current_branch) old_sha = control_file_sha || remote_branch_sha(remote_branch) fetch_remote_changes new_sha = remote_branch_sha(remote_branch) if old_sha != new_sha logger.info('The remote branch has changed since the last time') return old_sha else logger.debug 'The remote branch has not changed since the last time' return nil end end def remote_branch_sha(remote_branch) logger.debug { "getting sha for remotes/#{remote_branch}" } return rev_parse("remotes/#{remote_branch}") rescue '' end # @return [Boolean] is the current branch the "_parked_" branch? def is_parked? mybranches = self.branches() return mybranches.parking == mybranches.current end # Push the repository to the server. # # @param local_branch [String] the name of the local branch to push from # @param remote_branch [String] the name of the remote branch to push to # # @option opts [Boolean] :local should this do nothing because it is in local-only mode? # @option opts [Boolean] :force should it force the push even if it can not fast-forward? # @option opts [Proc] :prepush a block to call before doing the push # @option opts [Proc] :postpush a block to call after doing the push # # @return [void] # def push_to_server(local_branch, remote_branch, opts = {}) if opts[:local] logger.debug('Not pushing to the server because the user selected local-only.') elsif not has_a_remote? logger.debug('Not pushing to the server because there is no remote.') elsif local_branch == config.master_branch logger.warn('Not pushing to the server because the current branch is the mainline branch.') else opts[:prepush].call if opts[:prepush] push(remote.name, local_branch, remote_branch, :force => opts[:force]) opts[:postpush].call if opts[:postpush] end end # @return [GitConfig] the git configuration def config if @config.nil? @config = GitConfig.new(self) end return @config end # @return [GitRemote] the git remote configuration def remote if @remote.nil? @remote = GitProc::GitRemote.new(config) end return @remote end # @return [Boolean] does this have a remote defined? def has_a_remote? remote.exists? end # # `git add` # # @param [String] file the name of the file to add to the index # @return [String] the output of 'git add' def add(file) logger.info { "Adding #{[*file].join(', ')}" } return command(:add, ['--', file]) end # # `git commit` # # @param [String] msg the commit message # @return [String] the output of 'git commit' def commit(msg = nil) logger.info 'Committing changes' return command(:commit, msg.nil? ? nil : ['-m', msg]) end # # `git rebase` # # @param [String] upstream the commit-ish to rebase against # @option opts :interactive do an interactive rebase # @option opts [String] :oldbase the old base to rebase from # # @return [String] the output of 'git rebase' def rebase(upstream, opts = {}) args = [] if opts[:interactive] logger.info { "Interactively rebasing #{branches.current.name} against #{upstream}" } args << '-i' args << upstream elsif opts[:oldbase] logger.info { "Doing rebase from #{opts[:oldbase]} against #{upstream} on #{branches.current.name}" } args << '--onto' << upstream << opts[:oldbase] << branches.current.name else logger.info { "Rebasing #{branches.current.name} against #{upstream}" } args << upstream end return command('rebase', args) end # # `git merge` # # @return [String] the output of 'git merge' def merge(base, opts= {}) logger.info { "Merging #{branches.current.name} with #{base}" } args = [] args << '-s' << opts[:merge_strategy] if opts[:merge_strategy] args << base return command(:merge, args) end # # `git fetch` # # @return [String] the output of 'git fetch' def fetch(name = remote.name) logger.info 'Fetching the latest changes from the server' output = self.command(:fetch, ['-p', name]) log_fetch_changes(fetch_changes(output)) return output end # @return [Hash] with lists for each of :new_branch, :new_tag, :force_updated, :deleted, :updated def fetch_changes(output) changed = output.split("\n") changes = {:new_branch => [], :new_tag => [], :force_updated => [], :deleted => [], :updated => []} line = changed.shift until line.nil? do case line when /^\s\s\s/ m = /^\s\s\s(\S+)\s+(\S+)\s/.match(line) changes[:updated] << "#{m[2]} (#{m[1]})" when /^\s\*\s\[new branch\]/ m = /^\s\*\s\[new branch\]\s+(\S+)\s/.match(line) changes[:new_branch] << m[1] when /^\s\*\s\[new tag\]/ m = /^\s\*\s\[new tag\]\s+(\S+)\s/.match(line) changes[:new_tag] << m[1] when /^\sx\s/ m = /^\sx\s\[deleted\]\s+\(none\)\s+->\s+[^\/]+\/(\S+)/.match(line) changes[:deleted] << m[1] when /^\s\+\s/ m = /^\s\+\s(\S+)\s+(\S+)\s/.match(line) changes[:force_updated] << "#{m[2]} (#{m[1]})" else # ignore the line end line = changed.shift end changes end # @return [GitBranches] def branches GitProc::GitBranches.new(self) end # @return [GitBranches] def remote_branches GitProc::GitBranches.new(self, :remote => true) end # # Does branch manipulation. # # @param [String] branch_name the name of the branch # # @option opts [Boolean] :delete delete the remote branch # @option opts [Boolean] :force force the update # @option opts [Boolean] :all list all branches, local and remote # @option opts [Boolean] :no_color force not using any ANSI color codes # @option opts [String] :rename the new name for the branch # @option opts [String] :upstream the new branch to track # @option opts [String] :base_branch ('master') the branch to base the new branch off of # # @return [String] the output of running the git command def branch(branch_name, opts = {}) if branch_name if opts[:delete] return delete_branch(branch_name, opts[:force]) elsif opts[:rename] return rename_branch(branch_name, opts[:rename]) elsif opts[:upstream] return set_upstream_branch(branch_name, opts[:upstream]) else base_branch = opts[:base_branch] || 'master' if opts[:force] return change_branch(branch_name, base_branch) else return create_branch(branch_name, base_branch) end end else #list_branches(opts) return list_branches(opts[:all], opts[:remote], opts[:no_color]) end end # # Pushes the given branch to the server. # # @param [String] remote_name the repository name; nil -> 'origin' # @param [String] local_branch the local branch to push; nil -> the current branch # @param [String] remote_branch the name of the branch to push to; nil -> same as local_branch # # @option opts [Boolean, String] :delete delete the remote branch # @option opts [Boolean] :force force the update, even if not a fast-forward? # # @return [String] the output of the push command # # @raise [ArgumentError] if :delete is true, but no branch name is given # def push(remote_name, local_branch, remote_branch, opts = {}) if opts[:delete] return push_delete(remote_branch || local_branch, remote_name, opts) else return push_to_remote(local_branch, remote_branch, remote_name, opts) end end # # Pushes the given branch to the server. # # @param [String] remote_name the repository name; nil -> 'origin' # @param [String] local_branch the local branch to push; nil -> the current branch # @param [String] remote_branch the name of the branch to push to; nil -> same as local_branch # # @option opts [Boolean] :force force the update, even if not a fast-forward? # # @return [String] the output of the push command # def push_to_remote(local_branch, remote_branch, remote_name, opts) remote_name ||= 'origin' args = [remote_name] local_branch ||= branches.current remote_branch ||= local_branch args << '-f' if opts[:force] logger.info do if local_branch == remote_branch "Pushing to '#{remote_branch}' on '#{remote_name}'." else "Pushing #{local_branch} to '#{remote_branch}' on '#{remote_name}'." end end args << "#{local_branch}:#{remote_branch}" return command(:push, args) end # # Pushes the given branch to the server. # # @param [String] remote_name the repository name; nil -> 'origin' # @param [String] branch_name the name of the branch to push to # # @option opts [Boolean, String] :delete if a String it is the branch name # # @return [String] the output of the push command # # @raise [ArgumentError] no branch name is given # @raise [raise GitProc::GitProcessError] trying to delete the integration branch # # @todo remove the opts param # def push_delete(branch_name, remote_name, opts) remote_name ||= 'origin' args = [remote_name] if branch_name rb = branch_name elsif !(opts[:delete].is_a? TrueClass) rb = opts[:delete] else raise ArgumentError.new('Need a branch name to delete.') end int_branch = config.master_branch if rb == int_branch raise GitProc::GitProcessError.new("Can not delete the integration branch '#{int_branch}'") end logger.info { "Deleting remote branch '#{rb}' on '#{remote_name}'." } args << '--delete' << rb return command(:push, args) end # `git rebase --continue` # # @return [String] the output of the git command def rebase_continue command(:rebase, '--continue') end # `git stash --save` # # @return [String] the output of the git command def stash_save command(:stash, %w(save)) end # `git stash --pop` # # @return [String] the output of the git command def stash_pop command(:stash, %w(pop)) end # `git show` # # @return [String] the output of the git command def show(refspec) command(:show, refspec) end # @param [String] branch_name the name of the branch to checkout/create # @option opts [Boolean] :no_track do not track the base branch # @option opts [String] :new_branch the name of the base branch # # @return [void] def checkout(branch_name, opts = {}) args = [] args << '--no-track' if opts[:no_track] args << '-b' if opts[:new_branch] args << branch_name args << opts[:new_branch] if opts[:new_branch] branches = branches() command(:checkout, args) branches << GitBranch.new(branch_name, opts[:new_branch] != nil, self) if block_given? yield command(:checkout, branches.current.name) branches.current else branches[branch_name] end end # @return [int] the number of commits that exist in the current branch def log_count command(:log, '--oneline').split(/\n/).length end # Remove the files from the Index # # @param [Array<String>] files the file names to remove from the Index # # @option opts :force if exists and not false, will force the removal of the files # # @return [String] the output of the git command def remove(files, opts = {}) args = [] args << '-f' if opts[:force] args << [*files] command(:rm, args) end # # Returns the status of the git repository. # # @return [Status] def status GitStatus.new(self) end # @return [String] the raw porcelain status string def porcelain_status command(:status, '--porcelain') end # # Resets the Index/Working Directory to the given revision # # @param [String] rev_name the revision name (commit-ish) to go back to # # @option opts :hard should the working directory be changed? If {false} or missing, will only update the Index # def reset(rev_name, opts = {}) args = [] args << '--hard' if opts[:hard] args << rev_name logger.info { "Resetting #{opts[:hard] ? '(hard)' : ''} to #{rev_name}" } command(:reset, args) end def rev_list(start_revision, end_revision, opts ={}) args = [] args << "-#{opts[:num_revs]}" if opts[:num_revs] args << '--oneline' if opts[:oneline] args << "#{start_revision}..#{end_revision}" command('rev-list', args) end # # Translate the commit-ish name to the SHA-1 hash value # # @return [String, nil] the SHA-1 value, or nil if the revision name is unknown # def rev_parse(name) sha = command('rev-parse', ['--revs-only', name]) return sha.empty? ? nil : sha end alias :sha :rev_parse # # Executes the given git command # # @param [Symbol, String] cmd the command to run (e.g., :commit) # @param [Array<String, Symbol>] opts the arguments to pass to the command # @param [Boolean] chdir should the shell change to the top of the working dir before executing the command? # @param [String] redirect ??????? # @yield the block to run in the context of running the command # # @return [String] the output of the git command # def command(cmd, opts = [], chdir = true, redirect = '', &block) ENV['GIT_INDEX_FILE'] = File.join(workdir, '.git', 'index') ENV['GIT_DIR'] = File.join(workdir, '.git') ENV['GIT_WORK_TREE'] = workdir path = workdir git_cmd = create_git_command(cmd, opts, redirect) out = command_git_cmd(path, git_cmd, chdir, block) if logger logger.debug(git_cmd) logger.debug(out) end handle_exitstatus($?, git_cmd, out) end # # Writes the current SHA-1 for the tip of the branch to the "sync control file" # # @return [void] # @see GitLib#read_sync_control_file def write_sync_control_file(branch_name) latest_sha = rev_parse(branch_name) filename = sync_control_filename(branch_name) logger.debug { "Writing sync control file, #{filename}, with #{latest_sha}" } File.open(filename, 'w') { |f| f.puts latest_sha } end # @return [String, nil] the SHA-1 of the latest sync performed for the branch, or nil if none is recorded # @see GitLib#write_sync_control_file def read_sync_control_file(branch_name) filename = sync_control_filename(branch_name) if File.exists?(filename) sha = File.open(filename) do |file| file.readline.chop end logger.debug "Read sync control file, #{filename}: #{sha}" sha else logger.debug "Sync control file, #{filename}, was not found" nil end end # # Delete the sync control file for the branch # # @return [void] # @see GitLib#write_sync_control_file def delete_sync_control_file!(branch_name) filename = sync_control_filename(branch_name) logger.debug { "Deleting sync control file, #{filename}" } # on some systems, especially Windows, the file may be locked. wait for it to unlock counter = 10 while counter > 0 begin File.delete(filename) counter = 0 rescue counter = counter - 1 sleep(0.25) end end end # @return [Boolean] does the sync control file exist? # @see GitLib#write_sync_control_file def sync_control_file_exists?(branch_name) filename = sync_control_filename(branch_name) File.exist?(filename) end def set_upstream_branch(branch_name, upstream) logger.info { "Setting upstream/tracking for branch '#{branch_name}' to '#{upstream}'." } if has_a_remote? parts = upstream.split(/\//) if parts.length() > 1 potential_remote = parts.shift if remote.remote_names.include?(potential_remote) config["branch.#{branch_name}.remote"] = potential_remote config["branch.#{branch_name}.merge"] = "refs/heads/#{parts.join('/')}" end else config["branch.#{branch_name}.merge"] = "refs/heads/#{upstream}" end else config["branch.#{branch_name}.merge"] = "refs/heads/#{upstream}" end # The preferred way assuming using git 1.8 cli #command(:branch, ['--set-upstream-to', upstream, branch_name]) end private # # Create the CLI for the git command # # @param [Symbol, String] cmd the command to run (e.g., :commit) # @param [Array<String, Symbol>] opts the arguments to pass to the command # @param [String] redirect ??????? # # @return [String] the command line to run # def create_git_command(cmd, opts, redirect) opts = [opts].flatten.map { |s| escape(s) }.join(' ') return "git #{cmd} #{opts} #{redirect} 2>&1" end # # Executes the given git command # # @param [String] path the directory to run the command in # @param [String] git_cmd the CLI command to execute # @param [Boolean] chdir should the shell change to the top of the working dir before executing the command? # @param [Proc] block the block to run in the context of running the command # # @return [String] the output of the git command # def command_git_cmd(path, git_cmd, chdir, block) out = nil if chdir and (Dir.getwd != path) Dir.chdir(path) { out = run_command(git_cmd, &block) } else out = run_command(git_cmd, &block) end return out end # @return [String] def handle_exitstatus(proc_status, git_cmd, out) if proc_status.exitstatus > 0 unless proc_status.exitstatus == 1 && out == '' raise GitProc::GitExecuteError.new(git_cmd + ':' + out.to_s) end end return out end # # Executes the given git command # # @param [String] git_cmd the CLI command to execute # @yield the block to run in the context of running the command. See {IO#popen} # # @return [String] the output of the git command # def run_command(git_cmd, &block) if block_given? return IO.popen(git_cmd, &block) else return `#{git_cmd}`.chomp end end # @return [String] def escape(s) escaped = s.to_s.gsub('\'', '\'\\\'\'') %Q{"#{escaped}"} end # @return [String] def change_branch(branch_name, base_branch) raise ArgumentError.new('Need :base_branch when using :force for a branch.') unless base_branch logger.info { "Changing branch '#{branch_name}' to point to '#{base_branch}'." } command(:branch, ['-f', branch_name, base_branch]) end # @return [String] def create_branch(branch_name, base_branch) logger.info { "Creating new branch '#{branch_name}' based on '#{base_branch}'." } command(:branch, [branch_name, (base_branch || 'master')]) end # @return [String] def list_branches(all_branches, remote_branches, no_color) args = [] args << '-a' if all_branches args << '-r' if remote_branches args << '--no-color' if no_color command(:branch, args) end # @return [String] def delete_branch(branch_name, force) logger.info { "Deleting local branch '#{branch_name}'." } unless branch_name == '_parking_' command(:branch, [force ? '-D' : '-d', branch_name]) end # @return [String] def rename_branch(branch_name, new_name) logger.info { "Renaming branch '#{branch_name}' to '#{new_name}'." } command(:branch, ['-m', branch_name, new_name]) end # @return [String] def sync_control_filename(branch_name) normalized_branch_name = branch_name.to_s.gsub(/[\/]/, "-") return File.join(File.join(workdir, '.git'), "gitprocess-sync-#{remote.name}--#{normalized_branch_name}") end # @param [Hash] changes a hash of the changes that were made # # @return [void] def log_fetch_changes(changes) changes.each do |key, v| unless v.empty? logger.info { " #{key.to_s.sub(/_/, ' ')}: #{v.join(', ')}" } end end end end
CocoaPods/Xcodeproj
lib/xcodeproj/project.rb
Xcodeproj.Project.save
ruby
def save(save_path = nil) save_path ||= path @dirty = false if save_path == path FileUtils.mkdir_p(save_path) file = File.join(save_path, 'project.pbxproj') Atomos.atomic_write(file) do |f| Nanaimo::Writer::PBXProjWriter.new(to_ascii_plist, :pretty => true, :output => f, :strict => false).write end end
Serializes the project in the xcodeproj format using the path provided during initialization or the given path (`xcodeproj` file). If a path is provided file references depending on the root of the project are not updated automatically, thus clients are responsible to perform any needed modification before saving. @param [String, Pathname] path The optional path where the project should be saved. @example Saving a project project.save project.save @return [void]
train
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/project.rb#L358-L366
class Project include Object # @return [Pathname] the path of the project. # attr_reader :path # @return [Pathname] the directory of the project # attr_reader :project_dir # @param [Pathname, String] path @see path # The path provided will be expanded to an absolute path. # @param [Bool] skip_initialization # Wether the project should be initialized from scratch. # @param [Int] object_version # Object version to use for serialization, defaults to Xcode 3.2 compatible. # # @example Creating a project # Project.new("path/to/Project.xcodeproj") # # @note When initializing the project, Xcodeproj mimics the Xcode behaviour # including the setup of a debug and release configuration. If you want a # clean project without any configurations, you should override the # `initialize_from_scratch` method to not add these configurations and # manually set the object version. # def initialize(path, skip_initialization = false, object_version = Constants::DEFAULT_OBJECT_VERSION) @path = Pathname.new(path).expand_path @project_dir = @path.dirname @objects_by_uuid = {} @generated_uuids = [] @available_uuids = [] @dirty = true unless skip_initialization.is_a?(TrueClass) || skip_initialization.is_a?(FalseClass) raise ArgumentError, '[Xcodeproj] Initialization parameter expected to ' \ "be a boolean #{skip_initialization}" end unless skip_initialization initialize_from_scratch @object_version = object_version.to_s unless Constants::COMPATIBILITY_VERSION_BY_OBJECT_VERSION.key?(object_version) raise ArgumentError, "[Xcodeproj] Unable to find compatibility version string for object version `#{object_version}`." end root_object.compatibility_version = Constants::COMPATIBILITY_VERSION_BY_OBJECT_VERSION[object_version] end end # Opens the project at the given path. # # @param [Pathname, String] path # The path to the Xcode project document (xcodeproj). # # @raise If the project versions are more recent than the ones know to # Xcodeproj to prevent it from corrupting existing projects. # Naturally, this would never happen with a project generated by # xcodeproj itself. # # @raise If it can't find the root object. This means that the project is # malformed. # # @example Opening a project # Project.open("path/to/Project.xcodeproj") # def self.open(path) path = Pathname.pwd + path unless Pathname.new(path).exist? raise "[Xcodeproj] Unable to open `#{path}` because it doesn't exist." end project = new(path, true) project.send(:initialize_from_file) project end # @return [String] the archive version. # attr_reader :archive_version # @return [Hash] an dictionary whose purpose is unknown. # attr_reader :classes # @return [String] the objects version. # attr_reader :object_version # @return [Hash{String => AbstractObject}] A hash containing all the # objects of the project by UUID. # attr_reader :objects_by_uuid # @return [PBXProject] the root object of the project. # attr_reader :root_object # A fast way to see if two {Project} instances refer to the same projects on # disk. Use this over {#eql?} when you do not need to compare the full data. # # This shallow comparison was chosen as the (common) `==` implementation, # because it was too easy to introduce changes into the Xcodeproj code-base # that were slower than O(1). # # @return [Boolean] whether or not the two `Project` instances refer to the # same projects on disk, determined solely by {#path} and # `root_object.uuid` equality. # # @todo If ever needed, we could also compare `uuids.sort` instead. # def ==(other) other && path == other.path && root_object.uuid == other.root_object.uuid end # Compares the project to another one, or to a plist representation. # # @note This operation can be extremely expensive, because it converts a # `Project` instance to a hash, and should _only_ ever be used to # determine wether or not the data contents of two `Project` instances # are completely equal. # # To simply determine wether or not two {Project} instances refer to # the same projects on disk, use the {#==} method instead. # # @param [#to_hash] other the object to compare. # # @return [Boolean] whether the project is equivalent to the given object. # def eql?(other) other.respond_to?(:to_hash) && to_hash == other.to_hash end def to_s "#<#{self.class}> path:`#{path}` UUID:`#{root_object.uuid}`" end alias_method :inspect, :to_s public # @!group Initialization #-------------------------------------------------------------------------# # Initializes the instance from scratch. # def initialize_from_scratch @archive_version = Constants::LAST_KNOWN_ARCHIVE_VERSION.to_s @classes = {} root_object.remove_referrer(self) if root_object @root_object = new(PBXProject) root_object.add_referrer(self) root_object.main_group = new(PBXGroup) root_object.product_ref_group = root_object.main_group.new_group('Products') config_list = new(XCConfigurationList) root_object.build_configuration_list = config_list config_list.default_configuration_name = 'Release' config_list.default_configuration_is_visible = '0' add_build_configuration('Debug', :debug) add_build_configuration('Release', :release) new_group('Frameworks') end # Initializes the instance with the project stored in the `path` attribute. # def initialize_from_file pbxproj_path = path + 'project.pbxproj' plist = Plist.read_from_path(pbxproj_path.to_s) root_object.remove_referrer(self) if root_object @root_object = new_from_plist(plist['rootObject'], plist['objects'], self) @archive_version = plist['archiveVersion'] @object_version = plist['objectVersion'] @classes = plist['classes'] || {} @dirty = false unless root_object raise "[Xcodeproj] Unable to find a root object in #{pbxproj_path}." end if archive_version.to_i > Constants::LAST_KNOWN_ARCHIVE_VERSION raise '[Xcodeproj] Unknown archive version.' end if object_version.to_i > Constants::LAST_KNOWN_OBJECT_VERSION raise '[Xcodeproj] Unknown object version.' end # Projects can have product_ref_groups that are not listed in the main_groups["Products"] root_object.product_ref_group ||= root_object.main_group['Products'] || root_object.main_group.new_group('Products') end public # @!group Plist serialization #-------------------------------------------------------------------------# # Creates a new object from the given UUID and `objects` hash (of a plist). # # The method sets up any relationship of the new object, generating the # destination object(s) if not already present in the project. # # @note This method is used to generate the root object # from a plist. Subsequent invocation are called by the # {AbstractObject#configure_with_plist}. Clients of {Xcodeproj} are # not expected to call this method. # # @param [String] uuid # The UUID of the object that needs to be generated. # # @param [Hash {String => Hash}] objects_by_uuid_plist # The `objects` hash of the plist representation of the project. # # @param [Boolean] root_object # Whether the requested object is the root object and needs to be # retained by the project before configuration to add it to the # `objects` hash and avoid infinite loops. # # @return [AbstractObject] the new object. # # @visibility private. # def new_from_plist(uuid, objects_by_uuid_plist, root_object = false) attributes = objects_by_uuid_plist[uuid] if attributes klass = Object.const_get(attributes['isa']) object = klass.new(self, uuid) objects_by_uuid[uuid] = object object.add_referrer(self) if root_object object.configure_with_plist(objects_by_uuid_plist) object end end # @return [Hash] The hash representation of the project. # def to_hash plist = {} objects_dictionary = {} objects.each { |obj| objects_dictionary[obj.uuid] = obj.to_hash } plist['objects'] = objects_dictionary plist['archiveVersion'] = archive_version.to_s plist['objectVersion'] = object_version.to_s plist['classes'] = classes plist['rootObject'] = root_object.uuid plist end def to_ascii_plist plist = {} objects_dictionary = {} objects .sort_by { |o| [o.isa, o.uuid] } .each do |obj| key = Nanaimo::String.new(obj.uuid, obj.ascii_plist_annotation) value = obj.to_ascii_plist.tap { |a| a.annotation = nil } objects_dictionary[key] = value end plist['archiveVersion'] = archive_version.to_s plist['classes'] = classes plist['objectVersion'] = object_version.to_s plist['objects'] = objects_dictionary plist['rootObject'] = Nanaimo::String.new(root_object.uuid, root_object.ascii_plist_annotation) Nanaimo::Plist.new.tap { |p| p.root_object = plist } end # Converts the objects tree to a hash substituting the hash # of the referenced to their UUID reference. As a consequence the hash of # an object might appear multiple times and the information about their # uniqueness is lost. # # This method is designed to work in conjunction with {Hash#recursive_diff} # to provide a complete, yet readable, diff of two projects *not* affected # by differences in UUIDs. # # @return [Hash] a hash representation of the project different from the # plist one. # def to_tree_hash hash = {} objects_dictionary = {} hash['objects'] = objects_dictionary hash['archiveVersion'] = archive_version.to_s hash['objectVersion'] = object_version.to_s hash['classes'] = classes hash['rootObject'] = root_object.to_tree_hash hash end # @return [Hash{String => Hash}] A hash suitable to display the project # to the user. # def pretty_print build_configurations = root_object.build_configuration_list.build_configurations { 'File References' => root_object.main_group.pretty_print.values.first, 'Targets' => root_object.targets.map(&:pretty_print), 'Build Configurations' => build_configurations.sort_by(&:name).map(&:pretty_print), } end # Serializes the project in the xcodeproj format using the path provided # during initialization or the given path (`xcodeproj` file). If a path is # provided file references depending on the root of the project are not # updated automatically, thus clients are responsible to perform any needed # modification before saving. # # @param [String, Pathname] path # The optional path where the project should be saved. # # @example Saving a project # project.save # project.save # # @return [void] # # Marks the project as dirty, that is, modified from what is on disk. # # @return [void] # def mark_dirty! @dirty = true end # @return [Boolean] Whether this project has been modified since read from # disk or saved. # def dirty? @dirty == true end # Replaces all the UUIDs in the project with deterministic MD5 checksums. # # @note The current sorting of the project is taken into account when # generating the new UUIDs. # # @note This method should only be used for entirely machine-generated # projects, as true UUIDs are useful for tracking changes in the # project. # # @return [void] # def predictabilize_uuids UUIDGenerator.new([self]).generate! end # Replaces all the UUIDs in the list of provided projects with deterministic MD5 checksums. # # @param [Array<Project>] projects # # @note The current sorting of the project is taken into account when # generating the new UUIDs. # # @note This method should only be used for entirely machine-generated # projects, as true UUIDs are useful for tracking changes in the # project. # # @return [void] # def self.predictabilize_uuids(projects) UUIDGenerator.new(projects).generate! end public # @!group Creating objects #-------------------------------------------------------------------------# # Creates a new object with a suitable UUID. # # The object is only configured with the default values of the `:simple` # attributes, for this reason it is better to use the convenience methods # offered by the {AbstractObject} subclasses or by this class. # # @param [Class, String] klass # The concrete subclass of AbstractObject for new object or its # ISA. # # @return [AbstractObject] the new object. # def new(klass) if klass.is_a?(String) klass = Object.const_get(klass) end object = klass.new(self, generate_uuid) object.initialize_defaults object end # Generates a UUID unique for the project. # # @note UUIDs are not guaranteed to be generated unique because we need # to trim the ones generated in the xcodeproj extension. # # @note Implementation detail: as objects usually are created serially # this method creates a batch of UUID and stores the not colliding # ones, so the search for collisions with known UUIDS (a # performance bottleneck) is performed less often. # # @return [String] A UUID unique to the project. # def generate_uuid generate_available_uuid_list while @available_uuids.empty? @available_uuids.shift end # @return [Array<String>] the list of all the generated UUIDs. # # @note Used for checking new UUIDs for duplicates with UUIDs already # generated but used for objects which are not yet part of the # `objects` hash but which might be added at a later time. # attr_reader :generated_uuids # Pre-generates the given number of UUIDs. Useful for optimizing # performance when the rough number of objects that will be created is # known in advance. # # @param [Integer] count # the number of UUIDs that should be generated. # # @note This method might generated a minor number of uniques UUIDs than # the given count, because some might be duplicated a thus will be # discarded. # # @return [void] # def generate_available_uuid_list(count = 100) new_uuids = (0..count).map { SecureRandom.hex(12).upcase } uniques = (new_uuids - (@generated_uuids + uuids)) @generated_uuids += uniques @available_uuids += uniques end public # @!group Convenience accessors #-------------------------------------------------------------------------# # @return [Array<AbstractObject>] all the objects of the project. # def objects objects_by_uuid.values end # @return [Array<String>] all the UUIDs of the project. # def uuids objects_by_uuid.keys end # @return [Array<AbstractObject>] all the objects of the project with a # given ISA. # def list_by_class(klass) objects.select { |o| o.class == klass } end # @return [PBXGroup] the main top-level group. # def main_group root_object.main_group end # @return [ObjectList<PBXGroup>] a list of all the groups in the # project. # def groups main_group.groups end # Returns a group at the given subpath relative to the main group. # # @example # frameworks = project['Frameworks'] # frameworks.name #=> 'Frameworks' # main_group.children.include? frameworks #=> True # # @param [String] group_path @see MobileCoreServices # # @return [PBXGroup] the group at the given subpath. # def [](group_path) main_group[group_path] end # @return [ObjectList<PBXFileReference>] a list of all the files in the # project. # def files objects.grep(PBXFileReference) end # Returns the file reference for the given absolute path. # # @param [#to_s] absolute_path # The absolute path of the file whose reference is needed. # # @return [PBXFileReference] The file reference. # @return [Nil] If no file reference could be found. # def reference_for_path(absolute_path) absolute_pathname = Pathname.new(absolute_path) unless absolute_pathname.absolute? raise ArgumentError, "Paths must be absolute #{absolute_path}" end objects.find do |child| child.isa == 'PBXFileReference' && child.real_path == absolute_pathname end end # @return [ObjectList<AbstractTarget>] A list of all the targets in the # project. # def targets root_object.targets end # @return [ObjectList<PBXNativeTarget>] A list of all the targets in the # project excluding aggregate targets. # def native_targets root_object.targets.grep(PBXNativeTarget) end # Checks the native target for any targets in the project # that are dependent on the native target and would be # embedded in it at build time # # @param [PBXNativeTarget] native target to check for # embedded targets # # # @return [Array<PBXNativeTarget>] A list of all targets that # are embedded in the passed in target # def embedded_targets_in_native_target(native_target) native_targets.select do |target| host_targets_for_embedded_target(target).map(&:uuid).include? native_target.uuid end end # Returns the native targets, in which the embedded target is # embedded. This works by traversing the targets to find those # where the target is a dependency. # # @param [PBXNativeTarget] native target that might be embedded # in another target # # @return [Array<PBXNativeTarget>] the native targets that host the # embedded target # def host_targets_for_embedded_target(embedded_target) native_targets.select do |native_target| ((embedded_target.uuid != native_target.uuid) && (native_target.dependencies.map(&:native_target_uuid).include? embedded_target.uuid)) end end # @return [PBXGroup] The group which holds the product file references. # def products_group root_object.product_ref_group end # @return [ObjectList<PBXFileReference>] A list of the product file # references. # def products products_group.children end # @return [PBXGroup] the `Frameworks` group creating it if necessary. # def frameworks_group main_group['Frameworks'] || main_group.new_group('Frameworks') end # @return [ObjectList<XCConfigurationList>] The build configuration list of # the project. # def build_configuration_list root_object.build_configuration_list end # @return [ObjectList<XCBuildConfiguration>] A list of project wide # build configurations. # def build_configurations root_object.build_configuration_list.build_configurations end # Returns the build settings of the project wide build configuration with # the given name. # # @param [String] name # The name of a project wide build configuration. # # @return [Hash] The build settings. # def build_settings(name) root_object.build_configuration_list.build_settings(name) end public # @!group Helpers #-------------------------------------------------------------------------# # Creates a new file reference in the main group. # # @param @see PBXGroup#new_file # # @return [PBXFileReference] the new file. # def new_file(path, source_tree = :group) main_group.new_file(path, source_tree) end # Creates a new group at the given subpath of the main group. # # @param @see PBXGroup#new_group # # @return [PBXGroup] the new group. # def new_group(name, path = nil, source_tree = :group) main_group.new_group(name, path, source_tree) end # Creates a new target and adds it to the project. # # The target is configured for the given platform and its file reference it # is added to the {products_group}. # # The target is pre-populated with common build settings, and the # appropriate Framework according to the platform is added to to its # Frameworks phase. # # @param [Symbol] type # the type of target. Can be `:application`, `:framework`, # `:dynamic_library` or `:static_library`. # # @param [String] name # the name of the target product. # # @param [Symbol] platform # the platform of the target. Can be `:ios` or `:osx`. # # @param [String] deployment_target # the deployment target for the platform. # # @param [PBXGroup] product_group # the product group, where to add to a file reference of the # created target. # # @param [Symbol] language # the primary language of the target, can be `:objc` or `:swift`. # # @return [PBXNativeTarget] the target. # def new_target(type, name, platform, deployment_target = nil, product_group = nil, language = nil) product_group ||= products_group ProjectHelper.new_target(self, type, name, platform, deployment_target, product_group, language) end # Creates a new resource bundles target and adds it to the project. # # The target is configured for the given platform and its file reference it # is added to the {products_group}. # # The target is pre-populated with common build settings # # @param [String] name # the name of the resources bundle. # # @param [Symbol] platform # the platform of the resources bundle. Can be `:ios` or `:osx`. # # @return [PBXNativeTarget] the target. # def new_resources_bundle(name, platform, product_group = nil) product_group ||= products_group ProjectHelper.new_resources_bundle(self, name, platform, product_group) end # Creates a new target and adds it to the project. # # The target is configured for the given platform and its file reference it # is added to the {products_group}. # # The target is pre-populated with common build settings, and the # appropriate Framework according to the platform is added to to its # Frameworks phase. # # @param [String] name # the name of the target. # # @param [Array<AbstractTarget>] target_dependencies # targets, which should be added as dependencies. # # @param [Symbol] platform # the platform of the aggregate target. Can be `:ios` or `:osx`. # # @param [String] deployment_target # the deployment target for the platform. # # @return [PBXNativeTarget] the target. # def new_aggregate_target(name, target_dependencies = [], platform = nil, deployment_target = nil) ProjectHelper.new_aggregate_target(self, name, platform, deployment_target).tap do |aggregate_target| target_dependencies.each do |dep| aggregate_target.add_dependency(dep) end end end # Adds a new build configuration to the project and populates its with # default settings according to the provided type. # # @param [String] name # The name of the build configuration. # # @param [Symbol] type # The type of the build configuration used to populate the build # settings, must be :debug or :release. # # @return [XCBuildConfiguration] The new build configuration. # def add_build_configuration(name, type) build_configuration_list = root_object.build_configuration_list if build_configuration = build_configuration_list[name] build_configuration else build_configuration = new(XCBuildConfiguration) build_configuration.name = name common_settings = Constants::PROJECT_DEFAULT_BUILD_SETTINGS settings = ProjectHelper.deep_dup(common_settings[:all]) settings.merge!(ProjectHelper.deep_dup(common_settings[type])) build_configuration.build_settings = settings build_configuration_list.build_configurations << build_configuration build_configuration end end # Sorts the project. # # @param [Hash] options # the sorting options. # @option options [Symbol] :groups_position # the position of the groups can be either `:above` or `:below`. # # @return [void] # def sort(options = nil) root_object.sort_recursively(options) end public # @!group Schemes #-------------------------------------------------------------------------# # Get list of shared schemes in project # # @param [String] path # project path # # @return [Array] # def self.schemes(project_path) schemes = Dir[File.join(project_path, 'xcshareddata', 'xcschemes', '*.xcscheme')].map do |scheme| File.basename(scheme, '.xcscheme') end schemes << File.basename(project_path, '.xcodeproj') if schemes.empty? schemes end # Recreates the user schemes of the project from scratch (removes the # folder) and optionally hides them. # # @param [Bool] visible # Whether the schemes should be visible or hidden. # # @return [void] # def recreate_user_schemes(visible = true) schemes_dir = XCScheme.user_data_dir(path) FileUtils.rm_rf(schemes_dir) FileUtils.mkdir_p(schemes_dir) xcschememanagement = {} xcschememanagement['SchemeUserState'] = {} xcschememanagement['SuppressBuildableAutocreation'] = {} targets.each do |target| scheme = XCScheme.new test_target = target if target.respond_to?(:test_target_type?) && target.test_target_type? launch_target = target.respond_to?(:launchable_target_type?) && target.launchable_target_type? scheme.configure_with_targets(target, test_target, :launch_target => launch_target) yield scheme, target if block_given? scheme.save_as(path, target.name, false) xcschememanagement['SchemeUserState']["#{target.name}.xcscheme"] = {} xcschememanagement['SchemeUserState']["#{target.name}.xcscheme"]['isShown'] = visible end xcschememanagement_path = schemes_dir + 'xcschememanagement.plist' Plist.write_to_path(xcschememanagement, xcschememanagement_path) end #-------------------------------------------------------------------------# end
treeder/quicky
lib/quicky/results_hash.rb
Quicky.ResultsHash.to_hash
ruby
def to_hash ret = {} self.each_pair do |k, v| ret[k] = v.to_hash() end ret end
returns results in a straight up hash.
train
https://github.com/treeder/quicky/blob/4ac89408c28ca04745280a4cef2db4f97ed5b6d2/lib/quicky/results_hash.rb#L6-L12
class ResultsHash < Hash # returns results in a straight up hash. # if given the same results from to_hash, this will recreate the ResultsHash def self.from_hash(h) rh = ResultsHash.new h.each_pair do |k, v| rh[k] = TimeCollector.from_hash(v) end rh end # merges multiple ResultsHash's def merge!(rh) rh.each_pair do |k, v| # v is a TimeCollector if self.has_key?(k) self[k].merge!(v) else self[k] = v end end end end
iyuuya/jkf
lib/jkf/parser/ki2.rb
Jkf::Parser.Ki2.transform_fugou
ruby
def transform_fugou(pl, pi, sou, dou, pro, da) ret = { "piece" => pi } if pl["same"] ret["same"] = true else ret["to"] = pl end ret["promote"] = (pro == "成") if pro if da ret["relative"] = "H" else rel = soutai2relative(sou) + dousa2relative(dou) ret["relative"] = rel unless rel.empty? end ret end
transfrom fugou to jkf
train
https://github.com/iyuuya/jkf/blob/4fd229c50737cab7b41281238880f1414e55e061/lib/jkf/parser/ki2.rb#L373-L388
class Ki2 < Base include Kifuable protected # kifu : header* initialboard? header* moves fork* def parse_root s0 = @current_pos s1 = [] s2 = parse_header while s2 != :failed s1 << s2 s2 = parse_header end if s1 != :failed s2 = parse_initialboard s2 = nil if s2 == :failed s3 = [] s4 = parse_header while s4 != :failed s3 << s4 s4 = parse_header end s4 = parse_moves if s4 != :failed s5 = [] s6 = parse_fork while s6 != :failed s5 << s6 s6 = parse_fork end @reported_pos = s0 s0 = transform_root(s1, s2, s3, s4, s5) else @current_pos = s0 s0 = :failed end else @current_pos = s0 s0 = :failed end s0 end # header : [^:\r\n]+ ":" nonls nl+ | header_teban def parse_header s0 = @current_pos s2 = match_regexp(/^[^*:\r\n]/) if s2 != :failed s1 = [] while s2 != :failed s1 << s2 s2 = match_regexp(/^[^:\r\n]/) end else s1 = :failed end if s1 != :failed if match_str(":") != :failed s3 = parse_nonls s5 = parse_nl if s5 != :failed s4 = [] while s5 != :failed s4 << s5 s5 = parse_nl end else s4 = :failed end if s4 != :failed @reported_pos = s0 s0 = { "k" => s1.join, "v" => s3.join } else @current_pos = s0 s0 = :failed end else @current_pos = s0 s0 = :failed end else @current_pos = s0 s0 = :failed end s0 = parse_header_teban if s0 == :failed s0 end # header_teban : [先後上下] "手番" nl def parse_header_teban s0 = @current_pos s1 = parse_turn if s1 != :failed s2 = match_str("手番") if s2 != :failed s3 = parse_nl if s3 != :failed @reported_pos = s0 { "k" => "手番", "v" => s1 } else @current_pos = s0 :failed end else @current_pos = s0 :failed end else @current_pos = s0 :failed end end # moves : firstboard : move* result? def parse_moves s0 = @current_pos s1 = parse_firstboard if s1 != :failed s2 = [] s3 = parse_move while s3 != :failed s2 << s3 s3 = parse_move end s3 = parse_result s3 = nil if s3 == :failed @reported_pos = s0 s0 = -> (hd, tl, res) do tl.unshift(hd) tl << { "special" => res } if res && !tl[tl.length - 1]["special"] tl end.call(s1, s2, s3) else @current_pos = s0 s0 = :failed end s0 end # firstboard : comment* pointer? def parse_firstboard s0 = @current_pos s1 = [] s2 = parse_comment while s2 != :failed s1 << s2 s2 = parse_comment end parse_pointer @reported_pos = s0 s0 = s1.empty? ? {} : { "comments" => s1 } s0 end # move : line comment* pointer? (nl | " ")* def parse_move s0 = @current_pos s1 = parse_line if s1 != :failed s2 = [] s3 = parse_comment while s3 != :failed s2 << s3 s3 = parse_comment end parse_pointer s4 = [] s5 = parse_nl s5 = match_space if s5 == :failed while s5 != :failed s4 << s5 s5 = parse_nl s5 = match_space if s5 == :failed end @reported_pos = s0 s0 = -> (line, c) do ret = { "move" => line } ret["comments"] = c if !c.empty? ret end.call(s1, s2) else @current_pos = s0 s0 = :failed end s0 end # line : [▲△] fugou (nl / " ")* def parse_line s0 = @current_pos s1 = match_regexp(/^[▲△]/) if s1 != :failed s1 = if s1 == "▲" { "color" => 0 } else { "color" => 1 } end s2 = parse_fugou if s2 != :failed s3 = [] s4 = parse_nl s4 = match_space if s4 == :failed while s4 != :failed s3 << s4 s4 = parse_nl s4 = match_space if s4 == :failed end @reported_pos = s0 s0 = s2.merge(s1) else @current_pos = s0 s0 = :failed end else @current_pos = s0 s0 = :failed end s0 end # fugou : place piece soutai? dousa? ("成" | "不成")? "打"? def parse_fugou s0 = @current_pos s1 = parse_place if s1 != :failed s2 = parse_piece if s2 != :failed s3 = parse_soutai s3 = nil if s3 == :failed s4 = parse_dousa s4 = nil if s4 == :failed s5 = match_str("成") s5 = match_str("不成") if s5 == :failed s5 = nil if s5 == :failed s6 = match_str("打") s6 = nil if s6 == :failed @reported_pos = s0 transform_fugou(s1, s2, s3, s4, s5, s6) else @current_pos = s0 :failed end else @current_pos = s0 :failed end end # place : num numkan def parse_place s0 = @current_pos s1 = parse_num if s1 != :failed s2 = parse_numkan if s2 != :failed @reported_pos = s0 s0 = { "x" => s1, "y" => s2 } else @current_pos = s0 s0 = :failed end else @current_pos = s0 s0 = :failed end if s0 == :failed s0 = @current_pos if match_regexp("同") != :failed match_str(" ") @reported_pos = s0 s0 = { "same" => true } else @current_pos = s0 s0 = :failed end end s0 end # soutai : [左直右] def parse_soutai match_regexp(/^[左直右]/) end # dousa : [上寄引] def parse_dousa match_regexp(/^[上寄引]/) end # "*" nonls nl def parse_comment s0 = @current_pos if match_str("*") != :failed s2 = parse_nonls if parse_nl != :failed @reported_pos = s0 s0 = s2.join else @current_pos = s0 s0 = :failed end else @current_pos = s0 s0 = :failed end s0 end # fork : "変化:" " "* [0-9]+ "手" nl moves def parse_fork s0 = @current_pos if match_str("変化:") != :failed match_spaces s3 = match_digits! if s3 != :failed if match_str("手") != :failed if parse_nl != :failed s6 = parse_moves if s6 != :failed @reported_pos = s0 s0 = { "te" => s3.join.to_i, "moves" => s6[1..-1] } else @current_pos = s0 s0 = :failed end else @current_pos = s0 s0 = :failed end else @current_pos = s0 s0 = :failed end else @current_pos = s0 s0 = :failed end else @current_pos = s0 s0 = :failed end s0 end # turn : [先後上下] def parse_turn match_regexp(/^[先後上下]/) end # transform to jkf def transform_root(headers, ini, headers2, moves, forks) ret = { "header" => {}, "moves" => moves } headers.compact.each { |h| ret["header"][h["k"]] = h["v"] } headers2.compact.each { |h| ret["header"][h["k"]] = h["v"] } if ini ret["initial"] = ini elsif ret["header"]["手合割"] preset = preset2str(ret["header"]["手合割"]) ret["initial"] = { "preset" => preset } if preset != "OTHER" end transform_root_header_data(ret) if ret["initial"] && ret["initial"]["data"] transform_root_forks(forks, moves) ret end # transfrom fugou to jkf # relative string to jkf def soutai2relative(str) { "左" => "L", "直" => "C", "右" => "R" }[str] || "" end # movement string to jkf def dousa2relative(str) { "上" => "U", "寄" => "M", "引" => "D" }[str] || "" end # generate motigoma def make_hand(str) ret = { "FU" => 0, "KY" => 0, "KE" => 0, "GI" => 0, "KI" => 0, "KA" => 0, "HI" => 0 } return ret if str.empty? str.gsub(/ $/, "").split(" ").each do |kind| next if kind.empty? ret[kind2csa(kind[0])] = kind.length == 1 ? 1 : kan2n2(kind[1..-1]) end ret end # check eos def eos? @input[@current_pos].nil? end end
mailgun/mailgun-ruby
lib/mailgun/messages/message_builder.rb
Mailgun.MessageBuilder.add_file
ruby
def add_file(disposition, filedata, filename) attachment = File.open(filedata, 'r') if filedata.is_a?(String) attachment = filedata.dup unless attachment fail(Mailgun::ParameterError, 'Unable to access attachment file object.' ) unless attachment.respond_to?(:read) unless filename.nil? attachment.instance_variable_set :@original_filename, filename attachment.instance_eval 'def original_filename; @original_filename; end' end set_multi_complex(disposition, attachment) end
Private: Adds a file to the message. @param [Symbol] disposition The type of file: :attachment or :inline @param [String|File] attachment A file object for attaching as an attachment. @param [String] filename The filename you wish the attachment to be. @return [void] Returns nothing
train
https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/messages/message_builder.rb#L404-L417
class MessageBuilder attr_reader :message, :counters # Public: Creates a new MessageBuilder object. def initialize @message = Hash.new { |hash, key| hash[key] = [] } @counters = { recipients: { to: 0, cc: 0, bcc: 0 }, attributes: { attachment: 0, campaign_id: 0, custom_option: 0, tag: 0 } } end # Adds a specific type of recipient to the message object. # # WARNING: Setting 'h:reply-to' with add_recipient() is deprecated! Use 'reply_to' instead. # # @param [String] recipient_type The type of recipient. "to", "cc", "bcc" or "h:reply-to". # @param [String] address The email address of the recipient to add to the message object. # @param [Hash] variables A hash of the variables associated with the recipient. We recommend "first" and "last" at a minimum! # @return [void] def add_recipient(recipient_type, address, variables = nil) if recipient_type == "h:reply-to" warn 'DEPRECATION: "add_recipient("h:reply-to", ...)" is deprecated. Please use "reply_to" instead.' return reply_to(address, variables) end if (@counters[:recipients][recipient_type] || 0) >= Mailgun::Chains::MAX_RECIPIENTS fail Mailgun::ParameterError, 'Too many recipients added to message.', address end compiled_address = parse_address(address, variables) set_multi_complex(recipient_type, compiled_address) @counters[:recipients][recipient_type] += 1 if @counters[:recipients].key?(recipient_type) end # Sets the from address for the message # # @param [String] address The address of the sender. # @param [Hash] variables A hash of the variables associated with the recipient. We recommend "first" and "last" at a minimum! # @return [void] def from(address, vars = nil) add_recipient(:from, address, vars) end # Deprecated: please use 'from' instead. def set_from_address(address, variables = nil) warn 'DEPRECATION: "set_from_address" is deprecated. Please use "from" instead.' from(address, variables) end # Set the message's Reply-To address. # # Rationale: According to RFC, only one Reply-To address is allowed, so it # is *okay* to bypass the set_multi_simple and set reply-to directly. # # @param [String] address The email address to provide as Reply-To. # @param [Hash] variables A hash of variables associated with the recipient. # @return [void] def reply_to(address, variables = nil) compiled_address = parse_address(address, variables) header("reply-to", compiled_address) end # Set a subject for the message object # # @param [String] subject The subject for the email. # @return [void] def subject(subj = nil) set_multi_simple(:subject, subj) end # Deprecated: Please use "subject" instead. def set_subject(subj = nil) warn 'DEPRECATION: "set_subject" is deprecated. Please use "subject" instead.' subject(subj) end # Set a text body for the message object # # @param [String] text_body The text body for the email. # @return [void] def body_text(text_body = nil) set_multi_simple(:text, text_body) end # Deprecated: Please use "body_text" instead. def set_text_body(text_body = nil) warn 'DEPRECATION: "set_text_body" is deprecated. Please use "body_text" instead.' body_text(text_body) end # Set a html body for the message object # # @param [String] html_body The html body for the email. # @return [void] def body_html(html_body = nil) set_multi_simple(:html, html_body) end # Deprecated: Please use "body_html" instead. def set_html_body(html_body = nil) warn 'DEPRECATION: "set_html_body" is deprecated. Please use "body_html" instead.' body_html(html_body) end # Adds a series of attachments, when called upon. # # @param [String|File] attachment A file object for attaching as an attachment. # @param [String] filename The filename you wish the attachment to be. # @return [void] def add_attachment(attachment, filename = nil) add_file(:attachment, attachment, filename) end # Adds an inline image to the mesage object. # # @param [String|File] inline_image A file object for attaching an inline image. # @param [String] filename The filename you wish the inline image to be. # @return [void] def add_inline_image(inline_image, filename = nil) add_file(:inline, inline_image, filename) end # Adds a List-Unsubscribe for the message header. # # @param [Array<String>] *variables Any number of url or mailto # @return [void] def list_unsubscribe(*variables) set_single('h:List-Unsubscribe', variables.map { |var| "<#{var}>" }.join(',')) end # Send a message in test mode. (The message won't really be sent to the recipient) # # @param [Boolean] mode The boolean or string value (will fix itself) # @return [void] def test_mode(mode) set_multi_simple('o:testmode', bool_lookup(mode)) end # Deprecated: 'set_test_mode' is depreciated. Please use 'test_mode' instead. def set_test_mode(mode) warn 'DEPRECATION: "set_test_mode" is deprecated. Please use "test_mode" instead.' test_mode(mode) end # Turn DKIM on or off per message # # @param [Boolean] mode The boolean or string value(will fix itself) # @return [void] def dkim(mode) set_multi_simple('o:dkim', bool_lookup(mode)) end # Deprecated: 'set_dkim' is deprecated. Please use 'dkim' instead. def set_dkim(mode) warn 'DEPRECATION: "set_dkim" is deprecated. Please use "dkim" instead.' dkim(mode) end # Add campaign IDs to message. Limit of 3 per message. # # @param [String] campaign_id A defined campaign ID to add to the message. # @return [void] def add_campaign_id(campaign_id) fail(Mailgun::ParameterError, 'Too many campaigns added to message.', campaign_id) if @counters[:attributes][:campaign_id] >= Mailgun::Chains::MAX_CAMPAIGN_IDS set_multi_complex('o:campaign', campaign_id) @counters[:attributes][:campaign_id] += 1 end # Add tags to message. Limit of 3 per message. # # @param [String] tag A defined campaign ID to add to the message. # @return [void] def add_tag(tag) if @counters[:attributes][:tag] >= Mailgun::Chains::MAX_TAGS fail Mailgun::ParameterError, 'Too many tags added to message.', tag end set_multi_complex('o:tag', tag) @counters[:attributes][:tag] += 1 end # Turn Open Tracking on and off, on a per message basis. # # @param [Boolean] tracking Boolean true or false. # @return [void] def track_opens(mode) set_multi_simple('o:tracking-opens', bool_lookup(mode)) end # Deprecated: 'set_open_tracking' is deprecated. Please use 'track_opens' instead. def set_open_tracking(tracking) warn 'DEPRECATION: "set_open_tracking" is deprecated. Please use "track_opens" instead.' track_opens(tracking) end # Turn Click Tracking on and off, on a per message basis. # # @param [String] mode True, False, or HTML (for HTML only tracking) # @return [void] def track_clicks(mode) set_multi_simple('o:tracking-clicks', bool_lookup(mode)) end # Depreciated: 'set_click_tracking. is deprecated. Please use 'track_clicks' instead. def set_click_tracking(tracking) warn 'DEPRECATION: "set_click_tracking" is deprecated. Please use "track_clicks" instead.' track_clicks(tracking) end # Enable Delivery delay on message. Specify an RFC2822 date, and Mailgun # will not deliver the message until that date/time. For conversion # options, see Ruby "Time". Example: "October 25, 2013 10:00PM CST" will # be converted to "Fri, 25 Oct 2013 22:00:00 -0600". # # @param [String] timestamp A date and time, including a timezone. # @return [void] def deliver_at(timestamp) time_str = DateTime.parse(timestamp) set_multi_simple('o:deliverytime', time_str.rfc2822) end # Deprecated: 'set_delivery_time' is deprecated. Please use 'deliver_at' instead. def set_delivery_time(timestamp) warn 'DEPRECATION: "set_delivery_time" is deprecated. Please use "deliver_at" instead.' deliver_at timestamp end # Add custom data to the message. The data should be either a hash or JSON # encoded. The custom data will be added as a header to your message. # # @param [string] name A name for the custom data. (Ex. X-Mailgun-<Name of Data>: {}) # @param [Hash] data Either a hash or JSON string. # @return [void] def header(name, data) fail(Mailgun::ParameterError, 'Header name for message must be specified') if name.to_s.empty? begin jsondata = make_json data set_single("h:#{name}", jsondata) rescue Mailgun::ParameterError set_single("h:#{name}", data) end end # Deprecated: 'set_custom_data' is deprecated. Please use 'header' instead. def set_custom_data(name, data) warn 'DEPRECATION: "set_custom_data" is deprecated. Please use "header" instead.' header name, data end # Attaches custom JSON data to the message. See the following doc page for more info. # https://documentation.mailgun.com/user_manual.html#attaching-data-to-messages # # @param [String] name A name for the custom variable block. # @param [String|Hash] data Either a string or a hash. If it is not valid JSON or # can not be converted to JSON, ParameterError will be raised. # @return [void] def variable(name, data) fail(Mailgun::ParameterError, 'Variable name must be specified') if name.to_s.empty? jsondata = make_json data set_single("v:#{name}", jsondata) end # Add custom parameter to the message. A custom parameter is any parameter that # is not yet supported by the SDK, but available at the API. Note: No validation # is performed. Don't forget to prefix the parameter with o, h, or v. # # @param [string] name A name for the custom parameter. # @param [string] data A string of data for the parameter. # @return [void] def add_custom_parameter(name, data) set_multi_complex(name, data) end # Set the Message-Id header to a custom value. Don't forget to enclose the # Message-Id in angle brackets, and ensure the @domain is present. Doesn't # use simple or complex setters because it should not set value in an array. # # @param [string] data A string of data for the parameter. Passing nil or # empty string will delete h:Message-Id key and value from @message hash. # @return [void] def message_id(data = nil) key = 'h:Message-Id' return @message.delete(key) if data.to_s.empty? set_single(key, data) end # Deprecated: 'set_message_id' is deprecated. Use 'message_id' instead. def set_message_id(data = nil) warn 'DEPRECATION: "set_message_id" is deprecated. Please use "message_id" instead.' message_id data end private # Sets a single value in the message hash where "multidict" features are not needed. # Does *not* permit duplicate params. # # @param [String] parameter The message object parameter name. # @param [String] value The value of the parameter. # @return [void] def set_single(parameter, value) @message[parameter] = value ? value : '' end # Sets values within the multidict, however, prevents # duplicate values for keys. # # @param [String] parameter The message object parameter name. # @param [String] value The value of the parameter. # @return [void] def set_multi_simple(parameter, value) @message[parameter] = value ? [value] : [''] end # Sets values within the multidict, however, allows # duplicate values for keys. # # @param [String] parameter The message object parameter name. # @param [String] value The value of the parameter. # @return [void] def set_multi_complex(parameter, value) @message[parameter] << (value || '') end # Converts boolean type to string # # @param [String] value The item to convert # @return [void] def bool_lookup(value) return 'yes' if %w(true yes yep).include? value.to_s.downcase return 'no' if %w(false no nope).include? value.to_s.downcase value end # Validates whether the input is JSON. # # @param [String] json_ The suspected JSON string. # @return [void] def valid_json?(json_) JSON.parse(json_) return true rescue JSON::ParserError false end # Private: given an object attempt to make it into JSON # # obj - an object. Hopefully a JSON string or Hash # # Returns a JSON object or raises ParameterError def make_json(obj) return JSON.parse(obj).to_json if obj.is_a?(String) return obj.to_json if obj.is_a?(Hash) return JSON.generate(obj).to_json rescue raise Mailgun::ParameterError, 'Provided data could not be made into JSON. Try a JSON string or Hash.', obj end # Parses the address and gracefully handles any # missing parameters. The result should be something like: # "'First Last' <person@domain.com>" # # @param [String] address The email address to parse. # @param [Hash] variables A list of recipient variables. # @return [void] def parse_address(address, vars) return address unless vars.is_a? Hash fail(Mailgun::ParameterError, 'Email address not specified') unless address.is_a? String if vars['full_name'] != nil && (vars['first'] != nil || vars['last'] != nil) fail(Mailgun::ParameterError, 'Must specify at most one of full_name or first/last. Vars passed: #{vars}') end if vars['full_name'] full_name = vars['full_name'] elsif vars['first'] || vars['last'] full_name = "#{vars['first']} #{vars['last']}".strip end return "'#{full_name}' <#{address}>" if defined?(full_name) address end # Private: Adds a file to the message. # # @param [Symbol] disposition The type of file: :attachment or :inline # @param [String|File] attachment A file object for attaching as an attachment. # @param [String] filename The filename you wish the attachment to be. # @return [void] # # Returns nothing end
zhimin/rwebspec
lib/rwebspec-watir/driver.rb
RWebSpec.Driver.take_screenshot
ruby
def take_screenshot(to_file = nil, opts = {}) # puts "calling new take screenshot: #{$screenshot_supported}" # unless $screenshot_supported # puts " [WARN] Screenhost not supported, check whether win32screenshot gem is installed" # return # end if to_file screenshot_image_filepath = to_file else screenshot_image_filename = "screenshot_" + Time.now.strftime("%m%d%H%M%S") + ".jpg" the_dump_dir = opts[:to_dir] || default_dump_dir FileUtils.mkdir_p(the_dump_dir) unless File.exists?(the_dump_dir) screenshot_image_filepath = File.join(the_dump_dir, screenshot_image_filename) screenshot_image_filepath.gsub!("/", "\\") if is_windows? FileUtils.rm_f(screenshot_image_filepath) if File.exist?(screenshot_image_filepath) end begin if is_firefox? then Win32::Screenshot::Take.of(:window, :title => /mozilla\sfirefox/i).write(screenshot_image_filepath) elsif ie Win32::Screenshot::Take.of(:window, :title => /internet\sexplorer/i).write(screenshot_image_filepath) else Win32::Screenshot::Take.of(:foreground).write(screenshot_image_filepath) end notify_screenshot_location(screenshot_image_filepath) rescue ::DL::DLTypeError => de puts "No screenshot libray found: #{de}" rescue => e puts "error on taking screenshot: #{e}" end end
TODO: Common driver module => this is shared by both Watir and Selenium TODO: Common driver module => this is shared by both Watir and Selenium use win32screenshot library or Selenium to save curernt active window opts[:to_dir] => the direcotry to save image under
train
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-watir/driver.rb#L783-L818
module Driver include RWebSpec::TestWisePlugin include RWebSpec::Popup # open a browser, and set base_url via hash, but does not acually # # example: # open_browser :base_url => http://localhost:8080 # # There are 3 ways to set base url # 1. pass as first argument # 2. If running using TestWise, used as confiured # 3. Use default value set def open_browser_by_watir(options = {}) begin support_unicode rescue => e puts "Unicode may not work in IE, #{e}" end if options && options.class == String options = {:base_url => options.to_s } end if options && options.class == Hash && options[:base_url] base_url ||= options[:base_url] end base_url = options[:base_url] rescue nil base_url ||= $TESTWISE_PROJECT_BASE_URL base_url ||= $BASE_URL raise "base_url must be set" if base_url.nil? default_options = {:speed => "fast", :visible => true, :highlight_colour => 'yellow', :close_others => true, :start_new => false, # start a new browser always :go => true} options = default_options.merge options ($TESTWISE_HIDE_BROWSER) ? $HIDE_IE = true : $HIDE_IE = false if base_url =~ /^file:/ uri_base = base_url else uri = URI.parse(base_url) uri_base = "#{uri.scheme}://#{uri.host}:#{uri.port}" end if options[:start_new] @web_browser = WebBrowser.new(uri_base, nil, options) else @web_browser = WebBrowser.reuse(uri_base, options) # Reuse existing browser end if base_url =~ /^file:/ goto_url(base_url) # for files, no base url else (uri.path.length == 0) ? begin_at("/") : begin_at(uri.path) if options[:go] end return @web_browser end # return the underlying RWebSpec::Browser object def browser @web_browser end # Close the current browser window (started by the script). If no browser started, then close # all browser windows. # def close_browser if @web_browser # Old TestWise version # @web_browser.close_browser unless $TESTWISE_LEAVE_BROWSER_OPEN_AFTER_RUN @web_browser.close_browser else close_all_browsers end end alias close_ie close_browser # Close all opening browser windows # def close_all_browsers @web_browser.close_all_browsers end # Verify the next page following an operation. # # Typical usage: # login_page.click_login # expect_page HomePage def expect_page(page_clazz, argument = nil) if argument @web_browser.expect_page(page_clazz, argument) else @web_browser.expect_page(page_clazz) end end def context @web_browser.context end # Starting browser with a URL # # Example: # begin_at("http://www.itest2.com") def begin_at(url) dump_caller_stack @web_browser.begin_at(url) end # Return the Watir::IE instance # def ie @web_browser.ie end # Return the FireWatir::Firefox instance # def firefox @web_browser.firefox end def is_firefox? @web_browser.is_firefox? if @web_browser end # Go to another page on the testing site. # # open_browser(:base_url => "http://www.itest2.com") # goto_page("/demo") # visit page http://www.itest2.com/demo # def goto_page(page) perform_operation { @web_browser.goto_page(page) if @web_browser } end alias visit goto_page # Go to another web site, normally different site being tested on # # open_browser(:base_url => "http://www.itest2.com") # goto_url("http://myorganized.info") def goto_url(url) @web_browser.goto_url url end # Go to specific url in background (i.e not via browwser, different from goto_url) # This won't share the session with what's currenlty in browser, proxy setting # # One use example: resetting database # background_visit("/reset") # def background_visit(url, opts = {}) require 'httpclient' begin client = HTTPClient.new if url && url =~ /^http/ http_response = client.get(url).body else base_url = $TESTWISE_PROJECT_BASE_URL || $TESTWISE_PROJECT_BASE_URL || $BASE_URL http_response = client.get("#{base_url}#{url}").body end http_response = http_response.content if http_response.respond_to?("content") rescue => e raise e end end # Attach to existing browser window # # attach_browser(:title, "Page" ) # attach_browser(:url, "http://wwww..." ) def attach_browser(how, what, options = {}) options.merge!(:browser => is_firefox? ? "Firefox" : "IE") unless options[:browser] begin options.merge!(:base_url => browser.context.base_url) rescue => e puts "failed to set base_url, ignore : #{e}" end WebBrowser.attach_browser(how, what, options) end # Reuse current an opened browser window instead of opening a new one # example: # use_current_watir_browser(:title, /.*/) # use what ever browser window # use_current_watir_browser(:title, "TestWise") # use browser window with title "TestWise" def use_current_watir_browser(how = :title, what = /.*/) @web_browser = WebBrowser.attach_browser(how, what) end ## # Delegate to WebTester # # Note: # label(:id, "abc") # OK # label(:id, :abc) # Error # # Depends on which object type, you can use following attribute # More details: http://wiki.openqa.org/display/WTR/Methods+supported+by+Element # # :id Used to find an element that has an "id=" attribute. Since each id should be unique, according to the XHTML specification, this is recommended as the most reliable method to find an object. * # :name Used to find an element that has a "name=" attribute. This is useful for older versions of HTML, but "name" is deprecated in XHTML. * # :value Used to find a text field with a given default value, or a button with a given caption, or a text field # :text Used for links, spans, divs and other element that contain text. # :index Used to find the nth element of the specified type on a page. For example, button(:index, 2) finds the second button. Current versions of WATIR use 1-based indexing, but future versions will use 0-based indexing. # :class Used for an element that has a "class=" attribute. # :title Used for an element that has a "title=" attribute. # :xpath Finds the item using xpath query. # :method Used only for forms, the method attribute of a form is either GET or POST. # :action Used only for form elements, specifies the URL where the form is to be submitted. # :href Used to identify a link by its "href=" attribute. # :src Used to identify an image by its URL. # # area <area> tags # button <input> tags with type=button, submit, image or reset # check_box <input> tags with type=checkbox # div <div> tags # form <form> tags # frame frames, including both the <frame> elements and the corresponding pages # h1 - h6 <h1>, <h2>, <h3>, <h4>, <h5>, <h6> tags # hidden <input> tags with type=hidden # image <img> tags # label <label> tags (including "for" attribute) # li <li> tags # link <a> (anchor) tags # map <map> tags # radio <input> tags with the type=radio; known as radio buttons # select_list <select> tags, known as drop-downs or drop-down lists # span <span> tags # table <table> tags, including row and cell methods for accessing nested elements # text_field <input> tags with the type=text (single-line), type=textarea (multi-line), and type=password # p <p> (paragraph) tags, because [:area, :button, :td, :checkbox, :div, :form, :frame, :h1, :h2, :h3, :h4, :h5, :h6, :hidden, :image, :li, :link, :map, :pre, :tr, :radio, :select_list, :span, :table, :text_field, :paragraph, :file_field, :label].each do |method| define_method method do |* args| perform_operation { @web_browser.send(method, * args) if @web_browser } end end alias cell td alias check_box checkbox # seems watir doc is wrong, checkbox not check_box alias row tr alias a link alias img image [:back, :forward, :refresh, :execute_script].each do |method| define_method(method) do perform_operation { @web_browser.send(method) if @web_browser } end end alias refresh_page refresh alias go_back back alias go_forward forward [:images, :links, :buttons, :select_lists, :checkboxes, :radios, :text_fields, :divs, :dls, :dds, :dts, :ems, :lis, :maps, :spans, :strongs, :ps, :pres, :labels, :tds, :trs].each do |method| define_method method do perform_operation { @web_browser.send(method) if @web_browser } end end alias as links alias rows trs alias cells tds alias imgs images # Check one or more checkboxes with same name, can accept a string or an array of string as values checkbox, pass array as values will try to set mulitple checkboxes. # # page.check_checkbox('bad_ones', 'Chicken Little') # page.check_checkbox('good_ones', ['Cars', 'Toy Story']) # [:set_form_element, :click_link_with_text, :click_link_with_id, :submit, :click_button_with_id, :click_button_with_name, :click_button_with_caption, :click_button_with_value, :click_radio_option, :clear_radio_option, :check_checkbox, :uncheck_checkbox, :select_option, :element].each do |method| define_method method do |* args| perform_operation { @web_browser.send(method, * args) if @web_browser } end end alias enter_text set_form_element alias set_hidden_field set_form_element alias click_link click_link_with_text alias click_button_with_text click_button_with_caption alias click_button click_button_with_caption alias click_radio_button click_radio_option alias clear_radio_button clear_radio_option # for text field can be easier to be identified by attribute "id" instead of "name", not recommended though # # params opts takes :appending => true or false, if true, won't clear the text field. def enter_text_with_id(textfield_id, value, opts = {}) # For IE10, it seems unable to identify HTML5 elements # # However for IE10, the '.' is omitted. if opts.nil? || opts.empty? # for Watir, default is clear opts[:appending] = false end perform_operation { begin text_field(:id, textfield_id).set(value) rescue => e # However, this approach is not reliable with Watir (IE) # for example, for entering email, the dot cannot be entered, try ["a@b", :decimal, "com"] the_elem = element(:xpath, "//input[@id='#{textfield_id}']") the_elem.send_keys(:clear) unless opts[:appending] the_elem.send_keys(value) end } end def perform_operation(& block) begin dump_caller_stack operation_delay yield rescue RuntimeError => re raise re # ensure # puts "[DEBUG] ensure #{perform_ok}" unless perform_ok end end def contains_text(text) @web_browser.contains_text(text) end # In pages, can't use include, text.should include("abc") won't work # Instead, # text.should contains("abc" def contains(str) ContainsText.new(str) end alias contain contains # Click image buttion with image source name # # For an image submit button <input name="submit" type="image" src="/images/search_button.gif"> # click_button_with_image("search_button.gif") def click_button_with_image_src_contains(image_filename) perform_operation { found = nil raise "no buttons in this page" if buttons.length <= 0 buttons.each { |btn| if btn && btn.src && btn.src.include?(image_filename) then found = btn break end } raise "not image button with src: #{image_filename} found" if found.nil? found.click } end alias click_button_with_image click_button_with_image_src_contains def new_popup_window(options) @web_browser.new_popup_window(options) end # Warning: this does not work well with Firefox yet. def element_text(elem_id) @web_browser.element_value(elem_id) end # Identify DOM element by ID # Warning: it is only supported on IE def element_by_id(elem_id) @web_browser.element_by_id(elem_id) end # --- # For debugging # --- def dump_response(stream = nil) @web_browser.dump_response(stream) end def default_dump_dir if ($TESTWISE_RUNNING_SPEC_ID && $TESTWISE_WORKING_DIR) || ($TESTWISE_RUNNING_SPEC_ID && $TESTWISE_WORKING_DIR) $TESTWISE_DUMP_DIR = $TESTWISE_DUMP_DIR = File.join($TESTWISE_WORKING_DIR, "dump") FileUtils.mkdir($TESTWISE_DUMP_DIR) unless File.exists?($TESTWISE_DUMP_DIR) spec_run_id = $TESTWISE_RUNNING_SPEC_ID || $TESTWISE_RUNNING_SPEC_ID spec_run_dir_name = spec_run_id.to_s.rjust(4, "0") unless spec_run_id == "unknown" to_dir = File.join($TESTWISE_DUMP_DIR, spec_run_dir_name) else to_dir = ENV['TEMP_DIR'] || (is_windows? ? "C:\\temp" : "/tmp") end end # For current page souce to a file in specified folder for inspection # # save_current_page(:dir => "C:\\mysite", filename => "abc", :replacement => true) def save_current_page(options = {}) default_options = {:replacement => true} options = default_options.merge(options) to_dir = options[:dir] || default_dump_dir if options[:filename] file_name = options[:filename] else file_name = Time.now.strftime("%m%d%H%M%S") + ".html" end Dir.mkdir(to_dir) unless File.exists?(to_dir) file = File.join(to_dir, file_name) content = page_source base_url = @web_browser.context.base_url current_url = @web_browser.url current_url =~ /(.*\/).*$/ current_url_parent = $1 if options[:replacement] && base_url =~ /^http:/ File.new(file, "w").puts absolutize_page_nokogiri(content, base_url, current_url_parent) else File.new(file, "w").puts content end end # Return page HTML with absolute references of images, stylesheets and javascripts # def absolutize_page(content, base_url, current_url_parent) modified_content = "" content.each_line do |line| if line =~ /<script\s+.*src=["'']?(.*)["'].*/i then script_src = $1 substitute_relative_path_in_src_line(line, script_src, base_url, current_url_parent) elsif line =~ /<link\s+.*href=["'']?(.*)["'].*/i then link_href = $1 substitute_relative_path_in_src_line(line, link_href, base_url, current_url_parent) elsif line =~ /<img\s+.*src=["'']?(.*)["'].*/i then img_src = $1 substitute_relative_path_in_src_line(line, img_src, base_url, current_url_parent) end modified_content += line end return modified_content end # absolutize_page using hpricot # def absolutize_page_hpricot(content, base_url, parent_url) return absolutize_page(content, base_url, parent_url) if RUBY_PLATFORM == 'java' begin require 'hpricot' doc = Hpricot(content) base_url.slice!(-1) if ends_with?(base_url, "/") (doc/'link').each { |e| e['href'] = absolutify_url(e['href'], base_url, parent_url) || "" } (doc/'img').each { |e| e['src'] = absolutify_url(e['src'], base_url, parent_url) || "" } (doc/'script').each { |e| e['src'] = absolutify_url(e['src'], base_url, parent_url) || "" } return doc.to_html rescue => e absolutize_page(content, base_url, parent_url) end end def absolutize_page_nokogiri(content, base_url, parent_url) return absolutize_page(content, base_url, parent_url) if RUBY_PLATFORM == 'java' begin require 'nokogiri' doc = Nokogiri::HTML(content) base_url.slice!(-1) if ends_with?(base_url, "/") (doc/'link').each { |e| e['href'] = absolutify_url(e['href'], base_url, parent_url) || "" } (doc/'img').each { |e| e['src'] = absolutify_url(e['src'], base_url, parent_url) || "" } (doc/'script').each { |e| e['src'] = absolutify_url(e['src'], base_url, parent_url) || "" } return doc.to_html rescue => e absolutize_page(content, base_url, parent_url) end end ## # change # <script type="text/javascript" src="/javascripts/prototype.js"></script> # to # <script type="text/javascript" src="http://itest2.com/javascripts/prototype.js"></script> def absolutify_url(src, base_url, parent_url) if src.nil? || src.empty? || src == "//:" || src =~ /\s*http:\/\//i return src end return "#{base_url}#{src}" if src =~ /^\s*\// return "#{parent_url}#{src}" if parent_url return src end # substut def substitute_relative_path_in_src_line(line, script_src, host_url, page_parent_url) unless script_src =~ /^["']?http:/ host_url.slice!(-1) if ends_with?(host_url, "/") if script_src =~ /^\s*\// # absolute_path line.gsub!(script_src, "#{host_url}#{script_src}") else #relative_path line.gsub!(script_src, "#{page_parent_url}#{script_src}") end end end def ends_with?(str, suffix) suffix = suffix.to_s str[-suffix.length, suffix.length] == suffix end # current web page title def page_title @web_browser.page_title end # current page source (in HTML) def page_source @web_browser.page_source end # return plain text view of page def page_text @web_browser.text end # return the text of specific (identified by attribute "id") label tag # For page containing # <label id="preferred_ide">TestWise</label> # label_with_id("preferred_ids") # => TestWise # label_with_id("preferred_ids", :index => 2) # => TestWise def label_with_id(label_id, options = {}) if options && options[:index] then label(:id => label_id.to_s, :index => options[:index]).text else label(:id, label_id.to_s).text end end # return the text of specific (identified by attribute "id") span tag # For page containing # <span id="preferred_recorder">iTest2/Watir Recorder</span> # span_with_id("preferred_recorder") # => iTest2/Watir Recorder def span_with_id(span_id, options = {}) if options && options[:index] then span(:id => span_id.to_s, :index => options[:index]).text else span(:id, span_id).text end end # return the text of specific (identified by attribute "id") ta tag # For page containing # <td id="preferred_recorder">iTest2/Watir Recorder</span> # td_with_id("preferred_recorder") # => iTest2/Watir Recorder def cell_with_id(cell_id, options = {}) if options && options[:index] then cell(:id => cell_id.to_s, :index => options[:index]).text else cell(:id, cell_id).text end end alias table_data_with_id cell_with_id def is_mac? RUBY_PLATFORM.downcase.include?("darwin") end def is_windows? RUBY_PLATFORM.downcase.include?("mswin") or RUBY_PLATFORM.downcase.include?("mingw") end def is_linux? RUBY_PLATFORM.downcase.include?("linux") end # Support browser (IE) operations using unicode # Example: # click_button("Google 搜索") # Reference: http://jira.openqa.org/browse/WTR-219 def support_utf8 if is_windows? require 'win32ole' WIN32OLE.codepage = WIN32OLE::CP_UTF8 end end alias support_unicode support_utf8 # Execute the provided block until either (1) it returns true, or # (2) the timeout (in seconds) has been reached. If the timeout is reached, # a TimeOutException will be raised. The block will always # execute at least once. # # This does not handle error, if the given block raise error, the statement finish with error # Examples: # wait_until {puts 'hello'} # wait_until { div(:id, :receipt_date).exists? } # def wait_until(timeout = $testwise_polling_timeout || 30, polling_interval = $testwise_polling_interval || 1, & block) waiter = Watir::Waiter.new(timeout, polling_interval) waiter.wait_until { yield } end # Wait for specific seconds for an Ajax update finish. # Trick: In your Rails application, # :loading => "Element.show('search_indicator'); # :complete => "Element.hide('search_indicator'); # # <%= image_tag("indicator.gif", :id => 'search_indicator', :style => 'display:none') %> # # Typical usage: # ajax_wait_for_element("search_indicator", 30) # ajax_wait_for_element("search_indicator", 30, "show") # ajax_wait_for_element("search_indicator", 30, "hide") # ajax_wait_for_element("search_indicator", 30, "show", 5) # check every 5 seconds # # Warning: this method has not been fully tested, if you are not using Rails, change your parameter accordingly. # def ajax_wait_for_element(element_id, seconds, status='show', check_interval = $testwise_polling_interval) count = 0 check_interval = 1 if check_interval < 1 or check_interval > seconds while count < (seconds / check_interval) do search_indicator = @web_browser.element_by_id(element_id) search_indicator_outer_html = search_indicator.outerHtml if search_indicator if status == 'hide' return true if search_indicator_outer_html and !search_indicator_outer_html.include?('style="DISPLAY: none"') else return true if search_indicator_outer_html and search_indicator_outer_html.include?('style="DISPLAY: none"') end sleep check_interval if check_interval > 0 and check_interval < 5 * 60 # wait max 5 minutes count += 1 end return false end #Wait the element with given id to be present in web page # # Warning: this not working in Firefox, try use wait_util or try instead def wait_for_element(element_id, timeout = $testwise_polling_timeout, interval = $testwise_polling_interval) start_time = Time.now #TODO might not work with Firefox until @web_browser.element_by_id(element_id) do sleep(interval) if (Time.now - start_time) > timeout raise RuntimeError, "failed to find element: #{element_id} for max #{timeout}" end end end # Clear popup windows such as 'Security Alert' or 'Security Information' popup window, # # Screenshot see http://kb2.adobe.com/cps/165/tn_16588.html # # You can also by pass security alerts by change IE setting, http://kb.iu.edu/data/amuj.html # # Example # clear_popup("Security Information", 5, true) # check for Security Information for 5 seconds, click Yes def clear_popup(popup_win_title, seconds = 10, yes = true) # commonly "Security Alert", "Security Information" if is_windows? sleep 1 autoit = WIN32OLE.new('AutoItX3.Control') # Look for window with given title. Give up after 1 second. ret = autoit.WinWait(popup_win_title, '', seconds) # # If window found, send appropriate keystroke (e.g. {enter}, {Y}, {N}). if ret == 1 then puts "about to send click Yes" if debugging? button_id = yes ? "Button1" : "Button2" # Yes or No autoit.ControlClick(popup_win_title, '', button_id) end sleep(0.5) else raise "Currently supported only on Windows" end end # Watir 1.9 way of handling javascript dialog def javascript_dialog @web_browser.javascript_dialog end def select_file_for_upload(file_field_name, file_path) if is_windows? normalized_file_path = file_path.gsub("/", "\\") file_field(:name, file_field_name).set(normalized_file_path) else # for firefox, just call file_field, it may fail file_field(:name, file_field_name).set(normalized_file_path) end end def check_ie_version if is_windows? && @ie_version.nil? begin cmd = 'reg query "HKLM\SOFTWARE\Microsoft\Internet Explorer" /v Version'; result = `#{cmd}` version_line = nil result.each do |line| if (line =~ /Version\s+REG_SZ\s+([\d\.]+)/) version_line = $1 end end if version_line =~ /^\s*(\d+)\./ @ie_version = $1.to_i end rescue => e end end end # Use AutoIT3 to send password # title starts with "Connect to ..." def basic_authentication_ie(title, username, password, options = {}) default_options = {:textctrl_username => "Edit2", :textctrl_password => "Edit3", :button_ok => 'Button1' } options = default_options.merge(options) title ||= "" if title =~ /^Connect\sto/ full_title = title else full_title = "Connect to #{title}" end require 'rformspec' login_win = RFormSpec::Window.new(full_title) login_win.send_control_text(options[:textctrl_username], username) login_win.send_control_text(options[:textctrl_password], password) login_win.click_button("OK") end def basic_authentication(username, password, options = {}) basic_authentication_ie(options[:title], username, password, options) end # TODO: Common driver module => this is shared by both Watir and Selenium # # TODO: Common driver module => this is shared by both Watir and Selenium # # use win32screenshot library or Selenium to save curernt active window # # opts[:to_dir] => the direcotry to save image under def take_screenshot(to_file = nil, opts = {}) # puts "calling new take screenshot: #{$screenshot_supported}" # unless $screenshot_supported # puts " [WARN] Screenhost not supported, check whether win32screenshot gem is installed" # return # end if to_file screenshot_image_filepath = to_file else screenshot_image_filename = "screenshot_" + Time.now.strftime("%m%d%H%M%S") + ".jpg" the_dump_dir = opts[:to_dir] || default_dump_dir FileUtils.mkdir_p(the_dump_dir) unless File.exists?(the_dump_dir) screenshot_image_filepath = File.join(the_dump_dir, screenshot_image_filename) screenshot_image_filepath.gsub!("/", "\\") if is_windows? FileUtils.rm_f(screenshot_image_filepath) if File.exist?(screenshot_image_filepath) end begin if is_firefox? then Win32::Screenshot::Take.of(:window, :title => /mozilla\sfirefox/i).write(screenshot_image_filepath) elsif ie Win32::Screenshot::Take.of(:window, :title => /internet\sexplorer/i).write(screenshot_image_filepath) else Win32::Screenshot::Take.of(:foreground).write(screenshot_image_filepath) end notify_screenshot_location(screenshot_image_filepath) rescue ::DL::DLTypeError => de puts "No screenshot libray found: #{de}" rescue => e puts "error on taking screenshot: #{e}" end end # end of methods end
billychan/simple_activity
lib/simple_activity/models/activity.rb
SimpleActivity.Activity.update_cache
ruby
def update_cache(cache_rule) cache_rule.each do |type, type_methods| type_methods.each do |method| value = self.send(type).send(method) self.cache["#{type}_#{method}"] = value end end save end
TODO: Untested
train
https://github.com/billychan/simple_activity/blob/fd24768908393e6aeae285834902be05c7b8ce42/lib/simple_activity/models/activity.rb#L48-L56
class Activity < ActiveRecord::Base self.table_name = "simple_activity_activities" # cache can cache rule when necessary, for third party lib speeding # us processing. if Rails::VERSION::MAJOR == 3 attr_accessible :actor_type, :actor_id, :target_type, :target_id, :action_key, :display, :cache end serialize :cache default_scope order('created_at DESC') # Show activities belongs to an actor def self.actor_activities(obj) type = obj.class.to_s id = obj.id self.where(actor_type: type, actor_id: id) end # Show activities belongs to a target def self.target_activities(obj) type = obj.class.to_s id = obj.id self.where(target_type: type, target_id: id) end def cache read_attribute(:cache) || [] end # Delegate the methods start with "actor_" or "target_" to # cached result def method_missing(method_name, *arguments, &block) if method_name.to_s =~ /(actor|target)_(?!type|id).*/ self.cache.try(:[], method_name.to_s) else super end end def respond_to_missing?(method_name, include_private = false) method_name.to_s.match /(actor|target)_.*/ || super end # TODO: Untested def actor actor_type.capitalize.constantize.find(actor_id) end def target target_type.capitalize.constantize.find(target_id) end def can_display? display end # Get rules for an activity instance. # This can't replace similar method in Processor # # @param set [String] The specific rule set want to get def rules(set=nil) @rules ||= Rule.get_rules(self.target_type, set) end private def self.cache_methods Rule.get_rules_set self.class.to_s end def past_form(action) action.last == 'e' ? "#{action}d" : "#{action}ed" end end
postmodern/rprogram
lib/rprogram/program.rb
RProgram.Program.sudo
ruby
def sudo(*arguments) options = case arguments.last when Hash then arguments.pop else {} end task = SudoTask.new(options.delete(:sudo) || {}) task.command = [@path] + arguments arguments = task.arguments arguments << options unless options.empty? return System.sudo(*arguments) end
Runs the program under sudo. @overload sudo(*arguments) Run the program under `sudo` with the given arguments. @param [Array] arguments Additional arguments to run the program with. @overload sudo(*arguments,options) Run the program under `sudo` with the given arguments and options. @param [Array] arguments Additional arguments to run the program with. @param [Hash] options Additional options to execute the program with. @option options [Hash{Symbol => Object}] :sudo Additional `sudo` options. @return [Boolean] Specifies whether the program exited successfully. @raise [ProgramNotFound] Indicates that the `sudo` program could not be located. @since 0.1.8 @see http://rubydoc.info/stdlib/core/1.9.2/Kernel#spawn-instance_method For acceptable options. @see SudoTask For valid `:sudo` options.
train
https://github.com/postmodern/rprogram/blob/94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be/lib/rprogram/program.rb#L341-L354
class Program # Path to the program attr_reader :path # Name of the program attr_reader :name # # Creates a new Program object. # # @param [String] path # The full-path of the program. # # @yield [prog] # If a block is given, it will be passed the newly created Program # object. # # @yieldparam [Program] prog # The newly created program object. # # @raise [ProgramNotFound] # Specifies the given path was not a valid file. # # @example # Program.new('/usr/bin/ls') # def initialize(path) path = File.expand_path(path) unless File.file?(path) raise(ProgramNotFound,"program #{path.dump} does not exist") end @path = path @name = File.basename(path) yield self if block_given? end # # @return [String] # The name of the program. # def self.program_name @program_name ||= nil end # # @return [Array] # The program's aliases. # def self.program_aliases @program_aliases ||= [] end # # Combines program_name with program_aliases. # # @return [Array] # Names the program is known by. # def self.program_names ([program_name] + program_aliases).compact end # # Sets the program name for the class. # # @param [String, Symbol] name # The new program name. # # @example # name_program 'ls' # def self.name_program(name) @program_name = name.to_s end # # Sets the program aliases for the class. # # @param [Array] aliases # The new program aliases. # # @example # alias_program 'vim', 'vi' # def self.alias_program(*aliases) @program_aliases = aliases.map(&:to_s) end # # The default path of the program. # # @return [String, nil] # The path to the program. # # @since 0.2.0 # def self.path @program_path end # # Sets the default path to the program. # # @param [String] new_path # The new path to the program. # # @return [String, nil] # The path to the program. # # @since 0.2.0 # def self.path=(new_path) @program_path = if new_path File.expand_path(new_path) end end # # Creates a new program object. # # @param [String] path # The full-path of the program. # # @param [Array] arguments # Additional arguments to initialize the program with. # # @yield [prog] # If a block is given, it will be passed the newly created Program # object. # # @yieldparam [Program] prog # The newly created program object. # # @return [Program, nil] # Returns the newly created Program object. If the given path was # not a valid file, `nil` will be returned. # # @example # Program.find_with_path('/bin/cd') # # => Program # # @example # Program.find_with_path('/obviously/fake') # # => nil # def self.find_with_path(path,*arguments,&block) self.new(path,*arguments,&block) if File.file?(path) end # # Creates a new program object with the specified _paths_, # if a path within _paths_ is a valid file. Any given _arguments_ or # a given _block_ will be used in creating the new program. # # @param [Array] paths # The Array of paths to search for the program. # # @param [Array] arguments # Additional arguments to initialize the program with. # # @yield [prog] # If a block is given, it will be passed the newly created Program # object. # # @yieldparam [Program] prog # The newly created program object. # # @return [Program, nil] # Returns the newly created Program object. If none of the given # paths were valid files, `nil` will be returned. # # @example # Program.find_with_paths(['/bin/cd','/usr/bin/cd']) # # => Program # # @example # Program.find_with_paths(['/obviously/fake','/bla']) # # => nil # def self.find_with_paths(paths,*arguments,&block) paths.each do |path| if File.file?(path) return self.new(path,*arguments,&block) end end end # # Finds and creates the program using it's `program_names`. # # @param [Array] arguments # Additional arguments to initialize the program object with. # # @yield [prog] # If a block is given, it will be passed the newly created Program # object. # # @yieldparam [Program] prog # The newly created program object. # # @return [Program] # The newly created program object. # # @raise [ProgramNotFound] # Non of the `program_names` represented valid programs on the system. # # @example # Program.find # # => Program # # @example # MyProgram.find('stuff','here') do |prog| # # ... # end # def self.find(*arguments,&block) path = self.path path ||= System.find_program_by_names(*self.program_names) unless path names = self.program_names.map(&:dump).join(', ') raise(ProgramNotFound,"programs #{names} were not found") end return self.new(path,*arguments,&block) end # # @return [String] # The program name of the class. # def program_name self.class.program_name end # # @return [Array] # The program aliases of the class. # def program_aliases self.class.program_aliases end # # @return [Array] # The program names of the class. # def program_names self.class.program_names end # # Runs the program. # # @overload run(*arguments) # Run the program with the given arguments. # # @param [Array] arguments # Additional arguments to run the program with. # # @overload run(*arguments,options) # Run the program with the given arguments and options. # # @param [Array] arguments # Additional arguments to run the program with. # # @param [Hash] options # Additional options to execute the program with. # # @option options [Hash{String => String}] :env # Environment variables to execute the program with. # # @option options [String] :popen # Specifies to run the program using `IO.popen` with the given # IO mode. # # @return [true, false] # Specifies the exit status of the program. # # @example # echo = Program.find_by_name('echo') # echo.run('hello') # # hello # # => true # # @see http://rubydoc.info/stdlib/core/1.9.2/Kernel#spawn-instance_method # For acceptable options. # def run(*arguments) System.run(@path,*arguments) end # # Runs the program under sudo. # # @overload sudo(*arguments) # Run the program under `sudo` with the given arguments. # # @param [Array] arguments # Additional arguments to run the program with. # # @overload sudo(*arguments,options) # Run the program under `sudo` with the given arguments # and options. # # @param [Array] arguments # Additional arguments to run the program with. # # @param [Hash] options # Additional options to execute the program with. # # @option options [Hash{Symbol => Object}] :sudo # Additional `sudo` options. # # @return [Boolean] # Specifies whether the program exited successfully. # # @raise [ProgramNotFound] # Indicates that the `sudo` program could not be located. # # @since 0.1.8 # # @see http://rubydoc.info/stdlib/core/1.9.2/Kernel#spawn-instance_method # For acceptable options. # # @see SudoTask # For valid `:sudo` options. # # # Runs the program with the arguments from the given task. # # @param [Task, #to_a] task # The task who's arguments will be used to run the program. # # @param [Hash] options # Additional options to execute the program with. # # @return [true, false] # Specifies the exit status of the program. # # @see #run # def run_task(task,options={}) arguments = task.arguments arguments << options unless options.empty? return run(*arguments) end # # Runs the program under `sudo` with the arguments from the given task. # # @param [Task, #to_a] task # The task who's arguments will be used to run the program. # # @param [Hash] options # Spawn options for the program to be ran. # # @yield [sudo] # If a block is given, it will be passed the sudo task. # # @yieldparam [SudoTask] sudo # The sudo tasks. # # @return [true, false] # Specifies the exit status of the program. # # @see #sudo # # @since 0.3.0 # def sudo_task(task,options={},&block) arguments = task.arguments arguments << options unless options.empty? return sudo(*arguments,&block) end # # Converts the program to a String. # # @return [String] # The path of the program. # # @example # Program.find_by_name('echo').to_s # # => "/usr/bin/echo" # def to_s @path.to_s end end
senchalabs/jsduck
lib/jsduck/guides.rb
JsDuck.Guides.fix_icon
ruby
def fix_icon(dir) if File.exists?(dir+"/icon.png") # All ok elsif File.exists?(dir+"/icon-lg.png") FileUtils.mv(dir+"/icon-lg.png", dir+"/icon.png") else FileUtils.cp(@opts.template+"/resources/images/default-guide.png", dir+"/icon.png") end end
Ensures the guide dir contains icon.png. When there isn't looks for icon-lg.png and renames it to icon.png. When neither exists, copies over default icon.
train
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/guides.rb#L145-L153
class Guides < GroupedAsset # Creates Guides object from filename and formatter def self.create(filename, formatter, opts) if filename Guides.new(filename, formatter, opts) else Util::NullObject.new(:to_array => [], :to_html => "", :[] => nil) end end # Parses guides config file def initialize(filename, formatter, opts) @path = File.dirname(filename) @groups = Util::Json.read(filename) @formatter = formatter @opts = opts build_map_by_name load_all_guides end # Writes all guides to given dir in JsonP format def write(dir) FileUtils.mkdir(dir) unless File.exists?(dir) each_item {|guide| write_guide(guide, dir) } end def load_all_guides each_item do |guide| guide["url"] = resolve_url(guide) guide[:dir] = resolve_dir(guide) guide[:filename] = resolve_filename(guide) guide[:html] = load_guide(guide) end end # Modified to_array that excludes the :html from guide nodes def to_array map_items do |item| Hash[item.select {|k, v| k != :html }] end end def load_guide(guide) unless File.exists?(guide[:dir]) return Logger.warn(:guide, "Guide not found", {:filename => guide[:dir]}) end unless File.exists?(guide[:filename]) return Logger.warn(:guide, "Guide not found", {:filename => guide[:filename]}) end unless js_ident?(guide["name"]) # Guide name is also used as JSONP callback method name. return Logger.warn(:guide, "Guide name is not valid JS identifier: #{guide["name"]}", {:filename => guide[:filename]}) end begin return format_guide(guide) rescue Logger.fatal_backtrace("Error while reading/formatting guide #{guide[:filename]}", $!) exit(1) end end def format_guide(guide) @formatter.doc_context = {:filename => guide[:filename], :linenr => 0} @formatter.images = Img::Dir.new(guide[:dir], "guides/#{guide["name"]}") html = @formatter.format(Util::IO.read(guide[:filename])) html = GuideToc.new(html, guide['name'], @opts.guides_toc_level).inject! html = GuideAnchors.transform(html, guide['name']) # Report unused images (but ignore the icon files) @formatter.images.get("icon.png") @formatter.images.get("icon-lg.png") @formatter.images.report_unused return html end def write_guide(guide, dir) return unless guide[:html] out_dir = dir + "/" + guide["name"] Logger.log("Writing guide", out_dir) # Copy the whole guide dir over FileUtils.cp_r(guide[:dir], out_dir) # Ensure the guide has an icon fix_icon(out_dir) Util::Json.write_jsonp(out_dir+"/README.js", guide["name"], {:guide => guide[:html], :title => guide["title"]}) end # Turns guide URL into full path. # If no URL given at all, creates it from guide name. def resolve_url(guide) if guide["url"] File.expand_path(guide["url"], @path) else @path + "/guides/" + guide["name"] end end # Detects guide directory. # The URL either points to a file or directory. def resolve_dir(guide) if File.file?(guide["url"]) File.expand_path("..", guide["url"]) else guide["url"] end end # Detects guide filename. # Either use URL pointing to a file or look up README.md from directory. def resolve_filename(guide) if File.file?(guide["url"]) guide["url"] else guide[:dir] + "/README.md" end end # True when string is valid JavaScript identifier def js_ident?(str) /\A[$\w]+\z/ =~ str end # Ensures the guide dir contains icon.png. # When there isn't looks for icon-lg.png and renames it to icon.png. # When neither exists, copies over default icon. # Returns HTML listing of guides def to_html(style="") html = @groups.map do |group| [ "<h3>#{group['title']}</h3>", "<ul>", flatten_subgroups(group["items"]).map {|g| "<li><a href='#!/guide/#{g['name']}'>#{g['title']}</a></li>" }, "</ul>", ] end.flatten.join("\n") return <<-EOHTML <div id='guides-content' style='#{style}'> #{html} </div> EOHTML end def flatten_subgroups(items) result = [] each_item(items) do |item| result << item end result end # Extracts guide icon URL from guide hash def icon_url(guide) "guides/" + guide["name"] + "/icon.png" end end
mojombo/chronic
lib/chronic/handlers.rb
Chronic.Handlers.handle_sd_sm_sy
ruby
def handle_sd_sm_sy(tokens, options) new_tokens = [tokens[1], tokens[0], tokens[2]] time_tokens = tokens.last(tokens.size - 3) handle_sm_sd_sy(new_tokens + time_tokens, options) end
Handle scalar-day/scalar-month/scalar-year (endian little)
train
https://github.com/mojombo/chronic/blob/2b1eae7ec440d767c09e0b1a7f0e9bcf30ce1d6c/lib/chronic/handlers.rb#L231-L235
module Handlers module_function # Handle month/day def handle_m_d(month, day, time_tokens, options) month.start = self.now span = month.this(options[:context]) year, month = span.begin.year, span.begin.month day_start = Chronic.time_class.local(year, month, day) day_start = Chronic.time_class.local(year + 1, month, day) if options[:context] == :future && day_start < now day_or_time(day_start, time_tokens, options) end # Handle repeater-month-name/scalar-day def handle_rmn_sd(tokens, options) month = tokens[0].get_tag(RepeaterMonthName) day = tokens[1].get_tag(ScalarDay).type return if month_overflow?(self.now.year, month.index, day) handle_m_d(month, day, tokens[2..tokens.size], options) end # Handle repeater-month-name/scalar-day with separator-on def handle_rmn_sd_on(tokens, options) if tokens.size > 3 month = tokens[2].get_tag(RepeaterMonthName) day = tokens[3].get_tag(ScalarDay).type token_range = 0..1 else month = tokens[1].get_tag(RepeaterMonthName) day = tokens[2].get_tag(ScalarDay).type token_range = 0..0 end return if month_overflow?(self.now.year, month.index, day) handle_m_d(month, day, tokens[token_range], options) end # Handle repeater-month-name/ordinal-day def handle_rmn_od(tokens, options) month = tokens[0].get_tag(RepeaterMonthName) day = tokens[1].get_tag(OrdinalDay).type return if month_overflow?(self.now.year, month.index, day) handle_m_d(month, day, tokens[2..tokens.size], options) end # Handle ordinal this month def handle_od_rm(tokens, options) day = tokens[0].get_tag(OrdinalDay).type month = tokens[2].get_tag(RepeaterMonth) handle_m_d(month, day, tokens[3..tokens.size], options) end # Handle ordinal-day/repeater-month-name def handle_od_rmn(tokens, options) month = tokens[1].get_tag(RepeaterMonthName) day = tokens[0].get_tag(OrdinalDay).type return if month_overflow?(self.now.year, month.index, day) handle_m_d(month, day, tokens[2..tokens.size], options) end def handle_sy_rmn_od(tokens, options) year = tokens[0].get_tag(ScalarYear).type month = tokens[1].get_tag(RepeaterMonthName).index day = tokens[2].get_tag(OrdinalDay).type time_tokens = tokens.last(tokens.size - 3) return if month_overflow?(year, month, day) begin day_start = Chronic.time_class.local(year, month, day) day_or_time(day_start, time_tokens, options) rescue ArgumentError nil end end # Handle scalar-day/repeater-month-name def handle_sd_rmn(tokens, options) month = tokens[1].get_tag(RepeaterMonthName) day = tokens[0].get_tag(ScalarDay).type return if month_overflow?(self.now.year, month.index, day) handle_m_d(month, day, tokens[2..tokens.size], options) end # Handle repeater-month-name/ordinal-day with separator-on def handle_rmn_od_on(tokens, options) if tokens.size > 3 month = tokens[2].get_tag(RepeaterMonthName) day = tokens[3].get_tag(OrdinalDay).type token_range = 0..1 else month = tokens[1].get_tag(RepeaterMonthName) day = tokens[2].get_tag(OrdinalDay).type token_range = 0..0 end return if month_overflow?(self.now.year, month.index, day) handle_m_d(month, day, tokens[token_range], options) end # Handle scalar-year/repeater-quarter-name def handle_sy_rqn(tokens, options) handle_rqn_sy(tokens[0..1].reverse, options) end # Handle repeater-quarter-name/scalar-year def handle_rqn_sy(tokens, options) year = tokens[1].get_tag(ScalarYear).type quarter_tag = tokens[0].get_tag(RepeaterQuarterName) quarter_tag.start = Chronic.construct(year) quarter_tag.this(:none) end # Handle repeater-month-name/scalar-year def handle_rmn_sy(tokens, options) month = tokens[0].get_tag(RepeaterMonthName).index year = tokens[1].get_tag(ScalarYear).type if month == 12 next_month_year = year + 1 next_month_month = 1 else next_month_year = year next_month_month = month + 1 end begin end_time = Chronic.time_class.local(next_month_year, next_month_month) Span.new(Chronic.time_class.local(year, month), end_time) rescue ArgumentError nil end end # Handle generic timestamp (ruby 1.8) def handle_generic(tokens, options) t = Chronic.time_class.parse(options[:text]) Span.new(t, t + 1) rescue ArgumentError => e raise e unless e.message =~ /out of range/ end # Handle repeater-month-name/scalar-day/scalar-year def handle_rmn_sd_sy(tokens, options) month = tokens[0].get_tag(RepeaterMonthName).index day = tokens[1].get_tag(ScalarDay).type year = tokens[2].get_tag(ScalarYear).type time_tokens = tokens.last(tokens.size - 3) return if month_overflow?(year, month, day) begin day_start = Chronic.time_class.local(year, month, day) day_or_time(day_start, time_tokens, options) rescue ArgumentError nil end end # Handle repeater-month-name/ordinal-day/scalar-year def handle_rmn_od_sy(tokens, options) month = tokens[0].get_tag(RepeaterMonthName).index day = tokens[1].get_tag(OrdinalDay).type year = tokens[2].get_tag(ScalarYear).type time_tokens = tokens.last(tokens.size - 3) return if month_overflow?(year, month, day) begin day_start = Chronic.time_class.local(year, month, day) day_or_time(day_start, time_tokens, options) rescue ArgumentError nil end end # Handle oridinal-day/repeater-month-name/scalar-year def handle_od_rmn_sy(tokens, options) day = tokens[0].get_tag(OrdinalDay).type month = tokens[1].get_tag(RepeaterMonthName).index year = tokens[2].get_tag(ScalarYear).type time_tokens = tokens.last(tokens.size - 3) return if month_overflow?(year, month, day) begin day_start = Chronic.time_class.local(year, month, day) day_or_time(day_start, time_tokens, options) rescue ArgumentError nil end end # Handle scalar-day/repeater-month-name/scalar-year def handle_sd_rmn_sy(tokens, options) new_tokens = [tokens[1], tokens[0], tokens[2]] time_tokens = tokens.last(tokens.size - 3) handle_rmn_sd_sy(new_tokens + time_tokens, options) end # Handle scalar-month/scalar-day/scalar-year (endian middle) def handle_sm_sd_sy(tokens, options) month = tokens[0].get_tag(ScalarMonth).type day = tokens[1].get_tag(ScalarDay).type year = tokens[2].get_tag(ScalarYear).type time_tokens = tokens.last(tokens.size - 3) return if month_overflow?(year, month, day) begin day_start = Chronic.time_class.local(year, month, day) day_or_time(day_start, time_tokens, options) rescue ArgumentError nil end end # Handle scalar-day/scalar-month/scalar-year (endian little) # Handle scalar-year/scalar-month/scalar-day def handle_sy_sm_sd(tokens, options) new_tokens = [tokens[1], tokens[2], tokens[0]] time_tokens = tokens.last(tokens.size - 3) handle_sm_sd_sy(new_tokens + time_tokens, options) end # Handle scalar-month/scalar-day def handle_sm_sd(tokens, options) month = tokens[0].get_tag(ScalarMonth).type day = tokens[1].get_tag(ScalarDay).type year = self.now.year time_tokens = tokens.last(tokens.size - 2) return if month_overflow?(year, month, day) begin day_start = Chronic.time_class.local(year, month, day) if options[:context] == :future && day_start < now day_start = Chronic.time_class.local(year + 1, month, day) elsif options[:context] == :past && day_start > now day_start = Chronic.time_class.local(year - 1, month, day) end day_or_time(day_start, time_tokens, options) rescue ArgumentError nil end end # Handle scalar-day/scalar-month def handle_sd_sm(tokens, options) new_tokens = [tokens[1], tokens[0]] time_tokens = tokens.last(tokens.size - 2) handle_sm_sd(new_tokens + time_tokens, options) end def handle_year_and_month(year, month) if month == 12 next_month_year = year + 1 next_month_month = 1 else next_month_year = year next_month_month = month + 1 end begin end_time = Chronic.time_class.local(next_month_year, next_month_month) Span.new(Chronic.time_class.local(year, month), end_time) rescue ArgumentError nil end end # Handle scalar-month/scalar-year def handle_sm_sy(tokens, options) month = tokens[0].get_tag(ScalarMonth).type year = tokens[1].get_tag(ScalarYear).type handle_year_and_month(year, month) end # Handle scalar-year/scalar-month def handle_sy_sm(tokens, options) year = tokens[0].get_tag(ScalarYear).type month = tokens[1].get_tag(ScalarMonth).type handle_year_and_month(year, month) end # Handle RepeaterDayName RepeaterMonthName OrdinalDay def handle_rdn_rmn_od(tokens, options) month = tokens[1].get_tag(RepeaterMonthName) day = tokens[2].get_tag(OrdinalDay).type time_tokens = tokens.last(tokens.size - 3) year = self.now.year return if month_overflow?(year, month.index, day) begin if time_tokens.empty? start_time = Chronic.time_class.local(year, month.index, day) end_time = time_with_rollover(year, month.index, day + 1) Span.new(start_time, end_time) else day_start = Chronic.time_class.local(year, month.index, day) day_or_time(day_start, time_tokens, options) end rescue ArgumentError nil end end # Handle RepeaterDayName RepeaterMonthName OrdinalDay ScalarYear def handle_rdn_rmn_od_sy(tokens, options) month = tokens[1].get_tag(RepeaterMonthName) day = tokens[2].get_tag(OrdinalDay).type year = tokens[3].get_tag(ScalarYear).type return if month_overflow?(year, month.index, day) begin start_time = Chronic.time_class.local(year, month.index, day) end_time = time_with_rollover(year, month.index, day + 1) Span.new(start_time, end_time) rescue ArgumentError nil end end # Handle RepeaterDayName OrdinalDay def handle_rdn_od(tokens, options) day = tokens[1].get_tag(OrdinalDay).type time_tokens = tokens.last(tokens.size - 2) year = self.now.year month = self.now.month if options[:context] == :future self.now.day > day ? month += 1 : month end return if month_overflow?(year, month, day) begin if time_tokens.empty? start_time = Chronic.time_class.local(year, month, day) end_time = time_with_rollover(year, month, day + 1) Span.new(start_time, end_time) else day_start = Chronic.time_class.local(year, month, day) day_or_time(day_start, time_tokens, options) end rescue ArgumentError nil end end # Handle RepeaterDayName RepeaterMonthName ScalarDay def handle_rdn_rmn_sd(tokens, options) month = tokens[1].get_tag(RepeaterMonthName) day = tokens[2].get_tag(ScalarDay).type time_tokens = tokens.last(tokens.size - 3) year = self.now.year return if month_overflow?(year, month.index, day) begin if time_tokens.empty? start_time = Chronic.time_class.local(year, month.index, day) end_time = time_with_rollover(year, month.index, day + 1) Span.new(start_time, end_time) else day_start = Chronic.time_class.local(year, month.index, day) day_or_time(day_start, time_tokens, options) end rescue ArgumentError nil end end # Handle RepeaterDayName RepeaterMonthName ScalarDay ScalarYear def handle_rdn_rmn_sd_sy(tokens, options) month = tokens[1].get_tag(RepeaterMonthName) day = tokens[2].get_tag(ScalarDay).type year = tokens[3].get_tag(ScalarYear).type return if month_overflow?(year, month.index, day) begin start_time = Chronic.time_class.local(year, month.index, day) end_time = time_with_rollover(year, month.index, day + 1) Span.new(start_time, end_time) rescue ArgumentError nil end end def handle_sm_rmn_sy(tokens, options) day = tokens[0].get_tag(ScalarDay).type month = tokens[1].get_tag(RepeaterMonthName).index year = tokens[2].get_tag(ScalarYear).type if tokens.size > 3 time = get_anchor([tokens.last], options).begin h, m, s = time.hour, time.min, time.sec time = Chronic.time_class.local(year, month, day, h, m, s) end_time = Chronic.time_class.local(year, month, day + 1, h, m, s) else time = Chronic.time_class.local(year, month, day) day += 1 unless day >= 31 end_time = Chronic.time_class.local(year, month, day) end Span.new(time, end_time) end # anchors # Handle repeaters def handle_r(tokens, options) dd_tokens = dealias_and_disambiguate_times(tokens, options) get_anchor(dd_tokens, options) end # Handle repeater/grabber/repeater def handle_r_g_r(tokens, options) new_tokens = [tokens[1], tokens[0], tokens[2]] handle_r(new_tokens, options) end # arrows # Handle scalar/repeater/pointer helper def handle_srp(tokens, span, options) distance = tokens[0].get_tag(Scalar).type repeater = tokens[1].get_tag(Repeater) pointer = tokens[2].get_tag(Pointer).type repeater.offset(span, distance, pointer) if repeater.respond_to?(:offset) end # Handle scalar/repeater/pointer def handle_s_r_p(tokens, options) span = Span.new(self.now, self.now + 1) handle_srp(tokens, span, options) end # Handle pointer/scalar/repeater def handle_p_s_r(tokens, options) new_tokens = [tokens[1], tokens[2], tokens[0]] handle_s_r_p(new_tokens, options) end # Handle scalar/repeater/pointer/anchor def handle_s_r_p_a(tokens, options) anchor_span = get_anchor(tokens[3..tokens.size - 1], options) handle_srp(tokens, anchor_span, options) end # Handle repeater/scalar/repeater/pointer def handle_rmn_s_r_p(tokens, options) handle_s_r_p_a(tokens[1..3] + tokens[0..0], options) end def handle_s_r_a_s_r_p_a(tokens, options) anchor_span = get_anchor(tokens[4..tokens.size - 1], options) span = handle_srp(tokens[0..1]+tokens[4..6], anchor_span, options) handle_srp(tokens[2..3]+tokens[4..6], span, options) end # narrows # Handle oridinal repeaters def handle_orr(tokens, outer_span, options) repeater = tokens[1].get_tag(Repeater) repeater.start = outer_span.begin - 1 ordinal = tokens[0].get_tag(Ordinal).type span = nil ordinal.times do span = repeater.next(:future) if span.begin >= outer_span.end span = nil break end end span end # Handle ordinal/repeater/separator/repeater def handle_o_r_s_r(tokens, options) outer_span = get_anchor([tokens[3]], options) handle_orr(tokens[0..1], outer_span, options) end # Handle ordinal/repeater/grabber/repeater def handle_o_r_g_r(tokens, options) outer_span = get_anchor(tokens[2..3], options) handle_orr(tokens[0..1], outer_span, options) end # support methods def day_or_time(day_start, time_tokens, options) outer_span = Span.new(day_start, day_start + (24 * 60 * 60)) unless time_tokens.empty? self.now = outer_span.begin get_anchor(dealias_and_disambiguate_times(time_tokens, options), options.merge(:context => :future)) else outer_span end end def get_anchor(tokens, options) grabber = Grabber.new(:this) pointer = :future repeaters = get_repeaters(tokens) repeaters.size.times { tokens.pop } if tokens.first && tokens.first.get_tag(Grabber) grabber = tokens.shift.get_tag(Grabber) end head = repeaters.shift head.start = self.now case grabber.type when :last outer_span = head.next(:past) when :this if options[:context] != :past and repeaters.size > 0 outer_span = head.this(:none) else outer_span = head.this(options[:context]) end when :next outer_span = head.next(:future) else raise 'Invalid grabber' end if Chronic.debug puts "Handler-class: #{head.class}" puts "--#{outer_span}" end find_within(repeaters, outer_span, pointer) end def get_repeaters(tokens) tokens.map { |token| token.get_tag(Repeater) }.compact.sort.reverse end def month_overflow?(year, month, day) if ::Date.leap?(year) day > RepeaterMonth::MONTH_DAYS_LEAP[month - 1] else day > RepeaterMonth::MONTH_DAYS[month - 1] end rescue ArgumentError false end # Recursively finds repeaters within other repeaters. # Returns a Span representing the innermost time span # or nil if no repeater union could be found def find_within(tags, span, pointer) puts "--#{span}" if Chronic.debug return span if tags.empty? head = tags.shift head.start = (pointer == :future ? span.begin : span.end) h = head.this(:none) if span.cover?(h.begin) || span.cover?(h.end) find_within(tags, h, pointer) end end def time_with_rollover(year, month, day) date_parts = if month_overflow?(year, month, day) if month == 12 [year + 1, 1, 1] else [year, month + 1, 1] end else [year, month, day] end Chronic.time_class.local(*date_parts) end def dealias_and_disambiguate_times(tokens, options) # handle aliases of am/pm # 5:00 in the morning -> 5:00 am # 7:00 in the evening -> 7:00 pm day_portion_index = nil tokens.each_with_index do |t, i| if t.get_tag(RepeaterDayPortion) day_portion_index = i break end end time_index = nil tokens.each_with_index do |t, i| if t.get_tag(RepeaterTime) time_index = i break end end if day_portion_index && time_index t1 = tokens[day_portion_index] t1tag = t1.get_tag(RepeaterDayPortion) case t1tag.type when :morning puts '--morning->am' if Chronic.debug t1.untag(RepeaterDayPortion) t1.tag(RepeaterDayPortion.new(:am)) when :afternoon, :evening, :night puts "--#{t1tag.type}->pm" if Chronic.debug t1.untag(RepeaterDayPortion) t1.tag(RepeaterDayPortion.new(:pm)) end end # handle ambiguous times if :ambiguous_time_range is specified if options[:ambiguous_time_range] != :none ambiguous_tokens = [] tokens.each_with_index do |token, i| ambiguous_tokens << token next_token = tokens[i + 1] if token.get_tag(RepeaterTime) && token.get_tag(RepeaterTime).type.ambiguous? && (!next_token || !next_token.get_tag(RepeaterDayPortion)) distoken = Token.new('disambiguator') distoken.tag(RepeaterDayPortion.new(options[:ambiguous_time_range])) ambiguous_tokens << distoken end end tokens = ambiguous_tokens end tokens end end
sailthru/sailthru-ruby-client
lib/sailthru/client.rb
Sailthru.Client.process_job
ruby
def process_job(job, options = {}, report_email = nil, postback_url = nil, binary_key = nil) data = options data['job'] = job if !report_email.nil? data['report_email'] = report_email end if !postback_url.nil? data['postback_url'] = postback_url end api_post(:job, data, binary_key) end
params job, String options, hash report_email, String postback_url, String binary_key, String interface for making request to job call
train
https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L595-L606
class Client DEFAULT_API_URI = 'https://api.sailthru.com' include Helpers attr_accessor :verify_ssl # params: # api_key, String # secret, String # api_uri, String # # Instantiate a new client; constructor optionally takes overrides for key/secret/uri and proxy server settings. def initialize(api_key=nil, secret=nil, api_uri=nil, proxy_host=nil, proxy_port=nil, opts={}) @api_key = api_key || Sailthru.api_key || raise(ArgumentError, "You must provide an API key or call Sailthru.credentials() first") @secret = secret || Sailthru.secret || raise(ArgumentError, "You must provide your secret or call Sailthru.credentials() first") @api_uri = api_uri.nil? ? DEFAULT_API_URI : api_uri @proxy_host = proxy_host @proxy_port = proxy_port @verify_ssl = true @opts = opts @last_rate_limit_info = {} end # params: # template_name, String # email, String # vars, Hash # options, Hash # replyto: override Reply-To header # test: send as test email (subject line will be marked, will not count towards stats) # returns: # Hash, response data from server def send_email(template_name, email, vars={}, options = {}, schedule_time = nil, limit = {}) post = {} post[:template] = template_name post[:email] = email post[:vars] = vars if vars.length >= 1 post[:options] = options if options.length >= 1 post[:schedule_time] = schedule_time if !schedule_time.nil? post[:limit] = limit if limit.length >= 1 api_post(:send, post) end def multi_send(template_name, emails, vars={}, options = {}, schedule_time = nil, evars = {}) post = {} post[:template] = template_name post[:email] = emails post[:vars] = vars if vars.length >= 1 post[:options] = options if options.length >= 1 post[:schedule_time] = schedule_time if !schedule_time.nil? post[:evars] = evars if evars.length >= 1 api_post(:send, post) end # params: # send_id, Fixnum # returns: # Hash, response data from server # # Get the status of a send. def get_send(send_id) api_get(:send, {:send_id => send_id.to_s}) end def cancel_send(send_id) api_delete(:send, {:send_id => send_id.to_s}) end # params: # name, String # list, String # schedule_time, String # from_name, String # from_email, String # subject, String # content_html, String # content_text, String # options, Hash # returns: # Hash, response data from server # # Schedule a mass mail blast def schedule_blast(name, list, schedule_time, from_name, from_email, subject, content_html, content_text, options = {}) post = options ? options : {} post[:name] = name post[:list] = list post[:schedule_time] = schedule_time post[:from_name] = from_name post[:from_email] = from_email post[:subject] = subject post[:content_html] = content_html post[:content_text] = content_text api_post(:blast, post) end # Schedule a mass mail blast from template def schedule_blast_from_template(template, list, schedule_time, options={}) post = options ? options : {} post[:copy_template] = template post[:list] = list post[:schedule_time] = schedule_time api_post(:blast, post) end # Schedule a mass mail blast from previous blast def schedule_blast_from_blast(blast_id, schedule_time, options={}) post = options ? options : {} post[:copy_blast] = blast_id #post[:name] = name post[:schedule_time] = schedule_time api_post(:blast, post) end # params # blast_id, Fixnum | String # name, String # list, String # schedule_time, String # from_name, String # from_email, String # subject, String # content_html, String # content_text, String # options, hash # # updates existing blast def update_blast(blast_id, name = nil, list = nil, schedule_time = nil, from_name = nil, from_email = nil, subject = nil, content_html = nil, content_text = nil, options = {}) data = options ? options : {} data[:blast_id] = blast_id if name != nil data[:name] = name end if list != nil data[:list] = list end if schedule_time != nil data[:schedule_time] = schedule_time end if from_name != nil data[:from_name] = from_name end if from_email != nil data[:from_email] = from_email end if subject != nil data[:subject] = subject end if content_html != nil data[:content_html] = content_html end if content_text != nil data[:content_text] = content_text end api_post(:blast, data) end # params: # blast_id, Fixnum | String # options, hash # returns: # Hash, response data from server # # Get information on a previously scheduled email blast def get_blast(blast_id, options={}) options[:blast_id] = blast_id.to_s api_get(:blast, options) end # params: # blast_id, Fixnum | String # # Cancel a scheduled Blast def cancel_blast(blast_id) api_post(:blast, {:blast_id => blast_id, :schedule_time => ''}) end # params: # blast_id, Fixnum | String # # Delete a Blast def delete_blast(blast_id) api_delete(:blast, {:blast_id => blast_id}) end # params: # email, String # returns: # Hash, response data from server # # Return information about an email address, including replacement vars and lists. def get_email(email) api_get(:email, {:email => email}) end # params: # email, String # vars, Hash # lists, Hash mapping list name => 1 for subscribed, 0 for unsubscribed # options, Hash mapping optional parameters # returns: # Hash, response data from server # # Set replacement vars and/or list subscriptions for an email address. def set_email(email, vars = {}, lists = {}, templates = {}, options = {}) data = options data[:email] = email data[:vars] = vars unless vars.empty? data[:lists] = lists unless lists.empty? data[:templates] = templates unless templates.empty? api_post(:email, data) end # params: # new_email, String # old_email, String # options, Hash mapping optional parameters # returns: # Hash of response data. # # change a user's email address. def change_email(new_email, old_email, options = {}) data = options data[:email] = new_email data[:change_email] = old_email api_post(:email, data) end # returns: # Hash of response data. # # Get all templates def get_templates(templates = {}) api_get(:template, templates) end # params: # template_name, String # returns: # Hash of response data. # # Get a template. def get_template(template_name) api_get(:template, {:template => template_name}) end # params: # template_name, String # template_fields, Hash # returns: # Hash containg response from the server. # # Save a template. def save_template(template_name, template_fields) data = template_fields data[:template] = template_name api_post(:template, data) end # params: # template_name, String # returns: # Hash of response data. # # Delete a template. def delete_template(template_name) api_delete(:template, {:template => template_name}) end # params: # params, Hash # request, String # returns: # boolean, Returns true if the incoming request is an authenticated verify post. def receive_verify_post(params, request) if request.post? [:action, :email, :send_id, :sig].each { |key| return false unless params.has_key?(key) } return false unless params[:action] == :verify sig = params.delete(:sig) params.delete(:controller) return false unless sig == get_signature_hash(params, @secret) _send = get_send(params[:send_id]) return false unless _send.has_key?('email') return false unless _send['email'] == params[:email] return true else return false end end # params: # params, Hash # request, String # returns: # TrueClass or FalseClass, Returns true if the incoming request is an authenticated optout post. def receive_optout_post(params, request) if request.post? [:action, :email, :sig].each { |key| return false unless params.has_key?(key) } return false unless params[:action] == 'optout' sig = params.delete(:sig) params.delete(:controller) sig == get_signature_hash(params, @secret) else false end end # List Postbacks must be enabled by Sailthru # Contact your account manager or contact support to have this enabled # # params: # params, Hash # request, String # returns: # TrueClass or FalseClass, Returns true if the incoming request is an authenticated list post. def receive_list_post(params, request) if request.post? [:action, :email, :sig].each { |key| return false unless params.has_key?(key) } return false unless params[:action] == 'update' sig = params.delete(:sig) params.delete(:controller) sig == get_signature_hash(params, @secret) else false end end # params: # params, Hash # request, String # returns: # TrueClass or FalseClass, Returns true if the incoming request is an authenticated hardbounce post. def receive_hardbounce_post(params, request) if request.post? [:action, :email, :sig].each { |key| return false unless params.has_key?(key) } return false unless params[:action] == 'hardbounce' sig = params.delete(:sig) params.delete(:controller) sig == get_signature_hash(params, @secret) else false end end # params: # email, String # items, Array of Hashes # incomplete, Integer # message_id, String # options, Hash # returns: # hash, response from server # # Record that a user has made a purchase, or has added items to their purchase total. def purchase(email, items, incomplete = nil, message_id = nil, options = {}) data = options data[:email] = email data[:items] = items if incomplete != nil data[:incomplete] = incomplete.to_i end if message_id != nil data[:message_id] = message_id end api_post(:purchase, data) end # <b>DEPRECATED:</b> Please use either stats_list or stats_blast # params: # stat, String # # returns: # hash, response from server # Request various stats from Sailthru. def get_stats(stat) warn "[DEPRECATION] `get_stats` is deprecated. Please use `stats_list` and `stats_blast` instead" api_get(:stats, {:stat => stat}) end # params # list, String # date, String # # returns: # hash, response from server # Retrieve information about your subscriber counts on a particular list, on a particular day. def stats_list(list = nil, date = nil) data = {} if list != nil data[:list] = list end if date != nil data[:date] = date end data[:stat] = 'list' api_get(:stats, data) end # params # blast_id, String # start_date, String # end_date, String # options, Hash # # returns: # hash, response from server # Retrieve information about a particular blast or aggregated information from all of blasts over a specified date range def stats_blast(blast_id = nil, start_date = nil, end_date = nil, options = {}) data = options if blast_id != nil data[:blast_id] = blast_id end if start_date != nil data[:start_date] = start_date end if end_date != nil data[:end_date] = end_date end data[:stat] = 'blast' api_get(:stats, data) end # params # template, String # start_date, String # end_date, String # options, Hash # # returns: # hash, response from server # Retrieve information about a particular blast or aggregated information from all of blasts over a specified date range def stats_send(template = nil, start_date = nil, end_date = nil, options = {}) data = options if template != nil data[:template] = template end if start_date != nil data[:start_date] = start_date end if end_date != nil data[:end_date] = end_date end data[:stat] = 'send' api_get(:stats, data) end # <b>DEPRECATED:</b> Please use save_content # params # title, String # url, String # date, String # tags, Array or Comma separated string # vars, Hash # options, Hash # # Push a new piece of content to Sailthru, triggering any applicable alerts. # http://docs.sailthru.com/api/content def push_content(title, url, date = nil, tags = nil, vars = {}, options = {}) data = options data[:title] = title data[:url] = url if date != nil data[:date] = date end if tags != nil if tags.class == Array tags = tags.join(',') end data[:tags] = tags end if vars.length > 0 data[:vars] = vars end api_post(:content, data) end # params # id, String – An identifier for the item (by default, the item’s URL). # options, Hash - Containing any of the parameters described on # https://getstarted.sailthru.com/developers/api/content/#POST_Mode # # Push a new piece of content to Sailthru, triggering any applicable alerts. # http://docs.sailthru.com/api/content def save_content(id, options) data = options data[:id] = id data[:tags] = data[:tags].join(',') if data[:tags].respond_to?(:join) api_post(:content, data) end # params # list, String # # Get information about a list. def get_list(list) api_get(:list, {:list => list}) end # params # # Get information about all lists def get_lists api_get(:list, {}) end # params # list, String # options, Hash # Create a list, or update a list. def save_list(list, options = {}) data = options data[:list] = list api_post(:list, data) end # params # list, String # # Deletes a list def delete_list(list) api_delete(:list, {:list => list}) end # params # email, String # # get user alert data def get_alert(email) api_get(:alert, {:email => email}) end # params # email, String # type, String # template, String # _when, String # options, hash # # Add a new alert to a user. You can add either a realtime or a summary alert (daily/weekly). # _when is only required when alert type is weekly or daily def save_alert(email, type, template, _when = nil, options = {}) data = options data[:email] = email data[:type] = type data[:template] = template if (type == 'weekly' || type == 'daily') data[:when] = _when end api_post(:alert, data) end # params # email, String # alert_id, String # # delete user alert def delete_alert(email, alert_id) data = {:email => email, :alert_id => alert_id} api_delete(:alert, data) end # params # job, String # options, hash # report_email, String # postback_url, String # binary_key, String # # interface for making request to job call # params # emails, String | Array # implementation for import_job def process_import_job(list, emails, report_email = nil, postback_url = nil, options = {}) data = options data['list'] = list data['emails'] = Array(emails).join(',') process_job(:import, data, report_email, postback_url) end # implementation for import job using file upload def process_import_job_from_file(list, file_path, report_email = nil, postback_url = nil, options = {}) data = options data['list'] = list data['file'] = file_path process_job(:import, data, report_email, postback_url, 'file') end # implementation for update job using file upload def process_update_job_from_file(file_path, report_email = nil, postback_url = nil, options = {}) data = options data['file'] = file_path process_job(:update, data, report_email, postback_url, 'file') end # implementation for purchase import job using file upload def process_purchase_import_job_from_file(file_path, report_email = nil, postback_url = nil, options = {}) data = options data['file'] = file_path process_job(:purchase_import, data, report_email, postback_url, 'file') end # implementation for snapshot job def process_snapshot_job(query = {}, report_email = nil, postback_url = nil, options = {}) data = options data['query'] = query process_job(:snapshot, data, report_email, postback_url) end # implementation for export list job def process_export_list_job(list, report_email = nil, postback_url = nil, options = {}) data = options data['list'] = list process_job(:export_list_data, data, report_email, postback_url) end # get status of a job def get_job_status(job_id) api_get(:job, {'job_id' => job_id}) end # Get user by Sailthru ID def get_user_by_sid(id, fields = {}) api_get(:user, {'id' => id, 'fields' => fields}) end # Get user by specified key def get_user_by_key(id, key, fields = {}) data = { 'id' => id, 'key' => key, 'fields' => fields } api_get(:user, data) end # Create new user, or update existing user def save_user(id, options = {}) data = options data['id'] = id api_post(:user, data) end # params # Get an existing trigger def get_triggers api_get(:trigger, {}) end # params # template, String # trigger_id, String # Get an existing trigger def get_trigger_by_template(template, trigger_id = nil) data = {} data['template'] = template if trigger_id != nil then data['trigger_id'] = trigger_id end api_get(:trigger, data) end # params # event, String # Get an existing trigger def get_trigger_by_event(event) data = {} data['event'] = event api_get(:trigger, data) end # params # template, String # time, String # time_unit, String # event, String # zephyr, String # Create or update a trigger def post_template_trigger(template, time, time_unit, event, zephyr) data = {} data['template'] = template data['time'] = time data['time_unit'] = time_unit data['event'] = event data['zephyr'] = zephyr api_post(:trigger, data) end # params # template, String # time, String # time_unit, String # zephyr, String # Create or update a trigger def post_event_trigger(event, time, time_unit, zephyr) data = {} data['time'] = time data['time_unit'] = time_unit data['event'] = event data['zephyr'] = zephyr api_post(:trigger, data) end # params # id, String # event, String # options, Hash (Can contain vars, Hash and/or key) # Notify Sailthru of an Event def post_event(id, event, options = {}) data = options data['id'] = id data['event'] = event api_post(:event, data) end # Perform API GET request def api_get(action, data) api_request(action, data, 'GET') end # Perform API POST request def api_post(action, data, binary_key = nil) api_request(action, data, 'POST', binary_key) end #Perform API DELETE request def api_delete(action, data) api_request(action, data, 'DELETE') end # params # endpoint, String a e.g. "user" or "send" # method, String "GET" or "POST" # returns # Hash rate info # Get rate info for a particular endpoint/method, as of the last time a request was sent to the given endpoint/method # Includes the following keys: # limit: the per-minute limit for the given endpoint/method # remaining: the number of allotted requests remaining in the current minute for the given endpoint/method # reset: unix timestamp of the top of the next minute, when the rate limit will reset def get_last_rate_limit_info(endpoint, method) rate_info_key = get_rate_limit_info_key(endpoint, method) @last_rate_limit_info[rate_info_key] end protected # params: # action, String # data, Hash # request, String "GET" or "POST" # returns: # Hash # # Perform an API request, using the shared-secret auth hash. # def api_request(action, data, request_type, binary_key = nil) if !binary_key.nil? binary_key_data = data[binary_key] data.delete(binary_key) end if data[:format].nil? || data[:format] == 'json' data = prepare_json_payload(data) else data[:api_key] = @api_key data[:format] ||= 'json' data[:sig] = get_signature_hash(data, @secret) end if !binary_key.nil? data[binary_key] = binary_key_data end _result = http_request(action, data, request_type, binary_key) # NOTE: don't do the unserialize here if data[:format] == 'json' begin unserialized = JSON.parse(_result) return unserialized ? unserialized : _result rescue JSON::JSONError => e return {'error' => e} end end _result end # set up our post request def set_up_post_request(uri, data, headers, binary_key = nil) if !binary_key.nil? binary_data = data[binary_key] if binary_data.is_a?(StringIO) data[binary_key] = UploadIO.new( binary_data, "text/plain", "local.path" ) else data[binary_key] = UploadIO.new( File.open(binary_data), "text/plain" ) end req = Net::HTTP::Post::Multipart.new(uri.path, data) else req = Net::HTTP::Post.new(uri.path, headers) req.set_form_data(data) end req end # params: # uri, String # data, Hash # method, String "GET" or "POST" # returns: # String, body of response def http_request(action, data, method = 'POST', binary_key = nil) data = flatten_nested_hash(data, false) uri = "#{@api_uri}/#{action}" if method != 'POST' uri += "?" + data.map{ |key, value| "#{CGI::escape(key.to_s)}=#{CGI::escape(value.to_s)}" }.join("&") end req = nil headers = {"User-Agent" => "Sailthru API Ruby Client #{Sailthru::VERSION}"} _uri = URI.parse(uri) if method == 'POST' req = set_up_post_request( _uri, data, headers, binary_key ) else request_uri = "#{_uri.path}?#{_uri.query}" if method == 'DELETE' req = Net::HTTP::Delete.new(request_uri, headers) else req = Net::HTTP::Get.new(request_uri, headers) end end begin http = Net::HTTP::Proxy(@proxy_host, @proxy_port).new(_uri.host, _uri.port) if _uri.scheme == 'https' http.ssl_version = :TLSv1 http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE if @verify_ssl != true # some openSSL client doesn't work without doing this http.ssl_timeout = @opts[:http_ssl_timeout] || 5 end http.open_timeout = @opts[:http_open_timeout] || 5 http.read_timeout = @opts[:http_read_timeout] || 10 http.close_on_empty_response = @opts[:http_close_on_empty_response] || true response = http.start do http.request(req) end rescue Timeout::Error, Errno::ETIMEDOUT => e raise UnavailableError, "Timed out: #{_uri}" rescue => e raise ClientError, "Unable to open stream to #{_uri}: #{e.message}" end save_rate_limit_info(action, method, response) response.body || raise(ClientError, "No response received from stream: #{_uri}") end def http_multipart_request(uri, data) Net::HTTP::Post::Multipart.new url.path, "file" => UploadIO.new(data['file'], "application/octet-stream") end def prepare_json_payload(data) payload = { :api_key => @api_key, :format => 'json', #<3 XML :json => data.to_json } payload[:sig] = get_signature_hash(payload, @secret) payload end def save_rate_limit_info(action, method, response) limit = response['x-rate-limit-limit'].to_i remaining = response['x-rate-limit-remaining'].to_i reset = response['x-rate-limit-reset'].to_i if limit.nil? or remaining.nil? or reset.nil? return end rate_info_key = get_rate_limit_info_key(action, method) @last_rate_limit_info[rate_info_key] = { limit: limit, remaining: remaining, reset: reset } end def get_rate_limit_info_key(endpoint, method) :"#{endpoint}_#{method.downcase}" end end
dropofwill/rtasklib
lib/rtasklib/controller.rb
Rtasklib.Controller.add_udas_to_model!
ruby
def add_udas_to_model! uda_hash, type=nil, model=Models::TaskModel uda_hash.each do |attr, val| val.each do |k, v| type = Helpers.determine_type(v) if type.nil? model.attribute attr, type end end end
Add new found udas to our internal TaskModel @param uda_hash [Hash{Symbol=>Hash}] @param type [Class, nil] @param model [Models::TaskModel, Class] @api protected
train
https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/controller.rb#L325-L332
module Controller extend self # Retrieves the current task list from the TaskWarrior database. Defaults # to just show active (waiting & pending) tasks, which is usually what is # exposed to the end user through the default reports. To see everything # including completed, deleted, and parent recurring tasks, set # `active: false`. For more granular control see Controller#some. # # @example # tw.all.count #=> 200 # tw.all(active: true) #=> 200 # tw.all(active: false) #=> 578 # # @param active [Boolean] return only pending & waiting tasks # @return [Array<Models::TaskModel>] # @api public def all active: true all = [] f = Helpers.pending_or_waiting(active) Execute.task_popen3(*override_a, f, "export") do |i, o, e, t| all = MultiJson.load(o.read).map do |x| Rtasklib::Models::TaskModel.new(x) end end return all end # Retrieves the current task list filtered by id, tag, or a dom query # # @example filter by an array of ids # tw.some(ids: [1..2, 5]) # @example filter by tags # tw.some(tags: ["+school", "or", "-work"] # # You can also pass in a TW style string if you prefer # tw.some(tags: "+school or -work"] # @example filter by a dom query # require "date" # today = DateTime.now # # note that queries with dots need to be Strings, as they would be # # invalid Symbols # tw.some(dom: {project: "Work", "due.before" => today}) # # You can also pass in a TW style string if you prefer # tw.some(dom: "project:Work due.before:#{today}") # # @param ids [Array<Range, Fixnum, String>, String, Range, Fixnum] # @param tags [Array<String>, String] # @param dom [Array<String>, String] # @param active [Boolean] return only pending & waiting tasks # @return [Array<Models::TaskModel>] # @api public def some ids: nil, tags: nil, dom: nil, active: true some = [] f = Helpers.filter(ids: ids, tags: tags, dom: dom) a = Helpers.pending_or_waiting(active) Execute.task_popen3(*@override_a, f, a, "export") do |i, o, e, t| some = MultiJson.load(o.read).map do |x| Rtasklib::Models::TaskModel.new(x) end end return some end # Count the number of tasks that match a given filter. Faster than counting # an array returned by Controller#all or Controller#some. # # @param ids [Array<Range, Fixnum, String>, String, Range, Fixnum] # @param tags [Array<String>, String] # @param dom [Array<String>, String] # @param active [Boolean] return only pending & waiting tasks # @api public def count ids: nil, tags: nil, dom: nil, active: true f = Helpers.filter(ids: ids, tags: tags, dom: dom) a = Helpers.pending_or_waiting(active) Execute.task_popen3(*@override_a, f, a, "count") do |i, o, e, t| return Integer(o.read) end end alias_method :size, :count alias_method :length, :count # Calls `task _show` with initial overrides returns a Taskrc object of the # result # # @return [Rtasklib::Taskrc] # @api public def get_rc res = [] Execute.task_popen3(*@override_a, "_show") do |i, o, e, t| res = o.read.each_line.map { |l| l.chomp } end Taskrc.new(res, :array) end # Calls `task _version` and returns the result # # @return [String] # @api public def get_version version = nil Execute.task_popen3("_version") do |i, o, e, t| version = Helpers.to_gem_version(o.read.chomp) end version end # Mark the filter of tasks as started # Returns false if filter (ids:, tags:, dom:) is blank. # # @example # tw.start!(ids: 1) # # @param ids [Array<Range, Fixnum, String>, String, Range, Fixnum] # @param tags [Array<String>, String] # @param dom [Array<String>, String] # @param active [Boolean] return only pending & waiting tasks # @return [Process::Status, False] the exit status of the thread or false # if it exited early because filter was blank. # @api public def start! ids: nil, tags: nil, dom: nil, active: true f = Helpers.filter(ids: ids, tags: tags, dom: dom) a = Helpers.pending_or_waiting(active) return false if f.blank? Execute.task_popen3(*@override_a, f, a, "start") do |i, o, e, t| return t.value end end # Mark the filter of tasks as stopped # Returns false if filter (ids:, tags:, dom:) is blank. # # @param ids [Array<Range, Fixnum, String>, String, Range, Fixnum] # @param tags [Array<String>, String] # @param dom [Array<String>, String] # @param active [Boolean] return only pending & waiting tasks # @return [Process::Status, False] the exit status of the thread or false # if it exited early because filter was blank. # @api public def stop! ids: nil, tags: nil, dom: nil, active: true f = Helpers.filter(ids: ids, tags: tags, dom: dom) a = Helpers.pending_or_waiting(active) return false if f.blank? Execute.task_popen3(*@override_a, f, a, "stop") do |i, o, e, t| return t.value end end # Add a single task to the database w/required description and optional # tags and dom queries (e.g. project:Work) # # @param description [String] the required desc of the task # @param tags [Array<String>, String] # @param dom [Array<String>, String] # @return [Process::Status] the exit status of the thread # @api public def add! description, tags: nil, dom: nil f = Helpers.filter(tags: tags, dom: dom) d = Helpers.wrap_string(description) Execute.task_popen3(*override_a, "add", d, f) do |i, o, e, t| return t.value end end # Modify a set of task the match the input filter with a single attr/value # pair. # Returns false if filter (ids:, tags:, dom:) is blank. # # @param attr [String] # @param val [String] # @param ids [Array<Range, Fixnum, String>, String, Range, Fixnum] # @param tags [Array<String>, String] # @param dom [Array<String>, String] # @param active [Boolean] return only pending & waiting tasks # @return [Process::Status] the exit status of the thread # @api public def modify! attr, val, ids: nil, tags: nil, dom: nil, active: true f = Helpers.filter(ids: ids, tags: tags, dom: dom) a = Helpers.pending_or_waiting(active) return false if f.blank? query = "#{f} #{a} modify #{attr}:#{val}" Execute.task_popen3(*override_a, query) do |i, o, e, t| return t.value end end # Finishes the filtered tasks. # Returns false if filter (ids:, tags:, dom:) is blank. # # @param ids [Array<Range, Fixnum, String>, String, Range, Fixnum] # @param tags [Array<String>, String] # @param dom [Array<String>, String] # @param active [Boolean] return only pending & waiting tasks # @return [Process::Status] the exit status of the thread # @api public def done! ids: nil, tags: nil, dom: nil, active: true f = Helpers.filter(ids: ids, tags: tags, dom: dom) a = Helpers.pending_or_waiting(active) return false if f.blank? Execute.task_popen3(*override_a, f, a, "done") do |i, o, e, t| return t.value end end # Returns false if filter is blank. # # @param ids [Array<Range, Fixnum, String>, String, Range, Fixnum] # @param tags [Array<String>, String] # @param dom [Array<String>, String] # @param active [Boolean] return only pending & waiting tasks # @return [Process::Status] the exit status of the thread # @api public def delete! ids: nil, tags: nil, dom: nil, active: true f = Helpers.filter(ids: ids, tags: tags, dom: dom) a = Helpers.pending_or_waiting(active) return false if f.blank? Execute.task_popen3(*override_a, f, a, "delete") do |i, o, e, t| return t.value end end # Directly call `task undo`, which only applies to edits to the task db # not configuration changes # # @api public def undo! Execute.task_popen3(*override_a, "undo") do |i, o, e, t| return t.value end end # Retrieves a hash of hashes with info about the UDAs currently available # # @return [Hash{Symbol=>Hash}] # @api public def get_udas udas = {} taskrc.config.attributes .select { |attr, val| Helpers.uda_attr? attr } .sort .chunk { |attr, val| Helpers.arbitrary_attr attr } .each do |attr, arr| uda = arr.map do |pair| [Helpers.deep_attr(pair[0]), pair[1]] end udas[attr.to_sym] = Hash[uda] end return udas end # Update a configuration variable in the .taskrc # # @param attr [String] # @param val [String] # @return [Process::Status] the exit status of the thread # @api public def update_config! attr, val Execute.task_popen3(*override_a, "config #{attr} #{val}") do |i, o, e, t| return t.value end end # Add new found udas to our internal TaskModel # # @param uda_hash [Hash{Symbol=>Hash}] # @param type [Class, nil] # @param model [Models::TaskModel, Class] # @api protected protected :add_udas_to_model! # Retrieve an array of the uda names # # @return [Array<String>] # @api public def get_uda_names Execute.task_popen3(*@override_a, "_udas") do |i, o, e, t| return o.read.each_line.map { |l| l.chomp } end end # Checks if a given uda exists in the current task database # # @param uda_name [String] the uda name to check for # @return [Boolean] whether it matches or not # @api public def uda_exists? uda_name if get_udas.any? { |uda| uda == uda_name } true else false end end # Add a UDA to the users config/database # # @param name [String] # @param type [String] # @param label [String] # @param values [String] # @param default [String] # @param urgency [String] # @return [Boolean] success # @api public def create_uda! name, type: "string", label: nil, values: nil, default: nil, urgency: nil label = name if label.nil? update_config!("uda.#{name}.type", type) update_config!("uda.#{name}.label", label) update_config!("uda.#{name}.values", values) unless values.nil? update_config!("uda.#{name}.default", default) unless default.nil? update_config!("uda.#{name}.urgency", urgency) unless urgency.nil? end # Sync the local TaskWarrior database changes to the remote databases. # Remotes need to be configured in the .taskrc. # # @example # # make some local changes with add!, modify!, or the like # tw.sync! # # @return [Process::Status] the exit status of the thread # @api public def sync! Execute.task_popen3(*override_a, "sync") do |i, o, e, t| return t.value end end # TODO: implement and test convenience methods for modifying tasks # # def annotate # end # # def denotate # end # # def append # end # # def prepend # end end
Thermatix/ruta
lib/ruta/context.rb
Ruta.Context.component
ruby
def component id,attribs={}, &block self.elements[id] = { attributes: attribs, type: :element, content: block } end
@see #Context#handle_render define a component of the composition @param [Symbol] id of element to mount element contents to @param [{Symbol => String,Number,Boolean}] list of attributes to attach to tag @yield block containing component to be rendered to page @yieldreturn [Object] a component that will be passed to the renderer to be rendered to the page
train
https://github.com/Thermatix/ruta/blob/b4a6e3bc7c0c4b66c804023d638b173e3f61e157/lib/ruta/context.rb#L37-L43
class Context # @!attribute [r] elements # @return [{ref => { attributes: {},type: Symbol, content: Proc,Symbol}] Hash of all elements defined # @!attribute [r] ref # @return [Symbol] this contexts reference in (see #Context#collection) # @!attribute [r,w] handlers # @return [{ref => Proc}] list of route handlers attached to this context # @!attribute [r,w] routes # @return [{ref => Route}] list of all routes attached to this context attr_reader :elements, :ref attr_accessor :handlers, :routes,:sub_contexts DOM = ::Kernel.method(:DOM) # @see #Context#handle_render def initialize ref,block @ref = ref @elements = {} @handlers = {} @routes = {} @sub_contexts = [] instance_exec(&block) if block end # define a component of the composition # # @param [Symbol] id of element to mount element contents to # @param [{Symbol => String,Number,Boolean}] list of attributes to attach to tag # @yield block containing component to be rendered to page # @yieldreturn [Object] a component that will be passed to the renderer to be rendered to the page # mount a context as a sub context here # # @param [Symbol] id of component to mount context to # @param [Symbol] ref of context to be mounted # @param [{Symbol => String,Number,Boolean}] list of attributes to attach to tag def sub_context id,ref,attribs={} @sub_contexts << ref self.elements[id] = { attributes: attribs, type: :sub_context, content: ref, } end class << self # @!attribute [r] collection # @return [{ref => Context}] Hash of all Contexts created # @!attribute [r] renderer # @return [Proc] the renderer used to render and or mount components on to the DOM # @!attribute [r,w] current_context # @return [Symbol] The reference to the current context being rendered attr_reader :collection,:renderer attr_accessor :current_context # Used to tell the router how to render components to the DOM # # @example render a react.rb component to the dom # Ruta::Context.handle_render do |object,element_id| # React.render React.create_element(object), `document.getElementById(#{element_id})` # end # @yield [object,element_id] A block of code that gets executed to render a given object to a given element id # @yieldparam [Object] object to be rendered # @yieldparam [String] ID of page element object will be mounted to def handle_render &block @renderer = block end # used to define a context's page composition # # @example Define a composition for a context called :main # Ruta::Context.define :main do # element :header do # #some code that returns a component # end # # sub_context :info, :info_view # # element :footer do # #some code that returns a component # end # end # @param [Symbol] ref reference to the context being defined # @yield a block that is used to define the composition of a context def define ref, &block @collection[ref] = new(ref,block) end # used to wipe clear an element's content # # @param [String] id of element to be cleared, if no id is provided will clear body tag of content def wipe id=nil if id $document[id].clear else $document.body.clear end end # used to render a composition to the screen # # @param [Symbol] context the context to render # @param [String] id of element context is to be rendered to, if no id is provided will default to body tagt def render context, id=nil this = id ? $document[id]: $document.body context_to_render = @collection[context] render_context_elements context_to_render,context, this render_element_contents context_to_render,context end private def render_context_elements context_to_render,context,this context_to_render.elements.each do |element_name,details| DOM { div(details[:attributes].merge(id: element_name, "data-context" => context)) }.append_to(this) end end def render_element_contents context_to_render,context @current_context = context context_to_render.elements.each do |element_name,details| case details[:type] when :sub_context render details[:content],element_name when :element @renderer.call(details[:content].call,element_name,context) end end @current_context = :no_context end end @collection = {} @current_context = :no_context end
ikayzo/SDL.rb
lib/sdl4r/parser.rb
SDL4R.Parser.add_tag_attributes
ruby
def add_tag_attributes(tag, tokens, start) i = start size = tokens.size while i < size token = tokens[i] if token.type != :IDENTIFIER expecting_but_got("IDENTIFIER", token.type, token.line, token.position) end name_or_namespace = token.text; if i == (size - 1) expecting_but_got( "\":\" or \"=\" \"LITERAL\"", "END OF LINE.", token.line, token.position) end i += 1 token = tokens[i] if token.type == :COLON if i == (size - 1) expecting_but_got( "IDENTIFIER", "END OF LINE", token.line, token.position) end i += 1 token = tokens[i] if token.type != :IDENTIFIER expecting_but_got( "IDENTIFIER", token.type, token.line, token.position) end name = token.text if i == (size - 1) expecting_but_got("\"=\"", "END OF LINE", token.line, token.position) end i += 1 token = tokens[i] if token.type != :EQUALS expecting_but_got("\"=\"", token.type, token.line, token.position) end if i == (size - 1) expecting_but_got("LITERAL", "END OF LINE", token.line, token.position) end i += 1 token = tokens[i] if !token.literal? expecting_but_got("LITERAL", token.type, token.line, token.position) end if token.type == :DATE and (i + 1) < size and tokens[i + 1].type == :TIME date = token.get_object_for_literal() time_span_with_zone = tokens[i + 1].get_object_for_literal() if time_span_with_zone.days != 0 expecting_but_got( "TIME (component of date/time) in attribute value", "TIME SPAN", token.line, token.position) else tag.set_attribute(name_or_namespace, name, combine(date, time_span_with_zone)) end i += 1 else value = token.object_for_literal(); if value.is_a?(TimeSpanWithZone) time_span_with_zone = value if time_span_with_zone.time_zone_offset expecting_but_got( "TIME SPAN", "TIME (component of date/time)", token.line, token.position) end time_span = SdlTimeSpan.new( time_span_with_zone.day, time_span_with_zone.hour, time_span_with_zone.min, time_span_with_zone.sec) tag.set_attribute(name_or_namespace, name, time_span) else tag.set_attribute(name_or_namespace, name, value); end end elsif token.type == :EQUALS if i == (size - 1) expecting_but_got("LITERAL", "END OF LINE", token.line, token.position) end i += 1 token = tokens[i] if !token.literal? expecting_but_got("LITERAL", token.type, token.line, token.position) end if token.type == :DATE and (i + 1) < size and tokens[i + 1].type == :TIME date = token.object_for_literal() time_span_with_zone = tokens[i + 1].object_for_literal() if time_span_with_zone.day != 0 expecting_but_got( "TIME (component of date/time) in attribute value", "TIME SPAN", token.line, token.position) end tag.set_attribute(name_or_namespace, combine(date, time_span_with_zone)) i += 1 else value = token.object_for_literal() if value.is_a?(TimeSpanWithZone) time_span_with_zone = value if time_span_with_zone.time_zone_offset expecting_but_got( "TIME SPAN", "TIME (component of date/time)", token.line, token.position) end time_span = SdlTimeSpan.new( time_span_with_zone.day, time_span_with_zone.hour, time_span_with_zone.min, time_span_with_zone.sec) tag.set_attribute(name_or_namespace, time_span) else tag.set_attribute(name_or_namespace, value); end end else expecting_but_got( "\":\" or \"=\"", token.type, token.line, token.position) end i += 1 end end
Add attributes to the given tag
train
https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/parser.rb#L265-L413
class Parser # Passed to parse_error() in order to specify an error that occured on no specific position # (column). UNKNOWN_POSITION = -2 # Creates an SDL parser on the specified +IO+. # # IO.open("path/to/sdl_file") { |io| # parser = SDL4R::Parser.new(io) # tags = parser.parse() # } # def initialize(io) raise ArgumentError, "io == nil" if io.nil? @tokenizer = Tokenizer.new(io) end # Parses the underlying +IO+ and returns an +Array+ of +Tag+. # # ==Errors # [IOError] If a problem is encountered with the IO # [SdlParseError] If the document is malformed def parse tags = [] while tokens = @tokenizer.read_line_tokens() if tokens.last.type == :START_BLOCK # tag with a block tag = construct_tag(tokens[0...-1]) add_children(tag) tags << tag elsif tokens.first.type == :END_BLOCK # we found an block end token that should have been consumed by # add_children() normally parse_error( "No opening block ({) for close block (}).", tokens.first.line, tokens.first.position) else # tag without block tags << construct_tag(tokens) end end @tokenizer.close() return tags end # Creates and returns the object representing a datetime (DateTime in the default # implementation). Can be overriden. # # def new_date_time(year, month, day, hour, min, sec, time_zone_offset) # Time.utc(year, month, day, hour, min, sec) # end # def new_date_time(year, month, day, hour, min, sec, time_zone_offset) SDL4R::new_date_time(year, month, day, hour, min, sec, time_zone_offset) end private # Parses the children tags of +parent+ until an end of block is found. def add_children(parent) while tokens = @tokenizer.read_line_tokens() if tokens.first.type == :END_BLOCK return elsif tokens.last.type == :START_BLOCK # found a child with a block tag = construct_tag(tokens[0...-1]); add_children(tag) parent.add_child(tag) else parent.add_child(construct_tag(tokens)) end end parse_error("No close block (}).", @tokenizer.line_no, UNKNOWN_POSITION) end # Construct a Tag (but not its children) from a string of tokens # # Throws SdlParseError if some bad syntax is found. def construct_tag(tokens) raise ArgumentError, "tokens == nil" if tokens.nil? if tokens.empty? parse_error("Internal Error: empty token list", @tokenizer.line_no, UNKNOWN_POSITION) end first_token = tokens.first if first_token.literal? first_token = Token.new("content") tokens.insert(0, first_token) elsif first_token.type != :IDENTIFIER expecting_but_got( "IDENTIFIER", "#{first_token.type} (#{first_token.text})", first_token.line, first_token.position) end tag = nil if tokens.size == 1 tag = Tag.new(first_token.text) else values_start_index = 1 second_token = tokens[1] if second_token.type == :COLON if tokens.size == 2 or tokens[2].type != :IDENTIFIER parse_error( "Colon (:) encountered in unexpected location.", second_token.line, second_token.position) end third_token = tokens[2]; tag = Tag.new(first_token.text, third_token.text) values_start_index = 3 else tag = Tag.new(first_token.text) end # read values attribute_start_index = add_tag_values(tag, tokens, values_start_index) # read attributes if attribute_start_index < tokens.size add_tag_attributes(tag, tokens, attribute_start_index) end end return tag end # # @return The position at the end of the value list # def add_tag_values(tag, tokens, start) size = tokens.size() i = start; while i < size token = tokens[i] if token.literal? # if a DATE token is followed by a TIME token combine them next_token = ((i + 1) < size)? tokens[i + 1] : nil if token.type == :DATE && next_token && next_token.type == :TIME date = token.object_for_literal() time_zone_with_zone = next_token.object_for_literal() if time_zone_with_zone.day != 0 # as there are days specified, it can't be a full precision date tag.add_value(date); tag.add_value( SdlTimeSpan.new( time_zone_with_zone.day, time_zone_with_zone.hour, time_zone_with_zone.min, time_zone_with_zone.sec)) if time_zone_with_zone.time_zone_offset parse_error("TimeSpan cannot have a timeZone", t.line, t.position) end else tag.add_value(combine(date, time_zone_with_zone)) end i += 1 else value = token.object_for_literal() if value.is_a?(TimeSpanWithZone) # the literal looks like a time zone if value.time_zone_offset expecting_but_got( "TIME SPAN", "TIME (component of date/time)", token.line, token.position) end tag.add_value( SdlTimeSpan.new( value.day, value.hour, value.min, value.sec)) else tag.add_value(value) end end elsif token.type == :IDENTIFIER break else expecting_but_got( "LITERAL or IDENTIFIER", token.type, token.line, token.position) end i += 1 end return i end # # Add attributes to the given tag # def add_tag_attributes(tag, tokens, start) i = start size = tokens.size while i < size token = tokens[i] if token.type != :IDENTIFIER expecting_but_got("IDENTIFIER", token.type, token.line, token.position) end name_or_namespace = token.text; if i == (size - 1) expecting_but_got( "\":\" or \"=\" \"LITERAL\"", "END OF LINE.", token.line, token.position) end i += 1 token = tokens[i] if token.type == :COLON if i == (size - 1) expecting_but_got( "IDENTIFIER", "END OF LINE", token.line, token.position) end i += 1 token = tokens[i] if token.type != :IDENTIFIER expecting_but_got( "IDENTIFIER", token.type, token.line, token.position) end name = token.text if i == (size - 1) expecting_but_got("\"=\"", "END OF LINE", token.line, token.position) end i += 1 token = tokens[i] if token.type != :EQUALS expecting_but_got("\"=\"", token.type, token.line, token.position) end if i == (size - 1) expecting_but_got("LITERAL", "END OF LINE", token.line, token.position) end i += 1 token = tokens[i] if !token.literal? expecting_but_got("LITERAL", token.type, token.line, token.position) end if token.type == :DATE and (i + 1) < size and tokens[i + 1].type == :TIME date = token.get_object_for_literal() time_span_with_zone = tokens[i + 1].get_object_for_literal() if time_span_with_zone.days != 0 expecting_but_got( "TIME (component of date/time) in attribute value", "TIME SPAN", token.line, token.position) else tag.set_attribute(name_or_namespace, name, combine(date, time_span_with_zone)) end i += 1 else value = token.object_for_literal(); if value.is_a?(TimeSpanWithZone) time_span_with_zone = value if time_span_with_zone.time_zone_offset expecting_but_got( "TIME SPAN", "TIME (component of date/time)", token.line, token.position) end time_span = SdlTimeSpan.new( time_span_with_zone.day, time_span_with_zone.hour, time_span_with_zone.min, time_span_with_zone.sec) tag.set_attribute(name_or_namespace, name, time_span) else tag.set_attribute(name_or_namespace, name, value); end end elsif token.type == :EQUALS if i == (size - 1) expecting_but_got("LITERAL", "END OF LINE", token.line, token.position) end i += 1 token = tokens[i] if !token.literal? expecting_but_got("LITERAL", token.type, token.line, token.position) end if token.type == :DATE and (i + 1) < size and tokens[i + 1].type == :TIME date = token.object_for_literal() time_span_with_zone = tokens[i + 1].object_for_literal() if time_span_with_zone.day != 0 expecting_but_got( "TIME (component of date/time) in attribute value", "TIME SPAN", token.line, token.position) end tag.set_attribute(name_or_namespace, combine(date, time_span_with_zone)) i += 1 else value = token.object_for_literal() if value.is_a?(TimeSpanWithZone) time_span_with_zone = value if time_span_with_zone.time_zone_offset expecting_but_got( "TIME SPAN", "TIME (component of date/time)", token.line, token.position) end time_span = SdlTimeSpan.new( time_span_with_zone.day, time_span_with_zone.hour, time_span_with_zone.min, time_span_with_zone.sec) tag.set_attribute(name_or_namespace, time_span) else tag.set_attribute(name_or_namespace, value); end end else expecting_but_got( "\":\" or \"=\"", token.type, token.line, token.position) end i += 1 end end # Combines a simple Date with a TimeSpanWithZone to create a DateTime # def combine(date, time_span_with_zone) time_zone_offset = time_span_with_zone.time_zone_offset time_zone_offset = TimeSpanWithZone.default_time_zone_offset if time_zone_offset.nil? new_date_time( date.year, date.month, date.day, time_span_with_zone.hour, time_span_with_zone.min, time_span_with_zone.sec, time_zone_offset) end private ############################################################################ ## Parsers for types ############################################################################ def Parser.parse_string(literal) unless literal =~ /(^`.*`$)|(^\".*\"$)/m raise ArgumentError, "Malformed string <#{literal}>." + " Strings must start and end with \" or `" end return literal[1..-2] end def Parser.parse_character(literal) unless literal =~ /(^'.*'$)/ raise ArgumentError, "Malformed character <#{literal}>." + " Character must start and end with single quotes" end return literal[1] end def Parser.parse_number(literal) # we use the fact that Kernel.Integer() and Kernel.Float() raise ArgumentErrors if literal =~ /(.*)(L)$/i return Integer($1) elsif literal =~ /([^BDF]*)(BD)$/i return BigDecimal($1) elsif literal =~ /([^BDF]*)(F|D)$/i return Float($1) elsif literal.count(".e") == 0 return Integer(literal) else return Float(literal) end end # Parses the given literal into a returned array # [days, hours, minutes, seconds, time_zone_offset]. # 'days', 'hours' and 'minutes' are integers. # 'seconds' and 'time_zone_offset' are rational numbers. # 'days' and 'seconds' are equal to 0 if they're not specified in ((|literal|)). # 'time_zone_offset' is equal to nil if not specified. # # ((|allowDays|)) indicates whether the specification of days is allowed # in ((|literal|)) # ((|allowTimeZone|)) indicates whether the specification of the timeZone is # allowed in ((|literal|)) # # All components are returned disregarding the values of ((|allowDays|)) and # ((|allowTimeZone|)). # # Raises an ArgumentError if ((|literal|)) has a bad format. def Parser.parse_time_span_and_time_zone(literal, allowDays, allowTimeZone) overall_sign = (literal =~ /^-/)? -1 : +1 if literal =~ /^(([+\-]?\d+)d:)/ if allowDays days = Integer($2) days_specified = true time_part = literal[($1.length)..-1] else # detected a day specification in a pure time literal raise ArgumentError, "unexpected day specification in #{literal}" end else days = 0; days_specified = false time_part = literal end # We have to parse the string ourselves because AFAIK : # - strptime() can't parse milliseconds # - strptime() can't parse the time zone custom offset (CET+02:30) # - strptime() accepts trailing chars # (e.g. "12:24-xyz@" ==> "xyz@" is obviously wrong but strptime() # won't mind) if time_part =~ /^([+-]?\d+):(\d+)(?::(\d+)(?:\.(\d+))?)?(?:(?:-([a-zA-Z]+))?(?:([\+\-]\d+)(?::(\d+))?)?)?$/i hours = $1.to_i minutes = $2.to_i # seconds and milliseconds are implemented as one rational number # unless there are no milliseconds millisecond_part = ($4)? $4.ljust(3, "0") : nil if millisecond_part seconds = Rational(($3 + millisecond_part).to_i, 10 ** millisecond_part.length) else seconds = ($3)? Integer($3) : 0 end if ($5 or $6) and not allowTimeZone raise ArgumentError, "unexpected time zone specification in #{literal}" end time_zone_code = $5 # might be nil if $6 zone_custom_minute_offset = $6.to_i * 60 if $7 if zone_custom_minute_offset > 0 zone_custom_minute_offset = zone_custom_minute_offset + $7.to_i else zone_custom_minute_offset = zone_custom_minute_offset - $7.to_i end end end time_zone_offset = get_time_zone_offset(time_zone_code, zone_custom_minute_offset) if not allowDays and $1 =~ /^[+-]/ # unexpected timeSpan syntax raise ArgumentError, "unexpected sign on hours : #{literal}" end # take the sign into account hours *= overall_sign if days_specified # otherwise the sign is already applied to the hours minutes *= overall_sign seconds *= overall_sign return [ days, hours, minutes, seconds, time_zone_offset ] else raise ArgumentError, "bad time component : #{literal}" end end # Parses the given literal (String) into a returned DateTime object. # # Raises an ArgumentError if ((|literal|)) has a bad format. def Parser.parse_date_time(literal) raise ArgumentError("date literal is nil") if literal.nil? begin parts = literal.split(" ") if parts.length == 1 return parse_date(literal) else date = parse_date(parts[0]); time_part = parts[1] days, hours, minutes, seconds, time_zone_offset = parse_time_span_and_time_zone(time_part, false, true) return new_date_time( date.year, date.month, date.day, hours, minutes, seconds, time_zone_offset) end rescue ArgumentError raise ArgumentError, "Bad date/time #{literal} : #{$!.message}" end end ## # Returns the time zone offset (Rational) corresponding to the provided parameters as a fraction # of a day. This method adds the two offsets if they are both provided. # # +time_zone_code+: can be nil # +custom_minute_offset+: can be nil # def Parser.get_time_zone_offset(time_zone_code, custom_minute_offset) return nil unless time_zone_code or custom_minute_offset time_zone_offset = custom_minute_offset ? Rational(custom_minute_offset, 60 * 24) : 0 return time_zone_offset unless time_zone_code # we have to provide some bogus year/month/day in order to parse our time zone code d = DateTime.strptime("1999/01/01 #{time_zone_code}", "%Y/%m/%d %Z") # the offset is a fraction of a day return d.offset() + time_zone_offset end # Parses the +literal+ into a returned Date object. # # Raises an ArgumentError if +literal+ has a bad format. def Parser.parse_date(literal) # here, we're being stricter than strptime() alone as we forbid trailing chars if literal =~ /^(\d+)\/(\d+)\/(\d+)$/ begin return Date.strptime(literal, "%Y/%m/%d") rescue ArgumentError raise ArgumentError, "Malformed Date <#{literal}> : #{$!.message}" end end raise ArgumentError, "Malformed Date <#{literal}>" end # Returns a String that contains the binary content corresponding to ((|literal|)). # # ((|literal|)) : a base-64 encoded literal (e.g. # "[V2hvIHdhbnRzIHRvIGxpdmUgZm9yZXZlcj8=]") def Parser.parse_binary(literal) clean_literal = literal[1..-2] # remove square brackets return SdlBinary.decode64(clean_literal) end # Parses +literal+ (String) into the corresponding SDLTimeSpan, which is then # returned. # # Raises an ArgumentError if the literal is not a correct timeSpan literal. def Parser.parse_time_span(literal) days, hours, minutes, seconds, time_zone_offset = parse_time_span_and_time_zone(literal, true, false) milliseconds = ((seconds - seconds.to_i) * 1000).to_i seconds = seconds.to_i return SDLTimeSpan.new(days, hours, minutes, seconds, milliseconds) end # Close the reader and throw a SdlParseError using the format # Was expecting X but got Y. # def expecting_but_got(expecting, got, line, position) @tokenizer.expecting_but_got(expecting, got, line, position) end end
etewiah/property_web_builder
app/services/pwb/page_part_manager.rb
Pwb.PagePartManager.rebuild_page_content
ruby
def rebuild_page_content(locale) unless page_part && page_part.template raise "page_part with valid template not available" end # page_part = self.page_parts.find_by_page_part_key page_part_key if page_part.present? l_template = Liquid::Template.parse(page_part.template) new_fragment_html = l_template.render('page_part' => page_part.block_contents[locale]["blocks"] ) # p "#{page_part_key} content for #{self.slug} page parsed." # save in content model associated with page page_fragment_content = find_or_create_content # container.contents.find_or_create_by(page_part_key: page_part_key) content_html_col = "raw_" + locale + "=" # above is the col used by globalize gem to store localized data # page_fragment_content[content_html_col] = new_fragment_html page_fragment_content.send content_html_col, new_fragment_html page_fragment_content.save! # set page_part_key value on join model page_content_join_model = get_join_model # page_fragment_content.page_contents.find_by_page_id self.id page_content_join_model.page_part_key = page_part_key page_content_join_model.save! else new_fragment_html = "" end new_fragment_html end
Will retrieve saved page_part blocks and use that along with template to rebuild page_content html
train
https://github.com/etewiah/property_web_builder/blob/fba4e6d4ffa7bc1f4d3b50dfa5a6a9fbfee23f21/app/services/pwb/page_part_manager.rb#L153-L183
class PagePartManager attr_accessor :page_part_key, :page_part, :container def initialize(page_part_key, container) raise "Please provide valid container" unless container.present? self.page_part_key = page_part_key # container can be either a page or the website self.container = container self.page_part = container.get_page_part page_part_key # PagePart.find_by_page_part_key page_part_key raise "Please provide valid page_part_key" unless page_part.present? end def find_or_create_content # sets up the connection between a container and content model # ensuring the intermediate page_content join is created too page_content_join_model = find_or_create_join_model unless page_content_join_model.content.present? page_content_join_model.create_content(page_part_key: page_part_key) # without calling save! below, content and page_content will not be associated page_content_join_model.save! end page_content_join_model.content # just creating contents like below will result in join_model without page_part_key # page_fragment_content = container.contents.find_or_create_by(page_part_key: page_part_key) end def find_or_create_join_model # Particularly important for rails_parts # They may may not have content to seed but this # call is needed when seeding to set up r/n between # container (page or website) and content page_content_join_model = container.page_contents.find_or_create_by(page_part_key: page_part_key) if page_part.is_rails_part page_content_join_model.is_rails_part = true page_content_join_model.save! end page_content_join_model end # TODO: Use below for page_part_content_spec def get_seed_content(locale) locale_seed_file = Pwb::Engine.root.join('db', 'yml_seeds', 'content_translations', locale.to_s + '.yml') raise Exception, "Contents seed for #{locale} not found" unless File.exist? locale_seed_file yml = YAML.load_file(locale_seed_file) if yml[locale] && yml[locale][container_label] && yml[locale][container_label][page_part_key] seed_content = yml[locale][container_label][page_part_key] page_part_manager.seed_container_block_content locale, seed_content p "#{container_label} #{page_part_key} content set for #{locale}." end end # seed_content is ... def seed_container_block_content(locale, seed_content) page_part_editor_setup = page_part.editor_setup raise "Invalid editorBlocks for page_part_editor_setup" unless page_part_editor_setup && page_part_editor_setup["editorBlocks"].present? # page = page_part.page # page_part_key uniquely identifies a fragment # page_part_key = page_part.page_part_key # container for json to be attached to page details locale_block_content_json = {"blocks" => {}} # {"blocks"=>{"title_a"=>{"content"=>"about our agency"}, "content_a"=>{"content"=>""}}} page_part_editor_setup["editorBlocks"].each do |configColBlocks| configColBlocks.each do |configRowBlock| row_block_label = configRowBlock["label"] row_block_content = "" # find the content for current block from within the seed content if seed_content[row_block_label] if configRowBlock["isImage"] photo = seed_fragment_photo row_block_label, seed_content[row_block_label] if photo.present? && photo.optimized_image_url.present? # optimized_image_url is defined in content_photo and will # return cloudinary url or filesystem url depending on settings row_block_content = photo.optimized_image_url else row_block_content = "http://via.placeholder.com/350x250" end else row_block_content = seed_content[row_block_label] end end locale_block_content_json["blocks"][row_block_label] = {"content" => row_block_content} end end # # save the block contents (in associated page_part model) # updated_details = container.set_page_part_block_contents page_part_key, locale, locale_block_content_json # # retrieve the contents saved above and use to rebuild html for that page_part # # (and save it in associated page_content model) # fragment_html = container.rebuild_page_content page_part_key, locale update_page_part_content locale, locale_block_content_json p " #{page_part_key} content set for #{locale}." end def update_page_part_content(locale, fragment_block) # save the block contents (in associated page_part model) json_fragment_block = set_page_part_block_contents page_part_key, locale, fragment_block # retrieve the contents saved above and use to rebuild html for that page_part # (and save it in associated page_content model) fragment_html = rebuild_page_content locale { json_fragment_block: json_fragment_block, fragment_html: fragment_html } end def set_default_page_content_order_and_visibility join_model = get_join_model unless join_model puts "Unable to set_default_page_content_order_and_visibility for #{page_part_key}" return end page_part_editor_setup = page_part.editor_setup # page = page_part.page # # page_part_key uniquely identifies a fragment # page_part_key = page_part.page_part_key sort_order = page_part_editor_setup["default_sort_order"] || 1 join_model.sort_order = sort_order visible_on_page = false if page_part_editor_setup["default_visible_on_page"] visible_on_page = true end join_model.visible_on_page = visible_on_page join_model.save! end private def get_join_model container.page_contents.find_by_page_part_key page_part_key end # set block contents # on page_part model def set_page_part_block_contents(_page_part_key, locale, fragment_details) # page_part = self.page_parts.find_by_page_part_key page_part_key if page_part.present? page_part.block_contents[locale] = fragment_details page_part.save! # fragment_details passed in might be a params object # - retrieving what has just been saved will return it as JSON fragment_details = page_part.block_contents[locale] end fragment_details end # Will retrieve saved page_part blocks and use that along with template # to rebuild page_content html # when seeding I only need to ensure that a photo exists for the fragment # so will return existing photo if it can be found def seed_fragment_photo(block_label, photo_file) # content_key = self.slug + "_" + page_part_key # get in content model associated with page and fragment # join_model = page_contents.find_or_create_by(page_part_key: page_part_key) # page_fragment_content = join_model.create_content(page_part_key: page_part_key) # join_model.save! # page_fragment_content = contents.find_or_create_by(page_part_key: page_part_key) page_fragment_content = find_or_create_content photo = page_fragment_content.content_photos.find_by_block_key(block_label) if photo.present? return photo else photo = page_fragment_content.content_photos.create(block_key: block_label) end if ENV["RAILS_ENV"] == "test" # don't create photos for tests return nil end begin # if photo_file.is_a?(String) # photo.image = photo_file photo.image = Pwb::Engine.root.join(photo_file).open photo.save! print "#{slug}--#{page_part_key} image created: #{photo.optimized_image_url}\n" # reload the record to ensure that url is available photo.reload print "#{slug}--#{page_part_key} image created: #{photo.optimized_image_url}(after reload..)" rescue Exception => e # log exception to console print e end photo end end
osulp/triplestore-adapter
lib/triplestore_adapter/providers/blazegraph.rb
TriplestoreAdapter::Providers.Blazegraph.delete
ruby
def delete(statements) raise(TriplestoreAdapter::TriplestoreException, "delete received invalid array of statements") unless statements.any? #TODO: Evaluate that all statements are singular, and without bnodes? writer = RDF::Writer.for(:jsonld) uri = URI.parse("#{@uri}?delete") request = Net::HTTP::Post.new(uri) request['Content-Type'] = 'application/ld+json' request.body = writer.dump(statements) @http.request(uri, request) return true end
Delete the provided statements from the triplestore @param [RDF::Enumerable] statements to delete from the triplestore @return [Boolean] true if the delete was successful
train
https://github.com/osulp/triplestore-adapter/blob/597fa5842f846e57cba7574da873f1412ab76ffa/lib/triplestore_adapter/providers/blazegraph.rb#L39-L50
class Blazegraph attr_reader :url, :sparql_client ## # @param [String] url of SPARQL endpoint def initialize(url) @http = Net::HTTP::Persistent.new(self.class) @url = url @uri = URI.parse(@url.to_s) @sparql_client = SPARQL::Client.new(@uri) end ## # Insert the provided statements into the triplestore, JSONLD allows for # UTF8 charset. # @param [RDF::Enumerable] statements to insert into triplestore # @return [Boolean] true if the insert was successful def insert(statements) raise(TriplestoreAdapter::TriplestoreException, "insert received an invalid array of statements") unless statements.any? writer = RDF::Writer.for(:jsonld) request = Net::HTTP::Post.new(@uri) request['Content-Type'] = 'application/ld+json' request.body = writer.dump(statements) @http.request(@uri, request) return true end ## # Delete the provided statements from the triplestore # @param [RDF::Enumerable] statements to delete from the triplestore # @return [Boolean] true if the delete was successful ## # Returns statements matching the subject # @param [String] subject url # @return [RDF::Enumerable] RDF statements def get_statements(subject: nil) raise(TriplestoreAdapter::TriplestoreException, "get_statements received blank subject") if subject.empty? subject = URI.escape(subject.to_s) uri = URI.parse(format("%{uri}?GETSTMTS&s=<%{subject}>&includeInferred=false", {uri: @uri, subject: subject})) request = Net::HTTP::Get.new(uri) response = @http.request(uri, request) RDF::Reader.for(:ntriples).new(response.body) end ## # Clear all statements from the triplestore contained in the namespace # specified in the @uri. *BE CAREFUL* # @return [Boolean] true if the triplestore was cleared def clear_statements request = Net::HTTP::Delete.new(@uri) @http.request(@uri, request) return true end ## # Create a new namespace on the triplestore # @param [String] namespace to be built # @return [String] URI for the new namespace def build_namespace(namespace) raise(TriplestoreAdapter::TriplestoreException, "build_namespace received blank namespace") if namespace.empty? request = Net::HTTP::Post.new("#{build_url}/blazegraph/namespace") request['Content-Type'] = 'text/plain' request.body = "com.bigdata.rdf.sail.namespace=#{namespace}" @http.request(@uri, request) "#{build_url}/blazegraph/namespace/#{namespace}/sparql" end ## # Delete the namespace from the triplestore. *BE CAREFUL* # @param [String] namespace to be deleted # @return [Boolean] true if the namespace was deleted def delete_namespace(namespace) raise(TriplestoreAdapter::TriplestoreException, "delete_namespace received blank namespace") if namespace.empty? request = Net::HTTP::Delete.new("#{build_url}/blazegraph/namespace/#{namespace}") @http.request(@uri, request) return true end private def build_url port = ":#{@uri.port}" if @uri.port != 80 "#{@uri.scheme}://#{@uri.host}#{port}" end end
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.build_collection_query_object
ruby
def build_collection_query_object(name, additional_parameters, *args) root = "/#{name.to_s}" if args.empty? #nothing to add elsif args.size == 1 if args.first.to_s =~ /\d+/ id_metadata = find_id_metadata(name.to_s) root << build_id_path(args.first, id_metadata) else root << "(#{args.first})" end else root << "(#{args.join(',')})" end QueryBuilder.new(root, additional_parameters) end
Constructs a QueryBuilder instance for a collection using the arguments provided. @param [String] name the name of the collection @param [Hash] additional_parameters the additional parameters @param [Array] args the arguments to use for query
train
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L178-L193
class Service attr_reader :classes, :class_metadata, :options, :collections, :edmx, :function_imports, :response # Creates a new instance of the Service class # # @param [String] service_uri the root URI of the OData service # @param [Hash] options the options to pass to the service # @option options [String] :username for http basic auth # @option options [String] :password for http basic auth # @option options [Object] :verify_ssl false if no verification, otherwise mode (OpenSSL::SSL::VERIFY_PEER is default) # @option options [Hash] :rest_options a hash of rest-client options that will be passed to all OData::Resource.new calls # @option options [Hash] :additional_params a hash of query string params that will be passed on all calls # @option options [Boolean, true] :eager_partial true if queries should consume partial feeds until the feed is complete, false if explicit calls to next must be performed def initialize(service_uri, options = {}) @uri = service_uri.gsub!(/\/?$/, '') set_options! options default_instance_vars! set_namespaces build_collections_and_classes end # Handles the dynamic `AddTo<EntityName>` methods as well as the collections on the service def method_missing(name, *args) # Queries if @collections.include?(name.to_s) @query = build_collection_query_object(name,@additional_params, *args) return @query # Adds elsif name.to_s =~ /^AddTo(.*)/ type = $1 if @collections.include?(type) @save_operations << Operation.new("Add", $1, args[0]) else super end elsif @function_imports.include?(name.to_s) execute_import_function(name.to_s, args) else super end end # Queues an object for deletion. To actually remove it from the server, you must call save_changes as well. # # @param [Object] obj the object to mark for deletion # # @raise [NotSupportedError] if the `obj` isn't a tracked entity def delete_object(obj) type = obj.class.to_s if obj.respond_to?(:__metadata) && !obj.send(:__metadata).nil? @save_operations << Operation.new("Delete", type, obj) else raise OData::NotSupportedError.new "You cannot delete a non-tracked entity" end end # Queues an object for update. To actually update it on the server, you must call save_changes as well. # # @param [Object] obj the object to queue for update # # @raise [NotSupportedError] if the `obj` isn't a tracked entity def update_object(obj) type = obj.class.to_s if obj.respond_to?(:__metadata) && !obj.send(:__metadata).nil? @save_operations << Operation.new("Update", type, obj) else raise OData::NotSupportedError.new "You cannot update a non-tracked entity" end end # Performs save operations (Create/Update/Delete) against the server def save_changes return nil if @save_operations.empty? result = nil begin if @save_operations.length == 1 result = single_save(@save_operations[0]) else result = batch_save(@save_operations) end # TODO: We should probably perform a check here # to make sure everything worked before clearing it out @save_operations.clear return result rescue Exception => e handle_exception(e) end end # Performs query operations (Read) against the server. # Typically this returns an array of record instances, except in the case of count queries # @raise [ServiceError] if there is an error when talking to the service def execute begin @response = OData::Resource.new(build_query_uri, @rest_options).get rescue Exception => e handle_exception(e) end return Integer(@response.body) if @response.body =~ /\A\d+\z/ handle_collection_result(@response.body) end # Overridden to identify methods handled by method_missing def respond_to?(method) if @collections.include?(method.to_s) return true # Adds elsif method.to_s =~ /^AddTo(.*)/ type = $1 if @collections.include?(type) return true else super end # Function Imports elsif @function_imports.include?(method.to_s) return true else super end end # Retrieves the next resultset of a partial result (if any). Does not honor the `:eager_partial` option. def next return if not partial? handle_partial end # Does the most recent collection returned represent a partial collection? Will aways be false if a query hasn't executed, even if the query would have a partial def partial? @has_partial end # Lazy loads a navigation property on a model # # @param [Object] obj the object to fill # @param [String] nav_prop the navigation property to fill # # @raise [NotSupportedError] if the `obj` isn't a tracked entity # @raise [ArgumentError] if the `nav_prop` isn't a valid navigation property def load_property(obj, nav_prop) raise NotSupportedError, "You cannot load a property on an entity that isn't tracked" if obj.send(:__metadata).nil? raise ArgumentError, "'#{nav_prop}' is not a valid navigation property" unless obj.respond_to?(nav_prop.to_sym) raise ArgumentError, "'#{nav_prop}' is not a valid navigation property" unless @class_metadata[obj.class.to_s][nav_prop].nav_prop results = OData::Resource.new(build_load_property_uri(obj, nav_prop), @rest_options).get prop_results = build_classes_from_result(results.body) obj.send "#{nav_prop}=", (singular?(nav_prop) ? prop_results.first : prop_results) end # Adds a child object to a parent object's collection # # @param [Object] parent the parent object # @param [String] nav_prop the name of the navigation property to add the child to # @param [Object] child the child object # @raise [NotSupportedError] if the `parent` isn't a tracked entity # @raise [ArgumentError] if the `nav_prop` isn't a valid navigation property # @raise [NotSupportedError] if the `child` isn't a tracked entity def add_link(parent, nav_prop, child) raise NotSupportedError, "You cannot add a link on an entity that isn't tracked (#{parent.class})" if parent.send(:__metadata).nil? raise ArgumentError, "'#{nav_prop}' is not a valid navigation property for #{parent.class}" unless parent.respond_to?(nav_prop.to_sym) raise ArgumentError, "'#{nav_prop}' is not a valid navigation property for #{parent.class}" unless @class_metadata[parent.class.to_s][nav_prop].nav_prop raise NotSupportedError, "You cannot add a link on a child entity that isn't tracked (#{child.class})" if child.send(:__metadata).nil? @save_operations << Operation.new("AddLink", nav_prop, parent, child) end private # Constructs a QueryBuilder instance for a collection using the arguments provided. # # @param [String] name the name of the collection # @param [Hash] additional_parameters the additional parameters # @param [Array] args the arguments to use for query # Finds the metadata associated with the given collection's first id property # Remarks: This is used for single item lookup queries using the ID, e.g. Products(1), not complex primary keys # # @param [String] collection_name the name of the collection def find_id_metadata(collection_name) collection_data = @collections.fetch(collection_name) class_metadata = @class_metadata.fetch(collection_data[:type].to_s) key = class_metadata.select{|k,h| h.is_key }.collect{|k,h| h.name }[0] class_metadata[key] end # Builds the ID expression of a given id for query # # @param [Object] id_value the actual value to be used # @param [PropertyMetadata] id_metadata the property metadata object for the id def build_id_path(id_value, id_metadata) if id_metadata.type == "Edm.Int64" "(#{id_value}L)" else "(#{id_value})" end end def set_options!(options) @options = options if @options[:eager_partial].nil? @options[:eager_partial] = true end @rest_options = { :verify_ssl => get_verify_mode, :user => @options[:username], :password => @options[:password] } @rest_options.merge!(options[:rest_options] || {}) @additional_params = options[:additional_params] || {} @namespace = options[:namespace] @json_type = options[:json_type] || 'application/json' end def default_instance_vars! @collections = {} @function_imports = {} @save_operations = [] @has_partial = false @next_uri = nil end def set_namespaces @edmx = Nokogiri::XML(OData::Resource.new(build_metadata_uri, @rest_options).get.body) @ds_namespaces = { "m" => "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata", "edmx" => "http://schemas.microsoft.com/ado/2007/06/edmx", "ds" => "http://schemas.microsoft.com/ado/2007/08/dataservices", "atom" => "http://www.w3.org/2005/Atom" } # Get the edm namespace from the edmx edm_ns = @edmx.xpath("edmx:Edmx/edmx:DataServices/*", @namespaces).first.namespaces['xmlns'].to_s @ds_namespaces.merge! "edm" => edm_ns end # Gets ssl certificate verification mode, or defaults to verify_peer def get_verify_mode if @options[:verify_ssl].nil? return OpenSSL::SSL::VERIFY_PEER else return @options[:verify_ssl] end end # Build the classes required by the metadata def build_collections_and_classes @classes = Hash.new @class_metadata = Hash.new # This is used to store property information about a class # Build complex types first, these will be used for entities complex_types = @edmx.xpath("//edm:ComplexType", @ds_namespaces) || [] complex_types.each do |c| name = qualify_class_name(c['Name']) props = c.xpath(".//edm:Property", @ds_namespaces) methods = props.collect { |p| p['Name'] } # Standard Properties @classes[name] = ClassBuilder.new(name, methods, [], self, @namespace).build unless @classes.keys.include?(name) end entity_types = @edmx.xpath("//edm:EntityType", @ds_namespaces) entity_types.each do |e| next if e['Abstract'] == "true" klass_name = qualify_class_name(e['Name']) methods = collect_properties(klass_name, e, @edmx) nav_props = collect_navigation_properties(klass_name, e, @edmx) @classes[klass_name] = ClassBuilder.new(klass_name, methods, nav_props, self, @namespace).build unless @classes.keys.include?(klass_name) end # Fill in the collections instance variable collections = @edmx.xpath("//edm:EntityContainer/edm:EntitySet", @ds_namespaces) collections.each do |c| entity_type = c["EntityType"] @collections[c["Name"]] = { :edmx_type => entity_type, :type => convert_to_local_type(entity_type) } end build_function_imports end # Parses the function imports and fills the @function_imports collection def build_function_imports # Fill in the function imports functions = @edmx.xpath("//edm:EntityContainer/edm:FunctionImport", @ds_namespaces) functions.each do |f| http_method_attribute = f.xpath("@m:HttpMethod", @ds_namespaces).first # HttpMethod is no longer required http://www.odata.org/2011/10/actions-in-odata/ is_side_effecting_attribute = f.xpath("@edm:IsSideEffecting", @ds_namespaces).first http_method = 'POST' # default to POST if http_method_attribute http_method = http_method_attribute.content elsif is_side_effecting_attribute is_side_effecting = is_side_effecting_attribute.content http_method = is_side_effecting ? 'POST' : 'GET' end return_type = f["ReturnType"] inner_return_type = nil unless return_type.nil? return_type = (return_type =~ /^Collection/) ? Array : convert_to_local_type(return_type) if f["ReturnType"] =~ /\((.*)\)/ inner_return_type = convert_to_local_type($~[1]) end end params = f.xpath("edm:Parameter", @ds_namespaces) parameters = nil if params.length > 0 parameters = {} params.each do |p| parameters[p["Name"]] = p["Type"] end end @function_imports[f["Name"]] = { :http_method => http_method, :return_type => return_type, :inner_return_type => inner_return_type, :parameters => parameters } end end # Converts the EDMX model type to the local model type def convert_to_local_type(edmx_type) return edm_to_ruby_type(edmx_type) if edmx_type =~ /^Edm/ klass_name = qualify_class_name(edmx_type.split('.').last) klass_name.camelize.constantize end # Converts a class name to its fully qualified name (if applicable) and returns the new name def qualify_class_name(klass_name) unless @namespace.nil? || @namespace.blank? || klass_name.include?('::') namespaces = @namespace.split(/\.|::/) namespaces << klass_name klass_name = namespaces.join '::' end klass_name.camelize end # Builds the metadata need for each property for things like feed customizations and navigation properties def build_property_metadata(props, keys=[]) metadata = {} props.each do |property_element| prop_meta = PropertyMetadata.new(property_element) prop_meta.is_key = keys.include?(prop_meta.name) # If this is a navigation property, we need to add the association to the property metadata prop_meta.association = Association.new(property_element, @edmx) if prop_meta.nav_prop metadata[prop_meta.name] = prop_meta end metadata end # Handle parsing of OData Atom result and return an array of Entry classes def handle_collection_result(result) results = build_classes_from_result(result) while partial? && @options[:eager_partial] results.concat handle_partial end results end # Handles errors from the OData service def handle_exception(e) raise e unless defined?(e.response) && e.response != nil code = e.response[:status] error = Nokogiri::XML(e.response[:body]) message = if error.xpath("m:error/m:message", @ds_namespaces).first error.xpath("m:error/m:message", @ds_namespaces).first.content else "Server returned error but no message." end raise ServiceError.new(code), message end # Loops through the standard properties (non-navigation) for a given class and returns the appropriate list of methods def collect_properties(klass_name, element, doc) props = element.xpath(".//edm:Property", @ds_namespaces) key_elemnts = element.xpath(".//edm:Key//edm:PropertyRef", @ds_namespaces) keys = key_elemnts.collect { |k| k['Name'] } @class_metadata[klass_name] = build_property_metadata(props, keys) methods = props.collect { |p| p['Name'] } unless element["BaseType"].nil? base = element["BaseType"].split(".").last() baseType = doc.xpath("//edm:EntityType[@Name=\"#{base}\"]", @ds_namespaces).first() props = baseType.xpath(".//edm:Property", @ds_namespaces) @class_metadata[klass_name].merge!(build_property_metadata(props)) methods = methods.concat(props.collect { |p| p['Name']}) end methods end # Similar to +collect_properties+, but handles the navigation properties def collect_navigation_properties(klass_name, element, doc) nav_props = element.xpath(".//edm:NavigationProperty", @ds_namespaces) @class_metadata[klass_name].merge!(build_property_metadata(nav_props)) nav_props.collect { |p| p['Name'] } end # Helper to loop through a result and create an instance for each entity in the results def build_classes_from_result(result) doc = Nokogiri::XML(result) is_links = doc.at_xpath("/ds:links", @ds_namespaces) return parse_link_results(doc) if is_links entries = doc.xpath("//atom:entry[not(ancestor::atom:entry)]", @ds_namespaces) extract_partial(doc) results = [] entries.each do |entry| results << entry_to_class(entry) end return results end # Converts an XML Entry into a class def entry_to_class(entry) # Retrieve the class name from the fully qualified name (the last string after the last dot) klass_name = entry.xpath("./atom:category/@term", @ds_namespaces).to_s.split('.')[-1] # Is the category missing? See if there is a title that we can use to build the class if klass_name.nil? title = entry.xpath("./atom:title", @ds_namespaces).first return nil if title.nil? klass_name = title.content.to_s end return nil if klass_name.nil? properties = entry.xpath("./atom:content/m:properties/*", @ds_namespaces) klass = @classes[qualify_class_name(klass_name)].new # Fill metadata meta_id = entry.xpath("./atom:id", @ds_namespaces)[0].content klass.send :__metadata=, { :uri => meta_id } # Fill properties for prop in properties prop_name = prop.name klass.send "#{prop_name}=", parse_value_xml(prop) end # Fill properties represented outside of the properties collection @class_metadata[qualify_class_name(klass_name)].select { |k,v| v.fc_keep_in_content == false }.each do |k, meta| if meta.fc_target_path == "SyndicationTitle" title = entry.xpath("./atom:title", @ds_namespaces).first klass.send "#{meta.name}=", title.content elsif meta.fc_target_path == "SyndicationSummary" summary = entry.xpath("./atom:summary", @ds_namespaces).first klass.send "#{meta.name}=", summary.content end end inline_links = entry.xpath("./atom:link[m:inline]", @ds_namespaces) for link in inline_links # TODO: Use the metadata's associations to determine the multiplicity instead of this "hack" property_name = link.attributes['title'].to_s if singular?(property_name) inline_entry = link.xpath("./m:inline/atom:entry", @ds_namespaces).first inline_klass = build_inline_class(klass, inline_entry, property_name) klass.send "#{property_name}=", inline_klass else inline_classes, inline_entries = [], link.xpath("./m:inline/atom:feed/atom:entry", @ds_namespaces) for inline_entry in inline_entries # Build the class inline_klass = entry_to_class(inline_entry) # Add the property to the temp collection inline_classes << inline_klass end # Assign the array of classes to the property property_name = link.xpath("@title", @ds_namespaces) klass.send "#{property_name}=", inline_classes end end klass end # Tests for and extracts the next href of a partial def extract_partial(doc) next_links = doc.xpath('//atom:link[@rel="next"]', @ds_namespaces) @has_partial = next_links.any? if @has_partial uri = Addressable::URI.parse(next_links[0]['href']) uri.query_values = uri.query_values.merge @additional_params unless @additional_params.empty? @next_uri = uri.to_s end end def handle_partial if @next_uri result = OData::Resource.new(@next_uri, @rest_options).get results = handle_collection_result(result.body) end results end # Handle link results def parse_link_results(doc) uris = doc.xpath("/ds:links/ds:uri", @ds_namespaces) results = [] uris.each do |uri_el| link = uri_el.content results << URI.parse(link) end results end # Build URIs def build_metadata_uri uri = "#{@uri}/$metadata" uri << "?#{@additional_params.to_query}" unless @additional_params.empty? uri end def build_query_uri "#{@uri}#{@query.query}" end def build_save_uri(operation) uri = "#{@uri}/#{operation.klass_name}" uri << "?#{@additional_params.to_query}" unless @additional_params.empty? uri end def build_add_link_uri(operation) uri = operation.klass.send(:__metadata)[:uri].dup uri << "/$links/#{operation.klass_name}" uri << "?#{@additional_params.to_query}" unless @additional_params.empty? uri end def build_resource_uri(operation) uri = operation.klass.send(:__metadata)[:uri].dup uri << "?#{@additional_params.to_query}" unless @additional_params.empty? uri end def build_batch_uri uri = "#{@uri}/$batch" uri << "?#{@additional_params.to_query}" unless @additional_params.empty? uri end def build_load_property_uri(obj, property) uri = obj.__metadata[:uri].dup uri << "/#{property}" uri end def build_function_import_uri(name, params) uri = "#{@uri}/#{name}" params.merge! @additional_params uri << "?#{params.to_query}" unless params.empty? uri end def build_inline_class(klass, entry, property_name) # Build the class inline_klass = entry_to_class(entry) # Add the property klass.send "#{property_name}=", inline_klass end # Used to link a child object to its parent and vice-versa after a add_link operation def link_child_to_parent(operation) child_collection = operation.klass.send("#{operation.klass_name}") || [] child_collection << operation.child_klass operation.klass.send("#{operation.klass_name}=", child_collection) # Attach the parent to the child parent_meta = @class_metadata[operation.klass.class.to_s][operation.klass_name] child_meta = @class_metadata[operation.child_klass.class.to_s] # Find the matching relationship on the child object child_properties = Helpers.normalize_to_hash( child_meta.select { |k, prop| prop.nav_prop && prop.association.relationship == parent_meta.association.relationship }) child_property_to_set = child_properties.keys.first # There should be only one match # TODO: Handle many to many scenarios where the child property is an enumerable operation.child_klass.send("#{child_property_to_set}=", operation.klass) end def single_save(operation) if operation.kind == "Add" save_uri = build_save_uri(operation) json_klass = operation.klass.to_json(:type => :add) post_result = OData::Resource.new(save_uri, @rest_options).post json_klass, {:content_type => @json_type} return build_classes_from_result(post_result.body) elsif operation.kind == "Update" update_uri = build_resource_uri(operation) json_klass = operation.klass.to_json update_result = OData::Resource.new(update_uri, @rest_options).put json_klass, {:content_type => @json_type} return (update_result.status == 204) elsif operation.kind == "Delete" delete_uri = build_resource_uri(operation) delete_result = OData::Resource.new(delete_uri, @rest_options).delete return (delete_result.status == 204) elsif operation.kind == "AddLink" save_uri = build_add_link_uri(operation) json_klass = operation.child_klass.to_json(:type => :link) post_result = OData::Resource.new(save_uri, @rest_options).post json_klass, {:content_type => @json_type} # Attach the child to the parent link_child_to_parent(operation) if (post_result.status == 204) return(post_result.status == 204) end end # Batch Saves def generate_guid rand(36**12).to_s(36).insert(4, "-").insert(9, "-") end def batch_save(operations) batch_num = generate_guid changeset_num = generate_guid batch_uri = build_batch_uri body = build_batch_body(operations, batch_num, changeset_num) result = OData::Resource.new( batch_uri, @rest_options).post body, {:content_type => "multipart/mixed; boundary=batch_#{batch_num}"} # TODO: More result validation needs to be done. # The result returns HTTP 202 even if there is an error in the batch return (result.status == 202) end def build_batch_body(operations, batch_num, changeset_num) # Header body = "--batch_#{batch_num}\n" body << "Content-Type: multipart/mixed;boundary=changeset_#{changeset_num}\n\n" # Operations operations.each do |operation| body << build_batch_operation(operation, changeset_num) body << "\n" end # Footer body << "\n\n--changeset_#{changeset_num}--\n" body << "--batch_#{batch_num}--" return body end def build_batch_operation(operation, changeset_num) accept_headers = "Accept-Charset: utf-8\n" accept_headers << "Content-Type: application/json;charset=utf-8\n" unless operation.kind == "Delete" accept_headers << "\n" content = "--changeset_#{changeset_num}\n" content << "Content-Type: application/http\n" content << "Content-Transfer-Encoding: binary\n\n" if operation.kind == "Add" save_uri = "#{@uri}/#{operation.klass_name}" json_klass = operation.klass.to_json(:type => :add) content << "POST #{save_uri} HTTP/1.1\n" content << accept_headers content << json_klass elsif operation.kind == "Update" update_uri = operation.klass.send(:__metadata)[:uri] json_klass = operation.klass.to_json content << "PUT #{update_uri} HTTP/1.1\n" content << accept_headers content << json_klass elsif operation.kind == "Delete" delete_uri = operation.klass.send(:__metadata)[:uri] content << "DELETE #{delete_uri} HTTP/1.1\n" content << accept_headers elsif save_uri = build_add_link_uri(operation) json_klass = operation.child_klass.to_json(:type => :link) content << "POST #{save_uri} HTTP/1.1\n" content << accept_headers content << json_klass link_child_to_parent(operation) end return content end # Complex Types def complex_type_to_class(complex_type_xml) type = Helpers.get_namespaced_attribute(complex_type_xml, 'type', 'm') is_collection = false # Extract the class name in case this is a Collection if type =~ /\(([^)]*)\)/m type = $~[1] is_collection = true collection = [] end klass_name = qualify_class_name(type.split('.')[-1]) if is_collection # extract the elements from the collection elements = complex_type_xml.xpath(".//d:element", @namespaces) elements.each do |e| if type.match(/^Edm/) collection << parse_value(e.content, type) else element = @classes[klass_name].new fill_complex_type_properties(e, element) collection << element end end return collection else klass = @classes[klass_name].new # Fill in the properties fill_complex_type_properties(complex_type_xml, klass) return klass end end # Helper method for complex_type_to_class def fill_complex_type_properties(complex_type_xml, klass) properties = complex_type_xml.xpath(".//*") properties.each do |prop| klass.send "#{prop.name}=", parse_value_xml(prop) end end # Field Converters # Handles parsing datetimes from a string def parse_date(sdate) # Assume this is UTC if no timezone is specified sdate = sdate + "Z" unless sdate.match(/Z|([+|-]\d{2}:\d{2})$/) # This is to handle older versions of Ruby (e.g. ruby 1.8.7 (2010-12-23 patchlevel 330) [i386-mingw32]) # See http://makandra.com/notes/1017-maximum-representable-value-for-a-ruby-time-object # In recent versions of Ruby, Time has a much larger range begin result = Time.parse(sdate) rescue ArgumentError result = DateTime.parse(sdate) end return result end # Parses a value into the proper type based on an xml property element def parse_value_xml(property_xml) property_type = Helpers.get_namespaced_attribute(property_xml, 'type', 'm') property_null = Helpers.get_namespaced_attribute(property_xml, 'null', 'm') if property_type.nil? || (property_type && property_type.match(/^Edm/)) return parse_value(property_xml.content, property_type, property_null) end complex_type_to_class(property_xml) end def parse_value(content, property_type = nil, property_null = nil) # Handle anything marked as null return nil if !property_null.nil? && property_null == "true" # Handle a nil property type, this is a string return content if property_type.nil? # Handle integers return content.to_i if property_type.match(/^Edm.Int/) # Handle decimals return content.to_d if property_type.match(/Edm.Decimal/) # Handle DateTimes # return Time.parse(property_xml.content) if property_type.match(/Edm.DateTime/) return parse_date(content) if property_type.match(/Edm.DateTime/) # If we can't parse the value, just return the element's content content end # Parses a value into the proper type based on a specified return type def parse_primative_type(value, return_type) return value.to_i if return_type == Fixnum return value.to_d if return_type == Float return parse_date(value.to_s) if return_type == Time return value.to_s end # Converts an edm type (string) to a ruby type def edm_to_ruby_type(edm_type) return String if edm_type =~ /Edm.String/ return Fixnum if edm_type =~ /^Edm.Int/ return Float if edm_type =~ /Edm.Decimal/ return Time if edm_type =~ /Edm.DateTime/ return String end # Method Missing Handlers # Executes an import function def execute_import_function(name, *args) func = @function_imports[name] # Check the args making sure that more weren't passed in than the function needs param_count = func[:parameters].nil? ? 0 : func[:parameters].count arg_count = args.nil? ? 0 : args[0].count if arg_count > param_count raise ArgumentError, "wrong number of arguments (#{arg_count} for #{param_count})" end # Convert the parameters to a hash params = {} func[:parameters].keys.each_with_index { |key, i| params[key] = args[0][i] } unless func[:parameters].nil? function_uri = build_function_import_uri(name, params) result = OData::Resource.new(function_uri, @rest_options).send(func[:http_method].downcase, {}) # Is this a 204 (No content) result? return true if result.status == 204 # No? Then we need to parse the results. There are 4 kinds... if func[:return_type] == Array # a collection of entites return build_classes_from_result(result.body) if @classes.include?(func[:inner_return_type].to_s) # a collection of native types elements = Nokogiri::XML(result.body).xpath("//ds:element", @ds_namespaces) results = [] elements.each do |e| results << parse_primative_type(e.content, func[:inner_return_type]) end return results end # a single entity if @classes.include?(func[:return_type].to_s) entry = Nokogiri::XML(result.body).xpath("atom:entry[not(ancestor::atom:entry)]", @ds_namespaces) return entry_to_class(entry) end # or a single native type unless func[:return_type].nil? e = Nokogiri::XML(result.body).xpath("/*").first return parse_primative_type(e.content, func[:return_type]) end # Nothing could be parsed, so just return if we got a 200 or not return (result.status == 200) end # Helpers def singular?(value) value.singularize == value end end
alltom/ruck
lib/ruck/shreduler.rb
Ruck.ObjectConvenienceMethods.spork_loop
ruby
def spork_loop(delay_or_event = nil, clock = nil, &block) shred = Shred.new do while Shred.current.running? if delay_or_event if delay_or_event.is_a?(Numeric) Shred.yield(delay_or_event, clock) else Shred.wait_on(delay_or_event) end end block.call end end $shreduler.shredule(shred) end
creates a new Shred with the given block on the global Shreduler, automatically surrounded by loop { }. If the delay_or_event parameter is given, a Shred.yield(delay) or Shred.wait_on(event) is inserted before the call to your block.
train
https://github.com/alltom/ruck/blob/a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d/lib/ruck/shreduler.rb#L133-L148
module ObjectConvenienceMethods # creates a new Shred with the given block on the global Shreduler def spork(&block) $shreduler.shredule(Shred.new(&block)) end # creates a new Shred with the given block on the global Shreduler, # automatically surrounded by loop { }. If the delay_or_event parameter # is given, a Shred.yield(delay) or Shred.wait_on(event) is inserted # before the call to your block. # raises an event on the default EventClock of the global Shreduler. def raise_event(event) $shreduler.event_clock.raise_all(event) end end
DigitPaint/roger
lib/roger/renderer.rb
Roger.Renderer.find_partial
ruby
def find_partial(name) current_path, current_ext = current_template_path_and_extension # Try to find _ named partials first. # This will alaso search for partials relative to the current path local_name = [File.dirname(name), "_" + File.basename(name)].join("/") resolver = Resolver.new([File.dirname(current_path)] + @paths[:partials]) result = resolver.find_template(local_name, prefer: current_ext) return result if result # Try to look for templates the old way resolver = Resolver.new(@paths[:partials]) resolver.find_template(name, prefer: current_ext) end
Find a partial
train
https://github.com/DigitPaint/roger/blob/1153119f170d1b0289b659a52fcbf054df2d9633/lib/roger/renderer.rb#L288-L302
class Renderer MAX_ALLOWED_TEMPLATE_NESTING = 10 class << self # Register a helper module that should be included in # every template context. def helper(mod) @helpers ||= [] @helpers << mod end def helpers @helpers || [] end # Will the renderer render this path to something meaningful? def will_render?(path) Tilt.templates_for(path.to_s).any? end # Try to infer the final extension of the output file. def target_extension_for(path) if type = MIME::Types[target_mime_type_for(path)].first # Dirty little hack to enforce the use of .html instead of .htm if type.sub_type == "html" "html" else type.extensions.first end else File.extname(path.to_s).sub(/^\./, "") end end def source_extension_for(path) parts = File.basename(File.basename(path.to_s)).split(".") if parts.size > 2 parts[-2..-1].join(".") else File.extname(path.to_s).sub(/^\./, "") end end # Try to figure out the mime type based on the Tilt class and if that doesn't # work we try to infer the type by looking at extensions (needed for .erb) def target_mime_type_for(path) mime = mime_type_from_template(path) || mime_type_from_filename(path) || mime_type_from_sub_extension(path) mime.to_s if mime end protected # Check last template processor default # output mime type def mime_type_from_template(path) templates = Tilt.templates_for(path.to_s) templates.last && templates.last.default_mime_type end def mime_type_from_filename(path) MIME::Types.type_for(File.basename(path.to_s)).first end # Will get mime_type from source_path extension # but it will only look at the second extension so # .html.erb will look at .html def mime_type_from_sub_extension(path) parts = File.basename(path.to_s).split(".") MIME::Types.type_for(parts[0..-2].join(".")).sort.first if parts.size > 2 end end attr_accessor :data attr_reader :template_nesting def initialize(env = {}, options = {}) @options = options @context = prepare_context(env) @paths = { partials: [@options[:partials_path]].flatten, layouts: [@options[:layouts_path]].flatten } # State data. Whenever we render a new template # we need to update: # # - data from front matter # - template_nesting # - current_template @data = {} @template_nesting = [] end # The render function # # The render function will take care of rendering the right thing # in the right context. It will: # # - Wrap templates with layouts if it's defined in the frontmatter and # load them from the right layout path. # - Render only partials if called from within an existing template # # If you just want to render an arbitrary file, use #render_file instead # # @option options [Hash] :locals Locals to use during rendering # @option options [String] :source The source for the template # @option options [String, nil] :layout The default layout to use def render(path, options = {}, &block) template, layout = template_and_layout_for_render(path, options) # Set new current template template_nesting.push(template) # Copy data to our data store. A bit clunky; as this should be inherited @data = {}.update(@data).update(template.data) # Render the template first so we have access to # it's data in the layout. render_result = template.render(options[:locals] || {}, &block) # Wrap it in a layout layout.render do render_result end ensure # Only pop the template from the nesting if we actually # put it on the nesting stack. template_nesting.pop if template end # Render any file on disk. No magic. Just rendering. # # A couple of things to keep in mind: # - The file will be rendered in this rendering context # - Does not have layouts or block style # - When you pass a relative path and we are within another template # it will be relative to that template. # # @options options [Hash] :locals def render_file(path, options = {}) pn = absolute_path_from_current_template(path) template = template(pn.to_s, nil) # Track rendered file also on the rendered stack template_nesting.push(template) template.render(options[:locals] || {}) ensure # Only pop the template from the nesting if we actually # put it on the nesting stack. template_nesting.pop if template end # The current template being rendered def current_template template_nesting.last end # The parent template in the nesting. def parent_template template_nesting[-2] end protected def absolute_path_from_current_template(path) pn = Pathname.new(path) if pn.relative? # We're explicitly checking for source_path instead of real_source_path # as you could also just have an inline template. if current_template && current_template.source_path (Pathname.new(current_template.source_path).dirname + pn).realpath else err = "Only within another template you can use relative paths" raise ArgumentError, err end else pn.realpath end end def template_and_layout_for_render(path, options = {}) # A previous template has been set so it's a partial # If no previous template is set, we're # at the top level and this means we get to do layouts! template_type = current_template ? :partial : :template template = template(path, options[:source], template_type) layout = layout_for_template(template, options) [template, layout] end # Gets the layout for a specific template def layout_for_template(template, options) layout_name = if template.data.key?(:layout) template.data[:layout] else get_default_layout(template, options) end # Only attempt to load layout when: # - Template is the toplevel template # - A layout_name is available return BlankTemplate.new if current_template || !layout_name template(layout_name, nil, :layout) end # Gets the default layout that can be specified by the Rogerfile: # roger.project.options[:renderer][:layout] = { # "html.erb" => "default" # } def get_default_layout(template, options) source_ext = Renderer.source_extension_for(template.source_path) options[:layout][source_ext] if options.key?(:layout) end # Will check the template nesting if we haven't already # rendered this path before. If it has we'll throw an argumenteerror def prevent_recursion!(template) # If this template is not a real file it cannot ever conflict. return unless template.real_source_path caller_templates = template_nesting.select do |t| t.real_source_path == template.real_source_path end # We're good, no deeper recursion then MAX_ALLOWED_TEMPLATE_NESTING return if caller_templates.length <= MAX_ALLOWED_TEMPLATE_NESTING err = "Recursive render detected for '#{template.source_path}'" err += " in '#{current_template.source_path}'" raise ArgumentError, err end # Will instantiate a Template or throw an ArgumentError # if it could not find the template def template(path, source, type = :template) if source template = Template.new(source, @context, source_path: path) else template_path = case type when :partial find_partial(path) when :layout find_layout(path) else path end if template_path && File.exist?(template_path) template = Template.open(template_path, @context) else template_not_found!(type, path) end end prevent_recursion!(template) template end def template_not_found!(type, path) err = "No such #{type} #{path}" err += " in #{@current_template.source_path}" if @current_template raise ArgumentError, err end # Find a partial def find_layout(name) _, current_ext = current_template_path_and_extension resolver = Resolver.new(@paths[:layouts]) resolver.find_template(name, prefer: current_ext) end def current_template_path_and_extension path = nil extension = nil # We want the preferred extension to be the same as ours if current_template path = current_template.source_path extension = self.class.target_extension_for(path) end [path, extension] end # Will set up a new template context for this renderer def prepare_context(env) context = Roger::Template::TemplateContext.new(self, env) # Extend context with all helpers self.class.helpers.each do |mod| context.extend(mod) end context end end
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.clear_rules!
ruby
def clear_rules!(forward_to_replicas = false, request_options = {}) res = clear_rules(forward_to_replicas, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) return res end
Clear all rules and wait the end of indexing @param forward_to_replicas should we forward the delete to replica indices @param request_options contains extra parameters to send with your query
train
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L1133-L1137
class Index attr_accessor :name, :client def initialize(name, client = nil) self.name = name self.client = client || Algolia.client end # # Delete an index # # @param request_options contains extra parameters to send with your query # # return an hash of the form { "deletedAt" => "2013-01-18T15:33:13.556Z", "taskID" => "42" } # def delete(request_options = {}) client.delete(Protocol.index_uri(name), :write, request_options) end alias_method :delete_index, :delete # # Delete an index and wait until the deletion has been processed # # @param request_options contains extra parameters to send with your query # # return an hash of the form { "deletedAt" => "2013-01-18T15:33:13.556Z", "taskID" => "42" } # def delete!(request_options = {}) res = delete(request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end alias_method :delete_index!, :delete! # # Add an object in this index # # @param object the object to add to the index. # The object is represented by an associative array # @param objectID (optional) an objectID you want to attribute to this object # (if the attribute already exist the old object will be overridden) # @param request_options contains extra parameters to send with your query # def add_object(object, objectID = nil, request_options = {}) check_object(object) if objectID.nil? || objectID.to_s.empty? client.post(Protocol.index_uri(name), object.to_json, :write, request_options) else client.put(Protocol.object_uri(name, objectID), object.to_json, :write, request_options) end end # # Add an object in this index and wait end of indexing # # @param object the object to add to the index. # The object is represented by an associative array # @param objectID (optional) an objectID you want to attribute to this object # (if the attribute already exist the old object will be overridden) # @param Request options object. Contains extra URL parameters or headers # def add_object!(object, objectID = nil, request_options = {}) res = add_object(object, objectID, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end # # Add several objects in this index # # @param objects the array of objects to add inside the index. # Each object is represented by an associative array # @param request_options contains extra parameters to send with your query # def add_objects(objects, request_options = {}) batch(build_batch('addObject', objects, false), request_options) end # # Add several objects in this index and wait end of indexing # # @param objects the array of objects to add inside the index. # Each object is represented by an associative array # @param request_options contains extra parameters to send with your query # def add_objects!(objects, request_options = {}) res = add_objects(objects, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end # # Search inside the index # # @param query the full text query # @param args (optional) if set, contains an associative array with query parameters: # - page: (integer) Pagination parameter used to select the page to retrieve. # Page is zero-based and defaults to 0. Thus, to retrieve the 10th page you need to set page=9 # - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20. # - attributesToRetrieve: a string that contains the list of object attributes you want to retrieve (let you minimize the answer size). # Attributes are separated with a comma (for example "name,address"). # You can also use a string array encoding (for example ["name","address"]). # By default, all attributes are retrieved. You can also use '*' to retrieve all values when an attributesToRetrieve setting is specified for your index. # - attributesToHighlight: a string that contains the list of attributes you want to highlight according to the query. # Attributes are separated by a comma. You can also use a string array encoding (for example ["name","address"]). # If an attribute has no match for the query, the raw value is returned. By default all indexed text attributes are highlighted. # You can use `*` if you want to highlight all textual attributes. Numerical attributes are not highlighted. # A matchLevel is returned for each highlighted attribute and can contain: # - full: if all the query terms were found in the attribute, # - partial: if only some of the query terms were found, # - none: if none of the query terms were found. # - attributesToSnippet: a string that contains the list of attributes to snippet alongside the number of words to return (syntax is `attributeName:nbWords`). # Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10). # You can also use a string array encoding (Example: attributesToSnippet: ["name:10","content:10"]). By default no snippet is computed. # - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word. Defaults to 3. # - minWordSizefor2Typos: the minimum number of characters in a query word to accept two typos in this word. Defaults to 7. # - getRankingInfo: if set to 1, the result hits will contain ranking information in _rankingInfo attribute. # - aroundLatLng: search for entries around a given latitude/longitude (specified as two floats separated by a comma). # For example aroundLatLng=47.316669,5.016670). # You can specify the maximum distance in meters with the aroundRadius parameter (in meters) and the precision for ranking with aroundPrecision # (for example if you set aroundPrecision=100, two objects that are distant of less than 100m will be considered as identical for "geo" ranking parameter). # At indexing, you should specify geoloc of an object with the _geoloc attribute (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) # - insideBoundingBox: search entries inside a given area defined by the two extreme points of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng). # For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201). # At indexing, you should specify geoloc of an object with the _geoloc attribute (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) # - numericFilters: a string that contains the list of numeric filters you want to apply separated by a comma. # The syntax of one filter is `attributeName` followed by `operand` followed by `value`. Supported operands are `<`, `<=`, `=`, `>` and `>=`. # You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000. # You can also use a string array encoding (for example numericFilters: ["price>100","price<1000"]). # - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas. # To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3). # You can also use a string array encoding, for example tagFilters: ["tag1",["tag2","tag3"]] means tag1 AND (tag2 OR tag3). # At indexing, tags should be added in the _tags** attribute of objects (for example {"_tags":["tag1","tag2"]}). # - facetFilters: filter the query by a list of facets. # Facets are separated by commas and each facet is encoded as `attributeName:value`. # For example: `facetFilters=category:Book,author:John%20Doe`. # You can also use a string array encoding (for example `["category:Book","author:John%20Doe"]`). # - facets: List of object attributes that you want to use for faceting. # Attributes are separated with a comma (for example `"category,author"` ). # You can also use a JSON string array encoding (for example ["category","author"]). # Only attributes that have been added in **attributesForFaceting** index setting can be used in this parameter. # You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**. # - queryType: select how the query words are interpreted, it can be one of the following value: # - prefixAll: all query words are interpreted as prefixes, # - prefixLast: only the last word is interpreted as a prefix (default behavior), # - prefixNone: no query word is interpreted as a prefix. This option is not recommended. # - optionalWords: a string that contains the list of words that should be considered as optional when found in the query. # The list of words is comma separated. # - distinct: If set to 1, enable the distinct feature (disabled by default) if the attributeForDistinct index setting is set. # This feature is similar to the SQL "distinct" keyword: when enabled in a query with the distinct=1 parameter, # all hits containing a duplicate value for the attributeForDistinct attribute are removed from results. # For example, if the chosen attribute is show_name and several hits have the same value for show_name, then only the best # one is kept and others are removed. # @param request_options contains extra parameters to send with your query # def search(query, params = {}, request_options = {}) encoded_params = Hash[params.map { |k, v| [k.to_s, v.is_a?(Array) ? v.to_json : v] }] encoded_params[:query] = query client.post(Protocol.search_post_uri(name), { :params => Protocol.to_query(encoded_params) }.to_json, :search, request_options) end class IndexBrowser def initialize(client, name, params) @client = client @name = name @params = params @cursor = params[:cursor] || params['cursor'] || nil end def browse(request_options = {}, &block) loop do answer = @client.get(Protocol.browse_uri(@name, @params.merge({ :cursor => @cursor })), :read, request_options) answer['hits'].each do |hit| if block.arity == 2 yield hit, @cursor else yield hit end end @cursor = answer['cursor'] break if @cursor.nil? end end end # # Browse all index content # # @param queryParameters The hash of query parameters to use to browse # To browse from a specific cursor, just add a ":cursor" parameters # @param queryParameters An optional second parameters hash here for backward-compatibility (which will be merged with the first) # @param request_options contains extra parameters to send with your query # # @DEPRECATED: # @param page Pagination parameter used to select the page to retrieve. # @param hits_per_page Pagination parameter used to select the number of hits per page. Defaults to 1000. # def browse(page_or_query_parameters = nil, hits_per_page = nil, request_options = {}, &block) params = {} if page_or_query_parameters.is_a?(Hash) params.merge!(page_or_query_parameters) else params[:page] = page_or_query_parameters unless page_or_query_parameters.nil? end if hits_per_page.is_a?(Hash) params.merge!(hits_per_page) else params[:hitsPerPage] = hits_per_page unless hits_per_page.nil? end if block_given? IndexBrowser.new(client, name, params).browse(request_options, &block) else params[:page] ||= 0 params[:hitsPerPage] ||= 1000 client.get(Protocol.browse_uri(name, params), :read, request_options) end end # # Browse a single page from a specific cursor # # @param request_options contains extra parameters to send with your query # def browse_from(cursor, hits_per_page = 1000, request_options = {}) client.post(Protocol.browse_uri(name), { :cursor => cursor, :hitsPerPage => hits_per_page }.to_json, :read, request_options) end # # Get an object from this index # # @param objectID the unique identifier of the object to retrieve # @param attributes_to_retrieve (optional) if set, contains the list of attributes to retrieve as an array of strings of a string separated by "," # @param request_options contains extra parameters to send with your query # def get_object(objectID, attributes_to_retrieve = nil, request_options = {}) attributes_to_retrieve = attributes_to_retrieve.join(',') if attributes_to_retrieve.is_a?(Array) if attributes_to_retrieve.nil? client.get(Protocol.object_uri(name, objectID, nil), :read, request_options) else client.get(Protocol.object_uri(name, objectID, { :attributes => attributes_to_retrieve }), :read, request_options) end end # # Get a list of objects from this index # # @param objectIDs the array of unique identifier of the objects to retrieve # @param attributes_to_retrieve (optional) if set, contains the list of attributes to retrieve as an array of strings of a string separated by "," # @param request_options contains extra parameters to send with your query # def get_objects(objectIDs, attributes_to_retrieve = nil, request_options = {}) attributes_to_retrieve = attributes_to_retrieve.join(',') if attributes_to_retrieve.is_a?(Array) requests = objectIDs.map do |objectID| req = { :indexName => name, :objectID => objectID.to_s } req[:attributesToRetrieve] = attributes_to_retrieve unless attributes_to_retrieve.nil? req end client.post(Protocol.objects_uri, { :requests => requests }.to_json, :read, request_options)['results'] end # # Check the status of a task on the server. # All server task are asynchronous and you can check the status of a task with this method. # # @param taskID the id of the task returned by server # @param request_options contains extra parameters to send with your query # def get_task_status(taskID, request_options = {}) client.get_task_status(name, taskID, request_options) end # # Wait the publication of a task on the server. # All server task are asynchronous and you can check with this method that the task is published. # # @param taskID the id of the task returned by server # @param time_before_retry the time in milliseconds before retry (default = 100ms) # @param request_options contains extra parameters to send with your query # def wait_task(taskID, time_before_retry = WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options = {}) client.wait_task(name, taskID, time_before_retry, request_options) end # # Override the content of an object # # @param object the object to save # @param objectID the associated objectID, if nil 'object' must contain an 'objectID' key # @param request_options contains extra parameters to send with your query # def save_object(object, objectID = nil, request_options = {}) client.put(Protocol.object_uri(name, get_objectID(object, objectID)), object.to_json, :write, request_options) end # # Override the content of object and wait end of indexing # # @param object the object to save # @param objectID the associated objectID, if nil 'object' must contain an 'objectID' key # @param request_options contains extra parameters to send with your query # def save_object!(object, objectID = nil, request_options = {}) res = save_object(object, objectID, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end # # Override the content of several objects # # @param objects the array of objects to save, each object must contain an 'objectID' key # @param request_options contains extra parameters to send with your query # def save_objects(objects, request_options = {}) batch(build_batch('updateObject', objects, true), request_options) end # # Override the content of several objects and wait end of indexing # # @param objects the array of objects to save, each object must contain an objectID attribute # @param request_options contains extra parameters to send with your query # def save_objects!(objects, request_options = {}) res = save_objects(objects, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end # # Override the current objects by the given array of objects and wait end of indexing. Settings, # synonyms and query rules are untouched. The objects are replaced without any downtime. # # @param objects the array of objects to save # @param request_options contains extra parameters to send with your query # def replace_all_objects(objects, request_options = {}) safe = request_options[:safe] || request_options['safe'] || false request_options.delete(:safe) request_options.delete('safe') tmp_index = @client.init_index(@name + '_tmp_' + rand(10000000).to_s) responses = [] scope = ['settings', 'synonyms', 'rules'] res = @client.copy_index(@name, tmp_index.name, scope, request_options) responses << res if safe wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) end batch = [] batch_size = 1000 count = 0 objects.each do |object| batch << object count += 1 if count == batch_size res = tmp_index.add_objects(batch, request_options) responses << res batch = [] count = 0 end end if batch.any? res = tmp_index.add_objects(batch, request_options) responses << res end if safe responses.each do |res| tmp_index.wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) end end res = @client.move_index(tmp_index.name, @name, request_options) responses << res if safe wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) end responses end # # Override the current objects by the given array of objects and wait end of indexing # # @param objects the array of objects to save # @param request_options contains extra parameters to send with your query # def replace_all_objects!(objects, request_options = {}) replace_all_objects(objects, request_options.merge(:safe => true)) end # # Update partially an object (only update attributes passed in argument) # # @param object the object attributes to override # @param objectID the associated objectID, if nil 'object' must contain an 'objectID' key # @param create_if_not_exits a boolean, if true creates the object if this one doesn't exist # @param request_options contains extra parameters to send with your query # def partial_update_object(object, objectID = nil, create_if_not_exits = true, request_options = {}) client.post(Protocol.partial_object_uri(name, get_objectID(object, objectID), create_if_not_exits), object.to_json, :write, request_options) end # # Partially override the content of several objects # # @param objects an array of objects to update (each object must contains a objectID attribute) # @param create_if_not_exits a boolean, if true create the objects if they don't exist # @param request_options contains extra parameters to send with your query # def partial_update_objects(objects, create_if_not_exits = true, request_options = {}) if create_if_not_exits batch(build_batch('partialUpdateObject', objects, true), request_options) else batch(build_batch('partialUpdateObjectNoCreate', objects, true), request_options) end end # # Partially override the content of several objects and wait end of indexing # # @param objects an array of objects to update (each object must contains a objectID attribute) # @param create_if_not_exits a boolean, if true create the objects if they don't exist # @param request_options contains extra parameters to send with your query # def partial_update_objects!(objects, create_if_not_exits = true, request_options = {}) res = partial_update_objects(objects, create_if_not_exits, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end # # Update partially an object (only update attributes passed in argument) and wait indexing # # @param object the attributes to override # @param objectID the associated objectID, if nil 'object' must contain an 'objectID' key # @param create_if_not_exits a boolean, if true creates the object if this one doesn't exist # @param request_options contains extra parameters to send with your query # def partial_update_object!(object, objectID = nil, create_if_not_exits = true, request_options = {}) res = partial_update_object(object, objectID, create_if_not_exits, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end # # Delete an object from the index # # @param objectID the unique identifier of object to delete # @param request_options contains extra parameters to send with your query # def delete_object(objectID, request_options = {}) raise ArgumentError.new('objectID must not be blank') if objectID.nil? || objectID == '' client.delete(Protocol.object_uri(name, objectID), :write, request_options) end # # Delete an object from the index and wait end of indexing # # @param objectID the unique identifier of object to delete # @param request_options contains extra parameters to send with your query # def delete_object!(objectID, request_options = {}) res = delete_object(objectID, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end # # Delete several objects # # @param objects an array of objectIDs # @param request_options contains extra parameters to send with your query # def delete_objects(objects, request_options = {}) check_array(objects) batch(build_batch('deleteObject', objects.map { |objectID| { :objectID => objectID } }, false), request_options) end # # Delete several objects and wait end of indexing # # @param objects an array of objectIDs # @param request_options contains extra parameters to send with your query # def delete_objects!(objects, request_options = {}) res = delete_objects(objects, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end # # Delete all objects matching a query # This method retrieves all objects synchronously but deletes in batch # asynchronously # # @param query the query string # @param params the optional query parameters # @param request_options contains extra parameters to send with your query # def delete_by_query(query, params = nil, request_options = {}) raise ArgumentError.new('query cannot be nil, use the `clear` method to wipe the entire index') if query.nil? && params.nil? params = sanitized_delete_by_query_params(params) params[:query] = query params[:hitsPerPage] = 1000 params[:distinct] = false params[:attributesToRetrieve] = ['objectID'] params[:cursor] = '' ids = [] while params[:cursor] != nil result = browse(params, nil, request_options) params[:cursor] = result['cursor'] hits = result['hits'] break if hits.empty? ids += hits.map { |hit| hit['objectID'] } end delete_objects(ids, request_options) end # # Delete all objects matching a query and wait end of indexing # # @param query the query string # @param params the optional query parameters # @param request_options contains extra parameters to send with your query # def delete_by_query!(query, params = nil, request_options = {}) res = delete_by_query(query, params, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) if res res end # # Delete all objects matching a query (doesn't work with actual text queries) # This method deletes every record matching the filters provided # # @param params query parameters # @param request_options contains extra parameters to send with your query # def delete_by(params, request_options = {}) raise ArgumentError.new('params cannot be nil, use the `clear` method to wipe the entire index') if params.nil? params = sanitized_delete_by_query_params(params) client.post(Protocol.delete_by_uri(name), params.to_json, :write, request_options) end # # Delete all objects matching a query (doesn't work with actual text queries) # This method deletes every record matching the filters provided and waits for the end of indexing # @param params query parameters # @param request_options contains extra parameters to send with your query # def delete_by!(params, request_options = {}) res = delete_by(params, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) if res res end # # Delete the index content # # @param request_options contains extra parameters to send with your query # def clear(request_options = {}) client.post(Protocol.clear_uri(name), {}, :write, request_options) end alias_method :clear_index, :clear # # Delete the index content and wait end of indexing # def clear!(request_options = {}) res = clear(request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end alias_method :clear_index!, :clear! # # Set settings for this index # def set_settings(new_settings, options = {}, request_options = {}) client.put(Protocol.settings_uri(name, options), new_settings.to_json, :write, request_options) end # # Set settings for this index and wait end of indexing # def set_settings!(new_settings, options = {}, request_options = {}) res = set_settings(new_settings, options, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end # # Get settings of this index # def get_settings(options = {}, request_options = {}) options['getVersion'] = 2 if !options[:getVersion] && !options['getVersion'] client.get(Protocol.settings_uri(name, options).to_s, :read, request_options) end # # List all existing user keys with their associated ACLs # # Deprecated: Please us `client.list_api_keys` instead. def list_api_keys(request_options = {}) client.get(Protocol.index_keys_uri(name), :read, request_options) end # # Get ACL of a user key # # Deprecated: Please us `client.get_api_key` instead. def get_api_key(key, request_options = {}) client.get(Protocol.index_key_uri(name, key), :read, request_options) end # # Create a new user key # # @param object can be two different parameters: # The list of parameters for this key. Defined by a Hash that can # contains the following values: # - acl: array of string # - validity: int # - referers: array of string # - description: string # - maxHitsPerQuery: integer # - queryParameters: string # - maxQueriesPerIPPerHour: integer # Or the list of ACL for this key. Defined by an array of String that # can contains the following values: # - search: allow to search (https and http) # - addObject: allows to add/update an object in the index (https only) # - deleteObject : allows to delete an existing object (https only) # - deleteIndex : allows to delete index content (https only) # - settings : allows to get index settings (https only) # - editSettings : allows to change index settings (https only) # @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key) # @param max_queries_per_IP_per_hour the maximum number of API calls allowed from an IP address per hour (0 means unlimited) # @param max_hits_per_query the maximum number of hits this API key can retrieve in one call (0 means unlimited) # @param request_options contains extra parameters to send with your query #
 # Deprecated: Please use `client.add_api_key` instead def add_api_key(object, validity = 0, max_queries_per_IP_per_hour = 0, max_hits_per_query = 0, request_options = {}) if object.instance_of?(Array) params = { :acl => object } else params = object end params['validity'] = validity.to_i if validity != 0 params['maxHitsPerQuery'] = max_hits_per_query.to_i if max_hits_per_query != 0 params['maxQueriesPerIPPerHour'] = max_queries_per_IP_per_hour.to_i if max_queries_per_IP_per_hour != 0 client.post(Protocol.index_keys_uri(name), params.to_json, :write, request_options) end # # Update a user key # # @param object can be two different parameters: # The list of parameters for this key. Defined by a Hash that # can contains the following values: # - acl: array of string # - validity: int # - referers: array of string # - description: string # - maxHitsPerQuery: integer # - queryParameters: string # - maxQueriesPerIPPerHour: integer # Or the list of ACL for this key. Defined by an array of String that # can contains the following values: # - search: allow to search (https and http) # - addObject: allows to add/update an object in the index (https only) # - deleteObject : allows to delete an existing object (https only) # - deleteIndex : allows to delete index content (https only) # - settings : allows to get index settings (https only) # - editSettings : allows to change index settings (https only) # @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key) # @param max_queries_per_IP_per_hour the maximum number of API calls allowed from an IP address per hour (0 means unlimited) # @param max_hits_per_query the maximum number of hits this API key can retrieve in one call (0 means unlimited) # @param request_options contains extra parameters to send with your query # # Deprecated: Please use `client.update_api_key` instead def update_api_key(key, object, validity = 0, max_queries_per_IP_per_hour = 0, max_hits_per_query = 0, request_options = {}) if object.instance_of?(Array) params = { :acl => object } else params = object end params['validity'] = validity.to_i if validity != 0 params['maxHitsPerQuery'] = max_hits_per_query.to_i if max_hits_per_query != 0 params['maxQueriesPerIPPerHour'] = max_queries_per_IP_per_hour.to_i if max_queries_per_IP_per_hour != 0 client.put(Protocol.index_key_uri(name, key), params.to_json, :write, request_options) end # # Delete an existing user key # # Deprecated: Please use `client.delete_api_key` instead def delete_api_key(key, request_options = {}) client.delete(Protocol.index_key_uri(name, key), :write, request_options) end # # Send a batch request # def batch(request, request_options = {}) client.post(Protocol.batch_uri(name), request.to_json, :batch, request_options) end # # Send a batch request and wait the end of the indexing # def batch!(request, request_options = {}) res = batch(request, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end # # Search for facet values # # @param facet_name Name of the facet to search. It must have been declared in the # index's`attributesForFaceting` setting with the `searchable()` modifier. # @param facet_query Text to search for in the facet's values # @param search_parameters An optional query to take extra search parameters into account. # These parameters apply to index objects like in a regular search query. # Only facet values contained in the matched objects will be returned. # @param request_options contains extra parameters to send with your query # def search_for_facet_values(facet_name, facet_query, search_parameters = {}, request_options = {}) params = search_parameters.clone params['facetQuery'] = facet_query client.post(Protocol.search_facet_uri(name, facet_name), params.to_json, :read, request_options) end # deprecated alias_method :search_facet, :search_for_facet_values # # Perform a search with disjunctive facets generating as many queries as number of disjunctive facets # # @param query the query # @param disjunctive_facets the array of disjunctive facets # @param params a hash representing the regular query parameters # @param refinements a hash ("string" -> ["array", "of", "refined", "values"]) representing the current refinements # ex: { "my_facet1" => ["my_value1", ["my_value2"], "my_disjunctive_facet1" => ["my_value1", "my_value2"] } # @param request_options contains extra parameters to send with your query # def search_disjunctive_faceting(query, disjunctive_facets, params = {}, refinements = {}, request_options = {}) raise ArgumentError.new('Argument "disjunctive_facets" must be a String or an Array') unless disjunctive_facets.is_a?(String) || disjunctive_facets.is_a?(Array) raise ArgumentError.new('Argument "refinements" must be a Hash of Arrays') if !refinements.is_a?(Hash) || !refinements.select { |k, v| !v.is_a?(Array) }.empty? # extract disjunctive facets & associated refinements disjunctive_facets = disjunctive_facets.split(',') if disjunctive_facets.is_a?(String) disjunctive_refinements = {} refinements.each do |k, v| disjunctive_refinements[k] = v if disjunctive_facets.include?(k) || disjunctive_facets.include?(k.to_s) end # build queries queries = [] ## hits + regular facets query filters = [] refinements.to_a.each do |k, values| r = values.map { |v| "#{k}:#{v}" } if disjunctive_refinements[k.to_s] || disjunctive_refinements[k.to_sym] # disjunctive refinements are ORed filters << r else # regular refinements are ANDed filters += r end end queries << params.merge({ :index_name => self.name, :query => query, :facetFilters => filters }) ## one query per disjunctive facet (use all refinements but the current one + hitsPerPage=1 + single facet) disjunctive_facets.each do |disjunctive_facet| filters = [] refinements.each do |k, values| if k.to_s != disjunctive_facet.to_s r = values.map { |v| "#{k}:#{v}" } if disjunctive_refinements[k.to_s] || disjunctive_refinements[k.to_sym] # disjunctive refinements are ORed filters << r else # regular refinements are ANDed filters += r end end end queries << params.merge({ :index_name => self.name, :query => query, :page => 0, :hitsPerPage => 1, :attributesToRetrieve => [], :attributesToHighlight => [], :attributesToSnippet => [], :facets => disjunctive_facet, :facetFilters => filters, :analytics => false }) end answers = client.multiple_queries(queries, { :request_options => request_options }) # aggregate answers ## first answer stores the hits + regular facets aggregated_answer = answers['results'][0] ## others store the disjunctive facets aggregated_answer['disjunctiveFacets'] = {} answers['results'].each_with_index do |a, i| next if i == 0 a['facets'].each do |facet, values| ## add the facet to the disjunctive facet hash aggregated_answer['disjunctiveFacets'][facet] = values ## concatenate missing refinements (disjunctive_refinements[facet.to_s] || disjunctive_refinements[facet.to_sym] || []).each do |r| if aggregated_answer['disjunctiveFacets'][facet][r].nil? aggregated_answer['disjunctiveFacets'][facet][r] = 0 end end end end aggregated_answer end # # Alias of Algolia.list_indexes # # @param request_options contains extra parameters to send with your query # def Index.all(request_options = {}) Algolia.list_indexes(request_options) end # # Search synonyms # # @param query the query # @param params an optional hash of :type, :page, :hitsPerPage # @param request_options contains extra parameters to send with your query # def search_synonyms(query, params = {}, request_options = {}) type = params[:type] || params['type'] type = type.join(',') if type.is_a?(Array) page = params[:page] || params['page'] || 0 hits_per_page = params[:hitsPerPage] || params['hitsPerPage'] || 20 params = { :query => query, :type => type.to_s, :page => page, :hitsPerPage => hits_per_page } client.post(Protocol.search_synonyms_uri(name), params.to_json, :read, request_options) end # # Get a synonym # # @param objectID the synonym objectID # @param request_options contains extra parameters to send with your query def get_synonym(objectID, request_options = {}) client.get(Protocol.synonym_uri(name, objectID), :read, request_options) end # # Delete a synonym # # @param objectID the synonym objectID # @param forward_to_replicas should we forward the delete to replica indices # @param request_options contains extra parameters to send with your query # def delete_synonym(objectID, forward_to_replicas = false, request_options = {}) client.delete("#{Protocol.synonym_uri(name, objectID)}?forwardToReplicas=#{forward_to_replicas}", :write, request_options) end # # Delete a synonym and wait the end of indexing # # @param objectID the synonym objectID # @param forward_to_replicas should we forward the delete to replica indices # @param request_options contains extra parameters to send with your query # def delete_synonym!(objectID, forward_to_replicas = false, request_options = {}) res = delete_synonym(objectID, forward_to_replicas, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end # # Save a synonym # # @param objectID the synonym objectID # @param synonym the synonym # @param forward_to_replicas should we forward the delete to replica indices # @param request_options contains extra parameters to send with your query # def save_synonym(objectID, synonym, forward_to_replicas = false, request_options = {}) client.put("#{Protocol.synonym_uri(name, objectID)}?forwardToReplicas=#{forward_to_replicas}", synonym.to_json, :write, request_options) end # # Save a synonym and wait the end of indexing # # @param objectID the synonym objectID # @param synonym the synonym # @param forward_to_replicas should we forward the delete to replica indices # @param request_options contains extra parameters to send with your query # def save_synonym!(objectID, synonym, forward_to_replicas = false, request_options = {}) res = save_synonym(objectID, synonym, forward_to_replicas, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end # # Clear all synonyms # # @param forward_to_replicas should we forward the delete to replica indices # @param request_options contains extra parameters to send with your query # def clear_synonyms(forward_to_replicas = false, request_options = {}) client.post("#{Protocol.clear_synonyms_uri(name)}?forwardToReplicas=#{forward_to_replicas}", {}, :write, request_options) end # # Clear all synonyms and wait the end of indexing # # @param forward_to_replicas should we forward the delete to replica indices # @param request_options contains extra parameters to send with your query # def clear_synonyms!(forward_to_replicas = false, request_options = {}) res = clear_synonyms(forward_to_replicas, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end # # Add/Update an array of synonyms # # @param synonyms the array of synonyms to add/update # @param forward_to_replicas should we forward the delete to replica indices # @param replace_existing_synonyms should we replace the existing synonyms before adding the new ones # @param request_options contains extra parameters to send with your query # def batch_synonyms(synonyms, forward_to_replicas = false, replace_existing_synonyms = false, request_options = {}) client.post("#{Protocol.batch_synonyms_uri(name)}?forwardToReplicas=#{forward_to_replicas}&replaceExistingSynonyms=#{replace_existing_synonyms}", synonyms.to_json, :batch, request_options) end # # Add/Update an array of synonyms and wait the end of indexing # # @param synonyms the array of synonyms to add/update # @param forward_to_replicas should we forward the delete to replica indices # @param replace_existing_synonyms should we replace the existing synonyms before adding the new ones # @param request_options contains extra parameters to send with your query # def batch_synonyms!(synonyms, forward_to_replicas = false, replace_existing_synonyms = false, request_options = {}) res = batch_synonyms(synonyms, forward_to_replicas, replace_existing_synonyms, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end # # Replace synonyms in the index by the given array of synonyms # # @param synonyms the array of synonyms to add # @param request_options contains extra parameters to send with your query # def replace_all_synonyms(synonyms, request_options = {}) forward_to_replicas = request_options[:forwardToReplicas] || request_options['forwardToReplicas'] || false batch_synonyms(synonyms, forward_to_replicas, true, request_options) end # # Replace synonyms in the index by the given array of synonyms and wait the end of indexing # # @param synonyms the array of synonyms to add # @param request_options contains extra parameters to send with your query # def replace_all_synonyms!(synonyms, request_options = {}) res = replace_all_synonyms(synonyms, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end # # Export the full list of synonyms # Accepts an optional block to which it will pass each synonym # Also returns an array with all the synonyms # # @param hits_per_page Amount of synonyms to retrieve on each internal request - Optional - Default: 100 # @param request_options contains extra parameters to send with your query - Optional # def export_synonyms(hits_per_page = 100, request_options = {}, &_block) res = [] page = 0 loop do curr = search_synonyms('', { :hitsPerPage => hits_per_page, :page => page }, request_options)['hits'] curr.each do |synonym| res << synonym yield synonym if block_given? end break if curr.size < hits_per_page page += 1 end res end # # Search rules # # @param query the query # @param params an optional hash of :anchoring, :context, :page, :hitsPerPage # @param request_options contains extra parameters to send with your query # def search_rules(query, params = {}, request_options = {}) anchoring = params[:anchoring] context = params[:context] page = params[:page] || params['page'] || 0 hits_per_page = params[:hitsPerPage] || params['hitsPerPage'] || 20 params = { :query => query, :page => page, :hitsPerPage => hits_per_page } params[:anchoring] = anchoring unless anchoring.nil? params[:context] = context unless context.nil? client.post(Protocol.search_rules_uri(name), params.to_json, :read, request_options) end # # Get a rule # # @param objectID the rule objectID # @param request_options contains extra parameters to send with your query # def get_rule(objectID, request_options = {}) client.get(Protocol.rule_uri(name, objectID), :read, request_options) end # # Delete a rule # # @param objectID the rule objectID # @param forward_to_replicas should we forward the delete to replica indices # @param request_options contains extra parameters to send with your query # def delete_rule(objectID, forward_to_replicas = false, request_options = {}) client.delete("#{Protocol.rule_uri(name, objectID)}?forwardToReplicas=#{forward_to_replicas}", :write, request_options) end # # Delete a rule and wait the end of indexing # # @param objectID the rule objectID # @param forward_to_replicas should we forward the delete to replica indices # @param request_options contains extra parameters to send with your query # def delete_rule!(objectID, forward_to_replicas = false, request_options = {}) res = delete_rule(objectID, forward_to_replicas, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) return res end # # Save a rule # # @param objectID the rule objectID # @param rule the rule # @param forward_to_replicas should we forward the delete to replica indices # @param request_options contains extra parameters to send with your query # def save_rule(objectID, rule, forward_to_replicas = false, request_options = {}) raise ArgumentError.new('objectID must not be blank') if objectID.nil? || objectID == '' client.put("#{Protocol.rule_uri(name, objectID)}?forwardToReplicas=#{forward_to_replicas}", rule.to_json, :write, request_options) end # # Save a rule and wait the end of indexing # # @param objectID the rule objectID # @param rule the rule # @param forward_to_replicas should we forward the delete to replica indices # @param request_options contains extra parameters to send with your query # def save_rule!(objectID, rule, forward_to_replicas = false, request_options = {}) res = save_rule(objectID, rule, forward_to_replicas, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) return res end # # Clear all rules # # @param forward_to_replicas should we forward the delete to replica indices # @param request_options contains extra parameters to send with your query # def clear_rules(forward_to_replicas = false, request_options = {}) client.post("#{Protocol.clear_rules_uri(name)}?forwardToReplicas=#{forward_to_replicas}", {}, :write, request_options) end # # Clear all rules and wait the end of indexing # # @param forward_to_replicas should we forward the delete to replica indices # @param request_options contains extra parameters to send with your query # # # Add/Update an array of rules # # @param rules the array of rules to add/update # @param forward_to_replicas should we forward the delete to replica indices # @param clear_existing_rules should we clear the existing rules before adding the new ones # @param request_options contains extra parameters to send with your query # def batch_rules(rules, forward_to_replicas = false, clear_existing_rules = false, request_options = {}) client.post("#{Protocol.batch_rules_uri(name)}?forwardToReplicas=#{forward_to_replicas}&clearExistingRules=#{clear_existing_rules}", rules.to_json, :batch, request_options) end # # Add/Update an array of rules and wait the end of indexing # # @param rules the array of rules to add/update # @param forward_to_replicas should we forward the delete to replica indices # @param clear_existing_rules should we clear the existing rules before adding the new ones # @param request_options contains extra parameters to send with your query # def batch_rules!(rules, forward_to_replicas = false, clear_existing_rules = false, request_options = {}) res = batch_rules(rules, forward_to_replicas, clear_existing_rules, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) return res end # # Replace rules in the index by the given array of rules # # @param rules the array of rules to add # @param request_options contains extra parameters to send with your query # def replace_all_rules(rules, request_options = {}) forward_to_replicas = request_options[:forwardToReplicas] || request_options['forwardToReplicas'] || false batch_rules(rules, forward_to_replicas, true, request_options) end # # Replace rules in the index by the given array of rules and wait the end of indexing # # @param rules the array of rules to add # @param request_options contains extra parameters to send with your query # def replace_all_rules!(rules, request_options = {}) res = replace_all_rules(rules, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end # # Export the full list of rules # Accepts an optional block to which it will pass each rule # Also returns an array with all the rules # # @param hits_per_page Amount of rules to retrieve on each internal request - Optional - Default: 100 # @param request_options contains extra parameters to send with your query - Optional # def export_rules(hits_per_page = 100, request_options = {}, &_block) res = [] page = 0 loop do curr = search_rules('', { :hits_per_page => hits_per_page, :page => page }, request_options)['hits'] curr.each do |rule| res << rule yield rule if block_given? end break if curr.size < hits_per_page page += 1 end res end # Deprecated alias_method :get_user_key, :get_api_key alias_method :list_user_keys, :list_api_keys alias_method :add_user_key, :add_api_key alias_method :update_user_key, :update_api_key alias_method :delete_user_key, :delete_api_key private def check_array(object) raise ArgumentError.new('argument must be an array of objects') if !object.is_a?(Array) end def check_object(object, in_array = false) case object when Array raise ArgumentError.new(in_array ? 'argument must be an array of objects' : 'argument must not be an array') when String, Integer, Float, TrueClass, FalseClass, NilClass raise ArgumentError.new("argument must be an #{'array of' if in_array} object, got: #{object.inspect}") else # ok end end def get_objectID(object, objectID = nil) check_object(object) objectID ||= object[:objectID] || object['objectID'] raise ArgumentError.new("Missing 'objectID'") if objectID.nil? return objectID end def build_batch(action, objects, with_object_id = false) check_array(objects) { :requests => objects.map { |object| check_object(object, true) h = { :action => action, :body => object } h[:objectID] = get_objectID(object).to_s if with_object_id h } } end def sanitized_delete_by_query_params(params) params ||= {} params.delete(:hitsPerPage) params.delete('hitsPerPage') params.delete(:attributesToRetrieve) params.delete('attributesToRetrieve') params end end
kontena/kontena
cli/lib/kontena/cli/services/update_command.rb
Kontena::Cli::Services.UpdateCommand.parse_service_data_from_options
ruby
def parse_service_data_from_options data = {} data[:strategy] = deploy_strategy if deploy_strategy data[:ports] = parse_ports(ports_list) unless ports_list.empty? data[:links] = parse_links(link_list) unless link_list.empty? data[:memory] = parse_memory(memory) if memory data[:memory_swap] = parse_memory(memory_swap) if memory_swap data[:shm_size] = parse_memory(shm_size) if shm_size data[:cpus] = cpus if cpus data[:cpu_shares] = cpu_shares if cpu_shares data[:affinity] = affinity_list unless affinity_list.empty? data[:env] = env_list unless env_list.empty? data[:secrets] = parse_secrets(secret_list) unless secret_list.empty? data[:container_count] = instances if instances data[:cmd] = Shellwords.split(cmd) if cmd data[:user] = user if user data[:image] = parse_image(image) if image data[:privileged] = privileged? data[:cap_add] = cap_add_list if cap_add_list data[:cap_drop] = cap_drop_list if cap_drop_list data[:net] = net if net data[:log_driver] = log_driver if log_driver data[:log_opts] = parse_log_opts(log_opt_list) if log_opt_list deploy_opts = parse_deploy_opts data[:deploy_opts] = deploy_opts unless deploy_opts.empty? health_check = parse_health_check data[:health_check] = health_check unless health_check.empty? data[:pid] = pid if pid data[:stop_signal] = stop_signal if stop_signal data[:stop_grace_period] = stop_timeout if stop_timeout data end
parse given options to hash @return [Hash]
train
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/services/update_command.rb#L61-L92
class UpdateCommand < Kontena::Command include Kontena::Cli::Common include Kontena::Cli::GridOptions include ServicesHelper parameter "NAME", "Service name" option "--image", "IMAGE", "Docker image to use" option ["-p", "--ports"], "PORT", "Publish a service's port to the host", multivalued: true option ["-e", "--env"], "ENV", "Set environment variables", multivalued: true option ["-l", "--link"], "LINK", "Add link to another service in the form of name:alias", multivalued: true option ["-a", "--affinity"], "AFFINITY", "Set service affinity", multivalued: true option "--cpus", "CPUS", "Number of CPUs" do |cpus| Float(cpus) end option ["-c", "--cpu-shares"], "CPU_SHARES", "CPU shares (relative weight)" option ["-m", "--memory"], "MEMORY", "Memory limit (format: <number><optional unit>, where unit = b, k, m or g)" option ["--memory-swap"], "MEMORY_SWAP", "Total memory usage (memory + swap), set \'-1\' to disable swap (format: <number><optional unit>, where unit = b, k, m or g)" option ["--shm-size"], "SHM_SIZE", "Size of /dev/shm (format: <number><optional unit>, where unit = b, k, m or g)" option "--cmd", "CMD", "Command to execute" option "--instances", "INSTANCES", "How many instances should be deployed" option ["-u", "--user"], "USER", "Username who executes first process inside container" option "--privileged", :flag, "Give extended privileges to this service", default: false option "--cap-add", "CAP_ADD", "Add capabitilies", multivalued: true, default: nil option "--cap-drop", "CAP_DROP", "Drop capabitilies", multivalued: true, default: nil option "--net", "NET", "Network mode" option "--log-driver", "LOG_DRIVER", "Set logging driver" option "--log-opt", "LOG_OPT", "Add logging options", multivalued: true, default: nil option "--deploy-strategy", "STRATEGY", "Deploy strategy to use (ha, daemon, random)" option "--deploy-wait-for-port", "PORT", "Wait for port to respond when deploying" option "--deploy-min-health", "FLOAT", "The minimum percentage (0.0 - 1.0) of healthy instances that do not sacrifice overall service availability while deploying" option "--deploy-interval", "TIME", "Auto-deploy with given interval (format: <number><unit>, where unit = min, h, d)" option "--pid", "PID", "Pid namespace to use" option "--secret", "SECRET", "Import secret from Vault (format: <secret>:<name>:<type>)", multivalued: true option "--health-check-uri", "URI", "URI path for HTTP health check" option "--health-check-timeout", "TIMEOUT", "Timeout for HTTP health check" option "--health-check-interval", "INTERVAL", "Interval for HTTP health check" option "--health-check-initial-delay", "DELAY", "Initial for HTTP health check" option "--health-check-port", "PORT", "Port for HTTP health check" option "--health-check-protocol", "PROTOCOL", "Protocol of health check" option "--stop-signal", "STOP_SIGNAL", "Alternative signal to stop container" option "--stop-timeout", "STOP_TIMEOUT", "Timeout (duration) to stop a container" def execute require_api_url token = require_token data = parse_service_data_from_options spinner "Updating #{pastel.cyan(name)} service " do update_service(token, name, data) end end ## # parse given options to hash # @return [Hash] end
kmuto/review
lib/epubmaker/epubcommon.rb
EPUBMaker.EPUBCommon.colophon
ruby
def colophon @title = CGI.escapeHTML(@producer.res.v('colophontitle')) @body = <<EOT <div class="colophon"> EOT if @producer.config['subtitle'].nil? @body << <<EOT <p class="title">#{CGI.escapeHTML(@producer.config.name_of('title'))}</p> EOT else @body << <<EOT <p class="title">#{CGI.escapeHTML(@producer.config.name_of('title'))}<br /><span class="subtitle">#{CGI.escapeHTML(@producer.config.name_of('subtitle'))}</span></p> EOT end @body << colophon_history if @producer.config['date'] || @producer.config['history'] @body << %Q( <table class="colophon">\n) @body << @producer.config['colophon_order'].map do |role| if @producer.config[role] %Q( <tr><th>#{CGI.escapeHTML(@producer.res.v(role))}</th><td>#{CGI.escapeHTML(join_with_separator(@producer.config.names_of(role), ReVIEW::I18n.t('names_splitter')))}</td></tr>\n) else '' end end.join @body << %Q( <tr><th>ISBN</th><td>#{@producer.isbn_hyphen}</td></tr>\n) if @producer.isbn_hyphen @body << %Q( </table>\n) if @producer.config['rights'] && !@producer.config['rights'].empty? @body << %Q( <p class="copyright">#{join_with_separator(@producer.config.names_of('rights').map { |m| CGI.escapeHTML(m) }, '<br />')}</p>\n) end @body << %Q( </div>\n) @language = @producer.config['language'] @stylesheets = @producer.config['stylesheet'] tmplfile = if @producer.config['htmlversion'].to_i == 5 File.expand_path('./html/layout-html5.html.erb', ReVIEW::Template::TEMPLATE_DIR) else File.expand_path('./html/layout-xhtml1.html.erb', ReVIEW::Template::TEMPLATE_DIR) end tmpl = ReVIEW::Template.load(tmplfile) tmpl.result(binding) end
Return colophon content.
train
https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/epubcommon.rb#L211-L254
class EPUBCommon # Construct object with parameter hash +config+ and message resource hash +res+. def initialize(producer) @body_ext = '' @producer = producer @body_ext = nil end # Return mimetype content. def mimetype 'application/epub+zip' end def opf_path "OEBPS/#{@producer.config['bookname']}.opf" end def opf_coverimage s = '' if @producer.config['coverimage'] file = nil @producer.contents.each do |item| if !item.media.start_with?('image') || item.file !~ /#{@producer.config['coverimage']}\Z/ next end s << %Q( <meta name="cover" content="#{item.id}"/>\n) file = item.file break end if file.nil? raise "coverimage #{@producer.config['coverimage']} not found. Abort." end end s end def ncx_isbn uid = @producer.config['isbn'] || @producer.config['urnid'] %Q( <meta name="dtb:uid" content="#{uid}"/>\n) end def ncx_doctitle <<EOT <docTitle> <text>#{CGI.escapeHTML(@producer.config['title'])}</text> </docTitle> <docAuthor> <text>#{@producer.config['aut'].nil? ? '' : CGI.escapeHTML(join_with_separator(@producer.config['aut'], ReVIEW::I18n.t('names_splitter')))}</text> </docAuthor> EOT end def ncx_navmap(indentarray) s = <<EOT <navMap> <navPoint id="top" playOrder="1"> <navLabel> <text>#{CGI.escapeHTML(@producer.config['title'])}</text> </navLabel> <content src="#{@producer.config['cover']}"/> </navPoint> EOT nav_count = 2 unless @producer.config['mytoc'].nil? s << <<EOT <navPoint id="toc" playOrder="#{nav_count}"> <navLabel> <text>#{CGI.escapeHTML(@producer.res.v('toctitle'))}</text> </navLabel> <content src="#{@producer.config['bookname']}-toc.#{@producer.config['htmlext']}"/> </navPoint> EOT nav_count += 1 end @producer.contents.each do |item| next if item.title.nil? indent = indentarray.nil? ? [''] : indentarray level = item.level.nil? ? 0 : (item.level - 1) level = indent.size - 1 if level >= indent.size s << <<EOT <navPoint id="nav-#{nav_count}" playOrder="#{nav_count}"> <navLabel> <text>#{indent[level]}#{CGI.escapeHTML(item.title)}</text> </navLabel> <content src="#{item.file}"/> </navPoint> EOT nav_count += 1 end s << <<EOT </navMap> EOT s end # Return container content. def container @opf_path = opf_path tmplfile = File.expand_path('./xml/container.xml.erb', ReVIEW::Template::TEMPLATE_DIR) tmpl = ReVIEW::Template.load(tmplfile) tmpl.result(binding) end # Return cover content. def cover(type = nil) @body_ext = type.nil? ? '' : %Q( epub:type="#{type}") if @producer.config['coverimage'] file = @producer.coverimage raise "coverimage #{@producer.config['coverimage']} not found. Abort." unless file @body = <<-EOT <div id="cover-image" class="cover-image"> <img src="#{file}" alt="#{CGI.escapeHTML(@producer.config.name_of('title'))}" class="max"/> </div> EOT else @body = <<-EOT <h1 class="cover-title">#{CGI.escapeHTML(@producer.config.name_of('title'))}</h1> EOT if @producer.config['subtitle'] @body << <<-EOT <h2 class="cover-subtitle">#{CGI.escapeHTML(@producer.config.name_of('subtitle'))}</h2> EOT end end @title = CGI.escapeHTML(@producer.config.name_of('title')) @language = @producer.config['language'] @stylesheets = @producer.config['stylesheet'] tmplfile = if @producer.config['htmlversion'].to_i == 5 File.expand_path('./html/layout-html5.html.erb', ReVIEW::Template::TEMPLATE_DIR) else File.expand_path('./html/layout-xhtml1.html.erb', ReVIEW::Template::TEMPLATE_DIR) end tmpl = ReVIEW::Template.load(tmplfile) tmpl.result(binding) end # Return title (copying) content. # NOTE: this method is not used yet. # see lib/review/epubmaker.rb#build_titlepage def titlepage @title = CGI.escapeHTML(@producer.config.name_of('title')) @body = <<EOT <h1 class="tp-title">#{@title}</h1> EOT if @producer.config['subtitle'] @body << <<EOT <h2 class="tp-subtitle">#{CGI.escapeHTML(@producer.config.name_of('subtitle'))}</h2> EOT end if @producer.config['aut'] @body << <<EOT <p> <br /> <br /> </p> <h2 class="tp-author">#{CGI.escapeHTML(join_with_separator(@producer.config.names_of('aut'), ReVIEW::I18n.t('names_splitter')))}</h2> EOT end publisher = @producer.config.names_of('pbl') if publisher @body << <<EOT <p> <br /> <br /> <br /> <br /> </p> <h3 class="tp-publisher">#{CGI.escapeHTML(join_with_separator(publisher, ReVIEW::I18n.t('names_splitter')))}</h3> EOT end @language = @producer.config['language'] @stylesheets = @producer.config['stylesheet'] tmplfile = if @producer.config['htmlversion'].to_i == 5 File.expand_path('./html/layout-html5.html.erb', ReVIEW::Template::TEMPLATE_DIR) else File.expand_path('./html/layout-xhtml1.html.erb', ReVIEW::Template::TEMPLATE_DIR) end tmpl = ReVIEW::Template.load(tmplfile) tmpl.result(binding) end # Return colophon content. def colophon_history buf = '' buf << %Q( <div class="pubhistory">\n) if @producer.config['history'] @producer.config['history'].each_with_index do |items, edit| items.each_with_index do |item, rev| editstr = edit == 0 ? ReVIEW::I18n.t('first_edition') : ReVIEW::I18n.t('nth_edition', (edit + 1).to_s) revstr = ReVIEW::I18n.t('nth_impression', (rev + 1).to_s) if item =~ /\A\d+\-\d+\-\d+\Z/ buf << %Q( <p>#{ReVIEW::I18n.t('published_by1', [date_to_s(item), editstr + revstr])}</p>\n) elsif item =~ /\A(\d+\-\d+\-\d+)[\s ](.+)/ # custom date with string item.match(/\A(\d+\-\d+\-\d+)[\s ](.+)/) do |m| buf << %Q( <p>#{ReVIEW::I18n.t('published_by3', [date_to_s(m[1]), m[2]])}</p>\n) end else # free format buf << %Q( <p>#{item}</p>\n) end end end else buf << %Q( <p>#{ReVIEW::I18n.t('published_by2', date_to_s(@producer.config['date']))}</p>\n) end buf << %Q( </div>\n) buf end def date_to_s(date) require 'date' d = Date.parse(date) d.strftime(ReVIEW::I18n.t('date_format')) end # Return own toc content. def mytoc @title = CGI.escapeHTML(@producer.res.v('toctitle')) @body = %Q( <h1 class="toc-title">#{CGI.escapeHTML(@producer.res.v('toctitle'))}</h1>\n) if @producer.config['epubmaker']['flattoc'].nil? @body << hierarchy_ncx('ul') else @body << flat_ncx('ul', @producer.config['epubmaker']['flattocindent']) end @language = @producer.config['language'] @stylesheets = @producer.config['stylesheet'] tmplfile = if @producer.config['htmlversion'].to_i == 5 File.expand_path('./html/layout-html5.html.erb', ReVIEW::Template::TEMPLATE_DIR) else File.expand_path('./html/layout-xhtml1.html.erb', ReVIEW::Template::TEMPLATE_DIR) end tmpl = ReVIEW::Template.load(tmplfile) tmpl.result(binding) end def hierarchy_ncx(type) require 'rexml/document' level = 1 find_jump = nil has_part = nil toclevel = @producer.config['toclevel'].to_i # check part existance @producer.contents.each do |item| next if item.notoc || item.chaptype != 'part' has_part = true break end if has_part @producer.contents.each do |item| if item.chaptype == 'part' && item.level > 0 # sections in part item.level -= 1 end # down level for part and chaps. pre, appendix, post are preserved if item.chaptype == 'part' || item.chaptype == 'body' item.level += 1 end end toclevel += 1 end doc = REXML::Document.new(%Q(<#{type} class="toc-h#{level}"><li /></#{type}>)) doc.context[:attribute_quote] = :quote e = doc.root.elements[1] # first <li/> @producer.contents.each do |item| next if !item.notoc.nil? || item.level.nil? || item.file.nil? || item.title.nil? || item.level > toclevel if item.level == level e2 = e.parent.add_element('li') e = e2 elsif item.level > level find_jump = true if (item.level - level) > 1 # deeper (level + 1).upto(item.level) do |n| if e.size == 0 # empty span for epubcheck e.attributes['style'] = 'list-style-type: none;' es = e.add_element('span', 'style' => 'display:none;') es.add_text(REXML::Text.new('&#xa0;', false, nil, true)) end e2 = e.add_element(type, 'class' => "toc-h#{n}") e3 = e2.add_element('li') e = e3 end level = item.level elsif item.level < level # shallower (level - 1).downto(item.level) { e = e.parent.parent } e2 = e.parent.add_element('li') e = e2 level = item.level end e2 = e.add_element('a', 'href' => item.file) e2.add_text(REXML::Text.new(item.title, true)) end warn %Q(found level jumping in table of contents. consider to use 'epubmaker:flattoc: true' for strict ePUB validator.) unless find_jump.nil? doc.to_s.gsub('<li/>', '').gsub('</li>', "</li>\n").gsub("<#{type} ", "\n" + '\&') # ugly end def flat_ncx(type, indent = nil) s = %Q(<#{type} class="toc-h1">\n) @producer.contents.each do |item| next if !item.notoc.nil? || item.level.nil? || item.file.nil? || item.title.nil? || item.level > @producer.config['toclevel'].to_i is = indent == true ? ' ' * item.level : '' s << %Q(<li><a href="#{item.file}">#{is}#{CGI.escapeHTML(item.title)}</a></li>\n) end s << %Q(</#{type}>\n) s end def produce_write_common(basedir, tmpdir) File.open("#{tmpdir}/mimetype", 'w') { |f| @producer.mimetype(f) } FileUtils.mkdir_p("#{tmpdir}/META-INF") File.open("#{tmpdir}/META-INF/container.xml", 'w') { |f| @producer.container(f) } FileUtils.mkdir_p("#{tmpdir}/OEBPS") File.open(File.join(tmpdir, opf_path), 'w') { |f| @producer.opf(f) } if File.exist?("#{basedir}/#{@producer.config['cover']}") FileUtils.cp("#{basedir}/#{@producer.config['cover']}", "#{tmpdir}/OEBPS") else File.open("#{tmpdir}/OEBPS/#{@producer.config['cover']}", 'w') { |f| @producer.cover(f) } end @producer.contents.each do |item| next if item.file =~ /#/ # skip subgroup fname = "#{basedir}/#{item.file}" raise "#{fname} doesn't exist. Abort." unless File.exist?(fname) FileUtils.mkdir_p(File.dirname("#{tmpdir}/OEBPS/#{item.file}")) FileUtils.cp(fname, "#{tmpdir}/OEBPS/#{item.file}") end end def legacy_cover_and_title_file(loadfile, writefile) @title = @producer.config['booktitle'] s = '' File.open(loadfile) do |f| f.each_line do |l| s << l end end File.open(writefile, 'w') do |f| f.puts s end end def join_with_separator(value, sep) if value.is_a?(Array) value.join(sep) else value end end end
documentcloud/cloud-crowd
lib/cloud_crowd/command_line.rb
CloudCrowd.CommandLine.run_install
ruby
def run_install(install_path) require 'fileutils' install_path ||= '.' FileUtils.mkdir_p install_path unless File.exists?(install_path) install_file "#{CC_ROOT}/config/config.example.yml", "#{install_path}/config.yml" install_file "#{CC_ROOT}/config/config.example.ru", "#{install_path}/config.ru" install_file "#{CC_ROOT}/config/database.example.yml", "#{install_path}/database.yml" install_file "#{CC_ROOT}/actions", "#{install_path}/actions", true end
Install the required CloudCrowd configuration files into the specified directory, or the current one.
train
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/command_line.rb#L143-L151
class CommandLine # Configuration files required for the `crowd` command to function. CONFIG_FILES = ['config.yml', 'config.ru', 'database.yml'] # Reference the absolute path to the root. CC_ROOT = File.expand_path(File.dirname(__FILE__) + '/../..') # Command-line banner for the usage message. BANNER = <<-EOS CloudCrowd is a MapReduce-inspired Parallel Processing System for Ruby. Wiki: http://wiki.github.com/documentcloud/cloud-crowd Rdoc: http://rdoc.info/projects/documentcloud/cloud-crowd Usage: crowd COMMAND OPTIONS Commands: install Install the CloudCrowd configuration files to the specified directory server Start up the central server (requires a database) node Start up a worker node (only one node per machine, please) console Launch a CloudCrowd console, connected to the central database load_schema Load the schema into the database specified by database.yml cleanup Removes jobs that were finished over --days (7 by default) ago server -d [start | stop | restart] Servers and nodes can be launched as node -d [start | stop | restart] daemons, then stopped or restarted. Options: EOS # Creating a CloudCrowd::CommandLine runs from the contents of ARGV. def initialize parse_options command = ARGV.shift subcommand = ARGV.shift case command when 'console' then run_console when 'server' then run_server(subcommand) when 'node' then run_node(subcommand) when 'load_schema' then run_load_schema when 'install' then run_install(subcommand) when 'cleanup' then run_cleanup else usage end end # Spin up an IRB session with the CloudCrowd code loaded in, and a database # connection established. The equivalent of Rails' `script/console`. def run_console require 'irb' require 'irb/completion' require 'pp' load_code connect_to_database true CloudCrowd::Server # Preload server to autoload classes. Object.send(:include, CloudCrowd) IRB.start end # `crowd server` can either 'start', 'stop', or 'restart'. def run_server(subcommand) load_code subcommand ||= 'start' case subcommand when 'start' then start_server when 'stop' then stop_server when 'restart' then restart_server end end # Convenience command for quickly spinning up the central server. More # sophisticated deployments, load-balancing across multiple app servers, # should use the config.ru rackup file directly. This method will start # a single Thin server. def start_server port = @options[:port] || 9173 daemonize = @options[:daemonize] ? '-d' : '' log_path = CloudCrowd.log_path('server.log') pid_path = CloudCrowd.pid_path('server.pid') rackup_path = File.expand_path("#{@options[:config_path]}/config.ru") FileUtils.mkdir_p(CloudCrowd.log_path) if @options[:daemonize] && !File.exists?(CloudCrowd.log_path) puts "Starting CloudCrowd Central Server (#{VERSION}) on port #{port}..." exec "thin -e #{@options[:environment]} -p #{port} #{daemonize} --tag cloud-crowd-server --log #{log_path} --pid #{pid_path} -R #{rackup_path} start" end # Stop the daemonized central server, if it exists. def stop_server Thin::Server.kill(CloudCrowd.pid_path('server.pid'), 0) end # Restart the daemonized central server. def restart_server stop_server sleep 1 start_server end # `crowd node` can either 'start', 'stop', or 'restart'. def run_node(subcommand) load_code ENV['RACK_ENV'] = @options[:environment] case (subcommand || 'start') when 'start' then start_node when 'stop' then stop_node when 'restart' then restart_node end end # Launch a Node. Please only run a single node per machine. The Node process # will be long-lived, although its workers will come and go. def start_node @options[:port] ||= Node::DEFAULT_PORT puts "Starting CloudCrowd Node (#{VERSION}) on port #{@options[:port]}..." Node.new(@options) end # If the daemonized Node is running, stop it. def stop_node Thin::Server.kill CloudCrowd.pid_path('node.pid') end # Restart the daemonized Node, if it exists. def restart_node stop_node sleep 1 start_node end # Load in the database schema to the database specified in 'database.yml'. def run_load_schema load_code connect_to_database(false) require 'cloud_crowd/schema.rb' end # Install the required CloudCrowd configuration files into the specified # directory, or the current one. # Clean up all Jobs in the CloudCrowd database older than --days old. def run_cleanup load_code connect_to_database(true) Job.cleanup_all(:days => @options[:days]) end # Print `crowd` usage. def usage puts "\n#{@option_parser}\n" end private # Check for configuration files, either in the current directory, or in # the CLOUD_CROWD_CONFIG environment variable. Exit if they're not found. def ensure_config return if @config_found found = CONFIG_FILES.all? {|f| File.exists? "#{@options[:config_path]}/#{f}" } found ? @config_dir = true : config_not_found end # Parse all options for all commands. # Valid options are: --config --port --environment --tag --daemonize --days. def parse_options @options = { :environment => 'production', :config_path => ENV['CLOUD_CROWD_CONFIG'] || '.', :daemonize => false } @option_parser = OptionParser.new do |opts| opts.on('-c', '--config PATH', 'path to configuration directory') do |conf_path| @options[:config_path] = conf_path end opts.on('-p', '--port PORT', 'port number for server (central or node)') do |port_num| @options[:port] = port_num end opts.on('-e', '--environment ENV', 'server environment (defaults to production)') do |env| @options[:environment] = env end opts.on('-t', '--tag TAG', 'tag a node with a name') do |tag| @options[:tag] = tag end opts.on('-d', '--daemonize', 'run as a background daemon') do |daemonize| @options[:daemonize] = daemonize end opts.on('--days NUM_DAYS', 'grace period before cleanup (7 by default)') do |days| @options[:days] = days.to_i if days.match(/\A\d+\Z/) end opts.on_tail('-v', '--version', 'show version') do require "#{CC_ROOT}/lib/cloud-crowd" puts "CloudCrowd version #{VERSION}" exit end end @option_parser.banner = BANNER @option_parser.parse!(ARGV) end # Load in the CloudCrowd module code, dependencies, lib files and models. # Not all commands require this. def load_code ensure_config require "#{CC_ROOT}/lib/cloud-crowd" CloudCrowd.configure("#{@options[:config_path]}/config.yml") end # Establish a connection to the central server's database. Not all commands # require this. def connect_to_database(validate_schema) require 'cloud_crowd/models' CloudCrowd.configure_database("#{@options[:config_path]}/database.yml", validate_schema) end # Exit with an explanation if the configuration files couldn't be found. def config_not_found puts "`crowd` can't find the CloudCrowd configuration directory. Please use `crowd -c path/to/config`, or run `crowd` from inside of the configuration directory itself." exit(1) end # Install a file and log the installation. If we're overwriting a file, # offer a chance to back out. def install_file(source, dest, is_dir=false) if File.exists?(dest) print "#{dest} already exists. Overwrite it? (yes/no) " return unless ['y', 'yes', 'ok'].include? gets.chomp.downcase end is_dir ? FileUtils.cp_r(source, dest) : FileUtils.cp(source, dest) puts "installed #{dest}" unless ENV['RACK_ENV'] == 'test' end end
zhimin/rwebspec
lib/rwebspec-common/assert.rb
RWebSpec.Assert.assert
ruby
def assert test, msg = nil msg ||= "Failed assertion, no message given." # comment out self.assertions += 1 to counting assertions unless test then msg = msg.call if Proc === msg raise RWebSpec::Assertion, msg end true end
own assert method
train
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-common/assert.rb#L6-L14
module Assert # own assert method def assert test, msg = nil msg ||= "Failed assertion, no message given." # comment out self.assertions += 1 to counting assertions unless test then msg = msg.call if Proc === msg raise RWebSpec::Assertion, msg end true end def fail(message) perform_assertion { assert(false, message) } end def assert_not(condition, msg = "") perform_assertion { assert(!condition, msg) } end def assert_not_nil(actual, msg="") perform_assertion { assert(!actual.nil?, msg) } end def assert_title_equals(title) assert_equals(title, @web_browser.page_title) end alias assert_title assert_title_equals # Assert text present in page source (html) # assert_text_in_page_source("<b>iTest2</b> Cool") # <b>iTest2</b> Cool def assert_text_in_page_source(text) perform_assertion { assert((@web_browser.page_source.include? text), 'expected html: ' + text + ' not found') } end # Assert text not present in page source (html) # assert_text_not_in_page_source("<b>iTest2</b> Cool") # <b>iTest2</b> Cool def assert_text_not_in_page_source(text) perform_assertion { assert(!(@web_browser.page_source.include? text), 'expected html: ' + text + ' found') } end # Assert text present in page source (html) # assert_text_present("iTest2 Cool") # <b>iTest2</b> Cool def assert_text_present(text) perform_assertion { assert((@web_browser.text.include? text), 'expected text: ' + text + ' not found') } end # Assert text not present in page source (html) # assert_text_not_present("iTest2 Cool") # <b>iTest2</b> Cool def assert_text_not_present(text) perform_assertion { assert(!(@web_browser.text.include? text), 'expected text: ' + text + ' found') } end ## # Link # Assert a link with specified text (exact match) in the page # # <a href="">Click Me</a> # assert_link_present_with_exact("Click Me") => true # assert_link_present_with_exact("Click") => false # def assert_link_present_with_exact(link_text) @web_browser.links.each { |link| return if link_text == link.text } fail( "can't find the link with text: #{link_text}") end def assert_link_not_present_with_exact(link_text) @web_browser.links.each { |link| perform_assertion { assert(link_text != link.text, "unexpected link (exact): #{link_text} found") } } end # Assert a link containing specified text in the page # # <a href="">Click Me</a> # assert_link_present_with_text("Click ") # => # def assert_link_present_with_text(link_text) @web_browser.links.each { |link| return if link.text.include?(link_text) } fail( "can't find the link containing text: #{link_text}") end def assert_link_not_present_with_text(link_text) @web_browser.links.each { |link| perform_assertion { assert(!link.text.include?(link_text), "unexpected link containing: #{link_text} found") } } end def is_selenium_element?(elem) elem.class.name =~ /Selenium/ end def element_name(elem) elem.class.name =~ /Selenium/ ? elem['name'] : elem.name end def element_value(elem) elem.class.name =~ /Selenium/ ? elem['value'] : elem.value end ## # Checkbox def assert_checkbox_not_selected(checkbox_name) @web_browser.checkboxes.each { |checkbox| the_element_name = element_name(checkbox) if (the_element_name == checkbox_name) then if is_selenium_element?(checkbox) perform_assertion { assert(!checkbox.selected?, "Checkbox #{checkbox_name} is checked unexpectly") } else perform_assertion { assert(!checkbox.set?, "Checkbox #{checkbox_name} is checked unexpectly") } end end } end alias assert_checkbox_not_checked assert_checkbox_not_selected def assert_checkbox_selected(checkbox_name) @web_browser.checkboxes.each { |checkbox| the_element_name = element_name(checkbox) if (the_element_name == checkbox_name) then if is_selenium_element?(checkbox) perform_assertion { assert(checkbox.selected?, "Checkbox #{checkbox_name} not checked") } else perform_assertion { assert(checkbox.set?, "Checkbox #{checkbox_name} not checked") } end end } end alias assert_checkbox_checked assert_checkbox_selected ## # select def assert_option_value_not_present(select_name, option_value) @web_browser.select_lists.each { |select| the_element_name = element_name(select) next unless the_element_name == select_name if RWebSpec.framework =~ /watir/i select.options.each do |option| # items in the list perform_assertion { assert(!(option.value == option_value), "unexpected select option: #{option_value} for #{select_name} found") } end else select.find_elements(:tag_name => "option" ).each do |option| fail("unexpected option value: #{option_label} found") if option.value == option_value end end } end alias assert_select_value_not_present assert_option_value_not_present def assert_option_not_present(select_name, option_label) @web_browser.select_lists.each { |select| the_element_name = element_name(select) next unless the_element_name == select_name if RWebSpec.framework =~ /watir/i select.options.each do |option| # items in the list perform_assertion { assert(!(option.text == option_label), "unexpected select option: #{option_label} for #{select_name} found") } end else select.find_elements(:tag_name => "option" ).each do |option| fail("unexpected option label: #{option_label} found") if option.text == option_label end end } end alias assert_select_label_not_present assert_option_not_present def assert_option_value_present(select_name, option_value) @web_browser.select_lists.each { |select| the_element_name = element_name(select) next unless the_element_name == select_name if RWebSpec.framework == "Watir" select.options.each do |option| # items in the list return if option.value == option_value end else select.find_elements(:tag_name => "option" ).each do |option| return if element_value(option) == option_value end end } fail("can't find the combo box with value: #{option_value}") end alias assert_select_value_present assert_option_value_present alias assert_menu_value_present assert_option_value_present def assert_option_present(select_name, option_label) @web_browser.select_lists.each { |select| the_element_name = element_name(select) next unless the_element_name == select_name if RWebSpec.framework == "Watir" select.options.each do |option| # items in the list return if option.text == option_label end else select.find_elements(:tag_name => "option" ).each do |option| return if option.text == option_label end end } fail("can't find the combo box: #{select_name} with value: #{option_label}") end alias assert_select_label_present assert_option_present alias assert_menu_label_present assert_option_present def assert_option_equals(select_name, option_label) @web_browser.select_lists.each { |select| the_element_name = element_name(select) next unless the_element_name == select_name if RWebSpec.framework == "Watir" select.options.each do |option| # items in the list if (option.text == option_label) then perform_assertion { assert_equal(select.value, option.value, "Select #{select_name}'s value is not equal to expected option label: '#{option_label}'") } end end else select.find_elements(:tag_name => "option" ).each do |option| if (option.text == option_label) then assert option.selected? end end end } end alias assert_select_label assert_option_equals alias assert_menu_label assert_option_equals def assert_option_value_equals(select_name, option_value) @web_browser.select_lists.each { |select| the_element_name = element_name(select) next unless the_element_name == select_name if RWebSpec.framework == "Watir" perform_assertion { assert_equal(select.value, option_value, "Select #{select_name}'s value is not equal to expected: '#{option_value}'") } else perform_assertion { assert_equal(element_value(select), option_value, "Select #{select_name}'s value is not equal to expected: '#{option_value}'") } end } end alias assert_select_value assert_option_value_equals alias assert_menu_value assert_option_value_equals ## # radio # radio_group is the name field, radio options 'value' field def assert_radio_option_not_present(radio_group, radio_option) @web_browser.radios.each { |radio| the_element_name = element_name(radio) if (the_element_name == radio_group) then perform_assertion { assert(!(radio_option == element_value(radio) ), "unexpected radio option: " + radio_option + " found") } end } end def assert_radio_option_present(radio_group, radio_option) @web_browser.radios.each { |radio| the_element_name = element_name(radio) return if (the_element_name == radio_group) and (radio_option == element_value(radio) ) } fail("can't find the radio option : '#{radio_option}'") end def assert_radio_option_selected(radio_group, radio_option) @web_browser.radios.each { |radio| the_element_name = element_name(radio) if (the_element_name == radio_group and radio_option == element_value(radio) ) then if is_selenium_element?(radio) perform_assertion { assert(radio.selected?, "Radio button #{radio_group}-[#{radio_option}] not checked") } else perform_assertion { assert(radio.set?, "Radio button #{radio_group}-[#{radio_option}] not checked") } end end } end alias assert_radio_button_checked assert_radio_option_selected alias assert_radio_option_checked assert_radio_option_selected def assert_radio_option_not_selected(radio_group, radio_option) @web_browser.radios.each { |radio| the_element_name = element_name(radio) if (the_element_name == radio_group and radio_option == element_value(radio) ) then if is_selenium_element?(radio) perform_assertion { assert(!radio.selected?, "Radio button #{radio_group}-[#{radio_option}] checked unexpected") } else perform_assertion { assert(!radio.set?, "Radio button #{radio_group}-[#{radio_option}] checked unexpected") } end end } end alias assert_radio_button_not_checked assert_radio_option_not_selected alias assert_radio_option_not_checked assert_radio_option_not_selected ## # Button def assert_button_not_present(button_id) @web_browser.buttons.each { |button| the_button_id = RWebSpec.framework == "Watir" ? button.id : button["id"] perform_assertion { assert(the_button_id != button_id, "unexpected button id: #{button_id} found") } } end def assert_button_not_present_with_text(text) @web_browser.buttons.each { |button| perform_assertion { assert(element_value(button) != text, "unexpected button id: #{text} found") } } end def assert_button_present(button_id) @web_browser.buttons.each { |button| the_button_id = RWebSpec.framework == "Watir" ? button.id : button["id"] return if button_id == the_button_id } fail("can't find the button with id: #{button_id}") end def assert_button_present_with_text(button_text) @web_browser.buttons.each { |button| return if button_text == element_value(button) } fail("can't find the button with text: #{button_text}") end def assert_equals(expected, actual, msg=nil) perform_assertion { assert(expected == actual, (msg.nil?) ? "Expected: #{expected} diff from actual: #{actual}" : msg) } end # Check a HTML element exists or not # Example: # assert_exists("label", "receipt_date") # assert_exists(:span, :receipt_date) def assert_exists(tag, element_id) if RWebSpec.framework == "Watir" perform_assertion { assert(eval("#{tag}(:id, '#{element_id.to_s}').exists?"), "Element '#{tag}' with id: '#{element_id}' not found") } else perform_assertion { assert( @web_browser.driver.find_element(:tag_name => tag, :id => element_id))} end end alias assert_exists? assert_exists alias assert_element_exists assert_exists def assert_not_exists(tag, element_id) if RWebSpec.framework == "Watir" perform_assertion { assert_not(eval("#{tag}(:id, '#{element_id.to_s}').exists?"), "Unexpected element'#{tag}' + with id: '#{element_id}' found")} else perform_assertion { begin @web_browser.driver.find_element(:tag_name => tag, :id => element_id) fail("the element #{tag}##{element_id} found") rescue =>e end } end end alias assert_not_exists? assert_not_exists alias assert_element_not_exists? assert_not_exists # Assert tag with element id is visible?, eg. # assert_visible(:div, "public_notice") # assert_visible(:span, "public_span") def assert_visible(tag, element_id) if RWebSpec.framework =~ /selenium/i perform_assertion { assert(eval("#{tag}(:id, '#{element_id.to_s}').displayed?"), "Element '#{tag}' with id: '#{element_id}' not visible") } else perform_assertion { assert(eval("#{tag}(:id, '#{element_id.to_s}').visible?"), "Element '#{tag}' with id: '#{element_id}' not visible") } end end # Assert tag with element id is hidden?, example # assert_hidden(:div, "secret") # assert_hidden(:span, "secret_span") def assert_hidden(tag, element_id) if RWebSpec.framework =~ /selenium/i perform_assertion { assert(!eval("#{tag}(:id, '#{element_id.to_s}').displayed?"), "Element '#{tag}' with id: '#{element_id}' is visible") } else perform_assertion { assert(!eval("#{tag}(:id, '#{element_id.to_s}').visible?"), "Element '#{tag}' with id: '#{element_id}' is visible") } end end alias assert_not_visible assert_hidden # Assert given text appear inside a table (inside <table> tag like below) # # <table id="t1"> # # <tbody> # <tr id="row_1"> # <td id="cell_1_1">A</td> # <td id="cell_1_2">B</td> # </tr> # <tr id="row_2"> # <td id="cell_2_1">a</td> # <td id="cell_2_2">b</td> # </tr> # </tbody> # # </table> # # The plain text view of above table # A B a b # # Examples # assert_text_present_in_table("t1", ">A<") # => true # assert_text_present_in_table("t1", ">A<", :just_plain_text => true) # => false def assert_text_present_in_table(table_id, text, options = {}) options[:just_plain_text] ||= false perform_assertion { assert(the_table_source(table_id, options).include?(text), "the text #{text} not found in table #{table_id}") } end alias assert_text_in_table assert_text_present_in_table def assert_text_not_present_in_table(table_id, text, options = {}) options[:just_plain_text] ||= false perform_assertion { assert_not(the_table_source(table_id, options).include?(text), "the text #{text} not found in table #{table_id}") } end alias assert_text_not_in_table assert_text_not_present_in_table # Assert a text field (with given name) has the value # # <input id="tid" name="text1" value="text already there" type="text"> # # assert_text_field_value("text1", "text already there") => true # def assert_text_field_value(textfield_name, text) if RWebSpec.framework == "Watir" perform_assertion { assert_equal(text, text_field(:name, textfield_name).value) } else the_element = @web_browser.driver.find_element(:name, textfield_name) perform_assertion { assert_equal(text, element_value(the_element)) } end end #-- Not tested # ----- def assert_text_in_element(element_id, text) elem = element_by_id(element_id) if RWebSpec.framework == "Watir" assert_not_nil(elem.innerText, "element #{element_id} has no text") perform_assertion { assert(elem.innerText.include?(text), "the text #{text} not found in element #{element_id}") } else perform_assertion { # this works in text field assert(element_value(elem).include?(text), "the text #{text} not found in element #{element_id}") # TODO } end end # Use # #TODO for drag-n-drop, check the postion in list # def assert_position_in_list(list_element_id) # raise "not implemented" # end private def the_table_source(table_id, options) elem_table = RWebSpec.framework == "Watir" ? table(:id, table_id.to_s) : @web_browser.driver.find_element(:id => table_id) elem_table_text = elem_table.text elem_table_html = RWebSpec.framework == "Watir" ? elem_table.html : elem_table["innerHTML"]; table_source = options[:just_plain_text] ? elem_table_text : elem_table_html end def perform_assertion(&block) begin yield rescue StandardError => e # puts "[DEBUG] Assertion error: #{e}" take_screenshot if $take_screenshot raise e rescue MiniTest::Assertion => e2 take_screenshot if $take_screenshot raise e2 end end end
chaintope/bitcoinrb
lib/bitcoin/tx.rb
Bitcoin.Tx.witness_commitment
ruby
def witness_commitment return nil unless coinbase_tx? outputs.each do |output| commitment = output.script_pubkey.witness_commitment return commitment if commitment end nil end
get the witness commitment of coinbase tx. if this tx does not coinbase or not have commitment, return nil.
train
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/tx.rb#L94-L101
class Tx MAX_STANDARD_VERSION = 2 # The maximum weight for transactions we're willing to relay/mine MAX_STANDARD_TX_WEIGHT = 400000 MARKER = 0x00 FLAG = 0x01 attr_accessor :version attr_accessor :marker attr_accessor :flag attr_reader :inputs attr_reader :outputs attr_accessor :lock_time def initialize @inputs = [] @outputs = [] @version = 1 @lock_time = 0 end alias_method :in, :inputs alias_method :out, :outputs def self.parse_from_payload(payload, non_witness: false) buf = payload.is_a?(String) ? StringIO.new(payload) : payload tx = new tx.version = buf.read(4).unpack('V').first in_count = Bitcoin.unpack_var_int_from_io(buf) witness = false if in_count.zero? && !non_witness tx.marker = 0 tx.flag = buf.read(1).unpack('c').first if tx.flag.zero? buf.pos -= 1 else in_count = Bitcoin.unpack_var_int_from_io(buf) witness = true end end in_count.times do tx.inputs << TxIn.parse_from_payload(buf) end out_count = Bitcoin.unpack_var_int_from_io(buf) out_count.times do tx.outputs << TxOut.parse_from_payload(buf) end if witness in_count.times do |i| tx.inputs[i].script_witness = Bitcoin::ScriptWitness.parse_from_payload(buf) end end tx.lock_time = buf.read(4).unpack('V').first tx end def hash to_payload.bth.to_i(16) end def tx_hash Bitcoin.double_sha256(serialize_old_format).bth end def txid tx_hash.rhex end def witness_hash Bitcoin.double_sha256(to_payload).bth end def wtxid witness_hash.rhex end # get the witness commitment of coinbase tx. # if this tx does not coinbase or not have commitment, return nil. def to_payload witness? ? serialize_witness_format : serialize_old_format end def coinbase_tx? inputs.length == 1 && inputs.first.coinbase? end def witness? !inputs.find { |i| !i.script_witness.empty? }.nil? end def ==(other) to_payload == other.to_payload end # serialize tx with old tx format def serialize_old_format buf = [version].pack('V') buf << Bitcoin.pack_var_int(inputs.length) << inputs.map(&:to_payload).join buf << Bitcoin.pack_var_int(outputs.length) << outputs.map(&:to_payload).join buf << [lock_time].pack('V') buf end # serialize tx with segwit tx format # https://github.com/bitcoin/bips/blob/master/bip-0144.mediawiki def serialize_witness_format buf = [version, MARKER, FLAG].pack('Vcc') buf << Bitcoin.pack_var_int(inputs.length) << inputs.map(&:to_payload).join buf << Bitcoin.pack_var_int(outputs.length) << outputs.map(&:to_payload).join buf << witness_payload << [lock_time].pack('V') buf end def witness_payload inputs.map { |i| i.script_witness.to_payload }.join end # check this tx is standard. def standard? return false if version > MAX_STANDARD_VERSION return false if weight > MAX_STANDARD_TX_WEIGHT inputs.each do |i| # Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed keys (remember the 520 byte limit on redeemScript size). # That works out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627 # bytes of scriptSig, which we round off to 1650 bytes for some minor future-proofing. # That's also enough to spend a 20-of-20 CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not considered standard. return false if i.script_sig.size > 1650 return false unless i.script_sig.push_only? end data_count = 0 outputs.each do |o| return false unless o.script_pubkey.standard? data_count += 1 if o.script_pubkey.op_return? # TODO add non P2SH multisig relay(permitbaremultisig) # TODO add dust relay check end return false if data_count > 1 true end # The serialized transaction size def size to_payload.bytesize end # The virtual transaction size (differs from size for witness transactions) def vsize (weight.to_f / 4).ceil end # calculate tx weight # weight = (legacy tx payload) * 3 + (witness tx payload) def weight if witness? serialize_old_format.bytesize * (WITNESS_SCALE_FACTOR - 1) + serialize_witness_format.bytesize else serialize_old_format.bytesize * WITNESS_SCALE_FACTOR end end # get signature hash # @param [Integer] input_index input index. # @param [Integer] hash_type signature hash type # @param [Bitcoin::Script] output_script script pubkey or script code. if script pubkey is P2WSH, set witness script to this. # @param [Integer] amount bitcoin amount locked in input. required for witness input only. # @param [Integer] skip_separator_index If output_script is P2WSH and output_script contains any OP_CODESEPARATOR, # the script code needs is the witnessScript but removing everything up to and including the last executed OP_CODESEPARATOR before the signature checking opcode being executed. def sighash_for_input(input_index, output_script, hash_type: SIGHASH_TYPE[:all], sig_version: :base, amount: nil, skip_separator_index: 0) raise ArgumentError, 'input_index must be specified.' unless input_index raise ArgumentError, 'does not exist input corresponding to input_index.' if input_index >= inputs.size raise ArgumentError, 'script_pubkey must be specified.' unless output_script raise ArgumentError, 'unsupported sig version specified.' unless SIG_VERSION.include?(sig_version) if sig_version == :witness_v0 || Bitcoin.chain_params.fork_chain? raise ArgumentError, 'amount must be specified.' unless amount sighash_for_witness(input_index, output_script, hash_type, amount, skip_separator_index) else sighash_for_legacy(input_index, output_script, hash_type) end end # verify input signature. # @param [Integer] input_index # @param [Bitcoin::Script] script_pubkey the script pubkey for target input. # @param [Integer] amount the amount of bitcoin, require for witness program only. # @param [Array] flags the flags used when execute script interpreter. def verify_input_sig(input_index, script_pubkey, amount: nil, flags: STANDARD_SCRIPT_VERIFY_FLAGS) script_sig = inputs[input_index].script_sig has_witness = inputs[input_index].has_witness? if script_pubkey.p2sh? flags << SCRIPT_VERIFY_P2SH redeem_script = Script.parse_from_payload(script_sig.chunks.last) script_pubkey = redeem_script if redeem_script.p2wpkh? end if has_witness || Bitcoin.chain_params.fork_chain? verify_input_sig_for_witness(input_index, script_pubkey, amount, flags) else verify_input_sig_for_legacy(input_index, script_pubkey, flags) end end def to_h { txid: txid, hash: witness_hash.rhex, version: version, size: size, vsize: vsize, locktime: lock_time, vin: inputs.map(&:to_h), vout: outputs.map.with_index{|tx_out, index| tx_out.to_h.merge({n: index})} } end private # generate sighash with legacy format def sighash_for_legacy(index, script_code, hash_type) ins = inputs.map.with_index do |i, idx| if idx == index i.to_payload(script_code.delete_opcode(Bitcoin::Opcodes::OP_CODESEPARATOR)) else case hash_type & 0x1f when SIGHASH_TYPE[:none], SIGHASH_TYPE[:single] i.to_payload(Bitcoin::Script.new, 0) else i.to_payload(Bitcoin::Script.new) end end end outs = outputs.map(&:to_payload) out_size = Bitcoin.pack_var_int(outputs.size) case hash_type & 0x1f when SIGHASH_TYPE[:none] outs = '' out_size = Bitcoin.pack_var_int(0) when SIGHASH_TYPE[:single] return "\x01".ljust(32, "\x00") if index >= outputs.size outs = outputs[0...(index + 1)].map.with_index { |o, idx| (idx == index) ? o.to_payload : o.to_empty_payload }.join out_size = Bitcoin.pack_var_int(index + 1) end if hash_type & SIGHASH_TYPE[:anyonecanpay] != 0 ins = [ins[index]] end buf = [[version].pack('V'), Bitcoin.pack_var_int(ins.size), ins, out_size, outs, [lock_time, hash_type].pack('VV')].join Bitcoin.double_sha256(buf) end # generate sighash with BIP-143 format # https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki def sighash_for_witness(index, script_pubkey_or_script_code, hash_type, amount, skip_separator_index) hash_prevouts = Bitcoin.double_sha256(inputs.map{|i|i.out_point.to_payload}.join) hash_sequence = Bitcoin.double_sha256(inputs.map{|i|[i.sequence].pack('V')}.join) outpoint = inputs[index].out_point.to_payload amount = [amount].pack('Q') nsequence = [inputs[index].sequence].pack('V') hash_outputs = Bitcoin.double_sha256(outputs.map{|o|o.to_payload}.join) script_code = script_pubkey_or_script_code.to_script_code(skip_separator_index) case (hash_type & 0x1f) when SIGHASH_TYPE[:single] hash_outputs = index >= outputs.size ? "\x00".ljust(32, "\x00") : Bitcoin.double_sha256(outputs[index].to_payload) hash_sequence = "\x00".ljust(32, "\x00") when SIGHASH_TYPE[:none] hash_sequence = hash_outputs = "\x00".ljust(32, "\x00") end if (hash_type & SIGHASH_TYPE[:anyonecanpay]) != 0 hash_prevouts = hash_sequence ="\x00".ljust(32, "\x00") end hash_type |= (Bitcoin.chain_params.fork_id << 8) if Bitcoin.chain_params.fork_chain? buf = [ [version].pack('V'), hash_prevouts, hash_sequence, outpoint, script_code ,amount, nsequence, hash_outputs, [@lock_time, hash_type].pack('VV')].join Bitcoin.double_sha256(buf) end # verify input signature for legacy tx. def verify_input_sig_for_legacy(input_index, script_pubkey, flags) script_sig = inputs[input_index].script_sig checker = Bitcoin::TxChecker.new(tx: self, input_index: input_index) interpreter = Bitcoin::ScriptInterpreter.new(checker: checker, flags: flags) interpreter.verify_script(script_sig, script_pubkey) end # verify input signature for witness tx. def verify_input_sig_for_witness(input_index, script_pubkey, amount, flags) flags |= SCRIPT_VERIFY_WITNESS flags |= SCRIPT_VERIFY_WITNESS_PUBKEYTYPE checker = Bitcoin::TxChecker.new(tx: self, input_index: input_index, amount: amount) interpreter = Bitcoin::ScriptInterpreter.new(checker: checker, flags: flags) i = inputs[input_index] script_sig = i.script_sig witness = i.script_witness interpreter.verify_script(script_sig, script_pubkey, witness) end end
ynab/ynab-sdk-ruby
lib/ynab/api/transactions_api.rb
YNAB.TransactionsApi.create_transaction
ruby
def create_transaction(budget_id, data, opts = {}) data, _status_code, _headers = create_transaction_with_http_info(budget_id, data, opts) data end
Create a single transaction or multiple transactions Creates a single transaction or multiple transactions. If you provide a body containing a 'transaction' object, a single transaction will be created and if you provide a body containing a 'transactions' array, multiple transactions will be created. @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param data The transaction or transactions to create. To create a single transaction you can specify a value for the &#39;transaction&#39; object and to create multiple transactions you can specify an array of &#39;transactions&#39;. It is expected that you will only provide a value for one of these objects. @param [Hash] opts the optional parameters @return [SaveTransactionsResponse]
train
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/transactions_api.rb#L28-L31
class TransactionsApi attr_accessor :api_client def initialize(api_client = ApiClient.default) @api_client = api_client end # Create a single transaction or multiple transactions # Creates a single transaction or multiple transactions. If you provide a body containing a 'transaction' object, a single transaction will be created and if you provide a body containing a 'transactions' array, multiple transactions will be created. # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param data The transaction or transactions to create. To create a single transaction you can specify a value for the &#39;transaction&#39; object and to create multiple transactions you can specify an array of &#39;transactions&#39;. It is expected that you will only provide a value for one of these objects. # @param [Hash] opts the optional parameters # @return [SaveTransactionsResponse] # Create a single transaction or multiple transactions # Creates a single transaction or multiple transactions. If you provide a body containing a &#39;transaction&#39; object, a single transaction will be created and if you provide a body containing a &#39;transactions&#39; array, multiple transactions will be created. # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param data The transaction or transactions to create. To create a single transaction you can specify a value for the &#39;transaction&#39; object and to create multiple transactions you can specify an array of &#39;transactions&#39;. It is expected that you will only provide a value for one of these objects. # @param [Hash] opts the optional parameters # @return [Array<(SaveTransactionsResponse, Fixnum, Hash)>] SaveTransactionsResponse data, response status code and response headers def create_transaction_with_http_info(budget_id, data, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: TransactionsApi.create_transaction ...' end # verify the required parameter 'budget_id' is set if @api_client.config.client_side_validation && budget_id.nil? fail ArgumentError, "Missing the required parameter 'budget_id' when calling TransactionsApi.create_transaction" end # verify the required parameter 'data' is set if @api_client.config.client_side_validation && data.nil? fail ArgumentError, "Missing the required parameter 'data' when calling TransactionsApi.create_transaction" end # resource path local_var_path = '/budgets/{budget_id}/transactions'.sub('{' + 'budget_id' + '}', budget_id.to_s) # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(data) auth_names = ['bearer'] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'SaveTransactionsResponse') if @api_client.config.debugging @api_client.config.logger.debug "API called: TransactionsApi#create_transaction\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Single transaction # Returns a single transaction # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param transaction_id The id of the transaction # @param [Hash] opts the optional parameters # @return [TransactionResponse] def get_transaction_by_id(budget_id, transaction_id, opts = {}) data, _status_code, _headers = get_transaction_by_id_with_http_info(budget_id, transaction_id, opts) data end # Single transaction # Returns a single transaction # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param transaction_id The id of the transaction # @param [Hash] opts the optional parameters # @return [Array<(TransactionResponse, Fixnum, Hash)>] TransactionResponse data, response status code and response headers def get_transaction_by_id_with_http_info(budget_id, transaction_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: TransactionsApi.get_transaction_by_id ...' end # verify the required parameter 'budget_id' is set if @api_client.config.client_side_validation && budget_id.nil? fail ArgumentError, "Missing the required parameter 'budget_id' when calling TransactionsApi.get_transaction_by_id" end # verify the required parameter 'transaction_id' is set if @api_client.config.client_side_validation && transaction_id.nil? fail ArgumentError, "Missing the required parameter 'transaction_id' when calling TransactionsApi.get_transaction_by_id" end # resource path local_var_path = '/budgets/{budget_id}/transactions/{transaction_id}'.sub('{' + 'budget_id' + '}', budget_id.to_s).sub('{' + 'transaction_id' + '}', transaction_id.to_s) # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = ['bearer'] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'TransactionResponse') if @api_client.config.debugging @api_client.config.logger.debug "API called: TransactionsApi#get_transaction_by_id\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # List transactions # Returns budget transactions # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param [Hash] opts the optional parameters # @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). # @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. # @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. # @return [TransactionsResponse] def get_transactions(budget_id, opts = {}) data, _status_code, _headers = get_transactions_with_http_info(budget_id, opts) data end # List transactions # Returns budget transactions # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param [Hash] opts the optional parameters # @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). # @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. # @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. # @return [Array<(TransactionsResponse, Fixnum, Hash)>] TransactionsResponse data, response status code and response headers def get_transactions_with_http_info(budget_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: TransactionsApi.get_transactions ...' end # verify the required parameter 'budget_id' is set if @api_client.config.client_side_validation && budget_id.nil? fail ArgumentError, "Missing the required parameter 'budget_id' when calling TransactionsApi.get_transactions" end if @api_client.config.client_side_validation && opts[:'type'] && !['uncategorized', 'unapproved'].include?(opts[:'type']) fail ArgumentError, 'invalid value for "type", must be one of uncategorized, unapproved' end # resource path local_var_path = '/budgets/{budget_id}/transactions'.sub('{' + 'budget_id' + '}', budget_id.to_s) # query parameters query_params = {} query_params[:'since_date'] = opts[:'since_date'] if !opts[:'since_date'].nil? query_params[:'type'] = opts[:'type'] if !opts[:'type'].nil? query_params[:'last_knowledge_of_server'] = opts[:'last_knowledge_of_server'] if !opts[:'last_knowledge_of_server'].nil? # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = ['bearer'] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'TransactionsResponse') if @api_client.config.debugging @api_client.config.logger.debug "API called: TransactionsApi#get_transactions\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # List account transactions # Returns all transactions for a specified account # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param account_id The id of the account # @param [Hash] opts the optional parameters # @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). # @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. # @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. # @return [TransactionsResponse] def get_transactions_by_account(budget_id, account_id, opts = {}) data, _status_code, _headers = get_transactions_by_account_with_http_info(budget_id, account_id, opts) data end # List account transactions # Returns all transactions for a specified account # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param account_id The id of the account # @param [Hash] opts the optional parameters # @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). # @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. # @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. # @return [Array<(TransactionsResponse, Fixnum, Hash)>] TransactionsResponse data, response status code and response headers def get_transactions_by_account_with_http_info(budget_id, account_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: TransactionsApi.get_transactions_by_account ...' end # verify the required parameter 'budget_id' is set if @api_client.config.client_side_validation && budget_id.nil? fail ArgumentError, "Missing the required parameter 'budget_id' when calling TransactionsApi.get_transactions_by_account" end # verify the required parameter 'account_id' is set if @api_client.config.client_side_validation && account_id.nil? fail ArgumentError, "Missing the required parameter 'account_id' when calling TransactionsApi.get_transactions_by_account" end if @api_client.config.client_side_validation && opts[:'type'] && !['uncategorized', 'unapproved'].include?(opts[:'type']) fail ArgumentError, 'invalid value for "type", must be one of uncategorized, unapproved' end # resource path local_var_path = '/budgets/{budget_id}/accounts/{account_id}/transactions'.sub('{' + 'budget_id' + '}', budget_id.to_s).sub('{' + 'account_id' + '}', account_id.to_s) # query parameters query_params = {} query_params[:'since_date'] = opts[:'since_date'] if !opts[:'since_date'].nil? query_params[:'type'] = opts[:'type'] if !opts[:'type'].nil? query_params[:'last_knowledge_of_server'] = opts[:'last_knowledge_of_server'] if !opts[:'last_knowledge_of_server'].nil? # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = ['bearer'] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'TransactionsResponse') if @api_client.config.debugging @api_client.config.logger.debug "API called: TransactionsApi#get_transactions_by_account\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # List category transactions # Returns all transactions for a specified category # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param category_id The id of the category # @param [Hash] opts the optional parameters # @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). # @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. # @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. # @return [HybridTransactionsResponse] def get_transactions_by_category(budget_id, category_id, opts = {}) data, _status_code, _headers = get_transactions_by_category_with_http_info(budget_id, category_id, opts) data end # List category transactions # Returns all transactions for a specified category # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param category_id The id of the category # @param [Hash] opts the optional parameters # @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). # @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. # @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. # @return [Array<(HybridTransactionsResponse, Fixnum, Hash)>] HybridTransactionsResponse data, response status code and response headers def get_transactions_by_category_with_http_info(budget_id, category_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: TransactionsApi.get_transactions_by_category ...' end # verify the required parameter 'budget_id' is set if @api_client.config.client_side_validation && budget_id.nil? fail ArgumentError, "Missing the required parameter 'budget_id' when calling TransactionsApi.get_transactions_by_category" end # verify the required parameter 'category_id' is set if @api_client.config.client_side_validation && category_id.nil? fail ArgumentError, "Missing the required parameter 'category_id' when calling TransactionsApi.get_transactions_by_category" end if @api_client.config.client_side_validation && opts[:'type'] && !['uncategorized', 'unapproved'].include?(opts[:'type']) fail ArgumentError, 'invalid value for "type", must be one of uncategorized, unapproved' end # resource path local_var_path = '/budgets/{budget_id}/categories/{category_id}/transactions'.sub('{' + 'budget_id' + '}', budget_id.to_s).sub('{' + 'category_id' + '}', category_id.to_s) # query parameters query_params = {} query_params[:'since_date'] = opts[:'since_date'] if !opts[:'since_date'].nil? query_params[:'type'] = opts[:'type'] if !opts[:'type'].nil? query_params[:'last_knowledge_of_server'] = opts[:'last_knowledge_of_server'] if !opts[:'last_knowledge_of_server'].nil? # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = ['bearer'] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'HybridTransactionsResponse') if @api_client.config.debugging @api_client.config.logger.debug "API called: TransactionsApi#get_transactions_by_category\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # List payee transactions # Returns all transactions for a specified payee # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param payee_id The id of the payee # @param [Hash] opts the optional parameters # @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). # @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. # @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. # @return [HybridTransactionsResponse] def get_transactions_by_payee(budget_id, payee_id, opts = {}) data, _status_code, _headers = get_transactions_by_payee_with_http_info(budget_id, payee_id, opts) data end # List payee transactions # Returns all transactions for a specified payee # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param payee_id The id of the payee # @param [Hash] opts the optional parameters # @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). # @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. # @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. # @return [Array<(HybridTransactionsResponse, Fixnum, Hash)>] HybridTransactionsResponse data, response status code and response headers def get_transactions_by_payee_with_http_info(budget_id, payee_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: TransactionsApi.get_transactions_by_payee ...' end # verify the required parameter 'budget_id' is set if @api_client.config.client_side_validation && budget_id.nil? fail ArgumentError, "Missing the required parameter 'budget_id' when calling TransactionsApi.get_transactions_by_payee" end # verify the required parameter 'payee_id' is set if @api_client.config.client_side_validation && payee_id.nil? fail ArgumentError, "Missing the required parameter 'payee_id' when calling TransactionsApi.get_transactions_by_payee" end if @api_client.config.client_side_validation && opts[:'type'] && !['uncategorized', 'unapproved'].include?(opts[:'type']) fail ArgumentError, 'invalid value for "type", must be one of uncategorized, unapproved' end # resource path local_var_path = '/budgets/{budget_id}/payees/{payee_id}/transactions'.sub('{' + 'budget_id' + '}', budget_id.to_s).sub('{' + 'payee_id' + '}', payee_id.to_s) # query parameters query_params = {} query_params[:'since_date'] = opts[:'since_date'] if !opts[:'since_date'].nil? query_params[:'type'] = opts[:'type'] if !opts[:'type'].nil? query_params[:'last_knowledge_of_server'] = opts[:'last_knowledge_of_server'] if !opts[:'last_knowledge_of_server'].nil? # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = ['bearer'] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'HybridTransactionsResponse') if @api_client.config.debugging @api_client.config.logger.debug "API called: TransactionsApi#get_transactions_by_payee\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Updates an existing transaction # Updates a transaction # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param transaction_id The id of the transaction # @param data The transaction to update # @param [Hash] opts the optional parameters # @return [TransactionResponse] def update_transaction(budget_id, transaction_id, data, opts = {}) data, _status_code, _headers = update_transaction_with_http_info(budget_id, transaction_id, data, opts) data end # Updates an existing transaction # Updates a transaction # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param transaction_id The id of the transaction # @param data The transaction to update # @param [Hash] opts the optional parameters # @return [Array<(TransactionResponse, Fixnum, Hash)>] TransactionResponse data, response status code and response headers def update_transaction_with_http_info(budget_id, transaction_id, data, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: TransactionsApi.update_transaction ...' end # verify the required parameter 'budget_id' is set if @api_client.config.client_side_validation && budget_id.nil? fail ArgumentError, "Missing the required parameter 'budget_id' when calling TransactionsApi.update_transaction" end # verify the required parameter 'transaction_id' is set if @api_client.config.client_side_validation && transaction_id.nil? fail ArgumentError, "Missing the required parameter 'transaction_id' when calling TransactionsApi.update_transaction" end # verify the required parameter 'data' is set if @api_client.config.client_side_validation && data.nil? fail ArgumentError, "Missing the required parameter 'data' when calling TransactionsApi.update_transaction" end # resource path local_var_path = '/budgets/{budget_id}/transactions/{transaction_id}'.sub('{' + 'budget_id' + '}', budget_id.to_s).sub('{' + 'transaction_id' + '}', transaction_id.to_s) # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(data) auth_names = ['bearer'] data, status_code, headers = @api_client.call_api(:PUT, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'TransactionResponse') if @api_client.config.debugging @api_client.config.logger.debug "API called: TransactionsApi#update_transaction\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Update multiple transactions # Updates multiple transactions, by 'id' or 'import_id'. # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param data The transactions to update. Optionally, transaction &#39;id&#39; value(s) can be specified as null and an &#39;import_id&#39; value can be provided which will allow transaction(s) to updated by their import_id. # @param [Hash] opts the optional parameters # @return [SaveTransactionsResponse] def update_transactions(budget_id, data, opts = {}) data, _status_code, _headers = update_transactions_with_http_info(budget_id, data, opts) data end # Update multiple transactions # Updates multiple transactions, by &#39;id&#39; or &#39;import_id&#39;. # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param data The transactions to update. Optionally, transaction &#39;id&#39; value(s) can be specified as null and an &#39;import_id&#39; value can be provided which will allow transaction(s) to updated by their import_id. # @param [Hash] opts the optional parameters # @return [Array<(SaveTransactionsResponse, Fixnum, Hash)>] SaveTransactionsResponse data, response status code and response headers def update_transactions_with_http_info(budget_id, data, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: TransactionsApi.update_transactions ...' end # verify the required parameter 'budget_id' is set if @api_client.config.client_side_validation && budget_id.nil? fail ArgumentError, "Missing the required parameter 'budget_id' when calling TransactionsApi.update_transactions" end # verify the required parameter 'data' is set if @api_client.config.client_side_validation && data.nil? fail ArgumentError, "Missing the required parameter 'data' when calling TransactionsApi.update_transactions" end # resource path local_var_path = '/budgets/{budget_id}/transactions'.sub('{' + 'budget_id' + '}', budget_id.to_s) # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(data) auth_names = ['bearer'] data, status_code, headers = @api_client.call_api(:PATCH, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'SaveTransactionsResponse') if @api_client.config.debugging @api_client.config.logger.debug "API called: TransactionsApi#update_transactions\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end end
mongodb/mongo-ruby-driver
lib/mongo/uri.rb
Mongo.URI.inverse_bool
ruby
def inverse_bool(name, value) b = convert_bool(name, value) if b.nil? nil else !b end end
Parses a boolean value and returns its inverse. @param value [ String ] The URI option value. @return [ true | false | nil ] The inverse of the boolean value parsed out, otherwise nil (and a warning will be logged).
train
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/uri.rb#L872-L880
class URI include Loggable # The uri parser object options. # # @since 2.0.0 attr_reader :options # The options specified in the uri. # # @since 2.1.0 attr_reader :uri_options # The servers specified in the uri. # # @since 2.0.0 attr_reader :servers # The mongodb connection string scheme. # # @deprecated Will be removed in 3.0. # # @since 2.0.0 SCHEME = 'mongodb://'.freeze # The mongodb connection string scheme root. # # @since 2.5.0 MONGODB_SCHEME = 'mongodb'.freeze # The mongodb srv protocol connection string scheme root. # # @since 2.5.0 MONGODB_SRV_SCHEME = 'mongodb+srv'.freeze # Error details for an invalid scheme. # # @since 2.1.0 INVALID_SCHEME = "Invalid scheme. Scheme must be '#{MONGODB_SCHEME}' or '#{MONGODB_SRV_SCHEME}'".freeze # MongoDB URI format specification. # # @since 2.0.0 FORMAT = 'mongodb://[username:password@]host1[:port1][,host2[:port2]' + ',...[,hostN[:portN]]][/[database][?options]]'.freeze # MongoDB URI (connection string) documentation url # # @since 2.0.0 HELP = 'http://docs.mongodb.org/manual/reference/connection-string/'.freeze # Unsafe characters that must be urlencoded. # # @since 2.1.0 UNSAFE = /[\:\/\+\@]/ # Percent sign that must be encoded in user creds. # # @since 2.5.1 PERCENT_CHAR = /\%/ # Unix socket suffix. # # @since 2.1.0 UNIX_SOCKET = /.sock/ # The character delimiting hosts. # # @since 2.1.0 HOST_DELIM = ','.freeze # The character separating a host and port. # # @since 2.1.0 HOST_PORT_DELIM = ':'.freeze # The character delimiting a database. # # @since 2.1.0 DATABASE_DELIM = '/'.freeze # The character delimiting options. # # @since 2.1.0 URI_OPTS_DELIM = '?'.freeze # The character delimiting multiple options. # # @since 2.1.0 INDIV_URI_OPTS_DELIM = '&'.freeze # The character delimiting an option and its value. # # @since 2.1.0 URI_OPTS_VALUE_DELIM = '='.freeze # The character separating a username from the password. # # @since 2.1.0 AUTH_USER_PWD_DELIM = ':'.freeze # The character delimiting auth credentials. # # @since 2.1.0 AUTH_DELIM = '@'.freeze # Scheme delimiter. # # @since 2.5.0 SCHEME_DELIM = '://'.freeze # Error details for an invalid options format. # # @since 2.1.0 INVALID_OPTS_VALUE_DELIM = "Options and their values must be delimited" + " by '#{URI_OPTS_VALUE_DELIM}'".freeze # Error details for an non-urlencoded user name or password. # # @since 2.1.0 UNESCAPED_USER_PWD = "User name and password must be urlencoded.".freeze # Error details for a non-urlencoded unix socket path. # # @since 2.1.0 UNESCAPED_UNIX_SOCKET = "UNIX domain sockets must be urlencoded.".freeze # Error details for a non-urlencoded auth database name. # # @since 2.1.0 UNESCAPED_DATABASE = "Auth database must be urlencoded.".freeze # Error details for providing options without a database delimiter. # # @since 2.1.0 INVALID_OPTS_DELIM = "Database delimiter '#{DATABASE_DELIM}' must be present if options are specified.".freeze # Error details for a missing host. # # @since 2.1.0 INVALID_HOST = "Missing host; at least one must be provided.".freeze # Error details for an invalid port. # # @since 2.1.0 INVALID_PORT = "Invalid port. Port must be an integer greater than 0 and less than 65536".freeze # Map of URI read preference modes to Ruby driver read preference modes # # @since 2.0.0 READ_MODE_MAP = { 'primary' => :primary, 'primarypreferred' => :primary_preferred, 'secondary' => :secondary, 'secondarypreferred' => :secondary_preferred, 'nearest' => :nearest }.freeze # Map of URI authentication mechanisms to Ruby driver mechanisms # # @since 2.0.0 AUTH_MECH_MAP = { 'PLAIN' => :plain, # MONGODB-CR is deprecated and will be removed in driver version 3.0 'MONGODB-CR' => :mongodb_cr, 'GSSAPI' => :gssapi, 'MONGODB-X509' => :mongodb_x509, 'SCRAM-SHA-1' => :scram, 'SCRAM-SHA-256' => :scram256 }.freeze # Options that are allowed to appear more than once in the uri. # # In order to follow the URI options spec requirement that all instances of 'tls' and 'ssl' have # the same value, we need to keep track of all of the values passed in for those options. # Assuming they don't conflict, they will be condensed to a single value immediately after # parsing the URI. # # @since 2.1.0 REPEATABLE_OPTIONS = [ :tag_sets, :ssl ] # Get either a URI object or a SRVProtocol URI object. # # @example Get the uri object. # URI.get(string) # # @return [URI, URI::SRVProtocol] The uri object. # # @since 2.5.0 def self.get(string, opts = {}) scheme, _, remaining = string.partition(SCHEME_DELIM) case scheme when MONGODB_SCHEME URI.new(string, opts) when MONGODB_SRV_SCHEME SRVProtocol.new(string, opts) else raise Error::InvalidURI.new(string, INVALID_SCHEME) end end # Gets the options hash that needs to be passed to a Mongo::Client on # instantiation, so we don't have to merge the credentials and database in # at that point - we only have a single point here. # # @example Get the client options. # uri.client_options # # @return [ Hash ] The options passed to the Mongo::Client # # @since 2.0.0 def client_options opts = uri_options.merge(:database => database) @user ? opts.merge(credentials) : opts end # Create the new uri from the provided string. # # @example Create the new URI. # URI.new('mongodb://localhost:27017') # # @param [ String ] string The uri string. # @param [ Hash ] options The options. # # @raise [ Error::InvalidURI ] If the uri does not match the spec. # # @since 2.0.0 def initialize(string, options = {}) @string = string @options = options parsed_scheme, _, remaining = string.partition(SCHEME_DELIM) raise_invalid_error!(INVALID_SCHEME) unless parsed_scheme == scheme if remaining.empty? raise_invalid_error!('No hosts in the URI') end parse!(remaining) # The URI options spec requires that we raise an error if there are conflicting values of # 'tls' and 'ssl'. In order to fulfill this, we parse the values of each instance into an # array; assuming all values in the array are the same, we replace the array with that value. unless @uri_options[:ssl].nil? || @uri_options[:ssl].empty? unless @uri_options[:ssl].uniq.length == 1 raise_invalid_error_no_fmt!("all instances of 'tls' and 'ssl' must have the same value") end @uri_options[:ssl] = @uri_options[:ssl].first end # Check for conflicting TLS insecure options. unless @uri_options[:ssl_verify].nil? unless @uri_options[:ssl_verify_certificate].nil? raise_invalid_error_no_fmt!("'tlsInsecure' and 'tlsAllowInvalidCertificates' cannot both be specified") end unless @uri_options[:ssl_verify_hostname].nil? raise_invalid_error_no_fmt!("tlsInsecure' and 'tlsAllowInvalidHostnames' cannot both be specified") end end # Since we know that the only URI option that sets :ssl_cert is "tlsCertificateKeyFile", any # value set for :ssl_cert must also be set for :ssl_key. if @uri_options[:ssl_cert] @uri_options[:ssl_key] = @uri_options[:ssl_cert] end end # Get the credentials provided in the URI. # # @example Get the credentials. # uri.credentials # # @return [ Hash ] The credentials. # * :user [ String ] The user. # * :password [ String ] The provided password. # # @since 2.0.0 def credentials { :user => @user, :password => @password } end # Get the database provided in the URI. # # @example Get the database. # uri.database # # @return [String] The database. # # @since 2.0.0 def database @database ? @database : Database::ADMIN end private def scheme MONGODB_SCHEME end def parse!(remaining) hosts_and_db, options = remaining.split('?', 2) if options && options.index('?') raise_invalid_error!("Options contain an unescaped question mark (?), or the database name contains a question mark and was not escaped") end if options && !hosts_and_db.index('/') raise_invalid_error!("MongoDB URI must have a slash (/) after the hosts if options are given") end hosts, db = hosts_and_db.split('/', 2) if db && db.index('/') raise_invalid_error!("Database name contains an unescaped slash (/): #{db}") end if hosts.index('@') creds, hosts = hosts.split('@', 2) if hosts.empty? raise_invalid_error!("Empty hosts list") end if hosts.index('@') raise_invalid_error!("Unescaped @ in auth info") end end @servers = parse_servers!(hosts) @user = parse_user!(creds) @password = parse_password!(creds) @uri_options = Options::Redacted.new(parse_uri_options!(options)) if db @database = parse_database!(db) end end def extract_db_opts!(string) db_opts, _, creds_hosts = string.reverse.partition(DATABASE_DELIM) db_opts, creds_hosts = creds_hosts, db_opts if creds_hosts.empty? if db_opts.empty? && creds_hosts.include?(URI_OPTS_DELIM) raise_invalid_error!(INVALID_OPTS_DELIM) end [ creds_hosts, db_opts ].map { |s| s.reverse } end def parse_uri_options!(string) return {} unless string string.split(INDIV_URI_OPTS_DELIM).reduce({}) do |uri_options, opt| key, value = opt.split('=', 2) if value.nil? raise_invalid_error!("Option #{key} has no value") end if value.index('=') raise_invalid_error!("Value for option #{key} contains the key/value delimiter (=): #{value}") end key = ::URI.decode(key) strategy = URI_OPTION_MAP[key.downcase] if strategy.nil? log_warn("Unsupported URI option '#{key}' on URI '#{@string}'. It will be ignored.") else value = ::URI.decode(value) add_uri_option(key, strategy, value, uri_options) end uri_options end end def parse_user!(string) if (string && user = string.partition(AUTH_USER_PWD_DELIM)[0]) if user.length > 0 raise_invalid_error!(UNESCAPED_USER_PWD) if user =~ UNSAFE user_decoded = decode(user) if user_decoded =~ PERCENT_CHAR && encode(user_decoded) != user raise_invalid_error!(UNESCAPED_USER_PWD) end user_decoded end end end def parse_password!(string) if (string && pwd = string.partition(AUTH_USER_PWD_DELIM)[2]) if pwd.length > 0 raise_invalid_error!(UNESCAPED_USER_PWD) if pwd =~ UNSAFE pwd_decoded = decode(pwd) if pwd_decoded =~ PERCENT_CHAR && encode(pwd_decoded) != pwd raise_invalid_error!(UNESCAPED_USER_PWD) end pwd_decoded end end end def parse_database!(string) raise_invalid_error!(UNESCAPED_DATABASE) if string =~ UNSAFE decode(string) if string.length > 0 end def validate_port_string!(port) unless port.nil? || (port.length > 0 && port.to_i > 0 && port.to_i <= 65535) raise_invalid_error!(INVALID_PORT) end end def parse_servers!(string) raise_invalid_error!(INVALID_HOST) unless string.size > 0 string.split(HOST_DELIM).reduce([]) do |servers, host| if host[0] == '[' if host.index(']:') h, p = host.split(']:') validate_port_string!(p) end elsif host.index(HOST_PORT_DELIM) h, _, p = host.partition(HOST_PORT_DELIM) raise_invalid_error!(INVALID_HOST) unless h.size > 0 validate_port_string!(p) elsif host =~ UNIX_SOCKET raise_invalid_error!(UNESCAPED_UNIX_SOCKET) if host =~ UNSAFE host = decode(host) end servers << host end end def raise_invalid_error!(details) raise Error::InvalidURI.new(@string, details, FORMAT) end def raise_invalid_error_no_fmt!(details) raise Error::InvalidURI.new(@string, details) end def decode(value) ::URI.decode(value) end def encode(value) ::URI.encode(value) end # Hash for storing map of URI option parameters to conversion strategies URI_OPTION_MAP = {} # Simple internal dsl to register a MongoDB URI option in the URI_OPTION_MAP. # # @param uri_key [String] The MongoDB URI option to register. # @param name [Symbol] The name of the option in the driver. # @param extra [Hash] Extra options. # * :group [Symbol] Nested hash where option will go. # * :type [Symbol] Name of function to transform value. def self.uri_option(uri_key, name, extra = {}) URI_OPTION_MAP[uri_key] = { :name => name }.merge(extra) end # Replica Set Options uri_option 'replicaset', :replica_set, :type => :replica_set # Timeout Options uri_option 'connecttimeoutms', :connect_timeout, :type => :connect_timeout uri_option 'sockettimeoutms', :socket_timeout, :type => :socket_timeout uri_option 'serverselectiontimeoutms', :server_selection_timeout, :type => :server_selection_timeout uri_option 'localthresholdms', :local_threshold, :type => :local_threshold uri_option 'heartbeatfrequencyms', :heartbeat_frequency, :type => :heartbeat_frequency uri_option 'maxidletimems', :max_idle_time, :type => :max_idle_time # Write Options uri_option 'w', :w, :group => :write, type: :w uri_option 'journal', :j, :group => :write, :type => :journal uri_option 'fsync', :fsync, :group => :write, type: :bool uri_option 'wtimeoutms', :wtimeout, :group => :write, :type => :wtimeout # Read Options uri_option 'readpreference', :mode, :group => :read, :type => :read_mode uri_option 'readpreferencetags', :tag_sets, :group => :read, :type => :read_tags uri_option 'maxstalenessseconds', :max_staleness, :group => :read, :type => :max_staleness # Pool options uri_option 'minpoolsize', :min_pool_size, :type => :min_pool_size uri_option 'maxpoolsize', :max_pool_size, :type => :max_pool_size uri_option 'waitqueuetimeoutms', :wait_queue_timeout, :type => :wait_queue_timeout # Security Options uri_option 'ssl', :ssl, :type => :ssl uri_option 'tls', :ssl, :type => :tls uri_option 'tlsallowinvalidcertificates', :ssl_verify_certificate, :type => :ssl_verify_certificate uri_option 'tlsallowinvalidhostnames', :ssl_verify_hostname, :type => :ssl_verify_hostname uri_option 'tlscafile', :ssl_ca_cert uri_option 'tlscertificatekeyfile', :ssl_cert uri_option 'tlscertificatekeyfilepassword', :ssl_key_pass_phrase uri_option 'tlsinsecure', :ssl_verify, :type => :ssl_verify # Topology options uri_option 'connect', :connect, type: :symbol # Auth Options uri_option 'authsource', :auth_source, :type => :auth_source uri_option 'authmechanism', :auth_mech, :type => :auth_mech uri_option 'authmechanismproperties', :auth_mech_properties, :type => :auth_mech_props # Client Options uri_option 'appname', :app_name uri_option 'compressors', :compressors, :type => :array uri_option 'readconcernlevel', :level, group: :read_concern uri_option 'retrywrites', :retry_writes, :type => :retry_writes uri_option 'zlibcompressionlevel', :zlib_compression_level, :type => :zlib_compression_level # Applies URI value transformation by either using the default cast # or a transformation appropriate for the given type. # # @param key [String] URI option name. # @param value [String] The value to be transformed. # @param type [Symbol] The transform method. def apply_transform(key, value, type) if type if respond_to?("convert_#{type}", true) send("convert_#{type}", key, value) else send(type, value) end else value end end # Selects the output destination for an option. # # @param [Hash] uri_options The base target. # @param [Symbol] group Group subtarget. # # @return [Hash] The target for the option. def select_target(uri_options, group = nil) if group uri_options[group] ||= {} else uri_options end end # Merges a new option into the target. # # If the option exists at the target destination the merge will # be an addition. # # Specifically required to append an additional tag set # to the array of tag sets without overwriting the original. # # @param target [Hash] The destination. # @param value [Object] The value to be merged. # @param name [Symbol] The name of the option. def merge_uri_option(target, value, name) if target.key?(name) if REPEATABLE_OPTIONS.include?(name) target[name] += value else log_warn("Repeated option key: #{name}.") end else target.merge!(name => value) end end # Adds an option to the uri options hash via the supplied strategy. # # Acquires a target for the option based on group. # Transforms the value. # Merges the option into the target. # # @param key [String] URI option name. # @param strategy [Symbol] The strategy for this option. # @param value [String] The value of the option. # @param uri_options [Hash] The base option target. def add_uri_option(key, strategy, value, uri_options) target = select_target(uri_options, strategy[:group]) value = apply_transform(key, value, strategy[:type]) merge_uri_option(target, value, strategy[:name]) end # Replica set transformation, avoid converting to Symbol. # # @param value [String] Replica set name. # # @return [String] Same value to avoid cast to Symbol. def replica_set(value) decode(value) end # Auth source transformation, either db string or :external. # # @param value [String] Authentication source. # # @return [String] If auth source is database name. # @return [:external] If auth source is external authentication. def auth_source(value) value == '$external' ? :external : decode(value) end # Authentication mechanism transformation. # # @param value [String] The authentication mechanism. # # @return [Symbol] The transformed authentication mechanism. def auth_mech(value) AUTH_MECH_MAP[value.upcase].tap do |mech| log_warn("#{value} is not a valid auth mechanism") unless mech end end # Read preference mode transformation. # # @param value [String] The read mode string value. # # @return [Symbol] The read mode symbol. def read_mode(value) READ_MODE_MAP[value.downcase] end # Read preference tags transformation. # # @param value [String] The string representing tag set. # # @return [Array<Hash>] Array with tag set. def read_tags(value) [read_set(value)] end # Read preference tag set extractor. # # @param value [String] The tag set string. # # @return [Hash] The tag set hash. def read_set(value) hash_extractor('readPreferenceTags', value) end # Auth mechanism properties extractor. # # @param value [ String ] The auth mechanism properties string. # # @return [ Hash ] The auth mechanism properties hash. def auth_mech_props(value) properties = hash_extractor('authMechanismProperties', value) if properties[:canonicalize_host_name] properties.merge!(canonicalize_host_name: %w(true TRUE).include?(properties[:canonicalize_host_name])) end properties end # Parses the zlib compression level. # # @param value [ String ] The zlib compression level string. # # @return [ Integer | nil ] The compression level value if it is between -1 and 9 (inclusive), # otherwise nil (and a warning will be logged). def zlib_compression_level(value) if /\A-?\d+\z/ =~ value i = value.to_i if i >= -1 && i <= 9 return i end end log_warn("#{value} is not a valid zlibCompressionLevel") nil end # Parses the max pool size. # # @param value [ String ] The max pool size string. # # @return [ Integer | nil ] The min pool size if it is valid, otherwise nil (and a warning will) # be logged. def max_pool_size(value) if /\A\d+\z/ =~ value return value.to_i end log_warn("#{value} is not a valid maxPoolSize") nil end # Parses the min pool size. # # @param value [ String ] The min pool size string. # # @return [ Integer | nil ] The min pool size if it is valid, otherwise nil (and a warning will # be logged). def min_pool_size(value) if /\A\d+\z/ =~ value return value.to_i end log_warn("#{value} is not a valid minPoolSize") nil end # Parses the journal value. # # @param value [ String ] The journal value. # # @return [ true | false | nil ] The journal value parsed out, otherwise nil (and a warning # will be logged). def journal(value) convert_bool('journal', value) end # Parses the ssl value from the URI. # # @param value [ String ] The ssl value. # # @return [ Array<true | false> ] The ssl value parsed out (stored in an array to facilitate # keeping track of all values). def ssl(value) [convert_bool('ssl', value)] end # Parses the tls value from the URI. # # @param value [ String ] The tls value. # # @return [ Array<true | false> ] The tls value parsed out (stored in an array to facilitate # keeping track of all values). def tls(value) [convert_bool('tls', value)] end # Parses the ssl_verify value from the tlsInsecure URI value. Note that this will be the inverse # of the value of tlsInsecure (if present). # # @param value [ String ] The tlsInsecure value. # # @return [ true | false | nil ] The ssl_verify value parsed out, otherwise nil (and a warning # will be logged). def ssl_verify(value) inverse_bool('tlsAllowInvalidCertificates', value) end # Parses the ssl_verify_certificate value from the tlsAllowInvalidCertificates URI value. Note # that this will be the inverse of the value of tlsInsecure (if present). # # @param value [ String ] The tlsAllowInvalidCertificates value. # # @return [ true | false | nil ] The ssl_verify_certificate value parsed out, otherwise nil # (and a warning will be logged). def ssl_verify_certificate(value) inverse_bool('tlsAllowInvalidCertificates', value) end # Parses the ssl_verify_hostname value from the tlsAllowInvalidHostnames URI value. Note that # this will be the inverse of the value of tlsAllowInvalidHostnames (if present). # # @param value [ String ] The tlsAllowInvalidHostnames value. # # @return [ true | false | nil ] The ssl_verify_hostname value parsed out, otherwise nil # (and a warning will be logged). def ssl_verify_hostname(value) inverse_bool('tlsAllowInvalidHostnames', value) end # Parses the retryWrites value. # # @param value [ String ] The retryWrites value. # # @return [ true | false | nil ] The boolean value parsed out, otherwise nil (and a warning # will be logged). def retry_writes(value) convert_bool('retryWrites', value) end # Converts +value+ into an integer. # # If the value is not a valid integer, warns and returns nil. # # @param name [ String ] Name of the URI option being processed. # @param value [ String ] URI option value. # # @return [ nil | Integer ] Converted value. def convert_integer(name, value) unless /\A\d+\z/ =~ value log_warn("#{value} is not a valid integer for #{name}") return nil end value.to_i end # Converts +value+ into a symbol. # # @param name [ String ] Name of the URI option being processed. # @param value [ String ] URI option value. # # @return [ Symbol ] Converted value. def convert_symbol(name, value) value.to_sym end # Converts +value+ as a write concern. # # If +value+ is the word "majority", returns the symbol :majority. # If +value+ is a number, returns the number as an integer. # Otherwise returns the string +value+ unchanged. # # @param name [ String ] Name of the URI option being processed. # @param value [ String ] URI option value. # # @return [ Integer | Symbol | String ] Converted value. def convert_w(name, value) case value when 'majority' :majority when /\A[0-9]+\z/ value.to_i else value end end # Converts +value+ to a boolean. # # Returns true for 'true', false for 'false', otherwise nil. # # @param name [ String ] Name of the URI option being processed. # @param value [ String ] URI option value. # # @return [ true | false | nil ] Converted value. def convert_bool(name, value) case value when "true", 'TRUE' true when "false", 'FALSE' false else log_warn("invalid boolean option for #{name}: #{value}") nil end end # Parses a boolean value and returns its inverse. # # @param value [ String ] The URI option value. # # @return [ true | false | nil ] The inverse of the boolean value parsed out, otherwise nil # (and a warning will be logged). # Parses the max staleness value, which must be either "0" or an integer greater or equal to 90. # # @param value [ String ] The max staleness string. # # @return [ Integer | nil ] The max staleness integer parsed out if it is valid, otherwise nil # (and a warning will be logged). def max_staleness(value) if /\A\d+\z/ =~ value int = value.to_i if int >= 0 && int < 90 log_warn("max staleness must be either 0 or greater than 90: #{value}") end return int end log_warn("Invalid max staleness value: #{value}") nil end # Parses the connectTimeoutMS value. # # @param value [ String ] The connectTimeoutMS value. # # @return [ Integer | nil ] The integer parsed out, otherwise nil (and a warning will be # logged). def connect_timeout(value) ms_convert('connectTimeoutMS', value) end # Parses the localThresholdMS value. # # @param value [ String ] The localThresholdMS value. # # @return [ Integer | nil ] The integer parsed out, otherwise nil (and a warning will be # logged). def local_threshold(value) ms_convert('localThresholdMS', value) end # Parses the heartbeatFrequencyMS value. # # @param value [ String ] The heartbeatFrequencyMS value. # # @return [ Integer | nil ] The integer parsed out, otherwise nil (and a warning will be # logged). def heartbeat_frequency(value) ms_convert('heartbeatFrequencyMS', value) end # Parses the maxIdleTimeMS value. # # @param value [ String ] The maxIdleTimeMS value. # # @return [ Integer | nil ] The integer parsed out, otherwise nil (and a warning will be # logged). def max_idle_time(value) ms_convert('maxIdleTimeMS', value) end # Parses the serverSelectionMS value. # # @param value [ String ] The serverSelectionMS value. # # @return [ Integer | nil ] The integer parsed out, otherwise nil (and a warning will be # logged). def server_selection_timeout(value) ms_convert('serverSelectionTimeoutMS', value) end # Parses the socketTimeoutMS value. # # @param value [ String ] The socketTimeoutMS value. # # @return [ Integer | nil ] The integer parsed out, otherwise nil (and a warning will be # logged). def socket_timeout(value) ms_convert('socketTimeoutMS', value) end # Parses the waitQueueTimeoutMS value. # # @param value [ String ] The waitQueueTimeoutMS value. # # @return [ Integer | nil ] The integer parsed out, otherwise nil (and a warning will be # logged). def wait_queue_timeout(value) ms_convert('MS', value) end # Parses the wtimeoutMS value. # # @param value [ String ] The wtimeoutMS value. # # @return [ Integer | nil ] The integer parsed out, otherwise nil (and a warning will be # logged). def wtimeout(value) unless /\A\d+\z/ =~ value log_warn("Invalid wtimeoutMS value: #{value}") return nil end value.to_i end # Ruby's convention is to provide timeouts in seconds, not milliseconds and # to use fractions where more precision is necessary. The connection string # options are always in MS so we provide an easy conversion type. # # @param [ Integer ] value The millisecond value. # # @return [ Float ] The seconds value. # # @since 2.0.0 def ms_convert(name, value) unless /\A-?\d+(\.\d+)?\z/ =~ value log_warn("Invalid ms value for #{name}: #{value}") return nil end if value[0] == '-' log_warn("#{name} cannot be a negative number") return nil end value.to_f / 1000 end # Extract values from the string and put them into a nested hash. # # @param value [ String ] The string to build a hash from. # # @return [ Hash ] The hash built from the string. def hash_extractor(name, value) value.split(',').reduce({}) do |set, tag| k, v = tag.split(':') if v.nil? log_warn("Invalid hash value for #{name}: #{value}") return nil end set.merge(decode(k).downcase.to_sym => decode(v)) end end # Extract values from the string and put them into an array. # # @param [ String ] value The string to build an array from. # # @return [ Array ] The array built from the string. def array(value) value.split(',') end end
rjoberon/bibsonomy-ruby
lib/bibsonomy/api.rb
BibSonomy.API.get_posts_for_group
ruby
def get_posts_for_group(group_name, resource_type, tags = nil, start = 0, endc = $MAX_POSTS_PER_REQUEST) return get_posts("group", group_name, resource_type, tags, start, endc) end
Get the posts of the users of a group, optionally filtered by tags. @param group_name [String] the name of the group @param resource_type [String] the type of the post. Currently supported are 'bookmark' and 'publication'. @param tags [Array<String>] the tags that all posts must contain (can be empty) @param start [Integer] number of first post to download @param endc [Integer] number of last post to download @return [Array<BibSonomy::Post>, String] the requested posts
train
https://github.com/rjoberon/bibsonomy-ruby/blob/15afed3f32e434d28576ac62ecf3cfd8a392e055/lib/bibsonomy/api.rb#L114-L116
class API # Initializes the client with the given credentials. # # @param user_name [String] the name of the user account used for accessing the API # @param api_key [String] the API key corresponding to the user account - can be obtained from http://www.bibsonomy.org/settings?selTab=1 # # @param format [String] The requested return format. One of: # 'xml', 'json', 'ruby', 'csl', 'bibtex'. The default is 'ruby' # which returns Ruby objects defined by this library. Currently, # 'csl' and 'bibtex' are only available for publications. # def initialize(user_name, api_key, format = 'ruby') # configure output format if format == 'ruby' @format = 'json' @parse = true else @format = format @parse = false end @conn = Faraday.new(:url => $API_URL) do |faraday| faraday.request :url_encoded # form-encode POST params #faraday.response :logger faraday.adapter Faraday.default_adapter # make requests with # Net::HTTP end @conn.basic_auth(user_name, api_key) # initialise URLs @url_post = Addressable::Template.new("/api/users/{user_name}/posts/{intra_hash}?format={format}") @url_posts = Addressable::Template.new("/api/posts{?format,resourcetype,start,end,user,group,tags}") @url_doc = Addressable::Template.new("/api/users/{user_name}/posts/{intra_hash}/documents/{file_name}") end # # Get a single post # # @param user_name [String] the name of the post's owner # @param intra_hash [String] the intrag hash of the post # @return [BibSonomy::Post, String] the requested post def get_post(user_name, intra_hash) response = @conn.get @url_post.expand({ :user_name => user_name, :intra_hash => intra_hash, :format => @format }) if @parse attributes = JSON.parse(response.body) return Post.new(attributes["post"]) end return response.body end # # Get posts owned by a user, optionally filtered by tags. # # @param user_name [String] the name of the posts' owner # @param resource_type [String] the type of the post. Currently supported are 'bookmark' and 'publication'. # @param tags [Array<String>] the tags that all posts must contain (can be empty) # @param start [Integer] number of first post to download # @param endc [Integer] number of last post to download # @return [Array<BibSonomy::Post>, String] the requested posts def get_posts_for_user(user_name, resource_type, tags = nil, start = 0, endc = $MAX_POSTS_PER_REQUEST) return get_posts("user", user_name, resource_type, tags, start, endc) end # # Get the posts of the users of a group, optionally filtered by tags. # # @param group_name [String] the name of the group # @param resource_type [String] the type of the post. Currently supported are 'bookmark' and 'publication'. # @param tags [Array<String>] the tags that all posts must contain (can be empty) # @param start [Integer] number of first post to download # @param endc [Integer] number of last post to download # @return [Array<BibSonomy::Post>, String] the requested posts # # Get posts for a user or group, optionally filtered by tags. # # @param grouping [String] the type of the name (either "user" or "group") # @param name [String] the name of the group or user # @param resource_type [String] the type of the post. Currently supported are 'bookmark' and 'publication'. # @param tags [Array<String>] the tags that all posts must contain (can be empty) # @param start [Integer] number of first post to download # @param endc [Integer] number of last post to download # @return [Array<BibSonomy::Post>, String] the requested posts def get_posts(grouping, name, resource_type, tags = nil, start = 0, endc = $MAX_POSTS_PER_REQUEST) url = @url_posts.partial_expand({ :format => @format, :resourcetype => get_resource_type(resource_type), :start => start, :end => endc }) # decide what to get if grouping == "user" url = url.partial_expand({:user => name}) elsif grouping == "group" url = url.partial_expand({:group => name}) end # add tags, if requested if tags != nil url = url.partial_expand({:tags => tags.join(" ")}) end response = @conn.get url.expand({}) if @parse posts = JSON.parse(response.body)["posts"]["post"] return posts.map { |attributes| Post.new(attributes) } end return response.body end def get_document_href(user_name, intra_hash, file_name) return @url_doc.expand({ :user_name => user_name, :intra_hash => intra_hash, :file_name => file_name }) end # # Get a document belonging to a post. # # @param user_name # @param intra_hash # @param file_name # @return the document and the content type def get_document(user_name, intra_hash, file_name) response = @conn.get get_document_href(user_name, intra_hash, file_name) if response.status == 200 return [response.body, response.headers['content-type']] end return nil, nil end # # Get the preview for a document belonging to a post. # # @param user_name # @param intra_hash # @param file_name # @param size [String] requested preview size (allowed values: SMALL, MEDIUM, LARGE) # @return the preview image and the content type `image/jpeg` def get_document_preview(user_name, intra_hash, file_name, size) response = @conn.get get_document_href(user_name, intra_hash, file_name), { :preview => size } if response.status == 200 return [response.body, 'image/jpeg'] end return nil, nil end private # # Convenience method to allow sloppy specification of the resource # type. # def get_resource_type(resource_type) if $resource_types_bookmark.include? resource_type.downcase() return "bookmark" end if $resource_types_bibtex.include? resource_type.downcase() return "bibtex" end raise ArgumentError.new("Unknown resource type: #{resource_type}. Supported resource types are ") end end
hashicorp/vagrant
lib/vagrant/box_collection.rb
Vagrant.BoxCollection.with_temp_dir
ruby
def with_temp_dir(dir=nil) dir ||= Dir.mktmpdir(TEMP_PREFIX, @temp_root) dir = Pathname.new(dir) yield dir ensure FileUtils.rm_rf(dir.to_s) end
This is a helper that makes sure that our temporary directories are cleaned up no matter what. @param [String] dir Path to a temporary directory @return [Object] The result of whatever the yield is
train
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box_collection.rb#L466-L473
class BoxCollection TEMP_PREFIX = "vagrant-box-add-temp-".freeze VAGRANT_SLASH = "-VAGRANTSLASH-".freeze VAGRANT_COLON = "-VAGRANTCOLON-".freeze # The directory where the boxes in this collection are stored. # # A box collection matches a very specific folder structure that Vagrant # expects in order to easily manage and modify boxes. The folder structure # is the following: # # COLLECTION_ROOT/BOX_NAME/PROVIDER/metadata.json # # Where: # # * COLLECTION_ROOT - This is the root of the box collection, and is # the directory given to the initializer. # * BOX_NAME - The name of the box. This is a logical name given by # the user of Vagrant. # * PROVIDER - The provider that the box was built for (VirtualBox, # VMware, etc.). # * metadata.json - A simple JSON file that at the bare minimum # contains a "provider" key that matches the provider for the # box. This metadata JSON, however, can contain anything. # # @return [Pathname] attr_reader :directory # Initializes the collection. # # @param [Pathname] directory The directory that contains the collection # of boxes. def initialize(directory, options=nil) options ||= {} @directory = directory @hook = options[:hook] @lock = Monitor.new @temp_root = options[:temp_dir_root] @logger = Log4r::Logger.new("vagrant::box_collection") end # This adds a new box to the system. # # There are some exceptional cases: # * BoxAlreadyExists - The box you're attempting to add already exists. # * BoxProviderDoesntMatch - If the given box provider doesn't match the # actual box provider in the untarred box. # * BoxUnpackageFailure - An invalid tar file. # # Preconditions: # * File given in `path` must exist. # # @param [Pathname] path Path to the box file on disk. # @param [String] name Logical name for the box. # @param [String] version The version of this box. # @param [Array<String>] providers The providers that this box can # be a part of. This will be verified with the `metadata.json` and is # meant as a basic check. If this isn't given, then whatever provider # the box represents will be added. # @param [Boolean] force If true, any existing box with the same name # and provider will be replaced. def add(path, name, version, **opts) providers = opts[:providers] providers = Array(providers) if providers provider = nil # A helper to check if a box exists. We store this in a variable # since we call it multiple times. check_box_exists = lambda do |box_formats| box = find(name, box_formats, version) next if !box if !opts[:force] @logger.error( "Box already exists, can't add: #{name} v#{version} #{box_formats.join(", ")}") raise Errors::BoxAlreadyExists, name: name, provider: box_formats.join(", "), version: version end # We're forcing, so just delete the old box @logger.info( "Box already exists, but forcing so removing: " + "#{name} v#{version} #{box_formats.join(", ")}") box.destroy! end with_collection_lock do log_provider = providers ? providers.join(", ") : "any provider" @logger.debug("Adding box: #{name} (#{log_provider}) from #{path}") # Verify the box doesn't exist early if we're given a provider. This # can potentially speed things up considerably since we don't need # to unpack any files. check_box_exists.call(providers) if providers # Create a temporary directory since we're not sure at this point if # the box we're unpackaging already exists (if no provider was given) with_temp_dir do |temp_dir| # Extract the box into a temporary directory. @logger.debug("Unpacking box into temporary directory: #{temp_dir}") result = Util::Subprocess.execute( "bsdtar", "--no-same-owner", "--no-same-permissions", "-v", "-x", "-m", "-s", "|\\\\\|/|", "-C", temp_dir.to_s, "-f", path.to_s) if result.exit_code != 0 raise Errors::BoxUnpackageFailure, output: result.stderr.to_s end # If we get a V1 box, we want to update it in place if v1_box?(temp_dir) @logger.debug("Added box is a V1 box. Upgrading in place.") temp_dir = v1_upgrade(temp_dir) end # We re-wrap ourselves in the safety net in case we upgraded. # If we didn't upgrade, then this is still safe because the # helper will only delete the directory if it exists with_temp_dir(temp_dir) do |final_temp_dir| # Get an instance of the box we just added before it is finalized # in the system so we can inspect and use its metadata. box = Box.new(name, nil, version, final_temp_dir) # Get the provider, since we'll need that to at the least add it # to the system or check that it matches what is given to us. box_provider = box.metadata["provider"] if providers found = providers.find { |p| p.to_sym == box_provider.to_sym } if !found @logger.error("Added box provider doesnt match expected: #{log_provider}") raise Errors::BoxProviderDoesntMatch, expected: log_provider, actual: box_provider end else # Verify the box doesn't already exist check_box_exists.call([box_provider]) end # We weren't given a provider, so store this one. provider = box_provider.to_sym # Create the directory for this box, not including the provider root_box_dir = @directory.join(dir_name(name)) box_dir = root_box_dir.join(version) box_dir.mkpath @logger.debug("Box directory: #{box_dir}") # This is the final directory we'll move it to final_dir = box_dir.join(provider.to_s) if final_dir.exist? @logger.debug("Removing existing provider directory...") final_dir.rmtree end # Move to final destination final_dir.mkpath # Recursively move individual files from the temporary directory # to the final location. We do this instead of moving the entire # directory to avoid issues on Windows. [GH-1424] copy_pairs = [[final_temp_dir, final_dir]] while !copy_pairs.empty? from, to = copy_pairs.shift from.children(true).each do |f| dest = to.join(f.basename) # We don't copy entire directories, so create the # directory and then add to our list to copy. if f.directory? dest.mkpath copy_pairs << [f, dest] next end # Copy the single file @logger.debug("Moving: #{f} => #{dest}") FileUtils.mv(f, dest) end end if opts[:metadata_url] root_box_dir.join("metadata_url").open("w") do |f| f.write(opts[:metadata_url]) end end end end end # Return the box find(name, provider, version) end # This returns an array of all the boxes on the system, given by # their name and their provider. # # @return [Array] Array of `[name, version, provider]` of the boxes # installed on this system. def all results = [] with_collection_lock do @logger.debug("Finding all boxes in: #{@directory}") @directory.children(true).each do |child| # Ignore non-directories, since files are not interesting to # us in our folder structure. next if !child.directory? box_name = undir_name(child.basename.to_s) # Otherwise, traverse the subdirectories and see what versions # we have. child.children(true).each do |versiondir| next if !versiondir.directory? next if versiondir.basename.to_s.start_with?(".") version = versiondir.basename.to_s versiondir.children(true).each do |provider| # Ensure version of box is correct before continuing if !Gem::Version.correct?(version) ui = Vagrant::UI::Prefixed.new(Vagrant::UI::Colored.new, "vagrant") ui.warn(I18n.t("vagrant.box_version_malformed", version: version, box_name: box_name)) @logger.debug("Invalid version #{version} for box #{box_name}") next end # Verify this is a potentially valid box. If it looks # correct enough then include it. if provider.directory? && provider.join("metadata.json").file? provider_name = provider.basename.to_s.to_sym @logger.debug("Box: #{box_name} (#{provider_name}, #{version})") results << [box_name, version, provider_name] else @logger.debug("Invalid box #{box_name}, ignoring: #{provider}") end end end end end # Sort the list to group like providers and properly ordered versions results.sort_by! do |box_result| [box_result[0], box_result[2], Gem::Version.new(box_result[1])] end results end # Find a box in the collection with the given name and provider. # # @param [String] name Name of the box (logical name). # @param [Array] providers Providers that the box implements. # @param [String] version Version constraints to adhere to. Example: # "~> 1.0" or "= 1.0, ~> 1.1" # @return [Box] The box found, or `nil` if not found. def find(name, providers, version) providers = Array(providers) # Build up the requirements we have requirements = version.to_s.split(",").map do |v| Gem::Requirement.new(v.strip) end with_collection_lock do box_directory = @directory.join(dir_name(name)) if !box_directory.directory? @logger.info("Box not found: #{name} (#{providers.join(", ")})") return nil end # Keep a mapping of Gem::Version mangled versions => directories. # ie. 0.1.0.pre.alpha.2 => 0.1.0-alpha.2 # This is so we can sort version numbers properly here, but still # refer to the real directory names in path checks below and pass an # unmangled version string to Box.new version_dir_map = {} versions = box_directory.children(true).map do |versiondir| next if !versiondir.directory? next if versiondir.basename.to_s.start_with?(".") version = Gem::Version.new(versiondir.basename.to_s) version_dir_map[version.to_s] = versiondir.basename.to_s version end.compact # Traverse through versions with the latest version first versions.sort.reverse.each do |v| if !requirements.all? { |r| r.satisfied_by?(v) } # Unsatisfied version requirements next end versiondir = box_directory.join(version_dir_map[v.to_s]) providers.each do |provider| provider_dir = versiondir.join(provider.to_s) next if !provider_dir.directory? @logger.info("Box found: #{name} (#{provider})") metadata_url = nil metadata_url_file = box_directory.join("metadata_url") metadata_url = metadata_url_file.read if metadata_url_file.file? if metadata_url && @hook hook_env = @hook.call( :authenticate_box_url, box_urls: [metadata_url]) metadata_url = hook_env[:box_urls].first end return Box.new( name, provider, version_dir_map[v.to_s], provider_dir, metadata_url: metadata_url, ) end end end nil end # This upgrades a v1.1 - v1.4 box directory structure up to a v1.5 # directory structure. This will raise exceptions if it fails in any # way. def upgrade_v1_1_v1_5 with_collection_lock do temp_dir = Pathname.new(Dir.mktmpdir(TEMP_PREFIX, @temp_root)) @directory.children(true).each do |boxdir| # Ignore all non-directories because they can't be boxes next if !boxdir.directory? box_name = boxdir.basename.to_s # If it is a v1 box, then we need to upgrade it first if v1_box?(boxdir) upgrade_dir = v1_upgrade(boxdir) FileUtils.mv(upgrade_dir, boxdir.join("virtualbox")) end # Create the directory for this box new_box_dir = temp_dir.join(dir_name(box_name), "0") new_box_dir.mkpath # Go through each provider and move it boxdir.children(true).each do |providerdir| FileUtils.cp_r(providerdir, new_box_dir.join(providerdir.basename)) end end # Move the folder into place @directory.rmtree FileUtils.mv(temp_dir.to_s, @directory.to_s) end end # Cleans the directory for a box by removing the folders that are # empty. def clean(name) return false if exists?(name) path = File.join(directory, dir_name(name)) FileUtils.rm_rf(path) end protected # Returns the directory name for the box of the given name. # # @param [String] name # @return [String] def dir_name(name) name = name.dup name.gsub!(":", VAGRANT_COLON) if Util::Platform.windows? name.gsub!("/", VAGRANT_SLASH) name end # Returns the directory name for the box cleaned up def undir_name(name) name = name.dup name.gsub!(VAGRANT_COLON, ":") name.gsub!(VAGRANT_SLASH, "/") name end # This checks if the given directory represents a V1 box on the # system. # # @param [Pathname] dir Directory where the box is unpacked. # @return [Boolean] def v1_box?(dir) # We detect a V1 box given by whether there is a "box.ovf" which # is a heuristic but is pretty accurate. dir.join("box.ovf").file? end # This upgrades the V1 box contained unpacked in the given directory # and returns the directory of the upgraded version. This is # _destructive_ to the contents of the old directory. That is, the # contents of the old V1 box will be destroyed or moved. # # Preconditions: # * `dir` is a valid V1 box. Verify with {#v1_box?} # # @param [Pathname] dir Directory where the V1 box is unpacked. # @return [Pathname] Path to the unpackaged V2 box. def v1_upgrade(dir) @logger.debug("Upgrading box in directory: #{dir}") temp_dir = Pathname.new(Dir.mktmpdir(TEMP_PREFIX, @temp_root)) @logger.debug("Temporary directory for upgrading: #{temp_dir}") # Move all the things into the temporary directory dir.children(true).each do |child| # Don't move the temp_dir next if child == temp_dir # Move every other directory into the temporary directory @logger.debug("Copying to upgrade directory: #{child}") FileUtils.mv(child, temp_dir.join(child.basename)) end # If there is no metadata.json file, make one, since this is how # we determine if the box is a V2 box. metadata_file = temp_dir.join("metadata.json") if !metadata_file.file? metadata_file.open("w") do |f| f.write(JSON.generate({ provider: "virtualbox" })) end end # Return the temporary directory temp_dir end # This locks the region given by the block with a lock on this # collection. def with_collection_lock @lock.synchronize do return yield end end # This is a helper that makes sure that our temporary directories # are cleaned up no matter what. # # @param [String] dir Path to a temporary directory # @return [Object] The result of whatever the yield is # Checks if a box with a given name exists. def exists?(box_name) all.any? { |box| box.first.eql?(box_name) } end end
wvanbergen/request-log-analyzer
lib/request_log_analyzer/file_format.rb
RequestLogAnalyzer::FileFormat.CommonRegularExpressions.hostname_or_ip_address
ruby
def hostname_or_ip_address(blank = false) regexp = Regexp.union(hostname, ip_address) add_blank_option(regexp, blank) end
Creates a regular expression to match a hostname or ip address
train
https://github.com/wvanbergen/request-log-analyzer/blob/b83865d440278583ac8e4901bb33878244fd7c75/lib/request_log_analyzer/file_format.rb#L134-L137
module CommonRegularExpressions TIMESTAMP_PARTS = { 'a' => '(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)', 'b' => '(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)', 'y' => '\d{2}', 'Y' => '\d{4}', 'm' => '\d{2}', 'd' => '\d{2}', 'H' => '\d{2}', 'M' => '\d{2}', 'S' => '\d{2}', 'k' => '(?:\d| )\d', 'z' => '(?:[+-]\d{4}|[A-Z]{3,4})', 'Z' => '(?:[+-]\d{4}|[A-Z]{3,4})', '%' => '%' } # Creates a regular expression to match a hostname def hostname(blank = false) regexp = /(?:(?:[a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*(?:[A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])/ add_blank_option(regexp, blank) end # Creates a regular expression to match a hostname or ip address # Create a regular expression for a timestamp, generated by a strftime call. # Provide the format string to construct a matching regular expression. # Set blank to true to allow and empty string, or set blank to a string to set # a substitute for the nil value. def timestamp(format_string, blank = false) regexp = '' format_string.scan(/([^%]*)(?:%([A-Za-z%]))?/) do |literal, variable| regexp << Regexp.quote(literal) if variable if TIMESTAMP_PARTS.key?(variable) regexp << TIMESTAMP_PARTS[variable] else fail "Unknown variable: %#{variable}" end end end add_blank_option(Regexp.new(regexp), blank) end # Construct a regular expression to parse IPv4 and IPv6 addresses. # # Allow nil values if the blank option is given. This can be true to # allow an empty string or to a string substitute for the nil value. def ip_address(blank = false) # IP address regexp copied from Resolv::IPv4 and Resolv::IPv6, # but adjusted to work for the purpose of request-log-analyzer. ipv4_regexp = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/ ipv6_regex_8_hex = /(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}/ ipv6_regex_compressed_hex = /(?:(?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::(?:(?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)/ ipv6_regex_6_hex_4_dec = /(?:(?:[0-9A-Fa-f]{1,4}:){6})#{ipv4_regexp}/ ipv6_regex_compressed_hex_4_dec = /(?:(?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::(?:(?:[0-9A-Fa-f]{1,4}:)*)#{ipv4_regexp}/ ipv6_regexp = Regexp.union(ipv6_regex_8_hex, ipv6_regex_compressed_hex, ipv6_regex_6_hex_4_dec, ipv6_regex_compressed_hex_4_dec) add_blank_option(Regexp.union(ipv4_regexp, ipv6_regexp), blank) end def anchored(regexp) /^#{regexp}$/ end protected # Allow the field to be blank if this option is given. This can be true to # allow an empty string or a string alternative for the nil value. def add_blank_option(regexp, blank) case blank when String then Regexp.union(regexp, Regexp.new(Regexp.quote(blank))) when true then Regexp.union(regexp, //) else regexp end end end
metanorma/relaton
lib/relaton/db_cache.rb
Relaton.DbCache.valid_entry?
ruby
def valid_entry?(key, year) datestr = fetched key return false unless datestr date = Date.parse datestr year || Date.today - date < 60 end
if cached reference is undated, expire it after 60 days @param key [String] @param year [String]
train
https://github.com/metanorma/relaton/blob/2fac19da2f3ef3c30b8e8d8815a14d2115df0be6/lib/relaton/db_cache.rb#L82-L87
class DbCache # @return [String] attr_reader :dir # @param dir [String] DB directory def initialize(dir) @dir = dir FileUtils::mkdir_p @dir file_version = "#{@dir}/version" File.write file_version, VERSION, encoding: "utf-8" unless File.exist? file_version end # Save item # @param key [String] # @param value [String] Bibitem xml serialization def []=(key, value) return if value.nil? prefix_dir = "#{@dir}/#{prefix(key)}" FileUtils::mkdir_p prefix_dir File.write filename(key), value, encoding: "utf-8" end # Read item # @param key [String] # @return [String] def [](key) file = filename key return unless File.exist? file File.read(file, encoding: "utf-8") end # Return fetched date # @param key [String] # @return [String] def fetched(key) value = self[key] return unless value if value =~ /^not_found/ value.match(/\d{4}-\d{2}-\d{2}/).to_s else doc = Nokogiri::XML value doc.at('/bibitem/fetched')&.text end end # Returns all items # @return [Array<Hash>] def all Dir.glob("#{@dir}/**/*.xml").sort.map do |f| File.read(f, encoding: "utf-8") end end # Delete item # @param key [String] def delete(key) file = filename key File.delete file if File.exist? file end # Check if version of the DB match to the gem version. # @return [TrueClass, FalseClass] def check_version? v = File.read @dir + "/version", encoding: "utf-8" v == VERSION end # Set version of the DB to the gem version. # @return [Relaton::DbCache] def set_version File.write @dir + "/version", VERSION, encoding: "utf-8" self end # if cached reference is undated, expire it after 60 days # @param key [String] # @param year [String] private # Return item's file name # @param key [String] # @return [String] def filename(key) prefcode = key.downcase.match /^(?<prefix>[^\(]+)\((?<code>[^\)]+)/ if prefcode "#{@dir}/#{prefcode[:prefix]}/#{prefcode[:code].gsub(/[-:\s\/]/, '_')}.xml" else "#{@dir}/#{key.gsub(/[-:\s]/, '_')}.xml" end end # Return item's subdir # @param key [String] # @return [String] def prefix(key) # @registry.processors.detect do |_n, p| # /^#{p.prefix}/.match(key) || processor.defaultprefix.match(key) # end[1].prefix.downcase key.downcase.match(/^[^\(]+(?=\()/).to_s end end
grempe/opensecrets
lib/opensecrets.rb
OpenSecrets.Committee.by_industry
ruby
def by_industry(options = {}) raise ArgumentError, 'You must provide a :cmte option' if options[:cmte].nil? || options[:cmte].empty? raise ArgumentError, 'You must provide a :congno option' if options[:congno].nil? || options[:congno].empty? raise ArgumentError, 'You must provide a :indus option' if options[:indus].nil? || options[:indus].empty? options.merge!({:method => 'congCmteIndus'}) self.class.get("/", :query => options) end
Provides summary fundraising information for a specific committee, industry and Congress number. See : http://www.opensecrets.org/api/?method=congCmteIndus&output=doc @option options [String] :cmte ("") Committee ID in CQ format @option options [String] :congno ("") Congress Number (like 110) @option options [String] :indus ("") Industry code
train
https://github.com/grempe/opensecrets/blob/2f507e214de716ce7b23831e056160b1384bff78/lib/opensecrets.rb#L138-L144
class Committee < OpenSecrets::Base # Provides summary fundraising information for a specific committee, industry and Congress number. # # See : http://www.opensecrets.org/api/?method=congCmteIndus&output=doc # # @option options [String] :cmte ("") Committee ID in CQ format # @option options [String] :congno ("") Congress Number (like 110) # @option options [String] :indus ("") Industry code # end # committee
anthonator/dirigible
lib/dirigible/request.rb
Dirigible.Request.request
ruby
def request(method, path, options, headers) headers.merge!({ 'User-Agent' => user_agent, 'Accept' => 'application/vnd.urbanairship+json; version=3;', }) response = connection.send(method) do |request| request.url("#{endpoint}#{path}/") if [:post, :put].member?(method) request.body = options.to_json else request.params.merge!(options) end request.headers.merge!(headers) end Utils.handle_api_error(response) unless (200..399).include?(response.status) Utils.parse_message(response) end
Perform an HTTP request.
train
https://github.com/anthonator/dirigible/blob/829b265ae4e54e3d4b284900b2a51a707afb6105/lib/dirigible/request.rb#L21-L42
module Request def get(path, options = {}, headers = {}) request(:get, path, options, headers) end def post(path, options = {}, headers = {}) request(:post, path, options, headers) end def put(path, options = {}, headers = {}) request(:put, path, options, headers) end def delete(path, options = {}, headers = {}) request(:delete, path, options, headers) end private # Perform an HTTP request. end
sailthru/sailthru-ruby-client
lib/sailthru/client.rb
Sailthru.Client.process_snapshot_job
ruby
def process_snapshot_job(query = {}, report_email = nil, postback_url = nil, options = {}) data = options data['query'] = query process_job(:snapshot, data, report_email, postback_url) end
implementation for snapshot job
train
https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L641-L645
class Client DEFAULT_API_URI = 'https://api.sailthru.com' include Helpers attr_accessor :verify_ssl # params: # api_key, String # secret, String # api_uri, String # # Instantiate a new client; constructor optionally takes overrides for key/secret/uri and proxy server settings. def initialize(api_key=nil, secret=nil, api_uri=nil, proxy_host=nil, proxy_port=nil, opts={}) @api_key = api_key || Sailthru.api_key || raise(ArgumentError, "You must provide an API key or call Sailthru.credentials() first") @secret = secret || Sailthru.secret || raise(ArgumentError, "You must provide your secret or call Sailthru.credentials() first") @api_uri = api_uri.nil? ? DEFAULT_API_URI : api_uri @proxy_host = proxy_host @proxy_port = proxy_port @verify_ssl = true @opts = opts @last_rate_limit_info = {} end # params: # template_name, String # email, String # vars, Hash # options, Hash # replyto: override Reply-To header # test: send as test email (subject line will be marked, will not count towards stats) # returns: # Hash, response data from server def send_email(template_name, email, vars={}, options = {}, schedule_time = nil, limit = {}) post = {} post[:template] = template_name post[:email] = email post[:vars] = vars if vars.length >= 1 post[:options] = options if options.length >= 1 post[:schedule_time] = schedule_time if !schedule_time.nil? post[:limit] = limit if limit.length >= 1 api_post(:send, post) end def multi_send(template_name, emails, vars={}, options = {}, schedule_time = nil, evars = {}) post = {} post[:template] = template_name post[:email] = emails post[:vars] = vars if vars.length >= 1 post[:options] = options if options.length >= 1 post[:schedule_time] = schedule_time if !schedule_time.nil? post[:evars] = evars if evars.length >= 1 api_post(:send, post) end # params: # send_id, Fixnum # returns: # Hash, response data from server # # Get the status of a send. def get_send(send_id) api_get(:send, {:send_id => send_id.to_s}) end def cancel_send(send_id) api_delete(:send, {:send_id => send_id.to_s}) end # params: # name, String # list, String # schedule_time, String # from_name, String # from_email, String # subject, String # content_html, String # content_text, String # options, Hash # returns: # Hash, response data from server # # Schedule a mass mail blast def schedule_blast(name, list, schedule_time, from_name, from_email, subject, content_html, content_text, options = {}) post = options ? options : {} post[:name] = name post[:list] = list post[:schedule_time] = schedule_time post[:from_name] = from_name post[:from_email] = from_email post[:subject] = subject post[:content_html] = content_html post[:content_text] = content_text api_post(:blast, post) end # Schedule a mass mail blast from template def schedule_blast_from_template(template, list, schedule_time, options={}) post = options ? options : {} post[:copy_template] = template post[:list] = list post[:schedule_time] = schedule_time api_post(:blast, post) end # Schedule a mass mail blast from previous blast def schedule_blast_from_blast(blast_id, schedule_time, options={}) post = options ? options : {} post[:copy_blast] = blast_id #post[:name] = name post[:schedule_time] = schedule_time api_post(:blast, post) end # params # blast_id, Fixnum | String # name, String # list, String # schedule_time, String # from_name, String # from_email, String # subject, String # content_html, String # content_text, String # options, hash # # updates existing blast def update_blast(blast_id, name = nil, list = nil, schedule_time = nil, from_name = nil, from_email = nil, subject = nil, content_html = nil, content_text = nil, options = {}) data = options ? options : {} data[:blast_id] = blast_id if name != nil data[:name] = name end if list != nil data[:list] = list end if schedule_time != nil data[:schedule_time] = schedule_time end if from_name != nil data[:from_name] = from_name end if from_email != nil data[:from_email] = from_email end if subject != nil data[:subject] = subject end if content_html != nil data[:content_html] = content_html end if content_text != nil data[:content_text] = content_text end api_post(:blast, data) end # params: # blast_id, Fixnum | String # options, hash # returns: # Hash, response data from server # # Get information on a previously scheduled email blast def get_blast(blast_id, options={}) options[:blast_id] = blast_id.to_s api_get(:blast, options) end # params: # blast_id, Fixnum | String # # Cancel a scheduled Blast def cancel_blast(blast_id) api_post(:blast, {:blast_id => blast_id, :schedule_time => ''}) end # params: # blast_id, Fixnum | String # # Delete a Blast def delete_blast(blast_id) api_delete(:blast, {:blast_id => blast_id}) end # params: # email, String # returns: # Hash, response data from server # # Return information about an email address, including replacement vars and lists. def get_email(email) api_get(:email, {:email => email}) end # params: # email, String # vars, Hash # lists, Hash mapping list name => 1 for subscribed, 0 for unsubscribed # options, Hash mapping optional parameters # returns: # Hash, response data from server # # Set replacement vars and/or list subscriptions for an email address. def set_email(email, vars = {}, lists = {}, templates = {}, options = {}) data = options data[:email] = email data[:vars] = vars unless vars.empty? data[:lists] = lists unless lists.empty? data[:templates] = templates unless templates.empty? api_post(:email, data) end # params: # new_email, String # old_email, String # options, Hash mapping optional parameters # returns: # Hash of response data. # # change a user's email address. def change_email(new_email, old_email, options = {}) data = options data[:email] = new_email data[:change_email] = old_email api_post(:email, data) end # returns: # Hash of response data. # # Get all templates def get_templates(templates = {}) api_get(:template, templates) end # params: # template_name, String # returns: # Hash of response data. # # Get a template. def get_template(template_name) api_get(:template, {:template => template_name}) end # params: # template_name, String # template_fields, Hash # returns: # Hash containg response from the server. # # Save a template. def save_template(template_name, template_fields) data = template_fields data[:template] = template_name api_post(:template, data) end # params: # template_name, String # returns: # Hash of response data. # # Delete a template. def delete_template(template_name) api_delete(:template, {:template => template_name}) end # params: # params, Hash # request, String # returns: # boolean, Returns true if the incoming request is an authenticated verify post. def receive_verify_post(params, request) if request.post? [:action, :email, :send_id, :sig].each { |key| return false unless params.has_key?(key) } return false unless params[:action] == :verify sig = params.delete(:sig) params.delete(:controller) return false unless sig == get_signature_hash(params, @secret) _send = get_send(params[:send_id]) return false unless _send.has_key?('email') return false unless _send['email'] == params[:email] return true else return false end end # params: # params, Hash # request, String # returns: # TrueClass or FalseClass, Returns true if the incoming request is an authenticated optout post. def receive_optout_post(params, request) if request.post? [:action, :email, :sig].each { |key| return false unless params.has_key?(key) } return false unless params[:action] == 'optout' sig = params.delete(:sig) params.delete(:controller) sig == get_signature_hash(params, @secret) else false end end # List Postbacks must be enabled by Sailthru # Contact your account manager or contact support to have this enabled # # params: # params, Hash # request, String # returns: # TrueClass or FalseClass, Returns true if the incoming request is an authenticated list post. def receive_list_post(params, request) if request.post? [:action, :email, :sig].each { |key| return false unless params.has_key?(key) } return false unless params[:action] == 'update' sig = params.delete(:sig) params.delete(:controller) sig == get_signature_hash(params, @secret) else false end end # params: # params, Hash # request, String # returns: # TrueClass or FalseClass, Returns true if the incoming request is an authenticated hardbounce post. def receive_hardbounce_post(params, request) if request.post? [:action, :email, :sig].each { |key| return false unless params.has_key?(key) } return false unless params[:action] == 'hardbounce' sig = params.delete(:sig) params.delete(:controller) sig == get_signature_hash(params, @secret) else false end end # params: # email, String # items, Array of Hashes # incomplete, Integer # message_id, String # options, Hash # returns: # hash, response from server # # Record that a user has made a purchase, or has added items to their purchase total. def purchase(email, items, incomplete = nil, message_id = nil, options = {}) data = options data[:email] = email data[:items] = items if incomplete != nil data[:incomplete] = incomplete.to_i end if message_id != nil data[:message_id] = message_id end api_post(:purchase, data) end # <b>DEPRECATED:</b> Please use either stats_list or stats_blast # params: # stat, String # # returns: # hash, response from server # Request various stats from Sailthru. def get_stats(stat) warn "[DEPRECATION] `get_stats` is deprecated. Please use `stats_list` and `stats_blast` instead" api_get(:stats, {:stat => stat}) end # params # list, String # date, String # # returns: # hash, response from server # Retrieve information about your subscriber counts on a particular list, on a particular day. def stats_list(list = nil, date = nil) data = {} if list != nil data[:list] = list end if date != nil data[:date] = date end data[:stat] = 'list' api_get(:stats, data) end # params # blast_id, String # start_date, String # end_date, String # options, Hash # # returns: # hash, response from server # Retrieve information about a particular blast or aggregated information from all of blasts over a specified date range def stats_blast(blast_id = nil, start_date = nil, end_date = nil, options = {}) data = options if blast_id != nil data[:blast_id] = blast_id end if start_date != nil data[:start_date] = start_date end if end_date != nil data[:end_date] = end_date end data[:stat] = 'blast' api_get(:stats, data) end # params # template, String # start_date, String # end_date, String # options, Hash # # returns: # hash, response from server # Retrieve information about a particular blast or aggregated information from all of blasts over a specified date range def stats_send(template = nil, start_date = nil, end_date = nil, options = {}) data = options if template != nil data[:template] = template end if start_date != nil data[:start_date] = start_date end if end_date != nil data[:end_date] = end_date end data[:stat] = 'send' api_get(:stats, data) end # <b>DEPRECATED:</b> Please use save_content # params # title, String # url, String # date, String # tags, Array or Comma separated string # vars, Hash # options, Hash # # Push a new piece of content to Sailthru, triggering any applicable alerts. # http://docs.sailthru.com/api/content def push_content(title, url, date = nil, tags = nil, vars = {}, options = {}) data = options data[:title] = title data[:url] = url if date != nil data[:date] = date end if tags != nil if tags.class == Array tags = tags.join(',') end data[:tags] = tags end if vars.length > 0 data[:vars] = vars end api_post(:content, data) end # params # id, String – An identifier for the item (by default, the item’s URL). # options, Hash - Containing any of the parameters described on # https://getstarted.sailthru.com/developers/api/content/#POST_Mode # # Push a new piece of content to Sailthru, triggering any applicable alerts. # http://docs.sailthru.com/api/content def save_content(id, options) data = options data[:id] = id data[:tags] = data[:tags].join(',') if data[:tags].respond_to?(:join) api_post(:content, data) end # params # list, String # # Get information about a list. def get_list(list) api_get(:list, {:list => list}) end # params # # Get information about all lists def get_lists api_get(:list, {}) end # params # list, String # options, Hash # Create a list, or update a list. def save_list(list, options = {}) data = options data[:list] = list api_post(:list, data) end # params # list, String # # Deletes a list def delete_list(list) api_delete(:list, {:list => list}) end # params # email, String # # get user alert data def get_alert(email) api_get(:alert, {:email => email}) end # params # email, String # type, String # template, String # _when, String # options, hash # # Add a new alert to a user. You can add either a realtime or a summary alert (daily/weekly). # _when is only required when alert type is weekly or daily def save_alert(email, type, template, _when = nil, options = {}) data = options data[:email] = email data[:type] = type data[:template] = template if (type == 'weekly' || type == 'daily') data[:when] = _when end api_post(:alert, data) end # params # email, String # alert_id, String # # delete user alert def delete_alert(email, alert_id) data = {:email => email, :alert_id => alert_id} api_delete(:alert, data) end # params # job, String # options, hash # report_email, String # postback_url, String # binary_key, String # # interface for making request to job call def process_job(job, options = {}, report_email = nil, postback_url = nil, binary_key = nil) data = options data['job'] = job if !report_email.nil? data['report_email'] = report_email end if !postback_url.nil? data['postback_url'] = postback_url end api_post(:job, data, binary_key) end # params # emails, String | Array # implementation for import_job def process_import_job(list, emails, report_email = nil, postback_url = nil, options = {}) data = options data['list'] = list data['emails'] = Array(emails).join(',') process_job(:import, data, report_email, postback_url) end # implementation for import job using file upload def process_import_job_from_file(list, file_path, report_email = nil, postback_url = nil, options = {}) data = options data['list'] = list data['file'] = file_path process_job(:import, data, report_email, postback_url, 'file') end # implementation for update job using file upload def process_update_job_from_file(file_path, report_email = nil, postback_url = nil, options = {}) data = options data['file'] = file_path process_job(:update, data, report_email, postback_url, 'file') end # implementation for purchase import job using file upload def process_purchase_import_job_from_file(file_path, report_email = nil, postback_url = nil, options = {}) data = options data['file'] = file_path process_job(:purchase_import, data, report_email, postback_url, 'file') end # implementation for snapshot job # implementation for export list job def process_export_list_job(list, report_email = nil, postback_url = nil, options = {}) data = options data['list'] = list process_job(:export_list_data, data, report_email, postback_url) end # get status of a job def get_job_status(job_id) api_get(:job, {'job_id' => job_id}) end # Get user by Sailthru ID def get_user_by_sid(id, fields = {}) api_get(:user, {'id' => id, 'fields' => fields}) end # Get user by specified key def get_user_by_key(id, key, fields = {}) data = { 'id' => id, 'key' => key, 'fields' => fields } api_get(:user, data) end # Create new user, or update existing user def save_user(id, options = {}) data = options data['id'] = id api_post(:user, data) end # params # Get an existing trigger def get_triggers api_get(:trigger, {}) end # params # template, String # trigger_id, String # Get an existing trigger def get_trigger_by_template(template, trigger_id = nil) data = {} data['template'] = template if trigger_id != nil then data['trigger_id'] = trigger_id end api_get(:trigger, data) end # params # event, String # Get an existing trigger def get_trigger_by_event(event) data = {} data['event'] = event api_get(:trigger, data) end # params # template, String # time, String # time_unit, String # event, String # zephyr, String # Create or update a trigger def post_template_trigger(template, time, time_unit, event, zephyr) data = {} data['template'] = template data['time'] = time data['time_unit'] = time_unit data['event'] = event data['zephyr'] = zephyr api_post(:trigger, data) end # params # template, String # time, String # time_unit, String # zephyr, String # Create or update a trigger def post_event_trigger(event, time, time_unit, zephyr) data = {} data['time'] = time data['time_unit'] = time_unit data['event'] = event data['zephyr'] = zephyr api_post(:trigger, data) end # params # id, String # event, String # options, Hash (Can contain vars, Hash and/or key) # Notify Sailthru of an Event def post_event(id, event, options = {}) data = options data['id'] = id data['event'] = event api_post(:event, data) end # Perform API GET request def api_get(action, data) api_request(action, data, 'GET') end # Perform API POST request def api_post(action, data, binary_key = nil) api_request(action, data, 'POST', binary_key) end #Perform API DELETE request def api_delete(action, data) api_request(action, data, 'DELETE') end # params # endpoint, String a e.g. "user" or "send" # method, String "GET" or "POST" # returns # Hash rate info # Get rate info for a particular endpoint/method, as of the last time a request was sent to the given endpoint/method # Includes the following keys: # limit: the per-minute limit for the given endpoint/method # remaining: the number of allotted requests remaining in the current minute for the given endpoint/method # reset: unix timestamp of the top of the next minute, when the rate limit will reset def get_last_rate_limit_info(endpoint, method) rate_info_key = get_rate_limit_info_key(endpoint, method) @last_rate_limit_info[rate_info_key] end protected # params: # action, String # data, Hash # request, String "GET" or "POST" # returns: # Hash # # Perform an API request, using the shared-secret auth hash. # def api_request(action, data, request_type, binary_key = nil) if !binary_key.nil? binary_key_data = data[binary_key] data.delete(binary_key) end if data[:format].nil? || data[:format] == 'json' data = prepare_json_payload(data) else data[:api_key] = @api_key data[:format] ||= 'json' data[:sig] = get_signature_hash(data, @secret) end if !binary_key.nil? data[binary_key] = binary_key_data end _result = http_request(action, data, request_type, binary_key) # NOTE: don't do the unserialize here if data[:format] == 'json' begin unserialized = JSON.parse(_result) return unserialized ? unserialized : _result rescue JSON::JSONError => e return {'error' => e} end end _result end # set up our post request def set_up_post_request(uri, data, headers, binary_key = nil) if !binary_key.nil? binary_data = data[binary_key] if binary_data.is_a?(StringIO) data[binary_key] = UploadIO.new( binary_data, "text/plain", "local.path" ) else data[binary_key] = UploadIO.new( File.open(binary_data), "text/plain" ) end req = Net::HTTP::Post::Multipart.new(uri.path, data) else req = Net::HTTP::Post.new(uri.path, headers) req.set_form_data(data) end req end # params: # uri, String # data, Hash # method, String "GET" or "POST" # returns: # String, body of response def http_request(action, data, method = 'POST', binary_key = nil) data = flatten_nested_hash(data, false) uri = "#{@api_uri}/#{action}" if method != 'POST' uri += "?" + data.map{ |key, value| "#{CGI::escape(key.to_s)}=#{CGI::escape(value.to_s)}" }.join("&") end req = nil headers = {"User-Agent" => "Sailthru API Ruby Client #{Sailthru::VERSION}"} _uri = URI.parse(uri) if method == 'POST' req = set_up_post_request( _uri, data, headers, binary_key ) else request_uri = "#{_uri.path}?#{_uri.query}" if method == 'DELETE' req = Net::HTTP::Delete.new(request_uri, headers) else req = Net::HTTP::Get.new(request_uri, headers) end end begin http = Net::HTTP::Proxy(@proxy_host, @proxy_port).new(_uri.host, _uri.port) if _uri.scheme == 'https' http.ssl_version = :TLSv1 http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE if @verify_ssl != true # some openSSL client doesn't work without doing this http.ssl_timeout = @opts[:http_ssl_timeout] || 5 end http.open_timeout = @opts[:http_open_timeout] || 5 http.read_timeout = @opts[:http_read_timeout] || 10 http.close_on_empty_response = @opts[:http_close_on_empty_response] || true response = http.start do http.request(req) end rescue Timeout::Error, Errno::ETIMEDOUT => e raise UnavailableError, "Timed out: #{_uri}" rescue => e raise ClientError, "Unable to open stream to #{_uri}: #{e.message}" end save_rate_limit_info(action, method, response) response.body || raise(ClientError, "No response received from stream: #{_uri}") end def http_multipart_request(uri, data) Net::HTTP::Post::Multipart.new url.path, "file" => UploadIO.new(data['file'], "application/octet-stream") end def prepare_json_payload(data) payload = { :api_key => @api_key, :format => 'json', #<3 XML :json => data.to_json } payload[:sig] = get_signature_hash(payload, @secret) payload end def save_rate_limit_info(action, method, response) limit = response['x-rate-limit-limit'].to_i remaining = response['x-rate-limit-remaining'].to_i reset = response['x-rate-limit-reset'].to_i if limit.nil? or remaining.nil? or reset.nil? return end rate_info_key = get_rate_limit_info_key(action, method) @last_rate_limit_info[rate_info_key] = { limit: limit, remaining: remaining, reset: reset } end def get_rate_limit_info_key(endpoint, method) :"#{endpoint}_#{method.downcase}" end end
barkerest/incline
app/controllers/incline/users_controller.rb
Incline.UsersController.promote
ruby
def promote # add the administrator flag to the selected user. if @user.system_admin? flash[:warning] = "User #{@user} is already an administrator." unless inline_request? redirect_to users_path and return end else if @user.update(system_admin: true) flash[:success] = "User #{@user} has been promoted to administrator." else flash[:danger] = "Failed to promote user #{@user}." end end if inline_request? render 'show', formats: [ :json ] else redirect_to users_path end end
PUT /incline/users/1/promote
train
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/controllers/incline/users_controller.rb#L182-L202
class UsersController < ApplicationController before_action :set_user, except: [ :index, :new, :create, :api ] before_action :set_dt_request, only: [ :index, :locate ] before_action :set_disable_info, only: [ :disable_confirm, :disable ] before_action :not_current, only: [ :destroy, :disable, :disable_confirm, :enable, :promote, :demote ] layout :use_layout, except: [ :index ] # Only anonymous users can signup. require_anon :new, :create # Only admins can delete/disable/enable users, or list all users, or show/edit/update other users. require_admin :index, :show, :edit, :update, :destroy, :disable, :disable_confirm, :enable, :promote, :demote, :locate ## # GET /incline/users def index end ## # GET /incline/signup def new @user = Incline::User.new end ## # POST /incline/signup def create @user = Incline::User.new(user_params :before_create) if system_admin? # skip recaptcha check if an admin is currently logged in. @user.recaptcha = :verified end if @user.valid? if @user.save @user.send_activation_email request.remote_ip if system_admin? flash[:info] = "The user #{@user} has been created, but will need to activate their account before use." additional_params = user_params :after_create if additional_params.any? unless @user.update_attributes(additional_params) flash[:warning] = 'Failed to apply additional attributes to new user account.' end end if inline_request? render 'show', formats: [ :json ] else redirect_to users_url end return else flash[:safe_info] = 'Your account has been created, but needs to be activated before you can use it.<br>Please check your email to activate your account.' if inline_request? render 'show', formats: [ :json ] else redirect_to main_app.root_url end return end else @user.errors[:base] << 'Failed to create user account.' end end render 'new' end ## # GET /incline/users/1 def show render 'show' end ## # GET /incline/users/1/edit def edit render 'edit' end ## # PUT /incline/users/1 def update if @user.update_attributes(user_params) if current_user?(@user) flash[:success] = 'Your profile has been updated.' if inline_request? render 'show', formats: [ :json ] else redirect_to @user end return else flash[:success] = "The user #{@user} has been updated." if inline_request? render 'show', formats: [ :json ] else redirect_to users_path end return end end render 'edit' end ## # DELETE /incline/users/1 def destroy if @user.enabled? flash[:danger] = 'Cannot delete an enabled user.' elsif @user.disabled_at.blank? || @user.disabled_at > 15.days.ago flash[:danger] = 'Cannot delete a user within 15 days of being disabled.' else @user.destroy flash[:success] = "User #{@user} has been deleted." end if inline_request? render 'show', formats: [ :json ] else redirect_to users_path end end ## # GET /incline/users/1/disable def disable_confirm unless @disable_info.user.enabled? flash[:warning] = "User #{@disable_info.user} is already disabled." unless inline_request? redirect_to users_path end end end ## # PUT /incline/users/1/disable def disable if @disable_info.valid? if @disable_info.user.disable(current_user, @disable_info.reason) flash[:success] = "User #{@disable_info.user} has been disabled." if inline_request? render 'show', formats: [ :json ] else redirect_to users_path end return else @disable_info.errors.add(:user, 'was unable to be updated') end end render 'disable_confirm' end ## # PUT /incline/users/1/enable def enable if @user.enabled? flash[:warning] = "User #{@user} is already enabled." unless inline_request? redirect_to users_path and return end else if @user.enable flash[:success] = "User #{@user} has been enabled." else flash[:danger] = "Failed to enable user #{@user}." end end if inline_request? render 'show', formats: [ :json ] else redirect_to users_path end end ## # PUT /incline/users/1/promote ## # PUT /incline/users/1/demote def demote # remove the administrator flag from the selected user. if @user.system_admin? if @user.update(system_admin: false) flash[:success] = "User #{@user} has been demoted from administrator." else flash[:danger] = "Failed to demote user #{@user}." end else flash[:warning] = "User #{@user} is not an administrator." unless inline_request? redirect_to users_path and return end end if inline_request? render 'show', formats: [ :json ] else redirect_to users_path end end # POST /incline/users/1/locate def locate render json: { record: @dt_request.record_location } end # GET/POST /incline/users/api?action=... def api process_api_action end private def set_dt_request @dt_request = Incline::DataTablesRequest.new(params) do (current_user.system_admin? ? Incline::User.known : Incline::User.known.enabled) end end def use_layout inline_request? ? false : nil end def valid_user? # This method allows us to override the "require_admin" and "require_anon" settings for these actions. action = params[:action].to_sym # The current user can show or edit their own details without any further validation. return true if [ :show, :edit, :update ].include?(action) && logged_in? && current_user?(set_user) # A system administrator can create new users. return true if [ :new, :create ].include?(action) && logged_in? && system_admin? super end def set_user @user ||= if system_admin? Incline::User.find(params[:id]) else Incline::User.enabled.find(params[:id]) end || Incline::User.new(name: 'Invalid User', email: 'invalid-user') end def set_disable_info @disable_info = Incline::DisableInfo.new(disable_info_params) @disable_info.user = @user end def user_params(mode = :all) ok = (mode == :all || mode == :before_create) ? [ :name, :email, :password, :password_confirmation, :recaptcha ] : [ ] # admins can add groups to other users. ok += [ { group_ids: [] } ] if (mode == :all || mode == :after_create) && logged_in? && system_admin? && !current_user?(set_user) params.require(:user).permit(ok) end def disable_info_params params[:disable_info] ? params.require(:disable_info).permit(:reason) : { } end def not_current if current_user?(@user) flash[:warning] = 'You cannot perform this operation on yourself.' redirect_to users_path end end end
DavidEGrayson/ruby_ecdsa
lib/ecdsa/prime_field.rb
ECDSA.PrimeField.square_roots_for_p_5_mod_8
ruby
def square_roots_for_p_5_mod_8(n) case power n, (prime - 1) / 4 when 1 candidate = power n, (prime + 3) / 8 when prime - 1 candidate = mod 2 * n * power(4 * n, (prime - 5) / 8) else # I think this can happen because we are not checking the Jacobi. return [] end square_roots_given_candidate n, candidate end
This is Algorithm 3.37 from http://cacr.uwaterloo.ca/hac/
train
https://github.com/DavidEGrayson/ruby_ecdsa/blob/2216043b38170b9603c05bf1d4e43e184fc6181e/lib/ecdsa/prime_field.rb#L151-L162
class PrimeField # @return (Integer) the prime number that the field is based on. attr_reader :prime def initialize(prime) raise ArgumentError, "Invalid prime #{prime.inspect}" if !prime.is_a?(Integer) @prime = prime end # Returns true if the given object is an integer and a member of the field. # @param e (Object) # @return (true or false) def include?(e) e.is_a?(Integer) && e >= 0 && e < prime end # Calculates the remainder of `n` after being divided by the field's prime. # @param n (Integer) # @return (Integer) def mod(n) n % prime end # Computes the multiplicative inverse of a field element using the # [Extended Euclidean Algorithm](http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm). # # @param n (Integer) # @return (Integer) integer `inv` such that `(inv * num) % prime` is one. def inverse(n) raise ArgumentError, '0 has no multiplicative inverse.' if n.zero? # For every i, we make sure that num * s[i] + prime * t[i] = r[i]. # Eventually r[i] will equal 1 because gcd(num, prime) is always 1. # At that point, s[i] is the multiplicative inverse of num in the field. remainders = [n, prime] s = [1, 0] t = [0, 1] arrays = [remainders, s, t] while remainders.last > 0 quotient = remainders[-2] / remainders[-1] arrays.each do |array| array << array[-2] - quotient * array[-1] end end raise 'Inversion bug: remainder is not 1.' if remainders[-2] != 1 mod s[-2] end # Computes `n` raised to the power `m`. # This algorithm uses the same idea as {Point#multiply_by_scalar}. # # @param n (Integer) the base # @param m (Integer) the exponent # @return (Integer) def power(n, m) result = 1 v = n while m > 0 result = mod result * v if m.odd? v = square v m >>= 1 end result end # Computes `n` multiplied by itself. # @param n (Integer) # @return (Integer) def square(n) mod n * n end # Finds all possible square roots of the given field element. # # @param n (Integer) # @return (Array) A sorted array of numbers whose square is equal to `n`. def square_roots(n) raise ArgumentError, "Not a member of the field: #{n}." if !include?(n) case when prime == 2 then [n] when (prime % 4) == 3 then square_roots_for_p_3_mod_4(n) when (prime % 8) == 5 then square_roots_for_p_5_mod_8(n) else square_roots_default(n) end end # This method is NOT part of the public API of the ECDSA gem. def self.factor_out_twos(x) e = 0 while x.even? x /= 2 e += 1 end [e, x] end # This method is NOT part of the public API of the ECDSA gem. # # Algorithm algorithm 2.149 from http://cacr.uwaterloo.ca/hac/ def self.jacobi(n, p) raise 'Jacobi symbol is not defined for primes less than 3.' if p < 3 n = n % p return 0 if n == 0 # Step 1 return 1 if n == 1 # Step 2 e, n1 = factor_out_twos n # Step 3 s = (e.even? || [1, 7].include?(p % 8)) ? 1 : -1 # Step 4 s = -s if (p % 4) == 3 && (n1 % 4) == 3 # Step 5 # Step 6 and 7 return s if n1 == 1 s * jacobi(p, n1) end private def jacobi(n) self.class.send(:jacobi, n, prime) end # This is Algorithm 1 from http://math.stanford.edu/~jbooher/expos/sqr_qnr.pdf # It is also Algorithm 3.36 from http://cacr.uwaterloo.ca/hac/ # The algorithm assumes that its input actually does have a square root. # To get around that, we double check the answer after running the algorithm to make # sure it works. def square_roots_for_p_3_mod_4(n) candidate = power n, (prime + 1) / 4 square_roots_given_candidate n, candidate end # This is Algorithm 3.37 from http://cacr.uwaterloo.ca/hac/ # This is Algorithm 3.34 from http://cacr.uwaterloo.ca/hac/ # It has no limitations except prime must be at least three, so we could # remove all the other square root algorithms if we wanted to. def square_roots_default(n) return [0] if n == 0 return [] if jacobi(n) == -1 # Step 1 # Step 2, except we don't want to use randomness. b = (1...prime).find { |i| jacobi(i) == -1 } s, t = self.class.factor_out_twos(prime - 1) # Step 3 n_inv = inverse(n) # Step 4 # Step 5 c = power b, t r = power n, (t + 1) / 2 # Step 6 (1...s).each do |i| d = power r * r * n_inv, 1 << (s - i - 1) r = mod r * c if d == prime - 1 c = square c end square_roots_given_candidate n, r end def square_roots_given_candidate(n, candidate) return [] if square(candidate) != n [candidate, mod(-candidate)].uniq.sort end end
oleganza/btcruby
lib/btcruby/script/cltv_extension.rb
BTC.CLTVExtension.handle_opcode
ruby
def handle_opcode(interpreter: nil, opcode: nil) # We are not supposed to handle any other opcodes here. return false if opcode != OP_CHECKLOCKTIMEVERIFY if interpreter.stack.size < 1 return interpreter.set_error(SCRIPT_ERR_INVALID_STACK_OPERATION) end # Note that elsewhere numeric opcodes are limited to # operands in the range -2**31+1 to 2**31-1, however it is # legal for opcodes to produce results exceeding that # range. This limitation is implemented by CScriptNum's # default 4-byte limit. # # If we kept to that limit we'd have a year 2038 problem, # even though the nLockTime field in transactions # themselves is uint32 which only becomes meaningless # after the year 2106. # # Thus as a special case we tell CScriptNum to accept up # to 5-byte bignums, which are good until 2**39-1, well # beyond the 2**32-1 limit of the nLockTime field itself. locktime = interpreter.cast_to_number(interpreter.stack.last, max_size: @locktime_max_size) # In the rare event that the argument may be < 0 due to # some arithmetic being done first, you can always use # 0 MAX CHECKLOCKTIMEVERIFY. if locktime < 0 return interpreter.set_error(SCRIPT_ERR_NEGATIVE_LOCKTIME) end # Actually compare the specified lock time with the transaction. checker = @lock_time_checker || interpreter.signature_checker if !checker.check_lock_time(locktime) return interpreter.set_error(SCRIPT_ERR_UNSATISFIED_LOCKTIME) end return true end
Returns `false` if failed to execute the opcode.
train
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/script/cltv_extension.rb#L22-L60
class CLTVExtension include ScriptInterpreterExtension # Default `locktime_max_size` is 5. # Default `lock_time_checker` equals current interpreter's signature checker. def initialize(locktime_max_size: nil, lock_time_checker: nil) @locktime_max_size = locktime_max_size || 5 @lock_time_checker = lock_time_checker end def extra_flags SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY end def should_handle_opcode(interpreter: nil, opcode: nil) opcode == OP_CHECKLOCKTIMEVERIFY end # Returns `false` if failed to execute the opcode. end
ynab/ynab-sdk-ruby
lib/ynab/api/transactions_api.rb
YNAB.TransactionsApi.get_transactions_by_category
ruby
def get_transactions_by_category(budget_id, category_id, opts = {}) data, _status_code, _headers = get_transactions_by_category_with_http_info(budget_id, category_id, opts) data end
List category transactions Returns all transactions for a specified category @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param category_id The id of the category @param [Hash] opts the optional parameters @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. @return [HybridTransactionsResponse]
train
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/transactions_api.rb#L281-L284
class TransactionsApi attr_accessor :api_client def initialize(api_client = ApiClient.default) @api_client = api_client end # Create a single transaction or multiple transactions # Creates a single transaction or multiple transactions. If you provide a body containing a 'transaction' object, a single transaction will be created and if you provide a body containing a 'transactions' array, multiple transactions will be created. # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param data The transaction or transactions to create. To create a single transaction you can specify a value for the &#39;transaction&#39; object and to create multiple transactions you can specify an array of &#39;transactions&#39;. It is expected that you will only provide a value for one of these objects. # @param [Hash] opts the optional parameters # @return [SaveTransactionsResponse] def create_transaction(budget_id, data, opts = {}) data, _status_code, _headers = create_transaction_with_http_info(budget_id, data, opts) data end # Create a single transaction or multiple transactions # Creates a single transaction or multiple transactions. If you provide a body containing a &#39;transaction&#39; object, a single transaction will be created and if you provide a body containing a &#39;transactions&#39; array, multiple transactions will be created. # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param data The transaction or transactions to create. To create a single transaction you can specify a value for the &#39;transaction&#39; object and to create multiple transactions you can specify an array of &#39;transactions&#39;. It is expected that you will only provide a value for one of these objects. # @param [Hash] opts the optional parameters # @return [Array<(SaveTransactionsResponse, Fixnum, Hash)>] SaveTransactionsResponse data, response status code and response headers def create_transaction_with_http_info(budget_id, data, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: TransactionsApi.create_transaction ...' end # verify the required parameter 'budget_id' is set if @api_client.config.client_side_validation && budget_id.nil? fail ArgumentError, "Missing the required parameter 'budget_id' when calling TransactionsApi.create_transaction" end # verify the required parameter 'data' is set if @api_client.config.client_side_validation && data.nil? fail ArgumentError, "Missing the required parameter 'data' when calling TransactionsApi.create_transaction" end # resource path local_var_path = '/budgets/{budget_id}/transactions'.sub('{' + 'budget_id' + '}', budget_id.to_s) # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(data) auth_names = ['bearer'] data, status_code, headers = @api_client.call_api(:POST, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'SaveTransactionsResponse') if @api_client.config.debugging @api_client.config.logger.debug "API called: TransactionsApi#create_transaction\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Single transaction # Returns a single transaction # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param transaction_id The id of the transaction # @param [Hash] opts the optional parameters # @return [TransactionResponse] def get_transaction_by_id(budget_id, transaction_id, opts = {}) data, _status_code, _headers = get_transaction_by_id_with_http_info(budget_id, transaction_id, opts) data end # Single transaction # Returns a single transaction # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param transaction_id The id of the transaction # @param [Hash] opts the optional parameters # @return [Array<(TransactionResponse, Fixnum, Hash)>] TransactionResponse data, response status code and response headers def get_transaction_by_id_with_http_info(budget_id, transaction_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: TransactionsApi.get_transaction_by_id ...' end # verify the required parameter 'budget_id' is set if @api_client.config.client_side_validation && budget_id.nil? fail ArgumentError, "Missing the required parameter 'budget_id' when calling TransactionsApi.get_transaction_by_id" end # verify the required parameter 'transaction_id' is set if @api_client.config.client_side_validation && transaction_id.nil? fail ArgumentError, "Missing the required parameter 'transaction_id' when calling TransactionsApi.get_transaction_by_id" end # resource path local_var_path = '/budgets/{budget_id}/transactions/{transaction_id}'.sub('{' + 'budget_id' + '}', budget_id.to_s).sub('{' + 'transaction_id' + '}', transaction_id.to_s) # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = ['bearer'] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'TransactionResponse') if @api_client.config.debugging @api_client.config.logger.debug "API called: TransactionsApi#get_transaction_by_id\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # List transactions # Returns budget transactions # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param [Hash] opts the optional parameters # @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). # @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. # @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. # @return [TransactionsResponse] def get_transactions(budget_id, opts = {}) data, _status_code, _headers = get_transactions_with_http_info(budget_id, opts) data end # List transactions # Returns budget transactions # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param [Hash] opts the optional parameters # @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). # @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. # @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. # @return [Array<(TransactionsResponse, Fixnum, Hash)>] TransactionsResponse data, response status code and response headers def get_transactions_with_http_info(budget_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: TransactionsApi.get_transactions ...' end # verify the required parameter 'budget_id' is set if @api_client.config.client_side_validation && budget_id.nil? fail ArgumentError, "Missing the required parameter 'budget_id' when calling TransactionsApi.get_transactions" end if @api_client.config.client_side_validation && opts[:'type'] && !['uncategorized', 'unapproved'].include?(opts[:'type']) fail ArgumentError, 'invalid value for "type", must be one of uncategorized, unapproved' end # resource path local_var_path = '/budgets/{budget_id}/transactions'.sub('{' + 'budget_id' + '}', budget_id.to_s) # query parameters query_params = {} query_params[:'since_date'] = opts[:'since_date'] if !opts[:'since_date'].nil? query_params[:'type'] = opts[:'type'] if !opts[:'type'].nil? query_params[:'last_knowledge_of_server'] = opts[:'last_knowledge_of_server'] if !opts[:'last_knowledge_of_server'].nil? # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = ['bearer'] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'TransactionsResponse') if @api_client.config.debugging @api_client.config.logger.debug "API called: TransactionsApi#get_transactions\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # List account transactions # Returns all transactions for a specified account # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param account_id The id of the account # @param [Hash] opts the optional parameters # @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). # @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. # @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. # @return [TransactionsResponse] def get_transactions_by_account(budget_id, account_id, opts = {}) data, _status_code, _headers = get_transactions_by_account_with_http_info(budget_id, account_id, opts) data end # List account transactions # Returns all transactions for a specified account # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param account_id The id of the account # @param [Hash] opts the optional parameters # @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). # @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. # @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. # @return [Array<(TransactionsResponse, Fixnum, Hash)>] TransactionsResponse data, response status code and response headers def get_transactions_by_account_with_http_info(budget_id, account_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: TransactionsApi.get_transactions_by_account ...' end # verify the required parameter 'budget_id' is set if @api_client.config.client_side_validation && budget_id.nil? fail ArgumentError, "Missing the required parameter 'budget_id' when calling TransactionsApi.get_transactions_by_account" end # verify the required parameter 'account_id' is set if @api_client.config.client_side_validation && account_id.nil? fail ArgumentError, "Missing the required parameter 'account_id' when calling TransactionsApi.get_transactions_by_account" end if @api_client.config.client_side_validation && opts[:'type'] && !['uncategorized', 'unapproved'].include?(opts[:'type']) fail ArgumentError, 'invalid value for "type", must be one of uncategorized, unapproved' end # resource path local_var_path = '/budgets/{budget_id}/accounts/{account_id}/transactions'.sub('{' + 'budget_id' + '}', budget_id.to_s).sub('{' + 'account_id' + '}', account_id.to_s) # query parameters query_params = {} query_params[:'since_date'] = opts[:'since_date'] if !opts[:'since_date'].nil? query_params[:'type'] = opts[:'type'] if !opts[:'type'].nil? query_params[:'last_knowledge_of_server'] = opts[:'last_knowledge_of_server'] if !opts[:'last_knowledge_of_server'].nil? # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = ['bearer'] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'TransactionsResponse') if @api_client.config.debugging @api_client.config.logger.debug "API called: TransactionsApi#get_transactions_by_account\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # List category transactions # Returns all transactions for a specified category # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param category_id The id of the category # @param [Hash] opts the optional parameters # @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). # @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. # @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. # @return [HybridTransactionsResponse] # List category transactions # Returns all transactions for a specified category # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param category_id The id of the category # @param [Hash] opts the optional parameters # @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). # @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. # @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. # @return [Array<(HybridTransactionsResponse, Fixnum, Hash)>] HybridTransactionsResponse data, response status code and response headers def get_transactions_by_category_with_http_info(budget_id, category_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: TransactionsApi.get_transactions_by_category ...' end # verify the required parameter 'budget_id' is set if @api_client.config.client_side_validation && budget_id.nil? fail ArgumentError, "Missing the required parameter 'budget_id' when calling TransactionsApi.get_transactions_by_category" end # verify the required parameter 'category_id' is set if @api_client.config.client_side_validation && category_id.nil? fail ArgumentError, "Missing the required parameter 'category_id' when calling TransactionsApi.get_transactions_by_category" end if @api_client.config.client_side_validation && opts[:'type'] && !['uncategorized', 'unapproved'].include?(opts[:'type']) fail ArgumentError, 'invalid value for "type", must be one of uncategorized, unapproved' end # resource path local_var_path = '/budgets/{budget_id}/categories/{category_id}/transactions'.sub('{' + 'budget_id' + '}', budget_id.to_s).sub('{' + 'category_id' + '}', category_id.to_s) # query parameters query_params = {} query_params[:'since_date'] = opts[:'since_date'] if !opts[:'since_date'].nil? query_params[:'type'] = opts[:'type'] if !opts[:'type'].nil? query_params[:'last_knowledge_of_server'] = opts[:'last_knowledge_of_server'] if !opts[:'last_knowledge_of_server'].nil? # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = ['bearer'] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'HybridTransactionsResponse') if @api_client.config.debugging @api_client.config.logger.debug "API called: TransactionsApi#get_transactions_by_category\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # List payee transactions # Returns all transactions for a specified payee # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param payee_id The id of the payee # @param [Hash] opts the optional parameters # @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). # @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. # @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. # @return [HybridTransactionsResponse] def get_transactions_by_payee(budget_id, payee_id, opts = {}) data, _status_code, _headers = get_transactions_by_payee_with_http_info(budget_id, payee_id, opts) data end # List payee transactions # Returns all transactions for a specified payee # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param payee_id The id of the payee # @param [Hash] opts the optional parameters # @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). # @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. # @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. # @return [Array<(HybridTransactionsResponse, Fixnum, Hash)>] HybridTransactionsResponse data, response status code and response headers def get_transactions_by_payee_with_http_info(budget_id, payee_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: TransactionsApi.get_transactions_by_payee ...' end # verify the required parameter 'budget_id' is set if @api_client.config.client_side_validation && budget_id.nil? fail ArgumentError, "Missing the required parameter 'budget_id' when calling TransactionsApi.get_transactions_by_payee" end # verify the required parameter 'payee_id' is set if @api_client.config.client_side_validation && payee_id.nil? fail ArgumentError, "Missing the required parameter 'payee_id' when calling TransactionsApi.get_transactions_by_payee" end if @api_client.config.client_side_validation && opts[:'type'] && !['uncategorized', 'unapproved'].include?(opts[:'type']) fail ArgumentError, 'invalid value for "type", must be one of uncategorized, unapproved' end # resource path local_var_path = '/budgets/{budget_id}/payees/{payee_id}/transactions'.sub('{' + 'budget_id' + '}', budget_id.to_s).sub('{' + 'payee_id' + '}', payee_id.to_s) # query parameters query_params = {} query_params[:'since_date'] = opts[:'since_date'] if !opts[:'since_date'].nil? query_params[:'type'] = opts[:'type'] if !opts[:'type'].nil? query_params[:'last_knowledge_of_server'] = opts[:'last_knowledge_of_server'] if !opts[:'last_knowledge_of_server'].nil? # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # form parameters form_params = {} # http body (model) post_body = nil auth_names = ['bearer'] data, status_code, headers = @api_client.call_api(:GET, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'HybridTransactionsResponse') if @api_client.config.debugging @api_client.config.logger.debug "API called: TransactionsApi#get_transactions_by_payee\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Updates an existing transaction # Updates a transaction # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param transaction_id The id of the transaction # @param data The transaction to update # @param [Hash] opts the optional parameters # @return [TransactionResponse] def update_transaction(budget_id, transaction_id, data, opts = {}) data, _status_code, _headers = update_transaction_with_http_info(budget_id, transaction_id, data, opts) data end # Updates an existing transaction # Updates a transaction # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param transaction_id The id of the transaction # @param data The transaction to update # @param [Hash] opts the optional parameters # @return [Array<(TransactionResponse, Fixnum, Hash)>] TransactionResponse data, response status code and response headers def update_transaction_with_http_info(budget_id, transaction_id, data, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: TransactionsApi.update_transaction ...' end # verify the required parameter 'budget_id' is set if @api_client.config.client_side_validation && budget_id.nil? fail ArgumentError, "Missing the required parameter 'budget_id' when calling TransactionsApi.update_transaction" end # verify the required parameter 'transaction_id' is set if @api_client.config.client_side_validation && transaction_id.nil? fail ArgumentError, "Missing the required parameter 'transaction_id' when calling TransactionsApi.update_transaction" end # verify the required parameter 'data' is set if @api_client.config.client_side_validation && data.nil? fail ArgumentError, "Missing the required parameter 'data' when calling TransactionsApi.update_transaction" end # resource path local_var_path = '/budgets/{budget_id}/transactions/{transaction_id}'.sub('{' + 'budget_id' + '}', budget_id.to_s).sub('{' + 'transaction_id' + '}', transaction_id.to_s) # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(data) auth_names = ['bearer'] data, status_code, headers = @api_client.call_api(:PUT, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'TransactionResponse') if @api_client.config.debugging @api_client.config.logger.debug "API called: TransactionsApi#update_transaction\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end # Update multiple transactions # Updates multiple transactions, by 'id' or 'import_id'. # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param data The transactions to update. Optionally, transaction &#39;id&#39; value(s) can be specified as null and an &#39;import_id&#39; value can be provided which will allow transaction(s) to updated by their import_id. # @param [Hash] opts the optional parameters # @return [SaveTransactionsResponse] def update_transactions(budget_id, data, opts = {}) data, _status_code, _headers = update_transactions_with_http_info(budget_id, data, opts) data end # Update multiple transactions # Updates multiple transactions, by &#39;id&#39; or &#39;import_id&#39;. # @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) # @param data The transactions to update. Optionally, transaction &#39;id&#39; value(s) can be specified as null and an &#39;import_id&#39; value can be provided which will allow transaction(s) to updated by their import_id. # @param [Hash] opts the optional parameters # @return [Array<(SaveTransactionsResponse, Fixnum, Hash)>] SaveTransactionsResponse data, response status code and response headers def update_transactions_with_http_info(budget_id, data, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: TransactionsApi.update_transactions ...' end # verify the required parameter 'budget_id' is set if @api_client.config.client_side_validation && budget_id.nil? fail ArgumentError, "Missing the required parameter 'budget_id' when calling TransactionsApi.update_transactions" end # verify the required parameter 'data' is set if @api_client.config.client_side_validation && data.nil? fail ArgumentError, "Missing the required parameter 'data' when calling TransactionsApi.update_transactions" end # resource path local_var_path = '/budgets/{budget_id}/transactions'.sub('{' + 'budget_id' + '}', budget_id.to_s) # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(data) auth_names = ['bearer'] data, status_code, headers = @api_client.call_api(:PATCH, local_var_path, :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => 'SaveTransactionsResponse') if @api_client.config.debugging @api_client.config.logger.debug "API called: TransactionsApi#update_transactions\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end end
zhimin/rwebspec
lib/rwebspec-watir/driver.rb
RWebSpec.Driver.enter_text_with_id
ruby
def enter_text_with_id(textfield_id, value, opts = {}) # For IE10, it seems unable to identify HTML5 elements # # However for IE10, the '.' is omitted. if opts.nil? || opts.empty? # for Watir, default is clear opts[:appending] = false end perform_operation { begin text_field(:id, textfield_id).set(value) rescue => e # However, this approach is not reliable with Watir (IE) # for example, for entering email, the dot cannot be entered, try ["a@b", :decimal, "com"] the_elem = element(:xpath, "//input[@id='#{textfield_id}']") the_elem.send_keys(:clear) unless opts[:appending] the_elem.send_keys(value) end } end
for text field can be easier to be identified by attribute "id" instead of "name", not recommended though params opts takes :appending => true or false, if true, won't clear the text field.
train
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-watir/driver.rb#L319-L340
module Driver include RWebSpec::TestWisePlugin include RWebSpec::Popup # open a browser, and set base_url via hash, but does not acually # # example: # open_browser :base_url => http://localhost:8080 # # There are 3 ways to set base url # 1. pass as first argument # 2. If running using TestWise, used as confiured # 3. Use default value set def open_browser_by_watir(options = {}) begin support_unicode rescue => e puts "Unicode may not work in IE, #{e}" end if options && options.class == String options = {:base_url => options.to_s } end if options && options.class == Hash && options[:base_url] base_url ||= options[:base_url] end base_url = options[:base_url] rescue nil base_url ||= $TESTWISE_PROJECT_BASE_URL base_url ||= $BASE_URL raise "base_url must be set" if base_url.nil? default_options = {:speed => "fast", :visible => true, :highlight_colour => 'yellow', :close_others => true, :start_new => false, # start a new browser always :go => true} options = default_options.merge options ($TESTWISE_HIDE_BROWSER) ? $HIDE_IE = true : $HIDE_IE = false if base_url =~ /^file:/ uri_base = base_url else uri = URI.parse(base_url) uri_base = "#{uri.scheme}://#{uri.host}:#{uri.port}" end if options[:start_new] @web_browser = WebBrowser.new(uri_base, nil, options) else @web_browser = WebBrowser.reuse(uri_base, options) # Reuse existing browser end if base_url =~ /^file:/ goto_url(base_url) # for files, no base url else (uri.path.length == 0) ? begin_at("/") : begin_at(uri.path) if options[:go] end return @web_browser end # return the underlying RWebSpec::Browser object def browser @web_browser end # Close the current browser window (started by the script). If no browser started, then close # all browser windows. # def close_browser if @web_browser # Old TestWise version # @web_browser.close_browser unless $TESTWISE_LEAVE_BROWSER_OPEN_AFTER_RUN @web_browser.close_browser else close_all_browsers end end alias close_ie close_browser # Close all opening browser windows # def close_all_browsers @web_browser.close_all_browsers end # Verify the next page following an operation. # # Typical usage: # login_page.click_login # expect_page HomePage def expect_page(page_clazz, argument = nil) if argument @web_browser.expect_page(page_clazz, argument) else @web_browser.expect_page(page_clazz) end end def context @web_browser.context end # Starting browser with a URL # # Example: # begin_at("http://www.itest2.com") def begin_at(url) dump_caller_stack @web_browser.begin_at(url) end # Return the Watir::IE instance # def ie @web_browser.ie end # Return the FireWatir::Firefox instance # def firefox @web_browser.firefox end def is_firefox? @web_browser.is_firefox? if @web_browser end # Go to another page on the testing site. # # open_browser(:base_url => "http://www.itest2.com") # goto_page("/demo") # visit page http://www.itest2.com/demo # def goto_page(page) perform_operation { @web_browser.goto_page(page) if @web_browser } end alias visit goto_page # Go to another web site, normally different site being tested on # # open_browser(:base_url => "http://www.itest2.com") # goto_url("http://myorganized.info") def goto_url(url) @web_browser.goto_url url end # Go to specific url in background (i.e not via browwser, different from goto_url) # This won't share the session with what's currenlty in browser, proxy setting # # One use example: resetting database # background_visit("/reset") # def background_visit(url, opts = {}) require 'httpclient' begin client = HTTPClient.new if url && url =~ /^http/ http_response = client.get(url).body else base_url = $TESTWISE_PROJECT_BASE_URL || $TESTWISE_PROJECT_BASE_URL || $BASE_URL http_response = client.get("#{base_url}#{url}").body end http_response = http_response.content if http_response.respond_to?("content") rescue => e raise e end end # Attach to existing browser window # # attach_browser(:title, "Page" ) # attach_browser(:url, "http://wwww..." ) def attach_browser(how, what, options = {}) options.merge!(:browser => is_firefox? ? "Firefox" : "IE") unless options[:browser] begin options.merge!(:base_url => browser.context.base_url) rescue => e puts "failed to set base_url, ignore : #{e}" end WebBrowser.attach_browser(how, what, options) end # Reuse current an opened browser window instead of opening a new one # example: # use_current_watir_browser(:title, /.*/) # use what ever browser window # use_current_watir_browser(:title, "TestWise") # use browser window with title "TestWise" def use_current_watir_browser(how = :title, what = /.*/) @web_browser = WebBrowser.attach_browser(how, what) end ## # Delegate to WebTester # # Note: # label(:id, "abc") # OK # label(:id, :abc) # Error # # Depends on which object type, you can use following attribute # More details: http://wiki.openqa.org/display/WTR/Methods+supported+by+Element # # :id Used to find an element that has an "id=" attribute. Since each id should be unique, according to the XHTML specification, this is recommended as the most reliable method to find an object. * # :name Used to find an element that has a "name=" attribute. This is useful for older versions of HTML, but "name" is deprecated in XHTML. * # :value Used to find a text field with a given default value, or a button with a given caption, or a text field # :text Used for links, spans, divs and other element that contain text. # :index Used to find the nth element of the specified type on a page. For example, button(:index, 2) finds the second button. Current versions of WATIR use 1-based indexing, but future versions will use 0-based indexing. # :class Used for an element that has a "class=" attribute. # :title Used for an element that has a "title=" attribute. # :xpath Finds the item using xpath query. # :method Used only for forms, the method attribute of a form is either GET or POST. # :action Used only for form elements, specifies the URL where the form is to be submitted. # :href Used to identify a link by its "href=" attribute. # :src Used to identify an image by its URL. # # area <area> tags # button <input> tags with type=button, submit, image or reset # check_box <input> tags with type=checkbox # div <div> tags # form <form> tags # frame frames, including both the <frame> elements and the corresponding pages # h1 - h6 <h1>, <h2>, <h3>, <h4>, <h5>, <h6> tags # hidden <input> tags with type=hidden # image <img> tags # label <label> tags (including "for" attribute) # li <li> tags # link <a> (anchor) tags # map <map> tags # radio <input> tags with the type=radio; known as radio buttons # select_list <select> tags, known as drop-downs or drop-down lists # span <span> tags # table <table> tags, including row and cell methods for accessing nested elements # text_field <input> tags with the type=text (single-line), type=textarea (multi-line), and type=password # p <p> (paragraph) tags, because [:area, :button, :td, :checkbox, :div, :form, :frame, :h1, :h2, :h3, :h4, :h5, :h6, :hidden, :image, :li, :link, :map, :pre, :tr, :radio, :select_list, :span, :table, :text_field, :paragraph, :file_field, :label].each do |method| define_method method do |* args| perform_operation { @web_browser.send(method, * args) if @web_browser } end end alias cell td alias check_box checkbox # seems watir doc is wrong, checkbox not check_box alias row tr alias a link alias img image [:back, :forward, :refresh, :execute_script].each do |method| define_method(method) do perform_operation { @web_browser.send(method) if @web_browser } end end alias refresh_page refresh alias go_back back alias go_forward forward [:images, :links, :buttons, :select_lists, :checkboxes, :radios, :text_fields, :divs, :dls, :dds, :dts, :ems, :lis, :maps, :spans, :strongs, :ps, :pres, :labels, :tds, :trs].each do |method| define_method method do perform_operation { @web_browser.send(method) if @web_browser } end end alias as links alias rows trs alias cells tds alias imgs images # Check one or more checkboxes with same name, can accept a string or an array of string as values checkbox, pass array as values will try to set mulitple checkboxes. # # page.check_checkbox('bad_ones', 'Chicken Little') # page.check_checkbox('good_ones', ['Cars', 'Toy Story']) # [:set_form_element, :click_link_with_text, :click_link_with_id, :submit, :click_button_with_id, :click_button_with_name, :click_button_with_caption, :click_button_with_value, :click_radio_option, :clear_radio_option, :check_checkbox, :uncheck_checkbox, :select_option, :element].each do |method| define_method method do |* args| perform_operation { @web_browser.send(method, * args) if @web_browser } end end alias enter_text set_form_element alias set_hidden_field set_form_element alias click_link click_link_with_text alias click_button_with_text click_button_with_caption alias click_button click_button_with_caption alias click_radio_button click_radio_option alias clear_radio_button clear_radio_option # for text field can be easier to be identified by attribute "id" instead of "name", not recommended though # # params opts takes :appending => true or false, if true, won't clear the text field. def enter_text_with_id(textfield_id, value, opts = {}) # For IE10, it seems unable to identify HTML5 elements # # However for IE10, the '.' is omitted. if opts.nil? || opts.empty? # for Watir, default is clear opts[:appending] = false end perform_operation { begin text_field(:id, textfield_id).set(value) rescue => e # However, this approach is not reliable with Watir (IE) # for example, for entering email, the dot cannot be entered, try ["a@b", :decimal, "com"] the_elem = element(:xpath, "//input[@id='#{textfield_id}']") the_elem.send_keys(:clear) unless opts[:appending] the_elem.send_keys(value) end } end def perform_operation(& block) begin dump_caller_stack operation_delay yield rescue RuntimeError => re raise re # ensure # puts "[DEBUG] ensure #{perform_ok}" unless perform_ok end end def contains_text(text) @web_browser.contains_text(text) end # In pages, can't use include, text.should include("abc") won't work # Instead, # text.should contains("abc" def contains(str) ContainsText.new(str) end alias contain contains # Click image buttion with image source name # # For an image submit button <input name="submit" type="image" src="/images/search_button.gif"> # click_button_with_image("search_button.gif") def click_button_with_image_src_contains(image_filename) perform_operation { found = nil raise "no buttons in this page" if buttons.length <= 0 buttons.each { |btn| if btn && btn.src && btn.src.include?(image_filename) then found = btn break end } raise "not image button with src: #{image_filename} found" if found.nil? found.click } end alias click_button_with_image click_button_with_image_src_contains def new_popup_window(options) @web_browser.new_popup_window(options) end # Warning: this does not work well with Firefox yet. def element_text(elem_id) @web_browser.element_value(elem_id) end # Identify DOM element by ID # Warning: it is only supported on IE def element_by_id(elem_id) @web_browser.element_by_id(elem_id) end # --- # For debugging # --- def dump_response(stream = nil) @web_browser.dump_response(stream) end def default_dump_dir if ($TESTWISE_RUNNING_SPEC_ID && $TESTWISE_WORKING_DIR) || ($TESTWISE_RUNNING_SPEC_ID && $TESTWISE_WORKING_DIR) $TESTWISE_DUMP_DIR = $TESTWISE_DUMP_DIR = File.join($TESTWISE_WORKING_DIR, "dump") FileUtils.mkdir($TESTWISE_DUMP_DIR) unless File.exists?($TESTWISE_DUMP_DIR) spec_run_id = $TESTWISE_RUNNING_SPEC_ID || $TESTWISE_RUNNING_SPEC_ID spec_run_dir_name = spec_run_id.to_s.rjust(4, "0") unless spec_run_id == "unknown" to_dir = File.join($TESTWISE_DUMP_DIR, spec_run_dir_name) else to_dir = ENV['TEMP_DIR'] || (is_windows? ? "C:\\temp" : "/tmp") end end # For current page souce to a file in specified folder for inspection # # save_current_page(:dir => "C:\\mysite", filename => "abc", :replacement => true) def save_current_page(options = {}) default_options = {:replacement => true} options = default_options.merge(options) to_dir = options[:dir] || default_dump_dir if options[:filename] file_name = options[:filename] else file_name = Time.now.strftime("%m%d%H%M%S") + ".html" end Dir.mkdir(to_dir) unless File.exists?(to_dir) file = File.join(to_dir, file_name) content = page_source base_url = @web_browser.context.base_url current_url = @web_browser.url current_url =~ /(.*\/).*$/ current_url_parent = $1 if options[:replacement] && base_url =~ /^http:/ File.new(file, "w").puts absolutize_page_nokogiri(content, base_url, current_url_parent) else File.new(file, "w").puts content end end # Return page HTML with absolute references of images, stylesheets and javascripts # def absolutize_page(content, base_url, current_url_parent) modified_content = "" content.each_line do |line| if line =~ /<script\s+.*src=["'']?(.*)["'].*/i then script_src = $1 substitute_relative_path_in_src_line(line, script_src, base_url, current_url_parent) elsif line =~ /<link\s+.*href=["'']?(.*)["'].*/i then link_href = $1 substitute_relative_path_in_src_line(line, link_href, base_url, current_url_parent) elsif line =~ /<img\s+.*src=["'']?(.*)["'].*/i then img_src = $1 substitute_relative_path_in_src_line(line, img_src, base_url, current_url_parent) end modified_content += line end return modified_content end # absolutize_page using hpricot # def absolutize_page_hpricot(content, base_url, parent_url) return absolutize_page(content, base_url, parent_url) if RUBY_PLATFORM == 'java' begin require 'hpricot' doc = Hpricot(content) base_url.slice!(-1) if ends_with?(base_url, "/") (doc/'link').each { |e| e['href'] = absolutify_url(e['href'], base_url, parent_url) || "" } (doc/'img').each { |e| e['src'] = absolutify_url(e['src'], base_url, parent_url) || "" } (doc/'script').each { |e| e['src'] = absolutify_url(e['src'], base_url, parent_url) || "" } return doc.to_html rescue => e absolutize_page(content, base_url, parent_url) end end def absolutize_page_nokogiri(content, base_url, parent_url) return absolutize_page(content, base_url, parent_url) if RUBY_PLATFORM == 'java' begin require 'nokogiri' doc = Nokogiri::HTML(content) base_url.slice!(-1) if ends_with?(base_url, "/") (doc/'link').each { |e| e['href'] = absolutify_url(e['href'], base_url, parent_url) || "" } (doc/'img').each { |e| e['src'] = absolutify_url(e['src'], base_url, parent_url) || "" } (doc/'script').each { |e| e['src'] = absolutify_url(e['src'], base_url, parent_url) || "" } return doc.to_html rescue => e absolutize_page(content, base_url, parent_url) end end ## # change # <script type="text/javascript" src="/javascripts/prototype.js"></script> # to # <script type="text/javascript" src="http://itest2.com/javascripts/prototype.js"></script> def absolutify_url(src, base_url, parent_url) if src.nil? || src.empty? || src == "//:" || src =~ /\s*http:\/\//i return src end return "#{base_url}#{src}" if src =~ /^\s*\// return "#{parent_url}#{src}" if parent_url return src end # substut def substitute_relative_path_in_src_line(line, script_src, host_url, page_parent_url) unless script_src =~ /^["']?http:/ host_url.slice!(-1) if ends_with?(host_url, "/") if script_src =~ /^\s*\// # absolute_path line.gsub!(script_src, "#{host_url}#{script_src}") else #relative_path line.gsub!(script_src, "#{page_parent_url}#{script_src}") end end end def ends_with?(str, suffix) suffix = suffix.to_s str[-suffix.length, suffix.length] == suffix end # current web page title def page_title @web_browser.page_title end # current page source (in HTML) def page_source @web_browser.page_source end # return plain text view of page def page_text @web_browser.text end # return the text of specific (identified by attribute "id") label tag # For page containing # <label id="preferred_ide">TestWise</label> # label_with_id("preferred_ids") # => TestWise # label_with_id("preferred_ids", :index => 2) # => TestWise def label_with_id(label_id, options = {}) if options && options[:index] then label(:id => label_id.to_s, :index => options[:index]).text else label(:id, label_id.to_s).text end end # return the text of specific (identified by attribute "id") span tag # For page containing # <span id="preferred_recorder">iTest2/Watir Recorder</span> # span_with_id("preferred_recorder") # => iTest2/Watir Recorder def span_with_id(span_id, options = {}) if options && options[:index] then span(:id => span_id.to_s, :index => options[:index]).text else span(:id, span_id).text end end # return the text of specific (identified by attribute "id") ta tag # For page containing # <td id="preferred_recorder">iTest2/Watir Recorder</span> # td_with_id("preferred_recorder") # => iTest2/Watir Recorder def cell_with_id(cell_id, options = {}) if options && options[:index] then cell(:id => cell_id.to_s, :index => options[:index]).text else cell(:id, cell_id).text end end alias table_data_with_id cell_with_id def is_mac? RUBY_PLATFORM.downcase.include?("darwin") end def is_windows? RUBY_PLATFORM.downcase.include?("mswin") or RUBY_PLATFORM.downcase.include?("mingw") end def is_linux? RUBY_PLATFORM.downcase.include?("linux") end # Support browser (IE) operations using unicode # Example: # click_button("Google 搜索") # Reference: http://jira.openqa.org/browse/WTR-219 def support_utf8 if is_windows? require 'win32ole' WIN32OLE.codepage = WIN32OLE::CP_UTF8 end end alias support_unicode support_utf8 # Execute the provided block until either (1) it returns true, or # (2) the timeout (in seconds) has been reached. If the timeout is reached, # a TimeOutException will be raised. The block will always # execute at least once. # # This does not handle error, if the given block raise error, the statement finish with error # Examples: # wait_until {puts 'hello'} # wait_until { div(:id, :receipt_date).exists? } # def wait_until(timeout = $testwise_polling_timeout || 30, polling_interval = $testwise_polling_interval || 1, & block) waiter = Watir::Waiter.new(timeout, polling_interval) waiter.wait_until { yield } end # Wait for specific seconds for an Ajax update finish. # Trick: In your Rails application, # :loading => "Element.show('search_indicator'); # :complete => "Element.hide('search_indicator'); # # <%= image_tag("indicator.gif", :id => 'search_indicator', :style => 'display:none') %> # # Typical usage: # ajax_wait_for_element("search_indicator", 30) # ajax_wait_for_element("search_indicator", 30, "show") # ajax_wait_for_element("search_indicator", 30, "hide") # ajax_wait_for_element("search_indicator", 30, "show", 5) # check every 5 seconds # # Warning: this method has not been fully tested, if you are not using Rails, change your parameter accordingly. # def ajax_wait_for_element(element_id, seconds, status='show', check_interval = $testwise_polling_interval) count = 0 check_interval = 1 if check_interval < 1 or check_interval > seconds while count < (seconds / check_interval) do search_indicator = @web_browser.element_by_id(element_id) search_indicator_outer_html = search_indicator.outerHtml if search_indicator if status == 'hide' return true if search_indicator_outer_html and !search_indicator_outer_html.include?('style="DISPLAY: none"') else return true if search_indicator_outer_html and search_indicator_outer_html.include?('style="DISPLAY: none"') end sleep check_interval if check_interval > 0 and check_interval < 5 * 60 # wait max 5 minutes count += 1 end return false end #Wait the element with given id to be present in web page # # Warning: this not working in Firefox, try use wait_util or try instead def wait_for_element(element_id, timeout = $testwise_polling_timeout, interval = $testwise_polling_interval) start_time = Time.now #TODO might not work with Firefox until @web_browser.element_by_id(element_id) do sleep(interval) if (Time.now - start_time) > timeout raise RuntimeError, "failed to find element: #{element_id} for max #{timeout}" end end end # Clear popup windows such as 'Security Alert' or 'Security Information' popup window, # # Screenshot see http://kb2.adobe.com/cps/165/tn_16588.html # # You can also by pass security alerts by change IE setting, http://kb.iu.edu/data/amuj.html # # Example # clear_popup("Security Information", 5, true) # check for Security Information for 5 seconds, click Yes def clear_popup(popup_win_title, seconds = 10, yes = true) # commonly "Security Alert", "Security Information" if is_windows? sleep 1 autoit = WIN32OLE.new('AutoItX3.Control') # Look for window with given title. Give up after 1 second. ret = autoit.WinWait(popup_win_title, '', seconds) # # If window found, send appropriate keystroke (e.g. {enter}, {Y}, {N}). if ret == 1 then puts "about to send click Yes" if debugging? button_id = yes ? "Button1" : "Button2" # Yes or No autoit.ControlClick(popup_win_title, '', button_id) end sleep(0.5) else raise "Currently supported only on Windows" end end # Watir 1.9 way of handling javascript dialog def javascript_dialog @web_browser.javascript_dialog end def select_file_for_upload(file_field_name, file_path) if is_windows? normalized_file_path = file_path.gsub("/", "\\") file_field(:name, file_field_name).set(normalized_file_path) else # for firefox, just call file_field, it may fail file_field(:name, file_field_name).set(normalized_file_path) end end def check_ie_version if is_windows? && @ie_version.nil? begin cmd = 'reg query "HKLM\SOFTWARE\Microsoft\Internet Explorer" /v Version'; result = `#{cmd}` version_line = nil result.each do |line| if (line =~ /Version\s+REG_SZ\s+([\d\.]+)/) version_line = $1 end end if version_line =~ /^\s*(\d+)\./ @ie_version = $1.to_i end rescue => e end end end # Use AutoIT3 to send password # title starts with "Connect to ..." def basic_authentication_ie(title, username, password, options = {}) default_options = {:textctrl_username => "Edit2", :textctrl_password => "Edit3", :button_ok => 'Button1' } options = default_options.merge(options) title ||= "" if title =~ /^Connect\sto/ full_title = title else full_title = "Connect to #{title}" end require 'rformspec' login_win = RFormSpec::Window.new(full_title) login_win.send_control_text(options[:textctrl_username], username) login_win.send_control_text(options[:textctrl_password], password) login_win.click_button("OK") end def basic_authentication(username, password, options = {}) basic_authentication_ie(options[:title], username, password, options) end # TODO: Common driver module => this is shared by both Watir and Selenium # # TODO: Common driver module => this is shared by both Watir and Selenium # # use win32screenshot library or Selenium to save curernt active window # # opts[:to_dir] => the direcotry to save image under def take_screenshot(to_file = nil, opts = {}) # puts "calling new take screenshot: #{$screenshot_supported}" # unless $screenshot_supported # puts " [WARN] Screenhost not supported, check whether win32screenshot gem is installed" # return # end if to_file screenshot_image_filepath = to_file else screenshot_image_filename = "screenshot_" + Time.now.strftime("%m%d%H%M%S") + ".jpg" the_dump_dir = opts[:to_dir] || default_dump_dir FileUtils.mkdir_p(the_dump_dir) unless File.exists?(the_dump_dir) screenshot_image_filepath = File.join(the_dump_dir, screenshot_image_filename) screenshot_image_filepath.gsub!("/", "\\") if is_windows? FileUtils.rm_f(screenshot_image_filepath) if File.exist?(screenshot_image_filepath) end begin if is_firefox? then Win32::Screenshot::Take.of(:window, :title => /mozilla\sfirefox/i).write(screenshot_image_filepath) elsif ie Win32::Screenshot::Take.of(:window, :title => /internet\sexplorer/i).write(screenshot_image_filepath) else Win32::Screenshot::Take.of(:foreground).write(screenshot_image_filepath) end notify_screenshot_location(screenshot_image_filepath) rescue ::DL::DLTypeError => de puts "No screenshot libray found: #{de}" rescue => e puts "error on taking screenshot: #{e}" end end # end of methods end
sailthru/sailthru-ruby-client
lib/sailthru/client.rb
Sailthru.Client.schedule_blast_from_blast
ruby
def schedule_blast_from_blast(blast_id, schedule_time, options={}) post = options ? options : {} post[:copy_blast] = blast_id #post[:name] = name post[:schedule_time] = schedule_time api_post(:blast, post) end
Schedule a mass mail blast from previous blast
train
https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L117-L123
class Client DEFAULT_API_URI = 'https://api.sailthru.com' include Helpers attr_accessor :verify_ssl # params: # api_key, String # secret, String # api_uri, String # # Instantiate a new client; constructor optionally takes overrides for key/secret/uri and proxy server settings. def initialize(api_key=nil, secret=nil, api_uri=nil, proxy_host=nil, proxy_port=nil, opts={}) @api_key = api_key || Sailthru.api_key || raise(ArgumentError, "You must provide an API key or call Sailthru.credentials() first") @secret = secret || Sailthru.secret || raise(ArgumentError, "You must provide your secret or call Sailthru.credentials() first") @api_uri = api_uri.nil? ? DEFAULT_API_URI : api_uri @proxy_host = proxy_host @proxy_port = proxy_port @verify_ssl = true @opts = opts @last_rate_limit_info = {} end # params: # template_name, String # email, String # vars, Hash # options, Hash # replyto: override Reply-To header # test: send as test email (subject line will be marked, will not count towards stats) # returns: # Hash, response data from server def send_email(template_name, email, vars={}, options = {}, schedule_time = nil, limit = {}) post = {} post[:template] = template_name post[:email] = email post[:vars] = vars if vars.length >= 1 post[:options] = options if options.length >= 1 post[:schedule_time] = schedule_time if !schedule_time.nil? post[:limit] = limit if limit.length >= 1 api_post(:send, post) end def multi_send(template_name, emails, vars={}, options = {}, schedule_time = nil, evars = {}) post = {} post[:template] = template_name post[:email] = emails post[:vars] = vars if vars.length >= 1 post[:options] = options if options.length >= 1 post[:schedule_time] = schedule_time if !schedule_time.nil? post[:evars] = evars if evars.length >= 1 api_post(:send, post) end # params: # send_id, Fixnum # returns: # Hash, response data from server # # Get the status of a send. def get_send(send_id) api_get(:send, {:send_id => send_id.to_s}) end def cancel_send(send_id) api_delete(:send, {:send_id => send_id.to_s}) end # params: # name, String # list, String # schedule_time, String # from_name, String # from_email, String # subject, String # content_html, String # content_text, String # options, Hash # returns: # Hash, response data from server # # Schedule a mass mail blast def schedule_blast(name, list, schedule_time, from_name, from_email, subject, content_html, content_text, options = {}) post = options ? options : {} post[:name] = name post[:list] = list post[:schedule_time] = schedule_time post[:from_name] = from_name post[:from_email] = from_email post[:subject] = subject post[:content_html] = content_html post[:content_text] = content_text api_post(:blast, post) end # Schedule a mass mail blast from template def schedule_blast_from_template(template, list, schedule_time, options={}) post = options ? options : {} post[:copy_template] = template post[:list] = list post[:schedule_time] = schedule_time api_post(:blast, post) end # Schedule a mass mail blast from previous blast # params # blast_id, Fixnum | String # name, String # list, String # schedule_time, String # from_name, String # from_email, String # subject, String # content_html, String # content_text, String # options, hash # # updates existing blast def update_blast(blast_id, name = nil, list = nil, schedule_time = nil, from_name = nil, from_email = nil, subject = nil, content_html = nil, content_text = nil, options = {}) data = options ? options : {} data[:blast_id] = blast_id if name != nil data[:name] = name end if list != nil data[:list] = list end if schedule_time != nil data[:schedule_time] = schedule_time end if from_name != nil data[:from_name] = from_name end if from_email != nil data[:from_email] = from_email end if subject != nil data[:subject] = subject end if content_html != nil data[:content_html] = content_html end if content_text != nil data[:content_text] = content_text end api_post(:blast, data) end # params: # blast_id, Fixnum | String # options, hash # returns: # Hash, response data from server # # Get information on a previously scheduled email blast def get_blast(blast_id, options={}) options[:blast_id] = blast_id.to_s api_get(:blast, options) end # params: # blast_id, Fixnum | String # # Cancel a scheduled Blast def cancel_blast(blast_id) api_post(:blast, {:blast_id => blast_id, :schedule_time => ''}) end # params: # blast_id, Fixnum | String # # Delete a Blast def delete_blast(blast_id) api_delete(:blast, {:blast_id => blast_id}) end # params: # email, String # returns: # Hash, response data from server # # Return information about an email address, including replacement vars and lists. def get_email(email) api_get(:email, {:email => email}) end # params: # email, String # vars, Hash # lists, Hash mapping list name => 1 for subscribed, 0 for unsubscribed # options, Hash mapping optional parameters # returns: # Hash, response data from server # # Set replacement vars and/or list subscriptions for an email address. def set_email(email, vars = {}, lists = {}, templates = {}, options = {}) data = options data[:email] = email data[:vars] = vars unless vars.empty? data[:lists] = lists unless lists.empty? data[:templates] = templates unless templates.empty? api_post(:email, data) end # params: # new_email, String # old_email, String # options, Hash mapping optional parameters # returns: # Hash of response data. # # change a user's email address. def change_email(new_email, old_email, options = {}) data = options data[:email] = new_email data[:change_email] = old_email api_post(:email, data) end # returns: # Hash of response data. # # Get all templates def get_templates(templates = {}) api_get(:template, templates) end # params: # template_name, String # returns: # Hash of response data. # # Get a template. def get_template(template_name) api_get(:template, {:template => template_name}) end # params: # template_name, String # template_fields, Hash # returns: # Hash containg response from the server. # # Save a template. def save_template(template_name, template_fields) data = template_fields data[:template] = template_name api_post(:template, data) end # params: # template_name, String # returns: # Hash of response data. # # Delete a template. def delete_template(template_name) api_delete(:template, {:template => template_name}) end # params: # params, Hash # request, String # returns: # boolean, Returns true if the incoming request is an authenticated verify post. def receive_verify_post(params, request) if request.post? [:action, :email, :send_id, :sig].each { |key| return false unless params.has_key?(key) } return false unless params[:action] == :verify sig = params.delete(:sig) params.delete(:controller) return false unless sig == get_signature_hash(params, @secret) _send = get_send(params[:send_id]) return false unless _send.has_key?('email') return false unless _send['email'] == params[:email] return true else return false end end # params: # params, Hash # request, String # returns: # TrueClass or FalseClass, Returns true if the incoming request is an authenticated optout post. def receive_optout_post(params, request) if request.post? [:action, :email, :sig].each { |key| return false unless params.has_key?(key) } return false unless params[:action] == 'optout' sig = params.delete(:sig) params.delete(:controller) sig == get_signature_hash(params, @secret) else false end end # List Postbacks must be enabled by Sailthru # Contact your account manager or contact support to have this enabled # # params: # params, Hash # request, String # returns: # TrueClass or FalseClass, Returns true if the incoming request is an authenticated list post. def receive_list_post(params, request) if request.post? [:action, :email, :sig].each { |key| return false unless params.has_key?(key) } return false unless params[:action] == 'update' sig = params.delete(:sig) params.delete(:controller) sig == get_signature_hash(params, @secret) else false end end # params: # params, Hash # request, String # returns: # TrueClass or FalseClass, Returns true if the incoming request is an authenticated hardbounce post. def receive_hardbounce_post(params, request) if request.post? [:action, :email, :sig].each { |key| return false unless params.has_key?(key) } return false unless params[:action] == 'hardbounce' sig = params.delete(:sig) params.delete(:controller) sig == get_signature_hash(params, @secret) else false end end # params: # email, String # items, Array of Hashes # incomplete, Integer # message_id, String # options, Hash # returns: # hash, response from server # # Record that a user has made a purchase, or has added items to their purchase total. def purchase(email, items, incomplete = nil, message_id = nil, options = {}) data = options data[:email] = email data[:items] = items if incomplete != nil data[:incomplete] = incomplete.to_i end if message_id != nil data[:message_id] = message_id end api_post(:purchase, data) end # <b>DEPRECATED:</b> Please use either stats_list or stats_blast # params: # stat, String # # returns: # hash, response from server # Request various stats from Sailthru. def get_stats(stat) warn "[DEPRECATION] `get_stats` is deprecated. Please use `stats_list` and `stats_blast` instead" api_get(:stats, {:stat => stat}) end # params # list, String # date, String # # returns: # hash, response from server # Retrieve information about your subscriber counts on a particular list, on a particular day. def stats_list(list = nil, date = nil) data = {} if list != nil data[:list] = list end if date != nil data[:date] = date end data[:stat] = 'list' api_get(:stats, data) end # params # blast_id, String # start_date, String # end_date, String # options, Hash # # returns: # hash, response from server # Retrieve information about a particular blast or aggregated information from all of blasts over a specified date range def stats_blast(blast_id = nil, start_date = nil, end_date = nil, options = {}) data = options if blast_id != nil data[:blast_id] = blast_id end if start_date != nil data[:start_date] = start_date end if end_date != nil data[:end_date] = end_date end data[:stat] = 'blast' api_get(:stats, data) end # params # template, String # start_date, String # end_date, String # options, Hash # # returns: # hash, response from server # Retrieve information about a particular blast or aggregated information from all of blasts over a specified date range def stats_send(template = nil, start_date = nil, end_date = nil, options = {}) data = options if template != nil data[:template] = template end if start_date != nil data[:start_date] = start_date end if end_date != nil data[:end_date] = end_date end data[:stat] = 'send' api_get(:stats, data) end # <b>DEPRECATED:</b> Please use save_content # params # title, String # url, String # date, String # tags, Array or Comma separated string # vars, Hash # options, Hash # # Push a new piece of content to Sailthru, triggering any applicable alerts. # http://docs.sailthru.com/api/content def push_content(title, url, date = nil, tags = nil, vars = {}, options = {}) data = options data[:title] = title data[:url] = url if date != nil data[:date] = date end if tags != nil if tags.class == Array tags = tags.join(',') end data[:tags] = tags end if vars.length > 0 data[:vars] = vars end api_post(:content, data) end # params # id, String – An identifier for the item (by default, the item’s URL). # options, Hash - Containing any of the parameters described on # https://getstarted.sailthru.com/developers/api/content/#POST_Mode # # Push a new piece of content to Sailthru, triggering any applicable alerts. # http://docs.sailthru.com/api/content def save_content(id, options) data = options data[:id] = id data[:tags] = data[:tags].join(',') if data[:tags].respond_to?(:join) api_post(:content, data) end # params # list, String # # Get information about a list. def get_list(list) api_get(:list, {:list => list}) end # params # # Get information about all lists def get_lists api_get(:list, {}) end # params # list, String # options, Hash # Create a list, or update a list. def save_list(list, options = {}) data = options data[:list] = list api_post(:list, data) end # params # list, String # # Deletes a list def delete_list(list) api_delete(:list, {:list => list}) end # params # email, String # # get user alert data def get_alert(email) api_get(:alert, {:email => email}) end # params # email, String # type, String # template, String # _when, String # options, hash # # Add a new alert to a user. You can add either a realtime or a summary alert (daily/weekly). # _when is only required when alert type is weekly or daily def save_alert(email, type, template, _when = nil, options = {}) data = options data[:email] = email data[:type] = type data[:template] = template if (type == 'weekly' || type == 'daily') data[:when] = _when end api_post(:alert, data) end # params # email, String # alert_id, String # # delete user alert def delete_alert(email, alert_id) data = {:email => email, :alert_id => alert_id} api_delete(:alert, data) end # params # job, String # options, hash # report_email, String # postback_url, String # binary_key, String # # interface for making request to job call def process_job(job, options = {}, report_email = nil, postback_url = nil, binary_key = nil) data = options data['job'] = job if !report_email.nil? data['report_email'] = report_email end if !postback_url.nil? data['postback_url'] = postback_url end api_post(:job, data, binary_key) end # params # emails, String | Array # implementation for import_job def process_import_job(list, emails, report_email = nil, postback_url = nil, options = {}) data = options data['list'] = list data['emails'] = Array(emails).join(',') process_job(:import, data, report_email, postback_url) end # implementation for import job using file upload def process_import_job_from_file(list, file_path, report_email = nil, postback_url = nil, options = {}) data = options data['list'] = list data['file'] = file_path process_job(:import, data, report_email, postback_url, 'file') end # implementation for update job using file upload def process_update_job_from_file(file_path, report_email = nil, postback_url = nil, options = {}) data = options data['file'] = file_path process_job(:update, data, report_email, postback_url, 'file') end # implementation for purchase import job using file upload def process_purchase_import_job_from_file(file_path, report_email = nil, postback_url = nil, options = {}) data = options data['file'] = file_path process_job(:purchase_import, data, report_email, postback_url, 'file') end # implementation for snapshot job def process_snapshot_job(query = {}, report_email = nil, postback_url = nil, options = {}) data = options data['query'] = query process_job(:snapshot, data, report_email, postback_url) end # implementation for export list job def process_export_list_job(list, report_email = nil, postback_url = nil, options = {}) data = options data['list'] = list process_job(:export_list_data, data, report_email, postback_url) end # get status of a job def get_job_status(job_id) api_get(:job, {'job_id' => job_id}) end # Get user by Sailthru ID def get_user_by_sid(id, fields = {}) api_get(:user, {'id' => id, 'fields' => fields}) end # Get user by specified key def get_user_by_key(id, key, fields = {}) data = { 'id' => id, 'key' => key, 'fields' => fields } api_get(:user, data) end # Create new user, or update existing user def save_user(id, options = {}) data = options data['id'] = id api_post(:user, data) end # params # Get an existing trigger def get_triggers api_get(:trigger, {}) end # params # template, String # trigger_id, String # Get an existing trigger def get_trigger_by_template(template, trigger_id = nil) data = {} data['template'] = template if trigger_id != nil then data['trigger_id'] = trigger_id end api_get(:trigger, data) end # params # event, String # Get an existing trigger def get_trigger_by_event(event) data = {} data['event'] = event api_get(:trigger, data) end # params # template, String # time, String # time_unit, String # event, String # zephyr, String # Create or update a trigger def post_template_trigger(template, time, time_unit, event, zephyr) data = {} data['template'] = template data['time'] = time data['time_unit'] = time_unit data['event'] = event data['zephyr'] = zephyr api_post(:trigger, data) end # params # template, String # time, String # time_unit, String # zephyr, String # Create or update a trigger def post_event_trigger(event, time, time_unit, zephyr) data = {} data['time'] = time data['time_unit'] = time_unit data['event'] = event data['zephyr'] = zephyr api_post(:trigger, data) end # params # id, String # event, String # options, Hash (Can contain vars, Hash and/or key) # Notify Sailthru of an Event def post_event(id, event, options = {}) data = options data['id'] = id data['event'] = event api_post(:event, data) end # Perform API GET request def api_get(action, data) api_request(action, data, 'GET') end # Perform API POST request def api_post(action, data, binary_key = nil) api_request(action, data, 'POST', binary_key) end #Perform API DELETE request def api_delete(action, data) api_request(action, data, 'DELETE') end # params # endpoint, String a e.g. "user" or "send" # method, String "GET" or "POST" # returns # Hash rate info # Get rate info for a particular endpoint/method, as of the last time a request was sent to the given endpoint/method # Includes the following keys: # limit: the per-minute limit for the given endpoint/method # remaining: the number of allotted requests remaining in the current minute for the given endpoint/method # reset: unix timestamp of the top of the next minute, when the rate limit will reset def get_last_rate_limit_info(endpoint, method) rate_info_key = get_rate_limit_info_key(endpoint, method) @last_rate_limit_info[rate_info_key] end protected # params: # action, String # data, Hash # request, String "GET" or "POST" # returns: # Hash # # Perform an API request, using the shared-secret auth hash. # def api_request(action, data, request_type, binary_key = nil) if !binary_key.nil? binary_key_data = data[binary_key] data.delete(binary_key) end if data[:format].nil? || data[:format] == 'json' data = prepare_json_payload(data) else data[:api_key] = @api_key data[:format] ||= 'json' data[:sig] = get_signature_hash(data, @secret) end if !binary_key.nil? data[binary_key] = binary_key_data end _result = http_request(action, data, request_type, binary_key) # NOTE: don't do the unserialize here if data[:format] == 'json' begin unserialized = JSON.parse(_result) return unserialized ? unserialized : _result rescue JSON::JSONError => e return {'error' => e} end end _result end # set up our post request def set_up_post_request(uri, data, headers, binary_key = nil) if !binary_key.nil? binary_data = data[binary_key] if binary_data.is_a?(StringIO) data[binary_key] = UploadIO.new( binary_data, "text/plain", "local.path" ) else data[binary_key] = UploadIO.new( File.open(binary_data), "text/plain" ) end req = Net::HTTP::Post::Multipart.new(uri.path, data) else req = Net::HTTP::Post.new(uri.path, headers) req.set_form_data(data) end req end # params: # uri, String # data, Hash # method, String "GET" or "POST" # returns: # String, body of response def http_request(action, data, method = 'POST', binary_key = nil) data = flatten_nested_hash(data, false) uri = "#{@api_uri}/#{action}" if method != 'POST' uri += "?" + data.map{ |key, value| "#{CGI::escape(key.to_s)}=#{CGI::escape(value.to_s)}" }.join("&") end req = nil headers = {"User-Agent" => "Sailthru API Ruby Client #{Sailthru::VERSION}"} _uri = URI.parse(uri) if method == 'POST' req = set_up_post_request( _uri, data, headers, binary_key ) else request_uri = "#{_uri.path}?#{_uri.query}" if method == 'DELETE' req = Net::HTTP::Delete.new(request_uri, headers) else req = Net::HTTP::Get.new(request_uri, headers) end end begin http = Net::HTTP::Proxy(@proxy_host, @proxy_port).new(_uri.host, _uri.port) if _uri.scheme == 'https' http.ssl_version = :TLSv1 http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE if @verify_ssl != true # some openSSL client doesn't work without doing this http.ssl_timeout = @opts[:http_ssl_timeout] || 5 end http.open_timeout = @opts[:http_open_timeout] || 5 http.read_timeout = @opts[:http_read_timeout] || 10 http.close_on_empty_response = @opts[:http_close_on_empty_response] || true response = http.start do http.request(req) end rescue Timeout::Error, Errno::ETIMEDOUT => e raise UnavailableError, "Timed out: #{_uri}" rescue => e raise ClientError, "Unable to open stream to #{_uri}: #{e.message}" end save_rate_limit_info(action, method, response) response.body || raise(ClientError, "No response received from stream: #{_uri}") end def http_multipart_request(uri, data) Net::HTTP::Post::Multipart.new url.path, "file" => UploadIO.new(data['file'], "application/octet-stream") end def prepare_json_payload(data) payload = { :api_key => @api_key, :format => 'json', #<3 XML :json => data.to_json } payload[:sig] = get_signature_hash(payload, @secret) payload end def save_rate_limit_info(action, method, response) limit = response['x-rate-limit-limit'].to_i remaining = response['x-rate-limit-remaining'].to_i reset = response['x-rate-limit-reset'].to_i if limit.nil? or remaining.nil? or reset.nil? return end rate_info_key = get_rate_limit_info_key(action, method) @last_rate_limit_info[rate_info_key] = { limit: limit, remaining: remaining, reset: reset } end def get_rate_limit_info_key(endpoint, method) :"#{endpoint}_#{method.downcase}" end end
rmagick/rmagick
lib/rmagick_internal.rb
Magick.ImageList.scene=
ruby
def scene=(n) if n.nil? Kernel.raise IndexError, 'scene number out of bounds' unless @images.length.zero? @scene = nil return @scene elsif @images.length.zero? Kernel.raise IndexError, 'scene number out of bounds' end n = Integer(n) Kernel.raise IndexError, 'scene number out of bounds' if n < 0 || n > length - 1 @scene = n @scene end
Allow scene to be set to nil
train
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L1271-L1284
class ImageList include Comparable include Enumerable attr_reader :scene private def get_current @images[@scene].__id__ rescue StandardError nil end protected def is_an_image(obj) Kernel.raise ArgumentError, "Magick::Image required (#{obj.class} given)" unless obj.is_a? Magick::Image true end # Ensure array is always an array of Magick::Image objects def is_an_image_array(ary) Kernel.raise ArgumentError, "Magick::ImageList or array of Magick::Images required (#{ary.class} given)" unless ary.respond_to? :each ary.each { |obj| is_an_image obj } true end # Find old current image, update scene number # current is the id of the old current image. def set_current(current) if length.zero? self.scene = nil return # Don't bother looking for current image elsif scene.nil? || scene >= length self.scene = length - 1 return elsif !current.nil? # Find last instance of "current" in the list. # If "current" isn't in the list, set current to last image. self.scene = length - 1 each_with_index do |f, i| self.scene = i if f.__id__ == current end return end self.scene = length - 1 end public # Allow scene to be set to nil # All the binary operators work the same way. # 'other' should be either an ImageList or an Array %w[& + - |].each do |op| module_eval <<-END_BINOPS def #{op}(other) ilist = self.class.new begin a = other #{op} @images rescue TypeError Kernel.raise ArgumentError, "Magick::ImageList expected, got " + other.class.to_s end current = get_current() a.each do |image| is_an_image image ilist << image end ilist.set_current current return ilist end END_BINOPS end def *(other) Kernel.raise ArgumentError, "Integer required (#{other.class} given)" unless other.is_a? Integer current = get_current ilist = self.class.new (@images * other).each { |image| ilist << image } ilist.set_current current ilist end def <<(obj) is_an_image obj @images << obj @scene = @images.length - 1 self end # Compare ImageLists # Compare each image in turn until the result of a comparison # is not 0. If all comparisons return 0, then # return if A.scene != B.scene # return A.length <=> B.length def <=>(other) Kernel.raise TypeError, "#{self.class} required (#{other.class} given)" unless other.is_a? self.class size = [length, other.length].min size.times do |x| r = self[x] <=> other[x] return r unless r.zero? end return 0 if @scene.nil? && other.scene.nil? Kernel.raise TypeError, "cannot convert nil into #{other.scene.class}" if @scene.nil? && !other.scene.nil? Kernel.raise TypeError, "cannot convert nil into #{scene.class}" if !@scene.nil? && other.scene.nil? r = scene <=> other.scene return r unless r.zero? length <=> other.length end def [](*args) a = @images[*args] if a.respond_to?(:each) ilist = self.class.new a.each { |image| ilist << image } a = ilist end a end def []=(*args) obj = @images.[]=(*args) if obj && obj.respond_to?(:each) is_an_image_array(obj) set_current obj.last.__id__ elsif obj is_an_image(obj) set_current obj.__id__ else set_current nil end obj end %i[at each each_index empty? fetch first hash include? index length rindex sort!].each do |mth| module_eval <<-END_SIMPLE_DELEGATES def #{mth}(*args, &block) @images.#{mth}(*args, &block) end END_SIMPLE_DELEGATES end alias size length # Array#nitems is not available in 1.9 if Array.instance_methods.include?('nitems') def nitems @images.nitems end end def clear @scene = nil @images.clear end def clone ditto = dup ditto.freeze if frozen? ditto end # override Enumerable#collect def collect(&block) current = get_current a = @images.collect(&block) ilist = self.class.new a.each { |image| ilist << image } ilist.set_current current ilist end def collect!(&block) @images.collect!(&block) is_an_image_array @images self end # Make a deep copy def copy ditto = self.class.new @images.each { |f| ditto << f.copy } ditto.scene = @scene ditto.taint if tainted? ditto end # Return the current image def cur_image Kernel.raise IndexError, 'no images in this list' unless @scene @images[@scene] end # ImageList#map took over the "map" name. Use alternatives. alias __map__ collect alias map! collect! alias __map__! collect! # ImageMagic used affinity in 6.4.3, switch to remap in 6.4.4. alias affinity remap def compact current = get_current ilist = self.class.new a = @images.compact a.each { |image| ilist << image } ilist.set_current current ilist end def compact! current = get_current a = @images.compact! # returns nil if no changes were made set_current current a.nil? ? nil : self end def concat(other) is_an_image_array other other.each { |image| @images << image } @scene = length - 1 self end # Set same delay for all images def delay=(d) raise ArgumentError, 'delay must be greater than or equal to 0' if Integer(d) < 0 @images.each { |f| f.delay = Integer(d) } end def delete(obj, &block) is_an_image obj current = get_current a = @images.delete(obj, &block) set_current current a end def delete_at(ndx) current = get_current a = @images.delete_at(ndx) set_current current a end def delete_if(&block) current = get_current @images.delete_if(&block) set_current current self end def dup ditto = self.class.new @images.each { |img| ditto << img } ditto.scene = @scene ditto.taint if tainted? ditto end def eql?(other) is_an_image_array other eql = other.eql?(@images) begin # "other" is another ImageList eql &&= @scene == other.scene rescue NoMethodError # "other" is a plain Array end eql end def fill(*args, &block) is_an_image args[0] unless block_given? current = get_current @images.fill(*args, &block) is_an_image_array self set_current current self end # Override Enumerable's find_all def find_all(&block) current = get_current a = @images.find_all(&block) ilist = self.class.new a.each { |image| ilist << image } ilist.set_current current ilist end alias select find_all def from_blob(*blobs, &block) Kernel.raise ArgumentError, 'no blobs given' if blobs.length.zero? blobs.each do |b| Magick::Image.from_blob(b, &block).each { |n| @images << n } end @scene = length - 1 self end # Initialize new instances def initialize(*filenames, &block) @images = [] @scene = nil filenames.each do |f| Magick::Image.read(f, &block).each { |n| @images << n } end if length > 0 @scene = length - 1 # last image in array end self end def insert(index, *args) args.each { |image| is_an_image image } current = get_current @images.insert(index, *args) set_current current self end # Call inspect for all the images def inspect img = [] @images.each { |image| img << image.inspect } img = '[' + img.join(",\n") + "]\nscene=#{@scene}" end # Set the number of iterations of an animated GIF def iterations=(n) n = Integer(n) Kernel.raise ArgumentError, 'iterations must be between 0 and 65535' if n < 0 || n > 65_535 @images.each { |f| f.iterations = n } self end def last(*args) if args.length.zero? a = @images.last else a = @images.last(*args) ilist = self.class.new a.each { |img| ilist << img } @scene = a.length - 1 a = ilist end a end # Custom marshal/unmarshal for Ruby 1.8. def marshal_dump ary = [@scene] @images.each { |i| ary << Marshal.dump(i) } ary end def marshal_load(ary) @scene = ary.shift @images = [] ary.each { |a| @images << Marshal.load(a) } end # The ImageList class supports the Magick::Image class methods by simply sending # the method to the current image. If the method isn't explicitly supported, # send it to the current image in the array. If there are no images, send # it up the line. Catch a NameError and emit a useful message. def method_missing(meth_id, *args, &block) if @scene @images[@scene].send(meth_id, *args, &block) else super end rescue NoMethodError Kernel.raise NoMethodError, "undefined method `#{meth_id.id2name}' for #{self.class}" rescue Exception $ERROR_POSITION.delete_if { |s| /:in `send'$/.match(s) || /:in `method_missing'$/.match(s) } Kernel.raise end # Create a new image and add it to the end def new_image(cols, rows, *fill, &info_blk) self << Magick::Image.new(cols, rows, *fill, &info_blk) end def partition(&block) a = @images.partition(&block) t = self.class.new a[0].each { |img| t << img } t.set_current nil f = self.class.new a[1].each { |img| f << img } f.set_current nil [t, f] end # Ping files and concatenate the new images def ping(*files, &block) Kernel.raise ArgumentError, 'no files given' if files.length.zero? files.each do |f| Magick::Image.ping(f, &block).each { |n| @images << n } end @scene = length - 1 self end def pop current = get_current a = @images.pop # can return nil set_current current a end def push(*objs) objs.each do |image| is_an_image image @images << image end @scene = length - 1 self end # Read files and concatenate the new images def read(*files, &block) Kernel.raise ArgumentError, 'no files given' if files.length.zero? files.each do |f| Magick::Image.read(f, &block).each { |n| @images << n } end @scene = length - 1 self end # override Enumerable's reject def reject(&block) current = get_current ilist = self.class.new a = @images.reject(&block) a.each { |image| ilist << image } ilist.set_current current ilist end def reject!(&block) current = get_current a = @images.reject!(&block) @images = a unless a.nil? set_current current a.nil? ? nil : self end def replace(other) is_an_image_array other current = get_current @images.clear other.each { |image| @images << image } @scene = length.zero? ? nil : 0 set_current current self end # Ensure respond_to? answers correctly when we are delegating to Image alias __respond_to__? respond_to? def respond_to?(meth_id, priv = false) return true if __respond_to__?(meth_id, priv) if @scene @images[@scene].respond_to?(meth_id, priv) else super end end def reverse current = get_current a = self.class.new @images.reverse_each { |image| a << image } a.set_current current a end def reverse! current = get_current @images.reverse! set_current current self end def reverse_each @images.reverse_each { |image| yield(image) } self end def shift current = get_current a = @images.shift set_current current a end def slice(*args) slice = @images.slice(*args) if slice ilist = self.class.new if slice.respond_to?(:each) slice.each { |image| ilist << image } else ilist << slice end else ilist = nil end ilist end def slice!(*args) current = get_current a = @images.slice!(*args) set_current current a end def ticks_per_second=(t) Kernel.raise ArgumentError, 'ticks_per_second must be greater than or equal to 0' if Integer(t) < 0 @images.each { |f| f.ticks_per_second = Integer(t) } end def to_a a = [] @images.each { |image| a << image } a end def uniq current = get_current a = self.class.new @images.uniq.each { |image| a << image } a.set_current current a end def uniq!(*_args) current = get_current a = @images.uniq! set_current current a.nil? ? nil : self end # @scene -> new object def unshift(obj) is_an_image obj @images.unshift(obj) @scene = 0 self end def values_at(*args) a = @images.values_at(*args) a = self.class.new @images.values_at(*args).each { |image| a << image } a.scene = a.length - 1 a end alias indexes values_at alias indices values_at end # Magick::ImageList
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.find_one_and_replace
ruby
def find_one_and_replace(filter, replacement, options = {}) find(filter, options).find_one_and_update(replacement, options) end
Finds a single document and replaces it, returning the original doc unless otherwise specified. @example Find a document and replace it, returning the original. collection.find_one_and_replace({ name: 'test' }, { name: 'test1' }) @example Find a document and replace it, returning the new document. collection.find_one_and_replace({ name: 'test' }, { name: 'test1' }, :return_document => :after) @param [ Hash ] filter The filter to use. @param [ BSON::Document ] replacement The replacement document. @param [ Hash ] options The options. @option options [ Integer ] :max_time_ms The maximum amount of time to allow the command to run in milliseconds. @option options [ Hash ] :projection The fields to include or exclude in the returned doc. @option options [ Hash ] :sort The key and direction pairs by which the result set will be sorted. @option options [ Symbol ] :return_document Either :before or :after. @option options [ true, false ] :upsert Whether to upsert if the document doesn't exist. @option options [ true, false ] :bypass_document_validation Whether or not to skip document level validation. @option options [ Hash ] :write_concern The write concern options. Defaults to the collection's write concern. @option options [ Hash ] :collation The collation to use. @option options [ Session ] :session The session to use. @return [ BSON::Document ] The document. @since 2.1.0
train
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L759-L761
class Collection extend Forwardable include Retryable # The capped option. # # @since 2.1.0 CAPPED = 'capped'.freeze # The ns field constant. # # @since 2.1.0 NS = 'ns'.freeze # @return [ Mongo::Database ] The database the collection resides in. attr_reader :database # @return [ String ] The name of the collection. attr_reader :name # @return [ Hash ] The collection options. attr_reader :options # Get client, cluster, read preference, and write concern from client. def_delegators :database, :client, :cluster # Delegate to the cluster for the next primary. def_delegators :cluster, :next_primary # Options that can be updated on a new Collection instance via the #with method. # # @since 2.1.0 CHANGEABLE_OPTIONS = [ :read, :read_concern, :write ].freeze # Check if a collection is equal to another object. Will check the name and # the database for equality. # # @example Check collection equality. # collection == other # # @param [ Object ] other The object to check. # # @return [ true, false ] If the objects are equal. # # @since 2.0.0 def ==(other) return false unless other.is_a?(Collection) name == other.name && database == other.database && options == other.options end # Instantiate a new collection. # # @example Instantiate a new collection. # Mongo::Collection.new(database, 'test') # # @param [ Mongo::Database ] database The collection's database. # @param [ String, Symbol ] name The collection name. # @param [ Hash ] options The collection options. # # @since 2.0.0 def initialize(database, name, options = {}) raise Error::InvalidCollectionName.new unless name @database = database @name = name.to_s.freeze @options = options.freeze end # Get the read concern for this collection instance. # # @example Get the read concern. # collection.read_concern # # @return [ Hash ] The read concern. # # @since 2.2.0 def read_concern options[:read_concern] || database.read_concern end # Get the server selector on this collection. # # @example Get the server selector. # collection.server_selector # # @return [ Mongo::ServerSelector ] The server selector. # # @since 2.0.0 def server_selector @server_selector ||= ServerSelector.get(read_preference || database.server_selector) end # Get the read preference on this collection. # # @example Get the read preference. # collection.read_preference # # @return [ Hash ] The read preference. # # @since 2.0.0 def read_preference @read_preference ||= options[:read] || database.read_preference end # Get the write concern on this collection. # # @example Get the write concern. # collection.write_concern # # @return [ Mongo::WriteConcern ] The write concern. # # @since 2.0.0 def write_concern @write_concern ||= WriteConcern.get(options[:write] || database.write_concern) end # Provides a new collection with either a new read preference or new write concern # merged over the existing read preference / write concern. # # @example Get a collection with changed read preference. # collection.with(:read => { :mode => :primary_preferred }) # # @example Get a collection with changed write concern. # collection.with(:write => { w: 3 }) # @param [ Hash ] new_options The new options to use. # # @return [ Mongo::Collection ] A new collection instance. # # @since 2.1.0 def with(new_options) new_options.keys.each do |k| raise Error::UnchangeableCollectionOption.new(k) unless CHANGEABLE_OPTIONS.include?(k) end Collection.new(database, name, options.merge(new_options)) end # Is the collection capped? # # @example Is the collection capped? # collection.capped? # # @return [ true, false ] If the collection is capped. # # @since 2.0.0 def capped? database.command(:collstats => name).documents[0][CAPPED] end # Force the collection to be created in the database. # # @example Force the collection to be created. # collection.create # # @param [ Hash ] opts The options for the create operation. # # @option options [ Session ] :session The session to use for the operation. # # @return [ Result ] The result of the command. # # @since 2.0.0 def create(opts = {}) operation = { :create => name }.merge(options) operation.delete(:write) server = next_primary if (options[:collation] || options[Operation::COLLATION]) && !server.features.collation_enabled? raise Error::UnsupportedCollation.new end client.send(:with_session, opts) do |session| Operation::Create.new({ selector: operation, db_name: database.name, write_concern: write_concern, session: session }).execute(server) end end # Drop the collection. Will also drop all indexes associated with the # collection. # # @note An error returned if the collection doesn't exist is suppressed. # # @example Drop the collection. # collection.drop # # @param [ Hash ] opts The options for the drop operation. # # @option options [ Session ] :session The session to use for the operation. # # @return [ Result ] The result of the command. # # @since 2.0.0 def drop(opts = {}) client.send(:with_session, opts) do |session| Operation::Drop.new({ selector: { :drop => name }, db_name: database.name, write_concern: write_concern, session: session }).execute(next_primary) end rescue Error::OperationFailure => ex raise ex unless ex.message =~ /ns not found/ false end # Find documents in the collection. # # @example Find documents in the collection by a selector. # collection.find(name: 1) # # @example Get all documents in a collection. # collection.find # # @param [ Hash ] filter The filter to use in the find. # @param [ Hash ] options The options for the find. # # @option options [ true, false ] :allow_partial_results Allows the query to get partial # results if some shards are down. # @option options [ Integer ] :batch_size The number of documents returned in each batch # of results from MongoDB. # @option options [ String ] :comment Associate a comment with the query. # @option options [ :tailable, :tailable_await ] :cursor_type The type of cursor to use. # @option options [ Integer ] :limit The max number of docs to return from the query. # @option options [ Integer ] :max_time_ms The maximum amount of time to allow the query # to run in milliseconds. # @option options [ Hash ] :modifiers A document containing meta-operators modifying the # output or behavior of a query. # @option options [ true, false ] :no_cursor_timeout The server normally times out idle # cursors after an inactivity period (10 minutes) to prevent excess memory use. # Set this option to prevent that. # @option options [ true, false ] :oplog_replay Internal replication use only - driver # should not set. # @option options [ Hash ] :projection The fields to include or exclude from each doc # in the result set. # @option options [ Integer ] :skip The number of docs to skip before returning results. # @option options [ Hash ] :sort The key and direction pairs by which the result set # will be sorted. # @option options [ Hash ] :collation The collation to use. # @option options [ Session ] :session The session to use. # # @return [ CollectionView ] The collection view. # # @since 2.0.0 def find(filter = nil, options = {}) View.new(self, filter || {}, options) end # Perform an aggregation on the collection. # # @example Perform an aggregation. # collection.aggregate([ { "$group" => { "_id" => "$city", "tpop" => { "$sum" => "$pop" }}} ]) # # @param [ Array<Hash> ] pipeline The aggregation pipeline. # @param [ Hash ] options The aggregation options. # # @option options [ true, false ] :allow_disk_use Set to true if disk usage is allowed during # the aggregation. # @option options [ Integer ] :batch_size The number of documents to return per batch. # @option options [ Integer ] :max_time_ms The maximum amount of time in milliseconds to allow the # aggregation to run. # @option options [ true, false ] :use_cursor Indicates whether the command will request that the server # provide results using a cursor. Note that as of server version 3.6, aggregations always provide results # using a cursor and this option is therefore not valid. # @option options [ true, false ] :bypass_document_validation Whether or # not to skip document level validation. # @option options [ Hash ] :collation The collation to use. # @option options [ String ] :comment Associate a comment with the aggregation. # @option options [ Session ] :session The session to use. # # @return [ Aggregation ] The aggregation object. # # @since 2.1.0 def aggregate(pipeline, options = {}) View.new(self, {}, options).aggregate(pipeline, options) end # As of version 3.6 of the MongoDB server, a ``$changeStream`` pipeline # stage is supported in the aggregation framework. This stage allows users # to request that notifications are sent for all changes to a particular # collection. # # @example Get change notifications for a given collection. # collection.watch([{ '$match' => { operationType: { '$in' => ['insert', 'replace'] } } }]) # # @param [ Array<Hash> ] pipeline Optional additional filter operators. # @param [ Hash ] options The change stream options. # # @option options [ String ] :full_document Allowed values: ‘default’, # ‘updateLookup’. Defaults to ‘default’. When set to ‘updateLookup’, # the change notification for partial updates will include both a delta # describing the changes to the document, as well as a copy of the entire # document that was changed from some time after the change occurred. # @option options [ BSON::Document, Hash ] :resume_after Specifies the # logical starting point for the new change stream. # @option options [ Integer ] :max_await_time_ms The maximum amount of time # for the server to wait on new documents to satisfy a change stream query. # @option options [ Integer ] :batch_size The number of documents to return # per batch. # @option options [ BSON::Document, Hash ] :collation The collation to use. # @option options [ Session ] :session The session to use. # @option options [ BSON::Timestamp ] :start_at_operation_time Only return # changes that occurred at or after the specified timestamp. Any command run # against the server will return a cluster time that can be used here. # Only recognized by server versions 4.0+. # # @note A change stream only allows 'majority' read concern. # @note This helper method is preferable to running a raw aggregation with # a $changeStream stage, for the purpose of supporting resumability. # # @return [ ChangeStream ] The change stream object. # # @since 2.5.0 def watch(pipeline = [], options = {}) View::ChangeStream.new(View.new(self, {}, options), pipeline, nil, options) end # Gets the number of matching documents in the collection. # # @example Get the count. # collection.count(name: 1) # # @param [ Hash ] filter A filter for matching documents. # @param [ Hash ] options The count options. # # @option options [ Hash ] :hint The index to use. # @option options [ Integer ] :limit The maximum number of documents to count. # @option options [ Integer ] :max_time_ms The maximum amount of time to allow the command to run. # @option options [ Integer ] :skip The number of documents to skip before counting. # @option options [ Hash ] :read The read preference options. # @option options [ Hash ] :collation The collation to use. # @option options [ Session ] :session The session to use. # # @return [ Integer ] The document count. # # @since 2.1.0 # # @deprecated Use #count_documents or estimated_document_count instead. However, note that the # following operators will need to be substituted when switching to #count_documents: # * $where should be replaced with $expr (only works on 3.6+) # * $near should be replaced with $geoWithin with $center # * $nearSphere should be replaced with $geoWithin with $centerSphere def count(filter = nil, options = {}) View.new(self, filter || {}, options).count(options) end # Gets the number of of matching documents in the collection. Unlike the deprecated #count # method, this will return the exact number of documents matching the filter rather than the estimate. # # @example Get the number of documents in the collection. # collection_view.count_documents # # @param [ Hash ] filter A filter for matching documents. # @param [ Hash ] options Options for the operation. # # @option opts :skip [ Integer ] The number of documents to skip. # @option opts :hint [ Hash ] Override default index selection and force # MongoDB to use a specific index for the query. Requires server version 3.6+. # @option opts :limit [ Integer ] Max number of docs to count. # @option opts :max_time_ms [ Integer ] The maximum amount of time to allow the # command to run. # @option opts [ Hash ] :read The read preference options. # @option opts [ Hash ] :collation The collation to use. # # @return [ Integer ] The document count. # # @since 2.6.0 def count_documents(filter, options = {}) View.new(self, filter, options).count_documents(options) end # Gets an estimate of the count of documents in a collection using collection metadata. # # @example Get the number of documents in the collection. # collection_view.estimated_document_count # # @param [ Hash ] options Options for the operation. # # @option opts :max_time_ms [ Integer ] The maximum amount of time to allow the command to # run. # @option opts [ Hash ] :read The read preference options. # # @return [ Integer ] The document count. # # @since 2.6.0 def estimated_document_count(options = {}) View.new(self, {}, options).estimated_document_count(options) end # Get a list of distinct values for a specific field. # # @example Get the distinct values. # collection.distinct('name') # # @param [ Symbol, String ] field_name The name of the field. # @param [ Hash ] filter The documents from which to retrieve the distinct values. # @param [ Hash ] options The distinct command options. # # @option options [ Integer ] :max_time_ms The maximum amount of time to allow the command to run. # @option options [ Hash ] :read The read preference options. # @option options [ Hash ] :collation The collation to use. # @option options [ Session ] :session The session to use. # # @return [ Array<Object> ] The list of distinct values. # # @since 2.1.0 def distinct(field_name, filter = nil, options = {}) View.new(self, filter || {}, options).distinct(field_name, options) end # Get a view of all indexes for this collection. Can be iterated or has # more operations. # # @example Get the index view. # collection.indexes # # @param [ Hash ] options Options for getting a list of all indexes. # # @option options [ Session ] :session The session to use. # # @return [ View::Index ] The index view. # # @since 2.0.0 def indexes(options = {}) Index::View.new(self, options) end # Get a pretty printed string inspection for the collection. # # @example Inspect the collection. # collection.inspect # # @return [ String ] The collection inspection. # # @since 2.0.0 def inspect "#<Mongo::Collection:0x#{object_id} namespace=#{namespace}>" end # Insert a single document into the collection. # # @example Insert a document into the collection. # collection.insert_one({ name: 'test' }) # # @param [ Hash ] document The document to insert. # @param [ Hash ] opts The insert options. # # @option opts [ Session ] :session The session to use for the operation. # # @return [ Result ] The database response wrapper. # # @since 2.0.0 def insert_one(document, opts = {}) client.send(:with_session, opts) do |session| write_with_retry(session, write_concern) do |server, txn_num| Operation::Insert.new( :documents => [ document ], :db_name => database.name, :coll_name => name, :write_concern => write_concern, :bypass_document_validation => !!opts[:bypass_document_validation], :options => opts, :id_generator => client.options[:id_generator], :session => session, :txn_num => txn_num ).execute(server) end end end # Insert the provided documents into the collection. # # @example Insert documents into the collection. # collection.insert_many([{ name: 'test' }]) # # @param [ Array<Hash> ] documents The documents to insert. # @param [ Hash ] options The insert options. # # @option options [ Session ] :session The session to use for the operation. # # @return [ Result ] The database response wrapper. # # @since 2.0.0 def insert_many(documents, options = {}) inserts = documents.map{ |doc| { :insert_one => doc }} bulk_write(inserts, options) end # Execute a batch of bulk write operations. # # @example Execute a bulk write. # collection.bulk_write(operations, options) # # @param [ Array<Hash> ] requests The bulk write requests. # @param [ Hash ] options The options. # # @option options [ true, false ] :ordered Whether the operations # should be executed in order. # @option options [ Hash ] :write_concern The write concern options. # Can be :w => Integer, :fsync => Boolean, :j => Boolean. # @option options [ true, false ] :bypass_document_validation Whether or # not to skip document level validation. # @option options [ Session ] :session The session to use for the set of operations. # # @return [ BulkWrite::Result ] The result of the operation. # # @since 2.0.0 def bulk_write(requests, options = {}) BulkWrite.new(self, requests, options).execute end # Remove a document from the collection. # # @example Remove a single document from the collection. # collection.delete_one # # @param [ Hash ] filter The filter to use. # @param [ Hash ] options The options. # # @option options [ Hash ] :collation The collation to use. # @option options [ Session ] :session The session to use. # # @return [ Result ] The response from the database. # # @since 2.1.0 def delete_one(filter = nil, options = {}) find(filter, options).delete_one(options) end # Remove documents from the collection. # # @example Remove multiple documents from the collection. # collection.delete_many # # @param [ Hash ] filter The filter to use. # @param [ Hash ] options The options. # # @option options [ Hash ] :collation The collation to use. # @option options [ Session ] :session The session to use. # # @return [ Result ] The response from the database. # # @since 2.1.0 def delete_many(filter = nil, options = {}) find(filter, options).delete_many(options) end # Execute a parallel scan on the collection view. # # Returns a list of up to cursor_count cursors that can be iterated concurrently. # As long as the collection is not modified during scanning, each document appears once # in one of the cursors' result sets. # # @example Execute a parallel collection scan. # collection.parallel_scan(2) # # @param [ Integer ] cursor_count The max number of cursors to return. # @param [ Hash ] options The parallel scan command options. # # @option options [ Integer ] :max_time_ms The maximum amount of time to allow the command # to run in milliseconds. # @option options [ Session ] :session The session to use. # # @return [ Array<Cursor> ] An array of cursors. # # @since 2.1 def parallel_scan(cursor_count, options = {}) find({}, options).send(:parallel_scan, cursor_count, options) end # Replaces a single document in the collection with the new document. # # @example Replace a single document. # collection.replace_one({ name: 'test' }, { name: 'test1' }) # # @param [ Hash ] filter The filter to use. # @param [ Hash ] replacement The replacement document.. # @param [ Hash ] options The options. # # @option options [ true, false ] :upsert Whether to upsert if the # document doesn't exist. # @option options [ true, false ] :bypass_document_validation Whether or # not to skip document level validation. # @option options [ Hash ] :collation The collation to use. # @option options [ Session ] :session The session to use. # # @return [ Result ] The response from the database. # # @since 2.1.0 def replace_one(filter, replacement, options = {}) find(filter, options).replace_one(replacement, options) end # Update documents in the collection. # # @example Update multiple documents in the collection. # collection.update_many({ name: 'test'}, '$set' => { name: 'test1' }) # # @param [ Hash ] filter The filter to use. # @param [ Hash ] update The update statement. # @param [ Hash ] options The options. # # @option options [ true, false ] :upsert Whether to upsert if the # document doesn't exist. # @option options [ true, false ] :bypass_document_validation Whether or # not to skip document level validation. # @option options [ Hash ] :collation The collation to use. # @option options [ Array ] :array_filters A set of filters specifying to which array elements # an update should apply. # @option options [ Session ] :session The session to use. # # @return [ Result ] The response from the database. # # @since 2.1.0 def update_many(filter, update, options = {}) find(filter, options).update_many(update, options) end # Update a single document in the collection. # # @example Update a single document in the collection. # collection.update_one({ name: 'test'}, '$set' => { name: 'test1'}) # # @param [ Hash ] filter The filter to use. # @param [ Hash ] update The update statement. # @param [ Hash ] options The options. # # @option options [ true, false ] :upsert Whether to upsert if the # document doesn't exist. # @option options [ true, false ] :bypass_document_validation Whether or # not to skip document level validation. # @option options [ Hash ] :collation The collation to use. # @option options [ Array ] :array_filters A set of filters specifying to which array elements # an update should apply. # @option options [ Session ] :session The session to use. # # @return [ Result ] The response from the database. # # @since 2.1.0 def update_one(filter, update, options = {}) find(filter, options).update_one(update, options) end # Finds a single document in the database via findAndModify and deletes # it, returning the original document. # # @example Find one document and delete it. # collection.find_one_and_delete(name: 'test') # # @param [ Hash ] filter The filter to use. # @param [ Hash ] options The options. # # @option options [ Integer ] :max_time_ms The maximum amount of time to allow the command # to run in milliseconds. # @option options [ Hash ] :projection The fields to include or exclude in the returned doc. # @option options [ Hash ] :sort The key and direction pairs by which the result set # will be sorted. # @option options [ Hash ] :write_concern The write concern options. # Defaults to the collection's write concern. # @option options [ Hash ] :collation The collation to use. # @option options [ Session ] :session The session to use. # # @return [ BSON::Document, nil ] The document, if found. # # @since 2.1.0 def find_one_and_delete(filter, options = {}) find(filter, options).find_one_and_delete(options) end # Finds a single document via findAndModify and updates it, returning the original doc unless # otherwise specified. # # @example Find a document and update it, returning the original. # collection.find_one_and_update({ name: 'test' }, { "$set" => { name: 'test1' }}) # # @example Find a document and update it, returning the updated document. # collection.find_one_and_update({ name: 'test' }, { "$set" => { name: 'test1' }}, :return_document => :after) # # @param [ Hash ] filter The filter to use. # @param [ BSON::Document ] update The update statement. # @param [ Hash ] options The options. # # @option options [ Integer ] :max_time_ms The maximum amount of time to allow the command # to run in milliseconds. # @option options [ Hash ] :projection The fields to include or exclude in the returned doc. # @option options [ Hash ] :sort The key and direction pairs by which the result set # will be sorted. # @option options [ Symbol ] :return_document Either :before or :after. # @option options [ true, false ] :upsert Whether to upsert if the document doesn't exist. # @option options [ true, false ] :bypass_document_validation Whether or # not to skip document level validation. # @option options [ Hash ] :write_concern The write concern options. # Defaults to the collection's write concern. # @option options [ Hash ] :collation The collation to use. # @option options [ Array ] :array_filters A set of filters specifying to which array elements # an update should apply. # @option options [ Session ] :session The session to use. # # @return [ BSON::Document ] The document. # # @since 2.1.0 def find_one_and_update(filter, update, options = {}) find(filter, options).find_one_and_update(update, options) end # Finds a single document and replaces it, returning the original doc unless # otherwise specified. # # @example Find a document and replace it, returning the original. # collection.find_one_and_replace({ name: 'test' }, { name: 'test1' }) # # @example Find a document and replace it, returning the new document. # collection.find_one_and_replace({ name: 'test' }, { name: 'test1' }, :return_document => :after) # # @param [ Hash ] filter The filter to use. # @param [ BSON::Document ] replacement The replacement document. # @param [ Hash ] options The options. # # @option options [ Integer ] :max_time_ms The maximum amount of time to allow the command # to run in milliseconds. # @option options [ Hash ] :projection The fields to include or exclude in the returned doc. # @option options [ Hash ] :sort The key and direction pairs by which the result set # will be sorted. # @option options [ Symbol ] :return_document Either :before or :after. # @option options [ true, false ] :upsert Whether to upsert if the document doesn't exist. # @option options [ true, false ] :bypass_document_validation Whether or # not to skip document level validation. # @option options [ Hash ] :write_concern The write concern options. # Defaults to the collection's write concern. # @option options [ Hash ] :collation The collation to use. # @option options [ Session ] :session The session to use. # # @return [ BSON::Document ] The document. # # @since 2.1.0 # Get the fully qualified namespace of the collection. # # @example Get the fully qualified namespace. # collection.namespace # # @return [ String ] The collection namespace. # # @since 2.0.0 def namespace "#{database.name}.#{name}" end end
bmuller/bandit
lib/bandit/extensions/view_concerns.rb
Bandit.ViewConcerns.bandit_sticky_choose
ruby
def bandit_sticky_choose(exp) name = "bandit_#{exp}".intern # choose url param with preference value = params[name].nil? ? cookies.signed[name] : params[name] # sticky choice may outlast a given alternative alternative = if Bandit.get_experiment(exp).alternatives.include?(value) value else Bandit.get_experiment(exp).choose(value) end # re-set cookie cookies.permanent.signed[name] = alternative end
stick to one alternative until user deletes cookies or changes browser
train
https://github.com/bmuller/bandit/blob/4c2528adee6ed761b3298f5b8889819ed9e04483/lib/bandit/extensions/view_concerns.rb#L27-L39
module ViewConcerns extend ActiveSupport::Concern # default choose is a session based choice def bandit_choose(exp) bandit_session_choose(exp) end # always choose something new and increase the participant count def bandit_simple_choose(exp) Bandit.get_experiment(exp).choose(nil) end # stick to one alternative for the entire browser session def bandit_session_choose(exp) name = "bandit_#{exp}".intern # choose url param with preference value = params[name].nil? ? cookies.signed[name] : params[name] # choose with default, and set cookie cookies.signed[name] = Bandit.get_experiment(exp).choose(value) end # stick to one alternative until user deletes cookies or changes browser end
rmagick/rmagick
lib/rvg/rvg.rb
Magick.RVG.ref
ruby
def ref(x, y, rw, rh) #:nodoc: translate(x, y) if x != 0 || y != 0 @width = rw if rw @height = rh if rh end
Accept #use arguments. Use (x,y) to generate an additional translate. Override @width and @height if new values are supplied.
train
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rvg/rvg.rb#L245-L249
class RVG include Stylable include Transformable include Stretchable include Embellishable include Describable include Duplicatable private # background_fill defaults to 'none'. If background_fill has been set to something # else, combine it with the background_fill_opacity. def bgfill if @background_fill.nil? color = Magick::Pixel.new(0, 0, 0, Magick::TransparentOpacity) else color = @background_fill color.opacity = (1.0 - @background_fill_opacity) * Magick::TransparentOpacity end color end def new_canvas if @background_pattern canvas = Magick::Image.new(@width, @height, @background_pattern) elsif @background_image canvas = if @width != @background_image.columns || @height != @background_image.rows case @background_position when :scaled @background_image.resize(@width, @height) when :tiled Magick::Image.new(@width, @height, Magick::TextureFill.new(@background_image)) when :fit width = @width height = @height bgcolor = bgfill @background_image.change_geometry(Magick::Geometry.new(width, height)) do |new_cols, new_rows| bg_image = @background_image.resize(new_cols, new_rows) if bg_image.columns != width || bg_image.rows != height bg = Magick::Image.new(width, height) { self.background_color = bgcolor } bg_image = bg.composite!(bg_image, Magick::CenterGravity, Magick::OverCompositeOp) end bg_image end end else @background_image.copy end else bgcolor = bgfill canvas = Magick::Image.new(Integer(@width), Integer(@height)) { self.background_color = bgcolor } end canvas[:desc] = @desc if @desc canvas[:title] = @title if @title canvas[:metadata] = @metadata if @metadata canvas end if ENV['debug_prim'] def print_gc(gc) primitives = gc.inspect.split(/\n/) indent = 0 primitives.each do |cmd| indent -= 1 if cmd['pop '] print((' ' * indent), cmd, "\n") indent += 1 if cmd['push '] end end end public WORD_SEP = / / # Regexp to separate words # The background image specified by background_image= attr_reader :background_image # The background image layout specified by background_position= attr_reader :background_position # The background fill color specified by background_fill= attr_reader :background_fill # The background fill color opacity specified by background_fill_opacity= attr_reader :background_fill_opacity # The image after drawing has completed attr_reader :canvas # For embedded RVG objects, the x-axis coordinate of the upper-left corner attr_reader :x # For embedded RVG objects, the x-axis coordinate of the upper-left corner attr_reader :y attr_reader :width, :height # Sets an image to use as the canvas background. See background_position= for layout options. def background_image=(bg_image) warn 'background_image= has no effect in nested RVG objects' if @nested raise ArgumentError, "background image must be an Image (got #{bg_image.class})" if bg_image && !bg_image.is_a?(Magick::Image) @background_image = bg_image end # Sets an object to use to fill the canvas background. # The object must have a <tt>fill</tt> method. See the <b>Fill Classes</b> # section in the RMagick doc for more information. def background_pattern=(filler) warn 'background_pattern= has no effect in nested RVG objects' if @nested @background_pattern = filler end # How to position the background image on the canvas. One of the following symbols: # [:scaled] Scale the image to the canvas width and height. # [:tiled] Tile the image across the canvas. # [:fit] Scale the image to fit within the canvas while retaining the # image proportions. Center the image on the canvas. Color any part of # the canvas not covered by the image with the background color. def background_position=(pos) warn 'background_position= has no effect in nested RVG objects' if @nested bg_pos = pos.to_s.downcase raise ArgumentError, "background position must be `scaled', `tiled', or `fit' (#{pos} given)" unless %w[scaled tiled fit].include?(bg_pos) @background_position = bg_pos.to_sym end # Sets the canvas background color. Either a Magick::Pixel or a color name. # The default fill is "none", that is, transparent black. def background_fill=(color) warn 'background_fill= has no effect in nested RVG objects' if @nested if !color.is_a?(Magick::Pixel) begin @background_fill = Magick::Pixel.from_color(color) rescue Magick::ImageMagickError raise ArgumentError, "unknown color `#{color}'" rescue TypeError raise TypeError, "cannot convert #{color.class} into Pixel" rescue StandardError raise ArgumentError, "argument must be a color name or a Pixel (got #{color.class})" end else @background_fill = color end end # Opacity of the background fill color, a number between 0.0 (transparent) and # 1.0 (opaque). The default is 1.0 when the background_fill= attribute has been set. def background_fill_opacity=(opacity) warn 'background_fill_opacity= has no effect in nested RVG objects' if @nested begin @background_fill_opacity = Float(opacity) rescue ArgumentError raise ArgumentError, "background_fill_opacity must be a number between 0 and 1 (#{opacity} given)" end end # Draw a +width+ x +height+ image. The image is specified by calling # one or more drawing methods on the RVG object. # You can group the drawing method calls in the optional associated block. # The +x+ and +y+ arguments have no meaning for the outermost RVG object. # On nested RVG objects [+x+, +y+] is the coordinate of the upper-left # corner in the containing canvas on which the nested RVG object is placed. # # Drawing occurs on a +canvas+ created by the #draw method. By default the # canvas is transparent. You can specify a different canvas with the # #background_fill= or #background_image= methods. # # RVG objects are _containers_. That is, styles and transforms defined # on the object are used by contained objects such as shapes, text, and # groups unless overridden by an inner container or the object itself. def initialize(width = nil, height = nil) super @width = width @height = height @content = Content.new @canvas = nil @background_fill = nil @background_fill_opacity = 1.0 # applies only if background_fill= is used @background_position = :scaled @background_pattern, @background_image, @desc, @title, @metadata = nil @x = 0.0 @y = 0.0 @nested = false yield(self) if block_given? end # Construct a canvas or reuse an existing canvas. # Execute drawing commands. Return the canvas. def draw raise StandardError, 'draw not permitted in nested RVG objects' if @nested @canvas ||= new_canvas # allow drawing over existing canvas gc = Utility::GraphicContext.new add_outermost_primitives(gc) pp(self) if ENV['debug_rvg'] print_gc(gc) if ENV['debug_prim'] gc.draw(@canvas) @canvas end # Accept #use arguments. Use (x,y) to generate an additional translate. # Override @width and @height if new values are supplied. # Used by Magick::Embellishable.rvg to set non-0 x- and y-coordinates def corner(x, y) #:nodoc: @nested = true @x = Float(x) @y = Float(y) translate(@x, @y) if @x != 0.0 || @y != 0.0 end # Primitives for the outermost RVG object def add_outermost_primitives(gc) #:nodoc: add_transform_primitives(gc) gc.push add_viewbox_primitives(@width, @height, gc) add_style_primitives(gc) @content.each { |element| element.add_primitives(gc) } gc.pop self end # Primitives for nested RVG objects def add_primitives(gc) #:nodoc: raise ArgumentError, 'RVG width or height undefined' if @width.nil? || @height.nil? return self if @width.zero? || @height.zero? gc.push add_outermost_primitives(gc) gc.pop end end # end class RVG
chaintope/bitcoinrb
lib/bitcoin/gcs_filter.rb
Bitcoin.GCSFilter.golomb_rice_decode
ruby
def golomb_rice_decode(bit_reader, p) q = 0 while bit_reader.read(1) == 1 q +=1 end r = bit_reader.read(p) (q << p) + r end
decode golomb rice
train
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/gcs_filter.rb#L127-L134
class GCSFilter MAX_ELEMENTS_SIZE = 4294967296 # 2**32 attr_reader :p # Golomb-Rice coding parameter attr_reader :m # Inverse false positive rate attr_reader :n # Number of elements in the filter attr_reader :key # SipHash key attr_reader :encoded # encoded filter with hex format. # initialize Filter object. # @param [String] key the 128-bit key used to randomize the SipHash outputs. # @param [Integer] p the bit parameter of the Golomb-Rice coding. # @param [Integer] m which determines the false positive rate. # @param [Array] elements the filter elements. # @param [String] encoded_filter encoded filter with hex format. # @return [Bitcoin::GCSFilter] def initialize(key, p, m, elements: nil, encoded_filter: nil) raise 'specify either elements or encoded_filter.' if elements.nil? && encoded_filter.nil? raise 'p must be <= 32' if p > 32 @key = key @p = p @m = m if elements raise 'elements size must be < 2**32.' if elements.size >= MAX_ELEMENTS_SIZE @n = elements.size encoded = Bitcoin.pack_var_int(@n) bit_writer = Bitcoin::BitStreamWriter.new unless elements.empty? last_value = 0 hashed_set = elements.map{|e| hash_to_range(e) }.sort hashed_set.each do |v| delta = v - last_value golomb_rice_encode(bit_writer, p, delta) last_value = v end end bit_writer.flush encoded << bit_writer.stream @encoded = encoded.bth else @encoded = encoded_filter @n, payload = Bitcoin.unpack_var_int(encoded_filter.htb) end end # Range of element hashes, F = N * M def f n * m end # Hash a data element to an integer in the range [0, F). # @param [String] element with binary format. # @return [Integer] def hash_to_range(element) hash = SipHash.digest(key, element) map_into_range(hash, f) end # Checks if the element may be in the set. False positives are possible with probability 1/M. # @param [String] element with binary format # @return [Boolean] whether element in set. def match?(element) query = hash_to_range(element) match_internal?([query], 1) end # Checks if any of the given elements may be in the set. False positives are possible with probability 1/M per element checked. # This is more efficient that checking Match on multiple elements separately. # @param [Array] elements list of elements with binary format. # @return [Boolean] whether element in set. def match_any?(elements) queries = elements.map{|e| hash_to_range(e) }.sort match_internal?(queries, queries.size) end private # hash are then mapped uniformly over the desired range by multiplying with F and taking the top 64 bits of the 128-bit result. # https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/ # https://stackoverflow.com/a/26855440 def map_into_range(x, y) (x * y) >> 64 end # Checks if the elements may be in the set. # @param [Array[Integer]] hashes the query hash list. # @param [Integer] size query size. # @return [Boolean] whether elements in set. def match_internal?(hashes, size) n, payload = Bitcoin.unpack_var_int(encoded.htb) bit_reader = Bitcoin::BitStreamReader.new(payload) value = 0 hashes_index = 0 n.times do delta = golomb_rice_decode(bit_reader, p) value += delta loop do return false if hashes_index == size return true if hashes[hashes_index] == value break if hashes[hashes_index] > value hashes_index += 1 end end false end # encode golomb rice def golomb_rice_encode(bit_writer, p, x) q = x >> p while q > 0 nbits = q <= 64 ? q : 64 bit_writer.write(-1, nbits) # 18446744073709551615 is 2**64 - 1 = ~0ULL in cpp. q -= nbits end bit_writer.write(0, 1) bit_writer.write(x, p) end # decode golomb rice end
documentcloud/jammit
lib/jammit/compressor.rb
Jammit.Compressor.concatenate_and_tag_assets
ruby
def concatenate_and_tag_assets(paths, variant=nil) stylesheets = [paths].flatten.map do |css_path| contents = read_binary_file(css_path) contents.gsub(EMBED_DETECTOR) do |url| ipath, cpath = Pathname.new($1), Pathname.new(File.expand_path(css_path)) is_url = URI.parse($1).absolute? is_url ? url : "url(#{construct_asset_path(ipath, cpath, variant)})" end end stylesheets.join("\n") end
In order to support embedded assets from relative paths, we need to expand the paths before contatenating the CSS together and losing the location of the original stylesheet path. Validate the assets while we're at it.
train
https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/compressor.rb#L153-L163
class Compressor # Mapping from extension to mime-type of all embeddable assets. EMBED_MIME_TYPES = { '.png' => 'image/png', '.jpg' => 'image/jpeg', '.jpeg' => 'image/jpeg', '.gif' => 'image/gif', '.tif' => 'image/tiff', '.tiff' => 'image/tiff', '.ttf' => 'application/x-font-ttf', '.otf' => 'font/opentype', '.woff' => 'application/x-font-woff' } # Font extensions for which we allow embedding: EMBED_EXTS = EMBED_MIME_TYPES.keys EMBED_FONTS = ['.ttf', '.otf', '.woff'] # (32k - padding) maximum length for data-uri assets (an IE8 limitation). MAX_IMAGE_SIZE = 32700 # CSS asset-embedding regexes for URL rewriting. EMBED_DETECTOR = /url\(['"]?([^\s)]+\.[a-z]+)(\?\d+)?['"]?\)/ EMBEDDABLE = /[\A\/]embed\// EMBED_REPLACER = /url\(__EMBED__(.+?)(\?\d+)?\)/ # MHTML file constants. MHTML_START = "/*\r\nContent-Type: multipart/related; boundary=\"MHTML_MARK\"\r\n\r\n" MHTML_SEPARATOR = "--MHTML_MARK\r\n" MHTML_END = "\r\n--MHTML_MARK--\r\n*/\r\n" # JST file constants. JST_START = "(function(){" JST_END = "})();" JAVASCRIPT_COMPRESSORS = { :jsmin => Jammit.javascript_compressors.include?(:jsmin) ? Jammit::JsminCompressor : nil, :yui => Jammit.javascript_compressors.include?(:yui) ? YUI::JavaScriptCompressor : nil, :closure => Jammit.javascript_compressors.include?(:closure) ? Closure::Compiler : nil, :uglifier => Jammit.javascript_compressors.include?(:uglifier) ? Jammit::Uglifier : nil } CSS_COMPRESSORS = { :cssmin => Jammit.css_compressors.include?(:cssmin) ? Jammit::CssminCompressor : nil, :yui => Jammit.css_compressors.include?(:yui) ? YUI::CssCompressor : nil, :sass => Jammit.css_compressors.include?(:sass) ? Jammit::SassCompressor : nil } JAVASCRIPT_DEFAULT_OPTIONS = { :jsmin => {}, :yui => {:munge => true}, :closure => {}, :uglifier => {:copyright => false} } # CSS compression can be provided with YUI Compressor or sass. JS # compression can be provided with YUI Compressor, Google Closure # Compiler or UglifyJS. def initialize if Jammit.javascript_compressors.include?(:yui) || Jammit.javascript_compressors.include?(:closure) || Jammit.css_compressors.include?(:yui) Jammit.check_java_version end css_flavor = Jammit.css_compressor || Jammit::DEFAULT_CSS_COMPRESSOR @css_compressor = CSS_COMPRESSORS[css_flavor].new(Jammit.css_compressor_options || {}) js_flavor = Jammit.javascript_compressor || Jammit::DEFAULT_JAVASCRIPT_COMPRESSOR @options = JAVASCRIPT_DEFAULT_OPTIONS[js_flavor].merge(Jammit.compressor_options || {}) @js_compressor = JAVASCRIPT_COMPRESSORS[js_flavor].new(@options) end # Concatenate together a list of JavaScript paths, and pass them through the # YUI Compressor (with munging enabled). JST can optionally be included. def compress_js(paths) if (jst_paths = paths.grep(Jammit.template_extension_matcher)).empty? js = concatenate(paths) else js = concatenate(paths - jst_paths) + compile_jst(jst_paths) end Jammit.compress_assets ? @js_compressor.compress(js) : js end # Concatenate and compress a list of CSS stylesheets. When compressing a # :datauri or :mhtml variant, post-processes the result to embed # referenced assets. def compress_css(paths, variant=nil, asset_url=nil) @asset_contents = {} css = concatenate_and_tag_assets(paths, variant) css = @css_compressor.compress(css) if Jammit.compress_assets case variant when nil then return css when :datauri then return with_data_uris(css) when :mhtml then return with_mhtml(css, asset_url) else raise PackageNotFound, "\"#{variant}\" is not a valid stylesheet variant" end end # Compiles a single JST file by writing out a javascript that adds # template properties to a top-level template namespace object. Adds a # JST-compilation function to the top of the package, unless you've # specified your own preferred function, or turned it off. # JST templates are named with the basename of their file. def compile_jst(paths) namespace = Jammit.template_namespace paths = paths.grep(Jammit.template_extension_matcher).sort base_path = find_base_path(paths) compiled = paths.map do |path| contents = read_binary_file(path) contents = contents.gsub(/\r?\n/, "\\n").gsub("'", '\\\\\'') name = template_name(path, base_path) "#{namespace}['#{name}'] = #{Jammit.template_function}('#{contents}');" end compiler = Jammit.include_jst_script ? read_binary_file(DEFAULT_JST_SCRIPT) : ''; setup_namespace = "#{namespace} = #{namespace} || {};" [JST_START, setup_namespace, compiler, compiled, JST_END].flatten.join("\n") end private # Given a set of paths, find a common prefix path. def find_base_path(paths) return nil if paths.length <= 1 paths.sort! first = paths.first.split('/') last = paths.last.split('/') i = 0 while first[i] == last[i] && i <= first.length i += 1 end res = first.slice(0, i).join('/') res.empty? ? nil : res end # Determine the name of a JS template. If there's a common base path, use # the namespaced prefix. Otherwise, simply use the filename. def template_name(path, base_path) return File.basename(path, ".#{Jammit.template_extension}") unless base_path path.gsub(/\A#{Regexp.escape(base_path)}\/(.*)\.#{Jammit.template_extension}\Z/, '\1') end # In order to support embedded assets from relative paths, we need to # expand the paths before contatenating the CSS together and losing the # location of the original stylesheet path. Validate the assets while we're # at it. # Re-write all enabled asset URLs in a stylesheet with their corresponding # Data-URI Base-64 encoded asset contents. def with_data_uris(css) css.gsub(EMBED_REPLACER) do |url| "url(\"data:#{mime_type($1)};charset=utf-8;base64,#{encoded_contents($1)}\")" end end # Re-write all enabled asset URLs in a stylesheet with the MHTML equivalent. # The newlines ("\r\n") in the following method are critical. Without them # your MHTML will look identical, but won't work. def with_mhtml(css, asset_url) paths, index = {}, 0 css = css.gsub(EMBED_REPLACER) do |url| i = paths[$1] ||= "#{index += 1}-#{File.basename($1)}" "url(mhtml:#{asset_url}!#{i})" end mhtml = paths.sort.map do |path, identifier| mime, contents = mime_type(path), encoded_contents(path) [MHTML_SEPARATOR, "Content-Location: #{identifier}\r\n", "Content-Type: #{mime}\r\n", "Content-Transfer-Encoding: base64\r\n\r\n", contents, "\r\n"] end [MHTML_START, mhtml, MHTML_END, css].flatten.join('') end # Return a rewritten asset URL for a new stylesheet -- the asset should # be tagged for embedding if embeddable, and referenced at the correct level # if relative. def construct_asset_path(asset_path, css_path, variant) public_path = absolute_path(asset_path, css_path) return "__EMBED__#{public_path}" if embeddable?(public_path, variant) source = asset_path.absolute? || ! Jammit.rewrite_relative_paths ? asset_path.to_s : relative_path(public_path) rewrite_asset_path(source, public_path) end # Get the site-absolute public path for an asset file path that may or may # not be relative, given the path of the stylesheet that contains it. def absolute_path(asset_pathname, css_pathname) (asset_pathname.absolute? ? Pathname.new(File.join(Jammit.public_root, asset_pathname)) : css_pathname.dirname + asset_pathname).cleanpath end # CSS assets that are referenced by relative paths, and are *not* being # embedded, must be rewritten relative to the newly-merged stylesheet path. def relative_path(absolute_path) File.join('../', absolute_path.sub(Jammit.public_root, '')) end # Similar to the AssetTagHelper's method of the same name, this will # append the RAILS_ASSET_ID cache-buster to URLs, if it's defined. def rewrite_asset_path(path, file_path) asset_id = rails_asset_id(file_path) (!asset_id || asset_id == '') ? path : "#{path}?#{asset_id}" end # Similar to the AssetTagHelper's method of the same name, this will # determine the correct asset id for a file. def rails_asset_id(path) asset_id = ENV["RAILS_ASSET_ID"] return asset_id if asset_id File.exists?(path) ? File.mtime(path).to_i.to_s : '' end # An asset is valid for embedding if it exists, is less than 32K, and is # stored somewhere inside of a folder named "embed". IE does not support # Data-URIs larger than 32K, and you probably shouldn't be embedding assets # that large in any case. Because we need to check the base64 length here, # save it so that we don't have to compute it again later. def embeddable?(asset_path, variant) font = EMBED_FONTS.include?(asset_path.extname) return false unless variant return false unless asset_path.to_s.match(EMBEDDABLE) && asset_path.exist? return false unless EMBED_EXTS.include?(asset_path.extname) return false unless font || encoded_contents(asset_path).length < MAX_IMAGE_SIZE return false if font && variant == :mhtml return true end # Return the Base64-encoded contents of an asset on a single line. def encoded_contents(asset_path) return @asset_contents[asset_path] if @asset_contents[asset_path] data = read_binary_file(asset_path) @asset_contents[asset_path] = Base64.encode64(data).gsub(/\n/, '') end # Grab the mime-type of an asset, by filename. def mime_type(asset_path) EMBED_MIME_TYPES[File.extname(asset_path)] end # Concatenate together a list of asset files. def concatenate(paths) [paths].flatten.map {|p| read_binary_file(p) }.join("\n") end # `File.read`, but in "binary" mode. def read_binary_file(path) File.open(path, 'rb:UTF-8') {|f| f.read } end end
documentcloud/cloud-crowd
lib/cloud_crowd/models/job.rb
CloudCrowd.Job.fire_callback
ruby
def fire_callback begin response = RestClient.post(callback_url, {:job => self.to_json}) CloudCrowd.defer { self.destroy } if response && response.code == 201 rescue RestClient::Exception => e CloudCrowd.log "Job ##{id} (#{action}) failed to fire callback: #{callback_url}\n#{e.backtrace}" end end
If a <tt>callback_url</tt> is defined, post the Job's JSON to it upon completion. The <tt>callback_url</tt> may include HTTP basic authentication, if you like: http://user:password@example.com/job_complete If the callback URL returns a '201 Created' HTTP status code, CloudCrowd will assume that the resource has been successfully created, and the Job will be cleaned up.
train
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/models/job.rb#L89-L96
class Job < ActiveRecord::Base include ModelStatus CLEANUP_GRACE_PERIOD = 7 # That's a week. has_many :work_units, :dependent => :destroy validates_presence_of :status, :inputs, :action, :options # Set initial status # A Job starts out either splitting or processing, depending on its action. before_validation(:on => :create) do self.status = self.splittable? ? SPLITTING : PROCESSING end after_create :queue_for_workers before_destroy :cleanup_assets # Jobs that were last updated more than N days ago. scope :older_than, ->(num){ where ['updated_at < ?', num.days.ago] } # Create a Job from an incoming JSON request, and add it to the queue. def self.create_from_request(h) self.create( :inputs => h['inputs'].to_json, :action => h['action'], :options => (h['options'] || {}).to_json, :email => h['email'], :callback_url => h['callback_url'] ) end # Clean up all jobs beyond a certain age. def self.cleanup_all(opts = {}) days = opts[:days] || CLEANUP_GRACE_PERIOD self.complete.older_than(days).find_in_batches(:batch_size => 100) do |jobs| jobs.each {|job| job.destroy } end end # After work units are marked successful, we check to see if all of them have # finished, if so, continue on to the next phase of the job. def check_for_completion return unless all_work_units_complete? set_next_status outs = gather_outputs_from_work_units return queue_for_workers([outs]) if merging? if complete? update_attributes(:outputs => outs, :time => time_taken) CloudCrowd.log "Job ##{id} (#{action}) #{display_status}." unless ENV['RACK_ENV'] == 'test' CloudCrowd.defer { fire_callback } if callback_url end self end # Transition this Job's current status to the appropriate next one, based # on the state of the WorkUnits and the nature of the Action. def set_next_status update_attribute(:status, any_work_units_failed? ? FAILED : self.splitting? ? PROCESSING : self.mergeable? ? MERGING : SUCCEEDED ) end # This occurs often enough that it's time just to add a restart. def restart self.status = self.splittable? ? CloudCrowd::SPLITTING : CloudCrowd::PROCESSING self.save self.send(:queue_for_workers) end # If a <tt>callback_url</tt> is defined, post the Job's JSON to it upon # completion. The <tt>callback_url</tt> may include HTTP basic authentication, # if you like: # http://user:password@example.com/job_complete # If the callback URL returns a '201 Created' HTTP status code, CloudCrowd # will assume that the resource has been successfully created, and the Job # will be cleaned up. # Cleaning up after a job will remove all of its files from S3 or the # filesystem. Destroying a Job will cleanup_assets first. Run this in a # separate thread to get out of the transaction's way. # TODO: Convert this into a 'cleanup' work unit that gets run by a worker. def cleanup_assets # AssetStore.new.cleanup(self) end # Have all of the WorkUnits finished? def all_work_units_complete? self.work_units.incomplete.count <= 0 end # Have any of the WorkUnits failed? def any_work_units_failed? self.work_units.failed.count > 0 end # This job is splittable if its Action has a +split+ method. def splittable? self.action_class.public_instance_methods.map {|m| m.to_sym }.include? :split end # This job is done splitting if it's finished with its splitting work units. def done_splitting? splittable? && work_units.splitting.count <= 0 end # This job is mergeable if its Action has a +merge+ method. def mergeable? self.processing? && self.action_class.public_instance_methods.map {|m| m.to_sym }.include?(:merge) end # Retrieve the class for this Job's Action. def action_class @action_class ||= CloudCrowd.actions[self.action] return @action_class if @action_class raise Error::ActionNotFound, "no action named: '#{self.action}' could be found" end # How complete is this Job? # Unfortunately, with the current processing sequence, the percent_complete # can pull a fast one and go backwards. This happens when there's a single # large input that takes a long time to split, and when it finally does it # creates a whole swarm of work units. This seems unavoidable. def percent_complete return 99 if merging? return 100 if complete? unit_count = work_units.count return 100 if unit_count <= 0 (work_units.complete.count / unit_count.to_f * 100).round end # How long has this Job taken? def time_taken return self.time if self.time Time.now - self.created_at end # Generate a stable 8-bit Hex color code, based on the Job's id. def color @color ||= Digest::MD5.hexdigest(self.id.to_s)[-7...-1] end # A JSON representation of this job includes the statuses of its component # WorkUnits, as well as any completed outputs. def as_json(opts={}) atts = { 'id' => id, 'color' => color, 'status' => display_status, 'percent_complete' => percent_complete, 'work_units' => work_units.count, 'time_taken' => time_taken } atts['outputs'] = JSON.parse(outputs) if outputs atts['email'] = email if email atts end private # When the WorkUnits are all finished, gather all their outputs together # before removing them from the database entirely. Returns their merged JSON. def gather_outputs_from_work_units units = self.work_units.complete outs = self.work_units.complete.map {|u| u.parsed_output } self.work_units.complete.destroy_all outs.to_json end # When starting a new job, or moving to a new stage, split up the inputs # into WorkUnits, and queue them. Workers will start picking them up right # away. def queue_for_workers(input=nil) input ||= JSON.parse(self.inputs) input.each {|i| WorkUnit.start(self, action, i, status) } self end end
mojombo/chronic
lib/chronic/handlers.rb
Chronic.Handlers.handle_o_r_g_r
ruby
def handle_o_r_g_r(tokens, options) outer_span = get_anchor(tokens[2..3], options) handle_orr(tokens[0..1], outer_span, options) end
Handle ordinal/repeater/grabber/repeater
train
https://github.com/mojombo/chronic/blob/2b1eae7ec440d767c09e0b1a7f0e9bcf30ce1d6c/lib/chronic/handlers.rb#L513-L516
module Handlers module_function # Handle month/day def handle_m_d(month, day, time_tokens, options) month.start = self.now span = month.this(options[:context]) year, month = span.begin.year, span.begin.month day_start = Chronic.time_class.local(year, month, day) day_start = Chronic.time_class.local(year + 1, month, day) if options[:context] == :future && day_start < now day_or_time(day_start, time_tokens, options) end # Handle repeater-month-name/scalar-day def handle_rmn_sd(tokens, options) month = tokens[0].get_tag(RepeaterMonthName) day = tokens[1].get_tag(ScalarDay).type return if month_overflow?(self.now.year, month.index, day) handle_m_d(month, day, tokens[2..tokens.size], options) end # Handle repeater-month-name/scalar-day with separator-on def handle_rmn_sd_on(tokens, options) if tokens.size > 3 month = tokens[2].get_tag(RepeaterMonthName) day = tokens[3].get_tag(ScalarDay).type token_range = 0..1 else month = tokens[1].get_tag(RepeaterMonthName) day = tokens[2].get_tag(ScalarDay).type token_range = 0..0 end return if month_overflow?(self.now.year, month.index, day) handle_m_d(month, day, tokens[token_range], options) end # Handle repeater-month-name/ordinal-day def handle_rmn_od(tokens, options) month = tokens[0].get_tag(RepeaterMonthName) day = tokens[1].get_tag(OrdinalDay).type return if month_overflow?(self.now.year, month.index, day) handle_m_d(month, day, tokens[2..tokens.size], options) end # Handle ordinal this month def handle_od_rm(tokens, options) day = tokens[0].get_tag(OrdinalDay).type month = tokens[2].get_tag(RepeaterMonth) handle_m_d(month, day, tokens[3..tokens.size], options) end # Handle ordinal-day/repeater-month-name def handle_od_rmn(tokens, options) month = tokens[1].get_tag(RepeaterMonthName) day = tokens[0].get_tag(OrdinalDay).type return if month_overflow?(self.now.year, month.index, day) handle_m_d(month, day, tokens[2..tokens.size], options) end def handle_sy_rmn_od(tokens, options) year = tokens[0].get_tag(ScalarYear).type month = tokens[1].get_tag(RepeaterMonthName).index day = tokens[2].get_tag(OrdinalDay).type time_tokens = tokens.last(tokens.size - 3) return if month_overflow?(year, month, day) begin day_start = Chronic.time_class.local(year, month, day) day_or_time(day_start, time_tokens, options) rescue ArgumentError nil end end # Handle scalar-day/repeater-month-name def handle_sd_rmn(tokens, options) month = tokens[1].get_tag(RepeaterMonthName) day = tokens[0].get_tag(ScalarDay).type return if month_overflow?(self.now.year, month.index, day) handle_m_d(month, day, tokens[2..tokens.size], options) end # Handle repeater-month-name/ordinal-day with separator-on def handle_rmn_od_on(tokens, options) if tokens.size > 3 month = tokens[2].get_tag(RepeaterMonthName) day = tokens[3].get_tag(OrdinalDay).type token_range = 0..1 else month = tokens[1].get_tag(RepeaterMonthName) day = tokens[2].get_tag(OrdinalDay).type token_range = 0..0 end return if month_overflow?(self.now.year, month.index, day) handle_m_d(month, day, tokens[token_range], options) end # Handle scalar-year/repeater-quarter-name def handle_sy_rqn(tokens, options) handle_rqn_sy(tokens[0..1].reverse, options) end # Handle repeater-quarter-name/scalar-year def handle_rqn_sy(tokens, options) year = tokens[1].get_tag(ScalarYear).type quarter_tag = tokens[0].get_tag(RepeaterQuarterName) quarter_tag.start = Chronic.construct(year) quarter_tag.this(:none) end # Handle repeater-month-name/scalar-year def handle_rmn_sy(tokens, options) month = tokens[0].get_tag(RepeaterMonthName).index year = tokens[1].get_tag(ScalarYear).type if month == 12 next_month_year = year + 1 next_month_month = 1 else next_month_year = year next_month_month = month + 1 end begin end_time = Chronic.time_class.local(next_month_year, next_month_month) Span.new(Chronic.time_class.local(year, month), end_time) rescue ArgumentError nil end end # Handle generic timestamp (ruby 1.8) def handle_generic(tokens, options) t = Chronic.time_class.parse(options[:text]) Span.new(t, t + 1) rescue ArgumentError => e raise e unless e.message =~ /out of range/ end # Handle repeater-month-name/scalar-day/scalar-year def handle_rmn_sd_sy(tokens, options) month = tokens[0].get_tag(RepeaterMonthName).index day = tokens[1].get_tag(ScalarDay).type year = tokens[2].get_tag(ScalarYear).type time_tokens = tokens.last(tokens.size - 3) return if month_overflow?(year, month, day) begin day_start = Chronic.time_class.local(year, month, day) day_or_time(day_start, time_tokens, options) rescue ArgumentError nil end end # Handle repeater-month-name/ordinal-day/scalar-year def handle_rmn_od_sy(tokens, options) month = tokens[0].get_tag(RepeaterMonthName).index day = tokens[1].get_tag(OrdinalDay).type year = tokens[2].get_tag(ScalarYear).type time_tokens = tokens.last(tokens.size - 3) return if month_overflow?(year, month, day) begin day_start = Chronic.time_class.local(year, month, day) day_or_time(day_start, time_tokens, options) rescue ArgumentError nil end end # Handle oridinal-day/repeater-month-name/scalar-year def handle_od_rmn_sy(tokens, options) day = tokens[0].get_tag(OrdinalDay).type month = tokens[1].get_tag(RepeaterMonthName).index year = tokens[2].get_tag(ScalarYear).type time_tokens = tokens.last(tokens.size - 3) return if month_overflow?(year, month, day) begin day_start = Chronic.time_class.local(year, month, day) day_or_time(day_start, time_tokens, options) rescue ArgumentError nil end end # Handle scalar-day/repeater-month-name/scalar-year def handle_sd_rmn_sy(tokens, options) new_tokens = [tokens[1], tokens[0], tokens[2]] time_tokens = tokens.last(tokens.size - 3) handle_rmn_sd_sy(new_tokens + time_tokens, options) end # Handle scalar-month/scalar-day/scalar-year (endian middle) def handle_sm_sd_sy(tokens, options) month = tokens[0].get_tag(ScalarMonth).type day = tokens[1].get_tag(ScalarDay).type year = tokens[2].get_tag(ScalarYear).type time_tokens = tokens.last(tokens.size - 3) return if month_overflow?(year, month, day) begin day_start = Chronic.time_class.local(year, month, day) day_or_time(day_start, time_tokens, options) rescue ArgumentError nil end end # Handle scalar-day/scalar-month/scalar-year (endian little) def handle_sd_sm_sy(tokens, options) new_tokens = [tokens[1], tokens[0], tokens[2]] time_tokens = tokens.last(tokens.size - 3) handle_sm_sd_sy(new_tokens + time_tokens, options) end # Handle scalar-year/scalar-month/scalar-day def handle_sy_sm_sd(tokens, options) new_tokens = [tokens[1], tokens[2], tokens[0]] time_tokens = tokens.last(tokens.size - 3) handle_sm_sd_sy(new_tokens + time_tokens, options) end # Handle scalar-month/scalar-day def handle_sm_sd(tokens, options) month = tokens[0].get_tag(ScalarMonth).type day = tokens[1].get_tag(ScalarDay).type year = self.now.year time_tokens = tokens.last(tokens.size - 2) return if month_overflow?(year, month, day) begin day_start = Chronic.time_class.local(year, month, day) if options[:context] == :future && day_start < now day_start = Chronic.time_class.local(year + 1, month, day) elsif options[:context] == :past && day_start > now day_start = Chronic.time_class.local(year - 1, month, day) end day_or_time(day_start, time_tokens, options) rescue ArgumentError nil end end # Handle scalar-day/scalar-month def handle_sd_sm(tokens, options) new_tokens = [tokens[1], tokens[0]] time_tokens = tokens.last(tokens.size - 2) handle_sm_sd(new_tokens + time_tokens, options) end def handle_year_and_month(year, month) if month == 12 next_month_year = year + 1 next_month_month = 1 else next_month_year = year next_month_month = month + 1 end begin end_time = Chronic.time_class.local(next_month_year, next_month_month) Span.new(Chronic.time_class.local(year, month), end_time) rescue ArgumentError nil end end # Handle scalar-month/scalar-year def handle_sm_sy(tokens, options) month = tokens[0].get_tag(ScalarMonth).type year = tokens[1].get_tag(ScalarYear).type handle_year_and_month(year, month) end # Handle scalar-year/scalar-month def handle_sy_sm(tokens, options) year = tokens[0].get_tag(ScalarYear).type month = tokens[1].get_tag(ScalarMonth).type handle_year_and_month(year, month) end # Handle RepeaterDayName RepeaterMonthName OrdinalDay def handle_rdn_rmn_od(tokens, options) month = tokens[1].get_tag(RepeaterMonthName) day = tokens[2].get_tag(OrdinalDay).type time_tokens = tokens.last(tokens.size - 3) year = self.now.year return if month_overflow?(year, month.index, day) begin if time_tokens.empty? start_time = Chronic.time_class.local(year, month.index, day) end_time = time_with_rollover(year, month.index, day + 1) Span.new(start_time, end_time) else day_start = Chronic.time_class.local(year, month.index, day) day_or_time(day_start, time_tokens, options) end rescue ArgumentError nil end end # Handle RepeaterDayName RepeaterMonthName OrdinalDay ScalarYear def handle_rdn_rmn_od_sy(tokens, options) month = tokens[1].get_tag(RepeaterMonthName) day = tokens[2].get_tag(OrdinalDay).type year = tokens[3].get_tag(ScalarYear).type return if month_overflow?(year, month.index, day) begin start_time = Chronic.time_class.local(year, month.index, day) end_time = time_with_rollover(year, month.index, day + 1) Span.new(start_time, end_time) rescue ArgumentError nil end end # Handle RepeaterDayName OrdinalDay def handle_rdn_od(tokens, options) day = tokens[1].get_tag(OrdinalDay).type time_tokens = tokens.last(tokens.size - 2) year = self.now.year month = self.now.month if options[:context] == :future self.now.day > day ? month += 1 : month end return if month_overflow?(year, month, day) begin if time_tokens.empty? start_time = Chronic.time_class.local(year, month, day) end_time = time_with_rollover(year, month, day + 1) Span.new(start_time, end_time) else day_start = Chronic.time_class.local(year, month, day) day_or_time(day_start, time_tokens, options) end rescue ArgumentError nil end end # Handle RepeaterDayName RepeaterMonthName ScalarDay def handle_rdn_rmn_sd(tokens, options) month = tokens[1].get_tag(RepeaterMonthName) day = tokens[2].get_tag(ScalarDay).type time_tokens = tokens.last(tokens.size - 3) year = self.now.year return if month_overflow?(year, month.index, day) begin if time_tokens.empty? start_time = Chronic.time_class.local(year, month.index, day) end_time = time_with_rollover(year, month.index, day + 1) Span.new(start_time, end_time) else day_start = Chronic.time_class.local(year, month.index, day) day_or_time(day_start, time_tokens, options) end rescue ArgumentError nil end end # Handle RepeaterDayName RepeaterMonthName ScalarDay ScalarYear def handle_rdn_rmn_sd_sy(tokens, options) month = tokens[1].get_tag(RepeaterMonthName) day = tokens[2].get_tag(ScalarDay).type year = tokens[3].get_tag(ScalarYear).type return if month_overflow?(year, month.index, day) begin start_time = Chronic.time_class.local(year, month.index, day) end_time = time_with_rollover(year, month.index, day + 1) Span.new(start_time, end_time) rescue ArgumentError nil end end def handle_sm_rmn_sy(tokens, options) day = tokens[0].get_tag(ScalarDay).type month = tokens[1].get_tag(RepeaterMonthName).index year = tokens[2].get_tag(ScalarYear).type if tokens.size > 3 time = get_anchor([tokens.last], options).begin h, m, s = time.hour, time.min, time.sec time = Chronic.time_class.local(year, month, day, h, m, s) end_time = Chronic.time_class.local(year, month, day + 1, h, m, s) else time = Chronic.time_class.local(year, month, day) day += 1 unless day >= 31 end_time = Chronic.time_class.local(year, month, day) end Span.new(time, end_time) end # anchors # Handle repeaters def handle_r(tokens, options) dd_tokens = dealias_and_disambiguate_times(tokens, options) get_anchor(dd_tokens, options) end # Handle repeater/grabber/repeater def handle_r_g_r(tokens, options) new_tokens = [tokens[1], tokens[0], tokens[2]] handle_r(new_tokens, options) end # arrows # Handle scalar/repeater/pointer helper def handle_srp(tokens, span, options) distance = tokens[0].get_tag(Scalar).type repeater = tokens[1].get_tag(Repeater) pointer = tokens[2].get_tag(Pointer).type repeater.offset(span, distance, pointer) if repeater.respond_to?(:offset) end # Handle scalar/repeater/pointer def handle_s_r_p(tokens, options) span = Span.new(self.now, self.now + 1) handle_srp(tokens, span, options) end # Handle pointer/scalar/repeater def handle_p_s_r(tokens, options) new_tokens = [tokens[1], tokens[2], tokens[0]] handle_s_r_p(new_tokens, options) end # Handle scalar/repeater/pointer/anchor def handle_s_r_p_a(tokens, options) anchor_span = get_anchor(tokens[3..tokens.size - 1], options) handle_srp(tokens, anchor_span, options) end # Handle repeater/scalar/repeater/pointer def handle_rmn_s_r_p(tokens, options) handle_s_r_p_a(tokens[1..3] + tokens[0..0], options) end def handle_s_r_a_s_r_p_a(tokens, options) anchor_span = get_anchor(tokens[4..tokens.size - 1], options) span = handle_srp(tokens[0..1]+tokens[4..6], anchor_span, options) handle_srp(tokens[2..3]+tokens[4..6], span, options) end # narrows # Handle oridinal repeaters def handle_orr(tokens, outer_span, options) repeater = tokens[1].get_tag(Repeater) repeater.start = outer_span.begin - 1 ordinal = tokens[0].get_tag(Ordinal).type span = nil ordinal.times do span = repeater.next(:future) if span.begin >= outer_span.end span = nil break end end span end # Handle ordinal/repeater/separator/repeater def handle_o_r_s_r(tokens, options) outer_span = get_anchor([tokens[3]], options) handle_orr(tokens[0..1], outer_span, options) end # Handle ordinal/repeater/grabber/repeater # support methods def day_or_time(day_start, time_tokens, options) outer_span = Span.new(day_start, day_start + (24 * 60 * 60)) unless time_tokens.empty? self.now = outer_span.begin get_anchor(dealias_and_disambiguate_times(time_tokens, options), options.merge(:context => :future)) else outer_span end end def get_anchor(tokens, options) grabber = Grabber.new(:this) pointer = :future repeaters = get_repeaters(tokens) repeaters.size.times { tokens.pop } if tokens.first && tokens.first.get_tag(Grabber) grabber = tokens.shift.get_tag(Grabber) end head = repeaters.shift head.start = self.now case grabber.type when :last outer_span = head.next(:past) when :this if options[:context] != :past and repeaters.size > 0 outer_span = head.this(:none) else outer_span = head.this(options[:context]) end when :next outer_span = head.next(:future) else raise 'Invalid grabber' end if Chronic.debug puts "Handler-class: #{head.class}" puts "--#{outer_span}" end find_within(repeaters, outer_span, pointer) end def get_repeaters(tokens) tokens.map { |token| token.get_tag(Repeater) }.compact.sort.reverse end def month_overflow?(year, month, day) if ::Date.leap?(year) day > RepeaterMonth::MONTH_DAYS_LEAP[month - 1] else day > RepeaterMonth::MONTH_DAYS[month - 1] end rescue ArgumentError false end # Recursively finds repeaters within other repeaters. # Returns a Span representing the innermost time span # or nil if no repeater union could be found def find_within(tags, span, pointer) puts "--#{span}" if Chronic.debug return span if tags.empty? head = tags.shift head.start = (pointer == :future ? span.begin : span.end) h = head.this(:none) if span.cover?(h.begin) || span.cover?(h.end) find_within(tags, h, pointer) end end def time_with_rollover(year, month, day) date_parts = if month_overflow?(year, month, day) if month == 12 [year + 1, 1, 1] else [year, month + 1, 1] end else [year, month, day] end Chronic.time_class.local(*date_parts) end def dealias_and_disambiguate_times(tokens, options) # handle aliases of am/pm # 5:00 in the morning -> 5:00 am # 7:00 in the evening -> 7:00 pm day_portion_index = nil tokens.each_with_index do |t, i| if t.get_tag(RepeaterDayPortion) day_portion_index = i break end end time_index = nil tokens.each_with_index do |t, i| if t.get_tag(RepeaterTime) time_index = i break end end if day_portion_index && time_index t1 = tokens[day_portion_index] t1tag = t1.get_tag(RepeaterDayPortion) case t1tag.type when :morning puts '--morning->am' if Chronic.debug t1.untag(RepeaterDayPortion) t1.tag(RepeaterDayPortion.new(:am)) when :afternoon, :evening, :night puts "--#{t1tag.type}->pm" if Chronic.debug t1.untag(RepeaterDayPortion) t1.tag(RepeaterDayPortion.new(:pm)) end end # handle ambiguous times if :ambiguous_time_range is specified if options[:ambiguous_time_range] != :none ambiguous_tokens = [] tokens.each_with_index do |token, i| ambiguous_tokens << token next_token = tokens[i + 1] if token.get_tag(RepeaterTime) && token.get_tag(RepeaterTime).type.ambiguous? && (!next_token || !next_token.get_tag(RepeaterDayPortion)) distoken = Token.new('disambiguator') distoken.tag(RepeaterDayPortion.new(options[:ambiguous_time_range])) ambiguous_tokens << distoken end end tokens = ambiguous_tokens end tokens end end
kontena/kontena
cli/lib/kontena/cli/master/login_command.rb
Kontena::Cli::Master.LoginCommand.auth_works?
ruby
def auth_works?(server) return false unless (server && server.token && server.token.access_token) vspinner "Testing if authentication works using current access token" do Kontena::Client.new(server.url, server.token).authentication_ok?(master_account.userinfo_endpoint) end end
Check if the existing (or --token) authentication works without reauthenticating
train
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/master/login_command.rb#L112-L117
class LoginCommand < Kontena::Command include Kontena::Cli::Common parameter "[URL]", "Kontena Master URL or name" option ['-j', '--join'], '[INVITE_CODE]', "Join master using an invitation code" option ['-t', '--token'], '[TOKEN]', 'Use a pre-generated access token', environment_variable: 'KONTENA_TOKEN' option ['-n', '--name'], '[NAME]', 'Set server name', environment_variable: 'KONTENA_MASTER' option ['-c', '--code'], '[CODE]', 'Use authorization code generated during master install' option ['-r', '--[no-]remote'], :flag, 'Login using a browser on another device', default: Kontena.browserless? option ['-e', '--expires-in'], '[SECONDS]', 'Request token with expiration of X seconds. Use 0 to never expire', default: 7200 option ['-v', '--verbose'], :flag, 'Increase output verbosity' option ['-f', '--force'], :flag, 'Force reauthentication' option ['-s', '--silent'], :flag, 'Reduce output verbosity' option ['--grid'], '[GRID]', 'Set grid' option ['--no-login-info'], :flag, "Don't show login info", hidden: true def execute if self.code exit_with_error "Can't use --token and --code together" if self.token exit_with_error "Can't use --join and --code together" if self.join end if self.force? exit_with_error "Can't use --code and --force together" if self.code exit_with_error "Can't use --token and --force together" if self.token end server = select_a_server(self.name, self.url) if self.token # If a --token was given create a token with access_token set to --token value server.token = Kontena::Cli::Config::Token.new(access_token: self.token, parent_type: :master, parent_name: server.name) elsif server.token.nil? || self.force? # Force reauth or no existing token, create a token with no access_token server.token = Kontena::Cli::Config::Token.new(parent_type: :master, parent_name: server.name) end if self.grid self.skip_grid_auto_select = true if self.respond_to?(:skip_grid_auto_select?) server.grid = self.grid end # set server token by exchanging code if --code given if self.code use_authorization_code(server, self.code) exit 0 end # unless an invitation code was supplied, check auth and exit # if existing auth works already. unless self.join || self.force? if auth_works?(server) update_server_to_config(server) display_login_info(only: :master) unless self.no_login_info? exit 0 end end auth_params = { remote: self.remote?, invite_code: self.join, expires_in: self.expires_in } if self.remote? # no local browser? tell user to launch an external one display_remote_message(server, auth_params) auth_code = prompt.ask("Enter code displayed in browser:") use_authorization_code(server, auth_code) else # local web flow web_flow(server, auth_params) end display_login_info(only: :master) unless (running_silent? || self.no_login_info?) end def next_default_name next_name('kontena-master') end def next_name(base) if config.find_server(base) new_name = base.dup unless new_name =~ /\-\d+$/ new_name += "-2" end new_name.succ! until config.find_server(new_name).nil? new_name else base end end def master_account @master_account ||= config.find_account('master') end def use_authorization_code(server, code) response = vspinner "Exchanging authorization code for an access token from Kontena Master" do Kontena::Client.new(server.url, server.token).exchange_code(code) end update_server(server, response) update_server_to_config(server) end # Check if the existing (or --token) authentication works without reauthenticating # Build a path for master authentication # # @param local_port [Fixnum] tcp port where localhost webserver is listening # @param invite_code [String] an invitation code generated when user was invited # @param expires_in [Fixnum] expiration time for the requested access token # @param remote [Boolean] true when performing a login where the code is displayed on the web page # @return [String] def authentication_path(local_port: nil, invite_code: nil, expires_in: nil, remote: false) auth_url_params = {} if remote auth_url_params[:redirect_uri] = "/code" elsif local_port auth_url_params[:redirect_uri] = "http://localhost:#{local_port}/cb" else raise ArgumentError, "Local port not defined and not performing remote login" end auth_url_params[:invite_code] = invite_code if invite_code auth_url_params[:expires_in] = expires_in if expires_in "/authenticate?#{URI.encode_www_form(auth_url_params)}" end # Request a redirect to the authentication url from master # # @param master_url [String] master root url # @param auth_params [Hash] auth parameters (keyword arguments of #authentication_path) # @return [String] url to begin authentication web flow def authentication_url_from_master(master_url, auth_params) client = Kontena::Client.new(master_url) vspinner "Sending authentication request to receive an authorization URL" do response = client.request( http_method: :get, path: authentication_path(auth_params), expects: [501, 400, 302, 403], auth: false ) if client.last_response.status == 302 client.last_response.headers['Location'] elsif response.kind_of?(Hash) exit_with_error [response['error'], response['error_description']].compact.join(' : ') elsif response.kind_of?(String) && response.length > 1 exit_with_error response else exit_with_error "Invalid response to authentication request : HTTP#{client.last_response.status} #{client.last_response.body if debug?}" end end end def display_remote_message(server, auth_params) url = authentication_url_from_master(server.url, auth_params.merge(remote: true)) if running_silent? sputs url else puts "Visit this URL in a browser:" puts "#{url}" end end def web_flow(server, auth_params) require_relative '../localhost_web_server' require 'kontena/cli/browser_launcher' web_server = Kontena::LocalhostWebServer.new url = authentication_url_from_master(server.url, auth_params.merge(local_port: web_server.port)) uri = URI.parse(url) puts "Opening a browser to #{uri.scheme}://#{uri.host}" puts puts "If you are running this command over an ssh connection or it's" puts "otherwise not possible to open a browser from this terminal" puts "then you must use the --remote flag or use a pregenerated" puts "access token using the --token option." puts puts "Once the authentication is complete you can close the browser" puts "window or tab and return to this window to continue." puts any_key_to_continue(10) puts "If the browser does not open, try visiting this URL manually:" puts "#{uri.to_s}" puts server_thread = Thread.new { Thread.main['response'] = web_server.serve_one } Kontena::Cli::BrowserLauncher.open(uri.to_s) spinner "Waiting for browser authorization response" do server_thread.join end update_server(server, Thread.main['response']) update_server_to_config(server) end def update_server(server, response) update_server_token(server, response) update_server_name(server, response) update_server_username(server, response) end def update_server_name(server, response) return nil unless server.name.nil? if response.kind_of?(Hash) && response['server'] && response['server']['name'] server.name = next_name(response['server']['name']) else server.name = next_default_name end end def update_server_username(server, response) return nil unless response.kind_of?(Hash) return nil unless response['user'] server.token.username = response['user']['name'] || response['user']['email'] server.username = server.token.username end def update_server_token(server, response) if !response.kind_of?(Hash) raise TypeError, "Response type mismatch - expected Hash, got #{response.class}" elsif response['code'] use_authorization_code(server, response['code']) elsif response['error'] exit_with_error "Authentication failed: #{response['error']} #{response['error_description']}" else server.token = Kontena::Cli::Config::Token.new server.token.access_token = response['access_token'] server.token.refresh_token = response['refresh_token'] server.token.expires_at = response['expires_at'] end end def update_server_to_config(server) server.name ||= next_default_name config.servers << server unless config.servers.include?(server) config.current_master = server.name config.write config.reset_instance end # Figure out or create a server based on url or name. # # No name or url provided: try to use current_master # A name provided with --name but no url defined: try to find a server by name from config # An URL starting with 'http' provided: try to find a server by url from config # An URL not starting with 'http' provided: try to find a server by name # An URL and a name provided # - If a server is found by name: use entry and update URL to the provided url # - Else create a new entry with the url and name # # @param name [String] master name # @param url [String] master url or name # @return [Kontena::Cli::Config::Server] def select_a_server(name, url) # no url, no name, try to use current master if url.nil? && name.nil? if config.current_master return config.current_master else exit_with_error 'URL not specified and current master not selected' end end if name && url exact_match = config.find_server_by(url: url, name: name) return exact_match if exact_match # found an exact match, going to use that one. name_match = config.find_server(name) if name_match #found a server with the provided name, set the provided url to it and return name_match.url = url return name_match else # nothing found, create new. return Kontena::Cli::Config::Server.new(name: name, url: url) end elsif name # only --name provided, try to find a server with that name name_match = config.find_server(name) if name_match && name_match.url return name_match else exit_with_error "Master #{name} was found from config, but it does not have an URL and no URL was provided on command line" end elsif url # only url provided if url =~ /^https?:\/\// # url is actually an url url_match = config.find_server_by(url: url) if url_match return url_match else return Kontena::Cli::Config::Server.new(url: url, name: nil) end else name_match = config.find_server(url) if name_match unless name_match.url exit_with_error "Master #{url} was found from config, but it does not have an URL and no URL was provided on command line" end return name_match else exit_with_error "Can't find a master with name #{name} from configuration" end end end end end
MrJoy/orderly_garden
lib/orderly_garden/dsl.rb
OrderlyGarden.DSL.parent_task
ruby
def parent_task(name) task name do Rake::Task .tasks .select { |t| t.name =~ /^#{name}:/ } .sort_by(&:name) .each(&:execute) end end
Define a task named `name` that runs all tasks under an identically named `namespace`.
train
https://github.com/MrJoy/orderly_garden/blob/413bcf013de7b7c10650685f713d5131e19494a9/lib/orderly_garden/dsl.rb#L28-L36
module DSL # Create and manage a temp file, replacing `fname` with the temp file, if `fname` is provided. def with_tempfile(fname = nil, &_block) Tempfile.open("tmp") do |f| yield f.path, f.path.shellescape FileUtils.cp(f.path, fname) unless fname.nil? end end # Write an array of strings to a file, adding newline separators, and # ensuring a trailing newline at the end of a file. def write_file(file_name, file_contents) contents = file_contents .flatten .select { |line| line } .join("\n") File.open(file_name, "w") do |fh| fh.write(contents) fh.write("\n") end end # Define a task named `name` that runs all tasks under an identically named `namespace`. end
mongodb/mongoid
lib/mongoid/findable.rb
Mongoid.Findable.find_by
ruby
def find_by(attrs = {}) result = where(attrs).find_first if result.nil? && Mongoid.raise_not_found_error raise(Errors::DocumentNotFound.new(self, attrs)) end yield(result) if result && block_given? result end
Find the first +Document+ given the conditions. If a matching Document is not found and Mongoid.raise_not_found_error is true it raises Mongoid::Errors::DocumentNotFound, return null nil elsewise. @example Find the document by attribute other than id Person.find_by(:username => "superuser") @param [ Hash ] attrs The attributes to check. @raise [ Errors::DocumentNotFound ] If no document found and Mongoid.raise_not_found_error is true. @return [ Document, nil ] A matching document. @since 3.0.0
train
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/findable.rb#L114-L121
module Findable extend Mongoid::Criteria::Queryable::Forwardable select_with :with_default_scope # These are methods defined on the criteria that should also be accessible # directly from the class level. delegate \ :aggregates, :avg, :create_with, :distinct, :each, :each_with_index, :extras, :find_one_and_delete, :find_one_and_replace, :find_one_and_update, :find_or_create_by, :find_or_create_by!, :find_or_initialize_by, :first_or_create, :first_or_create!, :first_or_initialize, :for_js, :geo_near, :includes, :map_reduce, :max, :min, :none, :pluck, :read, :sum, :text_search, :update, :update_all, to: :with_default_scope # Returns a count of records in the database. # If you want to specify conditions use where. # # @example Get the count of matching documents. # Person.count # Person.where(title: "Sir").count # # @return [ Integer ] The number of matching documents. def count with_default_scope.count end # Returns true if count is zero # # @example Are there no saved documents for this model? # Person.empty? # # @return [ true, false ] If the collection is empty. def empty? count == 0 end # Returns true if there are on document in database based on the # provided arguments. # # @example Do any documents exist for the conditions? # Person.exists? # # @return [ true, false ] If any documents exist for the conditions. def exists? with_default_scope.exists? end # Find a +Document+ in several different ways. # # If a +String+ is provided, it will be assumed that it is a # representation of a Mongo::ObjectID and will attempt to find a single # +Document+ based on that id. If a +Symbol+ and +Hash+ is provided then # it will attempt to find either a single +Document+ or multiples based # on the conditions provided and the first parameter. # # @example Find a single document by an id. # Person.find(BSON::ObjectId) # # @param [ Array ] args An assortment of finder options. # # @return [ Document, nil, Criteria ] A document or matching documents. def find(*args) with_default_scope.find(*args) end # Find the first +Document+ given the conditions. # If a matching Document is not found and # Mongoid.raise_not_found_error is true it raises # Mongoid::Errors::DocumentNotFound, return null nil elsewise. # # @example Find the document by attribute other than id # Person.find_by(:username => "superuser") # # @param [ Hash ] attrs The attributes to check. # # @raise [ Errors::DocumentNotFound ] If no document found # and Mongoid.raise_not_found_error is true. # # @return [ Document, nil ] A matching document. # # @since 3.0.0 # Find the first +Document+ given the conditions, or raises # Mongoid::Errors::DocumentNotFound # # @example Find the document by attribute other than id # Person.find_by(:username => "superuser") # # @param [ Hash ] attrs The attributes to check. # # @raise [ Errors::DocumentNotFound ] If no document found. # # @return [ Document ] A matching document. # def find_by!(attrs = {}) result = where(attrs).find_first raise(Errors::DocumentNotFound.new(self, attrs)) unless result yield(result) if result && block_given? result end # Find the first +Document+ given the conditions. # # @example Find the first document. # Person.first # # @return [ Document ] The first matching document. def first with_default_scope.first end alias :one :first # Find the last +Document+ given the conditions. # # @example Find the last document. # Person.last # # @return [ Document ] The last matching document. def last with_default_scope.last end end
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.chown
ruby
def chown(user_and_group) return unless user_and_group user, group = user_and_group.split(':').map {|s| s == '' ? nil : s} FileUtils.chown user, group, selected_items.map(&:path) ls end
Change the file owner of the selected files and directories. ==== Parameters * +user_and_group+ - user name and group name separated by : (e.g. alice, nobody:nobody, :admin)
train
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L250-L255
class Controller include Rfd::Commands attr_reader :header_l, :header_r, :main, :command_line, :items, :displayed_items, :current_row, :current_page, :current_dir, :current_zip # :nodoc: def initialize @main = MainWindow.new @header_l = HeaderLeftWindow.new @header_r = HeaderRightWindow.new @command_line = CommandLineWindow.new @debug = DebugWindow.new if ENV['DEBUG'] @direction, @dir_history, @last_command, @times, @yanked_items = nil, [], nil, nil, nil end # The main loop. def run loop do begin number_pressed = false ret = case (c = Curses.getch) when 10, 13 # enter, return enter when 27 # ESC q when ' ' # space space when 127 # DEL del when Curses::KEY_DOWN j when Curses::KEY_UP k when Curses::KEY_LEFT h when Curses::KEY_RIGHT l when Curses::KEY_CTRL_A..Curses::KEY_CTRL_Z chr = ((c - 1 + 65) ^ 0b0100000).chr public_send "ctrl_#{chr}" if respond_to?("ctrl_#{chr}") when ?0..?9 public_send c number_pressed = true when ?!..?~ if respond_to? c public_send c else debug "key: #{c}" if ENV['DEBUG'] end when Curses::KEY_MOUSE if (mouse_event = Curses.getmouse) case mouse_event.bstate when Curses::BUTTON1_CLICKED click y: mouse_event.y, x: mouse_event.x when Curses::BUTTON1_DOUBLE_CLICKED double_click y: mouse_event.y, x: mouse_event.x end end else debug "key: #{c}" if ENV['DEBUG'] end Curses.doupdate if ret @times = nil unless number_pressed rescue StopIteration raise rescue => e command_line.show_error e.to_s raise if ENV['DEBUG'] end end ensure Curses.close_screen end # Change the number of columns in the main window. def spawn_panes(num) main.number_of_panes = num @current_row = @current_page = 0 end # Number of times to repeat the next command. def times (@times || 1).to_i end # The file or directory on which the cursor is on. def current_item items[current_row] end # * marked files and directories. def marked_items items.select(&:marked?) end # Marked files and directories or Array(the current file or directory). # # . and .. will not be included. def selected_items ((m = marked_items).any? ? m : Array(current_item)).reject {|i| %w(. ..).include? i.name} end # Move the cursor to specified row. # # The main window and the headers will be updated reflecting the displayed files and directories. # The row number can be out of range of the current page. def move_cursor(row = nil) if row if (prev_item = items[current_row]) main.draw_item prev_item end page = row / max_items switch_page page if page != current_page main.activate_pane row / maxy @current_row = row else @current_row = 0 end item = items[current_row] main.draw_item item, current: true main.display current_page header_l.draw_current_file_info item @current_row end # Change the current directory. def cd(dir = '~', pushd: true) dir = load_item path: expand_path(dir) unless dir.is_a? Item unless dir.zip? Dir.chdir dir @current_zip = nil else @current_zip = dir end @dir_history << current_dir if current_dir && pushd @current_dir, @current_page, @current_row = dir, 0, nil main.activate_pane 0 ls @current_dir end # cd to the previous directory. def popd cd @dir_history.pop, pushd: false if @dir_history.any? end # Fetch files from current directory. # Then update each windows reflecting the newest information. def ls fetch_items_from_filesystem_or_zip sort_items_according_to_current_direction @current_page ||= 0 draw_items move_cursor (current_row ? [current_row, items.size - 1].min : nil) draw_marked_items draw_total_items true end # Sort the whole files and directories in the current directory, then refresh the screen. # # ==== Parameters # * +direction+ - Sort order in a String. # nil : order by name # r : reverse order by name # s, S : order by file size # sr, Sr: reverse order by file size # t : order by mtime # tr : reverse order by mtime # c : order by ctime # cr : reverse order by ctime # u : order by atime # ur : reverse order by atime # e : order by extname # er : reverse order by extname def sort(direction = nil) @direction, @current_page = direction, 0 sort_items_according_to_current_direction switch_page 0 move_cursor 0 end # Change the file permission of the selected files and directories. # # ==== Parameters # * +mode+ - Unix chmod string (e.g. +w, g-r, 755, 0644) def chmod(mode = nil) return unless mode begin Integer mode mode = Integer mode.size == 3 ? "0#{mode}" : mode rescue ArgumentError end FileUtils.chmod mode, selected_items.map(&:path) ls end # Change the file owner of the selected files and directories. # # ==== Parameters # * +user_and_group+ - user name and group name separated by : (e.g. alice, nobody:nobody, :admin) # Fetch files from current directory or current .zip file. def fetch_items_from_filesystem_or_zip unless in_zip? @items = Dir.foreach(current_dir).map {|fn| load_item dir: current_dir, name: fn }.to_a.partition {|i| %w(. ..).include? i.name}.flatten else @items = [load_item(dir: current_dir, name: '.', stat: File.stat(current_dir)), load_item(dir: current_dir, name: '..', stat: File.stat(File.dirname(current_dir)))] zf = Zip::File.new current_dir zf.each {|entry| next if entry.name_is_directory? stat = zf.file.stat entry.name @items << load_item(dir: current_dir, name: entry.name, stat: stat) } end end # Focus at the first file or directory of which name starts with the given String. def find(str) index = items.index {|i| i.index > current_row && i.name.start_with?(str)} || items.index {|i| i.name.start_with? str} move_cursor index if index end # Focus at the last file or directory of which name starts with the given String. def find_reverse(str) index = items.reverse.index {|i| i.index < current_row && i.name.start_with?(str)} || items.reverse.index {|i| i.name.start_with? str} move_cursor items.size - index - 1 if index end # Height of the currently active pane. def maxy main.maxy end # Number of files or directories that the current main window can show in a page. def max_items main.max_items end # Update the main window with the loaded files and directories. Also update the header. def draw_items main.newpad items @displayed_items = items[current_page * max_items, max_items] main.display current_page header_l.draw_path_and_page_number path: current_dir.path, current: current_page + 1, total: total_pages end # Sort the loaded files and directories in already given sort order. def sort_items_according_to_current_direction case @direction when nil @items = items.shift(2) + items.partition(&:directory?).flat_map(&:sort) when 'r' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort.reverse} when 'S', 's' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by {|i| -i.size}} when 'Sr', 'sr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:size)} when 't' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.mtime <=> x.mtime}} when 'tr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:mtime)} when 'c' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.ctime <=> x.ctime}} when 'cr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:ctime)} when 'u' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.atime <=> x.atime}} when 'ur' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:atime)} when 'e' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.extname <=> x.extname}} when 'er' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:extname)} end items.each.with_index {|item, index| item.index = index} end # Search files and directories from the current directory, and update the screen. # # * +pattern+ - Search pattern against file names in Ruby Regexp string. # # === Example # # a : Search files that contains the letter "a" in their file name # .*\.pdf$ : Search PDF files def grep(pattern = '.*') regexp = Regexp.new(pattern) fetch_items_from_filesystem_or_zip @items = items.shift(2) + items.select {|i| i.name =~ regexp} sort_items_according_to_current_direction draw_items draw_total_items switch_page 0 move_cursor 0 end # Copy selected files and directories to the destination. def cp(dest) unless in_zip? src = (m = marked_items).any? ? m.map(&:path) : current_item FileUtils.cp_r src, expand_path(dest) else raise 'cping multiple items in .zip is not supported.' if selected_items.size > 1 Zip::File.open(current_zip) do |zip| entry = zip.find_entry(selected_items.first.name).dup entry.name, entry.name_length = dest, dest.size zip.instance_variable_get(:@entry_set) << entry end end ls end # Move selected files and directories to the destination. def mv(dest) unless in_zip? src = (m = marked_items).any? ? m.map(&:path) : current_item FileUtils.mv src, expand_path(dest) else raise 'mving multiple items in .zip is not supported.' if selected_items.size > 1 rename "#{selected_items.first.name}/#{dest}" end ls end # Rename selected files and directories. # # ==== Parameters # * +pattern+ - new filename, or a shash separated Regexp like string def rename(pattern) from, to = pattern.sub(/^\//, '').sub(/\/$/, '').split '/' if to.nil? from, to = current_item.name, from else from = Regexp.new from end unless in_zip? selected_items.each do |item| name = item.name.gsub from, to FileUtils.mv item, current_dir.join(name) if item.name != name end else Zip::File.open(current_zip) do |zip| selected_items.each do |item| name = item.name.gsub from, to zip.rename item.name, name end end end ls end # Soft delete selected files and directories. # # If the OS is not OSX, performs the same as `delete` command. def trash unless in_zip? if osx? FileUtils.mv selected_items.map(&:path), File.expand_path('~/.Trash/') else #TODO support other OS FileUtils.rm_rf selected_items.map(&:path) end else return unless ask %Q[Trashing zip entries is not supported. Actually the files will be deleted. Are you sure want to proceed? (y/n)] delete end @current_row -= selected_items.count {|i| i.index <= current_row} ls end # Delete selected files and directories. def delete unless in_zip? FileUtils.rm_rf selected_items.map(&:path) else Zip::File.open(current_zip) do |zip| zip.select {|e| selected_items.map(&:name).include? e.to_s}.each do |entry| if entry.name_is_directory? zip.dir.delete entry.to_s else zip.file.delete entry.to_s end end end end @current_row -= selected_items.count {|i| i.index <= current_row} ls end # Create a new directory. def mkdir(dir) unless in_zip? FileUtils.mkdir_p current_dir.join(dir) else Zip::File.open(current_zip) do |zip| zip.dir.mkdir dir end end ls end # Create a new empty file. def touch(filename) unless in_zip? FileUtils.touch current_dir.join(filename) else Zip::File.open(current_zip) do |zip| # zip.file.open(filename, 'w') {|_f| } #HAXX this code creates an unneeded temporary file zip.instance_variable_get(:@entry_set) << Zip::Entry.new(current_zip, filename) end end ls end # Create a symlink to the current file or directory. def symlink(name) FileUtils.ln_s current_item, name ls end # Yank selected file / directory names. def yank @yanked_items = selected_items end # Paste yanked files / directories here. def paste if @yanked_items if current_item.directory? FileUtils.cp_r @yanked_items.map(&:path), current_item else @yanked_items.each do |item| if items.include? item i = 1 while i += 1 new_item = load_item dir: current_dir, name: "#{item.basename}_#{i}#{item.extname}", stat: item.stat break unless File.exist? new_item.path end FileUtils.cp_r item, new_item else FileUtils.cp_r item, current_dir end end end ls end end # Copy selected files and directories' path into clipboard on OSX. def clipboard IO.popen('pbcopy', 'w') {|f| f << selected_items.map(&:path).join(' ')} if osx? end # Archive selected files and directories into a .zip file. def zip(zipfile_name) return unless zipfile_name zipfile_name += '.zip' unless zipfile_name.end_with? '.zip' Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile| selected_items.each do |item| next if item.symlink? if item.directory? Dir[item.join('**/**')].each do |file| zipfile.add file.sub("#{current_dir}/", ''), file end else zipfile.add item.name, item end end end ls end # Unarchive .zip and .tar.gz files within selected files and directories into current_directory. def unarchive unless in_zip? zips, gzs = selected_items.partition(&:zip?).tap {|z, others| break [z, *others.partition(&:gz?)]} zips.each do |item| FileUtils.mkdir_p current_dir.join(item.basename) Zip::File.open(item) do |zip| zip.each do |entry| FileUtils.mkdir_p File.join(item.basename, File.dirname(entry.to_s)) zip.extract(entry, File.join(item.basename, entry.to_s)) { true } end end end gzs.each do |item| Zlib::GzipReader.open(item) do |gz| Gem::Package::TarReader.new(gz) do |tar| dest_dir = current_dir.join (gz.orig_name || item.basename).sub(/\.tar$/, '') tar.each do |entry| dest = nil if entry.full_name == '././@LongLink' dest = File.join dest_dir, entry.read.strip next end dest ||= File.join dest_dir, entry.full_name if entry.directory? FileUtils.mkdir_p dest, :mode => entry.header.mode elsif entry.file? FileUtils.mkdir_p dest_dir File.open(dest, 'wb') {|f| f.print entry.read} FileUtils.chmod entry.header.mode, dest elsif entry.header.typeflag == '2' # symlink File.symlink entry.header.linkname, dest end unless Dir.exist? dest_dir FileUtils.mkdir_p dest_dir File.open(File.join(dest_dir, gz.orig_name || item.basename), 'wb') {|f| f.print gz.read} end end end end end else Zip::File.open(current_zip) do |zip| zip.select {|e| selected_items.map(&:name).include? e.to_s}.each do |entry| FileUtils.mkdir_p File.join(current_zip.dir, current_zip.basename, File.dirname(entry.to_s)) zip.extract(entry, File.join(current_zip.dir, current_zip.basename, entry.to_s)) { true } end end end ls end # Current page is the first page? def first_page? current_page == 0 end # Do we have more pages? def last_page? current_page == total_pages - 1 end # Number of pages in the current directory. def total_pages (items.size - 1) / max_items + 1 end # Move to the given page number. # # ==== Parameters # * +page+ - Target page number def switch_page(page) main.display (@current_page = page) @displayed_items = items[current_page * max_items, max_items] header_l.draw_path_and_page_number path: current_dir.path, current: current_page + 1, total: total_pages end # Update the header information concerning currently marked files or directories. def draw_marked_items items = marked_items header_r.draw_marked_items count: items.size, size: items.inject(0) {|sum, i| sum += i.size} end # Update the header information concerning total files and directories in the current directory. def draw_total_items header_r.draw_total_items count: items.size, size: items.inject(0) {|sum, i| sum += i.size} end # Swktch on / off marking on the current file or directory. def toggle_mark main.toggle_mark current_item end # Get a char as a String from user input. def get_char c = Curses.getch c if (0..255) === c.ord end def clear_command_line command_line.writeln 0, "" command_line.clear command_line.noutrefresh end # Accept user input, and directly execute it as a Ruby method call to the controller. # # ==== Parameters # * +preset_command+ - A command that would be displayed at the command line before user input. def process_command_line(preset_command: nil) prompt = preset_command ? ":#{preset_command} " : ':' command_line.set_prompt prompt cmd, *args = command_line.get_command(prompt: prompt).split(' ') if cmd && !cmd.empty? && respond_to?(cmd) ret = self.public_send cmd, *args clear_command_line ret end rescue Interrupt clear_command_line end # Accept user input, and directly execute it in an external shell. def process_shell_command command_line.set_prompt ':!' cmd = command_line.get_command(prompt: ':!')[1..-1] execute_external_command pause: true do system cmd end rescue Interrupt ensure command_line.clear command_line.noutrefresh end # Let the user answer y or n. # # ==== Parameters # * +prompt+ - Prompt message def ask(prompt = '(y/n)') command_line.set_prompt prompt command_line.refresh while (c = Curses.getch) next unless [?N, ?Y, ?n, ?y, 3, 27] .include? c # N, Y, n, y, ^c, esc command_line.clear command_line.noutrefresh break (c == 'y') || (c == 'Y') end end # Open current file or directory with the editor. def edit execute_external_command do editor = ENV['EDITOR'] || 'vim' unless in_zip? system %Q[#{editor} "#{current_item.path}"] else begin tmpdir, tmpfile_name = nil Zip::File.open(current_zip) do |zip| tmpdir = Dir.mktmpdir FileUtils.mkdir_p File.join(tmpdir, File.dirname(current_item.name)) tmpfile_name = File.join(tmpdir, current_item.name) File.open(tmpfile_name, 'w') {|f| f.puts zip.file.read(current_item.name)} system %Q[#{editor} "#{tmpfile_name}"] zip.add(current_item.name, tmpfile_name) { true } end ls ensure FileUtils.remove_entry_secure tmpdir if tmpdir end end end end # Open current file or directory with the viewer. def view pager = ENV['PAGER'] || 'less' execute_external_command do unless in_zip? system %Q[#{pager} "#{current_item.path}"] else begin tmpdir, tmpfile_name = nil Zip::File.open(current_zip) do |zip| tmpdir = Dir.mktmpdir FileUtils.mkdir_p File.join(tmpdir, File.dirname(current_item.name)) tmpfile_name = File.join(tmpdir, current_item.name) File.open(tmpfile_name, 'w') {|f| f.puts zip.file.read(current_item.name)} end system %Q[#{pager} "#{tmpfile_name}"] ensure FileUtils.remove_entry_secure tmpdir if tmpdir end end end end def move_cursor_by_click(y: nil, x: nil) if (idx = main.pane_index_at(y: y, x: x)) row = current_page * max_items + main.maxy * idx + y - main.begy move_cursor row if (row >= 0) && (row < items.size) end end private def execute_external_command(pause: false) Curses.def_prog_mode Curses.close_screen yield ensure Curses.reset_prog_mode Curses.getch if pause #NOTE needs to draw borders and ls again here since the stdlib Curses.refresh fails to retrieve the previous screen Rfd::Window.draw_borders Curses.refresh ls end def expand_path(path) File.expand_path path.start_with?('/', '~') ? path : current_dir ? current_dir.join(path) : path end def load_item(path: nil, dir: nil, name: nil, stat: nil) Item.new dir: dir || File.dirname(path), name: name || File.basename(path), stat: stat, window_width: main.width end def osx? @_osx ||= RbConfig::CONFIG['host_os'] =~ /darwin/ end def in_zip? @current_zip end def debug(str) @debug.debug str end end
sugaryourcoffee/syclink
lib/syclink/designer.rb
SycLink.Designer.create_website
ruby
def create_website(directory, template_filename) template = File.read(template_filename) File.open(html_file(directory, website.title), 'w') do |f| f.puts website.to_html(template) end end
Creates the html representation of the website. The website is saved to the directory with websites title and needs an erb-template where the links are integrated to. An example template can be found at templates/syclink.html.erb
train
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/designer.rb#L152-L157
class Designer # extend Forwardable # def_delegators :@website, :report_links_availability include Infrastructure # The website the designer is working on attr_accessor :website # Creates a new website where designer can operate on def new_website(title = "SYC LINK") @website = Website.new(title) end # Adds a link based on the provided arguments to the website def add_link(url, args = {}) website.add_link(Link.new(url, args)) end # Reads arguments from a CSV file and creates links accordingly. The links # are added to the websie def add_links_from_file(file) File.foreach(file) do |line| next if line.chomp.empty? url, name, description, tag = line.chomp.split(';') website.add_link(Link.new(url, { name: name, description: description, tag: tag })) end end # Accepts and SycLink::Importer to import Links and add them to the website def import_links(importer) importer.links.each do |link| website.add_link(link) end end # Export links to specified format def export(format) message = "to_#{format.downcase}" if website.respond_to? message website.send(message) else raise "cannot export to #{format}" end end # List links contained in the website and optionally filter on attributes def list_links(args = {}) website.list_links(args) end # Finds links based on a search string def find_links(search) website.find_links(search) end # Check links availability. Takes a filter which values to return and # whether to return available, unavailable or available and unavailable # links. In the following example only unavailable links' url and response # would be returned # report_links_availability(available: false, # unavailable: false, # columns: "url,response") def report_links_availability(opts) cols = opts[:columns].gsub(/ /, "").split(',') website.report_links_availability.map do |url, response| result = if response == "200" and opts[:available] { "url" => url, "response" => response } elsif response != "200" and opts[:unavailable] { "url" => url, "response" => response } end next if result.nil? cols.inject([]) { |res, c| res << result[c.downcase] } end.compact end # Updates a link. The link is identified by the URL. If there is more than # one link with the same URL, only the first link is updated def update_link(url, args) website.find_links(url).first.update(args) end # Updates links read from a file def update_links_from_file(file) File.foreach(file) do |line| next if line.chomp.empty? url, name, description, tag = line.chomp.split(';') website.find_links(url).first.update({ name: name, description: description, tag: tag }) end end # Merge links with same URL def merge_links website.merge_links_on(:url) end # Deletes one or more links from the website. Returns the deleted links. # Expects the links provided in an array def remove_links(urls) urls.map { |url| list_links({ url: url }) }.flatten.compact.each do |link| website.remove_link(link) end end # Deletes links based on URLs that are provided in a file. Each URL has to # be in one line def remove_links_from_file(file) urls = File.foreach(file).map { |url| url.chomp unless url.empty? } remove_links(urls) end # Saves the website to the specified directory with the downcased name of # the website and the extension 'website'. The website is save as YAML def save_website(directory) File.open(yaml_file(directory, website.title), 'w') do |f| YAML.dump(website, f) end end # Loads a website based on the provided YAML-file and asigns it to the # designer to operate on def load_website(website) @website = YAML.load_file(website) end # Deletes the website if it already exists def delete_website(directory) if File.exists? yaml_file(directory, website.title) FileUtils.rm(yaml_file(directory, website.title)) end end # Creates the html representation of the website. The website is saved to # the directory with websites title and needs an erb-template where the # links are integrated to. An example template can be found at # templates/syclink.html.erb end
iyuuya/jkf
lib/jkf/parser/kifuable.rb
Jkf::Parser.Kifuable.parse_pointer
ruby
def parse_pointer s0 = @current_pos s1 = match_str("&") if s1 != :failed s2 = parse_nonls s3 = parse_nl if s3 != :failed s0 = [s1, s2, s3] else @current_pos = s0 s0 = :failed end else @current_pos = s0 s0 = :failed end s0 end
pointer : "&" nonls nl
train
https://github.com/iyuuya/jkf/blob/4fd229c50737cab7b41281238880f1414e55e061/lib/jkf/parser/kifuable.rb#L151-L168
module Kifuable protected # initialboard : (" " nonls nl)? ("+" nonls nl)? ikkatsuline+ ("+" nonls nl)? def parse_initialboard s0 = s1 = @current_pos if match_space != :failed parse_nonls s2 = parse_nl @current_pos = s1 if s2 == :failed else @current_pos = s1 end s2 = @current_pos if match_str("+") != :failed parse_nonls @current_pos = s2 if parse_nl == :failed else @current_pos = s2 end s4 = parse_ikkatsuline if s4 != :failed s3 = [] while s4 != :failed s3 << s4 s4 = parse_ikkatsuline end else s3 = :failed end if s3 != :failed s4 = @current_pos if match_str("+") != :failed parse_nonls @current_pos = s4 if parse_nl == :failed else @current_pos = s4 end @reported_pos = s0 transform_initialboard(s3) else @current_pos = s0 :failed end end # ikkatsuline : "|" masu:masu+ "|" nonls! nl def parse_ikkatsuline s0 = @current_pos if match_str("|") != :failed s3 = parse_masu if s3 != :failed s2 = [] while s3 != :failed s2 << s3 s3 = parse_masu end else s2 = :failed end if s2 != :failed if match_str("|") != :failed s4 = parse_nonls! if s4 != :failed if parse_nl != :failed @reported_pos = s0 s0 = s2 else @current_pos = s0 s0 = :failed end else @current_pos = s0 s0 = :failed end else @current_pos = s0 s0 = :failed end else @current_pos = s0 s0 = :failed end else @current_pos = s0 s0 = :failed end s0 end # masu : teban piece | " ・" def parse_masu s0 = @current_pos s1 = parse_teban if s1 != :failed s2 = parse_piece if s2 != :failed @reported_pos = s0 s0 = { "color" => s1, "kind" => s2 } else @current_pos = s0 s0 = :failed end else @current_pos = s0 s0 = :failed end if s0 == :failed s0 = @current_pos s1 = match_str(" ・") if s1 != :failed @reported_pos = s0 s1 = {} end s0 = s1 end s0 end # teban : (" " | "+" | "^") | ("v" | "V") def parse_teban s0 = @current_pos s1 = match_space if s1 == :failed s1 = match_str("+") s1 = match_str("^") if s1 == :failed end if s1 != :failed @reported_pos = s0 s1 = 0 end s0 = s1 if s0 == :failed s0 = @current_pos s1 = match_str("v") s1 = match_str("V") if s1 == :failed if s1 != :failed @reported_pos = s0 s1 = 1 end s0 = s1 end s0 end # pointer : "&" nonls nl # num : [123456789] def parse_num s0 = @current_pos s1 = match_regexp(/^[123456789]/) if s1 != :failed @reported_pos = s0 s1 = zen2n(s1) end s1 end # numkan : [一二三四五六七八九] def parse_numkan s0 = @current_pos s1 = match_regexp(/^[一二三四五六七八九]/) if s1 != :failed @reported_pos = s0 s1 = kan2n(s1) end s1 end # piece : "成"? [歩香桂銀金角飛王玉と杏圭全馬竜龍] def parse_piece s0 = @current_pos s1 = match_str("成") s1 = "" if s1 == :failed s2 = match_regexp(/^[歩香桂銀金角飛王玉と杏圭全馬竜龍]/) if s2 != :failed @reported_pos = s0 kind2csa(s1 + s2) else @current_pos = s0 :failed end end # result : "まで" [0-9]+ "手" ( # "で" (turn "手の" (result_toryo | result_illegal)) | # result_timeup | result_chudan | result_jishogi | # result_sennichite | result_tsumi | result_fuzumi # ) nl def parse_result s0 = @current_pos if match_str("まで") != :failed s2 = match_digits! if s2 != :failed if match_str("手") != :failed s4 = @current_pos if match_str("で") != :failed if parse_turn != :failed if match_str("手の") != :failed s8 = parse_result_toryo s8 = parse_result_illegal if s8 == :failed s4 = if s8 != :failed @reported_pos = s4 s8 else @current_pos = s4 :failed end else @current_pos = s4 s4 = :failed end else @current_pos = s4 s4 = :failed end else @current_pos = s4 s4 = :failed end if s4 == :failed s4 = parse_result_timeup if s4 == :failed s4 = parse_result_chudan if s4 == :failed s4 = parse_result_jishogi if s4 == :failed s4 = parse_result_sennichite if s4 == :failed s4 = parse_result_tsumi s4 = parse_result_fuzumi if s4 == :failed end end end end end if s4 != :failed if parse_nl != :failed || eos? @reported_pos = s0 s4 else @current_pos = s0 :failed end else @current_pos = s0 :failed end else @current_pos = s0 :failed end else @current_pos = s0 :failed end else @current_pos = s0 :failed end end # result_toryo : "勝ち" def parse_result_toryo s0 = @current_pos s1 = match_str("勝ち") if s1 != :failed @reported_pos = s0 "TORYO" else @current_pos = s0 :failed end end # result_illegal : "反則" ("勝ち" | "負け") def parse_result_illegal s0 = @current_pos if match_str("反則") != :failed s10 = @current_pos s11 = match_str("勝ち") if s11 != :failed @reported_pos = s10 s11 = "ILLEGAL_ACTION" end s10 = s11 if s10 == :failed s10 = @current_pos s11 = match_str("負け") if s11 != :failed @reported_pos = s10 s11 = "ILLEGAL_MOVE" end s10 = s11 end if s10 != :failed @reported_pos = s0 s10 else @current_pos = s0 :failed end else @current_pos = s0 :failed end end # result_timeup : "で時間切れにより" turn "手の勝ち" def parse_result_timeup s0 = @current_pos if match_str("で時間切れにより") != :failed if parse_turn != :failed if match_str("手の勝ち") != :failed @reported_pos = s0 "TIME_UP" else @current_pos = s0 :failed end else @current_pos = s0 :failed end else @current_pos = s0 :failed end end # result_chudan : "で中断" def parse_result_chudan s0 = @current_pos s1 = match_str("で中断") if s1 != :failed @reported_pos = s0 "CHUDAN" else @current_pos = s0 :failed end end # result_jishogi : "で持将棋" def parse_result_jishogi s0 = @current_pos s1 = match_str("で持将棋") if s1 != :failed @reported_pos = s0 "JISHOGI" else @current_pos = s0 :failed end end # result_sennichite : "で千日手" def parse_result_sennichite s0 = @current_pos s1 = match_str("で千日手") if s1 != :failed @reported_pos = s0 "SENNICHITE" else @current_pos = s0 :failed end end # result_tsumi : "で"? "詰" "み"? def parse_result_tsumi s0 = @current_pos match_str("で") if match_str("詰") != :failed match_str("み") @reported_pos = s0 "TSUMI" else @current_pos = s0 :failed end end # result_fuzumi : "で不詰" def parse_result_fuzumi s0 = @current_pos s1 = match_str("で不詰") if s1 != :failed @reported_pos = s0 "FUZUMI" else @current_pos = s0 :failed end end # skipline : "#" nonls newline def parse_skipline s0 = @current_pos s1 = match_str("#") if s1 != :failed s2 = parse_nonls s3 = parse_newline s0 = if s3 != :failed [s1, s2, s3] else @current_pos = s0 :failed end else @current_pos = s0 s0 = :failed end s0 end # whitespace : " " | "\t" def parse_whitespace match_regexp(/^[ \t]/) end # newline : whitespace* ("\n" | "\r" "\n"?) def parse_newline s0 = @current_pos s1 = [] s2 = parse_whitespace while s2 != :failed s1 << s2 s2 = parse_whitespace end s2 = match_str("\n") if s2 == :failed s2 = @current_pos s3 = match_str("\r") s2 = if s3 != :failed s4 = match_str("\n") s4 = nil if s4 == :failed [s3, s4] else @current_pos = s2 :failed end end if s2 != :failed [s1, s2] else @current_pos = s0 :failed end end # nl : newline+ skipline* def parse_nl s0 = @current_pos s2 = parse_newline if s2 != :failed s1 = [] while s2 != :failed s1 << s2 s2 = parse_newline end else s1 = :failed end if s1 != :failed s2 = [] s3 = parse_skipline while s3 != :failed s2 << s3 s3 = parse_skipline end [s1, s2] else @current_pos = s0 :failed end end # nonl : def parse_nonl match_regexp(/^[^\r\n]/) end # nonls : nonl* def parse_nonls stack = [] matched = parse_nonl while matched != :failed stack << matched matched = parse_nonl end stack end # nonls! : nonl+ def parse_nonls! matched = parse_nonls if matched.empty? :failed else matched end end # transform header-data to jkf def transform_root_header_data(ret) if ret["header"]["手番"] ret["initial"]["data"]["color"] = "下先".include?(ret["header"]["手番"]) ? 0 : 1 ret["header"].delete("手番") else ret["initial"]["data"]["color"] = 0 end ret["initial"]["data"]["hands"] = [ make_hand(ret["header"]["先手の持駒"] || ret["header"]["下手の持駒"]), make_hand(ret["header"]["後手の持駒"] || ret["header"]["上手の持駒"]) ] %w(先手の持駒 下手の持駒 後手の持駒 上手の持駒).each do |key| ret["header"].delete(key) end end # transfrom forks to jkf def transform_root_forks(forks, moves) fork_stack = [{ "te" => 0, "moves" => moves }] forks.each do |f| now_fork = f _fork = fork_stack.pop _fork = fork_stack.pop while _fork["te"] > now_fork["te"] move = _fork["moves"][now_fork["te"] - _fork["te"]] move["forks"] ||= [] move["forks"] << now_fork["moves"] fork_stack << _fork fork_stack << now_fork end end # transform initialboard to jkf def transform_initialboard(lines) board = [] 9.times do |i| line = [] 9.times do |j| line << lines[j][8 - i] end board << line end { "preset" => "OTHER", "data" => { "board" => board } } end # zenkaku number to number def zen2n(s) "0123456789".index(s) end # kanji number to number (1) def kan2n(s) "〇一二三四五六七八九".index(s) end # kanji number to number (2) def kan2n2(s) case s.length when 1 "〇一二三四五六七八九十".index(s) when 2 "〇一二三四五六七八九十".index(s[1]) + 10 else raise "21以上の数値に対応していません" end end # kanji piece-type to csa def kind2csa(kind) if kind[0] == "成" { "香" => "NY", "桂" => "NK", "銀" => "NG" }[kind[1]] else { "歩" => "FU", "香" => "KY", "桂" => "KE", "銀" => "GI", "金" => "KI", "角" => "KA", "飛" => "HI", "玉" => "OU", "王" => "OU", "と" => "TO", "杏" => "NY", "圭" => "NK", "全" => "NG", "馬" => "UM", "竜" => "RY", "龍" => "RY" }[kind] end end # preset string to jkf def preset2str(preset) { "平手" => "HIRATE", "香落ち" => "KY", "右香落ち" => "KY_R", "角落ち" => "KA", "飛車落ち" => "HI", "飛香落ち" => "HIKY", "二枚落ち" => "2", "三枚落ち" => "3", "四枚落ち" => "4", "五枚落ち" => "5", "左五枚落ち" => "5_L", "六枚落ち" => "6", "八枚落ち" => "8", "十枚落ち" => "10", "その他" => "OTHER" }[preset.gsub(/\s/, "")] end end
cookpad/rrrspec
rrrspec-client/lib/rrrspec/redis_models.rb
RRRSpec.Taskset.add_task
ruby
def add_task(task) RRRSpec.redis.rpush(RRRSpec.make_key(key, 'tasks'), task.key) RRRSpec.redis.rpush(RRRSpec.make_key(key, 'tasks_left'), task.key) end
========================================================================== Tasks Public: Add a task. NOTE: This method does **NOT** enqueue to the task_queue
train
https://github.com/cookpad/rrrspec/blob/a5bde2b062ce68b1e32b8caddf194389c2ce28b0/rrrspec-client/lib/rrrspec/redis_models.rb#L301-L304
class Taskset attr_reader :key def initialize(taskset_key) @key = taskset_key end # Public: Create a new taskset. # NOTE: This method will **NOT** call ActiveTaskset.add. def self.create(rsync_name, setup_command, slave_command, worker_type, taskset_class, max_workers, max_trials, unknown_spec_timeout_sec, least_timeout_sec) now = Time.zone.now # For the reasons unknown, UUIDTools::UUID.timestamp_create changes 'now'. taskset_key = RRRSpec.make_key( 'rrrspec', 'taskset', UUIDTools::UUID.timestamp_create(now.dup) ) RRRSpec.redis.hmset( taskset_key, 'rsync_name', rsync_name, 'setup_command', setup_command, 'slave_command', slave_command, 'worker_type', worker_type, 'max_workers', max_workers, 'max_trials', max_trials, 'taskset_class', taskset_class, 'unknown_spec_timeout_sec', unknown_spec_timeout_sec.to_s, 'least_timeout_sec', least_timeout_sec.to_s, 'created_at', now.to_s, ) return new(taskset_key) end def ==(other) @key == other.key end def exist? RRRSpec.redis.exists(key) end def persisted? RRRSpec.redis.ttl(key) != -1 end def cancel ArbiterQueue.cancel(self) end # ========================================================================== # Property # Public: The path name that is used in rsync # # Returns string def rsync_name RRRSpec.redis.hget(key, 'rsync_name') end # Public: The command used in setup # # Returns string def setup_command RRRSpec.redis.hget(key, 'setup_command') end # Public: The command that invokes rrrspec slave # # Returns string def slave_command RRRSpec.redis.hget(key, 'slave_command') end # Public: Type of the worker required to run the specs # # Returns string def worker_type RRRSpec.redis.hget(key, 'worker_type') end # Public: The number of workers that is used to run the specs # # Returns number def max_workers RRRSpec.redis.hget(key, 'max_workers').to_i end # Public: The number of trials that should be made. # # Returns number def max_trials RRRSpec.redis.hget(key, 'max_trials').to_i end # Public: A value that identifies the same taskset. # # Returns string def taskset_class RRRSpec.redis.hget(key, 'taskset_class') end # Public: The timeout sec for unknown spec files. # # Returns number def unknown_spec_timeout_sec RRRSpec.redis.hget(key, 'unknown_spec_timeout_sec').to_i end # Public: Timeout sec at least any specs should wait. # # Returns number def least_timeout_sec RRRSpec.redis.hget(key, 'least_timeout_sec').to_i end # Public: Returns the created_at # # Returns Time def created_at v = RRRSpec.redis.hget(key, 'created_at') v.present? ? Time.zone.parse(v) : nil end # ========================================================================== # WorkerLogs # Public: Add a worker log def add_worker_log(worker_log) RRRSpec.redis.rpush(RRRSpec.make_key(key, 'worker_log'), worker_log.key) end # Public: Return an array of worker_logs def worker_logs RRRSpec.redis.lrange(RRRSpec.make_key(key, 'worker_log'), 0, -1).map do |key| WorkerLog.new(key) end end # ========================================================================== # Slaves # Public: Add a slave def add_slave(slave) RRRSpec.redis.rpush(RRRSpec.make_key(key, 'slave'), slave.key) end # Public: Return an array of slaves def slaves RRRSpec.redis.lrange(RRRSpec.make_key(key, 'slave'), 0, -1).map do |key| Slave.new(key) end end # ========================================================================== # Tasks # Public: Add a task. # NOTE: This method does **NOT** enqueue to the task_queue # Public: Finish the task. It is no longer appeared in the `tasks_left`. def finish_task(task) RRRSpec.redis.lrem(RRRSpec.make_key(key, 'tasks_left'), 0, task.key) end # Public: All the tasks that are contained by the taskset. # # Returns an array of the task instances def tasks RRRSpec.redis.lrange(RRRSpec.make_key(key, 'tasks'), 0, -1).map do |key| Task.new(key) end end # Public: Size of all tasks. def task_size RRRSpec.redis.llen(RRRSpec.make_key(key, 'tasks')).to_i end # Public: All the tasks that are not migrated into the persistent store. # In short, the tasks that are `add_task`ed but not `finish_task`ed. # # Returns an array of the task instances. def tasks_left RRRSpec.redis.lrange(RRRSpec.make_key(key, 'tasks_left'), 0, -1).map do |key| Task.new(key) end end # Public: Enqueue the task to the task_queue. def enqueue_task(task) RRRSpec.redis.rpush(RRRSpec.make_key(key, 'task_queue'), task.key) end # Public: Enqueue the task in the reversed way. def reversed_enqueue_task(task) RRRSpec.redis.lpush(RRRSpec.make_key(key, 'task_queue'), task.key) end # Public: Dequeue the task from the task_queue. # # Returns a task or nil if timeouts def dequeue_task(timeout) if timeout < 0 task_key = RRRSpec.redis.lpop(RRRSpec.make_key(key, 'task_queue')) else _, task_key = RRRSpec.redis.blpop(RRRSpec.make_key(key, 'task_queue'), timeout) end return nil unless task_key Task.new(task_key) end # Public: Remove all the tasks enqueued to the task_queue. def clear_queue RRRSpec.redis.del(RRRSpec.make_key(key, 'task_queue')) end # Public: Checks whether the task_queue is empty. def queue_empty? RRRSpec.redis.llen(RRRSpec.make_key(key, 'task_queue')) == 0 end # ========================================================================== # Status # Public: Current status # # Returns either nil, "running", "succeeded", "cancelled" or "failed" def status RRRSpec.redis.hget(key, 'status') end # Public: Update the status. It should be one of: # ["running", "succeeded", "cancelled", "failed"] def update_status(status) RRRSpec.redis.hset(key, 'status', status) end # Public: Current succeeded task count. A task is counted as succeeded one # if its status is "passed" or "pending". # # Returns a number def succeeded_count RRRSpec.redis.hget(key, 'succeeded_count').to_i end # Public: Increment succeeded_count def incr_succeeded_count RRRSpec.redis.hincrby(key, 'succeeded_count', 1) end # Public: Current failed task count. A task is counted as failed one if its # status is "failed". # # Returns a number def failed_count RRRSpec.redis.hget(key, 'failed_count').to_i end # Public: Increment failed_count def incr_failed_count RRRSpec.redis.hincrby(key, 'failed_count', 1) end # Public: Returns the finished_at def finished_at v = RRRSpec.redis.hget(key, 'finished_at') v.present? ? Time.zone.parse(v) : nil end # Public: Set finished_at time if it is empty def set_finished_time RRRSpec.redis.hsetnx(key, 'finished_at', Time.zone.now.to_s) end # Public: Overall logs of the taskset def log RRRSpec.redis.get(RRRSpec.make_key(key, 'log')) || "" end # Public: Append a line to the log def append_log(string) RRRSpec.redis.append(RRRSpec.make_key(key, 'log'), string) end # ========================================================================== # Serialize def to_h h = RRRSpec.redis.hgetall(key) h['key'] = key h['log'] = log h['tasks'] = tasks.map { |task| { 'key' => task.key } } h['slaves'] = slaves.map { |slave| { 'key' => slave.key } } h['worker_logs'] = worker_logs.map { |worker_log| { 'key' => worker_log.key } } RRRSpec.convert_if_present(h, 'max_workers') { |v| v.to_i } RRRSpec.convert_if_present(h, 'max_trials') { |v| v.to_i } RRRSpec.convert_if_present(h, 'unknown_spec_timeout_sec') { |v| v.to_i } RRRSpec.convert_if_present(h, 'least_timeout_sec') { |v| v.to_i } RRRSpec.convert_if_present(h, 'created_at') { |v| Time.zone.parse(v) } RRRSpec.convert_if_present(h, 'finished_at') { |v| Time.zone.parse(v) } h.delete('succeeded_count') h.delete('failed_count') h end def to_json(options=nil) to_h.to_json(options) end # ========================================================================== # Persistence def expire(sec) tasks.each { |task| task.expire(sec) } slaves.each { |slave| slave.expire(sec) } worker_logs.each { |worker_log| worker_log.expire(sec) } RRRSpec.redis.expire(key, sec) RRRSpec.redis.expire(RRRSpec.make_key(key, 'log'), sec) RRRSpec.redis.expire(RRRSpec.make_key(key, 'slave'), sec) RRRSpec.redis.expire(RRRSpec.make_key(key, 'worker_log'), sec) RRRSpec.redis.expire(RRRSpec.make_key(key, 'task_queue'), sec) RRRSpec.redis.expire(RRRSpec.make_key(key, 'tasks'), sec) RRRSpec.redis.expire(RRRSpec.make_key(key, 'tasks_left'), sec) end end
moneta-rb/moneta
lib/moneta/cache.rb
Moneta.Cache.store
ruby
def store(key, value, options = {}) @cache.store(key, value, options) @adapter.store(key, value, options) end
(see Proxy#store)
train
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/cache.rb#L64-L67
class Cache include Defaults # @api private class DSL def initialize(store, &block) @store = store instance_eval(&block) end # @api public def adapter(store = nil, &block) raise 'Adapter already set' if @store.adapter raise ArgumentError, 'Only argument or block allowed' if store && block @store.adapter = store || Moneta.build(&block) end # @api public def cache(store = nil, &block) raise 'Cache already set' if @store.cache raise ArgumentError, 'Only argument or block allowed' if store && block @store.cache = store || Moneta.build(&block) end end attr_accessor :cache, :adapter # @param [Hash] options Options hash # @option options [Moneta store] :cache Moneta store used as cache # @option options [Moneta store] :adapter Moneta store used as adapter # @yieldparam Builder block def initialize(options = {}, &block) @cache, @adapter = options[:cache], options[:adapter] DSL.new(self, &block) if block_given? end # (see Proxy#key?) def key?(key, options = {}) @cache.key?(key, options) || @adapter.key?(key, options) end # (see Proxy#load) def load(key, options = {}) if options[:sync] || (value = @cache.load(key, options)) == nil value = @adapter.load(key, options) @cache.store(key, value, options) if value != nil end value end # (see Proxy#store) # (see Proxy#increment) def increment(key, amount = 1, options = {}) @cache.delete(key, options) @adapter.increment(key, amount, options) end # (see Proxy#create) def create(key, value, options = {}) if @adapter.create(key, value, options) @cache.store(key, value, options) true else false end end # (see Proxy#delete) def delete(key, options = {}) @cache.delete(key, options) @adapter.delete(key, options) end # (see Proxy#clear) def clear(options = {}) @cache.clear(options) @adapter.clear(options) self end # (see Proxy#close) def close @cache.close @adapter.close end # (see Proxy#each_key) def each_key(&block) raise NotImplementedError, 'adapter doesn\'t support #each_key' \ unless supports? :each_key return enum_for(:each_key) unless block_given? @adapter.each_key(&block) self end # (see Proxy#features) def features @features ||= ((@cache.features + [:create, :increment, :each_key]) & @adapter.features).freeze end end
rakeoe/rakeoe
lib/rakeoe/binary_base.rb
RakeOE.BinaryBase.read_prj_settings
ruby
def read_prj_settings(file) unless File.file?(file) file = File.dirname(__FILE__)+'/prj.rake' end KeyValueReader.new(file) end
Read project file if it exists @param [String] file Filename of project file @return [KeyValueReader] New KeyValueReader object with values provided via read project file
train
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/binary_base.rb#L239-L244
class BinaryBase include Rake::DSL attr_reader :build_dir, :src_dir, :src_dirs, :inc_dirs, :test_dirs, :obj_dirs attr_accessor :name, :bin_dir, :test_dir, :settings, :tc, :prj_file, :binary, :objs, :deps, :test_deps, :test_binary, :test_objs # # The following parameters are expected in given hash params: # # @param [Hash] params # @option params [String] :name Name of the binary # @option params [String] :src_dir Base source directory # @option params [String] :bin_dir Output binary directory # @option params [String] :toolchain Toolchain builder to use # def initialize(params) check_params(params) @@all_libs ||= (PrjFileCache.project_names('LIB') + PrjFileCache.project_names('SOLIB')).uniq @@all_libs_and_deps ||= PrjFileCache.search_recursive(:names => @@all_libs, :attribute => 'ADD_LIBS') @name = params[:name] @settings = params[:settings] @src_dir = @settings['PRJ_HOME'] @bin_dir = params[:bin_dir] @tc = params[:toolchain] # derived parameters @build_dir = "#{@bin_dir}/.#{@name}" @binary = '.delete_me' @src_dirs = src_directories(src_dir, @settings['ADD_SOURCE_DIRS'].split, :subdir_only => false) @test_dirs = src_directories(src_dir, @settings['TEST_SOURCE_DIRS'].split, :subdir_only => true) @inc_dirs = src_directories(src_dir, @settings['ADD_INC_DIRS'].split << 'include/', :subdir_only => true) @inc_dirs += @src_dirs if @settings['EXPORTED_INC_DIRS'] @inc_dirs += src_directories(src_dir, @settings['EXPORTED_INC_DIRS'].split, :subdir_only => true) end @inc_dirs += lib_incs(@settings['ADD_LIBS'].split) @inc_dirs.uniq! # list of all object file directories to be created @obj_dirs = (@src_dirs+@test_dirs).map {|dir| dir.gsub(@src_dir, @build_dir)} @obj_dirs.each do |dir| directory dir end # fetch list of all sources with all supported source file extensions ignored_srcs = find_files_relative(@src_dir, @settings['IGNORED_SOURCES'].split) @srcs = (search_files(src_dirs, @tc.source_extensions) - ignored_srcs).uniq @test_srcs = search_files(test_dirs, @tc.source_extensions).uniq # special handling for Qt files if '1' == @settings['USE_QT'] mocs = assemble_moc_file_list(search_files(src_dirs, [@tc.moc_header_extension])) mocs.each do |moc| @srcs << moc CLEAN.include(moc) end @srcs.uniq! end if (@settings['TEST_FRAMEWORK'].nil? or @settings['TEST_FRAMEWORK'].empty?) @test_fw = @tc.default_test_framework else @test_fw = @tc.test_framework(@settings['TEST_FRAMEWORK']) end @objs = @srcs.map {|file| source_to_obj(file, @src_dir, @build_dir)} @deps = @objs.map {|obj| obj.ext('.d')} if has_tests? @test_objs = @test_srcs.map {|file| source_to_obj(file, @src_dir, @build_dir)} @test_deps = @test_objs.map {|obj| obj.ext('.d')} load_deps(@test_deps) @test_inc_dirs = @settings['TEST_SOURCE_DIRS'].empty? ? '' : @test_fw.include.join(' ') else @test_objs = [] @test_deps = [] @test_inc_dirs = '' end # load dependency files if already generated load_deps(@deps) # all objs are dependent on project file and platform file (@objs+@test_objs).each do |obj| file obj => [@settings['PRJ_FILE'], @tc.config.platform] end @test_binary = "#{bin_dir}/#{name}-test" handle_prj_type handle_qt if '1' == @settings['USE_QT'] # todo check all directories for existence ? end # Check params given to #initialize # # @param [Hash] params # @option params [String] :name Name of the library # @option params [String] :src_dir Base source directory of lib # @option params [String] :bin_dir Output binary directory of lib # @option params [String] :toolchain Toolchain builder to use # def check_params(params) raise 'No project name given' unless params[:name] raise 'No settings given' unless params[:settings] raise 'No build directory given' unless params[:bin_dir] raise 'No toolchain given' unless params[:toolchain] end # Qt special handling def handle_qt unless tc.qt.check_once puts '### WARN: QT prerequisites not complete!' end @settings['ADD_CFLAGS'] += tc.qt.cflags @settings['ADD_CXXFLAGS'] += tc.qt.cflags @settings['ADD_LDFLAGS'] += tc.qt.ldflags @settings['ADD_LIBS'] += tc.qt.libs end # Settings according to project type def handle_prj_type # TODO make these settable in defaults.rb case @settings['PRJ_TYPE'] when 'SOLIB' @binary = "#{bin_dir}/lib#{name}.so" @settings['ADD_CFLAGS'] += ' -fPIC -Wl,-export-dynamic' @settings['ADD_CXXFLAGS'] += ' -fPIC -Wl,-export-dynamic' when 'LIB' @binary = "#{bin_dir}/lib#{name}.a" when 'APP' @binary = "#{bin_dir}/#{name}" @app_lib = "#{build_dir}/lib#{name}-app.a" when 'DISABLED' puts "### WARNING: project #{name} is disabled !!" else raise "unsupported project type #{@settings['PRJ_TYPE']}" end end # Returns array of source code directories assembled via given parameters # # @param [String] main_dir Main directory where project source is located # @param [Array] sub_dirs List of sub directories inside main_dir # @param [Hash] params Option hash to control how directories should be added # @option params [Boolean] :subdir_only If true: only return sub directories, not main_dir in result # # @return [Array] List of sub directories assembled from each element in sub_dirs and appended to main_dir def src_directories(main_dir, sub_dirs, params={}) if params[:subdir_only] all_dirs=[] else all_dirs = [main_dir] end sub_dirs.each do |dir| all_dirs << "#{main_dir}/#{dir}" end all_dirs.compact end # Returns list of include directories for name of libraries in parameter libs # # @param [Array] libs List of library names # # @return [Array] List of includes found for given library names # def lib_incs(libs=[]) includes = Array.new libs.each do |name, param| lib_includes = PrjFileCache.exported_lib_incs(name) includes += lib_includes if lib_includes.any? end includes end # Search files recursively in directory with given extensions # # @param [Array] directories Array of directories to search # @param [Array] extensions Array of file extensions to use for search # # @return [Array] list of all found files # def search_files(directories, extensions) extensions.each_with_object([]) do |ext, obj| directories.each do |dir| obj << FileList["#{dir}/*#{ext}"] end end.flatten.compact end # Search list of files relative to given directory # # @param [String] directory Main directory # @param [Array] files List with Filenames # # @return [Array] List of path names of all found files # def find_files_relative(directory, files) return [] unless files.any? files.each_with_object([]) do |file, obj| path = "#{directory}/#{file}" obj << path if File.exist?(path) end end # Assemble list of to be generated moc files # # @param [Array] include_files List of include files # # @return [Array] List of to be generated moc_ files detected # via given include file list def assemble_moc_file_list(include_files) include_files.map do |file| "#{File.dirname(file)}/moc_#{File.basename(file).ext(@tc.moc_source)}" if fgrep(file,'Q_OBJECT') end.compact end # Read project file if it exists # # @param [String] file Filename of project file # @return [KeyValueReader] New KeyValueReader object with values provided via read project file # Depending on the read settings we have to # change various values like CXXFLAGS, LDFLAGS, etc. def override_toolchain_vars end # Returns if any test sources found def has_tests? return @test_srcs.any? end # Loads dependency files if already generated # # @param [Array] deps List of dependency files that have been generated via e.g. 'gcc -MM' def load_deps(deps) deps.each do |file| if File.file?(file) Rake::MakefileLoader.new.load(file) end end end # Disable a build. Is called from derived class # if e.g. set in prj.rake def disable_build desc '*** DISABLED ***' task @name => @binary file @binary do end end # Checks if projects build prerequisites are met. # # If at least one of the following criteria are met, the method returns false: # * project variable PRJ_TYPE == "DISABLED" # * project variable IGNORED_PLATFORMS contains build platform # @return true if project can be built on current platform # @return false if project settings prohibit building def project_can_build? (settings['PRJ_TYPE'] != 'DISABLED') and (! tc.current_platform_any?(settings['IGNORED_PLATFORMS'].split)) end # Match the file stub (i.e. the filename with absolute path without extension) # to one of all known source (including test source) files # # @param [String] stub A filename stub without its extension # @return [String] The found source filename # # TODO optimization possible for faster lookup by using hash of source files instead of array def stub_to_src(stub) (@srcs+@test_srcs).each do |src| if src.ext('') == stub return src end end nil end # Transforms an object file name to its source file name by replacing # build directory base with the source directory base and then iterating list of # known sources to match # # @param [String] obj Object filename # @param [String] source_dir Project source base directory # @param [String] obj_dir Project build base directory # @return [String] Mapped filename # def obj_to_source(obj, source_dir, obj_dir) stub = obj.gsub(obj_dir, source_dir).ext('') src = stub_to_src(stub) return src if src raise "No matching source for #{obj} found." end # Transforms a source file name in to its object file name by replacing # file name extension and the source directory base with the build directory base # # @param [String] src Source filename # @param [String] source_dir Project source base directory # @param [String] obj_dir Project build base directory # @return [String] Mapped filename # def source_to_obj(src, source_dir, obj_dir) exts = '\\' + @tc.source_extensions.join('|\\') src.sub(/(#{exts})$/, '.o').gsub(source_dir, obj_dir) end # Transforms a source file name in to its dependency file name by replacing # file name extension and the source directory base with the build directory base # # @param [String] src Source filename # @param [String] source_dir Project source base directory # @param [String] dep_dir Project dependency base directory # @return [String] Mapped filename # def source_to_dep(src, source_dir, dep_dir) exts = '\\' + @tc.source_extensions.join('|\\') src.sub(/(#{exts})$/, '.d').gsub(source_dir, dep_dir) end # Transforms an object file into its corresponding dependency file name by replacing # file name extension and object directory with dependency directory # # @param [String] src Source filename # @param [String] dep_dir Project dependency base directory # @param [String] obj_dir Project object base directory # @return [String] Mapped filename # def obj_to_dep(src, dep_dir, obj_dir) src.sub(/\.o$/, '.d').gsub(dep_dir, obj_dir) end # Transforms a dependency file name into its corresponding source file name by replacing # file name extension and object directory with dependency directory. # Searches through list of source files to find it. # # @param [String] dep Source filename # @param [String] source_dir Project source base directory # @param [String] dep_dir Project dependency base directory # @return [String] Mapped filename # def dep_to_source(dep, source_dir, dep_dir) stub = dep.gsub(dep_dir, source_dir).ext('') src = stub_to_src(stub) return src if src raise "No matching source for #{dep} found." end # Create build rules for generating an object. Dependency to corresponding source file is made via proc # object def create_build_rules platform_flags_fixup(search_libs(@settings)) incs = inc_dirs # map object to source file and make it dependent on creation of all object directories rule /#{build_dir}\/.*\.o/ => [ proc {|tn| obj_to_source(tn, src_dir, build_dir)}] + obj_dirs do |t| if t.name =~ /\/tests\// # test framework additions incs << @test_inc_dirs unless incs.include?(@test_inc_dirs) @settings['ADD_CXXFLAGS'] += @test_fw.cflags @settings['ADD_CFLAGS'] += @test_fw.cflags end tc.obj(:source => t.source, :object => t.name, :settings => @settings, :includes => incs.uniq) end # map dependency to source file and make it dependent on creation of all object directories rule /#{build_dir}\/.*\.d/ => [ proc {|tn| dep_to_source(tn, src_dir, build_dir)}] + obj_dirs do |t| # don't generate dependencies for assembler files XXX DS: use tc.file_extensions[:as_sources] if (t.source.end_with?('.S') || t.source.end_with?('.s')) tc.touch(t.name) next end if t.name =~ /\/tests\// # test framework additions incs << @test_inc_dirs unless incs.include?(@test_inc_dirs) @settings['ADD_CXXFLAGS'] += @test_fw.cflags @settings['ADD_CFLAGS'] += @test_fw.cflags end tc.dep(:source => t.source, :dep => t.name, :settings => @settings, :includes => incs.uniq) end # make moc source file dependent on corresponding header file, XXX DS: only if project uses QT rule /#{src_dir}\/.*moc_.*#{Regexp.escape(tc.moc_source)}$/ => [ proc {|tn| tn.gsub(/moc_/, '').ext(tc.moc_header_extension) } ] do |t| tc.moc(:source => t.source, :moc => t.name, :settings => @settings) end end # Change ADD_CFLAGS, ADD_CXXFLAGS, ADD_LDFLAGS according to settings in platform file. # # @param libs [Array] Array of libraries to be considered # def platform_flags_fixup(libs) libs[:all].each do |lib| ps = tc.platform_settings_for(lib) unless ps.empty? @settings['ADD_CFLAGS'] += " #{ps[:CFLAGS]}" if ps[:CFLAGS] @settings['ADD_CXXFLAGS'] += " #{ps[:CXXFLAGS]}" if ps[:CXXFLAGS] # remove all -lXX settings from ps[:LDFLAGS] and use rest for @settings['ADD_LDFLAGS'], # -lXX is set in Toolchain#linker_line_for @settings['ADD_LDFLAGS'] += ps[:LDFLAGS].gsub(/(\s|^)+-l\S+/, '') if ps[:LDFLAGS] end end end # Search dependent libraries as specified in ADD_LIBS setting # of prj.rake file # # @param [String] settings The project settings definition # # @return [Hash] Containing the following components mapped to an array: # @option return [Array] :local all local libs found by toolchain # @option return [Array] :local_alibs local static libs found by toolchain # @option return [Array] :local_solibs local shared libs found by toolchain # @option return [Array] :all local + external libs # def search_libs(settings) # get all libs specified in ADD_LIBS search_libs = settings['ADD_LIBS'].split our_lib_deps = [] search_libs.each do |lib| our_lib_deps << lib deps_of_lib = @@all_libs_and_deps[lib] if deps_of_lib our_lib_deps += deps_of_lib end end our_lib_deps.uniq! # match libs found by toolchain solibs_local = [] alibs_local = [] our_lib_deps.each do |lib| if PrjFileCache.contain?('LIB', lib) alibs_local << lib elsif PrjFileCache.contain?('SOLIB', lib) solibs_local << lib end end local_libs = (alibs_local + solibs_local) || [] # return value is a hash { :local => local_libs, :local_alibs => alibs_local, :local_solibs => solibs_local, :all => our_lib_deps } end # Iterate over each local library and execute given block # # @param [Block] block The block that is executed # def each_local_lib(&block) libs = search_libs(@settings) libs[:local].each do |lib| yield(lib) end end # # Returns absolute paths to given libraries, if they are local libraries # of the current project. # def paths_of_libs(some_libs) local_libs = Array.new some_libs.each do |lib| if PrjFileCache.contain?('LIB', lib) local_libs << "#{tc.settings['LIB_OUT']}/lib#{lib}.a" elsif PrjFileCache.contain?('SOLIB', lib) local_libs << "#{tc.settings['LIB_OUT']}/lib#{lib}.so" end end local_libs end # # Returns absolute paths to dependend local libraries, i.e. libraries # of the current project. # def paths_of_local_libs local_libs = Array.new each_local_lib() do |lib| if PrjFileCache.contain?('LIB', lib) local_libs << "#{tc.settings['LIB_OUT']}/lib#{lib}.a" elsif PrjFileCache.contain?('SOLIB', lib) local_libs << "#{tc.settings['LIB_OUT']}/lib#{lib}.so" end end local_libs end # Greps for a string in a file # # @param [String] file Filename to be used for operation # @param [String] string String to be searched for in file # # @return [boolean] true if string found inside file, false otherwise # def fgrep(file, string) open(file).grep(/#{string}/).any? end end
etewiah/property_web_builder
app/controllers/pwb/api/v1/properties_controller.rb
Pwb.Api::V1::PropertiesController.bulk_create
ruby
def bulk_create propertiesJSON = params["propertiesJSON"] unless propertiesJSON.is_a? Array propertiesJSON = JSON.parse propertiesJSON end new_props = [] existing_props = [] errors = [] properties_params(propertiesJSON).each_with_index do |property_params, index| propertyJSON = propertiesJSON[index] if Pwb::Prop.where(reference: propertyJSON["reference"]).exists? existing_props.push Pwb::Prop.find_by_reference propertyJSON["reference"] # propertyJSON else begin new_prop = Pwb::Prop.create(property_params) # new_prop = Pwb::Prop.create(propertyJSON.except("features", "property_photos", "image_urls", "last_retrieved_at")) # create will use website defaults for currency and area_unit # need to override that if propertyJSON["currency"] new_prop.currency = propertyJSON["currency"] new_prop.save! end if propertyJSON["area_unit"] new_prop.area_unit = propertyJSON["area_unit"] new_prop.save! end # TODO - go over supported locales and save title and description # into them # if propertyJSON["features"] # TODO - process feature (currently not retrieved by PWS so not important) # new_prop.set_features=propertyJSON["features"] # end if propertyJSON["property_photos"] # uploading images can slow things down so worth setting a limit max_photos_to_process = 20 # TODO - retrieve above as a param propertyJSON["property_photos"].each_with_index do |property_photo, index| if index > max_photos_to_process return end photo = PropPhoto.create photo.sort_order = property_photo["sort_order"] || nil photo.remote_image_url = property_photo["url"] # photo.remote_image_url = property_photo["image"]["url"] || property_photo["url"] photo.save! new_prop.prop_photos.push photo end end new_props.push new_prop rescue => err errors.push err.message # logger.error err.message end end end return render json: { new_props: new_props, existing_props: existing_props, errors: errors } end
def set_default_currency @model end
train
https://github.com/etewiah/property_web_builder/blob/fba4e6d4ffa7bc1f4d3b50dfa5a6a9fbfee23f21/app/controllers/pwb/api/v1/properties_controller.rb#L12-L78
class Api::V1::PropertiesController < JSONAPI::ResourceController # Skipping action below allows me to browse to endpoint # without having set mime type skip_before_action :ensure_valid_accept_media_type # def set_default_currency # @model # end # TODO: rename to update_features: def update_extras property = Prop.find(params[:id]) # The set_features method goes through ea property.set_features = params[:extras].to_unsafe_hash property.save! return render json: property.features end def order_photos ordered_photo_ids = params[:ordered_photo_ids] ordered_array = ordered_photo_ids.split(",") ordered_array.each.with_index(1) do |photo_id, index| photo = PropPhoto.find(photo_id) photo.sort_order = index photo.save! end @property = Prop.find(params[:prop_id]) return render json: @property.prop_photos # { "success": true }, status: :ok, head: :no_content end def add_photo_from_url # subdomain = request.subdomain || "" property = Prop.find(params[:id]) remote_urls = params[:remote_urls].split(",") photos_array = [] remote_urls.each do |remote_url| photo = PropPhoto.create # photo.subdomain = subdomain # photo.folder = current_tenant_model.whitelabel_country_code # photo.tenant_id = current_tenant_model.id # need the regex below to remove leading and trailing quotationmarks # photo.remote_image_url = remote_url.gsub!(/\A"|"\Z/, '') photo.remote_image_url = remote_url photo.save! property.prop_photos.push photo photos_array.push photo end # if json below is not valid, success callback on client will fail return render json: photos_array.to_json # { "success": true }, status: :ok, head: :no_content end def add_photo # subdomain = request.subdomain || "" property = Prop.find(params[:id]) files_array = params[:file] photos_array = [] files_array.each do |file| photo = PropPhoto.create # photo.subdomain = subdomain # photo.folder = current_tenant_model.whitelabel_country_code # photo.tenant_id = current_tenant_model.id photo.image = file photo.save! # photo.update_attributes(:url => photo.image.metadata['url']) # ul = Pwb::PropPhotoUploader.new # ul.store!(file) # tried various options like above to ensure photo.image.url # which is nil at this point gets updated # - in the end it was just a reload that was needed: photo.reload property.prop_photos.push photo photos_array.push photo end # if json below is not valid, success callback on client will fail return render json: photos_array.to_json # { "success": true }, status: :ok, head: :no_content end def remove_photo photo = PropPhoto.find(params[:id]) property = Prop.find(params[:prop_id]) property.prop_photos.destroy photo # if json below is not valid, success callback on client will fail return render json: { "success": true }, status: :ok, head: :no_content end # def set_owner # property = Prop.find(params[:prop_id]) # client = Client.find(params[:client_id]) # property.owners = [client] # property.save! # return render json: "success" # end # def unset_owner # property = Prop.find(params[:prop_id]) # client = Client.find(params[:client_id]) # property.owners = [] # property.save! # return render json: "success" # end private def properties_params propertiesJSON # propertiesJSON = params["propertiesJSON"] # unless propertiesJSON.is_a? Array # propertiesJSON = JSON.parse propertiesJSON # end # pp = ActionController::Parameters.new(propertiesJSON) pp = ActionController::Parameters.new({propertiesJSON: propertiesJSON}) # https://github.com/rails/strong_parameters/issues/140 # params.require(:propertiesJSON).map do |p| pp.require(:propertiesJSON).map do |p| p.permit( :title, :description, :reference, :street_address, :city, :postal_code, :price_rental_monthly_current, :for_rent_short_term, :visible, :count_bedrooms, :count_bathrooms, :longitude, :latitude ) # ActionController::Parameters.new(p.to_hash).permit(:title, :description) end end end
projectcypress/health-data-standards
lib/hqmf-parser/2.0/data_criteria_helpers/dc_definition_from_template_or_type_extract.rb
HQMF2.DataCriteriaTypeAndDefinitionExtraction.handle_known_template_id
ruby
def handle_known_template_id(template_id) case template_id when VARIABLE_TEMPLATE @derivation_operator = HQMF::DataCriteria::INTERSECT if @derivation_operator == HQMF::DataCriteria::XPRODUCT @definition ||= 'derived' @variable = true @negation = false when SATISFIES_ANY_TEMPLATE @definition = HQMF::DataCriteria::SATISFIES_ANY @negation = false when SATISFIES_ALL_TEMPLATE @definition = HQMF::DataCriteria::SATISFIES_ALL @derivation_operator = HQMF::DataCriteria::INTERSECT @negation = false else return false end true end
Given a template id, modify the variables inside this data criteria to reflect the template
train
https://github.com/projectcypress/health-data-standards/blob/252d4f0927c513eacde6b9ea41b76faa1423c34b/lib/hqmf-parser/2.0/data_criteria_helpers/dc_definition_from_template_or_type_extract.rb#L36-L54
module DataCriteriaTypeAndDefinitionExtraction VARIABLE_TEMPLATE = '0.1.2.3.4.5.6.7.8.9.1' SATISFIES_ANY_TEMPLATE = '2.16.840.1.113883.10.20.28.3.108' SATISFIES_ALL_TEMPLATE = '2.16.840.1.113883.10.20.28.3.109' def extract_definition_from_template_or_type # Try to determine what kind of data criteria we are dealing with # First we look for a template id and if we find one just use the definition # status and negation associated with that # If no template id or not one we recognize then try to determine type from # the definition element extract_definition_from_type unless extract_definition_from_template_id end # Given a template id, derive (if available) the definition for the template. # The definitions are stored in hqmf-model/data_criteria.json. def extract_definition_from_template_id found = false @template_ids.each do |template_id| defs = HQMF::DataCriteria.definition_for_template_id(template_id, 'r2') if defs @definition = defs['definition'] @status = defs['status'].length > 0 ? defs['status'] : nil found ||= true else found ||= handle_known_template_id(template_id) end end found end # Given a template id, modify the variables inside this data criteria to reflect the template # Extract the definition (sometimes status, sometimes other elements) of the data criteria based on the type def extract_definition_from_type # If we have a specific occurrence of a variable, pull attributes from the reference. # IDEA set this up to be called from dc_specific_and_source_extract, the number of # fields changed by handle_specific_variable_ref may pose an issue. extract_information_for_specific_variable if @variable && @specific_occurrence if @entry.at_xpath('./cda:grouperCriteria') @definition ||= 'derived' return end # See if we can find a match for the entry definition value and status. entry_type = attr_val('./*/cda:definition/*/cda:id/@extension') handle_entry_type(entry_type) end # Extracts information from a reference for a specific def extract_information_for_specific_variable reference = @entry.at_xpath('./*/cda:outboundRelationship/cda:criteriaReference', HQMF2::Document::NAMESPACES) if reference ref_id = strip_tokens( "#{HQMF2::Utilities.attr_val(reference, 'cda:id/@extension')}_#{HQMF2::Utilities.attr_val(reference, 'cda:id/@root')}") end reference_criteria = @data_criteria_references[ref_id] if ref_id # if the reference is derived, pull from the original variable if reference_criteria && reference_criteria.definition == 'derived' reference_criteria = @data_criteria_references["GROUP_#{ref_id}"] end return unless reference_criteria handle_specific_variable_ref(reference_criteria) end # Apply additional information to a specific occurrence's elements from the criteria it references. def handle_specific_variable_ref(reference_criteria) # if there are no referenced children, then it's a variable representing # a single data criteria, so just reference it if reference_criteria.children_criteria.empty? @children_criteria = [reference_criteria.id] # otherwise pull all the data criteria info from the reference else @field_values = reference_criteria.field_values @temporal_references = reference_criteria.temporal_references @subset_operators = reference_criteria.subset_operators @derivation_operator = reference_criteria.derivation_operator @definition = reference_criteria.definition @description = reference_criteria.description @status = reference_criteria.status @children_criteria = reference_criteria.children_criteria end end # Generate the definition and/or status from the entry type in most cases. # If the entry type is nil, and the value is a specific occurrence, more parsing may be necessary. def handle_entry_type(entry_type) # settings is required to trigger exceptions, which set the definition HQMF::DataCriteria.get_settings_for_definition(entry_type, @status) @definition = entry_type rescue # if no exact match then try a string match just using entry definition value case entry_type when 'Medication', 'Medications' @definition = 'medication' @status = 'active' unless @status when 'RX' @definition = 'medication' @status = 'dispensed' unless @status when nil definition_for_nil_entry else @definition = extract_definition_from_entry_type(entry_type) end end # If there is no entry type, extract the entry type from what it references, and extract additional information for # specific occurrences. If there are no outbound references, print an error and mark it as variable. def definition_for_nil_entry reference = @entry.at_xpath('./*/cda:outboundRelationship/cda:criteriaReference', HQMF2::Document::NAMESPACES) ref_id = nil unless reference.nil? ref_id = "#{HQMF2::Utilities.attr_val(reference, 'cda:id/@extension')}_#{HQMF2::Utilities.attr_val(reference, 'cda:id/@root')}" end reference_criteria = @data_criteria_references[strip_tokens(ref_id)] unless ref_id.nil? if reference_criteria # we only want to copy the reference criteria definition, status, and code_list_id if this is this is not a grouping criteria (i.e., there are no children) if @children_criteria.blank? @definition = reference_criteria.definition @status = reference_criteria.status if @specific_occurrence @title = reference_criteria.title @description = reference_criteria.description @code_list_id = reference_criteria.code_list_id end else # if this is a grouping data criteria (has children) mark it as derived and only pull title and description from the reference criteria @definition = 'derived' if @specific_occurrence @title = reference_criteria.title @description = reference_criteria.description end end else puts "MISSING_DC_REF: #{ref_id}" unless @variable @definition = 'variable' end end # Given an entry type (which describes the criteria's purpose) return the appropriate defintino def extract_definition_from_entry_type(entry_type) case entry_type when 'Problem', 'Problems' 'diagnosis' when 'Encounter', 'Encounters' 'encounter' when 'LabResults', 'Results' 'laboratory_test' when 'Procedure', 'Procedures' 'procedure' when 'Demographics' definition_for_demographic when 'Derived' 'derived' else fail "Unknown data criteria template identifier [#{entry_type}]" end end # Return the definition for a known subset of patient characteristics def definition_for_demographic demographic_type = attr_val('./cda:observationCriteria/cda:code/@code') demographic_translation = { '21112-8' => 'patient_characteristic_birthdate', '424144002' => 'patient_characteristic_age', '263495000' => 'patient_characteristic_gender', '102902016' => 'patient_characteristic_languages', '125680007' => 'patient_characteristic_marital_status', '103579009' => 'patient_characteristic_race' } if demographic_translation[demographic_type] demographic_translation[demographic_type] else fail "Unknown demographic identifier [#{demographic_type}]" end end end
koraktor/metior
lib/metior/report.rb
Metior.Report.render
ruby
def render Mustache.view_namespace = self.class result = {} self.class.views.each do |view_name| template = File.join 'templates', "#{view_name}.mustache" template_path = self.class.find template view = File.join 'views', "#{view_name}.rb" view_path = self.class.find view Mustache.template_path = File.dirname template_path Mustache.view_path = File.dirname view_path mustache = Mustache.view_class(view_name).new(self) mustache.template_name = view_name result[view_name] = mustache.render end result end
Renders the views of this report (or the its ancestors) and returns them in a hash @return [Hash<Symbol, String>] The names of the views and the corresponding rendered content
train
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/report.rb#L191-L209
module Report # The path where the reports bundled with Metior live REPORTS_PATH = File.expand_path File.join File.dirname(__FILE__), '..', '..', 'reports' # Returns the commits analyzed by this report # # @return [CommitCollection] The commits analyzed by this report attr_reader :commits # Returns the range of commits that should be analyzed by this report # # @return [String, Range] The range of commits covered by this report attr_reader :range # Returns the repository that should be analyzed by this report # # @return [Repository] The repository attached to this report attr_reader :repository module ClassMethods # Sets or returns the paths of the assets that need to be included in the # report # # @param [Array<String>] assets The paths of the assets for this report # @return [Array<String>] The paths of the assets to include def assets(assets = nil) if assets.nil? if class_variable_defined? :@@assets class_variable_get :@@assets else self == Report ? [] : superclass.assets end else class_variable_set :@@assets, assets end end # Find a file inside this report or one of its ancestors # # @param [String] file The name of the file to find # @param [Report] report The report this file was initially requested for # @return [String, nil] The absolute path of the file or `nil` if it # doesn't exist in this reports hierarchy def find(file, report = self) current_path = File.join self.path, file if File.exist? current_path current_path else if superclass == Object raise FileNotFoundError.new file, report end superclass.find file, report end end # Returns the file system path this report resides in # # @return [String] The path of this report def path File.join class_variable_get(:@@base_path), id.to_s end # Returns the file system path this report's templates reside in # # @return [String] The path of this report's templates def template_path File.join path, 'templates' end # Returns the file system path this report's views reside in # # @return [String] The path of this report's views def view_path File.join path, 'views' end # Sets or returns the symbolic names of the main views this report consists # of # # @param [Array<Symbol>] views The views for this report # @return [Array<Symbol>] This report's views def views(views = nil) if views.nil? if class_variable_defined? :@@views class_variable_get :@@views else self == Report ? [] : superclass.views end else class_variable_set :@@views, views end end end # Create a new report instance for the given report name, repository and # commit range # # @param [String, Symbol] name The name of the report to load and # initialize # @param [Repository] repository The repository to analyze # @param [String, Range] range The commit range to analyze # @return [Report] The requested report def self.create(name, repository, range = repository.current_branch) Metior.find_report(name).new(repository, range) end # Automatically registers a new report subclass as an available report type # # This will also set the path of the new report class, so it can find its # views, templates and assets. # # @param [Module] mod A report subclass def self.included(mod) mod.extend ClassMethods mod.extend Metior::Registerable base_path = File.dirname caller.first.split(':').first mod.send :class_variable_set, :@@base_path, base_path end # Creates a new report for the given repository and commit range # # @param [Repository] repository The repository to analyze # @param [String, Range] range The commit range to analyze def initialize(repository, range = repository.current_branch) @range = range @repository = repository @commits = repository.commits range init end # Generates this report's output into the given target directory # # This will generate individual HTML files for the main views of the # report. # # @param [String] target_dir The target directory of the report # @param [Boolean] with_assets If `false` the report's assets will not be # copied to the target directory def generate(target_dir, with_assets = true) target_dir = File.expand_path target_dir copy_assets target_dir if with_assets render.each do |view_name, output| file_name = File.join target_dir, view_name.to_s.downcase + '.html' begin output_file = File.open file_name, 'wb' output_file.write output ensure output_file.close end end end # Initializes a new report instance # # This can be used to gather initial data, e.g. used by multiple views. # # @abstract Override this method to customize the initial setup of a report def init end # Renders the views of this report (or the its ancestors) and returns them # in a hash # # @return [Hash<Symbol, String>] The names of the views and the # corresponding rendered content private # Copies the assets coming with this report to the given target directory # # This will copy the files and directories that have been specified for the # report from the report's path (or the report's ancestors) into the target # directory. # # @param [String] target_dir The target directory of the report # @see .assets def copy_assets(target_dir) FileUtils.mkdir_p target_dir self.class.assets.map do |asset| asset_path = self.class.find asset asset_dir = File.join target_dir, File.dirname(asset) FileUtils.mkdir_p asset_dir unless File.exists? asset_dir FileUtils.cp_r asset_path, asset_dir end end end
tbuehlmann/ponder
lib/ponder/thaum.rb
Ponder.Thaum.parse
ruby
def parse(message) message.chomp! if message =~ /^PING \S+$/ if @config.hide_ping_pongs send_data message.sub(/PING/, 'PONG') else @loggers.info "<< #{message}" raw message.sub(/PING/, 'PONG') end else @loggers.info "<< #{message}" event_data = IRC::Events::Parser.parse(message, @isupport['CHANTYPES']) parse_event_data(event_data) unless event_data.empty? end end
parsing incoming traffic
train
https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/thaum.rb#L79-L94
class Thaum include IRC attr_reader :config, :callbacks, :isupport, :channel_list, :user_list, :connection, :loggers attr_accessor :connected, :deferrables def initialize(&block) # default settings @config = OpenStruct.new( :server => 'chat.freenode.org', :port => 6667, :ssl => false, :nick => "Ponder#{rand(10_000)}", :username => 'Ponder', :real_name => 'Ponder Stibbons', :verbose => true, :logging => false, :reconnect => true, :reconnect_interval => 30, :hide_ping_pongs => true, :rejoin_after_kick => false ) # custom settings block.call(@config) if block_given? # setting up loggers @console_logger = if @config.verbose Logging::Twoflogger.new($stdout) else Logging::BlindIo.new end @logger = if @config.logging if @config.logger @config.logger else log_path = File.join($0, 'logs', 'log.log') log_dir = File.dirname(log_path) FileUtils.mkdir_p(log_dir) unless File.exist?(log_dir) Logging::Twoflogger.new(log_path, File::WRONLY | File::APPEND) end else Logging::BlindIo.new end @loggers = Logging::LoggerList.new @loggers.push(@console_logger, @logger) @connected = false # user callbacks @callbacks = Hash.new { |hash, key| hash[key] = [] } # setting up isuport @isupport = ISupport.new setup_default_callbacks setup_channel_and_user_tracking end def on(event_type = :channel, match = //, *options, &block) options = options.extract_options! callback = Callback.new(match, options, block) @callbacks[event_type] << callback callback end def connect @loggers.info '-- Starting Ponder' EventMachine::run do @connection = EventMachine::connect(@config.server, @config.port, Connection, self) end end # parsing incoming traffic # Each matching callback will run in its own fiber. So the execution # of code can be stopped until necessary data (eg from a WHOIS) gets in. # # The callback processing is exception handled, so the EM reactor won't die # from exceptions. def process_callbacks(event_type, event_data) @callbacks[event_type].each do |callback| fiber = Fiber.new do begin callback.call(event_data) rescue => e @loggers.error "-- #{e.class}: #{e.message}" e.backtrace.each { |line| @loggers.error("-- #{line}") } end end # If the callback has a :defer option, call it in a thread # from the EM thread pool. Else call it in the reactor thread. if callback.options[:defer] EM.defer(fiber.resume) else fiber.resume end end end private # parses incoming traffic (types) def parse_event_data(event_data) if ((event_data[:type] == 376) || (event_data[:type] == 422)) && !@connected @connected = true process_callbacks(:connect, event_data) end process_callbacks(event_data[:type], event_data) end # Default callbacks for PING, VERSION, TIME and ISUPPORT processing. def setup_default_callbacks on :query, /^\001PING \d+\001$/ do |event_data| time = event_data[:message].scan(/\d+/)[0] notice event_data[:nick], "\001PING #{time}\001" end on :query, /^\001VERSION\001$/ do |event_data| notice event_data[:nick], "\001VERSION Ponder #{Ponder::VERSION} (https://github.com/tbuehlmann/ponder)\001" end on :query, /^\001TIME\001$/ do |event_data| notice event_data[:nick], "\001TIME #{Time.now.strftime('%a %b %d %H:%M:%S %Y')}\001" end on 005 do |event_data| @isupport.parse event_data[:params] end end def setup_channel_and_user_tracking @channel_list = ChannelList.new @user_list = UserList.new on :connect do thaum = User.new(@config.nick, self) @user_list.add(thaum, true) end on :join do |event_data| joined_user = { :nick => event_data.delete(:nick), :user => event_data.delete(:user), :host => event_data.delete(:host) } channel = event_data.delete(:channel) # TODO: Update existing users with user/host information. # Refactor user = @user_list.find(joined_user[:nick]) if user if user.thaum? channel = Channel.new(channel, self) channel.get_mode @channel_list.add channel else channel = @channel_list.find(channel) end else channel = @channel_list.find(channel) user = User.new(joined_user[:nick], self) @user_list.add user end channel.add_user(user, []) event_data[:join] = IRC::Events::Join.new(user, channel) end on 353 do |event_data| channel_name = event_data[:params].split(' ')[2] channel = @channel_list.find(channel_name) nicks_with_prefixes = event_data[:params].scan(/:(.*)/)[0][0].split(' ') nicks, prefixes = [], [] channel_prefixes = @isupport['PREFIX'].values.map do |p| Regexp.escape(p) end.join('|') nicks_with_prefixes.each do |nick_with_prefixes| nick = nick_with_prefixes.gsub(/#{channel_prefixes}/, '') prefixes = nick_with_prefixes.scan(/#{channel_prefixes}/) user = @user_list.find(nick) unless user user = User.new(nick, self) @user_list.add(user) end channel.add_user(user, prefixes) end end on :part do |event_data| nick = event_data.delete(:nick) user = event_data.delete(:user) host = event_data.delete(:host) channel = event_data.delete(:channel) message = event_data.delete(:message) # TODO: Update existing users with user/host information. user = @user_list.find(nick) channel = @channel_list.find(channel) if user && user.thaum? # Remove the channel from the channel_list. @channel_list.remove(channel) # Remove all users from the user_list that do not share channels # with the Thaum. all_known_users = @channel_list.channels.map(&:users).flatten @user_list.kill_zombie_users(all_known_users) else channel.remove_user nick remove_user = @channel_list.channels.none? do |_channel| _channel.has_user? nick end @user_list.remove(nick) if remove_user end event_data[:part] = IRC::Events::Part.new(user, channel, message) end on :kick do |event_data| nick = event_data.delete(:nick) user = event_data.delete(:user) host = event_data.delete(:host) channel = event_data.delete(:channel) victim = event_data.delete(:victim) message = event_data.delete(:message) channel = @channel_list.find(channel) kicker = @user_list.find(nick) victim = @user_list.find(victim) channel.remove_user victim.nick if victim.thaum? # Remove the channel from the channel_list. @channel_list.remove(channel) # Remove all users from the user_list that do not share channels # with the Thaum. all_known_users = @channel_list.channels.map(&:users).flatten @user_list.kill_zombie_users(all_known_users) else remove_user = @channel_list.channels.none? do |_channel| _channel.has_user?(victim) end @user_list.remove(victim.nick) if remove_user end event_data[:kick] = Ponder::IRC::Events::Kick.new(kicker, victim, channel, message) end # If @config.rejoin_after_kick is set to `true`, let # the Thaum rejoin a channel after being kicked. on :kick do |event_data| if @config.rejoin_after_kick && event_data[:kick].victim.thaum? key = event_data[:kick].channel.modes['k'] event_data[:kick].channel.join key end end on :quit do |event_data| nick = event_data.delete(:nick) user = event_data.delete(:user) host = event_data.delete(:host) message = event_data.delete(:message) # TODO: Update existing users with user/host information. user = @user_list.find nick if user && user.thaum? channels = @channel_list.clear @user_list.clear else channels = @channel_list.remove_user(nick) @user_list.remove nick end event_data[:quit] = IRC::Events::Quit.new(user, channels, message) end on :disconnect do |event_data| @channel_list.clear @user_list.clear end on :channel do |event_data| nick = event_data[:nick] user = event_data[:user] host = event_data[:host] channel = event_data[:channel] message = event_data[:message] channel = @channel_list.find channel user = @user_list.find nick # TODO: Update existing users with user/host information. event_data[:message] = IRC::Events::Message.new(user, message, channel) end on :query do |event_data| nick = event_data[:nick] user = event_data[:user] host = event_data[:host] message = event_data[:message] user = @user_list.find nick # TODO: Update existing users with user/host information. event_data[:message] = IRC::Events::Message.new(user, message) end on :channel_mode do |event_data| # TODO: Update existing users with user/host information. # nick = event_data[:nick] # user = event_data[:user] # host = event_data[:host] channel = event_data.delete(:channel) nick = event_data.delete(:nick) params = event_data.delete(:params) modes = event_data.delete(:modes) channel = @channel_list.find(channel) event_data[:channel] = channel event_data[:user] = @user_list.find(nick) mode_changes = IRC::Events::ModeParser.parse(modes, params, @isupport) event_data[:channel_modes] = mode_changes.map do |mode_change| IRC::Events::ChannelMode.new(mode_change.merge(:channel => channel)) end event_data[:channel_modes].each do |mode| channel.set_mode(mode, isupport) end end # Response to MODE command, giving back the channel modes. on 324 do |event_data| split = event_data[:params].split(/ /) channel_name = split[1] channel = @channel_list.find(channel_name) if channel modes = split[2] params = split[3..-1] mode_changes = IRC::Events::ModeParser.parse(modes, params, @isupport) channel_modes = mode_changes.map do |mode_change| IRC::Events::ChannelMode.new(mode_change.merge(:channel => channel)) end channel_modes.each do |mode| channel.set_mode(mode, isupport) end end end # Response to MODE command, giving back the time, # the channel was created. on 329 do |event_data| split = event_data[:params].split(/ /) channel_name = split[1] channel = @channel_list.find(channel_name) # Only set created_at if the Thaum is on the channel. if channel epoch_time = split[2].to_i channel.created_at = Time.at(epoch_time) end end end end
sunspot/sunspot
sunspot/lib/sunspot/session.rb
Sunspot.Session.remove
ruby
def remove(*objects, &block) if block types = objects conjunction = Query::Connective::Conjunction.new if types.length == 1 conjunction.add_positive_restriction(TypeField.instance, Query::Restriction::EqualTo, types.first) else conjunction.add_positive_restriction(TypeField.instance, Query::Restriction::AnyOf, types) end dsl = DSL::Scope.new(conjunction, setup_for_types(types)) Util.instance_eval_or_call(dsl, &block) indexer.remove_by_scope(conjunction) else objects.flatten! @deletes += objects.length objects.each do |object| indexer.remove(object) end end end
See Sunspot.remove
train
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/session.rb#L137-L156
class Session class <<self attr_writer :connection_class #:nodoc: # # For testing purposes # def connection_class #:nodoc: @connection_class ||= RSolr end end # # Sunspot::Configuration object for this session # attr_reader :config # # Sessions are initialized with a Sunspot configuration and a Solr # connection. Usually you will want to stick with the default arguments # when instantiating your own sessions. # def initialize(config = Configuration.build, connection = nil) @config = config yield(@config) if block_given? @connection = connection @deletes = @adds = 0 end # # See Sunspot.new_search # def new_search(*types, &block) types.flatten! search = Search::StandardSearch.new( connection, setup_for_types(types), Query::StandardQuery.new(types), @config ) search.build(&block) if block search end # # See Sunspot.search # def search(*types, &block) search = new_search(*types, &block) search.execute end # # See Sunspot.new_more_like_this # def new_more_like_this(object, *types, &block) types[0] ||= object.class mlt = Search::MoreLikeThisSearch.new( connection, setup_for_types(types), Query::MoreLikeThisQuery.new(object, types), @config ) mlt.build(&block) if block mlt end # # See Sunspot.more_like_this # def more_like_this(object, *types, &block) mlt = new_more_like_this(object, *types, &block) mlt.execute end # # See Sunspot.index # def index(*objects) objects.flatten! @adds += objects.length indexer.add(objects) end # # See Sunspot.index! # def index!(*objects) index(*objects) commit end # # See Sunspot.atomic_update # def atomic_update(clazz, updates = {}) @adds += updates.keys.length indexer.add_atomic_update(clazz, updates) end # # See Sunspot.atomic_update! # def atomic_update!(clazz, updates = {}) atomic_update(clazz, updates) commit end # # See Sunspot.commit # def commit(soft_commit = false) @adds = @deletes = 0 connection.commit :commit_attributes => {:softCommit => soft_commit} end # # See Sunspot.optimize # def optimize @adds = @deletes = 0 connection.optimize end # # See Sunspot.remove # # # See Sunspot.remove! # def remove!(*objects, &block) remove(*objects, &block) commit end # # See Sunspot.remove_by_id # def remove_by_id(clazz, *ids) class_name = if clazz.is_a?(Class) clazz.name else clazz.to_s end indexer.remove_by_id(class_name, ids) end # # See Sunspot.remove_by_id! # def remove_by_id!(clazz, *ids) remove_by_id(clazz, ids) commit end # # See Sunspot.remove_all # def remove_all(*classes) classes.flatten! if classes.empty? @deletes += 1 indexer.remove_all else @deletes += classes.length classes.each { |clazz| indexer.remove_all(clazz) } end end # # See Sunspot.remove_all! # def remove_all!(*classes) remove_all(*classes) commit end # # See Sunspot.dirty? # def dirty? (@deletes + @adds) > 0 end # # See Sunspot.commit_if_dirty # def commit_if_dirty(soft_commit = false) commit soft_commit if dirty? end # # See Sunspot.delete_dirty? # def delete_dirty? @deletes > 0 end # # See Sunspot.commit_if_delete_dirty # def commit_if_delete_dirty(soft_commit = false) commit soft_commit if delete_dirty? end # # See Sunspot.batch # def batch indexer.start_batch yield indexer.flush_batch end private # # Retrieve the Solr connection for this session, creating one if it does not # already exist. # # ==== Returns # # RSolr::Connection::Base:: The connection for this session # def connection @connection ||= self.class.connection_class.connect( url: config.solr.url, read_timeout: config.solr.read_timeout, open_timeout: config.solr.open_timeout, proxy: config.solr.proxy, update_format: config.solr.update_format || :xml ) end def indexer @indexer ||= Indexer.new(connection) end def setup_for_types(types) if types.empty? raise(ArgumentError, "You must specify at least one type to search") end if types.length == 1 Setup.for(types.first) else CompositeSetup.for(types) end end end
ideonetwork/lato-blog
app/controllers/lato_blog/back/categories_controller.rb
LatoBlog.Back::CategoriesController.new_category_params
ruby
def new_category_params # take params from front-end request category_params = params.require(:category).permit(:title, :lato_blog_category_id).to_h # add current superuser id category_params[:lato_core_superuser_creator_id] = @core__current_superuser.id # add post parent id category_params[:lato_blog_category_parent_id] = (params[:parent] && !params[:parent].blank? ? params[:parent] : generate_category_parent) # add metadata category_params[:meta_language] = cookies[:lato_blog__current_language] # return final post object return category_params end
Params helpers: This function generate params for a new category.
train
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/categories_controller.rb#L116-L127
class Back::CategoriesController < Back::BackController before_action do core__set_menu_active_item('blog_articles') end # This function shows the list of possible categories. def index core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:categories]) # find categories to show @categories = LatoBlog::Category.where(meta_language: cookies[:lato_blog__current_language]).order('title ASC') @widget_index_categories = core__widgets_index(@categories, search: 'title', pagination: 10) end # This function shows a single category. It create a redirect to the edit path. def show # use edit as default post show page redirect_to lato_blog.edit_category_path(params[:id]) end # This function shows the view to create a new category. def new core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:categories_new]) @category = LatoBlog::Category.new if params[:language] set_current_language params[:language] end if params[:parent] @category_parent = LatoBlog::CategoryParent.find_by(id: params[:parent]) end fetch_external_objects end # This function creates a new category. def create @category = LatoBlog::Category.new(new_category_params) if !@category.save flash[:danger] = @category.errors.full_messages.to_sentence redirect_to lato_blog.new_category_path return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:category_create_success] redirect_to lato_blog.category_path(@category.id) end # This function show the view to edit a category. def edit core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:categories_edit]) @category = LatoBlog::Category.find_by(id: params[:id]) return unless check_category_presence if @category.meta_language != cookies[:lato_blog__current_language] set_current_language @category.meta_language end fetch_external_objects end # This function updates a category. def update @category = LatoBlog::Category.find_by(id: params[:id]) return unless check_category_presence if !@category.update(edit_category_params) flash[:danger] = @category.errors.full_messages.to_sentence redirect_to lato_blog.edit_category_path(@category.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:category_update_success] redirect_to lato_blog.category_path(@category.id) end # This function destroyes a category. def destroy @category = LatoBlog::Category.find_by(id: params[:id]) return unless check_category_presence if !@category.destroy flash[:danger] = @category.category_parent.errors.full_messages.to_sentence redirect_to lato_blog.edit_category_path(@category.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:category_destroy_success] redirect_to lato_blog.categories_path(status: 'deleted') end private def fetch_external_objects @categories_list = LatoBlog::Category.where(meta_language: cookies[:lato_blog__current_language]).where.not( id: @category.id).map { |cat| { title: cat.title, value: cat.id } } end # This function checks the @category variable is present and redirect to index if it not exist. def check_category_presence if !@category flash[:warning] = LANGUAGES[:lato_blog][:flashes][:category_not_found] redirect_to lato_blog.categories_path return false end return true end # Params helpers: # This function generate params for a new category. # This function generate params for a edit category. def edit_category_params params.require(:category).permit(:title, :lato_blog_category_id, :meta_permalink) end # This function generate and save a new category parent and return the id. def generate_category_parent category_parent = LatoBlog::CategoryParent.create return category_parent.id end end
sailthru/sailthru-ruby-client
lib/sailthru/client.rb
Sailthru.Client.receive_verify_post
ruby
def receive_verify_post(params, request) if request.post? [:action, :email, :send_id, :sig].each { |key| return false unless params.has_key?(key) } return false unless params[:action] == :verify sig = params.delete(:sig) params.delete(:controller) return false unless sig == get_signature_hash(params, @secret) _send = get_send(params[:send_id]) return false unless _send.has_key?('email') return false unless _send['email'] == params[:email] return true else return false end end
params: params, Hash request, String returns: boolean, Returns true if the incoming request is an authenticated verify post.
train
https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L285-L304
class Client DEFAULT_API_URI = 'https://api.sailthru.com' include Helpers attr_accessor :verify_ssl # params: # api_key, String # secret, String # api_uri, String # # Instantiate a new client; constructor optionally takes overrides for key/secret/uri and proxy server settings. def initialize(api_key=nil, secret=nil, api_uri=nil, proxy_host=nil, proxy_port=nil, opts={}) @api_key = api_key || Sailthru.api_key || raise(ArgumentError, "You must provide an API key or call Sailthru.credentials() first") @secret = secret || Sailthru.secret || raise(ArgumentError, "You must provide your secret or call Sailthru.credentials() first") @api_uri = api_uri.nil? ? DEFAULT_API_URI : api_uri @proxy_host = proxy_host @proxy_port = proxy_port @verify_ssl = true @opts = opts @last_rate_limit_info = {} end # params: # template_name, String # email, String # vars, Hash # options, Hash # replyto: override Reply-To header # test: send as test email (subject line will be marked, will not count towards stats) # returns: # Hash, response data from server def send_email(template_name, email, vars={}, options = {}, schedule_time = nil, limit = {}) post = {} post[:template] = template_name post[:email] = email post[:vars] = vars if vars.length >= 1 post[:options] = options if options.length >= 1 post[:schedule_time] = schedule_time if !schedule_time.nil? post[:limit] = limit if limit.length >= 1 api_post(:send, post) end def multi_send(template_name, emails, vars={}, options = {}, schedule_time = nil, evars = {}) post = {} post[:template] = template_name post[:email] = emails post[:vars] = vars if vars.length >= 1 post[:options] = options if options.length >= 1 post[:schedule_time] = schedule_time if !schedule_time.nil? post[:evars] = evars if evars.length >= 1 api_post(:send, post) end # params: # send_id, Fixnum # returns: # Hash, response data from server # # Get the status of a send. def get_send(send_id) api_get(:send, {:send_id => send_id.to_s}) end def cancel_send(send_id) api_delete(:send, {:send_id => send_id.to_s}) end # params: # name, String # list, String # schedule_time, String # from_name, String # from_email, String # subject, String # content_html, String # content_text, String # options, Hash # returns: # Hash, response data from server # # Schedule a mass mail blast def schedule_blast(name, list, schedule_time, from_name, from_email, subject, content_html, content_text, options = {}) post = options ? options : {} post[:name] = name post[:list] = list post[:schedule_time] = schedule_time post[:from_name] = from_name post[:from_email] = from_email post[:subject] = subject post[:content_html] = content_html post[:content_text] = content_text api_post(:blast, post) end # Schedule a mass mail blast from template def schedule_blast_from_template(template, list, schedule_time, options={}) post = options ? options : {} post[:copy_template] = template post[:list] = list post[:schedule_time] = schedule_time api_post(:blast, post) end # Schedule a mass mail blast from previous blast def schedule_blast_from_blast(blast_id, schedule_time, options={}) post = options ? options : {} post[:copy_blast] = blast_id #post[:name] = name post[:schedule_time] = schedule_time api_post(:blast, post) end # params # blast_id, Fixnum | String # name, String # list, String # schedule_time, String # from_name, String # from_email, String # subject, String # content_html, String # content_text, String # options, hash # # updates existing blast def update_blast(blast_id, name = nil, list = nil, schedule_time = nil, from_name = nil, from_email = nil, subject = nil, content_html = nil, content_text = nil, options = {}) data = options ? options : {} data[:blast_id] = blast_id if name != nil data[:name] = name end if list != nil data[:list] = list end if schedule_time != nil data[:schedule_time] = schedule_time end if from_name != nil data[:from_name] = from_name end if from_email != nil data[:from_email] = from_email end if subject != nil data[:subject] = subject end if content_html != nil data[:content_html] = content_html end if content_text != nil data[:content_text] = content_text end api_post(:blast, data) end # params: # blast_id, Fixnum | String # options, hash # returns: # Hash, response data from server # # Get information on a previously scheduled email blast def get_blast(blast_id, options={}) options[:blast_id] = blast_id.to_s api_get(:blast, options) end # params: # blast_id, Fixnum | String # # Cancel a scheduled Blast def cancel_blast(blast_id) api_post(:blast, {:blast_id => blast_id, :schedule_time => ''}) end # params: # blast_id, Fixnum | String # # Delete a Blast def delete_blast(blast_id) api_delete(:blast, {:blast_id => blast_id}) end # params: # email, String # returns: # Hash, response data from server # # Return information about an email address, including replacement vars and lists. def get_email(email) api_get(:email, {:email => email}) end # params: # email, String # vars, Hash # lists, Hash mapping list name => 1 for subscribed, 0 for unsubscribed # options, Hash mapping optional parameters # returns: # Hash, response data from server # # Set replacement vars and/or list subscriptions for an email address. def set_email(email, vars = {}, lists = {}, templates = {}, options = {}) data = options data[:email] = email data[:vars] = vars unless vars.empty? data[:lists] = lists unless lists.empty? data[:templates] = templates unless templates.empty? api_post(:email, data) end # params: # new_email, String # old_email, String # options, Hash mapping optional parameters # returns: # Hash of response data. # # change a user's email address. def change_email(new_email, old_email, options = {}) data = options data[:email] = new_email data[:change_email] = old_email api_post(:email, data) end # returns: # Hash of response data. # # Get all templates def get_templates(templates = {}) api_get(:template, templates) end # params: # template_name, String # returns: # Hash of response data. # # Get a template. def get_template(template_name) api_get(:template, {:template => template_name}) end # params: # template_name, String # template_fields, Hash # returns: # Hash containg response from the server. # # Save a template. def save_template(template_name, template_fields) data = template_fields data[:template] = template_name api_post(:template, data) end # params: # template_name, String # returns: # Hash of response data. # # Delete a template. def delete_template(template_name) api_delete(:template, {:template => template_name}) end # params: # params, Hash # request, String # returns: # boolean, Returns true if the incoming request is an authenticated verify post. # params: # params, Hash # request, String # returns: # TrueClass or FalseClass, Returns true if the incoming request is an authenticated optout post. def receive_optout_post(params, request) if request.post? [:action, :email, :sig].each { |key| return false unless params.has_key?(key) } return false unless params[:action] == 'optout' sig = params.delete(:sig) params.delete(:controller) sig == get_signature_hash(params, @secret) else false end end # List Postbacks must be enabled by Sailthru # Contact your account manager or contact support to have this enabled # # params: # params, Hash # request, String # returns: # TrueClass or FalseClass, Returns true if the incoming request is an authenticated list post. def receive_list_post(params, request) if request.post? [:action, :email, :sig].each { |key| return false unless params.has_key?(key) } return false unless params[:action] == 'update' sig = params.delete(:sig) params.delete(:controller) sig == get_signature_hash(params, @secret) else false end end # params: # params, Hash # request, String # returns: # TrueClass or FalseClass, Returns true if the incoming request is an authenticated hardbounce post. def receive_hardbounce_post(params, request) if request.post? [:action, :email, :sig].each { |key| return false unless params.has_key?(key) } return false unless params[:action] == 'hardbounce' sig = params.delete(:sig) params.delete(:controller) sig == get_signature_hash(params, @secret) else false end end # params: # email, String # items, Array of Hashes # incomplete, Integer # message_id, String # options, Hash # returns: # hash, response from server # # Record that a user has made a purchase, or has added items to their purchase total. def purchase(email, items, incomplete = nil, message_id = nil, options = {}) data = options data[:email] = email data[:items] = items if incomplete != nil data[:incomplete] = incomplete.to_i end if message_id != nil data[:message_id] = message_id end api_post(:purchase, data) end # <b>DEPRECATED:</b> Please use either stats_list or stats_blast # params: # stat, String # # returns: # hash, response from server # Request various stats from Sailthru. def get_stats(stat) warn "[DEPRECATION] `get_stats` is deprecated. Please use `stats_list` and `stats_blast` instead" api_get(:stats, {:stat => stat}) end # params # list, String # date, String # # returns: # hash, response from server # Retrieve information about your subscriber counts on a particular list, on a particular day. def stats_list(list = nil, date = nil) data = {} if list != nil data[:list] = list end if date != nil data[:date] = date end data[:stat] = 'list' api_get(:stats, data) end # params # blast_id, String # start_date, String # end_date, String # options, Hash # # returns: # hash, response from server # Retrieve information about a particular blast or aggregated information from all of blasts over a specified date range def stats_blast(blast_id = nil, start_date = nil, end_date = nil, options = {}) data = options if blast_id != nil data[:blast_id] = blast_id end if start_date != nil data[:start_date] = start_date end if end_date != nil data[:end_date] = end_date end data[:stat] = 'blast' api_get(:stats, data) end # params # template, String # start_date, String # end_date, String # options, Hash # # returns: # hash, response from server # Retrieve information about a particular blast or aggregated information from all of blasts over a specified date range def stats_send(template = nil, start_date = nil, end_date = nil, options = {}) data = options if template != nil data[:template] = template end if start_date != nil data[:start_date] = start_date end if end_date != nil data[:end_date] = end_date end data[:stat] = 'send' api_get(:stats, data) end # <b>DEPRECATED:</b> Please use save_content # params # title, String # url, String # date, String # tags, Array or Comma separated string # vars, Hash # options, Hash # # Push a new piece of content to Sailthru, triggering any applicable alerts. # http://docs.sailthru.com/api/content def push_content(title, url, date = nil, tags = nil, vars = {}, options = {}) data = options data[:title] = title data[:url] = url if date != nil data[:date] = date end if tags != nil if tags.class == Array tags = tags.join(',') end data[:tags] = tags end if vars.length > 0 data[:vars] = vars end api_post(:content, data) end # params # id, String – An identifier for the item (by default, the item’s URL). # options, Hash - Containing any of the parameters described on # https://getstarted.sailthru.com/developers/api/content/#POST_Mode # # Push a new piece of content to Sailthru, triggering any applicable alerts. # http://docs.sailthru.com/api/content def save_content(id, options) data = options data[:id] = id data[:tags] = data[:tags].join(',') if data[:tags].respond_to?(:join) api_post(:content, data) end # params # list, String # # Get information about a list. def get_list(list) api_get(:list, {:list => list}) end # params # # Get information about all lists def get_lists api_get(:list, {}) end # params # list, String # options, Hash # Create a list, or update a list. def save_list(list, options = {}) data = options data[:list] = list api_post(:list, data) end # params # list, String # # Deletes a list def delete_list(list) api_delete(:list, {:list => list}) end # params # email, String # # get user alert data def get_alert(email) api_get(:alert, {:email => email}) end # params # email, String # type, String # template, String # _when, String # options, hash # # Add a new alert to a user. You can add either a realtime or a summary alert (daily/weekly). # _when is only required when alert type is weekly or daily def save_alert(email, type, template, _when = nil, options = {}) data = options data[:email] = email data[:type] = type data[:template] = template if (type == 'weekly' || type == 'daily') data[:when] = _when end api_post(:alert, data) end # params # email, String # alert_id, String # # delete user alert def delete_alert(email, alert_id) data = {:email => email, :alert_id => alert_id} api_delete(:alert, data) end # params # job, String # options, hash # report_email, String # postback_url, String # binary_key, String # # interface for making request to job call def process_job(job, options = {}, report_email = nil, postback_url = nil, binary_key = nil) data = options data['job'] = job if !report_email.nil? data['report_email'] = report_email end if !postback_url.nil? data['postback_url'] = postback_url end api_post(:job, data, binary_key) end # params # emails, String | Array # implementation for import_job def process_import_job(list, emails, report_email = nil, postback_url = nil, options = {}) data = options data['list'] = list data['emails'] = Array(emails).join(',') process_job(:import, data, report_email, postback_url) end # implementation for import job using file upload def process_import_job_from_file(list, file_path, report_email = nil, postback_url = nil, options = {}) data = options data['list'] = list data['file'] = file_path process_job(:import, data, report_email, postback_url, 'file') end # implementation for update job using file upload def process_update_job_from_file(file_path, report_email = nil, postback_url = nil, options = {}) data = options data['file'] = file_path process_job(:update, data, report_email, postback_url, 'file') end # implementation for purchase import job using file upload def process_purchase_import_job_from_file(file_path, report_email = nil, postback_url = nil, options = {}) data = options data['file'] = file_path process_job(:purchase_import, data, report_email, postback_url, 'file') end # implementation for snapshot job def process_snapshot_job(query = {}, report_email = nil, postback_url = nil, options = {}) data = options data['query'] = query process_job(:snapshot, data, report_email, postback_url) end # implementation for export list job def process_export_list_job(list, report_email = nil, postback_url = nil, options = {}) data = options data['list'] = list process_job(:export_list_data, data, report_email, postback_url) end # get status of a job def get_job_status(job_id) api_get(:job, {'job_id' => job_id}) end # Get user by Sailthru ID def get_user_by_sid(id, fields = {}) api_get(:user, {'id' => id, 'fields' => fields}) end # Get user by specified key def get_user_by_key(id, key, fields = {}) data = { 'id' => id, 'key' => key, 'fields' => fields } api_get(:user, data) end # Create new user, or update existing user def save_user(id, options = {}) data = options data['id'] = id api_post(:user, data) end # params # Get an existing trigger def get_triggers api_get(:trigger, {}) end # params # template, String # trigger_id, String # Get an existing trigger def get_trigger_by_template(template, trigger_id = nil) data = {} data['template'] = template if trigger_id != nil then data['trigger_id'] = trigger_id end api_get(:trigger, data) end # params # event, String # Get an existing trigger def get_trigger_by_event(event) data = {} data['event'] = event api_get(:trigger, data) end # params # template, String # time, String # time_unit, String # event, String # zephyr, String # Create or update a trigger def post_template_trigger(template, time, time_unit, event, zephyr) data = {} data['template'] = template data['time'] = time data['time_unit'] = time_unit data['event'] = event data['zephyr'] = zephyr api_post(:trigger, data) end # params # template, String # time, String # time_unit, String # zephyr, String # Create or update a trigger def post_event_trigger(event, time, time_unit, zephyr) data = {} data['time'] = time data['time_unit'] = time_unit data['event'] = event data['zephyr'] = zephyr api_post(:trigger, data) end # params # id, String # event, String # options, Hash (Can contain vars, Hash and/or key) # Notify Sailthru of an Event def post_event(id, event, options = {}) data = options data['id'] = id data['event'] = event api_post(:event, data) end # Perform API GET request def api_get(action, data) api_request(action, data, 'GET') end # Perform API POST request def api_post(action, data, binary_key = nil) api_request(action, data, 'POST', binary_key) end #Perform API DELETE request def api_delete(action, data) api_request(action, data, 'DELETE') end # params # endpoint, String a e.g. "user" or "send" # method, String "GET" or "POST" # returns # Hash rate info # Get rate info for a particular endpoint/method, as of the last time a request was sent to the given endpoint/method # Includes the following keys: # limit: the per-minute limit for the given endpoint/method # remaining: the number of allotted requests remaining in the current minute for the given endpoint/method # reset: unix timestamp of the top of the next minute, when the rate limit will reset def get_last_rate_limit_info(endpoint, method) rate_info_key = get_rate_limit_info_key(endpoint, method) @last_rate_limit_info[rate_info_key] end protected # params: # action, String # data, Hash # request, String "GET" or "POST" # returns: # Hash # # Perform an API request, using the shared-secret auth hash. # def api_request(action, data, request_type, binary_key = nil) if !binary_key.nil? binary_key_data = data[binary_key] data.delete(binary_key) end if data[:format].nil? || data[:format] == 'json' data = prepare_json_payload(data) else data[:api_key] = @api_key data[:format] ||= 'json' data[:sig] = get_signature_hash(data, @secret) end if !binary_key.nil? data[binary_key] = binary_key_data end _result = http_request(action, data, request_type, binary_key) # NOTE: don't do the unserialize here if data[:format] == 'json' begin unserialized = JSON.parse(_result) return unserialized ? unserialized : _result rescue JSON::JSONError => e return {'error' => e} end end _result end # set up our post request def set_up_post_request(uri, data, headers, binary_key = nil) if !binary_key.nil? binary_data = data[binary_key] if binary_data.is_a?(StringIO) data[binary_key] = UploadIO.new( binary_data, "text/plain", "local.path" ) else data[binary_key] = UploadIO.new( File.open(binary_data), "text/plain" ) end req = Net::HTTP::Post::Multipart.new(uri.path, data) else req = Net::HTTP::Post.new(uri.path, headers) req.set_form_data(data) end req end # params: # uri, String # data, Hash # method, String "GET" or "POST" # returns: # String, body of response def http_request(action, data, method = 'POST', binary_key = nil) data = flatten_nested_hash(data, false) uri = "#{@api_uri}/#{action}" if method != 'POST' uri += "?" + data.map{ |key, value| "#{CGI::escape(key.to_s)}=#{CGI::escape(value.to_s)}" }.join("&") end req = nil headers = {"User-Agent" => "Sailthru API Ruby Client #{Sailthru::VERSION}"} _uri = URI.parse(uri) if method == 'POST' req = set_up_post_request( _uri, data, headers, binary_key ) else request_uri = "#{_uri.path}?#{_uri.query}" if method == 'DELETE' req = Net::HTTP::Delete.new(request_uri, headers) else req = Net::HTTP::Get.new(request_uri, headers) end end begin http = Net::HTTP::Proxy(@proxy_host, @proxy_port).new(_uri.host, _uri.port) if _uri.scheme == 'https' http.ssl_version = :TLSv1 http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE if @verify_ssl != true # some openSSL client doesn't work without doing this http.ssl_timeout = @opts[:http_ssl_timeout] || 5 end http.open_timeout = @opts[:http_open_timeout] || 5 http.read_timeout = @opts[:http_read_timeout] || 10 http.close_on_empty_response = @opts[:http_close_on_empty_response] || true response = http.start do http.request(req) end rescue Timeout::Error, Errno::ETIMEDOUT => e raise UnavailableError, "Timed out: #{_uri}" rescue => e raise ClientError, "Unable to open stream to #{_uri}: #{e.message}" end save_rate_limit_info(action, method, response) response.body || raise(ClientError, "No response received from stream: #{_uri}") end def http_multipart_request(uri, data) Net::HTTP::Post::Multipart.new url.path, "file" => UploadIO.new(data['file'], "application/octet-stream") end def prepare_json_payload(data) payload = { :api_key => @api_key, :format => 'json', #<3 XML :json => data.to_json } payload[:sig] = get_signature_hash(payload, @secret) payload end def save_rate_limit_info(action, method, response) limit = response['x-rate-limit-limit'].to_i remaining = response['x-rate-limit-remaining'].to_i reset = response['x-rate-limit-reset'].to_i if limit.nil? or remaining.nil? or reset.nil? return end rate_info_key = get_rate_limit_info_key(action, method) @last_rate_limit_info[rate_info_key] = { limit: limit, remaining: remaining, reset: reset } end def get_rate_limit_info_key(endpoint, method) :"#{endpoint}_#{method.downcase}" end end
tdg5/tco_method
lib/tco_method/block_extractor.rb
TCOMethod.BlockExtractor.determine_end_offset
ruby
def determine_end_offset(block, tokens, source, expected_matcher) lines = source.lines last_line_number = lines.length end_offset = nil tokens.reverse_each do |token| # Break once we're through with the last line. break if token[0][0] != last_line_number # Look for expected match to block opener next if token[1] != expected_matcher next if token[1] == :on_kw && token[2] != END_STR # Raise if we've already found something that looks like a block end. raise AmbiguousSourceError.from_proc(block) if end_offset # Ending offset is the position of the ending token, plus the length of # that token. end_offset = token[0][1] + token[2].length end raise AmbiguousSourceError.from_proc(block) unless end_offset determine_end_offset_relative_to_source(end_offset, lines.last.length) end
Encapsulates the logic required to determine the offset of the end of the block. The end of the block is characterized by a matching curly brace (`}`) or the `end` keyword.
train
https://github.com/tdg5/tco_method/blob/fc89b884b68ce2a4bc58abb22270b1f7685efbe9/lib/tco_method/block_extractor.rb#L27-L47
class BlockExtractor DO_STR = "do".freeze END_STR = "end".freeze attr_reader :source def initialize(block) source = block.source type = block.lambda? ? :lambda : :proc start_offset, end_offset = determine_offsets(block, source) @source = "#{type} #{source[start_offset..end_offset]}" rescue MethodSource::SourceNotFoundError => ex raise AmbiguousSourceError.wrap(ex) end private # Encapsulates the logic required to determine the offset of the end of the # block. The end of the block is characterized by a matching curly brace # (`}`) or the `end` keyword. # We subract the length of the last line from end offset to determine the # negative offset into the source string. However we must subtract 1 to # correct for the negative offset referring to the character after the # desired terminal character. def determine_end_offset_relative_to_source(end_offset, last_line_length) end_offset - last_line_length - 1 end # Tokenizes the source of the block as determined by the `method_source` gem # and determines the beginning and end of the block. # # In both cases the entire line is checked to ensure there's no unexpected # ambiguity as to the start or end of the block. See the test file for this # class for examples of ambiguous situations. # # @param [Proc] block The proc for which the starting offset of its source # code should be determined. # @param [String] source The source code of the provided block. # @raise [AmbiguousSourceError] Raised when the source of the block cannot # be determined unambiguously. # @return [Array<Integer>] The start and end offsets of the block's source # code as 2-element Array. def determine_offsets(block, source) tokens = Ripper.lex(source) start_offset, start_token = determine_start_offset(block, tokens) expected_match = start_token == :on_kw ? :on_kw : :on_rbrace end_offset = determine_end_offset(block, tokens, source, expected_match) [start_offset, end_offset] end # The logic required to determine the starting offset of the block. The # start of the block is characterized by the opening left curly brace (`{`) # of the block or the `do` keyword. Everything prior to the start of the # block is ignored because we can determine whether the block should be a # lambda or a proc by asking the block directly, and we may not always have # such a keyword available to us, e.g. a method that takes a block like # TCOMethod.with_tco. def determine_start_offset(block, tokens) start_offset = start_token = nil # The start of the block should occur somewhere on line 1. # Check the whole line to ensure there aren't multiple blocks on the line. tokens.each do |token| # Break after line 1. break if token[0][0] != 1 # Look for a left brace (`{`) or `do` keyword. if token[1] == :on_lbrace || (token[1] == :on_kw && token[2] == DO_STR) # Raise if we've already found something that looks like a block # start. raise AmbiguousSourceError.from_proc(block) if start_offset start_token = token[1] start_offset = token[0][1] end end raise AmbiguousSourceError.from_proc(block) unless start_offset [start_offset, start_token] end end
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.chmod
ruby
def chmod(mode = nil) return unless mode begin Integer mode mode = Integer mode.size == 3 ? "0#{mode}" : mode rescue ArgumentError end FileUtils.chmod mode, selected_items.map(&:path) ls end
Change the file permission of the selected files and directories. ==== Parameters * +mode+ - Unix chmod string (e.g. +w, g-r, 755, 0644)
train
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L235-L244
class Controller include Rfd::Commands attr_reader :header_l, :header_r, :main, :command_line, :items, :displayed_items, :current_row, :current_page, :current_dir, :current_zip # :nodoc: def initialize @main = MainWindow.new @header_l = HeaderLeftWindow.new @header_r = HeaderRightWindow.new @command_line = CommandLineWindow.new @debug = DebugWindow.new if ENV['DEBUG'] @direction, @dir_history, @last_command, @times, @yanked_items = nil, [], nil, nil, nil end # The main loop. def run loop do begin number_pressed = false ret = case (c = Curses.getch) when 10, 13 # enter, return enter when 27 # ESC q when ' ' # space space when 127 # DEL del when Curses::KEY_DOWN j when Curses::KEY_UP k when Curses::KEY_LEFT h when Curses::KEY_RIGHT l when Curses::KEY_CTRL_A..Curses::KEY_CTRL_Z chr = ((c - 1 + 65) ^ 0b0100000).chr public_send "ctrl_#{chr}" if respond_to?("ctrl_#{chr}") when ?0..?9 public_send c number_pressed = true when ?!..?~ if respond_to? c public_send c else debug "key: #{c}" if ENV['DEBUG'] end when Curses::KEY_MOUSE if (mouse_event = Curses.getmouse) case mouse_event.bstate when Curses::BUTTON1_CLICKED click y: mouse_event.y, x: mouse_event.x when Curses::BUTTON1_DOUBLE_CLICKED double_click y: mouse_event.y, x: mouse_event.x end end else debug "key: #{c}" if ENV['DEBUG'] end Curses.doupdate if ret @times = nil unless number_pressed rescue StopIteration raise rescue => e command_line.show_error e.to_s raise if ENV['DEBUG'] end end ensure Curses.close_screen end # Change the number of columns in the main window. def spawn_panes(num) main.number_of_panes = num @current_row = @current_page = 0 end # Number of times to repeat the next command. def times (@times || 1).to_i end # The file or directory on which the cursor is on. def current_item items[current_row] end # * marked files and directories. def marked_items items.select(&:marked?) end # Marked files and directories or Array(the current file or directory). # # . and .. will not be included. def selected_items ((m = marked_items).any? ? m : Array(current_item)).reject {|i| %w(. ..).include? i.name} end # Move the cursor to specified row. # # The main window and the headers will be updated reflecting the displayed files and directories. # The row number can be out of range of the current page. def move_cursor(row = nil) if row if (prev_item = items[current_row]) main.draw_item prev_item end page = row / max_items switch_page page if page != current_page main.activate_pane row / maxy @current_row = row else @current_row = 0 end item = items[current_row] main.draw_item item, current: true main.display current_page header_l.draw_current_file_info item @current_row end # Change the current directory. def cd(dir = '~', pushd: true) dir = load_item path: expand_path(dir) unless dir.is_a? Item unless dir.zip? Dir.chdir dir @current_zip = nil else @current_zip = dir end @dir_history << current_dir if current_dir && pushd @current_dir, @current_page, @current_row = dir, 0, nil main.activate_pane 0 ls @current_dir end # cd to the previous directory. def popd cd @dir_history.pop, pushd: false if @dir_history.any? end # Fetch files from current directory. # Then update each windows reflecting the newest information. def ls fetch_items_from_filesystem_or_zip sort_items_according_to_current_direction @current_page ||= 0 draw_items move_cursor (current_row ? [current_row, items.size - 1].min : nil) draw_marked_items draw_total_items true end # Sort the whole files and directories in the current directory, then refresh the screen. # # ==== Parameters # * +direction+ - Sort order in a String. # nil : order by name # r : reverse order by name # s, S : order by file size # sr, Sr: reverse order by file size # t : order by mtime # tr : reverse order by mtime # c : order by ctime # cr : reverse order by ctime # u : order by atime # ur : reverse order by atime # e : order by extname # er : reverse order by extname def sort(direction = nil) @direction, @current_page = direction, 0 sort_items_according_to_current_direction switch_page 0 move_cursor 0 end # Change the file permission of the selected files and directories. # # ==== Parameters # * +mode+ - Unix chmod string (e.g. +w, g-r, 755, 0644) # Change the file owner of the selected files and directories. # # ==== Parameters # * +user_and_group+ - user name and group name separated by : (e.g. alice, nobody:nobody, :admin) def chown(user_and_group) return unless user_and_group user, group = user_and_group.split(':').map {|s| s == '' ? nil : s} FileUtils.chown user, group, selected_items.map(&:path) ls end # Fetch files from current directory or current .zip file. def fetch_items_from_filesystem_or_zip unless in_zip? @items = Dir.foreach(current_dir).map {|fn| load_item dir: current_dir, name: fn }.to_a.partition {|i| %w(. ..).include? i.name}.flatten else @items = [load_item(dir: current_dir, name: '.', stat: File.stat(current_dir)), load_item(dir: current_dir, name: '..', stat: File.stat(File.dirname(current_dir)))] zf = Zip::File.new current_dir zf.each {|entry| next if entry.name_is_directory? stat = zf.file.stat entry.name @items << load_item(dir: current_dir, name: entry.name, stat: stat) } end end # Focus at the first file or directory of which name starts with the given String. def find(str) index = items.index {|i| i.index > current_row && i.name.start_with?(str)} || items.index {|i| i.name.start_with? str} move_cursor index if index end # Focus at the last file or directory of which name starts with the given String. def find_reverse(str) index = items.reverse.index {|i| i.index < current_row && i.name.start_with?(str)} || items.reverse.index {|i| i.name.start_with? str} move_cursor items.size - index - 1 if index end # Height of the currently active pane. def maxy main.maxy end # Number of files or directories that the current main window can show in a page. def max_items main.max_items end # Update the main window with the loaded files and directories. Also update the header. def draw_items main.newpad items @displayed_items = items[current_page * max_items, max_items] main.display current_page header_l.draw_path_and_page_number path: current_dir.path, current: current_page + 1, total: total_pages end # Sort the loaded files and directories in already given sort order. def sort_items_according_to_current_direction case @direction when nil @items = items.shift(2) + items.partition(&:directory?).flat_map(&:sort) when 'r' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort.reverse} when 'S', 's' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by {|i| -i.size}} when 'Sr', 'sr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:size)} when 't' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.mtime <=> x.mtime}} when 'tr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:mtime)} when 'c' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.ctime <=> x.ctime}} when 'cr' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:ctime)} when 'u' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.atime <=> x.atime}} when 'ur' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:atime)} when 'e' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort {|x, y| y.extname <=> x.extname}} when 'er' @items = items.shift(2) + items.partition(&:directory?).flat_map {|arr| arr.sort_by(&:extname)} end items.each.with_index {|item, index| item.index = index} end # Search files and directories from the current directory, and update the screen. # # * +pattern+ - Search pattern against file names in Ruby Regexp string. # # === Example # # a : Search files that contains the letter "a" in their file name # .*\.pdf$ : Search PDF files def grep(pattern = '.*') regexp = Regexp.new(pattern) fetch_items_from_filesystem_or_zip @items = items.shift(2) + items.select {|i| i.name =~ regexp} sort_items_according_to_current_direction draw_items draw_total_items switch_page 0 move_cursor 0 end # Copy selected files and directories to the destination. def cp(dest) unless in_zip? src = (m = marked_items).any? ? m.map(&:path) : current_item FileUtils.cp_r src, expand_path(dest) else raise 'cping multiple items in .zip is not supported.' if selected_items.size > 1 Zip::File.open(current_zip) do |zip| entry = zip.find_entry(selected_items.first.name).dup entry.name, entry.name_length = dest, dest.size zip.instance_variable_get(:@entry_set) << entry end end ls end # Move selected files and directories to the destination. def mv(dest) unless in_zip? src = (m = marked_items).any? ? m.map(&:path) : current_item FileUtils.mv src, expand_path(dest) else raise 'mving multiple items in .zip is not supported.' if selected_items.size > 1 rename "#{selected_items.first.name}/#{dest}" end ls end # Rename selected files and directories. # # ==== Parameters # * +pattern+ - new filename, or a shash separated Regexp like string def rename(pattern) from, to = pattern.sub(/^\//, '').sub(/\/$/, '').split '/' if to.nil? from, to = current_item.name, from else from = Regexp.new from end unless in_zip? selected_items.each do |item| name = item.name.gsub from, to FileUtils.mv item, current_dir.join(name) if item.name != name end else Zip::File.open(current_zip) do |zip| selected_items.each do |item| name = item.name.gsub from, to zip.rename item.name, name end end end ls end # Soft delete selected files and directories. # # If the OS is not OSX, performs the same as `delete` command. def trash unless in_zip? if osx? FileUtils.mv selected_items.map(&:path), File.expand_path('~/.Trash/') else #TODO support other OS FileUtils.rm_rf selected_items.map(&:path) end else return unless ask %Q[Trashing zip entries is not supported. Actually the files will be deleted. Are you sure want to proceed? (y/n)] delete end @current_row -= selected_items.count {|i| i.index <= current_row} ls end # Delete selected files and directories. def delete unless in_zip? FileUtils.rm_rf selected_items.map(&:path) else Zip::File.open(current_zip) do |zip| zip.select {|e| selected_items.map(&:name).include? e.to_s}.each do |entry| if entry.name_is_directory? zip.dir.delete entry.to_s else zip.file.delete entry.to_s end end end end @current_row -= selected_items.count {|i| i.index <= current_row} ls end # Create a new directory. def mkdir(dir) unless in_zip? FileUtils.mkdir_p current_dir.join(dir) else Zip::File.open(current_zip) do |zip| zip.dir.mkdir dir end end ls end # Create a new empty file. def touch(filename) unless in_zip? FileUtils.touch current_dir.join(filename) else Zip::File.open(current_zip) do |zip| # zip.file.open(filename, 'w') {|_f| } #HAXX this code creates an unneeded temporary file zip.instance_variable_get(:@entry_set) << Zip::Entry.new(current_zip, filename) end end ls end # Create a symlink to the current file or directory. def symlink(name) FileUtils.ln_s current_item, name ls end # Yank selected file / directory names. def yank @yanked_items = selected_items end # Paste yanked files / directories here. def paste if @yanked_items if current_item.directory? FileUtils.cp_r @yanked_items.map(&:path), current_item else @yanked_items.each do |item| if items.include? item i = 1 while i += 1 new_item = load_item dir: current_dir, name: "#{item.basename}_#{i}#{item.extname}", stat: item.stat break unless File.exist? new_item.path end FileUtils.cp_r item, new_item else FileUtils.cp_r item, current_dir end end end ls end end # Copy selected files and directories' path into clipboard on OSX. def clipboard IO.popen('pbcopy', 'w') {|f| f << selected_items.map(&:path).join(' ')} if osx? end # Archive selected files and directories into a .zip file. def zip(zipfile_name) return unless zipfile_name zipfile_name += '.zip' unless zipfile_name.end_with? '.zip' Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile| selected_items.each do |item| next if item.symlink? if item.directory? Dir[item.join('**/**')].each do |file| zipfile.add file.sub("#{current_dir}/", ''), file end else zipfile.add item.name, item end end end ls end # Unarchive .zip and .tar.gz files within selected files and directories into current_directory. def unarchive unless in_zip? zips, gzs = selected_items.partition(&:zip?).tap {|z, others| break [z, *others.partition(&:gz?)]} zips.each do |item| FileUtils.mkdir_p current_dir.join(item.basename) Zip::File.open(item) do |zip| zip.each do |entry| FileUtils.mkdir_p File.join(item.basename, File.dirname(entry.to_s)) zip.extract(entry, File.join(item.basename, entry.to_s)) { true } end end end gzs.each do |item| Zlib::GzipReader.open(item) do |gz| Gem::Package::TarReader.new(gz) do |tar| dest_dir = current_dir.join (gz.orig_name || item.basename).sub(/\.tar$/, '') tar.each do |entry| dest = nil if entry.full_name == '././@LongLink' dest = File.join dest_dir, entry.read.strip next end dest ||= File.join dest_dir, entry.full_name if entry.directory? FileUtils.mkdir_p dest, :mode => entry.header.mode elsif entry.file? FileUtils.mkdir_p dest_dir File.open(dest, 'wb') {|f| f.print entry.read} FileUtils.chmod entry.header.mode, dest elsif entry.header.typeflag == '2' # symlink File.symlink entry.header.linkname, dest end unless Dir.exist? dest_dir FileUtils.mkdir_p dest_dir File.open(File.join(dest_dir, gz.orig_name || item.basename), 'wb') {|f| f.print gz.read} end end end end end else Zip::File.open(current_zip) do |zip| zip.select {|e| selected_items.map(&:name).include? e.to_s}.each do |entry| FileUtils.mkdir_p File.join(current_zip.dir, current_zip.basename, File.dirname(entry.to_s)) zip.extract(entry, File.join(current_zip.dir, current_zip.basename, entry.to_s)) { true } end end end ls end # Current page is the first page? def first_page? current_page == 0 end # Do we have more pages? def last_page? current_page == total_pages - 1 end # Number of pages in the current directory. def total_pages (items.size - 1) / max_items + 1 end # Move to the given page number. # # ==== Parameters # * +page+ - Target page number def switch_page(page) main.display (@current_page = page) @displayed_items = items[current_page * max_items, max_items] header_l.draw_path_and_page_number path: current_dir.path, current: current_page + 1, total: total_pages end # Update the header information concerning currently marked files or directories. def draw_marked_items items = marked_items header_r.draw_marked_items count: items.size, size: items.inject(0) {|sum, i| sum += i.size} end # Update the header information concerning total files and directories in the current directory. def draw_total_items header_r.draw_total_items count: items.size, size: items.inject(0) {|sum, i| sum += i.size} end # Swktch on / off marking on the current file or directory. def toggle_mark main.toggle_mark current_item end # Get a char as a String from user input. def get_char c = Curses.getch c if (0..255) === c.ord end def clear_command_line command_line.writeln 0, "" command_line.clear command_line.noutrefresh end # Accept user input, and directly execute it as a Ruby method call to the controller. # # ==== Parameters # * +preset_command+ - A command that would be displayed at the command line before user input. def process_command_line(preset_command: nil) prompt = preset_command ? ":#{preset_command} " : ':' command_line.set_prompt prompt cmd, *args = command_line.get_command(prompt: prompt).split(' ') if cmd && !cmd.empty? && respond_to?(cmd) ret = self.public_send cmd, *args clear_command_line ret end rescue Interrupt clear_command_line end # Accept user input, and directly execute it in an external shell. def process_shell_command command_line.set_prompt ':!' cmd = command_line.get_command(prompt: ':!')[1..-1] execute_external_command pause: true do system cmd end rescue Interrupt ensure command_line.clear command_line.noutrefresh end # Let the user answer y or n. # # ==== Parameters # * +prompt+ - Prompt message def ask(prompt = '(y/n)') command_line.set_prompt prompt command_line.refresh while (c = Curses.getch) next unless [?N, ?Y, ?n, ?y, 3, 27] .include? c # N, Y, n, y, ^c, esc command_line.clear command_line.noutrefresh break (c == 'y') || (c == 'Y') end end # Open current file or directory with the editor. def edit execute_external_command do editor = ENV['EDITOR'] || 'vim' unless in_zip? system %Q[#{editor} "#{current_item.path}"] else begin tmpdir, tmpfile_name = nil Zip::File.open(current_zip) do |zip| tmpdir = Dir.mktmpdir FileUtils.mkdir_p File.join(tmpdir, File.dirname(current_item.name)) tmpfile_name = File.join(tmpdir, current_item.name) File.open(tmpfile_name, 'w') {|f| f.puts zip.file.read(current_item.name)} system %Q[#{editor} "#{tmpfile_name}"] zip.add(current_item.name, tmpfile_name) { true } end ls ensure FileUtils.remove_entry_secure tmpdir if tmpdir end end end end # Open current file or directory with the viewer. def view pager = ENV['PAGER'] || 'less' execute_external_command do unless in_zip? system %Q[#{pager} "#{current_item.path}"] else begin tmpdir, tmpfile_name = nil Zip::File.open(current_zip) do |zip| tmpdir = Dir.mktmpdir FileUtils.mkdir_p File.join(tmpdir, File.dirname(current_item.name)) tmpfile_name = File.join(tmpdir, current_item.name) File.open(tmpfile_name, 'w') {|f| f.puts zip.file.read(current_item.name)} end system %Q[#{pager} "#{tmpfile_name}"] ensure FileUtils.remove_entry_secure tmpdir if tmpdir end end end end def move_cursor_by_click(y: nil, x: nil) if (idx = main.pane_index_at(y: y, x: x)) row = current_page * max_items + main.maxy * idx + y - main.begy move_cursor row if (row >= 0) && (row < items.size) end end private def execute_external_command(pause: false) Curses.def_prog_mode Curses.close_screen yield ensure Curses.reset_prog_mode Curses.getch if pause #NOTE needs to draw borders and ls again here since the stdlib Curses.refresh fails to retrieve the previous screen Rfd::Window.draw_borders Curses.refresh ls end def expand_path(path) File.expand_path path.start_with?('/', '~') ? path : current_dir ? current_dir.join(path) : path end def load_item(path: nil, dir: nil, name: nil, stat: nil) Item.new dir: dir || File.dirname(path), name: name || File.basename(path), stat: stat, window_width: main.width end def osx? @_osx ||= RbConfig::CONFIG['host_os'] =~ /darwin/ end def in_zip? @current_zip end def debug(str) @debug.debug str end end
zhimin/rwebspec
lib/rwebspec-watir/web_browser.rb
RWebSpec.WebBrowser.element_by_id
ruby
def element_by_id(elem_id) if is_firefox? # elem = @browser.document.getElementById(elem_id) # elem = div(:id, elem_id) || label(:id, elem_id) || button(:id, elem_id) || # span(:id, elem_id) || hidden(:id, elem_id) || link(:id, elem_id) || radio(:id, elem_id) elem = browser.element_by_xpath("//*[@id='#{elem_id}']") else elem = @browser.document.getElementById(elem_id) end end
Deprecated: using Watir style directly instead
train
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-watir/web_browser.rb#L456-L465
class WebBrowser attr_accessor :context def initialize(base_url = nil, existing_browser = nil, options = {}) default_options = {:speed => "zippy", :visible => true, :highlight_colour => 'yellow', :close_others => true } options = default_options.merge options @context = Context.new base_url if base_url initialize_ie_browser(existing_browser, options) end def initialize_ie_browser(existing_browser, options) @browser = existing_browser || Watir::IE.new if ($TESTWISE_EMULATE_TYPING && $TESTWISE_TYPING_SPEED) then @browser.set_slow_speed if $TESTWISE_TYPING_SPEED == "slow" @browser.set_fast_speed if $TESTWISE_TYPING_SPEED == 'fast' else @browser.speed = :zippy end return if existing_browser # Watir-classic 3.4 drop the support # @browser.activeObjectHighLightColor = options[:highlight_colour] @browser.visible = options[:visible] unless $HIDE_IE #NOTE: close_others fails begin if options[:close_others] then @browser.windows.reject(&:current?).each(&:close) end rescue => e1 puts "Failed to close others" end end def self.reuse(base_url, options) if self.is_windows? && ($TESTWISE_BROWSER != "Firefox" && $TESTWISE_BROWSER != "Firefox") require 'watir-classic' # try to avoid # lib/ruby/1.8/dl/win32.rb:11:in `sym': unknown type specifier 'v' Watir::IE.each do |browser_window| return WebBrowser.new(base_url, browser_window, options) end #puts "no browser instance found" WebBrowser.new(base_url, nil, options) else WebBrowser.new(base_url, nil, options) end end # for popup windows def self.new_from_existing(underlying_browser, web_context = nil) return WebBrowser.new(web_context ? web_context.base_url : nil, underlying_browser, {:close_others => false}) end ## # Delegate to Watir # [:button, :td, :checkbox, :div, :form, :frame, :h1, :h2, :h3, :h4, :h5, :h6, :hidden, :image, :li, :link, :map, :pre, :tr, :radio, :select_list, :span, :table, :text_field, :paragraph, :file_field, :label].each do |method| define_method method do |*args| @browser.send(method, *args) end end alias cell td alias check_box checkbox # seems watir doc is wrong, checkbox not check_box alias row tr alias a link alias img image def area(*args) @browser.send("area", *args) end def modal_dialog(how=nil, what=nil) @browser.modal_dialog(how, what) end # This is the main method for accessing a generic element with a given attibute # * how - symbol - how we access the element. Supports all values except :index and :xpath # * what - string, integer or regular expression - what we are looking for, # # Valid values for 'how' are listed in the Watir Wiki - http://wiki.openqa.org/display/WTR/Methods+supported+by+Element # # returns an Watir::Element object # # Typical Usage # # element(:class, /foo/) # access the first element with class 'foo'. We can use a string in place of the regular expression # element(:id, "11") # access the first element that matches an id def element(how, what) return @browser.element(how, what) end # this is the main method for accessing generic html elements by an attribute # # Returns a HTMLElements object # # Typical usage: # # elements(:class, 'test').each { |l| puts l.to_s } # iterate through all elements of a given attribute # elements(:alt, 'foo')[1].to_s # get the first element of a given attribute # elements(:id, 'foo').length # show how many elements are foung in the collection # def elements(how, what) return @browser.elements(how, what) end def show_all_objects @browser.show_all_objects end # Returns the specified ole object for input elements on a web page. # # This method is used internally by Watir and should not be used externally. It cannot be marked as private because of the way mixins and inheritance work in watir # # * how - symbol - the way we look for the object. Supported values are # - :name # - :id # - :index # - :value etc # * what - string that we are looking for, ex. the name, or id tag attribute or index of the object we are looking for. # * types - what object types we will look at. # * value - used for objects that have one name, but many values. ex. radio lists and checkboxes def locate_input_element(how, what, types, value=nil) @browser.locate_input_element(how, what, types, value) end # This is the main method for accessing map tags - http://msdn.microsoft.com/workshop/author/dhtml/reference/objects/map.asp?frame=true # * how - symbol - how we access the map, # * what - string, integer or regular expression - what we are looking for, # # Valid values for 'how' are listed in the Watir Wiki - http://wiki.openqa.org/display/WTR/Methods+supported+by+Element # # returns a map object # # Typical Usage # # map(:id, /list/) # access the first map that matches list. # map(:index,2) # access the second map on the page # map(:title, "A Picture") # access a map using the tooltip text. See http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/title_1.asp?frame=true # def map(how, what=nil) @browser.map(how, what) end def contains_text(text) @browser.contains_text(text); end # return HTML of current web page def page_source @browser.html() #@browser.document.body end alias html_body page_source alias html page_source # return plain text of current web page def text @browser.text end def page_title case @browser.class.to_s when "Watir::IE" @browser.document.title else @browser.title end end [:images, :links, :buttons, :select_lists, :checkboxes, :radios, :text_fields, :divs, :dls, :dds, :dts, :ems, :lis, :maps, :spans, :strongs, :ps, :pres, :labels, :tds, :trs].each do |method| define_method method do @browser.send(method) end end alias as links alias rows trs alias cells tds alias imgs images # current url def url @browser.url end def base_url=(new_base_url) if @context @conext.base_url = new_base_url return end @context = Context.new base_url end def is_firefox? return false end # Close the browser window. Useful for automated test suites to reduce # test interaction. def close_browser @browser.close sleep 2 end alias close close_browser def close_all_browsers(browser_type = :ie) @browser.windows.each(&:close) end def full_url(relative_url) if @context && @context.base_url @context.base_url + relative_url else relative_url end end def begin_at(relative_url) @browser.goto full_url(relative_url) end def browser_opened? begin @browser != nil rescue => e return false end end # Some browsers (i.e. IE) need to be waited on before more actions can be # performed. Most action methods in Watir::Simple already call this before # and after. def wait_for_browser # Watir 3 does not support it any more # @browser.waitForIE unless is_firefox? end # A convenience method to wait at both ends of an operation for the browser # to catch up. def wait_before_and_after wait_for_browser yield wait_for_browser end [:back, :forward, :refresh, :focus, :close_others].each do |method| define_method(method) do @browser.send(method) end end alias refresh_page refresh alias go_back back alias go_forward forward # Go to a page # Usage: # open_browser(:base_url => "http://www.itest2.com") # .... # goto_page("/purchase") # full url => http://www.itest.com/purchase def goto_page(page) # puts "DEBUG calling goto page => #{page}" @browser.goto full_url(page); end # Go to a URL directly # goto_url("http://www.itest2.com/downloads") def goto_url(url) @browser.goto url end # text fields def enter_text_into_field_with_name(name, text) if is_firefox? wait_before_and_after { text_field(:name, name).value = text } sleep 0.3 else wait_before_and_after { text_field(:name, name).set(text) } end end alias set_form_element enter_text_into_field_with_name alias enter_text enter_text_into_field_with_name alias set_hidden_field set_form_element #links def click_link_with_id(link_id, opts = {}) if opts && opts[:index] wait_before_and_after { link(:id => link_id, :index => opts[:index]).click } else wait_before_and_after { link(:id, link_id).click } end end def click_link_with_text(text, opts = {}) if opts && opts[:index] wait_before_and_after { link(:text => text, :index => opts[:index]).click } else wait_before_and_after { link(:text, text).click } end end alias click_link click_link_with_text # Click a button with give HTML id # Usage: # click_button_with_id("btn_sumbit") def click_button_with_id(id, opts = {}) if opts && opts[:index] wait_before_and_after { button(:id => id, :index => opts[:index]).click } else wait_before_and_after { button(:id, id).click } end end # Click a button with give name # Usage: # click_button_with_name("confirm") def click_button_with_name(name, opts={}) if opts && opts[:index] wait_before_and_after { button(:name => name, :index => opts[:index]).click } else wait_before_and_after { button(:name, name).click } end end # Click a button with caption # Usage: # click_button_with_caption("Confirm payment") def click_button_with_caption(caption, opts={}) if opts && opts[:index] wait_before_and_after { button(:caption => caption, :index => opts[:index]).click } else wait_before_and_after { button(:caption, caption).click } end end alias click_button click_button_with_caption alias click_button_with_text click_button_with_caption # Click a button with value # Usage: # click_button_with_value("Confirm payment") def click_button_with_value(value, opts={}) if opts && opts[:index] wait_before_and_after { button(:value => value, :index => opts[:index]).click } else wait_before_and_after { button(:value, value).click } end end # Select a dropdown list by name # Usage: # select_option("country", "Australia") def select_option(selectName, option) select_list(:name, selectName).select(option) end # submit first submit button def submit(buttonName = nil) if (buttonName.nil?) then buttons.each { |button| next if button.type != 'submit' button.click return } else click_button_with_name(buttonName) end end # Check a checkbox # Usage: # check_checkbox("agree") # check_checkbox("agree", "true") def check_checkbox(checkBoxName, values=nil) if values values.class == Array ? arys = values : arys = [values] arys.each {|cbx_value| if Watir::VERSION =~ /^1/ then checkbox(:name, checkBoxName, cbx_value).set else checkbox(:name => checkBoxName, :value => cbx_value).set end } else checkbox(:name, checkBoxName).set end end # Check a checkbox # Usage: # uncheck_checkbox("agree") # uncheck_checkbox("agree", "false") def uncheck_checkbox(checkBoxName, values = nil) if values values.class == Array ? arys = values : arys = [values] arys.each {|cbx_value| if Watir::VERSION =~ /^1/ then checkbox(:name, checkBoxName, cbx_value).clear else checkbox(:name => checkBoxName, :value => cbx_value).clear end } else checkbox(:name, checkBoxName).clear end end # Click a radio button # Usage: # click_radio_option("country", "Australia") def click_radio_option(radio_group, radio_option) if Watir::VERSION =~ /^1/ then radio(:name, radio_group, radio_option).set else radio(:name => radio_group, :value => radio_option).set end end alias click_radio_button click_radio_option # Clear a radio button # Usage: # click_radio_option("country", "Australia") def clear_radio_option(radio_group, radio_option) if Watir::VERSION =~ /^2/ then radio(:name => radio_group, :value => radio_option).clear else radio(:name, radio_group, radio_option).clear end end alias clear_radio_button clear_radio_option # Deprecated: using Watir style directly instead def element_by_id(elem_id) if is_firefox? # elem = @browser.document.getElementById(elem_id) # elem = div(:id, elem_id) || label(:id, elem_id) || button(:id, elem_id) || # span(:id, elem_id) || hidden(:id, elem_id) || link(:id, elem_id) || radio(:id, elem_id) elem = browser.element_by_xpath("//*[@id='#{elem_id}']") else elem = @browser.document.getElementById(elem_id) end end def element_value(elementId) elem = element_by_id(elementId) elem ? elem.invoke('innerText') : nil end def element_source(elementId) elem = element_by_id(elementId) assert_not_nil(elem, "HTML element: #{elementId} not exists") elem.innerHTML end def select_file_for_upload(file_field, file_path) normalized_file_path = RUBY_PLATFORM.downcase.include?("mingw") ? file_path.gsub("/", "\\") : file_path file_field(:name, file_field).set(normalized_file_path) end # Watir 1.9 def javascript_dialog @browser.javascript_dialog end def start_window(url = nil) @browser.start_window(url); end # Attach to existing browser # # Usage: # WebBrowser.attach_browser(:title, "iTest2") # WebBrowser.attach_browser(:url, "http://www.itest2.com") # WebBrowser.attach_browser(:url, "http://www.itest2.com", {:browser => "Firefox", :base_url => "http://www.itest2.com"}) # WebBrowser.attach_browser(:title, /agileway\.com\.au\/attachment/) # regular expression def self.attach_browser(how, what, options={}) default_options = {:browser => "IE"} options = default_options.merge(options) site_context = Context.new(options[:base_url]) if options[:base_url] return WebBrowser.new_from_existing(Watir::IE.attach(how, what), site_context) end # Attach a Watir::IE instance to a popup window. # # Typical usage # new_popup_window(:url => "http://www.google.com/a.pdf") def new_popup_window(options, browser = "ie") if is_firefox? raise "not implemented" else if options[:url] Watir::IE.attach(:url, options[:url]) elsif options[:title] Watir::IE.attach(:title, options[:title]) else raise 'Please specify title or url of new pop up window' end end end # --- # For deubgging # --- def dump_response(stream = nil) stream.nil? ? puts(page_source) : stream.puts(page_source) end # A Better Popup Handler using the latest Watir version. Posted by Mark_cain@rl.gov # # http://wiki.openqa.org/display/WTR/FAQ#FAQ-HowdoIattachtoapopupwindow%3F # def start_clicker( button, waitTime= 9, user_input=nil) # get a handle if one exists hwnd = @browser.enabled_popup(waitTime) if (hwnd) # yes there is a popup w = WinClicker.new if ( user_input ) w.setTextValueForFileNameField( hwnd, "#{user_input}" ) end # I put this in to see the text being input it is not necessary to work sleep 3 # "OK" or whatever the name on the button is w.clickWindowsButton_hwnd( hwnd, "#{button}" ) # # this is just cleanup w = nil end end # return underlying browser def ie @browser end # Save current web page source to file # usage: # save_page("/tmp/01.html") # save_page() => # will save to "20090830112200.html" def save_page(file_name = nil) file_name ||= Time.now.strftime("%Y%m%d%H%M%S") + ".html" puts "about to save page: #{File.expand_path(file_name)}" if $DEBUG File.open(file_name, "w").puts page_source end # Verify the next page following an operation. # # Typical usage: # browser.expect_page HomePage def expect_page(page_clazz, argument = nil) if argument page_clazz.new(self, argument) else page_clazz.new(self) end end # is it running in MS Windows platforms? def self.is_windows? RUBY_PLATFORM.downcase.include?("mswin") or RUBY_PLATFORM.downcase.include?("mingw") end end
chaintope/bitcoinrb
lib/bitcoin/script/script.rb
Bitcoin.Script.p2pkh?
ruby
def p2pkh? return false unless chunks.size == 5 [OP_DUP, OP_HASH160, OP_EQUALVERIFY, OP_CHECKSIG] == (chunks[0..1]+ chunks[3..4]).map(&:ord) && chunks[2].bytesize == 21 end
whether this script is a P2PKH format script.
train
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L169-L173
class Script include Bitcoin::Opcodes attr_accessor :chunks def initialize @chunks = [] end # generate P2PKH script def self.to_p2pkh(pubkey_hash) new << OP_DUP << OP_HASH160 << pubkey_hash << OP_EQUALVERIFY << OP_CHECKSIG end # generate P2WPKH script def self.to_p2wpkh(pubkey_hash) new << WITNESS_VERSION << pubkey_hash end # generate m of n multisig p2sh script # @param [String] m the number of signatures required for multisig # @param [Array] pubkeys array of public keys that compose multisig # @return [Script, Script] first element is p2sh script, second one is redeem script. def self.to_p2sh_multisig_script(m, pubkeys) redeem_script = to_multisig_script(m, pubkeys) [redeem_script.to_p2sh, redeem_script] end # generate p2sh script. # @param [String] script_hash script hash for P2SH # @return [Script] P2SH script def self.to_p2sh(script_hash) Script.new << OP_HASH160 << script_hash << OP_EQUAL end # generate p2sh script with this as a redeem script # @return [Script] P2SH script def to_p2sh Script.to_p2sh(to_hash160) end def get_multisig_pubkeys num = Bitcoin::Opcodes.opcode_to_small_int(chunks[-2].bth.to_i(16)) (1..num).map{ |i| chunks[i].pushed_data } end # generate m of n multisig script # @param [String] m the number of signatures required for multisig # @param [Array] pubkeys array of public keys that compose multisig # @return [Script] multisig script. def self.to_multisig_script(m, pubkeys) new << m << pubkeys << pubkeys.size << OP_CHECKMULTISIG end # generate p2wsh script for +redeem_script+ # @param [Script] redeem_script target redeem script # @param [Script] p2wsh script def self.to_p2wsh(redeem_script) new << WITNESS_VERSION << redeem_script.to_sha256 end # generate script from string. def self.from_string(string) script = new string.split(' ').each do |v| opcode = Opcodes.name_to_opcode(v) if opcode script << (v =~ /^\d/ && Opcodes.small_int_to_opcode(v.ord) ? v.ord : opcode) else script << (v =~ /^[0-9]+$/ ? v.to_i : v) end end script end # generate script from addr. # @param [String] addr address. # @return [Bitcoin::Script] parsed script. def self.parse_from_addr(addr) begin segwit_addr = Bech32::SegwitAddr.new(addr) raise 'Invalid hrp.' unless Bitcoin.chain_params.bech32_hrp == segwit_addr.hrp Bitcoin::Script.parse_from_payload(segwit_addr.to_script_pubkey.htb) rescue Exception => e hex, addr_version = Bitcoin.decode_base58_address(addr) case addr_version when Bitcoin.chain_params.address_version Bitcoin::Script.to_p2pkh(hex) when Bitcoin.chain_params.p2sh_version Bitcoin::Script.to_p2sh(hex) else throw e end end end def self.parse_from_payload(payload) s = new buf = StringIO.new(payload) until buf.eof? opcode = buf.read(1) if opcode.pushdata? pushcode = opcode.ord packed_size = nil len = case pushcode when OP_PUSHDATA1 packed_size = buf.read(1) packed_size.unpack('C').first when OP_PUSHDATA2 packed_size = buf.read(2) packed_size.unpack('v').first when OP_PUSHDATA4 packed_size = buf.read(4) packed_size.unpack('V').first else pushcode if pushcode < OP_PUSHDATA1 end if len s.chunks << [len].pack('C') if buf.eof? unless buf.eof? chunk = (packed_size ? (opcode + packed_size) : (opcode)) + buf.read(len) s.chunks << chunk end end else if Opcodes.defined?(opcode.ord) s << opcode.ord else s.chunks << (opcode + buf.read) # If opcode is invalid, put all remaining data in last chunk. end end end s end def to_payload chunks.join end def to_hex to_payload.bth end def empty? chunks.size == 0 end def addresses return [p2pkh_addr] if p2pkh? return [p2sh_addr] if p2sh? return [bech32_addr] if witness_program? return get_multisig_pubkeys.map{|pubkey| Bitcoin::Key.new(pubkey: pubkey.bth).to_p2pkh} if multisig? [] end # check whether standard script. def standard? p2pkh? | p2sh? | p2wpkh? | p2wsh? | multisig? | standard_op_return? end # whether this script is a P2PKH format script. # whether this script is a P2WPKH format script. def p2wpkh? return false unless chunks.size == 2 chunks[0].ord == WITNESS_VERSION && chunks[1].bytesize == 21 end def p2wsh? return false unless chunks.size == 2 chunks[0].ord == WITNESS_VERSION && chunks[1].bytesize == 33 end def p2sh? return false unless chunks.size == 3 OP_HASH160 == chunks[0].ord && OP_EQUAL == chunks[2].ord && chunks[1].bytesize == 21 end def multisig? return false if chunks.size < 4 || chunks.last.ord != OP_CHECKMULTISIG pubkey_count = Opcodes.opcode_to_small_int(chunks[-2].opcode) sig_count = Opcodes.opcode_to_small_int(chunks[0].opcode) return false unless pubkey_count || sig_count sig_count <= pubkey_count end def op_return? chunks.size >= 1 && chunks[0].ord == OP_RETURN end def standard_op_return? op_return? && size <= MAX_OP_RETURN_RELAY && (chunks.size == 1 || chunks[1].opcode <= OP_16) end def op_return_data return nil unless op_return? return nil if chunks.size == 1 chunks[1].pushed_data end # whether data push only script which dose not include other opcode def push_only? chunks.each do |c| return false if !c.opcode.nil? && c.opcode > OP_16 end true end # A witness program is any valid Script that consists of a 1-byte push opcode followed by a data push between 2 and 40 bytes. def witness_program? return false if size < 4 || size > 42 || chunks.size < 2 opcode = chunks[0].opcode return false if opcode != OP_0 && (opcode < OP_1 || opcode > OP_16) return false unless chunks[1].pushdata? if size == (chunks[1][0].unpack('C').first + 2) program_size = chunks[1].pushed_data.bytesize return program_size >= 2 && program_size <= 40 end false end # get witness commitment def witness_commitment return nil if !op_return? || op_return_data.bytesize < 36 buf = StringIO.new(op_return_data) return nil unless buf.read(4).bth == WITNESS_COMMITMENT_HEADER buf.read(32).bth end # If this script is witness program, return its script code, # otherwise returns the self payload. ScriptInterpreter does not use this. def to_script_code(skip_separator_index = 0) payload = to_payload if p2wpkh? payload = Script.to_p2pkh(chunks[1].pushed_data.bth).to_payload elsif skip_separator_index > 0 payload = subscript_codeseparator(skip_separator_index) end Bitcoin.pack_var_string(payload) end # get witness version and witness program def witness_data version = opcode_to_small_int(chunks[0].opcode) program = chunks[1].pushed_data [version, program] end # append object to payload def <<(obj) if obj.is_a?(Integer) push_int(obj) elsif obj.is_a?(String) append_data(obj) elsif obj.is_a?(Array) obj.each { |o| self.<< o} self end end # push integer to stack. def push_int(n) begin append_opcode(n) rescue ArgumentError append_data(Script.encode_number(n)) end self end # append opcode to payload # @param [Integer] opcode append opcode which defined by Bitcoin::Opcodes # @return [Script] return self def append_opcode(opcode) opcode = Opcodes.small_int_to_opcode(opcode) if -1 <= opcode && opcode <= 16 raise ArgumentError, "specified invalid opcode #{opcode}." unless Opcodes.defined?(opcode) chunks << opcode.chr self end # append data to payload with pushdata opcode # @param [String] data append data. this data is not binary # @return [Script] return self def append_data(data) data = Encoding::ASCII_8BIT == data.encoding ? data : data.htb chunks << Bitcoin::Script.pack_pushdata(data) self end # Check the item is in the chunk of the script. def include?(item) chunk_item = if item.is_a?(Integer) item.chr elsif item.is_a?(String) data = Encoding::ASCII_8BIT == item.encoding ? item : item.htb Bitcoin::Script.pack_pushdata(data) end return false unless chunk_item chunks.include?(chunk_item) end def to_s chunks.map { |c| case c when Integer opcode_to_name(c) when String if c.pushdata? v = Opcodes.opcode_to_small_int(c.ord) if v v else data = c.pushed_data if data.bytesize <= 4 Script.decode_number(data.bth) # for scriptnum else data.bth end end else opcode = Opcodes.opcode_to_name(c.ord) opcode ? opcode : 'OP_UNKNOWN [error]' end end }.join(' ') end # generate sha-256 hash for payload def to_sha256 Bitcoin.sha256(to_payload).bth end # generate hash160 hash for payload def to_hash160 Bitcoin.hash160(to_payload.bth) end # script size def size to_payload.bytesize end # execute script interpreter using this script for development. def run Bitcoin::ScriptInterpreter.eval(Bitcoin::Script.new, self.dup) end # encode int value to script number hex. # The stacks hold byte vectors. # When used as numbers, byte vectors are interpreted as little-endian variable-length integers # with the most significant bit determining the sign of the integer. # Thus 0x81 represents -1. 0x80 is another representation of zero (so called negative 0). # Positive 0 is represented by a null-length vector. # Byte vectors are interpreted as Booleans where False is represented by any representation of zero, # and True is represented by any representation of non-zero. def self.encode_number(i) return '' if i == 0 negative = i < 0 hex = i.abs.to_even_length_hex hex = '0' + hex unless (hex.length % 2).zero? v = hex.htb.reverse # change endian v = v << (negative ? 0x80 : 0x00) unless (v[-1].unpack('C').first & 0x80) == 0 v[-1] = [v[-1].unpack('C').first | 0x80].pack('C') if negative v.bth end # decode script number hex to int value def self.decode_number(s) v = s.htb.reverse return 0 if v.length.zero? mbs = v[0].unpack('C').first v[0] = [mbs - 0x80].pack('C') unless (mbs & 0x80) == 0 result = v.bth.to_i(16) result = -result unless (mbs & 0x80) == 0 result end # binary +data+ convert pushdata which contains data length and append PUSHDATA opcode if necessary. def self.pack_pushdata(data) size = data.bytesize header = if size < OP_PUSHDATA1 [size].pack('C') elsif size < 0xff [OP_PUSHDATA1, size].pack('CC') elsif size < 0xffff [OP_PUSHDATA2, size].pack('Cv') elsif size < 0xffffffff [OP_PUSHDATA4, size].pack('CV') else raise ArgumentError, 'data size is too big.' end header + data end # subscript this script to the specified range. def subscript(*args) s = self.class.new s.chunks = chunks[*args] s end # removes chunks matching subscript byte-for-byte and returns as a new object. def find_and_delete(subscript) raise ArgumentError, 'subscript must be Bitcoin::Script' unless subscript.is_a?(Script) return self if subscript.chunks.empty? buf = [] i = 0 result = Script.new chunks.each do |chunk| sub_chunk = subscript.chunks[i] if chunk.start_with?(sub_chunk) if chunk == sub_chunk buf << chunk i += 1 (i = 0; buf.clear) if i == subscript.chunks.size # matched the whole subscript else # matched the part of head i = 0 tmp = chunk.dup tmp.slice!(sub_chunk) result.chunks << tmp end else result.chunks << buf.join unless buf.empty? if buf.first == chunk i = 1 buf = [chunk] else i = 0 result.chunks << chunk end end end result end # remove all occurences of opcode. Typically it's OP_CODESEPARATOR. def delete_opcode(opcode) @chunks = chunks.select{|chunk| chunk.ord != opcode} self end # Returns a script that deleted the script before the index specified by separator_index. def subscript_codeseparator(separator_index) buf = [] process_separator_index = 0 chunks.each{|chunk| buf << chunk if process_separator_index == separator_index if chunk.ord == OP_CODESEPARATOR && process_separator_index < separator_index process_separator_index += 1 end } buf.join end def ==(other) return false unless other chunks == other.chunks end def type return 'pubkeyhash' if p2pkh? return 'scripthash' if p2sh? return 'multisig' if multisig? return 'witness_v0_keyhash' if p2wpkh? return 'witness_v0_scripthash' if p2wsh? 'nonstandard' end def to_h h = {asm: to_s, hex: to_payload.bth, type: type} addrs = addresses unless addrs.empty? h[:req_sigs] = multisig? ? Bitcoin::Opcodes.opcode_to_small_int(chunks[0].bth.to_i(16)) :addrs.size h[:addresses] = addrs end h end private # generate p2pkh address. if script dose not p2pkh, return nil. def p2pkh_addr return nil unless p2pkh? hash160 = chunks[2].pushed_data.bth return nil unless hash160.htb.bytesize == 20 Bitcoin.encode_base58_address(hash160, Bitcoin.chain_params.address_version) end # generate p2wpkh address. if script dose not p2wpkh, return nil. def p2wpkh_addr p2wpkh? ? bech32_addr : nil end # generate p2sh address. if script dose not p2sh, return nil. def p2sh_addr return nil unless p2sh? hash160 = chunks[1].pushed_data.bth return nil unless hash160.htb.bytesize == 20 Bitcoin.encode_base58_address(hash160, Bitcoin.chain_params.p2sh_version) end # generate p2wsh address. if script dose not p2wsh, return nil. def p2wsh_addr p2wsh? ? bech32_addr : nil end # return bech32 address for payload def bech32_addr segwit_addr = Bech32::SegwitAddr.new segwit_addr.hrp = Bitcoin.chain_params.bech32_hrp segwit_addr.script_pubkey = to_payload.bth segwit_addr.addr end end
tandusrl/acts_as_bookable
lib/acts_as_bookable/booking.rb
ActsAsBookable.Booking.booker_must_be_booker
ruby
def booker_must_be_booker if booker.present? && !booker.class.booker? errors.add(:booker, T.er('booking.booker_must_be_booker', model: booker.class.to_s)) end end
Validation method. Check if the booker model is actually a booker
train
https://github.com/tandusrl/acts_as_bookable/blob/45b78114e1a5dab96e59fc70933277a56f65b53b/lib/acts_as_bookable/booking.rb#L48-L52
class Booking < ::ActiveRecord::Base self.table_name = 'acts_as_bookable_bookings' belongs_to :bookable, polymorphic: true belongs_to :booker, polymorphic: true validates_presence_of :bookable validates_presence_of :booker validate :bookable_must_be_bookable, :booker_must_be_booker ## # Retrieves overlapped bookings, given a bookable and some booking options # scope :overlapped, ->(bookable,opts) { query = where(bookable_id: bookable.id) # Time options if(opts[:time].present?) query = DBUtils.time_comparison(query,'time','=',opts[:time]) end if(opts[:time_start].present?) query = DBUtils.time_comparison(query,'time_end', '>=', opts[:time_start]) end if(opts[:time_end].present?) query = DBUtils.time_comparison(query,'time_start', '<', opts[:time_end]) end query } private ## # Validation method. Check if the bookable resource is actually bookable # def bookable_must_be_bookable if bookable.present? && !bookable.class.bookable? errors.add(:bookable, T.er('booking.bookable_must_be_bookable', model: bookable.class.to_s)) end end ## # Validation method. Check if the booker model is actually a booker # end
willfore/cp_mgmt_ruby
lib/cp_mgmt/host.rb
CpMgmt.Host.show
ruby
def show(name) client = CpMgmt.configuration.client CpMgmt.logged_in? body = {name: name}.to_json response = client.post do |req| req.url '/web_api/show-host' req.headers['Content-Type'] = 'application/json' req.headers['X-chkp-sid'] = ENV.fetch("sid") req.body = body end CpMgmt.transform_response(response) end
Shows a host
train
https://github.com/willfore/cp_mgmt_ruby/blob/d25f169561f254bd13cc6fa5afa6b362637c1f65/lib/cp_mgmt/host.rb#L35-L47
class Host # Adds a host def add(name, ip_address, options={}) client = CpMgmt.configuration.client CpMgmt.logged_in? params = {name: name, "ip-address": ip_address} body = params.merge(options).to_json response = client.post do |req| req.url '/web_api/add-host' req.headers['Content-Type'] = 'application/json' req.headers['X-chkp-sid'] = ENV.fetch("sid") req.body = body end CpMgmt.transform_response(response) end # removes a host def remove(name) client = CpMgmt.configuration.client CpMgmt.logged_in? body = {name: name}.to_json response = client.post do |req| req.url '/web_api/delete-host' req.headers['Content-Type'] = 'application/json' req.headers['X-chkp-sid'] = ENV.fetch("sid") req.body = body end CpMgmt.transform_response(response) end # Shows a host # Shows all hosts def show_all client = CpMgmt.configuration.client CpMgmt.logged_in? response = client.post do |req| req.url '/web_api/show-hosts' req.headers['Content-Type'] = 'application/json' req.headers['X-chkp-sid'] = ENV.fetch("sid") req.body = "{}" end CpMgmt.transform_response(response) end end
mongodb/mongoid
lib/mongoid/fields.rb
Mongoid.Fields.apply_default
ruby
def apply_default(name) unless attributes.key?(name) if field = fields[name] default = field.eval_default(self) unless default.nil? || field.lazy? attribute_will_change!(name) attributes[name] = default end end end end
Applies a single default value for the given name. @example Apply a single default. model.apply_default("name") @param [ String ] name The name of the field. @since 2.4.0
train
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/fields.rb#L101-L111
module Fields extend ActiveSupport::Concern # For fields defined with symbols use the correct class. # # @since 4.0.0 TYPE_MAPPINGS = { array: Array, big_decimal: BigDecimal, binary: BSON::Binary, boolean: Mongoid::Boolean, date: Date, date_time: DateTime, float: Float, hash: Hash, integer: Integer, object_id: BSON::ObjectId, range: Range, regexp: Regexp, set: Set, string: String, symbol: Symbol, time: Time }.with_indifferent_access # Constant for all names of the id field in a document. # # @since 5.0.0 IDS = [ :_id, :id, '_id', 'id' ].freeze included do class_attribute :aliased_fields class_attribute :localized_fields class_attribute :fields class_attribute :pre_processed_defaults class_attribute :post_processed_defaults self.aliased_fields = { "id" => "_id" } self.fields = {} self.localized_fields = {} self.pre_processed_defaults = [] self.post_processed_defaults = [] field( :_id, default: ->{ BSON::ObjectId.new }, pre_processed: true, type: BSON::ObjectId ) alias :id :_id alias :id= :_id= end # Apply all default values to the document which are not procs. # # @example Apply all the non-proc defaults. # model.apply_pre_processed_defaults # # @return [ Array<String ] The names of the non-proc defaults. # # @since 2.4.0 def apply_pre_processed_defaults pre_processed_defaults.each do |name| apply_default(name) end end # Apply all default values to the document which are procs. # # @example Apply all the proc defaults. # model.apply_post_processed_defaults # # @return [ Array<String ] The names of the proc defaults. # # @since 2.4.0 def apply_post_processed_defaults post_processed_defaults.each do |name| apply_default(name) end end # Applies a single default value for the given name. # # @example Apply a single default. # model.apply_default("name") # # @param [ String ] name The name of the field. # # @since 2.4.0 # Apply all the defaults at once. # # @example Apply all the defaults. # model.apply_defaults # # @since 2.4.0 def apply_defaults apply_pre_processed_defaults apply_post_processed_defaults end # Returns an array of names for the attributes available on this object. # # Provides the field names in an ORM-agnostic way. Rails v3.1+ uses this # method to automatically wrap params in JSON requests. # # @example Get the field names # docment.attribute_names # # @return [ Array<String> ] The field names # # @since 3.0.0 def attribute_names self.class.attribute_names end # Get the name of the provided field as it is stored in the database. # Used in determining if the field is aliased or not. # # @example Get the database field name. # model.database_field_name(:authorization) # # @param [ String, Symbol ] name The name to get. # # @return [ String ] The name of the field as it's stored in the db. # # @since 3.0.7 def database_field_name(name) self.class.database_field_name(name) end # Is the provided field a lazy evaluation? # # @example If the field is lazy settable. # doc.lazy_settable?(field, nil) # # @param [ Field ] field The field. # @param [ Object ] value The current value. # # @return [ true, false ] If we set the field lazily. # # @since 3.1.0 def lazy_settable?(field, value) !frozen? && value.nil? && field.lazy? end # Is the document using object ids? # # @note Refactored from using delegate for class load performance. # # @example Is the document using object ids? # model.using_object_ids? # # @return [ true, false ] Using object ids. def using_object_ids? self.class.using_object_ids? end class << self # Stores the provided block to be run when the option name specified is # defined on a field. # # No assumptions are made about what sort of work the handler might # perform, so it will always be called if the `option_name` key is # provided in the field definition -- even if it is false or nil. # # @example # Mongoid::Fields.option :required do |model, field, value| # model.validates_presence_of field if value # end # # @param [ Symbol ] option_name the option name to match against # @param [ Proc ] block the handler to execute when the option is # provided. # # @since 2.1.0 def option(option_name, &block) options[option_name] = block end # Return a map of custom option names to their handlers. # # @example # Mongoid::Fields.options # # => { :required => #<Proc:0x00000100976b38> } # # @return [ Hash ] the option map # # @since 2.1.0 def options @options ||= {} end end module ClassMethods # Returns an array of names for the attributes available on this object. # # Provides the field names in an ORM-agnostic way. Rails v3.1+ uses this # method to automatically wrap params in JSON requests. # # @example Get the field names # Model.attribute_names # # @return [ Array<String> ] The field names # # @since 3.0.0 def attribute_names fields.keys end # Get the name of the provided field as it is stored in the database. # Used in determining if the field is aliased or not. # # @example Get the database field name. # Model.database_field_name(:authorization) # # @param [ String, Symbol ] name The name to get. # # @return [ String ] The name of the field as it's stored in the db. # # @since 3.0.7 def database_field_name(name) return nil unless name normalized = name.to_s aliased_fields[normalized] || normalized end # Defines all the fields that are accessible on the Document # For each field that is defined, a getter and setter will be # added as an instance method to the Document. # # @example Define a field. # field :score, :type => Integer, :default => 0 # # @param [ Symbol ] name The name of the field. # @param [ Hash ] options The options to pass to the field. # # @option options [ Class ] :type The type of the field. # @option options [ String ] :label The label for the field. # @option options [ Object, Proc ] :default The field's default # # @return [ Field ] The generated field def field(name, options = {}) named = name.to_s Validators::Macro.validate(self, name, options) added = add_field(named, options) descendants.each do |subclass| subclass.add_field(named, options) end added end # Replace a field with a new type. # # @example Replace the field. # Model.replace_field("_id", String) # # @param [ String ] name The name of the field. # @param [ Class ] type The new type of field. # # @return [ Serializable ] The new field. # # @since 2.1.0 def replace_field(name, type) remove_defaults(name) add_field(name, fields[name].options.merge(type: type)) end # Convenience method for determining if we are using +BSON::ObjectIds+ as # our id. # # @example Does this class use object ids? # person.using_object_ids? # # @return [ true, false ] If the class uses BSON::ObjectIds for the id. # # @since 1.0.0 def using_object_ids? fields["_id"].object_id_field? end protected # Add the defaults to the model. This breaks them up between ones that # are procs and ones that are not. # # @example Add to the defaults. # Model.add_defaults(field) # # @param [ Field ] field The field to add for. # # @since 2.4.0 def add_defaults(field) default, name = field.default_val, field.name.to_s remove_defaults(name) unless default.nil? if field.pre_processed? pre_processed_defaults.push(name) else post_processed_defaults.push(name) end end end # Define a field attribute for the +Document+. # # @example Set the field. # Person.add_field(:name, :default => "Test") # # @param [ Symbol ] name The name of the field. # @param [ Hash ] options The hash of options. def add_field(name, options = {}) aliased = options[:as] aliased_fields[aliased.to_s] = name if aliased field = field_for(name, options) fields[name] = field add_defaults(field) create_accessors(name, name, options) create_accessors(name, aliased, options) if aliased process_options(field) create_dirty_methods(name, name) create_dirty_methods(name, aliased) if aliased field end # Run through all custom options stored in Mongoid::Fields.options and # execute the handler if the option is provided. # # @example # Mongoid::Fields.option :custom do # puts "called" # end # # field = Mongoid::Fields.new(:test, :custom => true) # Person.process_options(field) # # => "called" # # @param [ Field ] field the field to process def process_options(field) field_options = field.options Fields.options.each_pair do |option_name, handler| if field_options.key?(option_name) handler.call(self, field, field_options[option_name]) end end end # Create the field accessors. # # @example Generate the accessors. # Person.create_accessors(:name, "name") # person.name #=> returns the field # person.name = "" #=> sets the field # person.name? #=> Is the field present? # person.name_before_type_cast #=> returns the field before type cast # # @param [ Symbol ] name The name of the field. # @param [ Symbol ] meth The name of the accessor. # @param [ Hash ] options The options. # # @since 2.0.0 def create_accessors(name, meth, options = {}) field = fields[name] create_field_getter(name, meth, field) create_field_getter_before_type_cast(name, meth) create_field_setter(name, meth, field) create_field_check(name, meth) if options[:localize] create_translations_getter(name, meth) create_translations_setter(name, meth, field) localized_fields[name] = field end end # Create the getter method for the provided field. # # @example Create the getter. # Model.create_field_getter("name", "name", field) # # @param [ String ] name The name of the attribute. # @param [ String ] meth The name of the method. # @param [ Field ] field The field. # # @since 2.4.0 def create_field_getter(name, meth, field) generated_methods.module_eval do re_define_method(meth) do raw = read_raw_attribute(name) if lazy_settable?(field, raw) write_attribute(name, field.eval_default(self)) else value = field.demongoize(raw) attribute_will_change!(name) if value.resizable? value end end end end # Create the getter_before_type_cast method for the provided field. If # the attribute has been assigned, return the attribute before it was # type cast. Otherwise, delegate to the getter. # # @example Create the getter_before_type_cast. # Model.create_field_getter_before_type_cast("name", "name") # # @param [ String ] name The name of the attribute. # @param [ String ] meth The name of the method. # # @since 3.1.0 def create_field_getter_before_type_cast(name, meth) generated_methods.module_eval do re_define_method("#{meth}_before_type_cast") do if has_attribute_before_type_cast?(name) read_attribute_before_type_cast(name) else send meth end end end end # Create the setter method for the provided field. # # @example Create the setter. # Model.create_field_setter("name", "name") # # @param [ String ] name The name of the attribute. # @param [ String ] meth The name of the method. # @param [ Field ] field The field. # # @since 2.4.0 def create_field_setter(name, meth, field) generated_methods.module_eval do re_define_method("#{meth}=") do |value| val = write_attribute(name, value) if field.foreign_key? remove_ivar(field.association.name) end val end end end # Create the check method for the provided field. # # @example Create the check. # Model.create_field_check("name", "name") # # @param [ String ] name The name of the attribute. # @param [ String ] meth The name of the method. # # @since 2.4.0 def create_field_check(name, meth) generated_methods.module_eval do re_define_method("#{meth}?") do value = read_raw_attribute(name) lookup_attribute_presence(name, value) end end end # Create the translation getter method for the provided field. # # @example Create the translation getter. # Model.create_translations_getter("name", "name") # # @param [ String ] name The name of the attribute. # @param [ String ] meth The name of the method. # # @since 2.4.0 def create_translations_getter(name, meth) generated_methods.module_eval do re_define_method("#{meth}_translations") do (attributes[name] ||= {}).with_indifferent_access end alias_method :"#{meth}_t", :"#{meth}_translations" end end # Create the translation setter method for the provided field. # # @example Create the translation setter. # Model.create_translations_setter("name", "name") # # @param [ String ] name The name of the attribute. # @param [ String ] meth The name of the method. # @param [ Field ] field The field. # # @since 2.4.0 def create_translations_setter(name, meth, field) generated_methods.module_eval do re_define_method("#{meth}_translations=") do |value| attribute_will_change!(name) if value value.update_values do |_value| field.type.mongoize(_value) end end attributes[name] = value end alias_method :"#{meth}_t=", :"#{meth}_translations=" end end # Include the field methods as a module, so they can be overridden. # # @example Include the fields. # Person.generated_methods # # @return [ Module ] The module of generated methods. # # @since 2.0.0 def generated_methods @generated_methods ||= begin mod = Module.new include(mod) mod end end # Remove the default keys for the provided name. # # @example Remove the default keys. # Model.remove_defaults(name) # # @param [ String ] name The field name. # # @since 2.4.0 def remove_defaults(name) pre_processed_defaults.delete_one(name) post_processed_defaults.delete_one(name) end def field_for(name, options) opts = options.merge(klass: self) type_mapping = TYPE_MAPPINGS[options[:type]] opts[:type] = type_mapping || unmapped_type(options) return Fields::Localized.new(name, opts) if options[:localize] return Fields::ForeignKey.new(name, opts) if options[:identity] Fields::Standard.new(name, opts) end def unmapped_type(options) if "Boolean" == options[:type].to_s Mongoid::Boolean else options[:type] || Object end end end end