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
afex/beaker-librarian
5f53c72a003522440efe3aa7eee64a6c3a31c7e3
lib/beaker/librarian.rb
https://github.com/afex/beaker-librarian/blob/5f53c72a003522440efe3aa7eee64a6c3a31c7e3/lib/beaker/librarian.rb#L10-L23
ruby
test
# Install rubygems and the librarian-puppet gem onto each host
def install_librarian(opts = {}) # Check for 'librarian_version' option
# Install rubygems and the librarian-puppet gem onto each host def install_librarian(opts = {}) # Check for 'librarian_version' option
librarian_version = opts[:librarian_version] ||= nil hosts.each do |host| install_package host, 'rubygems' install_package host, 'git' if librarian_version on host, "gem install --no-ri --no-rdoc librarian-puppet -v '#{librarian_version}'" else on host, 'gem install --no-ri --no-rdoc librarian-puppet' end end end
afex/beaker-librarian
5f53c72a003522440efe3aa7eee64a6c3a31c7e3
lib/beaker/librarian.rb
https://github.com/afex/beaker-librarian/blob/5f53c72a003522440efe3aa7eee64a6c3a31c7e3/lib/beaker/librarian.rb#L30-L39
ruby
test
# Copy the module under test to a temporary directory onto the host, and execute librarian-puppet to install # dependencies into the 'distmoduledir'. # # This also manually installs the module under test into 'distmoduledir', but I'm noting here that this is # something I believe should be handled automatically by librarian-puppet, but is not.
def librarian_install_modules(directory, module_name)
# Copy the module under test to a temporary directory onto the host, and execute librarian-puppet to install # dependencies into the 'distmoduledir'. # # This also manually installs the module under test into 'distmoduledir', but I'm noting here that this is # something I believe should be handled automatically by librarian-puppet, but is not. def librarian_install_modules(directory, module_name)
hosts.each do |host| sut_dir = File.join('/tmp', module_name) scp_to host, directory, sut_dir on host, "cd #{sut_dir} && librarian-puppet install --clean --verbose --path #{host['distmoduledir']}" puppet_module_install(:source => directory, :module_name => module_name) end end
Sigimera/sigimera-ruby-client
b4db86637472ec7b5e1d368ebe69590fce16cec0
lib/sigimera/client.rb
https://github.com/Sigimera/sigimera-ruby-client/blob/b4db86637472ec7b5e1d368ebe69590fce16cec0/lib/sigimera/client.rb#L76-L82
ruby
test
# This method returns a single crisis. # # @param [String] identifier A unique crisis identifier # @return [Hash] The single crisis as JSON object
def get_crisis(identifier, params = nil)
# This method returns a single crisis. # # @param [String] identifier A unique crisis identifier # @return [Hash] The single crisis as JSON object def get_crisis(identifier, params = nil)
return nil if identifier.nil? or identifier.empty? endpoint = "/v1/crises/#{identifier}.json?auth_token=#{@auth_token}" endpoint += "&#{URI.encode_www_form params}" if params response = self.get(endpoint) Sigimera::Crisis.new JSON.parse response.body if response and response.body end
Sigimera/sigimera-ruby-client
b4db86637472ec7b5e1d368ebe69590fce16cec0
lib/sigimera/client.rb
https://github.com/Sigimera/sigimera-ruby-client/blob/b4db86637472ec7b5e1d368ebe69590fce16cec0/lib/sigimera/client.rb#L87-L90
ruby
test
# This method returns statistic information about the crises. # # @return [Array] Returns the crises statistic as JSON object
def get_crises_stat
# This method returns statistic information about the crises. # # @return [Array] Returns the crises statistic as JSON object def get_crises_stat
response = self.get("/v1/stats/crises.json?auth_token=#{@auth_token}") JSON.parse response.body if response and response.body end
Sigimera/sigimera-ruby-client
b4db86637472ec7b5e1d368ebe69590fce16cec0
lib/sigimera/client.rb
https://github.com/Sigimera/sigimera-ruby-client/blob/b4db86637472ec7b5e1d368ebe69590fce16cec0/lib/sigimera/client.rb#L95-L98
ruby
test
# This method returns statistic information about user. # # @return [Array] Returns the user statistic as JSON object
def get_user_stat
# This method returns statistic information about user. # # @return [Array] Returns the user statistic as JSON object def get_user_stat
response = self.get("/v1/stats/users.json?auth_token=#{@auth_token}") JSON.parse response.body if response and response.body end
zed-0xff/iostruct
420821811af020364ad482aef47f8d4b6ef936ed
lib/iostruct.rb
https://github.com/zed-0xff/iostruct/blob/420821811af020364ad482aef47f8d4b6ef936ed/lib/iostruct.rb#L26-L40
ruby
test
# src can be IO or String, or anything that responds to :read or :unpack
def read src, size = nil
# src can be IO or String, or anything that responds to :read or :unpack def read src, size = nil
size ||= const_get 'SIZE' data = if src.respond_to?(:read) src.read(size).to_s elsif src.respond_to?(:unpack) src else raise "[?] don't know how to read from #{src.inspect}" end if data.size < size $stderr.puts "[!] #{self.to_s} want #{size} bytes, got #{data.size}" end new(*data.unpack(const_get('FORMAT'))) end
cliftonm/clifton_lib
2b035dd85ba56c7c1618d543c923c04274af46d1
lib/clifton_lib/xml/xml_document.rb
https://github.com/cliftonm/clifton_lib/blob/2b035dd85ba56c7c1618d543c923c04274af46d1/lib/clifton_lib/xml/xml_document.rb#L21-L30
ruby
test
# XmlDocument.new() # XmlDeclarationNode create_xml_declaration(string version, string encoding) # Returns a node that will appear at the beginning of the document as: # <?xml version="[ver]" encoding="[enc]" ?> # The node must still be added to the parent (root) node with XmlNode#append_child.
def create_xml_declaration(version, encoding)
# XmlDocument.new() # XmlDeclarationNode create_xml_declaration(string version, string encoding) # Returns a node that will appear at the beginning of the document as: # <?xml version="[ver]" encoding="[enc]" ?> # The node must still be added to the parent (root) node with XmlNode#append_child. def create_xml_declaration(version, encoding)
declNode = XmlDeclarationNode.new() { @attributes << XmlAttribute.new() {@name='version'; @value=version} @attributes << XmlAttribute.new() {@name='encoding'; @value=encoding} } declNode.xml_document = self declNode end
cliftonm/clifton_lib
2b035dd85ba56c7c1618d543c923c04274af46d1
lib/clifton_lib/xml/xml_document.rb
https://github.com/cliftonm/clifton_lib/blob/2b035dd85ba56c7c1618d543c923c04274af46d1/lib/clifton_lib/xml/xml_document.rb#L57-L66
ruby
test
# XmlAttribute create_attribute(string name, string val = '') # Returns an XmlAttribute. Append to the desired element with XmlElement#append_attribute.
def create_attribute(name, value = '')
# XmlAttribute create_attribute(string name, string val = '') # Returns an XmlAttribute. Append to the desired element with XmlElement#append_attribute. def create_attribute(name, value = '')
attr = XmlAttribute.new() { @name = name @value = value } attr.xml_document = self attr end
cliftonm/clifton_lib
2b035dd85ba56c7c1618d543c923c04274af46d1
lib/clifton_lib/xml/xml_document.rb
https://github.com/cliftonm/clifton_lib/blob/2b035dd85ba56c7c1618d543c923c04274af46d1/lib/clifton_lib/xml/xml_document.rb#L95-L149
ruby
test
# void write_nodes(XmlTextWriter writer, XmlNodes[] nodes)
def write_nodes(writer, nodes)
# void write_nodes(XmlTextWriter writer, XmlNodes[] nodes) def write_nodes(writer, nodes)
nodes.each_with_index do |node, idx| # write xml declaration if it exists. # TODO: Should throw somewhere if this isn't the first node. if node.is_a?(XmlDeclarationNode) writer.write('<?xml') write_attributes(writer, node) writer.write('?>') writer.new_line() elsif node.is_a?(XmlFragment) # if it's a fragment, just write the fragment, which is expected to be a string. writer.write_fragment(node.text) else # begin element tag and attributes writer.write('<' + node.name) write_attributes(writer, node) # if inner text, write it out now. if node.inner_text writer.write('>' + node.inner_text) if node.has_child_nodes() write_child_nodes(writer, node) end writer.write('</' + node.name + '>') crlf_if_more_nodes(writer, nodes, idx) else # Children are allowed only if there is no inner text. if node.has_child_nodes() # close element tag, indent, and recurse. writer.write('>') write_child_nodes(writer, node) # close the element writer.write('</' + node.name + '>') crlf_if_more_nodes(writer, nodes, idx) else # if no children and no inner text, use the abbreviated closing tag token unless no closing tag is required and unless self closing tags are not allowed. if node.html_closing_tag if writer.allow_self_closing_tags writer.write('/>') else writer.write('></' + node.name + '>') end else writer.write('>') end crlf_if_more_nodes(writer, nodes, idx) end end end end nil end
cliftonm/clifton_lib
2b035dd85ba56c7c1618d543c923c04274af46d1
lib/clifton_lib/xml/xml_document.rb
https://github.com/cliftonm/clifton_lib/blob/2b035dd85ba56c7c1618d543c923c04274af46d1/lib/clifton_lib/xml/xml_document.rb#L153-L176
ruby
test
# Write the attribute collection for a node. # void write_attributes(XmlTextWriter writer, XmlNode node)
def write_attributes(writer, node)
# Write the attribute collection for a node. # void write_attributes(XmlTextWriter writer, XmlNode node) def write_attributes(writer, node)
if node.attributes.count > 0 # stuff them into an array of strings attrs = [] node.attributes.each do |attr| # special case: # example: <nav class="top-bar" data-topbar> if attr.value.nil? attrs << attr.name else attrs << attr.name + '="' + attr.value + '"' end end # separate them with a space attr_str = attrs.join(' ') # requires a leading space as well to separate from the element name. writer.write(' ' + attr_str) end nil end
po-se/pose
576d7463dcc33d3b28a088254c4c6230cf951f9a
lib/pose/activerecord_base_additions.rb
https://github.com/po-se/pose/blob/576d7463dcc33d3b28a088254c4c6230cf951f9a/lib/pose/activerecord_base_additions.rb#L6-L14
ruby
test
# Defines the searchable content in ActiveRecord objects.
def posify *source_methods, &block
# Defines the searchable content in ActiveRecord objects. def posify *source_methods, &block
include ModelClassAdditions self.pose_content = proc do text_chunks = source_methods.map { |source| send(source) } text_chunks << instance_eval(&block) if block text_chunks.reject(&:blank?).join(' ') end end
Aqutras/ika
d3b3cd4ae72dbfa2580462747e635bd1f34a90f9
lib/carrierwave/base64uploader.rb
https://github.com/Aqutras/ika/blob/d3b3cd4ae72dbfa2580462747e635bd1f34a90f9/lib/carrierwave/base64uploader.rb#L4-L16
ruby
test
# https://gist.github.com/hilotter/6a4c356499b55e8eaf9a/
def base64_conversion(uri_str, filename = 'base64')
# https://gist.github.com/hilotter/6a4c356499b55e8eaf9a/ def base64_conversion(uri_str, filename = 'base64')
image_data = split_base64(uri_str) image_data_string = image_data[:data] image_data_binary = Base64.decode64(image_data_string) temp_img_file = Tempfile.new(filename) temp_img_file.binmode temp_img_file << image_data_binary temp_img_file.rewind img_params = {:filename => "#{filename}", :type => image_data[:type], :tempfile => temp_img_file} ActionDispatch::Http::UploadedFile.new(img_params) end
wrzasa/fast-tcpn
b7e0b610163174208c21ea8565c4150a6f326124
lib/fast-tcpn/hash_marking.rb
https://github.com/wrzasa/fast-tcpn/blob/b7e0b610163174208c21ea8565c4150a6f326124/lib/fast-tcpn/hash_marking.rb#L64-L70
ruby
test
# Creates new HashMarking with specified keys. At least # one key must be specified. The keys are used to # store tokens in Hashes -- one hash for each key. Thus # finding tokens by the keys is fast. # # +keys+ is a hash of the form: { key_name => method }, where +key_name+ is a name that # will be used to access tokens indexed by this key and +method+ is a method that should # be called on token's value to get value that should be used group tokens indexed by this key. # Allows to iterate over all values in marking or over all values for which # specified +key+ has specified +value+. If no block is given, returns adequate # Enumerator. Yielded values are deep-cloned so you can use them without fear of # interfering with TCPN simulation. # # Values are yielded in random order -- each time each is called with block # or a new Enumerator is created, the order is changed. Thus tokens are selection # is `in some sense fair`. Current implementation assumes, that in most cases iteration # will finish quickly, without yielding large number of tokens. In such cases the # shuffling algorithm is efficient. But if for some reason most tokens from marking # should be yielded, it will be less and less efficient, with every nxt token. In this # case one should consider using standard +shuffle+ method here instead of +lazy_shuffle+.
def each(key = nil, value = nil)
# Creates new HashMarking with specified keys. At least # one key must be specified. The keys are used to # store tokens in Hashes -- one hash for each key. Thus # finding tokens by the keys is fast. # # +keys+ is a hash of the form: { key_name => method }, where +key_name+ is a name that # will be used to access tokens indexed by this key and +method+ is a method that should # be called on token's value to get value that should be used group tokens indexed by this key. # Allows to iterate over all values in marking or over all values for which # specified +key+ has specified +value+. If no block is given, returns adequate # Enumerator. Yielded values are deep-cloned so you can use them without fear of # interfering with TCPN simulation. # # Values are yielded in random order -- each time each is called with block # or a new Enumerator is created, the order is changed. Thus tokens are selection # is `in some sense fair`. Current implementation assumes, that in most cases iteration # will finish quickly, without yielding large number of tokens. In such cases the # shuffling algorithm is efficient. But if for some reason most tokens from marking # should be yielded, it will be less and less efficient, with every nxt token. In this # case one should consider using standard +shuffle+ method here instead of +lazy_shuffle+. def each(key = nil, value = nil)
return enum_for(:each, key, value) unless block_given? return if empty? list_for(key, value).lazy_shuffle do |token| yield clone token end end
wrzasa/fast-tcpn
b7e0b610163174208c21ea8565c4150a6f326124
lib/fast-tcpn/hash_marking.rb
https://github.com/wrzasa/fast-tcpn/blob/b7e0b610163174208c21ea8565c4150a6f326124/lib/fast-tcpn/hash_marking.rb#L92-L103
ruby
test
# Creates new token of the +object+ and adds it to the marking. # Objects added to the marking are deep-cloned, so you can use them # without fear to interfere with TCPN simulation. But have it in mind! # If you put a large object with a lot of references in the marking, # it will significanntly slow down simulation and increase memory usage.
def add(objects)
# Creates new token of the +object+ and adds it to the marking. # Objects added to the marking are deep-cloned, so you can use them # without fear to interfere with TCPN simulation. But have it in mind! # If you put a large object with a lot of references in the marking, # it will significanntly slow down simulation and increase memory usage. def add(objects)
unless objects.kind_of? Array objects = [ objects ] end objects.each do |object| value = object if object.instance_of? Hash value = object[:val] end add_token prepare_token(value) end end
wrzasa/fast-tcpn
b7e0b610163174208c21ea8565c4150a6f326124
lib/fast-tcpn/hash_marking.rb
https://github.com/wrzasa/fast-tcpn/blob/b7e0b610163174208c21ea8565c4150a6f326124/lib/fast-tcpn/hash_marking.rb#L110-L123
ruby
test
# Deletes the +token+ from the marking. # To do it you must first find the token in # the marking.
def delete(tokens)
# Deletes the +token+ from the marking. # To do it you must first find the token in # the marking. def delete(tokens)
unless tokens.instance_of? Array tokens = [ tokens ] end removed = tokens.map do |token| validate_token!(token) delete_token(token) end if removed.size == 1 removed.first else removed end end
po-se/pose
576d7463dcc33d3b28a088254c4c6230cf951f9a
lib/pose/search.rb
https://github.com/po-se/pose/blob/576d7463dcc33d3b28a088254c4c6230cf951f9a/lib/pose/search.rb#L34-L38
ruby
test
# Creates a JOIN to the given expression.
def add_joins arel
# Creates a JOIN to the given expression. def add_joins arel
@query.joins.inject(arel) do |memo, join_data| add_join memo, join_data end end
po-se/pose
576d7463dcc33d3b28a088254c4c6230cf951f9a
lib/pose/search.rb
https://github.com/po-se/pose/blob/576d7463dcc33d3b28a088254c4c6230cf951f9a/lib/pose/search.rb#L42-L44
ruby
test
# Adds the WHERE clauses from the given query to the given arel construct.
def add_wheres arel
# Adds the WHERE clauses from the given query to the given arel construct. def add_wheres arel
@query.where.inject(arel) { |memo, where| memo.where where } end
po-se/pose
576d7463dcc33d3b28a088254c4c6230cf951f9a
lib/pose/search.rb
https://github.com/po-se/pose/blob/576d7463dcc33d3b28a088254c4c6230cf951f9a/lib/pose/search.rb#L58-L63
ruby
test
# Truncates the result set based on the :limit parameter in the query.
def limit_ids result
# Truncates the result set based on the :limit parameter in the query. def limit_ids result
return unless @query.has_limit? result.each do |clazz, ids| result[clazz] = ids.slice 0, @query.limit end end
po-se/pose
576d7463dcc33d3b28a088254c4c6230cf951f9a
lib/pose/search.rb
https://github.com/po-se/pose/blob/576d7463dcc33d3b28a088254c4c6230cf951f9a/lib/pose/search.rb#L67-L77
ruby
test
# Converts the ids to classes, if the user wants classes.
def load_classes result
# Converts the ids to classes, if the user wants classes. def load_classes result
return if @query.ids_requested? result.each do |clazz, ids| if ids.size > 0 result[clazz] = clazz.where(id: ids) if @query.has_select result[clazz] = result[clazz].select(@query.options[:select]) end end end end
po-se/pose
576d7463dcc33d3b28a088254c4c6230cf951f9a
lib/pose/search.rb
https://github.com/po-se/pose/blob/576d7463dcc33d3b28a088254c4c6230cf951f9a/lib/pose/search.rb#L82-L88
ruby
test
# Merges the given posable object ids for a single query word into the given search result. # Helper method for :search_words.
def merge_search_result_word_matches result, class_name, ids
# Merges the given posable object ids for a single query word into the given search result. # Helper method for :search_words. def merge_search_result_word_matches result, class_name, ids
if result.has_key? class_name result[class_name] = result[class_name] & ids else result[class_name] = ids end end
po-se/pose
576d7463dcc33d3b28a088254c4c6230cf951f9a
lib/pose/search.rb
https://github.com/po-se/pose/blob/576d7463dcc33d3b28a088254c4c6230cf951f9a/lib/pose/search.rb#L101-L109
ruby
test
# Performs a complete search. # Clients should use :results to perform a search, # since it caches the results.
def search
# Performs a complete search. # Clients should use :results to perform a search, # since it caches the results. def search
{}.tap do |result| search_words.each do |class_name, ids| result[class_name.constantize] = ids end limit_ids result load_classes result end end
po-se/pose
576d7463dcc33d3b28a088254c4c6230cf951f9a
lib/pose/search.rb
https://github.com/po-se/pose/blob/576d7463dcc33d3b28a088254c4c6230cf951f9a/lib/pose/search.rb#L113-L125
ruby
test
# Finds all matching ids for a single word of the search query.
def search_word word
# Finds all matching ids for a single word of the search query. def search_word word
empty_result.tap do |result| data = Assignment.joins(:word) \ .select('pose_assignments.posable_id, pose_assignments.posable_type') \ .where('pose_words.text LIKE ?', "#{word}%") \ .where('pose_assignments.posable_type IN (?)', @query.class_names) data = add_joins data data = add_wheres data Assignment.connection.select_all(data.to_sql).each do |pose_assignment| result[pose_assignment['posable_type']] << pose_assignment['posable_id'].to_i end end end
po-se/pose
576d7463dcc33d3b28a088254c4c6230cf951f9a
lib/pose/search.rb
https://github.com/po-se/pose/blob/576d7463dcc33d3b28a088254c4c6230cf951f9a/lib/pose/search.rb#L129-L137
ruby
test
# Returns all matching ids for all words of the search query.
def search_words
# Returns all matching ids for all words of the search query. def search_words
{}.tap do |result| @query.query_words.each do |query_word| search_word(query_word).each do |class_name, ids| merge_search_result_word_matches result, class_name, ids end end end end
tkawa/activeresource-google_spreadsheets
a0e2abe08b6f3f594fb91e644d428a0639b88287
lib/google_spreadsheets/connection.rb
https://github.com/tkawa/activeresource-google_spreadsheets/blob/a0e2abe08b6f3f594fb91e644d428a0639b88287/lib/google_spreadsheets/connection.rb#L16-L30
ruby
test
# Deprecated and Not recommended
def client_login_authorization_header(http_method, uri)
# Deprecated and Not recommended def client_login_authorization_header(http_method, uri)
if @user && @password && !@auth_token email = CGI.escape(@user) password = CGI.escape(@password) http = Net::HTTP.new('www.google.com', 443) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE resp, data = http.post('/accounts/ClientLogin', "accountType=HOSTED_OR_GOOGLE&Email=#{email}&Passwd=#{password}&service=wise", { 'Content-Type' => 'application/x-www-form-urlencoded' }) handle_response(resp) @auth_token = (data || resp.body)[/Auth=(.*)/n, 1] end @auth_token ? { 'Authorization' => "GoogleLogin auth=#{@auth_token}" } : {} end
mikeyhogarth/duckpond
19a2127ac48bb052f9df0dbe65013b8c7e14e5fd
lib/duckpond/inspection.rb
https://github.com/mikeyhogarth/duckpond/blob/19a2127ac48bb052f9df0dbe65013b8c7e14e5fd/lib/duckpond/inspection.rb#L35-L45
ruby
test
# fulfilled_by? # # receives exactly one contract, and returns true/false if # the inspected object responds to the same methods indicated # by the contract's clauses.
def fulfilled_by?(contract)
# fulfilled_by? # # receives exactly one contract, and returns true/false if # the inspected object responds to the same methods indicated # by the contract's clauses. def fulfilled_by?(contract)
contract.each_clause do |clause| clause.legal_assesment(@subject).tap do |lawyer| unless lawyer.satisfied? @satisfied = false @messages << lawyer.messages end end end @satisfied end
cliftonm/clifton_lib
2b035dd85ba56c7c1618d543c923c04274af46d1
lib/clifton_lib/xml/xml_text_writer.rb
https://github.com/cliftonm/clifton_lib/blob/2b035dd85ba56c7c1618d543c923c04274af46d1/lib/clifton_lib/xml/xml_text_writer.rb#L24-L38
ruby
test
# void write(string str)
def write_fragment(str)
# void write(string str) def write_fragment(str)
if @formatting == :indented # Take the fragment, split up the CRLF's, and write out in an indented manner. # Let the formatting of the fragment handle its indentation at our current indent level. lines = str.split("\r\n") lines.each_with_index do |line, idx| @output << line new_line() if idx < lines.count - 1 # No need for a new line on the last line. end else @output << str end nil end
Pluvie/rails-dev-tools
7abd38da4d16fc46e92c0e6cabb99a06364392c1
lib/dev/project.rb
https://github.com/Pluvie/rails-dev-tools/blob/7abd38da4d16fc46e92c0e6cabb99a06364392c1/lib/dev/project.rb#L56-L63
ruby
test
# Determina se l'app è valida. Prende l'app corrente se non # viene specificata nessuna app. # # @param [String] app_name il nome dell'app. # # @return [Boolean] se l'app è fra quelle esistenti.
def valid_app?(app_name = self.current_app)
# Determina se l'app è valida. Prende l'app corrente se non # viene specificata nessuna app. # # @param [String] app_name il nome dell'app. # # @return [Boolean] se l'app è fra quelle esistenti. def valid_app?(app_name = self.current_app)
if app_name.in? self.apps true else raise ExecutionError.new "The app '#{app_name}' is neither a main app nor an engine "\ "within the project '#{self.name}'." end end
Pluvie/rails-dev-tools
7abd38da4d16fc46e92c0e6cabb99a06364392c1
lib/dev/project.rb
https://github.com/Pluvie/rails-dev-tools/blob/7abd38da4d16fc46e92c0e6cabb99a06364392c1/lib/dev/project.rb#L73-L83
ruby
test
# Ottiene la directory corrente nella cartella # dell'app specificata. Prende l'app corrente se non # viene specificata nessuna app. # # @param [String] app_name il nome dell'app. # # @return [nil]
def app_folder(app_name = self.current_app)
# Ottiene la directory corrente nella cartella # dell'app specificata. Prende l'app corrente se non # viene specificata nessuna app. # # @param [String] app_name il nome dell'app. # # @return [nil] def app_folder(app_name = self.current_app)
if self.type == :multi if app_name.in? self.main_apps "#{self.folder}/main_apps/#{app_name}" elsif app_name.in? self.engines "#{self.folder}/engines/#{app_name}" end elsif self.type == :single self.folder end end
Pluvie/rails-dev-tools
7abd38da4d16fc46e92c0e6cabb99a06364392c1
lib/dev/project.rb
https://github.com/Pluvie/rails-dev-tools/blob/7abd38da4d16fc46e92c0e6cabb99a06364392c1/lib/dev/project.rb#L92-L96
ruby
test
# Determina il file di versione dell'app. Prende l'app corrente se non # viene specificata nessuna app. # # @param [String] app_name il nome dell'app. # # @return [String] il file di versione dell'app.
def app_version_file(app_name = self.current_app)
# Determina il file di versione dell'app. Prende l'app corrente se non # viene specificata nessuna app. # # @param [String] app_name il nome dell'app. # # @return [String] il file di versione dell'app. def app_version_file(app_name = self.current_app)
Dir.glob("#{app_folder(app_name)}/lib/**/version.rb").min_by do |filename| filename.chars.count end end
Pluvie/rails-dev-tools
7abd38da4d16fc46e92c0e6cabb99a06364392c1
lib/dev/project.rb
https://github.com/Pluvie/rails-dev-tools/blob/7abd38da4d16fc46e92c0e6cabb99a06364392c1/lib/dev/project.rb#L105-L113
ruby
test
# Ritorna la versione dell'app. Prende l'app corrente se non # viene specificata nessuna app. # # @param [String] app_name il nome dell'app. # # @return [String] la versione dell'app.
def app_version(app_name = self.current_app)
# Ritorna la versione dell'app. Prende l'app corrente se non # viene specificata nessuna app. # # @param [String] app_name il nome dell'app. # # @return [String] la versione dell'app. def app_version(app_name = self.current_app)
if File.exists? app_version_file(app_name).to_s File.read(app_version_file(app_name)) .match(/VERSION = '([0-9\.]+)'\n/) .try(:captures).try(:first) else `git tag`.split("\n").first end end
Pluvie/rails-dev-tools
7abd38da4d16fc46e92c0e6cabb99a06364392c1
lib/dev/project.rb
https://github.com/Pluvie/rails-dev-tools/blob/7abd38da4d16fc46e92c0e6cabb99a06364392c1/lib/dev/project.rb#L121-L129
ruby
test
# Alza la versione dell'app corrente a quella specificata. # # @param [String] version la versione a cui arrivare. # # @return [nil]
def bump_app_version_to(version)
# Alza la versione dell'app corrente a quella specificata. # # @param [String] version la versione a cui arrivare. # # @return [nil] def bump_app_version_to(version)
if File.exists? self.app_version_file version_file = self.app_version_file version_content = File.read("#{version_file}") File.open(version_file, 'w+') do |f| f.puts version_content.gsub(/VERSION = '[0-9\.]+'\n/, "VERSION = '#{version}'\n") end end end
Pluvie/rails-dev-tools
7abd38da4d16fc46e92c0e6cabb99a06364392c1
lib/dev/executable.rb
https://github.com/Pluvie/rails-dev-tools/blob/7abd38da4d16fc46e92c0e6cabb99a06364392c1/lib/dev/executable.rb#L79-L84
ruby
test
# Inizializza l'eseguibile, in base al comando passato. # # @param [Array] argv gli argomenti del comando. # # Carica i dati del progetto prendendoli dal file # di configurazione del file 'dev.yml'. # # @return [nil]
def load_project
# Inizializza l'eseguibile, in base al comando passato. # # @param [Array] argv gli argomenti del comando. # # Carica i dati del progetto prendendoli dal file # di configurazione del file 'dev.yml'. # # @return [nil] def load_project
config_file = Dir.glob("#{Dir.pwd}/**/dev.yml").first raise ExecutionError.new "No valid configuration files found. Searched for a file named 'dev.yml' "\ "in folder #{Dir.pwd} and all its subdirectories." if config_file.nil? @project = Dev::Project.new(config_file) end
Pluvie/rails-dev-tools
7abd38da4d16fc46e92c0e6cabb99a06364392c1
lib/dev/executable.rb
https://github.com/Pluvie/rails-dev-tools/blob/7abd38da4d16fc46e92c0e6cabb99a06364392c1/lib/dev/executable.rb#L109-L117
ruby
test
# Esegue un comando e cattura l'output ritornandolo come # risultato di questo metodo. Si può passare l'opzione # +flush+ per stampare subito l'output come se non fosse stato # catturato. # # @param [String] command il comando da eseguire. # @param [Hash] options le opzioni. # # @return [nil]
def exec(command, options = {})
# Esegue un comando e cattura l'output ritornandolo come # risultato di questo metodo. Si può passare l'opzione # +flush+ per stampare subito l'output come se non fosse stato # catturato. # # @param [String] command il comando da eseguire. # @param [Hash] options le opzioni. # # @return [nil] def exec(command, options = {})
out, err, status = Open3.capture3(command) command_output = [ out.presence, err.presence ].compact.join("\n") if options[:flush] == true puts command_output else command_output end end
Pluvie/rails-dev-tools
7abd38da4d16fc46e92c0e6cabb99a06364392c1
lib/dev/executable.rb
https://github.com/Pluvie/rails-dev-tools/blob/7abd38da4d16fc46e92c0e6cabb99a06364392c1/lib/dev/executable.rb#L123-L201
ruby
test
# Stampa i comandi possibili. # # @return [nil]
def help
# Stampa i comandi possibili. # # @return [nil] def help
puts print "Dev".green print " - available commands:\n" puts print "\tversion\t\t".limegreen print "Prints current version.\n" puts print "\tfeature\t\t".limegreen print "Opens or closes a feature for the current app.\n" print "\t\t\tWarning: the app is determined from the current working directory!\n" print "\t\t\tExample: " print "dev feature open my-new-feature".springgreen print " (opens a new feature for the current app)" print ".\n" print "\t\t\tExample: " print "dev feature close my-new-feature".springgreen print " (closes a developed new feature for the current app)" print ".\n" puts print "\thotfix\t\t".limegreen print "Opens or closes a hotfix for the current app.\n" print "\t\t\tWarning: the app is determined from the current working directory!\n" print "\t\t\tExample: " print "dev hotfix open 0.2.1".springgreen print " (opens a new hotfix for the current app)" print ".\n" print "\t\t\tExample: " print "dev hotfix close 0.2.1".springgreen print " (closes a developed new hotfix for the current app)" print ".\n" puts print "\trelease\t\t".limegreen print "Opens or closes a release for the current app.\n" print "\t\t\tWarning: the app is determined from the current working directory!\n" print "\t\t\tExample: " print "dev release open 0.2.0".springgreen print " (opens a new release for the current app)" print ".\n" print "\t\t\tExample: " print "dev release close 0.2.0".springgreen print " (closes a developed new release for the current app)" print ".\n" puts print "\tpull\t\t".limegreen print "Pulls specified app's git repository, or pulls all apps if none are specified.\n" print "\t\t\tWarning: the pulled branch is the one the app is currently on!\n" print "\t\t\tExample: " print "dev pull [myapp]".springgreen print ".\n" puts print "\tpush\t\t".limegreen print "Commits and pushes the specified app.\n" print "\t\t\tWarning: the pushed branch is the one the app is currently on!\n" print "\t\t\tExample: " print "dev push myapp \"commit message\"".springgreen print ".\n" puts print "\ttest\t\t".limegreen print "Runs the app's test suite. Tests must be written with rspec.\n" print "\t\t\tIt is possibile to specify which app's test suite to run.\n" print "\t\t\tIf nothing is specified, all main app's test suites are run.\n" print "\t\t\tExample: " print "dev test mymainapp myengine".springgreen print " (runs tests for 'mymainapp' and 'myengine')" print ".\n" print "\t\t\tExample: " print "dev test".springgreen print " (runs tests for all main apps and engines within this project)" print ".\n" puts end
Sigimera/sigimera-ruby-client
b4db86637472ec7b5e1d368ebe69590fce16cec0
lib/sigimera/http_helper.rb
https://github.com/Sigimera/sigimera-ruby-client/blob/b4db86637472ec7b5e1d368ebe69590fce16cec0/lib/sigimera/http_helper.rb#L12-L20
ruby
test
# GET endpoint # # @param [String] endpoint The endpoint that should be called. # @return [Net::HTTPResponse] The HTTP response object
def get(endpoint)
# GET endpoint # # @param [String] endpoint The endpoint that should be called. # @return [Net::HTTPResponse] The HTTP response object def get(endpoint)
uri, http = get_connection(endpoint) req = Net::HTTP::Get.new("#{uri.path}?#{uri.query}") req.add_field("Content-Type", "application/json") req.add_field("User-Agent", "Sigimera Ruby Client v#{Sigimera::VERSION}") http.request(req) end
Sigimera/sigimera-ruby-client
b4db86637472ec7b5e1d368ebe69590fce16cec0
lib/sigimera/http_helper.rb
https://github.com/Sigimera/sigimera-ruby-client/blob/b4db86637472ec7b5e1d368ebe69590fce16cec0/lib/sigimera/http_helper.rb#L27-L36
ruby
test
# POST endpoint # # @param [String] endpoint The endpoint that should be called. # @param [String] basic_hash Base64.strict_encode64("username:password") # @return [Net::HTTPResponse] The HTTP response object
def post(endpoint, basic_hash = nil)
# POST endpoint # # @param [String] endpoint The endpoint that should be called. # @param [String] basic_hash Base64.strict_encode64("username:password") # @return [Net::HTTPResponse] The HTTP response object def post(endpoint, basic_hash = nil)
uri, http = get_connection(endpoint) req = Net::HTTP::Post.new("#{uri.path}?#{uri.query}") req.add_field("Content-Type", "application/json") req.add_field("User-Agent", "Sigimera Ruby Client v#{Sigimera::VERSION}") req.add_field("Authorization", "Basic #{basic_hash}") if basic_hash http.request(req) end
Sigimera/sigimera-ruby-client
b4db86637472ec7b5e1d368ebe69590fce16cec0
lib/sigimera/http_helper.rb
https://github.com/Sigimera/sigimera-ruby-client/blob/b4db86637472ec7b5e1d368ebe69590fce16cec0/lib/sigimera/http_helper.rb#L42-L49
ruby
test
# HEAD endpoint # # @param [String] endpoint The endpoint that should be called. # @return [Net::HTTPResponse] The HTTP response object
def head(endpoint)
# HEAD endpoint # # @param [String] endpoint The endpoint that should be called. # @return [Net::HTTPResponse] The HTTP response object def head(endpoint)
uri, http = get_connection(endpoint) req = Net::HTTP::Head.new("#{uri.path}?#{uri.query}") req.add_field("User-Agent", "Sigimera Ruby Client v#{Sigimera::VERSION}") http.request(req) end
bdurand/lumberjack_mongo_device
53653489f3fa7362cdb394880c2231e466936702
lib/lumberjack_mongo_device.rb
https://github.com/bdurand/lumberjack_mongo_device/blob/53653489f3fa7362cdb394880c2231e466936702/lib/lumberjack_mongo_device.rb#L132-L145
ruby
test
# Retrieve Lumberjack::LogEntry objects from the MongoDB collection. If a block is given, it will be yielded to # with each entry. Otherwise, it will return an array of all the entries.
def find(selector, options = {}, &block)
# Retrieve Lumberjack::LogEntry objects from the MongoDB collection. If a block is given, it will be yielded to # with each entry. Otherwise, it will return an array of all the entries. def find(selector, options = {}, &block)
entries = [] @collection.find(selector, options) do |cursor| cursor.each do |doc| entry = LogEntry.new(doc[TIME], doc[SEVERITY], doc[MESSAGE], doc[PROGNAME], doc[PID], doc[UNIT_OF_WORK_ID]) if block_given? yield entry else entries << entry end end end block_given? ? nil : entries end
po-se/pose
576d7463dcc33d3b28a088254c4c6230cf951f9a
lib/pose/model_class_additions.rb
https://github.com/po-se/pose/blob/576d7463dcc33d3b28a088254c4c6230cf951f9a/lib/pose/model_class_additions.rb#L58-L61
ruby
test
# Helper method. # Updates the search words with the text returned by search_strings.
def update_pose_words
# Helper method. # Updates the search words with the text returned by search_strings. def update_pose_words
self.pose_words.delete(Word.factory(pose_stale_words true)) self.pose_words << Word.factory(pose_words_to_add) end
wrzasa/fast-tcpn
b7e0b610163174208c21ea8565c4150a6f326124
lib/fast-tcpn/timed_hash_marking.rb
https://github.com/wrzasa/fast-tcpn/blob/b7e0b610163174208c21ea8565c4150a6f326124/lib/fast-tcpn/timed_hash_marking.rb#L22-L39
ruby
test
# Create a new TimedHashMarking # Creates token with +object+ as its value and adds it to the marking. # if no timestamp is given, current time will be used.
def add(objects, timestamp = @time)
# Create a new TimedHashMarking # Creates token with +object+ as its value and adds it to the marking. # if no timestamp is given, current time will be used. def add(objects, timestamp = @time)
unless objects.kind_of? Array objects = [ objects ] end objects.each do |object| if object.instance_of? Hash timestamp = object[:ts] || 0 object = object[:val] end token = prepare_token(object, timestamp) timestamp = token.timestamp if timestamp > @time add_to_waiting token else add_token token end end end
wrzasa/fast-tcpn
b7e0b610163174208c21ea8565c4150a6f326124
lib/fast-tcpn/timed_hash_marking.rb
https://github.com/wrzasa/fast-tcpn/blob/b7e0b610163174208c21ea8565c4150a6f326124/lib/fast-tcpn/timed_hash_marking.rb#L44-L59
ruby
test
# Set current time for the marking. # This will cause moving tokens from waiting to active list. # Putting clock back will cause error.
def time=(time)
# Set current time for the marking. # This will cause moving tokens from waiting to active list. # Putting clock back will cause error. def time=(time)
if time < @time raise InvalidTime.new("You are trying to put back clock from #{@time} back to #{time}") end @time = time @waiting.keys.sort.each do |timestamp| if timestamp > @time @next_time = timestamp break end @waiting[timestamp].each { |token| add_token token } @waiting.delete timestamp end @next_time = 0 if @waiting.empty? @time end
dansimpson/em-ws-client
6499762a21ed3087ede7b99c6594ed83ae53d0f7
lib/em-ws-client/client.rb
https://github.com/dansimpson/em-ws-client/blob/6499762a21ed3087ede7b99c6594ed83ae53d0f7/lib/em-ws-client/client.rb#L209-L217
ruby
test
# Send a message to the remote host # # data - The string contents of your message # # Examples # # ws.onping do |data| # end # # Returns nothing
def send_message data, binary=false
# Send a message to the remote host # # data - The string contents of your message # # Examples # # ws.onping do |data| # end # # Returns nothing def send_message data, binary=false
if established? unless @closing @socket.send_data(@encoder.encode(data.to_s, binary ? BINARY_FRAME : TEXT_FRAME)) end else raise WebSocketError.new "can't send on a closed channel" end end
dansimpson/em-ws-client
6499762a21ed3087ede7b99c6594ed83ae53d0f7
lib/em-ws-client/client.rb
https://github.com/dansimpson/em-ws-client/blob/6499762a21ed3087ede7b99c6594ed83ae53d0f7/lib/em-ws-client/client.rb#L252-L281
ruby
test
# Internal: setup encoder/decoder and bind # to all decoder events.
def on_handshake_complete
# Internal: setup encoder/decoder and bind # to all decoder events. def on_handshake_complete
@decoder.onping do |data| @socket.send_data @encoder.pong(data) emit :ping, data end @decoder.onpong do |data| emit :pong, data end @decoder.onclose do |code| close code end @decoder.onframe do |frame, binary| emit :frame, frame, binary end @decoder.onerror do |code, message| close code, message emit :error, code, message end emit :open if @handshake.extra receive_message_data @handshake.extra end end
dansimpson/em-ws-client
6499762a21ed3087ede7b99c6594ed83ae53d0f7
lib/em-ws-client/client.rb
https://github.com/dansimpson/em-ws-client/blob/6499762a21ed3087ede7b99c6594ed83ae53d0f7/lib/em-ws-client/client.rb#L285-L290
ruby
test
# Internal: Connect to the remote host and synchonize the socket # and this client object
def connect
# Internal: Connect to the remote host and synchonize the socket # and this client object def connect
EM.connect @uri.host, @uri.port || 80, WebSocketConnection do |conn| conn.client = self conn.send_data(@handshake.request) end end
fun-ruby/ruby-meetup2
f6d54b1c6691def7228f400d935527bbbea07700
lib/api_key_client.rb
https://github.com/fun-ruby/ruby-meetup2/blob/f6d54b1c6691def7228f400d935527bbbea07700/lib/api_key_client.rb#L48-L52
ruby
test
# :nodoc:
def short_key
# :nodoc: def short_key
key = @@key return "" if key.nil? || key.empty? key[0..3] + "..." + key[(key.length - 4)..(key.length - 1)] end
fun-ruby/ruby-meetup2
f6d54b1c6691def7228f400d935527bbbea07700
lib/authenticated_client.rb
https://github.com/fun-ruby/ruby-meetup2/blob/f6d54b1c6691def7228f400d935527bbbea07700/lib/authenticated_client.rb#L31-L39
ruby
test
# == instance methods # Make a POST API call with the current path value and @options. # Return a JSON string if successful, otherwise an Exception # TODO - test AuthenticatedClient.post()
def post(options)
# == instance methods # Make a POST API call with the current path value and @options. # Return a JSON string if successful, otherwise an Exception # TODO - test AuthenticatedClient.post() def post(options)
uri = new_uri params = merge_params(options) response = Net::HTTP.post_form(uri, params) unless response.is_a?(Net::HTTPSuccess) raise "#{response.code} #{response.message}\n#{response.body}" end response.body end
fun-ruby/ruby-meetup2
f6d54b1c6691def7228f400d935527bbbea07700
lib/authenticated_client.rb
https://github.com/fun-ruby/ruby-meetup2/blob/f6d54b1c6691def7228f400d935527bbbea07700/lib/authenticated_client.rb#L50-L62
ruby
test
# Make a DELETE API call with the current path value and @options. # Return true if successful, otherwise an Exception # TODO - test AuthenticatedClient.delete()
def delete(options={})
# Make a DELETE API call with the current path value and @options. # Return true if successful, otherwise an Exception # TODO - test AuthenticatedClient.delete() def delete(options={})
uri = new_uri params = merge_params(options) uri.query = URI.encode_www_form(params) http = Net::HTTP.new(uri.host, uri.port) request = Net::HTTP::Delete.new(uri) # uri or uri.request_uri? response = http.request(request) unless response.is_a?(Net::HTTPSuccess) raise "#{response.code} #{response.message}\n#{response.body}" end true end
fun-ruby/ruby-meetup2
f6d54b1c6691def7228f400d935527bbbea07700
lib/authenticated_client.rb
https://github.com/fun-ruby/ruby-meetup2/blob/f6d54b1c6691def7228f400d935527bbbea07700/lib/authenticated_client.rb#L84-L88
ruby
test
# :nodoc:
def short_token
# :nodoc: def short_token
return "" if access_token.nil? || access_token.empty? access_token[0..3] + "..." + access_token[(access_token.length - 4)..(access_token.length - 1)] end
GeoffWilliams/vagrantomatic
9e249c8ea4a1dd7ccf127d8bfc3b5ee123c300b1
lib/vagrantomatic/vagrantomatic.rb
https://github.com/GeoffWilliams/vagrantomatic/blob/9e249c8ea4a1dd7ccf127d8bfc3b5ee123c300b1/lib/vagrantomatic/vagrantomatic.rb#L19-L33
ruby
test
# Return a has representing the named instance. This is suitable for Puppet # type and provider, or you can use the returned info for whatever you like
def instance_metadata(name)
# Return a has representing the named instance. This is suitable for Puppet # type and provider, or you can use the returned info for whatever you like def instance_metadata(name)
instance = instance(name) config = {} # annotate the raw config hash with data for puppet (and humans...) if instance.configured? config = instance.configfile_hash config["ensure"] = :present else # VM missing or damaged config["ensure"] = :absent end config["name"] = name config end
GeoffWilliams/vagrantomatic
9e249c8ea4a1dd7ccf127d8bfc3b5ee123c300b1
lib/vagrantomatic/vagrantomatic.rb
https://github.com/GeoffWilliams/vagrantomatic/blob/9e249c8ea4a1dd7ccf127d8bfc3b5ee123c300b1/lib/vagrantomatic/vagrantomatic.rb#L36-L49
ruby
test
# Return a hash of all instances
def instances_metadata()
# Return a hash of all instances def instances_metadata()
instance_wildcard = File.join(@vagrant_vm_dir, "*", ::Vagrantomatic::Instance::VAGRANTFILE) instances = {} Dir.glob(instance_wildcard).each { |f| elements = f.split(File::SEPARATOR) # /var/lib/vagrantomatic/mycoolvm/Vagrantfile # -----------------------^^^^^^^^------------ name = elements[elements.size - 2] instances[name] = instance_metadata(name) } instances end
gurgeous/scripto
e28792ca91dbb578725882799d76f82a64dfaa80
lib/scripto/csv_commands.rb
https://github.com/gurgeous/scripto/blob/e28792ca91dbb578725882799d76f82a64dfaa80/lib/scripto/csv_commands.rb#L9-L22
ruby
test
# Read a csv from +path+. Returns an array of Structs, using the keys from # the csv header row.
def csv_read(path)
# Read a csv from +path+. Returns an array of Structs, using the keys from # the csv header row. def csv_read(path)
lines = begin if path =~ /\.gz$/ Zlib::GzipReader.open(path) do |f| CSV.new(f).read end else CSV.read(path) end end keys = lines.shift.map(&:to_sym) klass = Struct.new(*keys) lines.map { |i| klass.new(*i) } end
gurgeous/scripto
e28792ca91dbb578725882799d76f82a64dfaa80
lib/scripto/csv_commands.rb
https://github.com/gurgeous/scripto/blob/e28792ca91dbb578725882799d76f82a64dfaa80/lib/scripto/csv_commands.rb#L28-L32
ruby
test
# Write +rows+ to +path+ as csv. Rows can be an array of hashes, Structs, # OpenStructs, or anything else that responds to to_h. The keys from the # first row are used as the csv header. If +cols+ is specified, it will be # used as the column keys instead.
def csv_write(path, rows, cols: nil)
# Write +rows+ to +path+ as csv. Rows can be an array of hashes, Structs, # OpenStructs, or anything else that responds to to_h. The keys from the # first row are used as the csv header. If +cols+ is specified, it will be # used as the column keys instead. def csv_write(path, rows, cols: nil)
atomic_write(path) do |tmp| CSV.open(tmp.path, "wb") { |f| csv_write0(f, rows, cols: cols) } end end
gurgeous/scripto
e28792ca91dbb578725882799d76f82a64dfaa80
lib/scripto/csv_commands.rb
https://github.com/gurgeous/scripto/blob/e28792ca91dbb578725882799d76f82a64dfaa80/lib/scripto/csv_commands.rb#L35-L37
ruby
test
# Write +rows+ to $stdout as a csv. Similar to csv_write.
def csv_to_stdout(rows, cols: nil)
# Write +rows+ to $stdout as a csv. Similar to csv_write. def csv_to_stdout(rows, cols: nil)
CSV($stdout) { |f| csv_write0(f, rows, cols: cols) } end
gurgeous/scripto
e28792ca91dbb578725882799d76f82a64dfaa80
lib/scripto/csv_commands.rb
https://github.com/gurgeous/scripto/blob/e28792ca91dbb578725882799d76f82a64dfaa80/lib/scripto/csv_commands.rb#L40-L45
ruby
test
# Returns a string containing +rows+ as a csv. Similar to csv_write.
def csv_to_s(rows, cols: nil)
# Returns a string containing +rows+ as a csv. Similar to csv_write. def csv_to_s(rows, cols: nil)
string = "" f = CSV.new(StringIO.new(string)) csv_write0(f, rows, cols: cols) string end
gurgeous/scripto
e28792ca91dbb578725882799d76f82a64dfaa80
lib/scripto/csv_commands.rb
https://github.com/gurgeous/scripto/blob/e28792ca91dbb578725882799d76f82a64dfaa80/lib/scripto/csv_commands.rb#L50-L60
ruby
test
# :nodoc:
def csv_write0(csv, rows, cols: nil) # cols
# :nodoc: def csv_write0(csv, rows, cols: nil) # cols
cols ||= rows.first.to_h.keys csv << cols # rows rows.each do |row| row = row.to_h csv << cols.map { |i| row[i] } end end
ChrisMacNaughton/rusty_json
4de69fc7a5d4cc61a8b96b8fe26a578449d26bde
lib/rusty_json/rust_struct.rb
https://github.com/ChrisMacNaughton/rusty_json/blob/4de69fc7a5d4cc61a8b96b8fe26a578449d26bde/lib/rusty_json/rust_struct.rb#L58-L74
ruby
test
# Add Value is how we add keys to the resulting Struct # We need a name and a type, and potentially a subtype # # For example: # types could be String, Fixnum, or Array # If the tyoe is Array, then we need the subtype of the array, # is it an array of integers or strings? # # @param name [String] what is this key in the struct # @param type [Class] What typs are we # @param subtype [Class] What typs are we # # @return true
def add_value(name, type, subtype = nil)
# Add Value is how we add keys to the resulting Struct # We need a name and a type, and potentially a subtype # # For example: # types could be String, Fixnum, or Array # If the tyoe is Array, then we need the subtype of the array, # is it an array of integers or strings? # # @param name [String] what is this key in the struct # @param type [Class] What typs are we # @param subtype [Class] What typs are we # # @return true def add_value(name, type, subtype = nil)
if type.class == RustyJson::RustStruct || subtype.class == RustyJson::RustStruct if type.class == RustyJson::RustStruct t = type type = type.name struct = t elsif subtype.class == RustyJson::RustStruct s = subtype subtype = subtype.name struct = s end @structs << struct RustStruct.add_type(struct.name, struct.name) end @values[name] = [type, subtype] true end
ChrisMacNaughton/rusty_json
4de69fc7a5d4cc61a8b96b8fe26a578449d26bde
lib/rusty_json/rust_struct.rb
https://github.com/ChrisMacNaughton/rusty_json/blob/4de69fc7a5d4cc61a8b96b8fe26a578449d26bde/lib/rusty_json/rust_struct.rb#L82-L100
ruby
test
# two Rust structs are equal if all of their keys / value types are the same # to_s controlls how to display the RustStruct as a Rust Struct
def to_s
# two Rust structs are equal if all of their keys / value types are the same # to_s controlls how to display the RustStruct as a Rust Struct def to_s
return '' if @printed @printed = true struct = required_structs members = @values.map do |key, value| type = RustStruct.type_name(value[0]) subtype = RustStruct.type_name(value[1]) # TODO: add option for pub / private # Will this be a per field thing that is configurable from # within the JSON or will it be configured on the parse command? member = " pub #{key}: #{type}" member << "<#{subtype}>" unless value[1].nil? member end struct << "pub struct #{@name} {\n" + members.join(",\n") + ",\n}\n\n" struct = struct.gsub("\n\n\n", "\n\n") reset if @root struct end
brookisme/ng_on_rails
34fa3756c9a7775981763e76bdf5b0607792476b
lib/generators/ng_on_rails/ng_on_rails_generator.rb
https://github.com/brookisme/ng_on_rails/blob/34fa3756c9a7775981763e76bdf5b0607792476b/lib/generators/ng_on_rails/ng_on_rails_generator.rb#L125-L144
ruby
test
# Thor Helpers
def option_copy_file from_path, to_path, file_type, template=false
# Thor Helpers def option_copy_file from_path, to_path, file_type, template=false
if File.exist?(to_path) if options[:overwrite] remove_file(to_path) if template template from_path, to_path else copy_file from_path, to_path end else puts "ERROR: Failed to #{template ? "template" : "copy"} #{file_type || 'file'}. #{to_path} exists. Delete file or use the --overwrite=true option when generating the layout" end else if template template from_path, to_path else copy_file from_path, to_path end end end
mikbe/widget
d998720847b337c9b68e4df6c994a322013647e2
lib/widget/widget_data.rb
https://github.com/mikbe/widget/blob/d998720847b337c9b68e4df6c994a322013647e2/lib/widget/widget_data.rb#L22-L28
ruby
test
# CRUD
def create(name)
# CRUD def create(name)
return false unless @widgets.where(name).empty? time_now = now @widgets.add(:name=>name, :created_at=>time_now, :modified_at=>time_now) save_widgets true end
galetahub/ballot_box
d9fa4e262f1f5f8107bb4148790bb0693a247032
lib/ballot_box/callbacks.rb
https://github.com/galetahub/ballot_box/blob/d9fa4e262f1f5f8107bb4148790bb0693a247032/lib/ballot_box/callbacks.rb#L22-L25
ruby
test
# A callback that runs before create vote # Example: # BallotBox::Manager.before_vote do |env, opts| # end
def before_vote(options = {}, method = :push, &block)
# A callback that runs before create vote # Example: # BallotBox::Manager.before_vote do |env, opts| # end def before_vote(options = {}, method = :push, &block)
raise BlockNotGiven unless block_given? _before_vote.send(method, [block, options]) end
galetahub/ballot_box
d9fa4e262f1f5f8107bb4148790bb0693a247032
lib/ballot_box/callbacks.rb
https://github.com/galetahub/ballot_box/blob/d9fa4e262f1f5f8107bb4148790bb0693a247032/lib/ballot_box/callbacks.rb#L38-L41
ruby
test
# A callback that runs after vote created # Example: # BallotBox::Manager.after_vote do |env, opts| # end
def after_vote(options = {}, method = :push, &block)
# A callback that runs after vote created # Example: # BallotBox::Manager.after_vote do |env, opts| # end def after_vote(options = {}, method = :push, &block)
raise BlockNotGiven unless block_given? _after_vote.send(method, [block, options]) end
maxivak/optimacms
1e71d98b67cfe06d977102823b296b3010b10a83
app/models/optimacms/page.rb
https://github.com/maxivak/optimacms/blob/1e71d98b67cfe06d977102823b296b3010b10a83/app/models/optimacms/page.rb#L97-L102
ruby
test
# content
def content(lang='')
# content def content(lang='')
filename = content_filename_full(lang) return nil if filename.nil? return '' if !File.exists? filename File.read(filename) end
maxivak/optimacms
1e71d98b67cfe06d977102823b296b3010b10a83
app/models/optimacms/page.rb
https://github.com/maxivak/optimacms/blob/1e71d98b67cfe06d977102823b296b3010b10a83/app/models/optimacms/page.rb#L166-L173
ruby
test
# search # =begin # def self.search_by_filter(filter) # pg = filter.page # #pg =1 if pg.nil? || pg<=0 # # order = filter.order # # if order.empty? # orderby = 'id' # orderdir = 'asc' # else # orderby = order[0][0] # orderdir = order[0][1] # end # # self.where(get_where(filter.data)) # .order(" #{orderby} #{orderdir}") # .page(pg) # # end # # def self.get_where(values) # w = '1=1 ' # #w << " AND uid like '#{values['uid']}%' " if values['uid'] && !values['uid'].blank? # v = values[:title] # w << " AND title like '%#{v}%' " if v && !v.blank? # # v = values[:parent_id] # w << " AND parent_id = '#{v}' " if !v!=-1 # # w # end # =end
def _before_save
# search # =begin # def self.search_by_filter(filter) # pg = filter.page # #pg =1 if pg.nil? || pg<=0 # # order = filter.order # # if order.empty? # orderby = 'id' # orderdir = 'asc' # else # orderby = order[0][0] # orderdir = order[0][1] # end # # self.where(get_where(filter.data)) # .order(" #{orderby} #{orderdir}") # .page(pg) # # end # # def self.get_where(values) # w = '1=1 ' # #w << " AND uid like '#{values['uid']}%' " if values['uid'] && !values['uid'].blank? # v = values[:title] # w << " AND title like '%#{v}%' " if v && !v.blank? # # v = values[:parent_id] # w << " AND parent_id = '#{v}' " if !v!=-1 # # w # end # =end def _before_save
if self.url_changed? self.url_parts_count = PageServices::PageRouteService.count_url_parts(self.url) self.url_vars_count = PageServices::PageRouteService::count_url_vars(self.url) self.parsed_url = PageServices::PageRouteService::parse_url(self.url) end end
dklisiaris/bookshark
0650c09a79e8aab56744503ae2260235b7b612ef
lib/bookshark.rb
https://github.com/dklisiaris/bookshark/blob/0650c09a79e8aab56744503ae2260235b7b612ef/lib/bookshark.rb#L139-L151
ruby
test
# def bibliographical_book(options = {}) # bibliographical_book_extractor = Biblionet::Extractors::BibliographicalBookExtractor.new # uri = "http://www.biblionet.gr/main.asp?page=results&Titlesid=#{options[:id]}" # options[:format] ||= @format # book = bibliographical_book_extractor.load_and_extract_book(uri) # response = {} # response[:book] = !book.nil? ? [book] : [] # response = change_format(response, options[:format]) # response = bibliographical_book_extractor.decode_text(response) # end # puts Bookshark::Extractor.new(format: 'pretty_json').bibliographical_book(id: 103788)
def category(options = {})
# def bibliographical_book(options = {}) # bibliographical_book_extractor = Biblionet::Extractors::BibliographicalBookExtractor.new # uri = "http://www.biblionet.gr/main.asp?page=results&Titlesid=#{options[:id]}" # options[:format] ||= @format # book = bibliographical_book_extractor.load_and_extract_book(uri) # response = {} # response[:book] = !book.nil? ? [book] : [] # response = change_format(response, options[:format]) # response = bibliographical_book_extractor.decode_text(response) # end # puts Bookshark::Extractor.new(format: 'pretty_json').bibliographical_book(id: 103788) def category(options = {})
uri = process_options(options, __method__) options[:format] ||= @format category_extractor = Biblionet::Extractors::CategoryExtractor.new category = category_extractor.extract_categories_from(uri) response = {} response[:category] = !category.nil? ? [category] : [] response = change_format(response, options[:format]) return response end
pricees/rodeo_clown
be0e60b0cb5901904a762429f256d420e31581f1
lib/rodeo_clown/elb.rb
https://github.com/pricees/rodeo_clown/blob/be0e60b0cb5901904a762429f256d420e31581f1/lib/rodeo_clown/elb.rb#L47-L55
ruby
test
# Rotate servers given
def rotate(hsh)
# Rotate servers given def rotate(hsh)
current_ec2, new_ec2 = hsh.first cur_instances = EC2.by_tags("Name" => current_ec2.to_s) new_instances = EC2.by_tags("Name" => new_ec2.to_s) register_and_wait new_instances deregister cur_instances end
pricees/rodeo_clown
be0e60b0cb5901904a762429f256d420e31581f1
lib/rodeo_clown/elb.rb
https://github.com/pricees/rodeo_clown/blob/be0e60b0cb5901904a762429f256d420e31581f1/lib/rodeo_clown/elb.rb#L60-L83
ruby
test
# Wait for all the instances to become InService
def wait_for_state(instances, exp_state)
# Wait for all the instances to become InService def wait_for_state(instances, exp_state)
time = 0 all_good = false loop do all_good = instances.all? do |i| state = i.elb_health[:state] puts "#{i.id}: #{state}" exp_state == state end break if all_good || time > timeout sleep 1 time += 1 end # If timeout before all inservice, deregister and raise error unless all_good raise "Instances are out of service" end end
pedrocr/ownet
a2543bcfe0cffbb52372397bd1d1d66651f1485e
lib/connection.rb
https://github.com/pedrocr/ownet/blob/a2543bcfe0cffbb52372397bd1d1d66651f1485e/lib/connection.rb#L199-L204
ruby
test
# Read a value from an OW path.
def read(path)
# Read a value from an OW path. def read(path)
owconnect do |socket| owwrite(socket,:path => path, :function => READ) return to_number(owread(socket).data) end end
pedrocr/ownet
a2543bcfe0cffbb52372397bd1d1d66651f1485e
lib/connection.rb
https://github.com/pedrocr/ownet/blob/a2543bcfe0cffbb52372397bd1d1d66651f1485e/lib/connection.rb#L207-L212
ruby
test
# Write a value to an OW path.
def write(path, value)
# Write a value to an OW path. def write(path, value)
owconnect do |socket| owwrite(socket, :path => path, :value => value.to_s, :function => WRITE) return owread(socket).return_value end end
pedrocr/ownet
a2543bcfe0cffbb52372397bd1d1d66651f1485e
lib/connection.rb
https://github.com/pedrocr/ownet/blob/a2543bcfe0cffbb52372397bd1d1d66651f1485e/lib/connection.rb#L215-L230
ruby
test
# List the contents of an OW path.
def dir(path)
# List the contents of an OW path. def dir(path)
owconnect do |socket| owwrite(socket,:path => path, :function => DIR) fields = [] while true response = owread(socket) if response.data fields << response.data else break end end return fields end end
praxis/praxis-mapper
f8baf44948943194f0e4acddd24aa168add60645
lib/praxis-mapper/query_statistics.rb
https://github.com/praxis/praxis-mapper/blob/f8baf44948943194f0e4acddd24aa168add60645/lib/praxis-mapper/query_statistics.rb#L10-L27
ruby
test
# sums up statistics across all queries, indexed by model
def sum_totals_by_model
# sums up statistics across all queries, indexed by model def sum_totals_by_model
@sum_totals_by_model ||= begin totals = Hash.new { |hash, key| hash[key] = Hash.new(0) } @queries_by_model.each do |model, queries| totals[model][:query_count] = queries.length queries.each do |query| query.statistics.each do |stat, value| totals[model][stat] += value end end totals[model][:datastore_interaction_time] = totals[model][:datastore_interaction_time] end totals end end
praxis/praxis-mapper
f8baf44948943194f0e4acddd24aa168add60645
lib/praxis-mapper/query_statistics.rb
https://github.com/praxis/praxis-mapper/blob/f8baf44948943194f0e4acddd24aa168add60645/lib/praxis-mapper/query_statistics.rb#L30-L42
ruby
test
# sums up statistics across all models and queries
def sum_totals
# sums up statistics across all models and queries def sum_totals
@sum_totals ||= begin totals = Hash.new(0) sum_totals_by_model.each do |_, model_totals| model_totals.each do |stat, value| totals[stat] += value end end totals end end
sixoverground/tang
66fff66d5abe03f5e69e98601346a88c71e54675
app/models/concerns/tang/customer.rb
https://github.com/sixoverground/tang/blob/66fff66d5abe03f5e69e98601346a88c71e54675/app/models/concerns/tang/customer.rb#L74-L84
ruby
test
# NOTE: May be causing memory bloat
def subscribed_to?(stripe_id)
# NOTE: May be causing memory bloat def subscribed_to?(stripe_id)
subscription_plan = self.subscription.plan if self.subscription.present? if subscription_plan.present? return true if subscription_plan.stripe_id == stripe_id if Tang.plan_inheritance other_plan = Plan.find_by(stripe_id: stripe_id) return true if other_plan.present? && subscription_plan.order >= other_plan.order end end return false end
cdunn/toy-dynamo
d105a3036b83b89769b18176567c4c704f08939a
lib/toy/dynamo/attributes.rb
https://github.com/cdunn/toy-dynamo/blob/d105a3036b83b89769b18176567c4c704f08939a/lib/toy/dynamo/attributes.rb#L11-L26
ruby
test
# [OVERRIDE] 'write_attribute' to account for setting hash_key and id to same value # u.id = 1 # * set id to 1 # * set hash_key to 1 # u.hash_key = 2 # * set hash_key to 2 # * set id to 2
def write_attribute(key, value)
# [OVERRIDE] 'write_attribute' to account for setting hash_key and id to same value # u.id = 1 # * set id to 1 # * set hash_key to 1 # u.hash_key = 2 # * set hash_key to 2 # * set id to 2 def write_attribute(key, value)
key = key.to_s attribute = attribute_instance(key) if self.class.dynamo_table.hash_key[:attribute_name] != "id" # If primary hash_key is not the standard `id` if key == self.class.dynamo_table.hash_key[:attribute_name] @attributes[key] = attribute_instance(key).from_store(value) return @attributes["id"] = attribute_instance("id").from_store(value) elsif key == "id" @attributes["id"] = attribute_instance("id").from_store(value) return @attributes[self.class.dynamo_table.hash_key[:attribute_name]] = attribute_instance(self.class.dynamo_table.hash_key[:attribute_name]).from_store(value) end end @attributes[key] = attribute.from_store(value) end
glebtv/mongoid_time_field
c446e255dea72061250c989f2281093959a23931
lib/mongoid_time_field/value.rb
https://github.com/glebtv/mongoid_time_field/blob/c446e255dea72061250c989f2281093959a23931/lib/mongoid_time_field/value.rb#L72-L93
ruby
test
# source: https://github.com/arnau/ISO8601/blob/master/lib/iso8601/duration.rb (MIT)
def iso8601
# source: https://github.com/arnau/ISO8601/blob/master/lib/iso8601/duration.rb (MIT) def iso8601
duration = @seconds sign = '-' if (duration < 0) duration = duration.abs years, y_mod = (duration / YEARS_FACTOR).to_i, (duration % YEARS_FACTOR) months, m_mod = (y_mod / MONTHS_FACTOR).to_i, (y_mod % MONTHS_FACTOR) days, d_mod = (m_mod / 86400).to_i, (m_mod % 86400) hours, h_mod = (d_mod / 3600).to_i, (d_mod % 3600) minutes, mi_mod = (h_mod / 60).to_i, (h_mod % 60) seconds = mi_mod.div(1) == mi_mod ? mi_mod.to_i : mi_mod.to_f # Coerce to Integer when needed (`PT1S` instead of `PT1.0S`) seconds = (seconds != 0 or (years == 0 and months == 0 and days == 0 and hours == 0 and minutes == 0)) ? "#{seconds}S" : "" minutes = (minutes != 0) ? "#{minutes}M" : "" hours = (hours != 0) ? "#{hours}H" : "" days = (days != 0) ? "#{days}D" : "" months = (months != 0) ? "#{months}M" : "" years = (years != 0) ? "#{years}Y" : "" date = %[#{sign}P#{years}#{months}#{days}] time = (hours != "" or minutes != "" or seconds != "") ? %[T#{hours}#{minutes}#{seconds}] : "" date + time end
craigw/tai64
df5a0a843e1952172b59456ad260c7593a12c08f
lib/tai64.rb
https://github.com/craigw/tai64/blob/df5a0a843e1952172b59456ad260c7593a12c08f/lib/tai64.rb#L61-L70
ruby
test
# Warning, this will probably gain inappropriate accuracy - Ruby does not # support the same level of timing accuracy as TAI64N and TA64NA can # provide.
def to_label
# Warning, this will probably gain inappropriate accuracy - Ruby does not # support the same level of timing accuracy as TAI64N and TA64NA can # provide. def to_label
s = '%016x%08x' sec = tai_second ts = if sec >= 0 sec + EPOCH else EPOCH - sec end Label.new s % [ ts, tai_nanosecond ] end
dcrosby42/conject
df4b89ac97f65c6334db46b4652bfa6ae0a7446e
lib/conject/object_context.rb
https://github.com/dcrosby42/conject/blob/df4b89ac97f65c6334db46b4652bfa6ae0a7446e/lib/conject/object_context.rb#L12-L17
ruby
test
# Inject a named object into this context
def put(name, object)
# Inject a named object into this context def put(name, object)
raise "This ObjectContext already has an instance or configuration for '#{name.to_s}'" if directly_has?(name) Conject.install_object_context(object, self) object.instance_variable_set(:@_conject_contextual_name, name.to_s) @cache[name.to_sym] = object end
dcrosby42/conject
df4b89ac97f65c6334db46b4652bfa6ae0a7446e
lib/conject/object_context.rb
https://github.com/dcrosby42/conject/blob/df4b89ac97f65c6334db46b4652bfa6ae0a7446e/lib/conject/object_context.rb#L25-L37
ruby
test
# Retrieve a named object from this context. # If the object is already existant in this context, return it. # If we have a parent context and it contains the requested object, get and return object from parent context. (Recursive upward search) # If the object exists nowhere in this or a super context: construct, cache and return a new instance of the requested object using the object factory.
def get(name)
# Retrieve a named object from this context. # If the object is already existant in this context, return it. # If we have a parent context and it contains the requested object, get and return object from parent context. (Recursive upward search) # If the object exists nowhere in this or a super context: construct, cache and return a new instance of the requested object using the object factory. def get(name)
name = name.to_sym return @cache[name] if @cache.keys.include?(name) if !has_config?(name) and parent_context and parent_context.has?(name) return parent_context.get(name) else object = object_factory.construct_new(name,self) object.instance_variable_set(:@_conject_contextual_name, name.to_s) @cache[name] = object unless no_cache?(name) return object end end
dcrosby42/conject
df4b89ac97f65c6334db46b4652bfa6ae0a7446e
lib/conject/object_context.rb
https://github.com/dcrosby42/conject/blob/df4b89ac97f65c6334db46b4652bfa6ae0a7446e/lib/conject/object_context.rb#L73-L79
ruby
test
# Allow configuration options to be set for named objects.
def configure_objects(confs={})
# Allow configuration options to be set for named objects. def configure_objects(confs={})
confs.each do |key,opts| key = key.to_sym @object_configs[key] ={} unless has_config?(key) @object_configs[key].merge!(opts) end end
robertwahler/revenc
8b0ad162d916a239c4507b93cc8e5530f38d8afb
features/support/aruba.rb
https://github.com/robertwahler/revenc/blob/8b0ad162d916a239c4507b93cc8e5530f38d8afb/features/support/aruba.rb#L12-L19
ruby
test
# override aruba
def run_simple(cmd, fail_on_error=true) # run development version in verbose mode
# override aruba def run_simple(cmd, fail_on_error=true) # run development version in verbose mode
cmd = cmd.gsub(/^revenc/, "ruby -S #{APP_BIN_PATH} --verbose") # run original aruba 'run' old_run_simple(cmd, fail_on_error) end
beco-ippei/docomo-api-ruby
58cc97cda84daf7125d87ea61a99da92634d5f3e
lib/docomo_api/dialogue.rb
https://github.com/beco-ippei/docomo-api-ruby/blob/58cc97cda84daf7125d87ea61a99da92634d5f3e/lib/docomo_api/dialogue.rb#L22-L34
ruby
test
# call api
def talk(msg)
# call api def talk(msg)
response = @http.start do |h| res = h.request(request(msg)) JSON.parse(res.body) end if err = response['requestError'] raise err.inspect end @context = response['context'] response['utt'] end
xlymian/hansel
f8a07b3a7b3a5e3659944cfafc3de7fcf08f9a04
lib/hansel/httperf/httperf.rb
https://github.com/xlymian/hansel/blob/f8a07b3a7b3a5e3659944cfafc3de7fcf08f9a04/lib/hansel/httperf/httperf.rb#L20-L40
ruby
test
# Runs httperf with a given request rate. Parses the output and returns # a hash with the results.
def httperf warm_up = false
# Runs httperf with a given request rate. Parses the output and returns # a hash with the results. def httperf warm_up = false
httperf_cmd = build_httperf_cmd if warm_up # Do a warm up run to setup any resources status "\n#{httperf_cmd} (warm up run)" IO.popen("#{httperf_cmd} 2>&1") else IO.popen("#{httperf_cmd} 2>&1") do |pipe| status "\n#{httperf_cmd}" @results << (httperf_result = HttperfResult.new({ :rate => @current_rate, :server => @current_job.server, :port => @current_job.port, :uri => @current_job.uri, :num_conns => @current_job.num_conns, :description => @current_job.description })) HttperfResultParser.new(pipe).parse(httperf_result) end end end
bjjb/sfkb
a0bc802c08fed3d246090d2c73fdb5a199d4e2cf
lib/sfkb/rest.rb
https://github.com/bjjb/sfkb/blob/a0bc802c08fed3d246090d2c73fdb5a199d4e2cf/lib/sfkb/rest.rb#L26-L31
ruby
test
# Converts a path and params to a Salesforce-suitable URL.
def url(path, params = {})
# Converts a path and params to a Salesforce-suitable URL. def url(path, params = {})
params = params.inject({}, &@@stringify) path = path.gsub(@@placeholder) { params.delete($1, &@@required) } params = params.inject('', &@@parameterize) [path, params].reject(&:nil?).reject(&:empty?).join('?') end
bjjb/sfkb
a0bc802c08fed3d246090d2c73fdb5a199d4e2cf
lib/sfkb/rest.rb
https://github.com/bjjb/sfkb/blob/a0bc802c08fed3d246090d2c73fdb5a199d4e2cf/lib/sfkb/rest.rb#L46-L49
ruby
test
# endpoint takes a map, and for eack key/value pair, adds a singleton # method to the map which will fetch that resource (if it looks like a # URL).
def endpoint(map)
# endpoint takes a map, and for eack key/value pair, adds a singleton # method to the map which will fetch that resource (if it looks like a # URL). def endpoint(map)
map.each { |k, v| apply_endpoint(map, k, v) } map end
bjjb/sfkb
a0bc802c08fed3d246090d2c73fdb5a199d4e2cf
lib/sfkb/rest.rb
https://github.com/bjjb/sfkb/blob/a0bc802c08fed3d246090d2c73fdb5a199d4e2cf/lib/sfkb/rest.rb#L53-L59
ruby
test
# applies an endpoint to obj, named k, which fetches v and makes it an # endpoint if it looks like a URL
def apply_endpoint(obj, k, v)
# applies an endpoint to obj, named k, which fetches v and makes it an # endpoint if it looks like a URL def apply_endpoint(obj, k, v)
α = -> { endpoint(get(v).body) } β = -> { v } λ = url?(v) ? -> { α.call } : -> { β.call } obj.define_singleton_method(k, &λ) if url?(v) obj end
bjjb/sfkb
a0bc802c08fed3d246090d2c73fdb5a199d4e2cf
lib/sfkb/rest.rb
https://github.com/bjjb/sfkb/blob/a0bc802c08fed3d246090d2c73fdb5a199d4e2cf/lib/sfkb/rest.rb#L62-L66
ruby
test
# Identifies a valid URL for this REST instance
def url?(string)
# Identifies a valid URL for this REST instance def url?(string)
return false unless string.to_s =~ url_pattern return false if string.to_s =~ @@placeholder true end
averell23/assit
4daf03ddfcbfead42d1f639bd4c70bcde0ec1bab
lib/assit/assertions.rb
https://github.com/averell23/assit/blob/4daf03ddfcbfead42d1f639bd4c70bcde0ec1bab/lib/assit/assertions.rb#L12-L17
ruby
test
# Assert if two objects are equal
def assit_equal(expected, actual, message = "Object expected to be equal")
# Assert if two objects are equal def assit_equal(expected, actual, message = "Object expected to be equal")
if(expected != actual) message << " expected #{expected} but was #{actual}" assit(false, message) end end
averell23/assit
4daf03ddfcbfead42d1f639bd4c70bcde0ec1bab
lib/assit/assertions.rb
https://github.com/averell23/assit/blob/4daf03ddfcbfead42d1f639bd4c70bcde0ec1bab/lib/assit/assertions.rb#L20-L25
ruby
test
# Assert if something is of the right type
def assit_kind_of(klass, object, message = "Object of wrong type")
# Assert if something is of the right type def assit_kind_of(klass, object, message = "Object of wrong type")
if(!object.kind_of?(klass)) message << " (Expected #{klass} but was #{object.class})" assit(false, message) end end
averell23/assit
4daf03ddfcbfead42d1f639bd4c70bcde0ec1bab
lib/assit/assertions.rb
https://github.com/averell23/assit/blob/4daf03ddfcbfead42d1f639bd4c70bcde0ec1bab/lib/assit/assertions.rb#L37-L47
ruby
test
# Duck typing assertion: This checks if the given object responds to the # given method calls. This won't detect any calls that will be handled # through method_missing, of course. # # Methods can be a single method name, or an Enumerable with multiple names
def assit_quack(object, methods, message = "Quack assert failed.")
# Duck typing assertion: This checks if the given object responds to the # given method calls. This won't detect any calls that will be handled # through method_missing, of course. # # Methods can be a single method name, or an Enumerable with multiple names def assit_quack(object, methods, message = "Quack assert failed.")
unless(methods.kind_of?(Enumerable)) methods = [methods] end methods.each do |method| unless(object.respond_to?(method.to_sym)) assit(false, "#{message} - Method: #{method.to_s}") end end end
averell23/assit
4daf03ddfcbfead42d1f639bd4c70bcde0ec1bab
lib/assit/assertions.rb
https://github.com/averell23/assit/blob/4daf03ddfcbfead42d1f639bd4c70bcde0ec1bab/lib/assit/assertions.rb#L51-L55
ruby
test
# Asserts that the given element is a string that is not nil and not an # empty string, or a string only containing whitspaces
def assit_real_string(object, message = "Not a non-empty string.")
# Asserts that the given element is a string that is not nil and not an # empty string, or a string only containing whitspaces def assit_real_string(object, message = "Not a non-empty string.")
unless(object && object.kind_of?(String) && object.strip != "") assit(false, message) end end
averell23/assit
4daf03ddfcbfead42d1f639bd4c70bcde0ec1bab
lib/assit/assertions.rb
https://github.com/averell23/assit/blob/4daf03ddfcbfead42d1f639bd4c70bcde0ec1bab/lib/assit/assertions.rb#L64-L67
ruby
test
# Executes the given block and asserts if the result is true. This allows # you to assert on complex, custom expressions and be able to disable # those expressions together with the assertions. See the README for more. # # The block will be passed a single array, to which error messages can be # append. The assertion will always fail if an error is appended to the # array.
def assit_block(&block)
# Executes the given block and asserts if the result is true. This allows # you to assert on complex, custom expressions and be able to disable # those expressions together with the assertions. See the README for more. # # The block will be passed a single array, to which error messages can be # append. The assertion will always fail if an error is appended to the # array. def assit_block(&block)
errors = [] assit((block.call(errors) && errors.size == 0), errors.join(', ')) end
griffinmyers/hemingway
65d876d7b85a2d8c3ca28f1e2b9bd1f293162ace
lib/hemingway/latex_nodes.rb
https://github.com/griffinmyers/hemingway/blob/65d876d7b85a2d8c3ca28f1e2b9bd1f293162ace/lib/hemingway/latex_nodes.rb#L27-L40
ruby
test
# I'm passing in a time variable here to make links unique. You see, # if you parse many of these entries on a single HTML page you'll end up # with multiple #footnote1 divs. To make them unique, we'll pass down # a time variable from above to seed them.
def html(footnote_seed, time)
# I'm passing in a time variable here to make links unique. You see, # if you parse many of these entries on a single HTML page you'll end up # with multiple #footnote1 divs. To make them unique, we'll pass down # a time variable from above to seed them. def html(footnote_seed, time)
paragraph_content = sequence.elements.map do |element| if element.respond_to?(:footnote_html) footnote_seed += 1 element.html(footnote_seed, time) elsif element.respond_to?(:newline) element.newline.html else element.html end end.join Build.tag("p", paragraph_content) end
griffinmyers/hemingway
65d876d7b85a2d8c3ca28f1e2b9bd1f293162ace
lib/hemingway/latex_nodes.rb
https://github.com/griffinmyers/hemingway/blob/65d876d7b85a2d8c3ca28f1e2b9bd1f293162ace/lib/hemingway/latex_nodes.rb#L46-L55
ruby
test
# I'm passing in a time variable here to make links unique. You see, # if you parse many of these entries on a single HTML page you'll end up # with multiple #footnote1 divs. To make them unique, we'll pass down # a time variable from above to seed them.
def footnote_html(footnote_seed, time)
# I'm passing in a time variable here to make links unique. You see, # if you parse many of these entries on a single HTML page you'll end up # with multiple #footnote1 divs. To make them unique, we'll pass down # a time variable from above to seed them. def footnote_html(footnote_seed, time)
footnote_content = sequence.elements.reduce([]) do |memo, element| if element.respond_to?(:footnote_html) footnote_seed += 1 memo + [element.footnote_html(footnote_seed, time)] else memo end end end
woto/ckpages
c258fe291e6215d72904dc71b7cf60f17e7dbdd4
app/controllers/ckpages/uploads_controller.rb
https://github.com/woto/ckpages/blob/c258fe291e6215d72904dc71b7cf60f17e7dbdd4/app/controllers/ckpages/uploads_controller.rb#L15-L26
ruby
test
# POST /uploads
def create
# POST /uploads def create
@upload = Upload.new(upload_params) #{"fileName":"image(13).png","uploaded":1,"url":"\/ckfinder\/userfiles\/files\/image(13).png","error":{"number":201,"message":"A file with the same name is already available. The uploaded file was renamed to \"image(13).png\"."}} @upload.save respond_to do |format| format.json { render plain: {fileName: @upload.file.filename, uploaded: 1, url: @upload.file.url}.to_json } end end
jmcaffee/qbt_client
1e34d86c9ffc2e06fb7f0723fea13ba4596a1054
lib/qbt_client/web_ui.rb
https://github.com/jmcaffee/qbt_client/blob/1e34d86c9ffc2e06fb7f0723fea13ba4596a1054/lib/qbt_client/web_ui.rb#L49-L68
ruby
test
# constructor # # # Authenticate with the server # # Login with username and password. # Store returned SID cookie value used as auth token for later calls.
def authenticate
# constructor # # # Authenticate with the server # # Login with username and password. # Store returned SID cookie value used as auth token for later calls. def authenticate
options = { body: "username=#{@user}&password=#{@pass}" } # Have to clear out the cookies or the old SID gets sent while requesting # the new SID (and it fails). self.class.cookies.clear res = self.class.post('/login', options) if res.success? token = res.headers["Set-Cookie"] raise QbtClientError.new("Login failed: no SID (cookie) returned") if token.nil? token = token.split(";")[0] @sid = token else raise QbtClientError.new(res) end end
jmcaffee/qbt_client
1e34d86c9ffc2e06fb7f0723fea13ba4596a1054
lib/qbt_client/web_ui.rb
https://github.com/jmcaffee/qbt_client/blob/1e34d86c9ffc2e06fb7f0723fea13ba4596a1054/lib/qbt_client/web_ui.rb#L146-L162
ruby
test
# Polls the client for incremental changes. # # @param interval Update interval in seconds. # # @yield [Hash] the return result of #sync.
def poll interval: 10, &block
# Polls the client for incremental changes. # # @param interval Update interval in seconds. # # @yield [Hash] the return result of #sync. def poll interval: 10, &block
raise '#poll requires a block' unless block_given? response_id = 0 loop do res = self.sync response_id if res response_id = res['rid'] yield res end sleep interval end end
jmcaffee/qbt_client
1e34d86c9ffc2e06fb7f0723fea13ba4596a1054
lib/qbt_client/web_ui.rb
https://github.com/jmcaffee/qbt_client/blob/1e34d86c9ffc2e06fb7f0723fea13ba4596a1054/lib/qbt_client/web_ui.rb#L172-L180
ruby
test
# Requests partial data from the client. # # @param response_id [Integer] Response ID. Used to keep track of what has # already been sent by qBittorrent. # # @return [Hash, nil] parsed json data on success, nil otherwise # # @note Read more about `response_id` at https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-Documentation#get-partial-data
def sync response_id = 0
# Requests partial data from the client. # # @param response_id [Integer] Response ID. Used to keep track of what has # already been sent by qBittorrent. # # @return [Hash, nil] parsed json data on success, nil otherwise # # @note Read more about `response_id` at https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-Documentation#get-partial-data def sync response_id = 0
req = self.class.get '/sync/maindata', format: :json, query: { rid: response_id } res = req.parsed_response if req.success? return res end end
jmcaffee/qbt_client
1e34d86c9ffc2e06fb7f0723fea13ba4596a1054
lib/qbt_client/web_ui.rb
https://github.com/jmcaffee/qbt_client/blob/1e34d86c9ffc2e06fb7f0723fea13ba4596a1054/lib/qbt_client/web_ui.rb#L254-L265
ruby
test
# Add one or more trackers to a torrent # # If passing mulitple urls, pass them as an array.
def add_trackers torrent_hash, urls
# Add one or more trackers to a torrent # # If passing mulitple urls, pass them as an array. def add_trackers torrent_hash, urls
urls = Array(urls) # Ampersands in urls must be escaped. urls = urls.map { |url| url.gsub('&', '%26') } urls = urls.join('%0A') options = { body: "hash=#{torrent_hash}&urls=#{urls}" } self.class.post('/command/addTrackers', options) end
jmcaffee/qbt_client
1e34d86c9ffc2e06fb7f0723fea13ba4596a1054
lib/qbt_client/web_ui.rb
https://github.com/jmcaffee/qbt_client/blob/1e34d86c9ffc2e06fb7f0723fea13ba4596a1054/lib/qbt_client/web_ui.rb#L439-L448
ruby
test
# Begin downloading one or more torrents. # # If passing mulitple urls, pass them as an array.
def download urls
# Begin downloading one or more torrents. # # If passing mulitple urls, pass them as an array. def download urls
urls = Array(urls) urls = urls.join('%0A') options = { body: "urls=#{urls}" } self.class.post('/command/download', options) end
jmcaffee/qbt_client
1e34d86c9ffc2e06fb7f0723fea13ba4596a1054
lib/qbt_client/web_ui.rb
https://github.com/jmcaffee/qbt_client/blob/1e34d86c9ffc2e06fb7f0723fea13ba4596a1054/lib/qbt_client/web_ui.rb#L455-L464
ruby
test
# Delete one or more torrents AND THEIR DATA # # If passing multiple torrent hashes, pass them as an array.
def delete_torrent_and_data torrent_hashes
# Delete one or more torrents AND THEIR DATA # # If passing multiple torrent hashes, pass them as an array. def delete_torrent_and_data torrent_hashes
torrent_hashes = Array(torrent_hashes) torrent_hashes = torrent_hashes.join('|') options = { body: "hashes=#{torrent_hashes}" } self.class.post('/command/deletePerm', options) end
jmcaffee/qbt_client
1e34d86c9ffc2e06fb7f0723fea13ba4596a1054
lib/qbt_client/web_ui.rb
https://github.com/jmcaffee/qbt_client/blob/1e34d86c9ffc2e06fb7f0723fea13ba4596a1054/lib/qbt_client/web_ui.rb#L471-L480
ruby
test
# Delete one or more torrents (doesn't delete their data) # # If passing multiple torrent hashes, pass them as an array.
def delete torrent_hashes
# Delete one or more torrents (doesn't delete their data) # # If passing multiple torrent hashes, pass them as an array. def delete torrent_hashes
torrent_hashes = Array(torrent_hashes) torrent_hashes = torrent_hashes.join('|') options = { body: "hashes=#{torrent_hashes}" } self.class.post('/command/delete', options) end