repository_name
stringlengths
7
56
func_path_in_repository
stringlengths
10
101
func_name
stringlengths
12
78
language
stringclasses
1 value
func_code_string
stringlengths
74
11.9k
func_documentation_string
stringlengths
3
8.03k
split_name
stringclasses
1 value
func_code_url
stringlengths
98
213
enclosing_scope
stringlengths
42
98.2k
dennmart/wanikani-gem
lib/wanikani/client.rb
Wanikani.Client.api_response
ruby
def api_response(resource, optional_arg = nil) raise ArgumentError, "You must define a resource to query WaniKani" if resource.nil? || resource.empty? begin res = client.get("/api/#{@api_version}/user/#{@api_key}/#{resource}/#{optional_arg}") if !res.success? || res.body.has_key?("error") ...
Contacts the WaniKani API and returns the data specified. @param resource [String] the resource to access. @param optional_arg [String] optional arguments for the specified resource. @return [Hash] the parsed API response.
train
https://github.com/dennmart/wanikani-gem/blob/70f9e4289f758c9663c0ee4d1172acb711487df9/lib/wanikani/client.rb#L79-L93
class Client include Wanikani::User include Wanikani::StudyQueue include Wanikani::Level include Wanikani::SRS include Wanikani::RecentUnlocks include Wanikani::CriticalItems attr_accessor :api_key, :api_version # Initialize a client which will be used to communicate with WaniKani. ...
chicks/sugarcrm
lib/sugarcrm/connection/api/get_relationships.rb
SugarCRM.Connection.get_relationships
ruby
def get_relationships(module_name, id, related_to, opts={}) login! unless logged_in? options = { :query => '', :fields => [], :link_fields => [], :related_fields => [], :deleted => 0 }.merge! opts json = <<-EOF { "session": "#{@sugar_session_id}", ...
Retrieves a collection of beans that are related to the specified bean and, optionally, returns relationship data Ajay Singh --> changed as per our equirment. "related_fields": #{resolve_related_fields(module_name, related_to)},
train
https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/connection/api/get_relationships.rb#L8-L33
module SugarCRM; class Connection # Retrieves a collection of beans that are related # to the specified bean and, optionally, returns # relationship data # Ajay Singh --> changed as per our equirment. # "related_fields": #{resolve_related_fields(module_name, related_to)}, alias :get_relationship :get_rel...
state-machines/state_machines
lib/state_machines/machine.rb
StateMachines.Machine.event
ruby
def event(*names, &block) options = names.last.is_a?(Hash) ? names.pop : {} options.assert_valid_keys(:human_name) # Store the context so that it can be used for / matched against any event # that gets added @events.context(names, &block) if block_given? if names.first.is_a?(Matche...
Defines one or more events for the machine and the transitions that can be performed when those events are run. This method is also aliased as +on+ for improved compatibility with using a domain-specific language. Configuration options: * <tt>:human_name</tt> - The human-readable version of this event's name. ...
train
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L1307-L1333
class Machine include EvalHelpers include MatcherHelpers class << self # Attempts to find or create a state machine for the given class. For # example, # # StateMachines::Machine.find_or_create(Vehicle) # StateMachines::Machine.find_or_create(Vehicle, :initial => :par...
dmitrizagidulin/riagent
lib/riagent/persistence.rb
Riagent.Persistence.save
ruby
def save(options={:validate => true}) context = self.new_record? ? :create : :update return false if options[:validate] && !valid?(context) run_callbacks(context) do if context == :create key = self.class.persistence.insert(self) else key = self.class.persist...
Performs validations and saves the document The validation process can be skipped by passing <tt>validate: false</tt>. Also triggers :before_create / :after_create type callbacks @return [String] Returns the key for the inserted document
train
https://github.com/dmitrizagidulin/riagent/blob/074bbb9c354abc1ba2037d704b0706caa3f34f37/lib/riagent/persistence.rb#L56-L69
module Persistence extend ActiveSupport::Concern COLLECTION_TYPES = [:riak_kv] # Key Listing strategies for +:riak_kv+ collections VALID_KEY_LISTS = [:streaming_list_keys, :riak_dt_set] included do extend ActiveModel::Callbacks define_model_callbacks :create, :update, :...
kontena/kontena
agent/lib/kontena/observer.rb
Kontena.Observer.error
ruby
def error @values.each_pair{|observable, value| return Error.new(observable, value) if Exception === value } return nil end
Return Error for first crashed observable. Should only be used if error? @return [Exception, nil]
train
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/observer.rb#L290-L295
class Observer include Kontena::Logging attr_reader :logging_prefix # customize Kontena::Logging#logging_prefix by instance class Error < StandardError attr_reader :observable, :cause def initialize(observable, cause) super(cause.message) @observable = observable @ca...
sup-heliotrope/sup
lib/sup/modes/thread_index_mode.rb
Redwood.ThreadIndexMode.actually_toggle_spammed
ruby
def actually_toggle_spammed t thread = t if t.has_label? :spam t.remove_label :spam add_or_unhide t.first UpdateManager.relay self, :unspammed, t.first lambda do thread.apply_label :spam self.hide_thread thread UpdateManager.relay self,:spammed, thread.first ...
returns an undo lambda
train
https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/modes/thread_index_mode.rb#L353-L374
class ThreadIndexMode < LineCursorMode DATE_WIDTH = Time::TO_NICE_S_MAX_LEN MIN_FROM_WIDTH = 15 LOAD_MORE_THREAD_NUM = 20 HookManager.register "index-mode-size-widget", <<EOS Generates the per-thread size widget for each thread. Variables: thread: The message thread to be formatted. EOS HookManager.regist...
weshatheleopard/rubyXL
lib/rubyXL/objects/ooxml_object.rb
RubyXL.OOXMLObjectInstanceMethods.write_xml
ruby
def write_xml(xml = nil, node_name_override = nil) if xml.nil? then seed_xml = Nokogiri::XML('<?xml version = "1.0" standalone ="yes"?>') seed_xml.encoding = 'UTF-8' result = self.write_xml(seed_xml) return result if result == '' seed_xml << result return seed_xml.t...
Recursively write the OOXML object and all its children out as Nokogiri::XML. Immediately before the actual generation, +before_write_xml()+ is called to perform last-minute cleanup and validation operations; if it returns +false+, an empty string is returned (rather than +nil+, so Nokogiri::XML's <tt>&lt;&lt;</tt> o...
train
https://github.com/weshatheleopard/rubyXL/blob/e61d78de9486316cdee039d3590177dc05db0f0c/lib/rubyXL/objects/ooxml_object.rb#L269-L327
module OOXMLObjectInstanceMethods attr_accessor :local_namespaces def self.included(klass) klass.extend RubyXL::OOXMLObjectClassMethods end def obtain_class_variable(var_name, default = {}) self.class.obtain_class_variable(var_name, default) end private :obtain_class_variable ...
amatsuda/active_decorator
lib/active_decorator/decorator.rb
ActiveDecorator.Decorator.decorate_association
ruby
def decorate_association(owner, target) owner.is_a?(ActiveDecorator::Decorated) ? decorate(target) : target end
Decorates AR model object's association only when the object was decorated. Returns the association instance.
train
https://github.com/amatsuda/active_decorator/blob/e7cfa764e657ea8bbb4cbe92cb220ee67ebae58e/lib/active_decorator/decorator.rb#L61-L63
class Decorator include Singleton def initialize @@decorators = {} end # Decorates the given object. # Plus, performs special decoration for the classes below: # Array: decorates its each element # Hash: decorates its each value # AR::Relation: decorates its each record l...
jhund/filterrific
lib/filterrific/action_view_extension.rb
Filterrific.ActionViewExtension.form_for_filterrific
ruby
def form_for_filterrific(record, options = {}, &block) options[:as] ||= :filterrific options[:html] ||= {} options[:html][:method] ||= :get options[:html][:id] ||= :filterrific_filter options[:url] ||= url_for( :controller => controller.controller_name, :action => controlle...
Sets all options on form_for to defaults that work with Filterrific @param record [Filterrific] the @filterrific object @param options [Hash] standard options for form_for @param block [Proc] the form body
train
https://github.com/jhund/filterrific/blob/811edc57d3e2a3e538c1f0e9554e0909be052881/lib/filterrific/action_view_extension.rb#L14-L24
module ActionViewExtension include HasResetFilterrificUrlMixin # Sets all options on form_for to defaults that work with Filterrific # @param record [Filterrific] the @filterrific object # @param options [Hash] standard options for form_for # @param block [Proc] the form body # Renders a s...
hashicorp/vagrant
lib/vagrant/environment.rb
Vagrant.Environment.active_machines
ruby
def active_machines # We have no active machines if we have no data path return [] if !@local_data_path machine_folder = @local_data_path.join("machines") # If the machine folder is not a directory then we just return # an empty array since no active machines exist. return [] if !m...
Returns a list of machines that this environment is currently managing that physically have been created. An "active" machine is a machine that Vagrant manages that has been created. The machine itself may be in any state such as running, suspended, etc. but if a machine is "active" then it exists. Note that the...
train
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/environment.rb#L233-L265
class Environment # This is the current version that this version of Vagrant is # compatible with in the home directory. # # @return [String] CURRENT_SETUP_VERSION = "1.5" DEFAULT_LOCAL_DATA = ".vagrant" # The `cwd` that this environment represents attr_reader :cwd # The persist...
enkessler/cuke_modeler
lib/cuke_modeler/adapters/gherkin_6_adapter.rb
CukeModeler.Gherkin6Adapter.adapt_step!
ruby
def adapt_step!(parsed_step) # Saving off the original data parsed_step['cuke_modeler_parsing_data'] = Marshal::load(Marshal.dump(parsed_step)) # Removing parsed data for child elements in order to avoid duplicating data parsed_step['cuke_modeler_parsing_data'][:data_table] = nil parsed_s...
Adapts the AST sub-tree that is rooted at the given step node.
train
https://github.com/enkessler/cuke_modeler/blob/6c4c05a719741d7fdaad218432bfa76eaa47b0cb/lib/cuke_modeler/adapters/gherkin_6_adapter.rb#L189-L212
class Gherkin6Adapter # Adapts the given AST into the shape that this gem expects def adapt(parsed_ast) # Saving off the original data parsed_ast['cuke_modeler_parsing_data'] = Marshal::load(Marshal.dump(parsed_ast)) # Removing parsed data for child elements in order to avoid duplicating d...
barkerest/incline
lib/incline/user_manager.rb
Incline.UserManager.register_auth_engine
ruby
def register_auth_engine(engine, *domains) unless engine.nil? unless engine.is_a?(::Incline::AuthEngineBase) raise ArgumentError, "The 'engine' parameter must be an instance of an auth engine or a class defining an auth engine." unless engine.is_a?(::Class) engine = engine.new(@options...
Registers an authentication engine for one or more domains. The +engine+ passed in should take an options hash as the only argument to +initialize+ and should provide an +authenticate+ method that takes the +email+, +password+, and +client_ip+. You can optionally define an +authenticate_external+ method that takes...
train
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/user_manager.rb#L189-L204
class UserManager < AuthEngineBase ## # Creates a new user manager. # # The user manager itself takes no options, however options will be passed to # any registered authentication engines when they are instantiated. # # The options can be used to pre-register engines and provide configura...
rmagick/rmagick
lib/rmagick_internal.rb
Magick.Draw.interline_spacing
ruby
def interline_spacing(space) begin Float(space) rescue ArgumentError Kernel.raise ArgumentError, 'invalid value for interline_spacing' rescue TypeError Kernel.raise TypeError, "can't convert #{space.class} into Float" end primitive "interline-spacing #{space}" e...
IM 6.5.5-8 and later
train
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L369-L378
class Draw # Thse hashes are used to map Magick constant # values to the strings used in the primitives. ALIGN_TYPE_NAMES = { LeftAlign.to_i => 'left', RightAlign.to_i => 'right', CenterAlign.to_i => 'center' }.freeze ANCHOR_TYPE_NAMES = { StartAnchor.to_i => 'start', ...
documentcloud/cloud-crowd
lib/cloud_crowd/action.rb
CloudCrowd.Action.save
ruby
def save(file_path) save_path = File.join(remote_storage_prefix, File.basename(file_path)) @store.save(file_path, save_path) end
Takes a local filesystem path, saves the file to S3, and returns the public (or authenticated) url on S3 where the file can be accessed.
train
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/action.rb#L61-L64
class Action FILE_URL = /\Afile:\/\// attr_reader :input, :input_path, :file_name, :options, :work_directory # Initializing an Action sets up all of the read-only variables that # form the bulk of the API for action subclasses. (Paths to read from and # write to). It creates the +work_directory...
rmagick/rmagick
lib/rmagick_internal.rb
Magick.Image.texture_floodfill
ruby
def texture_floodfill(x, y, texture) target = pixel_color(x, y) texture_flood_fill(target, texture, x, y, FloodfillMethod) end
Replace matching neighboring pixels with texture pixels
train
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L985-L988
class Image include Comparable alias affinity remap # Provide an alternate version of Draw#annotate, for folks who # want to find it in this class. def annotate(draw, width, height, x, y, text, &block) check_destroyed draw.annotate(self, width, height, x, y, text, &block) self ...
rakeoe/rakeoe
lib/rakeoe/toolchain.rb
RakeOE.Toolchain.app
ruby
def app(params = {}) incs = compiler_incs_for(params[:includes]) ldflags = params[:settings]['ADD_LDFLAGS'] + ' ' + @settings['LDFLAGS'] objs = params[:objects].join(' ') dep_libs = (params[:libs] + libs_for_binary(params[:app])).uniq libs = linker_line_for(dep_libs) sh "#{@settings['S...
Creates application @param [Hash] params @option params [Array] :objects array of object file paths @option params [Array] :libs array of libraries that should be linked against @option params [String] :app application filename path @option params [Hash] :settings project specific settings @option...
train
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/toolchain.rb#L512-L528
class Toolchain attr_reader :qt, :settings, :target, :config # Initializes object # # @param [RakeOE::Config] config Project wide configurations # def initialize(config) raise 'Configuration failure' unless config.checks_pass? @config = config begin @kvr = KeyValueReader.new(confi...
dagrz/nba_stats
lib/nba_stats/stats/player_career_stats.rb
NbaStats.PlayerCareerStats.player_career_stats
ruby
def player_career_stats( player_id, per_mode=NbaStats::Constants::PER_MODE_TOTALS, league_id=NbaStats::Constants::LEAGUE_ID_NBA ) NbaStats::Resources::PlayerCareerStats.new( get(PLAYER_CAREER_STATS_PATH, { :PlayerID => player_id, :LeagueID => leagu...
Calls the playercareerstats API and returns a PlayerCareerStats resource. @param player_id [Integer] @param per_mode [String] @param league_id [String] @return [NbaStats::Resources::PlayerCareerStats]
train
https://github.com/dagrz/nba_stats/blob/d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa/lib/nba_stats/stats/player_career_stats.rb#L16-L28
module PlayerCareerStats # The path of the playercareerstats API PLAYER_CAREER_STATS_PATH = '/stats/playercareerstats' # Calls the playercareerstats API and returns a PlayerCareerStats resource. # # @param player_id [Integer] # @param per_mode [String] # @param league_id [String] #...
ideonetwork/lato-blog
lib/lato_blog/interfaces/categories.rb
LatoBlog.Interface::Categories.blog__create_default_category
ruby
def blog__create_default_category category_parent = LatoBlog::CategoryParent.find_by(meta_default: true) return if category_parent category_parent = LatoBlog::CategoryParent.new(meta_default: true) throw 'Impossible to create default category parent' unless category_parent.save languages...
This function create the default category if it not exists.
train
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/categories.rb#L7-L25
module Interface::Categories # This function create the default category if it not exists. # This function cleans all old category parents without any child. def blog__clean_category_parents category_parents = LatoBlog::CategoryParent.all category_parents.map { |cp| cp.destroy if cp.categor...
wvanbergen/request-log-analyzer
lib/request_log_analyzer/tracker.rb
RequestLogAnalyzer::Tracker.Base.setup_should_update_checks!
ruby
def setup_should_update_checks! @should_update_checks = [] @should_update_checks.push(lambda { |request| request.has_line_type?(options[:line_type]) }) if options[:line_type] @should_update_checks.push(options[:if]) if options[:if].respond_to?(:call) @should_update_checks.push(lambda { |request|...
Initialize the class Note that the options are only applicable if should_update? is not overwritten by the inheriting class. === Options * <tt>:if</tt> Handle request if this proc is true for the handled request. * <tt>:unless</tt> Handle request if this proc is false for the handled request. * <tt>:line_type</t...
train
https://github.com/wvanbergen/request-log-analyzer/blob/b83865d440278583ac8e4901bb33878244fd7c75/lib/request_log_analyzer/tracker.rb#L28-L35
class Base attr_reader :options # Initialize the class # Note that the options are only applicable if should_update? is not overwritten # by the inheriting class. # # === Options # * <tt>:if</tt> Handle request if this proc is true for the handled request. # * <tt>:unless</tt> Handle ...
jaymcgavren/zyps
lib/zyps/actions.rb
Zyps.SpawnAction.generate_child
ruby
def generate_child(actor, prototype) #Copy prototype so it can be spawned repeatedly if need be. child = prototype.copy child.location = actor.location.copy child end
Copy prototype to actor's location.
train
https://github.com/jaymcgavren/zyps/blob/7fa9dc497abc30fe2d1a2a17e129628ffb0456fb/lib/zyps/actions.rb#L286-L291
class SpawnAction < Action #Array of GameObjects to copy into environment. attr_accessor :prototypes def initialize(prototypes = []) self.prototypes = prototypes end #Add children to environment. def do(actor, targets) prototypes.each do |prototype| actor.environment.add_object(generate_child(...
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.create_volume
ruby
def create_volume(name, cpg_name, size_MiB, optional = nil) if @current_version < @min_version_with_compression && !optional.nil? optional.delete_if { |key, _value| key == :compression } end begin @volume.create_volume(name, cpg_name, size_MiB, optional) rescue => ex Util...
Creates a new volume. ==== Attributes * name - the name of the volume type name: String * cpg_name - the name of the destination CPG type cpg_name: String * size_MiB - size in MiB for the volume type size_MiB: Integer * optional - hash of other optional items type optional: hash op...
train
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L1406-L1416
class Client def initialize(api_url,debug:false, secure: false, timeout: nil, suppress_ssl_warnings: false, app_type: 'ruby_SDK_3par', log_file_path: nil) unless api_url.is_a?(String) raise Hpe3parSdk::HPE3PARException.new(nil, "'api_url' parameter i...
thelabtech/questionnaire
app/models/qe/question_set.rb
Qe.QuestionSet.posted_values
ruby
def posted_values(param) if param.kind_of?(Hash) and param.has_key?('year') and param.has_key?('month') year = param['year'] month = param['month'] if month.blank? or year.blank? values = '' else values = [Date.new(year.to_i, month.to_i, 1).strftime('%m/%d/...
convert posted response to a question into Array of values
train
https://github.com/thelabtech/questionnaire/blob/02eb47cbcda8cca28a5db78e18623d0957aa2c9b/app/models/qe/question_set.rb#L60-L79
class QuestionSet attr_reader :elements # associate answers from database with a set of elements def initialize(elements, answer_sheet) @elements = elements @answer_sheet = answer_sheet @questions = elements.select { |e| e.question? } # answers = @answer_sheet.a...
dsaenztagarro/simplecrud
lib/simple_crud/base_controller.rb
SimpleCrud.BaseController.update
ruby
def update respond_to do |wants| result = resource_get.update_attributes(resource_params) call_hook :after_update_attributes, result if result flash[:notice] = t 'messages.record_updated', model: t("models.#{resource_name}") wants.html { redirect_to(resource_get) } ...
PUT /resources/1 PUT /resources/1.json
train
https://github.com/dsaenztagarro/simplecrud/blob/f1f19b3db26d2e61f6f15fa9b9e306c06bf7b069/lib/simple_crud/base_controller.rb#L71-L84
class BaseController < ::ApplicationController include DecoratorHelper include ResourceHelper before_filter :find_resource, :only => [:show, :edit, :update, :destroy] respond_to :html, :json class << self attr_accessor :resource_klass def crud_for(klass) @resource_klass = kl...
sandipransing/rails_tiny_mce
plugins/paperclip/lib/paperclip/interpolations.rb
Paperclip.Interpolations.extension
ruby
def extension attachment, style_name ((style = attachment.styles[style_name]) && style[:format]) || File.extname(attachment.original_filename).gsub(/^\.+/, "") end
Returns the extension of the file. e.g. "jpg" for "file.jpg" If the style has a format defined, it will return the format instead of the actual extension.
train
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/lib/paperclip/interpolations.rb#L82-L85
module Interpolations extend self # Hash assignment of interpolations. Included only for compatability, # and is not intended for normal use. def self.[]= name, block define_method(name, &block) end # Hash access of interpolations. Included only for compatability, # and is not inte...
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.save_synonym
ruby
def save_synonym(objectID, synonym, forward_to_replicas = false, request_options = {}) client.put("#{Protocol.synonym_uri(name, objectID)}?forwardToReplicas=#{forward_to_replicas}", synonym.to_json, :write, request_options) end
Save a synonym @param objectID the synonym objectID @param synonym the synonym @param forward_to_replicas should we forward the delete to replica indices @param request_options contains extra parameters to send with your query
train
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L922-L924
class Index attr_accessor :name, :client def initialize(name, client = nil) self.name = name self.client = client || Algolia.client end # # Delete an index # # @param request_options contains extra parameters to send with your query # # return an hash of the form { "d...
sandipransing/rails_tiny_mce
plugins/paperclip/lib/paperclip/upfile.rb
Paperclip.Upfile.content_type
ruby
def content_type type = (self.path.match(/\.(\w+)$/)[1] rescue "octet-stream").downcase case type when %r"jp(e|g|eg)" then "image/jpeg" when %r"tiff?" then "image/tiff" when %r"png", "gif", "bmp" then "image/#{type}" when "txt" then ...
Infer the MIME-type of the file from the extension.
train
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/lib/paperclip/upfile.rb#L8-L24
module Upfile # Infer the MIME-type of the file from the extension. # Returns the file's normal name. def original_filename File.basename(self.path) end # Returns the size of the file. def size File.size(self) end end
sds/haml-lint
lib/haml_lint/cli.rb
HamlLint.CLI.scan_for_lints
ruby
def scan_for_lints(options) reporter = reporter_from_options(options) report = Runner.new.run(options.merge(reporter: reporter)) report.display report.failed? ? Sysexits::EX_DATAERR : Sysexits::EX_OK end
Scans the files specified by the given options for lints. @return [Integer] exit status code
train
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/cli.rb#L106-L111
class CLI # rubocop:disable Metrics/ClassLength # Create a CLI that outputs to the specified logger. # # @param logger [HamlLint::Logger] def initialize(logger) @log = logger end # Parses the given command-line arguments and executes appropriate logic # based on those arguments. ...
robertwahler/repo_manager
lib/repo_manager/views/base_view.rb
RepoManager.BaseView.partial
ruby
def partial(filename) filename = partial_path(filename) raise "unable to find partial file: #{filename}" unless File.exists?(filename) contents = File.open(filename, "rb") {|f| f.read} # TODO: detect template EOL and match it to the partial's EOL # force unix eol contents.gsub!(/\r\n...
render a partial filename: unless absolute, it will be relative to the main template @example slim escapes HTML, use '==' head == render 'mystyle.css' @return [String] of non-escaped textual content
train
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/views/base_view.rb#L86-L94
class BaseView def initialize(items, configuration={}) @configuration = configuration.deep_clone @items = items @template = File.expand_path('../templates/default.slim', __FILE__) end def configuration @configuration end def items @items end def template ...
adimichele/hubspot-ruby
lib/hubspot/form.rb
Hubspot.Form.update!
ruby
def update!(opts={}) response = Hubspot::Connection.post_json(FORM_PATH, params: { form_guid: @guid }, body: opts) self.send(:assign_properties, response) self end
{https://developers.hubspot.com/docs/methods/forms/update_form}
train
https://github.com/adimichele/hubspot-ruby/blob/8eb0a64dd0c14c79e631e81bfdc169583e775a46/lib/hubspot/form.rb#L71-L75
class Form FORMS_PATH = '/forms/v2/forms' # '/contacts/v1/forms' FORM_PATH = '/forms/v2/forms/:form_guid' # '/contacts/v1/forms/:form_guid' FIELDS_PATH = '/forms/v2/fields/:form_guid' # '/contacts/v1/fields/:form_guid' FIELD_PATH = FIELDS_PATH + '/:field_name' SUBMIT_DATA_P...
chicks/sugarcrm
lib/sugarcrm/attributes/attribute_typecast.rb
SugarCRM.AttributeTypeCast.typecast_attributes
ruby
def typecast_attributes @attributes.each_pair do |name,value| # skip primary key columns # ajay Singh --> skip the loop if attribute is null (!name.present?) next if (name == "id") or (!name.present?) attr_type = attr_type_for(name) # empty attributes should stay empty (e.g. an ...
Attempts to typecast each attribute based on the module field type
train
https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/attributes/attribute_typecast.rb#L16-L43
module SugarCRM; module AttributeTypeCast protected # Returns the attribute type for a given attribute def attr_type_for(attribute) fields = self.class._module.fields field = fields[attribute] raise UninitializedModule, "#{self.class.session.namespace_const}Module #{self.class._module.name} was n...
chaintope/bitcoinrb
lib/bitcoin/ext_key.rb
Bitcoin.ExtKey.to_base58
ruby
def to_base58 h = to_payload.bth hex = h + Bitcoin.calc_checksum(h) Base58.encode(hex) end
Base58 encoded extended private key
train
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/ext_key.rb#L51-L55
class ExtKey attr_accessor :ver attr_accessor :depth attr_accessor :number attr_accessor :chain_code attr_accessor :key # Bitcoin::Key attr_accessor :parent_fingerprint # generate master key from seed. # @params [String] seed a seed data with hex format. def self.generate_master(...
xi-livecode/xi
lib/xi/core_ext/string.rb
Xi::CoreExt.String.underscore
ruby
def underscore return self unless self =~ /[A-Z-]|::/ word = self.to_s.gsub('::'.freeze, '/'.freeze) word.gsub!(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2'.freeze) word.gsub!(/([a-z\d])([A-Z])/, '\1_\2'.freeze) word.tr!("-".freeze, "_".freeze) word.downcase! word end
Makes an underscored, lowercase form from the expression in the string. Changes '::' to '/' to convert namespaces to paths. underscore('ActiveModel') # => "active_model" underscore('ActiveModel::Errors') # => "active_model/errors" As a rule of thumb you can think of +underscore+ as the inverse of #c...
train
https://github.com/xi-livecode/xi/blob/215dfb84899b3dd00f11089ae3eab0febf498e95/lib/xi/core_ext/string.rb#L38-L46
module String # Converts strings to UpperCamelCase. # If the +uppercase_first_letter+ parameter is set to false, then produces # lowerCamelCase. # # Also converts '/' to '::' which is useful for converting # paths to namespaces. # # camelize('active_model') # => "Activ...
hoanganhhanoi/dhcp_parser
lib/dhcp_parser.rb
DHCPParser.Conf.net
ruby
def net i = 0 while i < @datas.count i += 1 new_net = Net.new new_net.subnet = DHCPParser::Conf.get_subnet(@datas["net#{i}"]) new_net.netmask = DHCPParser::Conf.get_netmask(@datas["net#{i}"]) list_option = DHCPParser::Conf.get_list_option(@datas["net#{i}"], true) ...
Set data in object
train
https://github.com/hoanganhhanoi/dhcp_parser/blob/baa59aab7b519117c162d323104fb6e56d7fd4fc/lib/dhcp_parser.rb#L361-L391
class Conf attr_accessor :datas # Function constructor of DHCP def initialize(path) @datas = DHCPParser::Conf.read_file(path) @array_net = [] end # Read file config return Net. Net is hash def self.read_file(path) str = "" count = 0 counter = ...
bitbucket-rest-api/bitbucket
lib/bitbucket_rest_api/issues/components.rb
BitBucket.Issues::Components.update
ruby
def update(user_name, repo_name, component_id, params={}) _update_user_repo_params(user_name, repo_name) _validate_user_repo_params(user, repo) unless user? && repo? _validate_presence_of component_id normalize! params filter! VALID_COMPONENT_INPUTS, params assert_required_keys(VALI...
Update a component = Inputs <tt>:name</tt> - Required string = Examples @bitbucket = BitBucket.new @bitbucket.issues.components.update 'user-name', 'repo-name', 'component-id', :name => 'API'
train
https://github.com/bitbucket-rest-api/bitbucket/blob/e03b6935104d59b3d9a922474c3dc210a5ef76d2/lib/bitbucket_rest_api/issues/components.rb#L76-L86
class Issues::Components < API VALID_COMPONENT_INPUTS = %w[ name ].freeze # Creates new Issues::Components API def initialize(options = {}) super(options) end # List all components for a repository # # = Examples # bitbucket = BitBucket.new :user => 'user-name', :repo => 'repo...
cul/cul-ldap
lib/cul/ldap.rb
Cul.LDAP.find_by_name
ruby
def find_by_name(name) if name.include?(',') name = name.split(',').map(&:strip).reverse.join(" ") end entries = search(base: "ou=People,o=Columbia University, c=US", filter: Net::LDAP::Filter.eq("cn", name)) (entries.count == 1) ? entries.first : nil end
LDAP lookup based on name. @param [String] name @return [Cul::LDAP::Entry] containing the entry matching this name, if it is unique @return [nil] if record could not be found or if there is more than one match
train
https://github.com/cul/cul-ldap/blob/07c35bbf1c2fdc73719e32c39397c3971c0878bc/lib/cul/ldap.rb#L38-L44
class LDAP < Net::LDAP CONFIG_FILENAME = 'cul_ldap.yml' CONFIG_DEFAULTS = { host: 'ldap.columbia.edu', port: '636', encryption: { method: :simple_tls, tls_options: OpenSSL::SSL::SSLContext::DEFAULT_PARAMS } }.freeze def initialize(options = {}) super(buil...
chicks/sugarcrm
lib/sugarcrm/connection/helper.rb
SugarCRM.Connection.resolve_related_fields
ruby
def resolve_related_fields(module_name, link_field) a = Association.new(class_for(module_name), link_field) if a.target fields = a.target.new.attributes.keys else fields = ["id"] end fields.to_json end
Attempts to return a list of fields for the target of the association. i.e. if we are associating Contact -> Account, using the "contacts" link field name - this will lookup the contacts association and try to determine the target object type (Contact). It will then pull the fields for that object and shove them i...
train
https://github.com/chicks/sugarcrm/blob/360060139b13788a7ec462c6ecd08d3dbda9849a/lib/sugarcrm/connection/helper.rb#L7-L15
module SugarCRM; class Connection # Attempts to return a list of fields for the target of the association. # i.e. if we are associating Contact -> Account, using the "contacts" link # field name - this will lookup the contacts association and try to determine # the target object type (Contact). It will then pu...
sup-heliotrope/sup
lib/sup/thread.rb
Redwood.ThreadSet.add_message
ruby
def add_message message el = @messages[message.id] return if el.message # we've seen it before #puts "adding: #{message.id}, refs #{message.refs.inspect}" el.message = message oldroot = el.root ## link via references: (message.refs + [el.id]).inject(nil) do |prev, ref_id| ref = @mes...
the heart of the threading code
train
https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/thread.rb#L403-L449
class ThreadSet attr_reader :num_messages bool_reader :thread_by_subj def initialize index, thread_by_subj=true @index = index @num_messages = 0 ## map from message ids to container objects @messages = SavingHash.new { |id| Container.new id } ## map from subject strings or (or root message id...
pusher/pusher-http-ruby
lib/pusher/client.rb
Pusher.Client.trigger_async
ruby
def trigger_async(channels, event_name, data, params = {}) post_async('/events', trigger_params(channels, event_name, data, params)) end
Trigger an event on one or more channels asynchronously. For parameters see #trigger
train
https://github.com/pusher/pusher-http-ruby/blob/cd666ca74b39dacfae6ca0235c35fcf80eba1e64/lib/pusher/client.rb#L309-L311
class Client attr_accessor :scheme, :host, :port, :app_id, :key, :secret, :notification_host, :notification_scheme attr_reader :http_proxy, :proxy attr_writer :connect_timeout, :send_timeout, :receive_timeout, :keep_alive_timeout ## CONFIGURATION ## # Loads the configuration from...
rossf7/elasticrawl
lib/elasticrawl/config.rb
Elasticrawl.Config.create_bucket
ruby
def create_bucket(bucket_name) begin s3 = AWS::S3.new s3.buckets.create(bucket_name) rescue AWS::Errors::Base => s3e raise S3AccessError.new(s3e.http_response), s3e.message end end
Creates a bucket using the S3 API.
train
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/config.rb#L156-L164
class Config CONFIG_DIR = '.elasticrawl' DATABASE_FILE = 'elasticrawl.sqlite3' TEMPLATES_DIR = '../../templates' TEMPLATE_FILES = ['aws.yml', 'cluster.yml', 'jobs.yml'] attr_reader :access_key_id attr_reader :secret_access_key # Sets the AWS access credentials needed for the S3 and EMR A...
barkerest/incline
app/models/incline/user.rb
Incline.User.authenticated?
ruby
def authenticated?(attribute, token) return false unless respond_to?("#{attribute}_digest") digest = send("#{attribute}_digest") return false if digest.blank? BCrypt::Password.new(digest).is_password?(token) end
Determines if the supplied token digests to the stored digest in the user model.
train
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/models/incline/user.rb#L164-L169
class User < ActiveRecord::Base ANONYMOUS_EMAIL = 'anonymous@server.local' has_many :login_histories, class_name: 'Incline::UserLoginHistory' has_many :access_group_user_members, class_name: 'Incline::AccessGroupUserMember', foreign_key: 'member_id' private :access_group_user_members, :access_group...
senchalabs/jsduck
lib/jsduck/grouped_asset.rb
JsDuck.GroupedAsset.each_item
ruby
def each_item(group=nil, &block) group = group || @groups group.each do |item| if item["items"] each_item(item["items"], &block) else block.call(item) end end end
Iterates over all items in all groups
train
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/grouped_asset.rb#L26-L36
class GroupedAsset # Should be called from constructor after @groups have been read in, # and after it's been ensured that all items in groupes have names. def build_map_by_name @map_by_name = {} each_item do |item| @map_by_name[item["name"]] = item end end # Accesses it...
altabyte/ebay_trader
lib/ebay_trader/session_id.rb
EbayTrader.SessionID.sign_in_url
ruby
def sign_in_url(ruparams = {}) url = [] url << EbayTrader.configuration.production? ? 'https://signin.ebay.com' : 'https://signin.sandbox.ebay.com' url << '/ws/eBayISAPI.dll?SignIn' url << "&runame=#{url_encode ru_name}" url << "&SessID=#{url_encode id}" if ruparams && ruparams.is_a?...
Get the URL through which a user must sign in using this session ID. @param [Hash] ruparams eBay appends this data to the AcceptURL and RejectURL. In a typical rails app this might include the user's model primary key. @return [String] the sign-in URL.
train
https://github.com/altabyte/ebay_trader/blob/4442b683ea27f02fa0ef73f3f6357396fbe29b56/lib/ebay_trader/session_id.rb#L49-L61
class SessionID < Request CALL_NAME = 'GetSessionID' # The application RuName defined in {Configuration#ru_name}, unless over-ridden in {#initialize} args. # @return [String] the RuName for this call. # @see https://developer.ebay.com/DevZone/account/appsettings/Consent/ # attr_reader :ru_na...
kwatch/erubis
lib/erubis/engine.rb
Erubis.Engine.process_proc
ruby
def process_proc(proc_obj, context=nil, filename=nil) if context.is_a?(Binding) filename ||= '(erubis)' return eval(proc_obj, context, filename) else context = Context.new(context) if context.is_a?(Hash) return context.instance_eval(&proc_obj) end end
helper method evaluate Proc object with contect object. context may be Binding, Hash, or Object.
train
https://github.com/kwatch/erubis/blob/14d3eab57fbc361312c8f3af350cbf9a5bafce17/lib/erubis/engine.rb#L88-L96
class Engine #include Evaluator #include Converter #include Generator def initialize(input=nil, properties={}) #@input = input init_generator(properties) init_converter(properties) init_evaluator(properties) @src = convert(input) if input end ## ## conve...
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.save_rule
ruby
def save_rule(objectID, rule, forward_to_replicas = false, request_options = {}) raise ArgumentError.new('objectID must not be blank') if objectID.nil? || objectID == '' client.put("#{Protocol.rule_uri(name, objectID)}?forwardToReplicas=#{forward_to_replicas}", rule.to_json, :write, request_options) end
Save a rule @param objectID the rule objectID @param rule the rule @param forward_to_replicas should we forward the delete to replica indices @param request_options contains extra parameters to send with your query
train
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L1098-L1101
class Index attr_accessor :name, :client def initialize(name, client = nil) self.name = name self.client = client || Algolia.client end # # Delete an index # # @param request_options contains extra parameters to send with your query # # return an hash of the form { "d...
Syncano/syncano-ruby
lib/syncano/jimson_client.rb
Jimson.ClientHelper.send_batch
ruby
def send_batch batch = @batch.map(&:first) # get the requests response = send_batch_request(batch) begin responses = JSON.parse(response) rescue raise Jimson::ClientError::InvalidJSON.new(json) end process_batch_response(responses) responses = @batch @b...
Overwritten send_batch method, so it now returns collection of responses @return [Array] collection of responses
train
https://github.com/Syncano/syncano-ruby/blob/59155f8afd7a19dd1a168716c4409270a7edc0d3/lib/syncano/jimson_client.rb#L39-L55
class ClientHelper # Overwritten send_single_request method, so it now adds header with the user agent # @return [Array] collection of responses def send_single_request(method, args) post_data = { 'jsonrpc' => JSON_RPC_VERSION, 'method' => method, 'params' => args, ...
senchalabs/jsduck
lib/jsduck/cache.rb
JsDuck.Cache.read
ruby
def read(file_name, file_contents) fname = cache_file_name(file_name, file_contents) if File.exists?(fname) @previous_entry = fname File.open(fname, "rb") {|file| Marshal::load(file) } else @previous_entry = nil nil end end
Given the name and contents of a source file, reads the already parsed data structure from cache. Returns nil when not found.
train
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/cache.rb#L76-L85
class Cache # Factory method to produce a cache object. When caching is # disabled, returns a NullObject which emulates a cache that's # always empty. def self.create(opts) # Check also for cache_dir, which will be nil when output_dir is :stdout if opts.cache && opts.cache_dir Ca...
rmagick/rmagick
lib/rmagick_internal.rb
Magick.Image.get_exif_by_number
ruby
def get_exif_by_number(*tag) hash = {} if tag.length.zero? exif_data = self['EXIF:!'] if exif_data exif_data.split("\n").each do |exif| tag, value = exif.split('=') tag = tag[1, 4].hex hash[tag] = value end end else ...
Retrieve EXIF data by tag number or all tag/value pairs. The return value is a hash.
train
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L831-L850
class Image include Comparable alias affinity remap # Provide an alternate version of Draw#annotate, for folks who # want to find it in this class. def annotate(draw, width, height, x, y, text, &block) check_destroyed draw.annotate(self, width, height, x, y, text, &block) self ...
puppetlabs/beaker-aws
lib/beaker/hypervisor/aws_sdk.rb
Beaker.AwsSdk.log_instances
ruby
def log_instances(key = key_name, status = /running/) instances = [] regions.each do |region| @logger.debug "Reviewing: #{region}" client(region).describe_instances.reservations.each do |reservation| reservation.instances.each do |instance| if (instance.key_name =~ /#{k...
Print instances to the logger. Instances will be from all regions associated with provided key name and limited by regex compared to instance status. Defaults to running instances. @param [String] key The key_name to match for @param [Regex] status The regular expression to match against the instance's status
train
https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L139-L158
class AwsSdk < Beaker::Hypervisor ZOMBIE = 3 #anything older than 3 hours is considered a zombie PING_SECURITY_GROUP_NAME = 'beaker-ping' attr_reader :default_region # Initialize AwsSdk hypervisor driver # # @param [Array<Beaker::Host>] hosts Array of Beaker::Host objects # @param [Hash<S...
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.partial_update_object!
ruby
def partial_update_object!(object, objectID = nil, create_if_not_exits = true, request_options = {}) res = partial_update_object(object, objectID, create_if_not_exits, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
Update partially an object (only update attributes passed in argument) and wait indexing @param object the attributes to override @param objectID the associated objectID, if nil 'object' must contain an 'objectID' key @param create_if_not_exits a boolean, if true creates the object if this one doesn't exist @param...
train
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L454-L458
class Index attr_accessor :name, :client def initialize(name, client = nil) self.name = name self.client = client || Algolia.client end # # Delete an index # # @param request_options contains extra parameters to send with your query # # return an hash of the form { "d...
mongodb/mongoid
lib/mongoid/loggable.rb
Mongoid.Loggable.default_logger
ruby
def default_logger logger = Logger.new($stdout) logger.level = Mongoid::Config.log_level logger end
Gets the default Mongoid logger - stdout. @api private @example Get the default logger. Loggable.default_logger @return [ Logger ] The default logger. @since 3.0.0
train
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/loggable.rb#L50-L54
module Loggable # Get the logger. # # @note Will try to grab Rails' logger first before creating a new logger # with stdout. # # @example Get the logger. # Loggable.logger # # @return [ Logger ] The logger. # # @since 3.0.0 def logger return @logger if define...
arvicco/win_gui
old_code/lib/win_gui/def_api.rb
WinGui.DefApi.return_enum
ruby
def return_enum lambda do |api, *args, &block| WinGui.enforce_count( args, api.prototype, -1) handles = [] cb = if block callback('LP', 'I', &block) else callback('LP', 'I') do |handle, message| handles << handle true end ...
Procedure that calls api function expecting a callback. If runtime block is given it is converted into actual callback, otherwise procedure returns an array of all handles pushed into callback by api enumeration
train
https://github.com/arvicco/win_gui/blob/a3a4c18db2391144fcb535e4be2f0fb47e9dcec7/old_code/lib/win_gui/def_api.rb#L125-L141
module DefApi # DLL to use with API decarations by default ('user32') DEFAULT_DLL = 'user32' ## # Defines new method wrappers for Windows API function call: # - Defines method with original (CamelCase) API function name and original signature (matches MSDN description) # - Defines method ...
jaymcgavren/zyps
lib/zyps/environmental_factors.rb
Zyps.PopulationLimit.act
ruby
def act(environment) excess = environment.object_count - @count if excess > 0 objects_for_removal = [] environment.objects.each do |object| objects_for_removal << object break if objects_for_removal.length >= excess end objects_for_removal.each {|object| environment.remov...
Remove objects if there are too many objects in environment.
train
https://github.com/jaymcgavren/zyps/blob/7fa9dc497abc30fe2d1a2a17e129628ffb0456fb/lib/zyps/environmental_factors.rb#L263-L273
class PopulationLimit < EnvironmentalFactor #Maximum allowed population. attr_accessor :count def initialize(count = nil) self.count = count end #Remove objects if there are too many objects in environment. #True if count is the same. def ==(other) return false unless super self.c...
chaintope/bitcoinrb
lib/bitcoin/tx.rb
Bitcoin.Tx.sighash_for_witness
ruby
def sighash_for_witness(index, script_pubkey_or_script_code, hash_type, amount, skip_separator_index) hash_prevouts = Bitcoin.double_sha256(inputs.map{|i|i.out_point.to_payload}.join) hash_sequence = Bitcoin.double_sha256(inputs.map{|i|[i.sequence].pack('V')}.join) outpoint = inputs[index].out_point.t...
generate sighash with BIP-143 format https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki
train
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/tx.rb#L278-L303
class Tx MAX_STANDARD_VERSION = 2 # The maximum weight for transactions we're willing to relay/mine MAX_STANDARD_TX_WEIGHT = 400000 MARKER = 0x00 FLAG = 0x01 attr_accessor :version attr_accessor :marker attr_accessor :flag attr_reader :inputs attr_reader :outputs attr_a...
alltom/ruck
lib/ruck/clock.rb
Ruck.Clock.unschedule
ruby
def unschedule(obj) if @occurrences.has_key? obj last_priority = @occurrences.min_priority obj, time = @occurrences.delete obj if parent && @occurrences.min_priority != last_priority if @occurrences.min_priority parent.schedule([:clock, self], unscale_time(@occurrence...
dequeues the earliest occurrence from this clock or any child clocks. returns nil if it wasn't there, or its relative_time otherwise
train
https://github.com/alltom/ruck/blob/a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d/lib/ruck/clock.rb#L75-L91
class Clock attr_reader :now # current time in this clock's units attr_accessor :relative_rate # rate relative to parent clock attr_accessor :parent def initialize(relative_rate = 1.0) @relative_rate = relative_rate @now = 0 @children = [] @occurrences = PriorityQueue.new ...
state-machines/state_machines
lib/state_machines/machine.rb
StateMachines.Machine.define_name_helpers
ruby
def define_name_helpers # Gets the humanized version of a state define_helper(:class, "human_#{attribute(:name)}") do |machine, klass, state| machine.states.fetch(state).human_name(klass) end # Gets the humanized version of an event define_helper(:class, "human_#{attribute(:event_...
Adds helper methods for accessing naming information about states and events on the owner class
train
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L2085-L2105
class Machine include EvalHelpers include MatcherHelpers class << self # Attempts to find or create a state machine for the given class. For # example, # # StateMachines::Machine.find_or_create(Vehicle) # StateMachines::Machine.find_or_create(Vehicle, :initial => :par...
NullVoxPopuli/authorizable
lib/authorizable/model.rb
Authorizable.Model.method_missing
ruby
def method_missing(name, *args, &block) string_name = name.to_s if string_name =~ /can_(.+)\?/ self.can?(name, *args) else super(name, *args, &block) end end
alternative access via user.can_create_event? or user.can_update_event?(@event) TODO: What do we do if something else wants to use method_missing?
train
https://github.com/NullVoxPopuli/authorizable/blob/6a4ef94848861bb79b0ab1454264366aed4e2db8/lib/authorizable/model.rb#L20-L28
module Model extend ActiveSupport::Concern included do # set up our access to the permission checking after_initialize :permission_proxy end # alternative access via # user.can_create_event? # or # user.can_update_event?(@event) # # TODO: What do we do if somet...
grpc/grpc
src/ruby/lib/grpc/generic/active_call.rb
GRPC.ActiveCall.send_status
ruby
def send_status(code = OK, details = '', assert_finished = false, metadata: {}) send_initial_metadata ops = { SEND_STATUS_FROM_SERVER => Struct::Status.new(code, details, metadata) } ops[RECV_CLOSE_ON_SERVER] = nil if assert_finished @call.run_batch(ops) s...
send_status sends a status to the remote endpoint. @param code [int] the status code to send @param details [String] details @param assert_finished [true, false] when true(default), waits for FINISHED. @param metadata [Hash] metadata to send to the server. If a value is a list, mulitple metadata for its key are ...
train
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/active_call.rb#L206-L217
class ActiveCall # rubocop:disable Metrics/ClassLength include Core::TimeConsts include Core::CallOps extend Forwardable attr_reader :deadline, :metadata_sent, :metadata_to_send, :peer, :peer_cert def_delegators :@call, :cancel, :metadata, :write_flag, :write_flag=, :trailing_me...
d11wtq/rdo
lib/rdo/connection.rb
RDO.Connection.normalize_options
ruby
def normalize_options(options) case options when Hash Hash[options.map{|k,v| [k.respond_to?(:to_sym) ? k.to_sym : k, v]}].tap do |opts| opts[:driver] = opts[:driver].to_s if opts[:driver] end when String, URI parse_connection_uri(options) else raise RDO:...
Normalizes the given options String or Hash into a Symbol-keyed Hash. @param [Object] options either a String, a URI or a Hash @return [Hash] a Symbol-keyed Hash
train
https://github.com/d11wtq/rdo/blob/91fe0c70cbce9947b879141c0f1001b8c4eeef19/lib/rdo/connection.rb#L150-L162
class Connection class << self # List all known drivers, as a Hash mapping the URI scheme to the Class. # # @return [Hash] # the mapping of driver names to class names def drivers @drivers ||= {} end # Register a known driver class for the given URI scheme name...
grempe/opensecrets
lib/opensecrets.rb
OpenSecrets.Organization.get_orgs
ruby
def get_orgs(options = {}) raise ArgumentError, 'You must provide a :org option' if options[:org].nil? || options[:org].empty? options.merge!({:method => 'getOrgs'}) self.class.get("/", :query => options) end
Look up an organization by name. See : https://www.opensecrets.org/api/?method=getOrgs&output=doc @option options [String] :org ("") name or partial name of organization requested
train
https://github.com/grempe/opensecrets/blob/2f507e214de716ce7b23831e056160b1384bff78/lib/opensecrets.rb#L156-L160
class Organization < OpenSecrets::Base # Look up an organization by name. # # See : https://www.opensecrets.org/api/?method=getOrgs&output=doc # # @option options [String] :org ("") name or partial name of organization requested # # Provides summary fundraising information for the speci...
state-machines/state_machines
lib/state_machines/machine.rb
StateMachines.Machine.define_path_helpers
ruby
def define_path_helpers # Gets the paths of transitions available to the current object define_helper(:instance, attribute(:paths)) do |machine, object, *args| machine.paths_for(object, *args) end end
Adds helper methods for getting information about this state machine's available transition paths
train
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L1997-L2002
class Machine include EvalHelpers include MatcherHelpers class << self # Attempts to find or create a state machine for the given class. For # example, # # StateMachines::Machine.find_or_create(Vehicle) # StateMachines::Machine.find_or_create(Vehicle, :initial => :par...
puppetlabs/beaker-aws
lib/beaker/hypervisor/aws_sdk.rb
Beaker.AwsSdk.ensure_ping_group
ruby
def ensure_ping_group(vpc, sg_cidr_ips = ['0.0.0.0/0']) @logger.notify("aws-sdk: Ensure security group exists that enables ping, create if not") group = client.describe_security_groups( :filters => [ { :name => 'group-name', :values => [PING_SECURITY_GROUP_NAME] }, { :name => 'v...
Return an existing group, or create new one Accepts a VPC as input for checking & creation. @param vpc [Aws::EC2::VPC] the AWS vpc control object @param sg_cidr_ips [Array<String>] CIDRs used for outbound security group rule @return [Aws::EC2::SecurityGroup] created security group @api private
train
https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L981-L996
class AwsSdk < Beaker::Hypervisor ZOMBIE = 3 #anything older than 3 hours is considered a zombie PING_SECURITY_GROUP_NAME = 'beaker-ping' attr_reader :default_region # Initialize AwsSdk hypervisor driver # # @param [Array<Beaker::Host>] hosts Array of Beaker::Host objects # @param [Hash<S...
leandog/gametel
lib/gametel/accessors.rb
Gametel.Accessors.view
ruby
def view(name, locator) define_method(name) do platform.click_view(locator) end define_method("#{name}_view") do Gametel::Views::View.new(platform, locator) end end
Generates one method to click a view. @example view(:clickable_text, :id => 'id_name_of_your_control') # will generate 'clickable_text' method @param [Symbol] the name used for the generated methods @param [Hash] locator indicating an id for how the view is found. The only valid keys are: * :id * :...
train
https://github.com/leandog/gametel/blob/fc9468da9a443b5e6ac553b3e445333a0eabfc18/lib/gametel/accessors.rb#L165-L172
module Accessors # # Generates a method named active? which will wait for the # activity to become active # # returns true when successful # def activity(activity_name) define_method("active?") do platform.wait_for_activity activity_name platform.last_json end ...
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.add_object!
ruby
def add_object!(object, objectID = nil, request_options = {}) res = add_object(object, objectID, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
Add an object in this index and wait end of indexing @param object the object to add to the index. The object is represented by an associative array @param objectID (optional) an objectID you want to attribute to this object (if the attribute already exist the old object will be overridden) @param Request optio...
train
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L67-L71
class Index attr_accessor :name, :client def initialize(name, client = nil) self.name = name self.client = client || Algolia.client end # # Delete an index # # @param request_options contains extra parameters to send with your query # # return an hash of the form { "d...
sup-heliotrope/sup
lib/sup/thread.rb
Redwood.Thread.dump
ruby
def dump f=$stdout f.puts "=== start thread with #{@containers.length} trees ===" @containers.each { |c| c.dump_recursive f; f.puts } f.puts "=== end thread ===" end
unused
train
https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/thread.rb#L53-L57
class Thread include Enumerable attr_reader :containers def initialize ## ah, the joys of a multithreaded application with a class called ## "Thread". i keep instantiating the wrong one... raise "wrong Thread class, buddy!" if block_given? @containers = [] end def << c @containers << c ...
sugaryourcoffee/syclink
lib/syclink/chrome.rb
SycLink.Chrome.extract_children
ruby
def extract_children(tag, children) children.map do |child| if child["children"] extract_children("#{tag},#{child['name']}", child["children"]) else [child["url"], child["name"], "", tag] end end end
Extracts the children from the JSON file
train
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/chrome.rb#L25-L33
class Chrome < Importer # Reads the content of the Google Chrome bookmarks file def read serialized = File.read(path) extract_links(JSON.parse(serialized)).flatten.each_slice(4).to_a end private # Extracts the links from the JSON file def extract_links(json) json["roots"]....
barkerest/incline
app/controllers/incline/users_controller.rb
Incline.UsersController.enable
ruby
def enable if @user.enabled? flash[:warning] = "User #{@user} is already enabled." unless inline_request? redirect_to users_path and return end else if @user.enable flash[:success] = "User #{@user} has been enabled." else flash[:danger] =...
PUT /incline/users/1/enable
train
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/controllers/incline/users_controller.rb#L160-L178
class UsersController < ApplicationController before_action :set_user, except: [ :index, :new, :create, :api ] before_action :set_dt_request, only: [ :index, :locate ] before_action :set_disable_info, only: [ :disable_confirm, :disable ] before_action :not_current, only: [ :destroy...
igrigorik/http-2
lib/http/2/flow_buffer.rb
HTTP2.FlowBuffer.send_data
ruby
def send_data(frame = nil, encode = false) @send_buffer.push frame unless frame.nil? # FIXME: Frames with zero length with the END_STREAM flag set (that # is, an empty DATA frame) MAY be sent if there is no available space # in either flow control window. while @remote_window > 0 && !@sen...
Buffers outgoing DATA frames and applies flow control logic to split and emit DATA frames based on current flow control window. If the window is large enough, the data is sent immediately. Otherwise, the data is buffered until the flow control window is updated. Buffered DATA frames are emitted in FIFO order. @p...
train
https://github.com/igrigorik/http-2/blob/d52934f144db97fc7534e4c6025ed6ae86909b6a/lib/http/2/flow_buffer.rb#L56-L92
module FlowBuffer # Amount of buffered data. Only DATA payloads are subject to flow stream # and connection flow control. # # @return [Integer] def buffered_amount @send_buffer.map { |f| f[:length] }.reduce(:+) || 0 end private def update_local_window(frame) frame_size = ...
chaintope/bitcoinrb
lib/bitcoin/util.rb
Bitcoin.Util.encode_base58_address
ruby
def encode_base58_address(hex, addr_version) base = addr_version + hex Base58.encode(base + calc_checksum(base)) end
encode Base58 check address. @param [String] hex the address payload. @param [String] addr_version the address version for P2PKH and P2SH. @return [String] Base58 check encoding address.
train
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/util.rb#L94-L97
module Util def pack_var_string(payload) pack_var_int(payload.bytesize) + payload end def unpack_var_string(payload) size, payload = unpack_var_int(payload) size > 0 ? payload.unpack("a#{size}a*") : [nil, payload] end def pack_var_int(i) if i < 0xfd [i].pack('C'...
chaintope/bitcoinrb
lib/bitcoin/script/script.rb
Bitcoin.Script.p2pkh_addr
ruby
def p2pkh_addr return nil unless p2pkh? hash160 = chunks[2].pushed_data.bth return nil unless hash160.htb.bytesize == 20 Bitcoin.encode_base58_address(hash160, Bitcoin.chain_params.address_version) end
generate p2pkh address. if script dose not p2pkh, return nil.
train
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L501-L506
class Script include Bitcoin::Opcodes attr_accessor :chunks def initialize @chunks = [] end # generate P2PKH script def self.to_p2pkh(pubkey_hash) new << OP_DUP << OP_HASH160 << pubkey_hash << OP_EQUALVERIFY << OP_CHECKSIG end # generate P2WPKH script def self.to_p2...
klacointe/has_media
lib/has_media.rb
HasMedia.ClassMethods.create_many_accessors
ruby
def create_many_accessors(context, options) define_method(context.to_s.pluralize) do media.with_context(context.to_sym).uniq end module_eval <<-"end;", __FILE__, __LINE__ def #{context}=(values) return if values.blank? Array(values).each do |value| next...
create_many_accessors Create needed accessors on master object for multiple relation @param [String] context @param [Hash] options
train
https://github.com/klacointe/has_media/blob/a886d36a914d8244f3761455458b9d0226fa22d5/lib/has_media.rb#L287-L302
module ClassMethods ## # has_one_medium # Define a class method to link to a medium # # @param [String] context, the context (or accessor) to link medium # @param [Hash] options, can be one of : encode, only # def has_one_medium(context, options = {}) set_relations(context, :...
iyuuya/jkf
lib/jkf/parser/kifuable.rb
Jkf::Parser.Kifuable.transform_initialboard
ruby
def transform_initialboard(lines) board = [] 9.times do |i| line = [] 9.times do |j| line << lines[j][8 - i] end board << line end { "preset" => "OTHER", "data" => { "board" => board } } end
transform initialboard to jkf
train
https://github.com/iyuuya/jkf/blob/4fd229c50737cab7b41281238880f1414e55e061/lib/jkf/parser/kifuable.rb#L560-L570
module Kifuable protected # initialboard : (" " nonls nl)? ("+" nonls nl)? ikkatsuline+ ("+" nonls nl)? def parse_initialboard s0 = s1 = @current_pos if match_space != :failed parse_nonls s2 = parse_nl @current_pos = s1 if s2 == :failed else @current_pos ...
jaredbeck/template_params
lib/template_params/assertion.rb
TemplateParams.Assertion.udef_msg
ruby
def udef_msg(name_error, block) prefix = "Undefined template parameter: #{name_error}" if block.respond_to?(:source) format("%s: %s", prefix, block.source.strip) else prefix end end
Given a `NameError` and the block, return a string like: Undefined template parameter: undefined local variable or method `banana' for ..: template_param(::Banana, allow_nil: true) { banana } `Proc#source` is provided by the `method_source` gem. @api private
train
https://github.com/jaredbeck/template_params/blob/32dba5caef32646f663bc46a7a44b55de225e76e/lib/template_params/assertion.rb#L63-L70
class Assertion # @api public def initialize(type, options) @type = type @options = options end # Convenience constructor. # @api public def self.assert(type = nil, options = {}, &block) new(type, options).apply(&block) end # Apply the instantiated assertion to the ...
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.delete_vlun
ruby
def delete_vlun(volume_name, lun_id, host_name = nil, port = nil) begin @vlun.delete_vlun(volume_name, lun_id, host_name, port) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
Deletes a VLUN. ==== Attributes * volume_name: Volume name of the VLUN type volume_name: String * lun_id: LUN ID type lun_id: Integer * host_name: Name of the host which the volume is exported. For VLUN of port type,the value is empty type host_name: String * port: Specifies the system port of the...
train
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L523-L530
class Client def initialize(api_url,debug:false, secure: false, timeout: nil, suppress_ssl_warnings: false, app_type: 'ruby_SDK_3par', log_file_path: nil) unless api_url.is_a?(String) raise Hpe3parSdk::HPE3PARException.new(nil, "'api_url' parameter i...
weshatheleopard/rubyXL
lib/rubyXL/objects/workbook.rb
RubyXL.Workbook.[]
ruby
def [](ind) case ind when Integer then worksheets[ind] when String then worksheets.find { |ws| ws.sheet_name == ind } end end
Finds worksheet by its name or numerical index
train
https://github.com/weshatheleopard/rubyXL/blob/e61d78de9486316cdee039d3590177dc05db0f0c/lib/rubyXL/objects/workbook.rb#L463-L468
class Workbook < OOXMLTopLevelObject CONTENT_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml' CONTENT_TYPE_WITH_MACROS = 'application/vnd.ms-excel.sheet.macroEnabled.main+xml' REL_TYPE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocum...
radiant/radiant
lib/radiant/extension.rb
Radiant.Extension.extension_enabled?
ruby
def extension_enabled?(extension) begin extension = (extension.to_s.camelcase + 'Extension').constantize extension.enabled? rescue NameError false end end
Determine if another extension is installed and up to date. if MyExtension.extension_enabled?(:third_party) ThirdPartyExtension.extend(MyExtension::IntegrationPoints) end
train
https://github.com/radiant/radiant/blob/5802d7bac2630a1959c463baa3aa7adcd0f497ee/lib/radiant/extension.rb#L97-L104
class Extension include Simpleton include Annotatable annotate :version, :description, :url, :extension_name, :path attr_writer :active def active? @active end def root path.to_s end def migrated? migrator.new(:up, migrations_path).pending_migrati...
grpc/grpc
src/ruby/lib/grpc/generic/bidi_call.rb
GRPC.BidiCall.run_on_client
ruby
def run_on_client(requests, set_input_stream_done, set_output_stream_done, &blk) @enq_th = Thread.new do write_loop(requests, set_output_stream_done: set_output_stream_done) end read_loop(set_input_stream_done, &blk) end
Creates a BidiCall. BidiCall should only be created after a call is accepted. That means different things on a client and a server. On the client, the call is accepted after call.invoke. On the server, this is after call.accept. #initialize cannot determine if the call is accepted or not; so if a call that's n...
train
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/bidi_call.rb#L70-L78
class BidiCall include Core::CallOps include Core::StatusCodes include Core::TimeConsts # Creates a BidiCall. # # BidiCall should only be created after a call is accepted. That means # different things on a client and a server. On the client, the call is # accepted after call.invoke...
state-machines/state_machines
lib/state_machines/node_collection.rb
StateMachines.NodeCollection.update_index
ruby
def update_index(name, node) index = self.index(name) old_key = index.key(node) new_key = value(node, name) # Only replace the key if it's changed if old_key != new_key remove_from_index(name, old_key) add_to_index(name, new_key, node) end end
Updates the node for the given index, including the string and symbol versions of the index
train
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/node_collection.rb#L196-L206
class NodeCollection include Enumerable # The machine associated with the nodes attr_reader :machine # Creates a new collection of nodes for the given state machine. By default, # the collection is empty. # # Configuration options: # * <tt>:index</tt> - One or more attributes to aut...
NCSU-Libraries/lentil
lib/lentil/instagram_harvester.rb
Lentil.InstagramHarvester.harvest_image_data
ruby
def harvest_image_data(image) response = Typhoeus.get(image.large_url(false), followlocation: true) if response.success? raise "Invalid content type: " + response.headers['Content-Type'] unless (response.headers['Content-Type'] == 'image/jpeg') elsif response.timed_out? raise "Request...
Retrieve the binary image data for a given Image object @param [Image] image An Image model object from the Instagram service @raise [Exception] If there are request problems @return [String] Binary image data
train
https://github.com/NCSU-Libraries/lentil/blob/c31775447a52db1781c05f6724ae293698527fe6/lib/lentil/instagram_harvester.rb#L206-L220
class InstagramHarvester # # Configure the Instagram class in preparation requests. # # @options opts [String] :client_id (Lentil::Engine::APP_CONFIG["instagram_client_id"]) The Instagram client ID # @options opts [String] :client_secret (Lentil::Engine::APP_CONFIG["instagram_client_secret"]) The...
simplymadeapps/simple_scheduler
lib/simple_scheduler/future_job.rb
SimpleScheduler.FutureJob.perform
ruby
def perform(task_params, scheduled_time) @task = Task.new(task_params) @scheduled_time = Time.at(scheduled_time).in_time_zone(@task.time_zone) raise Expired if expired? queue_task end
Perform the future job as defined by the task. @param task_params [Hash] The params from the scheduled task @param scheduled_time [Integer] The epoch time for when the job was scheduled to be run
train
https://github.com/simplymadeapps/simple_scheduler/blob/4d186042507c1397ee79a5e8fe929cc14008c026/lib/simple_scheduler/future_job.rb#L22-L28
class FutureJob < ActiveJob::Base # An error class that is raised if a job does not run because the run time is # too late when compared to the scheduled run time. # @!attribute run_time # @return [Time] The actual run time # @!attribute scheduled_time # @return [Time] The scheduled run ti...
sds/haml-lint
lib/haml_lint/tree/tag_node.rb
HamlLint::Tree.TagNode.dynamic_attributes_sources
ruby
def dynamic_attributes_sources @dynamic_attributes_sources ||= if Gem::Version.new(Haml::VERSION) < Gem::Version.new('5') @value[:attributes_hashes] else Array(@value[:dynamic_attributes].to_literal).reject(&:empty?) end end
rubocop:disable ClassLength Computed set of attribute hashes code. This is a combination of all dynamically calculated attributes from the different attribute setting syntaxes (`{...}`/`(...)`), converted into Ruby code. @note This has to be memoized because of a design decision in Haml 5. When calling `Dynamic...
train
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/tree/tag_node.rb#L19-L26
class TagNode < Node # rubocop:disable ClassLength # Computed set of attribute hashes code. # # This is a combination of all dynamically calculated attributes from the # different attribute setting syntaxes (`{...}`/`(...)`), converted into # Ruby code. # # @note This has to be memoized be...
robertwahler/repo_manager
lib/repo_manager/settings.rb
RepoManager.Settings.configure
ruby
def configure(options) # config file default options configuration = { :options => { :verbose => false, :color => 'AUTO', :short => false, :unmodified => 'HIDE', ...
read options from YAML config
train
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/settings.rb#L38-L94
class Settings < Hash include RepoManager::Extensions::MethodReader include RepoManager::Extensions::MethodWriter def initialize(working_dir=nil, options={}) @working_dir = working_dir || FileUtils.pwd @configuration = configure(options.deep_clone) # call super without args super...
DigitPaint/roger
lib/roger/resolver.rb
Roger.Resolver.find_template_path
ruby
def find_template_path(name, options = {}) options = { prefer: "html", # Prefer a template with extension }.update(options) path = sanitize_name(name, options[:prefer]) # Exact match return Pathname.new(path) if File.exist?(path) # Split extension and path path_exten...
Finds the template path for "name"
train
https://github.com/DigitPaint/roger/blob/1153119f170d1b0289b659a52fcbf054df2d9633/lib/roger/resolver.rb#L117-L145
class Resolver # Maps output extensions to template extensions to find # source files. EXTENSION_MAP = { "html" => %w( rhtml markdown mkd md ad adoc asciidoc rdoc textile ), "csv" => %w( rcsv ), #...
kristianmandrup/roles_generic
lib/roles_generic/generic/user/implementation.rb
Roles::Generic::User.Implementation.role=
ruby
def role= role raise ArgumentError, '#add_role takes a single role String or Symbol as the argument' if !role || role.kind_of?(Array) self.roles = role end
set a single role
train
https://github.com/kristianmandrup/roles_generic/blob/94588ac58bcca1f44ace5695d1984da1bd98fe1a/lib/roles_generic/generic/user/implementation.rb#L10-L13
module Implementation include Roles::Generic::RoleUtil def role_attribute strategy_class.roles_attribute_name end # set a single role # add a single role def add_role role raise ArgumentError, '#add_role takes a single role String or Symbol as the argument' if !...
jhund/filterrific
lib/filterrific/action_view_extension.rb
Filterrific.ActionViewExtension.filterrific_sorting_link_reverse_order
ruby
def filterrific_sorting_link_reverse_order(filterrific, new_sort_key, opts) # current sort column, toggle search_direction new_sort_direction = 'asc' == opts[:current_sort_direction] ? 'desc' : 'asc' new_sorting = safe_join([new_sort_key, new_sort_direction], '_') css_classes = safe_join([ ...
Renders HTML to reverse sort order on currently sorted column. @param filterrific [Filterrific::ParamSet] @param new_sort_key [String] @param opts [Hash] @return [String] an HTML fragment
train
https://github.com/jhund/filterrific/blob/811edc57d3e2a3e538c1f0e9554e0909be052881/lib/filterrific/action_view_extension.rb#L102-L119
module ActionViewExtension include HasResetFilterrificUrlMixin # Sets all options on form_for to defaults that work with Filterrific # @param record [Filterrific] the @filterrific object # @param options [Hash] standard options for form_for # @param block [Proc] the form body def form_for_fi...
NCSU-Libraries/quick_search
app/controllers/quick_search/search_controller.rb
QuickSearch.SearchController.xhr_search
ruby
def xhr_search endpoint = params[:endpoint] if params[:template] == 'with_paging' template = 'xhr_response_with_paging' else template = 'xhr_response' end @query = params_q_scrubbed @page = page @per_page = per_page(endpoint) @offset = offset(@page,@per_...
The following searches for individual sections of the page. This allows us to do client-side requests in cases where the original server-side request times out or otherwise fails.
train
https://github.com/NCSU-Libraries/quick_search/blob/2e2c3f8682eed63a2bf2c008fa77f04ff9dd6a03/app/controllers/quick_search/search_controller.rb#L46-L119
class SearchController < ApplicationController include QuickSearch::SearcherConcern include QuickSearch::DoiTrap include QuickSearch::OnCampus include QuickSearch::QueryParser include QuickSearch::EncodeUtf8 include QuickSearch::QueryFilter include QuickSearch::SearcherConfig require ...
puppetlabs/beaker-hostgenerator
lib/beaker-hostgenerator/generator.rb
BeakerHostGenerator.Generator.unstringify_value
ruby
def unstringify_value(value) result = Integer(value) rescue value if value == 'true' result = true elsif value == 'false' result = false elsif value.kind_of?(Array) value.each_with_index do |v, i| result[i] = unstringify_value(v) end end resu...
Attempts to convert numeric strings and boolean strings into proper integer and boolean types. If value is an array, it will recurse through those values. Returns the input value if it's not a number string or boolean string. For example "123" would be converted to 123, and "true"/"false" would be converted to tru...
train
https://github.com/puppetlabs/beaker-hostgenerator/blob/276830215efedf00f133ddedc8b636c25d7510c4/lib/beaker-hostgenerator/generator.rb#L146-L158
class Generator include BeakerHostGenerator::Data include BeakerHostGenerator::Parser include BeakerHostGenerator::Roles # Main host generation entry point, returns a Ruby map for the given host # specification and optional configuration. # # @param layout [String] The raw hosts specifica...
iyuuya/jkf
lib/jkf/parser/ki2.rb
Jkf::Parser.Ki2.parse_fork
ruby
def parse_fork s0 = @current_pos if match_str("変化:") != :failed match_spaces s3 = match_digits! if s3 != :failed if match_str("手") != :failed if parse_nl != :failed s6 = parse_moves if s6 != :failed @reported_pos = s0 ...
fork : "変化:" " "* [0-9]+ "手" nl moves
train
https://github.com/iyuuya/jkf/blob/4fd229c50737cab7b41281238880f1414e55e061/lib/jkf/parser/ki2.rb#L316-L349
class Ki2 < Base include Kifuable protected # kifu : header* initialboard? header* moves fork* def parse_root s0 = @current_pos s1 = [] s2 = parse_header while s2 != :failed s1 << s2 s2 = parse_header end if s1 != :failed s2 = parse_initial...
mailgun/mailgun-ruby
lib/mailgun/response.rb
Mailgun.Response.to_yaml
ruby
def to_yaml YAML.dump(to_h) rescue => err raise ParseError.new(err), err end
Return response as Yaml @return [String] A string containing response as YAML
train
https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/response.rb#L47-L51
class Response # All responses have a payload and a code corresponding to http, though # slightly different attr_accessor :body, :code def self.from_hash(h) # Create a "fake" response object with the data passed from h self.new OpenStruct.new(h) end def initialize(response) ...
CocoaPods/Xcodeproj
lib/xcodeproj/project.rb
Xcodeproj.Project.reference_for_path
ruby
def reference_for_path(absolute_path) absolute_pathname = Pathname.new(absolute_path) unless absolute_pathname.absolute? raise ArgumentError, "Paths must be absolute #{absolute_path}" end objects.find do |child| child.isa == 'PBXFileReference' && child.real_path == absolute_pat...
Returns the file reference for the given absolute path. @param [#to_s] absolute_path The absolute path of the file whose reference is needed. @return [PBXFileReference] The file reference. @return [Nil] If no file reference could be found.
train
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/project.rb#L553-L563
class Project include Object # @return [Pathname] the path of the project. # attr_reader :path # @return [Pathname] the directory of the project # attr_reader :project_dir # @param [Pathname, String] path @see path # The path provided will be expanded to an absolute pat...
lostisland/faraday
lib/faraday/connection.rb
Faraday.Connection.run_request
ruby
def run_request(method, url, body, headers) unless METHODS.include?(method) raise ArgumentError, "unknown http method: #{method}" end # Resets temp_proxy @temp_proxy = proxy_for_request(url) request = build_request(method) do |req| req.options = req.options.merge(proxy: @...
Builds and runs the Faraday::Request. @param method [Symbol] HTTP method. @param url [String, URI] String or URI to access. @param body [Object] The request body that will eventually be converted to a string. @param headers [Hash] unencoded HTTP header key/value pairs. @return [Faraday::Response]
train
https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/lib/faraday/connection.rb#L488-L505
class Connection # A Set of allowed HTTP verbs. METHODS = Set.new %i[get post put delete head patch options trace connect] # @return [Hash] URI query unencoded key/value pairs. attr_reader :params # @return [Hash] unencoded HTTP header key/value pairs. attr_reader :headers # @return [St...
pusher/pusher-http-ruby
lib/pusher/channel.rb
Pusher.Channel.authentication_string
ruby
def authentication_string(socket_id, custom_string = nil) validate_socket_id(socket_id) unless custom_string.nil? || custom_string.kind_of?(String) raise Error, 'Custom argument must be a string' end string_to_sign = [socket_id, name, custom_string]. compact.map(&:to_s).join(':...
Compute authentication string required as part of the authentication endpoint response. Generally the authenticate method should be used in preference to this one @param socket_id [String] Each Pusher socket connection receives a unique socket_id. This is sent from pusher.js to your server when channel authen...
train
https://github.com/pusher/pusher-http-ruby/blob/cd666ca74b39dacfae6ca0235c35fcf80eba1e64/lib/pusher/channel.rb#L128-L143
class Channel attr_reader :name INVALID_CHANNEL_REGEX = /[^A-Za-z0-9_\-=@,.;]/ def initialize(_, name, client = Pusher) if Pusher::Channel::INVALID_CHANNEL_REGEX.match(name) raise Pusher::Error, "Illegal channel name '#{name}'" elsif name.length > 200 raise Pusher::Error, "Cha...
litaio/lita
lib/lita/configuration_validator.rb
Lita.ConfigurationValidator.validate
ruby
def validate(type, plugin, attributes, attribute_namespace = []) attributes.each do |attribute| if attribute.children? validate(type, plugin, attribute.children, attribute_namespace.clone.push(attribute.name)) elsif attribute.required? && attribute.value.nil? registry.logger.fa...
Validates an array of attributes, recursing if any nested attributes are encountered.
train
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/configuration_validator.rb#L57-L70
class ConfigurationValidator # @param registry [Registry] The registry containing the configuration to validate. def initialize(registry) self.registry = registry end # Validates adapter and handler configuration. Logs a fatal warning and aborts if any required # configuration attributes ar...
kristianmandrup/roles_generic
lib/roles_generic/generic/user/implementation.rb
Roles::Generic::User.Implementation.is_in_groups?
ruby
def is_in_groups? *groups groups = groups.flat_uniq groups.all? {|group| is_in_group? group} end
is_in_groups? :editor, :admin,
train
https://github.com/kristianmandrup/roles_generic/blob/94588ac58bcca1f44ace5695d1984da1bd98fe1a/lib/roles_generic/generic/user/implementation.rb#L56-L59
module Implementation include Roles::Generic::RoleUtil def role_attribute strategy_class.roles_attribute_name end # set a single role def role= role raise ArgumentError, '#add_role takes a single role String or Symbol as the argument' if !role || role.kind_of?(Array) ...
murb/workbook
lib/workbook/column.rb
Workbook.Column.table=
ruby
def table= table raise(ArgumentError, "value should be nil or Workbook::Table") unless [NilClass,Workbook::Table].include? table.class @table = table end
Set the table this column belongs to @param [Workbook::Table] table this column belongs to
train
https://github.com/murb/workbook/blob/2e12f43c882b7c235455192a2fc48183fe6ec965/lib/workbook/column.rb#L43-L46
class Column attr_accessor :limit, :width #character limit def initialize(table=nil, options={}) self.table = table options.each{ |k,v| self.public_send("#{k}=",v) } end # Returns column type, either :primary_key, :string, :text, :integer, :float, :decimal, :datetime, :date, :binary, :bo...
zhimin/rwebspec
lib/rwebspec-common/database_checker.rb
RWebSpec.DatabaseChecker.connect_to_database
ruby
def connect_to_database(db_settings, force = false) # only setup database connection once if force ActiveRecord::Base.establish_connection(db_settings) else begin ActiveRecord::Base.connection rescue => e require 'pp' pp db_settings puts ...
Connect to databse, example mysql_db(:host => "localhost", :database => "lavabuild_local", :user => "root", :password => "")
train
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-common/database_checker.rb#L42-L56
module DatabaseChecker # Example # connect_to_database mysql_db(:host => "localhost", :database => "lavabuild_local", :user => "root", :password => ""), true def mysql_db(settings) options = {:adapter => "mysql"} options.merge!(settings) end # connect_to_database sqlite3_db(:databa...
dagrz/nba_stats
lib/nba_stats/stats/box_score_scoring.rb
NbaStats.BoxScoreScoring.box_score_scoring
ruby
def box_score_scoring( game_id, range_type=0, start_period=0, end_period=0, start_range=0, end_range=0 ) NbaStats::Resources::BoxScoreScoring.new( get(BOX_SCORE_SCORING_PATH, { :GameID => game_id, :RangeType => range_type, ...
Calls the boxscorescoring API and returns a BoxScoreScoring resource. @param game_id [String] @param range_type [Integer] @param start_period [Integer] @param end_period [Integer] @param start_range [Integer] @param end_range [Integer] @return [NbaStats::Resources::BoxScoreScoring]
train
https://github.com/dagrz/nba_stats/blob/d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa/lib/nba_stats/stats/box_score_scoring.rb#L19-L37
module BoxScoreScoring # The path of the boxscorescoring API BOX_SCORE_SCORING_PATH = '/stats/boxscorescoring' # Calls the boxscorescoring API and returns a BoxScoreScoring resource. # # @param game_id [String] # @param range_type [Integer] # @param start_period [Integer] # @param ...
DigitPaint/roger
lib/roger/renderer.rb
Roger.Renderer.get_default_layout
ruby
def get_default_layout(template, options) source_ext = Renderer.source_extension_for(template.source_path) options[:layout][source_ext] if options.key?(:layout) end
Gets the default layout that can be specified by the Rogerfile: roger.project.options[:renderer][:layout] = { "html.erb" => "default" }
train
https://github.com/DigitPaint/roger/blob/1153119f170d1b0289b659a52fcbf054df2d9633/lib/roger/renderer.rb#L230-L233
class Renderer MAX_ALLOWED_TEMPLATE_NESTING = 10 class << self # Register a helper module that should be included in # every template context. def helper(mod) @helpers ||= [] @helpers << mod end def helpers @helpers || [] end # Will the rend...
stripe/stripe-ruby
lib/stripe/stripe_client.rb
Stripe.StripeClient.format_app_info
ruby
def format_app_info(info) str = info[:name] str = "#{str}/#{info[:version]}" unless info[:version].nil? str = "#{str} (#{info[:url]})" unless info[:url].nil? str end
Formats a plugin "app info" hash into a string that we can tack onto the end of a User-Agent string where it'll be fairly prominent in places like the Dashboard. Note that this formatting has been implemented to match other libraries, and shouldn't be changed without universal consensus.
train
https://github.com/stripe/stripe-ruby/blob/322a8c60be8a9b9ac8aad8857864680a32176935/lib/stripe/stripe_client.rb#L319-L324
class StripeClient attr_accessor :conn # Initializes a new StripeClient. Expects a Faraday connection object, and # uses a default connection unless one is passed. def initialize(conn = nil) self.conn = conn || self.class.default_conn @system_profiler = SystemProfiler.new @last_requ...
arvicco/win_gui
old_code/lib/win_gui/def_api.rb
WinGui.DefApi.callback
ruby
def callback(params, returns, &block) Win32::API::Callback.new(params, returns, &block) end
Converts block into API::Callback object that can be used as API callback argument
train
https://github.com/arvicco/win_gui/blob/a3a4c18db2391144fcb535e4be2f0fb47e9dcec7/old_code/lib/win_gui/def_api.rb#L88-L90
module DefApi # DLL to use with API decarations by default ('user32') DEFAULT_DLL = 'user32' ## # Defines new method wrappers for Windows API function call: # - Defines method with original (CamelCase) API function name and original signature (matches MSDN description) # - Defines method ...
NCSU-Libraries/quick_search
app/controllers/quick_search/logging_controller.rb
QuickSearch.LoggingController.send_event_to_ga
ruby
def send_event_to_ga(category, action, label) # google_analytics_client_id is a UUID that identifies a particular client to the GA Measurement Protocol API if QuickSearch::Engine::APP_CONFIG['google_analytics_tracking_id'].blank? or QuickSearch::Engine::APP_CONFIG['google_analytics_client_id'].blank? ...
Logs an event to Google Analytics using the Measurement Protocol API https://developers.google.com/analytics/devguides/collection/protocol/v1/
train
https://github.com/NCSU-Libraries/quick_search/blob/2e2c3f8682eed63a2bf2c008fa77f04ff9dd6a03/app/controllers/quick_search/logging_controller.rb#L66-L95
class LoggingController < ApplicationController include QuickSearch::OnCampus before_action :handle_session protect_from_forgery except: :log_event ## # Logs a search to the database # # This is an API endpoint for logging a search. It requires that at least a search query and a page ar...