code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def version ["lib/#{name}.rb", "lib/#{name}/version.rb"].each do |v| path = project_path(v) line = path.read[/^\s*VERSION\s*=\s*.*/] return line.match(/.*VERSION\s*=\s*['"](.*)['"]/)[1] if line end end
Public: return the version of ThisProject Search the ruby files in the project looking for the one that has the version string in it. This does not eval any code in the project, it parses the source code looking for the string. Returns a String version
version
ruby
copiousfreetime/launchy
tasks/this.rb
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
ISC
def section_of(file, section_name) re = /^[=#]+ (.*)$/ sectional = project_path(file) parts = sectional.read.split(re)[1..] parts.map!(&:strip) sections = {} Hash[*parts].each do |k, v| sections[k] = v.split("\n\n") end sections[section_name] end
Internal: Return a section of an RDoc file with the given section name path - the relative path in the project of the file to parse section_name - the section out of the file from which to parse data Retuns the text of the section as an array of paragrphs.
section_of
ruby
copiousfreetime/launchy
tasks/this.rb
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
ISC
def task_warning(task) warn "WARNING: '#{task}' tasks are not defined. Please run 'bin/setup'" end
Internal: print out a warning about the give task
task_warning
ruby
copiousfreetime/launchy
tasks/this.rb
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
ISC
def project_root this_file_path.ascend do |p| rakefile = p.join("Rakefile") return p if rakefile.exist? end end
Internal: The root directory of this project This is defined as being the directory that is in the path of this project that has the first Rakefile Returns the Pathname of the directory
project_root
ruby
copiousfreetime/launchy
tasks/this.rb
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
ISC
def manifest manifest_file = project_path("Manifest.txt") abort "You need a Manifest.txt" unless manifest_file.readable? manifest_file.readlines.map(&:strip) end
Internal: Returns the contents of the Manifest.txt file as an array Returns an Array of strings
manifest
ruby
copiousfreetime/launchy
tasks/this.rb
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
ISC
def platform_gemspec gemspecs.fetch(platform) { This.ruby_gemspec } end
Internal: Returns the gemspace associated with the current ruby platform
platform_gemspec
ruby
copiousfreetime/launchy
tasks/this.rb
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
ISC
def ruby_gemspec(core = core_gemspec, &) yielding_gemspec("ruby", core, &) end
Internal: Return the gemspec for the ruby platform
ruby_gemspec
ruby
copiousfreetime/launchy
tasks/this.rb
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
ISC
def java_gemspec(core = core_gemspec, &) yielding_gemspec("java", core, &) end
Internal: Return the gemspec for the jruby platform
java_gemspec
ruby
copiousfreetime/launchy
tasks/this.rb
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
ISC
def yielding_gemspec(key, core) spec = gemspecs[key] ||= core.dup spec.platform = key yield spec if block_given? spec end
Internal: give an initial spec and a key, create a new gemspec based off of it. This will force the new gemspecs 'platform' to be that of the key, since the only reason you would have multiple gemspecs at this point is to deal with different platforms.
yielding_gemspec
ruby
copiousfreetime/launchy
tasks/this.rb
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
ISC
def platform (RUBY_PLATFORM == "java") ? "java" : Gem::Platform::RUBY end
Internal: Return the platform of ThisProject at the current moment in time.
platform
ruby
copiousfreetime/launchy
tasks/this.rb
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
ISC
def description_section section_of("README.md", "DESCRIPTION") end
Internal: Return the DESCRIPTION section of the README.rdoc file
description_section
ruby
copiousfreetime/launchy
tasks/this.rb
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
ISC
def description description_section.join(" ").tr("\n", " ").gsub(/[{}]/, "").gsub(/\[[^\]]+\]/, "") # strip rdoc end
Internal: Return the full description text from the README
description
ruby
copiousfreetime/launchy
tasks/this.rb
https://github.com/copiousfreetime/launchy/blob/master/tasks/this.rb
ISC
def configure yield(configuration); nil end
# This method is used to configure HireFire @yield [config] the instance of HireFire::Configuration class @yieldparam [Fixnum] max_workers default: 1 (set at least 1) @yieldparam [Array] job_worker_ratio default: see example @yieldparam [Symbol, nil] environment (:heroku, :local, :noop or nil) - default: nil @note Every param has it's own defaults. It's best to leave the environment param at "nil". When environment is set to "nil", it'll default to the :noop environment. This basically means that you have to run "rake jobs:work" yourself from the console to get the jobs running in development mode. In production, it'll automatically use :heroku if deployed to the Heroku platform. @example HireFire.configure do |config| config.environment = nil config.max_workers = 5 config.min_workers = 0 config.job_worker_ratio = [ { :jobs => 1, :workers => 1 }, { :jobs => 15, :workers => 2 }, { :jobs => 35, :workers => 3 }, { :jobs => 60, :workers => 4 }, { :jobs => 80, :workers => 5 } ] end @return [nil]
configure
ruby
hirefire/hirefire
lib/hirefire.rb
https://github.com/hirefire/hirefire/blob/master/lib/hirefire.rb
MIT
def configuration @configuration ||= HireFire::Configuration.new end
# Instantiates a new HireFire::Configuration instance and instance variable caches it
configuration
ruby
hirefire/hirefire
lib/hirefire.rb
https://github.com/hirefire/hirefire/blob/master/lib/hirefire.rb
MIT
def initialize @max_workers = 1 @min_workers = 0 @job_worker_ratio = [ { :jobs => 1, :workers => 1 }, { :jobs => 25, :workers => 2 }, { :jobs => 50, :workers => 3 }, { :jobs => 75, :workers => 4 }, { :jobs => 100, :workers => 5 } ] end
# Instantiates a new HireFire::Configuration object with the default configuration. These default configurations may be overwritten using the HireFire.configure class method @return [HireFire::Configuration]
initialize
ruby
hirefire/hirefire
lib/hirefire/configuration.rb
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/configuration.rb
MIT
def environment @environment ||= HireFire::Environment.const_get( if environment = HireFire.configuration.environment environment.to_s.camelize else ENV.include?('HEROKU_UPID') ? 'Heroku' : 'Noop' end ).new end
# Returns the environment class method (containing an instance of the proper environment class) for either Delayed::Job or Resque::Job If HireFire.configuration.environment is nil (the default) then it'll auto-detect which environment to run in (either Heroku or Noop) If HireFire.configuration.environment isn't nil (explicitly set) then it'll run in the specified environment (Heroku, Local or Noop) @return [HireFire::Environment::Heroku, HireFire::Environment::Local, HireFire::Environment::Noop]
environment
ruby
hirefire/hirefire
lib/hirefire/environment.rb
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/environment.rb
MIT
def hirefire_hire delayed_job = ::Delayed::Job.new if delayed_job.working == 0 \ or delayed_job.jobs == 1 environment.hire end end
# This method is an attempt to improve web-request throughput. A class method for Delayed::Job which first checks if any worker is currently running by checking to see if there are any jobs locked by a worker. If there aren't any jobs locked by a worker there is a high chance that there aren't any workers running. If this is the case, then we sure also invoke the 'self.class.environment.hire' method Another check is to see if there is only 1 job (which is the one that was just added before this callback invoked). If this is the case then it's very likely there aren't any workers running and we should invoke the 'self.class.environment.hire' method to make sure this is the case. @return [nil]
hirefire_hire
ruby
hirefire/hirefire
lib/hirefire/environment.rb
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/environment.rb
MIT
def jobs ::Delayed::Job. where(:failed_at => nil). where('run_at <= ?', Time.now).count end
# Counts the amount of queued jobs in the database, failed jobs are excluded from the sum @return [Fixnum] the amount of pending jobs
jobs
ruby
hirefire/hirefire
lib/hirefire/backend/delayed_job/active_record.rb
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/backend/delayed_job/active_record.rb
MIT
def working ::Delayed::Job. where('locked_by IS NOT NULL').count end
# Counts the amount of jobs that are locked by a worker There is no other performant way to determine the amount of workers there currently are @return [Fixnum] the amount of (assumably working) workers
working
ruby
hirefire/hirefire
lib/hirefire/backend/delayed_job/active_record.rb
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/backend/delayed_job/active_record.rb
MIT
def jobs ::Delayed::Job.all( :conditions => ['failed_at IS NULL and run_at <= ?', Time.now.utc] ).count end
# Counts the amount of queued jobs in the database, failed jobs are excluded from the sum @return [Fixnum] the amount of pending jobs
jobs
ruby
hirefire/hirefire
lib/hirefire/backend/delayed_job/active_record_2.rb
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/backend/delayed_job/active_record_2.rb
MIT
def working ::Delayed::Job.all( :conditions => 'locked_by IS NOT NULL' ).count end
# Counts the amount of jobs that are locked by a worker There is no other performant way to determine the amount of workers there currently are @return [Fixnum] the amount of (assumably working) workers
working
ruby
hirefire/hirefire
lib/hirefire/backend/delayed_job/active_record_2.rb
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/backend/delayed_job/active_record_2.rb
MIT
def jobs ::Delayed::Job.count(:failed_at => nil, :run_at.lte => Time.now.utc) end
# Counts the amount of queued jobs in the database, failed jobs are excluded from the sum @return [Fixnum] the amount of pending jobs
jobs
ruby
hirefire/hirefire
lib/hirefire/backend/delayed_job/data_mapper.rb
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/backend/delayed_job/data_mapper.rb
MIT
def working ::Delayed::Job.count(:locked_by.not => nil) end
# Counts the amount of jobs that are locked by a worker There is no other performant way to determine the amount of workers there currently are @return [Fixnum] the amount of (assumably working) workers
working
ruby
hirefire/hirefire
lib/hirefire/backend/delayed_job/data_mapper.rb
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/backend/delayed_job/data_mapper.rb
MIT
def jobs ::Delayed::Job.where( :failed_at => nil, :run_at.lte => Time.now ).count end
# Counts the amount of queued jobs in the database, failed jobs and jobs scheduled for the future are excluded @return [Fixnum]
jobs
ruby
hirefire/hirefire
lib/hirefire/backend/delayed_job/mongoid.rb
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/backend/delayed_job/mongoid.rb
MIT
def working ::Delayed::Job. where(:locked_by.ne => nil).count end
# Counts the amount of jobs that are locked by a worker There is no other performant way to determine the amount of workers there currently are @return [Fixnum] the amount of (assumably working) workers
working
ruby
hirefire/hirefire
lib/hirefire/backend/delayed_job/mongoid.rb
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/backend/delayed_job/mongoid.rb
MIT
def hire jobs_count = jobs workers_count = workers || return ## # Use "Standard Notation" if not ratio.first[:when].respond_to? :call ## # Since the "Standard Notation" is defined in the in an ascending order # in the array of hashes, we need to reverse this order in order to properly # loop through and break out of the array at the correctly matched ratio ratio.reverse! ## # Iterates through all the defined job/worker ratio's # until it finds a match. Then it hires (if necessary) the appropriate # amount of workers and breaks out of the loop ratio.each do |ratio| ## # Standard notation # This is the code for the default notation # # @example # { :jobs => 35, :workers => 3 } # if jobs_count >= ratio[:jobs] and max_workers >= ratio[:workers] if workers_count < ratio[:workers] log_and_hire(ratio[:workers]) end return end end ## # If no match is found in the above job/worker ratio loop, then we'll # perform one last operation to see whether the the job count is greater # than the highest job/worker ratio, and if this is the case then we also # check to see whether the maximum amount of allowed workers is greater # than the amount that are currently running, if this is the case, we are # allowed to hire the max amount of workers. if jobs_count >= ratio.first[:jobs] and max_workers > workers_count log_and_hire(max_workers) return end end ## # Use "Functional (Lambda) Notation" if ratio.first[:when].respond_to? :call ## # Iterates through all the defined job/worker ratio's # until it finds a match. Then it hires (if necessary) the appropriate # amount of workers and breaks out of the loop ratio.each do |ratio| ## # Functional (Lambda) Notation # This is the code for the Lambda notation, more verbose, # but more humanly understandable # # @example # { :when => lambda {|jobs| jobs < 60 }, :workers => 3 } # if ratio[:when].call(jobs_count) and max_workers >= ratio[:workers] if workers_count < ratio[:workers] log_and_hire(ratio[:workers]) end break end end end ## # Applies only to the Functional (Lambda) Notation # If the amount of queued jobs exceeds that of which was defined in the # job/worker ratio array, it will hire the maximum amount of workers # # "if statements": # 1. true if we use the Functional (Lambda) Notation # 2. true if the last ratio (highest job/worker ratio) was exceeded # 3. true if the max amount of workers are not yet running # # If all the the above statements are true, HireFire will hire the maximum # amount of workers that were specified in the configuration # if ratio.last[:when].respond_to? :call \ and ratio.last[:when].call(jobs_count) === false \ and max_workers != workers_count log_and_hire(max_workers) end end
# This method gets invoked when a new job has been queued Iterates through the default (or user-defined) job/worker ratio until it finds a match for the for the current situation (see example). @example # Say we have 40 queued jobs, and we configured our job/worker ratio like so: HireFire.configure do |config| config.max_workers = 5 config.min_workers = 0 config.job_worker_ratio = [ { :jobs => 1, :workers => 1 }, { :jobs => 15, :workers => 2 }, { :jobs => 35, :workers => 3 }, { :jobs => 60, :workers => 4 }, { :jobs => 80, :workers => 5 } ] end # It'll match at { :jobs => 35, :workers => 3 }, (35 jobs or more: hire 3 workers) # meaning that it'll ensure there are 3 workers running. # If there were already were 3 workers, it'll leave it as is. # Alternatively, you can use a more functional syntax, which works in the same way. HireFire.configure do |config| config.max_workers = 5 config.job_worker_ratio = [ { :when => lambda {|jobs| jobs < 15 }, :workers => 1 }, { :when => lambda {|jobs| jobs < 35 }, :workers => 2 }, { :when => lambda {|jobs| jobs < 60 }, :workers => 3 }, { :when => lambda {|jobs| jobs < 80 }, :workers => 4 } ] end # If there were more than 3 workers running (say, 4 or 5), it will NOT reduce # the number. This is because when you reduce the number of workers, you cannot # tell which worker Heroku will shut down, meaning you might interrupt a worker # that's currently working, causing the job to fail. Also, consider the fact that # there are, for example, 35 jobs still to be picked up, so the more workers, # the faster it processes. You aren't even paying more because it doesn't matter whether # you have 1 worker, or 5 workers processing jobs, because workers are pro-rated to the second. # So basically 5 workers would cost 5 times more, but will also process 5 times faster. # Once all jobs finished processing (e.g. Delayed::Job.jobs == 0), HireFire will invoke a signal # which will set the workers back to 0 and shuts down all the workers simultaneously. @return [nil]
hire
ruby
hirefire/hirefire
lib/hirefire/environment/base.rb
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/environment/base.rb
MIT
def fire if jobs == 0 and workers > min_workers Logger.message("All queued jobs have been processed. " + (min_workers > 0 ? "Setting workers to #{min_workers}." : "Firing all workers.")) workers(min_workers) return true end return false end
# This method gets invoked when a job is either "destroyed" or "updated, unless the job didn't fail" If there are workers active, but there are no more pending jobs, then fire all the workers or set to the minimum_workers @return [Boolean] if the workers have been fired
fire
ruby
hirefire/hirefire
lib/hirefire/environment/base.rb
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/environment/base.rb
MIT
def log_and_hire(amount) Logger.message("Hiring more workers so we have #{ amount } in total.") workers(amount) end
# Helper method for hire that logs the hiring of more workers, then hires those workers. @return [nil]
log_and_hire
ruby
hirefire/hirefire
lib/hirefire/environment/base.rb
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/environment/base.rb
MIT
def workers(amount = nil) # # Returns the amount of Delayed Job # workers that are currently running on Heroku if amount.nil? return client.info(ENV['APP_NAME'])[:workers].to_i end ## # Sets the amount of Delayed Job # workers that need to be running on Heroku client.set_workers(ENV['APP_NAME'], amount) rescue RestClient::Exception # Heroku library uses rest-client, currently, and it is quite # possible to receive RestClient exceptions through the client. HireFire::Logger.message("Worker query request failed with #{ $!.class.name } #{ $!.message }") nil end
# Either retrieves the amount of currently running workers, or set the amount of workers to a specific amount by providing a value @overload workers(amount = nil) @param [Fixnum] amount will tell heroku to run N workers @return [nil] @overload workers(amount = nil) @param [nil] amount @return [Fixnum] will request the amount of currently running workers from Heroku
workers
ruby
hirefire/hirefire
lib/hirefire/environment/heroku.rb
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/environment/heroku.rb
MIT
def client @client ||= ::Heroku::Client.new( ENV['HIREFIRE_EMAIL'], ENV['HIREFIRE_PASSWORD'] ) end
# @return [Heroku::Client] instance of the heroku client
client
ruby
hirefire/hirefire
lib/hirefire/environment/heroku.rb
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/environment/heroku.rb
MIT
def workers(amount = nil) ## # Returns the amount of Delayed Job workers that are currently # running on the local machine if amount is nil if amount.nil? return Rush::Box.new.processes.filter( :cmdline => /rake jobs:work WORKER=HIREFIRE/ ).size end ## # Fire workers # # If the amount of workers required is set to 0 # then we fire all the workers and we return # # The worker that finished the last job will go ahead and # kill all the other (if any) workers first, and then kill itself afterwards if amount == 0 ## # Gather process ids from all HireFire workers pids = Rush::Box.new.processes.filter( :cmdline => /rake jobs:work WORKER=HIREFIRE/ ).map(&:pid) ## # Instantiate a new local (shell) connection shell = Rush::Connection::Local.new ## # Kill all Freelance workers, # except the one that's doing the killing (pids - [Rush.my_process.pid]).each do |pid| shell.kill_process(pid) end ## # Kill the last Freelance worker (self) Logger.message("There are now #{ amount } workers.") shell.kill_process(Rush.my_process.pid) return end ## # Hire workers # # If the amount of workers required is greater than # the amount of workers already working, then hire the # additional amount of workers required workers_count = workers if amount > workers_count (amount - workers_count).times do Rush::Box.new[Rails.root].bash( 'rake jobs:work WORKER=HIREFIRE', :background => true ) end end end
# Either retrieve the amount of currently running workers, or set the amount of workers to a specific amount by providing a value @overload workers(amount = nil) @param [Fixnum] amount will tell the local machine to run N workers @return [nil] @overload workers(amount = nil) @param [nil] amount @return [Fixnum] will request the amount of currently running workers from the local machine
workers
ruby
hirefire/hirefire
lib/hirefire/environment/local.rb
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/environment/local.rb
MIT
def start HireFire::Logger.message "Starting job worker!" trap('TERM') { HireFire::Logger.message 'Exiting...'; $exit = true } trap('INT') { HireFire::Logger.message 'Exiting...'; $exit = true } queued = Delayed::Job.new loop do ::Delayed::Job.environment.hire result = nil realtime = Benchmark.realtime do result = work_off end count = result.sum break if $exit if count.zero? sleep(1) else HireFire::Logger.message "#{count} jobs processed at %.4f j/s, %d failed ..." % [count / realtime, result.last] end ## # HireFire Hook # After the last job in the queue finishes processing, Delayed::Job.new.jobs (queued.jobs) # will return 0. This means that there aren't any more jobs to process for any of the workers. # If this is the case it'll command the current environment to fire all the hired workers # and then immediately break out of this infinite loop. if queued.jobs == 0 break if Delayed::Job.environment.fire end break if $exit end ensure Delayed::Job.clear_locks!(name) end
# @note This method gets invoked on heroku by the rake task "jobs:work" This is basically the same method as the Delayed Job version, except for the following: 1. All ouput will now go through the HireFire::Logger. 2. Invoke the ::Delayed::Job.environment.hire method at every loop to see whether we need to hire more workers so that we can delegate this task to the workers, rather than the web servers to improve web-throughput by avoiding any unnecessary API calls to Heroku. If there are any workers running, then the front end will never invoke API calls since the worker(s) can handle this itself. 3. When HireFire cannot find any jobs to process it sends the "fire" signal to all workers, ending all the processes simultaneously. The reason we wait for all the processes to finish before sending the signal is because it'll otherwise interrupt workers and leave jobs unfinished.
start
ruby
hirefire/hirefire
lib/hirefire/workers/delayed_job/worker.rb
https://github.com/hirefire/hirefire/blob/master/lib/hirefire/workers/delayed_job/worker.rb
MIT
def workers(amount = nil) if amount.nil? @_workers ||= 0 return @_workers end end
# Stubbed out since this normally comes from a sub class like HireFire::Environment::Heroku or HireFire::Environment::Local
workers
ruby
hirefire/hirefire
spec/environment_spec.rb
https://github.com/hirefire/hirefire/blob/master/spec/environment_spec.rb
MIT
def jobs @_jobs ||= 0 end
# Returns the amount of jobs Defaults to: 0
jobs
ruby
hirefire/hirefire
spec/environment_spec.rb
https://github.com/hirefire/hirefire/blob/master/spec/environment_spec.rb
MIT
def initialize(configuration) @printer = Printer.new @logger = Logger.new(configuration.logger_mode) @config = configuration @scanner = Scanner.new(options) end
Default +options+: { project_path: Pathname.pwd logger: nil, # can be :quiet or :debug decisions_file: "doc/dependency_decisions.yml", gradle_command: "gradle", rebar_command: "rebar", rebar_deps_dir: "deps", }
initialize
ruby
pivotal/LicenseFinder
lib/license_finder/core.rb
https://github.com/pivotal/LicenseFinder/blob/master/lib/license_finder/core.rb
MIT
def decision_applier # lazy, do not move to `initialize` # Needs to be lazy loaded to prvent multiple decision appliers being created each time @decision_applier ||= DecisionApplier.new(decisions: decisions, packages: current_packages) end
The core of the system. The saved decisions are applied to the current packages.
decision_applier
ruby
pivotal/LicenseFinder
lib/license_finder/core.rb
https://github.com/pivotal/LicenseFinder/blob/master/lib/license_finder/core.rb
MIT
def licenses @licenses ||= activations.map(&:license).sort_by(&:name).to_set end
# LICENSING # stubbed in tests, otherwise private # checked in tests, otherwise private
licenses
ruby
pivotal/LicenseFinder
lib/license_finder/package.rb
https://github.com/pivotal/LicenseFinder/blob/master/lib/license_finder/package.rb
MIT
def subcommand(namespace, klass, namespace_description) description = "#{namespace} [#{(klass.tasks.keys - ['help']).join('|')}]" desc description, "#{namespace_description} - see `license_finder #{namespace} help` for more information" super namespace, klass end
Helper to auto-generate the documentation for a group of commands
subcommand
ruby
pivotal/LicenseFinder
lib/license_finder/cli/patched_thor.rb
https://github.com/pivotal/LicenseFinder/blob/master/lib/license_finder/cli/patched_thor.rb
MIT
def banner(command, _namespace = nil, _subcommand = nil) "#{basename} #{underscore_name(name)} #{command.usage}" end
Hack to override the help message produced by Thor. https://github.com/wycats/thor/issues/261#issuecomment-16880836
banner
ruby
pivotal/LicenseFinder
lib/license_finder/cli/patched_thor.rb
https://github.com/pivotal/LicenseFinder/blob/master/lib/license_finder/cli/patched_thor.rb
MIT
def prepare_command "conda env create -f #{detected_package_path}" end
This command is *not* directly executable. See .conda() below.
prepare_command
ruby
pivotal/LicenseFinder
lib/license_finder/package_managers/conda.rb
https://github.com/pivotal/LicenseFinder/blob/master/lib/license_finder/package_managers/conda.rb
MIT
def maven_repository_path command = "#{package_management_command} help:evaluate -Dexpression=settings.localRepository -q -DforceStdout" command += " #{@maven_options}" unless @maven_options.nil? stdout, stderr, status = Dir.chdir(project_path) { Cmd.run(command) } raise "Command '#{command}' failed to execute: #{stderr}" unless status.success? Pathname(stdout) end
Look up the path of the Maven repository (e.g. ~/.m2)
maven_repository_path
ruby
pivotal/LicenseFinder
lib/license_finder/package_managers/maven.rb
https://github.com/pivotal/LicenseFinder/blob/master/lib/license_finder/package_managers/maven.rb
MIT
def filter_yarn_internal_package(all_packages) internal_package_pattern = /workspace-aggregator-[a-zA-z0-9]{8}-[a-zA-z0-9]{4}-[a-zA-z0-9]{4}-[a-zA-z0-9]{4}-[a-zA-z0-9]{12}/ yarn_internal_package = all_packages.find { |package| internal_package_pattern.match(package['Name']) } all_packages - [yarn_internal_package] end
remove fake package created by yarn [Yarn Bug]
filter_yarn_internal_package
ruby
pivotal/LicenseFinder
lib/license_finder/package_managers/yarn.rb
https://github.com/pivotal/LicenseFinder/blob/master/lib/license_finder/package_managers/yarn.rb
MIT
def add_info_from_pom(pom_file, dep) pom = XmlSimple.xml_in(pom_file.read, { 'ForceArray' => false }) name = pom['name'] dep.store('summary', name) unless name.nil? description = pom['description'] dep.store('description', description) unless description.nil? url = pom['url'] dep.store('homepage', url) unless url.nil? end
Extract name, description and URL from pom.xml
add_info_from_pom
ruby
pivotal/LicenseFinder
lib/license_finder/package_utils/maven_dependency_finder.rb
https://github.com/pivotal/LicenseFinder/blob/master/lib/license_finder/package_utils/maven_dependency_finder.rb
MIT
def config @_config ||= Config.new end
@return [Config] The global configuration object
config
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_rails.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_rails.rb
MIT
def initialize(llm:) # If the line below is called, the generator fails as calls to # LangchainrbRails.config.vectorsearch will generate an exception. # These happen in the template files. # depends_on "neighbor" @operator = OPERATORS[DEFAULT_OPERATOR] super(llm: llm) end
@param url [String] The URL of the PostgreSQL database @param index_name [String] The name of the table to use for the index @param llm [Object] The LLM client to use @param namespace [String] The namespace to use for the index when inserting/querying
initialize
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_overrides/vectorsearch/pgvector.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_overrides/vectorsearch/pgvector.rb
MIT
def add_texts(texts:, ids:) embeddings = texts.map do |text| llm.embed(text: text).embedding end # I believe the records returned by #find must be in the # same order as the embeddings. I _think_ this works for uuid ids but didn't test # deeply. # TODO - implement find_each so we don't load all records into memory model.find(ids).each.with_index do |record, i| record.update_column(:embedding, embeddings[i]) end end
Add a list of texts to the index @param texts [Array<String>] The texts to add to the index @param ids [Array<String>] The ids to add to the index, in the same order as the texts @return [Array<Integer>] The the ids of the added texts.
add_texts
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_overrides/vectorsearch/pgvector.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_overrides/vectorsearch/pgvector.rb
MIT
def remove_texts(ids:) # Since the record is being destroyed and the `embedding` is a column on the record, # we don't need to do anything here. true end
Remove vectors from the index @param ids [Array<String>] The ids of the vectors to remove @return [Boolean] true
remove_texts
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_overrides/vectorsearch/pgvector.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_overrides/vectorsearch/pgvector.rb
MIT
def similarity_search(query:, k: 4) embedding = llm.embed(text: query).embedding similarity_search_by_vector( embedding: embedding, k: k ) end
Search for similar texts in the index @param query [String] The text to search for @param k [Integer] The number of top results to return @return [Array<Hash>] The results of the search TODO - drop the named "query:" param so it is the same interface as #ask?
similarity_search
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_overrides/vectorsearch/pgvector.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_overrides/vectorsearch/pgvector.rb
MIT
def similarity_search_by_vector(embedding:, k: 4) model .nearest_neighbors(:embedding, embedding, distance: operator) .limit(k) end
Search for similar texts in the index by the passed in vector. You must generate your own vector using the same LLM that generated the embeddings stored in the Vectorsearch DB. @param embedding [Array<Float>] The vector to search for @param k [Integer] The number of top results to return @return [Array<Hash>] The results of the search TODO - drop the named "embedding:" param so it is the same interface as #ask?
similarity_search_by_vector
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_overrides/vectorsearch/pgvector.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_overrides/vectorsearch/pgvector.rb
MIT
def ask(question:, k: 4, &block) # Noisy as the embedding column has a lot of data ActiveRecord::Base.logger.silence do search_results = similarity_search(query: question, k: k) context = search_results.map do |result| result.as_vector end context = context.join("\n---\n") prompt = generate_rag_prompt(question: question, context: context) messages = [{role: "user", content: prompt}] llm.chat(messages: messages, &block) end end
Ask a question and return the answer @param question [String] The question to ask @param k [Integer] The number of results to have in context @yield [String] Stream responses back one String at a time @return [String] The answer to the question
ask
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_overrides/vectorsearch/pgvector.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_overrides/vectorsearch/pgvector.rb
MIT
def upsert_to_vectorsearch if previously_new_record? self.class.class_variable_get(:@@provider).add_texts( texts: [as_vector], ids: [id] ) else self.class.class_variable_get(:@@provider).update_texts( texts: [as_vector], ids: [id] ) end end
Index the text to the vector search provider You'd typically call this method in an ActiveRecord callback @return [Boolean] true @raise [Error] Indexing to vector search DB failed
upsert_to_vectorsearch
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_rails/active_record/hooks.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_rails/active_record/hooks.rb
MIT
def destroy_from_vectorsearch self.class.class_variable_get(:@@provider).remove_texts( ids: [id] ) end
Remove the record from the vector search provider This method should be called in an ActiveRecord `after_destroy` callback @return [Boolean] true @raise [Error] Removing from vector search DB failed
destroy_from_vectorsearch
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_rails/active_record/hooks.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_rails/active_record/hooks.rb
MIT
def as_vector # Don't vectorize the embedding ... this would happen if it already exists # for a record and we update. to_json(except: :embedding) end
Used to serialize the DB record to an indexable vector text Overwrite this method in your model to customize @return [String] the text representation of the model
as_vector
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_rails/active_record/hooks.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_rails/active_record/hooks.rb
MIT
def vectorsearch class_variable_set(:@@provider, LangchainrbRails.config.vectorsearch.dup) # Pgvector-specific configuration if LangchainrbRails.config.vectorsearch.is_a?(Langchain::Vectorsearch::Pgvector) has_neighbors(:embedding) class_variable_get(:@@provider).model = self end end
Set the vector search provider @param provider [Object] The `Langchain::Vectorsearch::*` instance
vectorsearch
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_rails/active_record/hooks.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_rails/active_record/hooks.rb
MIT
def embed! find_each do |record| record.upsert_to_vectorsearch end end
Iterates over records and generate embeddings. Will re-generate for ALL records (not just records with embeddings).
embed!
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_rails/active_record/hooks.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_rails/active_record/hooks.rb
MIT
def similarity_search(query, k: 1) records = class_variable_get(:@@provider).similarity_search( query: query, k: k ) return records if LangchainrbRails.config.vectorsearch.is_a?(Langchain::Vectorsearch::Pgvector) # We use "__id" when Weaviate is the provider ids = records.map { |record| record.try("id") || record.dig("__id") } where(id: ids) end
Search for similar texts @param query [String] The query to search for @param k [Integer] The number of results to return @return [ActiveRecord::Relation] The ActiveRecord relation
similarity_search
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_rails/active_record/hooks.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_rails/active_record/hooks.rb
MIT
def ask(question, k: 4, &block) class_variable_get(:@@provider).ask( question: question, k: k, &block ).chat_completion end
Ask a question and return the answer @param question [String] The question to ask @param k [Integer] The number of results to have in context @yield [String] Stream responses back one String at a time @return [String] The answer to the question standard:disable Style/ArgumentsForwarding
ask
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_rails/active_record/hooks.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_rails/active_record/hooks.rb
MIT
def copy_stylesheets template "assistant/stylesheets/chat.css", "app/assets/stylesheets/chat.css" end
TODO: Copy stylesheet into app/assets/stylesheets or whatever the host app uses
copy_stylesheets
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_rails/generators/langchainrb_rails/assistant_generator.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_rails/generators/langchainrb_rails/assistant_generator.rb
MIT
def add_to_gemfile gem_name = "turbo-rails" if gem_exists?(gem_name) say_status :skipped, "#{gem_name} already exists in Gemfile" else inside Rails.root do run "bundle add #{gem_name}" end end end
TODO: Depending on the LLM provider, we may need to add additional gems
add_to_gemfile
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_rails/generators/langchainrb_rails/assistant_generator.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_rails/generators/langchainrb_rails/assistant_generator.rb
MIT
def after_generate run "bundle install" end
Run bundle install after running the generator
after_generate
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_rails/generators/langchainrb_rails/base_generator.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_rails/generators/langchainrb_rails/base_generator.rb
MIT
def add_to_model inject_into_class "app/models/#{model_name.downcase}.rb", model_name do " vectorsearch\n\n after_save :upsert_to_vectorsearch\n\n" end end
Adds `vectorsearch` class method to the model and `after_save` callback that calls `upsert_to_vectorsearch()`
add_to_model
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_rails/generators/langchainrb_rails/chroma_generator.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_rails/generators/langchainrb_rails/chroma_generator.rb
MIT
def add_to_gemfile gem "chroma-db" end
Adds `chroma-db` gem to the Gemfile
add_to_gemfile
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_rails/generators/langchainrb_rails/chroma_generator.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_rails/generators/langchainrb_rails/chroma_generator.rb
MIT
def add_to_model inject_into_class "app/models/#{model_name.downcase}.rb", model_name do " vectorsearch\n\n after_save :upsert_to_vectorsearch\n\n" end end
Adds `vectorsearch` class method to the model and `after_save` callback that calls `upsert_to_vectorsearch()`
add_to_model
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_rails/generators/langchainrb_rails/pinecone_generator.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_rails/generators/langchainrb_rails/pinecone_generator.rb
MIT
def add_to_gemfile gem "pinecone" end
Adds `pinecone` gem to the Gemfile
add_to_gemfile
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_rails/generators/langchainrb_rails/pinecone_generator.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_rails/generators/langchainrb_rails/pinecone_generator.rb
MIT
def add_to_model inject_into_class "app/models/#{model_name.downcase}.rb", model_name do " vectorsearch\n\n after_save :upsert_to_vectorsearch\n\n" end end
Adds `vectorsearch` class method to the model and `after_save` callback that calls `upsert_to_vectorsearch()`
add_to_model
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_rails/generators/langchainrb_rails/qdrant_generator.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_rails/generators/langchainrb_rails/qdrant_generator.rb
MIT
def add_to_gemfile gem "qdrant-ruby" end
Adds `qdrant-ruby` gem to the Gemfile
add_to_gemfile
ruby
patterns-ai-core/langchainrb_rails
lib/langchainrb_rails/generators/langchainrb_rails/qdrant_generator.rb
https://github.com/patterns-ai-core/langchainrb_rails/blob/master/lib/langchainrb_rails/generators/langchainrb_rails/qdrant_generator.rb
MIT
def run(manifest, prefix, source, destination, tag, type, config) # rubocop:enable Metrics/ParameterLists # Get hash for pipeline hash = hash(source, manifest, config) # Check if pipeline has been cached return cache[hash], true if cache.key?(hash) begin puts "Processing '#{tag}' manifest '#{prefix}'" pipeline = new(manifest, prefix, source, destination, type, config) process_pipeline(hash, pipeline) rescue StandardError => e # Add exception to cache cache[hash] = e # Re-raise the exception raise e end end
Run the pipeline This is called from JekyllAssetPipeline::LiquidBlockExtensions.render or, to be more precise, from JekyllAssetPipeline::CssAssetTag.render and JekyllAssetPipeline::JavaScriptAssetTag.render rubocop:disable Metrics/ParameterLists
run
ruby
matthodan/jekyll-asset-pipeline
lib/jekyll_asset_pipeline/pipeline.rb
https://github.com/matthodan/jekyll-asset-pipeline/blob/master/lib/jekyll_asset_pipeline/pipeline.rb
MIT
def initialize(manifest, prefix, source, destination, type, options = {}) # rubocop:enable Metrics/ParameterLists @manifest = manifest @prefix = prefix @source = source @destination = destination @type = type @options = ::JekyllAssetPipeline::DEFAULTS.merge(options) process end
Initialize new pipeline rubocop:disable Metrics/ParameterLists
initialize
ruby
matthodan/jekyll-asset-pipeline
lib/jekyll_asset_pipeline/pipeline.rb
https://github.com/matthodan/jekyll-asset-pipeline/blob/master/lib/jekyll_asset_pipeline/pipeline.rb
MIT
def convert @assets.each do |asset| # Convert asset multiple times if more than one converter is found finished = false while finished == false # Find a converter to use klass = ::JekyllAssetPipeline::Converter.klass(asset.filename) # Convert asset if converter is found if klass.nil? finished = true else convert_asset(klass, asset) end end end end
Convert assets based on the file extension if converter is defined
convert
ruby
matthodan/jekyll-asset-pipeline
lib/jekyll_asset_pipeline/pipeline.rb
https://github.com/matthodan/jekyll-asset-pipeline/blob/master/lib/jekyll_asset_pipeline/pipeline.rb
MIT
def convert_asset(klass, asset) # Convert asset content converter = klass.new(asset) # Replace asset content and filename asset.content = converter.converted asset.filename = File.basename(asset.filename, '.*') # Add back the output extension if no extension left if File.extname(asset.filename) == '' asset.filename = "#{asset.filename}#{@type}" end rescue StandardError => e puts "Asset Pipeline: Failed to convert '#{asset.filename}' " \ "with '#{klass}': #{e.message}" raise e end
Convert an asset with a given converter class
convert_asset
ruby
matthodan/jekyll-asset-pipeline
lib/jekyll_asset_pipeline/pipeline.rb
https://github.com/matthodan/jekyll-asset-pipeline/blob/master/lib/jekyll_asset_pipeline/pipeline.rb
MIT
def bundle content = @assets.map(&:content).join("\n") hash = ::JekyllAssetPipeline::Pipeline.hash(@source, @manifest, @options) @assets = [ ::JekyllAssetPipeline::Asset.new(content, "#{@prefix}-#{hash}#{@type}") ] end
Bundle multiple assets into a single asset
bundle
ruby
matthodan/jekyll-asset-pipeline
lib/jekyll_asset_pipeline/pipeline.rb
https://github.com/matthodan/jekyll-asset-pipeline/blob/master/lib/jekyll_asset_pipeline/pipeline.rb
MIT
def compress @assets.each do |asset| # Find a compressor to use klass = ::JekyllAssetPipeline::Compressor.subclasses.select do |c| c.filetype == @type end.last break unless klass begin asset.content = klass.new(asset.content).compressed rescue StandardError => e puts "Asset Pipeline: Failed to compress '#{asset.filename}' " \ "with '#{klass}': #{e.message}" raise e end end end
Compress assets if compressor is defined
compress
ruby
matthodan/jekyll-asset-pipeline
lib/jekyll_asset_pipeline/pipeline.rb
https://github.com/matthodan/jekyll-asset-pipeline/blob/master/lib/jekyll_asset_pipeline/pipeline.rb
MIT
def markup # Use display_path if defined, otherwise use output_path in url display_path = @options['display_path'] || @options['output_path'] @html = @assets.map do |asset| klass = ::JekyllAssetPipeline::Template.klass(asset.filename) html = klass.new(display_path, asset.filename).html unless klass.nil? html end.join end
Generate html markup pointing to assets
markup
ruby
matthodan/jekyll-asset-pipeline
lib/jekyll_asset_pipeline/pipeline.rb
https://github.com/matthodan/jekyll-asset-pipeline/blob/master/lib/jekyll_asset_pipeline/pipeline.rb
MIT
def inherited(base) subclasses << base end
Record subclasses of this class (this method is automatically called by ruby)
inherited
ruby
matthodan/jekyll-asset-pipeline
lib/jekyll_asset_pipeline/extensions/ruby/subclass_tracking.rb
https://github.com/matthodan/jekyll-asset-pipeline/blob/master/lib/jekyll_asset_pipeline/extensions/ruby/subclass_tracking.rb
MIT
def subclasses @subclasses ||= [] end
Return an array of classes that are subclasses of this object
subclasses
ruby
matthodan/jekyll-asset-pipeline
lib/jekyll_asset_pipeline/extensions/ruby/subclass_tracking.rb
https://github.com/matthodan/jekyll-asset-pipeline/blob/master/lib/jekyll_asset_pipeline/extensions/ruby/subclass_tracking.rb
MIT
def initialize(files, config) @files, @config = files, config @stylesheets = [] parameters = [@config.wkhtmltopdf_parameters] if config.cover @coverfile = Tempfile.new(['coverfile', '.html']) parameters << '--cover' << @coverfile.path end @wkhtmltopdf = Wkhtmltopdf.new parameters.join(' ') end
Initialize the converter with a File @param [Array] files The list of Gimli::MarkupFile to convert (passing a single file will still work) @param [Gimli::Config] config
initialize
ruby
walle/gimli
lib/gimli/converter.rb
https://github.com/walle/gimli/blob/master/lib/gimli/converter.rb
MIT
def convert! merged_contents = [] @files.each do |file| markup = Markup::Renderer.new file, @config.remove_front_matter html = convert_image_urls markup.render, file.filename if @config.merge html = "<div class=\"page-break\"></div>#{html}" unless merged_contents.empty? merged_contents << html else output_pdf(html, file) end puts html if @config.debug end unless merged_contents.empty? html = merged_contents.join output_pdf(html, nil) end end
Convert the file and save it as a PDF file
convert!
ruby
walle/gimli
lib/gimli/converter.rb
https://github.com/walle/gimli/blob/master/lib/gimli/converter.rb
MIT
def convert_image_urls(html, filename) dir_string = ::File.dirname(::File.expand_path(filename)) html.scan(/<img[^>]+src="([^"]+)"/).each do |url| html.gsub!(url[0], ::File.expand_path(url[0], dir_string)) unless url[0] =~ /^https?/ end html end
Rewrite relative image urls to absolute @param [String] html some html to parse @return [String] the html with all image urls replaced to absolute
convert_image_urls
ruby
walle/gimli
lib/gimli/converter.rb
https://github.com/walle/gimli/blob/master/lib/gimli/converter.rb
MIT
def output_pdf(html, filename) html = add_head html load_stylesheets generate_cover! append_stylesheets html puts @wkhtmltopdf.command(output_file(filename)).join(' ') if @config.debug @wkhtmltopdf.output_pdf html, output_file(filename) end
Create the pdf @param [String] html the html input @param [String] filename the name of the output file
output_pdf
ruby
walle/gimli
lib/gimli/converter.rb
https://github.com/walle/gimli/blob/master/lib/gimli/converter.rb
MIT
def load_stylesheets # Load standard stylesheet style = ::File.expand_path("../../../config/style.css", __FILE__) @stylesheets << style @stylesheets << stylesheet if ::File.exists?(stylesheet) end
Load the stylesheets to pdfkit loads the default and the user selected if any
load_stylesheets
ruby
walle/gimli
lib/gimli/converter.rb
https://github.com/walle/gimli/blob/master/lib/gimli/converter.rb
MIT
def stylesheet @config.stylesheet.nil? ? 'gimli.css' : @config.stylesheet end
Returns the selected stylesheet. Defaults to ./gimli.css @return [String]
stylesheet
ruby
walle/gimli
lib/gimli/converter.rb
https://github.com/walle/gimli/blob/master/lib/gimli/converter.rb
MIT
def output_dir output_dir = @config.output_dir.nil? ? Dir.getwd : @config.output_dir FileUtils.mkdir_p(output_dir) unless ::File.directory?(output_dir) output_dir end
Returns the directory where to save the output. Defaults to ./ @return [String]
output_dir
ruby
walle/gimli
lib/gimli/converter.rb
https://github.com/walle/gimli/blob/master/lib/gimli/converter.rb
MIT
def output_file(file = nil) if file output_filename = file.name if [email protected]_filename.nil? && @files.length == 1 output_filename = @config.output_filename end else output_filename = Time.now.to_s.split(' ').join('_') output_filename = @files.last.name if @files.length == 1 || @config.merge output_filename = @config.output_filename unless @config.output_filename.nil? end ::File.join(output_dir, "#{output_filename}.pdf") end
Generate the name of the output file @return [String] @param [Gimli::MarkupFile] file optionally, specify a file, otherwise use output filename
output_file
ruby
walle/gimli
lib/gimli/converter.rb
https://github.com/walle/gimli/blob/master/lib/gimli/converter.rb
MIT
def generate_cover! return unless @config.cover cover_file = MarkupFile.new @config.cover markup = Markup::Renderer.new cover_file html = "<div class=\"cover\">\n#{markup.render}\n</div>" append_stylesheets(html) html = add_head(html) @coverfile.write(html) @coverfile.close end
Generate cover file if optional cover was given
generate_cover!
ruby
walle/gimli
lib/gimli/converter.rb
https://github.com/walle/gimli/blob/master/lib/gimli/converter.rb
MIT
def initialize(filename) @filename = filename extension = ::File.extname(@filename) @format = load_format(extension) @name = ::File.basename(@filename, extension) @data = ::File.open(@filename, 'rb') { |f| f.read } if valid? && ::File.exists?(@filename) end
Initializes the file object. Only reads contents if it's a valid file
initialize
ruby
walle/gimli
lib/gimli/markupfile.rb
https://github.com/walle/gimli/blob/master/lib/gimli/markupfile.rb
MIT
def valid? valid_format? @format end
Is the file valid @return [Boolean]
valid?
ruby
walle/gimli
lib/gimli/markupfile.rb
https://github.com/walle/gimli/blob/master/lib/gimli/markupfile.rb
MIT
def load_format(format) case format.to_s when /(md|mkdn?|mdown|markdown)$/i :markdown when /(textile)$/i :textile when /(rdoc)$/i :rdoc when /(org)$/i :org when /(creole)$/i :creole when /(re?st(\.txt)?)$/i :rest when /(asciidoc)$/i :asciidoc when /(pod)$/i :pod when /(\d)$/i :roff when /(media)?wiki$/i :mediawiki else nil end end
Converts the format to a symbol if it's a valid format nil otherwise @param [String] format @return [Symbol|nil]
load_format
ruby
walle/gimli
lib/gimli/markupfile.rb
https://github.com/walle/gimli/blob/master/lib/gimli/markupfile.rb
MIT
def valid_format?(format) return false if format.nil? FORMATS.include? format.to_sym end
Checks if the format is a valid one @param [String] format @return [Boolean]
valid_format?
ruby
walle/gimli
lib/gimli/markupfile.rb
https://github.com/walle/gimli/blob/master/lib/gimli/markupfile.rb
MIT
def initialize(parameters = nil) @parameters = parameters end
Set up options for wkhtmltopdf @param [String] parameters
initialize
ruby
walle/gimli
lib/gimli/wkhtmltopdf.rb
https://github.com/walle/gimli/blob/master/lib/gimli/wkhtmltopdf.rb
MIT
def output_pdf(html, filename) args = command(filename) invoke = args.join(' ') IO.popen(invoke, "wb+") do |pdf| pdf.puts(html) pdf.close_write pdf.gets(nil) end end
Convert the html to pdf and write it to file @param [String] html the html input @param [String] filename the name of the output file
output_pdf
ruby
walle/gimli
lib/gimli/wkhtmltopdf.rb
https://github.com/walle/gimli/blob/master/lib/gimli/wkhtmltopdf.rb
MIT
def command(filename) [bin, @parameters, '-q', '-', "\"#{filename}\""].compact end
Assemble the command to run @param [String] filename the outputed pdf's filename @return [Array] a list of strings that make out the call to wkhtmltopdf
command
ruby
walle/gimli
lib/gimli/wkhtmltopdf.rb
https://github.com/walle/gimli/blob/master/lib/gimli/wkhtmltopdf.rb
MIT
def bin @bin ||= "\"#{(`which wkhtmltopdf`).chomp}\"" end
Find the wkhtmltopdf binary @return [String] the path to the binary
bin
ruby
walle/gimli
lib/gimli/wkhtmltopdf.rb
https://github.com/walle/gimli/blob/master/lib/gimli/wkhtmltopdf.rb
MIT
def extract(data) data.gsub!(/^``` ?([^\r\n]+)?\r?\n(.+?)\r?\n```\r?$/m) do id = Digest::SHA1.hexdigest($2) @code_blocks << CodeBlock.new(id, $1, $2) id end data end
Extract all code blocks into the codemap and replace with placeholders. @return [String] Returns the placeholder'd String data.
extract
ruby
walle/gimli
lib/gimli/markup/code.rb
https://github.com/walle/gimli/blob/master/lib/gimli/markup/code.rb
MIT
def process(data) return data if data.nil? || data.size.zero? || @code_blocks.size.zero? @code_blocks.each do |block| data.gsub!(block.id, block.highlighted) end data end
Process all code from the codemap and replace the placeholders with the final HTML. @return [String] Returns the marked up String data.
process
ruby
walle/gimli
lib/gimli/markup/code.rb
https://github.com/walle/gimli/blob/master/lib/gimli/markup/code.rb
MIT
def highlighted if @language CodeRay.scan(@code, @language).html(:line_numbers => :table) else CodeRay.scan(@code, :text).div end end
Returns the code with syntax highlightning @return [String]
highlighted
ruby
walle/gimli
lib/gimli/markup/code_block.rb
https://github.com/walle/gimli/blob/master/lib/gimli/markup/code_block.rb
MIT
def initialize(file, do_remove_yaml_front_matter = false) @file = file @do_remove_yaml_front_matter = do_remove_yaml_front_matter @data = file.data @code = Code.new @yaml_frontmatter_remover = YamlFrontmatterRemover.new end
Initialize a new Markup object. @param [Gimli::File] file The Gimli::File to process @param [Boolean] do_remove_yaml_front_matter Should we remove the front matter? @return [Gimli::Markup]
initialize
ruby
walle/gimli
lib/gimli/markup/renderer.rb
https://github.com/walle/gimli/blob/master/lib/gimli/markup/renderer.rb
MIT
def render prepare_data render_data post_process_data return @data end
Render the content with Gollum wiki syntax on top of the file's own markup language. @return [String] The formatted data
render
ruby
walle/gimli
lib/gimli/markup/renderer.rb
https://github.com/walle/gimli/blob/master/lib/gimli/markup/renderer.rb
MIT
def render_data begin @data = @data.force_encoding('utf-8') if @data.respond_to? :force_encoding @data = GitHub::Markup.render(@file.filename, @data) if @data.nil? raise "There was an error converting #{@file.name} to HTML." end rescue Object => e @data = %{<p class="gimli-error">#{e.message}</p>} end end
Do the markup to html rendering
render_data
ruby
walle/gimli
lib/gimli/markup/renderer.rb
https://github.com/walle/gimli/blob/master/lib/gimli/markup/renderer.rb
MIT
def process(data) data.gsub /^(---\s*\n.*?\n?)^(---\s*$\n?)/m, '' end
Removes YAML Front Matter Useful if you want to PDF your Jekyll site.
process
ruby
walle/gimli
lib/gimli/markup/yaml_frontmatter_remover.rb
https://github.com/walle/gimli/blob/master/lib/gimli/markup/yaml_frontmatter_remover.rb
MIT
def show @projects = Project.active.by_language(@language).distinct.limit(20) @users = User.order('contributions_count desc').by_language(@language).limit(200).sample(45) @contributions = Contribution.by_language(@language).year(current_year).latest(5) end
GET: /languages/:id filters the projects, users and contributions by language sets the @projects, @users and @contributions instance variable
show
ruby
24pullrequests/24pullrequests
app/controllers/languages_controller.rb
https://github.com/24pullrequests/24pullrequests/blob/master/app/controllers/languages_controller.rb
MIT