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 initialize(rules_collection, config) @rules_collection = rules_collection @config = config super({ config: }) end
Creates a new compiler DSL for the given collection of rules. @api private @param [Nanoc::RuleDSL::RulesCollection] rules_collection The collection of rules to modify when loading this DSL @param [Hash] config The site configuration
initialize
ruby
nanoc/nanoc
nanoc/lib/nanoc/rule_dsl/compiler_dsl.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/rule_dsl/compiler_dsl.rb
MIT
def preprocess(&block) if @rules_collection.preprocessors[rules_filename] warn 'WARNING: A preprocess block is already defined. Defining ' \ 'another preprocess block overrides the previously one.' end @rules_collection.preprocessors[rules_filename] = block end
Creates a preprocessor block that will be executed after all data is loaded, but before the site is compiled. @yield The block that will be executed before site compilation starts @return [void]
preprocess
ruby
nanoc/nanoc
nanoc/lib/nanoc/rule_dsl/compiler_dsl.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/rule_dsl/compiler_dsl.rb
MIT
def compile(identifier, rep: :default, &block) raise ArgumentError.new('#compile requires a block') unless block_given? rule = Nanoc::RuleDSL::CompilationRule.new(create_pattern(identifier), rep, block) @rules_collection.add_item_compilation_rule(rule) end
Creates a compilation rule for all items whose identifier match the given identifier, which may either be a string containing the * wildcard, or a regular expression. This rule will be applicable to reps with a name equal to `:default`; this can be changed by giving an explicit `:rep` parameter. An item rep will be compiled by calling the given block and passing the rep as a block argument. @param [String] identifier A pattern matching identifiers of items that should be compiled using this rule @param [Symbol] rep The name of the representation @yield The block that will be executed when an item matching this compilation rule needs to be compiled @return [void] @example Compiling the default rep of the `/foo/` item compile '/foo/' do rep.filter :erb end @example Compiling the `:raw` rep of the `/bar/` item compile '/bar/', :rep => :raw do # do nothing end
compile
ruby
nanoc/nanoc
nanoc/lib/nanoc/rule_dsl/compiler_dsl.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/rule_dsl/compiler_dsl.rb
MIT
def route(identifier, rep: :default, snapshot: :last, &block) raise ArgumentError.new('#route requires a block') unless block_given? rule = Nanoc::RuleDSL::RoutingRule.new(create_pattern(identifier), rep, block, snapshot_name: snapshot) @rules_collection.add_item_routing_rule(rule) end
Creates a routing rule for all items whose identifier match the given identifier, which may either be a string containing the `*` wildcard, or a regular expression. This rule will be applicable to reps with a name equal to `:default`; this can be changed by giving an explicit `:rep` parameter. The path of an item rep will be determined by calling the given block and passing the rep as a block argument. @param [String] identifier A pattern matching identifiers of items that should be routed using this rule @param [Symbol] rep The name of the representation @param [Symbol] snapshot The name of the snapshot @yield The block that will be executed when an item matching this compilation rule needs to be routed @return [void] @example Routing the default rep of the `/foo/` item route '/foo/' do item.identifier + 'index.html' end @example Routing the `:raw` rep of the `/bar/` item route '/bar/', :rep => :raw do '/raw' + item.identifier + 'index.txt' end
route
ruby
nanoc/nanoc
nanoc/lib/nanoc/rule_dsl/compiler_dsl.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/rule_dsl/compiler_dsl.rb
MIT
def layout(identifier, filter_name, params = {}) pattern = Nanoc::Core::Pattern.from(create_pattern(identifier)) @rules_collection.layout_filter_mapping[pattern] = [filter_name, params] end
Creates a layout rule for all layouts whose identifier match the given identifier, which may either be a string containing the * wildcard, or a regular expression. The layouts matching the identifier will be filtered using the filter specified in the second argument. The params hash contains filter arguments that will be passed to the filter. @param [String] identifier A pattern matching identifiers of layouts that should be filtered using this rule @param [Symbol] filter_name The name of the filter that should be run when processing the layout @param [Hash] params Extra filter arguments that should be passed to the filter when processing the layout (see {Nanoc::Filter#run}) @return [void] @example Specifying the filter to use for a layout layout '/default/', :erb @example Using custom filter arguments for a layout layout '/custom/', :haml, :format => :html5
layout
ruby
nanoc/nanoc
nanoc/lib/nanoc/rule_dsl/compiler_dsl.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/rule_dsl/compiler_dsl.rb
MIT
def passthrough(identifier, rep: :default) raise ArgumentError.new('#passthrough does not require a block') if block_given? compilation_block = proc {} compilation_rule = Nanoc::RuleDSL::CompilationRule.new(create_pattern(identifier), rep, compilation_block) @rules_collection.add_item_compilation_rule(compilation_rule) # Create routing rule routing_block = proc do if item.identifier.full? item.identifier.to_s else # This is a temporary solution until an item can map back to its data # source. # ATM item[:content_filename] is nil for items coming from the static # data source. item[:extension].nil? || (item[:content_filename].nil? && item.identifier =~ %r{#{item[:extension]}/$}) ? item.identifier.chop : item.identifier.chop + '.' + item[:extension] end end routing_rule = Nanoc::RuleDSL::RoutingRule.new(create_pattern(identifier), rep, routing_block, snapshot_name: :last) @rules_collection.add_item_routing_rule(routing_rule) end
Creates a pair of compilation and routing rules that indicate that the specified item(s) should be copied to the output folder as-is. The items are selected using an identifier, which may either be a string containing the `*` wildcard, or a regular expression. This meta-rule will be applicable to reps with a name equal to `:default`; this can be changed by giving an explicit `:rep` parameter. @param [String] identifier A pattern matching identifiers of items that should be processed using this meta-rule @param [Symbol] rep The name of the representation @return [void] @example Copying the `/foo/` item as-is passthrough '/foo/' @example Copying the `:raw` rep of the `/bar/` item as-is passthrough '/bar/', :rep => :raw
passthrough
ruby
nanoc/nanoc
nanoc/lib/nanoc/rule_dsl/compiler_dsl.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/rule_dsl/compiler_dsl.rb
MIT
def ignore(identifier, rep: :default) raise ArgumentError.new('#ignore does not require a block') if block_given? compilation_rule = Nanoc::RuleDSL::CompilationRule.new(create_pattern(identifier), rep, proc {}) @rules_collection.add_item_compilation_rule(compilation_rule) routing_rule = Nanoc::RuleDSL::RoutingRule.new(create_pattern(identifier), rep, proc {}, snapshot_name: :last) @rules_collection.add_item_routing_rule(routing_rule) end
Creates a pair of compilation and routing rules that indicate that the specified item(s) should be ignored, e.g. compiled and routed with an empty rule. The items are selected using an identifier, which may either be a string containing the `*` wildcard, or a regular expression. This meta-rule will be applicable to reps with a name equal to `:default`; this can be changed by giving an explicit `:rep` parameter. @param [String] identifier A pattern matching identifiers of items that should be processed using this meta-rule @param [Symbol] rep The name of the representation @return [void] @example Suppressing compilation and output for all all `/foo/*` items. ignore '/foo/*'
ignore
ruby
nanoc/nanoc
nanoc/lib/nanoc/rule_dsl/compiler_dsl.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/rule_dsl/compiler_dsl.rb
MIT
def add_item_compilation_rule(rule) @item_compilation_rules << rule end
Add the given rule to the list of item compilation rules. @param [Nanoc::Int::Rule] rule The item compilation rule to add @return [void]
add_item_compilation_rule
ruby
nanoc/nanoc
nanoc/lib/nanoc/rule_dsl/rules_collection.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/rule_dsl/rules_collection.rb
MIT
def add_item_routing_rule(rule) @item_routing_rules << rule end
Add the given rule to the list of item routing rules. @param [Nanoc::Int::Rule] rule The item routing rule to add @return [void]
add_item_routing_rule
ruby
nanoc/nanoc
nanoc/lib/nanoc/rule_dsl/rules_collection.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/rule_dsl/rules_collection.rb
MIT
def item_compilation_rules_for(item) @item_compilation_rules.select { |r| r.applicable_to?(item) } end
@param [Nanoc::Core::Item] item The item for which the compilation rules should be retrieved @return [Array] The list of item compilation rules for the given item
item_compilation_rules_for
ruby
nanoc/nanoc
nanoc/lib/nanoc/rule_dsl/rules_collection.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/rule_dsl/rules_collection.rb
MIT
def compilation_rule_for(rep) @item_compilation_rules.find do |rule| rule.applicable_to?(rep.item) && rule.rep_name == rep.name end end
Finds the first matching compilation rule for the given item representation. @param [Nanoc::Core::ItemRep] rep The item rep for which to fetch the rule @return [Nanoc::Int::Rule, nil] The compilation rule for the given item rep, or nil if no rules have been found
compilation_rule_for
ruby
nanoc/nanoc
nanoc/lib/nanoc/rule_dsl/rules_collection.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/rule_dsl/rules_collection.rb
MIT
def routing_rules_for(rep) rules = {} @item_routing_rules.each do |rule| next unless rule.applicable_to?(rep.item) next if rule.rep_name != rep.name next if rules.key?(rule.snapshot_name) rules[rule.snapshot_name] = rule end rules end
Returns the list of routing rules that can be applied to the given item representation. For each snapshot, the first matching rule will be returned. The result is a hash containing the corresponding rule for each snapshot. @param [Nanoc::Core::ItemRep] rep The item rep for which to fetch the rules @return [Hash<Symbol, Nanoc::Int::Rule>] The routing rules for the given rep
routing_rules_for
ruby
nanoc/nanoc
nanoc/lib/nanoc/rule_dsl/rules_collection.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/rule_dsl/rules_collection.rb
MIT
def filter_for_layout(layout) @layout_filter_mapping.each_pair do |pattern, filter_name_and_args| return filter_name_and_args if pattern.match?(layout.identifier) end nil end
Finds the filter name and arguments to use for the given layout. @param [Nanoc::Core::Layout] layout The layout for which to fetch the filter. @return [Array, nil] A tuple containing the filter name and the filter arguments for the given layout.
filter_for_layout
ruby
nanoc/nanoc
nanoc/lib/nanoc/rule_dsl/rules_collection.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/rule_dsl/rules_collection.rb
MIT
def assert_examples_correct(object) P(object).tags(:example).each do |example| # Classify lines = example.text.lines.map do |line| [/^\s*# ?=>/.match?(line) ? :result : :code, line] end # Join pieces = [] lines.each do |line| if !pieces.empty? && pieces.last.first == line.first pieces.last.last << line.last else pieces << line end end lines = pieces.map(&:last) # Test b = binding lines.each_slice(2) do |pair| actual_out = eval(pair.first, b) expected_out = eval(pair.last.match(/# ?=>(.*)/)[1], b) assert_equal( expected_out, actual_out, "Incorrect example:\n#{pair.first}", ) end end end
Adapted from https://github.com/lsegal/yard-examples/tree/master/doctest
assert_examples_correct
ruby
nanoc/nanoc
nanoc/test/helper.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/test/helper.rb
MIT
def resource_uris_in_file(filename) uris_in_file filename, %w[audio base form iframe img link object script source video] end
embedded resources, used by the mixed-content checker
resource_uris_in_file
ruby
nanoc/nanoc
nanoc-checking/lib/nanoc/checking/link_collector.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-checking/lib/nanoc/checking/link_collector.rb
MIT
def initialize(site) @site = site @log_mutex = Thread::Mutex.new end
@param [Nanoc::Core::Site] site The Nanoc site this runner is for
initialize
ruby
nanoc/nanoc
nanoc-checking/lib/nanoc/checking/runner.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-checking/lib/nanoc/checking/runner.rb
MIT
def list_checks load_all puts 'Available checks:' puts puts all_check_classes.map { |i| ' ' + i.identifier.to_s }.sort.join("\n") end
Lists all available checks on stdout. @return [void]
list_checks
ruby
nanoc/nanoc
nanoc-checking/lib/nanoc/checking/runner.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-checking/lib/nanoc/checking/runner.rb
MIT
def run_all load_all run_check_classes(all_check_classes) end
Runs all checks. @return [Boolean] true if successful, false otherwise
run_all
ruby
nanoc/nanoc
nanoc-checking/lib/nanoc/checking/runner.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-checking/lib/nanoc/checking/runner.rb
MIT
def run_for_deploy # TODO: rename to #run_enabled load_all run_check_classes(check_classes_named(enabled_checks)) end
Runs the checks marked for deployment. @return [Boolean] true if successful, false otherwise
run_for_deploy
ruby
nanoc/nanoc
nanoc-checking/lib/nanoc/checking/runner.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-checking/lib/nanoc/checking/runner.rb
MIT
def run_specific(check_class_names) load_all run_check_classes(check_classes_named(check_class_names)) end
Runs the checks with the given names. @param [Array<Symbol>] check_class_names The names of the checks @return [Boolean] true if successful, false otherwise
run_specific
ruby
nanoc/nanoc
nanoc-checking/lib/nanoc/checking/runner.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-checking/lib/nanoc/checking/runner.rb
MIT
def run # TODO: de-duplicate this (duplicated in external links check) filenames = output_html_filenames uris = ::Nanoc::Checking::LinkCollector.new(filenames, :internal).filenames_per_href uris.each_pair do |href, fns| fns.each do |filename| next if valid?(href, filename) add_issue( "broken reference to <#{href}>", subject: filename, ) end end end
Starts the validator. The results will be printed to stdout. Internal links that match a regexp pattern in `@config[:checks][:internal_links][:exclude]` will be skipped. @return [void]
run
ruby
nanoc/nanoc
nanoc-checking/lib/nanoc/checking/checks/internal_links.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-checking/lib/nanoc/checking/checks/internal_links.rb
MIT
def assert_examples_correct(object) P(object).tags(:example).each do |example| # Classify lines = example.text.lines.map do |line| [/^\s*# ?=>/.match?(line) ? :result : :code, line] end # Join pieces = [] lines.each do |line| if !pieces.empty? && pieces.last.first == line.first pieces.last.last << line.last else pieces << line end end lines = pieces.map(&:last) # Test b = binding lines.each_slice(2) do |pair| actual_out = eval(pair.first, b) expected_out = eval(pair.last.match(/# ?=>(.*)/)[1], b) assert_equal( expected_out, actual_out, "Incorrect example:\n#{pair.first}", ) end end end
Adapted from https://github.com/lsegal/yard-examples/tree/master/doctest
assert_examples_correct
ruby
nanoc/nanoc
nanoc-checking/test/helper.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-checking/test/helper.rb
MIT
def c(str, *attrs) if enabled? attrs.map { |a| MAPPING[a] }.join('') + str + CLEAR else str end end
@param [String] str The string to colorize @param [Array] attrs An array of attributes from `MAPPING` to colorize the string with @return [String] A string colorized using the given attributes
c
ruby
nanoc/nanoc
nanoc-cli/lib/nanoc/cli/ansi_string_colorizer.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-cli/lib/nanoc/cli/ansi_string_colorizer.rb
MIT
def initialize(stream) @stream = stream @stream_cleaners = [] end
@param [IO, StringIO] stream The stream to wrap
initialize
ruby
nanoc/nanoc
nanoc-cli/lib/nanoc/cli/cleaning_stream.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-cli/lib/nanoc/cli/cleaning_stream.rb
MIT
def add_stream_cleaner(klass) unless @stream_cleaners.map(&:class).include?(klass) @stream_cleaners << klass.new end end
Adds a stream cleaner for the given class to this cleaning stream. If the cleaning stream already has the given stream cleaner, nothing happens. @param [Nanoc::CLI::StreamCleaners::Abstract] klass The class of the stream cleaner to add @return [void]
add_stream_cleaner
ruby
nanoc/nanoc
nanoc-cli/lib/nanoc/cli/cleaning_stream.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-cli/lib/nanoc/cli/cleaning_stream.rb
MIT
def remove_stream_cleaner(klass) @stream_cleaners.delete_if { |c| c.instance_of?(klass) } end
Removes the stream cleaner for the given class from this cleaning stream. If the cleaning stream does not have the given stream cleaner, nothing happens. @param [Nanoc::CLI::StreamCleaners::Abstract] klass The class of the stream cleaner to add @return [void]
remove_stream_cleaner
ruby
nanoc/nanoc
nanoc-cli/lib/nanoc/cli/cleaning_stream.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-cli/lib/nanoc/cli/cleaning_stream.rb
MIT
def write(str) _nanoc_swallow_broken_pipe_errors_while do @stream.write(_nanoc_clean(str)) end end
@group IO proxy methods @see IO#write
write
ruby
nanoc/nanoc
nanoc-cli/lib/nanoc/cli/cleaning_stream.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-cli/lib/nanoc/cli/cleaning_stream.rb
MIT
def call Nanoc::CLI::ErrorHandler.handle_while do run end end
@see http://rubydoc.info/gems/cri/Cri/CommandRunner#call-instance_method @return [void]
call
ruby
nanoc/nanoc
nanoc-cli/lib/nanoc/cli/command_runner.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-cli/lib/nanoc/cli/command_runner.rb
MIT
def handle_while(exit_on_error:) # Set exit handler %w[INT TERM].each do |signal| Signal.trap(signal) do puts exit(0) end end # Set stack trace dump handler if !defined?(RUBY_ENGINE) || RUBY_ENGINE != 'jruby' begin Signal.trap('USR1') do puts 'Caught USR1; dumping a stack trace' puts caller.map { |i| " #{i}" }.join("\n") end rescue ArgumentError end end # Run yield rescue Exception => e # rubocop:disable Lint/RescueException # The exception could be wrapped in a # Nanoc::Core::Errors::CompilationError, so find the # underlying exception and handle that one instead. e = unwrap_error(e) case e when Interrupt puts exit(1) when StandardError, ScriptError handle_error(e, exit_on_error:) else raise e end end
Enables error handling in the given block. This method should not be called directly; use {Nanoc::CLI::ErrorHandler.handle_while} instead. @return [void]
handle_while
ruby
nanoc/nanoc
nanoc-cli/lib/nanoc/cli/error_handler.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-cli/lib/nanoc/cli/error_handler.rb
MIT
def print_error(error) write_compact_error(error, $stderr) File.open('crash.log', 'w') do |io| write_verbose_error(error, io) end end
Prints the given error to stderr. Includes message, possible resolution (see {#resolution_for}), compilation stack, backtrace, etc. @param [Error] error The error that should be described @return [void]
print_error
ruby
nanoc/nanoc
nanoc-cli/lib/nanoc/cli/error_handler.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-cli/lib/nanoc/cli/error_handler.rb
MIT
def file(level, action, name, duration = nil) colorizer = Nanoc::CLI::ANSIStringColorizer.new($stdout) colored_action = colorizer.c(action.to_s, *ACTION_COLORS[action.to_sym]) message = format( '%12s %s%s', colored_action, duration.nil? ? '' : format('[%2.2fs] ', duration), name, ) log(level, message) end
Logs a file-related action. @param [:high, :low] level The importance of this action @param [:create, :update, :identical, :cached, :skip, :delete] action The kind of file action @param [String] name The name of the file the action was performed on @return [void]
file
ruby
nanoc/nanoc
nanoc-cli/lib/nanoc/cli/logger.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-cli/lib/nanoc/cli/logger.rb
MIT
def log(level, message) return if @level == :off return if @level != :low && @level != level @mutex.synchronize do puts(message) end end
Logs a message. @param [:high, :low] level The importance of this message @param [String] message The message to be logged @return [void]
log
ruby
nanoc/nanoc
nanoc-cli/lib/nanoc/cli/logger.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-cli/lib/nanoc/cli/logger.rb
MIT
def array_to_yaml(array) '[ ' + array.map { |s| "'" + s + "'" }.join(', ') + ' ]' end
Converts the given array to YAML format
array_to_yaml
ruby
nanoc/nanoc
nanoc-cli/lib/nanoc/cli/commands/create-site.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-cli/lib/nanoc/cli/commands/create-site.rb
MIT
def initialize(reps:) @reps = reps @stages_summary = DDMetrics::Summary.new @phases_summary = DDMetrics::Summary.new @outdatedness_rules_summary = DDMetrics::Summary.new @filters_summary = DDMetrics::Summary.new @load_stores_summary = DDMetrics::Summary.new @store_stores_summary = DDMetrics::Summary.new end
@param [Enumerable<Nanoc::Core::ItemRep>] reps
initialize
ruby
nanoc/nanoc
nanoc-cli/lib/nanoc/cli/compile_listeners/timing_recorder.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-cli/lib/nanoc/cli/compile_listeners/timing_recorder.rb
MIT
def clean(str) raise NotImplementedError, 'Subclasses of Nanoc::CLI::StreamCleaners::Abstract must implement #clean' end
Returns a cleaned version of the given string. @param [String] str The string to clean @return [String] The cleaned string
clean
ruby
nanoc/nanoc
nanoc-cli/lib/nanoc/cli/stream_cleaners/abstract.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-cli/lib/nanoc/cli/stream_cleaners/abstract.rb
MIT
def snapshot_actions @actions.select { |a| a.is_a?(Nanoc::Core::ProcessingActions::Snapshot) } end
contract C::None => C::ArrayOf[Nanoc::Core::ProcessingAction]
snapshot_actions
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/action_sequence.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/action_sequence.rb
MIT
def each(&) @actions.each(&) self end
contract C::Func[Nanoc::Core::ProcessingAction => C::Any] => self
each
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/action_sequence.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/action_sequence.rb
MIT
def map(&) self.class.new( actions: @actions.map(&), ) end
contract C::Func[Nanoc::Core::ProcessingAction => C::Any] => self
map
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/action_sequence.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/action_sequence.rb
MIT
def each @item_reps.each { |ir| yield view_class.new(ir, @context) } self end
Calls the given block once for each item rep, passing that item rep as a parameter. @yieldparam [Object] item rep view @yieldreturn [void] @return [self]
each
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/basic_item_rep_collection_view.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/basic_item_rep_collection_view.rb
MIT
def fetch(rep_name) res = @item_reps.find { |ir| ir.name == rep_name } if res view_class.new(res, @context) else raise NoSuchItemRepError.new(rep_name) end end
Return the item rep with the given name, or raises an exception if there is no rep with the given name. @param [Symbol] rep_name @return [Nanoc::Core::BasicItemRepView] @raise if no rep was found
fetch
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/basic_item_rep_collection_view.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/basic_item_rep_collection_view.rb
MIT
def children unless _unwrap.identifier.legacy? raise Nanoc::Core::Errors::CannotGetParentOrChildrenOfNonLegacyItem.new(_unwrap.identifier) end children_pattern = Nanoc::Core::Pattern.from(_unwrap.identifier.to_s + '*/') children = @context.items.select { |i| children_pattern.match?(i.identifier) } children.map { |i| self.class.new(i, @context) }.freeze end
Returns the children of this item. For items with identifiers that have extensions, returns an empty collection. @return [Enumerable<Nanoc::Core::CompilationItemView>]
children
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/basic_item_view.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/basic_item_view.rb
MIT
def parent unless _unwrap.identifier.legacy? raise Nanoc::Core::Errors::CannotGetParentOrChildrenOfNonLegacyItem.new(_unwrap.identifier) end parent_identifier = '/' + _unwrap.identifier.components[0..-2].join('/') + '/' parent_identifier = '/' if parent_identifier == '//' parent = @context.items.object_with_identifier(parent_identifier) parent && self.class.new(parent, @context) end
Returns the parent of this item, if one exists. For items with identifiers that have extensions, returns nil. @return [Nanoc::Core::CompilationItemView] if the item has a parent @return [nil] if the item has no parent
parent
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/basic_item_view.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/basic_item_view.rb
MIT
def raw_filename @context.dependency_tracker.bounce(_unwrap, raw_content: true) _unwrap.content.filename end
@return [String, nil] The path to the file containing the uncompiled content of this item.
raw_filename
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/basic_item_view.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/basic_item_view.rb
MIT
def initialize(data, filename) @data = data @filename = filename end
Creates a new code snippet. @param [String] data The raw source code which will be executed before compilation @param [String] filename The filename corresponding to this code snippet
initialize
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/code_snippet.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/code_snippet.rb
MIT
def load # rubocop:disable Security/Eval eval(<<~CODE, TOPLEVEL_BINDING) unless respond_to?(:use_helper) def self.use_helper(mod) Nanoc::Core::Context.instance_eval { include mod } end end CODE eval(@data, TOPLEVEL_BINDING, @filename) # rubocop:enable Security/Eval nil end
Loads the code by executing it. @return [void]
load
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/code_snippet.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/code_snippet.rb
MIT
def full_cache_available?(rep) @textual_cache.include?(rep) && @binary_cache.include?(rep) end
True if there is cached compiled content available for this item, and all entries are present (either textual or binary).
full_cache_available?
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/compiled_content_cache.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/compiled_content_cache.rb
MIT
def initialize(hash) hash.each_pair do |key, value| instance_variable_set('@' + key.to_s, value) end end
Creates a new context based off the contents of the hash. Each pair in the hash will be converted to an instance variable and an instance method. For example, passing the hash `{ :foo => 'bar' }` will cause `@foo` to have the value `"bar"`, and the instance method `#foo` to return the same value `"bar"`. @param [Hash] hash A list of key-value pairs to make available @example Defining a context and accessing values context = Nanoc::Core::Context.new( :name => 'Max Payne', :location => 'in a cheap motel' ) context.instance_eval do "I am #{name} and I am hiding #{@location}." end # => "I am Max Payne and I am hiding in a cheap motel."
initialize
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/context.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/context.rb
MIT
def use up if @references.zero? @references += 1 end
Marks the data source as used by the caller. Calling this method increases the internal reference count. When the data source is used for the first time (first {#use} call), the data source will be loaded ({#up} will be called). @return [void]
use
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/data_source.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/data_source.rb
MIT
def unuse @references -= 1 down if @references.zero? end
Marks the data source as unused by the caller. Calling this method decreases the internal reference count. When the reference count reaches zero, i.e. when the data source is not used any more, the data source will be unloaded ({#down} will be called). @return [void]
unuse
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/data_source.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/data_source.rb
MIT
def new_item(content, attributes, identifier, binary: false, checksum_data: nil, content_checksum_data: nil, attributes_checksum_data: nil) content = Nanoc::Core::Content.create(content, binary:) Nanoc::Core::Item.new(content, attributes, identifier, checksum_data:, content_checksum_data:, attributes_checksum_data:) end
Creates a new in-memory item instance. This is intended for use within the {#items} method. @param [String, Proc] content The uncompiled item content (if it is a textual item) or the path to the filename containing the content (if it is a binary item). @param [Hash, Proc] attributes A hash containing this item's attributes. @param [String] identifier This item's identifier. @param [Boolean] binary Whether or not this item is binary @param [String, nil] checksum_data @param [String, nil] content_checksum_data @param [String, nil] attributes_checksum_data
new_item
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/data_source.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/data_source.rb
MIT
def new_layout(raw_content, attributes, identifier, checksum_data: nil, content_checksum_data: nil, attributes_checksum_data: nil) Nanoc::Core::Layout.new(raw_content, attributes, identifier, checksum_data:, content_checksum_data:, attributes_checksum_data:) end
Creates a new in-memory layout instance. This is intended for use within the {#layouts} method. @param [String] raw_content The raw content of this layout. @param [Hash] attributes A hash containing this layout's attributes. @param [String] identifier This layout's identifier. @param [String, nil] checksum_data @param [String, nil] content_checksum_data @param [String, nil] attributes_checksum_data
new_layout
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/data_source.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/data_source.rb
MIT
def record_dependency(src, dst, raw_content: false, attributes: false, compiled_content: false, path: false) return if src == dst add_vertex_for(src) add_vertex_for(dst) src_ref = obj2ref(src) dst_ref = obj2ref(dst) # Convert attributes into key-value pairs, if necessary if attributes.is_a?(Hash) attributes = attributes.to_a end existing_props = @graph.props_for(dst_ref, src_ref) new_props = Nanoc::Core::DependencyProps.new(raw_content:, attributes:, compiled_content:, path:) props = existing_props ? existing_props.merge(new_props) : new_props @graph.add_edge(dst_ref, src_ref, props:) end
Records a dependency from `src` to `dst` in the dependency graph. When `dst` is oudated, `src` will also become outdated. @param [Nanoc::Core::Item, Nanoc::Core::Layout] src The source of the dependency, i.e. the object that will become outdated if dst is outdated @param [Nanoc::Core::Item, Nanoc::Core::Layout] dst The destination of the dependency, i.e. the object that will cause the source to become outdated if the destination is outdated @return [void]
record_dependency
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/dependency_store.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/dependency_store.rb
MIT
def initialize(vertices) @vertices = {} @next_vertex_idx = 0 vertices.each do |v| @vertices[v] = @next_vertex_idx.tap { @next_vertex_idx += 1 } end @to_graph = {} @edge_props = {} invalidate_caches end
@group Creating a graph Creates a new directed graph with the given vertices.
initialize
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/directed_graph.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/directed_graph.rb
MIT
def add_edge(from, to, props: nil) add_vertex(from) add_vertex(to) @to_graph[to] ||= Set.new @to_graph[to] << from if props @edge_props[[from, to]] = props end invalidate_caches end
@group Modifying the graph Adds an edge from the first vertex to the second vertex. @param from Vertex where the edge should start @param to Vertex where the edge should end @return [void]
add_edge
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/directed_graph.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/directed_graph.rb
MIT
def add_vertex(vertex) return if @vertices.key?(vertex) @vertices[vertex] = @next_vertex_idx.tap { @next_vertex_idx += 1 } end
Adds the given vertex to the graph. @param vertex The vertex to add to the graph @return [void]
add_vertex
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/directed_graph.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/directed_graph.rb
MIT
def delete_edges_to(to) return if @to_graph[to].nil? @to_graph[to].each do |from| @edge_props.delete([from, to]) end @to_graph.delete(to) invalidate_caches end
Deletes all edges going to the given vertex. @param to Vertex to which all edges should be removed @return [void]
delete_edges_to
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/directed_graph.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/directed_graph.rb
MIT
def direct_predecessors_of(to) @to_graph.fetch(to, Set.new) end
@group Querying the graph Returns the direct predecessors of the given vertex, i.e. the vertices x where there is an edge from x to the given vertex y. @param to The vertex of which the predecessors should be calculated @return [Array] Direct predecessors of the given vertex
direct_predecessors_of
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/directed_graph.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/directed_graph.rb
MIT
def predecessors_of(to) @predecessors[to] ||= recursively_find_vertices(to, :direct_predecessors_of) end
Returns the predecessors of the given vertex, i.e. the vertices x for which there is a path from x to the given vertex y. @param to The vertex of which the predecessors should be calculated @return [Array] Predecessors of the given vertex
predecessors_of
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/directed_graph.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/directed_graph.rb
MIT
def vertices @vertices.keys.sort_by { |v| @vertices[v] } end
@return [Array] The list of all vertices in this graph.
vertices
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/directed_graph.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/directed_graph.rb
MIT
def edges result = [] @vertices.each_pair do |v2, i2| direct_predecessors_of(v2).map { |v1| [@vertices[v1], v1] }.each do |i1, v1| result << [i1, i2, @edge_props[[v1, v2]]] end end result end
Returns an array of tuples representing the edges. The result of this method may take a while to compute and should be cached if possible. @return [Array] The list of all edges in this graph.
edges
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/directed_graph.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/directed_graph.rb
MIT
def invalidate_caches @predecessors = {} end
Invalidates cached data. This method should be called when the internal graph representation is changed.
invalidate_caches
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/directed_graph.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/directed_graph.rb
MIT
def recursively_find_vertices(start, method) all_vertices = Set.new processed_vertices = Set.new unprocessed_vertices = [start] until unprocessed_vertices.empty? # Get next unprocessed vertex vertex = unprocessed_vertices.pop next if processed_vertices.include?(vertex) processed_vertices << vertex # Add predecessors of this vertex send(method, vertex).each do |v| all_vertices << v unless all_vertices.include?(v) unprocessed_vertices << v end end all_vertices end
Recursively finds vertices, starting at the vertex start, using the given method, which should be a symbol to a method that takes a vertex and returns related vertices (e.g. predecessors, successors).
recursively_find_vertices
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/directed_graph.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/directed_graph.rb
MIT
def initialize(content, attributes, identifier, checksum_data: nil, content_checksum_data: nil, attributes_checksum_data: nil) @content = Nanoc::Core::Content.create(content) @attributes = Nanoc::Core::LazyValue.new(attributes).map(&:__nanoc_symbolize_keys_recursively) @identifier = Nanoc::Core::Identifier.from(identifier) @checksum_data = checksum_data @content_checksum_data = content_checksum_data @attributes_checksum_data = attributes_checksum_data # Precalculate for performance @hash = [self.class, identifier].hash reference end
@param [String, Nanoc::Core::Content] content @param [Hash, Proc] attributes @param [String, Nanoc::Core::Identifier] identifier @param [String, nil] checksum_data @param [String, nil] content_checksum_data @param [String, nil] attributes_checksum_data
initialize
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/document.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/document.rb
MIT
def reference raise NotImplementedError end
@abstract @return Unique reference to this object
reference
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/document.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/document.rb
MIT
def initialize_basic(config, objects = [], name = nil) @config = config @objects = Immutable::Vector.new(objects) @name = name end
contract C::Or[Hash, C::Named['Nanoc::Core::Configuration']], C::IterOf[C::RespondTo[:identifier]], C::Maybe[String] => C::Any
initialize_basic
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/identifiable_collection.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/identifiable_collection.rb
MIT
def reject(&) self.class.new(@config, @objects.reject(&)) end
contract C::Func[C::RespondTo[:identifier] => C::Any] => self
reject
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/identifiable_collection.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/identifiable_collection.rb
MIT
def each @context.dependency_tracker.bounce(_unwrap, raw_content: true) @objects.each { |i| yield view_class.new(i, @context) } self end
Calls the given block once for each object, passing that object as a parameter. @yieldparam [#identifier] object @yieldreturn [void] @return [self]
each
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/identifiable_collection_view.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/identifiable_collection_view.rb
MIT
def find_all(arg = NOTHING, &) if NOTHING.equal?(arg) @context.dependency_tracker.bounce(_unwrap, raw_content: true) return @objects.map { |i| view_class.new(i, @context) }.select(&) end prop_attribute = case arg when String, Nanoc::Core::Identifier [arg.to_s] when Regexp [arg] else true end @context.dependency_tracker.bounce(_unwrap, raw_content: prop_attribute) @objects.find_all(arg).map { |i| view_class.new(i, @context) } end
Finds all objects whose identifier matches the given argument. @param [String, Regex] arg @return [Enumerable]
find_all
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/identifiable_collection_view.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/identifiable_collection_view.rb
MIT
def where(**hash) unless Nanoc::Core::Feature.enabled?(Nanoc::Core::Feature::WHERE) raise( Nanoc::Core::TrivialError, '#where is experimental, and not yet available unless the corresponding feature flag is turned on. Set the `NANOC_FEATURES` environment variable to `where` to enable its usage. (Alternatively, set the environment variable to `all` to turn on all feature flags.)', ) end @context.dependency_tracker.bounce(_unwrap, attributes: hash) # IDEA: Nanoc could remember (from the previous compilation) how many # times #where is called with a given attribute key, and memoize the # key-to-identifiers list. found_objects = @objects.select do |i| hash.all? { |k, v| i.attributes[k] == v } end found_objects.map { |i| view_class.new(i, @context) } end
Finds all objects that have the given attribute key/value pair. @example @items.where(kind: 'article') @items.where(kind: 'article', year: 2020) @return [Enumerable]
where
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/identifiable_collection_view.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/identifiable_collection_view.rb
MIT
def full? @type == :full end
Whether or not this is a full identifier (i.e.includes the extension).
full?
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/identifier.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/identifier.rb
MIT
def legacy? @type == :legacy end
Whether or not this is a legacy identifier (i.e. does not include the extension).
legacy?
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/identifier.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/identifier.rb
MIT
def without_ext unless full? raise UnsupportedLegacyOperationError end extname = File.extname(@string) if extname.empty? @string else @string[0..-extname.size - 1] end end
The identifier, as string, with the last extension removed
without_ext
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/identifier.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/identifier.rb
MIT
def without_exts extname = exts.join('.') if extname.empty? @string else @string[0..-extname.size - 2] end end
The identifier, as string, with all extensions removed
without_exts
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/identifier.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/identifier.rb
MIT
def exts unless full? raise UnsupportedLegacyOperationError end s = File.basename(@string) s ? s.split('.', -1).drop(1) : [] end
The list of extensions, without a leading dot
exts
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/identifier.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/identifier.rb
MIT
def initialize(value_or_proc) @value = { raw: value_or_proc } end
Takes a value or a proc to generate the value
initialize
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/lazy_value.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/lazy_value.rb
MIT
def value if @value.key?(:raw) value = @value.delete(:raw) @value[:final] = value.respond_to?(:call) ? value.call : value @value.__nanoc_freeze_recursively if frozen? end @value[:final] end
Returns the value, generated when needed
value
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/lazy_value.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/lazy_value.rb
MIT
def map self.class.new(-> { yield(value) }) end
Returns a new lazy value that will apply the given transformation when the value is requested.
map
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/lazy_value.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/lazy_value.rb
MIT
def update_attributes(hash) hash.each { |k, v| _unwrap.set_attribute(k, v) } self end
Updates the attributes based on the given hash. @param [Hash] hash @return [self]
update_attributes
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/mutable_document_view_mixin.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/mutable_document_view_mixin.rb
MIT
def delete_if(&) @objects = @objects.reject { |o| yield(view_class.new(o, @context)) } self end
Deletes every object for which the block evaluates to true. @yieldparam [#identifier] object @yieldreturn [Boolean] @return [self]
delete_if
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/mutable_identifiable_collection_view.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/mutable_identifiable_collection_view.rb
MIT
def initialize(message, props = Nanoc::Core::DependencyProps.new) # TODO: Replace `DependencyProps` with its own `OutdatednessProps` # type. For `OutdatednessProps`, the only values are true/false; # giving a collection for `raw_content` makes no sense (anymore). @message = message @props = props end
@param [String] message The descriptive message for this outdatedness reason
initialize
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/outdatedness_reasons.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/outdatedness_reasons.rb
MIT
def initialize(filename, version) @filename = filename @version = version end
Creates a new store for the given filename. @param [String] filename The name of the file where data will be loaded from and stored to. @param [Numeric] version The version number corresponding to the file format the data is in. When the file format changes, the version number should be incremented.
initialize
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/store.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/store.rb
MIT
def data raise NotImplementedError.new('Nanoc::Core::Store subclasses must implement #data and #data=') end
@group Loading and storing data @return The data that should be written to the disk @abstract This method must be implemented by the subclass.
data
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/store.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/store.rb
MIT
def load Nanoc::Core::Instrumentor.call(:store_loaded, self.class) do load_uninstrumented end end
Loads the data from the filesystem into memory. This method will set the loaded data using the {#data=} method. @return [void]
load
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/store.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/store.rb
MIT
def create(prefix) count = nil @mutex.synchronize do count = @counts.fetch(prefix, 0) @counts[prefix] = count + 1 end dirname = File.join(@root_dir, prefix) filename = File.join(@root_dir, prefix, count.to_s) FileUtils.mkdir_p(dirname) filename end
@param [String] prefix A string prefix to include in the temporary filename, often the type of filename being provided. @return [String] A new unused filename
create
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/temp_filename_factory.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/temp_filename_factory.rb
MIT
def cleanup(prefix) path = File.join(@root_dir, prefix) FileUtils.rm_rf(path) @counts.delete(prefix) if @counts.empty? && File.directory?(@root_dir) FileUtils.rm_rf(@root_dir) end end
@param [String] prefix A string prefix that indicates which temporary filenames should be deleted. @return [void]
cleanup
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/temp_filename_factory.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/temp_filename_factory.rb
MIT
def full_cache_available?(rep) cache = self[rep] cache ? cache.none? { |_snapshot_name, content| content.binary? } : false end
True if there is cached compiled content available for this item, and all entries are textual.
full_cache_available?
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/textual_compiled_content_cache.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/textual_compiled_content_cache.rb
MIT
def __nanoc_symbolize_keys_recursively map do |element| if element.respond_to?(:__nanoc_symbolize_keys_recursively) element.__nanoc_symbolize_keys_recursively else element end end end
Returns a new array where all items' keys are recursively converted to symbols by calling {Nanoc::ArrayExtensions#__nanoc_symbolize_keys_recursively} or {Nanoc::HashExtensions#__nanoc_symbolize_keys_recursively}. @return [Array] The converted array
__nanoc_symbolize_keys_recursively
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/core_ext/array.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/core_ext/array.rb
MIT
def __nanoc_freeze_recursively return if frozen? freeze each do |value| if value.respond_to?(:__nanoc_freeze_recursively) value.__nanoc_freeze_recursively else value.freeze end end end
Freezes the contents of the array, as well as all array elements. The array elements will be frozen using {#__nanoc_freeze_recursively} if they respond to that message, or #freeze if they do not. @see Hash#__nanoc_freeze_recursively @return [void]
__nanoc_freeze_recursively
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/core_ext/array.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/core_ext/array.rb
MIT
def __nanoc_symbolize_keys_recursively hash = {} each_pair do |key, value| new_key = key.respond_to?(:to_sym) ? key.to_sym : key new_value = value.respond_to?(:__nanoc_symbolize_keys_recursively) ? value.__nanoc_symbolize_keys_recursively : value hash[new_key] = new_value end hash end
Returns a new hash where all keys are recursively converted to symbols by calling {Nanoc::ArrayExtensions#__nanoc_symbolize_keys_recursively} or {Nanoc::HashExtensions#__nanoc_symbolize_keys_recursively}. @return [Hash] The converted hash
__nanoc_symbolize_keys_recursively
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/core_ext/hash.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/core_ext/hash.rb
MIT
def __nanoc_freeze_recursively return if frozen? freeze each_pair do |_key, value| if value.respond_to?(:__nanoc_freeze_recursively) value.__nanoc_freeze_recursively else value.freeze end end end
Freezes the contents of the hash, as well as all hash values. The hash values will be frozen using {#__nanoc_freeze_recursively} if they respond to that message, or #freeze if they do not. @see Array#__nanoc_freeze_recursively @return [void]
__nanoc_freeze_recursively
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/core_ext/hash.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/core_ext/hash.rb
MIT
def __nanoc_cleaned_identifier "/#{self}/".gsub(/^\/+|\/+$/, '/') end
Transforms string into an actual identifier @return [String] The identifier generated from the receiver
__nanoc_cleaned_identifier
ruby
nanoc/nanoc
nanoc-core/lib/nanoc/core/core_ext/string.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-core/lib/nanoc/core/core_ext/string.rb
MIT
def run(content, params = {}) # Read syntax syntax = params[:syntax] syntax ||= Util.syntax_from_ext(item.identifier.ext) result = Sass.compile_string( content, importer: NanocImporter.new(@items, item), **params, syntax:, ) result.css end
Runs the content through [Dart Sass](https://sass-lang.com/dart-sass). Parameters passed as `:args` will be passed on to Dart Sass. @param [String] content The content to filter @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc-dart-sass/lib/nanoc/dart_sass/filter.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-dart-sass/lib/nanoc/dart_sass/filter.rb
MIT
def initialize(source_path, config, dry_run: false) @source_path = source_path @config = config @dry_run = dry_run end
@param [String] source_path The path to the directory that contains the files to upload. It should not have a trailing slash. @return [Hash] config The deployer configuration @param [Boolean] dry_run true if the deployer should only show what would be deployed instead actually deploying
initialize
ruby
nanoc/nanoc
nanoc-deploying/lib/nanoc/deploying/deployer.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-deploying/lib/nanoc/deploying/deployer.rb
MIT
def initialize(mod) @mod = mod @erbout = +'' @action_sequence = {} @config = Nanoc::Core::Configuration.new(dir: Dir.getwd).with_defaults @reps = Nanoc::Core::ItemRepRepo.new @items = Nanoc::Core::ItemCollection.new(@config) @layouts = Nanoc::Core::LayoutCollection.new(@config) @compiled_content_store = Nanoc::Core::CompiledContentStore.new @action_provider = new_action_provider end
@param [Module] mod The helper module to create a context for
initialize
ruby
nanoc/nanoc
nanoc-spec/lib/nanoc/spec.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-spec/lib/nanoc/spec.rb
MIT
def run(content, params = {}) # Get options options = params.fetch(:args, {}) # Create context context = ::Nanoc::Core::Context.new(assigns) # Get result proc = assigns[:content] ? -> { assigns[:content] } : nil # Find Tilt template class ext = item.identifier.ext || item[:extension] template_class = ::Tilt[ext] # Render template = template_class.new(options) { content } template.render(context, assigns, &proc) end
Runs the content through [Tilt](https://github.com/rtomayko/tilt). Parameters passed as `:args` will be passed on to Tilt. @param [String] content The content to filter @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc-tilt/lib/nanoc/tilt/filter.rb
https://github.com/nanoc/nanoc/blob/master/nanoc-tilt/lib/nanoc/tilt/filter.rb
MIT
def instrument(method_name, opts) data = opts[:data] topic = opts.fetch(:topic, "#{method_name}.cequel") data_proc = if data.respond_to? :call data else ->(_) { data } end define_method(:"__data_for_#{method_name}_instrumentation", &data_proc) mod = Module.new mod.module_eval <<-METH def #{method_name}(*args) instrument("#{topic}", __data_for_#{method_name}_instrumentation(self)) do super(*args) end end METH prepend mod end
Instruments `method_name` to publish the value returned by the `data_builder` proc onto `topic` Example: extend Instrumentation instrument :create, data: {topic: "create.cequel", table_name: table_name} @param method_name [Symbol,String] The method to instrument @param opts [String] :topic ("#{method_name}.cequel") The name with which to publish this instrumentation @option opts [Object] :data_method (nil) the data to publish along with the notification. If it responds to `#call` it will be called with the record object and the return value used for each notification.
instrument
ruby
cequel/cequel
lib/cequel/instrumentation.rb
https://github.com/cequel/cequel/blob/master/lib/cequel/instrumentation.rb
MIT
def establish_connection(configuration) self.connection = Cequel.connect(configuration) end
Establish a connection with the given configuration @param (see Cequel.connect) @option (see Cequel.connect) @return [void]
establish_connection
ruby
cequel/cequel
lib/cequel/record.rb
https://github.com/cequel/cequel/blob/master/lib/cequel/record.rb
MIT
def descendants weak_descendants.map do |clazz| begin clazz.__getobj__ if clazz.weakref_alive? rescue WeakRef::RefError nil end end.compact end
@return [Array<Class>] All the record classes that are currently defined.
descendants
ruby
cequel/cequel
lib/cequel/record.rb
https://github.com/cequel/cequel/blob/master/lib/cequel/record.rb
MIT
def included(base) weak_descendants << WeakRef.new(base) end
Hook called when new record classes are created.
included
ruby
cequel/cequel
lib/cequel/record.rb
https://github.com/cequel/cequel/blob/master/lib/cequel/record.rb
MIT
def uuid(value = nil) if value.nil? timeuuid_generator.now elsif value.is_a?(Time) timeuuid_generator.at(value) elsif value.is_a?(DateTime) timeuuid_generator.at(Time.at(value.to_f)) else Type::Timeuuid.instance.cast(value) end end
Create a UUID @param value [Time,String,Integer] timestamp to assign to the UUID, or numeric or string representation of the UUID @return a UUID appropriate for use with Cequel
uuid
ruby
cequel/cequel
lib/cequel/uuids.rb
https://github.com/cequel/cequel/blob/master/lib/cequel/uuids.rb
MIT