id
int32
0
24.9k
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
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
16,000
adamcooke/procodile
lib/procodile/instance.rb
Procodile.Instance.pid_from_file
def pid_from_file if File.exist?(pid_file_path) pid = File.read(pid_file_path) pid.length > 0 ? pid.strip.to_i : nil else nil end end
ruby
def pid_from_file if File.exist?(pid_file_path) pid = File.read(pid_file_path) pid.length > 0 ? pid.strip.to_i : nil else nil end end
[ "def", "pid_from_file", "if", "File", ".", "exist?", "(", "pid_file_path", ")", "pid", "=", "File", ".", "read", "(", "pid_file_path", ")", "pid", ".", "length", ">", "0", "?", "pid", ".", "strip", ".", "to_i", ":", "nil", "else", "nil", "end", "end" ]
Return the PID that is in the instances process PID file
[ "Return", "the", "PID", "that", "is", "in", "the", "instances", "process", "PID", "file" ]
57f42940715cba7186f0ce82b9bc4763f384cf2a
https://github.com/adamcooke/procodile/blob/57f42940715cba7186f0ce82b9bc4763f384cf2a/lib/procodile/instance.rb#L78-L85
16,001
adamcooke/procodile
lib/procodile/instance.rb
Procodile.Instance.start
def start if stopping? Procodile.log(@process.log_color, description, "Process is stopped/stopping therefore cannot be started again.") return false end update_pid if running? Procodile.log(@process.log_color, description, "Already running with PID #{@pid}") nil else if @supervisor.run_options[:port_allocations] && chosen_port = @supervisor.run_options[:port_allocations][@process.name] if chosen_port == 0 allocate_port else @port = chosen_port Procodile.log(@process.log_color, description, "Assigned #{chosen_port} to process") end elsif @process.proxy? && @supervisor.tcp_proxy # Allocate a port randomly if a proxy is needed allocate_port elsif @process.allocate_port_from && @process.restart_mode != 'start-term' # Allocate ports to this process sequentially from the starting port allocated_ports = (@supervisor.processes[@process] ? @supervisor.processes[@process].select(&:running?) : []).map(&:port) proposed_port = @process.allocate_port_from until @port unless allocated_ports.include?(proposed_port) @port = proposed_port end proposed_port += 1 end end if self.process.log_path && @supervisor.run_options[:force_single_log] != true log_destination = File.open(self.process.log_path, 'a') io = nil else reader, writer = IO.pipe log_destination = writer io = reader end @tag = @supervisor.tag.dup if @supervisor.tag Dir.chdir(@process.config.root) without_rbenv do @pid = ::Process.spawn(environment_variables, @process.command, :out => log_destination, :err => log_destination, :pgroup => true) end log_destination.close File.open(pid_file_path, 'w') { |f| f.write(@pid.to_s + "\n") } @supervisor.add_instance(self, io) ::Process.detach(@pid) Procodile.log(@process.log_color, description, "Started with PID #{@pid}" + (@tag ? " (tagged with #{@tag})" : '')) if self.process.log_path && io.nil? Procodile.log(@process.log_color, description, "Logging to #{self.process.log_path}") end @started_at = Time.now end end
ruby
def start if stopping? Procodile.log(@process.log_color, description, "Process is stopped/stopping therefore cannot be started again.") return false end update_pid if running? Procodile.log(@process.log_color, description, "Already running with PID #{@pid}") nil else if @supervisor.run_options[:port_allocations] && chosen_port = @supervisor.run_options[:port_allocations][@process.name] if chosen_port == 0 allocate_port else @port = chosen_port Procodile.log(@process.log_color, description, "Assigned #{chosen_port} to process") end elsif @process.proxy? && @supervisor.tcp_proxy # Allocate a port randomly if a proxy is needed allocate_port elsif @process.allocate_port_from && @process.restart_mode != 'start-term' # Allocate ports to this process sequentially from the starting port allocated_ports = (@supervisor.processes[@process] ? @supervisor.processes[@process].select(&:running?) : []).map(&:port) proposed_port = @process.allocate_port_from until @port unless allocated_ports.include?(proposed_port) @port = proposed_port end proposed_port += 1 end end if self.process.log_path && @supervisor.run_options[:force_single_log] != true log_destination = File.open(self.process.log_path, 'a') io = nil else reader, writer = IO.pipe log_destination = writer io = reader end @tag = @supervisor.tag.dup if @supervisor.tag Dir.chdir(@process.config.root) without_rbenv do @pid = ::Process.spawn(environment_variables, @process.command, :out => log_destination, :err => log_destination, :pgroup => true) end log_destination.close File.open(pid_file_path, 'w') { |f| f.write(@pid.to_s + "\n") } @supervisor.add_instance(self, io) ::Process.detach(@pid) Procodile.log(@process.log_color, description, "Started with PID #{@pid}" + (@tag ? " (tagged with #{@tag})" : '')) if self.process.log_path && io.nil? Procodile.log(@process.log_color, description, "Logging to #{self.process.log_path}") end @started_at = Time.now end end
[ "def", "start", "if", "stopping?", "Procodile", ".", "log", "(", "@process", ".", "log_color", ",", "description", ",", "\"Process is stopped/stopping therefore cannot be started again.\"", ")", "return", "false", "end", "update_pid", "if", "running?", "Procodile", ".", "log", "(", "@process", ".", "log_color", ",", "description", ",", "\"Already running with PID #{@pid}\"", ")", "nil", "else", "if", "@supervisor", ".", "run_options", "[", ":port_allocations", "]", "&&", "chosen_port", "=", "@supervisor", ".", "run_options", "[", ":port_allocations", "]", "[", "@process", ".", "name", "]", "if", "chosen_port", "==", "0", "allocate_port", "else", "@port", "=", "chosen_port", "Procodile", ".", "log", "(", "@process", ".", "log_color", ",", "description", ",", "\"Assigned #{chosen_port} to process\"", ")", "end", "elsif", "@process", ".", "proxy?", "&&", "@supervisor", ".", "tcp_proxy", "# Allocate a port randomly if a proxy is needed", "allocate_port", "elsif", "@process", ".", "allocate_port_from", "&&", "@process", ".", "restart_mode", "!=", "'start-term'", "# Allocate ports to this process sequentially from the starting port", "allocated_ports", "=", "(", "@supervisor", ".", "processes", "[", "@process", "]", "?", "@supervisor", ".", "processes", "[", "@process", "]", ".", "select", "(", ":running?", ")", ":", "[", "]", ")", ".", "map", "(", ":port", ")", "proposed_port", "=", "@process", ".", "allocate_port_from", "until", "@port", "unless", "allocated_ports", ".", "include?", "(", "proposed_port", ")", "@port", "=", "proposed_port", "end", "proposed_port", "+=", "1", "end", "end", "if", "self", ".", "process", ".", "log_path", "&&", "@supervisor", ".", "run_options", "[", ":force_single_log", "]", "!=", "true", "log_destination", "=", "File", ".", "open", "(", "self", ".", "process", ".", "log_path", ",", "'a'", ")", "io", "=", "nil", "else", "reader", ",", "writer", "=", "IO", ".", "pipe", "log_destination", "=", "writer", "io", "=", "reader", "end", "@tag", "=", "@supervisor", ".", "tag", ".", "dup", "if", "@supervisor", ".", "tag", "Dir", ".", "chdir", "(", "@process", ".", "config", ".", "root", ")", "without_rbenv", "do", "@pid", "=", "::", "Process", ".", "spawn", "(", "environment_variables", ",", "@process", ".", "command", ",", ":out", "=>", "log_destination", ",", ":err", "=>", "log_destination", ",", ":pgroup", "=>", "true", ")", "end", "log_destination", ".", "close", "File", ".", "open", "(", "pid_file_path", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "@pid", ".", "to_s", "+", "\"\\n\"", ")", "}", "@supervisor", ".", "add_instance", "(", "self", ",", "io", ")", "::", "Process", ".", "detach", "(", "@pid", ")", "Procodile", ".", "log", "(", "@process", ".", "log_color", ",", "description", ",", "\"Started with PID #{@pid}\"", "+", "(", "@tag", "?", "\" (tagged with #{@tag})\"", ":", "''", ")", ")", "if", "self", ".", "process", ".", "log_path", "&&", "io", ".", "nil?", "Procodile", ".", "log", "(", "@process", ".", "log_color", ",", "description", ",", "\"Logging to #{self.process.log_path}\"", ")", "end", "@started_at", "=", "Time", ".", "now", "end", "end" ]
Start a new instance of this process
[ "Start", "a", "new", "instance", "of", "this", "process" ]
57f42940715cba7186f0ce82b9bc4763f384cf2a
https://github.com/adamcooke/procodile/blob/57f42940715cba7186f0ce82b9bc4763f384cf2a/lib/procodile/instance.rb#L103-L159
16,002
adamcooke/procodile
lib/procodile/instance.rb
Procodile.Instance.stop
def stop @stopping = Time.now update_pid if self.running? Procodile.log(@process.log_color, description, "Sending #{@process.term_signal} to #{@pid}") ::Process.kill(@process.term_signal, pid) else Procodile.log(@process.log_color, description, "Process already stopped") end end
ruby
def stop @stopping = Time.now update_pid if self.running? Procodile.log(@process.log_color, description, "Sending #{@process.term_signal} to #{@pid}") ::Process.kill(@process.term_signal, pid) else Procodile.log(@process.log_color, description, "Process already stopped") end end
[ "def", "stop", "@stopping", "=", "Time", ".", "now", "update_pid", "if", "self", ".", "running?", "Procodile", ".", "log", "(", "@process", ".", "log_color", ",", "description", ",", "\"Sending #{@process.term_signal} to #{@pid}\"", ")", "::", "Process", ".", "kill", "(", "@process", ".", "term_signal", ",", "pid", ")", "else", "Procodile", ".", "log", "(", "@process", ".", "log_color", ",", "description", ",", "\"Process already stopped\"", ")", "end", "end" ]
Send this signal the signal to stop and mark the instance in a state that tells us that we want it to be stopped.
[ "Send", "this", "signal", "the", "signal", "to", "stop", "and", "mark", "the", "instance", "in", "a", "state", "that", "tells", "us", "that", "we", "want", "it", "to", "be", "stopped", "." ]
57f42940715cba7186f0ce82b9bc4763f384cf2a
https://github.com/adamcooke/procodile/blob/57f42940715cba7186f0ce82b9bc4763f384cf2a/lib/procodile/instance.rb#L186-L195
16,003
adamcooke/procodile
lib/procodile/instance.rb
Procodile.Instance.restart
def restart Procodile.log(@process.log_color, description, "Restarting using #{@process.restart_mode} mode") update_pid case @process.restart_mode when 'usr1', 'usr2' if running? ::Process.kill(@process.restart_mode.upcase, @pid) @tag = @supervisor.tag if @supervisor.tag Procodile.log(@process.log_color, description, "Sent #{@process.restart_mode.upcase} signal to process #{@pid}") else Procodile.log(@process.log_color, description, "Process not running already. Starting it.") on_stop new_instance = @process.create_instance(@supervisor) new_instance.port = self.port new_instance.start end self when 'start-term' new_instance = @process.create_instance(@supervisor) new_instance.start stop new_instance when 'term-start' stop new_instance = @process.create_instance(@supervisor) new_instance.port = self.port Thread.new do sleep 0.5 while running? new_instance.start end new_instance end end
ruby
def restart Procodile.log(@process.log_color, description, "Restarting using #{@process.restart_mode} mode") update_pid case @process.restart_mode when 'usr1', 'usr2' if running? ::Process.kill(@process.restart_mode.upcase, @pid) @tag = @supervisor.tag if @supervisor.tag Procodile.log(@process.log_color, description, "Sent #{@process.restart_mode.upcase} signal to process #{@pid}") else Procodile.log(@process.log_color, description, "Process not running already. Starting it.") on_stop new_instance = @process.create_instance(@supervisor) new_instance.port = self.port new_instance.start end self when 'start-term' new_instance = @process.create_instance(@supervisor) new_instance.start stop new_instance when 'term-start' stop new_instance = @process.create_instance(@supervisor) new_instance.port = self.port Thread.new do sleep 0.5 while running? new_instance.start end new_instance end end
[ "def", "restart", "Procodile", ".", "log", "(", "@process", ".", "log_color", ",", "description", ",", "\"Restarting using #{@process.restart_mode} mode\"", ")", "update_pid", "case", "@process", ".", "restart_mode", "when", "'usr1'", ",", "'usr2'", "if", "running?", "::", "Process", ".", "kill", "(", "@process", ".", "restart_mode", ".", "upcase", ",", "@pid", ")", "@tag", "=", "@supervisor", ".", "tag", "if", "@supervisor", ".", "tag", "Procodile", ".", "log", "(", "@process", ".", "log_color", ",", "description", ",", "\"Sent #{@process.restart_mode.upcase} signal to process #{@pid}\"", ")", "else", "Procodile", ".", "log", "(", "@process", ".", "log_color", ",", "description", ",", "\"Process not running already. Starting it.\"", ")", "on_stop", "new_instance", "=", "@process", ".", "create_instance", "(", "@supervisor", ")", "new_instance", ".", "port", "=", "self", ".", "port", "new_instance", ".", "start", "end", "self", "when", "'start-term'", "new_instance", "=", "@process", ".", "create_instance", "(", "@supervisor", ")", "new_instance", ".", "start", "stop", "new_instance", "when", "'term-start'", "stop", "new_instance", "=", "@process", ".", "create_instance", "(", "@supervisor", ")", "new_instance", ".", "port", "=", "self", ".", "port", "Thread", ".", "new", "do", "sleep", "0.5", "while", "running?", "new_instance", ".", "start", "end", "new_instance", "end", "end" ]
Retarts the process using the appropriate method from the process configuraiton
[ "Retarts", "the", "process", "using", "the", "appropriate", "method", "from", "the", "process", "configuraiton" ]
57f42940715cba7186f0ce82b9bc4763f384cf2a
https://github.com/adamcooke/procodile/blob/57f42940715cba7186f0ce82b9bc4763f384cf2a/lib/procodile/instance.rb#L218-L250
16,004
adamcooke/procodile
lib/procodile/instance.rb
Procodile.Instance.update_pid
def update_pid pid_from_file = self.pid_from_file if pid_from_file && pid_from_file != @pid @pid = pid_from_file @started_at = File.mtime(self.pid_file_path) Procodile.log(@process.log_color, description, "PID file changed. Updated pid to #{@pid}") true else false end end
ruby
def update_pid pid_from_file = self.pid_from_file if pid_from_file && pid_from_file != @pid @pid = pid_from_file @started_at = File.mtime(self.pid_file_path) Procodile.log(@process.log_color, description, "PID file changed. Updated pid to #{@pid}") true else false end end
[ "def", "update_pid", "pid_from_file", "=", "self", ".", "pid_from_file", "if", "pid_from_file", "&&", "pid_from_file", "!=", "@pid", "@pid", "=", "pid_from_file", "@started_at", "=", "File", ".", "mtime", "(", "self", ".", "pid_file_path", ")", "Procodile", ".", "log", "(", "@process", ".", "log_color", ",", "description", ",", "\"PID file changed. Updated pid to #{@pid}\"", ")", "true", "else", "false", "end", "end" ]
Update the locally cached PID from that stored on the file system.
[ "Update", "the", "locally", "cached", "PID", "from", "that", "stored", "on", "the", "file", "system", "." ]
57f42940715cba7186f0ce82b9bc4763f384cf2a
https://github.com/adamcooke/procodile/blob/57f42940715cba7186f0ce82b9bc4763f384cf2a/lib/procodile/instance.rb#L255-L265
16,005
adamcooke/procodile
lib/procodile/instance.rb
Procodile.Instance.check
def check(options = {}) return if failed? if self.running? # Everything is OK. The process is running. true else # If the process isn't running any more, update the PID in our memory from # the file in case the process has changed itself. return check if update_pid if @supervisor.allow_respawning? if can_respawn? Procodile.log(@process.log_color, description, "Process has stopped. Respawning...") start add_respawn elsif respawns >= @process.max_respawns Procodile.log(@process.log_color, description, "\e[41;37mWarning:\e[0m\e[31m this process has been respawned #{respawns} times and keeps dying.\e[0m") Procodile.log(@process.log_color, description, "It will not be respawned automatically any longer and will no longer be managed.".color(31)) @failed = Time.now tidy end else Procodile.log(@process.log_color, description, "Process has stopped. Respawning not available.") @failed = Time.now tidy end end end
ruby
def check(options = {}) return if failed? if self.running? # Everything is OK. The process is running. true else # If the process isn't running any more, update the PID in our memory from # the file in case the process has changed itself. return check if update_pid if @supervisor.allow_respawning? if can_respawn? Procodile.log(@process.log_color, description, "Process has stopped. Respawning...") start add_respawn elsif respawns >= @process.max_respawns Procodile.log(@process.log_color, description, "\e[41;37mWarning:\e[0m\e[31m this process has been respawned #{respawns} times and keeps dying.\e[0m") Procodile.log(@process.log_color, description, "It will not be respawned automatically any longer and will no longer be managed.".color(31)) @failed = Time.now tidy end else Procodile.log(@process.log_color, description, "Process has stopped. Respawning not available.") @failed = Time.now tidy end end end
[ "def", "check", "(", "options", "=", "{", "}", ")", "return", "if", "failed?", "if", "self", ".", "running?", "# Everything is OK. The process is running.", "true", "else", "# If the process isn't running any more, update the PID in our memory from", "# the file in case the process has changed itself.", "return", "check", "if", "update_pid", "if", "@supervisor", ".", "allow_respawning?", "if", "can_respawn?", "Procodile", ".", "log", "(", "@process", ".", "log_color", ",", "description", ",", "\"Process has stopped. Respawning...\"", ")", "start", "add_respawn", "elsif", "respawns", ">=", "@process", ".", "max_respawns", "Procodile", ".", "log", "(", "@process", ".", "log_color", ",", "description", ",", "\"\\e[41;37mWarning:\\e[0m\\e[31m this process has been respawned #{respawns} times and keeps dying.\\e[0m\"", ")", "Procodile", ".", "log", "(", "@process", ".", "log_color", ",", "description", ",", "\"It will not be respawned automatically any longer and will no longer be managed.\"", ".", "color", "(", "31", ")", ")", "@failed", "=", "Time", ".", "now", "tidy", "end", "else", "Procodile", ".", "log", "(", "@process", ".", "log_color", ",", "description", ",", "\"Process has stopped. Respawning not available.\"", ")", "@failed", "=", "Time", ".", "now", "tidy", "end", "end", "end" ]
Check the status of this process and handle as appropriate.
[ "Check", "the", "status", "of", "this", "process", "and", "handle", "as", "appropriate", "." ]
57f42940715cba7186f0ce82b9bc4763f384cf2a
https://github.com/adamcooke/procodile/blob/57f42940715cba7186f0ce82b9bc4763f384cf2a/lib/procodile/instance.rb#L270-L298
16,006
adamcooke/procodile
lib/procodile/instance.rb
Procodile.Instance.allocate_port
def allocate_port(max_attempts = 10) attempts = 0 until @port attempts += 1 possible_port = rand(10000) + 20000 if self.port_available?(possible_port) Procodile.log(@process.log_color, description, "Allocated port as #{possible_port}") return @port = possible_port elsif attempts >= max_attempts raise Procodile::Error, "Couldn't allocate port for #{instance.name}" end end end
ruby
def allocate_port(max_attempts = 10) attempts = 0 until @port attempts += 1 possible_port = rand(10000) + 20000 if self.port_available?(possible_port) Procodile.log(@process.log_color, description, "Allocated port as #{possible_port}") return @port = possible_port elsif attempts >= max_attempts raise Procodile::Error, "Couldn't allocate port for #{instance.name}" end end end
[ "def", "allocate_port", "(", "max_attempts", "=", "10", ")", "attempts", "=", "0", "until", "@port", "attempts", "+=", "1", "possible_port", "=", "rand", "(", "10000", ")", "+", "20000", "if", "self", ".", "port_available?", "(", "possible_port", ")", "Procodile", ".", "log", "(", "@process", ".", "log_color", ",", "description", ",", "\"Allocated port as #{possible_port}\"", ")", "return", "@port", "=", "possible_port", "elsif", "attempts", ">=", "max_attempts", "raise", "Procodile", "::", "Error", ",", "\"Couldn't allocate port for #{instance.name}\"", "end", "end", "end" ]
Find a port number for this instance to listen on. We just check that nothing is already listening on it. The process is expected to take it straight away if it wants it.
[ "Find", "a", "port", "number", "for", "this", "instance", "to", "listen", "on", ".", "We", "just", "check", "that", "nothing", "is", "already", "listening", "on", "it", ".", "The", "process", "is", "expected", "to", "take", "it", "straight", "away", "if", "it", "wants", "it", "." ]
57f42940715cba7186f0ce82b9bc4763f384cf2a
https://github.com/adamcooke/procodile/blob/57f42940715cba7186f0ce82b9bc4763f384cf2a/lib/procodile/instance.rb#L351-L363
16,007
adamcooke/procodile
lib/procodile/instance.rb
Procodile.Instance.port_available?
def port_available?(port) case @process.network_protocol when 'tcp' server = TCPServer.new('127.0.0.1', port) server.close true when 'udp' server = UDPSocket.new server.bind('127.0.0.1', port) server.close true else raise Procodile::Error, "Invalid network_protocol '#{@process.network_protocol}'" end rescue Errno::EADDRINUSE => e false end
ruby
def port_available?(port) case @process.network_protocol when 'tcp' server = TCPServer.new('127.0.0.1', port) server.close true when 'udp' server = UDPSocket.new server.bind('127.0.0.1', port) server.close true else raise Procodile::Error, "Invalid network_protocol '#{@process.network_protocol}'" end rescue Errno::EADDRINUSE => e false end
[ "def", "port_available?", "(", "port", ")", "case", "@process", ".", "network_protocol", "when", "'tcp'", "server", "=", "TCPServer", ".", "new", "(", "'127.0.0.1'", ",", "port", ")", "server", ".", "close", "true", "when", "'udp'", "server", "=", "UDPSocket", ".", "new", "server", ".", "bind", "(", "'127.0.0.1'", ",", "port", ")", "server", ".", "close", "true", "else", "raise", "Procodile", "::", "Error", ",", "\"Invalid network_protocol '#{@process.network_protocol}'\"", "end", "rescue", "Errno", "::", "EADDRINUSE", "=>", "e", "false", "end" ]
Is the given port available?
[ "Is", "the", "given", "port", "available?" ]
57f42940715cba7186f0ce82b9bc4763f384cf2a
https://github.com/adamcooke/procodile/blob/57f42940715cba7186f0ce82b9bc4763f384cf2a/lib/procodile/instance.rb#L368-L384
16,008
adamcooke/procodile
lib/procodile/instance.rb
Procodile.Instance.without_rbenv
def without_rbenv(&block) previous_environment = ENV.select { |k,v| k =~ /\A(RBENV\_)/ } if previous_environment.size > 0 previous_environment.each { |key, value| ENV[key] = nil } previous_environment['PATH'] = ENV['PATH'] ENV['PATH'] = ENV['PATH'].split(':').select { |p| !(p =~ /\.rbenv\/versions/) }.join(':') end yield ensure previous_environment.each do |key, value| ENV[key] = value end end
ruby
def without_rbenv(&block) previous_environment = ENV.select { |k,v| k =~ /\A(RBENV\_)/ } if previous_environment.size > 0 previous_environment.each { |key, value| ENV[key] = nil } previous_environment['PATH'] = ENV['PATH'] ENV['PATH'] = ENV['PATH'].split(':').select { |p| !(p =~ /\.rbenv\/versions/) }.join(':') end yield ensure previous_environment.each do |key, value| ENV[key] = value end end
[ "def", "without_rbenv", "(", "&", "block", ")", "previous_environment", "=", "ENV", ".", "select", "{", "|", "k", ",", "v", "|", "k", "=~", "/", "\\A", "\\_", "/", "}", "if", "previous_environment", ".", "size", ">", "0", "previous_environment", ".", "each", "{", "|", "key", ",", "value", "|", "ENV", "[", "key", "]", "=", "nil", "}", "previous_environment", "[", "'PATH'", "]", "=", "ENV", "[", "'PATH'", "]", "ENV", "[", "'PATH'", "]", "=", "ENV", "[", "'PATH'", "]", ".", "split", "(", "':'", ")", ".", "select", "{", "|", "p", "|", "!", "(", "p", "=~", "/", "\\.", "\\/", "/", ")", "}", ".", "join", "(", "':'", ")", "end", "yield", "ensure", "previous_environment", ".", "each", "do", "|", "key", ",", "value", "|", "ENV", "[", "key", "]", "=", "value", "end", "end" ]
If procodile is executed through rbenv it will pollute our environment which means that any spawned processes will be invoked with procodile's ruby rather than the ruby that the application wishes to use
[ "If", "procodile", "is", "executed", "through", "rbenv", "it", "will", "pollute", "our", "environment", "which", "means", "that", "any", "spawned", "processes", "will", "be", "invoked", "with", "procodile", "s", "ruby", "rather", "than", "the", "ruby", "that", "the", "application", "wishes", "to", "use" ]
57f42940715cba7186f0ce82b9bc4763f384cf2a
https://github.com/adamcooke/procodile/blob/57f42940715cba7186f0ce82b9bc4763f384cf2a/lib/procodile/instance.rb#L391-L403
16,009
adamcooke/procodile
lib/procodile/process.rb
Procodile.Process.environment_variables
def environment_variables global_variables = @config.environment_variables process_vars = @config.process_options[@name] ? @config.process_options[@name]['env'] || {} : {} process_local_vars = @config.local_process_options[@name] ? @config.local_process_options[@name]['env'] || {} : {} global_variables.merge(process_vars.merge(process_local_vars)).each_with_object({}) do |(key, value), hash| hash[key.to_s] = value.to_s end end
ruby
def environment_variables global_variables = @config.environment_variables process_vars = @config.process_options[@name] ? @config.process_options[@name]['env'] || {} : {} process_local_vars = @config.local_process_options[@name] ? @config.local_process_options[@name]['env'] || {} : {} global_variables.merge(process_vars.merge(process_local_vars)).each_with_object({}) do |(key, value), hash| hash[key.to_s] = value.to_s end end
[ "def", "environment_variables", "global_variables", "=", "@config", ".", "environment_variables", "process_vars", "=", "@config", ".", "process_options", "[", "@name", "]", "?", "@config", ".", "process_options", "[", "@name", "]", "[", "'env'", "]", "||", "{", "}", ":", "{", "}", "process_local_vars", "=", "@config", ".", "local_process_options", "[", "@name", "]", "?", "@config", ".", "local_process_options", "[", "@name", "]", "[", "'env'", "]", "||", "{", "}", ":", "{", "}", "global_variables", ".", "merge", "(", "process_vars", ".", "merge", "(", "process_local_vars", ")", ")", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "key", ",", "value", ")", ",", "hash", "|", "hash", "[", "key", ".", "to_s", "]", "=", "value", ".", "to_s", "end", "end" ]
Return all environment variables for this process
[ "Return", "all", "environment", "variables", "for", "this", "process" ]
57f42940715cba7186f0ce82b9bc4763f384cf2a
https://github.com/adamcooke/procodile/blob/57f42940715cba7186f0ce82b9bc4763f384cf2a/lib/procodile/process.rb#L37-L44
16,010
adamcooke/procodile
lib/procodile/process.rb
Procodile.Process.to_hash
def to_hash { :name => self.name, :log_color => self.log_color, :quantity => self.quantity, :max_respawns => self.max_respawns, :respawn_window => self.respawn_window, :command => self.command, :restart_mode => self.restart_mode, :log_path => self.log_path, :removed => self.removed ? true : false, :proxy_port => proxy_port, :proxy_address => proxy_address } end
ruby
def to_hash { :name => self.name, :log_color => self.log_color, :quantity => self.quantity, :max_respawns => self.max_respawns, :respawn_window => self.respawn_window, :command => self.command, :restart_mode => self.restart_mode, :log_path => self.log_path, :removed => self.removed ? true : false, :proxy_port => proxy_port, :proxy_address => proxy_address } end
[ "def", "to_hash", "{", ":name", "=>", "self", ".", "name", ",", ":log_color", "=>", "self", ".", "log_color", ",", ":quantity", "=>", "self", ".", "quantity", ",", ":max_respawns", "=>", "self", ".", "max_respawns", ",", ":respawn_window", "=>", "self", ".", "respawn_window", ",", ":command", "=>", "self", ".", "command", ",", ":restart_mode", "=>", "self", ".", "restart_mode", ",", ":log_path", "=>", "self", ".", "log_path", ",", ":removed", "=>", "self", ".", "removed", "?", "true", ":", "false", ",", ":proxy_port", "=>", "proxy_port", ",", ":proxy_address", "=>", "proxy_address", "}", "end" ]
Return a hash
[ "Return", "a", "hash" ]
57f42940715cba7186f0ce82b9bc4763f384cf2a
https://github.com/adamcooke/procodile/blob/57f42940715cba7186f0ce82b9bc4763f384cf2a/lib/procodile/process.rb#L165-L179
16,011
adamcooke/procodile
lib/procodile/app_determination.rb
Procodile.AppDetermination.app_options
def app_options if ambiguous? hash = {} @global_options.each_with_index do |option, i| hash[i] = option['name'] || option['root'] end hash else {} end end
ruby
def app_options if ambiguous? hash = {} @global_options.each_with_index do |option, i| hash[i] = option['name'] || option['root'] end hash else {} end end
[ "def", "app_options", "if", "ambiguous?", "hash", "=", "{", "}", "@global_options", ".", "each_with_index", "do", "|", "option", ",", "i", "|", "hash", "[", "i", "]", "=", "option", "[", "'name'", "]", "||", "option", "[", "'root'", "]", "end", "hash", "else", "{", "}", "end", "end" ]
Return an hash of possible options to settle the ambiguity
[ "Return", "an", "hash", "of", "possible", "options", "to", "settle", "the", "ambiguity" ]
57f42940715cba7186f0ce82b9bc4763f384cf2a
https://github.com/adamcooke/procodile/blob/57f42940715cba7186f0ce82b9bc4763f384cf2a/lib/procodile/app_determination.rb#L49-L59
16,012
rom-rb/rom
core/lib/rom/pipeline.rb
ROM.Pipeline.map_with
def map_with(*names) [self, *names.map { |name| mappers[name] }] .reduce { |a, e| composite_class.new(a, e) } end
ruby
def map_with(*names) [self, *names.map { |name| mappers[name] }] .reduce { |a, e| composite_class.new(a, e) } end
[ "def", "map_with", "(", "*", "names", ")", "[", "self", ",", "names", ".", "map", "{", "|", "name", "|", "mappers", "[", "name", "]", "}", "]", ".", "reduce", "{", "|", "a", ",", "e", "|", "composite_class", ".", "new", "(", "a", ",", "e", ")", "}", "end" ]
Send data through specified mappers @return [Relation::Composite] @api public
[ "Send", "data", "through", "specified", "mappers" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/pipeline.rb#L41-L44
16,013
rom-rb/rom
core/lib/rom/plugin_registry.rb
ROM.PluginRegistry.plugins_for
def plugins_for(type, adapter) case type when :configuration then configuration when :command then commands.adapter(adapter) when :mapper then mappers.adapter(adapter) when :relation then relations.adapter(adapter) when :schema then schemas.adapter(adapter) end end
ruby
def plugins_for(type, adapter) case type when :configuration then configuration when :command then commands.adapter(adapter) when :mapper then mappers.adapter(adapter) when :relation then relations.adapter(adapter) when :schema then schemas.adapter(adapter) end end
[ "def", "plugins_for", "(", "type", ",", "adapter", ")", "case", "type", "when", ":configuration", "then", "configuration", "when", ":command", "then", "commands", ".", "adapter", "(", "adapter", ")", "when", ":mapper", "then", "mappers", ".", "adapter", "(", "adapter", ")", "when", ":relation", "then", "relations", ".", "adapter", "(", "adapter", ")", "when", ":schema", "then", "schemas", ".", "adapter", "(", "adapter", ")", "end", "end" ]
Determine which specific registry to use @api private
[ "Determine", "which", "specific", "registry", "to", "use" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/plugin_registry.rb#L75-L83
16,014
rom-rb/rom
core/lib/rom/plugin_registry.rb
ROM.PluginRegistryBase.register
def register(name, mod, options) elements[name] = plugin_type.new(mod, options) end
ruby
def register(name, mod, options) elements[name] = plugin_type.new(mod, options) end
[ "def", "register", "(", "name", ",", "mod", ",", "options", ")", "elements", "[", "name", "]", "=", "plugin_type", ".", "new", "(", "mod", ",", "options", ")", "end" ]
Assign a plugin to this environment registry @param [Symbol] name The registered plugin name @param [Module] mod The plugin to register @param [Hash] options optional configuration data @api private
[ "Assign", "a", "plugin", "to", "this", "environment", "registry" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/plugin_registry.rb#L114-L116
16,015
rom-rb/rom
core/lib/rom/plugin_registry.rb
ROM.PluginRegistryBase.plugin_name
def plugin_name(plugin) tuple = elements.find { |(_, p)| p.equal?(plugin) } tuple[0] if tuple end
ruby
def plugin_name(plugin) tuple = elements.find { |(_, p)| p.equal?(plugin) } tuple[0] if tuple end
[ "def", "plugin_name", "(", "plugin", ")", "tuple", "=", "elements", ".", "find", "{", "|", "(", "_", ",", "p", ")", "|", "p", ".", "equal?", "(", "plugin", ")", "}", "tuple", "[", "0", "]", "if", "tuple", "end" ]
Returns plugin name by instance @return [Symbol] Plugin name @api private
[ "Returns", "plugin", "name", "by", "instance" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/plugin_registry.rb#L123-L126
16,016
rom-rb/rom
core/lib/rom/plugin_registry.rb
ROM.InternalPluginRegistry.fetch
def fetch(name, adapter_name = :default) adapter(adapter_name)[name] || adapter(:default)[name] || raise(UnknownPluginError, name) end
ruby
def fetch(name, adapter_name = :default) adapter(adapter_name)[name] || adapter(:default)[name] || raise(UnknownPluginError, name) end
[ "def", "fetch", "(", "name", ",", "adapter_name", "=", ":default", ")", "adapter", "(", "adapter_name", ")", "[", "name", "]", "||", "adapter", "(", ":default", ")", "[", "name", "]", "||", "raise", "(", "UnknownPluginError", ",", "name", ")", "end" ]
Return the plugin for a given adapter @param [Symbol] name The name of the plugin @param [Symbol] adapter_name (:default) The name of the adapter used @raise [UnknownPluginError] if no plugin is found with the given name @api public
[ "Return", "the", "plugin", "for", "a", "given", "adapter" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/plugin_registry.rb#L192-L195
16,017
rom-rb/rom
core/lib/rom/setup/auto_registration.rb
ROM.AutoRegistration.load_entities
def load_entities(entity) Dir[globs[entity]].map do |file| require file klass_name = case namespace when String AutoRegistrationStrategies::CustomNamespace.new( namespace: namespace, file: file, directory: directory ).call when TrueClass AutoRegistrationStrategies::WithNamespace.new( file: file, directory: directory ).call when FalseClass AutoRegistrationStrategies::NoNamespace.new( file: file, directory: directory, entity: component_dirs.fetch(entity) ).call end Inflector.constantize(klass_name) end end
ruby
def load_entities(entity) Dir[globs[entity]].map do |file| require file klass_name = case namespace when String AutoRegistrationStrategies::CustomNamespace.new( namespace: namespace, file: file, directory: directory ).call when TrueClass AutoRegistrationStrategies::WithNamespace.new( file: file, directory: directory ).call when FalseClass AutoRegistrationStrategies::NoNamespace.new( file: file, directory: directory, entity: component_dirs.fetch(entity) ).call end Inflector.constantize(klass_name) end end
[ "def", "load_entities", "(", "entity", ")", "Dir", "[", "globs", "[", "entity", "]", "]", ".", "map", "do", "|", "file", "|", "require", "file", "klass_name", "=", "case", "namespace", "when", "String", "AutoRegistrationStrategies", "::", "CustomNamespace", ".", "new", "(", "namespace", ":", "namespace", ",", "file", ":", "file", ",", "directory", ":", "directory", ")", ".", "call", "when", "TrueClass", "AutoRegistrationStrategies", "::", "WithNamespace", ".", "new", "(", "file", ":", "file", ",", "directory", ":", "directory", ")", ".", "call", "when", "FalseClass", "AutoRegistrationStrategies", "::", "NoNamespace", ".", "new", "(", "file", ":", "file", ",", "directory", ":", "directory", ",", "entity", ":", "component_dirs", ".", "fetch", "(", "entity", ")", ")", ".", "call", "end", "Inflector", ".", "constantize", "(", "klass_name", ")", "end", "end" ]
Load given component files @api private
[ "Load", "given", "component", "files" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/setup/auto_registration.rb#L80-L101
16,018
rom-rb/rom
core/lib/rom/setup/finalize.rb
ROM.Finalize.run!
def run! mappers = load_mappers relations = load_relations(mappers) commands = load_commands(relations) container = Container.new(gateways, relations, mappers, commands) container.freeze container end
ruby
def run! mappers = load_mappers relations = load_relations(mappers) commands = load_commands(relations) container = Container.new(gateways, relations, mappers, commands) container.freeze container end
[ "def", "run!", "mappers", "=", "load_mappers", "relations", "=", "load_relations", "(", "mappers", ")", "commands", "=", "load_commands", "(", "relations", ")", "container", "=", "Container", ".", "new", "(", "gateways", ",", "relations", ",", "mappers", ",", "commands", ")", "container", ".", "freeze", "container", "end" ]
Run the finalization process This creates relations, mappers and commands @return [Container] @api private
[ "Run", "the", "finalization", "process" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/setup/finalize.rb#L62-L70
16,019
rom-rb/rom
core/lib/rom/setup/finalize.rb
ROM.Finalize.load_relations
def load_relations(mappers) global_plugins = plugins.select { |p| p.relation? || p.schema? } FinalizeRelations.new( gateways, relation_classes, mappers: mappers, plugins: global_plugins, notifications: notifications ).run! end
ruby
def load_relations(mappers) global_plugins = plugins.select { |p| p.relation? || p.schema? } FinalizeRelations.new( gateways, relation_classes, mappers: mappers, plugins: global_plugins, notifications: notifications ).run! end
[ "def", "load_relations", "(", "mappers", ")", "global_plugins", "=", "plugins", ".", "select", "{", "|", "p", "|", "p", ".", "relation?", "||", "p", ".", "schema?", "}", "FinalizeRelations", ".", "new", "(", "gateways", ",", "relation_classes", ",", "mappers", ":", "mappers", ",", "plugins", ":", "global_plugins", ",", "notifications", ":", "notifications", ")", ".", "run!", "end" ]
Build entire relation registry from all known relation subclasses This includes both classes created via DSL and explicit definitions @api private
[ "Build", "entire", "relation", "registry", "from", "all", "known", "relation", "subclasses" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/setup/finalize.rb#L79-L89
16,020
rom-rb/rom
changeset/lib/rom/changeset.rb
ROM.Changeset.new
def new(relation, new_options = EMPTY_HASH) self.class.new(relation, new_options.empty? ? options : options.merge(new_options)) end
ruby
def new(relation, new_options = EMPTY_HASH) self.class.new(relation, new_options.empty? ? options : options.merge(new_options)) end
[ "def", "new", "(", "relation", ",", "new_options", "=", "EMPTY_HASH", ")", "self", ".", "class", ".", "new", "(", "relation", ",", "new_options", ".", "empty?", "?", "options", ":", "options", ".", "merge", "(", "new_options", ")", ")", "end" ]
Return a new changeset with provided relation New options can be provided too @param [Relation] relation @param [Hash] new_options @return [Changeset] @api public
[ "Return", "a", "new", "changeset", "with", "provided", "relation" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/changeset/lib/rom/changeset.rb#L86-L88
16,021
rom-rb/rom
core/lib/rom/support/notifications.rb
ROM.Notifications.register_event
def register_event(id, info = EMPTY_HASH) Notifications.events[id] = Event.new(id, info) end
ruby
def register_event(id, info = EMPTY_HASH) Notifications.events[id] = Event.new(id, info) end
[ "def", "register_event", "(", "id", ",", "info", "=", "EMPTY_HASH", ")", "Notifications", ".", "events", "[", "id", "]", "=", "Event", ".", "new", "(", "id", ",", "info", ")", "end" ]
Register an event @param [String] id A unique event key @param [Hash] info @api public
[ "Register", "an", "event" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/support/notifications.rb#L160-L162
16,022
rom-rb/rom
core/lib/rom/plugin.rb
ROM.Plugin.apply_to
def apply_to(klass, options = EMPTY_HASH) if mod.respond_to?(:new) klass.send(:include, mod.new(options)) else klass.send(:include, mod) end end
ruby
def apply_to(klass, options = EMPTY_HASH) if mod.respond_to?(:new) klass.send(:include, mod.new(options)) else klass.send(:include, mod) end end
[ "def", "apply_to", "(", "klass", ",", "options", "=", "EMPTY_HASH", ")", "if", "mod", ".", "respond_to?", "(", ":new", ")", "klass", ".", "send", "(", ":include", ",", "mod", ".", "new", "(", "options", ")", ")", "else", "klass", ".", "send", "(", ":include", ",", "mod", ")", "end", "end" ]
Apply this plugin to the provided class @param [Class] klass @api private
[ "Apply", "this", "plugin", "to", "the", "provided", "class" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/plugin.rb#L19-L25
16,023
rom-rb/rom
core/lib/rom/schema.rb
ROM.Schema.project
def project(*names) new(names.map { |name| name.is_a?(Symbol) ? self[name] : name }) end
ruby
def project(*names) new(names.map { |name| name.is_a?(Symbol) ? self[name] : name }) end
[ "def", "project", "(", "*", "names", ")", "new", "(", "names", ".", "map", "{", "|", "name", "|", "name", ".", "is_a?", "(", "Symbol", ")", "?", "self", "[", "name", "]", ":", "name", "}", ")", "end" ]
Project a schema to include only specified attributes @param [*Array<Symbol, Attribute>] names Attribute names @return [Schema] @api public
[ "Project", "a", "schema", "to", "include", "only", "specified", "attributes" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/schema.rb#L245-L247
16,024
rom-rb/rom
core/lib/rom/schema.rb
ROM.Schema.rename
def rename(mapping) new_attributes = map do |attr| alias_name = mapping[attr.name] alias_name ? attr.aliased(alias_name) : attr end new(new_attributes) end
ruby
def rename(mapping) new_attributes = map do |attr| alias_name = mapping[attr.name] alias_name ? attr.aliased(alias_name) : attr end new(new_attributes) end
[ "def", "rename", "(", "mapping", ")", "new_attributes", "=", "map", "do", "|", "attr", "|", "alias_name", "=", "mapping", "[", "attr", ".", "name", "]", "alias_name", "?", "attr", ".", "aliased", "(", "alias_name", ")", ":", "attr", "end", "new", "(", "new_attributes", ")", "end" ]
Project a schema with renamed attributes @param [Hash] mapping The attribute mappings @return [Schema] @api public
[ "Project", "a", "schema", "with", "renamed", "attributes" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/schema.rb#L267-L274
16,025
rom-rb/rom
core/lib/rom/schema.rb
ROM.Schema.wrap
def wrap(prefix = name.dataset) new(map { |attr| attr.wrapped? ? attr : attr.wrapped(prefix) }) end
ruby
def wrap(prefix = name.dataset) new(map { |attr| attr.wrapped? ? attr : attr.wrapped(prefix) }) end
[ "def", "wrap", "(", "prefix", "=", "name", ".", "dataset", ")", "new", "(", "map", "{", "|", "attr", "|", "attr", ".", "wrapped?", "?", "attr", ":", "attr", ".", "wrapped", "(", "prefix", ")", "}", ")", "end" ]
Return new schema with all attributes marked as prefixed and wrapped This is useful when relations are joined and the right side should be marked as wrapped @param [Symbol] prefix The prefix used for aliasing wrapped attributes @return [Schema] @api public
[ "Return", "new", "schema", "with", "all", "attributes", "marked", "as", "prefixed", "and", "wrapped" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/schema.rb#L297-L299
16,026
rom-rb/rom
core/lib/rom/schema.rb
ROM.Schema.uniq
def uniq(&block) if block new(attributes.uniq(&block)) else new(attributes.uniq(&:name)) end end
ruby
def uniq(&block) if block new(attributes.uniq(&block)) else new(attributes.uniq(&:name)) end end
[ "def", "uniq", "(", "&", "block", ")", "if", "block", "new", "(", "attributes", ".", "uniq", "(", "block", ")", ")", "else", "new", "(", "attributes", ".", "uniq", "(", ":name", ")", ")", "end", "end" ]
Return a new schema with uniq attributes @return [Schema] @api public
[ "Return", "a", "new", "schema", "with", "uniq", "attributes" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/schema.rb#L349-L355
16,027
rom-rb/rom
core/lib/rom/schema.rb
ROM.Schema.finalize_attributes!
def finalize_attributes!(gateway: nil, relations: nil) inferrer.(self, gateway).each { |key, value| set!(key, value) } yield if block_given? initialize_primary_key_names self end
ruby
def finalize_attributes!(gateway: nil, relations: nil) inferrer.(self, gateway).each { |key, value| set!(key, value) } yield if block_given? initialize_primary_key_names self end
[ "def", "finalize_attributes!", "(", "gateway", ":", "nil", ",", "relations", ":", "nil", ")", "inferrer", ".", "(", "self", ",", "gateway", ")", ".", "each", "{", "|", "key", ",", "value", "|", "set!", "(", "key", ",", "value", ")", "}", "yield", "if", "block_given?", "initialize_primary_key_names", "self", "end" ]
This hook is called when relation is being build during container finalization When block is provided it'll be called just before freezing the instance so that additional ivars can be set @return [self] @api private
[ "This", "hook", "is", "called", "when", "relation", "is", "being", "build", "during", "container", "finalization" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/schema.rb#L395-L403
16,028
rom-rb/rom
core/lib/rom/schema.rb
ROM.Schema.to_output_hash
def to_output_hash HASH_SCHEMA.schema( map { |attr| [attr.key, attr.to_read_type] }.to_h ) end
ruby
def to_output_hash HASH_SCHEMA.schema( map { |attr| [attr.key, attr.to_read_type] }.to_h ) end
[ "def", "to_output_hash", "HASH_SCHEMA", ".", "schema", "(", "map", "{", "|", "attr", "|", "[", "attr", ".", "key", ",", "attr", ".", "to_read_type", "]", "}", ".", "to_h", ")", "end" ]
Return coercion function using attribute read types This is used for `output_schema` in relations @return [Dry::Types::Hash] @api private
[ "Return", "coercion", "function", "using", "attribute", "read", "types" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/schema.rb#L424-L428
16,029
rom-rb/rom
core/lib/rom/schema.rb
ROM.Schema.to_input_hash
def to_input_hash HASH_SCHEMA.schema( map { |attr| [attr.name, attr.to_write_type] }.to_h ) end
ruby
def to_input_hash HASH_SCHEMA.schema( map { |attr| [attr.name, attr.to_write_type] }.to_h ) end
[ "def", "to_input_hash", "HASH_SCHEMA", ".", "schema", "(", "map", "{", "|", "attr", "|", "[", "attr", ".", "name", ",", "attr", ".", "to_write_type", "]", "}", ".", "to_h", ")", "end" ]
Return coercion function using attribute types This is used for `input_schema` in relations, typically commands use it for processing input @return [Dry::Types::Hash] @api private
[ "Return", "coercion", "function", "using", "attribute", "types" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/schema.rb#L438-L442
16,030
rom-rb/rom
core/lib/rom/auto_curry.rb
ROM.AutoCurry.auto_curry
def auto_curry(name, &block) arity = instance_method(name).arity return unless public_instance_methods.include?(name) && arity != 0 mod = Module.new mod.module_eval do define_method(name) do |*args, &mblock| response = if arity < 0 || arity == args.size super(*args, &mblock) else self.class.curried.new(self, view: name, curry_args: args, arity: arity) end if block response.instance_exec(&block) else response end end end auto_curried_methods << name prepend(mod) end
ruby
def auto_curry(name, &block) arity = instance_method(name).arity return unless public_instance_methods.include?(name) && arity != 0 mod = Module.new mod.module_eval do define_method(name) do |*args, &mblock| response = if arity < 0 || arity == args.size super(*args, &mblock) else self.class.curried.new(self, view: name, curry_args: args, arity: arity) end if block response.instance_exec(&block) else response end end end auto_curried_methods << name prepend(mod) end
[ "def", "auto_curry", "(", "name", ",", "&", "block", ")", "arity", "=", "instance_method", "(", "name", ")", ".", "arity", "return", "unless", "public_instance_methods", ".", "include?", "(", "name", ")", "&&", "arity", "!=", "0", "mod", "=", "Module", ".", "new", "mod", ".", "module_eval", "do", "define_method", "(", "name", ")", "do", "|", "*", "args", ",", "&", "mblock", "|", "response", "=", "if", "arity", "<", "0", "||", "arity", "==", "args", ".", "size", "super", "(", "args", ",", "mblock", ")", "else", "self", ".", "class", ".", "curried", ".", "new", "(", "self", ",", "view", ":", "name", ",", "curry_args", ":", "args", ",", "arity", ":", "arity", ")", "end", "if", "block", "response", ".", "instance_exec", "(", "block", ")", "else", "response", "end", "end", "end", "auto_curried_methods", "<<", "name", "prepend", "(", "mod", ")", "end" ]
Auto-curry a method @param [Symbol] name The name of a method @api private
[ "Auto", "-", "curry", "a", "method" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/auto_curry.rb#L39-L66
16,031
rom-rb/rom
core/lib/rom/command_registry.rb
ROM.CommandRegistry.[]
def [](*args) if args.size.equal?(1) command = super mapper = options[:mapper] if mapper command.curry >> mapper else command end else cache.fetch_or_store(args.hash) { compiler.(*args) } end end
ruby
def [](*args) if args.size.equal?(1) command = super mapper = options[:mapper] if mapper command.curry >> mapper else command end else cache.fetch_or_store(args.hash) { compiler.(*args) } end end
[ "def", "[]", "(", "*", "args", ")", "if", "args", ".", "size", ".", "equal?", "(", "1", ")", "command", "=", "super", "mapper", "=", "options", "[", ":mapper", "]", "if", "mapper", "command", ".", "curry", ">>", "mapper", "else", "command", "end", "else", "cache", ".", "fetch_or_store", "(", "args", ".", "hash", ")", "{", "compiler", ".", "(", "args", ")", "}", "end", "end" ]
Return a command from the registry If mapper is set command will be turned into a composite command with auto-mapping @overload [](name) @param [Symbol] name The command identifier from the registry @example create_user = rom.commands[:users][:create] create_user[name: 'Jane'] # with mapping, assuming :entity mapper is registered for :users relation create_user = rom.commands[:users].map_with(:entity)[:create] create_user[name: 'Jane'] # => result is sent through :entity mapper @overload [](*args) @param [Array] *args {CommandCompiler} arguments @see CommandCompiler#call @return [Command,Command::Composite] @api public
[ "Return", "a", "command", "from", "the", "registry" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/command_registry.rb#L63-L76
16,032
rom-rb/rom
core/lib/rom/configuration_dsl.rb
ROM.ConfigurationDSL.relation
def relation(name, options = EMPTY_HASH, &block) klass_opts = { adapter: default_adapter }.merge(options) klass = Relation.build_class(name, klass_opts) klass.schema_opts(dataset: name, relation: name) klass.class_eval(&block) if block register_relation(klass) klass end
ruby
def relation(name, options = EMPTY_HASH, &block) klass_opts = { adapter: default_adapter }.merge(options) klass = Relation.build_class(name, klass_opts) klass.schema_opts(dataset: name, relation: name) klass.class_eval(&block) if block register_relation(klass) klass end
[ "def", "relation", "(", "name", ",", "options", "=", "EMPTY_HASH", ",", "&", "block", ")", "klass_opts", "=", "{", "adapter", ":", "default_adapter", "}", ".", "merge", "(", "options", ")", "klass", "=", "Relation", ".", "build_class", "(", "name", ",", "klass_opts", ")", "klass", ".", "schema_opts", "(", "dataset", ":", "name", ",", "relation", ":", "name", ")", "klass", ".", "class_eval", "(", "block", ")", "if", "block", "register_relation", "(", "klass", ")", "klass", "end" ]
Relation definition DSL @example setup.relation(:users) do def names project(:name) end end @api public
[ "Relation", "definition", "DSL" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/configuration_dsl.rb#L21-L28
16,033
rom-rb/rom
core/lib/rom/configuration_dsl.rb
ROM.ConfigurationDSL.commands
def commands(name, &block) register_command(*CommandDSL.new(name, default_adapter, &block).command_classes) end
ruby
def commands(name, &block) register_command(*CommandDSL.new(name, default_adapter, &block).command_classes) end
[ "def", "commands", "(", "name", ",", "&", "block", ")", "register_command", "(", "CommandDSL", ".", "new", "(", "name", ",", "default_adapter", ",", "block", ")", ".", "command_classes", ")", "end" ]
Command definition DSL @example setup.commands(:users) do define(:create) do input NewUserParams result :one end define(:update) do input UserParams result :many end define(:delete) do result :many end end @api public
[ "Command", "definition", "DSL" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/configuration_dsl.rb#L50-L52
16,034
rom-rb/rom
core/lib/rom/configuration_dsl.rb
ROM.ConfigurationDSL.plugin
def plugin(adapter, spec, &block) type, name = spec.flatten(1) plugin = plugin_registry.send(type).adapter(adapter).fetch(name) { plugin_registry.send(type).fetch(name) } if block register_plugin(plugin.configure(&block)) else register_plugin(plugin) end end
ruby
def plugin(adapter, spec, &block) type, name = spec.flatten(1) plugin = plugin_registry.send(type).adapter(adapter).fetch(name) { plugin_registry.send(type).fetch(name) } if block register_plugin(plugin.configure(&block)) else register_plugin(plugin) end end
[ "def", "plugin", "(", "adapter", ",", "spec", ",", "&", "block", ")", "type", ",", "name", "=", "spec", ".", "flatten", "(", "1", ")", "plugin", "=", "plugin_registry", ".", "send", "(", "type", ")", ".", "adapter", "(", "adapter", ")", ".", "fetch", "(", "name", ")", "{", "plugin_registry", ".", "send", "(", "type", ")", ".", "fetch", "(", "name", ")", "}", "if", "block", "register_plugin", "(", "plugin", ".", "configure", "(", "block", ")", ")", "else", "register_plugin", "(", "plugin", ")", "end", "end" ]
Configures a plugin for a specific adapter to be enabled for all relations @example config = ROM::Configuration.new(:sql, 'sqlite::memory') config.plugin(:sql, relations: :instrumentation) do |p| p.notifications = MyNotificationsBackend end config.plugin(:sql, relations: :pagination) @param [Symbol] adapter The adapter identifier @param [Hash<Symbol=>Symbol>] spec Component identifier => plugin identifier @return [Plugin] @api public
[ "Configures", "a", "plugin", "for", "a", "specific", "adapter", "to", "be", "enabled", "for", "all", "relations" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/configuration_dsl.rb#L71-L80
16,035
rom-rb/rom
core/lib/rom/command.rb
ROM.Command.call
def call(*args, &block) tuples = if hooks? prepared = if curried? apply_hooks(before_hooks, *(curry_args + args)) else apply_hooks(before_hooks, *args) end result = prepared ? execute(prepared, &block) : execute(&block) if curried? if args.size > 0 apply_hooks(after_hooks, result, *args) elsif curry_args.size > 1 apply_hooks(after_hooks, result, curry_args[1]) else apply_hooks(after_hooks, result) end else apply_hooks(after_hooks, result, *args[1..args.size-1]) end else execute(*(curry_args + args), &block) end if one? tuples.first else tuples end end
ruby
def call(*args, &block) tuples = if hooks? prepared = if curried? apply_hooks(before_hooks, *(curry_args + args)) else apply_hooks(before_hooks, *args) end result = prepared ? execute(prepared, &block) : execute(&block) if curried? if args.size > 0 apply_hooks(after_hooks, result, *args) elsif curry_args.size > 1 apply_hooks(after_hooks, result, curry_args[1]) else apply_hooks(after_hooks, result) end else apply_hooks(after_hooks, result, *args[1..args.size-1]) end else execute(*(curry_args + args), &block) end if one? tuples.first else tuples end end
[ "def", "call", "(", "*", "args", ",", "&", "block", ")", "tuples", "=", "if", "hooks?", "prepared", "=", "if", "curried?", "apply_hooks", "(", "before_hooks", ",", "(", "curry_args", "+", "args", ")", ")", "else", "apply_hooks", "(", "before_hooks", ",", "args", ")", "end", "result", "=", "prepared", "?", "execute", "(", "prepared", ",", "block", ")", ":", "execute", "(", "block", ")", "if", "curried?", "if", "args", ".", "size", ">", "0", "apply_hooks", "(", "after_hooks", ",", "result", ",", "args", ")", "elsif", "curry_args", ".", "size", ">", "1", "apply_hooks", "(", "after_hooks", ",", "result", ",", "curry_args", "[", "1", "]", ")", "else", "apply_hooks", "(", "after_hooks", ",", "result", ")", "end", "else", "apply_hooks", "(", "after_hooks", ",", "result", ",", "args", "[", "1", "..", "args", ".", "size", "-", "1", "]", ")", "end", "else", "execute", "(", "(", "curry_args", "+", "args", ")", ",", "block", ")", "end", "if", "one?", "tuples", ".", "first", "else", "tuples", "end", "end" ]
Call the command and return one or many tuples This method will apply before/after hooks automatically @api public
[ "Call", "the", "command", "and", "return", "one", "or", "many", "tuples" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/command.rb#L272-L304
16,036
rom-rb/rom
core/lib/rom/command.rb
ROM.Command.curry
def curry(*args) if curry_args.empty? && args.first.is_a?(Graph::InputEvaluator) Lazy[self].new(self, *args) else self.class.build(relation, { **options, curry_args: args }) end end
ruby
def curry(*args) if curry_args.empty? && args.first.is_a?(Graph::InputEvaluator) Lazy[self].new(self, *args) else self.class.build(relation, { **options, curry_args: args }) end end
[ "def", "curry", "(", "*", "args", ")", "if", "curry_args", ".", "empty?", "&&", "args", ".", "first", ".", "is_a?", "(", "Graph", "::", "InputEvaluator", ")", "Lazy", "[", "self", "]", ".", "new", "(", "self", ",", "args", ")", "else", "self", ".", "class", ".", "build", "(", "relation", ",", "{", "**", "options", ",", "curry_args", ":", "args", "}", ")", "end", "end" ]
Curry this command with provided args Curried command can be called without args. If argument is a graph input processor, lazy command will be returned, which is used for handling nested input hashes. @return [Command, Lazy] @api public
[ "Curry", "this", "command", "with", "provided", "args" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/command.rb#L315-L321
16,037
rom-rb/rom
core/lib/rom/command.rb
ROM.Command.map_input_tuples
def map_input_tuples(tuples, &mapper) return enum_for(:with_input_tuples, tuples) unless mapper if tuples.respond_to? :merge mapper[tuples] else tuples.map(&mapper) end end
ruby
def map_input_tuples(tuples, &mapper) return enum_for(:with_input_tuples, tuples) unless mapper if tuples.respond_to? :merge mapper[tuples] else tuples.map(&mapper) end end
[ "def", "map_input_tuples", "(", "tuples", ",", "&", "mapper", ")", "return", "enum_for", "(", ":with_input_tuples", ",", "tuples", ")", "unless", "mapper", "if", "tuples", ".", "respond_to?", ":merge", "mapper", "[", "tuples", "]", "else", "tuples", ".", "map", "(", "mapper", ")", "end", "end" ]
Yields tuples for insertion or return an enumerator @api private
[ "Yields", "tuples", "for", "insertion", "or", "return", "an", "enumerator" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/command.rb#L449-L457
16,038
rom-rb/rom
core/lib/rom/command.rb
ROM.Command.apply_hooks
def apply_hooks(hooks, tuples, *args) hooks.reduce(tuples) do |a, e| if e.is_a?(Hash) hook_meth, hook_args = e.to_a.flatten(1) __send__(hook_meth, a, *args, **hook_args) else __send__(e, a, *args) end end end
ruby
def apply_hooks(hooks, tuples, *args) hooks.reduce(tuples) do |a, e| if e.is_a?(Hash) hook_meth, hook_args = e.to_a.flatten(1) __send__(hook_meth, a, *args, **hook_args) else __send__(e, a, *args) end end end
[ "def", "apply_hooks", "(", "hooks", ",", "tuples", ",", "*", "args", ")", "hooks", ".", "reduce", "(", "tuples", ")", "do", "|", "a", ",", "e", "|", "if", "e", ".", "is_a?", "(", "Hash", ")", "hook_meth", ",", "hook_args", "=", "e", ".", "to_a", ".", "flatten", "(", "1", ")", "__send__", "(", "hook_meth", ",", "a", ",", "args", ",", "**", "hook_args", ")", "else", "__send__", "(", "e", ",", "a", ",", "args", ")", "end", "end", "end" ]
Apply provided hooks Used by #call @return [Array<Hash>] @api private
[ "Apply", "provided", "hooks" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/command.rb#L477-L486
16,039
rom-rb/rom
core/lib/rom/command.rb
ROM.Command.wrap_dataset
def wrap_dataset(dataset) if relation.is_a?(Relation::Composite) relation.new(dataset).to_a else dataset end end
ruby
def wrap_dataset(dataset) if relation.is_a?(Relation::Composite) relation.new(dataset).to_a else dataset end end
[ "def", "wrap_dataset", "(", "dataset", ")", "if", "relation", ".", "is_a?", "(", "Relation", "::", "Composite", ")", "relation", ".", "new", "(", "dataset", ")", ".", "to_a", "else", "dataset", "end", "end" ]
Pipes a dataset through command's relation @return [Array] @api private
[ "Pipes", "a", "dataset", "through", "command", "s", "relation" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/command.rb#L493-L499
16,040
rom-rb/rom
core/lib/rom/mapper.rb
ROM.Mapper.call
def call(relation) transformers.reduce(relation.to_a) { |a, e| e.call(a) } end
ruby
def call(relation) transformers.reduce(relation.to_a) { |a, e| e.call(a) } end
[ "def", "call", "(", "relation", ")", "transformers", ".", "reduce", "(", "relation", ".", "to_a", ")", "{", "|", "a", ",", "e", "|", "e", ".", "call", "(", "a", ")", "}", "end" ]
Process a relation using the transformers @api private
[ "Process", "a", "relation", "using", "the", "transformers" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/mapper.rb#L96-L98
16,041
rom-rb/rom
core/lib/rom/command_compiler.rb
ROM.CommandCompiler.call
def call(*args) cache.fetch_or_store(args.hash) do type, adapter, ast, plugins, plugins_options, meta = args compiler = with( id: type, adapter: adapter, plugins: Array(plugins), plugins_options: plugins_options, meta: meta ) graph_opts = compiler.visit(ast) command = ROM::Commands::Graph.build(registry, graph_opts) if command.graph? CommandProxy.new(command) elsif command.lazy? command.unwrap else command end end end
ruby
def call(*args) cache.fetch_or_store(args.hash) do type, adapter, ast, plugins, plugins_options, meta = args compiler = with( id: type, adapter: adapter, plugins: Array(plugins), plugins_options: plugins_options, meta: meta ) graph_opts = compiler.visit(ast) command = ROM::Commands::Graph.build(registry, graph_opts) if command.graph? CommandProxy.new(command) elsif command.lazy? command.unwrap else command end end end
[ "def", "call", "(", "*", "args", ")", "cache", ".", "fetch_or_store", "(", "args", ".", "hash", ")", "do", "type", ",", "adapter", ",", "ast", ",", "plugins", ",", "plugins_options", ",", "meta", "=", "args", "compiler", "=", "with", "(", "id", ":", "type", ",", "adapter", ":", "adapter", ",", "plugins", ":", "Array", "(", "plugins", ")", ",", "plugins_options", ":", "plugins_options", ",", "meta", ":", "meta", ")", "graph_opts", "=", "compiler", ".", "visit", "(", "ast", ")", "command", "=", "ROM", "::", "Commands", "::", "Graph", ".", "build", "(", "registry", ",", "graph_opts", ")", "if", "command", ".", "graph?", "CommandProxy", ".", "new", "(", "command", ")", "elsif", "command", ".", "lazy?", "command", ".", "unwrap", "else", "command", "end", "end", "end" ]
Return a specific command type for a given adapter and relation AST This class holds its own registry where all generated commands are being stored CommandProxy is returned for complex command graphs as they expect root relation name to be present in the input, which we don't want to have in repositories. It might be worth looking into removing this requirement from rom core Command::Graph API. @overload [](type, adapter, ast, plugins, meta) @param type [Symbol] The type of command @param adapter [Symbol] The adapter identifier @param ast [Array] The AST representation of a relation @param plugins [Array<Symbol>] A list of optional command plugins that should be used @param meta [Hash] Meta data for a command @return [Command, CommandProxy] @api private
[ "Return", "a", "specific", "command", "type", "for", "a", "given", "adapter", "and", "relation", "AST" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/command_compiler.rb#L89-L112
16,042
rom-rb/rom
core/lib/rom/command_compiler.rb
ROM.CommandCompiler.register_command
def register_command(rel_name, type, meta, parent_relation = nil) relation = relations[rel_name] type.create_class(rel_name, type) do |klass| klass.result(meta.fetch(:combine_type, result)) if meta[:combine_type] setup_associates(klass, relation, meta, parent_relation) end plugins.each do |plugin| plugin_options = plugins_options.fetch(plugin) { EMPTY_HASH } klass.use(plugin, plugin_options) end gateway = gateways[relation.gateway] notifications.trigger( 'configuration.commands.class.before_build', command: klass, gateway: gateway, dataset: relation.dataset, adapter: adapter ) klass.extend_for_relation(relation) if klass.restrictable registry[rel_name][type] = klass.build(relation, input: relation.input_schema) end end
ruby
def register_command(rel_name, type, meta, parent_relation = nil) relation = relations[rel_name] type.create_class(rel_name, type) do |klass| klass.result(meta.fetch(:combine_type, result)) if meta[:combine_type] setup_associates(klass, relation, meta, parent_relation) end plugins.each do |plugin| plugin_options = plugins_options.fetch(plugin) { EMPTY_HASH } klass.use(plugin, plugin_options) end gateway = gateways[relation.gateway] notifications.trigger( 'configuration.commands.class.before_build', command: klass, gateway: gateway, dataset: relation.dataset, adapter: adapter ) klass.extend_for_relation(relation) if klass.restrictable registry[rel_name][type] = klass.build(relation, input: relation.input_schema) end end
[ "def", "register_command", "(", "rel_name", ",", "type", ",", "meta", ",", "parent_relation", "=", "nil", ")", "relation", "=", "relations", "[", "rel_name", "]", "type", ".", "create_class", "(", "rel_name", ",", "type", ")", "do", "|", "klass", "|", "klass", ".", "result", "(", "meta", ".", "fetch", "(", ":combine_type", ",", "result", ")", ")", "if", "meta", "[", ":combine_type", "]", "setup_associates", "(", "klass", ",", "relation", ",", "meta", ",", "parent_relation", ")", "end", "plugins", ".", "each", "do", "|", "plugin", "|", "plugin_options", "=", "plugins_options", ".", "fetch", "(", "plugin", ")", "{", "EMPTY_HASH", "}", "klass", ".", "use", "(", "plugin", ",", "plugin_options", ")", "end", "gateway", "=", "gateways", "[", "relation", ".", "gateway", "]", "notifications", ".", "trigger", "(", "'configuration.commands.class.before_build'", ",", "command", ":", "klass", ",", "gateway", ":", "gateway", ",", "dataset", ":", "relation", ".", "dataset", ",", "adapter", ":", "adapter", ")", "klass", ".", "extend_for_relation", "(", "relation", ")", "if", "klass", ".", "restrictable", "registry", "[", "rel_name", "]", "[", "type", "]", "=", "klass", ".", "build", "(", "relation", ",", "input", ":", "relation", ".", "input_schema", ")", "end", "end" ]
Build a command object for a specific relation The command will be prepared for handling associations if it's a combined relation. Additional plugins will be enabled if they are configured for this compiler. @param [Symbol] rel_name A relation identifier from the container registry @param [Symbol] type The command type @param [Hash] meta Meta information from relation AST @param [Symbol] parent_relation Optional parent relation identifier @return [ROM::Command] @api private
[ "Build", "a", "command", "object", "for", "a", "specific", "relation" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/command_compiler.rb#L190-L216
16,043
rom-rb/rom
core/lib/rom/command_compiler.rb
ROM.CommandCompiler.setup_associates
def setup_associates(klass, relation, meta, parent_relation) assoc_name = if relation.associations.key?(parent_relation) parent_relation else singular_name = Inflector.singularize(parent_relation).to_sym singular_name if relation.associations.key?(singular_name) end if assoc_name klass.associates(assoc_name) else klass.associates(parent_relation) end end
ruby
def setup_associates(klass, relation, meta, parent_relation) assoc_name = if relation.associations.key?(parent_relation) parent_relation else singular_name = Inflector.singularize(parent_relation).to_sym singular_name if relation.associations.key?(singular_name) end if assoc_name klass.associates(assoc_name) else klass.associates(parent_relation) end end
[ "def", "setup_associates", "(", "klass", ",", "relation", ",", "meta", ",", "parent_relation", ")", "assoc_name", "=", "if", "relation", ".", "associations", ".", "key?", "(", "parent_relation", ")", "parent_relation", "else", "singular_name", "=", "Inflector", ".", "singularize", "(", "parent_relation", ")", ".", "to_sym", "singular_name", "if", "relation", ".", "associations", ".", "key?", "(", "singular_name", ")", "end", "if", "assoc_name", "klass", ".", "associates", "(", "assoc_name", ")", "else", "klass", ".", "associates", "(", "parent_relation", ")", "end", "end" ]
Sets up `associates` plugin for a given command class and relation @param [Class] klass The command class @param [Relation] relation The relation for the command @api private
[ "Sets", "up", "associates", "plugin", "for", "a", "given", "command", "class", "and", "relation" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/command_compiler.rb#L233-L247
16,044
rom-rb/rom
core/lib/rom/environment.rb
ROM.Environment.normalize_gateways
def normalize_gateways(gateways_config) gateways_config.each_with_object(map: {}, gateways: {}) do |(name, spec), hash| identifier, *args = Array(spec) if identifier.is_a?(Gateway) gateway = identifier else gateway = Gateway.setup(identifier, *args.flatten) end hash[:map][gateway] = name hash[:gateways][name] = gateway end end
ruby
def normalize_gateways(gateways_config) gateways_config.each_with_object(map: {}, gateways: {}) do |(name, spec), hash| identifier, *args = Array(spec) if identifier.is_a?(Gateway) gateway = identifier else gateway = Gateway.setup(identifier, *args.flatten) end hash[:map][gateway] = name hash[:gateways][name] = gateway end end
[ "def", "normalize_gateways", "(", "gateways_config", ")", "gateways_config", ".", "each_with_object", "(", "map", ":", "{", "}", ",", "gateways", ":", "{", "}", ")", "do", "|", "(", "name", ",", "spec", ")", ",", "hash", "|", "identifier", ",", "*", "args", "=", "Array", "(", "spec", ")", "if", "identifier", ".", "is_a?", "(", "Gateway", ")", "gateway", "=", "identifier", "else", "gateway", "=", "Gateway", ".", "setup", "(", "identifier", ",", "args", ".", "flatten", ")", "end", "hash", "[", ":map", "]", "[", "gateway", "]", "=", "name", "hash", "[", ":gateways", "]", "[", "name", "]", "=", "gateway", "end", "end" ]
Build gateways using the setup interface @api private
[ "Build", "gateways", "using", "the", "setup", "interface" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/environment.rb#L47-L60
16,045
rom-rb/rom
core/lib/rom/attribute.rb
ROM.Attribute.meta
def meta(opts = nil) if opts self.class.new(type.meta(opts), options) else type.meta end end
ruby
def meta(opts = nil) if opts self.class.new(type.meta(opts), options) else type.meta end end
[ "def", "meta", "(", "opts", "=", "nil", ")", "if", "opts", "self", ".", "class", ".", "new", "(", "type", ".", "meta", "(", "opts", ")", ",", "options", ")", "else", "type", ".", "meta", "end", "end" ]
Return attribute type with additional meta information Return meta information hash if no opts are provided @param [Hash] opts The meta options @return [Attribute] @api public
[ "Return", "attribute", "type", "with", "additional", "meta", "information" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/attribute.rb#L305-L311
16,046
rom-rb/rom
core/lib/rom/attribute.rb
ROM.Attribute.inspect
def inspect opts = options.reject { |k| %i[type name].include?(k) } meta_and_opts = meta.merge(opts).map { |k, v| "#{k}=#{v.inspect}" } %(#<#{self.class}[#{type.name}] name=#{name.inspect} #{meta_and_opts.join(' ')}>) end
ruby
def inspect opts = options.reject { |k| %i[type name].include?(k) } meta_and_opts = meta.merge(opts).map { |k, v| "#{k}=#{v.inspect}" } %(#<#{self.class}[#{type.name}] name=#{name.inspect} #{meta_and_opts.join(' ')}>) end
[ "def", "inspect", "opts", "=", "options", ".", "reject", "{", "|", "k", "|", "%i[", "type", "name", "]", ".", "include?", "(", "k", ")", "}", "meta_and_opts", "=", "meta", ".", "merge", "(", "opts", ")", ".", "map", "{", "|", "k", ",", "v", "|", "\"#{k}=#{v.inspect}\"", "}", "%(#<#{self.class}[#{type.name}] name=#{name.inspect} #{meta_and_opts.join(' ')}>)", "end" ]
Return string representation of the attribute type @return [String] @api public
[ "Return", "string", "representation", "of", "the", "attribute", "type" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/attribute.rb#L318-L322
16,047
rom-rb/rom
core/lib/rom/attribute.rb
ROM.Attribute.optional
def optional sum = self.class.new(super, options) read? ? sum.meta(read: meta[:read].optional) : sum end
ruby
def optional sum = self.class.new(super, options) read? ? sum.meta(read: meta[:read].optional) : sum end
[ "def", "optional", "sum", "=", "self", ".", "class", ".", "new", "(", "super", ",", "options", ")", "read?", "?", "sum", ".", "meta", "(", "read", ":", "meta", "[", ":read", "]", ".", "optional", ")", ":", "sum", "end" ]
Return nullable attribute @return [Attribute] @api public
[ "Return", "nullable", "attribute" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/attribute.rb#L369-L372
16,048
rom-rb/rom
core/lib/rom/relation.rb
ROM.Relation.each
def each return to_enum unless block_given? if auto_map? mapper.(dataset.map { |tuple| output_schema[tuple] }).each { |struct| yield(struct) } else dataset.each { |tuple| yield(output_schema[tuple]) } end end
ruby
def each return to_enum unless block_given? if auto_map? mapper.(dataset.map { |tuple| output_schema[tuple] }).each { |struct| yield(struct) } else dataset.each { |tuple| yield(output_schema[tuple]) } end end
[ "def", "each", "return", "to_enum", "unless", "block_given?", "if", "auto_map?", "mapper", ".", "(", "dataset", ".", "map", "{", "|", "tuple", "|", "output_schema", "[", "tuple", "]", "}", ")", ".", "each", "{", "|", "struct", "|", "yield", "(", "struct", ")", "}", "else", "dataset", ".", "each", "{", "|", "tuple", "|", "yield", "(", "output_schema", "[", "tuple", "]", ")", "}", "end", "end" ]
Yields relation tuples Every tuple is processed through Relation#output_schema, it's a no-op by default @yield [Hash] @return [Enumerator] if block is not provided @api public
[ "Yields", "relation", "tuples" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/relation.rb#L219-L227
16,049
rom-rb/rom
core/lib/rom/relation.rb
ROM.Relation.node
def node(name) assoc = associations[name] other = assoc.node other.eager_load(assoc) end
ruby
def node(name) assoc = associations[name] other = assoc.node other.eager_load(assoc) end
[ "def", "node", "(", "name", ")", "assoc", "=", "associations", "[", "name", "]", "other", "=", "assoc", ".", "node", "other", ".", "eager_load", "(", "assoc", ")", "end" ]
Create a graph node for a given association identifier @param [Symbol, Relation::Name] name @return [Relation] @api public
[ "Create", "a", "graph", "node", "for", "a", "given", "association", "identifier" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/relation.rb#L289-L293
16,050
rom-rb/rom
core/lib/rom/relation.rb
ROM.Relation.eager_load
def eager_load(assoc) relation = assoc.prepare(self) if assoc.override? relation.(assoc) else relation.preload_assoc(assoc) end end
ruby
def eager_load(assoc) relation = assoc.prepare(self) if assoc.override? relation.(assoc) else relation.preload_assoc(assoc) end end
[ "def", "eager_load", "(", "assoc", ")", "relation", "=", "assoc", ".", "prepare", "(", "self", ")", "if", "assoc", ".", "override?", "relation", ".", "(", "assoc", ")", "else", "relation", ".", "preload_assoc", "(", "assoc", ")", "end", "end" ]
Return a graph node prepared by the given association @param [Association] assoc An association object @return [Relation] @api public
[ "Return", "a", "graph", "node", "prepared", "by", "the", "given", "association" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/relation.rb#L302-L310
16,051
rom-rb/rom
core/lib/rom/relation.rb
ROM.Relation.new
def new(dataset, new_opts = EMPTY_HASH) opts = if new_opts.empty? options elsif new_opts.key?(:schema) options.merge(new_opts).reject { |k, _| k == :input_schema || k == :output_schema } else options.merge(new_opts) end self.class.new(dataset, opts) end
ruby
def new(dataset, new_opts = EMPTY_HASH) opts = if new_opts.empty? options elsif new_opts.key?(:schema) options.merge(new_opts).reject { |k, _| k == :input_schema || k == :output_schema } else options.merge(new_opts) end self.class.new(dataset, opts) end
[ "def", "new", "(", "dataset", ",", "new_opts", "=", "EMPTY_HASH", ")", "opts", "=", "if", "new_opts", ".", "empty?", "options", "elsif", "new_opts", ".", "key?", "(", ":schema", ")", "options", ".", "merge", "(", "new_opts", ")", ".", "reject", "{", "|", "k", ",", "_", "|", "k", "==", ":input_schema", "||", "k", "==", ":output_schema", "}", "else", "options", ".", "merge", "(", "new_opts", ")", "end", "self", ".", "class", ".", "new", "(", "dataset", ",", "opts", ")", "end" ]
Return a new relation with provided dataset and additional options Use this method whenever you need to use dataset API to get a new dataset and you want to return a relation back. Typically relation API should be enough though. If you find yourself using this method, it might be worth to consider reporting an issue that some dataset functionality is not available through relation API. @example with a new dataset users.new(users.dataset.some_method) @example with a new dataset and options users.new(users.dataset.some_method, other: 'options') @param [Object] dataset @param [Hash] new_opts Additional options @api public
[ "Return", "a", "new", "relation", "with", "provided", "dataset", "and", "additional", "options" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/relation.rb#L420-L431
16,052
rom-rb/rom
core/lib/rom/relation.rb
ROM.Relation.with
def with(opts) new_options = if opts.key?(:meta) opts.merge(meta: meta.merge(opts[:meta])) else opts end new(dataset, options.merge(new_options)) end
ruby
def with(opts) new_options = if opts.key?(:meta) opts.merge(meta: meta.merge(opts[:meta])) else opts end new(dataset, options.merge(new_options)) end
[ "def", "with", "(", "opts", ")", "new_options", "=", "if", "opts", ".", "key?", "(", ":meta", ")", "opts", ".", "merge", "(", "meta", ":", "meta", ".", "merge", "(", "opts", "[", ":meta", "]", ")", ")", "else", "opts", "end", "new", "(", "dataset", ",", "options", ".", "merge", "(", "new_options", ")", ")", "end" ]
Returns a new instance with the same dataset but new options @example users.with(output_schema: -> tuple { .. }) @param [Hash] opts New options @return [Relation] @api public
[ "Returns", "a", "new", "instance", "with", "the", "same", "dataset", "but", "new", "options" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/relation.rb#L445-L454
16,053
rom-rb/rom
core/lib/rom/relation.rb
ROM.Relation.map_to
def map_to(klass, **opts) with(opts.merge(auto_map: false, auto_struct: true, meta: { model: klass })) end
ruby
def map_to(klass, **opts) with(opts.merge(auto_map: false, auto_struct: true, meta: { model: klass })) end
[ "def", "map_to", "(", "klass", ",", "**", "opts", ")", "with", "(", "opts", ".", "merge", "(", "auto_map", ":", "false", ",", "auto_struct", ":", "true", ",", "meta", ":", "{", "model", ":", "klass", "}", ")", ")", "end" ]
Return a new relation that will map its tuples to instances of the provided class @example users.map_to(MyUserModel) @param [Class] klass Your custom model class @return [Relation] @api public
[ "Return", "a", "new", "relation", "that", "will", "map", "its", "tuples", "to", "instances", "of", "the", "provided", "class" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/relation.rb#L541-L543
16,054
rom-rb/rom
core/lib/rom/schema_plugin.rb
ROM.SchemaPlugin.apply_to
def apply_to(schema, options = EMPTY_HASH) mod.apply(schema, options) if mod.respond_to?(:apply) end
ruby
def apply_to(schema, options = EMPTY_HASH) mod.apply(schema, options) if mod.respond_to?(:apply) end
[ "def", "apply_to", "(", "schema", ",", "options", "=", "EMPTY_HASH", ")", "mod", ".", "apply", "(", "schema", ",", "options", ")", "if", "mod", ".", "respond_to?", "(", ":apply", ")", "end" ]
Apply this plugin to the provided configuration @param [ROM::Schema] schema A schema instance for extension @param [Hash] options Extension options @api private
[ "Apply", "this", "plugin", "to", "the", "provided", "configuration" ]
7245b8cb6dadb5a9413606997a0294dd4a956f19
https://github.com/rom-rb/rom/blob/7245b8cb6dadb5a9413606997a0294dd4a956f19/core/lib/rom/schema_plugin.rb#L16-L18
16,055
libvips/ruby-vips
lib/vips/operation.rb
Vips.Operation.get_construct_args
def get_construct_args args = [] argument_map do |pspec, argument_class, argument_instance| flags = argument_class[:flags] if (flags & ARGUMENT_CONSTRUCT) != 0 # names can include - as punctuation, but we always use _ in # Ruby name = pspec[:name].tr("-", "_") args << [name, flags] end end return args end
ruby
def get_construct_args args = [] argument_map do |pspec, argument_class, argument_instance| flags = argument_class[:flags] if (flags & ARGUMENT_CONSTRUCT) != 0 # names can include - as punctuation, but we always use _ in # Ruby name = pspec[:name].tr("-", "_") args << [name, flags] end end return args end
[ "def", "get_construct_args", "args", "=", "[", "]", "argument_map", "do", "|", "pspec", ",", "argument_class", ",", "argument_instance", "|", "flags", "=", "argument_class", "[", ":flags", "]", "if", "(", "flags", "&", "ARGUMENT_CONSTRUCT", ")", "!=", "0", "# names can include - as punctuation, but we always use _ in", "# Ruby", "name", "=", "pspec", "[", ":name", "]", ".", "tr", "(", "\"-\"", ",", "\"_\"", ")", "args", "<<", "[", "name", ",", "flags", "]", "end", "end", "return", "args", "end" ]
not quick! try to call this infrequently
[ "not", "quick!", "try", "to", "call", "this", "infrequently" ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/operation.rb#L93-L108
16,056
libvips/ruby-vips
lib/vips/operation.rb
Vips.Operation.set
def set name, value, match_image = nil, flags = 0 gtype = get_typeof name if gtype == IMAGE_TYPE value = Operation::imageize match_image, value if (flags & ARGUMENT_MODIFY) != 0 # make sure we have a unique copy value = value.copy.copy_memory end elsif gtype == ARRAY_IMAGE_TYPE value = value.map {|x| Operation::imageize match_image, x} end super name, value end
ruby
def set name, value, match_image = nil, flags = 0 gtype = get_typeof name if gtype == IMAGE_TYPE value = Operation::imageize match_image, value if (flags & ARGUMENT_MODIFY) != 0 # make sure we have a unique copy value = value.copy.copy_memory end elsif gtype == ARRAY_IMAGE_TYPE value = value.map {|x| Operation::imageize match_image, x} end super name, value end
[ "def", "set", "name", ",", "value", ",", "match_image", "=", "nil", ",", "flags", "=", "0", "gtype", "=", "get_typeof", "name", "if", "gtype", "==", "IMAGE_TYPE", "value", "=", "Operation", "::", "imageize", "match_image", ",", "value", "if", "(", "flags", "&", "ARGUMENT_MODIFY", ")", "!=", "0", "# make sure we have a unique copy", "value", "=", "value", ".", "copy", ".", "copy_memory", "end", "elsif", "gtype", "==", "ARRAY_IMAGE_TYPE", "value", "=", "value", ".", "map", "{", "|", "x", "|", "Operation", "::", "imageize", "match_image", ",", "x", "}", "end", "super", "name", ",", "value", "end" ]
set an operation argument, expanding constants and copying images as required
[ "set", "an", "operation", "argument", "expanding", "constants", "and", "copying", "images", "as", "required" ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/operation.rb#L140-L155
16,057
libvips/ruby-vips
lib/vips/image.rb
Vips.Image.call_enum
def call_enum(name, other, enum) if other.is_a?(Vips::Image) Vips::Operation.call name.to_s, [self, other, enum] else Vips::Operation.call name.to_s + "_const", [self, enum, other] end end
ruby
def call_enum(name, other, enum) if other.is_a?(Vips::Image) Vips::Operation.call name.to_s, [self, other, enum] else Vips::Operation.call name.to_s + "_const", [self, enum, other] end end
[ "def", "call_enum", "(", "name", ",", "other", ",", "enum", ")", "if", "other", ".", "is_a?", "(", "Vips", "::", "Image", ")", "Vips", "::", "Operation", ".", "call", "name", ".", "to_s", ",", "[", "self", ",", "other", ",", "enum", "]", "else", "Vips", "::", "Operation", ".", "call", "name", ".", "to_s", "+", "\"_const\"", ",", "[", "self", ",", "enum", ",", "other", "]", "end", "end" ]
handy for expanding enum operations
[ "handy", "for", "expanding", "enum", "operations" ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/image.rb#L142-L148
16,058
libvips/ruby-vips
lib/vips/image.rb
Vips.Image.new_from_image
def new_from_image value pixel = (Vips::Image.black(1, 1) + value).cast(format) image = pixel.embed 0, 0, width, height, extend: :copy image.copy interpretation: interpretation, xres: xres, yres: yres, xoffset: xoffset, yoffset: yoffset end
ruby
def new_from_image value pixel = (Vips::Image.black(1, 1) + value).cast(format) image = pixel.embed 0, 0, width, height, extend: :copy image.copy interpretation: interpretation, xres: xres, yres: yres, xoffset: xoffset, yoffset: yoffset end
[ "def", "new_from_image", "value", "pixel", "=", "(", "Vips", "::", "Image", ".", "black", "(", "1", ",", "1", ")", "+", "value", ")", ".", "cast", "(", "format", ")", "image", "=", "pixel", ".", "embed", "0", ",", "0", ",", "width", ",", "height", ",", "extend", ":", ":copy", "image", ".", "copy", "interpretation", ":", "interpretation", ",", "xres", ":", "xres", ",", "yres", ":", "yres", ",", "xoffset", ":", "xoffset", ",", "yoffset", ":", "yoffset", "end" ]
A new image is created with the same width, height, format, interpretation, resolution and offset as self, but with every pixel set to the specified value. You can pass an array to make a many-band image, or a single value to make a one-band image. @param value [Real, Array<Real>] value to put in each pixel @return [Image] constant image
[ "A", "new", "image", "is", "created", "with", "the", "same", "width", "height", "format", "interpretation", "resolution", "and", "offset", "as", "self", "but", "with", "every", "pixel", "set", "to", "the", "specified", "value", "." ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/image.rb#L385-L390
16,059
libvips/ruby-vips
lib/vips/image.rb
Vips.Image.write_to_memory
def write_to_memory len = Vips::SizeStruct.new ptr = Vips::vips_image_write_to_memory self, len # wrap up as an autopointer ptr = FFI::AutoPointer.new(ptr, GLib::G_FREE) ptr.get_bytes 0, len[:value] end
ruby
def write_to_memory len = Vips::SizeStruct.new ptr = Vips::vips_image_write_to_memory self, len # wrap up as an autopointer ptr = FFI::AutoPointer.new(ptr, GLib::G_FREE) ptr.get_bytes 0, len[:value] end
[ "def", "write_to_memory", "len", "=", "Vips", "::", "SizeStruct", ".", "new", "ptr", "=", "Vips", "::", "vips_image_write_to_memory", "self", ",", "len", "# wrap up as an autopointer", "ptr", "=", "FFI", "::", "AutoPointer", ".", "new", "(", "ptr", ",", "GLib", "::", "G_FREE", ")", "ptr", ".", "get_bytes", "0", ",", "len", "[", ":value", "]", "end" ]
Write this image to a large memory buffer. @return [String] the pixels as a huge binary string
[ "Write", "this", "image", "to", "a", "large", "memory", "buffer", "." ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/image.rb#L480-L488
16,060
libvips/ruby-vips
lib/vips/image.rb
Vips.Image.get_typeof
def get_typeof name # on libvips before 8.5, property types must be searched first, # since vips_image_get_typeof returned built-in enums as int unless Vips::at_least_libvips?(8, 5) gtype = parent_get_typeof name return gtype if gtype != 0 end Vips::vips_image_get_typeof self, name end
ruby
def get_typeof name # on libvips before 8.5, property types must be searched first, # since vips_image_get_typeof returned built-in enums as int unless Vips::at_least_libvips?(8, 5) gtype = parent_get_typeof name return gtype if gtype != 0 end Vips::vips_image_get_typeof self, name end
[ "def", "get_typeof", "name", "# on libvips before 8.5, property types must be searched first,", "# since vips_image_get_typeof returned built-in enums as int", "unless", "Vips", "::", "at_least_libvips?", "(", "8", ",", "5", ")", "gtype", "=", "parent_get_typeof", "name", "return", "gtype", "if", "gtype", "!=", "0", "end", "Vips", "::", "vips_image_get_typeof", "self", ",", "name", "end" ]
Get the `GType` of a metadata field. The result is 0 if no such field exists. @see get @param name [String] Metadata field to fetch @return [Integer] GType
[ "Get", "the", "GType", "of", "a", "metadata", "field", ".", "The", "result", "is", "0", "if", "no", "such", "field", "exists", "." ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/image.rb#L496-L505
16,061
libvips/ruby-vips
lib/vips/image.rb
Vips.Image.get
def get name # with old libvips, we must fetch properties (as opposed to # metadata) via VipsObject unless Vips::at_least_libvips?(8, 5) return super if parent_get_typeof(name) != 0 end gvalue = GObject::GValue.alloc result = Vips::vips_image_get self, name, gvalue raise Vips::Error if result != 0 gvalue.get end
ruby
def get name # with old libvips, we must fetch properties (as opposed to # metadata) via VipsObject unless Vips::at_least_libvips?(8, 5) return super if parent_get_typeof(name) != 0 end gvalue = GObject::GValue.alloc result = Vips::vips_image_get self, name, gvalue raise Vips::Error if result != 0 gvalue.get end
[ "def", "get", "name", "# with old libvips, we must fetch properties (as opposed to", "# metadata) via VipsObject", "unless", "Vips", "::", "at_least_libvips?", "(", "8", ",", "5", ")", "return", "super", "if", "parent_get_typeof", "(", "name", ")", "!=", "0", "end", "gvalue", "=", "GObject", "::", "GValue", ".", "alloc", "result", "=", "Vips", "::", "vips_image_get", "self", ",", "name", ",", "gvalue", "raise", "Vips", "::", "Error", "if", "result", "!=", "0", "gvalue", ".", "get", "end" ]
Get a metadata item from an image. Ruby types are constructed automatically from the `GValue`, if possible. For example, you can read the ICC profile from an image like this: ``` profile = image.get "icc-profile-data" ``` and profile will be an array containing the profile. @param name [String] Metadata field to get @return [Object] Value of field
[ "Get", "a", "metadata", "item", "from", "an", "image", ".", "Ruby", "types", "are", "constructed", "automatically", "from", "the", "GValue", "if", "possible", "." ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/image.rb#L520-L532
16,062
libvips/ruby-vips
lib/vips/image.rb
Vips.Image.get_fields
def get_fields # vips_image_get_fields() was added in libvips 8.5 return [] unless Vips.respond_to? :vips_image_get_fields array = Vips::vips_image_get_fields self names = [] p = array until (q = p.read_pointer).null? names << q.read_string GLib::g_free q p += FFI::Type::POINTER.size end GLib::g_free array names end
ruby
def get_fields # vips_image_get_fields() was added in libvips 8.5 return [] unless Vips.respond_to? :vips_image_get_fields array = Vips::vips_image_get_fields self names = [] p = array until (q = p.read_pointer).null? names << q.read_string GLib::g_free q p += FFI::Type::POINTER.size end GLib::g_free array names end
[ "def", "get_fields", "# vips_image_get_fields() was added in libvips 8.5", "return", "[", "]", "unless", "Vips", ".", "respond_to?", ":vips_image_get_fields", "array", "=", "Vips", "::", "vips_image_get_fields", "self", "names", "=", "[", "]", "p", "=", "array", "until", "(", "q", "=", "p", ".", "read_pointer", ")", ".", "null?", "names", "<<", "q", ".", "read_string", "GLib", "::", "g_free", "q", "p", "+=", "FFI", "::", "Type", "::", "POINTER", ".", "size", "end", "GLib", "::", "g_free", "array", "names", "end" ]
Get the names of all fields on an image. Use this to loop over all image metadata. @return [[String]] array of field names
[ "Get", "the", "names", "of", "all", "fields", "on", "an", "image", ".", "Use", "this", "to", "loop", "over", "all", "image", "metadata", "." ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/image.rb#L538-L554
16,063
libvips/ruby-vips
lib/vips/image.rb
Vips.Image.set_type
def set_type gtype, name, value gvalue = GObject::GValue.alloc gvalue.init gtype gvalue.set value Vips::vips_image_set self, name, gvalue end
ruby
def set_type gtype, name, value gvalue = GObject::GValue.alloc gvalue.init gtype gvalue.set value Vips::vips_image_set self, name, gvalue end
[ "def", "set_type", "gtype", ",", "name", ",", "value", "gvalue", "=", "GObject", "::", "GValue", ".", "alloc", "gvalue", ".", "init", "gtype", "gvalue", ".", "set", "value", "Vips", "::", "vips_image_set", "self", ",", "name", ",", "gvalue", "end" ]
Create a metadata item on an image of the specifed type. Ruby types are automatically transformed into the matching `GType`, if possible. For example, you can use this to set an image's ICC profile: ``` x = y.set_type Vips::BLOB_TYPE, "icc-profile-data", profile ``` where `profile` is an ICC profile held as a binary string object. @see set @param gtype [Integer] GType of item @param name [String] Metadata field to set @param value [Object] Value to set
[ "Create", "a", "metadata", "item", "on", "an", "image", "of", "the", "specifed", "type", ".", "Ruby", "types", "are", "automatically", "transformed", "into", "the", "matching", "GType", "if", "possible", "." ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/image.rb#L571-L576
16,064
libvips/ruby-vips
lib/vips/image.rb
Vips.Image.draw_point
def draw_point ink, left, top, opts = {} draw_rect ink, left, top, 1, 1, opts end
ruby
def draw_point ink, left, top, opts = {} draw_rect ink, left, top, 1, 1, opts end
[ "def", "draw_point", "ink", ",", "left", ",", "top", ",", "opts", "=", "{", "}", "draw_rect", "ink", ",", "left", ",", "top", ",", "1", ",", "1", ",", "opts", "end" ]
Draw a point on an image. See {Image#draw_rect}. @return [Image] modified image
[ "Draw", "a", "point", "on", "an", "image", "." ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/image.rb#L756-L758
16,065
libvips/ruby-vips
lib/vips/image.rb
Vips.Image.-
def - other other.is_a?(Vips::Image) ? subtract(other) : linear(1, Image::smap(other) {|x| x * -1}) end
ruby
def - other other.is_a?(Vips::Image) ? subtract(other) : linear(1, Image::smap(other) {|x| x * -1}) end
[ "def", "-", "other", "other", ".", "is_a?", "(", "Vips", "::", "Image", ")", "?", "subtract", "(", "other", ")", ":", "linear", "(", "1", ",", "Image", "::", "smap", "(", "other", ")", "{", "|", "x", "|", "x", "*", "-", "1", "}", ")", "end" ]
Subtract an image, constant or array. @param other [Image, Real, Array<Real>] Thing to subtract from self @return [Image] result of subtraction
[ "Subtract", "an", "image", "constant", "or", "array", "." ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/image.rb#L773-L776
16,066
libvips/ruby-vips
lib/vips/image.rb
Vips.Image./
def / other other.is_a?(Vips::Image) ? divide(other) : linear(Image::smap(other) {|x| 1.0 / x}, 0) end
ruby
def / other other.is_a?(Vips::Image) ? divide(other) : linear(Image::smap(other) {|x| 1.0 / x}, 0) end
[ "def", "/", "other", "other", ".", "is_a?", "(", "Vips", "::", "Image", ")", "?", "divide", "(", "other", ")", ":", "linear", "(", "Image", "::", "smap", "(", "other", ")", "{", "|", "x", "|", "1.0", "/", "x", "}", ",", "0", ")", "end" ]
Divide an image, constant or array. @param other [Image, Real, Array<Real>] Thing to divide self by @return [Image] result of division
[ "Divide", "an", "image", "constant", "or", "array", "." ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/image.rb#L791-L794
16,067
libvips/ruby-vips
lib/vips/image.rb
Vips.Image.[]
def [] index if index.is_a? Range n = index.size extract_band index.begin, n: n elsif index.is_a? Numeric extract_band index else raise Vips::Error, "[] index is not range or numeric." end end
ruby
def [] index if index.is_a? Range n = index.size extract_band index.begin, n: n elsif index.is_a? Numeric extract_band index else raise Vips::Error, "[] index is not range or numeric." end end
[ "def", "[]", "index", "if", "index", ".", "is_a?", "Range", "n", "=", "index", ".", "size", "extract_band", "index", ".", "begin", ",", "n", ":", "n", "elsif", "index", ".", "is_a?", "Numeric", "extract_band", "index", "else", "raise", "Vips", "::", "Error", ",", "\"[] index is not range or numeric.\"", "end", "end" ]
Fetch bands using a number or a range @param index [Numeric, Range] extract these band(s) @return [Image] extracted band(s)
[ "Fetch", "bands", "using", "a", "number", "or", "a", "range" ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/image.rb#L943-L952
16,068
libvips/ruby-vips
lib/vips/image.rb
Vips.Image.to_a
def to_a # we render the image to a big string, then unpack # as a Ruby array of the correct type memory = write_to_memory # make the template for unpack template = { :char => 'c', :uchar => 'C', :short => 's_', :ushort => 'S_', :int => 'i_', :uint => 'I_', :float => 'f', :double => 'd', :complex => 'f', :dpcomplex => 'd' }[format] + '*' # and unpack into something like [1, 2, 3, 4 ..] array = memory.unpack(template) # gather band elements together pixel_array = array.each_slice(bands).to_a # build rows row_array = pixel_array.each_slice(width).to_a return row_array end
ruby
def to_a # we render the image to a big string, then unpack # as a Ruby array of the correct type memory = write_to_memory # make the template for unpack template = { :char => 'c', :uchar => 'C', :short => 's_', :ushort => 'S_', :int => 'i_', :uint => 'I_', :float => 'f', :double => 'd', :complex => 'f', :dpcomplex => 'd' }[format] + '*' # and unpack into something like [1, 2, 3, 4 ..] array = memory.unpack(template) # gather band elements together pixel_array = array.each_slice(bands).to_a # build rows row_array = pixel_array.each_slice(width).to_a return row_array end
[ "def", "to_a", "# we render the image to a big string, then unpack", "# as a Ruby array of the correct type", "memory", "=", "write_to_memory", "# make the template for unpack", "template", "=", "{", ":char", "=>", "'c'", ",", ":uchar", "=>", "'C'", ",", ":short", "=>", "'s_'", ",", ":ushort", "=>", "'S_'", ",", ":int", "=>", "'i_'", ",", ":uint", "=>", "'I_'", ",", ":float", "=>", "'f'", ",", ":double", "=>", "'d'", ",", ":complex", "=>", "'f'", ",", ":dpcomplex", "=>", "'d'", "}", "[", "format", "]", "+", "'*'", "# and unpack into something like [1, 2, 3, 4 ..]", "array", "=", "memory", ".", "unpack", "(", "template", ")", "# gather band elements together", "pixel_array", "=", "array", ".", "each_slice", "(", "bands", ")", ".", "to_a", "# build rows", "row_array", "=", "pixel_array", ".", "each_slice", "(", "width", ")", ".", "to_a", "return", "row_array", "end" ]
Convert to an Array. This will be slow for large images. @return [Array] array of Fixnum
[ "Convert", "to", "an", "Array", ".", "This", "will", "be", "slow", "for", "large", "images", "." ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/image.rb#L957-L986
16,069
libvips/ruby-vips
lib/vips/image.rb
Vips.Image.bandjoin
def bandjoin other unless other.is_a? Array other = [other] end # if other is just Numeric, we can use bandjoin_const not_all_real = !other.all?{|x| x.is_a? Numeric} if not_all_real Vips::Image.bandjoin([self] + other) else bandjoin_const other end end
ruby
def bandjoin other unless other.is_a? Array other = [other] end # if other is just Numeric, we can use bandjoin_const not_all_real = !other.all?{|x| x.is_a? Numeric} if not_all_real Vips::Image.bandjoin([self] + other) else bandjoin_const other end end
[ "def", "bandjoin", "other", "unless", "other", ".", "is_a?", "Array", "other", "=", "[", "other", "]", "end", "# if other is just Numeric, we can use bandjoin_const", "not_all_real", "=", "!", "other", ".", "all?", "{", "|", "x", "|", "x", ".", "is_a?", "Numeric", "}", "if", "not_all_real", "Vips", "::", "Image", ".", "bandjoin", "(", "[", "self", "]", "+", "other", ")", "else", "bandjoin_const", "other", "end", "end" ]
Join a set of images bandwise. @param other [Image, Array<Image>, Real, Array<Real>] bands to append @return [Image] many band image
[ "Join", "a", "set", "of", "images", "bandwise", "." ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/image.rb#L1041-L1054
16,070
libvips/ruby-vips
lib/vips/image.rb
Vips.Image.composite
def composite overlay, mode, opts = {} unless overlay.is_a? Array overlay = [overlay] end unless mode.is_a? Array mode = [mode] end mode = mode.map do |x| GObject::GValue.from_nick Vips::BLEND_MODE_TYPE, x end Vips::Image.composite([self] + overlay, mode, opts) end
ruby
def composite overlay, mode, opts = {} unless overlay.is_a? Array overlay = [overlay] end unless mode.is_a? Array mode = [mode] end mode = mode.map do |x| GObject::GValue.from_nick Vips::BLEND_MODE_TYPE, x end Vips::Image.composite([self] + overlay, mode, opts) end
[ "def", "composite", "overlay", ",", "mode", ",", "opts", "=", "{", "}", "unless", "overlay", ".", "is_a?", "Array", "overlay", "=", "[", "overlay", "]", "end", "unless", "mode", ".", "is_a?", "Array", "mode", "=", "[", "mode", "]", "end", "mode", "=", "mode", ".", "map", "do", "|", "x", "|", "GObject", "::", "GValue", ".", "from_nick", "Vips", "::", "BLEND_MODE_TYPE", ",", "x", "end", "Vips", "::", "Image", ".", "composite", "(", "[", "self", "]", "+", "overlay", ",", "mode", ",", "opts", ")", "end" ]
Composite a set of images with a set of blend modes. @param overlay [Image, Array<Image>] images to composite @param mode [BlendMode, Array<BlendMode>] blend modes to use @param opts [Hash] Set of options @option opts [Vips::Interpretation] :compositing_space Composite images in this colour space @option opts [Boolean] :premultiplied Images have premultiplied alpha @return [Image] blended image
[ "Composite", "a", "set", "of", "images", "with", "a", "set", "of", "blend", "modes", "." ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/image.rb#L1064-L1077
16,071
libvips/ruby-vips
lib/vips/image.rb
Vips.Image.maxpos
def maxpos v, opts = max x: true, y: true x = opts['x'] y = opts['y'] return v, x, y end
ruby
def maxpos v, opts = max x: true, y: true x = opts['x'] y = opts['y'] return v, x, y end
[ "def", "maxpos", "v", ",", "opts", "=", "max", "x", ":", "true", ",", "y", ":", "true", "x", "=", "opts", "[", "'x'", "]", "y", "=", "opts", "[", "'y'", "]", "return", "v", ",", "x", ",", "y", "end" ]
Return the coordinates of the image maximum. @return [Real, Real, Real] maximum value, x coordinate of maximum, y coordinate of maximum
[ "Return", "the", "coordinates", "of", "the", "image", "maximum", "." ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/image.rb#L1083-L1088
16,072
libvips/ruby-vips
lib/vips/image.rb
Vips.Image.minpos
def minpos v, opts = min x: true, y: true x = opts['x'] y = opts['y'] return v, x, y end
ruby
def minpos v, opts = min x: true, y: true x = opts['x'] y = opts['y'] return v, x, y end
[ "def", "minpos", "v", ",", "opts", "=", "min", "x", ":", "true", ",", "y", ":", "true", "x", "=", "opts", "[", "'x'", "]", "y", "=", "opts", "[", "'y'", "]", "return", "v", ",", "x", ",", "y", "end" ]
Return the coordinates of the image minimum. @return [Real, Real, Real] minimum value, x coordinate of minimum, y coordinate of minimum
[ "Return", "the", "coordinates", "of", "the", "image", "minimum", "." ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/image.rb#L1094-L1099
16,073
libvips/ruby-vips
lib/vips/object.rb
Vips.Object.get_pspec
def get_pspec name pspec = GObject::GParamSpecPtr.new argument_class = Vips::ArgumentClassPtr.new argument_instance = Vips::ArgumentInstancePtr.new result = Vips::vips_object_get_argument self, name, pspec, argument_class, argument_instance return nil if result != 0 pspec end
ruby
def get_pspec name pspec = GObject::GParamSpecPtr.new argument_class = Vips::ArgumentClassPtr.new argument_instance = Vips::ArgumentInstancePtr.new result = Vips::vips_object_get_argument self, name, pspec, argument_class, argument_instance return nil if result != 0 pspec end
[ "def", "get_pspec", "name", "pspec", "=", "GObject", "::", "GParamSpecPtr", ".", "new", "argument_class", "=", "Vips", "::", "ArgumentClassPtr", ".", "new", "argument_instance", "=", "Vips", "::", "ArgumentInstancePtr", ".", "new", "result", "=", "Vips", "::", "vips_object_get_argument", "self", ",", "name", ",", "pspec", ",", "argument_class", ",", "argument_instance", "return", "nil", "if", "result", "!=", "0", "pspec", "end" ]
return a pspec, or nil ... nil wil leave a message in the error log which you must clear
[ "return", "a", "pspec", "or", "nil", "...", "nil", "wil", "leave", "a", "message", "in", "the", "error", "log", "which", "you", "must", "clear" ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/object.rb#L120-L130
16,074
libvips/ruby-vips
lib/vips/object.rb
Vips.Object.get_typeof_error
def get_typeof_error name pspec = get_pspec name raise Vips::Error unless pspec pspec[:value][:value_type] end
ruby
def get_typeof_error name pspec = get_pspec name raise Vips::Error unless pspec pspec[:value][:value_type] end
[ "def", "get_typeof_error", "name", "pspec", "=", "get_pspec", "name", "raise", "Vips", "::", "Error", "unless", "pspec", "pspec", "[", ":value", "]", "[", ":value_type", "]", "end" ]
return a gtype, raise an error on not found
[ "return", "a", "gtype", "raise", "an", "error", "on", "not", "found" ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/object.rb#L133-L138
16,075
libvips/ruby-vips
lib/vips/gvalue.rb
GObject.GValue.set
def set value # GLib::logger.debug("GObject::GValue.set") { # "value = #{value.inspect[0..50]}" # } gtype = self[:gtype] fundamental = ::GObject::g_type_fundamental gtype case gtype when GBOOL_TYPE ::GObject::g_value_set_boolean self, (value ? 1 : 0) when GINT_TYPE ::GObject::g_value_set_int self, value when GUINT64_TYPE ::GObject::g_value_set_uint64 self, value when GDOUBLE_TYPE ::GObject::g_value_set_double self, value when GSTR_TYPE ::GObject::g_value_set_string self, value when Vips::REFSTR_TYPE ::Vips::vips_value_set_ref_string self, value when Vips::ARRAY_INT_TYPE value = [value] unless value.is_a? Array Vips::vips_value_set_array_int self, nil, value.length ptr = Vips::vips_value_get_array_int self, nil ptr.write_array_of_int32 value when Vips::ARRAY_DOUBLE_TYPE value = [value] unless value.is_a? Array # this will allocate an array in the gvalue Vips::vips_value_set_array_double self, nil, value.length # pull the array out and fill it ptr = Vips::vips_value_get_array_double self, nil ptr.write_array_of_double value when Vips::ARRAY_IMAGE_TYPE value = [value] unless value.is_a? Array Vips::vips_value_set_array_image self, value.length ptr = Vips::vips_value_get_array_image self, nil ptr.write_array_of_pointer value # the gvalue needs a ref on each of the images value.each {|image| ::GObject::g_object_ref image} when Vips::BLOB_TYPE len = value.bytesize ptr = GLib::g_malloc len Vips::vips_value_set_blob self, GLib::G_FREE, ptr, len ptr.write_bytes value else case fundamental when GFLAGS_TYPE ::GObject::g_value_set_flags self, value when GENUM_TYPE enum_value = GValue.from_nick(self[:gtype], value) ::GObject::g_value_set_enum self, enum_value when GOBJECT_TYPE ::GObject::g_value_set_object self, value else raise Vips::Error, "unimplemented gtype for set: " + "#{::GObject::g_type_name gtype} (#{gtype})" end end end
ruby
def set value # GLib::logger.debug("GObject::GValue.set") { # "value = #{value.inspect[0..50]}" # } gtype = self[:gtype] fundamental = ::GObject::g_type_fundamental gtype case gtype when GBOOL_TYPE ::GObject::g_value_set_boolean self, (value ? 1 : 0) when GINT_TYPE ::GObject::g_value_set_int self, value when GUINT64_TYPE ::GObject::g_value_set_uint64 self, value when GDOUBLE_TYPE ::GObject::g_value_set_double self, value when GSTR_TYPE ::GObject::g_value_set_string self, value when Vips::REFSTR_TYPE ::Vips::vips_value_set_ref_string self, value when Vips::ARRAY_INT_TYPE value = [value] unless value.is_a? Array Vips::vips_value_set_array_int self, nil, value.length ptr = Vips::vips_value_get_array_int self, nil ptr.write_array_of_int32 value when Vips::ARRAY_DOUBLE_TYPE value = [value] unless value.is_a? Array # this will allocate an array in the gvalue Vips::vips_value_set_array_double self, nil, value.length # pull the array out and fill it ptr = Vips::vips_value_get_array_double self, nil ptr.write_array_of_double value when Vips::ARRAY_IMAGE_TYPE value = [value] unless value.is_a? Array Vips::vips_value_set_array_image self, value.length ptr = Vips::vips_value_get_array_image self, nil ptr.write_array_of_pointer value # the gvalue needs a ref on each of the images value.each {|image| ::GObject::g_object_ref image} when Vips::BLOB_TYPE len = value.bytesize ptr = GLib::g_malloc len Vips::vips_value_set_blob self, GLib::G_FREE, ptr, len ptr.write_bytes value else case fundamental when GFLAGS_TYPE ::GObject::g_value_set_flags self, value when GENUM_TYPE enum_value = GValue.from_nick(self[:gtype], value) ::GObject::g_value_set_enum self, enum_value when GOBJECT_TYPE ::GObject::g_value_set_object self, value else raise Vips::Error, "unimplemented gtype for set: " + "#{::GObject::g_type_name gtype} (#{gtype})" end end end
[ "def", "set", "value", "# GLib::logger.debug(\"GObject::GValue.set\") {", "# \"value = #{value.inspect[0..50]}\"", "# }", "gtype", "=", "self", "[", ":gtype", "]", "fundamental", "=", "::", "GObject", "::", "g_type_fundamental", "gtype", "case", "gtype", "when", "GBOOL_TYPE", "::", "GObject", "::", "g_value_set_boolean", "self", ",", "(", "value", "?", "1", ":", "0", ")", "when", "GINT_TYPE", "::", "GObject", "::", "g_value_set_int", "self", ",", "value", "when", "GUINT64_TYPE", "::", "GObject", "::", "g_value_set_uint64", "self", ",", "value", "when", "GDOUBLE_TYPE", "::", "GObject", "::", "g_value_set_double", "self", ",", "value", "when", "GSTR_TYPE", "::", "GObject", "::", "g_value_set_string", "self", ",", "value", "when", "Vips", "::", "REFSTR_TYPE", "::", "Vips", "::", "vips_value_set_ref_string", "self", ",", "value", "when", "Vips", "::", "ARRAY_INT_TYPE", "value", "=", "[", "value", "]", "unless", "value", ".", "is_a?", "Array", "Vips", "::", "vips_value_set_array_int", "self", ",", "nil", ",", "value", ".", "length", "ptr", "=", "Vips", "::", "vips_value_get_array_int", "self", ",", "nil", "ptr", ".", "write_array_of_int32", "value", "when", "Vips", "::", "ARRAY_DOUBLE_TYPE", "value", "=", "[", "value", "]", "unless", "value", ".", "is_a?", "Array", "# this will allocate an array in the gvalue", "Vips", "::", "vips_value_set_array_double", "self", ",", "nil", ",", "value", ".", "length", "# pull the array out and fill it", "ptr", "=", "Vips", "::", "vips_value_get_array_double", "self", ",", "nil", "ptr", ".", "write_array_of_double", "value", "when", "Vips", "::", "ARRAY_IMAGE_TYPE", "value", "=", "[", "value", "]", "unless", "value", ".", "is_a?", "Array", "Vips", "::", "vips_value_set_array_image", "self", ",", "value", ".", "length", "ptr", "=", "Vips", "::", "vips_value_get_array_image", "self", ",", "nil", "ptr", ".", "write_array_of_pointer", "value", "# the gvalue needs a ref on each of the images", "value", ".", "each", "{", "|", "image", "|", "::", "GObject", "::", "g_object_ref", "image", "}", "when", "Vips", "::", "BLOB_TYPE", "len", "=", "value", ".", "bytesize", "ptr", "=", "GLib", "::", "g_malloc", "len", "Vips", "::", "vips_value_set_blob", "self", ",", "GLib", "::", "G_FREE", ",", "ptr", ",", "len", "ptr", ".", "write_bytes", "value", "else", "case", "fundamental", "when", "GFLAGS_TYPE", "::", "GObject", "::", "g_value_set_flags", "self", ",", "value", "when", "GENUM_TYPE", "enum_value", "=", "GValue", ".", "from_nick", "(", "self", "[", ":gtype", "]", ",", "value", ")", "::", "GObject", "::", "g_value_set_enum", "self", ",", "enum_value", "when", "GOBJECT_TYPE", "::", "GObject", "::", "g_value_set_object", "self", ",", "value", "else", "raise", "Vips", "::", "Error", ",", "\"unimplemented gtype for set: \"", "+", "\"#{::GObject::g_type_name gtype} (#{gtype})\"", "end", "end", "end" ]
Set the value of a GValue. The value is converted to the type of the GValue, if possible. @param value [Any] The value to set
[ "Set", "the", "value", "of", "a", "GValue", ".", "The", "value", "is", "converted", "to", "the", "type", "of", "the", "GValue", "if", "possible", "." ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/gvalue.rb#L84-L163
16,076
libvips/ruby-vips
lib/vips/gvalue.rb
GObject.GValue.get
def get gtype = self[:gtype] fundamental = ::GObject::g_type_fundamental gtype result = nil case gtype when GBOOL_TYPE result = ::GObject::g_value_get_boolean(self) != 0 ? true : false when GINT_TYPE result = ::GObject::g_value_get_int self when GUINT64_TYPE result = ::GObject::g_value_get_uint64 self when GDOUBLE_TYPE result = ::GObject::g_value_get_double self when GSTR_TYPE result = ::GObject::g_value_get_string self when Vips::REFSTR_TYPE len = Vips::SizeStruct.new result = ::Vips::vips_value_get_ref_string self, len when Vips::ARRAY_INT_TYPE len = Vips::IntStruct.new array = Vips::vips_value_get_array_int self, len result = array.get_array_of_int32 0, len[:value] when Vips::ARRAY_DOUBLE_TYPE len = Vips::IntStruct.new array = Vips::vips_value_get_array_double self, len result = array.get_array_of_double 0, len[:value] when Vips::ARRAY_IMAGE_TYPE len = Vips::IntStruct.new array = Vips::vips_value_get_array_image self, len result = array.get_array_of_pointer 0, len[:value] result.map! do |pointer| ::GObject::g_object_ref pointer Vips::Image.new pointer end when Vips::BLOB_TYPE len = Vips::SizeStruct.new array = Vips::vips_value_get_blob self, len result = array.get_bytes 0, len[:value] else case fundamental when GFLAGS_TYPE result = ::GObject::g_value_get_flags self when GENUM_TYPE enum_value = ::GObject::g_value_get_enum(self) result = GValue.to_nick self[:gtype], enum_value when GOBJECT_TYPE obj = ::GObject::g_value_get_object self # g_value_get_object() does not add a ref ... we need to add # one to match the unref in gobject release ::GObject::g_object_ref obj result = Vips::Image.new obj else raise Vips::Error, "unimplemented gtype for get: " + "#{::GObject::g_type_name gtype} (#{gtype})" end end # GLib::logger.debug("GObject::GValue.get") { # "result = #{result.inspect[0..50]}" # } return result end
ruby
def get gtype = self[:gtype] fundamental = ::GObject::g_type_fundamental gtype result = nil case gtype when GBOOL_TYPE result = ::GObject::g_value_get_boolean(self) != 0 ? true : false when GINT_TYPE result = ::GObject::g_value_get_int self when GUINT64_TYPE result = ::GObject::g_value_get_uint64 self when GDOUBLE_TYPE result = ::GObject::g_value_get_double self when GSTR_TYPE result = ::GObject::g_value_get_string self when Vips::REFSTR_TYPE len = Vips::SizeStruct.new result = ::Vips::vips_value_get_ref_string self, len when Vips::ARRAY_INT_TYPE len = Vips::IntStruct.new array = Vips::vips_value_get_array_int self, len result = array.get_array_of_int32 0, len[:value] when Vips::ARRAY_DOUBLE_TYPE len = Vips::IntStruct.new array = Vips::vips_value_get_array_double self, len result = array.get_array_of_double 0, len[:value] when Vips::ARRAY_IMAGE_TYPE len = Vips::IntStruct.new array = Vips::vips_value_get_array_image self, len result = array.get_array_of_pointer 0, len[:value] result.map! do |pointer| ::GObject::g_object_ref pointer Vips::Image.new pointer end when Vips::BLOB_TYPE len = Vips::SizeStruct.new array = Vips::vips_value_get_blob self, len result = array.get_bytes 0, len[:value] else case fundamental when GFLAGS_TYPE result = ::GObject::g_value_get_flags self when GENUM_TYPE enum_value = ::GObject::g_value_get_enum(self) result = GValue.to_nick self[:gtype], enum_value when GOBJECT_TYPE obj = ::GObject::g_value_get_object self # g_value_get_object() does not add a ref ... we need to add # one to match the unref in gobject release ::GObject::g_object_ref obj result = Vips::Image.new obj else raise Vips::Error, "unimplemented gtype for get: " + "#{::GObject::g_type_name gtype} (#{gtype})" end end # GLib::logger.debug("GObject::GValue.get") { # "result = #{result.inspect[0..50]}" # } return result end
[ "def", "get", "gtype", "=", "self", "[", ":gtype", "]", "fundamental", "=", "::", "GObject", "::", "g_type_fundamental", "gtype", "result", "=", "nil", "case", "gtype", "when", "GBOOL_TYPE", "result", "=", "::", "GObject", "::", "g_value_get_boolean", "(", "self", ")", "!=", "0", "?", "true", ":", "false", "when", "GINT_TYPE", "result", "=", "::", "GObject", "::", "g_value_get_int", "self", "when", "GUINT64_TYPE", "result", "=", "::", "GObject", "::", "g_value_get_uint64", "self", "when", "GDOUBLE_TYPE", "result", "=", "::", "GObject", "::", "g_value_get_double", "self", "when", "GSTR_TYPE", "result", "=", "::", "GObject", "::", "g_value_get_string", "self", "when", "Vips", "::", "REFSTR_TYPE", "len", "=", "Vips", "::", "SizeStruct", ".", "new", "result", "=", "::", "Vips", "::", "vips_value_get_ref_string", "self", ",", "len", "when", "Vips", "::", "ARRAY_INT_TYPE", "len", "=", "Vips", "::", "IntStruct", ".", "new", "array", "=", "Vips", "::", "vips_value_get_array_int", "self", ",", "len", "result", "=", "array", ".", "get_array_of_int32", "0", ",", "len", "[", ":value", "]", "when", "Vips", "::", "ARRAY_DOUBLE_TYPE", "len", "=", "Vips", "::", "IntStruct", ".", "new", "array", "=", "Vips", "::", "vips_value_get_array_double", "self", ",", "len", "result", "=", "array", ".", "get_array_of_double", "0", ",", "len", "[", ":value", "]", "when", "Vips", "::", "ARRAY_IMAGE_TYPE", "len", "=", "Vips", "::", "IntStruct", ".", "new", "array", "=", "Vips", "::", "vips_value_get_array_image", "self", ",", "len", "result", "=", "array", ".", "get_array_of_pointer", "0", ",", "len", "[", ":value", "]", "result", ".", "map!", "do", "|", "pointer", "|", "::", "GObject", "::", "g_object_ref", "pointer", "Vips", "::", "Image", ".", "new", "pointer", "end", "when", "Vips", "::", "BLOB_TYPE", "len", "=", "Vips", "::", "SizeStruct", ".", "new", "array", "=", "Vips", "::", "vips_value_get_blob", "self", ",", "len", "result", "=", "array", ".", "get_bytes", "0", ",", "len", "[", ":value", "]", "else", "case", "fundamental", "when", "GFLAGS_TYPE", "result", "=", "::", "GObject", "::", "g_value_get_flags", "self", "when", "GENUM_TYPE", "enum_value", "=", "::", "GObject", "::", "g_value_get_enum", "(", "self", ")", "result", "=", "GValue", ".", "to_nick", "self", "[", ":gtype", "]", ",", "enum_value", "when", "GOBJECT_TYPE", "obj", "=", "::", "GObject", "::", "g_value_get_object", "self", "# g_value_get_object() does not add a ref ... we need to add", "# one to match the unref in gobject release", "::", "GObject", "::", "g_object_ref", "obj", "result", "=", "Vips", "::", "Image", ".", "new", "obj", "else", "raise", "Vips", "::", "Error", ",", "\"unimplemented gtype for get: \"", "+", "\"#{::GObject::g_type_name gtype} (#{gtype})\"", "end", "end", "# GLib::logger.debug(\"GObject::GValue.get\") {", "# \"result = #{result.inspect[0..50]}\"", "# }", "return", "result", "end" ]
Get the value of a GValue. The value is converted to a Ruby type in the obvious way. @return [Any] the value held by the GValue
[ "Get", "the", "value", "of", "a", "GValue", ".", "The", "value", "is", "converted", "to", "a", "Ruby", "type", "in", "the", "obvious", "way", "." ]
8f14b1afda91e1078d7a5e6afe94098fef2f2da1
https://github.com/libvips/ruby-vips/blob/8f14b1afda91e1078d7a5e6afe94098fef2f2da1/lib/vips/gvalue.rb#L169-L247
16,077
pcreux/csv-importer
lib/csv_importer/runner.rb
CSVImporter.Runner.call
def call if rows.empty? report.done! return report end report.in_progress! persist_rows! report.done! report rescue ImportAborted report.aborted! report end
ruby
def call if rows.empty? report.done! return report end report.in_progress! persist_rows! report.done! report rescue ImportAborted report.aborted! report end
[ "def", "call", "if", "rows", ".", "empty?", "report", ".", "done!", "return", "report", "end", "report", ".", "in_progress!", "persist_rows!", "report", ".", "done!", "report", "rescue", "ImportAborted", "report", ".", "aborted!", "report", "end" ]
Persist the rows' model and return a `Report`
[ "Persist", "the", "rows", "model", "and", "return", "a", "Report" ]
942070b4b22eed0b36989b98fe4ebe9104b9f665
https://github.com/pcreux/csv-importer/blob/942070b4b22eed0b36989b98fe4ebe9104b9f665/lib/csv_importer/runner.rb#L21-L36
16,078
pcreux/csv-importer
lib/csv_importer/csv_reader.rb
CSVImporter.CSVReader.sanitize_cells
def sanitize_cells(rows) rows.map do |cells| cells.map do |cell| cell ? cell.strip : "" end end end
ruby
def sanitize_cells(rows) rows.map do |cells| cells.map do |cell| cell ? cell.strip : "" end end end
[ "def", "sanitize_cells", "(", "rows", ")", "rows", ".", "map", "do", "|", "cells", "|", "cells", ".", "map", "do", "|", "cell", "|", "cell", "?", "cell", ".", "strip", ":", "\"\"", "end", "end", "end" ]
Remove trailing white spaces and ensure we always return a string
[ "Remove", "trailing", "white", "spaces", "and", "ensure", "we", "always", "return", "a", "string" ]
942070b4b22eed0b36989b98fe4ebe9104b9f665
https://github.com/pcreux/csv-importer/blob/942070b4b22eed0b36989b98fe4ebe9104b9f665/lib/csv_importer/csv_reader.rb#L60-L66
16,079
pcreux/csv-importer
lib/csv_importer/row.rb
CSVImporter.Row.model
def model @model ||= begin model = find_or_build_model set_attributes(model) after_build_blocks.each { |block| instance_exec(model, &block) } model end end
ruby
def model @model ||= begin model = find_or_build_model set_attributes(model) after_build_blocks.each { |block| instance_exec(model, &block) } model end end
[ "def", "model", "@model", "||=", "begin", "model", "=", "find_or_build_model", "set_attributes", "(", "model", ")", "after_build_blocks", ".", "each", "{", "|", "block", "|", "instance_exec", "(", "model", ",", "block", ")", "}", "model", "end", "end" ]
The model to be persisted
[ "The", "model", "to", "be", "persisted" ]
942070b4b22eed0b36989b98fe4ebe9104b9f665
https://github.com/pcreux/csv-importer/blob/942070b4b22eed0b36989b98fe4ebe9104b9f665/lib/csv_importer/row.rb#L18-L27
16,080
pcreux/csv-importer
lib/csv_importer/row.rb
CSVImporter.Row.set_attribute
def set_attribute(model, column, csv_value) column_definition = column.definition if column_definition.to && column_definition.to.is_a?(Proc) to_proc = column_definition.to case to_proc.arity when 1 # to: ->(email) { email.downcase } model.public_send("#{column_definition.name}=", to_proc.call(csv_value)) when 2 # to: ->(published, post) { post.published_at = Time.now if published == "true" } to_proc.call(csv_value, model) when 3 # to: ->(field_value, post, column) { post.hash_field[column.name] = field_value } to_proc.call(csv_value, model, column) else raise ArgumentError, "`to` proc can only have 1, 2 or 3 arguments" end else attribute = column_definition.attribute model.public_send("#{attribute}=", csv_value) end model end
ruby
def set_attribute(model, column, csv_value) column_definition = column.definition if column_definition.to && column_definition.to.is_a?(Proc) to_proc = column_definition.to case to_proc.arity when 1 # to: ->(email) { email.downcase } model.public_send("#{column_definition.name}=", to_proc.call(csv_value)) when 2 # to: ->(published, post) { post.published_at = Time.now if published == "true" } to_proc.call(csv_value, model) when 3 # to: ->(field_value, post, column) { post.hash_field[column.name] = field_value } to_proc.call(csv_value, model, column) else raise ArgumentError, "`to` proc can only have 1, 2 or 3 arguments" end else attribute = column_definition.attribute model.public_send("#{attribute}=", csv_value) end model end
[ "def", "set_attribute", "(", "model", ",", "column", ",", "csv_value", ")", "column_definition", "=", "column", ".", "definition", "if", "column_definition", ".", "to", "&&", "column_definition", ".", "to", ".", "is_a?", "(", "Proc", ")", "to_proc", "=", "column_definition", ".", "to", "case", "to_proc", ".", "arity", "when", "1", "# to: ->(email) { email.downcase }", "model", ".", "public_send", "(", "\"#{column_definition.name}=\"", ",", "to_proc", ".", "call", "(", "csv_value", ")", ")", "when", "2", "# to: ->(published, post) { post.published_at = Time.now if published == \"true\" }", "to_proc", ".", "call", "(", "csv_value", ",", "model", ")", "when", "3", "# to: ->(field_value, post, column) { post.hash_field[column.name] = field_value }", "to_proc", ".", "call", "(", "csv_value", ",", "model", ",", "column", ")", "else", "raise", "ArgumentError", ",", "\"`to` proc can only have 1, 2 or 3 arguments\"", "end", "else", "attribute", "=", "column_definition", ".", "attribute", "model", ".", "public_send", "(", "\"#{attribute}=\"", ",", "csv_value", ")", "end", "model", "end" ]
Set the attribute using the column_definition and the csv_value
[ "Set", "the", "attribute", "using", "the", "column_definition", "and", "the", "csv_value" ]
942070b4b22eed0b36989b98fe4ebe9104b9f665
https://github.com/pcreux/csv-importer/blob/942070b4b22eed0b36989b98fe4ebe9104b9f665/lib/csv_importer/row.rb#L53-L74
16,081
pcreux/csv-importer
lib/csv_importer/row.rb
CSVImporter.Row.errors
def errors Hash[ model.errors.map do |attribute, errors| if column_name = header.column_name_for_model_attribute(attribute) [column_name, errors] else [attribute, errors] end end ] end
ruby
def errors Hash[ model.errors.map do |attribute, errors| if column_name = header.column_name_for_model_attribute(attribute) [column_name, errors] else [attribute, errors] end end ] end
[ "def", "errors", "Hash", "[", "model", ".", "errors", ".", "map", "do", "|", "attribute", ",", "errors", "|", "if", "column_name", "=", "header", ".", "column_name_for_model_attribute", "(", "attribute", ")", "[", "column_name", ",", "errors", "]", "else", "[", "attribute", ",", "errors", "]", "end", "end", "]", "end" ]
Error from the model mapped back to the CSV header if we can
[ "Error", "from", "the", "model", "mapped", "back", "to", "the", "CSV", "header", "if", "we", "can" ]
942070b4b22eed0b36989b98fe4ebe9104b9f665
https://github.com/pcreux/csv-importer/blob/942070b4b22eed0b36989b98fe4ebe9104b9f665/lib/csv_importer/row.rb#L77-L87
16,082
pcreux/csv-importer
lib/csv_importer/column_definition.rb
CSVImporter.ColumnDefinition.match?
def match?(column_name, search_query=(as || name)) return false if column_name.nil? downcased_column_name = column_name.downcase underscored_column_name = downcased_column_name.gsub(/\s+/, '_') case search_query when Symbol underscored_column_name == search_query.to_s when String downcased_column_name == search_query.downcase when Regexp column_name =~ search_query when Array search_query.any? { |query| match?(column_name, query) } else raise Error, "Invalid `as`. Should be a Symbol, String, Regexp or Array - was #{as.inspect}" end end
ruby
def match?(column_name, search_query=(as || name)) return false if column_name.nil? downcased_column_name = column_name.downcase underscored_column_name = downcased_column_name.gsub(/\s+/, '_') case search_query when Symbol underscored_column_name == search_query.to_s when String downcased_column_name == search_query.downcase when Regexp column_name =~ search_query when Array search_query.any? { |query| match?(column_name, query) } else raise Error, "Invalid `as`. Should be a Symbol, String, Regexp or Array - was #{as.inspect}" end end
[ "def", "match?", "(", "column_name", ",", "search_query", "=", "(", "as", "||", "name", ")", ")", "return", "false", "if", "column_name", ".", "nil?", "downcased_column_name", "=", "column_name", ".", "downcase", "underscored_column_name", "=", "downcased_column_name", ".", "gsub", "(", "/", "\\s", "/", ",", "'_'", ")", "case", "search_query", "when", "Symbol", "underscored_column_name", "==", "search_query", ".", "to_s", "when", "String", "downcased_column_name", "==", "search_query", ".", "downcase", "when", "Regexp", "column_name", "=~", "search_query", "when", "Array", "search_query", ".", "any?", "{", "|", "query", "|", "match?", "(", "column_name", ",", "query", ")", "}", "else", "raise", "Error", ",", "\"Invalid `as`. Should be a Symbol, String, Regexp or Array - was #{as.inspect}\"", "end", "end" ]
Return true if column definition matches the column name passed in.
[ "Return", "true", "if", "column", "definition", "matches", "the", "column", "name", "passed", "in", "." ]
942070b4b22eed0b36989b98fe4ebe9104b9f665
https://github.com/pcreux/csv-importer/blob/942070b4b22eed0b36989b98fe4ebe9104b9f665/lib/csv_importer/column_definition.rb#L44-L62
16,083
piotrmurach/tty
lib/tty/templater.rb
TTY.Templater.generate
def generate(template_options, color_option) templates.each do |src, dst| source = @source_path.join(src) destination = @target_path.join(dst).to_s next unless ::File.exist?(source) within_root_path do TTY::File.copy_file(source, destination, { context: template_options }.merge(color_option)) end end end
ruby
def generate(template_options, color_option) templates.each do |src, dst| source = @source_path.join(src) destination = @target_path.join(dst).to_s next unless ::File.exist?(source) within_root_path do TTY::File.copy_file(source, destination, { context: template_options }.merge(color_option)) end end end
[ "def", "generate", "(", "template_options", ",", "color_option", ")", "templates", ".", "each", "do", "|", "src", ",", "dst", "|", "source", "=", "@source_path", ".", "join", "(", "src", ")", "destination", "=", "@target_path", ".", "join", "(", "dst", ")", ".", "to_s", "next", "unless", "::", "File", ".", "exist?", "(", "source", ")", "within_root_path", "do", "TTY", "::", "File", ".", "copy_file", "(", "source", ",", "destination", ",", "{", "context", ":", "template_options", "}", ".", "merge", "(", "color_option", ")", ")", "end", "end", "end" ]
Process templates by injecting vars and moving to location @api private
[ "Process", "templates", "by", "injecting", "vars", "and", "moving", "to", "location" ]
872fa26d321d95b48807569f25cb1633f6fecd17
https://github.com/piotrmurach/tty/blob/872fa26d321d95b48807569f25cb1633f6fecd17/lib/tty/templater.rb#L41-L51
16,084
piotrmurach/tty
lib/tty/plugins.rb
TTY.Plugins.load_from
def load_from(gemspec_path, pattern) Gem.refresh spec = Gem::Specification.load(gemspec_path) dependencies = spec.runtime_dependencies.concat(spec.development_dependencies) dependencies.each do |gem| gem_name = gem.name[pattern] next if gem_name.to_s.empty? register(gem_name, Plugin.new(gem_name, gem)) end self end
ruby
def load_from(gemspec_path, pattern) Gem.refresh spec = Gem::Specification.load(gemspec_path) dependencies = spec.runtime_dependencies.concat(spec.development_dependencies) dependencies.each do |gem| gem_name = gem.name[pattern] next if gem_name.to_s.empty? register(gem_name, Plugin.new(gem_name, gem)) end self end
[ "def", "load_from", "(", "gemspec_path", ",", "pattern", ")", "Gem", ".", "refresh", "spec", "=", "Gem", "::", "Specification", ".", "load", "(", "gemspec_path", ")", "dependencies", "=", "spec", ".", "runtime_dependencies", ".", "concat", "(", "spec", ".", "development_dependencies", ")", "dependencies", ".", "each", "do", "|", "gem", "|", "gem_name", "=", "gem", ".", "name", "[", "pattern", "]", "next", "if", "gem_name", ".", "to_s", ".", "empty?", "register", "(", "gem_name", ",", "Plugin", ".", "new", "(", "gem_name", ",", "gem", ")", ")", "end", "self", "end" ]
Loads gemspec from a file and registers gems matching pattern. @param [String|Pathname] gemspec_path the path to gemspec @param [Regex] pattern the pattern to match gems by @example plugins.load_from('foo.gemspec', /tty-(.*)/) @api public
[ "Loads", "gemspec", "from", "a", "file", "and", "registers", "gems", "matching", "pattern", "." ]
872fa26d321d95b48807569f25cb1633f6fecd17
https://github.com/piotrmurach/tty/blob/872fa26d321d95b48807569f25cb1633f6fecd17/lib/tty/plugins.rb#L55-L65
16,085
piotrmurach/tty
lib/tty/plugins.rb
TTY.Plugins.names
def names plugins.reduce({}) do |hash, plugin| hash[plugin.name] = plugin hash end end
ruby
def names plugins.reduce({}) do |hash, plugin| hash[plugin.name] = plugin hash end end
[ "def", "names", "plugins", ".", "reduce", "(", "{", "}", ")", "do", "|", "hash", ",", "plugin", "|", "hash", "[", "plugin", ".", "name", "]", "=", "plugin", "hash", "end", "end" ]
Return a list of all plugin names as strings @api public
[ "Return", "a", "list", "of", "all", "plugin", "names", "as", "strings" ]
872fa26d321d95b48807569f25cb1633f6fecd17
https://github.com/piotrmurach/tty/blob/872fa26d321d95b48807569f25cb1633f6fecd17/lib/tty/plugins.rb#L80-L85
16,086
piotrmurach/tty
lib/tty/path_helpers.rb
TTY.PathHelpers.relative_path_from
def relative_path_from(root_path, path) project_path = Pathname.new(path) return project_path if project_path.relative? project_path.relative_path_from(root_path) end
ruby
def relative_path_from(root_path, path) project_path = Pathname.new(path) return project_path if project_path.relative? project_path.relative_path_from(root_path) end
[ "def", "relative_path_from", "(", "root_path", ",", "path", ")", "project_path", "=", "Pathname", ".", "new", "(", "path", ")", "return", "project_path", "if", "project_path", ".", "relative?", "project_path", ".", "relative_path_from", "(", "root_path", ")", "end" ]
Extract a relative path for the app @api private
[ "Extract", "a", "relative", "path", "for", "the", "app" ]
872fa26d321d95b48807569f25cb1633f6fecd17
https://github.com/piotrmurach/tty/blob/872fa26d321d95b48807569f25cb1633f6fecd17/lib/tty/path_helpers.rb#L31-L35
16,087
heroku/databasedotcom
lib/databasedotcom/client.rb
Databasedotcom.Client.authenticate
def authenticate(options = nil) if user_and_pass?(options) req = https_request(self.host) user = self.username || options[:username] pass = self.password || options[:password] path = encode_path_with_params('/services/oauth2/token', :grant_type => 'password', :client_id => self.client_id, :client_secret => self.client_secret, :username => user, :password => pass) log_request("https://#{self.host}/#{path}") result = req.post(path, "") log_response(result) raise SalesForceError.new(result) unless result.is_a?(Net::HTTPOK) self.username = user self.password = pass parse_auth_response(result.body) elsif options.is_a?(Hash) if options.has_key?("provider") parse_user_id_and_org_id_from_identity_url(options["uid"]) self.instance_url = options["credentials"]["instance_url"] self.oauth_token = options["credentials"]["token"] self.refresh_token = options["credentials"]["refresh_token"] else raise ArgumentError unless options.has_key?(:token) && options.has_key?(:instance_url) self.instance_url = options[:instance_url] self.oauth_token = options[:token] self.refresh_token = options[:refresh_token] end end self.version = "22.0" unless self.version self.oauth_token end
ruby
def authenticate(options = nil) if user_and_pass?(options) req = https_request(self.host) user = self.username || options[:username] pass = self.password || options[:password] path = encode_path_with_params('/services/oauth2/token', :grant_type => 'password', :client_id => self.client_id, :client_secret => self.client_secret, :username => user, :password => pass) log_request("https://#{self.host}/#{path}") result = req.post(path, "") log_response(result) raise SalesForceError.new(result) unless result.is_a?(Net::HTTPOK) self.username = user self.password = pass parse_auth_response(result.body) elsif options.is_a?(Hash) if options.has_key?("provider") parse_user_id_and_org_id_from_identity_url(options["uid"]) self.instance_url = options["credentials"]["instance_url"] self.oauth_token = options["credentials"]["token"] self.refresh_token = options["credentials"]["refresh_token"] else raise ArgumentError unless options.has_key?(:token) && options.has_key?(:instance_url) self.instance_url = options[:instance_url] self.oauth_token = options[:token] self.refresh_token = options[:refresh_token] end end self.version = "22.0" unless self.version self.oauth_token end
[ "def", "authenticate", "(", "options", "=", "nil", ")", "if", "user_and_pass?", "(", "options", ")", "req", "=", "https_request", "(", "self", ".", "host", ")", "user", "=", "self", ".", "username", "||", "options", "[", ":username", "]", "pass", "=", "self", ".", "password", "||", "options", "[", ":password", "]", "path", "=", "encode_path_with_params", "(", "'/services/oauth2/token'", ",", ":grant_type", "=>", "'password'", ",", ":client_id", "=>", "self", ".", "client_id", ",", ":client_secret", "=>", "self", ".", "client_secret", ",", ":username", "=>", "user", ",", ":password", "=>", "pass", ")", "log_request", "(", "\"https://#{self.host}/#{path}\"", ")", "result", "=", "req", ".", "post", "(", "path", ",", "\"\"", ")", "log_response", "(", "result", ")", "raise", "SalesForceError", ".", "new", "(", "result", ")", "unless", "result", ".", "is_a?", "(", "Net", "::", "HTTPOK", ")", "self", ".", "username", "=", "user", "self", ".", "password", "=", "pass", "parse_auth_response", "(", "result", ".", "body", ")", "elsif", "options", ".", "is_a?", "(", "Hash", ")", "if", "options", ".", "has_key?", "(", "\"provider\"", ")", "parse_user_id_and_org_id_from_identity_url", "(", "options", "[", "\"uid\"", "]", ")", "self", ".", "instance_url", "=", "options", "[", "\"credentials\"", "]", "[", "\"instance_url\"", "]", "self", ".", "oauth_token", "=", "options", "[", "\"credentials\"", "]", "[", "\"token\"", "]", "self", ".", "refresh_token", "=", "options", "[", "\"credentials\"", "]", "[", "\"refresh_token\"", "]", "else", "raise", "ArgumentError", "unless", "options", ".", "has_key?", "(", ":token", ")", "&&", "options", ".", "has_key?", "(", ":instance_url", ")", "self", ".", "instance_url", "=", "options", "[", ":instance_url", "]", "self", ".", "oauth_token", "=", "options", "[", ":token", "]", "self", ".", "refresh_token", "=", "options", "[", ":refresh_token", "]", "end", "end", "self", ".", "version", "=", "\"22.0\"", "unless", "self", ".", "version", "self", ".", "oauth_token", "end" ]
Returns a new client object. _options_ can be one of the following * A String containing the name of a YAML file formatted like: --- client_id: <your_salesforce_client_id> client_secret: <your_salesforce_client_secret> host: login.salesforce.com debugging: true version: 23.0 sobject_module: My::Module ca_file: some/ca/file.cert verify_mode: OpenSSL::SSL::VERIFY_PEER * A Hash containing the following keys: client_id client_secret host debugging version sobject_module ca_file verify_mode If the environment variables DATABASEDOTCOM_CLIENT_ID, DATABASEDOTCOM_CLIENT_SECRET, DATABASEDOTCOM_HOST, DATABASEDOTCOM_DEBUGGING, DATABASEDOTCOM_VERSION, DATABASEDOTCOM_SOBJECT_MODULE, DATABASEDOTCOM_CA_FILE, and/or DATABASEDOTCOM_VERIFY_MODE are present, they override any other values provided Authenticate to the Force.com API. _options_ is a Hash, interpreted as follows: * If _options_ contains the keys <tt>:username</tt> and <tt>:password</tt>, those credentials are used to authenticate. In this case, the value of <tt>:password</tt> may need to include a concatenated security token, if required by your Salesforce org * If _options_ contains the key <tt>:provider</tt>, it is assumed to be the hash returned by Omniauth from a successful web-based OAuth2 authentication * If _options_ contains the keys <tt>:token</tt> and <tt>:instance_url</tt>, those are assumed to be a valid OAuth2 token and instance URL for a Salesforce account, obtained from an external source. _options_ may also optionally contain the key <tt>:refresh_token</tt> Raises SalesForceError if an error occurs
[ "Returns", "a", "new", "client", "object", ".", "_options_", "can", "be", "one", "of", "the", "following" ]
a9173ff9c47bf2321a6959c9616d00cb6d8e93be
https://github.com/heroku/databasedotcom/blob/a9173ff9c47bf2321a6959c9616d00cb6d8e93be/lib/databasedotcom/client.rb#L103-L133
16,088
heroku/databasedotcom
lib/databasedotcom/client.rb
Databasedotcom.Client.list_sobjects
def list_sobjects result = http_get("/services/data/v#{self.version}/sobjects") if result.is_a?(Net::HTTPOK) JSON.parse(result.body)["sobjects"].collect { |sobject| sobject["name"] } elsif result.is_a?(Net::HTTPBadRequest) raise SalesForceError.new(result) end end
ruby
def list_sobjects result = http_get("/services/data/v#{self.version}/sobjects") if result.is_a?(Net::HTTPOK) JSON.parse(result.body)["sobjects"].collect { |sobject| sobject["name"] } elsif result.is_a?(Net::HTTPBadRequest) raise SalesForceError.new(result) end end
[ "def", "list_sobjects", "result", "=", "http_get", "(", "\"/services/data/v#{self.version}/sobjects\"", ")", "if", "result", ".", "is_a?", "(", "Net", "::", "HTTPOK", ")", "JSON", ".", "parse", "(", "result", ".", "body", ")", "[", "\"sobjects\"", "]", ".", "collect", "{", "|", "sobject", "|", "sobject", "[", "\"name\"", "]", "}", "elsif", "result", ".", "is_a?", "(", "Net", "::", "HTTPBadRequest", ")", "raise", "SalesForceError", ".", "new", "(", "result", ")", "end", "end" ]
Returns an Array of Strings listing the class names for every type of _Sobject_ in the database. Raises SalesForceError if an error occurs.
[ "Returns", "an", "Array", "of", "Strings", "listing", "the", "class", "names", "for", "every", "type", "of", "_Sobject_", "in", "the", "database", ".", "Raises", "SalesForceError", "if", "an", "error", "occurs", "." ]
a9173ff9c47bf2321a6959c9616d00cb6d8e93be
https://github.com/heroku/databasedotcom/blob/a9173ff9c47bf2321a6959c9616d00cb6d8e93be/lib/databasedotcom/client.rb#L141-L148
16,089
heroku/databasedotcom
lib/databasedotcom/client.rb
Databasedotcom.Client.trending_topics
def trending_topics result = http_get("/services/data/v#{self.version}/chatter/topics/trending") result = JSON.parse(result.body) result["topics"].collect { |topic| topic["name"] } end
ruby
def trending_topics result = http_get("/services/data/v#{self.version}/chatter/topics/trending") result = JSON.parse(result.body) result["topics"].collect { |topic| topic["name"] } end
[ "def", "trending_topics", "result", "=", "http_get", "(", "\"/services/data/v#{self.version}/chatter/topics/trending\"", ")", "result", "=", "JSON", ".", "parse", "(", "result", ".", "body", ")", "result", "[", "\"topics\"", "]", ".", "collect", "{", "|", "topic", "|", "topic", "[", "\"name\"", "]", "}", "end" ]
Returns an array of trending topic names.
[ "Returns", "an", "array", "of", "trending", "topic", "names", "." ]
a9173ff9c47bf2321a6959c9616d00cb6d8e93be
https://github.com/heroku/databasedotcom/blob/a9173ff9c47bf2321a6959c9616d00cb6d8e93be/lib/databasedotcom/client.rb#L278-L282
16,090
heroku/databasedotcom
lib/databasedotcom/client.rb
Databasedotcom.Client.record_from_hash
def record_from_hash(data) attributes = data.delete('attributes') new_record = find_or_materialize(attributes["type"]).new data.each do |name, value| field = new_record.description['fields'].find do |field| key_from_label(field["label"]) == name || field["name"] == name || field["relationshipName"] == name end # Field not found if field == nil break end # If reference/lookup field data was fetched, recursively build the child record and apply if value.is_a?(Hash) and field['type'] == 'reference' and field["relationshipName"] relation = record_from_hash( value ) set_value( new_record, field["relationshipName"], relation, 'reference' ) # Apply the raw value for all other field types else set_value(new_record, field["name"], value, field["type"]) if field end end new_record end
ruby
def record_from_hash(data) attributes = data.delete('attributes') new_record = find_or_materialize(attributes["type"]).new data.each do |name, value| field = new_record.description['fields'].find do |field| key_from_label(field["label"]) == name || field["name"] == name || field["relationshipName"] == name end # Field not found if field == nil break end # If reference/lookup field data was fetched, recursively build the child record and apply if value.is_a?(Hash) and field['type'] == 'reference' and field["relationshipName"] relation = record_from_hash( value ) set_value( new_record, field["relationshipName"], relation, 'reference' ) # Apply the raw value for all other field types else set_value(new_record, field["name"], value, field["type"]) if field end end new_record end
[ "def", "record_from_hash", "(", "data", ")", "attributes", "=", "data", ".", "delete", "(", "'attributes'", ")", "new_record", "=", "find_or_materialize", "(", "attributes", "[", "\"type\"", "]", ")", ".", "new", "data", ".", "each", "do", "|", "name", ",", "value", "|", "field", "=", "new_record", ".", "description", "[", "'fields'", "]", ".", "find", "do", "|", "field", "|", "key_from_label", "(", "field", "[", "\"label\"", "]", ")", "==", "name", "||", "field", "[", "\"name\"", "]", "==", "name", "||", "field", "[", "\"relationshipName\"", "]", "==", "name", "end", "# Field not found", "if", "field", "==", "nil", "break", "end", "# If reference/lookup field data was fetched, recursively build the child record and apply", "if", "value", ".", "is_a?", "(", "Hash", ")", "and", "field", "[", "'type'", "]", "==", "'reference'", "and", "field", "[", "\"relationshipName\"", "]", "relation", "=", "record_from_hash", "(", "value", ")", "set_value", "(", "new_record", ",", "field", "[", "\"relationshipName\"", "]", ",", "relation", ",", "'reference'", ")", "# Apply the raw value for all other field types", "else", "set_value", "(", "new_record", ",", "field", "[", "\"name\"", "]", ",", "value", ",", "field", "[", "\"type\"", "]", ")", "if", "field", "end", "end", "new_record", "end" ]
Converts a Hash of object data into a concrete SObject
[ "Converts", "a", "Hash", "of", "object", "data", "into", "a", "concrete", "SObject" ]
a9173ff9c47bf2321a6959c9616d00cb6d8e93be
https://github.com/heroku/databasedotcom/blob/a9173ff9c47bf2321a6959c9616d00cb6d8e93be/lib/databasedotcom/client.rb#L437-L461
16,091
DamirSvrtan/fasterer
lib/fasterer/scanners/method_call_scanner.rb
Fasterer.MethodCallScanner.check_symbol_to_proc
def check_symbol_to_proc return unless method_call.block_argument_names.count == 1 return if method_call.block_body.nil? return unless method_call.block_body.sexp_type == :call return if method_call.arguments.count > 0 body_method_call = MethodCall.new(method_call.block_body) return unless body_method_call.arguments.count.zero? return if body_method_call.has_block? return unless body_method_call.receiver.name == method_call.block_argument_names.first add_offense(:block_vs_symbol_to_proc) end
ruby
def check_symbol_to_proc return unless method_call.block_argument_names.count == 1 return if method_call.block_body.nil? return unless method_call.block_body.sexp_type == :call return if method_call.arguments.count > 0 body_method_call = MethodCall.new(method_call.block_body) return unless body_method_call.arguments.count.zero? return if body_method_call.has_block? return unless body_method_call.receiver.name == method_call.block_argument_names.first add_offense(:block_vs_symbol_to_proc) end
[ "def", "check_symbol_to_proc", "return", "unless", "method_call", ".", "block_argument_names", ".", "count", "==", "1", "return", "if", "method_call", ".", "block_body", ".", "nil?", "return", "unless", "method_call", ".", "block_body", ".", "sexp_type", "==", ":call", "return", "if", "method_call", ".", "arguments", ".", "count", ">", "0", "body_method_call", "=", "MethodCall", ".", "new", "(", "method_call", ".", "block_body", ")", "return", "unless", "body_method_call", ".", "arguments", ".", "count", ".", "zero?", "return", "if", "body_method_call", ".", "has_block?", "return", "unless", "body_method_call", ".", "receiver", ".", "name", "==", "method_call", ".", "block_argument_names", ".", "first", "add_offense", "(", ":block_vs_symbol_to_proc", ")", "end" ]
Need to refactor, fukken complicated conditions.
[ "Need", "to", "refactor", "fukken", "complicated", "conditions", "." ]
f451a740879efa3c82c0604e3cc80b651f3461ab
https://github.com/DamirSvrtan/fasterer/blob/f451a740879efa3c82c0604e3cc80b651f3461ab/lib/fasterer/scanners/method_call_scanner.rb#L123-L136
16,092
jmettraux/rufus-scheduler
lib/rufus/scheduler.rb
Rufus.Scheduler.scheduled?
def scheduled?(job_or_job_id) job, _ = fetch(job_or_job_id) !! (job && job.unscheduled_at.nil? && job.next_time != nil) end
ruby
def scheduled?(job_or_job_id) job, _ = fetch(job_or_job_id) !! (job && job.unscheduled_at.nil? && job.next_time != nil) end
[ "def", "scheduled?", "(", "job_or_job_id", ")", "job", ",", "_", "=", "fetch", "(", "job_or_job_id", ")", "!", "!", "(", "job", "&&", "job", ".", "unscheduled_at", ".", "nil?", "&&", "job", ".", "next_time", "!=", "nil", ")", "end" ]
Returns true if this job is currently scheduled. Takes extra care to answer true if the job is a repeat job currently firing.
[ "Returns", "true", "if", "this", "job", "is", "currently", "scheduled", "." ]
db3b559fbd988ef44126ea59508e0c62bfc45540
https://github.com/jmettraux/rufus-scheduler/blob/db3b559fbd988ef44126ea59508e0c62bfc45540/lib/rufus/scheduler.rb#L374-L379
16,093
toptal/crystalball
lib/crystalball/extensions/git/lib.rb
Git.Lib.merge_base
def merge_base(*args) opts = args.last.is_a?(Hash) ? args.pop : {} arg_opts = opts.map { |k, v| "--#{k}" if v }.compact + args command('merge-base', arg_opts) end
ruby
def merge_base(*args) opts = args.last.is_a?(Hash) ? args.pop : {} arg_opts = opts.map { |k, v| "--#{k}" if v }.compact + args command('merge-base', arg_opts) end
[ "def", "merge_base", "(", "*", "args", ")", "opts", "=", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", "arg_opts", "=", "opts", ".", "map", "{", "|", "k", ",", "v", "|", "\"--#{k}\"", "if", "v", "}", ".", "compact", "+", "args", "command", "(", "'merge-base'", ",", "arg_opts", ")", "end" ]
`git merge-base ...`. Returns common ancestor for all passed commits @param [Array<Object>] args - list of commits to process. Last argument can be options for merge-base command @return [String]
[ "git", "merge", "-", "base", "...", ".", "Returns", "common", "ancestor", "for", "all", "passed", "commits" ]
9cb62597425e0d0d3e8b428c7d08d3940a43fdea
https://github.com/toptal/crystalball/blob/9cb62597425e0d0d3e8b428c7d08d3940a43fdea/lib/crystalball/extensions/git/lib.rb#L10-L16
16,094
toptal/crystalball
lib/crystalball/map_generator.rb
Crystalball.MapGenerator.start!
def start! self.map = nil map_storage.clear! map_storage.dump(map.metadata.to_h) strategies.reverse.each(&:after_start) self.started = true end
ruby
def start! self.map = nil map_storage.clear! map_storage.dump(map.metadata.to_h) strategies.reverse.each(&:after_start) self.started = true end
[ "def", "start!", "self", ".", "map", "=", "nil", "map_storage", ".", "clear!", "map_storage", ".", "dump", "(", "map", ".", "metadata", ".", "to_h", ")", "strategies", ".", "reverse", ".", "each", "(", ":after_start", ")", "self", ".", "started", "=", "true", "end" ]
Registers strategies and prepares metadata for execution map
[ "Registers", "strategies", "and", "prepares", "metadata", "for", "execution", "map" ]
9cb62597425e0d0d3e8b428c7d08d3940a43fdea
https://github.com/toptal/crystalball/blob/9cb62597425e0d0d3e8b428c7d08d3940a43fdea/lib/crystalball/map_generator.rb#L35-L42
16,095
toptal/crystalball
lib/crystalball/map_generator.rb
Crystalball.MapGenerator.refresh_for_case
def refresh_for_case(example) map << strategies.run(ExampleGroupMap.new(example), example) { example.run } check_dump_threshold end
ruby
def refresh_for_case(example) map << strategies.run(ExampleGroupMap.new(example), example) { example.run } check_dump_threshold end
[ "def", "refresh_for_case", "(", "example", ")", "map", "<<", "strategies", ".", "run", "(", "ExampleGroupMap", ".", "new", "(", "example", ")", ",", "example", ")", "{", "example", ".", "run", "}", "check_dump_threshold", "end" ]
Runs example and collects execution map for it
[ "Runs", "example", "and", "collects", "execution", "map", "for", "it" ]
9cb62597425e0d0d3e8b428c7d08d3940a43fdea
https://github.com/toptal/crystalball/blob/9cb62597425e0d0d3e8b428c7d08d3940a43fdea/lib/crystalball/map_generator.rb#L45-L48
16,096
toptal/crystalball
lib/crystalball/map_generator.rb
Crystalball.MapGenerator.finalize!
def finalize! return unless started strategies.each(&:before_finalize) return unless map.size.positive? example_groups = (configuration.compact_map? ? MapCompactor.compact_map!(map) : map).example_groups map_storage.dump(example_groups) end
ruby
def finalize! return unless started strategies.each(&:before_finalize) return unless map.size.positive? example_groups = (configuration.compact_map? ? MapCompactor.compact_map!(map) : map).example_groups map_storage.dump(example_groups) end
[ "def", "finalize!", "return", "unless", "started", "strategies", ".", "each", "(", ":before_finalize", ")", "return", "unless", "map", ".", "size", ".", "positive?", "example_groups", "=", "(", "configuration", ".", "compact_map?", "?", "MapCompactor", ".", "compact_map!", "(", "map", ")", ":", "map", ")", ".", "example_groups", "map_storage", ".", "dump", "(", "example_groups", ")", "end" ]
Finalizes strategies and saves map
[ "Finalizes", "strategies", "and", "saves", "map" ]
9cb62597425e0d0d3e8b428c7d08d3940a43fdea
https://github.com/toptal/crystalball/blob/9cb62597425e0d0d3e8b428c7d08d3940a43fdea/lib/crystalball/map_generator.rb#L51-L60
16,097
gdelugre/origami
lib/origami/page.rb
Origami.ResourcesHolder.add_resource
def add_resource(type, rsrc, name = nil) if name.nil? rsrc_name = self.resources(type).key(rsrc) return rsrc_name if rsrc_name end name ||= new_id(type) target = self.is_a?(Resources) ? self : (self.Resources ||= Resources.new) rsrc_dict = (target[type] and target[type].solve) || (target[type] = Dictionary.new) rsrc_dict[name.to_sym] = rsrc name end
ruby
def add_resource(type, rsrc, name = nil) if name.nil? rsrc_name = self.resources(type).key(rsrc) return rsrc_name if rsrc_name end name ||= new_id(type) target = self.is_a?(Resources) ? self : (self.Resources ||= Resources.new) rsrc_dict = (target[type] and target[type].solve) || (target[type] = Dictionary.new) rsrc_dict[name.to_sym] = rsrc name end
[ "def", "add_resource", "(", "type", ",", "rsrc", ",", "name", "=", "nil", ")", "if", "name", ".", "nil?", "rsrc_name", "=", "self", ".", "resources", "(", "type", ")", ".", "key", "(", "rsrc", ")", "return", "rsrc_name", "if", "rsrc_name", "end", "name", "||=", "new_id", "(", "type", ")", "target", "=", "self", ".", "is_a?", "(", "Resources", ")", "?", "self", ":", "(", "self", ".", "Resources", "||=", "Resources", ".", "new", ")", "rsrc_dict", "=", "(", "target", "[", "type", "]", "and", "target", "[", "type", "]", ".", "solve", ")", "||", "(", "target", "[", "type", "]", "=", "Dictionary", ".", "new", ")", "rsrc_dict", "[", "name", ".", "to_sym", "]", "=", "rsrc", "name", "end" ]
Adds a resource of the specified _type_ in the current object. If _name_ is not specified, a new name will be automatically generated.
[ "Adds", "a", "resource", "of", "the", "specified", "_type_", "in", "the", "current", "object", ".", "If", "_name_", "is", "not", "specified", "a", "new", "name", "will", "be", "automatically", "generated", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/page.rb#L148-L161
16,098
gdelugre/origami
lib/origami/page.rb
Origami.ResourcesHolder.each_resource
def each_resource(type) target = self.is_a?(Resources) ? self : (self.Resources ||= Resources.new) rsrc = (target[type] and target[type].solve) return enum_for(__method__, type) { rsrc.is_a?(Dictionary) ? rsrc.length : 0 } unless block_given? return unless rsrc.is_a?(Dictionary) rsrc.each_pair do |name, obj| yield(name.value, obj.solve) end end
ruby
def each_resource(type) target = self.is_a?(Resources) ? self : (self.Resources ||= Resources.new) rsrc = (target[type] and target[type].solve) return enum_for(__method__, type) { rsrc.is_a?(Dictionary) ? rsrc.length : 0 } unless block_given? return unless rsrc.is_a?(Dictionary) rsrc.each_pair do |name, obj| yield(name.value, obj.solve) end end
[ "def", "each_resource", "(", "type", ")", "target", "=", "self", ".", "is_a?", "(", "Resources", ")", "?", "self", ":", "(", "self", ".", "Resources", "||=", "Resources", ".", "new", ")", "rsrc", "=", "(", "target", "[", "type", "]", "and", "target", "[", "type", "]", ".", "solve", ")", "return", "enum_for", "(", "__method__", ",", "type", ")", "{", "rsrc", ".", "is_a?", "(", "Dictionary", ")", "?", "rsrc", ".", "length", ":", "0", "}", "unless", "block_given?", "return", "unless", "rsrc", ".", "is_a?", "(", "Dictionary", ")", "rsrc", ".", "each_pair", "do", "|", "name", ",", "obj", "|", "yield", "(", "name", ".", "value", ",", "obj", ".", "solve", ")", "end", "end" ]
Iterates over the resources by _type_.
[ "Iterates", "over", "the", "resources", "by", "_type_", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/page.rb#L166-L177
16,099
gdelugre/origami
lib/origami/page.rb
Origami.ResourcesHolder.resources
def resources(type = nil) if type.nil? self.extgstates .merge self.colorspaces .merge self.patterns .merge self.shadings .merge self.xobjects .merge self.fonts .merge self.properties else self.each_resource(type).to_h end end
ruby
def resources(type = nil) if type.nil? self.extgstates .merge self.colorspaces .merge self.patterns .merge self.shadings .merge self.xobjects .merge self.fonts .merge self.properties else self.each_resource(type).to_h end end
[ "def", "resources", "(", "type", "=", "nil", ")", "if", "type", ".", "nil?", "self", ".", "extgstates", ".", "merge", "self", ".", "colorspaces", ".", "merge", "self", ".", "patterns", ".", "merge", "self", ".", "shadings", ".", "merge", "self", ".", "xobjects", ".", "merge", "self", ".", "fonts", ".", "merge", "self", ".", "properties", "else", "self", ".", "each_resource", "(", "type", ")", ".", "to_h", "end", "end" ]
Returns a Hash of all resources in the object or only the specified _type_.
[ "Returns", "a", "Hash", "of", "all", "resources", "in", "the", "object", "or", "only", "the", "specified", "_type_", "." ]
ac1df803517601d486556fd40af5d422a6f4378e
https://github.com/gdelugre/origami/blob/ac1df803517601d486556fd40af5d422a6f4378e/lib/origami/page.rb#L198-L210