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 grant_client_node_permissions(action_handler, chef_server, machine, perms, private_key) node_name = machine.name api = Cheffish.chef_server_api(chef_server) node_perms = api.get("/nodes/#{node_name}/_acl") begin perms.each do |p| if !node_perms[p]['actors'].include?(node_name) action_handler.perform_action "Add #{node_name} to client #{p} ACLs" do node_perms[p]['actors'] << node_name api.put("/nodes/#{node_name}/_acl/#{p}", p => node_perms[p]) end end end rescue Net::HTTPServerException => e if e.response.code == "400" action_handler.perform_action "Delete #{node_name} and recreate as client #{node_name}" do api.delete("/nodes/#{node_name}") as_user = chef_server.dup as_user[:options] = as_user[:options].merge( client_name: node_name, signing_key_filename: nil, raw_key: private_key.to_pem ) as_user_api = Cheffish.chef_server_api(as_user) as_user_api.post("/nodes", machine.node) end else raise end end end
Grant the client permissions to the node This procedure assumes that the client name and node name are the same
grant_client_node_permissions
ruby
chef-boneyard/chef-provisioning
lib/chef/provisioning/convergence_strategy/precreate_chef_objects.rb
https://github.com/chef-boneyard/chef-provisioning/blob/master/lib/chef/provisioning/convergence_strategy/precreate_chef_objects.rb
Apache-2.0
def file_exists?(path) result = transport.execute("ls -d #{path}", :read_only => true) result.exitstatus == 0 && result.stdout != '' end
Return true or false depending on whether file exists
file_exists?
ruby
chef-boneyard/chef-provisioning
lib/chef/provisioning/machine/unix_machine.rb
https://github.com/chef-boneyard/chef-provisioning/blob/master/lib/chef/provisioning/machine/unix_machine.rb
Apache-2.0
def set_attributes(action_handler, path, attributes) if attributes[:mode] || attributes[:owner] || attributes[:group] current_attributes = get_attributes(path) if attributes[:mode] && current_attributes[:mode].to_i != attributes[:mode].to_i action_handler.perform_action "change mode of #{path} on #{machine_spec.name} from #{current_attributes[:mode].to_i} to #{attributes[:mode].to_i}" do transport.execute("chmod #{attributes[:mode].to_i} #{path}").error! end end if attributes[:owner] && current_attributes[:owner] != attributes[:owner] action_handler.perform_action "change owner of #{path} on #{machine_spec.name} from #{current_attributes[:owner]} to #{attributes[:owner]}" do transport.execute("chown #{attributes[:owner]} #{path}").error! end end if attributes[:group] && current_attributes[:group] != attributes[:group] action_handler.perform_action "change group of #{path} on #{machine_spec.name} from #{current_attributes[:group]} to #{attributes[:group]}" do transport.execute("chgrp #{attributes[:group]} #{path}").error! end end end end
Set file attributes { mode, :owner, :group }
set_attributes
ruby
chef-boneyard/chef-provisioning
lib/chef/provisioning/machine/unix_machine.rb
https://github.com/chef-boneyard/chef-provisioning/blob/master/lib/chef/provisioning/machine/unix_machine.rb
Apache-2.0
def get_attributes(path) os = transport.execute('uname -s') result = if os.stdout =~ /darwin/i # macOS transport.execute("stat -f '%Lp %Su %Sg %N' #{path}", read_only: true) else transport.execute("stat -c '%a %U %G %n' #{path}", read_only: true) end return nil if result.exitstatus != 0 file_info = result.stdout.split(/\s+/) raise "#{path} does not exist in set_attributes()" if file_info.size <= 1 { mode: file_info[0], owner: file_info[1], group: file_info[2] } end
Get file attributes { :mode, :owner, :group }
get_attributes
ruby
chef-boneyard/chef-provisioning
lib/chef/provisioning/machine/unix_machine.rb
https://github.com/chef-boneyard/chef-provisioning/blob/master/lib/chef/provisioning/machine/unix_machine.rb
Apache-2.0
def file_exists?(path) parse_boolean(transport.execute("Test-Path #{escape(path)}", :read_only => true).stdout) end
Return true or false depending on whether file exists
file_exists?
ruby
chef-boneyard/chef-provisioning
lib/chef/provisioning/machine/windows_machine.rb
https://github.com/chef-boneyard/chef-provisioning/blob/master/lib/chef/provisioning/machine/windows_machine.rb
Apache-2.0
def read_file(path) Chef::Log.debug("Reading file #{path} from #{username}@#{host}") result = StringIO.new download(path, result) result.string end
TODO why does #read_file download it to the target host?
read_file
ruby
chef-boneyard/chef-provisioning
lib/chef/provisioning/transport/ssh.rb
https://github.com/chef-boneyard/chef-provisioning/blob/master/lib/chef/provisioning/transport/ssh.rb
Apache-2.0
def forward_port(local_port, local_host, remote_port, remote_host) # This bit is from the documentation. if session.forward.respond_to?(:active_remote_destinations) # active_remote_destinations tells us exactly what remotes the current # ssh session is *actually* tracking. If multiple people share this # session and set up their own remotes, this will prevent us from # overwriting them. actual_remote_port, actual_remote_host = session.forward.active_remote_destinations[[local_port, local_host]] if !actual_remote_port Chef::Log.info("Forwarding local server #{local_host}:#{local_port} to #{username}@#{self.host}") session.forward.remote(local_port, local_host, remote_port, remote_host) do |new_remote_port, new_remote_host| actual_remote_host = new_remote_host actual_remote_port = new_remote_port || :error :no_exception # I'll take care of it myself, thanks end # Kick SSH until we get a response session.loop { !actual_remote_port } if actual_remote_port == :error return nil end end [ actual_remote_port, actual_remote_host ] else # If active_remote_destinations isn't on net-ssh, we stash our own list # of ports *we* have forwarded on the connection, and hope that we are # right. # TODO let's remove this when net-ssh 2.9.2 is old enough, and # bump the required net-ssh version. @forwarded_ports ||= {} remote_port, remote_host = @forwarded_ports[[local_port, local_host]] if !remote_port Chef::Log.debug("Forwarding local server #{local_host}:#{local_port} to #{username}@#{self.host}") old_active_remotes = session.forward.active_remotes session.forward.remote(local_port, local_host, local_port) session.loop { !(session.forward.active_remotes.length > old_active_remotes.length) } remote_port, remote_host = (session.forward.active_remotes - old_active_remotes).first @forwarded_ports[[local_port, local_host]] = [ remote_port, remote_host ] end [ remote_port, remote_host ] end end
Forwards a port over the connection, and returns the
forward_port
ruby
chef-boneyard/chef-provisioning
lib/chef/provisioning/transport/ssh.rb
https://github.com/chef-boneyard/chef-provisioning/blob/master/lib/chef/provisioning/transport/ssh.rb
Apache-2.0
def initialize(endpoint, type, options, global_config) @options = options @options[:endpoint] = endpoint @options[:transport] = type # WinRM v2 switched from :pass to :password # we accept either to avoid having to update every driver @options[:password] = @options[:password] || @options[:pass] @config = global_config end
Create a new WinRM transport. == Arguments - endpoint: the WinRM endpoint, e.g. http://145.14.51.45:5985/wsman. - type: the connection type, e.g. :plaintext. - options: options hash, including both WinRM options and transport options. For transport options, see the Transport.options definition. WinRM options include :user, :pass, :disable_sspi => true, among others. - global_config: an options hash that looks suspiciously similar to Chef::Config, containing at least the key :log_level. The actual connection is made as ::WinRM::WinRMWebService.new(endpoint, type, options)
initialize
ruby
chef-boneyard/chef-provisioning
lib/chef/provisioning/transport/winrm.rb
https://github.com/chef-boneyard/chef-provisioning/blob/master/lib/chef/provisioning/transport/winrm.rb
Apache-2.0
def hydrate(chef_server = Cheffish.default_chef_server) chef_api = Cheffish.chef_server_api(chef_server) begin data = chef_api.get("/data/#{self.class.databag_name}/#{name}") load_from_hash(data) Chef::Log.debug("Rehydrating resource from #{self.class.databag_name}/#{name}: #{data}") rescue Net::HTTPServerException => e if e.response.code == '404' nil else raise end end end
Load persisted data from the server's databag. If the databag does not exist on the server, returns nil. @param chef_server [Hash] A hash representing which Chef server to talk to @option chef_server [String] :chef_server_url URL to the Chef server @option chef_server [Hash] :options Options for when talking to the Chef server @option options [String] :client_name The node name making the call @option options [String] :signing_key_filename Path to the signing key @return [Object] an instance of this class re-hydrated from the data hash stored in the databag.
hydrate
ruby
chef-boneyard/chef-provisioning
lib/chef/resource/chef_data_bag_resource.rb
https://github.com/chef-boneyard/chef-provisioning/blob/master/lib/chef/resource/chef_data_bag_resource.rb
Apache-2.0
def load_from_hash hash hash.each do |k,v| self.instance_variable_set("@#{k}", v) end self end
Load instance variable data from a hash. For each key,value pair, set @<key> to value @param hash [Hash] Hash containing the instance variable data @return [Object] self after having been populated with data.
load_from_hash
ruby
chef-boneyard/chef-provisioning
lib/chef/resource/chef_data_bag_resource.rb
https://github.com/chef-boneyard/chef-provisioning/blob/master/lib/chef/resource/chef_data_bag_resource.rb
Apache-2.0
def storage_hash ignored = [] hash = {} (self.class.stored_attributes - ignored).each do |attr_name| varname = "@#{attr_name.to_s.gsub('@', '')}" key = varname.gsub('@', '') hash[key] = self.instance_variable_get varname end hash end
Convert the values in {stored_attributes} to a hash for storing in a databag @return [Hash] a hash of (k,v) pairs where k is each record in {stored_attributes}
storage_hash
ruby
chef-boneyard/chef-provisioning
lib/chef/resource/chef_data_bag_resource.rb
https://github.com/chef-boneyard/chef-provisioning/blob/master/lib/chef/resource/chef_data_bag_resource.rb
Apache-2.0
def save create_databag_if_needed self.class.databag_name # Clone for inline_resource _databag_name = self.class.databag_name _hash = self.storage_hash _name = self.name Cheffish.inline_resource(self, @action) do chef_data_bag_item _name do data_bag _databag_name raw_data _hash action :create end end end
Save this entity to the server. If you have significant information that could be lost, you should do this as quickly as possible. @return [Void]
save
ruby
chef-boneyard/chef-provisioning
lib/chef/resource/chef_data_bag_resource.rb
https://github.com/chef-boneyard/chef-provisioning/blob/master/lib/chef/resource/chef_data_bag_resource.rb
Apache-2.0
def delete # Clone for inline_resource _name = self.name _databag_name = self.class.databag_name Cheffish.inline_resource(self, @action) do chef_data_bag_item _name do data_bag _databag_name action :delete end end end
Delete this entity from the server @return [Void]
delete
ruby
chef-boneyard/chef-provisioning
lib/chef/resource/chef_data_bag_resource.rb
https://github.com/chef-boneyard/chef-provisioning/blob/master/lib/chef/resource/chef_data_bag_resource.rb
Apache-2.0
def create_databag_if_needed databag_name _databag_name = databag_name Cheffish.inline_resource(self, @action) do chef_data_bag _databag_name do action :create end end end
Create the databag with Cheffish if required @return [Void]
create_databag_if_needed
ruby
chef-boneyard/chef-provisioning
lib/chef/resource/chef_data_bag_resource.rb
https://github.com/chef-boneyard/chef-provisioning/blob/master/lib/chef/resource/chef_data_bag_resource.rb
Apache-2.0
def load_prior_resource(*args) Chef::Log.debug "Overloading #{self.resource_name} load_prior_resource with NOOP" end
This is here because metal users will probably want to do things like: machine "foo" action :destroy end with_load_balancer_options :bootstrap_options => {...} machine "foo" converge true end Without this, the first resource's machine options will obliterate the second resource's machine options, and then unexpected (and undesired) things happen.
load_prior_resource
ruby
chef-boneyard/chef-provisioning
lib/chef/resource/load_balancer.rb
https://github.com/chef-boneyard/chef-provisioning/blob/master/lib/chef/resource/load_balancer.rb
Apache-2.0
def file(remote_path, local = nil) @files ||= {} if remote_path.is_a?(Hash) if local raise "file(Hash, something) does not make sense. Either pass a hash, or pass a pair, please." end remote_path.each_pair do |remote, local| @files[remote] = local end elsif remote_path.is_a?(String) if !local raise "Must pass both a remote path and a local path to file directive" end @files[remote_path] = local else raise "file remote_path must be a String, but is a #{remote_path.class}" end end
A single file to upload, in the format REMOTE_PATH, LOCAL_PATH|HASH. This directive may be passed multiple times, and multiple files will be uploaded. == Examples file '/remote/path.txt', '/local/path.txt' file '/remote/path.txt', { :local_path => '/local/path.txt' } file '/remote/path.txt', { :content => 'woo' }
file
ruby
chef-boneyard/chef-provisioning
lib/chef/resource/machine.rb
https://github.com/chef-boneyard/chef-provisioning/blob/master/lib/chef/resource/machine.rb
Apache-2.0
def load_prior_resource(*args) Chef::Log.debug "Overloading #{self.resource_name} load_prior_resource with NOOP" end
This is here because provisioning users will probably want to do things like: machine "foo" action :destroy end @example with_machine_options :bootstrap_options => { ... } machine "foo" converge true end Without this, the first resource's machine options will obliterate the second resource's machine options, and then unexpected (and undesired) things happen.
load_prior_resource
ruby
chef-boneyard/chef-provisioning
lib/chef/resource/machine.rb
https://github.com/chef-boneyard/chef-provisioning/blob/master/lib/chef/resource/machine.rb
Apache-2.0
def to_text ivars = instance_variables.map { |ivar| ivar.to_sym } - HIDDEN_IVARS - [ :@from_recipe, :@machines ] text = "# Declared in #{@source_line}\n\n" text << self.class.resource_name.to_s + "(\"#{name}\") do\n" ivars.each do |ivar| if (value = instance_variable_get(ivar)) && !(value.respond_to?(:empty?) && value.empty?) value_string = value.respond_to?(:to_text) ? value.to_text : value.inspect text << " #{ivar.to_s.sub(/^@/,'')} #{value_string}\n" end end machine_names = @machines.map do |m| if m.is_a?(Chef::Provisioning::ManagedEntry) m.name elsif m.is_a?(Chef::Resource::Machine) m.name else m end end text << " machines #{machine_names.inspect}\n" [@not_if, @only_if].flatten.each do |conditional| text << " #{conditional.to_text}\n" end text << "end\n" end
We override this because we want to hide @from_recipe and shorten @machines in error output.
to_text
ruby
chef-boneyard/chef-provisioning
lib/chef/resource/machine_batch.rb
https://github.com/chef-boneyard/chef-provisioning/blob/master/lib/chef/resource/machine_batch.rb
Apache-2.0
def set_properties(hash) hash.each do |key, value| add_or_remove_ostruct_member(key, value) end rest_reset_properties end
Set many properties at once and only issue one http request and update the node/relationship instance on the fly. To remove a property, set its value to nil.
set_properties
ruby
maxdemarzi/neography
lib/neography/property.rb
https://github.com/maxdemarzi/neography/blob/master/lib/neography/property.rb
MIT
def reset_properties(hash) @table.keys.each{|key| remove_ostruct_member(key)} hash.each{|key,value| new_ostruct_member(key,value)} rest_reset_properties end
As #set_properties, but this one hard resets the node's/relationship's properties to exactly what's given in the hash.
reset_properties
ruby
maxdemarzi/neography
lib/neography/property.rb
https://github.com/maxdemarzi/neography/blob/master/lib/neography/property.rb
MIT
def remove_node_from_index(index, id_or_key, id_or_value = nil, id = nil) if id remove_node_index_by_value(index, id, id_or_key, id_or_value) elsif id_or_value remove_node_index_by_key(index, id_or_value, id_or_key) else remove_node_index_by_id(index, id_or_key) end end
Mimick original neography API in Rest class.
remove_node_from_index
ruby
maxdemarzi/neography
lib/neography/rest/node_indexes.rb
https://github.com/maxdemarzi/neography/blob/master/lib/neography/rest/node_indexes.rb
MIT
def remove_relationship_from_index(index, id_or_key, id_or_value = nil, id = nil) if id remove_relationship_index_by_value(index, id, id_or_key, id_or_value) elsif id_or_value remove_relationship_index_by_key(index, id_or_value, id_or_key) else remove_relationship_index_by_id(index, id_or_key) end end
Mimick original neography API in Rest class.
remove_relationship_from_index
ruby
maxdemarzi/neography
lib/neography/rest/relationship_indexes.rb
https://github.com/maxdemarzi/neography/blob/master/lib/neography/rest/relationship_indexes.rb
MIT
def generate_text(length=8) chars = 'abcdefghjkmnpqrstuvwxyz' key = '' length.times { |i| key << chars[rand(chars.length)] } key end
If you want to see more, uncomment the next few lines require 'net-http-spy' Net::HTTP.http_logger_options = {:body => true} # just the body Net::HTTP.http_logger_options = {:verbose => true} # see everything
generate_text
ruby
maxdemarzi/neography
spec/spec_helper.rb
https://github.com/maxdemarzi/neography/blob/master/spec/spec_helper.rb
MIT
def encrypt(folder, key) Dir.each_child(folder) do | child | unless File.extname(child) != ".enc" next end cipher = OpenSSL::Cipher::AES256.new :CBC cipher.encrypt cipher.key = Digest::SHA256.digest key file = File.absolute_path(child, folder) content = File.open(file, "rb").read encrypted_content = cipher.update(content) + cipher.final output_file = File.absolute_path(child + ".enc", folder) File.open(output_file, "w").write(encrypted_content) end end
Encrypts all files of a folder @param folder Folder of the certificate and provisioning profile @param key Encryption key for the certificate and provisioning profile
encrypt
ruby
messeb/ios-project-template
fastlane/libs/encryption.rb
https://github.com/messeb/ios-project-template/blob/master/fastlane/libs/encryption.rb
MIT
def decrypt(folder, key) Dir.each_child(folder) do | child | unless File.extname(child) == ".enc" next end puts child decipher = OpenSSL::Cipher::AES256.new :CBC decipher.decrypt decipher.key = Digest::SHA256.digest key file = File.absolute_path(child, folder) content = File.open(file, "rb").read decrypted_content = decipher.update(content) + decipher.final output_file_path = File.absolute_path(File.basename(child, ".enc"), folder) output_file = File.open(output_file_path, "w") output_file.sync = true output_file.write(decrypted_content) end end
Decrypts all files of a folder @param folder Folder of the certificate and provisioning profile @param key Decryption key for the certificate and provisioning profile
decrypt
ruby
messeb/ios-project-template
fastlane/libs/encryption.rb
https://github.com/messeb/ios-project-template/blob/master/fastlane/libs/encryption.rb
MIT
def create_signing_configuration(folder, key) decrypt(folder, key) keychain_name = 'ios_build.keychain' keychain_password = key # only for temporary use create_keychain({ name: keychain_name, password: keychain_password, }) unlock_keychain({ path: FastlaneCore::Helper.keychain_path(keychain_name), add_to_search_list: true, set_default: true, password: keychain_password }) import_certificates_in_keychain( folder, FastlaneCore::Helper.keychain_path(keychain_name), keychain_password ) copy_mobile_provisioning_profiles(folder) end
Creates the signing configuration for the build. @param folder Folder of the certificate and provisioning profile @param key Decryption key for the certificate and provisioning profile
create_signing_configuration
ruby
messeb/ios-project-template
fastlane/libs/signing.rb
https://github.com/messeb/ios-project-template/blob/master/fastlane/libs/signing.rb
MIT
def import_certificates_in_keychain(folder, keychain_path, keychain_password) supported_extensions = [".p12", ".cer"] Find.find(folder) do |file| next if !supported_extensions.include?(File.extname(file)) puts "import: " + file FastlaneCore::KeychainImporter.import_file( file, keychain_path, keychain_password: keychain_password, output: FastlaneCore::Globals.verbose?) end end
Imports certificates from a folder to the keychain @param folder Folder of the certificate and provisioning profile @param keychain_path Path for the temporary keychain @param keychain_password Password for the temporary keychain
import_certificates_in_keychain
ruby
messeb/ios-project-template
fastlane/libs/signing.rb
https://github.com/messeb/ios-project-template/blob/master/fastlane/libs/signing.rb
MIT
def copy_mobile_provisioning_profiles(folder) supported_extensions = [".mobileprovision"] Find.find(folder) do |file| next if !supported_extensions.include?(File.extname(file)) basename = File.basename(file) FileUtils.mkdir_p("#{Dir.home}/Library/MobileDevice/Provisioning\ Profiles/") FileUtils.cp(file, "#{Dir.home}/Library/MobileDevice/Provisioning\ Profiles/#{basename}") end end
Copies mobile provisioning profiles from a folder to the Provisioning Profiles folder @param folder Folder of the certificate and provisioning profile
copy_mobile_provisioning_profiles
ruby
messeb/ios-project-template
fastlane/libs/signing.rb
https://github.com/messeb/ios-project-template/blob/master/fastlane/libs/signing.rb
MIT
def delete_certificates(folder) supported_extensions = [".p12", ".cer"] Find.find(folder) do |file| next if !supported_extensions.include?(File.extname(file)) FileUtils.rm(file) end end
Deletes encrypted certificates for a configuration @param configuration Configuration for the build
delete_certificates
ruby
messeb/ios-project-template
fastlane/libs/signing.rb
https://github.com/messeb/ios-project-template/blob/master/fastlane/libs/signing.rb
MIT
def delete_mobile_provisioning_profiles(folder) supported_extensions = [".mobileprovision"] Find.find(folder) do |file| next if !supported_extensions.include?(File.extname(file)) FileUtils.rm(file) end end
Deletes encrypted mobile provisioning profiles @param configuration Configuration for the build
delete_mobile_provisioning_profiles
ruby
messeb/ios-project-template
fastlane/libs/signing.rb
https://github.com/messeb/ios-project-template/blob/master/fastlane/libs/signing.rb
MIT
def clear_signing_configuration(folder) delete_certificates(folder) delete_mobile_provisioning_profiles(folder) remove_keychain end
Clears the signing configuration and deletes the certificates, profiles and keychains @param configuration Configuration for the build
clear_signing_configuration
ruby
messeb/ios-project-template
fastlane/libs/signing.rb
https://github.com/messeb/ios-project-template/blob/master/fastlane/libs/signing.rb
MIT
def errors return @errors if defined?(@errors) return @errors = super if @error child_errors = get_errors_by_index(children) return @errors = super if child_errors.empty? @errors ||= if @index_errors child_errors.map do |(error, i)| name = attach_child_name(:"#{@filter.name}[#{i}]", error) Filter::Error.new(error.filter, error.type, name: name) end.freeze else error, = child_errors.first [Filter::Error.new(@filter, error.type)].freeze end end
Any errors that occurred during processing. @return [Filter::Error]
errors
ruby
AaronLasseigne/active_interaction
lib/active_interaction/array_input.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/array_input.rb
MIT
def desc(desc = nil) if desc.nil? @_interaction_desc = nil unless instance_variable_defined?(:@_interaction_desc) else @_interaction_desc = desc end @_interaction_desc end
@!method run(inputs = {}) @note If the interaction inputs are valid and there are no runtime errors and execution completed successfully, {#valid?} will always return true. Runs validations and if there are no errors it will call {#execute}. @param input [Hash, ActionController::Parameters] @return [Base] @!method run!(inputs = {}) Like {.run} except that it returns the value of {#execute} or raises an exception if there were any validation errors. @param (see ActiveInteraction::Base.run) @return (see ActiveInteraction::Runnable::ClassMethods#run!) @raise (see ActiveInteraction::Runnable::ClassMethods#run!) Get or set the description. @example core.desc # => nil core.desc('Description!') core.desc # => "Description!" @param desc [String, nil] What to set the description to. @return [String, nil] The description.
desc
ruby
AaronLasseigne/active_interaction
lib/active_interaction/base.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/base.rb
MIT
def filters # rubocop:disable Naming/MemoizedInstanceVariableName @_interaction_filters ||= {} # rubocop:enable Naming/MemoizedInstanceVariableName end
Get all the filters defined on this interaction. @return [Hash{Symbol => Filter}]
filters
ruby
AaronLasseigne/active_interaction
lib/active_interaction/base.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/base.rb
MIT
def add_filter(klass, name, options, &block) raise InvalidFilterError, %("#{name}" is a reserved name) if Inputs.reserved?(name) initialize_filter(klass.new(name, options, &block)) end
rubocop:enable Style/MissingRespondToMissing @param klass [Class] @param name [Symbol] @param options [Hash]
add_filter
ruby
AaronLasseigne/active_interaction
lib/active_interaction/base.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/base.rb
MIT
def import_filters(klass, options = {}) only = options[:only] except = options[:except] other_filters = klass.filters.dup other_filters.select! { |k, _| [*only].include?(k) } if only other_filters.reject! { |k, _| [*except].include?(k) } if except other_filters.each_value { |filter| initialize_filter(filter) } end
Import filters from another interaction. @param klass [Class] The other interaction. @param options [Hash] @option options [Array<Symbol>, nil] :only Import only these filters. @option options [Array<Symbol>, nil] :except Import all filters except for these. @return (see .filters) @!visibility public
import_filters
ruby
AaronLasseigne/active_interaction
lib/active_interaction/base.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/base.rb
MIT
def merge!(other) other.messages.each do |attribute, messages| messages.zip(other.details[attribute]) do |message, detail| if detailed_error?(detail) merge_detail!(attribute, detail, message) else merge_message!(attribute, detail, message) end end end self end
Merge other errors into this one. @param other [Errors] @return [Errors]
merge!
ruby
AaronLasseigne/active_interaction
lib/active_interaction/errors.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/errors.rb
MIT
def factory(slug) CLASSES.fetch(slug) { raise MissingFilterError, slug.inspect } end
Get the filter associated with a symbol. @example ActiveInteraction::Filter.factory(:boolean) # => ActiveInteraction::BooleanFilter @example ActiveInteraction::Filter.factory(:invalid) # => ActiveInteraction::MissingFilterError: :invalid @param slug [Symbol] @return [Class] @raise [MissingFilterError] If the slug doesn't map to a filter. @see .slug
factory
ruby
AaronLasseigne/active_interaction
lib/active_interaction/filter.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/filter.rb
MIT
def initialize(name, options = {}, &block) @name = name @options = options.dup @filters = {} instance_eval(&block) if block_given? end
@param name [Symbol] @param options [Hash{Symbol => Object}] @option options [Object] :default Fallback value to use when given `nil`.
initialize
ruby
AaronLasseigne/active_interaction
lib/active_interaction/filter.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/filter.rb
MIT
def process(value, context) value, error = cast(value, context) Input.new(self, value: value, error: error) end
Processes the input through the filter and returns a variety of data about the input. @example input = ActiveInteraction::Filter.new(:example, default: nil).process(nil, nil) input.value # => nil @param value [Object] @param context [Base, nil] @return [Input, ArrayInput, HashInput] @raise (see #default)
process
ruby
AaronLasseigne/active_interaction
lib/active_interaction/filter.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/filter.rb
MIT
def default(context = nil) raise NoDefaultError, name unless default? value = raw_default(context) raise InvalidDefaultError, "#{name}: #{value.inspect}" if value.is_a?(GroupedInput) if value.nil? nil else default = process(value, context) if default.errors.any? && default.errors.first.is_a?(Filter::Error) raise InvalidDefaultError, "#{name}: #{value.inspect}" end default.value end end
Get the default value. @example ActiveInteraction::Filter.new(:example).default # => ActiveInteraction::NoDefaultError: example @example ActiveInteraction::Filter.new(:example, default: nil).default # => nil @example ActiveInteraction::Filter.new(:example, default: 0).default # => ActiveInteraction::InvalidDefaultError: example: 0 @param context [Base, nil] @return [Object] @raise [NoDefaultError] If the default is missing. @raise [InvalidDefaultError] If the default is invalid.
default
ruby
AaronLasseigne/active_interaction
lib/active_interaction/filter.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/filter.rb
MIT
def errors return @errors if defined?(@errors) return @errors = super if @error child_errors = get_errors(children) return @errors = super if child_errors.empty? @errors ||= child_errors.map do |error| Filter::Error.new(error.filter, error.type, name: :"#{@filter.name}.#{error.name}") end.freeze end
Any errors that occurred during processing. @return [Filter::Error]
errors
ruby
AaronLasseigne/active_interaction
lib/active_interaction/hash_input.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/hash_input.rb
MIT
def errors @errors ||= Array(@error) end
Any errors that occurred during processing. @return [Filter::Error]
errors
ruby
AaronLasseigne/active_interaction
lib/active_interaction/input.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/input.rb
MIT
def reserved?(name) name.to_s.start_with?('_interaction_') || name == :syscall || ( Base.method_defined?(name) && !Object.method_defined?(name) ) || ( Base.private_method_defined?(name) && !Object.private_method_defined?(name) ) end
Checking `syscall` is the result of what appears to be a bug in Ruby. https://bugs.ruby-lang.org/issues/15597 @private
reserved?
ruby
AaronLasseigne/active_interaction
lib/active_interaction/inputs.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/inputs.rb
MIT
def to_h @to_h ||= @inputs.transform_values(&:value).freeze end
Turn the inputs into a Hash. @return [Hash]
to_h
ruby
AaronLasseigne/active_interaction
lib/active_interaction/inputs.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/inputs.rb
MIT
def given?(input, *rest) filter_level = @base.class input_level = @normalized_inputs [input, *rest].each do |key_or_index| if key_or_index.is_a?(Symbol) || key_or_index.is_a?(String) key = key_or_index.to_sym key_to_s = key_or_index.to_s filter_level = filter_level.filters[key] break false if filter_level.nil? || input_level.nil? break false unless input_level.key?(key) || input_level.key?(key_to_s) input_level = input_level[key] || input_level[key_to_s] else index = key_or_index filter_level = filter_level.filters.first.last break false if filter_level.nil? || input_level.nil? break false unless index.between?(-input_level.size, input_level.size - 1) input_level = input_level[index] end end && true end
Returns `true` if the given key was in the hash passed to {.run}. Otherwise returns `false`. Use this to figure out if an input was given, even if it was `nil`. Keys within nested hash filter can also be checked by passing them in series. Arrays can be checked in the same manor as hashes by passing an index. @example class Example < ActiveInteraction::Base integer :x, default: nil def execute; given?(:x) end end Example.run!() # => false Example.run!(x: nil) # => true Example.run!(x: rand) # => true @example Nested checks class Example < ActiveInteraction::Base hash :x, default: {} do integer :y, default: nil end array :a, default: [] do integer end def execute; given?(:x, :y) || given?(:a, 2) end end Example.run!() # => false Example.run!(x: nil) # => false Example.run!(x: {}) # => false Example.run!(x: { y: nil }) # => true Example.run!(x: { y: rand }) # => true Example.run!(a: [1, 2]) # => false Example.run!(a: [1, 2, 3]) # => true @param input [#to_sym] @return [Boolean] rubocop:disable all
given?
ruby
AaronLasseigne/active_interaction
lib/active_interaction/inputs.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/inputs.rb
MIT
def column_for_attribute(name) filter = self.class.filters[name] Filter::Column.intern(filter.database_column_type) if filter end
Returns the column object for the named filter. @param name [Symbol] The name of a filter. @example class Interaction < ActiveInteraction::Base string :email, default: nil def execute; end end Interaction.new.column_for_attribute(:email) # => #<ActiveInteraction::Filter::Column:0x007faebeb2a6c8 @type=:string> Interaction.new.column_for_attribute(:not_a_filter) # => nil @return [Filter::Column, nil]
column_for_attribute
ruby
AaronLasseigne/active_interaction
lib/active_interaction/concerns/active_recordable.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/concerns/active_recordable.rb
MIT
def method_missing(slug, *args) return super unless (klass = filter(slug)) options = args.last.is_a?(Hash) ? args.pop : {} yield(klass, args, options) if block_given? self end
@param slug [Symbol] @yield [klass, args, options] @yieldparam klass [Class] @yieldparam args [Array] @yieldparam options [Hash] @return [Missable]
method_missing
ruby
AaronLasseigne/active_interaction
lib/active_interaction/concerns/missable.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/concerns/missable.rb
MIT
def filter(slug) Filter.factory(slug) rescue MissingFilterError nil end
@param slug [Symbol] @return [Filter, nil]
filter
ruby
AaronLasseigne/active_interaction
lib/active_interaction/concerns/missable.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/concerns/missable.rb
MIT
def compose(other, *args) outcome = other.run(*args) raise Interrupt, outcome.errors if outcome.invalid? outcome.result end
@param other [Class] The other interaction. @param (see ClassMethods.run) @return (see #result) @raise [Interrupt]
compose
ruby
AaronLasseigne/active_interaction
lib/active_interaction/concerns/runnable.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/concerns/runnable.rb
MIT
def run! run return result if valid? e = InvalidInteractionError.new(errors.full_messages.join(', ')) e.interaction = self e.set_backtrace(errors.backtrace) if errors.backtrace raise e end
@return [Object] @raise [InvalidInteractionError] If there are validation errors.
run!
ruby
AaronLasseigne/active_interaction
lib/active_interaction/concerns/runnable.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/concerns/runnable.rb
MIT
def run(*args) new(*args).tap { |instance| instance.send(:run) } end
@param (see Runnable#initialize) @return [Runnable]
run
ruby
AaronLasseigne/active_interaction
lib/active_interaction/concerns/runnable.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/concerns/runnable.rb
MIT
def intern(type) @columns ||= {} @columns[type] ||= new(type) end
Find or create the `Filter::Column` for a specific type. @param type [Symbol] A database column type. @example Filter::Column.intern(:string) # => #<ActiveInteraction::Filter::Column:0x007feeaa649c @type=:string> Filter::Column.intern(:string) # => #<ActiveInteraction::Filter::Column:0x007feeaa649c @type=:string> Filter::Column.intern(:boolean) # => #<ActiveInteraction::Filter::Column:0x007feeab8a08 @type=:boolean> @return [Filter::Column]
intern
ruby
AaronLasseigne/active_interaction
lib/active_interaction/filter/column.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/filter/column.rb
MIT
def initialize(type) @type = type end
@param type [type] The database column type. @private
initialize
ruby
AaronLasseigne/active_interaction
lib/active_interaction/filter/column.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/filter/column.rb
MIT
def number? %i[integer float].include?(type) end
Returns `true` if the column is either of type :integer or :float. @return [Boolean]
number?
ruby
AaronLasseigne/active_interaction
lib/active_interaction/filter/column.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/filter/column.rb
MIT
def text? type == :string end
Returns `true` if the column is of type :string. @return [Boolean]
text?
ruby
AaronLasseigne/active_interaction
lib/active_interaction/filter/column.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/filter/column.rb
MIT
def validate!(names) raise InvalidFilterError, 'multiple filters in array block' if filters.size > 1 raise InvalidFilterError, 'attribute names in array block' unless names.empty? nil end
rubocop:enable Style/MissingRespondToMissing @param filter [Filter] @param names [Array<Symbol>] @raise [InvalidFilterError]
validate!
ruby
AaronLasseigne/active_interaction
lib/active_interaction/filters/array_filter.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/filters/array_filter.rb
MIT
def validate(context, filters, inputs) filters.each_with_object([]) do |(name, filter), errors| input = filter.process(inputs[name], context) input.errors.each do |error| errors << [error.name, error.type, error.options] end end end
@param context [Base] @param filters [Hash{Symbol => Filter}] @param inputs [Inputs]
validate
ruby
AaronLasseigne/active_interaction
lib/active_interaction/modules/validation.rb
https://github.com/AaronLasseigne/active_interaction/blob/master/lib/active_interaction/modules/validation.rb
MIT
def initialize(filename) @filename = filename super("Too many indirections while resolving symlinks. I gave up after finding out #{filename} was yet another symlink. Sorry!") end
@param [String] filename The last filename that was attempted to be resolved before giving up
initialize
ruby
nanoc/nanoc
nanoc/lib/nanoc/data_sources/filesystem/tools.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/data_sources/filesystem/tools.rb
MIT
def initialize(filename) @filename = filename super("The file at #{filename} is of an unsupported type (expected file, directory or link, but it is #{File.ftype(filename)}") end
@param [String] filename The filename of the file whose type is not supported
initialize
ruby
nanoc/nanoc
nanoc/lib/nanoc/data_sources/filesystem/tools.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/data_sources/filesystem/tools.rb
MIT
def expand_and_relativize_path(path) from = Pathname.new(Dir.getwd) to = Pathname.new(File.expand_path(path)) to.relative_path_from(from).to_s end
Expands the path (including resolving ~ for home directory) and returns a relative path to the expanded path.
expand_and_relativize_path
ruby
nanoc/nanoc
nanoc/lib/nanoc/data_sources/filesystem/tools.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/data_sources/filesystem/tools.rb
MIT
def all_files_and_dirs_in(dir_name, extra_files) base_patterns = ["#{dir_name}/**/*"] extra_patterns = case extra_files when nil [] when String ["#{dir_name}/#{extra_files.dup.delete_prefix('/')}"] when Array extra_files.map { |extra_file| "#{dir_name}/#{extra_file.dup.delete_prefix('/')}" } else raise( Nanoc::Core::TrivialError, "Do not know how to handle extra_files: #{extra_files.inspect}", ) end patterns = base_patterns + extra_patterns Dir.glob(patterns) end
Returns all files and directories in the given directory and directories below it. @param [String] dir_name The name of the directory whose contents to fetch @param [String, Array, nil] extra_files The list of extra patterns to extend the file search for files not found by default, example "**/.{htaccess,htpasswd}" @return [Array<String>] A list of files and directories @raise [Nanoc::Core::TrivialError] when pattern can not be handled
all_files_and_dirs_in
ruby
nanoc/nanoc
nanoc/lib/nanoc/data_sources/filesystem/tools.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/data_sources/filesystem/tools.rb
MIT
def run(content, _params = {}) TTY::Command.new(printer: :null).run('asciidoc -o - -', input: content).out end
Runs the content through [AsciiDoc](http://www.methods.co.nz/asciidoc/). This method takes no options. @param [String] content The content to filter @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/asciidoc.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/asciidoc.rb
MIT
def strip(str) str.lines.drop_while { |line| line.strip.empty? }.join.rstrip end
Removes the first blank lines and any whitespace at the end.
strip
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/colorize_syntax.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/colorize_syntax.rb
MIT
def run(content, params = {}) # Add locals assigns.merge!(params[:locals] || {}) # Create context context = ::Nanoc::Core::Context.new(assigns) # Get binding proc = assigns[:content] ? -> { assigns[:content] } : nil assigns_binding = context.get_binding(&proc) # Get result trim_mode = params[:trim_mode] erb = ::ERB.new(content, trim_mode:) erb.filename = filename erb.result(assigns_binding) end
Runs the content through [ERB](http://ruby-doc.org/stdlib/libdoc/erb/rdoc/classes/ERB.html). @param [String] content The content to filter @option params [String] :trim_mode (nil) The trim mode to use @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/erb.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/erb.rb
MIT
def run(content, params = {}) # Create context context = ::Nanoc::Core::Context.new(assigns) # Get binding proc = assigns[:content] ? -> { assigns[:content] } : nil assigns_binding = context.get_binding(&proc) # Get result engine_opts = { bufvar: '_erbout', filename: }.merge(params) engine = ::Erubi::Engine.new(content, engine_opts) eval(engine.src, assigns_binding, filename) end
Runs the content through [Erubi](https://github.com/jeremyevans/erubi). To prevent single quote escaping use :escapefunc => 'Nanoc::Helpers::HTMLEscape.html_escape' See the Erubi documentation for more options. @param [String] content The content to filter @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/erubi.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/erubi.rb
MIT
def run(content, _params = {}) # Create context context = ::Nanoc::Core::Context.new(assigns) # Get binding proc = assigns[:content] ? -> { assigns[:content] } : nil assigns_binding = context.get_binding(&proc) # Get result erubis_with_erbout.new(content, filename:).result(assigns_binding) end
Runs the content through [Erubis](http://www.kuwata-lab.com/erubis/). This method takes no options. @param [String] content The content to filter @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/erubis.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/erubis.rb
MIT
def run(content, params = {}) # Get options options = params.merge( filename:, outvar: '_erbout', disable_capture: true, ) # Create context context = ::Nanoc::Core::Context.new(assigns) # Get result proc = assigns[:content] ? -> { assigns[:content] } : nil # Render haml_major_version = ::Haml::VERSION[0] case haml_major_version when '5' ::Haml::Engine.new(content, options).render(context, assigns, &proc) when '6' template = Tilt::HamlTemplate.new(options) { content } template.render(context, assigns, &proc) else raise Nanoc::Core::TrivialError.new( "Cannot run Haml filter: unsupported Haml major version: #{haml_major_version}", ) end end
Runs the content through [Haml](http://haml-lang.com/). Parameters passed to this filter will be passed on to Haml. @param [String] content The content to filter @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/haml.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/haml.rb
MIT
def run(content, _params = {}) context = item.attributes.dup context[:item] = assigns[:item].attributes context[:config] = assigns[:config] context[:yield] = assigns[:content] if assigns.key?(:layout) context[:layout] = assigns[:layout].attributes end handlebars = ::Handlebars::Handlebars.new template = handlebars.compile(content) template.call(context) end
Runs the content through [Handlebars](http://handlebarsjs.com/) using [Handlebars.rb](https://github.com/cowboyd/handlebars.rb). This method takes no options. @param [String] content The content to filter @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/handlebars.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/handlebars.rb
MIT
def run(content, params = {}) params = params.dup warning_filters = params.delete(:warning_filters) document = ::Kramdown::Document.new(content, params) if warning_filters r = Regexp.union(warning_filters) warnings = document.warnings.reject { |warning| r =~ warning } else warnings = document.warnings end unless warnings.empty? $stderr.puts "kramdown warning(s) for #{@item_rep.inspect}" warnings.each do |warning| $stderr.puts " #{warning}" end end document.to_html end
Runs the content through [Kramdown](https://kramdown.gettalong.org/). Parameters passed to this filter will be passed on to Kramdown. @param [String] content The content to filter @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/kramdown.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/kramdown.rb
MIT
def run(content, params = {}) # Create dependencies imported_filenames = imported_filenames_from(content) imported_items = imported_filenames_to_items(imported_filenames) depend_on(imported_items) # Add filename to load path paths = [File.dirname(@item[:content_filename])] on_main_fiber do parser = ::Less::Parser.new(paths:) parser.parse(content).to_css(params) end end
Runs the content through [LESS](http://lesscss.org/). This method takes no options. @param [String] content The content to filter @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/less.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/less.rb
MIT
def find_file(pathname, root_pathname) absolute_pathname = if pathname.relative? root_pathname + pathname else pathname end if absolute_pathname.exist? absolute_pathname.realpath else nil end end
@param [Pathname] pathname Pathname of the file to find. Can be relative or absolute. @param [Pathname] root_pathname Directory pathname from which the search will start. @return [String, nil] A string containing the full path if a file is found, otherwise nil.
find_file
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/less.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/less.rb
MIT
def run(content, _params = {}) # Get result ::Markaby::Builder.new(assigns).instance_eval(content).to_s end
Runs the content through [Markaby](http://markaby.github.io/). This method takes no options. @param [String] content The content to filter @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/markaby.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/markaby.rb
MIT
def run(content, params = {}) # Get result ::Maruku.new(content, params).to_html end
Runs the content through [Maruku](https://github.com/bhollis/maruku/). Parameters passed to this filter will be passed on to Maruku. @param [String] content The content to filter @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/maruku.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/maruku.rb
MIT
def run(content, _params = {}) context = item.attributes.merge(yield: assigns[:content]) ::Mustache.render(content, context) end
Runs the content through [Mustache](https://github.com/defunkt/mustache). This method takes no options. @param [String] content The content to filter @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/mustache.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/mustache.rb
MIT
def run(content, params = {}) ::Rainpress.compress(content, params) end
Runs the content through [Rainpress](https://github.com/ddfreyne/rainpress). Parameters passed to this filter will be passed on to Rainpress. @param [String] content The content to filter @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/rainpress.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/rainpress.rb
MIT
def run(content, params = {}) extensions = params[:extensions] || [] ::RDiscount.new(content, *extensions).to_html end
Runs the content through [RDiscount](https://github.com/davidfstr/rdiscount). @option params [Array] :extensions ([]) A list of RDiscount extensions @param [String] content The content to filter @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/rdiscount.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/rdiscount.rb
MIT
def run(content, _params = {}) options = ::RDoc::Options.new to_html = ::RDoc::Markup::ToHtml.new(options) ::RDoc::Markup.new.convert(content, to_html) end
Runs the content through [RDoc::Markup](http://docs.seattlerb.org/rdoc/RDoc/Markup.html). This method takes no options. @param [String] content The content to filter @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/rdoc.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/rdoc.rb
MIT
def run(content, params = {}) # Create formatter r = ::RedCloth.new(content) # Set options r.filter_classes = params[:filter_classes] if params.key?(:filter_classes) r.filter_html = params[:filter_html] if params.key?(:filter_html) r.filter_ids = params[:filter_ids] if params.key?(:filter_ids) r.filter_styles = params[:filter_styles] if params.key?(:filter_styles) r.hard_breaks = params[:hard_breaks] if params.key?(:hard_breaks) r.lite_mode = params[:lite_mode] if params.key?(:lite_mode) r.no_span_caps = params[:no_span_caps] if params.key?(:no_span_caps) r.sanitize_html = params[:sanitize_html] if params.key?(:sanitize_html) # Get result r.to_html end
Runs the content through [RedCloth](http://redcloth.org/). This method takes the following options: * `:filter_class` * `:filter_html` * `:filter_ids` * `:filter_style` * `:hard_breaks` * `:lite_mode` * `:no_span_caps` * `:sanitize_htm` Each of these options sets the corresponding attribute on the `RedCloth` instance. For example, when the `:hard_breaks => false` option is passed to this filter, the filter will call `r.hard_breaks = false` (with `r` being the `RedCloth` instance). @param [String] content The content to filter @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/redcloth.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/redcloth.rb
MIT
def run(content, params = {}) # Set assigns so helper function can be used @item_rep = assigns[:item_rep] if @item_rep.nil? # Filter case params[:type] when :css relativize_css(content, params) when :html, :html5, :xml, :xhtml relativize_html_like(content, params) else raise 'The relativize_paths needs to know the type of content to ' \ 'process. Pass a :type to the filter call (:html for HTML, ' \ ':xhtml for XHTML, :xml for XML, or :css for CSS).' end end
Relativizes all paths in the given content, which can be HTML, XHTML, XML or CSS. This filter is quite useful if a site needs to be hosted in a subdirectory instead of a subdomain. In HTML, all `href` and `src` attributes will be relativized. In CSS, all `url()` references will be relativized. @param [String] content The content to filter @option params [Symbol] :type The type of content to filter; can be `:html`, `:xhtml`, `:xml` or `:css`. @option params [Array] :select The XPath expressions that matches the nodes to modify. This param is useful only for the `:html`, `:xml` and `:xhtml` types. @option params [Hash] :namespaces The pairs `prefix => uri` to define any namespace you want to use in the XPath expressions. This param is useful only for the `:xml` and `:xhtml` types. @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/relativize_paths.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/relativize_paths.rb
MIT
def run(content, _params = {}) # Get result ::RubyPants.new(content).to_html end
Runs the content through [RubyPants](http://rubydoc.info/gems/rubypants/). This method takes no options. @param [String] content The content to filter @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/rubypants.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/rubypants.rb
MIT
def run(content, params = {}) params = { disable_capture: true, # Capture managed by Nanoc buffer: '_erbout', # Force slim to output to the buffer used by Nanoc }.merge params # Create context context = ::Nanoc::Core::Context.new(assigns) ::Slim::Template.new(filename, params) { content }.render(context) { assigns[:content] } end
Runs the content through [Slim](http://slim-lang.com/). This method takes no options. @param [String] content The content to filter @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/slim.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/slim.rb
MIT
def run(content, params = {}) # Add filename to load path ::Terser.new(params).compile(content) end
Runs the content through [terser](https://github.com/ahorek/terser-ruby). This method optionally takes options to pass directly to Terser. @param [String] content The content to filter @option params [Array] :options ([]) A list of options to pass on to Terser @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/terser.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/terser.rb
MIT
def run(content, _params = {}) # Get result ::Typogruby.improve(content) end
Runs the content through [Typogruby](http://avdgaag.github.com/typogruby/). This method takes no options. @param [String] content The content to filter @return [String] The filtered content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/typogruby.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/typogruby.rb
MIT
def run(_content, params = {}) if assigns[:layout].nil? raise 'The XSL filter can only be run as a layout' end xml = ::Nokogiri::XML(assigns[:content]) xsl = ::Nokogiri::XSLT(assigns[:layout].raw_content) xsl.apply_to(xml, ::Nokogiri::XSLT.quote_params(params)) end
Runs the item content through an [XSLT](http://www.w3.org/TR/xslt) stylesheet using [Nokogiri](http://nokogiri.org/). This filter can only be run for layouts, because it will need both the XML to convert (= the item content) as well as the XSLT stylesheet (= the layout content). Additional parameters can be passed to the layout call. These parameters will be turned into `xsl:param` elements. @example Invoking the filter as a layout compile '/reports/*/' do layout 'xsl-report' end layout 'xsl-report', :xsl, :awesome => 'definitely' @param [String] _content Ignored. As the filter can be run only as a layout, the value of the `:content` parameter passed to the class at initialization is used as the content to transform. @param [Hash] params The parameters that will be stored in corresponding `xsl:param` elements. @return [String] The transformed content
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/xsl.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/xsl.rb
MIT
def run(content, params = {}) ::YUICompressor.compress(content, params) end
Compress Javascript or CSS using [YUICompressor](http://rubydoc.info/gems/yuicompressor). This method optionally takes options to pass directly to the YUICompressor gem. @param [String] content JavaScript or CSS input @param [Hash] params Options passed to YUICompressor @return [String] Compressed but equivalent JavaScript or CSS
run
ruby
nanoc/nanoc
nanoc/lib/nanoc/filters/yui_compressor.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/filters/yui_compressor.rb
MIT
def attribute_to_time(arg) case arg when DateTime arg.to_time when Date Time.utc(arg.year, arg.month, arg.day) when String Time.parse(arg) else arg end end
@param [String, Time, Date, DateTime] arg @return [Time]
attribute_to_time
ruby
nanoc/nanoc
nanoc/lib/nanoc/helpers/blogging.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/helpers/blogging.rb
MIT
def content_for(*args, &) if block_given? # Set content name = args[0] params = case args.size when 1 {} when 2 args[1] else raise ArgumentError, 'expected 1 or 2 argument (the name ' \ "of the capture, and optionally params) but got #{args.size} instead" end SetContent.new(name, params, @item).run(&) elsif args.size > 1 && (args.first.is_a?(Symbol) || args.first.is_a?(String)) # Set content name = args[0] content = args.last params = case args.size when 2 {} when 3 args[1] else raise ArgumentError, 'expected 2 or 3 arguments (the name ' \ "of the capture, optionally params, and the content) but got #{args.size} instead" end _erbout = +'' # rubocop:disable Lint/UnderscorePrefixedVariableName SetContent.new(name, params, @item).run { _erbout << content } else # Get content if args.size != 2 raise ArgumentError, 'expected 2 arguments (the item ' \ "and the name of the capture) but got #{args.size} instead" end requested_item = args[0] name = args[1] GetContent.new(requested_item, name, @item, @config).run end end
@overload content_for(name, &block) @param [Symbol, String] name @return [void] @overload content_for(name, params, &block) @param [Symbol, String] name @option params [Symbol] existing @return [void] @overload content_for(name, content) @param [Symbol, String] name @param [String] content @return [void] @overload content_for(name, params, content) @param [Symbol, String] name @param [String] content @option params [Symbol] existing @return [void] @overload content_for(item, name) @param [Symbol, String] name @return [String]
content_for
ruby
nanoc/nanoc
nanoc/lib/nanoc/helpers/capturing.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/helpers/capturing.rb
MIT
def filter(filter_name, arguments = {}, &block) # Capture block data = capture(&block) # Find filter klass = Nanoc::Filter.named!(filter_name) # Create filter assigns = { item: @item, rep: @rep, item_rep: @item_rep, items: @items, layouts: @layouts, config: @config, content: @content, } filter = klass.new(assigns) # Filter captured data Nanoc::Core::NotificationCenter.post(:filtering_started, @item_rep._unwrap, filter_name) filtered_data = filter.setup_and_run(data, arguments) Nanoc::Core::NotificationCenter.post(:filtering_ended, @item_rep._unwrap, filter_name) # Append filtered data to buffer buffer = eval('_erbout', block.binding) buffer << filtered_data end
@param [Symbol] filter_name @param [Hash] arguments @return [void]
filter
ruby
nanoc/nanoc
nanoc/lib/nanoc/helpers/filtering.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/helpers/filtering.rb
MIT
def link_to(text, target, attributes = {}) # Find path path = case target when String target when Nanoc::Core::CompilationItemView, Nanoc::Core::BasicItemView, Nanoc::Core::BasicItemRepView raise "Cannot create a link to #{target.inspect} because this target is not outputted (its routing rule returns nil)" if target.path.nil? target.path else raise ArgumentError, "Cannot link to #{target.inspect} (expected a string or an item, not a #{target.class.name})" end # Join attributes attributes = attributes.reduce('') do |memo, (key, value)| memo + key.to_s + '="' + h(value) + '" ' end # Create link "<a #{attributes}href=\"#{h path}\">#{text}</a>" end
@param [String] text @param [Hash] attributes @return [String]
link_to
ruby
nanoc/nanoc
nanoc/lib/nanoc/helpers/link_to.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/helpers/link_to.rb
MIT
def link_to_unless_current(text, target, attributes = {}) # Find path path = target.is_a?(String) ? target : target.path if @item_rep&.path == path # Create message "<span class=\"active\">#{text}</span>" else link_to(text, target, attributes) end end
@param [String] text @param [Hash] attributes @return [String]
link_to_unless_current
ruby
nanoc/nanoc
nanoc/lib/nanoc/helpers/link_to.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/helpers/link_to.rb
MIT
def render(identifier, other_assigns = {}, &block) # Find layout layout_view = @layouts[identifier] layout_view ||= @layouts[identifier.__nanoc_cleaned_identifier] raise Nanoc::Core::Errors::UnknownLayout.new(identifier) if layout_view.nil? layout = layout_view._unwrap # Visit dependency_tracker = @config._context.dependency_tracker dependency_tracker.bounce(layout, raw_content: true) # Capture content, if any captured_content = block_given? ? capture(&block) : nil # Get assigns assigns = { content: captured_content, item: @item, item_rep: @item_rep, rep: @item_rep, items: @items, layout: layout_view, layouts: @layouts, config: @config, }.merge(other_assigns) # Get filter name filter_name_and_args = @config._context.compilation_context.filter_name_and_args_for_layout(layout) filter_name = filter_name_and_args.name filter_args = filter_name_and_args.args raise Nanoc::Core::Errors::CannotDetermineFilter.new(layout.identifier) if filter_name.nil? # Get filter class filter_class = Nanoc::Filter.named!(filter_name) # Create filter filter = filter_class.new(assigns) # Layout content = layout.content arg = content.binary? ? content.filename : content.string result = filter.setup_and_run(arg, filter_args) # Append to erbout if we have a block if block_given? # Append result and return nothing erbout = eval('_erbout', block.binding) erbout << result '' else # Return result result end end
@param [String] identifier @param [Hash] other_assigns @raise [Nanoc::Core::Errors::UnknownLayout] @raise [Nanoc::Core::Errors::CannotDetermineFilter] @raise [Nanoc::Filter::UnknownFilter] @return [String, nil]
render
ruby
nanoc/nanoc
nanoc/lib/nanoc/helpers/rendering.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/helpers/rendering.rb
MIT
def tags_for(item, base_url: nil, none_text: '(none)', separator: ', ') if item[:tags].nil? || item[:tags].empty? none_text else item[:tags].map { |tag| base_url ? link_for_tag(tag, base_url) : tag }.join(separator) end end
@param [String] base_url @param [String] none_text @param [String] separator @return [String]
tags_for
ruby
nanoc/nanoc
nanoc/lib/nanoc/helpers/tagging.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/helpers/tagging.rb
MIT
def link_for_tag(tag, base_url) %(<a href="#{h base_url}#{h tag}" rel="tag">#{h tag}</a>) end
@param [String] tag @param [String] base_url @return [String]
link_for_tag
ruby
nanoc/nanoc
nanoc/lib/nanoc/helpers/tagging.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/helpers/tagging.rb
MIT
def excerptize(string, length: 25, omission: '...') if string.length > length excerpt_length = [0, length - omission.length].max string[0...excerpt_length] + omission else string end end
@param [String] string @param [Number] length @param [String] omission @return [String]
excerptize
ruby
nanoc/nanoc
nanoc/lib/nanoc/helpers/text.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/helpers/text.rb
MIT
def xml_sitemap(params = {}) require 'builder' # Extract parameters items = params.fetch(:items) { @items.reject { |i| i[:is_hidden] } } select_proc = params.fetch(:rep_select, nil) # Create builder buffer = +'' xml = Builder::XmlMarkup.new(target: buffer, indent: 2) # Check for required attributes if @config[:base_url].nil? raise 'The Nanoc::Helpers::XMLSitemap helper requires the site configuration to specify the base URL for the site.' end # Build sitemap xml.instruct! xml.urlset(xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9') do # Add item items.sort_by(&:identifier).each do |item| reps = item.reps.select(&:path) reps.select! { |r| select_proc[r] } if select_proc reps.sort_by { |r| r.name.to_s }.each do |rep| xml.url do xml.loc Addressable::URI.escape(@config[:base_url] + rep.path) xml.lastmod item[:mtime].__nanoc_to_iso8601_date unless item[:mtime].nil? xml.changefreq item[:changefreq] unless item[:changefreq].nil? xml.priority item[:priority] unless item[:priority].nil? end end end end # Return sitemap buffer end
@option params [Array] :items @option params [Proc] :rep_select @return [String]
xml_sitemap
ruby
nanoc/nanoc
nanoc/lib/nanoc/helpers/xml_sitemap.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/helpers/xml_sitemap.rb
MIT
def filter(filter_name, filter_args = {}) @_recorder.filter(filter_name, filter_args) end
Filters the current representation (calls {Nanoc::Core::ItemRep#filter} with the given arguments on the rep). @see Nanoc::Core::ItemRep#filter @param [Symbol] filter_name The name of the filter to run the item representations' content through @param [Hash] filter_args The filter arguments that should be passed to the filter's #run method @return [void]
filter
ruby
nanoc/nanoc
nanoc/lib/nanoc/rule_dsl/compilation_rule_context.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/rule_dsl/compilation_rule_context.rb
MIT
def layout(layout_identifier, extra_filter_args = nil) @_recorder.layout(layout_identifier, extra_filter_args) end
Layouts the current representation (calls {Nanoc::Core::ItemRep#layout} with the given arguments on the rep). @see Nanoc::Core::ItemRep#layout @param [String] layout_identifier The identifier of the layout the item should be laid out with @return [void]
layout
ruby
nanoc/nanoc
nanoc/lib/nanoc/rule_dsl/compilation_rule_context.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/rule_dsl/compilation_rule_context.rb
MIT
def snapshot(snapshot_name, path: Nanoc::Core::UNDEFINED) @_recorder.snapshot(snapshot_name, path:) end
Creates a snapshot of the current compiled item content. Calls {Nanoc::Core::ItemRep#snapshot} with the given arguments on the rep. @see Nanoc::Core::ItemRep#snapshot @param [Symbol] snapshot_name The name of the snapshot to create @param [String, nil] path @return [void]
snapshot
ruby
nanoc/nanoc
nanoc/lib/nanoc/rule_dsl/compilation_rule_context.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/rule_dsl/compilation_rule_context.rb
MIT
def write(arg) @_write_snapshot_counter ||= 0 snapshot_name = :"_#{@_write_snapshot_counter}" @_write_snapshot_counter += 1 case arg when String, Nanoc::Core::Identifier, nil snapshot(snapshot_name, path: arg) when Hash if arg.key?(:ext) ext = arg[:ext].sub(/\A\./, '') path = @item.identifier.without_exts + '.' + ext snapshot(snapshot_name, path:) else raise ArgumentError, 'Cannot call #write this way (need path or :ext)' end else raise ArgumentError, 'Cannot call #write this way (need path or :ext)' end end
Creates a snapshot named :last the current compiled item content, with the given path. This is a convenience method for {#snapshot}. @see #snapshot @param [String] arg @return [void]
write
ruby
nanoc/nanoc
nanoc/lib/nanoc/rule_dsl/compilation_rule_context.rb
https://github.com/nanoc/nanoc/blob/master/nanoc/lib/nanoc/rule_dsl/compilation_rule_context.rb
MIT