repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
hashicorp/vagrant
lib/vagrant/box_collection.rb
Vagrant.BoxCollection.dir_name
def dir_name(name) name = name.dup name.gsub!(":", VAGRANT_COLON) if Util::Platform.windows? name.gsub!("/", VAGRANT_SLASH) name end
ruby
def dir_name(name) name = name.dup name.gsub!(":", VAGRANT_COLON) if Util::Platform.windows? name.gsub!("/", VAGRANT_SLASH) name end
[ "def", "dir_name", "(", "name", ")", "name", "=", "name", ".", "dup", "name", ".", "gsub!", "(", "\":\"", ",", "VAGRANT_COLON", ")", "if", "Util", "::", "Platform", ".", "windows?", "name", ".", "gsub!", "(", "\"/\"", ",", "VAGRANT_SLASH", ")", "name", "end" ]
Returns the directory name for the box of the given name. @param [String] name @return [String]
[ "Returns", "the", "directory", "name", "for", "the", "box", "of", "the", "given", "name", "." ]
c22a145c59790c098f95d50141d9afb48e1ef55f
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box_collection.rb#L386-L391
train
hashicorp/vagrant
lib/vagrant/box_collection.rb
Vagrant.BoxCollection.undir_name
def undir_name(name) name = name.dup name.gsub!(VAGRANT_COLON, ":") name.gsub!(VAGRANT_SLASH, "/") name end
ruby
def undir_name(name) name = name.dup name.gsub!(VAGRANT_COLON, ":") name.gsub!(VAGRANT_SLASH, "/") name end
[ "def", "undir_name", "(", "name", ")", "name", "=", "name", ".", "dup", "name", ".", "gsub!", "(", "VAGRANT_COLON", ",", "\":\"", ")", "name", ".", "gsub!", "(", "VAGRANT_SLASH", ",", "\"/\"", ")", "name", "end" ]
Returns the directory name for the box cleaned up
[ "Returns", "the", "directory", "name", "for", "the", "box", "cleaned", "up" ]
c22a145c59790c098f95d50141d9afb48e1ef55f
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box_collection.rb#L394-L399
train
hashicorp/vagrant
lib/vagrant/box_collection.rb
Vagrant.BoxCollection.v1_upgrade
def v1_upgrade(dir) @logger.debug("Upgrading box in directory: #{dir}") temp_dir = Pathname.new(Dir.mktmpdir(TEMP_PREFIX, @temp_root)) @logger.debug("Temporary directory for upgrading: #{temp_dir}") # Move all the things into the temporary directory dir.children(true).each do |child| # Don't move the temp_dir next if child == temp_dir # Move every other directory into the temporary directory @logger.debug("Copying to upgrade directory: #{child}") FileUtils.mv(child, temp_dir.join(child.basename)) end # If there is no metadata.json file, make one, since this is how # we determine if the box is a V2 box. metadata_file = temp_dir.join("metadata.json") if !metadata_file.file? metadata_file.open("w") do |f| f.write(JSON.generate({ provider: "virtualbox" })) end end # Return the temporary directory temp_dir end
ruby
def v1_upgrade(dir) @logger.debug("Upgrading box in directory: #{dir}") temp_dir = Pathname.new(Dir.mktmpdir(TEMP_PREFIX, @temp_root)) @logger.debug("Temporary directory for upgrading: #{temp_dir}") # Move all the things into the temporary directory dir.children(true).each do |child| # Don't move the temp_dir next if child == temp_dir # Move every other directory into the temporary directory @logger.debug("Copying to upgrade directory: #{child}") FileUtils.mv(child, temp_dir.join(child.basename)) end # If there is no metadata.json file, make one, since this is how # we determine if the box is a V2 box. metadata_file = temp_dir.join("metadata.json") if !metadata_file.file? metadata_file.open("w") do |f| f.write(JSON.generate({ provider: "virtualbox" })) end end # Return the temporary directory temp_dir end
[ "def", "v1_upgrade", "(", "dir", ")", "@logger", ".", "debug", "(", "\"Upgrading box in directory: #{dir}\"", ")", "temp_dir", "=", "Pathname", ".", "new", "(", "Dir", ".", "mktmpdir", "(", "TEMP_PREFIX", ",", "@temp_root", ")", ")", "@logger", ".", "debug", "(", "\"Temporary directory for upgrading: #{temp_dir}\"", ")", "dir", ".", "children", "(", "true", ")", ".", "each", "do", "|", "child", "|", "next", "if", "child", "==", "temp_dir", "@logger", ".", "debug", "(", "\"Copying to upgrade directory: #{child}\"", ")", "FileUtils", ".", "mv", "(", "child", ",", "temp_dir", ".", "join", "(", "child", ".", "basename", ")", ")", "end", "metadata_file", "=", "temp_dir", ".", "join", "(", "\"metadata.json\"", ")", "if", "!", "metadata_file", ".", "file?", "metadata_file", ".", "open", "(", "\"w\"", ")", "do", "|", "f", "|", "f", ".", "write", "(", "JSON", ".", "generate", "(", "{", "provider", ":", "\"virtualbox\"", "}", ")", ")", "end", "end", "temp_dir", "end" ]
This upgrades the V1 box contained unpacked in the given directory and returns the directory of the upgraded version. This is _destructive_ to the contents of the old directory. That is, the contents of the old V1 box will be destroyed or moved. Preconditions: * `dir` is a valid V1 box. Verify with {#v1_box?} @param [Pathname] dir Directory where the V1 box is unpacked. @return [Pathname] Path to the unpackaged V2 box.
[ "This", "upgrades", "the", "V1", "box", "contained", "unpacked", "in", "the", "given", "directory", "and", "returns", "the", "directory", "of", "the", "upgraded", "version", ".", "This", "is", "_destructive_", "to", "the", "contents", "of", "the", "old", "directory", ".", "That", "is", "the", "contents", "of", "the", "old", "V1", "box", "will", "be", "destroyed", "or", "moved", "." ]
c22a145c59790c098f95d50141d9afb48e1ef55f
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box_collection.rb#L422-L451
train
hashicorp/vagrant
lib/vagrant/box_collection.rb
Vagrant.BoxCollection.with_temp_dir
def with_temp_dir(dir=nil) dir ||= Dir.mktmpdir(TEMP_PREFIX, @temp_root) dir = Pathname.new(dir) yield dir ensure FileUtils.rm_rf(dir.to_s) end
ruby
def with_temp_dir(dir=nil) dir ||= Dir.mktmpdir(TEMP_PREFIX, @temp_root) dir = Pathname.new(dir) yield dir ensure FileUtils.rm_rf(dir.to_s) end
[ "def", "with_temp_dir", "(", "dir", "=", "nil", ")", "dir", "||=", "Dir", ".", "mktmpdir", "(", "TEMP_PREFIX", ",", "@temp_root", ")", "dir", "=", "Pathname", ".", "new", "(", "dir", ")", "yield", "dir", "ensure", "FileUtils", ".", "rm_rf", "(", "dir", ".", "to_s", ")", "end" ]
This is a helper that makes sure that our temporary directories are cleaned up no matter what. @param [String] dir Path to a temporary directory @return [Object] The result of whatever the yield is
[ "This", "is", "a", "helper", "that", "makes", "sure", "that", "our", "temporary", "directories", "are", "cleaned", "up", "no", "matter", "what", "." ]
c22a145c59790c098f95d50141d9afb48e1ef55f
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box_collection.rb#L466-L473
train
hashicorp/vagrant
lib/vagrant/capability_host.rb
Vagrant.CapabilityHost.initialize_capabilities!
def initialize_capabilities!(host, hosts, capabilities, *args) @cap_logger = Log4r::Logger.new( "vagrant::capability_host::#{self.class.to_s.downcase}") if host && !hosts[host] raise Errors::CapabilityHostExplicitNotDetected, value: host.to_s end if !host host = autodetect_capability_host(hosts, *args) if !host raise Errors::CapabilityHostNotDetected if !host end if !hosts[host] # This should never happen because the autodetect above uses the # hosts hash to look up hosts. And if an explicit host is specified, # we do another check higher up. raise "Internal error. Host not found: #{host}" end name = host host_info = hosts[name] host = host_info[0].new chain = [] chain << [name, host] # Build the proper chain of parents if there are any. # This allows us to do "inheritance" of capabilities later if host_info[1] parent_name = host_info[1] parent_info = hosts[parent_name] while parent_info chain << [parent_name, parent_info[0].new] parent_name = parent_info[1] parent_info = hosts[parent_name] end end @cap_host_chain = chain @cap_args = args @cap_caps = capabilities true end
ruby
def initialize_capabilities!(host, hosts, capabilities, *args) @cap_logger = Log4r::Logger.new( "vagrant::capability_host::#{self.class.to_s.downcase}") if host && !hosts[host] raise Errors::CapabilityHostExplicitNotDetected, value: host.to_s end if !host host = autodetect_capability_host(hosts, *args) if !host raise Errors::CapabilityHostNotDetected if !host end if !hosts[host] # This should never happen because the autodetect above uses the # hosts hash to look up hosts. And if an explicit host is specified, # we do another check higher up. raise "Internal error. Host not found: #{host}" end name = host host_info = hosts[name] host = host_info[0].new chain = [] chain << [name, host] # Build the proper chain of parents if there are any. # This allows us to do "inheritance" of capabilities later if host_info[1] parent_name = host_info[1] parent_info = hosts[parent_name] while parent_info chain << [parent_name, parent_info[0].new] parent_name = parent_info[1] parent_info = hosts[parent_name] end end @cap_host_chain = chain @cap_args = args @cap_caps = capabilities true end
[ "def", "initialize_capabilities!", "(", "host", ",", "hosts", ",", "capabilities", ",", "*", "args", ")", "@cap_logger", "=", "Log4r", "::", "Logger", ".", "new", "(", "\"vagrant::capability_host::#{self.class.to_s.downcase}\"", ")", "if", "host", "&&", "!", "hosts", "[", "host", "]", "raise", "Errors", "::", "CapabilityHostExplicitNotDetected", ",", "value", ":", "host", ".", "to_s", "end", "if", "!", "host", "host", "=", "autodetect_capability_host", "(", "hosts", ",", "*", "args", ")", "if", "!", "host", "raise", "Errors", "::", "CapabilityHostNotDetected", "if", "!", "host", "end", "if", "!", "hosts", "[", "host", "]", "raise", "\"Internal error. Host not found: #{host}\"", "end", "name", "=", "host", "host_info", "=", "hosts", "[", "name", "]", "host", "=", "host_info", "[", "0", "]", ".", "new", "chain", "=", "[", "]", "chain", "<<", "[", "name", ",", "host", "]", "if", "host_info", "[", "1", "]", "parent_name", "=", "host_info", "[", "1", "]", "parent_info", "=", "hosts", "[", "parent_name", "]", "while", "parent_info", "chain", "<<", "[", "parent_name", ",", "parent_info", "[", "0", "]", ".", "new", "]", "parent_name", "=", "parent_info", "[", "1", "]", "parent_info", "=", "hosts", "[", "parent_name", "]", "end", "end", "@cap_host_chain", "=", "chain", "@cap_args", "=", "args", "@cap_caps", "=", "capabilities", "true", "end" ]
Initializes the capability system by detecting the proper capability host to execute on and building the chain of capabilities to execute. @param [Symbol] host The host to use for the capabilities, or nil if we should auto-detect it. @param [Hash<Symbol, Array<Class, Symbol>>] hosts Potential capability hosts. The key is the name of the host, value[0] is a class that implements `#detect?` and value[1] is a parent host (if any). @param [Hash<Symbol, Hash<Symbol, Class>>] capabilities The capabilities that are supported. The key is the host of the capability. Within that is a hash where the key is the name of the capability and the value is the class/module implementing it.
[ "Initializes", "the", "capability", "system", "by", "detecting", "the", "proper", "capability", "host", "to", "execute", "on", "and", "building", "the", "chain", "of", "capabilities", "to", "execute", "." ]
c22a145c59790c098f95d50141d9afb48e1ef55f
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/capability_host.rb#L27-L69
train
hashicorp/vagrant
lib/vagrant/capability_host.rb
Vagrant.CapabilityHost.capability
def capability(cap_name, *args) cap_mod = capability_module(cap_name.to_sym) if !cap_mod raise Errors::CapabilityNotFound, cap: cap_name.to_s, host: @cap_host_chain[0][0].to_s end cap_method = nil begin cap_method = cap_mod.method(cap_name) rescue NameError raise Errors::CapabilityInvalid, cap: cap_name.to_s, host: @cap_host_chain[0][0].to_s end args = @cap_args + args @cap_logger.info( "Execute capability: #{cap_name} #{args.inspect} (#{@cap_host_chain[0][0]})") cap_method.call(*args) end
ruby
def capability(cap_name, *args) cap_mod = capability_module(cap_name.to_sym) if !cap_mod raise Errors::CapabilityNotFound, cap: cap_name.to_s, host: @cap_host_chain[0][0].to_s end cap_method = nil begin cap_method = cap_mod.method(cap_name) rescue NameError raise Errors::CapabilityInvalid, cap: cap_name.to_s, host: @cap_host_chain[0][0].to_s end args = @cap_args + args @cap_logger.info( "Execute capability: #{cap_name} #{args.inspect} (#{@cap_host_chain[0][0]})") cap_method.call(*args) end
[ "def", "capability", "(", "cap_name", ",", "*", "args", ")", "cap_mod", "=", "capability_module", "(", "cap_name", ".", "to_sym", ")", "if", "!", "cap_mod", "raise", "Errors", "::", "CapabilityNotFound", ",", "cap", ":", "cap_name", ".", "to_s", ",", "host", ":", "@cap_host_chain", "[", "0", "]", "[", "0", "]", ".", "to_s", "end", "cap_method", "=", "nil", "begin", "cap_method", "=", "cap_mod", ".", "method", "(", "cap_name", ")", "rescue", "NameError", "raise", "Errors", "::", "CapabilityInvalid", ",", "cap", ":", "cap_name", ".", "to_s", ",", "host", ":", "@cap_host_chain", "[", "0", "]", "[", "0", "]", ".", "to_s", "end", "args", "=", "@cap_args", "+", "args", "@cap_logger", ".", "info", "(", "\"Execute capability: #{cap_name} #{args.inspect} (#{@cap_host_chain[0][0]})\"", ")", "cap_method", ".", "call", "(", "*", "args", ")", "end" ]
Executes the capability with the given name, optionally passing more arguments onwards to the capability. If the capability returns a value, it will be returned. @param [Symbol] cap_name Name of the capability
[ "Executes", "the", "capability", "with", "the", "given", "name", "optionally", "passing", "more", "arguments", "onwards", "to", "the", "capability", ".", "If", "the", "capability", "returns", "a", "value", "it", "will", "be", "returned", "." ]
c22a145c59790c098f95d50141d9afb48e1ef55f
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/capability_host.rb#L91-L112
train
hashicorp/vagrant
lib/vagrant/capability_host.rb
Vagrant.CapabilityHost.capability_module
def capability_module(cap_name) @cap_logger.debug("Searching for cap: #{cap_name}") @cap_host_chain.each do |host_name, host| @cap_logger.debug("Checking in: #{host_name}") caps = @cap_caps[host_name] if caps && caps.key?(cap_name) @cap_logger.debug("Found cap: #{cap_name} in #{host_name}") return caps[cap_name] end end nil end
ruby
def capability_module(cap_name) @cap_logger.debug("Searching for cap: #{cap_name}") @cap_host_chain.each do |host_name, host| @cap_logger.debug("Checking in: #{host_name}") caps = @cap_caps[host_name] if caps && caps.key?(cap_name) @cap_logger.debug("Found cap: #{cap_name} in #{host_name}") return caps[cap_name] end end nil end
[ "def", "capability_module", "(", "cap_name", ")", "@cap_logger", ".", "debug", "(", "\"Searching for cap: #{cap_name}\"", ")", "@cap_host_chain", ".", "each", "do", "|", "host_name", ",", "host", "|", "@cap_logger", ".", "debug", "(", "\"Checking in: #{host_name}\"", ")", "caps", "=", "@cap_caps", "[", "host_name", "]", "if", "caps", "&&", "caps", ".", "key?", "(", "cap_name", ")", "@cap_logger", ".", "debug", "(", "\"Found cap: #{cap_name} in #{host_name}\"", ")", "return", "caps", "[", "cap_name", "]", "end", "end", "nil", "end" ]
Returns the registered module for a capability with the given name. @param [Symbol] cap_name @return [Module]
[ "Returns", "the", "registered", "module", "for", "a", "capability", "with", "the", "given", "name", "." ]
c22a145c59790c098f95d50141d9afb48e1ef55f
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/capability_host.rb#L162-L175
train
hashicorp/vagrant
lib/vagrant/box.rb
Vagrant.Box.in_use?
def in_use?(index) results = [] index.each do |entry| box_data = entry.extra_data["box"] next if !box_data # If all the data matches, record it if box_data["name"] == self.name && box_data["provider"] == self.provider.to_s && box_data["version"] == self.version.to_s results << entry end end return nil if results.empty? results end
ruby
def in_use?(index) results = [] index.each do |entry| box_data = entry.extra_data["box"] next if !box_data # If all the data matches, record it if box_data["name"] == self.name && box_data["provider"] == self.provider.to_s && box_data["version"] == self.version.to_s results << entry end end return nil if results.empty? results end
[ "def", "in_use?", "(", "index", ")", "results", "=", "[", "]", "index", ".", "each", "do", "|", "entry", "|", "box_data", "=", "entry", ".", "extra_data", "[", "\"box\"", "]", "next", "if", "!", "box_data", "if", "box_data", "[", "\"name\"", "]", "==", "self", ".", "name", "&&", "box_data", "[", "\"provider\"", "]", "==", "self", ".", "provider", ".", "to_s", "&&", "box_data", "[", "\"version\"", "]", "==", "self", ".", "version", ".", "to_s", "results", "<<", "entry", "end", "end", "return", "nil", "if", "results", ".", "empty?", "results", "end" ]
Checks if this box is in use according to the given machine index and returns the entries that appear to be using the box. The entries returned, if any, are not tested for validity with {MachineIndex::Entry#valid?}, so the caller should do that if the caller cares. @param [MachineIndex] index @return [Array<MachineIndex::Entry>]
[ "Checks", "if", "this", "box", "is", "in", "use", "according", "to", "the", "given", "machine", "index", "and", "returns", "the", "entries", "that", "appear", "to", "be", "using", "the", "box", "." ]
c22a145c59790c098f95d50141d9afb48e1ef55f
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box.rb#L100-L116
train
hashicorp/vagrant
lib/vagrant/box.rb
Vagrant.Box.load_metadata
def load_metadata(**download_options) tf = Tempfile.new("vagrant-load-metadata") tf.close url = @metadata_url if File.file?(url) || url !~ /^[a-z0-9]+:.*$/i url = File.expand_path(url) url = Util::Platform.cygwin_windows_path(url) url = "file:#{url}" end opts = { headers: ["Accept: application/json"] }.merge(download_options) Util::Downloader.new(url, tf.path, **opts).download! BoxMetadata.new(File.open(tf.path, "r")) rescue Errors::DownloaderError => e raise Errors::BoxMetadataDownloadError, message: e.extra_data[:message] ensure tf.unlink if tf end
ruby
def load_metadata(**download_options) tf = Tempfile.new("vagrant-load-metadata") tf.close url = @metadata_url if File.file?(url) || url !~ /^[a-z0-9]+:.*$/i url = File.expand_path(url) url = Util::Platform.cygwin_windows_path(url) url = "file:#{url}" end opts = { headers: ["Accept: application/json"] }.merge(download_options) Util::Downloader.new(url, tf.path, **opts).download! BoxMetadata.new(File.open(tf.path, "r")) rescue Errors::DownloaderError => e raise Errors::BoxMetadataDownloadError, message: e.extra_data[:message] ensure tf.unlink if tf end
[ "def", "load_metadata", "(", "**", "download_options", ")", "tf", "=", "Tempfile", ".", "new", "(", "\"vagrant-load-metadata\"", ")", "tf", ".", "close", "url", "=", "@metadata_url", "if", "File", ".", "file?", "(", "url", ")", "||", "url", "!~", "/", "/i", "url", "=", "File", ".", "expand_path", "(", "url", ")", "url", "=", "Util", "::", "Platform", ".", "cygwin_windows_path", "(", "url", ")", "url", "=", "\"file:#{url}\"", "end", "opts", "=", "{", "headers", ":", "[", "\"Accept: application/json\"", "]", "}", ".", "merge", "(", "download_options", ")", "Util", "::", "Downloader", ".", "new", "(", "url", ",", "tf", ".", "path", ",", "**", "opts", ")", ".", "download!", "BoxMetadata", ".", "new", "(", "File", ".", "open", "(", "tf", ".", "path", ",", "\"r\"", ")", ")", "rescue", "Errors", "::", "DownloaderError", "=>", "e", "raise", "Errors", "::", "BoxMetadataDownloadError", ",", "message", ":", "e", ".", "extra_data", "[", ":message", "]", "ensure", "tf", ".", "unlink", "if", "tf", "end" ]
Loads the metadata URL and returns the latest metadata associated with this box. @param [Hash] download_options Options to pass to the downloader. @return [BoxMetadata]
[ "Loads", "the", "metadata", "URL", "and", "returns", "the", "latest", "metadata", "associated", "with", "this", "box", "." ]
c22a145c59790c098f95d50141d9afb48e1ef55f
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box.rb#L123-L142
train
hashicorp/vagrant
lib/vagrant/box.rb
Vagrant.Box.has_update?
def has_update?(version=nil, download_options: {}) if !@metadata_url raise Errors::BoxUpdateNoMetadata, name: @name end if download_options.delete(:automatic_check) && !automatic_update_check_allowed? @logger.info("Skipping box update check") return end version += ", " if version version ||= "" version += "> #{@version}" md = self.load_metadata(download_options) newer = md.version(version, provider: @provider) return nil if !newer [md, newer, newer.provider(@provider)] end
ruby
def has_update?(version=nil, download_options: {}) if !@metadata_url raise Errors::BoxUpdateNoMetadata, name: @name end if download_options.delete(:automatic_check) && !automatic_update_check_allowed? @logger.info("Skipping box update check") return end version += ", " if version version ||= "" version += "> #{@version}" md = self.load_metadata(download_options) newer = md.version(version, provider: @provider) return nil if !newer [md, newer, newer.provider(@provider)] end
[ "def", "has_update?", "(", "version", "=", "nil", ",", "download_options", ":", "{", "}", ")", "if", "!", "@metadata_url", "raise", "Errors", "::", "BoxUpdateNoMetadata", ",", "name", ":", "@name", "end", "if", "download_options", ".", "delete", "(", ":automatic_check", ")", "&&", "!", "automatic_update_check_allowed?", "@logger", ".", "info", "(", "\"Skipping box update check\"", ")", "return", "end", "version", "+=", "\", \"", "if", "version", "version", "||=", "\"\"", "version", "+=", "\"> #{@version}\"", "md", "=", "self", ".", "load_metadata", "(", "download_options", ")", "newer", "=", "md", ".", "version", "(", "version", ",", "provider", ":", "@provider", ")", "return", "nil", "if", "!", "newer", "[", "md", ",", "newer", ",", "newer", ".", "provider", "(", "@provider", ")", "]", "end" ]
Checks if the box has an update and returns the metadata, version, and provider. If the box doesn't have an update that satisfies the constraints, it will return nil. This will potentially make a network call if it has to load the metadata from the network. @param [String] version Version constraints the update must satisfy. If nil, the version constrain defaults to being a larger version than this box. @return [Array]
[ "Checks", "if", "the", "box", "has", "an", "update", "and", "returns", "the", "metadata", "version", "and", "provider", ".", "If", "the", "box", "doesn", "t", "have", "an", "update", "that", "satisfies", "the", "constraints", "it", "will", "return", "nil", "." ]
c22a145c59790c098f95d50141d9afb48e1ef55f
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box.rb#L155-L173
train
hashicorp/vagrant
lib/vagrant/box.rb
Vagrant.Box.automatic_update_check_allowed?
def automatic_update_check_allowed? check_path = directory.join("box_update_check") if check_path.exist? last_check_span = Time.now.to_i - check_path.mtime.to_i if last_check_span < BOX_UPDATE_CHECK_INTERVAL @logger.info("box update check is under the interval threshold") return false end end FileUtils.touch(check_path) true end
ruby
def automatic_update_check_allowed? check_path = directory.join("box_update_check") if check_path.exist? last_check_span = Time.now.to_i - check_path.mtime.to_i if last_check_span < BOX_UPDATE_CHECK_INTERVAL @logger.info("box update check is under the interval threshold") return false end end FileUtils.touch(check_path) true end
[ "def", "automatic_update_check_allowed?", "check_path", "=", "directory", ".", "join", "(", "\"box_update_check\"", ")", "if", "check_path", ".", "exist?", "last_check_span", "=", "Time", ".", "now", ".", "to_i", "-", "check_path", ".", "mtime", ".", "to_i", "if", "last_check_span", "<", "BOX_UPDATE_CHECK_INTERVAL", "@logger", ".", "info", "(", "\"box update check is under the interval threshold\"", ")", "return", "false", "end", "end", "FileUtils", ".", "touch", "(", "check_path", ")", "true", "end" ]
Check if a box update check is allowed. Uses a file in the box data directory to track when the last auto update check was performed and returns true if the BOX_UPDATE_CHECK_INTERVAL has passed. @return [Boolean]
[ "Check", "if", "a", "box", "update", "check", "is", "allowed", ".", "Uses", "a", "file", "in", "the", "box", "data", "directory", "to", "track", "when", "the", "last", "auto", "update", "check", "was", "performed", "and", "returns", "true", "if", "the", "BOX_UPDATE_CHECK_INTERVAL", "has", "passed", "." ]
c22a145c59790c098f95d50141d9afb48e1ef55f
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box.rb#L181-L192
train
hashicorp/vagrant
lib/vagrant/box.rb
Vagrant.Box.repackage
def repackage(path) @logger.debug("Repackaging box '#{@name}' to: #{path}") Util::SafeChdir.safe_chdir(@directory) do # Find all the files in our current directory and tar it up! files = Dir.glob(File.join(".", "**", "*")).select { |f| File.file?(f) } # Package! Util::Subprocess.execute("bsdtar", "-czf", path.to_s, *files) end @logger.info("Repackaged box '#{@name}' successfully: #{path}") true end
ruby
def repackage(path) @logger.debug("Repackaging box '#{@name}' to: #{path}") Util::SafeChdir.safe_chdir(@directory) do # Find all the files in our current directory and tar it up! files = Dir.glob(File.join(".", "**", "*")).select { |f| File.file?(f) } # Package! Util::Subprocess.execute("bsdtar", "-czf", path.to_s, *files) end @logger.info("Repackaged box '#{@name}' successfully: #{path}") true end
[ "def", "repackage", "(", "path", ")", "@logger", ".", "debug", "(", "\"Repackaging box '#{@name}' to: #{path}\"", ")", "Util", "::", "SafeChdir", ".", "safe_chdir", "(", "@directory", ")", "do", "files", "=", "Dir", ".", "glob", "(", "File", ".", "join", "(", "\".\"", ",", "\"**\"", ",", "\"*\"", ")", ")", ".", "select", "{", "|", "f", "|", "File", ".", "file?", "(", "f", ")", "}", "Util", "::", "Subprocess", ".", "execute", "(", "\"bsdtar\"", ",", "\"-czf\"", ",", "path", ".", "to_s", ",", "*", "files", ")", "end", "@logger", ".", "info", "(", "\"Repackaged box '#{@name}' successfully: #{path}\"", ")", "true", "end" ]
This repackages this box and outputs it to the given path. @param [Pathname] path The full path (filename included) of where to output this box. @return [Boolean] true if this succeeds.
[ "This", "repackages", "this", "box", "and", "outputs", "it", "to", "the", "given", "path", "." ]
c22a145c59790c098f95d50141d9afb48e1ef55f
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box.rb#L199-L213
train
hashicorp/vagrant
lib/vagrant/alias.rb
Vagrant.Alias.interpret
def interpret(line) # is it a comment? return nil if line.strip.start_with?("#") keyword, command = line.split("=", 2).collect(&:strip) # validate the keyword if keyword.match(/\s/i) raise Errors::AliasInvalidError, alias: line, message: "Alias keywords must not contain any whitespace." end [keyword, command] end
ruby
def interpret(line) # is it a comment? return nil if line.strip.start_with?("#") keyword, command = line.split("=", 2).collect(&:strip) # validate the keyword if keyword.match(/\s/i) raise Errors::AliasInvalidError, alias: line, message: "Alias keywords must not contain any whitespace." end [keyword, command] end
[ "def", "interpret", "(", "line", ")", "return", "nil", "if", "line", ".", "strip", ".", "start_with?", "(", "\"#\"", ")", "keyword", ",", "command", "=", "line", ".", "split", "(", "\"=\"", ",", "2", ")", ".", "collect", "(", "&", ":strip", ")", "if", "keyword", ".", "match", "(", "/", "\\s", "/i", ")", "raise", "Errors", "::", "AliasInvalidError", ",", "alias", ":", "line", ",", "message", ":", "\"Alias keywords must not contain any whitespace.\"", "end", "[", "keyword", ",", "command", "]", "end" ]
This interprets a raw line from the aliases file.
[ "This", "interprets", "a", "raw", "line", "from", "the", "aliases", "file", "." ]
c22a145c59790c098f95d50141d9afb48e1ef55f
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/alias.rb#L28-L40
train
hashicorp/vagrant
lib/vagrant/alias.rb
Vagrant.Alias.register
def register(keyword, command) @aliases.register(keyword.to_sym) do lambda do |args| # directly execute shell commands if command.start_with?("!") return Util::SafeExec.exec "#{command[1..-1]} #{args.join(" ")}".strip end return CLI.new(command.split.concat(args), @env).execute end end end
ruby
def register(keyword, command) @aliases.register(keyword.to_sym) do lambda do |args| # directly execute shell commands if command.start_with?("!") return Util::SafeExec.exec "#{command[1..-1]} #{args.join(" ")}".strip end return CLI.new(command.split.concat(args), @env).execute end end end
[ "def", "register", "(", "keyword", ",", "command", ")", "@aliases", ".", "register", "(", "keyword", ".", "to_sym", ")", "do", "lambda", "do", "|", "args", "|", "if", "command", ".", "start_with?", "(", "\"!\"", ")", "return", "Util", "::", "SafeExec", ".", "exec", "\"#{command[1..-1]} #{args.join(\" \")}\"", ".", "strip", "end", "return", "CLI", ".", "new", "(", "command", ".", "split", ".", "concat", "(", "args", ")", ",", "@env", ")", ".", "execute", "end", "end", "end" ]
This registers an alias.
[ "This", "registers", "an", "alias", "." ]
c22a145c59790c098f95d50141d9afb48e1ef55f
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/alias.rb#L43-L54
train
github/linguist
samples/Ruby/sinatra.rb
Sinatra.Helpers.redirect
def redirect(uri, *args) if env['HTTP_VERSION'] == 'HTTP/1.1' and env["REQUEST_METHOD"] != 'GET' status 303 else status 302 end # According to RFC 2616 section 14.30, "the field value consists of a # single absolute URI" response['Location'] = uri(uri, settings.absolute_redirects?, settings.prefixed_redirects?) halt(*args) end
ruby
def redirect(uri, *args) if env['HTTP_VERSION'] == 'HTTP/1.1' and env["REQUEST_METHOD"] != 'GET' status 303 else status 302 end # According to RFC 2616 section 14.30, "the field value consists of a # single absolute URI" response['Location'] = uri(uri, settings.absolute_redirects?, settings.prefixed_redirects?) halt(*args) end
[ "def", "redirect", "(", "uri", ",", "*", "args", ")", "if", "env", "[", "'HTTP_VERSION'", "]", "==", "'HTTP/1.1'", "and", "env", "[", "\"REQUEST_METHOD\"", "]", "!=", "'GET'", "status", "303", "else", "status", "302", "end", "response", "[", "'Location'", "]", "=", "uri", "(", "uri", ",", "settings", ".", "absolute_redirects?", ",", "settings", ".", "prefixed_redirects?", ")", "halt", "(", "*", "args", ")", "end" ]
Halt processing and redirect to the URI provided.
[ "Halt", "processing", "and", "redirect", "to", "the", "URI", "provided", "." ]
9116c90fcbb82ac03b4b33c58cfbde1fcf745e99
https://github.com/github/linguist/blob/9116c90fcbb82ac03b4b33c58cfbde1fcf745e99/samples/Ruby/sinatra.rb#L167-L178
train
github/linguist
samples/Ruby/sinatra.rb
Sinatra.Helpers.uri
def uri(addr = nil, absolute = true, add_script_name = true) return addr if addr =~ /\A[A-z][A-z0-9\+\.\-]*:/ uri = [host = ""] if absolute host << "http#{'s' if request.secure?}://" if request.forwarded? or request.port != (request.secure? ? 443 : 80) host << request.host_with_port else host << request.host end end uri << request.script_name.to_s if add_script_name uri << (addr ? addr : request.path_info).to_s File.join uri end
ruby
def uri(addr = nil, absolute = true, add_script_name = true) return addr if addr =~ /\A[A-z][A-z0-9\+\.\-]*:/ uri = [host = ""] if absolute host << "http#{'s' if request.secure?}://" if request.forwarded? or request.port != (request.secure? ? 443 : 80) host << request.host_with_port else host << request.host end end uri << request.script_name.to_s if add_script_name uri << (addr ? addr : request.path_info).to_s File.join uri end
[ "def", "uri", "(", "addr", "=", "nil", ",", "absolute", "=", "true", ",", "add_script_name", "=", "true", ")", "return", "addr", "if", "addr", "=~", "/", "\\A", "\\+", "\\.", "\\-", "/", "uri", "=", "[", "host", "=", "\"\"", "]", "if", "absolute", "host", "<<", "\"http#{'s' if request.secure?}://\"", "if", "request", ".", "forwarded?", "or", "request", ".", "port", "!=", "(", "request", ".", "secure?", "?", "443", ":", "80", ")", "host", "<<", "request", ".", "host_with_port", "else", "host", "<<", "request", ".", "host", "end", "end", "uri", "<<", "request", ".", "script_name", ".", "to_s", "if", "add_script_name", "uri", "<<", "(", "addr", "?", "addr", ":", "request", ".", "path_info", ")", ".", "to_s", "File", ".", "join", "uri", "end" ]
Generates the absolute URI for a given path in the app. Takes Rack routers and reverse proxies into account.
[ "Generates", "the", "absolute", "URI", "for", "a", "given", "path", "in", "the", "app", ".", "Takes", "Rack", "routers", "and", "reverse", "proxies", "into", "account", "." ]
9116c90fcbb82ac03b4b33c58cfbde1fcf745e99
https://github.com/github/linguist/blob/9116c90fcbb82ac03b4b33c58cfbde1fcf745e99/samples/Ruby/sinatra.rb#L182-L196
train
github/linguist
samples/Ruby/sinatra.rb
Sinatra.Helpers.content_type
def content_type(type = nil, params={}) return response['Content-Type'] unless type default = params.delete :default mime_type = mime_type(type) || default fail "Unknown media type: %p" % type if mime_type.nil? mime_type = mime_type.dup unless params.include? :charset or settings.add_charset.all? { |p| not p === mime_type } params[:charset] = params.delete('charset') || settings.default_encoding end params.delete :charset if mime_type.include? 'charset' unless params.empty? mime_type << (mime_type.include?(';') ? ', ' : ';') mime_type << params.map { |kv| kv.join('=') }.join(', ') end response['Content-Type'] = mime_type end
ruby
def content_type(type = nil, params={}) return response['Content-Type'] unless type default = params.delete :default mime_type = mime_type(type) || default fail "Unknown media type: %p" % type if mime_type.nil? mime_type = mime_type.dup unless params.include? :charset or settings.add_charset.all? { |p| not p === mime_type } params[:charset] = params.delete('charset') || settings.default_encoding end params.delete :charset if mime_type.include? 'charset' unless params.empty? mime_type << (mime_type.include?(';') ? ', ' : ';') mime_type << params.map { |kv| kv.join('=') }.join(', ') end response['Content-Type'] = mime_type end
[ "def", "content_type", "(", "type", "=", "nil", ",", "params", "=", "{", "}", ")", "return", "response", "[", "'Content-Type'", "]", "unless", "type", "default", "=", "params", ".", "delete", ":default", "mime_type", "=", "mime_type", "(", "type", ")", "||", "default", "fail", "\"Unknown media type: %p\"", "%", "type", "if", "mime_type", ".", "nil?", "mime_type", "=", "mime_type", ".", "dup", "unless", "params", ".", "include?", ":charset", "or", "settings", ".", "add_charset", ".", "all?", "{", "|", "p", "|", "not", "p", "===", "mime_type", "}", "params", "[", ":charset", "]", "=", "params", ".", "delete", "(", "'charset'", ")", "||", "settings", ".", "default_encoding", "end", "params", ".", "delete", ":charset", "if", "mime_type", ".", "include?", "'charset'", "unless", "params", ".", "empty?", "mime_type", "<<", "(", "mime_type", ".", "include?", "(", "';'", ")", "?", "', '", ":", "';'", ")", "mime_type", "<<", "params", ".", "map", "{", "|", "kv", "|", "kv", ".", "join", "(", "'='", ")", "}", ".", "join", "(", "', '", ")", "end", "response", "[", "'Content-Type'", "]", "=", "mime_type", "end" ]
Set the Content-Type of the response body given a media type or file extension.
[ "Set", "the", "Content", "-", "Type", "of", "the", "response", "body", "given", "a", "media", "type", "or", "file", "extension", "." ]
9116c90fcbb82ac03b4b33c58cfbde1fcf745e99
https://github.com/github/linguist/blob/9116c90fcbb82ac03b4b33c58cfbde1fcf745e99/samples/Ruby/sinatra.rb#L236-L251
train
github/linguist
samples/Ruby/sinatra.rb
Sinatra.Helpers.stream
def stream(keep_open = false) scheduler = env['async.callback'] ? EventMachine : Stream current = @params.dup body Stream.new(scheduler, keep_open) { |out| with_params(current) { yield(out) } } end
ruby
def stream(keep_open = false) scheduler = env['async.callback'] ? EventMachine : Stream current = @params.dup body Stream.new(scheduler, keep_open) { |out| with_params(current) { yield(out) } } end
[ "def", "stream", "(", "keep_open", "=", "false", ")", "scheduler", "=", "env", "[", "'async.callback'", "]", "?", "EventMachine", ":", "Stream", "current", "=", "@params", ".", "dup", "body", "Stream", ".", "new", "(", "scheduler", ",", "keep_open", ")", "{", "|", "out", "|", "with_params", "(", "current", ")", "{", "yield", "(", "out", ")", "}", "}", "end" ]
Allows to start sending data to the client even though later parts of the response body have not yet been generated. The close parameter specifies whether Stream#close should be called after the block has been executed. This is only relevant for evented servers like Thin or Rainbows.
[ "Allows", "to", "start", "sending", "data", "to", "the", "client", "even", "though", "later", "parts", "of", "the", "response", "body", "have", "not", "yet", "been", "generated", "." ]
9116c90fcbb82ac03b4b33c58cfbde1fcf745e99
https://github.com/github/linguist/blob/9116c90fcbb82ac03b4b33c58cfbde1fcf745e99/samples/Ruby/sinatra.rb#L343-L347
train
github/linguist
samples/Ruby/sinatra.rb
Sinatra.Helpers.etag_matches?
def etag_matches?(list, new_resource = request.post?) return !new_resource if list == '*' list.to_s.split(/\s*,\s*/).include? response['ETag'] end
ruby
def etag_matches?(list, new_resource = request.post?) return !new_resource if list == '*' list.to_s.split(/\s*,\s*/).include? response['ETag'] end
[ "def", "etag_matches?", "(", "list", ",", "new_resource", "=", "request", ".", "post?", ")", "return", "!", "new_resource", "if", "list", "==", "'*'", "list", ".", "to_s", ".", "split", "(", "/", "\\s", "\\s", "/", ")", ".", "include?", "response", "[", "'ETag'", "]", "end" ]
Helper method checking if a ETag value list includes the current ETag.
[ "Helper", "method", "checking", "if", "a", "ETag", "value", "list", "includes", "the", "current", "ETag", "." ]
9116c90fcbb82ac03b4b33c58cfbde1fcf745e99
https://github.com/github/linguist/blob/9116c90fcbb82ac03b4b33c58cfbde1fcf745e99/samples/Ruby/sinatra.rb#L529-L532
train
github/linguist
samples/Ruby/sinatra.rb
Sinatra.Templates.render_ruby
def render_ruby(engine, template, options={}, locals={}, &block) options, template = template, nil if template.is_a?(Hash) template = Proc.new { block } if template.nil? render engine, template, options, locals end
ruby
def render_ruby(engine, template, options={}, locals={}, &block) options, template = template, nil if template.is_a?(Hash) template = Proc.new { block } if template.nil? render engine, template, options, locals end
[ "def", "render_ruby", "(", "engine", ",", "template", ",", "options", "=", "{", "}", ",", "locals", "=", "{", "}", ",", "&", "block", ")", "options", ",", "template", "=", "template", ",", "nil", "if", "template", ".", "is_a?", "(", "Hash", ")", "template", "=", "Proc", ".", "new", "{", "block", "}", "if", "template", ".", "nil?", "render", "engine", ",", "template", ",", "options", ",", "locals", "end" ]
logic shared between builder and nokogiri
[ "logic", "shared", "between", "builder", "and", "nokogiri" ]
9116c90fcbb82ac03b4b33c58cfbde1fcf745e99
https://github.com/github/linguist/blob/9116c90fcbb82ac03b4b33c58cfbde1fcf745e99/samples/Ruby/sinatra.rb#L665-L669
train
github/linguist
samples/Ruby/sinatra.rb
Sinatra.Base.filter!
def filter!(type, base = settings) filter! type, base.superclass if base.superclass.respond_to?(:filters) base.filters[type].each { |args| process_route(*args) } end
ruby
def filter!(type, base = settings) filter! type, base.superclass if base.superclass.respond_to?(:filters) base.filters[type].each { |args| process_route(*args) } end
[ "def", "filter!", "(", "type", ",", "base", "=", "settings", ")", "filter!", "type", ",", "base", ".", "superclass", "if", "base", ".", "superclass", ".", "respond_to?", "(", ":filters", ")", "base", ".", "filters", "[", "type", "]", ".", "each", "{", "|", "args", "|", "process_route", "(", "*", "args", ")", "}", "end" ]
Run filters defined on the class and all superclasses.
[ "Run", "filters", "defined", "on", "the", "class", "and", "all", "superclasses", "." ]
9116c90fcbb82ac03b4b33c58cfbde1fcf745e99
https://github.com/github/linguist/blob/9116c90fcbb82ac03b4b33c58cfbde1fcf745e99/samples/Ruby/sinatra.rb#L831-L834
train
github/linguist
samples/Ruby/sinatra.rb
Sinatra.Base.route!
def route!(base = settings, pass_block=nil) if routes = base.routes[@request.request_method] routes.each do |pattern, keys, conditions, block| pass_block = process_route(pattern, keys, conditions) do |*args| route_eval { block[*args] } end end end # Run routes defined in superclass. if base.superclass.respond_to?(:routes) return route!(base.superclass, pass_block) end route_eval(&pass_block) if pass_block route_missing end
ruby
def route!(base = settings, pass_block=nil) if routes = base.routes[@request.request_method] routes.each do |pattern, keys, conditions, block| pass_block = process_route(pattern, keys, conditions) do |*args| route_eval { block[*args] } end end end # Run routes defined in superclass. if base.superclass.respond_to?(:routes) return route!(base.superclass, pass_block) end route_eval(&pass_block) if pass_block route_missing end
[ "def", "route!", "(", "base", "=", "settings", ",", "pass_block", "=", "nil", ")", "if", "routes", "=", "base", ".", "routes", "[", "@request", ".", "request_method", "]", "routes", ".", "each", "do", "|", "pattern", ",", "keys", ",", "conditions", ",", "block", "|", "pass_block", "=", "process_route", "(", "pattern", ",", "keys", ",", "conditions", ")", "do", "|", "*", "args", "|", "route_eval", "{", "block", "[", "*", "args", "]", "}", "end", "end", "end", "if", "base", ".", "superclass", ".", "respond_to?", "(", ":routes", ")", "return", "route!", "(", "base", ".", "superclass", ",", "pass_block", ")", "end", "route_eval", "(", "&", "pass_block", ")", "if", "pass_block", "route_missing", "end" ]
Run routes defined on the class and all superclasses.
[ "Run", "routes", "defined", "on", "the", "class", "and", "all", "superclasses", "." ]
9116c90fcbb82ac03b4b33c58cfbde1fcf745e99
https://github.com/github/linguist/blob/9116c90fcbb82ac03b4b33c58cfbde1fcf745e99/samples/Ruby/sinatra.rb#L837-L853
train
github/linguist
samples/Ruby/sinatra.rb
Sinatra.Base.indifferent_hash
def indifferent_hash Hash.new {|hash,key| hash[key.to_s] if Symbol === key } end
ruby
def indifferent_hash Hash.new {|hash,key| hash[key.to_s] if Symbol === key } end
[ "def", "indifferent_hash", "Hash", ".", "new", "{", "|", "hash", ",", "key", "|", "hash", "[", "key", ".", "to_s", "]", "if", "Symbol", "===", "key", "}", "end" ]
Creates a Hash with indifferent access.
[ "Creates", "a", "Hash", "with", "indifferent", "access", "." ]
9116c90fcbb82ac03b4b33c58cfbde1fcf745e99
https://github.com/github/linguist/blob/9116c90fcbb82ac03b4b33c58cfbde1fcf745e99/samples/Ruby/sinatra.rb#L926-L928
train
github/linguist
samples/Ruby/racc.rb
RJSON.Parser._reduce_22
def _reduce_22(val, _values, result) n = val[0]; result = n.count('.') > 0 ? n.to_f : n.to_i result end
ruby
def _reduce_22(val, _values, result) n = val[0]; result = n.count('.') > 0 ? n.to_f : n.to_i result end
[ "def", "_reduce_22", "(", "val", ",", "_values", ",", "result", ")", "n", "=", "val", "[", "0", "]", ";", "result", "=", "n", ".", "count", "(", "'.'", ")", ">", "0", "?", "n", ".", "to_f", ":", "n", ".", "to_i", "result", "end" ]
reduce 21 omitted
[ "reduce", "21", "omitted" ]
9116c90fcbb82ac03b4b33c58cfbde1fcf745e99
https://github.com/github/linguist/blob/9116c90fcbb82ac03b4b33c58cfbde1fcf745e99/samples/Ruby/racc.rb#L237-L240
train
fluent/fluentd
lib/fluent/supervisor.rb
Fluent.Supervisor.dry_run
def dry_run begin Fluent::Engine.dry_run_mode = true change_privilege init_engine run_configure rescue Fluent::ConfigError => e $log.error "config error", file: @config_path, error: e $log.debug_backtrace exit!(1) ensure Fluent::Engine.dry_run_mode = false end end
ruby
def dry_run begin Fluent::Engine.dry_run_mode = true change_privilege init_engine run_configure rescue Fluent::ConfigError => e $log.error "config error", file: @config_path, error: e $log.debug_backtrace exit!(1) ensure Fluent::Engine.dry_run_mode = false end end
[ "def", "dry_run", "begin", "Fluent", "::", "Engine", ".", "dry_run_mode", "=", "true", "change_privilege", "init_engine", "run_configure", "rescue", "Fluent", "::", "ConfigError", "=>", "e", "$log", ".", "error", "\"config error\"", ",", "file", ":", "@config_path", ",", "error", ":", "e", "$log", ".", "debug_backtrace", "exit!", "(", "1", ")", "ensure", "Fluent", "::", "Engine", ".", "dry_run_mode", "=", "false", "end", "end" ]
Set Engine's dry_run_mode true to override all target_id of worker sections
[ "Set", "Engine", "s", "dry_run_mode", "true", "to", "override", "all", "target_id", "of", "worker", "sections" ]
add2af9a5b7f74fc36957b8e6138b3c5a2871a92
https://github.com/fluent/fluentd/blob/add2af9a5b7f74fc36957b8e6138b3c5a2871a92/lib/fluent/supervisor.rb#L574-L587
train
fluent/fluentd
lib/fluent/event.rb
Fluent.MessagePackEventStream.slice
def slice(index, num) ensure_unpacked! MultiEventStream.new(@unpacked_times.slice(index, num), @unpacked_records.slice(index, num)) end
ruby
def slice(index, num) ensure_unpacked! MultiEventStream.new(@unpacked_times.slice(index, num), @unpacked_records.slice(index, num)) end
[ "def", "slice", "(", "index", ",", "num", ")", "ensure_unpacked!", "MultiEventStream", ".", "new", "(", "@unpacked_times", ".", "slice", "(", "index", ",", "num", ")", ",", "@unpacked_records", ".", "slice", "(", "index", ",", "num", ")", ")", "end" ]
This method returns MultiEventStream, because there are no reason to surve binary serialized by msgpack.
[ "This", "method", "returns", "MultiEventStream", "because", "there", "are", "no", "reason", "to", "surve", "binary", "serialized", "by", "msgpack", "." ]
add2af9a5b7f74fc36957b8e6138b3c5a2871a92
https://github.com/fluent/fluentd/blob/add2af9a5b7f74fc36957b8e6138b3c5a2871a92/lib/fluent/event.rb#L248-L251
train
fluent/fluentd
lib/fluent/plugin/out_forward.rb
Fluent::Plugin.ForwardOutput.read_ack_from_sock
def read_ack_from_sock(sock, unpacker) begin raw_data = sock.instance_of?(Fluent::PluginHelper::Socket::WrappedSocket::TLS) ? sock.readpartial(@read_length) : sock.recv(@read_length) rescue Errno::ECONNRESET, EOFError # ECONNRESET for #recv, #EOFError for #readpartial raw_data = "" end info = @sock_ack_waiting_mutex.synchronize{ @sock_ack_waiting.find{|i| i.sock == sock } } # When connection is closed by remote host, socket is ready to read and #recv returns an empty string that means EOF. # If this happens we assume the data wasn't delivered and retry it. if raw_data.empty? log.warn "destination node closed the connection. regard it as unavailable.", host: info.node.host, port: info.node.port info.node.disable! rollback_write(info.chunk_id, update_retry: false) return nil else unpacker.feed(raw_data) res = unpacker.read log.trace "getting response from destination", host: info.node.host, port: info.node.port, chunk_id: dump_unique_id_hex(info.chunk_id), response: res if res['ack'] != info.chunk_id_base64 # Some errors may have occurred when ack and chunk id is different, so send the chunk again. log.warn "ack in response and chunk id in sent data are different", chunk_id: dump_unique_id_hex(info.chunk_id), ack: res['ack'] rollback_write(info.chunk_id, update_retry: false) return nil else log.trace "got a correct ack response", chunk_id: dump_unique_id_hex(info.chunk_id) end return info.chunk_id end rescue => e log.error "unexpected error while receiving ack message", error: e log.error_backtrace ensure info.sock.close_write rescue nil info.sock.close rescue nil @sock_ack_waiting_mutex.synchronize do @sock_ack_waiting.delete(info) end end
ruby
def read_ack_from_sock(sock, unpacker) begin raw_data = sock.instance_of?(Fluent::PluginHelper::Socket::WrappedSocket::TLS) ? sock.readpartial(@read_length) : sock.recv(@read_length) rescue Errno::ECONNRESET, EOFError # ECONNRESET for #recv, #EOFError for #readpartial raw_data = "" end info = @sock_ack_waiting_mutex.synchronize{ @sock_ack_waiting.find{|i| i.sock == sock } } # When connection is closed by remote host, socket is ready to read and #recv returns an empty string that means EOF. # If this happens we assume the data wasn't delivered and retry it. if raw_data.empty? log.warn "destination node closed the connection. regard it as unavailable.", host: info.node.host, port: info.node.port info.node.disable! rollback_write(info.chunk_id, update_retry: false) return nil else unpacker.feed(raw_data) res = unpacker.read log.trace "getting response from destination", host: info.node.host, port: info.node.port, chunk_id: dump_unique_id_hex(info.chunk_id), response: res if res['ack'] != info.chunk_id_base64 # Some errors may have occurred when ack and chunk id is different, so send the chunk again. log.warn "ack in response and chunk id in sent data are different", chunk_id: dump_unique_id_hex(info.chunk_id), ack: res['ack'] rollback_write(info.chunk_id, update_retry: false) return nil else log.trace "got a correct ack response", chunk_id: dump_unique_id_hex(info.chunk_id) end return info.chunk_id end rescue => e log.error "unexpected error while receiving ack message", error: e log.error_backtrace ensure info.sock.close_write rescue nil info.sock.close rescue nil @sock_ack_waiting_mutex.synchronize do @sock_ack_waiting.delete(info) end end
[ "def", "read_ack_from_sock", "(", "sock", ",", "unpacker", ")", "begin", "raw_data", "=", "sock", ".", "instance_of?", "(", "Fluent", "::", "PluginHelper", "::", "Socket", "::", "WrappedSocket", "::", "TLS", ")", "?", "sock", ".", "readpartial", "(", "@read_length", ")", ":", "sock", ".", "recv", "(", "@read_length", ")", "rescue", "Errno", "::", "ECONNRESET", ",", "EOFError", "raw_data", "=", "\"\"", "end", "info", "=", "@sock_ack_waiting_mutex", ".", "synchronize", "{", "@sock_ack_waiting", ".", "find", "{", "|", "i", "|", "i", ".", "sock", "==", "sock", "}", "}", "if", "raw_data", ".", "empty?", "log", ".", "warn", "\"destination node closed the connection. regard it as unavailable.\"", ",", "host", ":", "info", ".", "node", ".", "host", ",", "port", ":", "info", ".", "node", ".", "port", "info", ".", "node", ".", "disable!", "rollback_write", "(", "info", ".", "chunk_id", ",", "update_retry", ":", "false", ")", "return", "nil", "else", "unpacker", ".", "feed", "(", "raw_data", ")", "res", "=", "unpacker", ".", "read", "log", ".", "trace", "\"getting response from destination\"", ",", "host", ":", "info", ".", "node", ".", "host", ",", "port", ":", "info", ".", "node", ".", "port", ",", "chunk_id", ":", "dump_unique_id_hex", "(", "info", ".", "chunk_id", ")", ",", "response", ":", "res", "if", "res", "[", "'ack'", "]", "!=", "info", ".", "chunk_id_base64", "log", ".", "warn", "\"ack in response and chunk id in sent data are different\"", ",", "chunk_id", ":", "dump_unique_id_hex", "(", "info", ".", "chunk_id", ")", ",", "ack", ":", "res", "[", "'ack'", "]", "rollback_write", "(", "info", ".", "chunk_id", ",", "update_retry", ":", "false", ")", "return", "nil", "else", "log", ".", "trace", "\"got a correct ack response\"", ",", "chunk_id", ":", "dump_unique_id_hex", "(", "info", ".", "chunk_id", ")", "end", "return", "info", ".", "chunk_id", "end", "rescue", "=>", "e", "log", ".", "error", "\"unexpected error while receiving ack message\"", ",", "error", ":", "e", "log", ".", "error_backtrace", "ensure", "info", ".", "sock", ".", "close_write", "rescue", "nil", "info", ".", "sock", ".", "close", "rescue", "nil", "@sock_ack_waiting_mutex", ".", "synchronize", "do", "@sock_ack_waiting", ".", "delete", "(", "info", ")", "end", "end" ]
return chunk id to be committed
[ "return", "chunk", "id", "to", "be", "committed" ]
add2af9a5b7f74fc36957b8e6138b3c5a2871a92
https://github.com/fluent/fluentd/blob/add2af9a5b7f74fc36957b8e6138b3c5a2871a92/lib/fluent/plugin/out_forward.rb#L457-L495
train
fluent/fluentd
lib/fluent/time.rb
Fluent.NumericTimeParser.parse_unixtime
def parse_unixtime(value) unless value.is_a?(String) || value.is_a?(Numeric) raise TimeParseError, "value must be a string or a number: #{value}(value.class)" end if @cache1_key == value return @cache1_time elsif @cache2_key == value return @cache2_time end begin time = Fluent::EventTime.new(value.to_i) rescue => e raise TimeParseError, "invalid time format: value = #{value}, error_class = #{e.class.name}, error = #{e.message}" end @cache1_key = @cache2_key @cache1_time = @cache2_time @cache2_key = value @cache2_time = time time end
ruby
def parse_unixtime(value) unless value.is_a?(String) || value.is_a?(Numeric) raise TimeParseError, "value must be a string or a number: #{value}(value.class)" end if @cache1_key == value return @cache1_time elsif @cache2_key == value return @cache2_time end begin time = Fluent::EventTime.new(value.to_i) rescue => e raise TimeParseError, "invalid time format: value = #{value}, error_class = #{e.class.name}, error = #{e.message}" end @cache1_key = @cache2_key @cache1_time = @cache2_time @cache2_key = value @cache2_time = time time end
[ "def", "parse_unixtime", "(", "value", ")", "unless", "value", ".", "is_a?", "(", "String", ")", "||", "value", ".", "is_a?", "(", "Numeric", ")", "raise", "TimeParseError", ",", "\"value must be a string or a number: #{value}(value.class)\"", "end", "if", "@cache1_key", "==", "value", "return", "@cache1_time", "elsif", "@cache2_key", "==", "value", "return", "@cache2_time", "end", "begin", "time", "=", "Fluent", "::", "EventTime", ".", "new", "(", "value", ".", "to_i", ")", "rescue", "=>", "e", "raise", "TimeParseError", ",", "\"invalid time format: value = #{value}, error_class = #{e.class.name}, error = #{e.message}\"", "end", "@cache1_key", "=", "@cache2_key", "@cache1_time", "=", "@cache2_time", "@cache2_key", "=", "value", "@cache2_time", "=", "time", "time", "end" ]
to include TimeParseError
[ "to", "include", "TimeParseError" ]
add2af9a5b7f74fc36957b8e6138b3c5a2871a92
https://github.com/fluent/fluentd/blob/add2af9a5b7f74fc36957b8e6138b3c5a2871a92/lib/fluent/time.rb#L262-L283
train
fluent/fluentd
lib/fluent/plugin/in_monitor_agent.rb
Fluent::Plugin.MonitorAgentInput.plugin_info_by_id
def plugin_info_by_id(plugin_id, opts={}) found = all_plugins.find {|pe| pe.respond_to?(:plugin_id) && pe.plugin_id.to_s == plugin_id } if found get_monitor_info(found, opts) else nil end end
ruby
def plugin_info_by_id(plugin_id, opts={}) found = all_plugins.find {|pe| pe.respond_to?(:plugin_id) && pe.plugin_id.to_s == plugin_id } if found get_monitor_info(found, opts) else nil end end
[ "def", "plugin_info_by_id", "(", "plugin_id", ",", "opts", "=", "{", "}", ")", "found", "=", "all_plugins", ".", "find", "{", "|", "pe", "|", "pe", ".", "respond_to?", "(", ":plugin_id", ")", "&&", "pe", ".", "plugin_id", ".", "to_s", "==", "plugin_id", "}", "if", "found", "get_monitor_info", "(", "found", ",", "opts", ")", "else", "nil", "end", "end" ]
search a plugin by plugin_id
[ "search", "a", "plugin", "by", "plugin_id" ]
add2af9a5b7f74fc36957b8e6138b3c5a2871a92
https://github.com/fluent/fluentd/blob/add2af9a5b7f74fc36957b8e6138b3c5a2871a92/lib/fluent/plugin/in_monitor_agent.rb#L329-L338
train
fluent/fluentd
lib/fluent/plugin/in_monitor_agent.rb
Fluent::Plugin.MonitorAgentInput.plugins_info_by_type
def plugins_info_by_type(type, opts={}) array = all_plugins.select {|pe| (pe.config['@type'] == type) rescue nil } array.map {|pe| get_monitor_info(pe, opts) } end
ruby
def plugins_info_by_type(type, opts={}) array = all_plugins.select {|pe| (pe.config['@type'] == type) rescue nil } array.map {|pe| get_monitor_info(pe, opts) } end
[ "def", "plugins_info_by_type", "(", "type", ",", "opts", "=", "{", "}", ")", "array", "=", "all_plugins", ".", "select", "{", "|", "pe", "|", "(", "pe", ".", "config", "[", "'@type'", "]", "==", "type", ")", "rescue", "nil", "}", "array", ".", "map", "{", "|", "pe", "|", "get_monitor_info", "(", "pe", ",", "opts", ")", "}", "end" ]
This method returns an array because multiple plugins could have the same type
[ "This", "method", "returns", "an", "array", "because", "multiple", "plugins", "could", "have", "the", "same", "type" ]
add2af9a5b7f74fc36957b8e6138b3c5a2871a92
https://github.com/fluent/fluentd/blob/add2af9a5b7f74fc36957b8e6138b3c5a2871a92/lib/fluent/plugin/in_monitor_agent.rb#L342-L349
train
fluent/fluentd
lib/fluent/plugin/in_monitor_agent.rb
Fluent::Plugin.MonitorAgentInput.get_monitor_info
def get_monitor_info(pe, opts={}) obj = {} # Common plugin information obj['plugin_id'] = pe.plugin_id obj['plugin_category'] = plugin_category(pe) obj['type'] = pe.config['@type'] obj['config'] = pe.config if opts[:with_config] # run MONITOR_INFO in plugins' instance context and store the info to obj MONITOR_INFO.each_pair {|key,code| begin catch(:skip) do obj[key] = pe.instance_exec(&code) end rescue NoMethodError => e unless @first_warn log.error "NoMethodError in monitoring plugins", key: key, plugin: pe.class, error: e log.error_backtrace @first_warn = true end rescue => e log.warn "unexpected error in monitoring plugins", key: key, plugin: pe.class, error: e end } obj['retry'] = get_retry_info(pe.retry) if opts[:with_retry] and pe.instance_variable_defined?(:@retry) # include all instance variables if :with_debug_info is set if opts[:with_debug_info] iv = {} pe.instance_eval do instance_variables.each {|sym| next if IGNORE_ATTRIBUTES.include?(sym) key = sym.to_s[1..-1] # removes first '@' iv[key] = instance_variable_get(sym) } end obj['instance_variables'] = iv elsif ivars = opts[:ivars] iv = {} ivars.each {|name| iname = "@#{name}" iv[name] = pe.instance_variable_get(iname) if pe.instance_variable_defined?(iname) } obj['instance_variables'] = iv end obj end
ruby
def get_monitor_info(pe, opts={}) obj = {} # Common plugin information obj['plugin_id'] = pe.plugin_id obj['plugin_category'] = plugin_category(pe) obj['type'] = pe.config['@type'] obj['config'] = pe.config if opts[:with_config] # run MONITOR_INFO in plugins' instance context and store the info to obj MONITOR_INFO.each_pair {|key,code| begin catch(:skip) do obj[key] = pe.instance_exec(&code) end rescue NoMethodError => e unless @first_warn log.error "NoMethodError in monitoring plugins", key: key, plugin: pe.class, error: e log.error_backtrace @first_warn = true end rescue => e log.warn "unexpected error in monitoring plugins", key: key, plugin: pe.class, error: e end } obj['retry'] = get_retry_info(pe.retry) if opts[:with_retry] and pe.instance_variable_defined?(:@retry) # include all instance variables if :with_debug_info is set if opts[:with_debug_info] iv = {} pe.instance_eval do instance_variables.each {|sym| next if IGNORE_ATTRIBUTES.include?(sym) key = sym.to_s[1..-1] # removes first '@' iv[key] = instance_variable_get(sym) } end obj['instance_variables'] = iv elsif ivars = opts[:ivars] iv = {} ivars.each {|name| iname = "@#{name}" iv[name] = pe.instance_variable_get(iname) if pe.instance_variable_defined?(iname) } obj['instance_variables'] = iv end obj end
[ "def", "get_monitor_info", "(", "pe", ",", "opts", "=", "{", "}", ")", "obj", "=", "{", "}", "obj", "[", "'plugin_id'", "]", "=", "pe", ".", "plugin_id", "obj", "[", "'plugin_category'", "]", "=", "plugin_category", "(", "pe", ")", "obj", "[", "'type'", "]", "=", "pe", ".", "config", "[", "'@type'", "]", "obj", "[", "'config'", "]", "=", "pe", ".", "config", "if", "opts", "[", ":with_config", "]", "MONITOR_INFO", ".", "each_pair", "{", "|", "key", ",", "code", "|", "begin", "catch", "(", ":skip", ")", "do", "obj", "[", "key", "]", "=", "pe", ".", "instance_exec", "(", "&", "code", ")", "end", "rescue", "NoMethodError", "=>", "e", "unless", "@first_warn", "log", ".", "error", "\"NoMethodError in monitoring plugins\"", ",", "key", ":", "key", ",", "plugin", ":", "pe", ".", "class", ",", "error", ":", "e", "log", ".", "error_backtrace", "@first_warn", "=", "true", "end", "rescue", "=>", "e", "log", ".", "warn", "\"unexpected error in monitoring plugins\"", ",", "key", ":", "key", ",", "plugin", ":", "pe", ".", "class", ",", "error", ":", "e", "end", "}", "obj", "[", "'retry'", "]", "=", "get_retry_info", "(", "pe", ".", "retry", ")", "if", "opts", "[", ":with_retry", "]", "and", "pe", ".", "instance_variable_defined?", "(", ":@retry", ")", "if", "opts", "[", ":with_debug_info", "]", "iv", "=", "{", "}", "pe", ".", "instance_eval", "do", "instance_variables", ".", "each", "{", "|", "sym", "|", "next", "if", "IGNORE_ATTRIBUTES", ".", "include?", "(", "sym", ")", "key", "=", "sym", ".", "to_s", "[", "1", "..", "-", "1", "]", "iv", "[", "key", "]", "=", "instance_variable_get", "(", "sym", ")", "}", "end", "obj", "[", "'instance_variables'", "]", "=", "iv", "elsif", "ivars", "=", "opts", "[", ":ivars", "]", "iv", "=", "{", "}", "ivars", ".", "each", "{", "|", "name", "|", "iname", "=", "\"@#{name}\"", "iv", "[", "name", "]", "=", "pe", ".", "instance_variable_get", "(", "iname", ")", "if", "pe", ".", "instance_variable_defined?", "(", "iname", ")", "}", "obj", "[", "'instance_variables'", "]", "=", "iv", "end", "obj", "end" ]
get monitor info from the plugin `pe` and return a hash object
[ "get", "monitor", "info", "from", "the", "plugin", "pe", "and", "return", "a", "hash", "object" ]
add2af9a5b7f74fc36957b8e6138b3c5a2871a92
https://github.com/fluent/fluentd/blob/add2af9a5b7f74fc36957b8e6138b3c5a2871a92/lib/fluent/plugin/in_monitor_agent.rb#L360-L409
train
plataformatec/devise
lib/devise/parameter_sanitizer.rb
Devise.ParameterSanitizer.sanitize
def sanitize(action) permissions = @permitted[action] if permissions.respond_to?(:call) cast_to_hash permissions.call(default_params) elsif permissions.present? cast_to_hash permit_keys(default_params, permissions) else unknown_action!(action) end end
ruby
def sanitize(action) permissions = @permitted[action] if permissions.respond_to?(:call) cast_to_hash permissions.call(default_params) elsif permissions.present? cast_to_hash permit_keys(default_params, permissions) else unknown_action!(action) end end
[ "def", "sanitize", "(", "action", ")", "permissions", "=", "@permitted", "[", "action", "]", "if", "permissions", ".", "respond_to?", "(", ":call", ")", "cast_to_hash", "permissions", ".", "call", "(", "default_params", ")", "elsif", "permissions", ".", "present?", "cast_to_hash", "permit_keys", "(", "default_params", ",", "permissions", ")", "else", "unknown_action!", "(", "action", ")", "end", "end" ]
Sanitize the parameters for a specific +action+. === Arguments * +action+ - A +Symbol+ with the action that the controller is performing, like +sign_up+, +sign_in+, etc. === Examples # Inside the `RegistrationsController#create` action. resource = build_resource(devise_parameter_sanitizer.sanitize(:sign_up)) resource.save Returns an +ActiveSupport::HashWithIndifferentAccess+ with the permitted attributes.
[ "Sanitize", "the", "parameters", "for", "a", "specific", "+", "action", "+", "." ]
07f2712a22aa05b8da61c85307b80a3bd2ed6c4c
https://github.com/plataformatec/devise/blob/07f2712a22aa05b8da61c85307b80a3bd2ed6c4c/lib/devise/parameter_sanitizer.rb#L70-L80
train
plataformatec/devise
lib/devise/parameter_sanitizer.rb
Devise.ParameterSanitizer.permit
def permit(action, keys: nil, except: nil, &block) if block_given? @permitted[action] = block end if keys.present? @permitted[action] ||= @auth_keys.dup @permitted[action].concat(keys) end if except.present? @permitted[action] ||= @auth_keys.dup @permitted[action] = @permitted[action] - except end end
ruby
def permit(action, keys: nil, except: nil, &block) if block_given? @permitted[action] = block end if keys.present? @permitted[action] ||= @auth_keys.dup @permitted[action].concat(keys) end if except.present? @permitted[action] ||= @auth_keys.dup @permitted[action] = @permitted[action] - except end end
[ "def", "permit", "(", "action", ",", "keys", ":", "nil", ",", "except", ":", "nil", ",", "&", "block", ")", "if", "block_given?", "@permitted", "[", "action", "]", "=", "block", "end", "if", "keys", ".", "present?", "@permitted", "[", "action", "]", "||=", "@auth_keys", ".", "dup", "@permitted", "[", "action", "]", ".", "concat", "(", "keys", ")", "end", "if", "except", ".", "present?", "@permitted", "[", "action", "]", "||=", "@auth_keys", ".", "dup", "@permitted", "[", "action", "]", "=", "@permitted", "[", "action", "]", "-", "except", "end", "end" ]
Add or remove new parameters to the permitted list of an +action+. === Arguments * +action+ - A +Symbol+ with the action that the controller is performing, like +sign_up+, +sign_in+, etc. * +keys:+ - An +Array+ of keys that also should be permitted. * +except:+ - An +Array+ of keys that shouldn't be permitted. * +block+ - A block that should be used to permit the action parameters instead of the +Array+ based approach. The block will be called with an +ActionController::Parameters+ instance. === Examples # Adding new parameters to be permitted in the `sign_up` action. devise_parameter_sanitizer.permit(:sign_up, keys: [:subscribe_newsletter]) # Removing the `password` parameter from the `account_update` action. devise_parameter_sanitizer.permit(:account_update, except: [:password]) # Using the block form to completely override how we permit the # parameters for the `sign_up` action. devise_parameter_sanitizer.permit(:sign_up) do |user| user.permit(:email, :password, :password_confirmation) end Returns nothing.
[ "Add", "or", "remove", "new", "parameters", "to", "the", "permitted", "list", "of", "an", "+", "action", "+", "." ]
07f2712a22aa05b8da61c85307b80a3bd2ed6c4c
https://github.com/plataformatec/devise/blob/07f2712a22aa05b8da61c85307b80a3bd2ed6c4c/lib/devise/parameter_sanitizer.rb#L110-L124
train
plataformatec/devise
lib/devise/parameter_filter.rb
Devise.ParameterFilter.stringify_params
def stringify_params(conditions) return conditions unless conditions.is_a?(Hash) conditions.each do |k, v| conditions[k] = v.to_s if param_requires_string_conversion?(v) end end
ruby
def stringify_params(conditions) return conditions unless conditions.is_a?(Hash) conditions.each do |k, v| conditions[k] = v.to_s if param_requires_string_conversion?(v) end end
[ "def", "stringify_params", "(", "conditions", ")", "return", "conditions", "unless", "conditions", ".", "is_a?", "(", "Hash", ")", "conditions", ".", "each", "do", "|", "k", ",", "v", "|", "conditions", "[", "k", "]", "=", "v", ".", "to_s", "if", "param_requires_string_conversion?", "(", "v", ")", "end", "end" ]
Force keys to be string to avoid injection on mongoid related database.
[ "Force", "keys", "to", "be", "string", "to", "avoid", "injection", "on", "mongoid", "related", "database", "." ]
07f2712a22aa05b8da61c85307b80a3bd2ed6c4c
https://github.com/plataformatec/devise/blob/07f2712a22aa05b8da61c85307b80a3bd2ed6c4c/lib/devise/parameter_filter.rb#L31-L36
train
Shopify/liquid
lib/liquid/template.rb
Liquid.Template.parse
def parse(source, options = {}) @options = options @profiling = options[:profile] @line_numbers = options[:line_numbers] || @profiling parse_context = options.is_a?(ParseContext) ? options : ParseContext.new(options) @root = Document.parse(tokenize(source), parse_context) @warnings = parse_context.warnings self end
ruby
def parse(source, options = {}) @options = options @profiling = options[:profile] @line_numbers = options[:line_numbers] || @profiling parse_context = options.is_a?(ParseContext) ? options : ParseContext.new(options) @root = Document.parse(tokenize(source), parse_context) @warnings = parse_context.warnings self end
[ "def", "parse", "(", "source", ",", "options", "=", "{", "}", ")", "@options", "=", "options", "@profiling", "=", "options", "[", ":profile", "]", "@line_numbers", "=", "options", "[", ":line_numbers", "]", "||", "@profiling", "parse_context", "=", "options", ".", "is_a?", "(", "ParseContext", ")", "?", "options", ":", "ParseContext", ".", "new", "(", "options", ")", "@root", "=", "Document", ".", "parse", "(", "tokenize", "(", "source", ")", ",", "parse_context", ")", "@warnings", "=", "parse_context", ".", "warnings", "self", "end" ]
Parse source code. Returns self for easy chaining
[ "Parse", "source", "code", ".", "Returns", "self", "for", "easy", "chaining" ]
b3b63a683f6daaea7e70f1602ee829abdf970ef3
https://github.com/Shopify/liquid/blob/b3b63a683f6daaea7e70f1602ee829abdf970ef3/lib/liquid/template.rb#L127-L135
train
Shopify/liquid
lib/liquid/template.rb
Liquid.Template.render
def render(*args) return ''.freeze if @root.nil? context = case args.first when Liquid::Context c = args.shift if @rethrow_errors c.exception_renderer = ->(e) { raise } end c when Liquid::Drop drop = args.shift drop.context = Context.new([drop, assigns], instance_assigns, registers, @rethrow_errors, @resource_limits) when Hash Context.new([args.shift, assigns], instance_assigns, registers, @rethrow_errors, @resource_limits) when nil Context.new(assigns, instance_assigns, registers, @rethrow_errors, @resource_limits) else raise ArgumentError, "Expected Hash or Liquid::Context as parameter" end case args.last when Hash options = args.pop registers.merge!(options[:registers]) if options[:registers].is_a?(Hash) apply_options_to_context(context, options) when Module, Array context.add_filters(args.pop) end # Retrying a render resets resource usage context.resource_limits.reset begin # render the nodelist. # for performance reasons we get an array back here. join will make a string out of it. result = with_profiling(context) do @root.render(context) end result.respond_to?(:join) ? result.join : result rescue Liquid::MemoryError => e context.handle_error(e) ensure @errors = context.errors end end
ruby
def render(*args) return ''.freeze if @root.nil? context = case args.first when Liquid::Context c = args.shift if @rethrow_errors c.exception_renderer = ->(e) { raise } end c when Liquid::Drop drop = args.shift drop.context = Context.new([drop, assigns], instance_assigns, registers, @rethrow_errors, @resource_limits) when Hash Context.new([args.shift, assigns], instance_assigns, registers, @rethrow_errors, @resource_limits) when nil Context.new(assigns, instance_assigns, registers, @rethrow_errors, @resource_limits) else raise ArgumentError, "Expected Hash or Liquid::Context as parameter" end case args.last when Hash options = args.pop registers.merge!(options[:registers]) if options[:registers].is_a?(Hash) apply_options_to_context(context, options) when Module, Array context.add_filters(args.pop) end # Retrying a render resets resource usage context.resource_limits.reset begin # render the nodelist. # for performance reasons we get an array back here. join will make a string out of it. result = with_profiling(context) do @root.render(context) end result.respond_to?(:join) ? result.join : result rescue Liquid::MemoryError => e context.handle_error(e) ensure @errors = context.errors end end
[ "def", "render", "(", "*", "args", ")", "return", "''", ".", "freeze", "if", "@root", ".", "nil?", "context", "=", "case", "args", ".", "first", "when", "Liquid", "::", "Context", "c", "=", "args", ".", "shift", "if", "@rethrow_errors", "c", ".", "exception_renderer", "=", "->", "(", "e", ")", "{", "raise", "}", "end", "c", "when", "Liquid", "::", "Drop", "drop", "=", "args", ".", "shift", "drop", ".", "context", "=", "Context", ".", "new", "(", "[", "drop", ",", "assigns", "]", ",", "instance_assigns", ",", "registers", ",", "@rethrow_errors", ",", "@resource_limits", ")", "when", "Hash", "Context", ".", "new", "(", "[", "args", ".", "shift", ",", "assigns", "]", ",", "instance_assigns", ",", "registers", ",", "@rethrow_errors", ",", "@resource_limits", ")", "when", "nil", "Context", ".", "new", "(", "assigns", ",", "instance_assigns", ",", "registers", ",", "@rethrow_errors", ",", "@resource_limits", ")", "else", "raise", "ArgumentError", ",", "\"Expected Hash or Liquid::Context as parameter\"", "end", "case", "args", ".", "last", "when", "Hash", "options", "=", "args", ".", "pop", "registers", ".", "merge!", "(", "options", "[", ":registers", "]", ")", "if", "options", "[", ":registers", "]", ".", "is_a?", "(", "Hash", ")", "apply_options_to_context", "(", "context", ",", "options", ")", "when", "Module", ",", "Array", "context", ".", "add_filters", "(", "args", ".", "pop", ")", "end", "context", ".", "resource_limits", ".", "reset", "begin", "result", "=", "with_profiling", "(", "context", ")", "do", "@root", ".", "render", "(", "context", ")", "end", "result", ".", "respond_to?", "(", ":join", ")", "?", "result", ".", "join", ":", "result", "rescue", "Liquid", "::", "MemoryError", "=>", "e", "context", ".", "handle_error", "(", "e", ")", "ensure", "@errors", "=", "context", ".", "errors", "end", "end" ]
Render takes a hash with local variables. if you use the same filters over and over again consider registering them globally with <tt>Template.register_filter</tt> if profiling was enabled in <tt>Template#parse</tt> then the resulting profiling information will be available via <tt>Template#profiler</tt> Following options can be passed: * <tt>filters</tt> : array with local filters * <tt>registers</tt> : hash with register variables. Those can be accessed from filters and tags and might be useful to integrate liquid more with its host application
[ "Render", "takes", "a", "hash", "with", "local", "variables", "." ]
b3b63a683f6daaea7e70f1602ee829abdf970ef3
https://github.com/Shopify/liquid/blob/b3b63a683f6daaea7e70f1602ee829abdf970ef3/lib/liquid/template.rb#L167-L216
train
Shopify/liquid
lib/liquid/standardfilters.rb
Liquid.StandardFilters.truncate
def truncate(input, length = 50, truncate_string = "...".freeze) return if input.nil? input_str = input.to_s length = Utils.to_integer(length) truncate_string_str = truncate_string.to_s l = length - truncate_string_str.length l = 0 if l < 0 input_str.length > length ? input_str[0...l] + truncate_string_str : input_str end
ruby
def truncate(input, length = 50, truncate_string = "...".freeze) return if input.nil? input_str = input.to_s length = Utils.to_integer(length) truncate_string_str = truncate_string.to_s l = length - truncate_string_str.length l = 0 if l < 0 input_str.length > length ? input_str[0...l] + truncate_string_str : input_str end
[ "def", "truncate", "(", "input", ",", "length", "=", "50", ",", "truncate_string", "=", "\"...\"", ".", "freeze", ")", "return", "if", "input", ".", "nil?", "input_str", "=", "input", ".", "to_s", "length", "=", "Utils", ".", "to_integer", "(", "length", ")", "truncate_string_str", "=", "truncate_string", ".", "to_s", "l", "=", "length", "-", "truncate_string_str", ".", "length", "l", "=", "0", "if", "l", "<", "0", "input_str", ".", "length", ">", "length", "?", "input_str", "[", "0", "...", "l", "]", "+", "truncate_string_str", ":", "input_str", "end" ]
Truncate a string down to x characters
[ "Truncate", "a", "string", "down", "to", "x", "characters" ]
b3b63a683f6daaea7e70f1602ee829abdf970ef3
https://github.com/Shopify/liquid/blob/b3b63a683f6daaea7e70f1602ee829abdf970ef3/lib/liquid/standardfilters.rb#L75-L83
train
Shopify/liquid
lib/liquid/standardfilters.rb
Liquid.StandardFilters.sort
def sort(input, property = nil) ary = InputIterator.new(input) return [] if ary.empty? if property.nil? ary.sort do |a, b| nil_safe_compare(a, b) end elsif ary.all? { |el| el.respond_to?(:[]) } begin ary.sort { |a, b| nil_safe_compare(a[property], b[property]) } rescue TypeError raise_property_error(property) end end end
ruby
def sort(input, property = nil) ary = InputIterator.new(input) return [] if ary.empty? if property.nil? ary.sort do |a, b| nil_safe_compare(a, b) end elsif ary.all? { |el| el.respond_to?(:[]) } begin ary.sort { |a, b| nil_safe_compare(a[property], b[property]) } rescue TypeError raise_property_error(property) end end end
[ "def", "sort", "(", "input", ",", "property", "=", "nil", ")", "ary", "=", "InputIterator", ".", "new", "(", "input", ")", "return", "[", "]", "if", "ary", ".", "empty?", "if", "property", ".", "nil?", "ary", ".", "sort", "do", "|", "a", ",", "b", "|", "nil_safe_compare", "(", "a", ",", "b", ")", "end", "elsif", "ary", ".", "all?", "{", "|", "el", "|", "el", ".", "respond_to?", "(", ":[]", ")", "}", "begin", "ary", ".", "sort", "{", "|", "a", ",", "b", "|", "nil_safe_compare", "(", "a", "[", "property", "]", ",", "b", "[", "property", "]", ")", "}", "rescue", "TypeError", "raise_property_error", "(", "property", ")", "end", "end", "end" ]
Sort elements of the array provide optional property with which to sort an array of hashes or drops
[ "Sort", "elements", "of", "the", "array", "provide", "optional", "property", "with", "which", "to", "sort", "an", "array", "of", "hashes", "or", "drops" ]
b3b63a683f6daaea7e70f1602ee829abdf970ef3
https://github.com/Shopify/liquid/blob/b3b63a683f6daaea7e70f1602ee829abdf970ef3/lib/liquid/standardfilters.rb#L134-L150
train
Shopify/liquid
lib/liquid/standardfilters.rb
Liquid.StandardFilters.where
def where(input, property, target_value = nil) ary = InputIterator.new(input) if ary.empty? [] elsif ary.first.respond_to?(:[]) && target_value.nil? begin ary.select { |item| item[property] } rescue TypeError raise_property_error(property) end elsif ary.first.respond_to?(:[]) begin ary.select { |item| item[property] == target_value } rescue TypeError raise_property_error(property) end end end
ruby
def where(input, property, target_value = nil) ary = InputIterator.new(input) if ary.empty? [] elsif ary.first.respond_to?(:[]) && target_value.nil? begin ary.select { |item| item[property] } rescue TypeError raise_property_error(property) end elsif ary.first.respond_to?(:[]) begin ary.select { |item| item[property] == target_value } rescue TypeError raise_property_error(property) end end end
[ "def", "where", "(", "input", ",", "property", ",", "target_value", "=", "nil", ")", "ary", "=", "InputIterator", ".", "new", "(", "input", ")", "if", "ary", ".", "empty?", "[", "]", "elsif", "ary", ".", "first", ".", "respond_to?", "(", ":[]", ")", "&&", "target_value", ".", "nil?", "begin", "ary", ".", "select", "{", "|", "item", "|", "item", "[", "property", "]", "}", "rescue", "TypeError", "raise_property_error", "(", "property", ")", "end", "elsif", "ary", ".", "first", ".", "respond_to?", "(", ":[]", ")", "begin", "ary", ".", "select", "{", "|", "item", "|", "item", "[", "property", "]", "==", "target_value", "}", "rescue", "TypeError", "raise_property_error", "(", "property", ")", "end", "end", "end" ]
Filter the elements of an array to those with a certain property value. By default the target is any truthy value.
[ "Filter", "the", "elements", "of", "an", "array", "to", "those", "with", "a", "certain", "property", "value", ".", "By", "default", "the", "target", "is", "any", "truthy", "value", "." ]
b3b63a683f6daaea7e70f1602ee829abdf970ef3
https://github.com/Shopify/liquid/blob/b3b63a683f6daaea7e70f1602ee829abdf970ef3/lib/liquid/standardfilters.rb#L174-L192
train
Shopify/liquid
lib/liquid/standardfilters.rb
Liquid.StandardFilters.uniq
def uniq(input, property = nil) ary = InputIterator.new(input) if property.nil? ary.uniq elsif ary.empty? # The next two cases assume a non-empty array. [] elsif ary.first.respond_to?(:[]) begin ary.uniq { |a| a[property] } rescue TypeError raise_property_error(property) end end end
ruby
def uniq(input, property = nil) ary = InputIterator.new(input) if property.nil? ary.uniq elsif ary.empty? # The next two cases assume a non-empty array. [] elsif ary.first.respond_to?(:[]) begin ary.uniq { |a| a[property] } rescue TypeError raise_property_error(property) end end end
[ "def", "uniq", "(", "input", ",", "property", "=", "nil", ")", "ary", "=", "InputIterator", ".", "new", "(", "input", ")", "if", "property", ".", "nil?", "ary", ".", "uniq", "elsif", "ary", ".", "empty?", "[", "]", "elsif", "ary", ".", "first", ".", "respond_to?", "(", ":[]", ")", "begin", "ary", ".", "uniq", "{", "|", "a", "|", "a", "[", "property", "]", "}", "rescue", "TypeError", "raise_property_error", "(", "property", ")", "end", "end", "end" ]
Remove duplicate elements from an array provide optional property with which to determine uniqueness
[ "Remove", "duplicate", "elements", "from", "an", "array", "provide", "optional", "property", "with", "which", "to", "determine", "uniqueness" ]
b3b63a683f6daaea7e70f1602ee829abdf970ef3
https://github.com/Shopify/liquid/blob/b3b63a683f6daaea7e70f1602ee829abdf970ef3/lib/liquid/standardfilters.rb#L196-L210
train
Shopify/liquid
lib/liquid/standardfilters.rb
Liquid.StandardFilters.replace
def replace(input, string, replacement = ''.freeze) input.to_s.gsub(string.to_s, replacement.to_s) end
ruby
def replace(input, string, replacement = ''.freeze) input.to_s.gsub(string.to_s, replacement.to_s) end
[ "def", "replace", "(", "input", ",", "string", ",", "replacement", "=", "''", ".", "freeze", ")", "input", ".", "to_s", ".", "gsub", "(", "string", ".", "to_s", ",", "replacement", ".", "to_s", ")", "end" ]
Replace occurrences of a string with another
[ "Replace", "occurrences", "of", "a", "string", "with", "another" ]
b3b63a683f6daaea7e70f1602ee829abdf970ef3
https://github.com/Shopify/liquid/blob/b3b63a683f6daaea7e70f1602ee829abdf970ef3/lib/liquid/standardfilters.rb#L253-L255
train
Shopify/liquid
lib/liquid/standardfilters.rb
Liquid.StandardFilters.replace_first
def replace_first(input, string, replacement = ''.freeze) input.to_s.sub(string.to_s, replacement.to_s) end
ruby
def replace_first(input, string, replacement = ''.freeze) input.to_s.sub(string.to_s, replacement.to_s) end
[ "def", "replace_first", "(", "input", ",", "string", ",", "replacement", "=", "''", ".", "freeze", ")", "input", ".", "to_s", ".", "sub", "(", "string", ".", "to_s", ",", "replacement", ".", "to_s", ")", "end" ]
Replace the first occurrences of a string with another
[ "Replace", "the", "first", "occurrences", "of", "a", "string", "with", "another" ]
b3b63a683f6daaea7e70f1602ee829abdf970ef3
https://github.com/Shopify/liquid/blob/b3b63a683f6daaea7e70f1602ee829abdf970ef3/lib/liquid/standardfilters.rb#L258-L260
train
Shopify/liquid
lib/liquid/context.rb
Liquid.Context.stack
def stack(new_scope = nil) old_stack_used = @this_stack_used if new_scope push(new_scope) @this_stack_used = true else @this_stack_used = false end yield ensure pop if @this_stack_used @this_stack_used = old_stack_used end
ruby
def stack(new_scope = nil) old_stack_used = @this_stack_used if new_scope push(new_scope) @this_stack_used = true else @this_stack_used = false end yield ensure pop if @this_stack_used @this_stack_used = old_stack_used end
[ "def", "stack", "(", "new_scope", "=", "nil", ")", "old_stack_used", "=", "@this_stack_used", "if", "new_scope", "push", "(", "new_scope", ")", "@this_stack_used", "=", "true", "else", "@this_stack_used", "=", "false", "end", "yield", "ensure", "pop", "if", "@this_stack_used", "@this_stack_used", "=", "old_stack_used", "end" ]
Pushes a new local scope on the stack, pops it at the end of the block Example: context.stack do context['var'] = 'hi' end context['var] #=> nil
[ "Pushes", "a", "new", "local", "scope", "on", "the", "stack", "pops", "it", "at", "the", "end", "of", "the", "block" ]
b3b63a683f6daaea7e70f1602ee829abdf970ef3
https://github.com/Shopify/liquid/blob/b3b63a683f6daaea7e70f1602ee829abdf970ef3/lib/liquid/context.rb#L114-L127
train
Shopify/liquid
lib/liquid/context.rb
Liquid.Context.find_variable
def find_variable(key, raise_on_not_found: true) # This was changed from find() to find_index() because this is a very hot # path and find_index() is optimized in MRI to reduce object allocation index = @scopes.find_index { |s| s.key?(key) } scope = @scopes[index] if index variable = nil if scope.nil? @environments.each do |e| variable = lookup_and_evaluate(e, key, raise_on_not_found: raise_on_not_found) # When lookup returned a value OR there is no value but the lookup also did not raise # then it is the value we are looking for. if !variable.nil? || @strict_variables && raise_on_not_found scope = e break end end end scope ||= @environments.last || @scopes.last variable ||= lookup_and_evaluate(scope, key, raise_on_not_found: raise_on_not_found) variable = variable.to_liquid variable.context = self if variable.respond_to?(:context=) variable end
ruby
def find_variable(key, raise_on_not_found: true) # This was changed from find() to find_index() because this is a very hot # path and find_index() is optimized in MRI to reduce object allocation index = @scopes.find_index { |s| s.key?(key) } scope = @scopes[index] if index variable = nil if scope.nil? @environments.each do |e| variable = lookup_and_evaluate(e, key, raise_on_not_found: raise_on_not_found) # When lookup returned a value OR there is no value but the lookup also did not raise # then it is the value we are looking for. if !variable.nil? || @strict_variables && raise_on_not_found scope = e break end end end scope ||= @environments.last || @scopes.last variable ||= lookup_and_evaluate(scope, key, raise_on_not_found: raise_on_not_found) variable = variable.to_liquid variable.context = self if variable.respond_to?(:context=) variable end
[ "def", "find_variable", "(", "key", ",", "raise_on_not_found", ":", "true", ")", "index", "=", "@scopes", ".", "find_index", "{", "|", "s", "|", "s", ".", "key?", "(", "key", ")", "}", "scope", "=", "@scopes", "[", "index", "]", "if", "index", "variable", "=", "nil", "if", "scope", ".", "nil?", "@environments", ".", "each", "do", "|", "e", "|", "variable", "=", "lookup_and_evaluate", "(", "e", ",", "key", ",", "raise_on_not_found", ":", "raise_on_not_found", ")", "if", "!", "variable", ".", "nil?", "||", "@strict_variables", "&&", "raise_on_not_found", "scope", "=", "e", "break", "end", "end", "end", "scope", "||=", "@environments", ".", "last", "||", "@scopes", ".", "last", "variable", "||=", "lookup_and_evaluate", "(", "scope", ",", "key", ",", "raise_on_not_found", ":", "raise_on_not_found", ")", "variable", "=", "variable", ".", "to_liquid", "variable", ".", "context", "=", "self", "if", "variable", ".", "respond_to?", "(", ":context=", ")", "variable", "end" ]
Fetches an object starting at the local scope and then moving up the hierachy
[ "Fetches", "an", "object", "starting", "at", "the", "local", "scope", "and", "then", "moving", "up", "the", "hierachy" ]
b3b63a683f6daaea7e70f1602ee829abdf970ef3
https://github.com/Shopify/liquid/blob/b3b63a683f6daaea7e70f1602ee829abdf970ef3/lib/liquid/context.rb#L163-L190
train
rubocop-hq/rubocop
lib/rubocop/cached_data.rb
RuboCop.CachedData.deserialize_offenses
def deserialize_offenses(offenses) source_buffer = Parser::Source::Buffer.new(@filename) source_buffer.source = File.read(@filename, encoding: Encoding::UTF_8) offenses.map! do |o| location = Parser::Source::Range.new(source_buffer, o['location']['begin_pos'], o['location']['end_pos']) Cop::Offense.new(o['severity'], location, o['message'], o['cop_name'], o['status'].to_sym) end end
ruby
def deserialize_offenses(offenses) source_buffer = Parser::Source::Buffer.new(@filename) source_buffer.source = File.read(@filename, encoding: Encoding::UTF_8) offenses.map! do |o| location = Parser::Source::Range.new(source_buffer, o['location']['begin_pos'], o['location']['end_pos']) Cop::Offense.new(o['severity'], location, o['message'], o['cop_name'], o['status'].to_sym) end end
[ "def", "deserialize_offenses", "(", "offenses", ")", "source_buffer", "=", "Parser", "::", "Source", "::", "Buffer", ".", "new", "(", "@filename", ")", "source_buffer", ".", "source", "=", "File", ".", "read", "(", "@filename", ",", "encoding", ":", "Encoding", "::", "UTF_8", ")", "offenses", ".", "map!", "do", "|", "o", "|", "location", "=", "Parser", "::", "Source", "::", "Range", ".", "new", "(", "source_buffer", ",", "o", "[", "'location'", "]", "[", "'begin_pos'", "]", ",", "o", "[", "'location'", "]", "[", "'end_pos'", "]", ")", "Cop", "::", "Offense", ".", "new", "(", "o", "[", "'severity'", "]", ",", "location", ",", "o", "[", "'message'", "]", ",", "o", "[", "'cop_name'", "]", ",", "o", "[", "'status'", "]", ".", "to_sym", ")", "end", "end" ]
Restore an offense object loaded from a JSON file.
[ "Restore", "an", "offense", "object", "loaded", "from", "a", "JSON", "file", "." ]
2a4f4f0fdac4e1bb25891fc312af2ea60c6aa2f0
https://github.com/rubocop-hq/rubocop/blob/2a4f4f0fdac4e1bb25891fc312af2ea60c6aa2f0/lib/rubocop/cached_data.rb#L45-L56
train
rubocop-hq/rubocop
lib/rubocop/token.rb
RuboCop.Token.space_before?
def space_before? position = begin_pos.zero? ? begin_pos : begin_pos - 1 pos.source_buffer.source.match(/\G\s/, position) end
ruby
def space_before? position = begin_pos.zero? ? begin_pos : begin_pos - 1 pos.source_buffer.source.match(/\G\s/, position) end
[ "def", "space_before?", "position", "=", "begin_pos", ".", "zero?", "?", "begin_pos", ":", "begin_pos", "-", "1", "pos", ".", "source_buffer", ".", "source", ".", "match", "(", "/", "\\G", "\\s", "/", ",", "position", ")", "end" ]
Checks if there is whitespace before token
[ "Checks", "if", "there", "is", "whitespace", "before", "token" ]
2a4f4f0fdac4e1bb25891fc312af2ea60c6aa2f0
https://github.com/rubocop-hq/rubocop/blob/2a4f4f0fdac4e1bb25891fc312af2ea60c6aa2f0/lib/rubocop/token.rb#L47-L50
train
rubocop-hq/rubocop
lib/rubocop/options.rb
RuboCop.Options.option
def option(opts, *args) long_opt_symbol = long_opt_symbol(args) args += Array(OptionsHelp::TEXT[long_opt_symbol]) opts.on(*args) do |arg| @options[long_opt_symbol] = arg yield arg if block_given? end end
ruby
def option(opts, *args) long_opt_symbol = long_opt_symbol(args) args += Array(OptionsHelp::TEXT[long_opt_symbol]) opts.on(*args) do |arg| @options[long_opt_symbol] = arg yield arg if block_given? end end
[ "def", "option", "(", "opts", ",", "*", "args", ")", "long_opt_symbol", "=", "long_opt_symbol", "(", "args", ")", "args", "+=", "Array", "(", "OptionsHelp", "::", "TEXT", "[", "long_opt_symbol", "]", ")", "opts", ".", "on", "(", "*", "args", ")", "do", "|", "arg", "|", "@options", "[", "long_opt_symbol", "]", "=", "arg", "yield", "arg", "if", "block_given?", "end", "end" ]
Sets a value in the @options hash, based on the given long option and its value, in addition to calling the block if a block is given.
[ "Sets", "a", "value", "in", "the" ]
2a4f4f0fdac4e1bb25891fc312af2ea60c6aa2f0
https://github.com/rubocop-hq/rubocop/blob/2a4f4f0fdac4e1bb25891fc312af2ea60c6aa2f0/lib/rubocop/options.rb#L196-L203
train
rubocop-hq/rubocop
lib/rubocop/config.rb
RuboCop.Config.possibly_include_hidden?
def possibly_include_hidden? return @possibly_include_hidden if defined?(@possibly_include_hidden) @possibly_include_hidden = patterns_to_include.any? do |s| s.is_a?(Regexp) || s.start_with?('.') || s.include?('/.') end end
ruby
def possibly_include_hidden? return @possibly_include_hidden if defined?(@possibly_include_hidden) @possibly_include_hidden = patterns_to_include.any? do |s| s.is_a?(Regexp) || s.start_with?('.') || s.include?('/.') end end
[ "def", "possibly_include_hidden?", "return", "@possibly_include_hidden", "if", "defined?", "(", "@possibly_include_hidden", ")", "@possibly_include_hidden", "=", "patterns_to_include", ".", "any?", "do", "|", "s", "|", "s", ".", "is_a?", "(", "Regexp", ")", "||", "s", ".", "start_with?", "(", "'.'", ")", "||", "s", ".", "include?", "(", "'/.'", ")", "end", "end" ]
Returns true if there's a chance that an Include pattern matches hidden files, false if that's definitely not possible.
[ "Returns", "true", "if", "there", "s", "a", "chance", "that", "an", "Include", "pattern", "matches", "hidden", "files", "false", "if", "that", "s", "definitely", "not", "possible", "." ]
2a4f4f0fdac4e1bb25891fc312af2ea60c6aa2f0
https://github.com/rubocop-hq/rubocop/blob/2a4f4f0fdac4e1bb25891fc312af2ea60c6aa2f0/lib/rubocop/config.rb#L410-L416
train
rubocop-hq/rubocop
lib/rubocop/runner.rb
RuboCop.Runner.check_for_infinite_loop
def check_for_infinite_loop(processed_source, offenses) checksum = processed_source.checksum if @processed_sources.include?(checksum) raise InfiniteCorrectionLoop.new(processed_source.path, offenses) end @processed_sources << checksum end
ruby
def check_for_infinite_loop(processed_source, offenses) checksum = processed_source.checksum if @processed_sources.include?(checksum) raise InfiniteCorrectionLoop.new(processed_source.path, offenses) end @processed_sources << checksum end
[ "def", "check_for_infinite_loop", "(", "processed_source", ",", "offenses", ")", "checksum", "=", "processed_source", ".", "checksum", "if", "@processed_sources", ".", "include?", "(", "checksum", ")", "raise", "InfiniteCorrectionLoop", ".", "new", "(", "processed_source", ".", "path", ",", "offenses", ")", "end", "@processed_sources", "<<", "checksum", "end" ]
Check whether a run created source identical to a previous run, which means that we definitely have an infinite loop.
[ "Check", "whether", "a", "run", "created", "source", "identical", "to", "a", "previous", "run", "which", "means", "that", "we", "definitely", "have", "an", "infinite", "loop", "." ]
2a4f4f0fdac4e1bb25891fc312af2ea60c6aa2f0
https://github.com/rubocop-hq/rubocop/blob/2a4f4f0fdac4e1bb25891fc312af2ea60c6aa2f0/lib/rubocop/runner.rb#L259-L267
train
rubocop-hq/rubocop
lib/rubocop/target_finder.rb
RuboCop.TargetFinder.target_files_in_dir
def target_files_in_dir(base_dir = Dir.pwd) # Support Windows: Backslashes from command-line -> forward slashes if File::ALT_SEPARATOR base_dir = base_dir.gsub(File::ALT_SEPARATOR, File::SEPARATOR) end all_files = find_files(base_dir, File::FNM_DOTMATCH) hidden_files = Set.new(all_files - find_files(base_dir, 0)) base_dir_config = @config_store.for(base_dir) target_files = all_files.select do |file| to_inspect?(file, hidden_files, base_dir_config) end # Most recently modified file first. target_files.sort_by! { |path| -Integer(File.mtime(path)) } if fail_fast? target_files end
ruby
def target_files_in_dir(base_dir = Dir.pwd) # Support Windows: Backslashes from command-line -> forward slashes if File::ALT_SEPARATOR base_dir = base_dir.gsub(File::ALT_SEPARATOR, File::SEPARATOR) end all_files = find_files(base_dir, File::FNM_DOTMATCH) hidden_files = Set.new(all_files - find_files(base_dir, 0)) base_dir_config = @config_store.for(base_dir) target_files = all_files.select do |file| to_inspect?(file, hidden_files, base_dir_config) end # Most recently modified file first. target_files.sort_by! { |path| -Integer(File.mtime(path)) } if fail_fast? target_files end
[ "def", "target_files_in_dir", "(", "base_dir", "=", "Dir", ".", "pwd", ")", "if", "File", "::", "ALT_SEPARATOR", "base_dir", "=", "base_dir", ".", "gsub", "(", "File", "::", "ALT_SEPARATOR", ",", "File", "::", "SEPARATOR", ")", "end", "all_files", "=", "find_files", "(", "base_dir", ",", "File", "::", "FNM_DOTMATCH", ")", "hidden_files", "=", "Set", ".", "new", "(", "all_files", "-", "find_files", "(", "base_dir", ",", "0", ")", ")", "base_dir_config", "=", "@config_store", ".", "for", "(", "base_dir", ")", "target_files", "=", "all_files", ".", "select", "do", "|", "file", "|", "to_inspect?", "(", "file", ",", "hidden_files", ",", "base_dir_config", ")", "end", "target_files", ".", "sort_by!", "{", "|", "path", "|", "-", "Integer", "(", "File", ".", "mtime", "(", "path", ")", ")", "}", "if", "fail_fast?", "target_files", "end" ]
Finds all Ruby source files under the current or other supplied directory. A Ruby source file is defined as a file with the `.rb` extension or a file with no extension that has a ruby shebang line as its first line. It is possible to specify includes and excludes using the config file, so you can include other Ruby files like Rakefiles and gemspecs. @param base_dir Root directory under which to search for ruby source files @return [Array] Array of filenames
[ "Finds", "all", "Ruby", "source", "files", "under", "the", "current", "or", "other", "supplied", "directory", ".", "A", "Ruby", "source", "file", "is", "defined", "as", "a", "file", "with", "the", ".", "rb", "extension", "or", "a", "file", "with", "no", "extension", "that", "has", "a", "ruby", "shebang", "line", "as", "its", "first", "line", ".", "It", "is", "possible", "to", "specify", "includes", "and", "excludes", "using", "the", "config", "file", "so", "you", "can", "include", "other", "Ruby", "files", "like", "Rakefiles", "and", "gemspecs", "." ]
2a4f4f0fdac4e1bb25891fc312af2ea60c6aa2f0
https://github.com/rubocop-hq/rubocop/blob/2a4f4f0fdac4e1bb25891fc312af2ea60c6aa2f0/lib/rubocop/target_finder.rb#L55-L72
train
rubocop-hq/rubocop
lib/rubocop/result_cache.rb
RuboCop.ResultCache.rubocop_checksum
def rubocop_checksum ResultCache.source_checksum ||= begin lib_root = File.join(File.dirname(__FILE__), '..') exe_root = File.join(lib_root, '..', 'exe') # These are all the files we have `require`d plus everything in the # exe directory. A change to any of them could affect the cop output # so we include them in the cache hash. source_files = $LOADED_FEATURES + Find.find(exe_root).to_a sources = source_files .select { |path| File.file?(path) } .sort .map { |path| IO.read(path, encoding: Encoding::UTF_8) } Digest::SHA1.hexdigest(sources.join) end end
ruby
def rubocop_checksum ResultCache.source_checksum ||= begin lib_root = File.join(File.dirname(__FILE__), '..') exe_root = File.join(lib_root, '..', 'exe') # These are all the files we have `require`d plus everything in the # exe directory. A change to any of them could affect the cop output # so we include them in the cache hash. source_files = $LOADED_FEATURES + Find.find(exe_root).to_a sources = source_files .select { |path| File.file?(path) } .sort .map { |path| IO.read(path, encoding: Encoding::UTF_8) } Digest::SHA1.hexdigest(sources.join) end end
[ "def", "rubocop_checksum", "ResultCache", ".", "source_checksum", "||=", "begin", "lib_root", "=", "File", ".", "join", "(", "File", ".", "dirname", "(", "__FILE__", ")", ",", "'..'", ")", "exe_root", "=", "File", ".", "join", "(", "lib_root", ",", "'..'", ",", "'exe'", ")", "source_files", "=", "$LOADED_FEATURES", "+", "Find", ".", "find", "(", "exe_root", ")", ".", "to_a", "sources", "=", "source_files", ".", "select", "{", "|", "path", "|", "File", ".", "file?", "(", "path", ")", "}", ".", "sort", ".", "map", "{", "|", "path", "|", "IO", ".", "read", "(", "path", ",", "encoding", ":", "Encoding", "::", "UTF_8", ")", "}", "Digest", "::", "SHA1", ".", "hexdigest", "(", "sources", ".", "join", ")", "end", "end" ]
The checksum of the rubocop program running the inspection.
[ "The", "checksum", "of", "the", "rubocop", "program", "running", "the", "inspection", "." ]
2a4f4f0fdac4e1bb25891fc312af2ea60c6aa2f0
https://github.com/rubocop-hq/rubocop/blob/2a4f4f0fdac4e1bb25891fc312af2ea60c6aa2f0/lib/rubocop/result_cache.rb#L162-L178
train
rubocop-hq/rubocop
lib/rubocop/result_cache.rb
RuboCop.ResultCache.relevant_options_digest
def relevant_options_digest(options) options = options.reject { |key, _| NON_CHANGING.include?(key) } options = options.to_s.gsub(/[^a-z]+/i, '_') # We must avoid making file names too long for some filesystems to handle # If they are short, we can leave them human-readable options.length <= 32 ? options : Digest::SHA1.hexdigest(options) end
ruby
def relevant_options_digest(options) options = options.reject { |key, _| NON_CHANGING.include?(key) } options = options.to_s.gsub(/[^a-z]+/i, '_') # We must avoid making file names too long for some filesystems to handle # If they are short, we can leave them human-readable options.length <= 32 ? options : Digest::SHA1.hexdigest(options) end
[ "def", "relevant_options_digest", "(", "options", ")", "options", "=", "options", ".", "reject", "{", "|", "key", ",", "_", "|", "NON_CHANGING", ".", "include?", "(", "key", ")", "}", "options", "=", "options", ".", "to_s", ".", "gsub", "(", "/", "/i", ",", "'_'", ")", "options", ".", "length", "<=", "32", "?", "options", ":", "Digest", "::", "SHA1", ".", "hexdigest", "(", "options", ")", "end" ]
Return a hash of the options given at invocation, minus the ones that have no effect on which offenses and disabled line ranges are found, and thus don't affect caching.
[ "Return", "a", "hash", "of", "the", "options", "given", "at", "invocation", "minus", "the", "ones", "that", "have", "no", "effect", "on", "which", "offenses", "and", "disabled", "line", "ranges", "are", "found", "and", "thus", "don", "t", "affect", "caching", "." ]
2a4f4f0fdac4e1bb25891fc312af2ea60c6aa2f0
https://github.com/rubocop-hq/rubocop/blob/2a4f4f0fdac4e1bb25891fc312af2ea60c6aa2f0/lib/rubocop/result_cache.rb#L183-L189
train
rubocop-hq/rubocop
lib/rubocop/config_loader_resolver.rb
RuboCop.ConfigLoaderResolver.merge
def merge(base_hash, derived_hash, **opts) result = base_hash.merge(derived_hash) keys_appearing_in_both = base_hash.keys & derived_hash.keys keys_appearing_in_both.each do |key| if opts[:unset_nil] && derived_hash[key].nil? result.delete(key) elsif base_hash[key].is_a?(Hash) result[key] = merge(base_hash[key], derived_hash[key], **opts) elsif should_union?(base_hash, key, opts[:inherit_mode]) result[key] = base_hash[key] | derived_hash[key] elsif opts[:debug] warn_on_duplicate_setting(base_hash, derived_hash, key, opts) end end result end
ruby
def merge(base_hash, derived_hash, **opts) result = base_hash.merge(derived_hash) keys_appearing_in_both = base_hash.keys & derived_hash.keys keys_appearing_in_both.each do |key| if opts[:unset_nil] && derived_hash[key].nil? result.delete(key) elsif base_hash[key].is_a?(Hash) result[key] = merge(base_hash[key], derived_hash[key], **opts) elsif should_union?(base_hash, key, opts[:inherit_mode]) result[key] = base_hash[key] | derived_hash[key] elsif opts[:debug] warn_on_duplicate_setting(base_hash, derived_hash, key, opts) end end result end
[ "def", "merge", "(", "base_hash", ",", "derived_hash", ",", "**", "opts", ")", "result", "=", "base_hash", ".", "merge", "(", "derived_hash", ")", "keys_appearing_in_both", "=", "base_hash", ".", "keys", "&", "derived_hash", ".", "keys", "keys_appearing_in_both", ".", "each", "do", "|", "key", "|", "if", "opts", "[", ":unset_nil", "]", "&&", "derived_hash", "[", "key", "]", ".", "nil?", "result", ".", "delete", "(", "key", ")", "elsif", "base_hash", "[", "key", "]", ".", "is_a?", "(", "Hash", ")", "result", "[", "key", "]", "=", "merge", "(", "base_hash", "[", "key", "]", ",", "derived_hash", "[", "key", "]", ",", "**", "opts", ")", "elsif", "should_union?", "(", "base_hash", ",", "key", ",", "opts", "[", ":inherit_mode", "]", ")", "result", "[", "key", "]", "=", "base_hash", "[", "key", "]", "|", "derived_hash", "[", "key", "]", "elsif", "opts", "[", ":debug", "]", "warn_on_duplicate_setting", "(", "base_hash", ",", "derived_hash", ",", "key", ",", "opts", ")", "end", "end", "result", "end" ]
Return a recursive merge of two hashes. That is, a normal hash merge, with the addition that any value that is a hash, and occurs in both arguments, will also be merged. And so on. rubocop:disable Metrics/AbcSize
[ "Return", "a", "recursive", "merge", "of", "two", "hashes", ".", "That", "is", "a", "normal", "hash", "merge", "with", "the", "addition", "that", "any", "value", "that", "is", "a", "hash", "and", "occurs", "in", "both", "arguments", "will", "also", "be", "merged", ".", "And", "so", "on", "." ]
2a4f4f0fdac4e1bb25891fc312af2ea60c6aa2f0
https://github.com/rubocop-hq/rubocop/blob/2a4f4f0fdac4e1bb25891fc312af2ea60c6aa2f0/lib/rubocop/config_loader_resolver.rb#L83-L98
train
chef/chef
lib/chef/shell/shell_session.rb
Shell.DoppelGangerClient.build_node
def build_node Chef::Log.trace("Building node object for #{@node_name}") @node = Chef::Node.find_or_create(node_name) ohai_data = @ohai.data.merge(@node.automatic_attrs) @node.consume_external_attrs(ohai_data, nil) @run_list_expansion = @node.expand!("server") @expanded_run_list_with_versions = @run_list_expansion.recipes.with_version_constraints_strings Chef::Log.info("Run List is [#{@node.run_list}]") Chef::Log.info("Run List expands to [#{@expanded_run_list_with_versions.join(', ')}]") @node end
ruby
def build_node Chef::Log.trace("Building node object for #{@node_name}") @node = Chef::Node.find_or_create(node_name) ohai_data = @ohai.data.merge(@node.automatic_attrs) @node.consume_external_attrs(ohai_data, nil) @run_list_expansion = @node.expand!("server") @expanded_run_list_with_versions = @run_list_expansion.recipes.with_version_constraints_strings Chef::Log.info("Run List is [#{@node.run_list}]") Chef::Log.info("Run List expands to [#{@expanded_run_list_with_versions.join(', ')}]") @node end
[ "def", "build_node", "Chef", "::", "Log", ".", "trace", "(", "\"Building node object for #{@node_name}\"", ")", "@node", "=", "Chef", "::", "Node", ".", "find_or_create", "(", "node_name", ")", "ohai_data", "=", "@ohai", ".", "data", ".", "merge", "(", "@node", ".", "automatic_attrs", ")", "@node", ".", "consume_external_attrs", "(", "ohai_data", ",", "nil", ")", "@run_list_expansion", "=", "@node", ".", "expand!", "(", "\"server\"", ")", "@expanded_run_list_with_versions", "=", "@run_list_expansion", ".", "recipes", ".", "with_version_constraints_strings", "Chef", "::", "Log", ".", "info", "(", "\"Run List is [#{@node.run_list}]\"", ")", "Chef", "::", "Log", ".", "info", "(", "\"Run List expands to [#{@expanded_run_list_with_versions.join(', ')}]\"", ")", "@node", "end" ]
DoppelGanger implementation of build_node. preserves as many of the node's attributes, and does not save updates to the server
[ "DoppelGanger", "implementation", "of", "build_node", ".", "preserves", "as", "many", "of", "the", "node", "s", "attributes", "and", "does", "not", "save", "updates", "to", "the", "server" ]
61f69e18e69e0dca6e8cffdcd7451181d874cdb3
https://github.com/chef/chef/blob/61f69e18e69e0dca6e8cffdcd7451181d874cdb3/lib/chef/shell/shell_session.rb#L254-L264
train
chef/chef
lib/chef/shell/model_wrapper.rb
Shell.ModelWrapper.list_objects
def list_objects objects = @model_class.method(:list).arity == 0 ? @model_class.list : @model_class.list(true) objects.map { |obj| Array(obj).find { |o| o.kind_of?(@model_class) } } end
ruby
def list_objects objects = @model_class.method(:list).arity == 0 ? @model_class.list : @model_class.list(true) objects.map { |obj| Array(obj).find { |o| o.kind_of?(@model_class) } } end
[ "def", "list_objects", "objects", "=", "@model_class", ".", "method", "(", ":list", ")", ".", "arity", "==", "0", "?", "@model_class", ".", "list", ":", "@model_class", ".", "list", "(", "true", ")", "objects", ".", "map", "{", "|", "obj", "|", "Array", "(", "obj", ")", ".", "find", "{", "|", "o", "|", "o", ".", "kind_of?", "(", "@model_class", ")", "}", "}", "end" ]
paper over inconsistencies in the model classes APIs, and return the objects the user wanted instead of the URI=>object stuff
[ "paper", "over", "inconsistencies", "in", "the", "model", "classes", "APIs", "and", "return", "the", "objects", "the", "user", "wanted", "instead", "of", "the", "URI", "=", ">", "object", "stuff" ]
61f69e18e69e0dca6e8cffdcd7451181d874cdb3
https://github.com/chef/chef/blob/61f69e18e69e0dca6e8cffdcd7451181d874cdb3/lib/chef/shell/model_wrapper.rb#L82-L85
train
chef/chef
chef-config/lib/chef-config/workstation_config_loader.rb
ChefConfig.WorkstationConfigLoader.apply_defaults
def apply_defaults # If we don't have a better guess use the username. Config[:node_name] ||= Etc.getlogin # If we don't have a key (path or inline) check user.pem and $node_name.pem. unless Config.key?(:client_key) || Config.key?(:client_key_contents) key_path = find_default_key(["#{Config[:node_name]}.pem", "user.pem"]) Config[:client_key] = key_path if key_path end # Similarly look for a validation key file, though this should be less # common these days. unless Config.key?(:validation_key) || Config.key?(:validation_key_contents) key_path = find_default_key(["#{Config[:validation_client_name]}.pem", "validator.pem", "validation.pem"]) Config[:validation_key] = key_path if key_path end end
ruby
def apply_defaults # If we don't have a better guess use the username. Config[:node_name] ||= Etc.getlogin # If we don't have a key (path or inline) check user.pem and $node_name.pem. unless Config.key?(:client_key) || Config.key?(:client_key_contents) key_path = find_default_key(["#{Config[:node_name]}.pem", "user.pem"]) Config[:client_key] = key_path if key_path end # Similarly look for a validation key file, though this should be less # common these days. unless Config.key?(:validation_key) || Config.key?(:validation_key_contents) key_path = find_default_key(["#{Config[:validation_client_name]}.pem", "validator.pem", "validation.pem"]) Config[:validation_key] = key_path if key_path end end
[ "def", "apply_defaults", "Config", "[", ":node_name", "]", "||=", "Etc", ".", "getlogin", "unless", "Config", ".", "key?", "(", ":client_key", ")", "||", "Config", ".", "key?", "(", ":client_key_contents", ")", "key_path", "=", "find_default_key", "(", "[", "\"#{Config[:node_name]}.pem\"", ",", "\"user.pem\"", "]", ")", "Config", "[", ":client_key", "]", "=", "key_path", "if", "key_path", "end", "unless", "Config", ".", "key?", "(", ":validation_key", ")", "||", "Config", ".", "key?", "(", ":validation_key_contents", ")", "key_path", "=", "find_default_key", "(", "[", "\"#{Config[:validation_client_name]}.pem\"", ",", "\"validator.pem\"", ",", "\"validation.pem\"", "]", ")", "Config", "[", ":validation_key", "]", "=", "key_path", "if", "key_path", "end", "end" ]
Apply default configuration values for workstation-style tools. Global defaults should go in {ChefConfig::Config} instead, this is only for things like `knife` and `chef`. @api private @since 14.3 @return [void]
[ "Apply", "default", "configuration", "values", "for", "workstation", "-", "style", "tools", "." ]
61f69e18e69e0dca6e8cffdcd7451181d874cdb3
https://github.com/chef/chef/blob/61f69e18e69e0dca6e8cffdcd7451181d874cdb3/chef-config/lib/chef-config/workstation_config_loader.rb#L223-L237
train
chef/chef
chef-config/lib/chef-config/workstation_config_loader.rb
ChefConfig.WorkstationConfigLoader.find_default_key
def find_default_key(key_names) key_names.each do |filename| path = Pathname.new(filename) # If we have a config location (like ./.chef/), look there first. if config_location local_path = path.expand_path(File.dirname(config_location)) return local_path.to_s if local_path.exist? end # Then check ~/.chef. home_path = path.expand_path(home_chef_dir) return home_path.to_s if home_path.exist? end nil end
ruby
def find_default_key(key_names) key_names.each do |filename| path = Pathname.new(filename) # If we have a config location (like ./.chef/), look there first. if config_location local_path = path.expand_path(File.dirname(config_location)) return local_path.to_s if local_path.exist? end # Then check ~/.chef. home_path = path.expand_path(home_chef_dir) return home_path.to_s if home_path.exist? end nil end
[ "def", "find_default_key", "(", "key_names", ")", "key_names", ".", "each", "do", "|", "filename", "|", "path", "=", "Pathname", ".", "new", "(", "filename", ")", "if", "config_location", "local_path", "=", "path", ".", "expand_path", "(", "File", ".", "dirname", "(", "config_location", ")", ")", "return", "local_path", ".", "to_s", "if", "local_path", ".", "exist?", "end", "home_path", "=", "path", ".", "expand_path", "(", "home_chef_dir", ")", "return", "home_path", ".", "to_s", "if", "home_path", ".", "exist?", "end", "nil", "end" ]
Look for a default key file. This searches for any of a list of possible default keys, checking both the local `.chef/` folder and the home directory `~/.chef/`. Returns `nil` if no matching file is found. @api private @since 14.3 @param key_names [Array<String>] A list of possible filenames to check for. The first one found will be returned. @return [String, nil]
[ "Look", "for", "a", "default", "key", "file", "." ]
61f69e18e69e0dca6e8cffdcd7451181d874cdb3
https://github.com/chef/chef/blob/61f69e18e69e0dca6e8cffdcd7451181d874cdb3/chef-config/lib/chef-config/workstation_config_loader.rb#L250-L263
train
sinatra/sinatra
lib/sinatra/base.rb
Sinatra.Helpers.status
def status(value = nil) response.status = Rack::Utils.status_code(value) if value response.status end
ruby
def status(value = nil) response.status = Rack::Utils.status_code(value) if value response.status end
[ "def", "status", "(", "value", "=", "nil", ")", "response", ".", "status", "=", "Rack", "::", "Utils", ".", "status_code", "(", "value", ")", "if", "value", "response", ".", "status", "end" ]
Set or retrieve the response status code.
[ "Set", "or", "retrieve", "the", "response", "status", "code", "." ]
1aa64f9858edc3f93cc8d46e26f724c1ae103b1c
https://github.com/sinatra/sinatra/blob/1aa64f9858edc3f93cc8d46e26f724c1ae103b1c/lib/sinatra/base.rb#L247-L250
train
sinatra/sinatra
sinatra-contrib/lib/sinatra/config_file.rb
Sinatra.ConfigFile.config_file
def config_file(*paths) Dir.chdir(root || '.') do paths.each do |pattern| Dir.glob(pattern) do |file| raise UnsupportedConfigType unless ['.yml', '.erb'].include?(File.extname(file)) logger.info "loading config file '#{file}'" if logging? && respond_to?(:logger) document = ERB.new(IO.read(file)).result yaml = YAML.load(document) config = config_for_env(yaml) config.each_pair { |key, value| set(key, value) } end end end end
ruby
def config_file(*paths) Dir.chdir(root || '.') do paths.each do |pattern| Dir.glob(pattern) do |file| raise UnsupportedConfigType unless ['.yml', '.erb'].include?(File.extname(file)) logger.info "loading config file '#{file}'" if logging? && respond_to?(:logger) document = ERB.new(IO.read(file)).result yaml = YAML.load(document) config = config_for_env(yaml) config.each_pair { |key, value| set(key, value) } end end end end
[ "def", "config_file", "(", "*", "paths", ")", "Dir", ".", "chdir", "(", "root", "||", "'.'", ")", "do", "paths", ".", "each", "do", "|", "pattern", "|", "Dir", ".", "glob", "(", "pattern", ")", "do", "|", "file", "|", "raise", "UnsupportedConfigType", "unless", "[", "'.yml'", ",", "'.erb'", "]", ".", "include?", "(", "File", ".", "extname", "(", "file", ")", ")", "logger", ".", "info", "\"loading config file '#{file}'\"", "if", "logging?", "&&", "respond_to?", "(", ":logger", ")", "document", "=", "ERB", ".", "new", "(", "IO", ".", "read", "(", "file", ")", ")", ".", "result", "yaml", "=", "YAML", ".", "load", "(", "document", ")", "config", "=", "config_for_env", "(", "yaml", ")", "config", ".", "each_pair", "{", "|", "key", ",", "value", "|", "set", "(", "key", ",", "value", ")", "}", "end", "end", "end", "end" ]
Loads the configuration from the YAML files whose +paths+ are passed as arguments, filtering the settings for the current environment. Note that these +paths+ can actually be globs.
[ "Loads", "the", "configuration", "from", "the", "YAML", "files", "whose", "+", "paths", "+", "are", "passed", "as", "arguments", "filtering", "the", "settings", "for", "the", "current", "environment", ".", "Note", "that", "these", "+", "paths", "+", "can", "actually", "be", "globs", "." ]
1aa64f9858edc3f93cc8d46e26f724c1ae103b1c
https://github.com/sinatra/sinatra/blob/1aa64f9858edc3f93cc8d46e26f724c1ae103b1c/sinatra-contrib/lib/sinatra/config_file.rb#L120-L133
train
sinatra/sinatra
sinatra-contrib/lib/sinatra/config_file.rb
Sinatra.ConfigFile.environment_keys?
def environment_keys?(hash) hash.is_a?(Hash) && hash.any? { |k, _| environments.include?(k.to_s) } end
ruby
def environment_keys?(hash) hash.is_a?(Hash) && hash.any? { |k, _| environments.include?(k.to_s) } end
[ "def", "environment_keys?", "(", "hash", ")", "hash", ".", "is_a?", "(", "Hash", ")", "&&", "hash", ".", "any?", "{", "|", "k", ",", "_", "|", "environments", ".", "include?", "(", "k", ".", "to_s", ")", "}", "end" ]
Returns true if supplied with a hash that has any recognized +environments+ in its root keys.
[ "Returns", "true", "if", "supplied", "with", "a", "hash", "that", "has", "any", "recognized", "+", "environments", "+", "in", "its", "root", "keys", "." ]
1aa64f9858edc3f93cc8d46e26f724c1ae103b1c
https://github.com/sinatra/sinatra/blob/1aa64f9858edc3f93cc8d46e26f724c1ae103b1c/sinatra-contrib/lib/sinatra/config_file.rb#L166-L168
train
sinatra/sinatra
sinatra-contrib/lib/sinatra/link_header.rb
Sinatra.LinkHeader.stylesheet
def stylesheet(*urls) urls << {} unless urls.last.respond_to? :to_hash urls.last[:type] ||= mime_type(:css) link(:stylesheet, *urls) end
ruby
def stylesheet(*urls) urls << {} unless urls.last.respond_to? :to_hash urls.last[:type] ||= mime_type(:css) link(:stylesheet, *urls) end
[ "def", "stylesheet", "(", "*", "urls", ")", "urls", "<<", "{", "}", "unless", "urls", ".", "last", ".", "respond_to?", ":to_hash", "urls", ".", "last", "[", ":type", "]", "||=", "mime_type", "(", ":css", ")", "link", "(", ":stylesheet", ",", "*", "urls", ")", "end" ]
Sets Link HTTP header and returns HTML tags for using stylesheets.
[ "Sets", "Link", "HTTP", "header", "and", "returns", "HTML", "tags", "for", "using", "stylesheets", "." ]
1aa64f9858edc3f93cc8d46e26f724c1ae103b1c
https://github.com/sinatra/sinatra/blob/1aa64f9858edc3f93cc8d46e26f724c1ae103b1c/sinatra-contrib/lib/sinatra/link_header.rb#L65-L69
train
sinatra/sinatra
sinatra-contrib/lib/sinatra/link_header.rb
Sinatra.LinkHeader.link
def link(*urls) opts = urls.last.respond_to?(:to_hash) ? urls.pop : {} opts[:rel] = urls.shift unless urls.first.respond_to? :to_str options = opts.map { |k, v| " #{k}=#{v.to_s.inspect}" } html_pattern = "<link href=\"%s\"#{options.join} />" http_pattern = ["<%s>", *options].join ";" link = (response["Link"] ||= "") urls.map do |url| link << ",\n" unless link.empty? link << (http_pattern % url) html_pattern % url end.join "\n" end
ruby
def link(*urls) opts = urls.last.respond_to?(:to_hash) ? urls.pop : {} opts[:rel] = urls.shift unless urls.first.respond_to? :to_str options = opts.map { |k, v| " #{k}=#{v.to_s.inspect}" } html_pattern = "<link href=\"%s\"#{options.join} />" http_pattern = ["<%s>", *options].join ";" link = (response["Link"] ||= "") urls.map do |url| link << ",\n" unless link.empty? link << (http_pattern % url) html_pattern % url end.join "\n" end
[ "def", "link", "(", "*", "urls", ")", "opts", "=", "urls", ".", "last", ".", "respond_to?", "(", ":to_hash", ")", "?", "urls", ".", "pop", ":", "{", "}", "opts", "[", ":rel", "]", "=", "urls", ".", "shift", "unless", "urls", ".", "first", ".", "respond_to?", ":to_str", "options", "=", "opts", ".", "map", "{", "|", "k", ",", "v", "|", "\" #{k}=#{v.to_s.inspect}\"", "}", "html_pattern", "=", "\"<link href=\\\"%s\\\"#{options.join} />\"", "http_pattern", "=", "[", "\"<%s>\"", ",", "*", "options", "]", ".", "join", "\";\"", "link", "=", "(", "response", "[", "\"Link\"", "]", "||=", "\"\"", ")", "urls", ".", "map", "do", "|", "url", "|", "link", "<<", "\",\\n\"", "unless", "link", ".", "empty?", "link", "<<", "(", "http_pattern", "%", "url", ")", "html_pattern", "%", "url", "end", ".", "join", "\"\\n\"", "end" ]
Sets Link HTTP header and returns corresponding HTML tags. Example: # Sets header: # Link: </foo>; rel="next" # Returns String: # '<link href="/foo" rel="next" />' link '/foo', :rel => :next # Multiple URLs link :stylesheet, '/a.css', '/b.css'
[ "Sets", "Link", "HTTP", "header", "and", "returns", "corresponding", "HTML", "tags", "." ]
1aa64f9858edc3f93cc8d46e26f724c1ae103b1c
https://github.com/sinatra/sinatra/blob/1aa64f9858edc3f93cc8d46e26f724c1ae103b1c/sinatra-contrib/lib/sinatra/link_header.rb#L84-L97
train
elastic/elasticsearch-ruby
profile/benchmarking.rb
Elasticsearch.Benchmarking.each_run
def each_run(file) if file file = File.new(file) matrix = YAML.load(ERB.new(file.read).result) file.close matrix.each_with_index do |run, i| DEFAULT_RUN.merge(run) yield(run, i) end else yield(DEFAULT_RUN) end end
ruby
def each_run(file) if file file = File.new(file) matrix = YAML.load(ERB.new(file.read).result) file.close matrix.each_with_index do |run, i| DEFAULT_RUN.merge(run) yield(run, i) end else yield(DEFAULT_RUN) end end
[ "def", "each_run", "(", "file", ")", "if", "file", "file", "=", "File", ".", "new", "(", "file", ")", "matrix", "=", "YAML", ".", "load", "(", "ERB", ".", "new", "(", "file", ".", "read", ")", ".", "result", ")", "file", ".", "close", "matrix", ".", "each_with_index", "do", "|", "run", ",", "i", "|", "DEFAULT_RUN", ".", "merge", "(", "run", ")", "yield", "(", "run", ",", "i", ")", "end", "else", "yield", "(", "DEFAULT_RUN", ")", "end", "end" ]
Parse a file of run definitions and yield each run. @params [ String ] file The YAML file containing the matrix of test run definitions. @yieldparam [ Hash ] A test run definition. @since 7.0.0
[ "Parse", "a", "file", "of", "run", "definitions", "and", "yield", "each", "run", "." ]
c0dd04834e5c7cf13792b4ced8e894c44d1f6f35
https://github.com/elastic/elasticsearch-ruby/blob/c0dd04834e5c7cf13792b4ced8e894c44d1f6f35/profile/benchmarking.rb#L70-L83
train
thoughtbot/factory_bot
lib/factory_bot/definition_proxy.rb
FactoryBot.DefinitionProxy.add_attribute
def add_attribute(name, &block) declaration = Declaration::Dynamic.new(name, @ignore, block) @definition.declare_attribute(declaration) end
ruby
def add_attribute(name, &block) declaration = Declaration::Dynamic.new(name, @ignore, block) @definition.declare_attribute(declaration) end
[ "def", "add_attribute", "(", "name", ",", "&", "block", ")", "declaration", "=", "Declaration", "::", "Dynamic", ".", "new", "(", "name", ",", "@ignore", ",", "block", ")", "@definition", ".", "declare_attribute", "(", "declaration", ")", "end" ]
Adds an attribute to the factory. The attribute value will be generated "lazily" by calling the block whenever an instance is generated. The block will not be called if the attribute is overridden for a specific instance. Arguments: * name: +Symbol+ or +String+ The name of this attribute. This will be assigned using "name=" for generated instances.
[ "Adds", "an", "attribute", "to", "the", "factory", ".", "The", "attribute", "value", "will", "be", "generated", "lazily", "by", "calling", "the", "block", "whenever", "an", "instance", "is", "generated", ".", "The", "block", "will", "not", "be", "called", "if", "the", "attribute", "is", "overridden", "for", "a", "specific", "instance", "." ]
99ac02400fd56bd1872fc3ed84f81ea5e8f27737
https://github.com/thoughtbot/factory_bot/blob/99ac02400fd56bd1872fc3ed84f81ea5e8f27737/lib/factory_bot/definition_proxy.rb#L47-L50
train
thoughtbot/factory_bot
lib/factory_bot/definition_proxy.rb
FactoryBot.DefinitionProxy.sequence
def sequence(name, *args, &block) sequence = Sequence.new(name, *args, &block) FactoryBot::Internal.register_inline_sequence(sequence) add_attribute(name) { increment_sequence(sequence) } end
ruby
def sequence(name, *args, &block) sequence = Sequence.new(name, *args, &block) FactoryBot::Internal.register_inline_sequence(sequence) add_attribute(name) { increment_sequence(sequence) } end
[ "def", "sequence", "(", "name", ",", "*", "args", ",", "&", "block", ")", "sequence", "=", "Sequence", ".", "new", "(", "name", ",", "*", "args", ",", "&", "block", ")", "FactoryBot", "::", "Internal", ".", "register_inline_sequence", "(", "sequence", ")", "add_attribute", "(", "name", ")", "{", "increment_sequence", "(", "sequence", ")", "}", "end" ]
Adds an attribute that will have unique values generated by a sequence with a specified format. The result of: factory :user do sequence(:email) { |n| "person#{n}@example.com" } end Is equal to: sequence(:email) { |n| "person#{n}@example.com" } factory :user do email { FactoryBot.generate(:email) } end Except that no globally available sequence will be defined.
[ "Adds", "an", "attribute", "that", "will", "have", "unique", "values", "generated", "by", "a", "sequence", "with", "a", "specified", "format", "." ]
99ac02400fd56bd1872fc3ed84f81ea5e8f27737
https://github.com/thoughtbot/factory_bot/blob/99ac02400fd56bd1872fc3ed84f81ea5e8f27737/lib/factory_bot/definition_proxy.rb#L122-L126
train
thoughtbot/factory_bot
lib/factory_bot/definition_proxy.rb
FactoryBot.DefinitionProxy.association
def association(name, *options) if block_given? raise AssociationDefinitionError.new( "Unexpected block passed to '#{name}' association "\ "in '#{@definition.name}' factory", ) else declaration = Declaration::Association.new(name, *options) @definition.declare_attribute(declaration) end end
ruby
def association(name, *options) if block_given? raise AssociationDefinitionError.new( "Unexpected block passed to '#{name}' association "\ "in '#{@definition.name}' factory", ) else declaration = Declaration::Association.new(name, *options) @definition.declare_attribute(declaration) end end
[ "def", "association", "(", "name", ",", "*", "options", ")", "if", "block_given?", "raise", "AssociationDefinitionError", ".", "new", "(", "\"Unexpected block passed to '#{name}' association \"", "\"in '#{@definition.name}' factory\"", ",", ")", "else", "declaration", "=", "Declaration", "::", "Association", ".", "new", "(", "name", ",", "*", "options", ")", "@definition", ".", "declare_attribute", "(", "declaration", ")", "end", "end" ]
Adds an attribute that builds an association. The associated instance will be built using the same build strategy as the parent instance. Example: factory :user do name 'Joey' end factory :post do association :author, factory: :user end Arguments: * name: +Symbol+ The name of this attribute. * options: +Hash+ Options: * factory: +Symbol+ or +String+ The name of the factory to use when building the associated instance. If no name is given, the name of the attribute is assumed to be the name of the factory. For example, a "user" association will by default use the "user" factory.
[ "Adds", "an", "attribute", "that", "builds", "an", "association", ".", "The", "associated", "instance", "will", "be", "built", "using", "the", "same", "build", "strategy", "as", "the", "parent", "instance", "." ]
99ac02400fd56bd1872fc3ed84f81ea5e8f27737
https://github.com/thoughtbot/factory_bot/blob/99ac02400fd56bd1872fc3ed84f81ea5e8f27737/lib/factory_bot/definition_proxy.rb#L151-L161
train
rmosolgo/graphql-ruby
lib/graphql/query.rb
GraphQL.Query.lookahead
def lookahead @lookahead ||= begin ast_node = selected_operation root_type = warden.root_type_for_operation(ast_node.operation_type || "query") root_type = root_type.metadata[:type_class] || raise("Invariant: `lookahead` only works with class-based types") GraphQL::Execution::Lookahead.new(query: self, root_type: root_type, ast_nodes: [ast_node]) end end
ruby
def lookahead @lookahead ||= begin ast_node = selected_operation root_type = warden.root_type_for_operation(ast_node.operation_type || "query") root_type = root_type.metadata[:type_class] || raise("Invariant: `lookahead` only works with class-based types") GraphQL::Execution::Lookahead.new(query: self, root_type: root_type, ast_nodes: [ast_node]) end end
[ "def", "lookahead", "@lookahead", "||=", "begin", "ast_node", "=", "selected_operation", "root_type", "=", "warden", ".", "root_type_for_operation", "(", "ast_node", ".", "operation_type", "||", "\"query\"", ")", "root_type", "=", "root_type", ".", "metadata", "[", ":type_class", "]", "||", "raise", "(", "\"Invariant: `lookahead` only works with class-based types\"", ")", "GraphQL", "::", "Execution", "::", "Lookahead", ".", "new", "(", "query", ":", "self", ",", "root_type", ":", "root_type", ",", "ast_nodes", ":", "[", "ast_node", "]", ")", "end", "end" ]
A lookahead for the root selections of this query @return [GraphQL::Execution::Lookahead]
[ "A", "lookahead", "for", "the", "root", "selections", "of", "this", "query" ]
d5be13a816f220b9efbabeaa69a3e56fedf311f5
https://github.com/rmosolgo/graphql-ruby/blob/d5be13a816f220b9efbabeaa69a3e56fedf311f5/lib/graphql/query.rb#L151-L158
train
rmosolgo/graphql-ruby
lib/graphql/query.rb
GraphQL.Query.result
def result if !@executed with_prepared_ast { Execution::Multiplex.run_queries(@schema, [self], context: @context) } end @result ||= Query::Result.new(query: self, values: @result_values) end
ruby
def result if !@executed with_prepared_ast { Execution::Multiplex.run_queries(@schema, [self], context: @context) } end @result ||= Query::Result.new(query: self, values: @result_values) end
[ "def", "result", "if", "!", "@executed", "with_prepared_ast", "{", "Execution", "::", "Multiplex", ".", "run_queries", "(", "@schema", ",", "[", "self", "]", ",", "context", ":", "@context", ")", "}", "end", "@result", "||=", "Query", "::", "Result", ".", "new", "(", "query", ":", "self", ",", "values", ":", "@result_values", ")", "end" ]
Get the result for this query, executing it once @return [Hash] A GraphQL response, with `"data"` and/or `"errors"` keys
[ "Get", "the", "result", "for", "this", "query", "executing", "it", "once" ]
d5be13a816f220b9efbabeaa69a3e56fedf311f5
https://github.com/rmosolgo/graphql-ruby/blob/d5be13a816f220b9efbabeaa69a3e56fedf311f5/lib/graphql/query.rb#L183-L190
train
rmosolgo/graphql-ruby
lib/graphql/object_type.rb
GraphQL.ObjectType.implements
def implements(interfaces, inherit: false) if !interfaces.is_a?(Array) raise ArgumentError, "`implements(interfaces)` must be an array, not #{interfaces.class} (#{interfaces})" end @clean_interfaces = nil @clean_inherited_fields = nil dirty_ifaces = inherit ? @dirty_inherited_interfaces : @dirty_interfaces dirty_ifaces.concat(interfaces) end
ruby
def implements(interfaces, inherit: false) if !interfaces.is_a?(Array) raise ArgumentError, "`implements(interfaces)` must be an array, not #{interfaces.class} (#{interfaces})" end @clean_interfaces = nil @clean_inherited_fields = nil dirty_ifaces = inherit ? @dirty_inherited_interfaces : @dirty_interfaces dirty_ifaces.concat(interfaces) end
[ "def", "implements", "(", "interfaces", ",", "inherit", ":", "false", ")", "if", "!", "interfaces", ".", "is_a?", "(", "Array", ")", "raise", "ArgumentError", ",", "\"`implements(interfaces)` must be an array, not #{interfaces.class} (#{interfaces})\"", "end", "@clean_interfaces", "=", "nil", "@clean_inherited_fields", "=", "nil", "dirty_ifaces", "=", "inherit", "?", "@dirty_inherited_interfaces", ":", "@dirty_interfaces", "dirty_ifaces", ".", "concat", "(", "interfaces", ")", "end" ]
Declare that this object implements this interface. This declaration will be validated when the schema is defined. @param interfaces [Array<GraphQL::Interface>] add a new interface that this type implements @param inherits [Boolean] If true, copy the interfaces' field definitions to this type
[ "Declare", "that", "this", "object", "implements", "this", "interface", ".", "This", "declaration", "will", "be", "validated", "when", "the", "schema", "is", "defined", "." ]
d5be13a816f220b9efbabeaa69a3e56fedf311f5
https://github.com/rmosolgo/graphql-ruby/blob/d5be13a816f220b9efbabeaa69a3e56fedf311f5/lib/graphql/object_type.rb#L94-L103
train
rmosolgo/graphql-ruby
lib/graphql/backwards_compatibility.rb
GraphQL.BackwardsCompatibility.wrap_arity
def wrap_arity(callable, from:, to:, name:, last: false) arity = get_arity(callable) if arity == to || arity < 0 # It already matches, return it as is callable elsif arity == from # It has the old arity, so wrap it with an arity converter message ="#{name} with #{from} arguments is deprecated, it now accepts #{to} arguments, see:" backtrace = caller(0, 20) # Find the first line in the trace that isn't library internals: user_line = backtrace.find {|l| l !~ /lib\/graphql/ } warn(message + "\n" + user_line + "\n") wrapper = last ? LastArgumentsWrapper : FirstArgumentsWrapper wrapper.new(callable, from) else raise "Can't wrap #{callable} (arity: #{arity}) to have arity #{to}" end end
ruby
def wrap_arity(callable, from:, to:, name:, last: false) arity = get_arity(callable) if arity == to || arity < 0 # It already matches, return it as is callable elsif arity == from # It has the old arity, so wrap it with an arity converter message ="#{name} with #{from} arguments is deprecated, it now accepts #{to} arguments, see:" backtrace = caller(0, 20) # Find the first line in the trace that isn't library internals: user_line = backtrace.find {|l| l !~ /lib\/graphql/ } warn(message + "\n" + user_line + "\n") wrapper = last ? LastArgumentsWrapper : FirstArgumentsWrapper wrapper.new(callable, from) else raise "Can't wrap #{callable} (arity: #{arity}) to have arity #{to}" end end
[ "def", "wrap_arity", "(", "callable", ",", "from", ":", ",", "to", ":", ",", "name", ":", ",", "last", ":", "false", ")", "arity", "=", "get_arity", "(", "callable", ")", "if", "arity", "==", "to", "||", "arity", "<", "0", "callable", "elsif", "arity", "==", "from", "message", "=", "\"#{name} with #{from} arguments is deprecated, it now accepts #{to} arguments, see:\"", "backtrace", "=", "caller", "(", "0", ",", "20", ")", "user_line", "=", "backtrace", ".", "find", "{", "|", "l", "|", "l", "!~", "/", "\\/", "/", "}", "warn", "(", "message", "+", "\"\\n\"", "+", "user_line", "+", "\"\\n\"", ")", "wrapper", "=", "last", "?", "LastArgumentsWrapper", ":", "FirstArgumentsWrapper", "wrapper", ".", "new", "(", "callable", ",", "from", ")", "else", "raise", "\"Can't wrap #{callable} (arity: #{arity}) to have arity #{to}\"", "end", "end" ]
Given a callable whose API used to take `from` arguments, check its arity, and if needed, apply a wrapper so that it can be called with `to` arguments. If a wrapper is applied, warn the application with `name`. If `last`, then use the last arguments to call the function.
[ "Given", "a", "callable", "whose", "API", "used", "to", "take", "from", "arguments", "check", "its", "arity", "and", "if", "needed", "apply", "a", "wrapper", "so", "that", "it", "can", "be", "called", "with", "to", "arguments", ".", "If", "a", "wrapper", "is", "applied", "warn", "the", "application", "with", "name", "." ]
d5be13a816f220b9efbabeaa69a3e56fedf311f5
https://github.com/rmosolgo/graphql-ruby/blob/d5be13a816f220b9efbabeaa69a3e56fedf311f5/lib/graphql/backwards_compatibility.rb#L13-L30
train
rmosolgo/graphql-ruby
lib/graphql/subscriptions.rb
GraphQL.Subscriptions.execute
def execute(subscription_id, event, object) # Lookup the saved data for this subscription query_data = read_subscription(subscription_id) # Fetch the required keys from the saved data query_string = query_data.fetch(:query_string) variables = query_data.fetch(:variables) context = query_data.fetch(:context) operation_name = query_data.fetch(:operation_name) # Re-evaluate the saved query result = @schema.execute( { query: query_string, context: context, subscription_topic: event.topic, operation_name: operation_name, variables: variables, root_value: object, } ) deliver(subscription_id, result) rescue GraphQL::Schema::Subscription::NoUpdateError # This update was skipped in user code; do nothing. rescue GraphQL::Schema::Subscription::UnsubscribedError # `unsubscribe` was called, clean up on our side # TODO also send `{more: false}` to client? delete_subscription(subscription_id) end
ruby
def execute(subscription_id, event, object) # Lookup the saved data for this subscription query_data = read_subscription(subscription_id) # Fetch the required keys from the saved data query_string = query_data.fetch(:query_string) variables = query_data.fetch(:variables) context = query_data.fetch(:context) operation_name = query_data.fetch(:operation_name) # Re-evaluate the saved query result = @schema.execute( { query: query_string, context: context, subscription_topic: event.topic, operation_name: operation_name, variables: variables, root_value: object, } ) deliver(subscription_id, result) rescue GraphQL::Schema::Subscription::NoUpdateError # This update was skipped in user code; do nothing. rescue GraphQL::Schema::Subscription::UnsubscribedError # `unsubscribe` was called, clean up on our side # TODO also send `{more: false}` to client? delete_subscription(subscription_id) end
[ "def", "execute", "(", "subscription_id", ",", "event", ",", "object", ")", "query_data", "=", "read_subscription", "(", "subscription_id", ")", "query_string", "=", "query_data", ".", "fetch", "(", ":query_string", ")", "variables", "=", "query_data", ".", "fetch", "(", ":variables", ")", "context", "=", "query_data", ".", "fetch", "(", ":context", ")", "operation_name", "=", "query_data", ".", "fetch", "(", ":operation_name", ")", "result", "=", "@schema", ".", "execute", "(", "{", "query", ":", "query_string", ",", "context", ":", "context", ",", "subscription_topic", ":", "event", ".", "topic", ",", "operation_name", ":", "operation_name", ",", "variables", ":", "variables", ",", "root_value", ":", "object", ",", "}", ")", "deliver", "(", "subscription_id", ",", "result", ")", "rescue", "GraphQL", "::", "Schema", "::", "Subscription", "::", "NoUpdateError", "rescue", "GraphQL", "::", "Schema", "::", "Subscription", "::", "UnsubscribedError", "delete_subscription", "(", "subscription_id", ")", "end" ]
`event` was triggered on `object`, and `subscription_id` was subscribed, so it should be updated. Load `subscription_id`'s GraphQL data, re-evaluate the query, and deliver the result. This is where a queue may be inserted to push updates in the background. @param subscription_id [String] @param event [GraphQL::Subscriptions::Event] The event which was triggered @param object [Object] The value for the subscription field @return [void]
[ "event", "was", "triggered", "on", "object", "and", "subscription_id", "was", "subscribed", "so", "it", "should", "be", "updated", "." ]
d5be13a816f220b9efbabeaa69a3e56fedf311f5
https://github.com/rmosolgo/graphql-ruby/blob/d5be13a816f220b9efbabeaa69a3e56fedf311f5/lib/graphql/subscriptions.rb#L83-L109
train
rmosolgo/graphql-ruby
lib/graphql/subscriptions.rb
GraphQL.Subscriptions.execute_all
def execute_all(event, object) each_subscription_id(event) do |subscription_id| execute(subscription_id, event, object) end end
ruby
def execute_all(event, object) each_subscription_id(event) do |subscription_id| execute(subscription_id, event, object) end end
[ "def", "execute_all", "(", "event", ",", "object", ")", "each_subscription_id", "(", "event", ")", "do", "|", "subscription_id", "|", "execute", "(", "subscription_id", ",", "event", ",", "object", ")", "end", "end" ]
Event `event` occurred on `object`, Update all subscribers. @param event [Subscriptions::Event] @param object [Object] @return [void]
[ "Event", "event", "occurred", "on", "object", "Update", "all", "subscribers", "." ]
d5be13a816f220b9efbabeaa69a3e56fedf311f5
https://github.com/rmosolgo/graphql-ruby/blob/d5be13a816f220b9efbabeaa69a3e56fedf311f5/lib/graphql/subscriptions.rb#L116-L120
train
rmosolgo/graphql-ruby
lib/graphql/base_type.rb
GraphQL.BaseType.to_definition
def to_definition(schema, printer: nil, **args) printer ||= GraphQL::Schema::Printer.new(schema, **args) printer.print_type(self) end
ruby
def to_definition(schema, printer: nil, **args) printer ||= GraphQL::Schema::Printer.new(schema, **args) printer.print_type(self) end
[ "def", "to_definition", "(", "schema", ",", "printer", ":", "nil", ",", "**", "args", ")", "printer", "||=", "GraphQL", "::", "Schema", "::", "Printer", ".", "new", "(", "schema", ",", "**", "args", ")", "printer", ".", "print_type", "(", "self", ")", "end" ]
Return a GraphQL string for the type definition @param schema [GraphQL::Schema] @param printer [GraphQL::Schema::Printer] @see {GraphQL::Schema::Printer#initialize for additional options} @return [String] type definition
[ "Return", "a", "GraphQL", "string", "for", "the", "type", "definition" ]
d5be13a816f220b9efbabeaa69a3e56fedf311f5
https://github.com/rmosolgo/graphql-ruby/blob/d5be13a816f220b9efbabeaa69a3e56fedf311f5/lib/graphql/base_type.rb#L205-L208
train
rmosolgo/graphql-ruby
lib/graphql/rake_task.rb
GraphQL.RakeTask.write_outfile
def write_outfile(method_name, file) schema = @load_schema.call(self) context = @load_context.call(self) result = schema.public_send(method_name, only: @only, except: @except, context: context) dir = File.dirname(file) FileUtils.mkdir_p(dir) File.write(file, result) end
ruby
def write_outfile(method_name, file) schema = @load_schema.call(self) context = @load_context.call(self) result = schema.public_send(method_name, only: @only, except: @except, context: context) dir = File.dirname(file) FileUtils.mkdir_p(dir) File.write(file, result) end
[ "def", "write_outfile", "(", "method_name", ",", "file", ")", "schema", "=", "@load_schema", ".", "call", "(", "self", ")", "context", "=", "@load_context", ".", "call", "(", "self", ")", "result", "=", "schema", ".", "public_send", "(", "method_name", ",", "only", ":", "@only", ",", "except", ":", "@except", ",", "context", ":", "context", ")", "dir", "=", "File", ".", "dirname", "(", "file", ")", "FileUtils", ".", "mkdir_p", "(", "dir", ")", "File", ".", "write", "(", "file", ",", "result", ")", "end" ]
Use the provided `method_name` to generate a string from the specified schema then write it to `file`.
[ "Use", "the", "provided", "method_name", "to", "generate", "a", "string", "from", "the", "specified", "schema", "then", "write", "it", "to", "file", "." ]
d5be13a816f220b9efbabeaa69a3e56fedf311f5
https://github.com/rmosolgo/graphql-ruby/blob/d5be13a816f220b9efbabeaa69a3e56fedf311f5/lib/graphql/rake_task.rb#L103-L110
train
rmosolgo/graphql-ruby
lib/graphql/rake_task.rb
GraphQL.RakeTask.define_task
def define_task namespace(@namespace) do namespace("schema") do desc("Dump the schema to IDL in #{idl_path}") task :idl => @dependencies do write_outfile(:to_definition, idl_path) puts "Schema IDL dumped into #{idl_path}" end desc("Dump the schema to JSON in #{json_path}") task :json => @dependencies do write_outfile(:to_json, json_path) puts "Schema JSON dumped into #{json_path}" end desc("Dump the schema to JSON and IDL") task :dump => [:idl, :json] end end end
ruby
def define_task namespace(@namespace) do namespace("schema") do desc("Dump the schema to IDL in #{idl_path}") task :idl => @dependencies do write_outfile(:to_definition, idl_path) puts "Schema IDL dumped into #{idl_path}" end desc("Dump the schema to JSON in #{json_path}") task :json => @dependencies do write_outfile(:to_json, json_path) puts "Schema JSON dumped into #{json_path}" end desc("Dump the schema to JSON and IDL") task :dump => [:idl, :json] end end end
[ "def", "define_task", "namespace", "(", "@namespace", ")", "do", "namespace", "(", "\"schema\"", ")", "do", "desc", "(", "\"Dump the schema to IDL in #{idl_path}\"", ")", "task", ":idl", "=>", "@dependencies", "do", "write_outfile", "(", ":to_definition", ",", "idl_path", ")", "puts", "\"Schema IDL dumped into #{idl_path}\"", "end", "desc", "(", "\"Dump the schema to JSON in #{json_path}\"", ")", "task", ":json", "=>", "@dependencies", "do", "write_outfile", "(", ":to_json", ",", "json_path", ")", "puts", "\"Schema JSON dumped into #{json_path}\"", "end", "desc", "(", "\"Dump the schema to JSON and IDL\"", ")", "task", ":dump", "=>", "[", ":idl", ",", ":json", "]", "end", "end", "end" ]
Use the Rake DSL to add tasks
[ "Use", "the", "Rake", "DSL", "to", "add", "tasks" ]
d5be13a816f220b9efbabeaa69a3e56fedf311f5
https://github.com/rmosolgo/graphql-ruby/blob/d5be13a816f220b9efbabeaa69a3e56fedf311f5/lib/graphql/rake_task.rb#L121-L140
train
rmosolgo/graphql-ruby
lib/graphql/field.rb
GraphQL.Field.prepare_lazy
def prepare_lazy(obj, args, ctx) GraphQL::Execution::Lazy.new { lazy_resolve(obj, args, ctx) } end
ruby
def prepare_lazy(obj, args, ctx) GraphQL::Execution::Lazy.new { lazy_resolve(obj, args, ctx) } end
[ "def", "prepare_lazy", "(", "obj", ",", "args", ",", "ctx", ")", "GraphQL", "::", "Execution", "::", "Lazy", ".", "new", "{", "lazy_resolve", "(", "obj", ",", "args", ",", "ctx", ")", "}", "end" ]
Prepare a lazy value for this field. It may be `then`-ed and resolved later. @return [GraphQL::Execution::Lazy] A lazy wrapper around `obj` and its registered method name
[ "Prepare", "a", "lazy", "value", "for", "this", "field", ".", "It", "may", "be", "then", "-", "ed", "and", "resolved", "later", "." ]
d5be13a816f220b9efbabeaa69a3e56fedf311f5
https://github.com/rmosolgo/graphql-ruby/blob/d5be13a816f220b9efbabeaa69a3e56fedf311f5/lib/graphql/field.rb#L312-L316
train
rmosolgo/graphql-ruby
lib/graphql/filter.rb
GraphQL.Filter.call
def call(member, ctx) (@only ? @only.call(member, ctx) : true) && (@except ? [email protected](member, ctx) : true) end
ruby
def call(member, ctx) (@only ? @only.call(member, ctx) : true) && (@except ? [email protected](member, ctx) : true) end
[ "def", "call", "(", "member", ",", "ctx", ")", "(", "@only", "?", "@only", ".", "call", "(", "member", ",", "ctx", ")", ":", "true", ")", "&&", "(", "@except", "?", "!", "@except", ".", "call", "(", "member", ",", "ctx", ")", ":", "true", ")", "end" ]
Returns true if `member, ctx` passes this filter
[ "Returns", "true", "if", "member", "ctx", "passes", "this", "filter" ]
d5be13a816f220b9efbabeaa69a3e56fedf311f5
https://github.com/rmosolgo/graphql-ruby/blob/d5be13a816f220b9efbabeaa69a3e56fedf311f5/lib/graphql/filter.rb#L11-L14
train
rmosolgo/graphql-ruby
lib/graphql/analysis/analyze_query.rb
GraphQL.Analysis.analyze_query
def analyze_query(query, analyzers, multiplex_states: []) query.trace("analyze_query", { query: query }) do analyzers_to_run = analyzers.select do |analyzer| if analyzer.respond_to?(:analyze?) analyzer.analyze?(query) else true end end reducer_states = analyzers_to_run.map { |r| ReducerState.new(r, query) } + multiplex_states irep = query.internal_representation irep.operation_definitions.each do |name, op_node| reduce_node(op_node, reducer_states) end reducer_states.map(&:finalize_reducer) end end
ruby
def analyze_query(query, analyzers, multiplex_states: []) query.trace("analyze_query", { query: query }) do analyzers_to_run = analyzers.select do |analyzer| if analyzer.respond_to?(:analyze?) analyzer.analyze?(query) else true end end reducer_states = analyzers_to_run.map { |r| ReducerState.new(r, query) } + multiplex_states irep = query.internal_representation irep.operation_definitions.each do |name, op_node| reduce_node(op_node, reducer_states) end reducer_states.map(&:finalize_reducer) end end
[ "def", "analyze_query", "(", "query", ",", "analyzers", ",", "multiplex_states", ":", "[", "]", ")", "query", ".", "trace", "(", "\"analyze_query\"", ",", "{", "query", ":", "query", "}", ")", "do", "analyzers_to_run", "=", "analyzers", ".", "select", "do", "|", "analyzer", "|", "if", "analyzer", ".", "respond_to?", "(", ":analyze?", ")", "analyzer", ".", "analyze?", "(", "query", ")", "else", "true", "end", "end", "reducer_states", "=", "analyzers_to_run", ".", "map", "{", "|", "r", "|", "ReducerState", ".", "new", "(", "r", ",", "query", ")", "}", "+", "multiplex_states", "irep", "=", "query", ".", "internal_representation", "irep", ".", "operation_definitions", ".", "each", "do", "|", "name", ",", "op_node", "|", "reduce_node", "(", "op_node", ",", "reducer_states", ")", "end", "reducer_states", ".", "map", "(", "&", ":finalize_reducer", ")", "end", "end" ]
Visit `query`'s internal representation, calling `analyzers` along the way. - First, query analyzers are filtered down by calling `.analyze?(query)`, if they respond to that method - Then, query analyzers are initialized by calling `.initial_value(query)`, if they respond to that method. - Then, they receive `.call(memo, visit_type, irep_node)`, where visit type is `:enter` or `:leave`. - Last, they receive `.final_value(memo)`, if they respond to that method. It returns an array of final `memo` values in the order that `analyzers` were passed in. @param query [GraphQL::Query] @param analyzers [Array<#call>] Objects that respond to `#call(memo, visit_type, irep_node)` @return [Array<Any>] Results from those analyzers
[ "Visit", "query", "s", "internal", "representation", "calling", "analyzers", "along", "the", "way", "." ]
d5be13a816f220b9efbabeaa69a3e56fedf311f5
https://github.com/rmosolgo/graphql-ruby/blob/d5be13a816f220b9efbabeaa69a3e56fedf311f5/lib/graphql/analysis/analyze_query.rb#L40-L60
train
rmosolgo/graphql-ruby
lib/graphql/analysis/analyze_query.rb
GraphQL.Analysis.reduce_node
def reduce_node(irep_node, reducer_states) visit_analyzers(:enter, irep_node, reducer_states) irep_node.typed_children.each do |type_defn, children| children.each do |name, child_irep_node| reduce_node(child_irep_node, reducer_states) end end visit_analyzers(:leave, irep_node, reducer_states) end
ruby
def reduce_node(irep_node, reducer_states) visit_analyzers(:enter, irep_node, reducer_states) irep_node.typed_children.each do |type_defn, children| children.each do |name, child_irep_node| reduce_node(child_irep_node, reducer_states) end end visit_analyzers(:leave, irep_node, reducer_states) end
[ "def", "reduce_node", "(", "irep_node", ",", "reducer_states", ")", "visit_analyzers", "(", ":enter", ",", "irep_node", ",", "reducer_states", ")", "irep_node", ".", "typed_children", ".", "each", "do", "|", "type_defn", ",", "children", "|", "children", ".", "each", "do", "|", "name", ",", "child_irep_node", "|", "reduce_node", "(", "child_irep_node", ",", "reducer_states", ")", "end", "end", "visit_analyzers", "(", ":leave", ",", "irep_node", ",", "reducer_states", ")", "end" ]
Enter the node, visit its children, then leave the node.
[ "Enter", "the", "node", "visit", "its", "children", "then", "leave", "the", "node", "." ]
d5be13a816f220b9efbabeaa69a3e56fedf311f5
https://github.com/rmosolgo/graphql-ruby/blob/d5be13a816f220b9efbabeaa69a3e56fedf311f5/lib/graphql/analysis/analyze_query.rb#L67-L77
train
rmosolgo/graphql-ruby
lib/graphql/schema.rb
GraphQL.Schema.validate
def validate(string_or_document, rules: nil, context: nil) doc = if string_or_document.is_a?(String) GraphQL.parse(string_or_document) else string_or_document end query = GraphQL::Query.new(self, document: doc, context: context) validator_opts = { schema: self } rules && (validator_opts[:rules] = rules) validator = GraphQL::StaticValidation::Validator.new(validator_opts) res = validator.validate(query) res[:errors] end
ruby
def validate(string_or_document, rules: nil, context: nil) doc = if string_or_document.is_a?(String) GraphQL.parse(string_or_document) else string_or_document end query = GraphQL::Query.new(self, document: doc, context: context) validator_opts = { schema: self } rules && (validator_opts[:rules] = rules) validator = GraphQL::StaticValidation::Validator.new(validator_opts) res = validator.validate(query) res[:errors] end
[ "def", "validate", "(", "string_or_document", ",", "rules", ":", "nil", ",", "context", ":", "nil", ")", "doc", "=", "if", "string_or_document", ".", "is_a?", "(", "String", ")", "GraphQL", ".", "parse", "(", "string_or_document", ")", "else", "string_or_document", "end", "query", "=", "GraphQL", "::", "Query", ".", "new", "(", "self", ",", "document", ":", "doc", ",", "context", ":", "context", ")", "validator_opts", "=", "{", "schema", ":", "self", "}", "rules", "&&", "(", "validator_opts", "[", ":rules", "]", "=", "rules", ")", "validator", "=", "GraphQL", "::", "StaticValidation", "::", "Validator", ".", "new", "(", "validator_opts", ")", "res", "=", "validator", ".", "validate", "(", "query", ")", "res", "[", ":errors", "]", "end" ]
Validate a query string according to this schema. @param string_or_document [String, GraphQL::Language::Nodes::Document] @return [Array<GraphQL::StaticValidation::Error >]
[ "Validate", "a", "query", "string", "according", "to", "this", "schema", "." ]
d5be13a816f220b9efbabeaa69a3e56fedf311f5
https://github.com/rmosolgo/graphql-ruby/blob/d5be13a816f220b9efbabeaa69a3e56fedf311f5/lib/graphql/schema.rb#L249-L261
train
rmosolgo/graphql-ruby
lib/graphql/schema.rb
GraphQL.Schema.execute
def execute(query_str = nil, **kwargs) if query_str kwargs[:query] = query_str end # Some of the query context _should_ be passed to the multiplex, too multiplex_context = if (ctx = kwargs[:context]) { backtrace: ctx[:backtrace], tracers: ctx[:tracers], } else {} end # Since we're running one query, don't run a multiplex-level complexity analyzer all_results = multiplex([kwargs], max_complexity: nil, context: multiplex_context) all_results[0] end
ruby
def execute(query_str = nil, **kwargs) if query_str kwargs[:query] = query_str end # Some of the query context _should_ be passed to the multiplex, too multiplex_context = if (ctx = kwargs[:context]) { backtrace: ctx[:backtrace], tracers: ctx[:tracers], } else {} end # Since we're running one query, don't run a multiplex-level complexity analyzer all_results = multiplex([kwargs], max_complexity: nil, context: multiplex_context) all_results[0] end
[ "def", "execute", "(", "query_str", "=", "nil", ",", "**", "kwargs", ")", "if", "query_str", "kwargs", "[", ":query", "]", "=", "query_str", "end", "multiplex_context", "=", "if", "(", "ctx", "=", "kwargs", "[", ":context", "]", ")", "{", "backtrace", ":", "ctx", "[", ":backtrace", "]", ",", "tracers", ":", "ctx", "[", ":tracers", "]", ",", "}", "else", "{", "}", "end", "all_results", "=", "multiplex", "(", "[", "kwargs", "]", ",", "max_complexity", ":", "nil", ",", "context", ":", "multiplex_context", ")", "all_results", "[", "0", "]", "end" ]
Execute a query on itself. Raises an error if the schema definition is invalid. @see {Query#initialize} for arguments. @return [Hash] query result, ready to be serialized as JSON
[ "Execute", "a", "query", "on", "itself", ".", "Raises", "an", "error", "if", "the", "schema", "definition", "is", "invalid", "." ]
d5be13a816f220b9efbabeaa69a3e56fedf311f5
https://github.com/rmosolgo/graphql-ruby/blob/d5be13a816f220b9efbabeaa69a3e56fedf311f5/lib/graphql/schema.rb#L338-L354
train
rmosolgo/graphql-ruby
lib/graphql/schema.rb
GraphQL.Schema.check_resolved_type
def check_resolved_type(type, object, ctx = :__undefined__) if ctx == :__undefined__ # Old method signature ctx = object object = type type = nil end if object.is_a?(GraphQL::Schema::Object) object = object.object end if type.respond_to?(:graphql_definition) type = type.graphql_definition end # Prefer a type-local function; fall back to the schema-level function type_proc = type && type.resolve_type_proc type_result = if type_proc type_proc.call(object, ctx) else yield(type, object, ctx) end if type_result.nil? nil else after_lazy(type_result) do |resolved_type_result| if resolved_type_result.respond_to?(:graphql_definition) resolved_type_result = resolved_type_result.graphql_definition end if !resolved_type_result.is_a?(GraphQL::BaseType) type_str = "#{resolved_type_result} (#{resolved_type_result.class.name})" raise "resolve_type(#{object}) returned #{type_str}, but it should return a GraphQL type" else resolved_type_result end end end end
ruby
def check_resolved_type(type, object, ctx = :__undefined__) if ctx == :__undefined__ # Old method signature ctx = object object = type type = nil end if object.is_a?(GraphQL::Schema::Object) object = object.object end if type.respond_to?(:graphql_definition) type = type.graphql_definition end # Prefer a type-local function; fall back to the schema-level function type_proc = type && type.resolve_type_proc type_result = if type_proc type_proc.call(object, ctx) else yield(type, object, ctx) end if type_result.nil? nil else after_lazy(type_result) do |resolved_type_result| if resolved_type_result.respond_to?(:graphql_definition) resolved_type_result = resolved_type_result.graphql_definition end if !resolved_type_result.is_a?(GraphQL::BaseType) type_str = "#{resolved_type_result} (#{resolved_type_result.class.name})" raise "resolve_type(#{object}) returned #{type_str}, but it should return a GraphQL type" else resolved_type_result end end end end
[ "def", "check_resolved_type", "(", "type", ",", "object", ",", "ctx", "=", ":__undefined__", ")", "if", "ctx", "==", ":__undefined__", "ctx", "=", "object", "object", "=", "type", "type", "=", "nil", "end", "if", "object", ".", "is_a?", "(", "GraphQL", "::", "Schema", "::", "Object", ")", "object", "=", "object", ".", "object", "end", "if", "type", ".", "respond_to?", "(", ":graphql_definition", ")", "type", "=", "type", ".", "graphql_definition", "end", "type_proc", "=", "type", "&&", "type", ".", "resolve_type_proc", "type_result", "=", "if", "type_proc", "type_proc", ".", "call", "(", "object", ",", "ctx", ")", "else", "yield", "(", "type", ",", "object", ",", "ctx", ")", "end", "if", "type_result", ".", "nil?", "nil", "else", "after_lazy", "(", "type_result", ")", "do", "|", "resolved_type_result", "|", "if", "resolved_type_result", ".", "respond_to?", "(", ":graphql_definition", ")", "resolved_type_result", "=", "resolved_type_result", ".", "graphql_definition", "end", "if", "!", "resolved_type_result", ".", "is_a?", "(", "GraphQL", "::", "BaseType", ")", "type_str", "=", "\"#{resolved_type_result} (#{resolved_type_result.class.name})\"", "raise", "\"resolve_type(#{object}) returned #{type_str}, but it should return a GraphQL type\"", "else", "resolved_type_result", "end", "end", "end", "end" ]
This is a compatibility hack so that instance-level and class-level methods can get correctness checks without calling one another @api private
[ "This", "is", "a", "compatibility", "hack", "so", "that", "instance", "-", "level", "and", "class", "-", "level", "methods", "can", "get", "correctness", "checks", "without", "calling", "one", "another" ]
d5be13a816f220b9efbabeaa69a3e56fedf311f5
https://github.com/rmosolgo/graphql-ruby/blob/d5be13a816f220b9efbabeaa69a3e56fedf311f5/lib/graphql/schema.rb#L488-L527
train
rmosolgo/graphql-ruby
lib/graphql/schema.rb
GraphQL.Schema.id_from_object
def id_from_object(object, type, ctx) if @id_from_object_proc.nil? raise(NotImplementedError, "Can't generate an ID for #{object.inspect} of type #{type}, schema's `id_from_object` must be defined") else @id_from_object_proc.call(object, type, ctx) end end
ruby
def id_from_object(object, type, ctx) if @id_from_object_proc.nil? raise(NotImplementedError, "Can't generate an ID for #{object.inspect} of type #{type}, schema's `id_from_object` must be defined") else @id_from_object_proc.call(object, type, ctx) end end
[ "def", "id_from_object", "(", "object", ",", "type", ",", "ctx", ")", "if", "@id_from_object_proc", ".", "nil?", "raise", "(", "NotImplementedError", ",", "\"Can't generate an ID for #{object.inspect} of type #{type}, schema's `id_from_object` must be defined\"", ")", "else", "@id_from_object_proc", ".", "call", "(", "object", ",", "type", ",", "ctx", ")", "end", "end" ]
Get a unique identifier from this object @param object [Any] An application object @param type [GraphQL::BaseType] The current type definition @param ctx [GraphQL::Query::Context] the context for the current query @return [String] a unique identifier for `object` which clients can use to refetch it
[ "Get", "a", "unique", "identifier", "from", "this", "object" ]
d5be13a816f220b9efbabeaa69a3e56fedf311f5
https://github.com/rmosolgo/graphql-ruby/blob/d5be13a816f220b9efbabeaa69a3e56fedf311f5/lib/graphql/schema.rb#L605-L611
train
rmosolgo/graphql-ruby
lib/graphql/schema.rb
GraphQL.Schema.to_definition
def to_definition(only: nil, except: nil, context: {}) GraphQL::Schema::Printer.print_schema(self, only: only, except: except, context: context) end
ruby
def to_definition(only: nil, except: nil, context: {}) GraphQL::Schema::Printer.print_schema(self, only: only, except: except, context: context) end
[ "def", "to_definition", "(", "only", ":", "nil", ",", "except", ":", "nil", ",", "context", ":", "{", "}", ")", "GraphQL", "::", "Schema", "::", "Printer", ".", "print_schema", "(", "self", ",", "only", ":", "only", ",", "except", ":", "except", ",", "context", ":", "context", ")", "end" ]
Return the GraphQL IDL for the schema @param context [Hash] @param only [<#call(member, ctx)>] @param except [<#call(member, ctx)>] @return [String]
[ "Return", "the", "GraphQL", "IDL", "for", "the", "schema" ]
d5be13a816f220b9efbabeaa69a3e56fedf311f5
https://github.com/rmosolgo/graphql-ruby/blob/d5be13a816f220b9efbabeaa69a3e56fedf311f5/lib/graphql/schema.rb#L658-L660
train
rmosolgo/graphql-ruby
lib/graphql/enum_type.rb
GraphQL.EnumType.coerce_non_null_input
def coerce_non_null_input(value_name, ctx) if @values_by_name.key?(value_name) @values_by_name.fetch(value_name).value elsif match_by_value = @values_by_name.find { |k, v| v.value == value_name } # this is for matching default values, which are "inputs", but they're # the Ruby value, not the GraphQL string. match_by_value[1].value else nil end end
ruby
def coerce_non_null_input(value_name, ctx) if @values_by_name.key?(value_name) @values_by_name.fetch(value_name).value elsif match_by_value = @values_by_name.find { |k, v| v.value == value_name } # this is for matching default values, which are "inputs", but they're # the Ruby value, not the GraphQL string. match_by_value[1].value else nil end end
[ "def", "coerce_non_null_input", "(", "value_name", ",", "ctx", ")", "if", "@values_by_name", ".", "key?", "(", "value_name", ")", "@values_by_name", ".", "fetch", "(", "value_name", ")", ".", "value", "elsif", "match_by_value", "=", "@values_by_name", ".", "find", "{", "|", "k", ",", "v", "|", "v", ".", "value", "==", "value_name", "}", "match_by_value", "[", "1", "]", ".", "value", "else", "nil", "end", "end" ]
Get the underlying value for this enum value @example get episode value from Enum episode = EpisodeEnum.coerce("NEWHOPE") episode # => 6 @param value_name [String] the string representation of this enum value @return [Object] the underlying value for this enum value
[ "Get", "the", "underlying", "value", "for", "this", "enum", "value" ]
d5be13a816f220b9efbabeaa69a3e56fedf311f5
https://github.com/rmosolgo/graphql-ruby/blob/d5be13a816f220b9efbabeaa69a3e56fedf311f5/lib/graphql/enum_type.rb#L169-L179
train
rmosolgo/graphql-ruby
spec/support/jazz.rb
Jazz.Query.inspect_input
def inspect_input(input:) [ input.class.name, input.helper_method, # Access by method input.string_value, # Access by key: input[:string_value], input.key?(:string_value).to_s, # ~~Access by legacy key~~ # not anymore input[:string_value], input.ensemble, input.key?(:ensemble).to_s, ] end
ruby
def inspect_input(input:) [ input.class.name, input.helper_method, # Access by method input.string_value, # Access by key: input[:string_value], input.key?(:string_value).to_s, # ~~Access by legacy key~~ # not anymore input[:string_value], input.ensemble, input.key?(:ensemble).to_s, ] end
[ "def", "inspect_input", "(", "input", ":", ")", "[", "input", ".", "class", ".", "name", ",", "input", ".", "helper_method", ",", "input", ".", "string_value", ",", "input", "[", ":string_value", "]", ",", "input", ".", "key?", "(", ":string_value", ")", ".", "to_s", ",", "input", "[", ":string_value", "]", ",", "input", ".", "ensemble", ",", "input", ".", "key?", "(", ":ensemble", ")", ".", "to_s", ",", "]", "end" ]
This is for testing input object behavior
[ "This", "is", "for", "testing", "input", "object", "behavior" ]
d5be13a816f220b9efbabeaa69a3e56fedf311f5
https://github.com/rmosolgo/graphql-ruby/blob/d5be13a816f220b9efbabeaa69a3e56fedf311f5/spec/support/jazz.rb#L390-L404
train
elastic/elasticsearch-rails
elasticsearch-model/examples/activerecord_associations.rb
Searchable.Indexing.as_indexed_json
def as_indexed_json(options={}) self.as_json( include: { categories: { only: :title}, authors: { methods: [:full_name, :department], only: [:full_name, :department] }, comments: { only: :text } }) end
ruby
def as_indexed_json(options={}) self.as_json( include: { categories: { only: :title}, authors: { methods: [:full_name, :department], only: [:full_name, :department] }, comments: { only: :text } }) end
[ "def", "as_indexed_json", "(", "options", "=", "{", "}", ")", "self", ".", "as_json", "(", "include", ":", "{", "categories", ":", "{", "only", ":", ":title", "}", ",", "authors", ":", "{", "methods", ":", "[", ":full_name", ",", ":department", "]", ",", "only", ":", "[", ":full_name", ",", ":department", "]", "}", ",", "comments", ":", "{", "only", ":", ":text", "}", "}", ")", "end" ]
Customize the JSON serialization for Elasticsearch
[ "Customize", "the", "JSON", "serialization", "for", "Elasticsearch" ]
a67ecc1afc3a0615efa7ca6daecbb9132f61c318
https://github.com/elastic/elasticsearch-rails/blob/a67ecc1afc3a0615efa7ca6daecbb9132f61c318/elasticsearch-model/examples/activerecord_associations.rb#L102-L108
train
octokit/octokit.rb
lib/octokit/client.rb
Octokit.Client.inspect
def inspect inspected = super # mask password inspected.gsub! @password, '*******' if @password inspected.gsub! @management_console_password, '*******' if @management_console_password inspected.gsub! @bearer_token, '********' if @bearer_token # Only show last 4 of token, secret inspected.gsub! @access_token, "#{'*'*36}#{@access_token[36..-1]}" if @access_token inspected.gsub! @client_secret, "#{'*'*36}#{@client_secret[36..-1]}" if @client_secret inspected end
ruby
def inspect inspected = super # mask password inspected.gsub! @password, '*******' if @password inspected.gsub! @management_console_password, '*******' if @management_console_password inspected.gsub! @bearer_token, '********' if @bearer_token # Only show last 4 of token, secret inspected.gsub! @access_token, "#{'*'*36}#{@access_token[36..-1]}" if @access_token inspected.gsub! @client_secret, "#{'*'*36}#{@client_secret[36..-1]}" if @client_secret inspected end
[ "def", "inspect", "inspected", "=", "super", "inspected", ".", "gsub!", "@password", ",", "'*******'", "if", "@password", "inspected", ".", "gsub!", "@management_console_password", ",", "'*******'", "if", "@management_console_password", "inspected", ".", "gsub!", "@bearer_token", ",", "'********'", "if", "@bearer_token", "inspected", ".", "gsub!", "@access_token", ",", "\"#{'*'*36}#{@access_token[36..-1]}\"", "if", "@access_token", "inspected", ".", "gsub!", "@client_secret", ",", "\"#{'*'*36}#{@client_secret[36..-1]}\"", "if", "@client_secret", "inspected", "end" ]
Text representation of the client, masking tokens and passwords @return [String]
[ "Text", "representation", "of", "the", "client", "masking", "tokens", "and", "passwords" ]
ddf750601529a6a7da5fe5293d10031709b8605d
https://github.com/octokit/octokit.rb/blob/ddf750601529a6a7da5fe5293d10031709b8605d/lib/octokit/client.rb#L134-L146
train
octokit/octokit.rb
lib/octokit/connection.rb
Octokit.Connection.agent
def agent @agent ||= Sawyer::Agent.new(endpoint, sawyer_options) do |http| http.headers[:accept] = default_media_type http.headers[:content_type] = "application/json" http.headers[:user_agent] = user_agent if basic_authenticated? http.basic_auth(@login, @password) elsif token_authenticated? http.authorization 'token', @access_token elsif bearer_authenticated? http.authorization 'Bearer', @bearer_token elsif application_authenticated? http.params = http.params.merge application_authentication end end end
ruby
def agent @agent ||= Sawyer::Agent.new(endpoint, sawyer_options) do |http| http.headers[:accept] = default_media_type http.headers[:content_type] = "application/json" http.headers[:user_agent] = user_agent if basic_authenticated? http.basic_auth(@login, @password) elsif token_authenticated? http.authorization 'token', @access_token elsif bearer_authenticated? http.authorization 'Bearer', @bearer_token elsif application_authenticated? http.params = http.params.merge application_authentication end end end
[ "def", "agent", "@agent", "||=", "Sawyer", "::", "Agent", ".", "new", "(", "endpoint", ",", "sawyer_options", ")", "do", "|", "http", "|", "http", ".", "headers", "[", ":accept", "]", "=", "default_media_type", "http", ".", "headers", "[", ":content_type", "]", "=", "\"application/json\"", "http", ".", "headers", "[", ":user_agent", "]", "=", "user_agent", "if", "basic_authenticated?", "http", ".", "basic_auth", "(", "@login", ",", "@password", ")", "elsif", "token_authenticated?", "http", ".", "authorization", "'token'", ",", "@access_token", "elsif", "bearer_authenticated?", "http", ".", "authorization", "'Bearer'", ",", "@bearer_token", "elsif", "application_authenticated?", "http", ".", "params", "=", "http", ".", "params", ".", "merge", "application_authentication", "end", "end", "end" ]
Hypermedia agent for the GitHub API @return [Sawyer::Agent]
[ "Hypermedia", "agent", "for", "the", "GitHub", "API" ]
ddf750601529a6a7da5fe5293d10031709b8605d
https://github.com/octokit/octokit.rb/blob/ddf750601529a6a7da5fe5293d10031709b8605d/lib/octokit/connection.rb#L104-L119
train
octokit/octokit.rb
lib/octokit/connection.rb
Octokit.Connection.boolean_from_response
def boolean_from_response(method, path, options = {}) request(method, path, options) @last_response.status == 204 rescue Octokit::NotFound false end
ruby
def boolean_from_response(method, path, options = {}) request(method, path, options) @last_response.status == 204 rescue Octokit::NotFound false end
[ "def", "boolean_from_response", "(", "method", ",", "path", ",", "options", "=", "{", "}", ")", "request", "(", "method", ",", "path", ",", "options", ")", "@last_response", ".", "status", "==", "204", "rescue", "Octokit", "::", "NotFound", "false", "end" ]
Executes the request, checking if it was successful @return [Boolean] True on success, false otherwise
[ "Executes", "the", "request", "checking", "if", "it", "was", "successful" ]
ddf750601529a6a7da5fe5293d10031709b8605d
https://github.com/octokit/octokit.rb/blob/ddf750601529a6a7da5fe5293d10031709b8605d/lib/octokit/connection.rb#L163-L168
train
decidim/decidim
decidim-core/app/helpers/decidim/aria_selected_link_to_helper.rb
Decidim.AriaSelectedLinkToHelper.aria_selected_link_to
def aria_selected_link_to(text, link, options = {}) link_to( text, link, options.merge( "aria-selected": is_active_link?(link, options[:aria_link_type] || :inclusive) ) ) end
ruby
def aria_selected_link_to(text, link, options = {}) link_to( text, link, options.merge( "aria-selected": is_active_link?(link, options[:aria_link_type] || :inclusive) ) ) end
[ "def", "aria_selected_link_to", "(", "text", ",", "link", ",", "options", "=", "{", "}", ")", "link_to", "(", "text", ",", "link", ",", "options", ".", "merge", "(", "\"aria-selected\"", ":", "is_active_link?", "(", "link", ",", "options", "[", ":aria_link_type", "]", "||", ":inclusive", ")", ")", ")", "end" ]
Adds the `aria-selected` attribute to a link when it's pointing to the current path. The API is the same than the `link_to` one, and uses this helper internally. text - a String with the link text link - Where the link should point to. Accepts the same value than `link_to` helper. options - An options Hash that will be passed to `link_to`.
[ "Adds", "the", "aria", "-", "selected", "attribute", "to", "a", "link", "when", "it", "s", "pointing", "to", "the", "current", "path", ".", "The", "API", "is", "the", "same", "than", "the", "link_to", "one", "and", "uses", "this", "helper", "internally", "." ]
6e2b14e559a63088669904e3c5c49a5180700cf7
https://github.com/decidim/decidim/blob/6e2b14e559a63088669904e3c5c49a5180700cf7/decidim-core/app/helpers/decidim/aria_selected_link_to_helper.rb#L17-L25
train
decidim/decidim
decidim-core/lib/decidim/authorization_form_builder.rb
Decidim.AuthorizationFormBuilder.all_fields
def all_fields fields = public_attributes.map do |name, type| @template.content_tag(:div, input_field(name, type), class: "field") end safe_join(fields) end
ruby
def all_fields fields = public_attributes.map do |name, type| @template.content_tag(:div, input_field(name, type), class: "field") end safe_join(fields) end
[ "def", "all_fields", "fields", "=", "public_attributes", ".", "map", "do", "|", "name", ",", "type", "|", "@template", ".", "content_tag", "(", ":div", ",", "input_field", "(", "name", ",", "type", ")", ",", "class", ":", "\"field\"", ")", "end", "safe_join", "(", "fields", ")", "end" ]
Renders all form attributes defined by the handler. Returns a String.
[ "Renders", "all", "form", "attributes", "defined", "by", "the", "handler", "." ]
6e2b14e559a63088669904e3c5c49a5180700cf7
https://github.com/decidim/decidim/blob/6e2b14e559a63088669904e3c5c49a5180700cf7/decidim-core/lib/decidim/authorization_form_builder.rb#L11-L17
train
decidim/decidim
decidim-core/lib/decidim/authorization_form_builder.rb
Decidim.AuthorizationFormBuilder.input
def input(name, options = {}) if options[:as] send(options[:as].to_s, name, options[:input] || {}) else type = find_input_type(name.to_s) input_field(name, type) end end
ruby
def input(name, options = {}) if options[:as] send(options[:as].to_s, name, options[:input] || {}) else type = find_input_type(name.to_s) input_field(name, type) end end
[ "def", "input", "(", "name", ",", "options", "=", "{", "}", ")", "if", "options", "[", ":as", "]", "send", "(", "options", "[", ":as", "]", ".", "to_s", ",", "name", ",", "options", "[", ":input", "]", "||", "{", "}", ")", "else", "type", "=", "find_input_type", "(", "name", ".", "to_s", ")", "input_field", "(", "name", ",", "type", ")", "end", "end" ]
Renders a single attribute from the form handlers. name - The String name of the attribute. options - An optional Hash, accepted options are: :as - A String name with the type the field to render :input - An optional Hash to pass to the field method. Returns a String.
[ "Renders", "a", "single", "attribute", "from", "the", "form", "handlers", "." ]
6e2b14e559a63088669904e3c5c49a5180700cf7
https://github.com/decidim/decidim/blob/6e2b14e559a63088669904e3c5c49a5180700cf7/decidim-core/lib/decidim/authorization_form_builder.rb#L27-L34
train
decidim/decidim
decidim-core/app/services/decidim/home_activity_search.rb
Decidim.HomeActivitySearch.resource_types
def resource_types @resource_types ||= %w( Decidim::Accountability::Result Decidim::Blogs::Post Decidim::Comments::Comment Decidim::Consultations::Question Decidim::Debates::Debate Decidim::Meetings::Meeting Decidim::Proposals::Proposal Decidim::Surveys::Survey Decidim::Assembly Decidim::Consultation Decidim::Initiative Decidim::ParticipatoryProcess ).select do |klass| klass.safe_constantize.present? end end
ruby
def resource_types @resource_types ||= %w( Decidim::Accountability::Result Decidim::Blogs::Post Decidim::Comments::Comment Decidim::Consultations::Question Decidim::Debates::Debate Decidim::Meetings::Meeting Decidim::Proposals::Proposal Decidim::Surveys::Survey Decidim::Assembly Decidim::Consultation Decidim::Initiative Decidim::ParticipatoryProcess ).select do |klass| klass.safe_constantize.present? end end
[ "def", "resource_types", "@resource_types", "||=", "%w(", "Decidim::Accountability::Result", "Decidim::Blogs::Post", "Decidim::Comments::Comment", "Decidim::Consultations::Question", "Decidim::Debates::Debate", "Decidim::Meetings::Meeting", "Decidim::Proposals::Proposal", "Decidim::Surveys::Survey", "Decidim::Assembly", "Decidim::Consultation", "Decidim::Initiative", "Decidim::ParticipatoryProcess", ")", ".", "select", "do", "|", "klass", "|", "klass", ".", "safe_constantize", ".", "present?", "end", "end" ]
All the resource types that are eligible to be included as an activity.
[ "All", "the", "resource", "types", "that", "are", "eligible", "to", "be", "included", "as", "an", "activity", "." ]
6e2b14e559a63088669904e3c5c49a5180700cf7
https://github.com/decidim/decidim/blob/6e2b14e559a63088669904e3c5c49a5180700cf7/decidim-core/app/services/decidim/home_activity_search.rb#L34-L51
train
decidim/decidim
decidim-core/app/helpers/decidim/authorization_form_helper.rb
Decidim.AuthorizationFormHelper.authorization_form_for
def authorization_form_for(record, options = {}, &block) default_options = { builder: AuthorizationFormBuilder, as: "authorization_handler", url: decidim_verifications.authorizations_path } options = default_options.merge(options) decidim_form_for(record, options, &block) end
ruby
def authorization_form_for(record, options = {}, &block) default_options = { builder: AuthorizationFormBuilder, as: "authorization_handler", url: decidim_verifications.authorizations_path } options = default_options.merge(options) decidim_form_for(record, options, &block) end
[ "def", "authorization_form_for", "(", "record", ",", "options", "=", "{", "}", ",", "&", "block", ")", "default_options", "=", "{", "builder", ":", "AuthorizationFormBuilder", ",", "as", ":", "\"authorization_handler\"", ",", "url", ":", "decidim_verifications", ".", "authorizations_path", "}", "options", "=", "default_options", ".", "merge", "(", "options", ")", "decidim_form_for", "(", "record", ",", "options", ",", "&", "block", ")", "end" ]
Creates a ew authorization form in a view, accepts the same arguments as `form_for`. record - The record to use in the form, it shoulde be a descendant of AuthorizationHandler. options - An optional hash with options to pass wo the form builder. block - A block with the content of the form. Returns a String.
[ "Creates", "a", "ew", "authorization", "form", "in", "a", "view", "accepts", "the", "same", "arguments", "as", "form_for", "." ]
6e2b14e559a63088669904e3c5c49a5180700cf7
https://github.com/decidim/decidim/blob/6e2b14e559a63088669904e3c5c49a5180700cf7/decidim-core/app/helpers/decidim/authorization_form_helper.rb#L15-L24
train
decidim/decidim
decidim-core/app/controllers/decidim/application_controller.rb
Decidim.ApplicationController.store_current_location
def store_current_location return if (devise_controller? && params[:redirect_url].blank?) || !request.format.html? value = params[:redirect_url] || request.url store_location_for(:user, value) end
ruby
def store_current_location return if (devise_controller? && params[:redirect_url].blank?) || !request.format.html? value = params[:redirect_url] || request.url store_location_for(:user, value) end
[ "def", "store_current_location", "return", "if", "(", "devise_controller?", "&&", "params", "[", ":redirect_url", "]", ".", "blank?", ")", "||", "!", "request", ".", "format", ".", "html?", "value", "=", "params", "[", ":redirect_url", "]", "||", "request", ".", "url", "store_location_for", "(", ":user", ",", "value", ")", "end" ]
Stores the url where the user will be redirected after login. Uses the `redirect_url` param or the current url if there's no param. In Devise controllers we only store the URL if it's from the params, we don't want to overwrite the stored URL for a Devise one.
[ "Stores", "the", "url", "where", "the", "user", "will", "be", "redirected", "after", "login", "." ]
6e2b14e559a63088669904e3c5c49a5180700cf7
https://github.com/decidim/decidim/blob/6e2b14e559a63088669904e3c5c49a5180700cf7/decidim-core/app/controllers/decidim/application_controller.rb#L48-L53
train
decidim/decidim
decidim-core/app/helpers/decidim/scopes_helper.rb
Decidim.ScopesHelper.has_visible_scopes?
def has_visible_scopes?(resource) resource.participatory_space.scopes_enabled? && resource.scope.present? && resource.participatory_space.scope != resource.scope end
ruby
def has_visible_scopes?(resource) resource.participatory_space.scopes_enabled? && resource.scope.present? && resource.participatory_space.scope != resource.scope end
[ "def", "has_visible_scopes?", "(", "resource", ")", "resource", ".", "participatory_space", ".", "scopes_enabled?", "&&", "resource", ".", "scope", ".", "present?", "&&", "resource", ".", "participatory_space", ".", "scope", "!=", "resource", ".", "scope", "end" ]
Checks if the resource should show its scope or not. resource - the resource to analize Returns boolean.
[ "Checks", "if", "the", "resource", "should", "show", "its", "scope", "or", "not", ".", "resource", "-", "the", "resource", "to", "analize" ]
6e2b14e559a63088669904e3c5c49a5180700cf7
https://github.com/decidim/decidim/blob/6e2b14e559a63088669904e3c5c49a5180700cf7/decidim-core/app/helpers/decidim/scopes_helper.rb#L15-L19
train
decidim/decidim
decidim-core/app/helpers/decidim/scopes_helper.rb
Decidim.ScopesHelper.scopes_picker_tag
def scopes_picker_tag(name, value, options = {}) root = try(:current_participatory_space)&.scope field = options[:field] || name scopes_picker_field_tag name, value, id: options[:id] do |scope| { url: decidim.scopes_picker_path(root: root, current: scope&.id, field: field), text: scope_name_for_picker(scope, I18n.t("decidim.scopes.global")) } end end
ruby
def scopes_picker_tag(name, value, options = {}) root = try(:current_participatory_space)&.scope field = options[:field] || name scopes_picker_field_tag name, value, id: options[:id] do |scope| { url: decidim.scopes_picker_path(root: root, current: scope&.id, field: field), text: scope_name_for_picker(scope, I18n.t("decidim.scopes.global")) } end end
[ "def", "scopes_picker_tag", "(", "name", ",", "value", ",", "options", "=", "{", "}", ")", "root", "=", "try", "(", ":current_participatory_space", ")", "&.", "scope", "field", "=", "options", "[", ":field", "]", "||", "name", "scopes_picker_field_tag", "name", ",", "value", ",", "id", ":", "options", "[", ":id", "]", "do", "|", "scope", "|", "{", "url", ":", "decidim", ".", "scopes_picker_path", "(", "root", ":", "root", ",", "current", ":", "scope", "&.", "id", ",", "field", ":", "field", ")", ",", "text", ":", "scope_name_for_picker", "(", "scope", ",", "I18n", ".", "t", "(", "\"decidim.scopes.global\"", ")", ")", "}", "end", "end" ]
Renders a scopes picker field in a form, not linked to a specific model. name - name for the input value - value for the input Returns nothing.
[ "Renders", "a", "scopes", "picker", "field", "in", "a", "form", "not", "linked", "to", "a", "specific", "model", ".", "name", "-", "name", "for", "the", "input", "value", "-", "value", "for", "the", "input" ]
6e2b14e559a63088669904e3c5c49a5180700cf7
https://github.com/decidim/decidim/blob/6e2b14e559a63088669904e3c5c49a5180700cf7/decidim-core/app/helpers/decidim/scopes_helper.rb#L54-L62
train
decidim/decidim
decidim-core/app/helpers/decidim/amendments_helper.rb
Decidim.AmendmentsHelper.amendments_for
def amendments_for(amendable) return unless amendable.amendable? && amendable.emendations.count.positive? content = content_tag(:h2, class: "section-heading", id: "amendments") do t("section_heading", scope: "decidim.amendments.amendable", count: amendable.emendations.count) end content << cell("decidim/collapsible_list", amendable.emendations, cell_options: { context: { current_user: current_user } }, list_class: "row small-up-1 medium-up-2 card-grid", size: 4).to_s content_tag :div, content.html_safe, class: "section" end
ruby
def amendments_for(amendable) return unless amendable.amendable? && amendable.emendations.count.positive? content = content_tag(:h2, class: "section-heading", id: "amendments") do t("section_heading", scope: "decidim.amendments.amendable", count: amendable.emendations.count) end content << cell("decidim/collapsible_list", amendable.emendations, cell_options: { context: { current_user: current_user } }, list_class: "row small-up-1 medium-up-2 card-grid", size: 4).to_s content_tag :div, content.html_safe, class: "section" end
[ "def", "amendments_for", "(", "amendable", ")", "return", "unless", "amendable", ".", "amendable?", "&&", "amendable", ".", "emendations", ".", "count", ".", "positive?", "content", "=", "content_tag", "(", ":h2", ",", "class", ":", "\"section-heading\"", ",", "id", ":", "\"amendments\"", ")", "do", "t", "(", "\"section_heading\"", ",", "scope", ":", "\"decidim.amendments.amendable\"", ",", "count", ":", "amendable", ".", "emendations", ".", "count", ")", "end", "content", "<<", "cell", "(", "\"decidim/collapsible_list\"", ",", "amendable", ".", "emendations", ",", "cell_options", ":", "{", "context", ":", "{", "current_user", ":", "current_user", "}", "}", ",", "list_class", ":", "\"row small-up-1 medium-up-2 card-grid\"", ",", "size", ":", "4", ")", ".", "to_s", "content_tag", ":div", ",", "content", ".", "html_safe", ",", "class", ":", "\"section\"", "end" ]
Renders the emendations of an amendable resource Returns Html grid of CardM.
[ "Renders", "the", "emendations", "of", "an", "amendable", "resource" ]
6e2b14e559a63088669904e3c5c49a5180700cf7
https://github.com/decidim/decidim/blob/6e2b14e559a63088669904e3c5c49a5180700cf7/decidim-core/app/helpers/decidim/amendments_helper.rb#L9-L23
train
decidim/decidim
decidim-core/app/helpers/decidim/amendments_helper.rb
Decidim.AmendmentsHelper.allowed_to_accept_and_reject?
def allowed_to_accept_and_reject?(emendation) return unless emendation.amendment.evaluating? emendation.amendable.created_by?(current_user) || current_user.admin? end
ruby
def allowed_to_accept_and_reject?(emendation) return unless emendation.amendment.evaluating? emendation.amendable.created_by?(current_user) || current_user.admin? end
[ "def", "allowed_to_accept_and_reject?", "(", "emendation", ")", "return", "unless", "emendation", ".", "amendment", ".", "evaluating?", "emendation", ".", "amendable", ".", "created_by?", "(", "current_user", ")", "||", "current_user", ".", "admin?", "end" ]
Checks if the user can accept and reject the emendation
[ "Checks", "if", "the", "user", "can", "accept", "and", "reject", "the", "emendation" ]
6e2b14e559a63088669904e3c5c49a5180700cf7
https://github.com/decidim/decidim/blob/6e2b14e559a63088669904e3c5c49a5180700cf7/decidim-core/app/helpers/decidim/amendments_helper.rb#L83-L87
train