repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
palladius/ric
3078a1d917ffbc96a87cc5090485ca948631ddfb
lib/ric/files.rb
https://github.com/palladius/ric/blob/3078a1d917ffbc96a87cc5090485ca948631ddfb/lib/ric/files.rb#L10-L58
ruby
test
# =begin # # This tries to implement the xcopy for my git programs # # similar to xcopy # # Originally called 'tra va sa' # =end
def xcopy(from,to,glob_files, opts={})
# =begin # # This tries to implement the xcopy for my git programs # # similar to xcopy # # Originally called 'tra va sa' # =end def xcopy(from,to,glob_files, opts={})
n_actions = 0 puts "+ Travasing: #{yellow from} ==> #{green to}" verbose = opts.fetch :verbose, true dryrun = opts.fetch :dryrun, true # i scared of copying files! unless File.exists?("#{to}/.git") fatal 11,"Sorry cant travase data to an unversioned dir. Please version it with git (or add a .git dir/file to trick me)" exit 1 end unless File.exists?("#{to}/.safe_xcopy") fatal 12, "Sorry I refuse to xcopy data unless you explicitly ask me to. You have to do this before:\n #{yellow "touch #{to}/.safe_xcopy"} . You are for sure a very smart person but there are a LOT of people out there who could destroy theyr file system! Thanks" end # With this i can understand what has been deleted, with lots of magic from git on both ends.. :) deb "+ First the differences:" deb `diff -qr #{from} #{to} |egrep -v '\\.git' ` puts "Dryrun is: #{azure dryrun}" puts "+ Files: #{cyan glob_files}" Dir.chdir(from) Dir.glob(glob_files).each{ |file| from_file = "#{from}/#{file}" to_file = "#{to}/#{file}" destdir = File.dirname(to_file) deb "Copying: #{yellow from_file}.." # could need creating the dir.. if File.exists?(destdir) # just copy the file command = "cp \"#{from_file}\" \"#{to_file}\"" else # mkdir dest AND copy file pred "Hey, Dir '#{destdir}' doesnt exist! Creating it.." command = "mkdir -p \"#{destdir}\" && cp \"#{from_file}\" \"#{to_file}\"" end if dryrun puts "[DRYRUN] Skipping #{gray command}" else ret = `#{command} 2>&1` puts "EXE: #{gray command}" if verbose n_actions += 1 print( "[ret=$?]", ret, "\n") if (ret.length > 1 || $? != 0) # if output or not zero end } puts "#{n_actions} commands executed." end
chrisjones-tripletri/rake_command_filter
0c55e58f261b088d5ba67ea3bf28e6ad8b2be68f
lib/line_filter_result.rb
https://github.com/chrisjones-tripletri/rake_command_filter/blob/0c55e58f261b088d5ba67ea3bf28e6ad8b2be68f/lib/line_filter_result.rb#L52-L68
ruby
test
# Called to output the result to the console. # @param elapsed the time running the command so far # rubocop:disable MethodLength
def output(elapsed)
# Called to output the result to the console. # @param elapsed the time running the command so far # rubocop:disable MethodLength def output(elapsed)
case @result when MATCH_SUCCESS color = :green header = 'OK' when MATCH_FAILURE color = :red header = 'FAIL' when MATCH_WARNING color = :light_red header = 'WARN' end header = header.ljust(12).colorize(color) str_elapsed = "#{elapsed.round(2)}s" name = @name.to_s[0..17] puts "#{header} #{name.ljust(20)} #{str_elapsed.ljust(9)} #{@message}" end
vpereira/bugzilla
6832b6741adacbff7d177467325822dd90424a9d
lib/bugzilla/user.rb
https://github.com/vpereira/bugzilla/blob/6832b6741adacbff7d177467325822dd90424a9d/lib/bugzilla/user.rb#L41-L71
ruby
test
# rdoc # # ==== Bugzilla::User#session(user, password) # # Keeps the bugzilla session during doing something in the block.
def session(user, password)
# rdoc # # ==== Bugzilla::User#session(user, password) # # Keeps the bugzilla session during doing something in the block. def session(user, password)
key, fname = authentication_method # TODO # make those variables available host = @iface.instance_variable_get(:@xmlrpc).instance_variable_get(:@host) conf = load_authentication_token(fname) val = conf.fetch(host, nil) if !val.nil? if key == :token @iface.token = val else @iface.cookie = val end yield elsif user.nil? || password.nil? yield return else login('login' => user, 'password' => password, 'remember' => true) yield end conf[host] = @iface.send(key) if %i[token cookie].include? key save_authentication_token(fname, conf) key end
vpereira/bugzilla
6832b6741adacbff7d177467325822dd90424a9d
lib/bugzilla/user.rb
https://github.com/vpereira/bugzilla/blob/6832b6741adacbff7d177467325822dd90424a9d/lib/bugzilla/user.rb#L78-L99
ruby
test
# def session # rdoc # # ==== Bugzilla::User#get_userinfo(params)
def get_userinfo(user)
# def session # rdoc # # ==== Bugzilla::User#get_userinfo(params) def get_userinfo(user)
p = {} ids = [] names = [] if user.is_a?(Array) user.each do |u| names << u if u.is_a?(String) id << u if u.is_a?(Integer) end elsif user.is_a?(String) names << user elsif user.is_a?(Integer) ids << user else raise ArgumentError, format('Unknown type of arguments: %s', user.class) end result = get('ids' => ids, 'names' => names) result['users'] end
vpereira/bugzilla
6832b6741adacbff7d177467325822dd90424a9d
lib/bugzilla/user.rb
https://github.com/vpereira/bugzilla/blob/6832b6741adacbff7d177467325822dd90424a9d/lib/bugzilla/user.rb#L174-L180
ruby
test
# def _update
def _get(cmd, *args)
# def _update def _get(cmd, *args)
raise ArgumentError, 'Invalid parameters' unless args[0].is_a?(Hash) requires_version(cmd, 3.4) res = @iface.call(cmd, args[0]) # FIXME end
noiseunion/do-toolbox
7baf94bb89328da8ea1ec609950c7310cf097f37
lib/digital_opera/banker.rb
https://github.com/noiseunion/do-toolbox/blob/7baf94bb89328da8ea1ec609950c7310cf097f37/lib/digital_opera/banker.rb#L36-L43
ruby
test
# Instance Methods --------------------------------------------------------
def banker_convert_currency(value, conversion)
# Instance Methods -------------------------------------------------------- def banker_convert_currency(value, conversion)
case conversion.to_sym when :to_cents return (value.to_s.gsub(/,/, '').to_d * 100).to_i when :to_dollars return "%0.2f" % (value.to_f / 100) end end
avillafiorita/dreader
d2ed928ccaa1e35d34404a63cb65c17862aaf4ac
lib/dreader.rb
https://github.com/avillafiorita/dreader/blob/d2ed928ccaa1e35d34404a63cb65c17862aaf4ac/lib/dreader.rb#L120-L125
ruby
test
# define a DSL for options # any string is processed as an option and it ends up in the # @options hash
def options &block
# define a DSL for options # any string is processed as an option and it ends up in the # @options hash def options &block
options = Options.new options.instance_eval(&block) @options = options.to_hash end
avillafiorita/dreader
d2ed928ccaa1e35d34404a63cb65c17862aaf4ac
lib/dreader.rb
https://github.com/avillafiorita/dreader/blob/d2ed928ccaa1e35d34404a63cb65c17862aaf4ac/lib/dreader.rb#L132-L137
ruby
test
# define a DSL for column specification # - `name` is the name of the column # - `block` contains two declarations, `process` and `check`, which are # used, respectively, to make a cell into the desired data and to check # whether the desired data is ok
def column name, &block
# define a DSL for column specification # - `name` is the name of the column # - `block` contains two declarations, `process` and `check`, which are # used, respectively, to make a cell into the desired data and to check # whether the desired data is ok def column name, &block
column = Column.new column.instance_eval(&block) @colspec << column.to_hash.merge({name: name}) end
avillafiorita/dreader
d2ed928ccaa1e35d34404a63cb65c17862aaf4ac
lib/dreader.rb
https://github.com/avillafiorita/dreader/blob/d2ed928ccaa1e35d34404a63cb65c17862aaf4ac/lib/dreader.rb#L172-L181
ruby
test
# bulk declare columns we intend to read # # - hash is a hash in the form { symbolic_name: colref } # # i.bulk_declare {name: 'B', age: 'C'} is equivalent to: # # i.column :name do # colref 'B' # end # i.column :age do # colref 'C' # end # # i.bulk_declare {name: 'B', age: 'C'} do # process do |cell| # cell.strip # end # end # # is equivalent to: # # i.column :name do # colref 'B' # process do |cell| # cell.strip # end # end # i.column :age do # colref 'C' # process do |cell| # cell.strip # end # end
def bulk_declare hash, &block
# bulk declare columns we intend to read # # - hash is a hash in the form { symbolic_name: colref } # # i.bulk_declare {name: 'B', age: 'C'} is equivalent to: # # i.column :name do # colref 'B' # end # i.column :age do # colref 'C' # end # # i.bulk_declare {name: 'B', age: 'C'} do # process do |cell| # cell.strip # end # end # # is equivalent to: # # i.column :name do # colref 'B' # process do |cell| # cell.strip # end # end # i.column :age do # colref 'C' # process do |cell| # cell.strip # end # end def bulk_declare hash, &block
hash.keys.each do |key| column = Column.new column.colref hash[key] if block column.instance_eval(&block) end @colspec << column.to_hash.merge({name: key}) end end
avillafiorita/dreader
d2ed928ccaa1e35d34404a63cb65c17862aaf4ac
lib/dreader.rb
https://github.com/avillafiorita/dreader/blob/d2ed928ccaa1e35d34404a63cb65c17862aaf4ac/lib/dreader.rb#L215-L267
ruby
test
# read a file and store it internally # # @param hash, a hash, possibly overriding any of the parameters # set in the initial options. This allows you, for # instance, to apply the same column specification to # different files and different sheets # # @return the data read from filename, in the form of an array of # hashes
def read args = {}
# read a file and store it internally # # @param hash, a hash, possibly overriding any of the parameters # set in the initial options. This allows you, for # instance, to apply the same column specification to # different files and different sheets # # @return the data read from filename, in the form of an array of # hashes def read args = {}
if args.class == Hash hash = @options.merge(args) else puts "dreader error at #{__callee__}: this function takes a Hash as input" exit end spreadsheet = Dreader::Engine.open_spreadsheet (hash[:filename]) sheet = spreadsheet.sheet(hash[:sheet] || 0) @table = Array.new @errors = Array.new first_row = hash[:first_row] || 1 last_row = hash[:last_row] || sheet.last_row (first_row..last_row).each do |row_number| r = Hash.new @colspec.each_with_index do |colspec, index| cell = sheet.cell(row_number, colspec[:colref]) colname = colspec[:name] r[colname] = Hash.new r[colname][:row_number] = row_number r[colname][:col_number] = colspec[:colref] begin r[colname][:value] = value = colspec[:process] ? colspec[:process].call(cell) : cell rescue => e puts "dreader error at #{__callee__}: 'process' specification for :#{colname} raised an exception at row #{row_number} (col #{index + 1}, value: #{cell})" raise e end begin if colspec[:check] and not colspec[:check].call(value) then r[colname][:error] = true @errors << "dreader error at #{__callee__}: value \"#{cell}\" for #{colname} at row #{row_number} (col #{index + 1}) does not pass the check function" else r[colname][:error] = false end rescue => e puts "dreader error at #{__callee__}: 'check' specification for :#{colname} raised an exception at row #{row_number} (col #{index + 1}, value: #{cell})" raise e end end @table << r end @table end
avillafiorita/dreader
d2ed928ccaa1e35d34404a63cb65c17862aaf4ac
lib/dreader.rb
https://github.com/avillafiorita/dreader/blob/d2ed928ccaa1e35d34404a63cb65c17862aaf4ac/lib/dreader.rb#L292-L358
ruby
test
# show to stdout the first `n` records we read from the file given the current # configuration
def debug args = {}
# show to stdout the first `n` records we read from the file given the current # configuration def debug args = {}
if args.class == Hash hash = @options.merge(args) else puts "dreader error at #{__callee__}: this function takes a Hash as input" exit end # apply some defaults, if not defined in the options hash[:process] = true if not hash.has_key? :process # shall we apply the process function? hash[:check] = true if not hash.has_key? :check # shall we check the data read? hash[:n] = 10 if not hash[:n] spreadsheet = Dreader::Engine.open_spreadsheet (hash[:filename]) sheet = spreadsheet.sheet(hash[:sheet] || 0) puts "Current configuration:" @options.each do |k, v| puts " #{k}: #{v}" end puts "Configuration used by debug:" hash.each do |k, v| puts " #{k}: #{v}" end n = hash[:n] first_row = hash[:first_row] || 1 last_row = first_row + n - 1 puts " Last row (according to roo): #{sheet.last_row}" puts " Number of rows I will read in this session: #{n} (from #{first_row} to #{last_row})" (first_row..last_row).each do |row_number| puts "Row #{row_number} is:" r = Hash.new @colspec.each_with_index do |colspec, index| colname = colspec[:name] cell = sheet.cell(row_number, colspec[:colref]) processed_str = "" checked_str = "" if hash[:process] begin processed = colspec[:process] ? colspec[:process].call(cell) : cell processed_str = "processed: '#{processed}' (#{processed.class})" rescue => e puts "dreader error at #{__callee__}: 'check' specification for :#{colname} raised an exception at row #{row_number} (col #{index + 1}, value: #{cell})" raise e end end if hash[:check] begin processed = colspec[:process] ? colspec[:process].call(cell) : cell check = colspec[:check] ? colspec[:check].call(processed) : "no check specified" checked_str = "checked: '#{check}'" rescue => e puts "dreader error at #{__callee__}: 'check' specification for #{colname} at row #{row_number} raised an exception (col #{index + 1}, value: #{cell})" raise e end end puts " #{colname} => orig: '#{cell}' (#{cell.class}) #{processed_str} #{checked_str} (column: '#{colspec[:colref]}')" end end end
jiaola/omelette
4faa44c21350fa2ae7415c66cdf11c541564a975
lib/omelette/util.rb
https://github.com/jiaola/omelette/blob/4faa44c21350fa2ae7415c66cdf11c541564a975/lib/omelette/util.rb#L39-L73
ruby
test
# Provide a config source file path, and an exception. # # Returns the line number from the first line in the stack # trace of the exception that matches your file path. # of the first line in the backtrace matching that file_path. # # Returns `nil` if no suitable backtrace line can be found. # # Has special logic to try and grep the info out of a SyntaxError, bah.
def backtrace_lineno_for_config(file_path, exception) # For a SyntaxError, we really need to grep it from the # exception message, it really appears to be nowhere else. Ugh.
# Provide a config source file path, and an exception. # # Returns the line number from the first line in the stack # trace of the exception that matches your file path. # of the first line in the backtrace matching that file_path. # # Returns `nil` if no suitable backtrace line can be found. # # Has special logic to try and grep the info out of a SyntaxError, bah. def backtrace_lineno_for_config(file_path, exception) # For a SyntaxError, we really need to grep it from the # exception message, it really appears to be nowhere else. Ugh.
if exception.kind_of? SyntaxError if m = /:(\d+):/.match(exception.message) return m[1].to_i end end # Otherwise we try to fish it out of the backtrace, first # line matching the config file path. # exception.backtrace_locations exists in MRI 2.1+, which makes # our task a lot easier. But not yet in JRuby 1.7.x, so we got to # handle the old way of having to parse the strings in backtrace too. if (exception.respond_to?(:backtrace_locations) && exception.backtrace_locations && exception.backtrace_locations.length > 0) location = exception.backtrace_locations.find do |bt| bt.path == file_path end return location ? location.lineno : nil else # have to parse string backtrace exception.backtrace.each do |line| if line.start_with?(file_path) if m = /\A.*\:(\d+)\:in/.match(line) return m[1].to_i break end end end # if we got here, we have nothing return nil end end
jiaola/omelette
4faa44c21350fa2ae7415c66cdf11c541564a975
lib/omelette/util.rb
https://github.com/jiaola/omelette/blob/4faa44c21350fa2ae7415c66cdf11c541564a975/lib/omelette/util.rb#L82-L106
ruby
test
# Extract just the part of the backtrace that is "below" # the config file mentioned. If we can't find the config file # in the stack trace, we might return empty array. # # If the ruby supports Exception#backtrace_locations, the # returned array will actually be of Thread::Backtrace::Location elements.
def backtrace_from_config(file_path, exception)
# Extract just the part of the backtrace that is "below" # the config file mentioned. If we can't find the config file # in the stack trace, we might return empty array. # # If the ruby supports Exception#backtrace_locations, the # returned array will actually be of Thread::Backtrace::Location elements. def backtrace_from_config(file_path, exception)
filtered_trace = [] found = false # MRI 2.1+ has exception.backtrace_locations which makes # this a lot easier, but JRuby 1.7.x doesn't yet, so we # need to do it both ways. if (exception.respond_to?(:backtrace_locations) && exception.backtrace_locations && exception.backtrace_locations.length > 0) exception.backtrace_locations.each do |location| filtered_trace << location (found=true and break) if location.path == file_path end else filtered_trace = [] exception.backtrace.each do |line| filtered_trace << line (found=true and break) if line.start_with?(file_path) end end return found ? filtered_trace : [] end
jiaola/omelette
4faa44c21350fa2ae7415c66cdf11c541564a975
lib/omelette/util.rb
https://github.com/jiaola/omelette/blob/4faa44c21350fa2ae7415c66cdf11c541564a975/lib/omelette/util.rb#L114-L127
ruby
test
# Ruby stdlib queue lacks a 'drain' function, we write one. # # Removes everything currently in the ruby stdlib queue, and returns # it an array. Should be concurrent-safe, but queue may still have # some things in it after drain, if there are concurrent writers.
def drain_queue(queue)
# Ruby stdlib queue lacks a 'drain' function, we write one. # # Removes everything currently in the ruby stdlib queue, and returns # it an array. Should be concurrent-safe, but queue may still have # some things in it after drain, if there are concurrent writers. def drain_queue(queue)
result = [] queue_size = queue.size begin queue_size.times do result << queue.deq(:raise_if_empty) end rescue ThreadError # Need do nothing, queue was concurrently popped, no biggie end return result end
ebsaral/sentence-builder
4f3691323dbbcf370f7b2530ae0967f4ec16a3e9
lib/sentence_builder/builder.rb
https://github.com/ebsaral/sentence-builder/blob/4f3691323dbbcf370f7b2530ae0967f4ec16a3e9/lib/sentence_builder/builder.rb#L13-L15
ruby
test
# Return all nodes in order as an hashalways_use
def get_hash(params = {}, sorted = true)
# Return all nodes in order as an hashalways_use def get_hash(params = {}, sorted = true)
get_nodes(sorted).map{|n| n.to_hash(params[n.name])} end
ebsaral/sentence-builder
4f3691323dbbcf370f7b2530ae0967f4ec16a3e9
lib/sentence_builder/builder.rb
https://github.com/ebsaral/sentence-builder/blob/4f3691323dbbcf370f7b2530ae0967f4ec16a3e9/lib/sentence_builder/builder.rb#L18-L20
ruby
test
# Returns the string representation of nodes and blocks by updating with given parameters
def get_sentence(params = {}, sorted = true, separator = ' ')
# Returns the string representation of nodes and blocks by updating with given parameters def get_sentence(params = {}, sorted = true, separator = ' ')
build_sentence_from_hash(get_hash(params, sorted)).select(&:present?).join(separator) end
ebsaral/sentence-builder
4f3691323dbbcf370f7b2530ae0967f4ec16a3e9
lib/sentence_builder/builder.rb
https://github.com/ebsaral/sentence-builder/blob/4f3691323dbbcf370f7b2530ae0967f4ec16a3e9/lib/sentence_builder/builder.rb#L24-L26
ruby
test
# Return nodes by sorting option
def get_nodes(sorted = true)
# Return nodes by sorting option def get_nodes(sorted = true)
SentenceBuilder::Helper.to_boolean(sorted) ? @nodes.sort_by{|i| i.sort_by_value} : @nodes end
ebsaral/sentence-builder
4f3691323dbbcf370f7b2530ae0967f4ec16a3e9
lib/sentence_builder/builder.rb
https://github.com/ebsaral/sentence-builder/blob/4f3691323dbbcf370f7b2530ae0967f4ec16a3e9/lib/sentence_builder/builder.rb#L29-L42
ruby
test
# By parsing each node's hash, create a sentence
def build_sentence_from_hash(nodes)
# By parsing each node's hash, create a sentence def build_sentence_from_hash(nodes)
result = [] nodes.each do |node| # This node does not appear in params if node[:current_value].nil? if node[:always_use] result << node[:sentence] end else result << node[:sentence] end end result end
Dahie/caramelize
6bb93b65924edaaf071a8b3947d0545d5759bc5d
lib/caramelize/wiki/wikkawiki.rb
https://github.com/Dahie/caramelize/blob/6bb93b65924edaaf071a8b3947d0545d5759bc5d/lib/caramelize/wiki/wikkawiki.rb#L16-L37
ruby
test
# after calling this action, I expect the titles and @revisions to be filled
def read_pages
# after calling this action, I expect the titles and @revisions to be filled def read_pages
sql = "SELECT id, tag, body, time, latest, user, note FROM wikka_pages ORDER BY time;" results = database.query(sql) results.each do |row| titles << row["tag"] author = authors[row["user"]] page = Page.new({:id => row["id"], :title => row["tag"], :body => row["body"], :markup => :wikka, :latest => row["latest"] == "Y", :time => row["time"], :message => row["note"], :author => author, :author_name => row["user"]}) revisions << page end titles.uniq! #revisions.sort! { |a,b| a.time <=> b.time } revisions end
ImmaculatePine/filterable
7a3109314d431aed2fa8d11f510b8a0f260fa612
lib/filterable.rb
https://github.com/ImmaculatePine/filterable/blob/7a3109314d431aed2fa8d11f510b8a0f260fa612/lib/filterable.rb#L13-L19
ruby
test
# Iterates over params hash and # applies non-empty values as filters # @param params [Hash] filters list # @return [ActiveRecord::Relation] filtered list
def filter(params)
# Iterates over params hash and # applies non-empty values as filters # @param params [Hash] filters list # @return [ActiveRecord::Relation] filtered list def filter(params)
results = where(nil) params.each do |key, value| results = results.public_send(key, value) if value.present? end results end
Dahie/caramelize
6bb93b65924edaaf071a8b3947d0545d5759bc5d
lib/caramelize/filters/swap_wiki_links.rb
https://github.com/Dahie/caramelize/blob/6bb93b65924edaaf071a8b3947d0545d5759bc5d/lib/caramelize/filters/swap_wiki_links.rb#L5-L20
ruby
test
# take an input stream and convert all wikka syntax to markdown syntax
def run body
# take an input stream and convert all wikka syntax to markdown syntax def run body
migrated_body = body.dup migrated_body.gsub!(/\[\[(\S+)\|(.+?)\]\]/, '[[\2|\1]]') migrated_body.gsub!(/\[\[([\w\s\.]*)\]\]/) do |s| if $1 s = $1 t = $1.dup t.gsub!(' ', '_') t.gsub!(/\./, '') s = "[[#{s}|#{t}]]" end end migrated_body end
Montage-Inc/trimark-ruby
edecd8a574c36e327f2231a9a499598ac6cec4ad
lib/trimark/client.rb
https://github.com/Montage-Inc/trimark-ruby/blob/edecd8a574c36e327f2231a9a499598ac6cec4ad/lib/trimark/client.rb#L78-L85
ruby
test
# Gets a list of all the sites for the company
def sites
# Gets a list of all the sites for the company def sites
response = conn.get("#{base_url}/site", {}, query_headers) body = JSON.parse(response.body) body.map { |b| Site.new(b) } rescue JSON::ParserError fail QueryError, "Query Failed! HTTPStatus: #{response.status} - Response: #{body}" end
Montage-Inc/trimark-ruby
edecd8a574c36e327f2231a9a499598ac6cec4ad
lib/trimark/client.rb
https://github.com/Montage-Inc/trimark-ruby/blob/edecd8a574c36e327f2231a9a499598ac6cec4ad/lib/trimark/client.rb#L90-L98
ruby
test
# Returns site attributes and history data if an optional query_hash is supplied # @client.site_query(x) will return the attributes of site x # @client.site_query(x, query_hash) will return historical data from site x instrumentation
def site_query(*args)
# Returns site attributes and history data if an optional query_hash is supplied # @client.site_query(x) will return the attributes of site x # @client.site_query(x, query_hash) will return historical data from site x instrumentation def site_query(*args)
response = conn.get(url_picker(*args), {}, query_headers) if response.body['SiteId'] || response.body['PointId'] JSON.parse(response.body) else fail QueryError, "Query Failed! HTTPStatus: #{response.status}" end end
arvicco/my_scripts
e75ba2ec22adf15a8d6e224ca4bf2fdae044a754
lib/my_scripts/scripts/wake.rb
https://github.com/arvicco/my_scripts/blob/e75ba2ec22adf15a8d6e224ca4bf2fdae044a754/lib/my_scripts/scripts/wake.rb#L19-L30
ruby
test
# seconds
def move_mouse_randomly
# seconds def move_mouse_randomly
x, y = get_cursor_pos # For some reason, x or y returns as nil sometimes if x && y x1, y1 = x + rand(3) - 1, y + rand(3) - 1 mouse_event(MOUSEEVENTF_ABSOLUTE, x1, y1, 0, 0) puts "Cursor positon set to #{x1}, #{y1}" else puts "X: #{x}, Y: #{y}, last error: #{Win::Error::get_last_error}" end end
lbadura/currency_spy
be0689715649ff952d3d797a4b3f087793580924
lib/currency_spy/scrapers/walutomat.rb
https://github.com/lbadura/currency_spy/blob/be0689715649ff952d3d797a4b3f087793580924/lib/currency_spy/scrapers/walutomat.rb#L18-L25
ruby
test
# Constructor method. # Initializes the following: # * a url of the source # * and the name of the source # * a list of currency codes available # Fetch medium rate which is calculated based on current transactions in Walutomat
def medium_rate
# Constructor method. # Initializes the following: # * a url of the source # * and the name of the source # * a list of currency codes available # Fetch medium rate which is calculated based on current transactions in Walutomat def medium_rate
regexp = Regexp.new("#{currency_code} / PLN") page.search("//span[@name='pair']").each do |td| if (regexp.match(td.content)) return td.next_element.content.to_f end end end
lbadura/currency_spy
be0689715649ff952d3d797a4b3f087793580924
lib/currency_spy/scrapers/walutomat.rb
https://github.com/lbadura/currency_spy/blob/be0689715649ff952d3d797a4b3f087793580924/lib/currency_spy/scrapers/walutomat.rb#L28-L36
ruby
test
# The hour of the rate
def rate_time
# The hour of the rate def rate_time
regexp = Regexp.new(currency_code) page.search("//span[@name='pair']").each do |td| if regexp.match(td.content) hour = td.next_element.next_element.content return DateTime.parse(hour) end end end
jpace/logue
0d2bd5978aa32b2bb49dd72355527cca4fadeaef
lib/logue/logger.rb
https://github.com/jpace/logue/blob/0d2bd5978aa32b2bb49dd72355527cca4fadeaef/lib/logue/logger.rb#L77-L80
ruby
test
# Assigns output to a file with the given name. Returns the file; the client is responsible for # closing it.
def outfile= f
# Assigns output to a file with the given name. Returns the file; the client is responsible for # closing it. def outfile= f
io = f.kind_of?(IO) ? f : File.new(f, "w") @writer.output = io end
jpace/logue
0d2bd5978aa32b2bb49dd72355527cca4fadeaef
lib/logue/logger.rb
https://github.com/jpace/logue/blob/0d2bd5978aa32b2bb49dd72355527cca4fadeaef/lib/logue/logger.rb#L84-L86
ruby
test
# Creates a printf format for the given widths, for aligning output. To lead lines with zeros # (e.g., "00317") the line argument must be a string, with leading zeros, not an integer.
def set_widths file, line, method
# Creates a printf format for the given widths, for aligning output. To lead lines with zeros # (e.g., "00317") the line argument must be a string, with leading zeros, not an integer. def set_widths file, line, method
@format = LocationFormat.new file: file, line: line, method: method end
jpace/logue
0d2bd5978aa32b2bb49dd72355527cca4fadeaef
lib/logue/logger.rb
https://github.com/jpace/logue/blob/0d2bd5978aa32b2bb49dd72355527cca4fadeaef/lib/logue/logger.rb#L109-L111
ruby
test
# Logs the given message.
def log msg = "", obj = nil, level: Level::DEBUG, classname: nil, &blk
# Logs the given message. def log msg = "", obj = nil, level: Level::DEBUG, classname: nil, &blk
log_frames msg, obj, classname: classname, level: level, nframes: 0, &blk end
Dervol03/watir-formhandler
5bde899fd4e1f6d4293f8797bdeb32499507f798
lib/watir-formhandler/option_group.rb
https://github.com/Dervol03/watir-formhandler/blob/5bde899fd4e1f6d4293f8797bdeb32499507f798/lib/watir-formhandler/option_group.rb#L34-L43
ruby
test
# Returns all available options fields and their respective label as a Hash. # @return [Hash<label => field>] hash with all labels and fields.
def options
# Returns all available options fields and their respective label as a Hash. # @return [Hash<label => field>] hash with all labels and fields. def options
option_hash = {} my_labels = option_names my_inputs = option_fields my_labels.count.times do |index| option_hash[my_labels[index]] = my_inputs[index] end option_hash end
Dervol03/watir-formhandler
5bde899fd4e1f6d4293f8797bdeb32499507f798
lib/watir-formhandler/option_group.rb
https://github.com/Dervol03/watir-formhandler/blob/5bde899fd4e1f6d4293f8797bdeb32499507f798/lib/watir-formhandler/option_group.rb#L55-L63
ruby
test
# Selects the given option(s) and deselects all other ones. This can not be done with # radio buttons, however, as they cannot be deselected. # @param [String, Array<String>] wanted_options to be selected. # @example Passing a single String # group.set('Checkbox1') #=> selects 'Checkbox1' # @example Passing several options # group.set('Checkbox1', 'Checkbox2') #=> selects 'Checkbox1' and 'Checkbox2' # @example Passing several options as Array # group.set(['Checkbox1', 'Radio1']) #=> selects 'Checkbox1' and 'Radio1'
def set(*wanted_options)
# Selects the given option(s) and deselects all other ones. This can not be done with # radio buttons, however, as they cannot be deselected. # @param [String, Array<String>] wanted_options to be selected. # @example Passing a single String # group.set('Checkbox1') #=> selects 'Checkbox1' # @example Passing several options # group.set('Checkbox1', 'Checkbox2') #=> selects 'Checkbox1' and 'Checkbox2' # @example Passing several options as Array # group.set(['Checkbox1', 'Radio1']) #=> selects 'Checkbox1' and 'Radio1' def set(*wanted_options)
options_to_select = [*wanted_options].flatten options_to_deselect = option_names - options_to_select @options = options select(options_to_select, true) select(options_to_deselect, false) @options = nil end
Dervol03/watir-formhandler
5bde899fd4e1f6d4293f8797bdeb32499507f798
lib/watir-formhandler/option_group.rb
https://github.com/Dervol03/watir-formhandler/blob/5bde899fd4e1f6d4293f8797bdeb32499507f798/lib/watir-formhandler/option_group.rb#L68-L75
ruby
test
# Returns the selected options of this OptionGroup. # @return [Array<String>] the selected options.
def selected_options
# Returns the selected options of this OptionGroup. # @return [Array<String>] the selected options. def selected_options
selected = [] my_labels = option_names inputs.each_with_index do |field, index| selected << my_labels[index] if field.checked? end selected end
bys-control/action_cable_notifications
dc455e690ce87d4864a0833c89b77438da48da65
lib/action_cable_notifications/channel.rb
https://github.com/bys-control/action_cable_notifications/blob/dc455e690ce87d4864a0833c89b77438da48da65/lib/action_cable_notifications/channel.rb#L25-L66
ruby
test
# Public methods # # # Process actions sent from the client # # @param [Hash] data Contains command to be executed and its parameters # { # "publication": "model.model_name.name" # "command": "fetch" # "params": {} # }
def action(data)
# Public methods # # # Process actions sent from the client # # @param [Hash] data Contains command to be executed and its parameters # { # "publication": "model.model_name.name" # "command": "fetch" # "params": {} # } def action(data)
data.deep_symbolize_keys! publication = data[:publication] channel_options = @ChannelPublications[publication] if channel_options model = channel_options[:model] model_options = model.ChannelPublications[publication] params = data[:params] command = data[:command] action_params = { publication: publication, model: model, model_options: model_options, options: channel_options, params: params, command: command } case command when "fetch" fetch(action_params) when "create" create(action_params) when "update" update(action_params) when "destroy" destroy(action_params) end else response = { publication: publication, msg: 'error', command: command, error: "Stream for publication '#{publication}' does not exist in channel '#{self.channel_name}'." } # Send error notification to the client transmit response end end
bys-control/action_cable_notifications
dc455e690ce87d4864a0833c89b77438da48da65
lib/action_cable_notifications/channel.rb
https://github.com/bys-control/action_cable_notifications/blob/dc455e690ce87d4864a0833c89b77438da48da65/lib/action_cable_notifications/channel.rb#L98-L138
ruby
test
# Streams notification for ActiveRecord model changes # # @param [ActiveRecord::Base] model Model to watch for changes # @param [Hash] options Streaming options
def stream_notifications_for(model, options = {}) # Default publication options
# Streams notification for ActiveRecord model changes # # @param [ActiveRecord::Base] model Model to watch for changes # @param [Hash] options Streaming options def stream_notifications_for(model, options = {}) # Default publication options
options = { publication: model.model_name.name, cache: false, model_options: {}, scope: :all }.merge(options).merge(params.deep_symbolize_keys) # These options cannot be overridden options[:model] = model publication = options[:publication] # Checks if the publication already exists in the channel if not @ChannelPublications.include?(publication) # Sets channel options @ChannelPublications[publication] = options # Checks if model already includes notification callbacks if !model.respond_to? :ChannelPublications model.send('include', ActionCableNotifications::Model) end # Sets broadcast options if they are not already present in the model if not model.ChannelPublications.key? publication model.broadcast_notifications_from publication, options[:model_options] else # Reads options configuracion from model options[:model_options] = model.ChannelPublications[publication] end # Start streaming stream_from publication, coder: ActiveSupport::JSON do |packet| packet.merge!({publication: publication}) transmit_packet(packet, options) end # XXX: Transmit initial data end end
bys-control/action_cable_notifications
dc455e690ce87d4864a0833c89b77438da48da65
lib/action_cable_notifications/channel.rb
https://github.com/bys-control/action_cable_notifications/blob/dc455e690ce87d4864a0833c89b77438da48da65/lib/action_cable_notifications/channel.rb#L145-L162
ruby
test
# Transmits packets to connected client # # @param [Hash] packet Packet with changes notifications
def transmit_packet(packet, options={}) # Default options
# Transmits packets to connected client # # @param [Hash] packet Packet with changes notifications def transmit_packet(packet, options={}) # Default options
options = { cache: false }.merge(options) packet = packet.as_json.deep_symbolize_keys if validate_packet(packet, options) if options[:cache]==true if update_cache(packet) transmit packet end else transmit packet end end end
krakatoa/bliss
7703d2283e53a0d739b23be4eb4e74f3d18514d3
lib/bliss/constraint.rb
https://github.com/krakatoa/bliss/blob/7703d2283e53a0d739b23be4eb4e74f3d18514d3/lib/bliss/constraint.rb#L19-L77
ruby
test
# TODO should exist another method passed! for tag_name_required ?
def run!(hash=nil)
# TODO should exist another method passed! for tag_name_required ? def run!(hash=nil)
@state = :not_checked #@field.each do |field| #if @state == :passed # break #end case @setting when :tag_name_required, :tag_name_suggested content = nil if hash #puts "#{@depth.inspect} - required: #{required.inspect}" found = false self.tag_names.each do |key| if hash.keys.include?(key) found = true break end end if found @state = :passed else if @setting == :tag_name_required #puts "hash: #{hash.inspect}" #puts "self.tag_names: #{self.tag_names.inspect}" @state = :not_passed end end else @state = :passed end when :content_values if hash found = false self.tag_names.each do |key| content = hash[key] #puts content #puts @possible_values.inspect if @possible_values.include?(content) found = true break end end if found @state = :passed else @state = :not_passed end end #when :not_blank # if hash.has_key?(field) and !hash[field].to_s.empty? # @state = :passed # else # @state = :not_passed # end end #end @state end
dldinternet/knife-chop
eafba88b04356d70186971527aca246580da2b2e
lib/ruby-beautify/lib/ruby-beautify/block_start.rb
https://github.com/dldinternet/knife-chop/blob/eafba88b04356d70186971527aca246580da2b2e/lib/ruby-beautify/lib/ruby-beautify/block_start.rb#L70-L72
ruby
test
# Returns true if strict ancestor of
def strict_ancestor_of?(block_start)
# Returns true if strict ancestor of def strict_ancestor_of?(block_start)
block_start && block_start.parent && (self == block_start.parent || strict_ancestor_of?(block_start.parent)) end
jronallo/mead
119e25d762d228a17612afe327ac13227aa9825b
lib/mead/extractor.rb
https://github.com/jronallo/mead/blob/119e25d762d228a17612afe327ac13227aa9825b/lib/mead/extractor.rb#L97-L108
ruby
test
# FIXME: This currently depends on series being numbered sequentially and being # arranged in that order in the EAD XML.
def get_series
# FIXME: This currently depends on series being numbered sequentially and being # arranged in that order in the EAD XML. def get_series
c01_series = @dsc.xpath(".//xmlns:c01[@level='series']") if c01_series and !c01_series.empty? c01_series.each_with_index do |c01, i| if mead.series.to_i == i + 1 @series = c01 end end else @series = @dsc end end
wwidea/built_in_data
e05d4dbf4eda2647f5d359ae91f2c381c7de1f87
lib/built_in_data.rb
https://github.com/wwidea/built_in_data/blob/e05d4dbf4eda2647f5d359ae91f2c381c7de1f87/lib/built_in_data.rb#L60-L64
ruby
test
# memoized hash of built in object ids
def built_in_object_ids
# memoized hash of built in object ids def built_in_object_ids
@built_in_object_ids ||= Hash.new do |hash, key| hash[key] = where(built_in_key: key).pluck(:id).first end end
lbadura/currency_spy
be0689715649ff952d3d797a4b3f087793580924
lib/currency_spy/scrapers/nbp.rb
https://github.com/lbadura/currency_spy/blob/be0689715649ff952d3d797a4b3f087793580924/lib/currency_spy/scrapers/nbp.rb#L42-L51
ruby
test
# Get the time for this rate (based on the information on the website)
def rate_time
# Get the time for this rate (based on the information on the website) def rate_time
regexp = Regexp.new(/\d\d\d\d-\d\d-\d\d/) page.search('//p[@class="nag"]').each do |p| p.search('b').each do |b| if regexp.match(b.content) return DateTime.strptime(b.content, "%Y-%m-%d") end end end end
itrp/clacks
54714facb9cc5290246fe562c107b058a683f91d
lib/clacks/command.rb
https://github.com/itrp/clacks/blob/54714facb9cc5290246fe562c107b058a683f91d/lib/clacks/command.rb#L97-L125
ruby
test
# See Stevens's "Advanced Programming in the UNIX Environment" chapter 13
def daemonize(safe = true)
# See Stevens's "Advanced Programming in the UNIX Environment" chapter 13 def daemonize(safe = true)
$stdin.reopen '/dev/null' # Fork and have the parent exit. # This makes the shell or boot script think the command is done. # Also, the child process is guaranteed not to be a process group # leader (a prerequisite for setsid next) exit if fork # Call setsid to create a new session. This does three things: # - The process becomes a session leader of a new session # - The process becomes the process group leader of a new process group # - The process has no controlling terminal Process.setsid # Fork again and have the parent exit. # This guarantes that the daemon is not a session leader nor can # it acquire a controlling terminal (under SVR4) exit if fork unless safe ::Dir.chdir('/') ::File.umask(0000) end cfg_defaults = Clacks::Configurator::DEFAULTS cfg_defaults[:stdout_path] ||= "/dev/null" cfg_defaults[:stderr_path] ||= "/dev/null" end
itrp/clacks
54714facb9cc5290246fe562c107b058a683f91d
lib/clacks/command.rb
https://github.com/itrp/clacks/blob/54714facb9cc5290246fe562c107b058a683f91d/lib/clacks/command.rb#L128-L131
ruby
test
# Redirect file descriptors inherited from the parent.
def reopen_io(io, path)
# Redirect file descriptors inherited from the parent. def reopen_io(io, path)
io.reopen(::File.open(path, "ab")) if path io.sync = true end
itrp/clacks
54714facb9cc5290246fe562c107b058a683f91d
lib/clacks/command.rb
https://github.com/itrp/clacks/blob/54714facb9cc5290246fe562c107b058a683f91d/lib/clacks/command.rb#L134-L141
ruby
test
# Read the working pid from the pid file.
def running?(path)
# Read the working pid from the pid file. def running?(path)
wpid = ::File.read(path).to_i return if wpid <= 0 Process.kill(0, wpid) wpid rescue Errno::EPERM, Errno::ESRCH, Errno::ENOENT # noop end
itrp/clacks
54714facb9cc5290246fe562c107b058a683f91d
lib/clacks/command.rb
https://github.com/itrp/clacks/blob/54714facb9cc5290246fe562c107b058a683f91d/lib/clacks/command.rb#L144-L147
ruby
test
# Write the pid.
def write_pid(pid)
# Write the pid. def write_pid(pid)
::File.open(pid, 'w') { |f| f.write("#{Process.pid}") } at_exit { ::File.delete(pid) if ::File.exist?(pid) rescue nil } end
Dahie/caramelize
6bb93b65924edaaf071a8b3947d0545d5759bc5d
lib/caramelize/filters/wikka_to_markdown.rb
https://github.com/Dahie/caramelize/blob/6bb93b65924edaaf071a8b3947d0545d5759bc5d/lib/caramelize/filters/wikka_to_markdown.rb#L5-L37
ruby
test
# take an input stream and convert all wikka syntax to markdown syntax
def run body
# take an input stream and convert all wikka syntax to markdown syntax def run body
body = body.dup body.gsub!(/(======)(.*?)(======)/ ) {|s| '# ' + $2 } #h1 body.gsub!(/(=====)(.*?)(=====)/) {|s| '## ' + $2 } #h2 body.gsub!(/(====)(.*?)(====)/) {|s| '### ' + $2 } #h3 body.gsub!(/(===)(.*?)(===)/) {|s| '#### ' + $2 } #h4 body.gsub!(/(\*\*)(.*?)(\*\*)/) {|s| '**' + $2 + '**' } #bold body.gsub!(/(\/\/)(.*?)(\/\/)/) {|s| '_' + $2 + '_' } #italic #str.gsub!(/(===)(.*?)(===)/) {|s| '`' + $2 + '`'} #code body.gsub!(/(__)(.*?)(__)/) {|s| '<u>' + $2 + '</u>'} #underline body.gsub!(/(---)/, ' ') #forced linebreak #body.gsub!(/(.*?)(\n\t-)(.*?)/) {|s| $1 + $3 } #list body.gsub!(/(\t-)(.*)/, '*\2') # unordered list body.gsub!(/(~-)(.*)/, '*\2') # unordered list body.gsub!(/( -)(.*)/, '*\2') # unordered list # TODO ordered lists # TODO images: ({{image)(url\=?)?(.*)(}}) #str.gsub!(/(----)/) {|s| '~~~~'} #seperator body.gsub!(/(\[\[)(\w+)\s(.+?)(\]\])/, '[[\3|\2]]') #body.gsub!(/\[\[(\w+)\s(.+)\]\]/, ' [[\1 | \2]] ') # TODO more syntax conversion for links and images body end
sorentwo/dewey
91f505cc2492e0378c7cad4ca48fe744ab078eb7
lib/dewey/utils.rb
https://github.com/sorentwo/dewey/blob/91f505cc2492e0378c7cad4ca48fe744ab078eb7/lib/dewey/utils.rb#L4-L13
ruby
test
# :nodoc: # Perform string escaping for Atom slugs
def slug(string)
# :nodoc: # Perform string escaping for Atom slugs def slug(string)
string.chars.to_a.map do |char| decimal = char.unpack('U').join('').to_i if decimal < 32 || decimal > 126 || decimal == 37 char = "%#{char.unpack('H2').join('%').upcase}" end char end.join('') end
jronallo/mead
119e25d762d228a17612afe327ac13227aa9825b
lib/mead/identifier.rb
https://github.com/jronallo/mead/blob/119e25d762d228a17612afe327ac13227aa9825b/lib/mead/identifier.rb#L27-L32
ruby
test
# If a location is given then extraction can take place
def parse_mead(*args)
# If a location is given then extraction can take place def parse_mead(*args)
parts = @mead.split('-') args.each_with_index do |field, i| instance_variable_set('@' + field, parts[i]) end end
jochenseeber/mixml
0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214
lib/mixml/tool.rb
https://github.com/jochenseeber/mixml/blob/0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214/lib/mixml/tool.rb#L43-L54
ruby
test
# Intialize a new mixml tool # Load XML files # # @param file_names [Array] Names of the XML files to load # @return [void]
def load(*file_names)
# Intialize a new mixml tool # Load XML files # # @param file_names [Array] Names of the XML files to load # @return [void] def load(*file_names)
file_names.flatten.each do |file_name| xml = File.open(file_name, 'r') do |file| Nokogiri::XML(file) do |config| if @pretty then config.default_xml.noblanks end end end @documents << Document.new(file_name, xml) end end
jochenseeber/mixml
0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214
lib/mixml/tool.rb
https://github.com/jochenseeber/mixml/blob/0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214/lib/mixml/tool.rb#L77-L83
ruby
test
# Save all loaded XML files # # Pretty prints the XML if {#pretty} is enabled. # # @return [void]
def save_all
# Save all loaded XML files # # Pretty prints the XML if {#pretty} is enabled. # # @return [void] def save_all
output_all do |document, options| File.open(document.name, 'w') do |file| document.xml.write_xml_to(file, options) end end end
jochenseeber/mixml
0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214
lib/mixml/tool.rb
https://github.com/jochenseeber/mixml/blob/0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214/lib/mixml/tool.rb#L91-L100
ruby
test
# Print all loaded XML files # # Pretty prints the XML if {#pretty} is enabled. If more than one file is loaded, a header with the file's name # is printed before each file. # # @return [void]
def print_all
# Print all loaded XML files # # Pretty prints the XML if {#pretty} is enabled. If more than one file is loaded, a header with the file's name # is printed before each file. # # @return [void] def print_all
output_all do |document, options| if @documents.size > 1 then puts '-' * document.name.length puts document.name puts '-' * document.name.length end puts document.xml.to_xml(options) end end
jochenseeber/mixml
0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214
lib/mixml/tool.rb
https://github.com/jochenseeber/mixml/blob/0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214/lib/mixml/tool.rb#L139-L152
ruby
test
# Perform work on a list of XML files # # Perform the following steps: # #. Remove all loaded XML files without saving them # #. Load the supplied XML files # #. Execute the supplied block # #. Flush all XML files # # @param file_names [Array] Names of the XML files to load # @yield Block to execute with loaded XML files # @return [void]
def work(*file_names, &block)
# Perform work on a list of XML files # # Perform the following steps: # #. Remove all loaded XML files without saving them # #. Load the supplied XML files # #. Execute the supplied block # #. Flush all XML files # # @param file_names [Array] Names of the XML files to load # @yield Block to execute with loaded XML files # @return [void] def work(*file_names, &block)
remove_all file_names.each do |file_name| load(file_name) if not block.nil? then execute(&block) end flush remove_all end end
jochenseeber/mixml
0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214
lib/mixml/tool.rb
https://github.com/jochenseeber/mixml/blob/0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214/lib/mixml/tool.rb#L170-L182
ruby
test
# Select nodes using an XPath expression and execute DSL commands for these nodes # # @param paths [Array<String>] XPath expression # @yield Block to execute for each nodeset # @return [void]
def xpath(*paths, &block)
# Select nodes using an XPath expression and execute DSL commands for these nodes # # @param paths [Array<String>] XPath expression # @yield Block to execute for each nodeset # @return [void] def xpath(*paths, &block)
nodesets = [] process do |xml| nodesets << xml.xpath(*paths) end selection = Selection.new(nodesets) if block_given? then Docile.dsl_eval(selection, &block) end selection end
jochenseeber/mixml
0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214
lib/mixml/tool.rb
https://github.com/jochenseeber/mixml/blob/0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214/lib/mixml/tool.rb#L189-L201
ruby
test
# Select nodes using CSS selectors and execute DSL commands for these nodes # # @param selectors [Array<String>] CSS selectors # @yield Block to execute for each nodeset # @return [void]
def css(*selectors, &block)
# Select nodes using CSS selectors and execute DSL commands for these nodes # # @param selectors [Array<String>] CSS selectors # @yield Block to execute for each nodeset # @return [void] def css(*selectors, &block)
nodesets = [] process do |xml| nodesets << xml.css(*selectors) end selection = Selection.new(nodesets) if block_given? then Docile.dsl_eval(selection, &block) end selection end
jochenseeber/mixml
0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214
lib/mixml/tool.rb
https://github.com/jochenseeber/mixml/blob/0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214/lib/mixml/tool.rb#L224-L232
ruby
test
# Execute a script or a block # # @param program [String] DSL script to execute # @yield Block to execute # @return [void]
def execute(program = nil, &block)
# Execute a script or a block # # @param program [String] DSL script to execute # @yield Block to execute # @return [void] def execute(program = nil, &block)
if not program.nil? then instance_eval(program) end if not block.nil? then Docile.dsl_eval(self, &block) end end
jochenseeber/mixml
0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214
lib/mixml/tool.rb
https://github.com/jochenseeber/mixml/blob/0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214/lib/mixml/tool.rb#L239-L245
ruby
test
# Execute block for each node # # @param selection [Selection] Selected nodes # @yield Block to execute for each node # @yieldparam node [Nokogiri::XML::Node] Current node
def with_nodes(selection)
# Execute block for each node # # @param selection [Selection] Selected nodes # @yield Block to execute for each node # @yieldparam node [Nokogiri::XML::Node] Current node def with_nodes(selection)
selection.nodesets.each do |nodeset| nodeset.each do |node| yield node end end end
huerlisi/lyb_sidebar
adb67b830af669c9d2934ab879970c7dbbfc53f6
lib/lyb_sidebar/helper.rb
https://github.com/huerlisi/lyb_sidebar/blob/adb67b830af669c9d2934ab879970c7dbbfc53f6/lib/lyb_sidebar/helper.rb#L4-L9
ruby
test
# Tag support
def tag_filter(model = nil, filters = nil, scope = :tagged_with)
# Tag support def tag_filter(model = nil, filters = nil, scope = :tagged_with)
model ||= controller_name.singularize.camelize.constantize filters ||= model.top_tags render 'layouts/tag_filter', :filters => filters, :scope => scope end
mseymour/tag_formatter
242a823be38772a2f98da3c10ea6d2654b486172
lib/tag_formatter/formatter.rb
https://github.com/mseymour/tag_formatter/blob/242a823be38772a2f98da3c10ea6d2654b486172/lib/tag_formatter/formatter.rb#L60-L67
ruby
test
# Decommentifies the supplied input. # # @param [String] input The string to decommentify. # @return A string with the decommented input.
def decommentify input
# Decommentifies the supplied input. # # @param [String] input The string to decommentify. # @return A string with the decommented input. def decommentify input
output = input.dup # Remove multiline comments: output.gsub!(/(#{Regexp.quote @block_comment_start}.+?#{Regexp.quote @block_comment_end})/m, "") # Remove inline comments: output.gsub!(/(#{Regexp.quote @inline_comment_delimiter}.+$)/,"") return output.lines.map(&:strip).join($/) end
mseymour/tag_formatter
242a823be38772a2f98da3c10ea6d2654b486172
lib/tag_formatter/formatter.rb
https://github.com/mseymour/tag_formatter/blob/242a823be38772a2f98da3c10ea6d2654b486172/lib/tag_formatter/formatter.rb#L74-L79
ruby
test
# Tagifies the supplied input. # # @param [String] input The string to tagify. # @raise [StandardError] @tags must not be empty. # @return A string with the tags replaced with their values.
def tagify input
# Tagifies the supplied input. # # @param [String] input The string to tagify. # @raise [StandardError] @tags must not be empty. # @return A string with the tags replaced with their values. def tagify input
output = input.dup raise StandardError, "@tags is empty!" if @tags.empty? #improve on this @tags.each {|key,value| output.gsub!(tag_start.to_s+key.to_s+tag_end.to_s, value.to_s)} return output end
Dervol03/watir-formhandler
5bde899fd4e1f6d4293f8797bdeb32499507f798
lib/watir-formhandler/container.rb
https://github.com/Dervol03/watir-formhandler/blob/5bde899fd4e1f6d4293f8797bdeb32499507f798/lib/watir-formhandler/container.rb#L17-L28
ruby
test
# Searches for the specified label and returns the form field belonging to it, identified by the # 'for' attribute of the label. Alternatively, you may pass a Watir::Label. # @param [String, Watir::Label] label the label for which to find the form field. # @param [Watir::Element] start_node the node where to start searching for the label. # @param [Boolean] placeholder whether to handle label as Watir::Label or as placeholder # attribute for an input field. # @param [Boolean] id assumes the given label is an HTML ID and searches for it. # # @return [Watir::Element] form field of the given label. If the field is # no form field, it will be assumed to be an # OptionGroup.
def field(label, start_node: nil, placeholder: false, id: false)
# Searches for the specified label and returns the form field belonging to it, identified by the # 'for' attribute of the label. Alternatively, you may pass a Watir::Label. # @param [String, Watir::Label] label the label for which to find the form field. # @param [Watir::Element] start_node the node where to start searching for the label. # @param [Boolean] placeholder whether to handle label as Watir::Label or as placeholder # attribute for an input field. # @param [Boolean] id assumes the given label is an HTML ID and searches for it. # # @return [Watir::Element] form field of the given label. If the field is # no form field, it will be assumed to be an # OptionGroup. def field(label, start_node: nil, placeholder: false, id: false)
start_node ||= self if placeholder start_node.element(placeholder: label).to_subtype elsif id start_node.element(id: label).to_subtype else field_label = label.respond_to?(:for) ? label : start_node.label(text: label) determine_field(start_node, field_label) end end
Dervol03/watir-formhandler
5bde899fd4e1f6d4293f8797bdeb32499507f798
lib/watir-formhandler/container.rb
https://github.com/Dervol03/watir-formhandler/blob/5bde899fd4e1f6d4293f8797bdeb32499507f798/lib/watir-formhandler/container.rb#L39-L45
ruby
test
# Fills in the given value(s) to the passed attribute. It therefore accepts the same parameters # as the #field method. # @param [String, Watir::Label] label the label for which to find the form field. # @param [String, Boolean, Array] value to be set. # @param [Watir::Element] start_node the node where to start searching for the label. # @param [Boolean] placeholder whether to handle label as Watir::Label or as placeholder # attribute for an input field. # @param [Boolean] id assumes the given label is an HTML ID and searches for it.
def fill_in(label, value, start_node: nil, placeholder: false, id: false)
# Fills in the given value(s) to the passed attribute. It therefore accepts the same parameters # as the #field method. # @param [String, Watir::Label] label the label for which to find the form field. # @param [String, Boolean, Array] value to be set. # @param [Watir::Element] start_node the node where to start searching for the label. # @param [Boolean] placeholder whether to handle label as Watir::Label or as placeholder # attribute for an input field. # @param [Boolean] id assumes the given label is an HTML ID and searches for it. def fill_in(label, value, start_node: nil, placeholder: false, id: false)
field(label, start_node: start_node, placeholder: placeholder, id: id ).set(value) end
Dervol03/watir-formhandler
5bde899fd4e1f6d4293f8797bdeb32499507f798
lib/watir-formhandler/container.rb
https://github.com/Dervol03/watir-formhandler/blob/5bde899fd4e1f6d4293f8797bdeb32499507f798/lib/watir-formhandler/container.rb#L56-L62
ruby
test
# Returns the current value of the specified form field. It therefore accepts the same # parameters as the #field method. # @param [String, Watir::Label] label the label for which to find the form field. # @param [Watir::Element] start_node the node where to start searching for the label. # @param [Boolean] placeholder whether to handle label as Watir::Label or as placeholder # attribute for an input field. # @param [Boolean] id assumes the given label is an HTML ID and searches for it. # @return [String, Boolean, Array] current value of the field.
def value_of(label, start_node: nil, placeholder: false, id: false)
# Returns the current value of the specified form field. It therefore accepts the same # parameters as the #field method. # @param [String, Watir::Label] label the label for which to find the form field. # @param [Watir::Element] start_node the node where to start searching for the label. # @param [Boolean] placeholder whether to handle label as Watir::Label or as placeholder # attribute for an input field. # @param [Boolean] id assumes the given label is an HTML ID and searches for it. # @return [String, Boolean, Array] current value of the field. def value_of(label, start_node: nil, placeholder: false, id: false)
field(label, start_node: start_node, placeholder: placeholder, id: id ).field_value end
Dervol03/watir-formhandler
5bde899fd4e1f6d4293f8797bdeb32499507f798
lib/watir-formhandler/container.rb
https://github.com/Dervol03/watir-formhandler/blob/5bde899fd4e1f6d4293f8797bdeb32499507f798/lib/watir-formhandler/container.rb#L67-L74
ruby
test
# Returns an OptionGroup # @return [OptionGroup] the selected OptionGroup
def option_group(*args)
# Returns an OptionGroup # @return [OptionGroup] the selected OptionGroup def option_group(*args)
selector = if args.first.respond_to?(:elements) args.first else extract_selector(args) end OptionGroup.new(self, selector) end
chrisjones-tripletri/rake_command_filter
0c55e58f261b088d5ba67ea3bf28e6ad8b2be68f
lib/rake_command_filter.rb
https://github.com/chrisjones-tripletri/rake_command_filter/blob/0c55e58f261b088d5ba67ea3bf28e6ad8b2be68f/lib/rake_command_filter.rb#L68-L72
ruby
test
# default rake task initializer # call this to run a {CommandDefinition} subclass # @param defin an instance of a command definition subclass # @yield in the block, you can modify the internal state of the command, # using desc, add_filter, etc.
def run_definition(defin, &block)
# default rake task initializer # call this to run a {CommandDefinition} subclass # @param defin an instance of a command definition subclass # @yield in the block, you can modify the internal state of the command, # using desc, add_filter, etc. def run_definition(defin, &block)
command = defin defin.instance_eval(&block) if block add_command(command) end
Dahie/caramelize
6bb93b65924edaaf071a8b3947d0545d5759bc5d
lib/caramelize/cli/create_command.rb
https://github.com/Dahie/caramelize/blob/6bb93b65924edaaf071a8b3947d0545d5759bc5d/lib/caramelize/cli/create_command.rb#L27-L34
ruby
test
# Create a caramelize config file.
def execute(args) # create dummy config file
# Create a caramelize config file. def execute(args) # create dummy config file
target_file = @config_file.nil? ? "caramel.rb" : @config_file FileUtils.cp(File.dirname(__FILE__) +"/../caramel.rb", target_file) if commandparser.verbosity == :normal puts "Created new configuration file: #{target_file}" end end
arvicco/my_scripts
e75ba2ec22adf15a8d6e224ca4bf2fdae044a754
lib/my_scripts/cli.rb
https://github.com/arvicco/my_scripts/blob/e75ba2ec22adf15a8d6e224ca4bf2fdae044a754/lib/my_scripts/cli.rb#L27-L32
ruby
test
# Creates new command line interface # Runs a script with given name (token) and argv inside this CLI instance
def run( script_name, argv, argf=ARGF )
# Creates new command line interface # Runs a script with given name (token) and argv inside this CLI instance def run( script_name, argv, argf=ARGF )
script = script_class_name(script_name).to_class raise ScriptNameError.new("Script #{script_class_name(script_name)} not found") unless script script.new(script_name, self, argv, argf).run end
OSC/osc_machete_rails
103bb9b37b40684d4745b7198ebab854a5f6121e
lib/osc_machete_rails/workflow.rb
https://github.com/OSC/osc_machete_rails/blob/103bb9b37b40684d4745b7198ebab854a5f6121e/lib/osc_machete_rails/workflow.rb#L8-L20
ruby
test
# Registers a workflow relationship and sets up a hook to additional builder methods. # # @param [Symbol] jobs_active_record_relation_symbol The Job Identifier
def has_machete_workflow_of(jobs_active_record_relation_symbol) # yes, this is magic mimicked from http://guides.rubyonrails.org/plugins.html # and http://yehudakatz.com/2009/11/12/better-ruby-idioms/
# Registers a workflow relationship and sets up a hook to additional builder methods. # # @param [Symbol] jobs_active_record_relation_symbol The Job Identifier def has_machete_workflow_of(jobs_active_record_relation_symbol) # yes, this is magic mimicked from http://guides.rubyonrails.org/plugins.html # and http://yehudakatz.com/2009/11/12/better-ruby-idioms/
cattr_accessor :jobs_active_record_relation_symbol self.jobs_active_record_relation_symbol = jobs_active_record_relation_symbol # separate modules to group common methods for readability purposes # both builder methods and status methods need the jobs relation so # we include that first self.send :include, OscMacheteRails::Workflow::JobsRelation self.send :include, OscMacheteRails::Workflow::BuilderMethods self.send :include, OscMacheteRails::Workflow::StatusMethods end
PeterCamilleri/format_engine
f8df6e44895a0bf223882cf7526d5770c8a26d03
lib/format_engine/engine.rb
https://github.com/PeterCamilleri/format_engine/blob/f8df6e44895a0bf223882cf7526d5770c8a26d03/lib/format_engine/engine.rb#L38-L44
ruby
test
# Do the actual work of building the formatted output. # <br>Parameters # * src - The source object being formatted. # * format_spec_str - The format specification string.
def do_format(src, format_spec_str)
# Do the actual work of building the formatted output. # <br>Parameters # * src - The source object being formatted. # * format_spec_str - The format specification string. def do_format(src, format_spec_str)
spec_info = SpecInfo.new(src, "", self) due_process(spec_info, format_spec_str) do |format| spec_info.do_format(format) end end
PeterCamilleri/format_engine
f8df6e44895a0bf223882cf7526d5770c8a26d03
lib/format_engine/engine.rb
https://github.com/PeterCamilleri/format_engine/blob/f8df6e44895a0bf223882cf7526d5770c8a26d03/lib/format_engine/engine.rb#L51-L60
ruby
test
# Do the actual work of parsing the formatted input. # <br>Parameters # * src - The source string being parsed. # * dst - The class of the object being created. # * parse_spec_str - The format specification string.
def do_parse(src, dst, parse_spec_str)
# Do the actual work of parsing the formatted input. # <br>Parameters # * src - The source string being parsed. # * dst - The class of the object being created. # * parse_spec_str - The format specification string. def do_parse(src, dst, parse_spec_str)
spec_info = SpecInfo.new(src, dst, self) due_process(spec_info, parse_spec_str) do |format| spec_info.do_parse(format) end ensure @unparsed = spec_info.src end
PeterCamilleri/format_engine
f8df6e44895a0bf223882cf7526d5770c8a26d03
lib/format_engine/engine.rb
https://github.com/PeterCamilleri/format_engine/blob/f8df6e44895a0bf223882cf7526d5770c8a26d03/lib/format_engine/engine.rb#L69-L81
ruby
test
# Do the actual work of parsing the formatted input. # <br>Parameters # * spec_info - The state of the process. # * spec_str - The format specification string. # * block - A code block performed for each format specification.
def due_process(spec_info, spec_str)
# Do the actual work of parsing the formatted input. # <br>Parameters # * spec_info - The state of the process. # * spec_str - The format specification string. # * block - A code block performed for each format specification. def due_process(spec_info, spec_str)
format_spec = get_spec(spec_str) spec_info.instance_exec(&self[:before]) format_spec.specs.each do |format| break if yield(format) == :break end spec_info.instance_exec(&self[:after]) spec_info.dst end
palladius/ric
3078a1d917ffbc96a87cc5090485ca948631ddfb
lib/ric/conf.rb
https://github.com/palladius/ric/blob/3078a1d917ffbc96a87cc5090485ca948631ddfb/lib/ric/conf.rb#L20-L45
ruby
test
# =begin # This wants to be a magic configuration loader who looks for configuration automatically in many places, like: # # - ./.CONFNAME.yml # - ~/.CONFNAME.yml # - .CONFNAME/conf.yml # # Loads a YAML file looked upon in common places and returns a hash with appropriate values, or an exception # and maybe a nice explaination.. # # so you can call load_auto_conf('foo') and it will look throughout any ./.foo.yml, ~/.foo.yml or even /etc/foo.yml ! # # =end
def load_auto_conf(confname, opts={})
# =begin # This wants to be a magic configuration loader who looks for configuration automatically in many places, like: # # - ./.CONFNAME.yml # - ~/.CONFNAME.yml # - .CONFNAME/conf.yml # # Loads a YAML file looked upon in common places and returns a hash with appropriate values, or an exception # and maybe a nice explaination.. # # so you can call load_auto_conf('foo') and it will look throughout any ./.foo.yml, ~/.foo.yml or even /etc/foo.yml ! # # =end def load_auto_conf(confname, opts={})
libver = '1.1' dirs = opts.fetch :dirs, ['.', '~', '/etc/', '/etc/ric/auto_conf/'] file_patterns = opts.fetch :file_patterns, [".#{confname}.yml", "#{confname}/conf.yml"] sample_hash = opts.fetch :sample_hash, { 'load_auto_conf' => "please add an :sample_hash to me" , :anyway => "I'm in #{__FILE__}"} verbose = opts.fetch :verbose, true puts "load_auto_conf('#{confname}') v#{libver} start.." if verbose dirs.each{|d| dir = File.expand_path(d) deb "DIR: #{dir}" file_patterns.each{|fp| # if YML exists return the load.. file = "#{dir}/#{fp}" deb " - FILE: #{file}" if File.exists?(file) puts "Found! #{green file}" yaml = YAML.load( File.read(file) ) puts "load_auto_conf('#{confname}', v#{libver}) found: #{green yaml}" if verbose return yaml # in the future u can have a host based autoconf! Yay! end } } puts "Conf not found. Try this:\n---------------------------\n$ cat > ~/#{file_patterns.first}\n#{yellow "#Creatd by ric.rb:load_auto_conf()\n" +sample_hash.to_yaml}\n---------------------------\n" raise "LoadAutoConf: configuration not found for '#{confname}'!" return sample_hash end
bpardee/qwirk
5fb9700cff5511a01181be8ff9cfa9172036a531
lib/qwirk/task.rb
https://github.com/bpardee/qwirk/blob/5fb9700cff5511a01181be8ff9cfa9172036a531/lib/qwirk/task.rb#L168-L192
ruby
test
# Must be called within a mutex synchronize
def check_retry
# Must be called within a mutex synchronize def check_retry
if @finished_publishing && @pending_hash.empty? && @exception_count > 0 && (@retry || @auto_retry) # If we're just doing auto_retry but nothing succeeded last time, then don't run again return if !@retry && @auto_retry && @exception_count == @exceptions_per_run.last Qwirk.logger.info "#{self}: Retrying exception records, exception count = #{@exception_count}" @exceptions_per_run << @exception_count @exception_count = 0 @finished_publishing = false @fail_thread = Thread.new(@exceptions_per_run.last) do |count| begin java.lang.Thread.current_thread.name = "Qwirk fail task: #{task_id}" while !@stopped && (count > 0) && (object = @fail_consumer.receive) count -= 1 publish(object) @fail_consumer.acknowledge_message end @finished_publishing = true @pending_hash_mutex.synchronize { check_finish } rescue Exception => e do_stop Qwirk.logger.error "#{self}: Exception, thread terminating: #{e.message}\n\t#{e.backtrace.join("\n\t")}" end end end end
jochenseeber/mixml
0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214
lib/mixml/application.rb
https://github.com/jochenseeber/mixml/blob/0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214/lib/mixml/application.rb#L136-L204
ruby
test
# Run the mixml command
def run
# Run the mixml command def run
program :name, 'mixml' program :version, Mixml::VERSION program :description, 'XML helper tool' $tool = Mixml::Tool.new global_option('-p', '--pretty', 'Pretty print output') do |value| $tool.pretty = value end global_option('-i', '--inplace', 'Replace the processed files with the new files') do |value| $tool.save = value $tool.print = !value end global_option('-q', '--quiet', 'Do not print nodes') do |value| $tool.print = !value end command :pretty do |c| c.description = 'Pretty print XML files' c.action do |args, options| $tool.pretty = true $tool.work(args) end end modify_command :write do |c| c.description = 'Write selected nodes to the console' c.suppress_output = true c.optional_expression = true end select_command :remove do |c| c.description = 'Remove nodes from the XML documents' end modify_command :replace do |c| c.description = 'Replace nodes in the XML documents' end modify_command :append do |c| c.description = 'Append child nodes in the XML documents' end modify_command :rename do |c| c.description = 'Rename nodes in the XML documents' end modify_command :value do |c| c.description = 'Set node values' end command :execute do |c| c.description = 'Execute script on the XML documents' c.option '-s', '--script STRING', String, 'Script file to execute' c.option '-e', '--expression STRING', String, 'Command to execute' c.action do |args, options| script = options.expression || File.read(options.script) $tool.work(args) do execute(script) end end end run! end
cloudhead/koi
b7d85250e55ef07f70c4ebd339358ef723cfbdd6
lib/koi.rb
https://github.com/cloudhead/koi/blob/b7d85250e55ef07f70c4ebd339358ef723cfbdd6/lib/koi.rb#L126-L143
ruby
test
# List current tasks
def list entities = @db.list
# List current tasks def list entities = @db.list
out entities = entities.is_a?(Fixnum) ? @db.list[0...entities] : entities entities.reject {|e| e[:status] == :removed }.each_with_index do |e, i| out " [#{i}]".blue + "#{e.sticky?? " + ".bold : " "}" + e[:title].underline + " #{e[:tags].join(' ')}".cyan end.tap do |list| out " ..." if @db.list.length > entities.length && !entities.length.zero? out " there are no koi in the water".green if list.size.zero? end out entities end
cloudhead/koi
b7d85250e55ef07f70c4ebd339358ef723cfbdd6
lib/koi.rb
https://github.com/cloudhead/koi/blob/b7d85250e55ef07f70c4ebd339358ef723cfbdd6/lib/koi.rb#L170-L181
ruby
test
# Show task history
def log
# Show task history def log
@db.map do |entity| Entity::Status.map do |status| { title: entity[:title], action: status, time: entity[:"#{status}_at"].strftime("%Y/%m/%d %H:%m") } if entity[:"#{status}_at"] end.compact end.flatten.sort_by {|e| e[:time]}.reverse.each do |entry| out "#{entry[:time].blue} #{entry[:action].to_s.bold} #{entry[:title].underline}" end end
cloudhead/koi
b7d85250e55ef07f70c4ebd339358ef723cfbdd6
lib/koi.rb
https://github.com/cloudhead/koi/blob/b7d85250e55ef07f70c4ebd339358ef723cfbdd6/lib/koi.rb#L334-L340
ruby
test
# Handle things like `self.removed?`
def method_missing meth, *args, &blk
# Handle things like `self.removed?` def method_missing meth, *args, &blk
if meth.to_s.end_with?('?') && Status.include?(s = meth.to_s.chop.to_sym) self[:status] == s else super end end
OpenAMEE/amee-ruby
381b6e34dd0a238fad63594e4f7190b9707dd523
lib/amee/v3/connection.rb
https://github.com/OpenAMEE/amee-ruby/blob/381b6e34dd0a238fad63594e4f7190b9707dd523/lib/amee/v3/connection.rb#L16-L24
ruby
test
# Perform a GET request # options hash should contain query parameters
def v3_get(path, options = {}) # Create request parameters
# Perform a GET request # options hash should contain query parameters def v3_get(path, options = {}) # Create request parameters
get_params = { :method => "get" } get_params[:params] = options unless options.empty? # Send request (with caching) v3_do_request(get_params, path, :cache => true) end
OpenAMEE/amee-ruby
381b6e34dd0a238fad63594e4f7190b9707dd523
lib/amee/v3/connection.rb
https://github.com/OpenAMEE/amee-ruby/blob/381b6e34dd0a238fad63594e4f7190b9707dd523/lib/amee/v3/connection.rb#L28-L43
ruby
test
# Perform a PUT request # options hash should contain request body parameters
def v3_put(path, options = {}) # Expire cached objects from parent on down
# Perform a PUT request # options hash should contain request body parameters def v3_put(path, options = {}) # Expire cached objects from parent on down
expire_matching "#{parent_path(path)}.*" # Create request parameters put_params = { :method => "put", :body => options[:body] ? options[:body] : form_encode(options) } if options[:content_type] put_params[:headers] = { :'Content-Type' => content_type(options[:content_type]) } end # Request v3_do_request(put_params, path) end
OpenAMEE/amee-ruby
381b6e34dd0a238fad63594e4f7190b9707dd523
lib/amee/v3/connection.rb
https://github.com/OpenAMEE/amee-ruby/blob/381b6e34dd0a238fad63594e4f7190b9707dd523/lib/amee/v3/connection.rb#L49-L66
ruby
test
# Perform a POST request # options hash should contain request body parameters # It can also contain a :returnobj parameter which will cause # a full reponse object to be returned instead of just the body
def v3_post(path, options = {}) # Expire cached objects from here on down
# Perform a POST request # options hash should contain request body parameters # It can also contain a :returnobj parameter which will cause # a full reponse object to be returned instead of just the body def v3_post(path, options = {}) # Expire cached objects from here on down
expire_matching "#{raw_path(path)}.*" # Get 'return full response object' flag return_obj = options.delete(:returnobj) || false # Create request parameters post_params = { :method => "post", :body => form_encode(options) } if options[:content_type] post_params[:headers] = { :'Content-Type' => content_type(options[:content_type]) } end # Request v3_do_request(post_params, path, :return_obj => return_obj) end
OpenAMEE/amee-ruby
381b6e34dd0a238fad63594e4f7190b9707dd523
lib/amee/v3/connection.rb
https://github.com/OpenAMEE/amee-ruby/blob/381b6e34dd0a238fad63594e4f7190b9707dd523/lib/amee/v3/connection.rb#L93-L97
ruby
test
# Wrap up parameters into a request and execute it
def v3_do_request(params, path, options = {})
# Wrap up parameters into a request and execute it def v3_do_request(params, path, options = {})
req = Typhoeus::Request.new("https://#{v3_hostname}#{path}", v3_defaults.merge(params)) response = do_request(req, :xml, options) options[:return_obj]==true ? response : response.body end
wrzasa/fast-tcpn
b7e0b610163174208c21ea8565c4150a6f326124
lib/fast-tcpn/timed_place.rb
https://github.com/wrzasa/fast-tcpn/blob/b7e0b610163174208c21ea8565c4150a6f326124/lib/fast-tcpn/timed_place.rb#L34-L41
ruby
test
# Adds token with specified timestamp to the place. # Any callbacks defined for places will be fired.
def add(token, timestamp = nil)
# Adds token with specified timestamp to the place. # Any callbacks defined for places will be fired. def add(token, timestamp = nil)
@net.call_callbacks(:place, :add, Event.new(@name, [token], @net)) unless @net.nil? if timestamp.nil? @marking.add token else @marking.add token, timestamp end end
wanelo/spanx
9c8841527ee914b00aead7821b890e6a0f85d2f1
lib/spanx/cli.rb
https://github.com/wanelo/spanx/blob/9c8841527ee914b00aead7821b890e6a0f85d2f1/lib/spanx/cli.rb#L14-L18
ruby
test
# the first element of ARGV should be a subcommand, which maps to # a class in spanx/cli/
def run(args = ARGV)
# the first element of ARGV should be a subcommand, which maps to # a class in spanx/cli/ def run(args = ARGV)
@args = args validate! Spanx::CLI.subclass_class(args.shift).new.run(args) end
mikeyhogarth/duckpond
19a2127ac48bb052f9df0dbe65013b8c7e14e5fd
lib/duckpond/clause/method_clause.rb
https://github.com/mikeyhogarth/duckpond/blob/19a2127ac48bb052f9df0dbe65013b8c7e14e5fd/lib/duckpond/clause/method_clause.rb#L20-L42
ruby
test
# legal_assesment
def legal_assesment(subject)
# legal_assesment def legal_assesment(subject)
Lawyer.new do |lawyer| unless subject.respond_to? method lawyer.unsatisfied! "Expected subject to respond to method '#{method}'" end if @block || expected_response response_when_called(subject, method, args).tap do |response_when_called| if @block unless @block.call(response_when_called) lawyer.unsatisfied! "Block did not respond with 'true' for method #{method}" end end if expected_response unless response_when_called == expected_response lawyer.unsatisfied! "Expected method #{method} to return #{expected_response} but got #{response_when_called}" end end end end end end
iovis9/dev_training_bot
27413e39bd8a02da6ea3f481f39683ce134795b5
lib/dev_training_bot/services/google_drive_service.rb
https://github.com/iovis9/dev_training_bot/blob/27413e39bd8a02da6ea3f481f39683ce134795b5/lib/dev_training_bot/services/google_drive_service.rb#L51-L71
ruby
test
# Ensure valid credentials, either by restoring from the saved credentials # files or intitiating an OAuth2 authorization. If authorization is required, # the user's default browser will be launched to approve the request. # # @return [Google::Auth::UserRefreshCredentials] OAuth2 credentials
def authorize
# Ensure valid credentials, either by restoring from the saved credentials # files or intitiating an OAuth2 authorization. If authorization is required, # the user's default browser will be launched to approve the request. # # @return [Google::Auth::UserRefreshCredentials] OAuth2 credentials def authorize
client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH) token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH) authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store) user_id = 'default' credentials = authorizer.get_credentials(user_id) if credentials.nil? url = authorizer.get_authorization_url(base_url: OOB_URI) puts 'Open the following URL in the browser and enter the ' \ "resulting code after authorization:\n" + url code = STDIN.gets credentials = authorizer.get_and_store_credentials_from_code( user_id: user_id, code: code, base_url: OOB_URI ) end credentials end
OpenAMEE/amee-ruby
381b6e34dd0a238fad63594e4f7190b9707dd523
lib/amee/connection.rb
https://github.com/OpenAMEE/amee-ruby/blob/381b6e34dd0a238fad63594e4f7190b9707dd523/lib/amee/connection.rb#L108-L121
ruby
test
# GET data from the API, passing in a hash of parameters
def get(path, data = {}) # Allow format override
# GET data from the API, passing in a hash of parameters def get(path, data = {}) # Allow format override
format = data.delete(:format) || @format # Add parameters to URL query string get_params = { :method => "get", :verbose => DEBUG } get_params[:params] = data unless data.empty? # Create GET request get = Typhoeus::Request.new("#{protocol}#{@server}#{path}", get_params) # Send request do_request(get, format, :cache => true) end
OpenAMEE/amee-ruby
381b6e34dd0a238fad63594e4f7190b9707dd523
lib/amee/connection.rb
https://github.com/OpenAMEE/amee-ruby/blob/381b6e34dd0a238fad63594e4f7190b9707dd523/lib/amee/connection.rb#L124-L143
ruby
test
# POST to the AMEE API, passing in a hash of values
def post(path, data = {}) # Allow format override
# POST to the AMEE API, passing in a hash of values def post(path, data = {}) # Allow format override
format = data.delete(:format) || @format # Clear cache expire_matching "#{raw_path(path)}.*" # Extract return unit params query_params = {} query_params[:returnUnit] = data.delete(:returnUnit) if data[:returnUnit] query_params[:returnPerUnit] = data.delete(:returnPerUnit) if data[:returnPerUnit] # Create POST request post_params = { :verbose => DEBUG, :method => "post", :body => form_encode(data) } post_params[:params] = query_params unless query_params.empty? post = Typhoeus::Request.new("#{protocol}#{@server}#{path}", post_params) # Send request do_request(post, format) end
OpenAMEE/amee-ruby
381b6e34dd0a238fad63594e4f7190b9707dd523
lib/amee/connection.rb
https://github.com/OpenAMEE/amee-ruby/blob/381b6e34dd0a238fad63594e4f7190b9707dd523/lib/amee/connection.rb#L146-L161
ruby
test
# POST to the AMEE API, passing in a string of data
def raw_post(path, body, options = {}) # Allow format override
# POST to the AMEE API, passing in a string of data def raw_post(path, body, options = {}) # Allow format override
format = options.delete(:format) || @format # Clear cache expire_matching "#{raw_path(path)}.*" # Create POST request post = Typhoeus::Request.new("#{protocol}#{@server}#{path}", :verbose => DEBUG, :method => "post", :body => body, :headers => { :'Content-type' => options[:content_type] || content_type(format) } ) # Send request do_request(post, format) end
OpenAMEE/amee-ruby
381b6e34dd0a238fad63594e4f7190b9707dd523
lib/amee/connection.rb
https://github.com/OpenAMEE/amee-ruby/blob/381b6e34dd0a238fad63594e4f7190b9707dd523/lib/amee/connection.rb#L164-L183
ruby
test
# PUT to the AMEE API, passing in a hash of data
def put(path, data = {}) # Allow format override
# PUT to the AMEE API, passing in a hash of data def put(path, data = {}) # Allow format override
format = data.delete(:format) || @format # Clear cache expire_matching "#{parent_path(path)}.*" # Extract return unit params query_params = {} query_params[:returnUnit] = data.delete(:returnUnit) if data[:returnUnit] query_params[:returnPerUnit] = data.delete(:returnPerUnit) if data[:returnPerUnit] # Create PUT request put_params = { :verbose => DEBUG, :method => "put", :body => form_encode(data) } put_params[:params] = query_params unless query_params.empty? put = Typhoeus::Request.new("#{protocol}#{@server}#{path}", put_params) # Send request do_request(put, format) end
OpenAMEE/amee-ruby
381b6e34dd0a238fad63594e4f7190b9707dd523
lib/amee/connection.rb
https://github.com/OpenAMEE/amee-ruby/blob/381b6e34dd0a238fad63594e4f7190b9707dd523/lib/amee/connection.rb#L186-L200
ruby
test
# PUT to the AMEE API, passing in a string of data
def raw_put(path, body, options = {}) # Allow format override
# PUT to the AMEE API, passing in a string of data def raw_put(path, body, options = {}) # Allow format override
format = options.delete(:format) || @format # Clear cache expire_matching "#{parent_path(path)}.*" # Create PUT request put = Typhoeus::Request.new("#{protocol}#{@server}#{path}", :verbose => DEBUG, :method => "put", :body => body, :headers => { :'Content-type' => options[:content_type] || content_type(format) } ) # Send request do_request(put, format) end
OpenAMEE/amee-ruby
381b6e34dd0a238fad63594e4f7190b9707dd523
lib/amee/connection.rb
https://github.com/OpenAMEE/amee-ruby/blob/381b6e34dd0a238fad63594e4f7190b9707dd523/lib/amee/connection.rb#L216-L249
ruby
test
# Post to the sign in resource on the API, so that all future # requests are signed
def authenticate # :x_amee_source = "X-AMEE-Source".to_sym
# Post to the sign in resource on the API, so that all future # requests are signed def authenticate # :x_amee_source = "X-AMEE-Source".to_sym
request = Typhoeus::Request.new("#{protocol}#{@server}/auth/signIn", :method => "post", :verbose => DEBUG, :headers => { :Accept => content_type(:xml), }, :body => form_encode(:username=>@username, :password=>@password) ) hydra.queue(request) hydra.run response = request.response @auth_token = response.headers_hash['AuthToken'] d {request.url} d {response.code} d {@auth_token} connection_failed if response.code == 0 unless authenticated? raise AMEE::AuthFailed.new("Authentication failed. Please check your username and password. (tried #{@username},#{@password})") end # Detect API version if response.body.is_json? @version = JSON.parse(response.body)["user"]["apiVersion"].to_f elsif response.body.is_xml? @version = REXML::Document.new(response.body).elements['Resources'].elements['SignInResource'].elements['User'].elements['ApiVersion'].text.to_f else @version = 1.0 end end
OpenAMEE/amee-ruby
381b6e34dd0a238fad63594e4f7190b9707dd523
lib/amee/connection.rb
https://github.com/OpenAMEE/amee-ruby/blob/381b6e34dd0a238fad63594e4f7190b9707dd523/lib/amee/connection.rb#L290-L326
ruby
test
# run each request through some basic error checking, and # if needed log requests
def response_ok?(response, request) # first allow for debugging
# run each request through some basic error checking, and # if needed log requests def response_ok?(response, request) # first allow for debugging
d {request.object_id} d {request} d {response.object_id} d {response.code} d {response.headers_hash} d {response.body} case response.code.to_i when 502, 503, 504 raise AMEE::ConnectionFailed.new("A connection error occurred while talking to AMEE: HTTP response code #{response.code}.\nRequest: #{request.method.upcase} #{request.url.gsub(request.host, '')}") when 408 raise AMEE::TimeOut.new("Request timed out.") when 404 raise AMEE::NotFound.new("The URL was not found on the server.\nRequest: #{request.method.upcase} #{request.url.gsub(request.host, '')}") when 403 raise AMEE::PermissionDenied.new("You do not have permission to perform the requested operation.\nRequest: #{request.method.upcase} #{request.url.gsub(request.host, '')}\n#{request.body}\Response: #{response.body}") when 401 authenticate return false when 400 if response.body.include? "would have resulted in a duplicate resource being created" raise AMEE::DuplicateResource.new("The specified resource already exists. This is most often caused by creating an item that overlaps another in time.\nRequest: #{request.method.upcase} #{request.url.gsub(request.host, '')}\n#{request.body}\Response: #{response.body}") else raise AMEE::BadRequest.new("Bad request. This is probably due to malformed input data.\nRequest: #{request.method.upcase} #{request.url.gsub(request.host, '')}\n#{request.body}\Response: #{response.body}") end when 200, 201, 204 return response when 0 connection_failed end # If we get here, something unhandled has happened, so raise an unknown error. raise AMEE::UnknownError.new("An error occurred while talking to AMEE: HTTP response code #{response.code}.\nRequest: #{request.method.upcase} #{request.url}\n#{request.body}\Response: #{response.body}") end
OpenAMEE/amee-ruby
381b6e34dd0a238fad63594e4f7190b9707dd523
lib/amee/connection.rb
https://github.com/OpenAMEE/amee-ruby/blob/381b6e34dd0a238fad63594e4f7190b9707dd523/lib/amee/connection.rb#L332-L358
ruby
test
# Wrapper for sending requests through to the API. # Takes care of making sure requests authenticated, and # if set, attempts to retry a number of times set when # initialising the class
def do_request(request, format = @format, options = {}) # Is this a v3 request?
# Wrapper for sending requests through to the API. # Takes care of making sure requests authenticated, and # if set, attempts to retry a number of times set when # initialising the class def do_request(request, format = @format, options = {}) # Is this a v3 request?
v3_request = request.url.include?("/#{v3_hostname}/") # make sure we have our auth token before we start # any v1 or v2 requests if !@auth_token && !v3_request d "Authenticating first before we hit #{request.url}" authenticate end request.headers['Accept'] = content_type(format) # Set AMEE source header if set request.headers['X-AMEE-Source'] = @amee_source if @amee_source # path+query string only (split with an int limits the number of splits) path_and_query = '/' + request.url.split('/', 4)[3] if options[:cache] # Get response with caching response = cache(path_and_query) { run_request(request, :xml) } else response = run_request(request, :xml) end response end
OpenAMEE/amee-ruby
381b6e34dd0a238fad63594e4f7190b9707dd523
lib/amee/connection.rb
https://github.com/OpenAMEE/amee-ruby/blob/381b6e34dd0a238fad63594e4f7190b9707dd523/lib/amee/connection.rb#L362-L386
ruby
test
# run request. Extracted from do_request to make # cache code simpler
def run_request(request, format) # Is this a v3 request?
# run request. Extracted from do_request to make # cache code simpler def run_request(request, format) # Is this a v3 request?
v3_request = request.url.include?("/#{v3_hostname}/") # Execute with retries retries = [1] * @retries begin begin d "Queuing the request for #{request.url}" add_authentication_to(request) if @auth_token && !v3_request hydra.queue request hydra.run # Return response if OK end while !response_ok?(request.response, request) # Store updated authToken @auth_token = request.response.headers_hash['AuthToken'] return request.response rescue AMEE::ConnectionFailed, AMEE::TimeOut => e if delay = retries.shift sleep delay retry else raise end end end
wrzasa/fast-tcpn
b7e0b610163174208c21ea8565c4150a6f326124
lib/fast-tcpn/tcpn.rb
https://github.com/wrzasa/fast-tcpn/blob/b7e0b610163174208c21ea8565c4150a6f326124/lib/fast-tcpn/tcpn.rb#L91-L95
ruby
test
# Create and return a new timed place for this model. # # If a place with this # name exists somewhere in the model (e.g. on other pages), and object # representing exisiting place will be returned. Keys of both keys will # be merged. For description of keys see doc for HashMarking.
def timed_place(name, keys = {})
# Create and return a new timed place for this model. # # If a place with this # name exists somewhere in the model (e.g. on other pages), and object # representing exisiting place will be returned. Keys of both keys will # be merged. For description of keys see doc for HashMarking. def timed_place(name, keys = {})
place = create_or_find_place(name, keys, TimedPlace) @timed_places[place] = true place end
wrzasa/fast-tcpn
b7e0b610163174208c21ea8565c4150a6f326124
lib/fast-tcpn/tcpn.rb
https://github.com/wrzasa/fast-tcpn/blob/b7e0b610163174208c21ea8565c4150a6f326124/lib/fast-tcpn/tcpn.rb#L99-L106
ruby
test
# Create and return new transition for this model. # +name+ identifies transition in the net.
def transition(name)
# Create and return new transition for this model. # +name+ identifies transition in the net. def transition(name)
t = find_transition name if t.nil? t = Transition.new name, self @transitions << t end t end
wrzasa/fast-tcpn
b7e0b610163174208c21ea8565c4150a6f326124
lib/fast-tcpn/tcpn.rb
https://github.com/wrzasa/fast-tcpn/blob/b7e0b610163174208c21ea8565c4150a6f326124/lib/fast-tcpn/tcpn.rb#L129-L139
ruby
test
# Starts simulation of this net.
def sim
# Starts simulation of this net. def sim
@stopped = catch :stop_simulation do begin fired = fire_transitions advanced = move_clock_to find_next_time end while fired || advanced end @stopped = false if @stopped == nil rescue StandardError => e raise SimulationError.new(e) end
wrzasa/fast-tcpn
b7e0b610163174208c21ea8565c4150a6f326124
lib/fast-tcpn/tcpn.rb
https://github.com/wrzasa/fast-tcpn/blob/b7e0b610163174208c21ea8565c4150a6f326124/lib/fast-tcpn/tcpn.rb#L164-L174
ruby
test
# Defines new callback for this net. # +what+ can be +:transition+, +:place+ or +:clock+. # Transition callbacks are fired when transitions are fired, place # callbacks when place marking changes, clock callbacks when clock is moved. # +tag+ for transition and clock callback can be +:before+ or +:after+, for # place, can be +:add+ or +:remove+. It defines when the callbacks fill be # fired. If omitted, it will be called for both cases. # # Callback block for transition gets value of event +tag+ (:before or :after) # FastTCPN::Transition::Event object. # # Callback block for place gets value of event +tag+ (:add or :remove) # and FastTCPN::Place::Event object. # # Callback block for clock gets value of event +tag+ (:before or :after) # and FastTCPN::TCPN::ClockEvent object.
def cb_for(what, tag = nil, &block)
# Defines new callback for this net. # +what+ can be +:transition+, +:place+ or +:clock+. # Transition callbacks are fired when transitions are fired, place # callbacks when place marking changes, clock callbacks when clock is moved. # +tag+ for transition and clock callback can be +:before+ or +:after+, for # place, can be +:add+ or +:remove+. It defines when the callbacks fill be # fired. If omitted, it will be called for both cases. # # Callback block for transition gets value of event +tag+ (:before or :after) # FastTCPN::Transition::Event object. # # Callback block for place gets value of event +tag+ (:add or :remove) # and FastTCPN::Place::Event object. # # Callback block for clock gets value of event +tag+ (:before or :after) # and FastTCPN::TCPN::ClockEvent object. def cb_for(what, tag = nil, &block)
if what == :transition cb_for_transition tag, &block elsif what == :place cb_for_place tag, &block elsif what == :clock cb_for_clock tag, &block else raise InvalidCallback.new "Don't know how to add callback for #{what}" end end
wrzasa/fast-tcpn
b7e0b610163174208c21ea8565c4150a6f326124
lib/fast-tcpn/tcpn.rb
https://github.com/wrzasa/fast-tcpn/blob/b7e0b610163174208c21ea8565c4150a6f326124/lib/fast-tcpn/tcpn.rb#L178-L182
ruby
test
# :nodoc: # Calls callbacks, for internal use.
def call_callbacks(what, tag, *params)
# :nodoc: # Calls callbacks, for internal use. def call_callbacks(what, tag, *params)
@callbacks[what][tag].each do |block| block.call tag, *params end end
wrzasa/fast-tcpn
b7e0b610163174208c21ea8565c4150a6f326124
lib/fast-tcpn/transition.rb
https://github.com/wrzasa/fast-tcpn/blob/b7e0b610163174208c21ea8565c4150a6f326124/lib/fast-tcpn/transition.rb#L100-L104
ruby
test
# Add output arc to the +place+. # +block+ is the arc's expresstion, it will be called while firing # transition. Value returned from the block will be put in output # place. The block gets +binding+, and +clock+ values. +binding+ is # a hash with names of input places as keys nad tokens as values.
def output(place, &block)
# Add output arc to the +place+. # +block+ is the arc's expresstion, it will be called while firing # transition. Value returned from the block will be put in output # place. The block gets +binding+, and +clock+ values. +binding+ is # a hash with names of input places as keys nad tokens as values. def output(place, &block)
raise "This is not a Place object!" unless place.kind_of? Place raise "Tried to define output arc without expression! Block is required!" unless block_given? @outputs << OutputArc.new(place, block) end
wrzasa/fast-tcpn
b7e0b610163174208c21ea8565c4150a6f326124
lib/fast-tcpn/transition.rb
https://github.com/wrzasa/fast-tcpn/blob/b7e0b610163174208c21ea8565c4150a6f326124/lib/fast-tcpn/transition.rb#L118-L167
ruby
test
# fire this transition if possible # returns true if fired false otherwise
def fire(clock = 0) # Marking is shuffled each time before it is # used so here we can take first found binding
# fire this transition if possible # returns true if fired false otherwise def fire(clock = 0) # Marking is shuffled each time before it is # used so here we can take first found binding
mapping = Enumerator.new do |y| get_sentry.call(input_markings, clock, y) end.first return false if mapping.nil? tcpn_binding = TCPNBinding.new mapping, input_markings call_callbacks :before, Event.new(@name, tcpn_binding, clock, @net) tokens_for_outputs = @outputs.map do |o| o.block.call(tcpn_binding, clock) end mapping.each do |place_name, token| unless token.kind_of? Token t = if token.instance_of? Array token else [ token ] end t.each do |t| unless t.kind_of? Token raise InvalidToken.new("#{t.inspect} put by sentry for transition `#{name}` in binding for `#{place_name}`") end end end deleted = find_input(place_name).delete(token) if deleted.nil? raise InvalidToken.new("#{token.inspect} put by sentry for transition `#{name}` does not exists in `#{place_name}`") end end @outputs.each do |o| token = tokens_for_outputs.shift o.place.add token unless token.nil? end call_callbacks :after, Event.new(@name, mapping, clock, @net) true rescue InvalidToken raise rescue RuntimeError => e raise FiringError.new(self, e) end
stereobooster/art_typograf
5dd8f1c6a7bc22c94bdc5c4c35721cd1d09b0c0f
lib/art_typograf/client.rb
https://github.com/stereobooster/art_typograf/blob/5dd8f1c6a7bc22c94bdc5c4c35721cd1d09b0c0f/lib/art_typograf/client.rb#L74-L99
ruby
test
# Process text with remote web-service
def send_request(text)
# Process text with remote web-service def send_request(text)
begin request = Net::HTTP::Post.new(@url.path, { 'Content-Type' => 'text/xml', 'SOAPAction' => '"http://typograf.artlebedev.ru/webservices/ProcessText"' }) request.body = form_xml(text, @options) response = Net::HTTP.new(@url.host, @url.port).start do |http| http.request(request) end rescue StandardError => exception raise NetworkError.new(exception.message, exception.backtrace) end if !response.is_a?(Net::HTTPOK) raise NetworkError, "#{response.code}: #{response.message}" end if RESULT =~ response.body body = $1.gsub(/&gt;/, '>').gsub(/&lt;/, '<').gsub(/&amp;/, '&') body.force_encoding("UTF-8").chomp else raise NetworkError, "Can't match result #{response.body}" end end