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 slugify(string, mode: nil, cased: false) mode ||= "default" return nil if string.nil? unless SLUGIFY_MODES.include?(mode) return cased ? string : string.downcase end # Drop accent marks from latin characters. Everything else turns to ? if mode == "latin" I18n.config.available_locales = :en if I18n.config.available_locales.empty? string = I18n.transliterate(string) end slug = replace_character_sequence_with_hyphen(string, :mode => mode) # Remove leading/trailing hyphen slug.gsub!(%r!^-|-$!i, "") slug.downcase! unless cased Jekyll.logger.warn("Warning:", "Empty `slug` generated for '#{string}'.") if slug.empty? slug end
rubocop: enable Naming/PredicateName Slugify a filename or title. string - the filename or title to slugify mode - how string is slugified cased - whether to replace all uppercase letters with their lowercase counterparts When mode is "none", return the given string. When mode is "raw", return the given string, with every sequence of spaces characters replaced with a hyphen. When mode is "default" or nil, non-alphabetic characters are replaced with a hyphen too. When mode is "pretty", some non-alphabetic characters (._~!$&'()+,;=@) are not replaced with hyphen. When mode is "ascii", some everything else except ASCII characters a-z (lowercase), A-Z (uppercase) and 0-9 (numbers) are not replaced with hyphen. When mode is "latin", the input string is first preprocessed so that any letters with accents are replaced with the plain letter. Afterwards, it follows the "default" mode of operation. If cased is true, all uppercase letters in the result string are replaced with their lowercase counterparts. Examples: slugify("The _config.yml file") # => "the-config-yml-file" slugify("The _config.yml file", "pretty") # => "the-_config.yml-file" slugify("The _config.yml file", "pretty", true) # => "The-_config.yml file" slugify("The _config.yml file", "ascii") # => "the-config-yml-file" slugify("The _config.yml file", "latin") # => "the-config-yml-file" Returns the slugified string.
slugify
ruby
jekyll/jekyll
lib/jekyll/utils.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/utils.rb
MIT
def add_permalink_suffix(template, permalink_style) template = template.dup case permalink_style when :pretty template << "/" when :date, :ordinal, :none template << ":output_ext" else template << "/" if permalink_style.to_s.end_with?("/") template << ":output_ext" if permalink_style.to_s.end_with?(":output_ext") end template end
Add an appropriate suffix to template so that it matches the specified permalink style. template - permalink template without trailing slash or file extension permalink_style - permalink style, either built-in or custom The returned permalink template will use the same ending style as specified in permalink_style. For example, if permalink_style contains a trailing slash (or is :pretty, which indirectly has a trailing slash), then so will the returned template. If permalink_style has a trailing ":output_ext" (or is :none, :date, or :ordinal) then so will the returned template. Otherwise, template will be returned without modification. Examples: add_permalink_suffix("/:basename", :pretty) # => "/:basename/" add_permalink_suffix("/:basename", :date) # => "/:basename:output_ext" add_permalink_suffix("/:basename", "/:year/:month/:title/") # => "/:basename/" add_permalink_suffix("/:basename", "/:year/:month/:title") # => "/:basename" Returns the updated permalink template
add_permalink_suffix
ruby
jekyll/jekyll
lib/jekyll/utils.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/utils.rb
MIT
def safe_glob(dir, patterns, flags = 0) return [] unless Dir.exist?(dir) pattern = File.join(Array(patterns)) return [dir] if pattern.empty? Dir.chdir(dir) do Dir.glob(pattern, flags).map { |f| File.join(dir, f) } end end
Work the same way as Dir.glob but separating the input into two parts ('dir' + '/' + 'pattern') to make sure the first part('dir') does not act as a pattern. For example, Dir.glob("path[/*") always returns an empty array, because the method fails to find the closing pattern to '[' which is ']' Examples: safe_glob("path[", "*") # => ["path[/file1", "path[/file2"] safe_glob("path", "*", File::FNM_DOTMATCH) # => ["path/.", "path/..", "path/file1"] safe_glob("path", ["**", "*"]) # => ["path[/file1", "path[/folder/file2"] dir - the dir where glob will be executed under (the dir will be included to each result) patterns - the patterns (or the pattern) which will be applied under the dir flags - the flags which will be applied to the pattern Returns matched paths
safe_glob
ruby
jekyll/jekyll
lib/jekyll/utils.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/utils.rb
MIT
def merged_file_read_opts(site, opts) merged = (site ? site.file_read_opts : {}).merge(opts) # always use BOM when reading UTF-encoded files if merged[:encoding]&.downcase&.start_with?("utf-") merged[:encoding] = "bom|#{merged[:encoding]}" end if merged["encoding"]&.downcase&.start_with?("utf-") merged["encoding"] = "bom|#{merged["encoding"]}" end merged end
Returns merged option hash for File.read of self.site (if exists) and a given param
merged_file_read_opts
ruby
jekyll/jekyll
lib/jekyll/utils.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/utils.rb
MIT
def replace_character_sequence_with_hyphen(string, mode: "default") replaceable_char = case mode when "raw" SLUGIFY_RAW_REGEXP when "pretty" # "._~!$&'()+,;=@" is human readable (not URI-escaped) in URL # and is allowed in both extN and NTFS. SLUGIFY_PRETTY_REGEXP when "ascii" # For web servers not being able to handle Unicode, the safe # method is to ditch anything else but latin letters and numeric # digits. SLUGIFY_ASCII_REGEXP else SLUGIFY_DEFAULT_REGEXP end # Strip according to the mode string.gsub(replaceable_char, "-") end
Replace each character sequence with a hyphen. See Utils#slugify for a description of the character sequence specified by each mode.
replace_character_sequence_with_hyphen
ruby
jekyll/jekyll
lib/jekyll/utils.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/utils.rb
MIT
def init_with_program(prog) prog.command(:build) do |c| c.syntax "build [options]" c.description "Build your site" c.alias :b add_build_options(c) c.action do |_, options| options["serving"] = false process_with_graceful_fail(c, options, self) end end end
Create the Mercenary command for the Jekyll CLI for this Command
init_with_program
ruby
jekyll/jekyll
lib/jekyll/commands/build.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/commands/build.rb
MIT
def process(options) # Adjust verbosity quickly Jekyll.logger.adjust_verbosity(options) options = configuration_from_options(options) site = Jekyll::Site.new(options) if options.fetch("skip_initial_build", false) Jekyll.logger.warn "Build Warning:", "Skipping the initial build. This may result in an out-of-date site." else build(site, options) end if options.fetch("detach", false) Jekyll.logger.info "Auto-regeneration:", "disabled when running server detached." elsif options.fetch("watch", false) watch(site, options) else Jekyll.logger.info "Auto-regeneration:", "disabled. Use --watch to enable." end end
Build your jekyll site Continuously watch if `watch` is set to true in the config.
process
ruby
jekyll/jekyll
lib/jekyll/commands/build.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/commands/build.rb
MIT
def build(site, options) t = Time.now source = File.expand_path(options["source"]) destination = File.expand_path(options["destination"]) incremental = options["incremental"] Jekyll.logger.info "Source:", source Jekyll.logger.info "Destination:", destination Jekyll.logger.info "Incremental build:", (incremental ? "enabled" : "disabled. Enable with --incremental") Jekyll.logger.info "Generating..." process_site(site) Jekyll.logger.info "", "done in #{(Time.now - t).round(3)} seconds." end
Build your Jekyll site. site - the Jekyll::Site instance to build options - A Hash of options passed to the command Returns nothing.
build
ruby
jekyll/jekyll
lib/jekyll/commands/build.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/commands/build.rb
MIT
def watch(site, options) External.require_with_graceful_fail "jekyll-watch" Jekyll::Watcher.watch(options, site) end
Private: Watch for file changes and rebuild the site. site - A Jekyll::Site instance options - A Hash of options passed to the command Returns nothing.
watch
ruby
jekyll/jekyll
lib/jekyll/commands/build.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/commands/build.rb
MIT
def after_install(path, options = {}) unless options["blank"] || options["skip-bundle"] begin require "bundler" bundle_install path rescue LoadError Jekyll.logger.info "Could not load Bundler. Bundle install skipped." end end Jekyll.logger.info "New jekyll site installed in #{path.cyan}." Jekyll.logger.info "Bundle install skipped." if options["skip-bundle"] end
After a new blog has been created, print a success notification and then automatically execute bundle install from within the new blog dir unless the user opts to generate a blank blog or skip 'bundle install'.
after_install
ruby
jekyll/jekyll
lib/jekyll/commands/new.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/commands/new.rb
MIT
def setup(destination) require_relative "serve/servlet" FileUtils.mkdir_p(destination) if File.exist?(File.join(destination, "404.html")) WEBrick::HTTPResponse.class_eval do def create_error_page @header["Content-Type"] = "text/html; charset=UTF-8" @body = IO.read(File.join(@config[:DocumentRoot], "404.html")) end end end end
Do a base pre-setup of WEBRick so that everything is in place when we get ready to party, checking for an setting up an error page and making sure our destination exists. rubocop:disable Security/IoMethods
setup
ruby
jekyll/jekyll
lib/jekyll/commands/serve.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/commands/serve.rb
MIT
def boot_or_detach(server, opts) if opts["detach"] pid = Process.fork do # Detach the process from controlling terminal $stdin.reopen("/dev/null", "r") $stdout.reopen("/dev/null", "w") $stderr.reopen("/dev/null", "w") server.start end Process.detach(pid) Jekyll.logger.info "Server detached with pid '#{pid}'.", "Run `pkill -f jekyll' or `kill -9 #{pid}' to stop the server." # Exit without running `at_exit` inherited by the forked process. Process.exit! 0 else t = Thread.new { server.start } trap("INT") { server.shutdown } t.join end end
Keep in our area with a thread or detach the server as requested by the user. This method determines what we do based on what you ask us to do.
boot_or_detach
ruby
jekyll/jekyll
lib/jekyll/commands/serve.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/commands/serve.rb
MIT
def enable_logging(opts) opts[:AccessLog] = [] level = WEBrick::Log.const_get(opts[:JekyllOptions]["verbose"] ? :DEBUG : :WARN) opts[:Logger] = WEBrick::Log.new($stdout, level) end
Make the stack verbose if the user requests it.
enable_logging
ruby
jekyll/jekyll
lib/jekyll/commands/serve.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/commands/serve.rb
MIT
def enable_ssl(opts) cert, key, src = opts[:JekyllOptions].values_at("ssl_cert", "ssl_key", "source") return if cert.nil? && key.nil? raise "Missing --ssl_cert or --ssl_key. Both are required." unless cert && key require "openssl" require "webrick/https" opts[:SSLCertificate] = OpenSSL::X509::Certificate.new(read_file(src, cert)) begin opts[:SSLPrivateKey] = OpenSSL::PKey::RSA.new(read_file(src, key)) rescue StandardError if defined?(OpenSSL::PKey::EC) opts[:SSLPrivateKey] = OpenSSL::PKey::EC.new(read_file(src, key)) else raise end end opts[:SSLEnable] = true end
Add SSL to the stack if the user triggers --enable-ssl and they provide both types of certificates commonly needed. Raise if they forget to add one of the certificates.
enable_ssl
ruby
jekyll/jekyll
lib/jekyll/commands/serve.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/commands/serve.rb
MIT
def reload(pages) pages.each do |p| json_message = JSON.dump( :command => "reload", :path => p.url, :liveCSS => true ) Jekyll.logger.debug "LiveReload:", "Reloading URL #{p.url.inspect}" @websockets.each { |ws| ws.send(json_message) } end end
For a description of the protocol see http://feedback.livereload.com/knowledgebase/articles/86174-livereload-protocol
reload
ruby
jekyll/jekyll
lib/jekyll/commands/serve/live_reload_reactor.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/commands/serve/live_reload_reactor.rb
MIT
def search_file(req, res, basename) # /file.* > /file/index.html > /file.html super || super(req, res, "#{basename}.html") || super(req, res, "#{basename}.xhtml") end
Add the ability to tap file.html the same way that Nginx does on our Docker images (or on GitHub Pages.) The difference is that we might end up with a different preference on which comes first.
search_file
ruby
jekyll/jekyll
lib/jekyll/commands/serve/servlet.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/commands/serve/servlet.rb
MIT
def conditionally_inject_charset(res) typ = res.header["content-type"] return unless @mime_types_charset.key?(typ) return if %r!;\s*charset=!.match?(typ) res.header["content-type"] = "#{typ}; charset=#{@jekyll_opts["encoding"]}" end
Inject charset based on Jekyll config only if our mime-types database contains the charset metadata. Refer `script/vendor-mimes` in the repository for further details.
conditionally_inject_charset
ruby
jekyll/jekyll
lib/jekyll/commands/serve/servlet.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/commands/serve/servlet.rb
MIT
def get_processor case @config["markdown"].downcase when "kramdown" then KramdownParser.new(@config) else custom_processor end end
RuboCop does not allow reader methods to have names starting with `get_` To ensure compatibility, this check has been disabled on this method rubocop:disable Naming/AccessorMethodName
get_processor
ruby
jekyll/jekyll
lib/jekyll/converters/markdown.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/converters/markdown.rb
MIT
def valid_processors [:kramdown] + third_party_processors end
rubocop:enable Naming/AccessorMethodName Public: Provides you with a list of processors comprised of the ones we support internally and the ones that you have provided to us (if they're whitelisted for use in safe mode). Returns an array of symbols.
valid_processors
ruby
jekyll/jekyll
lib/jekyll/converters/markdown.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/converters/markdown.rb
MIT
def third_party_processors self.class.constants - [:KramdownParser, :PRIORITIES] end
Public: A list of processors that you provide via plugins. Returns an array of symbols
third_party_processors
ruby
jekyll/jekyll
lib/jekyll/converters/markdown.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/converters/markdown.rb
MIT
def convert(content) setup @cache.getset(content) do @parser.convert(content) end end
Logic to do the content conversion. content - String content of file (without front matter). Returns a String of the converted content.
convert
ruby
jekyll/jekyll
lib/jekyll/converters/markdown.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/converters/markdown.rb
MIT
def custom_class_allowed?(parser_name) parser_name !~ %r![^A-Za-z0-9_]! && self.class.constants.include?(parser_name.to_sym) end
Private: Determine whether a class name is an allowed custom markdown class name. parser_name - the name of the parser class Returns true if the parser name contains only alphanumeric characters and is defined within Jekyll::Converters::Markdown
custom_class_allowed?
ruby
jekyll/jekyll
lib/jekyll/converters/markdown.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/converters/markdown.rb
MIT
def convert(content) document = Kramdown::Document.new(content, @config) html_output = document.to_html.chomp if @config["show_warnings"] document.warnings.each do |warning| Jekyll.logger.warn "Kramdown warning:", warning.sub(%r!^Warning:\s+!, "") end end html_output end
Logic to do the content conversion. content - String content of file (without front matter). Returns a String of the converted content.
convert
ruby
jekyll/jekyll
lib/jekyll/converters/smartypants.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/converters/smartypants.rb
MIT
def setup(options) @cache ||= {} # reset variables on a subsequent set up with a different options Hash unless @cache[:id] == options.hash @options = @parser = nil @cache[:id] = options.hash end @options ||= Options.merge(options).freeze @parser ||= begin parser_name = (@options[:input] || "kramdown").to_s parser_name = parser_name[0..0].upcase + parser_name[1..-1] try_require("parser", parser_name) if Parser.const_defined?(parser_name) Parser.const_get(parser_name) else raise Kramdown::Error, "kramdown has no parser to handle the specified " \ "input format: #{@options[:input]}" end end end
The implementation is basically the core logic in +Kramdown::Document#initialize+ rubocop:disable Naming/MemoizedInstanceVariableName
setup
ruby
jekyll/jekyll
lib/jekyll/converters/markdown/kramdown_parser.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/converters/markdown/kramdown_parser.rb
MIT
def to_html output, warnings = Kramdown::Converter::Html.convert(@root, @options) @warnings.concat(warnings) output end
Use Kramdown::Converter::Html class to convert this document into HTML. The implementation is basically an optimized version of core logic in +Kramdown::Document#method_missing+ from kramdown-2.1.0.
to_html
ruby
jekyll/jekyll
lib/jekyll/converters/markdown/kramdown_parser.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/converters/markdown/kramdown_parser.rb
MIT
def setup @config["syntax_highlighter"] ||= highlighter @config["syntax_highlighter_opts"] ||= {} @config["syntax_highlighter_opts"]["default_lang"] ||= "plaintext" @config["syntax_highlighter_opts"]["guess_lang"] = @config["guess_lang"] @config["coderay"] ||= {} # XXX: Legacy. modernize_coderay_config end
Setup and normalize the configuration: * Create Kramdown if it doesn't exist. * Set syntax_highlighter, detecting enable_coderay and merging highlighter if none. * Merge kramdown[coderay] into syntax_highlighter_opts stripping coderay_. * Make sure `syntax_highlighter_opts` exists.
setup
ruby
jekyll/jekyll
lib/jekyll/converters/markdown/kramdown_parser.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/converters/markdown/kramdown_parser.rb
MIT
def highlighter return @highlighter if @highlighter if @config["syntax_highlighter"] return @highlighter = @config[ "syntax_highlighter" ] end @highlighter = if @config.key?("enable_coderay") && @config["enable_coderay"] Jekyll::Deprecator.deprecation_message( "You are using 'enable_coderay', " \ "use syntax_highlighter: coderay in your configuration file." ) "coderay" else @main_fallback_highlighter end end
config[kramdown][syntax_highlighter] > config[kramdown][enable_coderay] > config[highlighter] Where `enable_coderay` is now deprecated because Kramdown supports Rouge now too.
highlighter
ruby
jekyll/jekyll
lib/jekyll/converters/markdown/kramdown_parser.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/converters/markdown/kramdown_parser.rb
MIT
def modernize_coderay_config unless @config["coderay"].empty? Jekyll::Deprecator.deprecation_message( "You are using 'kramdown.coderay' in your configuration, " \ "please use 'syntax_highlighter_opts' instead." ) @config["syntax_highlighter_opts"] = begin strip_coderay_prefix( @config["syntax_highlighter_opts"] \ .merge(CODERAY_DEFAULTS) \ .merge(@config["coderay"]) ) end end end
If our highlighter is CodeRay we go in to merge the CodeRay defaults with your "coderay" key if it's there, deprecating it in the process of you using it.
modernize_coderay_config
ruby
jekyll/jekyll
lib/jekyll/converters/markdown/kramdown_parser.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/converters/markdown/kramdown_parser.rb
MIT
def hash_for_json(state = nil) to_h.tap do |hash| if state && state.depth >= 2 hash["previous"] = collapse_document(hash["previous"]) if hash["previous"] hash["next"] = collapse_document(hash["next"]) if hash["next"] end end end
Generate a Hash for use in generating JSON. This is useful if fields need to be cleared before the JSON can generate. state - the JSON::State object which determines the state of current processing. Returns a Hash ready for JSON generation.
hash_for_json
ruby
jekyll/jekyll
lib/jekyll/drops/document_drop.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/drops/document_drop.rb
MIT
def mutable(is_mutable = nil) @is_mutable = is_mutable || false end
Get or set whether the drop class is mutable. Mutability determines whether or not pre-defined fields may be overwritten. is_mutable - Boolean set mutability of the class (default: nil) Returns the mutability of the class
mutable
ruby
jekyll/jekyll
lib/jekyll/drops/drop.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/drops/drop.rb
MIT
def private_delegate_methods(*symbols) symbols.each { |symbol| private delegate_method(symbol) } nil end
public delegation helper methods that calls onto Drop's instance variable `@obj`. Generate private Drop instance_methods for each symbol in the given list. Returns nothing.
private_delegate_methods
ruby
jekyll/jekyll
lib/jekyll/drops/drop.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/drops/drop.rb
MIT
def delegate_methods(*symbols) symbols.each { |symbol| delegate_method(symbol) } nil end
Generate public Drop instance_methods for each symbol in the given list. Returns nothing.
delegate_methods
ruby
jekyll/jekyll
lib/jekyll/drops/drop.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/drops/drop.rb
MIT
def delegate_method(symbol) define_method(symbol) { @obj.send(symbol) } end
Generate public Drop instance_method for given symbol that calls `@obj.<sym>`. Returns delegated method symbol.
delegate_method
ruby
jekyll/jekyll
lib/jekyll/drops/drop.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/drops/drop.rb
MIT
def delegate_method_as(original, delegate) define_method(delegate) { @obj.send(original) } end
Generate public Drop instance_method named `delegate` that calls `@obj.<original>`. Returns delegated method symbol.
delegate_method_as
ruby
jekyll/jekyll
lib/jekyll/drops/drop.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/drops/drop.rb
MIT
def data_delegators(*strings) strings.each do |key| data_delegator(key) if key.is_a?(String) end nil end
Generate public Drop instance_methods for each string entry in the given list. The generated method(s) access(es) `@obj`'s data hash. Returns nothing.
data_delegators
ruby
jekyll/jekyll
lib/jekyll/drops/drop.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/drops/drop.rb
MIT
def data_delegator(key) define_method(key.to_sym) { @obj.data[key] } end
Generate public Drop instance_methods for given string `key`. The generated method access(es) `@obj`'s data hash. Returns method symbol.
data_delegator
ruby
jekyll/jekyll
lib/jekyll/drops/drop.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/drops/drop.rb
MIT
def getter_method_names @getter_method_names ||= instance_methods.map!(&:to_s).tap do |list| list.reject! { |item| item.end_with?("=") } end end
Array of stringified instance methods that do not end with the assignment operator. (<klass>.instance_methods always generates a new Array object so it can be mutated) Returns array of strings.
getter_method_names
ruby
jekyll/jekyll
lib/jekyll/drops/drop.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/drops/drop.rb
MIT
def initialize(obj) @obj = obj end
Create a new Drop obj - the Jekyll Site, Collection, or Document required by the drop. Returns nothing
initialize
ruby
jekyll/jekyll
lib/jekyll/drops/drop.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/drops/drop.rb
MIT
def content_methods @content_methods ||= \ self.class.getter_method_names \ - Jekyll::Drops::Drop.getter_method_names \ - NON_CONTENT_METHOD_NAMES end
Generates a list of strings which correspond to content getter methods. Returns an Array of strings which represent method-specific keys.
content_methods
ruby
jekyll/jekyll
lib/jekyll/drops/drop.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/drops/drop.rb
MIT
def key?(key) return false if key.nil? return true if self.class.mutable? && mutations.key?(key) respond_to?(key) || fallback_data.key?(key) end
Check if key exists in Drop key - the string key whose value to fetch Returns true if the given key is present
key?
ruby
jekyll/jekyll
lib/jekyll/drops/drop.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/drops/drop.rb
MIT
def keys (content_methods | mutations.keys | fallback_data.keys).flatten end
Generates a list of keys with user content as their values. This gathers up the Drop methods and keys of the mutations and underlying data hashes and performs a set union to ensure a list of unique keys for the Drop. Returns an Array of unique keys for content for the Drop.
keys
ruby
jekyll/jekyll
lib/jekyll/drops/drop.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/drops/drop.rb
MIT
def to_h keys.each_with_object({}) do |(key, _), result| result[key] = self[key] end end
Generate a Hash representation of the Drop by resolving each key's value. It includes Drop methods, mutations, and the underlying object's data. See the documentation for Drop#keys for more. Returns a Hash with all the keys and values resolved.
to_h
ruby
jekyll/jekyll
lib/jekyll/drops/drop.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/drops/drop.rb
MIT
def inspect JSON.pretty_generate to_h end
Inspect the drop's keys and values through a JSON representation of its keys and values. Returns a pretty generation of the hash representation of the Drop.
inspect
ruby
jekyll/jekyll
lib/jekyll/drops/drop.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/drops/drop.rb
MIT
def to_json(state = nil) JSON.generate(hash_for_json(state), state) end
Generate a JSON representation of the Drop. state - the JSON::State object which determines the state of current processing. Returns a JSON representation of the Drop in a String.
to_json
ruby
jekyll/jekyll
lib/jekyll/drops/drop.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/drops/drop.rb
MIT
def documents @documents ||= @obj.documents end
`Site#documents` cannot be memoized so that `Site#docs_to_write` can access the latest state of the attribute. Since this method will be called after `Site#pre_render` hook, the `Site#documents` array shouldn't thereafter change and can therefore be safely memoized to prevent additional computation of `Site#documents`.
documents
ruby
jekyll/jekyll
lib/jekyll/drops/site_drop.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/drops/site_drop.rb
MIT
def related_posts return nil unless @current_document.is_a?(Jekyll::Document) @current_document.related_posts end
`{{ site.related_posts }}` is how posts can get posts related to them, either through LSI if it's enabled, or through the most recent posts. We should remove this in 4.0 and switch to `{{ post.related_posts }}`.
related_posts
ruby
jekyll/jekyll
lib/jekyll/drops/site_drop.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/drops/site_drop.rb
MIT
def slugified_categories Array(@obj.data["categories"]).each_with_object(Set.new) do |category, set| set << Utils.slugify(category.to_s) end.to_a.join("/") end
Similar to output from #categories, but each category will be downcased and all non-alphanumeric characters of the category replaced with a hyphen.
slugified_categories
ruby
jekyll/jekyll
lib/jekyll/drops/url_drop.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/drops/url_drop.rb
MIT
def date_to_string(date, type = nil, style = nil) stringify_date(date, "%b", type, style) end
Format a date in short format e.g. "27 Jan 2011". Ordinal format is also supported, in both the UK (e.g. "27th Jan 2011") and US ("e.g. Jan 27th, 2011") formats. UK format is the default. date - the Time to format. type - if "ordinal" the returned String will be in ordinal format style - if "US" the returned String will be in US format. Otherwise it will be in UK format. Returns the formatting String.
date_to_string
ruby
jekyll/jekyll
lib/jekyll/filters/date_filters.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/filters/date_filters.rb
MIT
def date_to_long_string(date, type = nil, style = nil) stringify_date(date, "%B", type, style) end
Format a date in long format e.g. "27 January 2011". Ordinal format is also supported, in both the UK (e.g. "27th January 2011") and US ("e.g. January 27th, 2011") formats. UK format is the default. date - the Time to format. type - if "ordinal" the returned String will be in ordinal format style - if "US" the returned String will be in US format. Otherwise it will be in UK format. Returns the formatted String.
date_to_long_string
ruby
jekyll/jekyll
lib/jekyll/filters/date_filters.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/filters/date_filters.rb
MIT
def date_to_xmlschema(date) return date if date.to_s.empty? time(date).xmlschema end
Format a date for use in XML. date - The Time to format. Examples date_to_xmlschema(Time.now) # => "2011-04-24T20:34:46+08:00" Returns the formatted String.
date_to_xmlschema
ruby
jekyll/jekyll
lib/jekyll/filters/date_filters.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/filters/date_filters.rb
MIT
def date_to_rfc822(date) return date if date.to_s.empty? time(date).rfc822 end
Format a date according to RFC-822 date - The Time to format. Examples date_to_rfc822(Time.now) # => "Sun, 24 Apr 2011 12:34:46 +0000" Returns the formatted String.
date_to_rfc822
ruby
jekyll/jekyll
lib/jekyll/filters/date_filters.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/filters/date_filters.rb
MIT
def stringify_date(date, month_type, type = nil, style = nil) return date if date.to_s.empty? time = time(date) if type == "ordinal" day = time.day ordinal_day = "#{day}#{ordinal(day)}" return time.strftime("#{month_type} #{ordinal_day}, %Y") if style == "US" return time.strftime("#{ordinal_day} #{month_type} %Y") end time.strftime("%d #{month_type} %Y") end
month_type: Notations that evaluate to 'Month' via `Time#strftime` ("%b", "%B") type: nil (default) or "ordinal" style: nil (default) or "US" Returns a stringified date or the empty input.
stringify_date
ruby
jekyll/jekyll
lib/jekyll/filters/date_filters.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/filters/date_filters.rb
MIT
def group_by(input, property) if groupable?(input) groups = input.group_by { |item| item_property(item, property).to_s } grouped_array(groups) else input end end
Group an array of items by a property input - the inputted Enumerable property - the property Returns an array of Hashes, each looking something like this: {"name" => "larry" "items" => [...] } # all the items where `property` == "larry"
group_by
ruby
jekyll/jekyll
lib/jekyll/filters/grouping_filters.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/filters/grouping_filters.rb
MIT
def group_by_exp(input, variable, expression) return input unless groupable?(input) parsed_expr = parse_expression(expression) @context.stack do groups = input.group_by do |item| @context[variable] = item parsed_expr.render(@context) end grouped_array(groups) end end
Group an array of items by an expression input - the object array variable - the variable to assign each item to in the expression expression -a Liquid comparison expression passed in as a string Returns the filtered array of objects
group_by_exp
ruby
jekyll/jekyll
lib/jekyll/filters/grouping_filters.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/filters/grouping_filters.rb
MIT
def absolute_url(input) return if input.nil? cache = if input.is_a?(String) (@context.registers[:site].filter_cache[:absolute_url] ||= {}) else (@context.registers[:cached_absolute_url] ||= {}) end cache[input] ||= compute_absolute_url(input) # Duplicate cached string so that the cached value is never mutated by # a subsequent filter. cache[input].dup end
Produces an absolute URL based on site.url and site.baseurl. input - the URL to make absolute. Returns the absolute URL as a String.
absolute_url
ruby
jekyll/jekyll
lib/jekyll/filters/url_filters.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/filters/url_filters.rb
MIT
def relative_url(input) return if input.nil? cache = if input.is_a?(String) (@context.registers[:site].filter_cache[:relative_url] ||= {}) else (@context.registers[:cached_relative_url] ||= {}) end cache[input] ||= compute_relative_url(input) # Duplicate cached string so that the cached value is never mutated by # a subsequent filter. cache[input].dup end
Produces a URL relative to the domain root based on site.baseurl unless it is already an absolute url with an authority (host). input - the URL to make relative to the domain root Returns a URL relative to the domain root as a String.
relative_url
ruby
jekyll/jekyll
lib/jekyll/filters/url_filters.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/filters/url_filters.rb
MIT
def strip_index(input) return if input.nil? || input.to_s.empty? input.sub(%r!/index\.html?$!, "/") end
Strips trailing `/index.html` from URLs to create pretty permalinks input - the URL with a possible `/index.html` Returns a URL with the trailing `/index.html` removed
strip_index
ruby
jekyll/jekyll
lib/jekyll/filters/url_filters.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/filters/url_filters.rb
MIT
def render!(*args) reset_template_assigns measure_time do measure_bytes do measure_counts do @template.render!(*args) end end end end
This method simply 'rethrows any error' before attempting to render the template.
render!
ruby
jekyll/jekyll
lib/jekyll/liquid_renderer/file.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/liquid_renderer/file.rb
MIT
def read site.collections.each_value do |collection| collection.read unless SPECIAL_COLLECTIONS.include?(collection.label) end end
Read in all collections specified in the configuration Returns nothing.
read
ruby
jekyll/jekyll
lib/jekyll/readers/collection_reader.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/readers/collection_reader.rb
MIT
def read(dir) base = @in_source_dir.call(dir) read_data_to(base, @content) @content end
Read all the files in <dir> and adds them to @content dir - The String relative path of the directory to read. Returns @content, a Hash of the .yaml, .yml, .json, and .csv files in the base directory
read
ruby
jekyll/jekyll
lib/jekyll/readers/data_reader.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/readers/data_reader.rb
MIT
def read_data_to(dir, data) return unless File.directory?(dir) && !@entry_filter.symlink?(dir) entries = Dir.chdir(dir) do Dir["*.{yaml,yml,json,csv,tsv}"] + Dir["*"].select { |fn| File.directory?(fn) } end entries.each do |entry| path = @in_source_dir.call(dir, entry) next if @entry_filter.symlink?(path) if File.directory?(path) read_data_to(path, data[sanitize_filename(entry)] = {}) else key = sanitize_filename(File.basename(entry, ".*")) data[key] = read_data_file(path) end end end
Read and parse all .yaml, .yml, .json, .csv and .tsv files under <dir> and add them to the <data> variable. dir - The string absolute path of the directory to read. data - The variable to which data will be added. Returns nothing
read_data_to
ruby
jekyll/jekyll
lib/jekyll/readers/data_reader.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/readers/data_reader.rb
MIT
def read_data_file(path) Jekyll.logger.debug "Reading:", path.sub(@source_dir, "") case File.extname(path).downcase when ".csv" CSV.read(path, **csv_config).map { |row| convert_row(row) } when ".tsv" CSV.read(path, **tsv_config).map { |row| convert_row(row) } else SafeYAML.load_file(path) end end
Determines how to read a data file. Returns the contents of the data file.
read_data_file
ruby
jekyll/jekyll
lib/jekyll/readers/data_reader.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/readers/data_reader.rb
MIT
def read_config(config_key, overrides = {}) reader_config = config[config_key] || {} defaults = { :converters => reader_config.fetch("csv_converters", []).map(&:to_sym), :headers => reader_config.fetch("headers", true), :encoding => reader_config.fetch("encoding", config["encoding"]), } defaults.merge(overrides) end
@param config_key [String] @param overrides [Hash] @return [Hash] @see https://ruby-doc.org/stdlib-2.5.0/libdoc/csv/rdoc/CSV.html#Converters
read_config
ruby
jekyll/jekyll
lib/jekyll/readers/data_reader.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/readers/data_reader.rb
MIT
def convert_row(row) row.instance_of?(CSV::Row) ? row.to_hash : row end
@param row [Array, CSV::Row] @return [Array, Hash]
convert_row
ruby
jekyll/jekyll
lib/jekyll/readers/data_reader.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/readers/data_reader.rb
MIT
def read(files) files.each do |page| @unfiltered_content << Page.new(@site, @site.source, @dir, page) end @unfiltered_content.select { |page| site.publisher.publish?(page) } end
Create a new `Jekyll::Page` object for each entry in a given array. files - An array of file names inside `@dir` Returns an array of publishable `Jekyll::Page` objects.
read
ruby
jekyll/jekyll
lib/jekyll/readers/page_reader.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/readers/page_reader.rb
MIT
def read_drafts(dir) read_publishable(dir, "_drafts", Document::DATELESS_FILENAME_MATCHER) end
Read all the files in <source>/<dir>/_drafts and create a new Document object with each one. dir - The String relative path of the directory to read. Returns nothing.
read_drafts
ruby
jekyll/jekyll
lib/jekyll/readers/post_reader.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/readers/post_reader.rb
MIT
def read_posts(dir) read_publishable(dir, "_posts", Document::DATE_FILENAME_MATCHER) end
Read all the files in <source>/<dir>/_posts and create a new Document object with each one. dir - The String relative path of the directory to read. Returns nothing.
read_posts
ruby
jekyll/jekyll
lib/jekyll/readers/post_reader.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/readers/post_reader.rb
MIT
def read_publishable(dir, magic_dir, matcher) read_content(dir, magic_dir, matcher) .tap { |docs| docs.each(&:read) } .select { |doc| processable?(doc) } end
Read all the files in <source>/<dir>/<magic_dir> and create a new Document object with each one insofar as it matches the regexp matcher. dir - The String relative path of the directory to read. Returns nothing.
read_publishable
ruby
jekyll/jekyll
lib/jekyll/readers/post_reader.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/readers/post_reader.rb
MIT
def read_content(dir, magic_dir, matcher) @site.reader.get_entries(dir, magic_dir).map do |entry| next unless matcher.match?(entry) path = @site.in_source_dir(File.join(dir, magic_dir, entry)) Document.new(path, :site => @site, :collection => @site.posts) end.tap(&:compact!) end
Read all the content files from <source>/<dir>/magic_dir and return them with the type klass. dir - The String relative path of the directory to read. magic_dir - The String relative directory to <dir>, looks for content here. klass - The return type of the content. Returns klass type of content files
read_content
ruby
jekyll/jekyll
lib/jekyll/readers/post_reader.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/readers/post_reader.rb
MIT
def read(files) files.each do |file| @unfiltered_content << StaticFile.new(@site, @site.source, @dir, file) end @unfiltered_content end
Create a new StaticFile object for every entry in a given list of basenames. files - an array of file basenames. Returns an array of static files.
read
ruby
jekyll/jekyll
lib/jekyll/readers/static_file_reader.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/readers/static_file_reader.rb
MIT
def read_file(file, context) File.read(file, **file_read_opts(context)) end
This method allows to modify the file content by inheriting from the class.
read_file
ruby
jekyll/jekyll
lib/jekyll/tags/include.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/tags/include.rb
MIT
def parse_partial(path, context) LiquidRenderer.new(context.registers[:site]).file(path).parse(read_file(path, context)) rescue Liquid::Error => e e.template_name = path e.markup_context = "included " if e.markup_context.nil? raise e end
Since Jekyll 4 caches convertibles based on their path within the only instance of `LiquidRenderer`, initialize a new LiquidRenderer instance on every render of this tag to bypass caching rendered output of page / document.
parse_partial
ruby
jekyll/jekyll
lib/jekyll/tags/include.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/tags/include.rb
MIT
def post_slug(other) path = other.basename.split("/")[0...-1].join("/") if path.nil? || path == "" other.data["slug"] else "#{path}/#{other.data["slug"]}" end end
Construct the directory-aware post slug for a Jekyll::Document object. other - the Jekyll::Document object. Returns the post slug with the subdirectory (relative to _posts)
post_slug
ruby
jekyll/jekyll
lib/jekyll/tags/post_url.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/tags/post_url.rb
MIT
def strip(str) str.gsub MATCH, "" end
Strip ANSI from the current string. It also strips cursor stuff, well some of it, and it also strips some other stuff that a lot of the other ANSI strippers don't.
strip
ruby
jekyll/jekyll
lib/jekyll/utils/ansi.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/utils/ansi.rb
MIT
def reset(str = "") @ansi_reset ||= format("%c[0m", 27) "#{@ansi_reset}#{str}" end
Reset the color back to the default color so that you do not leak any colors when you move onto the next line. This is probably normally used as part of a wrapper so that we don't leak colors.
reset
ruby
jekyll/jekyll
lib/jekyll/utils/ansi.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/utils/ansi.rb
MIT
def run(*args) stdin, stdout, stderr, process = Open3.popen3(*args) out = stdout.read.strip err = stderr.read.strip [stdin, stdout, stderr].each(&:close) [process.value, out + err] end
Runs a program in a sub-shell. *args - a list of strings containing the program name and arguments Returns a Process::Status and a String of output in an array in that order.
run
ruby
jekyll/jekyll
lib/jekyll/utils/exec.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/utils/exec.rb
MIT
def vanilla_windows? rbconfig_host.match?(%r!mswin|mingw|cygwin!) && proc_version.empty? end
Not a Windows Subsystem for Linux (WSL)
vanilla_windows?
ruby
jekyll/jekyll
lib/jekyll/utils/platforms.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/utils/platforms.rb
MIT
def bash_on_windows? linux_os? && microsoft_proc_version? end
Determine if Windows Subsystem for Linux (WSL)
bash_on_windows?
ruby
jekyll/jekyll
lib/jekyll/utils/platforms.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/utils/platforms.rb
MIT
def calculate(timezone, now = Time.now) External.require_with_graceful_fail("tzinfo") unless defined?(TZInfo) tz = TZInfo::Timezone.get(timezone) # # Use period_for_utc and utc_total_offset instead of # period_for and observed_utc_offset for compatibility with tzinfo v1. offset = tz.period_for_utc(now.getutc).utc_total_offset # # POSIX style definition reverses the offset sign. # e.g. Eastern Standard Time (EST) that is 5Hrs. to the 'west' of Prime Meridian # is denoted as: # EST+5 (or) EST+05:00 # Reference: https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html sign = offset.positive? ? "-" : "+" rational_hours = offset.abs.to_r / 3600 hours = rational_hours.to_i minutes = ((rational_hours - hours) * 60).to_i # # Format the hours and minutes as two-digit numbers. time = format("%<hours>02d:%<minutes>02d", :hours => hours, :minutes => minutes) Jekyll.logger.debug "Timezone:", "#{timezone} #{sign}#{time}" # # Note: The 3-letter-word below doesn't have a particular significance. "WTZ#{sign}#{time}" end
Public: Calculate the Timezone for Windows when the config file has a defined 'timezone' key. timezone - the IANA Time Zone specified in "_config.yml" Returns a string that ultimately re-defines ENV["TZ"] in Windows
calculate
ruby
jekyll/jekyll
lib/jekyll/utils/win_tz.rb
https://github.com/jekyll/jekyll/blob/master/lib/jekyll/utils/win_tz.rb
MIT
def literal?(node) node && (simple_literal?(node) || complex_literal?(node)) end
This is not implement using a NodePattern because it seems to not be able to match against an explicit (nil) sexp
literal?
ruby
jekyll/jekyll
rubocop/jekyll/assert_equal_literal_actual.rb
https://github.com/jekyll/jekyll/blob/master/rubocop/jekyll/assert_equal_literal_actual.rb
MIT
def highlight_block_with_markup(markup) Jekyll::Tags::HighlightBlock.parse( "highlight", markup, Liquid::Tokenizer.new("test{% endhighlight %}\n"), Liquid::ParseContext.new ) end
Syntax sugar for low-level version of: ``` {% highlight markup%}test{% endhighlight %} ```
highlight_block_with_markup
ruby
jekyll/jekyll
test/test_tag_highlight.rb
https://github.com/jekyll/jekyll/blob/master/test/test_tag_highlight.rb
MIT
def validate!(machine) finalize! errors = [] if !chef_version.nil? && !valid_chef_version?(chef_version) msg = <<-EOH '#{chef_version}' is not a valid version of Chef. A list of valid versions can be found at: https://downloads.chef.io/chef-client/ EOH errors << msg end if errors.any? rendered_errors = Vagrant::Util::TemplateRenderer.render( "config/validation_failed", errors: { "vagrant-omnibus" => errors } ) raise Vagrant::Errors::ConfigInvalid, errors: rendered_errors end end
Performs validation and immediately raises an exception for any detected errors. @raise [Vagrant::Errors::ConfigInvalid] if validation fails
validate!
ruby
chef-boneyard/vagrant-omnibus
lib/vagrant-omnibus/config.rb
https://github.com/chef-boneyard/vagrant-omnibus/blob/master/lib/vagrant-omnibus/config.rb
Apache-2.0
def valid_chef_version?(version) return true if version.to_s == "latest" begin available = dependency_installer.find_gems_with_sources( chef_gem_dependency(version) ) rescue ArgumentError => e @logger.debug("#{version} is not a valid Chef version: #{e}") return false end !available.empty? end
Query RubyGems.org's Ruby API to see if the user-provided Chef version is in fact a real Chef version!
valid_chef_version?
ruby
chef-boneyard/vagrant-omnibus
lib/vagrant-omnibus/config.rb
https://github.com/chef-boneyard/vagrant-omnibus/blob/master/lib/vagrant-omnibus/config.rb
Apache-2.0
def find_install_script config_install_url || env_install_url || default_install_url end
Determines which install script should be used to install the Omnibus Chef package. Order of precedence: 1. from config 2. from env var 3. default
find_install_script
ruby
chef-boneyard/vagrant-omnibus
lib/vagrant-omnibus/action/install_chef.rb
https://github.com/chef-boneyard/vagrant-omnibus/blob/master/lib/vagrant-omnibus/action/install_chef.rb
Apache-2.0
def install(version, env) shell_escaped_version = Shellwords.escape(version) @machine.communicate.tap do |comm| unless windows_guest? comm.execute("mkdir -p #{install_script_folder}") end comm.upload(@script_tmp_path, install_script_path) if windows_guest? install_cmd = "& #{install_script_path} #{version}" else install_cmd = "sh #{install_script_path}" install_cmd << " -v #{shell_escaped_version}" if download_to_cached_dir? install_cmd << " -d #{cached_omnibus_download_dir}" end install_cmd << " 2>&1" end comm.sudo(install_cmd, communication_opts) do |type, data| if [:stderr, :stdout].include?(type) next if data =~ /stdin: is not a tty/ env[:ui].info(data) end end end end
Upload install script from Host's Vagrant TMP directory to guest and executes.
install
ruby
chef-boneyard/vagrant-omnibus
lib/vagrant-omnibus/action/install_chef.rb
https://github.com/chef-boneyard/vagrant-omnibus/blob/master/lib/vagrant-omnibus/action/install_chef.rb
Apache-2.0
def fetch_or_create_install_script(env) @script_tmp_path = env[:tmp_path].join( "#{Time.now.to_i}-#{install_script_name}" ).to_s @logger.info("Generating install script at: #{@script_tmp_path}") url = @install_script if File.file?(url) || url !~ /^[a-z0-9]+:.*$/i @logger.info("Assuming URL is a file.") file_path = File.expand_path(url) file_path = Vagrant::Util::Platform.cygwin_windows_path(file_path) url = "file:#{file_path}" end # Download the install.sh or create install.bat file to a temporary # path. We store the temporary path as an instance variable so that # the `#recover` method can access it. begin if windows_guest? # generate a install.bat file at the `@script_tmp_path` location # # We'll also disable Rubocop for this embedded PowerShell code: # # rubocop:disable LineLength, SpaceAroundBlockBraces # File.open(@script_tmp_path, "w") do |f| f.puts <<-EOH.gsub(/^\s{18}/, "") @echo off set version=%1 set dest=%~dp0chef-client-%version%-1.windows.msi echo Downloading Chef %version% for Windows... powershell -command "(New-Object System.Net.WebClient).DownloadFile('#{url}?v=%version%', '%dest%')" echo Installing Chef %version% msiexec /q /i "%dest%" EOH end # rubocop:enable LineLength, SpaceAroundBlockBraces else downloader = Vagrant::Util::Downloader.new( url, @script_tmp_path, {} ) downloader.download! end rescue Vagrant::Errors::DownloaderInterrupted # The downloader was interrupted, so just return, because that # means we were interrupted as well. env[:ui].info(I18n.t("vagrant-omnibus.download.interrupted")) return end end
Fetches or creates a platform specific install script to the Host's Vagrant TMP directory.
fetch_or_create_install_script
ruby
chef-boneyard/vagrant-omnibus
lib/vagrant-omnibus/action/install_chef.rb
https://github.com/chef-boneyard/vagrant-omnibus/blob/master/lib/vagrant-omnibus/action/install_chef.rb
Apache-2.0
def expensive_method puts "Called!" "Expensive message" end
We use this dummy method in order to see if the method gets called, but in practice, this method might do complicated string operations to construct a log message.
expensive_method
ruby
TwP/logging
examples/lazy.rb
https://github.com/TwP/logging/blob/master/examples/lazy.rb
MIT
def logger( *args ) return ::Logging::Logger if args.empty? opts = args.pop if args.last.instance_of?(Hash) opts ||= Hash.new dev = args.shift keep = age = args.shift size = args.shift name = case dev when String; dev when File; dev.path else dev.object_id.to_s end repo = ::Logging::Repository.instance return repo[name] if repo.has_logger? name l_opts = { :pattern => "%.1l, [%d #%p] %#{::Logging::MAX_LEVEL_LENGTH}l : %m\n", :date_pattern => '%Y-%m-%dT%H:%M:%S.%s' } [:pattern, :date_pattern, :date_method].each do |o| l_opts[o] = opts.delete(o) if opts.has_key? o end layout = ::Logging::Layouts::Pattern.new(l_opts) a_opts = Hash.new a_opts[:size] = size if size.is_a?(Integer) a_opts[:age] = age if age.instance_of?(String) a_opts[:keep] = keep if keep.is_a?(Integer) a_opts[:filename] = dev if dev.instance_of?(String) a_opts[:layout] = layout a_opts.merge! opts appender = case dev when String ::Logging::Appenders::RollingFile.new(name, a_opts) else ::Logging::Appenders::IO.new(name, dev, a_opts) end logger = ::Logging::Logger.new(name) logger.add_appenders appender logger.additive = false class << logger def close @appenders.each {|a| a.close} h = ::Logging::Repository.instance.instance_variable_get :@h h.delete(@name) class << self; undef :close; end end end logger end
call-seq: Logging.logger( device, age = 7, size = 1048576 ) Logging.logger( device, age = 'weekly' ) This convenience method returns a Logger instance configured to behave similarly to a core Ruby Logger instance. The _device_ is the logging destination. This can be a filename (String) or an IO object (STDERR, STDOUT, an open File, etc.). The _age_ is the number of old log files to keep or the frequency of rotation (+daily+, +weekly+, or +monthly+). The _size_ is the maximum logfile size and is only used when _age_ is a number. Using the same _device_ twice will result in the same Logger instance being returned. For example, if a Logger is created using STDOUT then the same Logger instance will be returned the next time STDOUT is used. A new Logger instance can be obtained by closing the previous logger instance. log1 = Logging.logger(STDOUT) log2 = Logging.logger(STDOUT) log1.object_id == log2.object_id #=> true log1.close log2 = Logging.logger(STDOUT) log1.object_id == log2.object_id #=> false The format of the log messages can be changed using a few optional parameters. The <tt>:pattern</tt> can be used to change the log message format. The <tt>:date_pattern</tt> can be used to change how timestamps are formatted. log = Logging.logger(STDOUT, :pattern => "[%d] %-5l : %m\n", :date_pattern => "%Y-%m-%d %H:%M:%S.%s") See the documentation for the Logging::Layouts::Pattern class for a full description of the :pattern and :date_pattern formatting strings.
logger
ruby
TwP/logging
lib/logging.rb
https://github.com/TwP/logging/blob/master/lib/logging.rb
MIT
def color_scheme( name, opts = {} ) if opts.empty? ::Logging::ColorScheme[name] else ::Logging::ColorScheme.new(name, opts) end end
Returns the color scheme identified by the given _name_. If there is no color scheme +nil+ is returned. If color scheme options are supplied then a new color scheme is created. Any existing color scheme with the given _name_ will be replaced by the new color scheme.
color_scheme
ruby
TwP/logging
lib/logging.rb
https://github.com/TwP/logging/blob/master/lib/logging.rb
MIT
def reopen log_internal {'re-opening all appenders'} ::Logging::Appenders.each {|appender| appender.reopen} self end
Reopen all appenders. This method should be called immediately after a fork to ensure no conflict with file descriptors and calls to fcntl or flock.
reopen
ruby
TwP/logging
lib/logging.rb
https://github.com/TwP/logging/blob/master/lib/logging.rb
MIT
def globally( name = :logger ) Module.new { eval "def #{name}() @_logging_logger ||= ::Logging::Logger[self] end" } end
call-seq: include Logging.globally include Logging.globally( :logger ) Add a "logger" method to the including context. If included from Object or Kernel, the logger method will be available to all objects. Optionally, a method name can be given and that will be used to provided access to the logger: include Logging.globally( :log ) log.info "Just using a shorter method name" If you prefer to use the shorter "log" to access the logger. ==== Example include Logging.globally class Foo logger.debug "Loading the Foo class" def initialize logger.info "Creating some new foo" end end logger.fatal "End of example"
globally
ruby
TwP/logging
lib/logging.rb
https://github.com/TwP/logging/blob/master/lib/logging.rb
MIT
def init( *args ) args = %w(debug info warn error fatal) if args.empty? args.flatten! levels = LEVELS.clear names = LNAMES.clear id = 0 args.each do |lvl| lvl = levelify lvl unless levels.has_key?(lvl) or lvl == 'all' or lvl == 'off' levels[lvl] = id names[id] = lvl.upcase id += 1 end end longest = names.inject {|x,y| (x.length > y.length) ? x : y} longest = 'off' if longest.length < 3 module_eval "MAX_LEVEL_LENGTH = #{longest.length}", __FILE__, __LINE__ self.cause_depth = nil unless defined? @cause_depth self.raise_errors = false unless defined? @raise_errors initialize_plugins levels.keys end
call-seq: Logging.init( levels ) Defines the levels available to the loggers. The _levels_ is an array of strings and symbols. Each element in the array is downcased and converted to a symbol; these symbols are used to create the logging methods in the loggers. The first element in the array is the lowest logging level. Setting the logging level to this value will enable all log messages. The last element in the array is the highest logging level. Setting the logging level to this value will disable all log messages except this highest level. This method should be invoked only once to configure the logging levels. It is automatically invoked with the default logging levels when the first logger is created. The levels "all" and "off" are reserved and will be ignored if passed to this method. Example: Logging.init :debug, :info, :warn, :error, :fatal log = Logging::Logger['my logger'] log.level = :warn log.warn 'Danger! Danger! Will Robinson' log.info 'Just FYI' # => not logged or Logging.init %w(DEBUG INFO NOTICE WARNING ERR CRIT ALERT EMERG) log = Logging::Logger['syslog'] log.level = :notice log.warning 'This is your first warning' log.info 'Just FYI' # => not logged
init
ruby
TwP/logging
lib/logging.rb
https://github.com/TwP/logging/blob/master/lib/logging.rb
MIT
def format_as( f ) f = f.intern if f.instance_of? String unless [:string, :inspect, :yaml, :json].include? f raise ArgumentError, "unknown object format '#{f}'" end module_eval "OBJ_FORMAT = :#{f}", __FILE__, __LINE__ self end
call-seq: Logging.format_as( obj_format ) Defines the default _obj_format_ method to use when converting objects into string representations for logging. _obj_format_ can be one of <tt>:string</tt>, <tt>:inspect</tt>, <tt>:json</tt> or <tt>:yaml</tt>. These formatting commands map to the following object methods * :string => to_s * :inspect => inspect * :yaml => to_yaml * :json => MultiJson.encode(obj) An +ArgumentError+ is raised if anything other than +:string+, +:inspect+, +:json+ or +:yaml+ is passed to this method.
format_as
ruby
TwP/logging
lib/logging.rb
https://github.com/TwP/logging/blob/master/lib/logging.rb
MIT
def backtrace( b = nil ) @backtrace = true unless defined? @backtrace return @backtrace if b.nil? @backtrace = case b when :on, 'on', true; true when :off, 'off', false; false else raise ArgumentError, "backtrace must be true or false" end end
call-seq: Logging.backtrace #=> true or false Logging.backtrace( value ) #=> true or false Without any arguments, returns the global exception backtrace logging value. When set to +true+ backtraces will be written to the logs; when set to +false+ backtraces will be suppressed. When an argument is given the global exception backtrace setting will be changed. Value values are <tt>"on"</tt>, <tt>:on<tt> and +true+ to turn on backtraces and <tt>"off"</tt>, <tt>:off</tt> and +false+ to turn off backtraces.
backtrace
ruby
TwP/logging
lib/logging.rb
https://github.com/TwP/logging/blob/master/lib/logging.rb
MIT
def libpath( *args, &block ) rv = args.empty? ? LIBPATH : ::File.join(LIBPATH, args.flatten) if block begin $LOAD_PATH.unshift LIBPATH rv = block.call ensure $LOAD_PATH.shift end end return rv end
Returns the library path for the module. If any arguments are given, they will be joined to the end of the library path using <tt>File.join</tt>.
libpath
ruby
TwP/logging
lib/logging.rb
https://github.com/TwP/logging/blob/master/lib/logging.rb
MIT
def path( *args, &block ) rv = args.empty? ? PATH : ::File.join(PATH, args.flatten) if block begin $LOAD_PATH.unshift PATH rv = block.call ensure $LOAD_PATH.shift end end return rv end
Returns the lpath for the module. If any arguments are given, they will be joined to the end of the path using <tt>File.join</tt>.
path
ruby
TwP/logging
lib/logging.rb
https://github.com/TwP/logging/blob/master/lib/logging.rb
MIT
def show_configuration( io = STDOUT, logger = 'root', indent = 0 ) logger = ::Logging::Logger[logger] unless logger.is_a?(::Logging::Logger) io << logger._dump_configuration(indent) indent += 2 children = ::Logging::Repository.instance.children(logger.name) children.sort {|a,b| a.name <=> b.name}.each do |child| ::Logging.show_configuration(io, child, indent) end io end
call-seq: show_configuration( io = STDOUT, logger = 'root' ) This method is used to show the configuration of the logging framework. The information is written to the given _io_ stream (defaulting to stdout). Normally the configuration is dumped starting with the root logger, but any logger name can be given. Each line contains information for a single logger and it's appenders. A child logger is indented two spaces from it's parent logger. Each line contains the logger name, level, additivity, and trace settings. Here is a brief example: root ........................... *info -T LoggerA ...................... info +A -T LoggerA::LoggerB ........... info +A -T LoggerA::LoggerC ........... *debug +A -T LoggerD ...................... *warn -A +T The lines can be deciphered as follows: 1) name - the name of the logger 2) level - the logger level; if it is preceded by an asterisk then the level was explicitly set for that logger (as opposed to being inherited from the parent logger) 3) additivity - a "+A" shows the logger is additive, and log events will be passed up to the parent logger; "-A" shows that the logger will *not* pass log events up to the parent logger 4) tracing - a "+T" shows that the logger will include caller tracing information in generated log events (this includes filename and line number of the log message); "-T" shows that the logger does not include caller tracing information in the log events If a logger has appenders then they are listed, one per line, immediately below the logger. Appender lines are pre-pended with a single dash: root ........................... *info -T - <Appenders::Stdout:0x8b02a4 name="stdout"> LoggerA ...................... info +A -T LoggerA::LoggerB ........... info +A -T LoggerA::LoggerC ........... *debug +A -T LoggerD ...................... *warn -A +T - <Appenders::Stderr:0x8b04ca name="stderr"> We can see in this configuration dump that all the loggers will append to stdout via the Stdout appender configured in the root logger. All the loggers are additive, and so their generated log events will be passed up to the root logger. The exception in this configuration is LoggerD. Its additivity is set to false. It uses its own appender to send messages to stderr.
show_configuration
ruby
TwP/logging
lib/logging.rb
https://github.com/TwP/logging/blob/master/lib/logging.rb
MIT
def levelify( level ) case level when String; level.downcase when Symbol; level.to_s.downcase else raise ArgumentError, "levels must be a String or Symbol" end end
:stopdoc: Convert the given level into a canonical form - a lowercase string.
levelify
ruby
TwP/logging
lib/logging.rb
https://github.com/TwP/logging/blob/master/lib/logging.rb
MIT
def level_num( level ) l = levelify(level) rescue level case l when 'all'; 0 when 'off'; LEVELS.length else begin; Integer(l); rescue ArgumentError; LEVELS[l] end end end
Convert the given level into a level number.
level_num
ruby
TwP/logging
lib/logging.rb
https://github.com/TwP/logging/blob/master/lib/logging.rb
MIT
def log_internal( level = 1, &block ) ::Logging::Logger[::Logging].__send__(levelify(LNAMES[level]), &block) end
Internal logging method for use by the framework.
log_internal
ruby
TwP/logging
lib/logging.rb
https://github.com/TwP/logging/blob/master/lib/logging.rb
MIT